diff --git a/mozilla/zap/Makefile.in b/mozilla/zap/Makefile.in index 3e3d842dcae..9d4bf3df524 100644 --- a/mozilla/zap/Makefile.in +++ b/mozilla/zap/Makefile.in @@ -5,7 +5,7 @@ VPATH = @srcdir@ include $(DEPTH)/config/autoconf.mk -DIRS = base audio media sdp sip app +DIRS = base zmk sdp sip app include $(topsrcdir)/config/rules.mk diff --git a/mozilla/zap/app/content/incomingcall.js b/mozilla/zap/app/content/incomingcall.js index b72ea8a7632..f79227d2d16 100644 --- a/mozilla/zap/app/content/incomingcall.js +++ b/mozilla/zap/app/content/incomingcall.js @@ -124,7 +124,7 @@ function cmdAccept() { // m= var mediaDescription = wSipClient.sdpService.createMediaDescription(); mediaDescription.media = "audio"; - mediaDescription.port = wCallHandler.rtpBase; + mediaDescription.port = wCallHandler.mediaSession.localRTPPort; mediaDescription.portCount = ""; mediaDescription.protocol = "RTP/AVP"; var fmt = wSipClient.sdpService.createMediaFormat(); diff --git a/mozilla/zap/app/content/outgoingcall.js b/mozilla/zap/app/content/outgoingcall.js index 3764da88caf..ed0b5b35ac9 100644 --- a/mozilla/zap/app/content/outgoingcall.js +++ b/mozilla/zap/app/content/outgoingcall.js @@ -120,7 +120,7 @@ function cmdCall() { // m= var mediaDescription = wSipClient.sdpService.createMediaDescription(); mediaDescription.media = "audio"; - mediaDescription.port = wCallHandler.rtpBase; + mediaDescription.port = wCallHandler.mediaSession.localRTPPort; mediaDescription.portCount = ""; mediaDescription.protocol = "RTP/AVP"; var fmt = wSipClient.sdpService.createMediaFormat(); @@ -173,22 +173,17 @@ CallHandler.addInterfaces(Components.interfaces.zapISipInviteMCH, CallHandler.obj( "dialog", null); -CallHandler.obj( - "rtpBase", 6000); - CallHandler.appendCtor( function() { - log("Create media stream"); - var thread = Components.classes["@mozilla.org/thread;1"].createInstance(Components.interfaces.nsIThread); - this.mediaStream = wSipClient.mediaService.createMediaStream(this.rtpBase, this.rtpBase+1); - thread.init(this.mediaStream, 0, 1, 1, 1); + log("Create media session"); + this.mediaSession = Components.classes["@mozilla.org/zap/mediasession;1"].createInstance(Components.interfaces.zapIMediaSession); }); CallHandler.fun( function destroy() { - if (this.mediaStream) { - this.mediaStream.close(); - this.mediaStream = null; + if (this.mediaSession) { + this.mediaSession.close(); + this.mediaSession = null; } this.dialog = null; wCallHandler = null; @@ -286,11 +281,10 @@ CallHandler.fun( } // start sending/receiving audio: - this.mediaStream.startReceive(); - this.mediaStream.startSend(remoteHost, - rtpPort, - rtpPort+1, - payloadFormat); + this.mediaSession.start(remoteHost, + rtpPort, + rtpPort+1, + payloadFormat); log("Established speex/8000 ("+payloadFormat+") call to "+remoteHost+":"+rtpPort); }); diff --git a/mozilla/zap/app/content/zap.js b/mozilla/zap/app/content/zap.js index 08c32518eb0..b8bb6a2499f 100644 --- a/mozilla/zap/app/content/zap.js +++ b/mozilla/zap/app/content/zap.js @@ -133,10 +133,6 @@ function initSipClient() SipClient.sipStack.QueryInterface(Components.interfaces.zapISipUAStack); SipClient.sipStack.init(gInviteMSHFactory); - log("Getting Media Service"); - SipClient.mediaService = Components.classes["@mozilla.org/zap/mediaservice;1"]. - getService(Components.interfaces.zapIMediaService); - // initialize host-name to our ip address: wHostNameElement.value = SipClient.sipStack.hostAddress; @@ -156,10 +152,8 @@ InviteMSH.addInterfaces(Components.interfaces.zapISipInviteMSH, InviteMSH.appendCtor( function() { - log("Create media stream"); - var thread = Components.classes["@mozilla.org/thread;1"].createInstance(Components.interfaces.nsIThread); - this.mediaStream = SipClient.mediaService.createMediaStream(this.rtpBase, this.rtpBase+1); - thread.init(this.mediaStream, 0, 1, 1, 1); + log("Create media session"); + this.mediaSession = Components.classes["@mozilla.org/zap/mediasession;1"].createInstance(Components.interfaces.zapIMediaSession); }); @@ -175,15 +169,11 @@ InviteMSH.obj("destroyHook", null); // this will be overwritten by the incomingcall window: InviteMSH.obj("callSuccessHook", null); -InviteMSH.obj( - "rtpBase", 6000); - - InviteMSH.fun( function destroy() { - if (this.mediaStream) { - this.mediaStream.close(); - this.mediaStream = null; + if (this.mediaSession) { + this.mediaSession.shutdown(); + this.mediaSession = null; } this.dialog = null; if (this.destroyHook) @@ -219,8 +209,7 @@ InviteMSH.fun( var mediaDescriptions = sd.getMediaDescriptions({}); // XXX assuming that there is only one media description for the moment: - this.remoteRtpPort = mediaDescriptions[0].port; - + this.remoteRtpPort = mediaDescriptions[0].port; var connection = mediaDescriptions[0].connection; if (!connection) connection = sd.connection; @@ -279,11 +268,10 @@ InviteMSH.fun( if (this.callSuccessHook) this.callSuccessHook(); // start sending/receiving audio: - this.mediaStream.startReceive(); - this.mediaStream.startSend(this.remoteMediaHost, - this.remoteRtpPort, - this.remoteRtpPort+1, - this.remotePayloadFormat); + this.mediaSession.start(this.remoteMediaHost, + this.remoteRtpPort, + this.remoteRtpPort+1, + this.remotePayloadFormat); this.log("Established speex/8000 ("+this.remotePayloadFormat+") call to "+this.remoteMediaHost+":"+this.remoteRtpPort); }); diff --git a/mozilla/zap/base/ClassUtils.js b/mozilla/zap/base/ClassUtils.js index 2febbb9960b..69512ea1b2f 100644 --- a/mozilla/zap/base/ClassUtils.js +++ b/mozilla/zap/base/ClassUtils.js @@ -44,7 +44,9 @@ EXPORTED_SYMBOLS = [ "StdClass", "ErrorReporter", "SupportsImpl", "AttributeParser", - "Unwrappable" ]; + "Unwrappable", + "PropertyBag", + "makePropertyBag" ]; // name our global object: function toString() { return "[ClassUtils.js]"; } @@ -495,11 +497,9 @@ AttributeParser.metafun( Adds a getter/setter pair for 'attrib' and a variable with name \n\ '_attrib' to the prototype. The setter will peform a syntax check \n\ using 'regex' and throw an error if the syntax is invalid. ", - function parsedAttrib(/*[opt] doc, attrib, regex, [opt] default*/) { + function parsedAttrib(/*[opt] doc, attrib, regex, default*/) { var i = arguments.length-1; - var defval = null; - if (typeof(arguments[i])!="function") - defval = arguments[i--]; + var defval = arguments[i--]; var regex = arguments[i--]; var attrib = arguments[i--]; @@ -535,3 +535,113 @@ var Unwrappable = makeClass("Unwrappable"); Unwrappable.getter("wrappedJSObject", function() { return this; }); + +//////////////////////////////////////////////////////////////////////// +// Class PropertyBag: a class implementing nsIPropertyBag, +// nsIPropertyBag2 and nsIWritablePropertyBag. +// Values are stored as properties on the instance, with keys prefixed +// by '$' (see ObjectUtils.js hash functions). + +var PropertyBag = makeClass("PropertyBag", SupportsImpl); +PropertyBag.addInterfaces(Components.interfaces.nsIPropertyBag, + Components.interfaces.nsIPropertyBag2, + Components.interfaces.nsIWritablePropertyBag); + +//---------------------------------------------------------------------- +// nsIPropertyBag implementation: + +/* readonly attribute nsISimpleEnumerator enumerator; */ +PropertyBag.getter( + "enumerator", + function get_enumerator() { + var keys = hashkeys(this); + var bag = this; + var i = 0; + return { // object implementing nsISimpleEnumerator + hasMoreElements : function() { return ikeys.length) throw Components.results.NS_ERROR_FAILURE; + var prop = { name: keys[i], value: bag.getProperty(keys[i]) }; + ++i; + return prop; + } + }; + }); + +/* nsIVariant getProperty(in AString name); */ +PropertyBag.fun( + function getProperty(key) { + var val = hashget(this, key); + if (val === undefined) throw(Components.results.NS_ERROR_FAILURE); + return val; + }); + +//---------------------------------------------------------------------- +// nsIPropertyBag2 implementation: +// XXX these methods will not perform type conversion when called +// directly from JS + +/* PRUint16 getPropertyAsUint16 (in AString prop); */ +PropertyBag.obj("getPropertyAsUint16", PropertyBag.prototype.getProperty); + +/* PRInt32 getPropertyAsInt32 (in AString prop); */ +PropertyBag.obj("getPropertyAsInt32", PropertyBag.prototype.getProperty); + +/* PRUint32 getPropertyAsUint32 (in AString prop); */ +PropertyBag.obj("getPropertyAsUint32", PropertyBag.prototype.getProperty); + +/* PRInt64 getPropertyAsInt64 (in AString prop); */ +PropertyBag.obj("getPropertyAsInt64", PropertyBag.prototype.getProperty); + +/* PRUint64 getPropertyAsUint64 (in AString prop); */ +PropertyBag.obj("getPropertyAsUint64", PropertyBag.prototype.getProperty); + +/* double getPropertyAsDouble (in AString prop); */ +PropertyBag.obj("getPropertyAsDouble", PropertyBag.prototype.getProperty); + +/* AString getPropertyAsAString (in AString prop); */ +PropertyBag.obj("getPropertyAsAString", PropertyBag.prototype.getProperty); + +/* ACString getPropertyAsACString (in AString prop); */ +PropertyBag.obj("getPropertyAsACString", PropertyBag.prototype.getProperty); + +/* AUTF8String getPropertyAsAUTF8String (in AString prop); */ +PropertyBag.obj("getPropertyAsAUTF8String", PropertyBag.prototype.getProperty); + +/* boolean getPropertyAsBool (in AString prop); */ +PropertyBag.obj("getPropertyAsBool", PropertyBag.prototype.getProperty); + +/* void getPropertyAsInterface (in AString prop, + in nsIIDRef iid, + [iid_is(iid), retval] out nsQIResult result); */ +PropertyBag.fun( + function getPropertyAsInterface(key, iid) { + return this.getProperty(key); + }); + +//PropertyBag.obj("getPropertyAsInterface", PropertyBag.prototype.getProperty); + +//---------------------------------------------------------------------- +// nsIWritablePropertyBag implementation: + +/* void setProperty(in AString name, in nsIVariant value); */ +PropertyBag.fun( + function setProperty(key, value) { + hashset(this, key, value); + }); + +/* void deleteProperty(in AString name); */ +PropertyBag.fun( + function deleteProperty(key) { + if (!hashhas(this, key)) + throw(Components.results.NS_ERROR_FAILURE); + hashdel(this, key); + }); + +//---------------------------------------------------------------------- + +// wrap 'obj' with nsIPropertyBag/nsIWritablePropertyBag interfaces +function makePropertyBag(obj) { + obj.__proto__ = PropertyBag.prototype; + return obj; +} diff --git a/mozilla/zap/sdp/Makefile.in b/mozilla/zap/sdp/Makefile.in index 18d2117de2f..29c6e74ceab 100644 --- a/mozilla/zap/sdp/Makefile.in +++ b/mozilla/zap/sdp/Makefile.in @@ -11,6 +11,7 @@ MODULE = zap_sdp EXTRA_PP_COMPONENTS = \ SdpService.js \ + MediaSession.js \ $(NULL) include $(topsrcdir)/config/rules.mk diff --git a/mozilla/zap/sdp/MediaSession.js b/mozilla/zap/sdp/MediaSession.js new file mode 100644 index 00000000000..1040392c9df --- /dev/null +++ b/mozilla/zap/sdp/MediaSession.js @@ -0,0 +1,135 @@ +// -*- moz-jssh-buffer-globalobj: "Components.classes['@mozilla.org/moz/jsloader;1'].getService(Components.interfaces.xpcIJSComponentLoader).importModule('rel:MediaSession.js')" -*- +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + + +debug("*** loading MediaSession\n"); + +Components.utils.importModule("resource:/jscodelib/JSComponentUtils.js"); +Components.utils.importModule("resource:/jscodelib/zap/ClassUtils.js"); +Components.utils.importModule("resource:/jscodelib/zap/ArrayUtils.js"); +Components.utils.importModule("resource:/jscodelib/zap/StringUtils.js"); +Components.utils.importModule("resource:/jscodelib/zap/ObjectUtils.js"); + +// name our global object: +function toString() { return "[MediaSession.js]"; } + +// object to hold component's documentation: +var _doc_ = {}; + +var PB = makePropertyBag; + +//////////////////////////////////////////////////////////////////////// +// Class MediaSession +// Maintains an SDP-negotiated media session + +var MediaSession = makeClass("MediaSession", SupportsImpl); +MediaSession.addInterfaces(Components.interfaces.zapIMediaSession); + +MediaSession.appendCtor( + function() { + this.mediaGraph = Components.classes["@mozilla.org/zap/mediagraph;1"].createInstance(Components.interfaces.zapIMediaGraph); + this.socketpair = this.mediaGraph.addNode("udp-socket-pair", null); + }); + +//---------------------------------------------------------------------- +// zapIMediaSession + +MediaSession.fun( + function start(remoteHost, remoteRTPPort, + remoteRTCPPort, remotePayloadFormat) { + this.ain = this.mediaGraph.addNode("audioin", null); + this.aout = this.mediaGraph.addNode("audioout", null); + this.enc = this.mediaGraph.addNode("speex-encoder", null); + this.dec = this.mediaGraph.addNode("speex-decoder", null); + this.buf1 = this.mediaGraph.addNode("buffer", PB({$prefill_size:2, $max_size:10})); + this.buf2 = this.mediaGraph.addNode("buffer", PB({$prefill_size:2, $max_size:10})); + this.speex2rtp = this.mediaGraph.addNode("speex-rtp-packetizer", + PB({$payload_type:remotePayloadFormat})); + this.rtp2speex = this.mediaGraph.addNode("speex-rtp-depacketizer", null); + this.rtpsession = this.mediaGraph.addNode("rtp-session", + PB({$address:remoteHost, + $rtp_port:remoteRTPPort, + $rtcp_port:remoteRTCPPort})); + // encoder pipe: + this.A = this.mediaGraph.connect(this.ain, null, this.enc, null); + this.B = this.mediaGraph.connect(this.enc, null, this.speex2rtp, null); + this.C = this.mediaGraph.connect(this.speex2rtp, null, + this.rtpsession, PB({$name:"local-rtp"})); + this.D = this.mediaGraph.connect(this.rtpsession, PB({$name:"remote-rtp"}), + this.buf1, null); + this.E = this.mediaGraph.connect(this.buf1, null, + this.socketpair, PB({$name:"socket-a"})); + // decoder pipe: + this.F = this.mediaGraph.connect(this.socketpair, PB({$name:"socket-a"}), + this.buf2, null); + this.G = this.mediaGraph.connect(this.buf2, null, + this.rtpsession, PB({$name:"remote-rtp"})); + this.H = this.mediaGraph.connect(this.rtpsession, PB({$name:"local-rtp"}), + this.rtp2speex, null); + this.I = this.mediaGraph.connect(this.rtp2speex, null, this.dec, null); + this.J = this.mediaGraph.connect(this.dec, null, this.aout, null); + }); + +MediaSession.getter( + "localRTPPort", + function getLocalRTPPort() { + var sp = this.mediaGraph.getNode(this.socketpair, Components.interfaces.zapIUDPSocketPair, true); + return sp.portA; + }); + +MediaSession.getter( + "localRTCPPort", + function getLocalRTCPPort() { + var sp = this.mediaGraph.getNode(this.socketpair, Components.interfaces.zapIUDPSocketPair, true); + return sp.portB; + }); + + +MediaSession.fun( + function shutdown() { + this.mediaGraph.shutdown(); + }); + +//////////////////////////////////////////////////////////////////////// +// Module definition + +NSGetModule = ComponentUtils.generateNSGetModule( + [{ className : "ZAP Media Session", + cid : Components.ID("{6ec361e6-eb0d-40ae-a2a5-5bcc942784b6}"), + contractID : "@mozilla.org/zap/mediasession;1", + factory : ComponentUtils.generateFactory(function() { return MediaSession.instantiate(); }) + }]); diff --git a/mozilla/zap/sdp/SdpService.js b/mozilla/zap/sdp/SdpService.js index 0a0093be0f8..79514583522 100644 --- a/mozilla/zap/sdp/SdpService.js +++ b/mozilla/zap/sdp/SdpService.js @@ -194,7 +194,7 @@ SdpGenericValue.fun( // zapISdpGenericValue implementation: // attribute ACString value; -SdpGenericValue.parsedAttrib("value", REGEXP_TEXT); +SdpGenericValue.parsedAttrib("value", REGEXP_TEXT, null); //////////////////////////////////////////////////////////////////////// @@ -283,10 +283,10 @@ SdpConnection.fun( // zapISdpConnection implementation: // attribute ACString addressType; -SdpConnection.parsedAttrib("addressType", REGEXP_TOKEN); +SdpConnection.parsedAttrib("addressType", REGEXP_TOKEN, null); // attribute ACString address; -SdpConnection.parsedAttrib("address", REGEXP_UNICAST_ADDRESS); //XXX add multicast +SdpConnection.parsedAttrib("address", REGEXP_UNICAST_ADDRESS, null); //XXX add multicast //////////////////////////////////////////////////////////////////////// @@ -305,7 +305,7 @@ SdpMediaFormat.fun( // zapISdpMediaFormat implementation: // attribute ACString format; -SdpMediaFormat.parsedAttrib("format", REGEXP_TOKEN); +SdpMediaFormat.parsedAttrib("format", REGEXP_TOKEN, null); //////////////////////////////////////////////////////////////////////// @@ -453,16 +453,16 @@ SdpMediaDescription.fun( // zapISdpMediaDescription implementation: // attribute ACString media; -SdpMediaDescription.parsedAttrib("media", REGEXP_TOKEN); +SdpMediaDescription.parsedAttrib("media", REGEXP_TOKEN, null); // attribute ACString long port; -SdpMediaDescription.parsedAttrib("port", REGEXP_DIGITS); +SdpMediaDescription.parsedAttrib("port", REGEXP_DIGITS, null); // attribute ACString portCount; -SdpMediaDescription.parsedAttrib("portCount", REGEXP_DIGITS_OR_NOTHING); +SdpMediaDescription.parsedAttrib("portCount", REGEXP_DIGITS_OR_NOTHING, null); // attribute ACString protocol; -SdpMediaDescription.parsedAttrib("protocol", REGEXP_PROTOCOL); +SdpMediaDescription.parsedAttrib("protocol", REGEXP_PROTOCOL, null); // void getFormats(out unsigned long count, // [retval, array, size_is(count)] out zapISdpMediaFormat formats); @@ -471,7 +471,7 @@ SdpMediaDescription.parsedAttrib("protocol", REGEXP_PROTOCOL); SdpMediaDescription.arr("Formats"); // attribute ACString information; -SdpMediaDescription.parsedAttrib("information", REGEXP_TEXT); +SdpMediaDescription.parsedAttrib("information", REGEXP_TEXT, null); // attribute zapISdpConnection connection; SdpMediaDescription.obj("connection", null); @@ -589,28 +589,28 @@ SdpSessionDescription.fun( SdpSessionDescription.parsedAttrib("protocolVersion", REGEXP_PROTOCOLVERSION, "0"); // attribute ACString username; -SdpSessionDescription.parsedAttrib("username", REGEXP_USERNAME); +SdpSessionDescription.parsedAttrib("username", REGEXP_USERNAME, null); // attribute ACString sessionID; -SdpSessionDescription.parsedAttrib("sessionID", REGEXP_DIGITS); +SdpSessionDescription.parsedAttrib("sessionID", REGEXP_DIGITS, null); // attribute ACString sessionVersion; -SdpSessionDescription.parsedAttrib("sessionVersion", REGEXP_DIGITS); +SdpSessionDescription.parsedAttrib("sessionVersion", REGEXP_DIGITS, null); // attribute ACString originAddressType; -SdpSessionDescription.parsedAttrib("originAddressType", REGEXP_TOKEN); +SdpSessionDescription.parsedAttrib("originAddressType", REGEXP_TOKEN, null); // attribute ACString originAddress; -SdpSessionDescription.parsedAttrib("originAddress", REGEXP_UNICAST_ADDRESS); +SdpSessionDescription.parsedAttrib("originAddress", REGEXP_UNICAST_ADDRESS, null); // attribute ACString sessionName; -SdpSessionDescription.parsedAttrib("sessionName", REGEXP_TEXT); +SdpSessionDescription.parsedAttrib("sessionName", REGEXP_TEXT, null); // attribute ACString information; -SdpSessionDescription.parsedAttrib("information", REGEXP_TEXT); +SdpSessionDescription.parsedAttrib("information", REGEXP_TEXT, null); // attribute ACString uri; -SdpSessionDescription.parsedAttrib("uri", REGEXP_URI); +SdpSessionDescription.parsedAttrib("uri", REGEXP_URI, null); // void getEmailAddresses(out unsigned long count, // [retval, array, size_is(count)] out zapISdpEmailAddress addresses); diff --git a/mozilla/zap/sdp/idl/Makefile.in b/mozilla/zap/sdp/idl/Makefile.in index e1a2fdb300c..e759b92b9e8 100644 --- a/mozilla/zap/sdp/idl/Makefile.in +++ b/mozilla/zap/sdp/idl/Makefile.in @@ -23,6 +23,7 @@ XPIDLSRCS = \ zapISdpZoneAdjustments.idl \ zapISdpGenericValue.idl \ zapISdpConnection.idl \ + zapIMediaSession.idl \ $(NULL) include $(topsrcdir)/config/rules.mk diff --git a/mozilla/zap/sdp/idl/zapIMediaSession.idl b/mozilla/zap/sdp/idl/zapIMediaSession.idl new file mode 100644 index 00000000000..ce7b755e377 --- /dev/null +++ b/mozilla/zap/sdp/idl/zapIMediaSession.idl @@ -0,0 +1,50 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "nsISupports.idl" + +[scriptable, uuid(af83aea5-6268-47a7-97e8-5252e1cd379b)] +interface zapIMediaSession : nsISupports +{ + void start(in ACString remoteHost, in unsigned short remoteRTPPort, + in unsigned short remoteRTCPPort, + in unsigned short remotePayloadFormat); + + readonly attribute unsigned short localRTPPort; + readonly attribute unsigned short localRTCPPort; + + void shutdown(); +}; diff --git a/mozilla/zap/sip/SipSyntaxFactory.js b/mozilla/zap/sip/SipSyntaxFactory.js index 0525f7d1243..f25f47093c2 100644 --- a/mozilla/zap/sip/SipSyntaxFactory.js +++ b/mozilla/zap/sip/SipSyntaxFactory.js @@ -516,12 +516,10 @@ SipSyntaxObject.metafun( which should return a serialized string representation of the elements. \n\ TODO: XXX add escaping filters. ", function parsedHash(/*[opt] doc, name, serializer, tokenizer, - re_name, re_value, [opt] re_hash*/) { + re_name, re_value, re_hash*/) { // unpack args: var i = arguments.length-1; - var re_hash = {}; - if (typeof(arguments[i]) == "object") - re_hash = arguments[i--]; + var re_hash = arguments[i--]; var re_value = arguments[i--]; var re_name = arguments[i--]; var tokenizer = arguments[i--]; @@ -636,13 +634,13 @@ SipSIPURI.fun( SipSIPURI.obj("sips", false); // attribute ACString userinfo; -SipSIPURI.parsedAttrib("userinfo", REGEXP_USERINFO); +SipSIPURI.parsedAttrib("userinfo", REGEXP_USERINFO, null); // attribute ACString host; -SipSIPURI.parsedAttrib("host", REGEXP_HOST); +SipSIPURI.parsedAttrib("host", REGEXP_HOST, null); // attribute ACString port; -SipSIPURI.parsedAttrib("port", REGEXP_PORT); +SipSIPURI.parsedAttrib("port", REGEXP_PORT, null); // ACString getURIParameter(in ACString name); // boolean hasURIParameter(in ACString name); @@ -674,7 +672,8 @@ SipSIPURI.parsedHash( SERIALIZER_URI_HEADERS, TOKENIZER_URI_HEADERS, REGEXP_URI_HEADER_NAME, - REGEXP_URI_HEADER_VALUE); + REGEXP_URI_HEADER_VALUE, + {}); //---------------------------------------------------------------------- @@ -730,7 +729,7 @@ SipAddress.fun( // zapISipAddress implementation: // attribute AUTF8String displayName; -SipAddress.parsedAttrib("displayName", REGEXP_DISPLAY_NAME); +SipAddress.parsedAttrib("displayName", REGEXP_DISPLAY_NAME, null); // attribute zapISipURI uri; SipAddress.obj("uri", null); @@ -906,7 +905,8 @@ SipReplyToHeader.parsedHash( SERIALIZER_PARAMS, TOKENIZER_GENERIC_PARAMS, REGEXP_TOKEN, - REGEXP_GEN_VALUE); + REGEXP_GEN_VALUE, + {}); //---------------------------------------------------------------------- @@ -1115,7 +1115,7 @@ SipCSeqHeader.fun( // zapISipCSeqHeader implementation // attribute ACString method; -SipCSeqHeader.parsedAttrib("method", REGEXP_TOKEN); +SipCSeqHeader.parsedAttrib("method", REGEXP_TOKEN, null); // attribute unsigned long sequenceNumber; SipCSeqHeader.obj("sequenceNumber", 0); @@ -1185,10 +1185,10 @@ SipContentTypeHeader.fun( // zapISipContentTypeHeader implementation // attribute ACString type; -SipContentTypeHeader.parsedAttrib("type", REGEXP_TOKEN); +SipContentTypeHeader.parsedAttrib("type", REGEXP_TOKEN, null); // attribute ACString subType; -SipContentTypeHeader.parsedAttrib("subType", REGEXP_TOKEN); +SipContentTypeHeader.parsedAttrib("subType", REGEXP_TOKEN, null); // ACString getParameter(in ACString name); // boolean hasParameter(in ACString name); @@ -1201,7 +1201,8 @@ SipContentTypeHeader.parsedHash( SERIALIZER_PARAMS, TOKENIZER_GENERIC_PARAMS, REGEXP_TOKEN, - REGEXP_GEN_VALUE); + REGEXP_GEN_VALUE, + {}); //---------------------------------------------------------------------- @@ -1236,7 +1237,7 @@ SipCallIDHeader.fun( // zapISipCallIDHeader implementation // attribute ACString callID; -SipCallIDHeader.parsedAttrib("callID", REGEXP_CALLID); +SipCallIDHeader.parsedAttrib("callID", REGEXP_CALLID, null); //---------------------------------------------------------------------- @@ -1273,19 +1274,19 @@ SipViaHeader.fun( // zapISipViaHeader implementation // attribute ACString protocol; -SipViaHeader.parsedAttrib("protocolName", REGEXP_TOKEN); +SipViaHeader.parsedAttrib("protocolName", REGEXP_TOKEN, null); // attribute ACString version; -SipViaHeader.parsedAttrib("protocolVersion", REGEXP_TOKEN); +SipViaHeader.parsedAttrib("protocolVersion", REGEXP_TOKEN, null); // attribute ACString transport; -SipViaHeader.parsedAttrib("transport", REGEXP_TOKEN); +SipViaHeader.parsedAttrib("transport", REGEXP_TOKEN, null); // attribute ACString host; -SipViaHeader.parsedAttrib("host", REGEXP_HOST); +SipViaHeader.parsedAttrib("host", REGEXP_HOST, null); // attribute ACString port; -SipViaHeader.parsedAttrib("port", REGEXP_PORT); +SipViaHeader.parsedAttrib("port", REGEXP_PORT, null); // ACString getParameter(in ACString name); // boolean hasParameter(in ACString name); @@ -1340,7 +1341,7 @@ SipAllowHeader.fun( //---------------------------------------------------------------------- // zapISipAllowHeader implementation -SipAllowHeader.parsedAttrib("method", REGEXP_TOKEN); +SipAllowHeader.parsedAttrib("method", REGEXP_TOKEN, null); //---------------------------------------------------------------------- @@ -1428,7 +1429,7 @@ SipPriorityHeader.fun( // zapISipPriorityHeader implementation // attribute ACString priority; -SipPriorityHeader.parsedAttrib("priority", REGEXP_TOKEN); +SipPriorityHeader.parsedAttrib("priority", REGEXP_TOKEN, null); //---------------------------------------------------------------------- @@ -1457,7 +1458,7 @@ SipUnknownHeader.fun( // zapISipUnknownHeader implementation: // attribute AUTF8String value; -SipUnknownHeader.parsedAttrib("value", REGEXP_EXTENSION_HEADER_VALUE); +SipUnknownHeader.parsedAttrib("value", REGEXP_EXTENSION_HEADER_VALUE, null); //---------------------------------------------------------------------- @@ -1740,7 +1741,7 @@ SipRequest.obj("isRequest", true); // zapISipRequest implementation: // attribute ACString method; -SipRequest.parsedAttrib("method", REGEXP_TOKEN); +SipRequest.parsedAttrib("method", REGEXP_TOKEN, null); // attribute zapISipURI requestURI; SipMessage.obj("requestURI", null); @@ -1790,10 +1791,10 @@ SipResponse.obj("isRequest", false); // zapISipResponse implementation: // attribute ACString statusCode; -SipResponse.parsedAttrib("statusCode", REGEXP_STATUS_CODE); +SipResponse.parsedAttrib("statusCode", REGEXP_STATUS_CODE, null); // attribute AUTF8String reasonPhrase; -SipResponse.parsedAttrib("reasonPhrase", REGEXP_REASON_PHRASE); +SipResponse.parsedAttrib("reasonPhrase", REGEXP_REASON_PHRASE, null); //---------------------------------------------------------------------- // zapISipSyntaxObject implementation: diff --git a/mozilla/zap/zmk/Makefile.in b/mozilla/zap/zmk/Makefile.in new file mode 100644 index 00000000000..9d229a959a0 --- /dev/null +++ b/mozilla/zap/zmk/Makefile.in @@ -0,0 +1,11 @@ +DEPTH = ../.. +topsrcdir = @top_srcdir@ +srcdir = @srcdir@ +VPATH = @srcdir@ + +include $(DEPTH)/config/autoconf.mk + +DIRS = portaudio_v18_1 speex-1.1.10 src + +include $(topsrcdir)/config/rules.mk + diff --git a/mozilla/zap/zmk/portaudio_v18_1/LICENSE.txt b/mozilla/zap/zmk/portaudio_v18_1/LICENSE.txt new file mode 100755 index 00000000000..7a95bee3f8a --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/LICENSE.txt @@ -0,0 +1,65 @@ +Portable header file to contain: +/* + * PortAudio Portable Real-Time Audio Library + * PortAudio API Header File + * Latest version available at: http://www.audiomulch.com/portaudio/ + * + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + + +Implementation files to contain: +/* + * PortAudio Portable Real-Time Audio Library + * Latest version at: http://www.audiomulch.com/portaudio/ + * Implementation + * Copyright (c) 1999-2000 + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ \ No newline at end of file diff --git a/mozilla/zap/zmk/portaudio_v18_1/Makefile.in b/mozilla/zap/zmk/portaudio_v18_1/Makefile.in new file mode 100755 index 00000000000..2d20ab764d7 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/Makefile.in @@ -0,0 +1,107 @@ +DEPTH = ../../.. +topsrcdir = @top_srcdir@ +srcdir = @srcdir@ +VPATH = @srcdir@ + +include $(DEPTH)/config/autoconf.mk + + +MODULE = portaudio_v18_1 +LIBRARY_NAME = moz_portaudio_v18_1 +#LIB_IS_C_ONLY = 1 +FORCE_STATIC_LIB= 1 + +CSRCS = \ + pa_common/pa_convert.c \ + pa_common/pa_lib.c \ + $(NULL) + +EXPORTS = \ + pa_common/portaudio.h \ + $(NULL) + +ifeq ($(OS_ARCH),WINNT) +CSRCS += \ + pa_win_ds/dsound_wrapper.c \ + pa_win_ds/pa_dsound.c \ + $(NULL) + + +OS_LIBS += dsound.lib winmm.lib +endif + +ifeq ($(OS_ARCH),Linux) +CSRCS += \ + pa_unix_oss/pa_unix.c \ + pa_unix_oss/pa_unix_oss.c \ + $(NULL) +endif + +#XXX Mac build + +SIMPLE_PROGRAMS = \ +pa_tests/debug_convert$(BIN_SUFFIX) \ +pa_tests/debug_dither_calc$(BIN_SUFFIX) \ +pa_tests/debug_dual$(BIN_SUFFIX) \ +pa_tests/debug_multi_in$(BIN_SUFFIX) \ +pa_tests/debug_multi_out$(BIN_SUFFIX) \ +pa_tests/debug_record$(BIN_SUFFIX) \ +pa_tests/debug_record_reuse$(BIN_SUFFIX) \ +pa_tests/debug_sine$(BIN_SUFFIX) \ +pa_tests/debug_sine_amp$(BIN_SUFFIX) \ +pa_tests/debug_sine_formats$(BIN_SUFFIX) \ +pa_tests/debug_srate$(BIN_SUFFIX) \ +pa_tests/debug_test1$(BIN_SUFFIX) \ +pa_tests/pa_devs$(BIN_SUFFIX) \ +pa_tests/pa_fuzz$(BIN_SUFFIX) \ +pa_tests/pa_minlat$(BIN_SUFFIX) \ +pa_tests/paqa_devs$(BIN_SUFFIX) \ +pa_tests/paqa_errs$(BIN_SUFFIX) \ +pa_tests/patest1$(BIN_SUFFIX) \ +pa_tests/patest_buffer$(BIN_SUFFIX) \ +pa_tests/patest_clip$(BIN_SUFFIX) \ +pa_tests/patest_dither$(BIN_SUFFIX) \ +pa_tests/patest_hang$(BIN_SUFFIX) \ +pa_tests/patest_latency$(BIN_SUFFIX) \ +pa_tests/patest_leftright$(BIN_SUFFIX) \ +pa_tests/patest_longsine$(BIN_SUFFIX) \ +pa_tests/patest_many$(BIN_SUFFIX) \ +pa_tests/patest_maxsines$(BIN_SUFFIX) \ +pa_tests/patest_multi_sine$(BIN_SUFFIX) \ +pa_tests/patest_pink$(BIN_SUFFIX) \ +pa_tests/patest_record$(BIN_SUFFIX) \ +pa_tests/patest_ringmix$(BIN_SUFFIX) \ +pa_tests/patest_saw$(BIN_SUFFIX) \ +pa_tests/patest_sine$(BIN_SUFFIX) \ +pa_tests/patest_sine8$(BIN_SUFFIX) \ +pa_tests/patest_sine_formats$(BIN_SUFFIX) \ +pa_tests/patest_sine_time$(BIN_SUFFIX) \ +pa_tests/patest_stop$(BIN_SUFFIX) \ +pa_tests/patest_sync$(BIN_SUFFIX) \ +pa_tests/patest_toomanysines$(BIN_SUFFIX) \ +pa_tests/patest_underflow$(BIN_SUFFIX) \ +pa_tests/patest_wire$(BIN_SUFFIX) + + +include $(topsrcdir)/config/rules.mk + +LOCAL_INCLUDES = -I$(srcdir)/pa_common + +# The portaudio code is dispersed over several subdirectory, but +# building separate libs is overkill. We drive the whole build from +# this Makefile, but we need to make sure that the object dirs exist: + +EXTRA_OBJDIRS = pa_common \ + pa_win_wmme \ + pa_win_ds \ + pa_unix_oss \ + pa_tests \ + $(NULL) + +export:: + mkdir -p $(EXTRA_OBJDIRS) + + +LIBS += $(LIB_PREFIX)$(LIBRARY_NAME).$(LIB_SUFFIX) + +$(SIMPLE_PROGRAMS): %$(BIN_SUFFIX): %.$(OBJ_SUFFIX) $(STATIC_LIBRARY) diff --git a/mozilla/zap/zmk/portaudio_v18_1/Makefile.in.portaudio b/mozilla/zap/zmk/portaudio_v18_1/Makefile.in.portaudio new file mode 100644 index 00000000000..9494d4fa620 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/Makefile.in.portaudio @@ -0,0 +1,96 @@ +# +# PortAudio Makefile.in +# +# Dominic Mazzoni +# + +PREFIX = @prefix@ +CC = @CC@ +CFLAGS = @CFLAGS@ -Ipa_common +LIBS = @LIBS@ +AR = @AR@ +RANLIB = @RANLIB@ +INSTALL = @INSTALL@ +SHARED_FLAGS = @SHARED_FLAGS@ +DLL_LIBS = @DLL_LIBS@ + +OTHER_OBJS = @OTHER_OBJS@ + +PALIB = libportaudio.a +PADLL = @PADLL@ +PADLLV = $(PADLL).0.0.18 +PAINC = pa_common/portaudio.h + +COMMON_OBJS = \ + pa_common/pa_convert.o \ + pa_common/pa_lib.o + +TESTS = \ + bin/patest_buffer \ + bin/patest_clip \ + bin/patest_dither \ + bin/patest_hang \ + bin/patest_latency \ + bin/patest_leftright \ + bin/patest_longsine \ + bin/patest_many \ + bin/patest_maxsines \ + bin/patest_multi_sine \ + bin/patest_pink \ + bin/patest_record \ + bin/patest_ringmix \ + bin/patest_saw \ + bin/patest_sine8 \ + bin/patest_sine \ + bin/patest_sine_formats \ + bin/patest_sine_time \ + bin/patest_stop \ + bin/patest_sync \ + bin/patest_toomanysines \ + bin/patest_underflow \ + bin/patest_wire + +OBJS = $(COMMON_OBJS) $(OTHER_OBJS) + +all: lib/$(PALIB) lib/$(PADLLV) tests + +tests: bin/ $(TESTS) + +lib/$(PALIB): lib/ $(OBJS) Makefile $(PAINC) + $(AR) ruv lib/$(PALIB) $(OBJS) + $(RANLIB) lib/$(PALIB) + +lib/$(PADLLV): lib/ $(OBJS) Makefile $(PAINC) + $(CC) $(SHARED_FLAGS) -o lib/$(PADLLV) $(OBJS) $(DLL_LIBS) + +$(TESTS): bin/%: lib/$(PALIB) Makefile $(PAINC) pa_tests/%.c + $(CC) -o $@ $(CFLAGS) pa_tests/$*.c lib/$(PALIB) $(LIBS) + +install: lib/$(PALIB) lib/$(PADLLV) + $(INSTALL) -m 644 lib/$(PADLLV) $(PREFIX)/lib/$(PADLLV) + $(INSTALL) -m 644 lib/$(PALIB) $(PREFIX)/lib/$(PALIB) + cd $(PREFIX)/lib && rm -f $(PADLL) && ln -s $(PADLLV) $(PADLL) + $(INSTALL) -m 644 pa_common/portaudio.h $(PREFIX)/include/portaudio.h + @echo "" + @echo "------------------------------------------------------------" + @echo "PortAudio was successfully installed." + @echo "" + @echo "On some systems (e.g. Linux) you should run 'ldconfig' now" + @echo "to make the shared object available. You may also need to" + @echo "modify your LD_LIBRARY_PATH environment variable to include" + @echo "the directory $(PREFIX)/lib" + @echo "------------------------------------------------------------" + @echo "" + +clean: + rm -f $(OBJS) $(TESTS) lib/$(PALIB) + rm -f config.log config.status + +%.o: %.c Makefile $(PAINC) + $(CC) -c $(CFLAGS) $< -o $@ + +bin: + mkdir bin + +lib: + mkdir lib diff --git a/mozilla/zap/zmk/portaudio_v18_1/Makefile.linux b/mozilla/zap/zmk/portaudio_v18_1/Makefile.linux new file mode 100755 index 00000000000..5b35453377b --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/Makefile.linux @@ -0,0 +1,59 @@ +# Make PortAudio for Linux +# Updated 2001/08/25 Bill Eldridge bill@rfa.org +# Updated 2001/10/16, philburk@softsynth.com, s/unix_oss/unix_oss/ +# Updated 2002/04/30 Bill Eldridge bill@rfa.org +# Made the libinstall and tests compile a bit cleaner + +# A pretty bare makefile, that figures out all the test files +# and compiles them against the library in the pa_unix_oss directory. + +# Do "make all" and then when happy, "make libinstall" +# (if not happy, "make clean") + +# The ldconfig stuff in libinstall is the wrong way to do it - +# someone tell me the right way, please + + +LIBS = -lm -lpthread + +CDEFINES = -I../pa_common +CFLAGS = -g +LIBINST = /usr/local/lib + +TESTS:= $(wildcard pa_tests/pa*.c pa_tests/debug*.c) +TESTO:= $(wildcard pa_tests/pa*.o pa_tests/debug*.o) + +LIBFILES:= ./pa_common/pa_lib.c ./pa_unix_oss/pa_unix_oss.c ./pa_unix_oss/pa_unix.c + +#all: sharedlib libinstall tests +all: sharedlib libinstall testo testq + +.c.o: + -gcc $(CFLAGS) -c -I./pa_common $< -o $*.o + +.o: + -gcc $*.o -o $* -Lpa_unix_oss -lportaudio $(LIBS) + +#.c.o: +# -gcc -c -I./pa_common $< -o $*.o +# -gcc $*.o -o $* -Lpa_unix_oss $(LIBS) -lportaudio + + +sharedlib: $(LIBFILES:.c=.o) + gcc -shared -o ./pa_unix_oss/libportaudio.so ./pa_common/pa_lib.o ./pa_unix_oss/pa_unix_oss.o ./pa_unix_oss/pa_unix.o + +libinstall: ./pa_unix_oss/libportaudio.so + @cp -f ./pa_unix_oss/libportaudio.so $(LIBINST) + @/sbin/ldconfig + +testo: $(TESTS:.c=.o) + +testq: $(TESTO:.o=) + +clean: + -@rm -f $(TESTS:.c=.o) + -@rm -f $(TESTS:.c=) + -@rm -f $(LIBFILES:.c=.o) + -@rm -f ./pa_unix_oss/libportaudio.so + + diff --git a/mozilla/zap/zmk/portaudio_v18_1/Makefile.mingw b/mozilla/zap/zmk/portaudio_v18_1/Makefile.mingw new file mode 100755 index 00000000000..3df64425cfc --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/Makefile.mingw @@ -0,0 +1,57 @@ + +# Makefile for PortAudio on mingw (http://mingw.sourceforge.net) + +# Contributed by Bill Eldridge, bill@rfa.org, Radio Free Asia +# Copyright 2002/02/20, GPL + +# Uses a common mingw32 cross-compiler that defaults +# to everything in /usr/local/cross-tools + +# First edit your path with +# export PATH=/usr/local/cross-tools/bin:$PATH + +# Usage: make -f Makefile.mingw all +# or make -f Makefile.mingw sharedlib +# make -f Makefile.mingw tests +# +# Then copy executables & portaudio.dll to your Windows machine +# +# To make work with pa_win_ds, you'll have to substitue +# all the pa_win_wmme files with pa_win_ds files, no biggie. + +CC= i586-mingw32msvc-gcc +DLLTOOL= i586-mingw32msvc-dlltool +DLLWRAP= i586-mingw32msvc-dllwrap + +ARCH= pa_win_wmme + +TESTS:= $(wildcard pa_tests/pa*.c pa_tests/debug*.c) + +.c.o: + -$(CC) -c -I./pa_common $< -o $*.o + -$(CC) $*.o -o $*.exe -L/usr/local/lib -L$(ARCH) -lportaudio.dll -lwinmm + +all: sharedlib tests + +sharedlib: ./pa_common/pa_lib.c + $(CC) -c -I./pa_common pa_common/pa_lib.c -o pa_common/pa_lib.o + $(CC) -c -I./pa_common pa_win_wmme/pa_win_wmme.c -o pa_win_wmme/pa_win_wmme.o + $(CC) -shared -mthreads -o portaudio.dll pa_common/pa_lib.o pa_win_wmme/pa_win_wmme.o -L/usr/local/cross-tools/i586-win32msvc/lib -lwinmm -lm + $(DLLWRAP) --export-all --output-def=libportaudio.def --output-lib=libportaudio.a --dllname=portaudio.dll --drivername=i586-mingw32msvc-gcc pa_common/pa_lib.o pa_win_wmme/pa_win_wmme.o -L/usr/local/cross-tools/i586-win32msvc/lib -lwinmm -lm + $(CC) -shared -Wl,--enable-auto-image-base -o portaudio.dll -Wl,--out-implib=pa_win_wmme/libportaudio.dll.a pa_common/pa_lib.o pa_win_wmme/pa_win_wmme.o -L/usr/local/cross-tools/i586-win32msvc/lib -lwinmm + + +tests: $(TESTS:.c=.o) + +sine: + $(CC) -c -I./pa_common pa_tests/patest_sine.c -o pa_tests/patest_sine.o + $(CC) pa_tests/patest_sine.o -o pa_tests/patest_sine.exe -L/usr/local/lib -lportaudio.dll -lwinmm + +clean: + -rm ./pa_tests/*.exe + -rm ./pa_tests/*.o + +nothing: + $(CC) pa_tests/patest_sine.o -L/usr/lib/w32api -L./pa_win_wmme -lportaudio.dll -lwinmm + + diff --git a/mozilla/zap/zmk/portaudio_v18_1/Makefile.solaris b/mozilla/zap/zmk/portaudio_v18_1/Makefile.solaris new file mode 100755 index 00000000000..2f638743873 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/Makefile.solaris @@ -0,0 +1,59 @@ +# Make PortAudio for Linux +# Updated 2001/08/25 Bill Eldridge bill@rfa.org +# Updated 2001/10/16, philburk@softsynth.com, s/unix_oss/unix_oss/ +# Updated 2002/04/30 Bill Eldridge bill@rfa.org +# Made the libinstall and tests compile a bit cleaner + +# A pretty bare makefile, that figures out all the test files +# and compiles them against the library in the pa_unix_oss directory. + +# Do "make all" and then when happy, "make libinstall" +# (if not happy, "make clean") + +# The ldconfig stuff in libinstall is the wrong way to do it - +# someone tell me the right way, please + + +LIBS = -lm -lpthread -lrt + +CDEFINES = -I../pa_common +CFLAGS = -g +LIBINST = /usr/local/lib + +TESTS:= $(wildcard pa_tests/pa*.c pa_tests/debug*.c) +TESTO:= $(wildcard pa_tests/pa*.o pa_tests/debug*.o) + +LIBFILES:= ./pa_common/pa_lib.c ./pa_unix_oss/pa_unix_solaris.c ./pa_unix_oss/pa_unix.c + +#all: sharedlib libinstall tests +all: sharedlib libinstall testo testq + +.c.o: + -gcc $(CFLAGS) -c -I./pa_common $< -o $*.o + +.o: + -gcc $*.o -o $* -Lpa_unix_oss -lportaudio $(LIBS) + +#.c.o: +# -gcc -c -I./pa_common $< -o $*.o +# -gcc $*.o -o $* -Lpa_unix_oss $(LIBS) -lportaudio + + +sharedlib: $(LIBFILES:.c=.o) + gcc -shared -o ./pa_unix_oss/libportaudio.so ./pa_common/pa_lib.o ./pa_unix_oss/pa_unix_solaris.o ./pa_unix_oss/pa_unix.o + +libinstall: ./pa_unix_oss/libportaudio.so + @cp -f ./pa_unix_oss/libportaudio.so $(LIBINST) + @/sbin/ldconfig + +testo: $(TESTS:.c=.o) + +testq: $(TESTO:.o=) + +clean: + -@rm -f $(TESTS:.c=.o) + -@rm -f $(TESTS:.c=) + -@rm -f $(LIBFILES:.c=.o) + -@rm -f ./pa_unix_oss/libportaudio.so + + diff --git a/mozilla/zap/zmk/portaudio_v18_1/README.txt b/mozilla/zap/zmk/portaudio_v18_1/README.txt new file mode 100755 index 00000000000..c05ec810f37 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/README.txt @@ -0,0 +1,81 @@ +README for PortAudio +Implementations for PC DirectSound and Mac SoundManager + +/* + * PortAudio Portable Real-Time Audio Library + * Latest Version at: http://www.portaudio.com// + * + * Copyright (c) 1999-2000 Phil Burk and Ross Bencina + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +PortAudio is a portable audio I/O library designed for cross-platform +support of audio. It uses a callback mechanism to request audio processing. +Audio can be generated in various formats, including 32 bit floating point, +and will be converted to the native format internally. + +Documentation: + See "pa_common/portaudio.h" for API spec. + See docs folder for a tutorial. + Also see http://www.portaudio.com/docs/ + And see "pa_tests/patest_saw.c" for an example. + +For information on compiling programs with PortAudio, please see the +tutorial at: + + http://www.portaudio.com/docs/pa_tutorial.html + +Important Files and Folders: + pa_common/ = platform independant code + pa_common/portaudio.h = header file for PortAudio API. Specifies API. + pa_common/pa_lib.c = host independant code for all implementations. + + pablio = simple blocking read/write interface + +Platform Implementations + pa_asio = ASIO for Windows and Macintosh + pa_beos = BeOS + pa_mac = Macintosh Sound Manager for OS 8,9 and Carbon + pa_mac_core = Macintosh Core Audio for OS X + pa_sgi = Silicon Graphics AL + pa_unix_oss = OSS implementation for various Unixes + pa_win_ds = Windows Direct Sound + pa_win_wmme = Windows MME (most widely supported) + +Test Programs + pa_tests/pa_fuzz.c = guitar fuzz box + pa_tests/pa_devs.c = print a list of available devices + pa_tests/pa_minlat.c = determine minimum latency for your machine + pa_tests/paqa_devs.c = self test that opens all devices + pa_tests/paqa_errs.c = test error detection and reporting + pa_tests/patest_clip.c = hear a sine wave clipped and unclipped + pa_tests/patest_dither.c = hear effects of dithering (extremely subtle) + pa_tests/patest_pink.c = fun with pink noise + pa_tests/patest_record.c = record and playback some audio + pa_tests/patest_maxsines.c = how many sine waves can we play? Tests Pa_GetCPULoad(). + pa_tests/patest_sine.c = output a sine wave in a simple PA app + pa_tests/patest_sync.c = test syncronization of audio and video + pa_tests/patest_wire.c = pass input to output, wire simulator diff --git a/mozilla/zap/zmk/portaudio_v18_1/config.guess b/mozilla/zap/zmk/portaudio_v18_1/config.guess new file mode 100755 index 00000000000..10fb02b719d --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/config.guess @@ -0,0 +1,1308 @@ +#! /bin/sh +# Attempt to guess a canonical system name. +# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001 +# Free Software Foundation, Inc. + +timestamp='2001-10-05' + +# This file is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +# +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + +# Originally written by Per Bothner . +# Please send patches to . Submit a context +# diff and a properly formatted ChangeLog entry. +# +# This script attempts to guess a canonical system name similar to +# config.sub. If it succeeds, it prints the system name on stdout, and +# exits with 0. Otherwise, it exits with 1. +# +# The plan is that this can be called by configure scripts if you +# don't specify an explicit build system type. + +me=`echo "$0" | sed -e 's,.*/,,'` + +usage="\ +Usage: $0 [OPTION] + +Output the configuration name of the system \`$me' is run on. + +Operation modes: + -h, --help print this help, then exit + -t, --time-stamp print date of last modification, then exit + -v, --version print version number, then exit + +Report bugs and patches to ." + +version="\ +GNU config.guess ($timestamp) + +Originally written by Per Bothner. +Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001 +Free Software Foundation, Inc. + +This is free software; see the source for copying conditions. There is NO +warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." + +help=" +Try \`$me --help' for more information." + +# Parse command line +while test $# -gt 0 ; do + case $1 in + --time-stamp | --time* | -t ) + echo "$timestamp" ; exit 0 ;; + --version | -v ) + echo "$version" ; exit 0 ;; + --help | --h* | -h ) + echo "$usage"; exit 0 ;; + -- ) # Stop option processing + shift; break ;; + - ) # Use stdin as input. + break ;; + -* ) + echo "$me: invalid option $1$help" >&2 + exit 1 ;; + * ) + break ;; + esac +done + +if test $# != 0; then + echo "$me: too many arguments$help" >&2 + exit 1 +fi + + +dummy=dummy-$$ +trap 'rm -f $dummy.c $dummy.o $dummy.rel $dummy; exit 1' 1 2 15 + +# CC_FOR_BUILD -- compiler used by this script. +# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still +# use `HOST_CC' if defined, but it is deprecated. + +set_cc_for_build='case $CC_FOR_BUILD,$HOST_CC,$CC in + ,,) echo "int dummy(){}" > $dummy.c ; + for c in cc gcc c89 ; do + ($c $dummy.c -c -o $dummy.o) >/dev/null 2>&1 ; + if test $? = 0 ; then + CC_FOR_BUILD="$c"; break ; + fi ; + done ; + rm -f $dummy.c $dummy.o $dummy.rel ; + if test x"$CC_FOR_BUILD" = x ; then + CC_FOR_BUILD=no_compiler_found ; + fi + ;; + ,,*) CC_FOR_BUILD=$CC ;; + ,*,*) CC_FOR_BUILD=$HOST_CC ;; +esac' + +# This is needed to find uname on a Pyramid OSx when run in the BSD universe. +# (ghazi@noc.rutgers.edu 1994-08-24) +if (test -f /.attbin/uname) >/dev/null 2>&1 ; then + PATH=$PATH:/.attbin ; export PATH +fi + +UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown +UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown +UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown +UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown + +# Note: order is significant - the case branches are not exclusive. + +case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in + *:NetBSD:*:*) + # NetBSD (nbsd) targets should (where applicable) match one or + # more of the tupples: *-*-netbsdelf*, *-*-netbsdaout*, + # *-*-netbsdecoff* and *-*-netbsd*. For targets that recently + # switched to ELF, *-*-netbsd* would select the old + # object file format. This provides both forward + # compatibility and a consistent mechanism for selecting the + # object file format. + # Determine the machine/vendor (is the vendor relevant). + case "${UNAME_MACHINE}" in + amiga) machine=m68k-unknown ;; + arm32) machine=arm-unknown ;; + atari*) machine=m68k-atari ;; + sun3*) machine=m68k-sun ;; + mac68k) machine=m68k-apple ;; + macppc) machine=powerpc-apple ;; + hp3[0-9][05]) machine=m68k-hp ;; + ibmrt|romp-ibm) machine=romp-ibm ;; + sparc*) machine=`uname -p`-unknown ;; + *) machine=${UNAME_MACHINE}-unknown ;; + esac + # The Operating System including object format, if it has switched + # to ELF recently, or will in the future. + case "${UNAME_MACHINE}" in + i386|sparc|amiga|arm*|hp300|mvme68k|vax|atari|luna68k|mac68k|news68k|next68k|pc532|sun3*|x68k) + eval $set_cc_for_build + if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \ + | grep __ELF__ >/dev/null + then + # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout). + # Return netbsd for either. FIX? + os=netbsd + else + os=netbsdelf + fi + ;; + *) + os=netbsd + ;; + esac + # The OS release + release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'` + # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM: + # contains redundant information, the shorter form: + # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used. + echo "${machine}-${os}${release}" + exit 0 ;; + amiga:OpenBSD:*:*) + echo m68k-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + arc:OpenBSD:*:*) + echo mipsel-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + hp300:OpenBSD:*:*) + echo m68k-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + mac68k:OpenBSD:*:*) + echo m68k-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + macppc:OpenBSD:*:*) + echo powerpc-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + mvme68k:OpenBSD:*:*) + echo m68k-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + mvme88k:OpenBSD:*:*) + echo m88k-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + mvmeppc:OpenBSD:*:*) + echo powerpc-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + pmax:OpenBSD:*:*) + echo mipsel-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + sgi:OpenBSD:*:*) + echo mipseb-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + sun3:OpenBSD:*:*) + echo m68k-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + wgrisc:OpenBSD:*:*) + echo mipsel-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + *:OpenBSD:*:*) + echo ${UNAME_MACHINE}-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + alpha:OSF1:*:*) + if test $UNAME_RELEASE = "V4.0"; then + UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'` + fi + # A Vn.n version is a released version. + # A Tn.n version is a released field test version. + # A Xn.n version is an unreleased experimental baselevel. + # 1.2 uses "1.2" for uname -r. + cat <$dummy.s + .data +\$Lformat: + .byte 37,100,45,37,120,10,0 # "%d-%x\n" + + .text + .globl main + .align 4 + .ent main +main: + .frame \$30,16,\$26,0 + ldgp \$29,0(\$27) + .prologue 1 + .long 0x47e03d80 # implver \$0 + lda \$2,-1 + .long 0x47e20c21 # amask \$2,\$1 + lda \$16,\$Lformat + mov \$0,\$17 + not \$1,\$18 + jsr \$26,printf + ldgp \$29,0(\$26) + mov 0,\$16 + jsr \$26,exit + .end main +EOF + eval $set_cc_for_build + $CC_FOR_BUILD $dummy.s -o $dummy 2>/dev/null + if test "$?" = 0 ; then + case `./$dummy` in + 0-0) + UNAME_MACHINE="alpha" + ;; + 1-0) + UNAME_MACHINE="alphaev5" + ;; + 1-1) + UNAME_MACHINE="alphaev56" + ;; + 1-101) + UNAME_MACHINE="alphapca56" + ;; + 2-303) + UNAME_MACHINE="alphaev6" + ;; + 2-307) + UNAME_MACHINE="alphaev67" + ;; + 2-1307) + UNAME_MACHINE="alphaev68" + ;; + esac + fi + rm -f $dummy.s $dummy + echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[VTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + exit 0 ;; + Alpha\ *:Windows_NT*:*) + # How do we know it's Interix rather than the generic POSIX subsystem? + # Should we change UNAME_MACHINE based on the output of uname instead + # of the specific Alpha model? + echo alpha-pc-interix + exit 0 ;; + 21064:Windows_NT:50:3) + echo alpha-dec-winnt3.5 + exit 0 ;; + Amiga*:UNIX_System_V:4.0:*) + echo m68k-unknown-sysv4 + exit 0;; + *:[Aa]miga[Oo][Ss]:*:*) + echo ${UNAME_MACHINE}-unknown-amigaos + exit 0 ;; + *:OS/390:*:*) + echo i370-ibm-openedition + exit 0 ;; + arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*) + echo arm-acorn-riscix${UNAME_RELEASE} + exit 0;; + SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*) + echo hppa1.1-hitachi-hiuxmpp + exit 0;; + Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*) + # akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE. + if test "`(/bin/universe) 2>/dev/null`" = att ; then + echo pyramid-pyramid-sysv3 + else + echo pyramid-pyramid-bsd + fi + exit 0 ;; + NILE*:*:*:dcosx) + echo pyramid-pyramid-svr4 + exit 0 ;; + sun4H:SunOS:5.*:*) + echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit 0 ;; + sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*) + echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit 0 ;; + i86pc:SunOS:5.*:*) + echo i386-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit 0 ;; + sun4*:SunOS:6*:*) + # According to config.sub, this is the proper way to canonicalize + # SunOS6. Hard to guess exactly what SunOS6 will be like, but + # it's likely to be more like Solaris than SunOS4. + echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit 0 ;; + sun4*:SunOS:*:*) + case "`/usr/bin/arch -k`" in + Series*|S4*) + UNAME_RELEASE=`uname -v` + ;; + esac + # Japanese Language versions have a version number like `4.1.3-JL'. + echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'` + exit 0 ;; + sun3*:SunOS:*:*) + echo m68k-sun-sunos${UNAME_RELEASE} + exit 0 ;; + sun*:*:4.2BSD:*) + UNAME_RELEASE=`(head -1 /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null` + test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3 + case "`/bin/arch`" in + sun3) + echo m68k-sun-sunos${UNAME_RELEASE} + ;; + sun4) + echo sparc-sun-sunos${UNAME_RELEASE} + ;; + esac + exit 0 ;; + aushp:SunOS:*:*) + echo sparc-auspex-sunos${UNAME_RELEASE} + exit 0 ;; + # The situation for MiNT is a little confusing. The machine name + # can be virtually everything (everything which is not + # "atarist" or "atariste" at least should have a processor + # > m68000). The system name ranges from "MiNT" over "FreeMiNT" + # to the lowercase version "mint" (or "freemint"). Finally + # the system name "TOS" denotes a system which is actually not + # MiNT. But MiNT is downward compatible to TOS, so this should + # be no problem. + atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*) + echo m68k-atari-mint${UNAME_RELEASE} + exit 0 ;; + atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*) + echo m68k-atari-mint${UNAME_RELEASE} + exit 0 ;; + *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*) + echo m68k-atari-mint${UNAME_RELEASE} + exit 0 ;; + milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*) + echo m68k-milan-mint${UNAME_RELEASE} + exit 0 ;; + hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*) + echo m68k-hades-mint${UNAME_RELEASE} + exit 0 ;; + *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*) + echo m68k-unknown-mint${UNAME_RELEASE} + exit 0 ;; + powerpc:machten:*:*) + echo powerpc-apple-machten${UNAME_RELEASE} + exit 0 ;; + RISC*:Mach:*:*) + echo mips-dec-mach_bsd4.3 + exit 0 ;; + RISC*:ULTRIX:*:*) + echo mips-dec-ultrix${UNAME_RELEASE} + exit 0 ;; + VAX*:ULTRIX*:*:*) + echo vax-dec-ultrix${UNAME_RELEASE} + exit 0 ;; + 2020:CLIX:*:* | 2430:CLIX:*:*) + echo clipper-intergraph-clix${UNAME_RELEASE} + exit 0 ;; + mips:*:*:UMIPS | mips:*:*:RISCos) + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c +#ifdef __cplusplus +#include /* for printf() prototype */ + int main (int argc, char *argv[]) { +#else + int main (argc, argv) int argc; char *argv[]; { +#endif + #if defined (host_mips) && defined (MIPSEB) + #if defined (SYSTYPE_SYSV) + printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0); + #endif + #if defined (SYSTYPE_SVR4) + printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0); + #endif + #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD) + printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0); + #endif + #endif + exit (-1); + } +EOF + $CC_FOR_BUILD $dummy.c -o $dummy \ + && ./$dummy `echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` \ + && rm -f $dummy.c $dummy && exit 0 + rm -f $dummy.c $dummy + echo mips-mips-riscos${UNAME_RELEASE} + exit 0 ;; + Motorola:PowerMAX_OS:*:*) + echo powerpc-motorola-powermax + exit 0 ;; + Night_Hawk:Power_UNIX:*:*) + echo powerpc-harris-powerunix + exit 0 ;; + m88k:CX/UX:7*:*) + echo m88k-harris-cxux7 + exit 0 ;; + m88k:*:4*:R4*) + echo m88k-motorola-sysv4 + exit 0 ;; + m88k:*:3*:R3*) + echo m88k-motorola-sysv3 + exit 0 ;; + AViiON:dgux:*:*) + # DG/UX returns AViiON for all architectures + UNAME_PROCESSOR=`/usr/bin/uname -p` + if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ] + then + if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \ + [ ${TARGET_BINARY_INTERFACE}x = x ] + then + echo m88k-dg-dgux${UNAME_RELEASE} + else + echo m88k-dg-dguxbcs${UNAME_RELEASE} + fi + else + echo i586-dg-dgux${UNAME_RELEASE} + fi + exit 0 ;; + M88*:DolphinOS:*:*) # DolphinOS (SVR3) + echo m88k-dolphin-sysv3 + exit 0 ;; + M88*:*:R3*:*) + # Delta 88k system running SVR3 + echo m88k-motorola-sysv3 + exit 0 ;; + XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3) + echo m88k-tektronix-sysv3 + exit 0 ;; + Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD) + echo m68k-tektronix-bsd + exit 0 ;; + *:IRIX*:*:*) + echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'` + exit 0 ;; + ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX. + echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id + exit 0 ;; # Note that: echo "'`uname -s`'" gives 'AIX ' + i*86:AIX:*:*) + echo i386-ibm-aix + exit 0 ;; + ia64:AIX:*:*) + if [ -x /usr/bin/oslevel ] ; then + IBM_REV=`/usr/bin/oslevel` + else + IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} + fi + echo ${UNAME_MACHINE}-ibm-aix${IBM_REV} + exit 0 ;; + *:AIX:2:3) + if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #include + + main() + { + if (!__power_pc()) + exit(1); + puts("powerpc-ibm-aix3.2.5"); + exit(0); + } +EOF + $CC_FOR_BUILD $dummy.c -o $dummy && ./$dummy && rm -f $dummy.c $dummy && exit 0 + rm -f $dummy.c $dummy + echo rs6000-ibm-aix3.2.5 + elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then + echo rs6000-ibm-aix3.2.4 + else + echo rs6000-ibm-aix3.2 + fi + exit 0 ;; + *:AIX:*:[45]) + IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | head -1 | awk '{ print $1 }'` + if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then + IBM_ARCH=rs6000 + else + IBM_ARCH=powerpc + fi + if [ -x /usr/bin/oslevel ] ; then + IBM_REV=`/usr/bin/oslevel` + else + IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} + fi + echo ${IBM_ARCH}-ibm-aix${IBM_REV} + exit 0 ;; + *:AIX:*:*) + echo rs6000-ibm-aix + exit 0 ;; + ibmrt:4.4BSD:*|romp-ibm:BSD:*) + echo romp-ibm-bsd4.4 + exit 0 ;; + ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and + echo romp-ibm-bsd${UNAME_RELEASE} # 4.3 with uname added to + exit 0 ;; # report: romp-ibm BSD 4.3 + *:BOSX:*:*) + echo rs6000-bull-bosx + exit 0 ;; + DPX/2?00:B.O.S.:*:*) + echo m68k-bull-sysv3 + exit 0 ;; + 9000/[34]??:4.3bsd:1.*:*) + echo m68k-hp-bsd + exit 0 ;; + hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*) + echo m68k-hp-bsd4.4 + exit 0 ;; + 9000/[34678]??:HP-UX:*:*) + HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` + case "${UNAME_MACHINE}" in + 9000/31? ) HP_ARCH=m68000 ;; + 9000/[34]?? ) HP_ARCH=m68k ;; + 9000/[678][0-9][0-9]) + if [ -x /usr/bin/getconf ]; then + sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null` + sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null` + case "${sc_cpu_version}" in + 523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0 + 528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1 + 532) # CPU_PA_RISC2_0 + case "${sc_kernel_bits}" in + 32) HP_ARCH="hppa2.0n" ;; + 64) HP_ARCH="hppa2.0w" ;; + '') HP_ARCH="hppa2.0" ;; # HP-UX 10.20 + esac ;; + esac + fi + if [ "${HP_ARCH}" = "" ]; then + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + + #define _HPUX_SOURCE + #include + #include + + int main () + { + #if defined(_SC_KERNEL_BITS) + long bits = sysconf(_SC_KERNEL_BITS); + #endif + long cpu = sysconf (_SC_CPU_VERSION); + + switch (cpu) + { + case CPU_PA_RISC1_0: puts ("hppa1.0"); break; + case CPU_PA_RISC1_1: puts ("hppa1.1"); break; + case CPU_PA_RISC2_0: + #if defined(_SC_KERNEL_BITS) + switch (bits) + { + case 64: puts ("hppa2.0w"); break; + case 32: puts ("hppa2.0n"); break; + default: puts ("hppa2.0"); break; + } break; + #else /* !defined(_SC_KERNEL_BITS) */ + puts ("hppa2.0"); break; + #endif + default: puts ("hppa1.0"); break; + } + exit (0); + } +EOF + (CCOPTS= $CC_FOR_BUILD $dummy.c -o $dummy 2>/dev/null) && HP_ARCH=`./$dummy` + if test -z "$HP_ARCH"; then HP_ARCH=hppa; fi + rm -f $dummy.c $dummy + fi ;; + esac + echo ${HP_ARCH}-hp-hpux${HPUX_REV} + exit 0 ;; + ia64:HP-UX:*:*) + HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` + echo ia64-hp-hpux${HPUX_REV} + exit 0 ;; + 3050*:HI-UX:*:*) + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #include + int + main () + { + long cpu = sysconf (_SC_CPU_VERSION); + /* The order matters, because CPU_IS_HP_MC68K erroneously returns + true for CPU_PA_RISC1_0. CPU_IS_PA_RISC returns correct + results, however. */ + if (CPU_IS_PA_RISC (cpu)) + { + switch (cpu) + { + case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break; + case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break; + case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break; + default: puts ("hppa-hitachi-hiuxwe2"); break; + } + } + else if (CPU_IS_HP_MC68K (cpu)) + puts ("m68k-hitachi-hiuxwe2"); + else puts ("unknown-hitachi-hiuxwe2"); + exit (0); + } +EOF + $CC_FOR_BUILD $dummy.c -o $dummy && ./$dummy && rm -f $dummy.c $dummy && exit 0 + rm -f $dummy.c $dummy + echo unknown-hitachi-hiuxwe2 + exit 0 ;; + 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* ) + echo hppa1.1-hp-bsd + exit 0 ;; + 9000/8??:4.3bsd:*:*) + echo hppa1.0-hp-bsd + exit 0 ;; + *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*) + echo hppa1.0-hp-mpeix + exit 0 ;; + hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* ) + echo hppa1.1-hp-osf + exit 0 ;; + hp8??:OSF1:*:*) + echo hppa1.0-hp-osf + exit 0 ;; + i*86:OSF1:*:*) + if [ -x /usr/sbin/sysversion ] ; then + echo ${UNAME_MACHINE}-unknown-osf1mk + else + echo ${UNAME_MACHINE}-unknown-osf1 + fi + exit 0 ;; + parisc*:Lites*:*:*) + echo hppa1.1-hp-lites + exit 0 ;; + C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*) + echo c1-convex-bsd + exit 0 ;; + C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*) + if getsysinfo -f scalar_acc + then echo c32-convex-bsd + else echo c2-convex-bsd + fi + exit 0 ;; + C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*) + echo c34-convex-bsd + exit 0 ;; + C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*) + echo c38-convex-bsd + exit 0 ;; + C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*) + echo c4-convex-bsd + exit 0 ;; + CRAY*X-MP:*:*:*) + echo xmp-cray-unicos + exit 0 ;; + CRAY*Y-MP:*:*:*) + echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit 0 ;; + CRAY*[A-Z]90:*:*:*) + echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \ + | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \ + -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \ + -e 's/\.[^.]*$/.X/' + exit 0 ;; + CRAY*TS:*:*:*) + echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit 0 ;; + CRAY*T3D:*:*:*) + echo alpha-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit 0 ;; + CRAY*T3E:*:*:*) + echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit 0 ;; + CRAY*SV1:*:*:*) + echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit 0 ;; + CRAY-2:*:*:*) + echo cray2-cray-unicos + exit 0 ;; + F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*) + FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` + FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'` + echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" + exit 0 ;; + i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*) + echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE} + exit 0 ;; + sparc*:BSD/OS:*:*) + echo sparc-unknown-bsdi${UNAME_RELEASE} + exit 0 ;; + *:BSD/OS:*:*) + echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE} + exit 0 ;; + *:FreeBSD:*:*) + echo ${UNAME_MACHINE}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` + exit 0 ;; + i*:CYGWIN*:*) + echo ${UNAME_MACHINE}-pc-cygwin + exit 0 ;; + i*:MINGW*:*) + echo ${UNAME_MACHINE}-pc-mingw32 + exit 0 ;; + i*:PW*:*) + echo ${UNAME_MACHINE}-pc-pw32 + exit 0 ;; + i*:Windows_NT*:* | Pentium*:Windows_NT*:*) + # How do we know it's Interix rather than the generic POSIX subsystem? + # It also conflicts with pre-2.0 versions of AT&T UWIN. Should we + # UNAME_MACHINE based on the output of uname instead of i386? + echo i386-pc-interix + exit 0 ;; + i*:UWIN*:*) + echo ${UNAME_MACHINE}-pc-uwin + exit 0 ;; + p*:CYGWIN*:*) + echo powerpcle-unknown-cygwin + exit 0 ;; + prep*:SunOS:5.*:*) + echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit 0 ;; + *:GNU:*:*) + echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-gnu`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'` + exit 0 ;; + i*86:Minix:*:*) + echo ${UNAME_MACHINE}-pc-minix + exit 0 ;; + arm*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit 0 ;; + ia64:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux + exit 0 ;; + m68*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit 0 ;; + mips:Linux:*:*) + case `sed -n '/^byte/s/^.*: \(.*\) endian/\1/p' < /proc/cpuinfo` in + big) echo mips-unknown-linux-gnu && exit 0 ;; + little) echo mipsel-unknown-linux-gnu && exit 0 ;; + esac + ;; + ppc:Linux:*:*) + echo powerpc-unknown-linux-gnu + exit 0 ;; + ppc64:Linux:*:*) + echo powerpc64-unknown-linux-gnu + exit 0 ;; + alpha:Linux:*:*) + case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in + EV5) UNAME_MACHINE=alphaev5 ;; + EV56) UNAME_MACHINE=alphaev56 ;; + PCA56) UNAME_MACHINE=alphapca56 ;; + PCA57) UNAME_MACHINE=alphapca56 ;; + EV6) UNAME_MACHINE=alphaev6 ;; + EV67) UNAME_MACHINE=alphaev67 ;; + EV68*) UNAME_MACHINE=alphaev68 ;; + esac + objdump --private-headers /bin/sh | grep ld.so.1 >/dev/null + if test "$?" = 0 ; then LIBC="libc1" ; else LIBC="" ; fi + echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC} + exit 0 ;; + parisc:Linux:*:* | hppa:Linux:*:*) + # Look for CPU level + case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in + PA7*) echo hppa1.1-unknown-linux-gnu ;; + PA8*) echo hppa2.0-unknown-linux-gnu ;; + *) echo hppa-unknown-linux-gnu ;; + esac + exit 0 ;; + parisc64:Linux:*:* | hppa64:Linux:*:*) + echo hppa64-unknown-linux-gnu + exit 0 ;; + s390:Linux:*:* | s390x:Linux:*:*) + echo ${UNAME_MACHINE}-ibm-linux + exit 0 ;; + sh*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit 0 ;; + sparc:Linux:*:* | sparc64:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit 0 ;; + x86_64:Linux:*:*) + echo x86_64-unknown-linux-gnu + exit 0 ;; + i*86:Linux:*:*) + # The BFD linker knows what the default object file format is, so + # first see if it will tell us. cd to the root directory to prevent + # problems with other programs or directories called `ld' in the path. + ld_supported_targets=`cd /; ld --help 2>&1 \ + | sed -ne '/supported targets:/!d + s/[ ][ ]*/ /g + s/.*supported targets: *// + s/ .*// + p'` + case "$ld_supported_targets" in + elf32-i386) + TENTATIVE="${UNAME_MACHINE}-pc-linux-gnu" + ;; + a.out-i386-linux) + echo "${UNAME_MACHINE}-pc-linux-gnuaout" + exit 0 ;; + coff-i386) + echo "${UNAME_MACHINE}-pc-linux-gnucoff" + exit 0 ;; + "") + # Either a pre-BFD a.out linker (linux-gnuoldld) or + # one that does not give us useful --help. + echo "${UNAME_MACHINE}-pc-linux-gnuoldld" + exit 0 ;; + esac + # Determine whether the default compiler is a.out or elf + eval $set_cc_for_build + cat >$dummy.c < +#ifdef __cplusplus +#include /* for printf() prototype */ + int main (int argc, char *argv[]) { +#else + int main (argc, argv) int argc; char *argv[]; { +#endif +#ifdef __ELF__ +# ifdef __GLIBC__ +# if __GLIBC__ >= 2 + printf ("%s-pc-linux-gnu\n", argv[1]); +# else + printf ("%s-pc-linux-gnulibc1\n", argv[1]); +# endif +# else + printf ("%s-pc-linux-gnulibc1\n", argv[1]); +# endif +#else + printf ("%s-pc-linux-gnuaout\n", argv[1]); +#endif + return 0; +} +EOF + $CC_FOR_BUILD $dummy.c -o $dummy 2>/dev/null && ./$dummy "${UNAME_MACHINE}" && rm -f $dummy.c $dummy && exit 0 + rm -f $dummy.c $dummy + test x"${TENTATIVE}" != x && echo "${TENTATIVE}" && exit 0 + ;; + i*86:DYNIX/ptx:4*:*) + # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there. + # earlier versions are messed up and put the nodename in both + # sysname and nodename. + echo i386-sequent-sysv4 + exit 0 ;; + i*86:UNIX_SV:4.2MP:2.*) + # Unixware is an offshoot of SVR4, but it has its own version + # number series starting with 2... + # I am not positive that other SVR4 systems won't match this, + # I just have to hope. -- rms. + # Use sysv4.2uw... so that sysv4* matches it. + echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION} + exit 0 ;; + i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*) + UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'` + if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then + echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL} + else + echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL} + fi + exit 0 ;; + i*86:*:5:[78]*) + case `/bin/uname -X | grep "^Machine"` in + *486*) UNAME_MACHINE=i486 ;; + *Pentium) UNAME_MACHINE=i586 ;; + *Pent*|*Celeron) UNAME_MACHINE=i686 ;; + esac + echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION} + exit 0 ;; + i*86:*:3.2:*) + if test -f /usr/options/cb.name; then + UNAME_REL=`sed -n 's/.*Version //p' /dev/null >/dev/null ; then + UNAME_REL=`(/bin/uname -X|egrep Release|sed -e 's/.*= //')` + (/bin/uname -X|egrep i80486 >/dev/null) && UNAME_MACHINE=i486 + (/bin/uname -X|egrep '^Machine.*Pentium' >/dev/null) \ + && UNAME_MACHINE=i586 + (/bin/uname -X|egrep '^Machine.*Pent ?II' >/dev/null) \ + && UNAME_MACHINE=i686 + (/bin/uname -X|egrep '^Machine.*Pentium Pro' >/dev/null) \ + && UNAME_MACHINE=i686 + echo ${UNAME_MACHINE}-pc-sco$UNAME_REL + else + echo ${UNAME_MACHINE}-pc-sysv32 + fi + exit 0 ;; + i*86:*DOS:*:*) + echo ${UNAME_MACHINE}-pc-msdosdjgpp + exit 0 ;; + pc:*:*:*) + # Left here for compatibility: + # uname -m prints for DJGPP always 'pc', but it prints nothing about + # the processor, so we play safe by assuming i386. + echo i386-pc-msdosdjgpp + exit 0 ;; + Intel:Mach:3*:*) + echo i386-pc-mach3 + exit 0 ;; + paragon:*:*:*) + echo i860-intel-osf1 + exit 0 ;; + i860:*:4.*:*) # i860-SVR4 + if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then + echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4 + else # Add other i860-SVR4 vendors below as they are discovered. + echo i860-unknown-sysv${UNAME_RELEASE} # Unknown i860-SVR4 + fi + exit 0 ;; + mini*:CTIX:SYS*5:*) + # "miniframe" + echo m68010-convergent-sysv + exit 0 ;; + M68*:*:R3V[567]*:*) + test -r /sysV68 && echo 'm68k-motorola-sysv' && exit 0 ;; + 3[34]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0) + OS_REL='' + test -r /etc/.relid \ + && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` + /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ + && echo i486-ncr-sysv4.3${OS_REL} && exit 0 + /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ + && echo i586-ncr-sysv4.3${OS_REL} && exit 0 ;; + 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*) + /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ + && echo i486-ncr-sysv4 && exit 0 ;; + m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*) + echo m68k-unknown-lynxos${UNAME_RELEASE} + exit 0 ;; + mc68030:UNIX_System_V:4.*:*) + echo m68k-atari-sysv4 + exit 0 ;; + i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.0*:*) + echo i386-unknown-lynxos${UNAME_RELEASE} + exit 0 ;; + TSUNAMI:LynxOS:2.*:*) + echo sparc-unknown-lynxos${UNAME_RELEASE} + exit 0 ;; + rs6000:LynxOS:2.*:*) + echo rs6000-unknown-lynxos${UNAME_RELEASE} + exit 0 ;; + PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.0*:*) + echo powerpc-unknown-lynxos${UNAME_RELEASE} + exit 0 ;; + SM[BE]S:UNIX_SV:*:*) + echo mips-dde-sysv${UNAME_RELEASE} + exit 0 ;; + RM*:ReliantUNIX-*:*:*) + echo mips-sni-sysv4 + exit 0 ;; + RM*:SINIX-*:*:*) + echo mips-sni-sysv4 + exit 0 ;; + *:SINIX-*:*:*) + if uname -p 2>/dev/null >/dev/null ; then + UNAME_MACHINE=`(uname -p) 2>/dev/null` + echo ${UNAME_MACHINE}-sni-sysv4 + else + echo ns32k-sni-sysv + fi + exit 0 ;; + PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort + # says + echo i586-unisys-sysv4 + exit 0 ;; + *:UNIX_System_V:4*:FTX*) + # From Gerald Hewes . + # How about differentiating between stratus architectures? -djm + echo hppa1.1-stratus-sysv4 + exit 0 ;; + *:*:*:FTX*) + # From seanf@swdc.stratus.com. + echo i860-stratus-sysv4 + exit 0 ;; + *:VOS:*:*) + # From Paul.Green@stratus.com. + echo hppa1.1-stratus-vos + exit 0 ;; + mc68*:A/UX:*:*) + echo m68k-apple-aux${UNAME_RELEASE} + exit 0 ;; + news*:NEWS-OS:6*:*) + echo mips-sony-newsos6 + exit 0 ;; + R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*) + if [ -d /usr/nec ]; then + echo mips-nec-sysv${UNAME_RELEASE} + else + echo mips-unknown-sysv${UNAME_RELEASE} + fi + exit 0 ;; + BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only. + echo powerpc-be-beos + exit 0 ;; + BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only. + echo powerpc-apple-beos + exit 0 ;; + BePC:BeOS:*:*) # BeOS running on Intel PC compatible. + echo i586-pc-beos + exit 0 ;; + SX-4:SUPER-UX:*:*) + echo sx4-nec-superux${UNAME_RELEASE} + exit 0 ;; + SX-5:SUPER-UX:*:*) + echo sx5-nec-superux${UNAME_RELEASE} + exit 0 ;; + Power*:Rhapsody:*:*) + echo powerpc-apple-rhapsody${UNAME_RELEASE} + exit 0 ;; + *:Rhapsody:*:*) + echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE} + exit 0 ;; + *:Darwin:*:*) + echo `uname -p`-apple-darwin${UNAME_RELEASE} + exit 0 ;; + *:procnto*:*:* | *:QNX:[0123456789]*:*) + if test "${UNAME_MACHINE}" = "x86pc"; then + UNAME_MACHINE=pc + fi + echo `uname -p`-${UNAME_MACHINE}-nto-qnx + exit 0 ;; + *:QNX:*:4*) + echo i386-pc-qnx + exit 0 ;; + NSR-[KW]:NONSTOP_KERNEL:*:*) + echo nsr-tandem-nsk${UNAME_RELEASE} + exit 0 ;; + *:NonStop-UX:*:*) + echo mips-compaq-nonstopux + exit 0 ;; + BS2000:POSIX*:*:*) + echo bs2000-siemens-sysv + exit 0 ;; + DS/*:UNIX_System_V:*:*) + echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE} + exit 0 ;; + *:Plan9:*:*) + # "uname -m" is not consistent, so use $cputype instead. 386 + # is converted to i386 for consistency with other x86 + # operating systems. + if test "$cputype" = "386"; then + UNAME_MACHINE=i386 + else + UNAME_MACHINE="$cputype" + fi + echo ${UNAME_MACHINE}-unknown-plan9 + exit 0 ;; + i*86:OS/2:*:*) + # If we were able to find `uname', then EMX Unix compatibility + # is probably installed. + echo ${UNAME_MACHINE}-pc-os2-emx + exit 0 ;; + *:TOPS-10:*:*) + echo pdp10-unknown-tops10 + exit 0 ;; + *:TENEX:*:*) + echo pdp10-unknown-tenex + exit 0 ;; + KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*) + echo pdp10-dec-tops20 + exit 0 ;; + XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*) + echo pdp10-xkl-tops20 + exit 0 ;; + *:TOPS-20:*:*) + echo pdp10-unknown-tops20 + exit 0 ;; + *:ITS:*:*) + echo pdp10-unknown-its + exit 0 ;; + i*86:XTS-300:*:STOP) + echo ${UNAME_MACHINE}-unknown-stop + exit 0 ;; + i*86:atheos:*:*) + echo ${UNAME_MACHINE}-unknown-atheos + exit 0 ;; +esac + +#echo '(No uname command or uname output not recognized.)' 1>&2 +#echo "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" 1>&2 + +eval $set_cc_for_build +cat >$dummy.c < +# include +#endif +main () +{ +#if defined (sony) +#if defined (MIPSEB) + /* BFD wants "bsd" instead of "newsos". Perhaps BFD should be changed, + I don't know.... */ + printf ("mips-sony-bsd\n"); exit (0); +#else +#include + printf ("m68k-sony-newsos%s\n", +#ifdef NEWSOS4 + "4" +#else + "" +#endif + ); exit (0); +#endif +#endif + +#if defined (__arm) && defined (__acorn) && defined (__unix) + printf ("arm-acorn-riscix"); exit (0); +#endif + +#if defined (hp300) && !defined (hpux) + printf ("m68k-hp-bsd\n"); exit (0); +#endif + +#if defined (NeXT) +#if !defined (__ARCHITECTURE__) +#define __ARCHITECTURE__ "m68k" +#endif + int version; + version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`; + if (version < 4) + printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version); + else + printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version); + exit (0); +#endif + +#if defined (MULTIMAX) || defined (n16) +#if defined (UMAXV) + printf ("ns32k-encore-sysv\n"); exit (0); +#else +#if defined (CMU) + printf ("ns32k-encore-mach\n"); exit (0); +#else + printf ("ns32k-encore-bsd\n"); exit (0); +#endif +#endif +#endif + +#if defined (__386BSD__) + printf ("i386-pc-bsd\n"); exit (0); +#endif + +#if defined (sequent) +#if defined (i386) + printf ("i386-sequent-dynix\n"); exit (0); +#endif +#if defined (ns32000) + printf ("ns32k-sequent-dynix\n"); exit (0); +#endif +#endif + +#if defined (_SEQUENT_) + struct utsname un; + + uname(&un); + + if (strncmp(un.version, "V2", 2) == 0) { + printf ("i386-sequent-ptx2\n"); exit (0); + } + if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */ + printf ("i386-sequent-ptx1\n"); exit (0); + } + printf ("i386-sequent-ptx\n"); exit (0); + +#endif + +#if defined (vax) +# if !defined (ultrix) +# include +# if defined (BSD) +# if BSD == 43 + printf ("vax-dec-bsd4.3\n"); exit (0); +# else +# if BSD == 199006 + printf ("vax-dec-bsd4.3reno\n"); exit (0); +# else + printf ("vax-dec-bsd\n"); exit (0); +# endif +# endif +# else + printf ("vax-dec-bsd\n"); exit (0); +# endif +# else + printf ("vax-dec-ultrix\n"); exit (0); +# endif +#endif + +#if defined (alliant) && defined (i860) + printf ("i860-alliant-bsd\n"); exit (0); +#endif + + exit (1); +} +EOF + +$CC_FOR_BUILD $dummy.c -o $dummy 2>/dev/null && ./$dummy && rm -f $dummy.c $dummy && exit 0 +rm -f $dummy.c $dummy + +# Apollos put the system type in the environment. + +test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit 0; } + +# Convex versions that predate uname can use getsysinfo(1) + +if [ -x /usr/convex/getsysinfo ] +then + case `getsysinfo -f cpu_type` in + c1*) + echo c1-convex-bsd + exit 0 ;; + c2*) + if getsysinfo -f scalar_acc + then echo c32-convex-bsd + else echo c2-convex-bsd + fi + exit 0 ;; + c34*) + echo c34-convex-bsd + exit 0 ;; + c38*) + echo c38-convex-bsd + exit 0 ;; + c4*) + echo c4-convex-bsd + exit 0 ;; + esac +fi + +cat >&2 < in order to provide the needed +information to handle your system. + +config.guess timestamp = $timestamp + +uname -m = `(uname -m) 2>/dev/null || echo unknown` +uname -r = `(uname -r) 2>/dev/null || echo unknown` +uname -s = `(uname -s) 2>/dev/null || echo unknown` +uname -v = `(uname -v) 2>/dev/null || echo unknown` + +/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null` +/bin/uname -X = `(/bin/uname -X) 2>/dev/null` + +hostinfo = `(hostinfo) 2>/dev/null` +/bin/universe = `(/bin/universe) 2>/dev/null` +/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null` +/bin/arch = `(/bin/arch) 2>/dev/null` +/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null` +/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null` + +UNAME_MACHINE = ${UNAME_MACHINE} +UNAME_RELEASE = ${UNAME_RELEASE} +UNAME_SYSTEM = ${UNAME_SYSTEM} +UNAME_VERSION = ${UNAME_VERSION} +EOF + +exit 1 + +# Local variables: +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "timestamp='" +# time-stamp-format: "%:y-%02m-%02d" +# time-stamp-end: "'" +# End: diff --git a/mozilla/zap/zmk/portaudio_v18_1/config.sub b/mozilla/zap/zmk/portaudio_v18_1/config.sub new file mode 100755 index 00000000000..952d668c628 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/config.sub @@ -0,0 +1,1413 @@ +#! /bin/sh +# Configuration validation subroutine script. +# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001 +# Free Software Foundation, Inc. + +timestamp='2001-10-05' + +# This file is (in principle) common to ALL GNU software. +# The presence of a machine in this file suggests that SOME GNU software +# can handle that machine. It does not imply ALL GNU software can. +# +# This file is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, +# Boston, MA 02111-1307, USA. + +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + +# Please send patches to . Submit a context +# diff and a properly formatted ChangeLog entry. +# +# Configuration subroutine to validate and canonicalize a configuration type. +# Supply the specified configuration type as an argument. +# If it is invalid, we print an error message on stderr and exit with code 1. +# Otherwise, we print the canonical config type on stdout and succeed. + +# This file is supposed to be the same for all GNU packages +# and recognize all the CPU types, system types and aliases +# that are meaningful with *any* GNU software. +# Each package is responsible for reporting which valid configurations +# it does not support. The user should be able to distinguish +# a failure to support a valid configuration from a meaningless +# configuration. + +# The goal of this file is to map all the various variations of a given +# machine specification into a single specification in the form: +# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM +# or in some cases, the newer four-part form: +# CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM +# It is wrong to echo any other type of specification. + +me=`echo "$0" | sed -e 's,.*/,,'` + +usage="\ +Usage: $0 [OPTION] CPU-MFR-OPSYS + $0 [OPTION] ALIAS + +Canonicalize a configuration name. + +Operation modes: + -h, --help print this help, then exit + -t, --time-stamp print date of last modification, then exit + -v, --version print version number, then exit + +Report bugs and patches to ." + +version="\ +GNU config.sub ($timestamp) + +Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001 +Free Software Foundation, Inc. + +This is free software; see the source for copying conditions. There is NO +warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." + +help=" +Try \`$me --help' for more information." + +# Parse command line +while test $# -gt 0 ; do + case $1 in + --time-stamp | --time* | -t ) + echo "$timestamp" ; exit 0 ;; + --version | -v ) + echo "$version" ; exit 0 ;; + --help | --h* | -h ) + echo "$usage"; exit 0 ;; + -- ) # Stop option processing + shift; break ;; + - ) # Use stdin as input. + break ;; + -* ) + echo "$me: invalid option $1$help" + exit 1 ;; + + *local*) + # First pass through any local machine types. + echo $1 + exit 0;; + + * ) + break ;; + esac +done + +case $# in + 0) echo "$me: missing argument$help" >&2 + exit 1;; + 1) ;; + *) echo "$me: too many arguments$help" >&2 + exit 1;; +esac + +# Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any). +# Here we must recognize all the valid KERNEL-OS combinations. +maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'` +case $maybe_os in + nto-qnx* | linux-gnu* | storm-chaos* | os2-emx* | windows32-*) + os=-$maybe_os + basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'` + ;; + *) + basic_machine=`echo $1 | sed 's/-[^-]*$//'` + if [ $basic_machine != $1 ] + then os=`echo $1 | sed 's/.*-/-/'` + else os=; fi + ;; +esac + +### Let's recognize common machines as not being operating systems so +### that things like config.sub decstation-3100 work. We also +### recognize some manufacturers as not being operating systems, so we +### can provide default operating systems below. +case $os in + -sun*os*) + # Prevent following clause from handling this invalid input. + ;; + -dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \ + -att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \ + -unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \ + -convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\ + -c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \ + -harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \ + -apple | -axis) + os= + basic_machine=$1 + ;; + -sim | -cisco | -oki | -wec | -winbond) + os= + basic_machine=$1 + ;; + -scout) + ;; + -wrs) + os=-vxworks + basic_machine=$1 + ;; + -chorusos*) + os=-chorusos + basic_machine=$1 + ;; + -chorusrdb) + os=-chorusrdb + basic_machine=$1 + ;; + -hiux*) + os=-hiuxwe2 + ;; + -sco5) + os=-sco3.2v5 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco4) + os=-sco3.2v4 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco3.2.[4-9]*) + os=`echo $os | sed -e 's/sco3.2./sco3.2v/'` + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco3.2v[4-9]*) + # Don't forget version if it is 3.2v4 or newer. + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco*) + os=-sco3.2v2 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -udk*) + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -isc) + os=-isc2.2 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -clix*) + basic_machine=clipper-intergraph + ;; + -isc*) + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -lynx*) + os=-lynxos + ;; + -ptx*) + basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'` + ;; + -windowsnt*) + os=`echo $os | sed -e 's/windowsnt/winnt/'` + ;; + -psos*) + os=-psos + ;; + -mint | -mint[0-9]*) + basic_machine=m68k-atari + os=-mint + ;; +esac + +# Decode aliases for certain CPU-COMPANY combinations. +case $basic_machine in + # Recognize the basic CPU types without company name. + # Some are omitted here because they have special meanings below. + 1750a | 580 \ + | a29k \ + | alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \ + | arc | arm | arm[bl]e | arme[lb] | armv[2345] | armv[345][lb] | avr \ + | c4x | clipper \ + | d10v | d30v | dsp16xx \ + | fr30 \ + | h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \ + | i370 | i860 | i960 | ia64 \ + | m32r | m68000 | m68k | m88k | mcore \ + | mips16 | mips64 | mips64el | mips64orion | mips64orionel \ + | mips64vr4100 | mips64vr4100el | mips64vr4300 \ + | mips64vr4300el | mips64vr5000 | mips64vr5000el \ + | mipsbe | mipseb | mipsel | mipsle | mipstx39 | mipstx39el \ + | mipsisa32 \ + | mn10200 | mn10300 \ + | ns16k | ns32k \ + | openrisc \ + | pdp10 | pdp11 | pj | pjl \ + | powerpc | powerpc64 | powerpc64le | powerpcle | ppcbe \ + | pyramid \ + | s390 | s390x \ + | sh | sh[34] | sh[34]eb | shbe | shle \ + | sparc | sparc64 | sparclet | sparclite | sparcv9 | sparcv9b \ + | stormy16 | strongarm \ + | tahoe | thumb | tic80 | tron \ + | v850 \ + | we32k \ + | x86 | xscale \ + | z8k) + basic_machine=$basic_machine-unknown + ;; + m6811 | m68hc11 | m6812 | m68hc12) + # Motorola 68HC11/12. + basic_machine=$basic_machine-unknown + os=-none + ;; + m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k) + ;; + + # We use `pc' rather than `unknown' + # because (1) that's what they normally are, and + # (2) the word "unknown" tends to confuse beginning users. + i*86 | x86_64) + basic_machine=$basic_machine-pc + ;; + # Object if more than one company name word. + *-*-*) + echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 + exit 1 + ;; + # Recognize the basic CPU types with company name. + 580-* \ + | a29k-* \ + | alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \ + | alphapca5[67]-* | arc-* \ + | arm-* | armbe-* | armle-* | armv*-* \ + | avr-* \ + | bs2000-* \ + | c[123]* | c30-* | [cjt]90-* | c54x-* \ + | clipper-* | cray2-* | cydra-* \ + | d10v-* | d30v-* \ + | elxsi-* \ + | f30[01]-* | f700-* | fr30-* | fx80-* \ + | h8300-* | h8500-* \ + | hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \ + | i*86-* | i860-* | i960-* | ia64-* \ + | m32r-* \ + | m68000-* | m680[01234]0-* | m68360-* | m683?2-* | m68k-* \ + | m88110-* | m88k-* | mcore-* \ + | mips-* | mips16-* | mips64-* | mips64el-* | mips64orion-* \ + | mips64orionel-* | mips64vr4100-* | mips64vr4100el-* \ + | mips64vr4300-* | mips64vr4300el-* | mipsbe-* | mipseb-* \ + | mipsle-* | mipsel-* | mipstx39-* | mipstx39el-* \ + | none-* | np1-* | ns16k-* | ns32k-* \ + | orion-* \ + | pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \ + | powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* | ppcbe-* \ + | pyramid-* \ + | romp-* | rs6000-* \ + | s390-* | s390x-* \ + | sh-* | sh[34]-* | sh[34]eb-* | shbe-* | shle-* \ + | sparc-* | sparc64-* | sparc86x-* | sparclite-* \ + | sparcv9-* | sparcv9b-* | stormy16-* | strongarm-* | sv1-* \ + | t3e-* | tahoe-* | thumb-* | tic30-* | tic54x-* | tic80-* | tron-* \ + | v850-* | vax-* \ + | we32k-* \ + | x86-* | x86_64-* | xmp-* | xps100-* | xscale-* \ + | ymp-* \ + | z8k-*) + ;; + # Recognize the various machine names and aliases which stand + # for a CPU type and a company and sometimes even an OS. + 386bsd) + basic_machine=i386-unknown + os=-bsd + ;; + 3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc) + basic_machine=m68000-att + ;; + 3b*) + basic_machine=we32k-att + ;; + a29khif) + basic_machine=a29k-amd + os=-udi + ;; + adobe68k) + basic_machine=m68010-adobe + os=-scout + ;; + alliant | fx80) + basic_machine=fx80-alliant + ;; + altos | altos3068) + basic_machine=m68k-altos + ;; + am29k) + basic_machine=a29k-none + os=-bsd + ;; + amdahl) + basic_machine=580-amdahl + os=-sysv + ;; + amiga | amiga-*) + basic_machine=m68k-unknown + ;; + amigaos | amigados) + basic_machine=m68k-unknown + os=-amigaos + ;; + amigaunix | amix) + basic_machine=m68k-unknown + os=-sysv4 + ;; + apollo68) + basic_machine=m68k-apollo + os=-sysv + ;; + apollo68bsd) + basic_machine=m68k-apollo + os=-bsd + ;; + aux) + basic_machine=m68k-apple + os=-aux + ;; + balance) + basic_machine=ns32k-sequent + os=-dynix + ;; + convex-c1) + basic_machine=c1-convex + os=-bsd + ;; + convex-c2) + basic_machine=c2-convex + os=-bsd + ;; + convex-c32) + basic_machine=c32-convex + os=-bsd + ;; + convex-c34) + basic_machine=c34-convex + os=-bsd + ;; + convex-c38) + basic_machine=c38-convex + os=-bsd + ;; + cray | ymp) + basic_machine=ymp-cray + os=-unicos + ;; + cray2) + basic_machine=cray2-cray + os=-unicos + ;; + [cjt]90) + basic_machine=${basic_machine}-cray + os=-unicos + ;; + crds | unos) + basic_machine=m68k-crds + ;; + cris | cris-* | etrax*) + basic_machine=cris-axis + ;; + da30 | da30-*) + basic_machine=m68k-da30 + ;; + decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn) + basic_machine=mips-dec + ;; + delta | 3300 | motorola-3300 | motorola-delta \ + | 3300-motorola | delta-motorola) + basic_machine=m68k-motorola + ;; + delta88) + basic_machine=m88k-motorola + os=-sysv3 + ;; + dpx20 | dpx20-*) + basic_machine=rs6000-bull + os=-bosx + ;; + dpx2* | dpx2*-bull) + basic_machine=m68k-bull + os=-sysv3 + ;; + ebmon29k) + basic_machine=a29k-amd + os=-ebmon + ;; + elxsi) + basic_machine=elxsi-elxsi + os=-bsd + ;; + encore | umax | mmax) + basic_machine=ns32k-encore + ;; + es1800 | OSE68k | ose68k | ose | OSE) + basic_machine=m68k-ericsson + os=-ose + ;; + fx2800) + basic_machine=i860-alliant + ;; + genix) + basic_machine=ns32k-ns + ;; + gmicro) + basic_machine=tron-gmicro + os=-sysv + ;; + go32) + basic_machine=i386-pc + os=-go32 + ;; + h3050r* | hiux*) + basic_machine=hppa1.1-hitachi + os=-hiuxwe2 + ;; + h8300hms) + basic_machine=h8300-hitachi + os=-hms + ;; + h8300xray) + basic_machine=h8300-hitachi + os=-xray + ;; + h8500hms) + basic_machine=h8500-hitachi + os=-hms + ;; + harris) + basic_machine=m88k-harris + os=-sysv3 + ;; + hp300-*) + basic_machine=m68k-hp + ;; + hp300bsd) + basic_machine=m68k-hp + os=-bsd + ;; + hp300hpux) + basic_machine=m68k-hp + os=-hpux + ;; + hp3k9[0-9][0-9] | hp9[0-9][0-9]) + basic_machine=hppa1.0-hp + ;; + hp9k2[0-9][0-9] | hp9k31[0-9]) + basic_machine=m68000-hp + ;; + hp9k3[2-9][0-9]) + basic_machine=m68k-hp + ;; + hp9k6[0-9][0-9] | hp6[0-9][0-9]) + basic_machine=hppa1.0-hp + ;; + hp9k7[0-79][0-9] | hp7[0-79][0-9]) + basic_machine=hppa1.1-hp + ;; + hp9k78[0-9] | hp78[0-9]) + # FIXME: really hppa2.0-hp + basic_machine=hppa1.1-hp + ;; + hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893) + # FIXME: really hppa2.0-hp + basic_machine=hppa1.1-hp + ;; + hp9k8[0-9][13679] | hp8[0-9][13679]) + basic_machine=hppa1.1-hp + ;; + hp9k8[0-9][0-9] | hp8[0-9][0-9]) + basic_machine=hppa1.0-hp + ;; + hppa-next) + os=-nextstep3 + ;; + hppaosf) + basic_machine=hppa1.1-hp + os=-osf + ;; + hppro) + basic_machine=hppa1.1-hp + os=-proelf + ;; + i370-ibm* | ibm*) + basic_machine=i370-ibm + ;; +# I'm not sure what "Sysv32" means. Should this be sysv3.2? + i*86v32) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-sysv32 + ;; + i*86v4*) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-sysv4 + ;; + i*86v) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-sysv + ;; + i*86sol2) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-solaris2 + ;; + i386mach) + basic_machine=i386-mach + os=-mach + ;; + i386-vsta | vsta) + basic_machine=i386-unknown + os=-vsta + ;; + iris | iris4d) + basic_machine=mips-sgi + case $os in + -irix*) + ;; + *) + os=-irix4 + ;; + esac + ;; + isi68 | isi) + basic_machine=m68k-isi + os=-sysv + ;; + m88k-omron*) + basic_machine=m88k-omron + ;; + magnum | m3230) + basic_machine=mips-mips + os=-sysv + ;; + merlin) + basic_machine=ns32k-utek + os=-sysv + ;; + mingw32) + basic_machine=i386-pc + os=-mingw32 + ;; + miniframe) + basic_machine=m68000-convergent + ;; + *mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*) + basic_machine=m68k-atari + os=-mint + ;; + mipsel*-linux*) + basic_machine=mipsel-unknown + os=-linux-gnu + ;; + mips*-linux*) + basic_machine=mips-unknown + os=-linux-gnu + ;; + mips3*-*) + basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'` + ;; + mips3*) + basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown + ;; + mmix*) + basic_machine=mmix-knuth + os=-mmixware + ;; + monitor) + basic_machine=m68k-rom68k + os=-coff + ;; + msdos) + basic_machine=i386-pc + os=-msdos + ;; + mvs) + basic_machine=i370-ibm + os=-mvs + ;; + ncr3000) + basic_machine=i486-ncr + os=-sysv4 + ;; + netbsd386) + basic_machine=i386-unknown + os=-netbsd + ;; + netwinder) + basic_machine=armv4l-rebel + os=-linux + ;; + news | news700 | news800 | news900) + basic_machine=m68k-sony + os=-newsos + ;; + news1000) + basic_machine=m68030-sony + os=-newsos + ;; + news-3600 | risc-news) + basic_machine=mips-sony + os=-newsos + ;; + necv70) + basic_machine=v70-nec + os=-sysv + ;; + next | m*-next ) + basic_machine=m68k-next + case $os in + -nextstep* ) + ;; + -ns2*) + os=-nextstep2 + ;; + *) + os=-nextstep3 + ;; + esac + ;; + nh3000) + basic_machine=m68k-harris + os=-cxux + ;; + nh[45]000) + basic_machine=m88k-harris + os=-cxux + ;; + nindy960) + basic_machine=i960-intel + os=-nindy + ;; + mon960) + basic_machine=i960-intel + os=-mon960 + ;; + nonstopux) + basic_machine=mips-compaq + os=-nonstopux + ;; + np1) + basic_machine=np1-gould + ;; + nsr-tandem) + basic_machine=nsr-tandem + ;; + op50n-* | op60c-*) + basic_machine=hppa1.1-oki + os=-proelf + ;; + OSE68000 | ose68000) + basic_machine=m68000-ericsson + os=-ose + ;; + os68k) + basic_machine=m68k-none + os=-os68k + ;; + pa-hitachi) + basic_machine=hppa1.1-hitachi + os=-hiuxwe2 + ;; + paragon) + basic_machine=i860-intel + os=-osf + ;; + pbd) + basic_machine=sparc-tti + ;; + pbb) + basic_machine=m68k-tti + ;; + pc532 | pc532-*) + basic_machine=ns32k-pc532 + ;; + pentium | p5 | k5 | k6 | nexgen | viac3) + basic_machine=i586-pc + ;; + pentiumpro | p6 | 6x86 | athlon) + basic_machine=i686-pc + ;; + pentiumii | pentium2) + basic_machine=i686-pc + ;; + pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*) + basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pentiumpro-* | p6-* | 6x86-* | athlon-*) + basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pentiumii-* | pentium2-*) + basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pn) + basic_machine=pn-gould + ;; + power) basic_machine=power-ibm + ;; + ppc) basic_machine=powerpc-unknown + ;; + ppc-*) basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ppcle | powerpclittle | ppc-le | powerpc-little) + basic_machine=powerpcle-unknown + ;; + ppcle-* | powerpclittle-*) + basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ppc64) basic_machine=powerpc64-unknown + ;; + ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ppc64le | powerpc64little | ppc64-le | powerpc64-little) + basic_machine=powerpc64le-unknown + ;; + ppc64le-* | powerpc64little-*) + basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ps2) + basic_machine=i386-ibm + ;; + pw32) + basic_machine=i586-unknown + os=-pw32 + ;; + rom68k) + basic_machine=m68k-rom68k + os=-coff + ;; + rm[46]00) + basic_machine=mips-siemens + ;; + rtpc | rtpc-*) + basic_machine=romp-ibm + ;; + sa29200) + basic_machine=a29k-amd + os=-udi + ;; + sequent) + basic_machine=i386-sequent + ;; + sh) + basic_machine=sh-hitachi + os=-hms + ;; + sparclite-wrs | simso-wrs) + basic_machine=sparclite-wrs + os=-vxworks + ;; + sps7) + basic_machine=m68k-bull + os=-sysv2 + ;; + spur) + basic_machine=spur-unknown + ;; + st2000) + basic_machine=m68k-tandem + ;; + stratus) + basic_machine=i860-stratus + os=-sysv4 + ;; + sun2) + basic_machine=m68000-sun + ;; + sun2os3) + basic_machine=m68000-sun + os=-sunos3 + ;; + sun2os4) + basic_machine=m68000-sun + os=-sunos4 + ;; + sun3os3) + basic_machine=m68k-sun + os=-sunos3 + ;; + sun3os4) + basic_machine=m68k-sun + os=-sunos4 + ;; + sun4os3) + basic_machine=sparc-sun + os=-sunos3 + ;; + sun4os4) + basic_machine=sparc-sun + os=-sunos4 + ;; + sun4sol2) + basic_machine=sparc-sun + os=-solaris2 + ;; + sun3 | sun3-*) + basic_machine=m68k-sun + ;; + sun4) + basic_machine=sparc-sun + ;; + sun386 | sun386i | roadrunner) + basic_machine=i386-sun + ;; + sv1) + basic_machine=sv1-cray + os=-unicos + ;; + symmetry) + basic_machine=i386-sequent + os=-dynix + ;; + t3e) + basic_machine=t3e-cray + os=-unicos + ;; + tic54x | c54x*) + basic_machine=tic54x-unknown + os=-coff + ;; + tx39) + basic_machine=mipstx39-unknown + ;; + tx39el) + basic_machine=mipstx39el-unknown + ;; + tower | tower-32) + basic_machine=m68k-ncr + ;; + udi29k) + basic_machine=a29k-amd + os=-udi + ;; + ultra3) + basic_machine=a29k-nyu + os=-sym1 + ;; + v810 | necv810) + basic_machine=v810-nec + os=-none + ;; + vaxv) + basic_machine=vax-dec + os=-sysv + ;; + vms) + basic_machine=vax-dec + os=-vms + ;; + vpp*|vx|vx-*) + basic_machine=f301-fujitsu + ;; + vxworks960) + basic_machine=i960-wrs + os=-vxworks + ;; + vxworks68) + basic_machine=m68k-wrs + os=-vxworks + ;; + vxworks29k) + basic_machine=a29k-wrs + os=-vxworks + ;; + w65*) + basic_machine=w65-wdc + os=-none + ;; + w89k-*) + basic_machine=hppa1.1-winbond + os=-proelf + ;; + windows32) + basic_machine=i386-pc + os=-windows32-msvcrt + ;; + xmp) + basic_machine=xmp-cray + os=-unicos + ;; + xps | xps100) + basic_machine=xps100-honeywell + ;; + z8k-*-coff) + basic_machine=z8k-unknown + os=-sim + ;; + none) + basic_machine=none-none + os=-none + ;; + +# Here we handle the default manufacturer of certain CPU types. It is in +# some cases the only manufacturer, in others, it is the most popular. + w89k) + basic_machine=hppa1.1-winbond + ;; + op50n) + basic_machine=hppa1.1-oki + ;; + op60c) + basic_machine=hppa1.1-oki + ;; + mips) + if [ x$os = x-linux-gnu ]; then + basic_machine=mips-unknown + else + basic_machine=mips-mips + fi + ;; + romp) + basic_machine=romp-ibm + ;; + rs6000) + basic_machine=rs6000-ibm + ;; + vax) + basic_machine=vax-dec + ;; + pdp10) + # there are many clones, so DEC is not a safe bet + basic_machine=pdp10-unknown + ;; + pdp11) + basic_machine=pdp11-dec + ;; + we32k) + basic_machine=we32k-att + ;; + sh3 | sh4 | sh3eb | sh4eb) + basic_machine=sh-unknown + ;; + sparc | sparcv9 | sparcv9b) + basic_machine=sparc-sun + ;; + cydra) + basic_machine=cydra-cydrome + ;; + orion) + basic_machine=orion-highlevel + ;; + orion105) + basic_machine=clipper-highlevel + ;; + mac | mpw | mac-mpw) + basic_machine=m68k-apple + ;; + pmac | pmac-mpw) + basic_machine=powerpc-apple + ;; + c4x*) + basic_machine=c4x-none + os=-coff + ;; + *-unknown) + # Make sure to match an already-canonicalized machine name. + ;; + *) + echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 + exit 1 + ;; +esac + +# Here we canonicalize certain aliases for manufacturers. +case $basic_machine in + *-digital*) + basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'` + ;; + *-commodore*) + basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'` + ;; + *) + ;; +esac + +# Decode manufacturer-specific aliases for certain operating systems. + +if [ x"$os" != x"" ] +then +case $os in + # First match some system type aliases + # that might get confused with valid system types. + # -solaris* is a basic system type, with this one exception. + -solaris1 | -solaris1.*) + os=`echo $os | sed -e 's|solaris1|sunos4|'` + ;; + -solaris) + os=-solaris2 + ;; + -svr4*) + os=-sysv4 + ;; + -unixware*) + os=-sysv4.2uw + ;; + -gnu/linux*) + os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'` + ;; + # First accept the basic system types. + # The portable systems comes first. + # Each alternative MUST END IN A *, to match a version number. + # -sysv* is not here because it comes later, after sysvr4. + -gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \ + | -*vms* | -sco* | -esix* | -isc* | -aix* | -sunos | -sunos[34]*\ + | -hpux* | -unos* | -osf* | -luna* | -dgux* | -solaris* | -sym* \ + | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \ + | -aos* \ + | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \ + | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \ + | -hiux* | -386bsd* | -netbsd* | -openbsd* | -freebsd* | -riscix* \ + | -lynxos* | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \ + | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \ + | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \ + | -chorusos* | -chorusrdb* \ + | -cygwin* | -pe* | -psos* | -moss* | -proelf* | -rtems* \ + | -mingw32* | -linux-gnu* | -uxpv* | -beos* | -mpeix* | -udk* \ + | -interix* | -uwin* | -rhapsody* | -darwin* | -opened* \ + | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \ + | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \ + | -os2* | -vos*) + # Remember, each alternative MUST END IN *, to match a version number. + ;; + -qnx*) + case $basic_machine in + x86-* | i*86-*) + ;; + *) + os=-nto$os + ;; + esac + ;; + -nto*) + os=-nto-qnx + ;; + -sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \ + | -windows* | -osx | -abug | -netware* | -os9* | -beos* \ + | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*) + ;; + -mac*) + os=`echo $os | sed -e 's|mac|macos|'` + ;; + -linux*) + os=`echo $os | sed -e 's|linux|linux-gnu|'` + ;; + -sunos5*) + os=`echo $os | sed -e 's|sunos5|solaris2|'` + ;; + -sunos6*) + os=`echo $os | sed -e 's|sunos6|solaris3|'` + ;; + -opened*) + os=-openedition + ;; + -wince*) + os=-wince + ;; + -osfrose*) + os=-osfrose + ;; + -osf*) + os=-osf + ;; + -utek*) + os=-bsd + ;; + -dynix*) + os=-bsd + ;; + -acis*) + os=-aos + ;; + -386bsd) + os=-bsd + ;; + -ctix* | -uts*) + os=-sysv + ;; + -ns2 ) + os=-nextstep2 + ;; + -nsk*) + os=-nsk + ;; + # Preserve the version number of sinix5. + -sinix5.*) + os=`echo $os | sed -e 's|sinix|sysv|'` + ;; + -sinix*) + os=-sysv4 + ;; + -triton*) + os=-sysv3 + ;; + -oss*) + os=-sysv3 + ;; + -svr4) + os=-sysv4 + ;; + -svr3) + os=-sysv3 + ;; + -sysvr4) + os=-sysv4 + ;; + # This must come after -sysvr4. + -sysv*) + ;; + -ose*) + os=-ose + ;; + -es1800*) + os=-ose + ;; + -xenix) + os=-xenix + ;; + -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) + os=-mint + ;; + -none) + ;; + *) + # Get rid of the `-' at the beginning of $os. + os=`echo $os | sed 's/[^-]*-//'` + echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2 + exit 1 + ;; +esac +else + +# Here we handle the default operating systems that come with various machines. +# The value should be what the vendor currently ships out the door with their +# machine or put another way, the most popular os provided with the machine. + +# Note that if you're going to try to match "-MANUFACTURER" here (say, +# "-sun"), then you have to tell the case statement up towards the top +# that MANUFACTURER isn't an operating system. Otherwise, code above +# will signal an error saying that MANUFACTURER isn't an operating +# system, and we'll never get to this point. + +case $basic_machine in + *-acorn) + os=-riscix1.2 + ;; + arm*-rebel) + os=-linux + ;; + arm*-semi) + os=-aout + ;; + pdp10-*) + os=-tops20 + ;; + pdp11-*) + os=-none + ;; + *-dec | vax-*) + os=-ultrix4.2 + ;; + m68*-apollo) + os=-domain + ;; + i386-sun) + os=-sunos4.0.2 + ;; + m68000-sun) + os=-sunos3 + # This also exists in the configure program, but was not the + # default. + # os=-sunos4 + ;; + m68*-cisco) + os=-aout + ;; + mips*-cisco) + os=-elf + ;; + mips*-*) + os=-elf + ;; + *-tti) # must be before sparc entry or we get the wrong os. + os=-sysv3 + ;; + sparc-* | *-sun) + os=-sunos4.1.1 + ;; + *-be) + os=-beos + ;; + *-ibm) + os=-aix + ;; + *-wec) + os=-proelf + ;; + *-winbond) + os=-proelf + ;; + *-oki) + os=-proelf + ;; + *-hp) + os=-hpux + ;; + *-hitachi) + os=-hiux + ;; + i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent) + os=-sysv + ;; + *-cbm) + os=-amigaos + ;; + *-dg) + os=-dgux + ;; + *-dolphin) + os=-sysv3 + ;; + m68k-ccur) + os=-rtu + ;; + m88k-omron*) + os=-luna + ;; + *-next ) + os=-nextstep + ;; + *-sequent) + os=-ptx + ;; + *-crds) + os=-unos + ;; + *-ns) + os=-genix + ;; + i370-*) + os=-mvs + ;; + *-next) + os=-nextstep3 + ;; + *-gould) + os=-sysv + ;; + *-highlevel) + os=-bsd + ;; + *-encore) + os=-bsd + ;; + *-sgi) + os=-irix + ;; + *-siemens) + os=-sysv4 + ;; + *-masscomp) + os=-rtu + ;; + f30[01]-fujitsu | f700-fujitsu) + os=-uxpv + ;; + *-rom68k) + os=-coff + ;; + *-*bug) + os=-coff + ;; + *-apple) + os=-macos + ;; + *-atari*) + os=-mint + ;; + *) + os=-none + ;; +esac +fi + +# Here we handle the case where we know the os, and the CPU type, but not the +# manufacturer. We pick the logical manufacturer. +vendor=unknown +case $basic_machine in + *-unknown) + case $os in + -riscix*) + vendor=acorn + ;; + -sunos*) + vendor=sun + ;; + -aix*) + vendor=ibm + ;; + -beos*) + vendor=be + ;; + -hpux*) + vendor=hp + ;; + -mpeix*) + vendor=hp + ;; + -hiux*) + vendor=hitachi + ;; + -unos*) + vendor=crds + ;; + -dgux*) + vendor=dg + ;; + -luna*) + vendor=omron + ;; + -genix*) + vendor=ns + ;; + -mvs* | -opened*) + vendor=ibm + ;; + -ptx*) + vendor=sequent + ;; + -vxsim* | -vxworks*) + vendor=wrs + ;; + -aux*) + vendor=apple + ;; + -hms*) + vendor=hitachi + ;; + -mpw* | -macos*) + vendor=apple + ;; + -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) + vendor=atari + ;; + -vos*) + vendor=stratus + ;; + esac + basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"` + ;; +esac + +echo $basic_machine$os +exit 0 + +# Local variables: +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "timestamp='" +# time-stamp-format: "%:y-%02m-%02d" +# time-stamp-end: "'" +# End: diff --git a/mozilla/zap/zmk/portaudio_v18_1/configure.in b/mozilla/zap/zmk/portaudio_v18_1/configure.in new file mode 100755 index 00000000000..fa7d67fb2a0 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/configure.in @@ -0,0 +1,81 @@ +dnl +dnl PortAudio configure.in script +dnl +dnl Dominic Mazzoni +dnl + +dnl Require autoconf >= 2.13 +AC_PREREQ(2.13) + +dnl Init autoconf and make sure configure is being called +dnl from the right directory +AC_INIT([pa_common/portaudio.h]) + +dnl Checks for programs +AC_PROG_CC +AC_PROG_RANLIB +AC_PROG_INSTALL +AC_PATH_PROG(AR, ar, no) +if [[ $AR = "no" ]] ; then + AC_MSG_ERROR("Could not find ar - needed to create a library"); +fi + +dnl Extra variables we want to substitute +AC_SUBST(OTHER_OBJS) +AC_SUBST(PADLL) +AC_SUBST(SHARED_FLAGS) +AC_SUBST(DLL_LIBS) + +dnl Determine the host operating system / platform +AC_CANONICAL_HOST + +case "${host_os}" in + darwin* ) + dnl Mac OS X configuration + + OTHER_OBJS="pa_mac_core/pa_mac_core.o"; + LIBS="-framework CoreAudio -lm"; + PADLL="libportaudio.dylib"; + SHARED_FLAGS="-framework CoreAudio -dynamiclib"; + ;; + + mingw* ) + dnl MingW configuration + + OTHER_OBJS="pa_win_wmme/pa_win_wmme.o"; + LIBS="-lwinmm -lm"; + PADLL="portaudio.dll"; + SHARED_FLAGS="-shared -mthreads"; + DLL_LIBS="-lwinmm"; + ;; + + cygwin* ) + dnl Cygwin configuration + + OTHER_OBJS="pa_win_wmme/pa_win_wmme.o"; + LIBS="-lwinmm -lm"; + PADLL="portaudio.dll"; + SHARED_FLAGS="-shared -mthreads"; + DLL_LIBS="-lwinmm"; + ;; + + *) + dnl Unix OSS configuration + + AC_CHECK_LIB(pthread, pthread_create, + , + AC_MSG_ERROR([libpthread not found!])) + + OTHER_OBJS="pa_unix_oss/pa_unix_oss.o pa_unix_oss/pa_unix.o"; + LIBS="-lm -lpthread"; + PADLL="libportaudio.so"; + SHARED_FLAGS="-shared"; +esac + +AC_OUTPUT([Makefile]) + +echo "" +echo "Finished configure." + +echo "" +echo "Type 'make' to build PortAudio and examples." diff --git a/mozilla/zap/zmk/portaudio_v18_1/docs/index.html b/mozilla/zap/zmk/portaudio_v18_1/docs/index.html new file mode 100755 index 00000000000..9a78161950b --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/docs/index.html @@ -0,0 +1,78 @@ + + + + + + + + + PortAudio Docs + + +  +
+ + + +
+
+

+PortAudio Documentation

+
+ +

Copyright 2000 Phil Burk and Ross Bencina +
+


+

+V18

+ +

+API Reference for V18

+ +
The Application Programmer Interface is documented in "portaudio.h".
+ +

+Tutorial

+ +
Describes how to write audio programs using the PortAudio API.
+ +

+Implementation Guide

+ +
Describes how to write an implementation of PortAudio for a +new computer platform.
+ +

+Paper Presented at ICMC2001 (PDF)

+ +
Describes the PortAudio API and discusses implementation issues. +Written July 2001.
+ +
+

+V19 - improved API

+ +

+Proposed V19 Changes

+ +
Describes API changes being considered by the developer community. +Feedback welcome.
+ +

+API Reference for V19

+ +
Reference documents for the Application Programmer Interface +for V19 generated by doxygen.
+ +
+

+Miscellaneous

+ +

+Improving Latency

+ +
How to tune your computer to achieve the lowest possible audio +delay.
+Return to PortAudio Home Page + + diff --git a/mozilla/zap/zmk/portaudio_v18_1/docs/latency.html b/mozilla/zap/zmk/portaudio_v18_1/docs/latency.html new file mode 100755 index 00000000000..dc8d690dafb --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/docs/latency.html @@ -0,0 +1,192 @@ + + + + + + + + + PortAudio Implementation - Start/Stop + + +  +
+ + + +
+
+

+PortAudio Latency

+
+ +

This page discusses the issues of audio latency for PortAudio +. It offers suggestions on how to lower latency to improve the responsiveness +of applications. +

What is Latency? +
PortAudio and Latency +
Macintosh +
Unix +
WIndows
+By Phil Burk, Copyright 2002 Phil Burk and Ross Bencina +

+What is Latency?

+Latency is basically longest time that you have to wait before you obtain +a desired result. For digital audio output it is the time between making +a sound in software and finally hearing it. +

Consider the example of pressing a key on the ASCII keyboard to play +a note. There are several stages in this process which each contribute +their own latency. First the operating system must respond to the keypress. +Then the audio signal generated must work its way through the PortAudio +buffers. Then it must work its way through the audio card hardware. Then +it must go through the audio amplifier which is very quick and then travel +through the air. Sound travels at abous one foot per millisecond through +air so placing speakers across the room can add 5-20 msec of delay. +

The reverse process occurs when recording or responding to audio input. +If you are processing audio, for example if you implement a software guitar +fuzz box, then you have both the audio input and audio output latencies +added together. +

The audio buffers are used to prevent glitches in the audio stream. +The user software writes audio into the output buffers. That audio is read +by the low level audio driver or by DMA and sent to the DAC. If the computer +gets busy doing something like reading the disk or redrawing the screen, +then it may not have time to fill the audio buffer. The audio hardware +then runs out of audio data, which causes a glitch. By using a large enough +buffer we can ensure that there is always enough audio data for the audio +hardware to play. But if the buffer is too large then the latency is high +and the system feels sluggish. If you play notes on the keyboard then the +"instrument" will feel unresponsive. So you want the buffers to be as small +as possible without glitching. +

+PortAudio and Latency

+The only delay that PortAudio can control is the total length of its buffers. +The Pa_OpenStream() call takes two parameters: numBuffers and framesPerBuffer. +The latency is also affected by the sample rate which we will call framesPerSecond. +A frame is a set of samples that occur simultaneously. For a stereo stream, +a frame is two samples. +

The latency in milliseconds due to this buffering  is: +

latency_msec = 1000 * numBuffers * framesPerBuffer / framesPerSecond
+This is not the total latency, as we have seen, but it is the part we can +control. +

If you call Pa_OpenStream() with numBuffers equal to zero, then PortAudio +will select a conservative number that will prevent audio glitches. If +you still get glitches, then you can pass a larger value for numBuffers +until the glitching stops. if you try to pass a numBuffers value that is +too small, then PortAudio will use its own idea of the minimum value. +

PortAudio decides on the minimum number of buffers in a conservative +way based on the frameRate, operating system and other variables. You can +query the value that PortAudio will use by calling: +

int Pa_GetMinNumBuffers( int framesPerBuffer, double sampleRate +);
+On some systems you can override the PortAudio minimum if you know your +system can handle a lower value. You do this by setting an environment +variable called PA_MIN_LATENCY_MSEC which is read by PortAudio when it +starts up. This is supported on the PortAudio implementations for Windows +MME, Windows DirectSound, and Unix OSS. +

+Macintosh

+The best thing you can do to improve latency on Mac OS 8 and 9 is to turn +off Virtual Memory. PortAudio V18 will detect that Virtual Memory is turned +off and use a very low latency. +

For Mac OS X the latency is very low because Apple Core Audio is so +well written. You can set the PA_MIN_LATENCY_MSEC variable using: +

setenv PA_MIN_LATENCY_MSEC 4
+ +

+Unix

+PortAudio under Unix currently uses a backgroud thread that reads and writes +to OSS. This gives you decent but not great latency. But if you raise the +priority of the background thread to a very priority then you can get under +10 milliseconds latency. In order to raise your priority you must run the +PortAudio program as root! You must also set PA_MIN_LATENCY_MSEC using +the appropriate command for your shell. +

+Windows

+Latency under Windows is a complex issue because of all the alternative +operating system versions and device drivers. I have seen latency range +from 8 milliseconds to 400 milliseconds. The worst case is when using Windows +NT. Windows 98 is a little better, and Windows XP can be quite good if +properly tuned. +

The underlying audio API also makes a lot of difference. If the audio +device has its own DirectSound driver then DirectSound can often provide +better latency than WMME. But if a real DirectSound driver is not available +for your device then it is emulated using WMME and the latency can be very +high. That's where I saw the 400 millisecond latency. The ASIO implementation +is generally very good and will give the lowest latency if available. +

You can set the PA_MIN_LATENCY_MSEC variable to 50, for example, by +entering in MS-DOS: +

set PA_MIN_LATENCY_MSEC=50
+If you enter this in a DOS window then you must run the PortAudio program +from that same window for the variable to have an effect. You can add that +line to your C:\AUTOEXEC.BAT file and reboot if you want it to affect any +PortAudio based program. +

For Windows XP, you can set environment variables as follows: +

    +
  1. +Select "Control Panel" from the "Start Menu".
  2. + +
  3. +Launch the "System" Control Panel
  4. + +
  5. +Click on the "Advanced" tab.
  6. + +
  7. +Click on the "Environment Variables" button.
  8. + +
  9. +Click "New" button under  User Variables.
  10. + +
  11. +Enter PA_MIN_LATENCY_MSEC for the name and some optimistic number for the +value.
  12. + +
  13. +Click OK, OK, OK.
  14. +
+ +

+Improving Latency on Windows

+There are several steps you can take to improve latency under windows. +
    +
  1. +Avoid reading or writng to disk when doing audio.
  2. + +
  3. +Turn off all automated background tasks such as email clients, virus scanners, +backup programs, FTP servers, web servers, etc. when doing audio.
  4. + +
  5. +Disconnect from the network to prevent network traffic from interrupting +your CPU.
  6. +
+Important: Windows XP users can also tune the OS to favor background +tasks, such as audio, over foreground tasks, such as word processing. I +lowered my latency from 40 to 10 milliseconds using this simple technique. +
    +
  1. +Select "Control Panel" from the "Start Menu".
  2. + +
  3. +Launch the "System" Control Panel
  4. + +
  5. +Click on the "Advanced" tab.
  6. + +
  7. +Click on the "Settings" button in the Performance area.
  8. + +
  9. +Click on the "Advanced" tab.
  10. + +
  11. +Select "Background services" in the Processor Scheduling area.
  12. + +
  13. +Click OK, OK.
  14. +
+Please let us know if you have others sugestions for lowering latency. +
  +
  + + diff --git a/mozilla/zap/zmk/portaudio_v18_1/docs/pa_drivermodel.c.txt b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_drivermodel.c.txt new file mode 100755 index 00000000000..120039b8415 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_drivermodel.c.txt @@ -0,0 +1,488 @@ +/* + This file contains the host-neutral code for implementing multiple driver model + support in PortAudio. + + It has not been compiled, but it is supplied only for example purposes at this stage. + + TODO: use of CHECK_DRIVER_MODEL is bogus in some instances since some + of those functions don't return a PaError + + +*/ + +#include "pa_drivermodel.h.txt" + + +#ifndef PA_MULTIDRIVER +/* single driver support, most functions will stay in the implementation files */ + +PaDriverModelID Pa_CountDriverModels() +{ + return 1; +} + +/* +Perhaps all drivers should define this with this signature +const PaDriverModelInfo* Pa_GetDriverModelInfo( PaDriverModelID driverModelID ) +{ +} +*/ + +PaDeviceID Pa_DriverModelDefaultInputDeviceID( PaDriverModelID driverModelID ) +{ + return Pa_GetDefaultInputDeviceID(); +} + + +PaDeviceID Pa_DriverModelDefaultOutputDeviceID( PaDriverModelID driverModelID ) +{ + return Pa_GetDefaultInputDeviceID(); +} + +/* +Perhaps all drivers should define with this signature +int Pa_DriverModelMinNumBuffers( PaDriverModelID driverModelID, int framesPerBuffer, double sampleRate ) +{ + +} +*/ + +int Pa_DriverModelCountDevices( PaDriverModelID driverModelID ) +{ + return Pa_CountDevices(); +} + +PaDeviceID Pa_DriverModelGetDeviceID(PaDriverModelID driverModelID, int perDriverModelIndex ) +{ + return perDriverModelIndex; +} + + +#else +/* multidriver support */ + + +typedef PaError (*PaInitializeFunPtr)( PaDriverModelImplementation** ); + +/* + the initializers array is a static table of function pointers + to all the available driverModels on the current platform. + + the order of pointers in the array is important. the first + pointer is always considered to be the "default" driver model. +*/ + +static PaInitializeFunPtr driverModelInitializers[] = { +#ifdef WINDOWS + PaWin32WMME_MultiDriverInitialize, + PaWin32DS_MultiDriverInitialize, + PaASIO_MultiDriverInitialize +#endif +#ifdef MAC + PaMacSM_MultiDriverInitialize, + PaMacCA_MultiDriverInitialize, + PaASIO_MultiDriverInitialize +#endif +/* other platforms here */ + (PaInitializeFunPtr*)0 /* NULL terminate the list */ +}; + + +/* + the driverModels array is a dynamically created table of + currently available driverModels. +*/ +static PaDriverModelImplementation* driverModels = 0; +static int numDriverModels = 0; + + +#define PA_CHECK_INITIALIZED\ + if( driverModels == 0 ) + return paLibraryNotInitialised + +#define PA_CHECK_DRIVER_MODEL_ID( id ) + if( id < 0 || id >= numDriverModels ) + return paBadDriverModelID; + + +/* + ConvertPublicDeviceIdToImplementationDeviceId converts deviceId + from a public device id, to a device id for a particular + PortAudio implementation. On return impl will either point + to a valid implementation or will be NULL. +*/ +static void ConvertPublicDeviceIDToImplementationDeviceID( + PaDriverModelImplementation *impl, PaDeviceID deviceID ) +{ + int i, count; + + impl = NULL; + + for( i=0; i < numDriverModels; ++i ){ + count = driverModels[i]->countDevices(); + if( deviceID < count ){ + impl = driverModels[i]; + return NULL; + }else{ + deviceID -= count; + } + } +} + +static PaDeviceID ConvertImplementationDeviceIDToPublicDeviceID( + PaDriverModelID driverModelID, PaDeviceID deviceID ) +{ + int i; + + for( i=0; i < driverModelID; ++i ) + deviceID += driverModels[i]->countDevices(); +} + + +PaError Pa_Initialize( void ) +{ + PaError result = paNoError; + int i, initializerCount; + PaDriverModelImplementation *impl; + + if( driverModels != 0 ) + return paAlreadyInitialized; + + /* count the number of driverModels */ + initializerCount=0; + while( driverModelInitializers[initializerCount] != 0 ){ + ++initializerCount; + } + + driverModels = malloc( sizeof(PaDriverModelImplementation*) * initializerCount ); + if( driverModels == NULL ) + return paInsufficientMemory; + + numDriverModels = 0; + for( i=0; iterminate( driverModels[i] ); +} + + +long Pa_GetHostError( void ) +{ + PA_CHECK_INITIALIZED; + + under construction. depends on error text proposal. +} + + +const char *Pa_GetErrorText( PaError errnum ) +{ + PA_CHECK_INITIALIZED; + + under construction. may need to call driver model specific code + depending on how the error text proposal pans out. +} + + + +int Pa_CountDevices() +{ + int i, result; + + PA_CHECK_INITIALIZED; + + result = 0; + for( i=0; i < numDriverModels; ++i ) + result += driverModels[i]->countDevices(); + + return result; +} + + +PaDeviceID Pa_GetDefaultInputDeviceID( void ) +{ + PA_CHECK_INITIALIZED; + + return driverModels[0]->getDefaultInputDeviceID(); +} + +PaDeviceID Pa_GetDefaultOutputDeviceID( void ) +{ + PA_CHECK_INITIALIZED; + + return driverModels[0]->getDefaultInputDeviceID(); +} + + +const PaDeviceInfo* Pa_GetDeviceInfo( PaDeviceID deviceID ) +{ + PaDriverModelImplementation *impl; + + PA_CHECK_INITIALIZED; + + ConvertPublicDeviceIDToImplementationDeviceID( impl, deviceID ); + if( impl == NULL ) + return paInvalidDeviceID; + + return impl->getDeviceInfo( deviceID ); +} + +/* NEW MULTIPLE DRIVER MODEL FUNCTIONS ---------------------------------- */ + +PaDriverModelID Pa_CountDriverModels() +{ + PA_CHECK_INITIALIZED; + + return numDriverModels; +} + + +const PaDriverModelInfo* Pa_GetDriverModelInfo( PaDriverModelID driverModelID ) +{ + PA_CHECK_INITIALIZED; + PA_CHECK_DRIVER_MODEL_ID( driverModelID ); + + return driverModels[ driverModelID ]->getDriverModelInfo(); +} + + +PaDeviceID Pa_DriverModelDefaultInputDeviceID( PaDriverModelID driverModelID ) +{ + PA_CHECK_INITIALIZED; + PA_CHECK_DRIVER_MODEL_ID( driverModelID ); + + return ConvertImplementationDeviceIDToPublicDeviceID( driverModelID, + driverModels[ driverModelID ]->getDefaultInputDeviceID(); +} + + +PaDeviceID Pa_DriverModelDefaultOutputDeviceID( PaDriverModelID driverModelID ) +{ + PA_CHECK_INITIALIZED; + PA_CHECK_DRIVER_MODEL_ID( driverModelID ); + + return ConvertImplementationDeviceIDToPublicDeviceID( driverModelID, + driverModels[ driverModelID ]->getDefaultOutputDeviceID(); +} + + +int Pa_DriverModelMinNumBuffers( PaDriverModelID driverModelID, int framesPerBuffer, double sampleRate ) +{ + PA_CHECK_INITIALIZED; + PA_CHECK_DRIVER_MODEL_ID( driverModelID ); + + return driverModels[ driverModelID ]->getMinNumBuffers( int framesPerBuffer, double sampleRate ); +} + + +int Pa_DriverModelCountDevices( PaDriverModelID driverModelID ) +{ + PA_CHECK_INITIALIZED; + PA_CHECK_DRIVER_MODEL_ID( driverModelID ); + + return driverModels[ driverModelID ]->coundDevices(); +} + +PaDeviceID Pa_DriverModelGetDeviceID(PaDriverModelID driverModelID, int perDriverModelIndex ) +{ + PA_CHECK_INITIALIZED; + PA_CHECK_DRIVER_MODEL_ID( driverModelID ); + + return ConvertImplementationDeviceIDToPublicDeviceID( driverModelID, perDriverModelIndex ); +} + +/* END NEW MULTIPLE DRIVER MODEL FUNCTIONS ------------------------------ */ + + +PaError Pa_OpenStream( PortAudioStream** stream, + PaDeviceID inputDevice, + int numInputChannels, + PaSampleFormat inputSampleFormat, + void *inputDriverInfo, + PaDeviceID outputDevice, + int numOutputChannels, + PaSampleFormat outputSampleFormat, + void *outputDriverInfo, + double sampleRate, + unsigned long framesPerBuffer, + unsigned long numberOfBuffers, + PaStreamFlags streamFlags, + PortAudioCallback *callback, + void *userData ) +{ + PaError result; + PaDriverModelImplementation *inputImpl, *outputImpl, impl; + + PA_CHECK_INITIALIZED; + + if( inputDevice != paNoDevice ){ + ConvertPublicDeviceIDToImplementationDeviceID( inputImpl, inputDevice ); + if( inputImpl == NULL ) + return paInvalidDeviceID; + else + impl = inputImpl; + } + + if( outputDevice != paNoDevice ){ + ConvertPublicDeviceIDToImplementationDeviceID( outputImpl, outputDevice ); + if( outputImpl == NULL ) + return paInvalidDeviceID; + else + impl = outputImpl; + } + + if( inputDevice != paNoDevice && outputDevice != paNoDevice ){ + if( inputImpl != outputImpl ) + return paDevicesMustBelongToTheSameDriverModel; + } + + + result = impl->openStream( stream, inputDevice, numInputChannels, inputSampleFormat, inputDriverInfo, + outputDevice, numOutputChannels, outputSampleFormat, outputDriverInfo, + sampleRate, framesPerBuffer, numberOfBuffers, streamFlags, callback, userData ); + + + if( result == paNoError ) + ((PaStreamImplementation*)stream)->magic = PA_STREAM_MAGIC; + + return result; +} + + +PaError Pa_OpenDefaultStream( PortAudioStream** stream, + int numInputChannels, + int numOutputChannels, + PaSampleFormat sampleFormat, + double sampleRate, + unsigned long framesPerBuffer, + unsigned long numberOfBuffers, + PortAudioCallback *callback, + void *userData ) +{ + PaError result; + int inputDevice = driverModels[0]->getDefaultInputDeviceID; + int outputDevice = driverModels[0]->getDefaultOutputDeviceID; + + result = driverModels[0]->openStream( stream, inputDevice, numInputChannels, sampleFormat, 0, + outputDevice, numOutputChannels, sampleFormat, 0, + sampleRate, framesPerBuffer, numberOfBuffers, + streamFlags, callback, userData ); + + if( result == paNoError ) + ((PaStreamImplementation*)stream)->magic = PA_STREAM_MAGIC; + + return result; +} + + +PaError Pa_CloseStream( PortAudioStream* stream ) +{ + PA_CHECK_INITIALIZED; + + PaError result = ((PaStreamImplementation*)stream)->close(); + + if( result == PaNoError ) + ((PaStreamImplementation*)stream)->magic = 0; /* clear magic number */ + + return result; +} + + +PaError Pa_StartStream( PortAudioStream *stream ); +{ + PA_CHECK_INITIALIZED; + + return ((PaStreamImplementation*)stream)->start(); +} + + +PaError Pa_StopStream( PortAudioStream *stream ); +{ + PA_CHECK_INITIALIZED; + + return ((PaStreamImplementation*)stream)->stop(); +} + + +PaError Pa_AbortStream( PortAudioStream *stream ); +{ + PA_CHECK_INITIALIZED; + + return ((PaStreamImplementation*)stream)->abort(); +} + + +PaError Pa_StreamActive( PortAudioStream *stream ) +{ + PA_CHECK_INITIALIZED; + + return ((PaStreamImplementation*)stream)->active(); +} + +PaTimestamp Pa_StreamTime( PortAudioStream *stream ) +{ + PA_CHECK_INITIALIZED; + + return ((PaStreamImplementation*)stream)->time(); +} + + +double Pa_StreamCPULoad( PortAudioStream* stream ) +{ + PA_CHECK_INITIALIZED; + + return ((PaStreamImplementation*)stream)->cpuLoad(); +} + + + +int Pa_GetMinNumBuffers( PaDeviceID deviceID, int framesPerBuffer, double sampleRate ) +{ + PaDriverModelImplementation *impl; + PA_CHECK_INITIALIZED; + + ConvertPublicDeviceIDToImplementationDeviceID( impl, deviceID ); + if( impl == NULL ) + return paInvalidDeviceID; + + return impl->getMinNumBuffers( framesPerBuffer, sampleRate ); +} + + +void Pa_Sleep( long msec ) +{ + same as existing implementaion +} + + +PaError Pa_GetSampleSize( PaSampleFormat format ) +{ + same as existing implementation +} + +#endif /* PA_MULTIDRIVER */ + + diff --git a/mozilla/zap/zmk/portaudio_v18_1/docs/pa_drivermodel.h.txt b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_drivermodel.h.txt new file mode 100755 index 00000000000..dec3e2b060c --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_drivermodel.h.txt @@ -0,0 +1,143 @@ +#ifndef PA_MULTIDRIVERMODEL_H +#define PA_MULTIDRIVERMODEL_H + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + + +/* + This file contains the host-neutral code for implementing multiple driver model + support in PortAudio. + + It has not been compiled, but it is supplied only for example purposes at this stage. +*/ + + +#include "portaudio.h" + + +#define PA_MULTIDRIVER // for multidriver support + + + +TODO: declare function pointer types for the following function pointers + +/* + Each driver model implementation needs to implement an initialize function + which is added to the driverModelInitializers array in pa_multidrivermodel.c + + the initializer function needs to return a pointer to a + PaDriverModelImplementation structure, or NULL if initiliazation failed. TODO: need error code instead + + the function pointer members of this structure point to funtions + which operate in exactly the same way as the corresponding functions + in the PortAudio API. +*/ + +struct{ + fptr terminate; /* takes the PaDriverModelImplementation* returned by initialize */ + fptr getDriverModelInfo; + fptr getHostError; + fptr getHostErrorText; + fptr countDevices; + fptr getDefaultInputDeviceID; + fptr getDefaultOutputDeviceID; + fptr getDeviceInfo; + fptr openStream; + fptr getMinNumBuffers; +} PaDriverModelImplementation; + +/* + whenever an implementaion's openstream method is called it should return a + PortAudioStream* whose first segment is actually the following structure. + + the functions pointer members of this structure point to funcitons + which operate in exactly the same way as the corresponding functions + in the PortAudio API. +*/ +struct{ + unsigned long magic; + fptr close; + fptr start; + fptr stop; + fptr abort; + fptr active; + fptr time; + fptr cpuLoad; +} PaStreamImplementation; + +/* + Implementations should set magic to PA_STREAM_MAGIC when opening + a stream _and_ clear it to zero when closing a stream. + All functions which operate on streams should check the validity + of magic. +*/ + +#define PA_STREAM_MAGIC 0x12345678 + +#define PA_CHECK_STREAM( stream )\ + if( ((PaStreamImplementation*)stream)->magic != PA_STREAM_MAGIC )\ + return paBadStreamPtr; + + +/* + PA_API allows the same implementation to be used for single + driver model and multi-driver model operation. If + PA_MULTIDRIVER not defined, PA_API will declare api + functions as global, otherwise they will be static, and include + the drivermodel code. + + Usage would be something like: + + int PA_API(CountDevices)(); + + The PA_MULTIDRIVER_SUPPORT macro declares the initialization and + termination functions required by the multidriver support. it also + allocates and deallocates the PaDriverModelImplementation structure. + + TODO: add macros for initializing PaStreamImplementation PortAudioStream + these would be PA_INITIALIZE_STREAM and PA_TERMINATE_STREAM + they would assign and clear the magic number and assign the + interface functions if neceassary. +*/ + +#ifdef PA_MULTIDRIVER + +#define PA_API( model, name ) static Pa ## model ## _ ## name + +#define PA_MULTIDRIVER_SUPPORT( model )\ +PaError Pa_ ## model ## _MultiDriverTerminate( PaStreamImplementation *impl )\ +{\ + free( impl );\ + return Pa ## model ## _Terminate();\ +}\ +PaError Pa ## model ## _MultiDriverInitialize( PaStreamImplementation** impl )\ +{\ + PaError result = Pa ## model ## _Initialize();\ +\ + if( result == paNoError ){\ + *impl = malloc( sizeof( PaDriverModelImplementation ) );\ + if( impl == NULL ){\ + // TODO: call terminate, return an error + }else{\ + (*impl)->terminate = Pa ## model ## _MultiDriverTerminate();\ + (*impl)->getDriverModelInfo = Pa ## model ## _GetDriverModelInfo();\ + (*impl)->getHostError = Pa ## model ## _GetHostError();\ + // TODO: assign the rest of the interface functions + }\ + }\ + return result;\ +} + +#else /* !PA_MULTIDRIVER */ + +#define PA_API( model, name ) Pa_ ## name + +#define PA_MULTIDRIVER_SUPPORT + +#endif /* PA_MULTIDRIVER */ + + + +#endif /* PA_MULTIDRIVERMODEL_H */ diff --git a/mozilla/zap/zmk/portaudio_v18_1/docs/pa_impl_guide.html b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_impl_guide.html new file mode 100755 index 00000000000..23afa1df771 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_impl_guide.html @@ -0,0 +1,197 @@ + + + + + + + + + PortAudio Implementation - Start/Stop + + +  +
+ + + +
+
+

+PortAudio Implementation Guide

+
+ +

This document describes how to implement the PortAudio API on a new +computer platform. Implementing PortAudio on a new platform, makes it possible +to port many existing audio applications to that platform. +

By Phil Burk +
Copyright 2000 Phil Burk and Ross Bencina +

Note that the license says: "Any person wishing to distribute modifications +to the Software is requested to send the modifications to the original +developer so that they can be incorporated into the canonical version.". +So when you have finished a new implementation, please send it back to +us at  "http://www.portaudio.com" +so that we can make it available for other users. Thank you! +

+Download the Latest PortAudio Implementation

+Always start with the latest implementation available at "http://www.portaudio.com". +Look for the nightly snapshot under the CVS section. +

+Select an Existing Implementation as a Basis

+The fastest way to get started is to take an existing implementation and +translate it for your new platform. Choose an implementation whose architecture +is as close as possible to your target. +
    +
  • +DirectSound Implementation - pa_win_ds - Uses a timer callback for the +background "thread". Polls a circular buffer and writes blocks of data +to keep it full.
  • + +
  • +Windows MME - pa_win_wmme - Spawns an actual Win32 thread. Writes blocks +of data to the HW device and waits for events that signal buffer completion.
  • + +
  • +Linux OSS - pa_linux - Spawns a real thread that writes to the "/dev/dsp" +stream using blocking I/O calls.
  • +
+When you write a new implementation, you will be using some code that is +in common with all implementations. This code is in the folder "pa_common". +It provides various functions such as parameter checking, error code to +text conversion, sample format conversion, clipping and dithering, etc. +

The code that you write will go into a separate folder called "pa_{os}_{api}". +For example, code specific to the DirectSound interface for Windows goes +in "pa_win_ds". +

+Read Docs and Code

+Famialiarize yourself with the system by reading the documentation provided. +here is a suggested order: +
    +
  1. +User Programming Tutorial
  2. + +
  3. +Header file "pa_common/portaudio.h" which defines API.
  4. + +
  5. +Header file "pa_common/pa_host.h" for host dependant code. This definces +the routine you will need to provide.
  6. + +
  7. +Shared code in "pa_common/pa_lib.c".
  8. + +
  9. +Docs on Implementation of Start/Stop +code.
  10. +
+ +

+Implement  Output to Default Device

+Now we are ready to crank some code. For instant gratification, let's try +to play a sine wave. +
    +
  1. +Link the test program "pa_tests/patest_sine.c" with the file "pa_lib.c" +and the implementation specific file you are creating.
  2. + +
  3. +For now, just stub out the device query code and the audio input code.
  4. + +
  5. +Modify PaHost_OpenStream() to open your default target device and get everything +setup.
  6. + +
  7. +Modify PaHost_StartOutput() to start playing audio.
  8. + +
  9. +Modify PaHost_StopOutput() to stop audio.
  10. + +
  11. +Modify PaHost_CloseStream() to clean up. Free all memory that you allocated +in PaHost_OpenStream().
  12. + +
  13. +Keep cranking until you can play a sine wave using "patest_sine.c".
  14. + +
  15. +Once that works, try "patest_pink.c", "patest_clip.c", "patest_sine8.c".
  16. + +
  17. +To test your Open and Close code, try "patest_many.c".
  18. + +
  19. +Now test to make sure that the three modes of stopping are properly supported +by running "patest_stop.c".
  20. + +
  21. +Test your implementation of time stamping with "patest_sync.c".
  22. +
+ +

+Implement Device Queries

+Now that output is working, lets implement the code for querying what devices +are available to the user. Run "pa_tests/pa_devs.c". It should print all +of the devices available and their characteristics. +

+Implement Input

+Implement audio input and test it with: +
    +
  1. +patest_record.c - record in half duplex, play back as recorded.
  2. + +
  3. +patest_wire.c - full duplex, copies input to output. Note that some HW +may not support full duplex.
  4. + +
  5. +patest_fuzz.c - plug in your guitar and get a feel for why latency is an +important issue in computer music.
  6. + +
  7. +paqa_devs.c - try to open every device and use it with every possible format
  8. +
+ +

+Debugging Tools

+You generally cannot use printf() calls to debug real-time processes because +they disturb the timing. Also calling printf() from your background thread +or interrupt could crash the machine. So PA includes a tool for capturing +events and storing the information while it is running. It then prints +the events when Pa_Terminate() is called. +
    +
  1. +To enable trace mode, change TRACE_REALTIME_EVENTS in "pa_common/pa_trace.h" +from a (0) to a (1).
  2. + +
  3. +Link with "pa_common/pa_trace.c".
  4. + +
  5. +Add trace messages to your code by calling:
  6. + +
       void AddTraceMessage( char *msg, int data ); +
    for example +
       AddTraceMessage("Pa_TimeSlice: past_NumCallbacks ", +past->past_NumCallbacks ); +
  7. +Run your program. You will get a dump of events at the end.
  8. + +
  9. +You can leave the trace messages in your code. They will turn to NOOPs +when you change TRACE_REALTIME_EVENTS back to (0).
  10. +
+ +

+Delivery

+Please send your new code along with notes on the implementation back to +us at "http://www.portaudio.com". +We will review the implementation and post it with your name. If you had +to make any modifications to the code in "pa_common" or "pa_tests" please +send us those modifications and your notes. We will try to merge your changes +so that the "pa_common" code works with all implementations. +

If you have suggestions for how to make future implementations easier, +please let us know. +
THANKS! +
  + + diff --git a/mozilla/zap/zmk/portaudio_v18_1/docs/pa_impl_startstop.html b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_impl_startstop.html new file mode 100755 index 00000000000..a1ee93a775b --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_impl_startstop.html @@ -0,0 +1,190 @@ + + + + + + + + + PortAudio Implementation - Start/Stop + + +  +

+ + + +
+
+

+PortAudio Implementation

+
+ +

+Starting and Stopping Streams

+PortAudio is generally executed in two "threads". The foreground thread +is the application thread. The background "thread" may be implemented as +an actual thread, an interrupt handler, or a callback from a timer thread. +

There are three ways that PortAudio can stop a stream. In each case +we look at the sequence of events and the messages sent between the two +threads. The following variables are contained in the internalPortAudioStream. +

int   past_IsActive;     +/* Background is still playing. */ +
int   past_StopSoon;     /* Stop +when last buffer done. */ +
int   past_StopNow;      /* +Stop IMMEDIATELY. */
+ +

+Pa_AbortStream()

+This function causes the background thread to terminate as soon as possible +and audio I/O to stop abruptly. +
  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Foreground ThreadBackground Thread
sets StopNow
sees StopNow
clears IsActive, stops thread
waits for thread to exit
turns off audio I/O
+ +

+Pa_StopStream()

+This function stops the user callback function from being called and then +waits for all audio data written to the output buffer to be played. In +a system with very low latency, you may not hear any difference between +
  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Foreground ThreadBackground Thread
sets StopSoon
stops calling user callback
continues until output buffer empty
clears IsActive, stops thread
waits for thread to exit
turns off audio I/O
+ +

+User callback returns one.

+If the user callback returns one then the user callback function will no +longer be called. Audio output will continue until all audio data written +to the output buffer has been played. Then the audio I/O is stopped, the +background thread terminates, and the stream becomes inactive. +
  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Foreground ThreadBackground Thread
callback returns 1
sets StopSoon
stops calling user callback
continues until output buffer empty
clears IsActive, stops thread
waits for thread to exit
turns off audio I/O
+ +
  + + diff --git a/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_asio.html b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_asio.html new file mode 100755 index 00000000000..ae129258654 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_asio.html @@ -0,0 +1,108 @@ + + + + + + + + + PortAudio Tutorial + + +  +
+ + + +
+
+

+PortAudio Tutorial

+
+ +

+home | +contents +| previousnext

+ +

+Compiling for ASIO (Windows or Macintosh)

+ +
ASIO is a low latency audio API from Steinberg. To compile +an ASIO application, you must first download +the ASIO SDK from Steinberg. You also need to obtain ASIO drivers from +the manufacturer of your audio hardware. +

Note: I am using '/' as a file separator below. On Macintosh replace +'/' with ':'. On Windows, replace '/' with '\'. +

You may try compiling the "pa_tests/patest_saw.c" file first because +it is the simplest. +

Several files are common to all PortAudio implementations. Add the following +source files to your project: +

pa_common/pa_lib.c +
pa_common/portaudio.h +
pa_common/pa_host.h
+To use ASIO with the PortAudio library add the following: +
+
pa_asio/pa_asio.cpp
+
+
+ +

+Macintosh Specific

+ +
Note: there is a bug in the Macintosh ASIO code. Mac +users should read the file "pa_asio:readme_asio_sdk_patch.txt" for information +on how to fix the bug. +

Add these files from the ASIO SDK downloaded from Steinberg:

+ +
+
host/asiodrivers.cpp +
host/mac/asioshlib.cpp +
host/mac/codefragements.cpp
+The ASIO drivers should be in a folder called "ASIO Drivers" beneath your +application.
+ +

+Windows Specific

+ +
Add these files from the ASIO SDK downloaded from Steinberg:
+ +
+
host/asiodrivers.cpp +
host/asiolist.cpp +
common/asio.cpp
+
+ +
Add these directories to the path for include files:
+ +
+
host +
host/pc +
common
+
+ +
and link with the system library "winmm.lib". For MS +Visual C++: +
    +
  • +select "Settings..." from the "Project" menu,
  • + +
  • +select the project name in the tree on the left,
  • + +
  • +choose "All Configurations" in the popup menu above the tree,
  • + +
  • +select the "Link" tab,
  • + +
  • +enter "winmm.lib", without quotes, as the first item in the "Object/library +modules:" field.
  • +
+
+home | +contents +| previousnext + + diff --git a/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_callback.html b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_callback.html new file mode 100755 index 00000000000..fb7b6d7d0ee --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_callback.html @@ -0,0 +1,91 @@ + + + + + + + + + PortAudio Tutorial + + +  +
+ + + +
+
+

+PortAudio Tutorial

+
+ +

+Writing a Callback Function

+ +
To write a program using PortAudio, you must include the "portaudio.h" +include file. You may wish to read "portaudio.h" +because it contains a complete description of the PortAudio functions and +constants. +
+
#include "portaudio.h"
+
+The next task is to write your custom callback function. It is a function +that is called by the PortAudio engine whenever it has captured audio data, +or when it needs more audio data for output. +

Your callback function is often called by an interrupt, or low level +process so you should not do any complex system activities like allocating +memory, or reading or writing files, or printf(). Just crunch numbers and +generate audio signals. What is safe or not safe will vary from platform +to platform. On the Macintosh, for example, you can only call "interrupt +safe" routines. Also do not call any PortAudio functions in the callback +except for Pa_StreamTime() and Pa_GetCPULoad(). +

Your callback function must return an int and accept the exact parameters +specified in this typedef: +

+
typedef int (PortAudioCallback)(
+               void *inputBuffer, void *outputBuffer,
+               unsigned long framesPerBuffer,
+               PaTimestamp outTime, void *userData );
+
+Here is an example callback function from the test file "patests/patest_saw.c". +It calculates a simple left and right sawtooth signal and writes it to +the output buffer. Notice that in this example, the signals are of float +data type. The signals must be between -1.0 and +1.0. You can also use +16 bit integers or other formats which are specified during setup. You +can pass a pointer to your data structure through PortAudio which will +appear as userData. +
+
int patestCallback(  void *inputBuffer, void *outputBuffer,
+                     unsigned long framesPerBuffer,
+                     PaTimestamp outTime, void *userData )
+{
+    unsigned int i;
+/* Cast data passed through stream to our structure type. */
+    paTestData *data = (paTestData*)userData;
+    float *out = (float*)outputBuffer;
+        
+    for( i=0; i<framesPerBuffer; i++ )
+    {
+    /* Stereo channels are interleaved. */
+        *out++ = data->left_phase;              /* left */
+        *out++ = data->right_phase;             /* right */
+
+    /* Generate simple sawtooth phaser that ranges between -1.0 and 1.0. */
+        data->left_phase += 0.01f;
+    /* When signal reaches top, drop back down. */
+        if( data->left_phase >= 1.0f ) data->left_phase -= 2.0f;
+
+    /* higher pitch so we can distinguish left and right. */
+        data->right_phase += 0.03f; 
+        if( data->right_phase >= 1.0f ) data->right_phase -= 2.0f;
+    }
+    return 0;
+}
+
+
+home | +contents +| previousnext + + diff --git a/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_devs.html b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_devs.html new file mode 100755 index 00000000000..6a8c08a3dd1 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_devs.html @@ -0,0 +1,65 @@ + + + + + + + + + PortAudio Tutorial + + +  +
+ + + +
+
+

+PortAudio Tutorial

+
+ +

+Querying for Available Devices

+ +
There are often several different audio devices available in +a computer with different capabilities. They can differ in the sample rates +supported, bit widths, etc. PortAudio provides a simple way to query for +the available devices, and then pass the selected device to Pa_OpenStream(). +For an example, see the file "pa_tests/pa_devs.c". +

To determine the number of devices: +

+
numDevices = Pa_CountDevices();
+
+You can then query each device in turn by calling Pa_GetDeviceInfo() with +an index. +
+
for( i=0; i<numDevices; i++ ) {
+     pdi = Pa_GetDeviceInfo( i );
+
+It will return a pointer to a PaDeviceInfo structure which is +defined as: +
+
typedef struct{
+    int structVersion; 
+    const char *name;
+    int maxInputChannels;
+    int maxOutputChannels;
+/* Number of discrete rates, or -1 if range supported. */
+    int numSampleRates;
+/* Array of supported sample rates, or {min,max} if range supported. */
+    const double *sampleRates;
+    PaSampleFormat nativeSampleFormat;
+}PaDeviceInfo;
+
+If the device supports a continuous range of sample rates, then numSampleRates +will equal -1, and the sampleRates array will have two values, the minimum  +and maximum rate. +

The device information is allocated by Pa_Initialize() and freed by +Pa_Terminate() so you do not have to free() the structure returned by Pa_GetDeviceInfo().

+home | +contents +| previousnext + + diff --git a/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_explore.html b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_explore.html new file mode 100755 index 00000000000..ea616c15482 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_explore.html @@ -0,0 +1,42 @@ + + + + + + + + + PortAudio Tutorial + + +  +
+ + + +
+
+

+PortAudio Tutorial

+
+ +

+Exploring PortAudio

+ +
Now that you have a good idea of how PortAudio works, you can +try out the test programs. +
    +
  • +For an example of playing a sine wave, see "pa_tests/patest_sine.c".
  • + +
  • +For an example of recording and playing back a sound, see  "pa_tests/patest_record.c".
  • +
+I also encourage you to examine the source for the PortAudio libraries. +If you have suggestions on ways to improve them, please let us know. if +you want to implement PortAudio on a new platform, please let us know as +well so we can coordinate people's efforts.
+home | contents +| previous |  next + + diff --git a/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_init.html b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_init.html new file mode 100755 index 00000000000..876130b088d --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_init.html @@ -0,0 +1,43 @@ + + + + + + + + + PortAudio Tutorial + + +  +
+ + + +
+
+

+PortAudio Tutorial

+
+ +

+Initializing PortAudio

+ +
Before making any other calls to PortAudio, you must call Pa_Initialize(). +This will trigger a scan of available devices which can be queried later. +Like most PA functions, it will return a result of type paError. +If the result is not paNoError, then an error has occurred. +
+
err = Pa_Initialize();
+if( err != paNoError ) goto error;
+
+You can get a text message that explains the error message by passing it +to +
+
printf(  "PortAudio error: %s\n", Pa_GetErrorText( err ) );
+
+
+home | contents +| previousnext + + diff --git a/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_mac.html b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_mac.html new file mode 100755 index 00000000000..57b6e1da908 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_mac.html @@ -0,0 +1,41 @@ + + + + + + + + + PortAudio Tutorial + + +  +
+ + + +
+
+

+PortAudio Tutorial

+
+ +

+Compiling for Macintosh

+ +
To compile a Macintosh application with the PortAudio library, +add the following source files to your project: +
+
pa_mac:pa_mac.c
+pa_common:pa_lib.c
+pa_common:portaudio.h
+pa_common:pa_host.h
+
+Also add the Apple SoundLib to your project. +

You may try compiling the "pa_tests:patest_saw.c" file first because +it is the simplest.

+home | +contents +| previousnext + + diff --git a/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_mac_osx.html b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_mac_osx.html new file mode 100755 index 00000000000..f5884f7908c --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_mac_osx.html @@ -0,0 +1,84 @@ + + + + + + + + + PortAudio Tutorial + + +  +
+ + + +
+
+

+PortAudio Tutorial

+
+ +

+home | +contents +| previousnext

+ +

+Compiling for Macintosh OS X

+ +
To compile a Macintosh OS X CoreAudio application with the +PortAudio library you will use the following source files: +
pa_mac_core/pa_mac_core.c
+pa_common/pa_lib.c
+pa_common/portaudio.h
+pa_common/pa_host.h
+pa_common/pa_convert.c
+pablio/ringbuffer.c
+pablio/ringbuffer.h
+
+ +

+Using Apple Project Builder

+ +
Create a new ProjectBuilder project. You can use a "Tool" project +to run the PortAudio examples. +

Add the source files from above to your Project. +

Add both the Apple CoreAudio.framework and the AudioToolbox.framework +to your project by selecting "Add FrameWorks..." from the Project menu. +

Compile and run the "pa_tests:patest_saw.c" file first because it is +the simplest.

+ +

+Or Using Metrowerks CodeWarrior 8

+ +
by James Vanlommel
+ +
Create a new CodeWarrior project using Mac OS C++ Stationery. +
Then choose Mac OS X Mach-O > Standard Console > C++ Console Mach-O. +

In the project window, Clear the HelloWorld.cpp file and add the source +files from above to your Project. +

Add a test file of your choosing, like +
   patests    /patest_sine8.c +
  +
Add the frameworks to the Frameworks tab using Project > Add Files... +
   CoreAudio +
   AudioToolbox +

(The System framework should already be a part of the project.) +

Open the current target's settings, and in Language Settings > C/C++ +Language, uncheck (disable) the "ANSI Strict" setting. (Do this for both +Debug and Release projects, if necessary.) +

Edit pa_mac_core.c: +
   On line 1546, cast the PaHost_AllocateFastMemory() result +to a (char *) or you will get a compile error. +
  +
Compile and run. (may need to run from a terminal window) +

I've successfully built patest_sine8.c this way using the CVS .tar version +of portaudio (date: 2003-04-27). I get 17 warnings during compilation, +all of which deal with unused variables or arguments.

+home | +contents +| previousnext + + diff --git a/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_open.html b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_open.html new file mode 100755 index 00000000000..86e7e0b59a4 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_open.html @@ -0,0 +1,56 @@ + + + + + + + + + PortAudio Tutorial + + +  +
+ + + +
+
+

+PortAudio Tutorial

+
+ +

+Opening a Stream using Defaults

+ +
The next step is to open a stream which is similar to opening +a file. You can specify whether you want audio input and/or output, how +many channels, the data format, sample rate, etc. +

First declare a variable to receive the stream pointer: +

+
PortAudioStream   *stream;
+
+There are two calls for opening streams, Pa_OpenStream() and Pa_OpenDefaultStream(). +Pa_OpenStream() takes extra  parameters which give you more +control. You can normally just use Pa_OpenDefaultStream() which +just calls Pa_OpenStream() with some reasonable default +values.  Let's open a stream for stereo output, using floating point +data, at 44100 Hz. +
+
err = Pa_OpenDefaultStream(
+    &stream,        /* passes back stream pointer */
+    0,              /* no input channels */
+    2,              /* stereo output */
+    paFloat32,      /* 32 bit floating point output */
+    44100,          /* sample rate */
+    256,            /* frames per buffer */
+    0,              /* number of buffers, if zero then use default minimum */
+    patestCallback, /* specify our custom callback */
+    &data );        /* pass our data through to callback */
+
+If you want to use 16 bit integer data, pass paInt16 instead of +paFloat32.
+home | contents +| previousnext + + diff --git a/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_oss.html b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_oss.html new file mode 100755 index 00000000000..447778f0940 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_oss.html @@ -0,0 +1,46 @@ + + + + + + + + + PortAudio Tutorial + + +  +
+ + + +
+
+

+PortAudio Tutorial

+
+ +

+Compiling for Unix OSS

+ +
[Skip this page if you are not using Unix and OSS] +

We currently support the OSS +audio drivers for Linux, Solaris, and FreeBSD. We hope to someday support +the newer ALSA drivers. +

    +
  1. +cd to pa_unix_oss directory
  2. + +
  3. +Edit the Makefile and uncomment one of the tests. You may try compiling +the "patest_sine.c" file first because it is very simple.
  4. + +
  5. +gmake run
  6. +
+
+home | +contents +| previousnext + + diff --git a/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_over.html b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_over.html new file mode 100755 index 00000000000..251cb0c088c --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_over.html @@ -0,0 +1,92 @@ + + + + + + + + + PortAudio Tutorial + + +  +
+ + + +
+
+

+PortAudio Tutorial

+
+ +

+Overview of PortAudio

+ +
PortAudio is a library that provides streaming audio input +and output. It is a cross-platform API (Application Programming Interface) +that works on Windows, Macintosh, Unix running OSS, SGI, BeOS, and perhaps +other platforms by the time you read this. This means that you can write +a simple 'C' program to process or generate an audio signal, and that program +can run on several different types of computer just by recompiling the +source code. +

Here are the steps to writing a PortAudio application: +

    +
  1. +Write a callback function that will be called by PortAudio when audio processing +is needed.
  2. + +
  3. +Initialize the PA library and open a stream for audio I/O.
  4. + +
  5. +Start the stream. Your callback function will be now be called repeatedly +by PA in the background.
  6. + +
  7. +In your callback you can read audio data from the inputBuffer and/or write +data to the outputBuffer.
  8. + +
  9. +Stop the stream by returning 1 from your callback, or by calling a stop +function.
  10. + +
  11. +Close the stream and terminate the library.
  12. +
+
+ +
There is also another interface +provided that allows you to generate audio in the foreground. You then +simply write data to the stream and the tool will not return until it is +ready to accept more data. This interface is simpler to use but is usually +not preferred for large applications because it requires that you launch +a thread to perform the synthesis. Launching a thread may be difficult +on non-multi-tasking systems such as the Macintosh prior to MacOS X. +

Let's continue by building a simple application that will play a sawtooth +wave. +

Please select the page for the specific implementation you would like +to use: +

+or continue with the next page of the programming +tutorial.
+home | +contents +| previous + + diff --git a/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_pc.html b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_pc.html new file mode 100755 index 00000000000..a14c82a1a89 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_pc.html @@ -0,0 +1,114 @@ + + + + + + + + + PortAudio Tutorial + + +  +
+ + + +
+
+

+PortAudio Tutorial

+
+ +

+Compiling for Windows (WMME or DirectSound)

+ +
To compile PortAudio for Windows, you can choose between three +options: +
    +
  • +DirectSound API.
  • + +
  • +Windows MultiMedia Extensions API (aka WMME or WAVE).
  • + +
  • +Steinberg's ASIO API
  • +
+Some advantages of using DirectSound are that DirectSound may have lower +latency than WMME, and supports effects processing plugins. But one disadvantage +is that DirectSound is not installed on all PCs, and is not well supported +under Windows NT. So WMME is the best choice for most projects. +

Note: If you are compiling one of the PortAudio test programs +with Visual C++, then create a new Project of type "Win32 Console Application". +

+All

+For any Windows implementation, add the following source files to your +project: +
+
pa_common\pa_lib.c
+pa_common\portaudio.h
+pa_common\pa_host.h
+
+Link with the system library "winmm.lib". For Visual C++: +
    +
  1. +select "Settings..." from the "Project" menu,
  2. + +
  3. +select the project name in the tree on the left,
  4. + +
  5. +choose "All Configurations" in the popup menu above the tree,
  6. + +
  7. +select the "Link" tab,
  8. + +
  9. +enter "winmm.lib", without quotes, as the first item in the "Object/library +modules:" field.
  10. +
+ +

+WMME

+To use the WMME implementation, add the following source files to your +project: +
pa_win_wmme/pa_win_wmme.c
+ +

+DirectSound

+If you want to use the DirectSound implementation of PortAudio then you +must have a recent copy of the free +DirectX +SDK for Developers from Microsoft installed on your computer. To compile +an application add the following source files to your project: +
+
pa_win_ds\dsound_wrapper.c
+pa_win_ds\pa_dsound.c
+
+Link with both system libraries "dsound.lib" and "winmm.lib" +using the procedure described above for "winmm.lib". +
  + + + + +
Borland users cannot link with the "dsound.lib" from Microsoft +directly. Emmanuel offered this advice: +

One can use implib from Borland to generate a new .lib file which is +compatible with Borland C++. +

Use: "implib dsound.dll dsound.lib" and include dsound.lib into your +project. +

I still had a problem executing the patest_record example. The thread +ended with an error like 'Floating point overflow at...'. This problem +was caused due to a fault in the compiler. Now I'm using Borland 5.02 (instead +of 5.01). Everything seems to be working fine at the moment.

+
+ +
You might try compiling the "pa_tests\patest_saw.c" file first +because it is the simplest.
+home | +contents +| previousnext + + diff --git a/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_run.html b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_run.html new file mode 100755 index 00000000000..476df682656 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_run.html @@ -0,0 +1,56 @@ + + + + + + + + + PortAudio Tutorial + + +  +
+ + + +
+
+

+PortAudio Tutorial

+
+ +

+Starting and Stopping a Stream

+ +
The stream will not start running until you call Pa_StartStream(). +Then it will start calling your callback function to perform the audio +processing. +
+
err = Pa_StartStream( stream );
+if( err != paNoError ) goto error;
+
+At this point, audio is being generated. You can communicate to your callback +routine through the data structure you passed in on the open call, or through +global variables, or using other interprocess communication techniques. +Please be aware that your callback function may be called at interrupt +time when your foreground process is least expecting it. So avoid sharing +complex data structures that are easily corrupted like double linked lists. +

In many of the tests we simply sleep for a few seconds so we can hear +the sound. This is easy to do with Pa_Sleep() which will sleep for some +number of milliseconds. Do not rely on this function for accurate scheduling. +it is mostly for writing examples. +

+
/* Sleep for several seconds. */
+Pa_Sleep(NUM_SECONDS*1000);
+
+When you are through, you can stop the stream from the foreground. +
+
err = Pa_StopStream( stream );
+if( err != paNoError ) goto error;
+
+You can also stop the stream by returning 1 from your custom callback function.
+home | contents +| previousnext + + diff --git a/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_rw.html b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_rw.html new file mode 100755 index 00000000000..d677f02f2c6 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_rw.html @@ -0,0 +1,79 @@ + + + + + + + + + PortAudio Tutorial + + +  +
+ + + +
+
+

+PortAudio Tutorial

+
+ +

+Blocking Read/Write Functions

+ +
[Note: These functions are not part of the official PortAudio +API. They are simply built on top of PortAudio as an extra utility. Also +note that they are under evaluation and their definition may change.] +

There are two fundamentally different ways to design an audio API. One +is to use callback functions the way we have already shown. The callback +function operates under an interrupt or background thread This leaves the +foreground application free to do other things while the audio just runs +in the background. But this can sometimes be awkward. +

So we have provided an alternative technique that lets a program generate +audio in the foreground and then just write it to the audio stream as if +it was a file. If there is not enough room in the audio buffer for more +data, then the write function will just block until more room is available. +This can make it very easy to write an audio example. To use this tool, +you must add the files "pablio/pablio.c" and "pablio/ringbuffer.c" to your +project. You must also: +

+
#include "pablio.h"
+
+Here is a short excerpt of a program that opens a stream for input and +output. It then reads a block of samples from input, and writes them to +output, in a loop.  The complete example can be found in "pablio/test_rw.c". +
+
    #define SAMPLES_PER_FRAME     (2)
+    #define FRAMES_PER_BLOCK    (1024)
+    SAMPLE          samples[SAMPLES_PER_FRAME * FRAMES_PER_BLOCK];
+    PaError         err;
+    PABLIO_Stream  *aStream;
+
+/* Open simplified blocking I/O layer on top of PortAudio. */
+    err = OpenAudioStream( &rwbl, SAMPLE_RATE, paFloat32,
+                         (PABLIO_READ_WRITE | PABLIO_STEREO) );
+    if( err != paNoError ) goto error;
+
+/* Process samples in the foreground. */
+    for( i=0; i<(NUM_SECONDS * SAMPLE_RATE); i++ )
+    {
+    /* Read one block of data into sample array from audio input. */
+        ReadAudioStream( aStream, samples, FRAMES_PER_BLOCK );
+    /*
+    ** At this point you could process the data in samples array,
+    ** and write the result back to the same samples array.
+    */
+    /* Write that same frame of data to output. */
+        WriteAudioStream( aStream, samples, FRAMES_PER_BLOCK );
+    }
+
+    CloseAudioStream( aStream );
+
+
+home | +contents +| previousnext + + diff --git a/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_term.html b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_term.html new file mode 100755 index 00000000000..f96e6288851 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_term.html @@ -0,0 +1,47 @@ + + + + + + + + + PortAudio Tutorial + + +  +
+ + + +
+
+

+PortAudio Tutorial

+
+ +

+Terminating PortAudio

+ +
You can start and stop a stream as many times as you like. +But when you are done using it, you should close it by calling:
+ +
+
+
err = Pa_CloseStream( stream );
+if( err != paNoError ) goto error;
+
+Then when you are done using PortAudio, you should terminate the whole +system by calling: +
+
Pa_Terminate();
+
+That's basically it. You can now write an audio program in 'C' that will +run on multiple platforms, for example PCs and Macintosh. +

In the rest of the tutorial we will look at some additional utility +functions, and a different way of using PortAudio that does not require +the use of a callback function.

+home | contents +| previousnext + + diff --git a/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_util.html b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_util.html new file mode 100755 index 00000000000..ddf7de82260 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tut_util.html @@ -0,0 +1,55 @@ + + + + + + + + + PortAudio Tutorial + + +  +
+ + + +
+
+

+PortAudio Tutorial

+
+ +

+Utility Functions

+ +
Here are several more functions that are not critical, but +may be handy when using PortAudio. +

Pa_StreamActive() returns one when the stream in playing audio, zero +when not playing, or a negative error number if the stream is invalid. +The stream is active between calls to Pa_StartStream() and Pa_StopStream(), +but may also become inactive if the callback returns a non-zero value. +In the latter case, the stream is considered inactive after the last buffer +has finished playing. +

+
PaError Pa_StreamActive( PortAudioStream *stream );
+
+Pa_StreamTime() returns the number of samples that have been generated. +PaTimeStamp is a double precision number which is a convenient way to pass +big numbers around even though we only need integers. +
+
PaTimestamp Pa_StreamTime( PortAudioStream *stream );
+
+The "CPU Load" is a fraction of total CPU time consumed by the stream's +audio processing. A value of 0.5 would imply that PortAudio and the sound +generating callback was consuming roughly 50% of the available CPU time. +This function may be called from the callback function or the application. +
+
double Pa_GetCPULoad( PortAudioStream* stream );
+
+
+home | +contents | previous +|  next + + diff --git a/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tutorial.html b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tutorial.html new file mode 100755 index 00000000000..3cfc4d1f76c --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/docs/pa_tutorial.html @@ -0,0 +1,46 @@ + + + + + + + + + PortAudio Tutorial + + +  +
+ + + +
+
+

+PortAudio Tutorial

+
+ +

Copyright 2000 Phil Burk and Ross Bencina +

+Table of Contents

+ +
Overview of PortAudio +
Compiling for Macintosh OS 7,8,9 +
Compiling for Macintosh OS X +
Compiling for Windows (DirectSound and WMME) +
Compiling for ASIO on Windows or Mac OS +8,9 +
Compiling for Unix OSS +
Writing a Callback Function +
Initializing PortAudio +
Opening a Stream using Defaults +
Starting and Stopping a Stream +
Cleaning Up +
Utilities +
Querying for Devices +
Blocking Read/Write Functions +
Exploring the PortAudio Package
+home | contents | +previous |  next + + diff --git a/mozilla/zap/zmk/portaudio_v18_1/docs/portaudio_h.txt b/mozilla/zap/zmk/portaudio_v18_1/docs/portaudio_h.txt new file mode 100755 index 00000000000..a5afbe40ee3 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/docs/portaudio_h.txt @@ -0,0 +1,425 @@ +#ifndef PORT_AUDIO_H +#define PORT_AUDIO_H + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/* + * PortAudio Portable Real-Time Audio Library + * PortAudio API Header File + * Latest version available at: http://www.audiomulch.com/portaudio/ + * + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +typedef int PaError; +typedef enum { + paNoError = 0, + + paHostError = -10000, + paInvalidChannelCount, + paInvalidSampleRate, + paInvalidDeviceId, + paInvalidFlag, + paSampleFormatNotSupported, + paBadIODeviceCombination, + paInsufficientMemory, + paBufferTooBig, + paBufferTooSmall, + paNullCallback, + paBadStreamPtr, + paTimedOut, + paInternalError +} PaErrorNum; + +/* + Pa_Initialize() is the library initialisation function - call this before + using the library. +*/ + +PaError Pa_Initialize( void ); + +/* + Pa_Terminate() is the library termination function - call this after + using the library. +*/ + +PaError Pa_Terminate( void ); + +/* + Return host specific error. + This can be called after receiving a paHostError. +*/ +long Pa_GetHostError( void ); + +/* + Translate the error number into a human readable message. +*/ +const char *Pa_GetErrorText( PaError errnum ); + +/* + Sample formats + + These are formats used to pass sound data between the callback and the + stream. Each device has a "native" format which may be used when optimum + efficiency or control over conversion is required. + + Formats marked "always available" are supported (emulated) by all devices. + + The floating point representation uses +1.0 and -1.0 as the respective + maximum and minimum. + +*/ + +typedef unsigned long PaSampleFormat; +#define paFloat32 ((PaSampleFormat) (1<<0)) /*always available*/ +#define paInt16 ((PaSampleFormat) (1<<1)) /*always available*/ +#define paInt32 ((PaSampleFormat) (1<<2)) /*always available*/ +#define paInt24 ((PaSampleFormat) (1<<3)) +#define paPackedInt24 ((PaSampleFormat) (1<<4)) +#define paInt8 ((PaSampleFormat) (1<<5)) +#define paUInt8 ((PaSampleFormat) (1<<6)) /* unsigned 8 bit, 128 is "ground" */ +#define paCustomFormat ((PaSampleFormat) (1<<16)) + +/* + Device enumeration mechanism. + + Device ids range from 0 to Pa_CountDevices()-1. + + Devices may support input, output or both. Device 0 is always the "default" + device and should support at least stereo in and out if that is available + on the taget platform _even_ if this involves kludging an input/output + device on platforms that usually separate input from output. Other platform + specific devices are specified by positive device ids. +*/ + +typedef int PaDeviceID; +#define paNoDevice -1 + +typedef struct{ + int structVersion; + const char *name; + int maxInputChannels; + int maxOutputChannels; +/* Number of discrete rates, or -1 if range supported. */ + int numSampleRates; +/* Array of supported sample rates, or {min,max} if range supported. */ + const double *sampleRates; + PaSampleFormat nativeSampleFormats; +} PaDeviceInfo; + + +int Pa_CountDevices(); +/* + Pa_GetDefaultInputDeviceID(), Pa_GetDefaultOutputDeviceID() + + Return the default device ID or paNoDevice if there is no devices. + The result can be passed to Pa_OpenStream(). + + On the PC, the user can specify a default device by + setting an environment variable. For example, to use device #1. + + set PA_RECOMMENDED_OUTPUT_DEVICE=1 + + The user should first determine the available device ID by using + the supplied application "pa_devs". +*/ +PaDeviceID Pa_GetDefaultInputDeviceID( void ); +PaDeviceID Pa_GetDefaultOutputDeviceID( void ); + +/* + PaTimestamp is used to represent a continuous sample clock with arbitrary + start time useful for syncronisation. The type is used in the outTime + argument to the callback function and the result of Pa_StreamTime() +*/ + +typedef double PaTimestamp; + +/* + Pa_GetDeviceInfo() returns a pointer to an immutable PaDeviceInfo structure + referring to the device specified by id. + If id is out of range the function returns NULL. + + The returned structure is owned by the PortAudio implementation and must + not be manipulated or freed. The pointer is guaranteed to be valid until + between calls to Pa_Initialize() and Pa_Terminate(). +*/ + +const PaDeviceInfo* Pa_GetDeviceInfo( PaDeviceID devID ); + +/* + PortAudioCallback is implemented by clients of the portable audio api. + + inputBuffer and outputBuffer are arrays of interleaved samples, + the format, packing and number of channels used by the buffers are + determined by parameters to Pa_OpenStream() (see below). + + framesPerBuffer is the number of sample frames to be processed by the callback. + + outTime is the time in samples when the buffer(s) processed by + this callback will begin being played at the audio output. + See also Pa_StreamTime() + + userData is the value of a user supplied pointer passed to Pa_OpenStream() + intended for storing synthesis data etc. + + return value: + The callback can return a nonzero value to stop the stream. This may be + useful in applications such as soundfile players where a specific duration + of output is required. However, it is not necessary to utilise this mechanism + as StopStream() will also terminate the stream. A callback returning a + nonzero value must fill the entire outputBuffer. + + NOTE: None of the other stream functions may be called from within the + callback function except for Pa_GetCPULoad(). + +*/ + +typedef int (PortAudioCallback)( + void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ); + + +/* + Stream flags + + These flags may be supplied (ored together) in the streamFlags argument to + the Pa_OpenStream() function. + + [ suggestions? ] +*/ + +#define paNoFlag (0) +#define paClipOff (1<<0) /* disable defult clipping of out of range samples */ +#define paDitherOff (1<<1) /* disable default dithering */ +#define paPlatformSpecificFlags (0x00010000) +typedef unsigned long PaStreamFlags; + +/* + A single PortAudioStream provides multiple channels of real-time + input and output audio streaming to a client application. + Pointers to PortAudioStream objects are passed between PortAudio functions. +*/ + +typedef void PortAudioStream; +#define PaStream PortAudioStream + +/* + Pa_OpenStream() opens a stream for either input, output or both. + + stream is the address of a PortAudioStream pointer which will receive + a pointer to the newly opened stream. + + inputDevice is the id of the device used for input (see PaDeviceID above.) + inputDevice may be paNoDevice to indicate that an input device is not required. + + numInputChannels is the number of channels of sound to be delivered to the + callback. It can range from 1 to the value of maxInputChannels in the + device input record for the device specified in the inputDevice parameter. + If inputDevice is paNoDevice numInputChannels is ignored. + + inputSampleFormat is the format of inputBuffer provided to the callback + function. inputSampleFormat may be any of the formats described by the + PaSampleFormat enumeration (see above). PortAudio guarantees support for + the sound devices native formats (nativeSampleFormats in the device info + record) and additionally 16 and 32 bit integer and 32 bit floating point + formats. Support for other formats is implementation defined. + + inputDriverInfo is a pointer to an optional driver specific data structure + containing additional information for device setup or stream processing. + inputDriverInfo is never required for correct operation. If not used + inputDriverInfo should be NULL. + + outputDevice is the id of the device used for output (see PaDeviceID above.) + outputDevice may be paNoDevice to indicate that an output device is not required. + + numOutputChannels is the number of channels of sound to be supplied by the + callback. See the definition of numInputChannels above for more details. + + outputSampleFormat is the sample format of the outputBuffer filled by the + callback function. See the definition of inputSampleFormat above for more + details. + + outputDriverInfo is a pointer to an optional driver specific data structure + containing additional information for device setup or stream processing. + outputDriverInfo is never required for correct operation. If not used + outputDriverInfo should be NULL. + + sampleRate is the desired sampleRate for input and output + + framesPerBuffer is the length in sample frames of all internal sample buffers + used for communication with platform specific audio routines. Wherever + possible this corresponds to the framesPerBuffer parameter passed to the + callback function. + + numberOfBuffers is the number of buffers used for multibuffered + communication with the platform specific audio routines. This parameter is + provided only as a guide - and does not imply that an implementation must + use multibuffered i/o when reliable double buffering is available (such as + SndPlayDoubleBuffer() on the Macintosh.) + + streamFlags may contain a combination of flags ORed together. + These flags modify the behavior of the + streaming process. Some flags may only be relevant to certain buffer formats. + + callback is a pointer to a client supplied function that is responsible + for processing and filling input and output buffers (see above for details.) + + userData is a client supplied pointer which is passed to the callback + function. It could for example, contain a pointer to instance data necessary + for processing the audio buffers. + + return value: + Apon success Pa_OpenStream() returns PaNoError and places a pointer to a + valid PortAudioStream in the stream argument. The stream is inactive (stopped). + If a call to Pa_OpenStream() fails a nonzero error code is returned (see + PAError above) and the value of stream is invalid. + +*/ + +PaError Pa_OpenStream( PortAudioStream** stream, + PaDeviceID inputDevice, + int numInputChannels, + PaSampleFormat inputSampleFormat, + void *inputDriverInfo, + PaDeviceID outputDevice, + int numOutputChannels, + PaSampleFormat outputSampleFormat, + void *outputDriverInfo, + double sampleRate, + unsigned long framesPerBuffer, + unsigned long numberOfBuffers, + PaStreamFlags streamFlags, + PortAudioCallback *callback, + void *userData ); + + +/* + Pa_OpenDefaultStream() is a simplified version of Pa_OpenStream() that + opens the default input and/or ouput devices. Most parameters have + identical meaning to their Pa_OpenStream() counterparts, with the following + exceptions: + + If either numInputChannels or numOutputChannels is 0 the respective device + is not opened (same as passing paNoDevice in the device arguments to Pa_OpenStream() ) + + sampleFormat applies to both the input and output buffers. +*/ + +PaError Pa_OpenDefaultStream( PortAudioStream** stream, + int numInputChannels, + int numOutputChannels, + PaSampleFormat sampleFormat, + double sampleRate, + unsigned long framesPerBuffer, + unsigned long numberOfBuffers, + PortAudioCallback *callback, + void *userData ); + +/* + Pa_CloseStream() closes an audio stream, flushing any pending buffers. +*/ + +PaError Pa_CloseStream( PortAudioStream* ); + +/* + Pa_StartStream() and Pa_StopStream() begin and terminate audio processing. + Pa_StopStream() waits until all pending audio buffers have been played. + Pa_AbortStream() stops playing immediately without waiting for pending + buffers to complete. +*/ + +PaError Pa_StartStream( PortAudioStream *stream ); + +PaError Pa_StopStream( PortAudioStream *stream ); + +PaError Pa_AbortStream( PortAudioStream *stream ); + +/* + Pa_StreamActive() returns one when the stream is playing audio, + zero when not playing, or a negative error number if the + stream is invalid. + The stream is active between calls to Pa_StartStream() and Pa_StopStream(), + but may also become inactive if the callback returns a non-zero value. + In the latter case, the stream is considered inactive after the last + buffer has finished playing. +*/ + +PaError Pa_StreamActive( PortAudioStream *stream ); + +/* + Pa_StreamTime() returns the current output time for the stream in samples. + This time may be used as a time reference (for example syncronising audio to + MIDI). +*/ + +PaTimestamp Pa_StreamTime( PortAudioStream *stream ); + +/* + The "CPU Load" is a fraction of total CPU time consumed by the + stream's audio processing. + A value of 0.5 would imply that PortAudio and the sound generating + callback was consuming roughly 50% of the available CPU time. + This function may be called from the callback function or the application. +*/ +double Pa_GetCPULoad( PortAudioStream* stream ); + +/* + Use Pa_GetMinNumBuffers() to determine minimum number of buffers required for + the current host based on minimum latency. + On the PC, for the DirectSound implementation, latency can be optionally set + by user by setting an environment variable. + For example, to set latency to 200 msec, put: + + set PA_MIN_LATENCY_MSEC=200 + + in the AUTOEXEC.BAT file and reboot. + If the environment variable is not set, then the latency will be determined + based on the OS. Windows NT has higher latency than Win95. +*/ + +int Pa_GetMinNumBuffers( int framesPerBuffer, double sampleRate ); + +/* + Sleep for at least 'msec' milliseconds. + You may sleep longer than the requested time so don't rely + on this for accurate musical timing. +*/ +void Pa_Sleep( long msec ); + +/* + Return size in bytes of a single sample in a given PaSampleFormat + or paSampleFormatNotSupported. +*/ +PaError Pa_GetSampleSize( PaSampleFormat format ); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ +#endif /* PORT_AUDIO_H */ diff --git a/mozilla/zap/zmk/portaudio_v18_1/docs/portaudio_icmc2001.pdf b/mozilla/zap/zmk/portaudio_v18_1/docs/portaudio_icmc2001.pdf new file mode 100755 index 00000000000..dd074b7d334 Binary files /dev/null and b/mozilla/zap/zmk/portaudio_v18_1/docs/portaudio_icmc2001.pdf differ diff --git a/mozilla/zap/zmk/portaudio_v18_1/docs/proposals.html b/mozilla/zap/zmk/portaudio_v18_1/docs/proposals.html new file mode 100755 index 00000000000..f210c58257b Binary files /dev/null and b/mozilla/zap/zmk/portaudio_v18_1/docs/proposals.html differ diff --git a/mozilla/zap/zmk/portaudio_v18_1/docs/releases.html b/mozilla/zap/zmk/portaudio_v18_1/docs/releases.html new file mode 100755 index 00000000000..40203560949 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/docs/releases.html @@ -0,0 +1,339 @@ + + + + + + + + + PortAudio Release Notes + + +  +
+ + + +
+
+

+PortAudio - Release Notes

+
+ +

Link to PortAudio Home Page +

+V18 - 5/6/02

+ +
All source code and documentation now under CVS. +

Ran most of the code through AStyle +to cleanup ragged indentation caused by using different editors. Used this +command: +
   astyle --style=ansi -c -o --convert-tabs --indent-preprocessor +*.c

+ +
Added "pa_common/pa_convert.c" for Mac OS X. Start of new conversion +utilities. +

ASIO +

    +
  • +New Pa_ASIO_Adaptor_Init function to init Callback adpatation variables,
  • + +
  • +Cleanup of Pa_ASIO_Callback_Input
  • + +
  • +Break apart device loading to debug random failure in Pa_ASIO_QueryDeviceInfo
  • + +
  • +Deallocate all resources in PaHost_Term for cases where Pa_CloseStream +is not called properly
  • + +
  • +New Pa_ASIO_loadDriver that calls CoInitialize on each thread on Windows. +Allows use by multiple threads.
  • + +
  • +Correct error code management in PaHost_Term, removed various compiler +warning
  • + +
  • +Add Mac includes for <Devices.h> and <Timer.h>
  • + +
  • +Pa_ASIO_QueryDeviceInfo bug correction, memory allocation checking, better +error handling
  • +
+Mac OS X +
    +
  • +Major cleanup and improvements.
  • + +
  • +Fixed device queries for numChannels and sampleRates,
  • + +
  • +Audio input works if using same CoreAudio device (some HW devices make +separate CoreAudio devices).
  • + +
  • +Added paInt16, paInt8, format using new "pa_common/pa_convert.c" file.
  • + +
  • +Return error if opened in mono mode cuz not supported.
  • + +
  • +Check for getenv("PA_MIN_LATEWNCY_MSEC") to set latency externally.
  • + +
  • +Use getrusage() instead of gettimeofday() for CPU Load calculation.
  • +
+Windows MME +
    +
  • +Fixed bug that caused TIMEOUT in Pa_StopStream(). Added check for past_StopSoon() +in Pa_TimeSlice(). Thanks Julien Maillard.
  • + +
  • +Detect Win XP versus NT, use lower latency.
  • + +
  • +Fix DBUG typo;
  • + +
  • +removed init of CurrentCount which was not compiling on Borland
  • + +
  • +general cleanup, factored streamData alloc and cpu usage initialization
  • + +
  • +stopped counting WAVE_MAPPER when there were no audio cards plugged in
  • +
+Windows DirectSound +
    +
  • +Detect Win XP and Win 2K properly when determining latency.
  • +
+Unix OSS +
    +
  • +Use high real-time priority if app is running with root priveledges. Lowers +latency.
  • + +
  • +Added watch dog thread that prevents real-time thread from hogging CPU +and hanging the computer.
  • + +
  • +Check error return from read() and write().
  • + +
  • +Check CPU endianness instead of assuming Little Endian.
  • +
+
+ +

+V17 - 10/15/01

+ +
Unix OSS +
    +
  • +Set num channels back to two after device query for ALSA. This fixed a +bug in V16 that sometimes caused a failure when querying for the sample +rates. Thanks Stweart Greenhill.
  • +
+
+ +
+

+Macintosh Sound Manager

+ +
    +
  • +Use NewSndCallBackUPP() for CARBON compatibility.
  • +
+
+ +

+V16 - 9/27/01

+ +
Added Alpha implementations for ASIO, SGI, and BeOS! +
  +
  • +CPULoad is now calculated based on the time spent to generate a known number +of frames. This is more accurate than a simple percentage of real-time. +Implemented in pa_unix_oss, pa_win_wmme and pa_win_ds.
  • + +
  • +Fix dither and shift for recording PaUInt8 format data.
  • + +
  • +Added "patest_maxsines.c" which tests Pa_GetCPULoad().
  • +
    + +
    +

    +Windows WMME

    + +
      +
    • +sDevicePtrs now allocated using GlobalAlloc(). This prevents a +crash in Pa_Terminate() on Win2000. Thanks Mike Berry for finding this. +Thanks Mike Berry.
    • + +
    • +Pass process instead of thread to SetPriorityClass(). This fixes +a bug that caused the priority to not be increased. Thanks to Alberto di +Bene for spotting this.
    • +
    + +

    +Windows DirectSound

    + +
      +
    • +Casts for compiling with __MWERKS__ CodeWarrior.
    • +
    + +

    +UNIX OSS

    + +
      +
    • +Derived from Linux OSS implementation.
    • + +
    • +Numerous patches from Heiko Purnhagen, Stephen Brandon, etc.
    • + +
    • +Improved query mechanism which often bailed out unnecessarily.
    • + +
    • +Removed sNumDevices and potential related bugs,
    • + +
    • +Use getenv("PA_MIN_LATENCY_MSEC") in code to set desired latency. +User can set by entering:
    • + +
          export PA_MIN_LATENCY_MSEC=40
    + +

    +Macintosh Sound Manager

    + +
      +
    • +Pass unused event to WaitNextEvent instead of NULL to prevent Mac OSX crash. +Thanks Dominic Mazzoni.
    • + +
    • +Use requested number of input channels.
    • + +
       
    +
    + +

    +V15 - 5/29/01

    + +
    +
      +
    • +New Linux OSS Beta
    • +
    + +

    +Windows WMME

    + +
      +
    • + sDevicePtrs now allocated based on sizeof(pointer). Was allocating +too much space.
    • + +
    • + Check for excessive numbers of channels. Some drivers reported bogus +numbers.
    • + +
    • +Apply Mike Berry's changes for CodeWarrior on PC including condition including +of memory.h, and explicit typecasting on memory allocation.
    • +
    + +

    +Macintosh Sound Manager

    + +
      +
    • +ScanInputDevices was setting sDefaultOutputDeviceID instead of sDefaultInputDeviceID.
    • + +
    • +Device Scan was crashing for anything other than siBadSoundInDevice, but +some Macs may return other errors! Caused failure to init on some G4s under +OS9.
    • + +
    • +Fix TIMEOUT in record mode.
    • + +
    • +Change CARBON_COMPATIBLE to TARGET_API_MAC_CARBON
    • +
    +
    + +

    +V14 - 2/6/01

    + +
    +
      +
    • +Added implementation for Windows MultiMedia Extensions (WMME) by Ross and +Phil
    • + +
    • +Changed Pa_StopStream() so that it waits for the buffers to drain.
    • + +
    • +Added Pa_AbortStream() that stops immediately without waiting.
    • + +
    • +Added new test: patest_stop.c to test above two mods.
    • + +
    • +Fixed Pa_StreamTime() so that it returns current play position instead +of the write position. Added "patest_sync.c" to demo audio/video sync.
    • + +
    • +Improved stability of Macintosh implementation. Added timeouts to prevent +hangs.
    • + +
    • +Added Pa_GetSampleSize( PaSampleFormat format );
    • + +
    • +Changes some "int"s to "long"s so that PA works properly on Macintosh which +often compiles using 16 bit ints.
    • + +
    • +Added Implementation Guide
    • +
    +
    + +

    +V12 - 1/9/01

    + +
    +
      +
    • +Mac now scans for and queries all devices. But it does not yet support +selecting any other than the default device.
    • + +
    • +Blocking I/O calls renamed to separate them from the PortAudio API.
    • + +
    • +Cleaned up indentation problems with tabs versus spaces.
    • + +
    • +Now attempts to correct bogus sample rate info returned from DirectSound +device queries.
    • +
    +
    + + + diff --git a/mozilla/zap/zmk/portaudio_v18_1/fixdir.bat b/mozilla/zap/zmk/portaudio_v18_1/fixdir.bat new file mode 100755 index 00000000000..b6e8c25bc46 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/fixdir.bat @@ -0,0 +1,19 @@ +rem Use Astyle to fix style in 'C' files +cd %1% + +fixlines -p *.c +fixlines -p *.cpp +fixlines -p *.cc + +astyle --style=ansi -c -o --convert-tabs --indent-preprocessor *.c +astyle --style=ansi -c -o --convert-tabs --indent-preprocessor *.cpp +astyle --style=ansi -c -o --convert-tabs --indent-preprocessor *.cc +del *.orig +@rem convert line terminators to Unix style LFs +fixlines -u *.c +fixlines -u *.cpp +fixlines -u *.cc +fixlines -u *.h +del *.bak + +cd ..\ diff --git a/mozilla/zap/zmk/portaudio_v18_1/fixfile.bat b/mozilla/zap/zmk/portaudio_v18_1/fixfile.bat new file mode 100755 index 00000000000..699ea7ff13f --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/fixfile.bat @@ -0,0 +1,7 @@ +rem Use Astyle to fix style in a file +fixlines -p %1% +astyle --style=ansi -c -o --convert-tabs --indent-preprocessor %1% +del %1%.orig +@rem convert line terminators to Unix style LFs +fixlines -u %1% +del %1%.bak diff --git a/mozilla/zap/zmk/portaudio_v18_1/index.html b/mozilla/zap/zmk/portaudio_v18_1/index.html new file mode 100755 index 00000000000..0737e2884ff --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/index.html @@ -0,0 +1,89 @@ + + + + + + + + + PortAudio - Cross-Platform Audio API + + +  +
    + + + +
    +
    +

    +PortAudio - Portable Audio Library

    +
    + +

    Last updated 5/6/02. +

    PortAudio is a cross platform, open-source, audio +I/O library proposed by Ross Bencina to the music-dsp +mailing list. It lets you write simple audio programs in 'C' that will +compile and run on Windows, Macintosh, Unix, BeOS. PortAudio is +intended to promote the exchange of audio synthesis software between developers +on different platforms. +

    For complete information on PortAudio and to download the latest releases, +please visit "http://www.portaudio.com". +
      +
      +

    +

    +Click here for Documentation

    + +

    +

    + +

    +Contacts and E-Mail List

    + +
      +
    • +If you are using or implementing PortAudio then please join the PortAudio +mail list generously administered by +Bill +Eldridge.
    • + +
    • +If you find bugs in one of these implementations, or have suggestions, +please e-mail them to Phil Burk.
    • + +
    • +If you make improvements to the library, please send them to us so we can +incorporate the improvements.
    • +
    + +

    +License

    +PortAudio Portable Real-Time Audio Library +
    Copyright (c) 1999-2000 Ross Bencina and Phil Burk +

    Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following conditions: +

      +
    • +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software.
    • + +
    • +Any person wishing to distribute modifications to the Software is requested +to send the modifications to the original developer so that they can be +incorporated into the canonical version.
    • +
    +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND ON INFRINGEMENT. +
    IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT +OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR +THE USE OR OTHER DEALINGS IN THE SOFTWARE. +
      + + diff --git a/mozilla/zap/zmk/portaudio_v18_1/install-sh b/mozilla/zap/zmk/portaudio_v18_1/install-sh new file mode 100755 index 00000000000..7dc2f289737 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/install-sh @@ -0,0 +1,251 @@ +#!/bin/sh +# +# install - install a program, script, or datafile +# This comes from X11R5 (mit/util/scripts/install.sh). +# +# Copyright 1991 by the Massachusetts Institute of Technology +# +# Permission to use, copy, modify, distribute, and sell this software and its +# documentation for any purpose is hereby granted without fee, provided that +# the above copyright notice appear in all copies and that both that +# copyright notice and this permission notice appear in supporting +# documentation, and that the name of M.I.T. not be used in advertising or +# publicity pertaining to distribution of the software without specific, +# written prior permission. M.I.T. makes no representations about the +# suitability of this software for any purpose. It is provided "as is" +# without express or implied warranty. +# +# Calling this script install-sh is preferred over install.sh, to prevent +# `make' implicit rules from creating a file called install from it +# when there is no Makefile. +# +# This script is compatible with the BSD install script, but was written +# from scratch. It can only install one file at a time, a restriction +# shared with many OS's install programs. + + +# set DOITPROG to echo to test this script + +# Don't use :- since 4.3BSD and earlier shells don't like it. +doit="${DOITPROG-}" + + +# put in absolute paths if you don't have them in your path; or use env. vars. + +mvprog="${MVPROG-mv}" +cpprog="${CPPROG-cp}" +chmodprog="${CHMODPROG-chmod}" +chownprog="${CHOWNPROG-chown}" +chgrpprog="${CHGRPPROG-chgrp}" +stripprog="${STRIPPROG-strip}" +rmprog="${RMPROG-rm}" +mkdirprog="${MKDIRPROG-mkdir}" + +transformbasename="" +transform_arg="" +instcmd="$mvprog" +chmodcmd="$chmodprog 0755" +chowncmd="" +chgrpcmd="" +stripcmd="" +rmcmd="$rmprog -f" +mvcmd="$mvprog" +src="" +dst="" +dir_arg="" + +while [ x"$1" != x ]; do + case $1 in + -c) instcmd="$cpprog" + shift + continue;; + + -d) dir_arg=true + shift + continue;; + + -m) chmodcmd="$chmodprog $2" + shift + shift + continue;; + + -o) chowncmd="$chownprog $2" + shift + shift + continue;; + + -g) chgrpcmd="$chgrpprog $2" + shift + shift + continue;; + + -s) stripcmd="$stripprog" + shift + continue;; + + -t=*) transformarg=`echo $1 | sed 's/-t=//'` + shift + continue;; + + -b=*) transformbasename=`echo $1 | sed 's/-b=//'` + shift + continue;; + + *) if [ x"$src" = x ] + then + src=$1 + else + # this colon is to work around a 386BSD /bin/sh bug + : + dst=$1 + fi + shift + continue;; + esac +done + +if [ x"$src" = x ] +then + echo "install: no input file specified" + exit 1 +else + true +fi + +if [ x"$dir_arg" != x ]; then + dst=$src + src="" + + if [ -d $dst ]; then + instcmd=: + chmodcmd="" + else + instcmd=mkdir + fi +else + +# Waiting for this to be detected by the "$instcmd $src $dsttmp" command +# might cause directories to be created, which would be especially bad +# if $src (and thus $dsttmp) contains '*'. + + if [ -f $src -o -d $src ] + then + true + else + echo "install: $src does not exist" + exit 1 + fi + + if [ x"$dst" = x ] + then + echo "install: no destination specified" + exit 1 + else + true + fi + +# If destination is a directory, append the input filename; if your system +# does not like double slashes in filenames, you may need to add some logic + + if [ -d $dst ] + then + dst="$dst"/`basename $src` + else + true + fi +fi + +## this sed command emulates the dirname command +dstdir=`echo $dst | sed -e 's,[^/]*$,,;s,/$,,;s,^$,.,'` + +# Make sure that the destination directory exists. +# this part is taken from Noah Friedman's mkinstalldirs script + +# Skip lots of stat calls in the usual case. +if [ ! -d "$dstdir" ]; then +defaultIFS=' +' +IFS="${IFS-${defaultIFS}}" + +oIFS="${IFS}" +# Some sh's can't handle IFS=/ for some reason. +IFS='%' +set - `echo ${dstdir} | sed -e 's@/@%@g' -e 's@^%@/@'` +IFS="${oIFS}" + +pathcomp='' + +while [ $# -ne 0 ] ; do + pathcomp="${pathcomp}${1}" + shift + + if [ ! -d "${pathcomp}" ] ; + then + $mkdirprog "${pathcomp}" + else + true + fi + + pathcomp="${pathcomp}/" +done +fi + +if [ x"$dir_arg" != x ] +then + $doit $instcmd $dst && + + if [ x"$chowncmd" != x ]; then $doit $chowncmd $dst; else true ; fi && + if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dst; else true ; fi && + if [ x"$stripcmd" != x ]; then $doit $stripcmd $dst; else true ; fi && + if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dst; else true ; fi +else + +# If we're going to rename the final executable, determine the name now. + + if [ x"$transformarg" = x ] + then + dstfile=`basename $dst` + else + dstfile=`basename $dst $transformbasename | + sed $transformarg`$transformbasename + fi + +# don't allow the sed command to completely eliminate the filename + + if [ x"$dstfile" = x ] + then + dstfile=`basename $dst` + else + true + fi + +# Make a temp file name in the proper directory. + + dsttmp=$dstdir/#inst.$$# + +# Move or copy the file name to the temp name + + $doit $instcmd $src $dsttmp && + + trap "rm -f ${dsttmp}" 0 && + +# and set any options; do chmod last to preserve setuid bits + +# If any of these fail, we abort the whole thing. If we want to +# ignore errors from any of these, just make sure not to ignore +# errors from the above "$doit $instcmd $src $dsttmp" command. + + if [ x"$chowncmd" != x ]; then $doit $chowncmd $dsttmp; else true;fi && + if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dsttmp; else true;fi && + if [ x"$stripcmd" != x ]; then $doit $stripcmd $dsttmp; else true;fi && + if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dsttmp; else true;fi && + +# Now rename the file to the real destination. + + $doit $rmcmd -f $dstdir/$dstfile && + $doit $mvcmd $dsttmp $dstdir/$dstfile + +fi && + + +exit 0 diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_asio/pa_asio.cpp b/mozilla/zap/zmk/portaudio_v18_1/pa_asio/pa_asio.cpp new file mode 100755 index 00000000000..a0e88e421ac --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_asio/pa_asio.cpp @@ -0,0 +1,3084 @@ +/* + * $Id: pa_asio.cpp,v 1.1.2.1 2005-08-16 20:04:00 alex%croczilla.com Exp $ + * Portable Audio I/O Library for ASIO Drivers + * + * Author: Stephane Letz + * Based on the Open Source API proposed by Ross Bencina + * Copyright (c) 2000-2001 Stephane Letz, Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* Modification History + + 08-03-01 First version : Stephane Letz + 08-06-01 Tweaks for PC, use C++, buffer allocation, Float32 to Int32 conversion : Phil Burk + 08-20-01 More conversion, PA_StreamTime, Pa_GetHostError : Stephane Letz + 08-21-01 PaUInt8 bug correction, implementation of ASIOSTFloat32LSB and ASIOSTFloat32MSB native formats : Stephane Letz + 08-24-01 MAX_INT32_FP hack, another Uint8 fix : Stephane and Phil + 08-27-01 Implementation of hostBufferSize < userBufferSize case, better management of the ouput buffer when + the stream is stopped : Stephane Letz + 08-28-01 Check the stream pointer for null in bufferSwitchTimeInfo, correct bug in bufferSwitchTimeInfo when + the stream is stopped : Stephane Letz + 10-12-01 Correct the PaHost_CalcNumHostBuffers function: computes FramesPerHostBuffer to be the lowest that + respect requested FramesPerUserBuffer and userBuffersPerHostBuffer : Stephane Letz + 10-26-01 Management of hostBufferSize and userBufferSize of any size : Stephane Letz + 10-27-01 Improve calculus of hostBufferSize to be multiple or divisor of userBufferSize if possible : Stephane and Phil + 10-29-01 Change MAX_INT32_FP to (2147483520.0f) to prevent roundup to 0x80000000 : Phil Burk + 10-31-01 Clear the ouput buffer and user buffers in PaHost_StartOutput, correct bug in GetFirstMultiple : Stephane Letz + 11-06-01 Rename functions : Stephane Letz + 11-08-01 New Pa_ASIO_Adaptor_Init function to init Callback adpatation variables, cleanup of Pa_ASIO_Callback_Input: Stephane Letz + 11-29-01 Break apart device loading to debug random failure in Pa_ASIO_QueryDeviceInfo ; Phil Burk + 01-03-02 Desallocate all resources in PaHost_Term for cases where Pa_CloseStream is not called properly : Stephane Letz + 02-01-02 Cleanup, test of multiple-stream opening : Stephane Letz + 19-02-02 New Pa_ASIO_loadDriver that calls CoInitialize on each thread on Windows : Stephane Letz + 09-04-02 Correct error code management in PaHost_Term, removes various compiler warning : Stephane Letz + 12-04-02 Add Mac includes for and : Phil Burk + 13-04-02 Removes another compiler warning : Stephane Letz + 30-04-02 Pa_ASIO_QueryDeviceInfo bug correction, memory allocation checking, better error handling : D Viens, P Burk, S Letz + 01-12-02 Fix Pa_GetDefaultInputDeviceID and Pa_GetDefaultOuputDeviceID result when no driver are available : S Letz + 05-12-02 More debug messages : S Letz + 01-23-03 Increased max channels to 128. Fixed comparison of (OutputChannels > kMaxInputChannels) : P Burk + 02-17-03 Better termination handling : PaHost_CloseStream is called in PaHost_term is the the stream was not explicitely closed by the application : S Letz + 04-02-03 More robust ASIO driver buffer size initialization : some buggy drivers (like the Hoontech DSP24) give incorrect [min, preferred, max] values + They should work with the preferred size value, thus if Pa_ASIO_CreateBuffers fails with the hostBufferSize computed in PaHost_CalcNumHostBuffers, + we try again with the preferred size. Fix an old (never detected?) bug in the buffer adapdation code : S Letz + 30-06-03 The audio callback was not protected against reentrancy : some drivers (like the Hoontech DSP24) seems to cause this behaviour + that corrupted the buffer adapdation state and finally caused crashes. The reentrancy state is now checked in bufferSwitchTimeInfo : S Letz + + TO DO : + + - Check Pa_StopSteam and Pa_AbortStream + - Optimization for Input only or Ouput only (really necessary ??) +*/ + + +#include +#include +#include + +#include "portaudio.h" +#include "pa_host.h" +#include "pa_trace.h" + +#include "asiosys.h" +#include "asio.h" +#include "asiodrivers.h" + + +#if MAC +#include +#include +#include +#else +#include +#include +#include +#endif + +enum { + // number of input and outputs supported by the host application + // you can change these to higher or lower values + kMaxInputChannels = 128, + kMaxOutputChannels = 128 +}; + +/* ASIO specific device information. */ +typedef struct internalPortAudioDevice +{ + PaDeviceInfo pad_Info; +} internalPortAudioDevice; + + +/* ASIO driver internal data storage */ +typedef struct PaHostSoundControl +{ + // ASIOInit() + ASIODriverInfo pahsc_driverInfo; + + // ASIOGetChannels() + int32 pahsc_NumInputChannels; + int32 pahsc_NumOutputChannels; + + // ASIOGetBufferSize() - sizes in frames per buffer + int32 pahsc_minSize; + int32 pahsc_maxSize; + int32 pahsc_preferredSize; + int32 pahsc_granularity; + + // ASIOGetSampleRate() + ASIOSampleRate pahsc_sampleRate; + + // ASIOOutputReady() + bool pahsc_postOutput; + + // ASIOGetLatencies () + int32 pahsc_inputLatency; + int32 pahsc_outputLatency; + + // ASIOCreateBuffers () + ASIOBufferInfo bufferInfos[kMaxInputChannels + kMaxOutputChannels]; // buffer info's + + // ASIOGetChannelInfo() + ASIOChannelInfo pahsc_channelInfos[kMaxInputChannels + kMaxOutputChannels]; // channel info's + // The above two arrays share the same indexing, as the data in them are linked together + + // Information from ASIOGetSamplePosition() + // data is converted to double floats for easier use, however 64 bit integer can be used, too + double nanoSeconds; + double samples; + double tcSamples; // time code samples + + // bufferSwitchTimeInfo() + ASIOTime tInfo; // time info state + unsigned long sysRefTime; // system reference time, when bufferSwitch() was called + + // Signal the end of processing in this example + bool stopped; + + ASIOCallbacks pahsc_asioCallbacks; + + + int32 pahsc_userInputBufferFrameOffset; // Position in Input user buffer + int32 pahsc_userOutputBufferFrameOffset; // Position in Output user buffer + int32 pahsc_hostOutputBufferFrameOffset; // Position in Output ASIO buffer + + int32 past_FramesPerHostBuffer; // Number of frames in ASIO buffer + + int32 pahsc_InputBufferOffset; // Number of null frames for input buffer alignement + int32 pahsc_OutputBufferOffset; // Number of null frames for ouput buffer alignement + +#if MAC + UInt64 pahsc_EntryCount; + UInt64 pahsc_LastExitCount; +#elif WINDOWS + LARGE_INTEGER pahsc_EntryCount; + LARGE_INTEGER pahsc_LastExitCount; +#endif + + PaTimestamp pahsc_NumFramesDone; + + internalPortAudioStream *past; + + int32 reenterCount; // Counter of audio callback reentrancy + int32 reenterError; // Counter of audio callback reentrancy detection + +} PaHostSoundControl; + + +//---------------------------------------------------------- +#define PRINT(x) { printf x; fflush(stdout); } +#define ERR_RPT(x) PRINT(x) + +#define DBUG(x) /* PRINT(x) */ +#define DBUGX(x) /* PRINT(x) */ + +/* We are trying to be compatible with CARBON but this has not been thoroughly tested. */ +#define CARBON_COMPATIBLE (0) +#define PA_MAX_DEVICE_INFO (32) + +#define MIN_INT8 (-0x80) +#define MAX_INT8 (0x7F) + +#define MIN_INT8_FP ((float)-0x80) +#define MAX_INT8_FP ((float)0x7F) + +#define MIN_INT16_FP ((float)-0x8000) +#define MAX_INT16_FP ((float)0x7FFF) + +#define MIN_INT16 (-0x8000) +#define MAX_INT16 (0x7FFF) + +#define MAX_INT32_FP (2147483520.0f) /* 0x0x7FFFFF80 - seems safe */ + +/************************************************************************************/ +/****************** Data ************************************************************/ +/************************************************************************************/ +static int sNumDevices = 0; +static internalPortAudioDevice sDevices[PA_MAX_DEVICE_INFO] = { 0 }; +static int32 sPaHostError = 0; +static int sDefaultOutputDeviceID = 0; +static int sDefaultInputDeviceID = 0; + +PaHostSoundControl asioDriverInfo = {0}; + +#ifdef MAC +static bool swap = true; +#elif WINDOWS +static bool swap = false; +#endif + +// Prototypes +static void bufferSwitch(long index, ASIOBool processNow); +static ASIOTime *bufferSwitchTimeInfo(ASIOTime *timeInfo, long index, ASIOBool processNow); +static void sampleRateChanged(ASIOSampleRate sRate); +static long asioMessages(long selector, long value, void* message, double* opt); +static void Pa_StartUsageCalculation( internalPortAudioStream *past ); +static void Pa_EndUsageCalculation( internalPortAudioStream *past ); + +static void Pa_ASIO_Convert_Inter_Input( + ASIOBufferInfo* nativeBuffer, + void* inputBuffer, + long NumInputChannels, + long NumOuputChannels, + long framePerBuffer, + long hostFrameOffset, + long userFrameOffset, + ASIOSampleType nativeFormat, + PaSampleFormat paFormat, + PaStreamFlags flags, + long index); + +static void Pa_ASIO_Convert_Inter_Output( + ASIOBufferInfo* nativeBuffer, + void* outputBuffer, + long NumInputChannels, + long NumOuputChannels, + long framePerBuffer, + long hostFrameOffset, + long userFrameOffset, + ASIOSampleType nativeFormat, + PaSampleFormat paFormat, + PaStreamFlags flags, + long index); + +static void Pa_ASIO_Clear_Output(ASIOBufferInfo* nativeBuffer, + ASIOSampleType nativeFormat, + long NumInputChannels, + long NumOuputChannels, + long index, + long hostFrameOffset, + long frames); + +static void Pa_ASIO_Callback_Input(long index); +static void Pa_ASIO_Callback_Output(long index, long framePerBuffer); +static void Pa_ASIO_Callback_End(); +static void Pa_ASIO_Clear_User_Buffers(); + +// Some external references +extern AsioDrivers* asioDrivers ; +bool loadAsioDriver(char *name); +unsigned long get_sys_reference_time(); + + +/************************************************************************************/ +/****************** Macro ************************************************************/ +/************************************************************************************/ + +#define SwapLong(v) ((((v)>>24)&0xFF)|(((v)>>8)&0xFF00)|(((v)&0xFF00)<<8)|(((v)&0xFF)<<24)) ; +#define SwapShort(v) ((((v)>>8)&0xFF)|(((v)&0xFF)<<8)) ; + +#define ClipShort(v) (((v)MAX_INT16)?MAX_INT16:(v))) +#define ClipChar(v) (((v)MAX_INT8)?MAX_INT8:(v))) +#define ClipFloat(v) (((v)<-1.0f)?-1.0f:(((v)>1.0f)?1.0f:(v))) + +#ifndef min +#define min(a,b) ((a)<(b)?(a):(b)) +#endif + +#ifndef max +#define max(a,b) ((a)>=(b)?(a):(b)) +#endif + + +static bool Pa_ASIO_loadAsioDriver(char *name) +{ + #ifdef WINDOWS + CoInitialize(0); + #endif + return loadAsioDriver(name); +} + + + +// Utilities for alignement buffer size computation +static int PGCD (int a, int b) {return (b == 0) ? a : PGCD (b,a%b);} +static int PPCM (int a, int b) {return (a*b) / PGCD (a,b);} + +// Takes the size of host buffer and user buffer : returns the number of frames needed for buffer adaptation +static int Pa_ASIO_CalcFrameShift (int M, int N) +{ + int res = 0; + for (int i = M; i < PPCM (M,N) ; i+=M) { res = max (res, i%N); } + return res; +} + +// We have the following relation : +// Pa_ASIO_CalcFrameShift (M,N) + M = Pa_ASIO_CalcFrameShift (N,M) + N + +/* ASIO sample type to PortAudio sample type conversion */ +static PaSampleFormat Pa_ASIO_Convert_SampleFormat(ASIOSampleType type) +{ + switch (type) { + + case ASIOSTInt16MSB: + case ASIOSTInt16LSB: + case ASIOSTInt32MSB16: + case ASIOSTInt32LSB16: + return paInt16; + + case ASIOSTFloat32MSB: + case ASIOSTFloat32LSB: + case ASIOSTFloat64MSB: + case ASIOSTFloat64LSB: + return paFloat32; + + case ASIOSTInt32MSB: + case ASIOSTInt32LSB: + case ASIOSTInt32MSB18: + case ASIOSTInt32MSB20: + case ASIOSTInt32MSB24: + case ASIOSTInt32LSB18: + case ASIOSTInt32LSB20: + case ASIOSTInt32LSB24: + return paInt32; + + case ASIOSTInt24MSB: + case ASIOSTInt24LSB: + return paInt24; + + default: + return paCustomFormat; + } +} + + + +//-------------------------------------------------------------------------------------------------------------------- +static void PaHost_CalcBufferOffset(internalPortAudioStream *past) +{ + if (asioDriverInfo.past_FramesPerHostBuffer > past->past_FramesPerUserBuffer){ + // Computes the MINIMUM value of null frames shift for the output buffer alignement + asioDriverInfo.pahsc_OutputBufferOffset = Pa_ASIO_CalcFrameShift (asioDriverInfo.past_FramesPerHostBuffer,past->past_FramesPerUserBuffer); + asioDriverInfo.pahsc_InputBufferOffset = 0; + DBUG(("PaHost_CalcBufferOffset : Minimum BufferOffset for Output = %d\n", asioDriverInfo.pahsc_OutputBufferOffset)); + }else{ + + //Computes the MINIMUM value of null frames shift for the input buffer alignement + asioDriverInfo.pahsc_InputBufferOffset = Pa_ASIO_CalcFrameShift (asioDriverInfo.past_FramesPerHostBuffer,past->past_FramesPerUserBuffer); + asioDriverInfo.pahsc_OutputBufferOffset = 0; + DBUG(("PaHost_CalcBufferOffset : Minimum BufferOffset for Input = %d\n", asioDriverInfo.pahsc_InputBufferOffset)); + } +} + +//-------------------------------------------------------------------------------------------------------------------- +/* Allocate ASIO buffers, initialise channels */ +static ASIOError Pa_ASIO_CreateBuffers (PaHostSoundControl *asioDriverInfo, long InputChannels, + long OutputChannels, long framesPerBuffer) +{ + ASIOError err; + int i; + + ASIOBufferInfo *info = asioDriverInfo->bufferInfos; + + // Check parameters + if ((InputChannels > kMaxInputChannels) || (OutputChannels > kMaxOutputChannels)) return ASE_InvalidParameter; + + for(i = 0; i < InputChannels; i++, info++){ + info->isInput = ASIOTrue; + info->channelNum = i; + info->buffers[0] = info->buffers[1] = 0; + } + + for(i = 0; i < OutputChannels; i++, info++){ + info->isInput = ASIOFalse; + info->channelNum = i; + info->buffers[0] = info->buffers[1] = 0; + } + + // Set up the asioCallback structure and create the ASIO data buffer + asioDriverInfo->pahsc_asioCallbacks.bufferSwitch = &bufferSwitch; + asioDriverInfo->pahsc_asioCallbacks.sampleRateDidChange = &sampleRateChanged; + asioDriverInfo->pahsc_asioCallbacks.asioMessage = &asioMessages; + asioDriverInfo->pahsc_asioCallbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfo; + + DBUG(("Pa_ASIO_CreateBuffers : ASIOCreateBuffers with inputChannels = %ld \n", InputChannels)); + DBUG(("Pa_ASIO_CreateBuffers : ASIOCreateBuffers with OutputChannels = %ld \n", OutputChannels)); + DBUG(("Pa_ASIO_CreateBuffers : ASIOCreateBuffers with size = %ld \n", framesPerBuffer)); + + err = ASIOCreateBuffers( asioDriverInfo->bufferInfos, InputChannels+OutputChannels, + framesPerBuffer, &asioDriverInfo->pahsc_asioCallbacks); + if (err != ASE_OK) return err; + + // Initialise buffers + for (i = 0; i < InputChannels + OutputChannels; i++) + { + asioDriverInfo->pahsc_channelInfos[i].channel = asioDriverInfo->bufferInfos[i].channelNum; + asioDriverInfo->pahsc_channelInfos[i].isInput = asioDriverInfo->bufferInfos[i].isInput; + err = ASIOGetChannelInfo(&asioDriverInfo->pahsc_channelInfos[i]); + if (err != ASE_OK) break; + } + + err = ASIOGetLatencies(&asioDriverInfo->pahsc_inputLatency, &asioDriverInfo->pahsc_outputLatency); + + DBUG(("Pa_ASIO_CreateBuffers : InputLatency = %ld latency = %ld msec \n", + asioDriverInfo->pahsc_inputLatency, + (long)((asioDriverInfo->pahsc_inputLatency*1000)/ asioDriverInfo->past->past_SampleRate))); + DBUG(("Pa_ASIO_CreateBuffers : OuputLatency = %ld latency = %ld msec \n", + asioDriverInfo->pahsc_outputLatency, + (long)((asioDriverInfo->pahsc_outputLatency*1000)/ asioDriverInfo->past->past_SampleRate))); + + return err; +} + + +/* + Query ASIO driver info : + + First we get all available ASIO drivers located in the ASIO folder, + then try to load each one. For each loaded driver, get all needed informations. +*/ +static PaError Pa_ASIO_QueryDeviceInfo( internalPortAudioDevice * ipad ) +{ + +#define NUM_STANDARDSAMPLINGRATES 3 /* 11.025, 22.05, 44.1 */ +#define NUM_CUSTOMSAMPLINGRATES 9 /* must be the same number of elements as in the array below */ +#define MAX_NUMSAMPLINGRATES (NUM_STANDARDSAMPLINGRATES+NUM_CUSTOMSAMPLINGRATES) + + ASIOSampleRate possibleSampleRates[] + = {8000.0, 9600.0, 11025.0, 12000.0, 16000.0, 22050.0, 24000.0, 32000.0, 44100.0, 48000.0, 88200.0, 96000.0}; + + ASIOChannelInfo channelInfos; + long InputChannels,OutputChannels; + double *sampleRates; + char* names[PA_MAX_DEVICE_INFO] ; + PaDeviceInfo *dev; + int i; + int numDrivers; + ASIOError asioError; + + /* Allocate names */ + for (i = 0 ; i < PA_MAX_DEVICE_INFO ; i++) { + names[i] = (char*)PaHost_AllocateFastMemory(32); + /* check memory */ + if(!names[i]) return paInsufficientMemory; + } + + /* MUST BE CHECKED : to force fragments loading on Mac */ + Pa_ASIO_loadAsioDriver("dummy"); + + /* Get names of all available ASIO drivers */ + asioDrivers->getDriverNames(names,PA_MAX_DEVICE_INFO); + + /* Check all available ASIO drivers */ +#if MAC + numDrivers = asioDrivers->getNumFragments(); +#elif WINDOWS + numDrivers = asioDrivers->asioGetNumDev(); +#endif + + DBUG(("PaASIO_QueryDeviceInfo: number of installed drivers = %d\n", numDrivers )); + + for (int driver = 0 ; driver < numDrivers ; driver++) + { + + #if WINDOWS + asioDriverInfo.pahsc_driverInfo.asioVersion = 2; // FIXME - is this right? PLB + asioDriverInfo.pahsc_driverInfo.sysRef = GetDesktopWindow(); // FIXME - is this right? PLB + #endif + + DBUG(("---------------------------------------\n")); + + DBUG(("PaASIO_QueryDeviceInfo: Driver name = %s\n", names[driver])); + + /* If the driver can be loaded : */ + if ( !Pa_ASIO_loadAsioDriver(names[driver]) ){ + DBUG(("PaASIO_QueryDeviceInfo could not loadAsioDriver %s\n", names[driver])); + } else { + + DBUG(("PaASIO_QueryDeviceInfo: loadAsioDriver OK\n")); + + if((asioError = ASIOInit(&asioDriverInfo.pahsc_driverInfo)) != ASE_OK){ + + DBUG(("PaASIO_QueryDeviceInfo: ASIOInit returned %d for %s\n", asioError, names[driver])); + + }else { + + DBUG(("PaASIO_QueryDeviceInfo: ASIOInit OK \n")); + + if(ASIOGetChannels(&InputChannels, &OutputChannels) != ASE_OK){ + + DBUG(("PaASIO_QueryDeviceInfo could not ASIOGetChannels for %s\n", names[driver])); + + }else { + + DBUG(("PaASIO_QueryDeviceInfo: ASIOGetChannels OK \n")); + + /* Gets the name */ + dev = &(ipad[sNumDevices].pad_Info); + dev->name = names[driver]; + names[driver] = 0; + + /* Gets Input and Output channels number */ + dev->maxInputChannels = InputChannels; + dev->maxOutputChannels = OutputChannels; + + DBUG(("PaASIO_QueryDeviceInfo: InputChannels = %d\n", InputChannels )); + DBUG(("PaASIO_QueryDeviceInfo: OutputChannels = %d\n", OutputChannels )); + + /* Make room in case device supports all rates. */ + sampleRates = (double*)PaHost_AllocateFastMemory(MAX_NUMSAMPLINGRATES * sizeof(double)); + /* check memory */ + if (!sampleRates) { + ASIOExit(); + return paInsufficientMemory; + } + dev->sampleRates = sampleRates; + dev->numSampleRates = 0; + + /* Loop through the possible sampling rates and check each to see if the device supports it. */ + for (int index = 0; index < MAX_NUMSAMPLINGRATES; index++) { + if (ASIOCanSampleRate(possibleSampleRates[index]) != ASE_NoClock) { + DBUG(("PaASIO_QueryDeviceInfo: possible sample rate = %d\n", (long)possibleSampleRates[index])); + dev->numSampleRates += 1; + *sampleRates = possibleSampleRates[index]; + sampleRates++; + } + } + + /* We assume that all channels have the same SampleType, so check the first */ + channelInfos.channel = 0; + channelInfos.isInput = 1; + + if ((asioError = ASIOGetChannelInfo(&channelInfos)) == ASE_NotPresent) { + DBUG(("PaASIO_QueryDeviceInfo: ASIOGetChannelInfo returned %d \n",asioError)); + } + + dev->nativeSampleFormats = Pa_ASIO_Convert_SampleFormat(channelInfos.type); + + /* unload the driver */ + if ((asioError = ASIOExit()) != ASE_OK) { + DBUG(("PaASIO_QueryDeviceInfo: ASIOExit returned %d \n",asioError)); + } + + sNumDevices++; + } + + } + } + } + + /* free only unused names */ + for (i = 0 ; i < PA_MAX_DEVICE_INFO ; i++) if (names[i]) PaHost_FreeFastMemory(names[i],32); + + return paNoError; +} + +//---------------------------------------------------------------------------------- +// TAKEN FROM THE ASIO SDK: +void sampleRateChanged(ASIOSampleRate sRate) +{ + // do whatever you need to do if the sample rate changed + // usually this only happens during external sync. + // Audio processing is not stopped by the driver, actual sample rate + // might not have even changed, maybe only the sample rate status of an + // AES/EBU or S/PDIF digital input at the audio device. + // You might have to update time/sample related conversion routines, etc. +} + +//---------------------------------------------------------------------------------- +// TAKEN FROM THE ASIO SDK: +long asioMessages(long selector, long value, void* message, double* opt) +{ + // currently the parameters "value", "message" and "opt" are not used. + long ret = 0; + switch(selector) + { + case kAsioSelectorSupported: + if(value == kAsioResetRequest + || value == kAsioEngineVersion + || value == kAsioResyncRequest + || value == kAsioLatenciesChanged + // the following three were added for ASIO 2.0, you don't necessarily have to support them + || value == kAsioSupportsTimeInfo + || value == kAsioSupportsTimeCode + || value == kAsioSupportsInputMonitor) + ret = 1L; + break; + + case kAsioBufferSizeChange: + //printf("kAsioBufferSizeChange \n"); + break; + + case kAsioResetRequest: + // defer the task and perform the reset of the driver during the next "safe" situation + // You cannot reset the driver right now, as this code is called from the driver. + // Reset the driver is done by completely destruct is. I.e. ASIOStop(), ASIODisposeBuffers(), Destruction + // Afterwards you initialize the driver again. + asioDriverInfo.stopped; // In this sample the processing will just stop + ret = 1L; + break; + case kAsioResyncRequest: + // This informs the application, that the driver encountered some non fatal data loss. + // It is used for synchronization purposes of different media. + // Added mainly to work around the Win16Mutex problems in Windows 95/98 with the + // Windows Multimedia system, which could loose data because the Mutex was hold too long + // by another thread. + // However a driver can issue it in other situations, too. + ret = 1L; + break; + case kAsioLatenciesChanged: + // This will inform the host application that the drivers were latencies changed. + // Beware, it this does not mean that the buffer sizes have changed! + // You might need to update internal delay data. + ret = 1L; + //printf("kAsioLatenciesChanged \n"); + break; + case kAsioEngineVersion: + // return the supported ASIO version of the host application + // If a host applications does not implement this selector, ASIO 1.0 is assumed + // by the driver + ret = 2L; + break; + case kAsioSupportsTimeInfo: + // informs the driver wether the asioCallbacks.bufferSwitchTimeInfo() callback + // is supported. + // For compatibility with ASIO 1.0 drivers the host application should always support + // the "old" bufferSwitch method, too. + ret = 1; + break; + case kAsioSupportsTimeCode: + // informs the driver wether application is interested in time code info. + // If an application does not need to know about time code, the driver has less work + // to do. + ret = 0; + break; + } + return ret; +} + + +//---------------------------------------------------------------------------------- +// conversion from 64 bit ASIOSample/ASIOTimeStamp to double float +#if NATIVE_INT64 + #define ASIO64toDouble(a) (a) +#else + const double twoRaisedTo32 = 4294967296.; + #define ASIO64toDouble(a) ((a).lo + (a).hi * twoRaisedTo32) +#endif + + +static ASIOTime *bufferSwitchTimeInfo(ASIOTime *timeInfo, long index, ASIOBool processNow) +{ + // the actual processing callback. + // Beware that this is normally in a seperate thread, hence be sure that you take care + // about thread synchronization. This is omitted here for simplicity. + + // store the timeInfo for later use + asioDriverInfo.tInfo = *timeInfo; + + // get the time stamp of the buffer, not necessary if no + // synchronization to other media is required + + if (timeInfo->timeInfo.flags & kSystemTimeValid) + asioDriverInfo.nanoSeconds = ASIO64toDouble(timeInfo->timeInfo.systemTime); + else + asioDriverInfo.nanoSeconds = 0; + + if (timeInfo->timeInfo.flags & kSamplePositionValid) + asioDriverInfo.samples = ASIO64toDouble(timeInfo->timeInfo.samplePosition); + else + asioDriverInfo.samples = 0; + + if (timeInfo->timeCode.flags & kTcValid) + asioDriverInfo.tcSamples = ASIO64toDouble(timeInfo->timeCode.timeCodeSamples); + else + asioDriverInfo.tcSamples = 0; + + // get the system reference time + asioDriverInfo.sysRefTime = get_sys_reference_time(); + +#if 0 + // a few debug messages for the Windows device driver developer + // tells you the time when driver got its interrupt and the delay until the app receives + // the event notification. + static double last_samples = 0; + char tmp[128]; + sprintf (tmp, "diff: %d / %d ms / %d ms / %d samples \n", asioDriverInfo.sysRefTime - (long)(asioDriverInfo.nanoSeconds / 1000000.0), asioDriverInfo.sysRefTime, (long)(asioDriverInfo.nanoSeconds / 1000000.0), (long)(asioDriverInfo.samples - last_samples)); + OutputDebugString (tmp); + last_samples = asioDriverInfo.samples; +#endif + + // To avoid the callback accessing a desallocated stream + if (asioDriverInfo.past == NULL) return 0L; + + // Keep sample position + asioDriverInfo.pahsc_NumFramesDone = timeInfo->timeInfo.samplePosition.lo; + + // Reentrancy control + if( ++asioDriverInfo.reenterCount) { + asioDriverInfo.reenterError++; + DBUG(("bufferSwitchTimeInfo : reentrancy detection = %d\n", asioDriverInfo.reenterError)); + return 0L; + } + + do { + + /* Has a user callback returned '1' to indicate finished at the last ASIO callback? */ + if( asioDriverInfo.past->past_StopSoon ) { + + Pa_ASIO_Clear_Output(asioDriverInfo.bufferInfos, + asioDriverInfo.pahsc_channelInfos[0].type, + asioDriverInfo.pahsc_NumInputChannels , + asioDriverInfo.pahsc_NumOutputChannels, + index, + 0, + asioDriverInfo.past_FramesPerHostBuffer); + + asioDriverInfo.past->past_IsActive = 0; + + // Finally if the driver supports the ASIOOutputReady() optimization, do it here, all data are in place + if (asioDriverInfo.pahsc_postOutput) ASIOOutputReady(); + + }else { + + /* CPU usage */ + Pa_StartUsageCalculation(asioDriverInfo.past); + + Pa_ASIO_Callback_Input(index); + + // Finally if the driver supports the ASIOOutputReady() optimization, do it here, all data are in place + if (asioDriverInfo.pahsc_postOutput) ASIOOutputReady(); + + Pa_ASIO_Callback_End(); + + /* CPU usage */ + Pa_EndUsageCalculation(asioDriverInfo.past); + } + + } while(asioDriverInfo.reenterCount--); + + return 0L; +} + + +//---------------------------------------------------------------------------------- +void bufferSwitch(long index, ASIOBool processNow) +{ + // the actual processing callback. + // Beware that this is normally in a seperate thread, hence be sure that you take care + // about thread synchronization. This is omitted here for simplicity. + + // as this is a "back door" into the bufferSwitchTimeInfo a timeInfo needs to be created + // though it will only set the timeInfo.samplePosition and timeInfo.systemTime fields and the according flags + + ASIOTime timeInfo; + memset (&timeInfo, 0, sizeof (timeInfo)); + + // get the time stamp of the buffer, not necessary if no + // synchronization to other media is required + if(ASIOGetSamplePosition(&timeInfo.timeInfo.samplePosition, &timeInfo.timeInfo.systemTime) == ASE_OK) + timeInfo.timeInfo.flags = kSystemTimeValid | kSamplePositionValid; + + // Call the real callback + bufferSwitchTimeInfo (&timeInfo, index, processNow); +} + +//---------------------------------------------------------------------------------- +unsigned long get_sys_reference_time() +{ + // get the system reference time + #if WINDOWS + return timeGetTime(); + #elif MAC + static const double twoRaisedTo32 = 4294967296.; + UnsignedWide ys; + Microseconds(&ys); + double r = ((double)ys.hi * twoRaisedTo32 + (double)ys.lo); + return (unsigned long)(r / 1000.); + #endif +} + + +/************************************************************* +** Calculate 2 LSB dither signal with a triangular distribution. +** Ranged properly for adding to a 32 bit integer prior to >>15. +*/ +#define DITHER_BITS (15) +#define DITHER_SCALE (1.0f / ((1<>(32-DITHER_BITS)) + (((long)randSeed2)>>(32-DITHER_BITS)); + /* High pass filter to reduce audibility. */ + highPass = current - previous; + previous = current; + return highPass; +} + +// TO BE COMPLETED WITH ALL SUPPORTED PA SAMPLE TYPES + +//------------------------------------------------------------------------------------------------------------------------------------------------------- +static void Input_Int16_Float32 (ASIOBufferInfo* nativeBuffer, float *inBufPtr, int framePerBuffer, int NumInputChannels, int index, int hostFrameOffset,int userFrameOffset, bool swap) +{ + long temp; + int i,j; + + for( j=0; j>16); + userBufPtr += NumInputChannels; + } + } + } + else + { + for( j=0; j> 1) + Pa_TriangularDither(); + temp = temp >> 15; + temp = (short) ClipShort(temp); + *userBufPtr = (short)temp; + userBufPtr += NumInputChannels; + } + } + + } +} + +//------------------------------------------------------------------------------------------------------------------------------------------------------- +// MUST BE TESTED +static void Input_Float32_Int16 (ASIOBufferInfo* nativeBuffer, short *inBufPtr, int framePerBuffer, int NumInputChannels, int index, int hostFrameOffset,int userFrameOffset,uint32 flags,bool swap) +{ + unsigned long temp; + int i,j; + + if( flags & paDitherOff ) + { + for( j=0; j>8); + userBufPtr += NumInputChannels; + } + } + } + else + { + for( j=0; j> 8; + temp = ClipShort(temp); + *userBufPtr = (char)(temp>>8); + userBufPtr += NumInputChannels; + } + } + } +} + +//------------------------------------------------------------------------------------------------------------------------------------------------------- +static void Input_Int32_Int8 (ASIOBufferInfo* nativeBuffer, char *inBufPtr, int framePerBuffer, int NumInputChannels, int index, int hostFrameOffset, int userFrameOffset, uint32 flags,bool swap) +{ + long temp; + int i,j; + + if( flags & paDitherOff ) + { + for( j=0; j>24); + userBufPtr += NumInputChannels; + } + } + } + else + { + for( j=0; j>16; // Shift to get a 16 bit value, then use the 16 bits to 8 bits code (MUST BE CHECHED) + temp += Pa_TriangularDither() >> 8; + temp = ClipShort(temp); + *userBufPtr = (char)(temp >> 8); + userBufPtr += NumInputChannels; + } + } + } +} + +//------------------------------------------------------------------------------------------------------------------------------------------------------- +// MUST BE TESTED + +static void Input_Float32_Int8 (ASIOBufferInfo* nativeBuffer, char *inBufPtr, int framePerBuffer, int NumInputChannels, int index, int hostFrameOffset,int userFrameOffset, uint32 flags,bool swap) +{ + unsigned long temp; + int i,j; + + if( flags & paDitherOff ) + { + for( j=0; j>8) + 0x80); + userBufPtr += NumInputChannels; + } + } + } + else + { + for( j=0; j> 8; + temp = ClipShort(temp); + *userBufPtr = (unsigned char)((temp>>8) + 0x80); + userBufPtr += NumInputChannels; + } + } + } +} + +//------------------------------------------------------------------------------------------------------------------------------------------------------- +static void Input_Int32_IntU8 (ASIOBufferInfo* nativeBuffer, unsigned char *inBufPtr, int framePerBuffer, int NumInputChannels, int index, int hostFrameOffset, int userFrameOffset,uint32 flags,bool swap) +{ + long temp; + int i,j; + + if( flags & paDitherOff ) + { + for( j=0; j>24) + 0x80); + userBufPtr += NumInputChannels; + } + } + } + else + { + for( j=0; j>16; // Shift to get a 16 bit value, then use the 16 bits to 8 bits code (MUST BE CHECHED) + temp += Pa_TriangularDither() >> 8; + temp = ClipShort(temp); + *userBufPtr = (unsigned char)((temp>>8) + 0x80); + userBufPtr += NumInputChannels; + } + } + } +} + +//------------------------------------------------------------------------------------------------------------------------------------------------------- +// MUST BE TESTED + +static void Input_Float32_IntU8 (ASIOBufferInfo* nativeBuffer, unsigned char *inBufPtr, int framePerBuffer, int NumInputChannels, int index, int hostFrameOffset,int userFrameOffset, uint32 flags,bool swap) +{ + unsigned long temp; + int i,j; + + if( flags & paDitherOff ) + { + for( j=0; j> 16); + if (swap) temp = SwapShort(temp); + asioBufPtr[i] = (short)temp; + userBufPtr += NumOuputChannels; + } + } + } + else + { + for (j= 0; j < NumOuputChannels; j++) + { + short *asioBufPtr = &((short*)nativeBuffer[j+NumInputChannels].buffers[index])[hostFrameOffset]; + long *userBufPtr = &outBufPtr[j+(userFrameOffset*NumOuputChannels)]; + for( i=0; i> 1) + Pa_TriangularDither(); + temp = temp >> 15; + temp = (short) ClipShort(temp); + if (swap) temp = SwapShort(temp); + asioBufPtr[i] = (short)temp; + userBufPtr += NumOuputChannels; + } + } + } +} + +//------------------------------------------------------------------------------------------------------------------------------------------------------- +static void Output_Int32_Int32(ASIOBufferInfo* nativeBuffer, long *outBufPtr, int framePerBuffer, int NumInputChannels, int NumOuputChannels, int index, int hostFrameOffset,int userFrameOffset,uint32 flags,bool swap) +{ + long temp; + int i,j; + + for (j= 0; j < NumOuputChannels; j++) + { + long *asioBufPtr = &((long*)nativeBuffer[j+NumInputChannels].buffers[index])[hostFrameOffset]; + long *userBufPtr = &outBufPtr[j+(userFrameOffset*NumOuputChannels)]; + for( i=0; ipast_FramesPerUserBuffer <= asioDriverInfo.past_FramesPerHostBuffer) { + asioDriverInfo.pahsc_hostOutputBufferFrameOffset = asioDriverInfo.pahsc_OutputBufferOffset; + asioDriverInfo.pahsc_userInputBufferFrameOffset = 0; // empty + asioDriverInfo.pahsc_userOutputBufferFrameOffset = asioDriverInfo.past->past_FramesPerUserBuffer; // empty + DBUG(("Pa_ASIO_Adaptor_Init : shift output\n")); + DBUG(("Pa_ASIO_Adaptor_Init : userInputBufferFrameOffset %d\n",asioDriverInfo.pahsc_userInputBufferFrameOffset)); + DBUG(("Pa_ASIO_Adaptor_Init : userOutputBufferFrameOffset %d\n",asioDriverInfo.pahsc_userOutputBufferFrameOffset)); + DBUG(("Pa_ASIO_Adaptor_Init : hostOutputBufferFrameOffset %d\n",asioDriverInfo.pahsc_hostOutputBufferFrameOffset)); + + }else { + asioDriverInfo.pahsc_hostOutputBufferFrameOffset = 0; // empty + asioDriverInfo.pahsc_userInputBufferFrameOffset = asioDriverInfo.pahsc_InputBufferOffset; + asioDriverInfo.pahsc_userOutputBufferFrameOffset = asioDriverInfo.past->past_FramesPerUserBuffer; // empty + DBUG(("Pa_ASIO_Adaptor_Init : shift input\n")); + DBUG(("Pa_ASIO_Adaptor_Init : userInputBufferFrameOffset %d\n",asioDriverInfo.pahsc_userInputBufferFrameOffset)); + DBUG(("Pa_ASIO_Adaptor_Init : userOutputBufferFrameOffset %d\n",asioDriverInfo.pahsc_userOutputBufferFrameOffset)); + DBUG(("Pa_ASIO_Adaptor_Init : hostOutputBufferFrameOffset %d\n",asioDriverInfo.pahsc_hostOutputBufferFrameOffset)); + } +} + +//------------------------------------------------------------------------------------------------------------------------------------------------------- +// FIXME : optimization for Input only or output only modes (really necessary ??) +static void Pa_ASIO_Callback_Input(long index) +{ + internalPortAudioStream *past = asioDriverInfo.past; + long framesInputHostBuffer = asioDriverInfo.past_FramesPerHostBuffer; // number of frames available into the host input buffer + long framesInputUserBuffer; // number of frames needed to complete the user input buffer + long framesOutputHostBuffer; // number of frames needed to complete the host output buffer + long framesOuputUserBuffer; // number of frames available into the user output buffer + long userResult; + long tmp; + + /* Fill host ASIO output with remaining frames in user output */ + framesOutputHostBuffer = asioDriverInfo.past_FramesPerHostBuffer - asioDriverInfo.pahsc_hostOutputBufferFrameOffset; + framesOuputUserBuffer = asioDriverInfo.past->past_FramesPerUserBuffer - asioDriverInfo.pahsc_userOutputBufferFrameOffset; + tmp = min(framesOutputHostBuffer, framesOuputUserBuffer); + framesOutputHostBuffer -= tmp; + Pa_ASIO_Callback_Output(index,tmp); + + /* Available frames in hostInputBuffer */ + while (framesInputHostBuffer > 0) { + + /* Number of frames needed to complete an user input buffer */ + framesInputUserBuffer = asioDriverInfo.past->past_FramesPerUserBuffer - asioDriverInfo.pahsc_userInputBufferFrameOffset; + + if (framesInputHostBuffer >= framesInputUserBuffer) { + + /* Convert ASIO input to user input */ + Pa_ASIO_Convert_Inter_Input (asioDriverInfo.bufferInfos, + past->past_InputBuffer, + asioDriverInfo.pahsc_NumInputChannels , + asioDriverInfo.pahsc_NumOutputChannels, + framesInputUserBuffer, + asioDriverInfo.past_FramesPerHostBuffer - framesInputHostBuffer, + asioDriverInfo.pahsc_userInputBufferFrameOffset, + asioDriverInfo.pahsc_channelInfos[0].type, + past->past_InputSampleFormat, + past->past_Flags, + index); + + /* Call PortAudio callback */ + userResult = asioDriverInfo.past->past_Callback(past->past_InputBuffer, past->past_OutputBuffer, + past->past_FramesPerUserBuffer,past->past_FrameCount,past->past_UserData ); + + /* User callback has asked us to stop in the middle of the host buffer */ + if( userResult != 0) { + + /* Put 0 in the end of the output buffer */ + Pa_ASIO_Clear_Output(asioDriverInfo.bufferInfos, + asioDriverInfo.pahsc_channelInfos[0].type, + asioDriverInfo.pahsc_NumInputChannels , + asioDriverInfo.pahsc_NumOutputChannels, + index, + asioDriverInfo.pahsc_hostOutputBufferFrameOffset, + asioDriverInfo.past_FramesPerHostBuffer - asioDriverInfo.pahsc_hostOutputBufferFrameOffset); + + past->past_StopSoon = 1; + return; + } + + + /* Full user ouput buffer : write offset */ + asioDriverInfo.pahsc_userOutputBufferFrameOffset = 0; + + /* Empty user input buffer : read offset */ + asioDriverInfo.pahsc_userInputBufferFrameOffset = 0; + + /* Fill host ASIO output */ + tmp = min (past->past_FramesPerUserBuffer,framesOutputHostBuffer); + Pa_ASIO_Callback_Output(index,tmp); + + framesOutputHostBuffer -= tmp; + framesInputHostBuffer -= framesInputUserBuffer; + + }else { + + /* Convert ASIO input to user input */ + Pa_ASIO_Convert_Inter_Input (asioDriverInfo.bufferInfos, + past->past_InputBuffer, + asioDriverInfo.pahsc_NumInputChannels , + asioDriverInfo.pahsc_NumOutputChannels, + framesInputHostBuffer, + asioDriverInfo.past_FramesPerHostBuffer - framesInputHostBuffer, + asioDriverInfo.pahsc_userInputBufferFrameOffset, + asioDriverInfo.pahsc_channelInfos[0].type, + past->past_InputSampleFormat, + past->past_Flags, + index); + + /* Update pahsc_userInputBufferFrameOffset */ + asioDriverInfo.pahsc_userInputBufferFrameOffset += framesInputHostBuffer; + + /* Update framesInputHostBuffer */ + framesInputHostBuffer = 0; + } + } + +} + +//------------------------------------------------------------------------------------------------------------------------------------------------------- +static void Pa_ASIO_Callback_Output(long index, long framePerBuffer) +{ + internalPortAudioStream *past = asioDriverInfo.past; + + if (framePerBuffer > 0) { + + /* Convert user output to ASIO ouput */ + Pa_ASIO_Convert_Inter_Output (asioDriverInfo.bufferInfos, + past->past_OutputBuffer, + asioDriverInfo.pahsc_NumInputChannels, + asioDriverInfo.pahsc_NumOutputChannels, + framePerBuffer, + asioDriverInfo.pahsc_hostOutputBufferFrameOffset, + asioDriverInfo.pahsc_userOutputBufferFrameOffset, + asioDriverInfo.pahsc_channelInfos[0].type, + past->past_InputSampleFormat, + past->past_Flags, + index); + + /* Update hostOuputFrameOffset */ + asioDriverInfo.pahsc_hostOutputBufferFrameOffset += framePerBuffer; + + /* Update userOutputFrameOffset */ + asioDriverInfo.pahsc_userOutputBufferFrameOffset += framePerBuffer; + } +} +//------------------------------------------------------------------------------------------------------------------------------------------------------- +static void Pa_ASIO_Callback_End() + { + /* Empty ASIO ouput : write offset */ + asioDriverInfo.pahsc_hostOutputBufferFrameOffset = 0; + } + +//------------------------------------------------------------------------------------------------------------------------------------------------------- +static void Pa_ASIO_Clear_User_Buffers() +{ + if( asioDriverInfo.past->past_InputBuffer != NULL ) + { + memset( asioDriverInfo.past->past_InputBuffer, 0, asioDriverInfo.past->past_InputBufferSize ); + } + if( asioDriverInfo.past->past_OutputBuffer != NULL ) + { + memset( asioDriverInfo.past->past_OutputBuffer, 0, asioDriverInfo.past->past_OutputBufferSize ); + } +} + +//------------------------------------------------------------------------------------------------------------------------------------------------------- + static void Pa_ASIO_Clear_Output(ASIOBufferInfo* nativeBuffer, + ASIOSampleType nativeFormat, + long NumInputChannels, + long NumOuputChannels, + long index, + long hostFrameOffset, + long frames) +{ + + switch (nativeFormat) { + + case ASIOSTInt16MSB: + case ASIOSTInt16LSB: + case ASIOSTInt32MSB16: + case ASIOSTInt32LSB16: + Pa_ASIO_Clear_Output_16(nativeBuffer, frames, NumInputChannels, NumOuputChannels, index, hostFrameOffset); + break; + + case ASIOSTFloat64MSB: + case ASIOSTFloat64LSB: + break; + + case ASIOSTFloat32MSB: + case ASIOSTFloat32LSB: + case ASIOSTInt32MSB: + case ASIOSTInt32LSB: + case ASIOSTInt32MSB18: + case ASIOSTInt32MSB20: + case ASIOSTInt32MSB24: + case ASIOSTInt32LSB18: + case ASIOSTInt32LSB20: + case ASIOSTInt32LSB24: + Pa_ASIO_Clear_Output_32(nativeBuffer, frames, NumInputChannels, NumOuputChannels, index, hostFrameOffset); + break; + + case ASIOSTInt24MSB: + case ASIOSTInt24LSB: + break; + + default: + break; + } +} + + +//--------------------------------------------------------------------------------------- +static void Pa_ASIO_Convert_Inter_Input( + ASIOBufferInfo* nativeBuffer, + void* inputBuffer, + long NumInputChannels, + long NumOuputChannels, + long framePerBuffer, + long hostFrameOffset, + long userFrameOffset, + ASIOSampleType nativeFormat, + PaSampleFormat paFormat, + PaStreamFlags flags, + long index) +{ + + if((NumInputChannels > 0) && (nativeBuffer != NULL)) + { + /* Convert from native format to PA format. */ + switch(paFormat) + { + case paFloat32: + { + float *inBufPtr = (float *) inputBuffer; + + switch (nativeFormat) { + case ASIOSTInt16LSB: + Input_Int16_Float32(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset, userFrameOffset, swap); + break; + case ASIOSTInt16MSB: + Input_Int16_Float32(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset, userFrameOffset,!swap); + break; + case ASIOSTInt32LSB: + Input_Int32_Float32(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset, userFrameOffset,swap); + break; + case ASIOSTInt32MSB: + Input_Int32_Float32(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset, userFrameOffset,!swap); + break; + case ASIOSTFloat32LSB: // IEEE 754 32 bit float, as found on Intel x86 architecture + Input_Float32_Float32(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset, userFrameOffset,swap); + break; + case ASIOSTFloat32MSB: // IEEE 754 32 bit float, as found on Intel x86 architecture + Input_Float32_Float32(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset, userFrameOffset,!swap); + break; + + case ASIOSTInt24LSB: // used for 20 bits as well + case ASIOSTInt24MSB: // used for 20 bits as well + + case ASIOSTFloat64LSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture + case ASIOSTFloat64MSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture + + // these are used for 32 bit data buffer, with different alignment of the data inside + // 32 bit PCI bus systems can more easily used with these + + case ASIOSTInt32LSB16: // 32 bit data with 16 bit alignment + case ASIOSTInt32LSB18: // 32 bit data with 18 bit alignment + case ASIOSTInt32LSB20: // 32 bit data with 20 bit alignment + case ASIOSTInt32LSB24: // 32 bit data with 24 bit alignment + + + case ASIOSTInt32MSB16: // 32 bit data with 16 bit alignment + case ASIOSTInt32MSB18: // 32 bit data with 18 bit alignment + case ASIOSTInt32MSB20: // 32 bit data with 20 bit alignment + case ASIOSTInt32MSB24: // 32 bit data with 24 bit alignment + DBUG(("Not yet implemented : please report the problem\n")); + break; + } + + break; + } + + case paInt32: + { + long *inBufPtr = (long *)inputBuffer; + + switch (nativeFormat) { + case ASIOSTInt16LSB: + Input_Int16_Int32(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, swap); + break; + case ASIOSTInt16MSB: + Input_Int16_Int32(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, !swap); + break; + case ASIOSTInt32LSB: + Input_Int32_Int32(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, swap); + break; + case ASIOSTInt32MSB: + Input_Int32_Int32(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, !swap); + break; + case ASIOSTFloat32LSB: // IEEE 754 32 bit float, as found on Intel x86 architecture + Input_Float32_Int32(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, swap); + break; + case ASIOSTFloat32MSB: // IEEE 754 32 bit float, as found on Intel x86 architecture + Input_Float32_Int32(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, !swap); + break; + + case ASIOSTInt24LSB: // used for 20 bits as well + case ASIOSTInt24MSB: // used for 20 bits as well + + case ASIOSTFloat64LSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture + case ASIOSTFloat64MSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture + + // these are used for 32 bit data buffer, with different alignment of the data inside + // 32 bit PCI bus systems can more easily used with these + + case ASIOSTInt32LSB16: // 32 bit data with 16 bit alignment + case ASIOSTInt32LSB18: // 32 bit data with 18 bit alignment + case ASIOSTInt32LSB20: // 32 bit data with 20 bit alignment + case ASIOSTInt32LSB24: // 32 bit data with 24 bit alignment + + + case ASIOSTInt32MSB16: // 32 bit data with 16 bit alignment + case ASIOSTInt32MSB18: // 32 bit data with 18 bit alignment + case ASIOSTInt32MSB20: // 32 bit data with 20 bit alignment + case ASIOSTInt32MSB24: // 32 bit data with 24 bit alignment + DBUG(("Not yet implemented : please report the problem\n")); + break; + + } + break; + } + + case paInt16: + { + short *inBufPtr = (short *) inputBuffer; + + switch (nativeFormat) { + case ASIOSTInt16LSB: + Input_Int16_Int16(nativeBuffer, inBufPtr, framePerBuffer , NumInputChannels, index , hostFrameOffset,userFrameOffset, swap); + break; + case ASIOSTInt16MSB: + Input_Int16_Int16(nativeBuffer, inBufPtr, framePerBuffer , NumInputChannels, index , hostFrameOffset,userFrameOffset, !swap); + break; + case ASIOSTInt32LSB: + Input_Int32_Int16(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, flags,swap); + break; + case ASIOSTInt32MSB: + Input_Int32_Int16(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, flags,!swap); + break; + case ASIOSTFloat32LSB: // IEEE 754 32 bit float, as found on Intel x86 architecture + Input_Float32_Int16(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, flags,swap); + break; + case ASIOSTFloat32MSB: // IEEE 754 32 bit float, as found on Intel x86 architecture + Input_Float32_Int16(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, flags,!swap); + break; + + case ASIOSTInt24LSB: // used for 20 bits as well + case ASIOSTInt24MSB: // used for 20 bits as well + + case ASIOSTFloat64LSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture + case ASIOSTFloat64MSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture + + // these are used for 32 bit data buffer, with different alignment of the data inside + // 32 bit PCI bus systems can more easily used with these + + case ASIOSTInt32LSB16: // 32 bit data with 16 bit alignment + case ASIOSTInt32LSB18: // 32 bit data with 18 bit alignment + case ASIOSTInt32LSB20: // 32 bit data with 20 bit alignment + case ASIOSTInt32LSB24: // 32 bit data with 24 bit alignment + + + case ASIOSTInt32MSB16: // 32 bit data with 16 bit alignment + case ASIOSTInt32MSB18: // 32 bit data with 18 bit alignment + case ASIOSTInt32MSB20: // 32 bit data with 20 bit alignment + case ASIOSTInt32MSB24: // 32 bit data with 24 bit alignment + DBUG(("Not yet implemented : please report the problem\n")); + break; + + } + break; + } + + case paInt8: + { + /* Convert 16 bit data to 8 bit chars */ + + char *inBufPtr = (char *) inputBuffer; + + switch (nativeFormat) { + case ASIOSTInt16LSB: + Input_Int16_Int8(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset,flags,swap); + break; + case ASIOSTInt16MSB: + Input_Int16_Int8(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, flags,!swap); + break; + case ASIOSTInt32LSB: + Input_Int32_Int8(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, flags,swap); + break; + case ASIOSTInt32MSB: + Input_Int32_Int8(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, flags,!swap); + break; + case ASIOSTFloat32LSB: // IEEE 754 32 bit float, as found on Intel x86 architecture + Input_Float32_Int8(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, flags,swap); + break; + case ASIOSTFloat32MSB: // IEEE 754 32 bit float, as found on Intel x86 architecture + Input_Float32_Int8(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, flags,!swap); + break; + + case ASIOSTInt24LSB: // used for 20 bits as well + case ASIOSTInt24MSB: // used for 20 bits as well + + case ASIOSTFloat64LSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture + case ASIOSTFloat64MSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture + + // these are used for 32 bit data buffer, with different alignment of the data inside + // 32 bit PCI bus systems can more easily used with these + + case ASIOSTInt32LSB16: // 32 bit data with 16 bit alignment + case ASIOSTInt32LSB18: // 32 bit data with 18 bit alignment + case ASIOSTInt32LSB20: // 32 bit data with 20 bit alignment + case ASIOSTInt32LSB24: // 32 bit data with 24 bit alignment + + + case ASIOSTInt32MSB16: // 32 bit data with 16 bit alignment + case ASIOSTInt32MSB18: // 32 bit data with 18 bit alignment + case ASIOSTInt32MSB20: // 32 bit data with 20 bit alignment + case ASIOSTInt32MSB24: // 32 bit data with 24 bit alignment + DBUG(("Not yet implemented : please report the problem\n")); + break; + } + break; + } + + case paUInt8: + { + /* Convert 16 bit data to 8 bit unsigned chars */ + + unsigned char *inBufPtr = (unsigned char *)inputBuffer; + + switch (nativeFormat) { + case ASIOSTInt16LSB: + Input_Int16_IntU8(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, flags,swap); + break; + case ASIOSTInt16MSB: + Input_Int16_IntU8(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, flags,!swap); + break; + case ASIOSTInt32LSB: + Input_Int32_IntU8(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset,flags,swap); + break; + case ASIOSTInt32MSB: + Input_Int32_IntU8(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, flags,!swap); + break; + case ASIOSTFloat32LSB: // IEEE 754 32 bit float, as found on Intel x86 architecture + Input_Float32_IntU8(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset,flags,swap); + break; + case ASIOSTFloat32MSB: // IEEE 754 32 bit float, as found on Intel x86 architecture + Input_Float32_IntU8(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset,flags,!swap); + break; + + case ASIOSTInt24LSB: // used for 20 bits as well + case ASIOSTInt24MSB: // used for 20 bits as well + + case ASIOSTFloat64LSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture + case ASIOSTFloat64MSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture + + // these are used for 32 bit data buffer, with different alignment of the data inside + // 32 bit PCI bus systems can more easily used with these + + case ASIOSTInt32LSB16: // 32 bit data with 16 bit alignment + case ASIOSTInt32LSB18: // 32 bit data with 18 bit alignment + case ASIOSTInt32LSB20: // 32 bit data with 20 bit alignment + case ASIOSTInt32LSB24: // 32 bit data with 24 bit alignment + + + case ASIOSTInt32MSB16: // 32 bit data with 16 bit alignment + case ASIOSTInt32MSB18: // 32 bit data with 18 bit alignment + case ASIOSTInt32MSB20: // 32 bit data with 20 bit alignment + case ASIOSTInt32MSB24: // 32 bit data with 24 bit alignment + DBUG(("Not yet implemented : please report the problem\n")); + break; + + } + break; + } + + default: + break; + } + } +} + + +//--------------------------------------------------------------------------------------- +static void Pa_ASIO_Convert_Inter_Output(ASIOBufferInfo* nativeBuffer, + void* outputBuffer, + long NumInputChannels, + long NumOuputChannels, + long framePerBuffer, + long hostFrameOffset, + long userFrameOffset, + ASIOSampleType nativeFormat, + PaSampleFormat paFormat, + PaStreamFlags flags, + long index) +{ + + if((NumOuputChannels > 0) && (nativeBuffer != NULL)) + { + /* Convert from PA format to native format */ + + switch(paFormat) + { + case paFloat32: + { + float *outBufPtr = (float *) outputBuffer; + + switch (nativeFormat) { + case ASIOSTInt16LSB: + Output_Float32_Int16(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset, userFrameOffset, flags, swap); + break; + case ASIOSTInt16MSB: + Output_Float32_Int16(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset, userFrameOffset, flags,!swap); + break; + case ASIOSTInt32LSB: + Output_Float32_Int32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset, userFrameOffset, flags,swap); + break; + case ASIOSTInt32MSB: + Output_Float32_Int32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, flags,!swap); + break; + case ASIOSTFloat32LSB: + Output_Float32_Float32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset,flags,swap); + break; + case ASIOSTFloat32MSB: + Output_Float32_Float32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, flags,!swap); + break; + + case ASIOSTInt24LSB: // used for 20 bits as well + case ASIOSTInt24MSB: // used for 20 bits as well + + case ASIOSTFloat64LSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture + case ASIOSTFloat64MSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture + + // these are used for 32 bit data buffer, with different alignment of the data inside + // 32 bit PCI bus systems can more easily used with these + + case ASIOSTInt32LSB16: // 32 bit data with 16 bit alignment + case ASIOSTInt32LSB18: // 32 bit data with 18 bit alignment + case ASIOSTInt32LSB20: // 32 bit data with 20 bit alignment + case ASIOSTInt32LSB24: // 32 bit data with 24 bit alignment + + + case ASIOSTInt32MSB16: // 32 bit data with 16 bit alignment + case ASIOSTInt32MSB18: // 32 bit data with 18 bit alignment + case ASIOSTInt32MSB20: // 32 bit data with 20 bit alignment + case ASIOSTInt32MSB24: // 32 bit data with 24 bit alignment + DBUG(("Not yet implemented : please report the problem\n")); + break; + } + break; + } + + case paInt32: + { + long *outBufPtr = (long *) outputBuffer; + + switch (nativeFormat) { + case ASIOSTInt16LSB: + Output_Int32_Int16(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, flags,swap); + break; + case ASIOSTInt16MSB: + Output_Int32_Int16(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, flags,!swap); + break; + case ASIOSTInt32LSB: + Output_Int32_Int32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, flags,swap); + break; + case ASIOSTInt32MSB: + Output_Int32_Int32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, flags,!swap); + break; + case ASIOSTFloat32LSB: + Output_Int32_Float32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, flags,swap); + break; + case ASIOSTFloat32MSB: + Output_Int32_Float32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, flags,!swap); + break; + + case ASIOSTInt24LSB: // used for 20 bits as well + case ASIOSTInt24MSB: // used for 20 bits as well + + case ASIOSTFloat64LSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture + case ASIOSTFloat64MSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture + + // these are used for 32 bit data buffer, with different alignment of the data inside + // 32 bit PCI bus systems can more easily used with these + + case ASIOSTInt32LSB16: // 32 bit data with 16 bit alignment + case ASIOSTInt32LSB18: // 32 bit data with 18 bit alignment + case ASIOSTInt32LSB20: // 32 bit data with 20 bit alignment + case ASIOSTInt32LSB24: // 32 bit data with 24 bit alignment + + + case ASIOSTInt32MSB16: // 32 bit data with 16 bit alignment + case ASIOSTInt32MSB18: // 32 bit data with 18 bit alignment + case ASIOSTInt32MSB20: // 32 bit data with 20 bit alignment + case ASIOSTInt32MSB24: // 32 bit data with 24 bit alignment + DBUG(("Not yet implemented : please report the problem\n")); + break; + } + break; + } + + case paInt16: + { + short *outBufPtr = (short *) outputBuffer; + + switch (nativeFormat) { + case ASIOSTInt16LSB: + Output_Int16_Int16(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, swap); + break; + case ASIOSTInt16MSB: + Output_Int16_Int16(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, !swap); + break; + case ASIOSTInt32LSB: + Output_Int16_Int32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, swap); + break; + case ASIOSTInt32MSB: + Output_Int16_Int32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, !swap); + break; + case ASIOSTFloat32LSB: + Output_Int16_Float32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, swap); + break; + case ASIOSTFloat32MSB: + Output_Int16_Float32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, !swap); + break; + + case ASIOSTInt24LSB: // used for 20 bits as well + case ASIOSTInt24MSB: // used for 20 bits as well + + case ASIOSTFloat64LSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture + case ASIOSTFloat64MSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture + + // these are used for 32 bit data buffer, with different alignment of the data inside + // 32 bit PCI bus systems can more easily used with these + + case ASIOSTInt32LSB16: // 32 bit data with 16 bit alignment + case ASIOSTInt32LSB18: // 32 bit data with 18 bit alignment + case ASIOSTInt32LSB20: // 32 bit data with 20 bit alignment + case ASIOSTInt32LSB24: // 32 bit data with 24 bit alignment + + + case ASIOSTInt32MSB16: // 32 bit data with 16 bit alignment + case ASIOSTInt32MSB18: // 32 bit data with 18 bit alignment + case ASIOSTInt32MSB20: // 32 bit data with 20 bit alignment + case ASIOSTInt32MSB24: // 32 bit data with 24 bit alignment + DBUG(("Not yet implemented : please report the problem\n")); + break; + + } + break; + } + + + case paInt8: + { + char *outBufPtr = (char *) outputBuffer; + + switch (nativeFormat) { + case ASIOSTInt16LSB: + Output_Int8_Int16(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, swap); + break; + case ASIOSTInt16MSB: + Output_Int8_Int16(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, !swap); + break; + case ASIOSTInt32LSB: + Output_Int8_Int32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, swap); + break; + case ASIOSTInt32MSB: + Output_Int8_Int32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, !swap); + break; + case ASIOSTFloat32LSB: + Output_Int8_Float32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, swap); + break; + case ASIOSTFloat32MSB: + Output_Int8_Float32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, !swap); + break; + + case ASIOSTInt24LSB: // used for 20 bits as well + case ASIOSTInt24MSB: // used for 20 bits as well + + case ASIOSTFloat64LSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture + case ASIOSTFloat64MSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture + + // these are used for 32 bit data buffer, with different alignment of the data inside + // 32 bit PCI bus systems can more easily used with these + + case ASIOSTInt32LSB16: // 32 bit data with 16 bit alignment + case ASIOSTInt32LSB18: // 32 bit data with 18 bit alignment + case ASIOSTInt32LSB20: // 32 bit data with 20 bit alignment + case ASIOSTInt32LSB24: // 32 bit data with 24 bit alignment + + + case ASIOSTInt32MSB16: // 32 bit data with 16 bit alignment + case ASIOSTInt32MSB18: // 32 bit data with 18 bit alignment + case ASIOSTInt32MSB20: // 32 bit data with 20 bit alignment + case ASIOSTInt32MSB24: // 32 bit data with 24 bit alignment + DBUG(("Not yet implemented : please report the problem\n")); + break; + } + break; + } + + case paUInt8: + { + unsigned char *outBufPtr = (unsigned char *) outputBuffer; + + switch (nativeFormat) { + case ASIOSTInt16LSB: + Output_IntU8_Int16(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, swap); + break; + case ASIOSTInt16MSB: + Output_IntU8_Int16(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, !swap); + break; + case ASIOSTInt32LSB: + Output_IntU8_Int32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, swap); + break; + case ASIOSTInt32MSB: + Output_IntU8_Int32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, !swap); + break; + case ASIOSTFloat32LSB: + Output_IntU8_Float32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, swap); + break; + case ASIOSTFloat32MSB: + Output_IntU8_Float32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, !swap); + break; + + case ASIOSTInt24LSB: // used for 20 bits as well + case ASIOSTInt24MSB: // used for 20 bits as well + + case ASIOSTFloat64LSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture + case ASIOSTFloat64MSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture + + // these are used for 32 bit data buffer, with different alignment of the data inside + // 32 bit PCI bus systems can more easily used with these + + case ASIOSTInt32LSB16: // 32 bit data with 16 bit alignment + case ASIOSTInt32LSB18: // 32 bit data with 18 bit alignment + case ASIOSTInt32LSB20: // 32 bit data with 20 bit alignment + case ASIOSTInt32LSB24: // 32 bit data with 24 bit alignment + + + case ASIOSTInt32MSB16: // 32 bit data with 16 bit alignment + case ASIOSTInt32MSB18: // 32 bit data with 18 bit alignment + case ASIOSTInt32MSB20: // 32 bit data with 20 bit alignment + case ASIOSTInt32MSB24: // 32 bit data with 24 bit alignment + DBUG(("Not yet implemented : please report the problem\n")); + break; + } + break; + } + + default: + break; + } + } + +} + + + +/* Load a ASIO driver corresponding to the required device */ +static PaError Pa_ASIO_loadDevice (long device) +{ + PaDeviceInfo * dev = &(sDevices[device].pad_Info); + + if (!Pa_ASIO_loadAsioDriver((char *) dev->name)) return paHostError; + if (ASIOInit(&asioDriverInfo.pahsc_driverInfo) != ASE_OK) return paHostError; + if (ASIOGetChannels(&asioDriverInfo.pahsc_NumInputChannels, &asioDriverInfo.pahsc_NumOutputChannels) != ASE_OK) return paHostError; + if (ASIOGetBufferSize(&asioDriverInfo.pahsc_minSize, &asioDriverInfo.pahsc_maxSize, &asioDriverInfo.pahsc_preferredSize, &asioDriverInfo.pahsc_granularity) != ASE_OK) return paHostError; + + if(ASIOOutputReady() == ASE_OK) + asioDriverInfo.pahsc_postOutput = true; + else + asioDriverInfo.pahsc_postOutput = false; + + return paNoError; +} + +//--------------------------------------------------- +static int GetHighestBitPosition (unsigned long n) +{ + int pos = -1; + while( n != 0 ) + { + pos++; + n = n >> 1; + } + return pos; +} + +//------------------------------------------------------------------------------------------ +static int GetFirstMultiple(long min, long val ){ return ((min + val - 1) / val) * val; } + +//------------------------------------------------------------------------------------------ +static int GetFirstPossibleDivisor(long max, long val ) +{ + for (int i = 2; i < 20; i++) {if (((val%i) == 0) && ((val/i) <= max)) return (val/i); } + return val; +} + +//------------------------------------------------------------------------ +static int IsPowerOfTwo( unsigned long n ) { return ((n & (n-1)) == 0); } + +/******************************************************************* +* Determine size of native ASIO audio buffer size +* Input parameters : FramesPerUserBuffer, NumUserBuffers +* Output values : FramesPerHostBuffer, OutputBufferOffset or InputtBufferOffset +*/ + +static PaError PaHost_CalcNumHostBuffers( internalPortAudioStream *past ) +{ + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + long requestedBufferSize; + long firstMultiple, firstDivisor; + + // Compute requestedBufferSize + if( past->past_NumUserBuffers < 1 ){ + requestedBufferSize = past->past_FramesPerUserBuffer; + }else{ + requestedBufferSize = past->past_NumUserBuffers * past->past_FramesPerUserBuffer; + } + + // Adjust FramesPerHostBuffer using requestedBufferSize, ASIO minSize and maxSize, + if (requestedBufferSize < asioDriverInfo.pahsc_minSize){ + + firstMultiple = GetFirstMultiple(asioDriverInfo.pahsc_minSize, requestedBufferSize); + + if (firstMultiple <= asioDriverInfo.pahsc_maxSize) + asioDriverInfo.past_FramesPerHostBuffer = firstMultiple; + else + asioDriverInfo.past_FramesPerHostBuffer = asioDriverInfo.pahsc_minSize; + + }else if (requestedBufferSize > asioDriverInfo.pahsc_maxSize){ + + firstDivisor = GetFirstPossibleDivisor(asioDriverInfo.pahsc_maxSize, requestedBufferSize); + + if ((firstDivisor >= asioDriverInfo.pahsc_minSize) && (firstDivisor <= asioDriverInfo.pahsc_maxSize)) + asioDriverInfo.past_FramesPerHostBuffer = firstDivisor; + else + asioDriverInfo.past_FramesPerHostBuffer = asioDriverInfo.pahsc_maxSize; + }else{ + asioDriverInfo.past_FramesPerHostBuffer = requestedBufferSize; + } + + // If ASIO buffer size needs to be a power of two + if( asioDriverInfo.pahsc_granularity < 0 ){ + // Needs to be a power of two. + + if( !IsPowerOfTwo( asioDriverInfo.past_FramesPerHostBuffer ) ) + { + int highestBit = GetHighestBitPosition(asioDriverInfo.past_FramesPerHostBuffer); + asioDriverInfo.past_FramesPerHostBuffer = 1 << (highestBit + 1); + } + } + + DBUG(("----------------------------------\n")); + DBUG(("PaHost_CalcNumHostBuffers : minSize = %ld \n",asioDriverInfo.pahsc_minSize)); + DBUG(("PaHost_CalcNumHostBuffers : preferredSize = %ld \n",asioDriverInfo.pahsc_preferredSize)); + DBUG(("PaHost_CalcNumHostBuffers : maxSize = %ld \n",asioDriverInfo.pahsc_maxSize)); + DBUG(("PaHost_CalcNumHostBuffers : granularity = %ld \n",asioDriverInfo.pahsc_granularity)); + DBUG(("PaHost_CalcNumHostBuffers : User buffer size = %d\n", asioDriverInfo.past->past_FramesPerUserBuffer )); + DBUG(("PaHost_CalcNumHostBuffers : ASIO buffer size = %d\n", asioDriverInfo.past_FramesPerHostBuffer )); + + return paNoError; +} + + +/***********************************************************************/ +int Pa_CountDevices() +{ + PaError err ; + + if( sNumDevices <= 0 ) + { + /* Force loading of ASIO drivers */ + err = Pa_ASIO_QueryDeviceInfo(sDevices); + if( err != paNoError ) goto error; + } + + return sNumDevices; + +error: + PaHost_Term(); + DBUG(("Pa_CountDevices: returns %d\n", err )); + return err; +} + +/***********************************************************************/ +PaError PaHost_Init( void ) +{ + /* Have we already initialized the device info? */ + PaError err = (PaError) Pa_CountDevices(); + return ( err < 0 ) ? err : paNoError; +} + +/***********************************************************************/ +PaError PaHost_Term( void ) +{ + int i; + PaDeviceInfo *dev; + double *rates; + PaError result = paNoError; + + if (sNumDevices > 0) { + + /* Free allocated sample rate arrays and names*/ + for( i=0; isampleRates; + if ((rates != NULL)) PaHost_FreeFastMemory(rates, MAX_NUMSAMPLINGRATES * sizeof(double)); + dev->sampleRates = NULL; + if(dev->name != NULL) PaHost_FreeFastMemory((void *) dev->name, 32); + dev->name = NULL; + } + + sNumDevices = 0; + + /* If the stream has been closed with PaHost_CloseStream, asioDriverInfo.past == null, otherwise close it now */ + if(asioDriverInfo.past != NULL) Pa_CloseStream(asioDriverInfo.past); + + /* remove the loaded ASIO driver */ + asioDrivers->removeCurrentDriver(); + } + + return result; +} + +/***********************************************************************/ +PaError PaHost_OpenStream( internalPortAudioStream *past ) +{ + PaError result = paNoError; + ASIOError err; + int32 device; + + /* Check if a stream already runs */ + if (asioDriverInfo.past != NULL) return paHostError; + + /* Check the device number */ + if ((past->past_InputDeviceID != paNoDevice) + &&(past->past_OutputDeviceID != paNoDevice) + &&(past->past_InputDeviceID != past->past_OutputDeviceID)) + { + return paInvalidDeviceId; + } + + /* Allocation */ + memset(&asioDriverInfo, 0, sizeof(PaHostSoundControl)); + past->past_DeviceData = (void*) &asioDriverInfo; + + /* Reentrancy counter initialisation */ + asioDriverInfo.reenterCount = -1; + asioDriverInfo.reenterError = 0; + + /* FIXME */ + asioDriverInfo.past = past; + + /* load the ASIO device */ + device = (past->past_InputDeviceID < 0) ? past->past_OutputDeviceID : past->past_InputDeviceID; + result = Pa_ASIO_loadDevice(device); + if (result != paNoError) goto error; + + /* Check ASIO parameters and input parameters */ + if ((past->past_NumInputChannels > asioDriverInfo.pahsc_NumInputChannels) + || (past->past_NumOutputChannels > asioDriverInfo.pahsc_NumOutputChannels)) { + result = paInvalidChannelCount; + goto error; + } + + /* Set sample rate */ + if (ASIOSetSampleRate(past->past_SampleRate) != ASE_OK) { + result = paInvalidSampleRate; + goto error; + } + + /* if OK calc buffer size */ + result = PaHost_CalcNumHostBuffers( past ); + if (result != paNoError) goto error; + + + /* + Allocating input and output buffers number for the real past_NumInputChannels and past_NumOutputChannels + optimize the data transfer. + */ + + asioDriverInfo.pahsc_NumInputChannels = past->past_NumInputChannels; + asioDriverInfo.pahsc_NumOutputChannels = past->past_NumOutputChannels; + + /* Allocate ASIO buffers and callback*/ + err = Pa_ASIO_CreateBuffers(&asioDriverInfo, + asioDriverInfo.pahsc_NumInputChannels, + asioDriverInfo.pahsc_NumOutputChannels, + asioDriverInfo.past_FramesPerHostBuffer); + + + /* + Some buggy drivers (like the Hoontech DSP24) give incorrect [min, preferred, max] values + They should work with the preferred size value, thus if Pa_ASIO_CreateBuffers fails with + the hostBufferSize computed in PaHost_CalcNumHostBuffers, we try again with the preferred size. + */ + + if (err != ASE_OK) { + + DBUG(("PaHost_OpenStream : Pa_ASIO_CreateBuffers failed with the requested framesPerBuffer = %ld \n", asioDriverInfo.past_FramesPerHostBuffer)); + + err = Pa_ASIO_CreateBuffers(&asioDriverInfo, + asioDriverInfo.pahsc_NumInputChannels, + asioDriverInfo.pahsc_NumOutputChannels, + asioDriverInfo.pahsc_preferredSize); + + if (err == ASE_OK) { + // Adjust FramesPerHostBuffer to take the preferredSize instead of the value computed in PaHost_CalcNumHostBuffers + asioDriverInfo.past_FramesPerHostBuffer = asioDriverInfo.pahsc_preferredSize; + DBUG(("PaHost_OpenStream : Adjust FramesPerHostBuffer to take the preferredSize instead of the value computed in PaHost_CalcNumHostBuffers\n")); + } else { + DBUG(("PaHost_OpenStream : Pa_ASIO_CreateBuffers failed with the preferred framesPerBuffer = %ld \n", asioDriverInfo.pahsc_preferredSize)); + } + } + + /* Compute buffer adapdation offset */ + PaHost_CalcBufferOffset(past); + + if (err == ASE_OK) + return paNoError; + else if (err == ASE_NoMemory) + result = paInsufficientMemory; + else if (err == ASE_InvalidParameter) + result = paInvalidChannelCount; + else if (err == ASE_InvalidMode) + result = paBufferTooBig; + else + result = paHostError; + +error: + ASIOExit(); + return result; + +} + +/***********************************************************************/ +PaError PaHost_CloseStream( internalPortAudioStream *past ) +{ + PaHostSoundControl *pahsc; + PaError result = paNoError; + + if( past == NULL ) return paBadStreamPtr; + pahsc = (PaHostSoundControl *) past->past_DeviceData; + if( pahsc == NULL ) return paNoError; + + #if PA_TRACE_START_STOP + AddTraceMessage( "PaHost_CloseStream: pahsc_HWaveOut ", (int) pahsc->pahsc_HWaveOut ); + #endif + + /* Free data and device for output. */ + past->past_DeviceData = NULL; + asioDriverInfo.past = NULL; + + /* Dispose */ + if(ASIODisposeBuffers() != ASE_OK) result = paHostError; + if(ASIOExit() != ASE_OK) result = paHostError; + + return result; +} + +/***********************************************************************/ +PaError PaHost_StartOutput( internalPortAudioStream *past ) +{ + /* Clear the index 0 host output buffer */ + Pa_ASIO_Clear_Output(asioDriverInfo.bufferInfos, + asioDriverInfo.pahsc_channelInfos[0].type, + asioDriverInfo.pahsc_NumInputChannels, + asioDriverInfo.pahsc_NumOutputChannels, + 0, + 0, + asioDriverInfo.past_FramesPerHostBuffer); + + /* Clear the index 1 host output buffer */ + Pa_ASIO_Clear_Output(asioDriverInfo.bufferInfos, + asioDriverInfo.pahsc_channelInfos[0].type, + asioDriverInfo.pahsc_NumInputChannels, + asioDriverInfo.pahsc_NumOutputChannels, + 1, + 0, + asioDriverInfo.past_FramesPerHostBuffer); + + Pa_ASIO_Clear_User_Buffers(); + + Pa_ASIO_Adaptor_Init(); + + return paNoError; +} + +/***********************************************************************/ +PaError PaHost_StopOutput( internalPortAudioStream *past, int abort ) +{ + /* Nothing to do ?? */ + return paNoError; +} + +/***********************************************************************/ +PaError PaHost_StartInput( internalPortAudioStream *past ) +{ + /* Nothing to do ?? */ + return paNoError; +} + +/***********************************************************************/ +PaError PaHost_StopInput( internalPortAudioStream *past, int abort ) +{ + /* Nothing to do */ + return paNoError; +} + +/***********************************************************************/ +PaError PaHost_StartEngine( internalPortAudioStream *past ) +{ + // TO DO : count of samples + past->past_IsActive = 1; + return (ASIOStart() == ASE_OK) ? paNoError : paHostError; +} + +/***********************************************************************/ +PaError PaHost_StopEngine( internalPortAudioStream *past, int abort ) +{ + // TO DO : count of samples + past->past_IsActive = 0; + return (ASIOStop() == ASE_OK) ? paNoError : paHostError; +} + +/***********************************************************************/ +// TO BE CHECKED +PaError PaHost_StreamActive( internalPortAudioStream *past ) +{ + PaHostSoundControl *pahsc; + if( past == NULL ) return paBadStreamPtr; + pahsc = (PaHostSoundControl *) past->past_DeviceData; + if( pahsc == NULL ) return paInternalError; + return (PaError) past->past_IsActive; +} + +/*************************************************************************/ +PaTimestamp Pa_StreamTime( PortAudioStream *stream ) +{ + PaHostSoundControl *pahsc; + internalPortAudioStream *past = (internalPortAudioStream *) stream; + if( past == NULL ) return paBadStreamPtr; + pahsc = (PaHostSoundControl *) past->past_DeviceData; + return pahsc->pahsc_NumFramesDone; +} + +/************************************************************************* + * Allocate memory that can be accessed in real-time. + * This may need to be held in physical memory so that it is not + * paged to virtual memory. + * This call MUST be balanced with a call to PaHost_FreeFastMemory(). + */ +void *PaHost_AllocateFastMemory( long numBytes ) +{ + #if MAC + void *addr = NewPtrClear( numBytes ); + if( (addr == NULL) || (MemError () != 0) ) return NULL; + + #if (CARBON_COMPATIBLE == 0) + if( HoldMemory( addr, numBytes ) != noErr ) + { + DisposePtr( (Ptr) addr ); + return NULL; + } + #endif + return addr; + #elif WINDOWS + void *addr = malloc( numBytes ); /* FIXME - do we need physical memory? */ + if( addr != NULL ) memset( addr, 0, numBytes ); + return addr; + #endif +} + +/************************************************************************* + * Free memory that could be accessed in real-time. + * This call MUST be balanced with a call to PaHost_AllocateFastMemory(). + */ +void PaHost_FreeFastMemory( void *addr, long numBytes ) +{ + #if MAC + if( addr == NULL ) return; + #if CARBON_COMPATIBLE + (void) numBytes; + #else + UnholdMemory( addr, numBytes ); + #endif + DisposePtr( (Ptr) addr ); + #elif WINDOWS + if( addr != NULL ) free( addr ); + #endif +} + + +/*************************************************************************/ +void Pa_Sleep( long msec ) +{ + #if MAC + int32 sleepTime, endTime; + /* Convert to ticks. Round up so we sleep a MINIMUM of msec time. */ + sleepTime = ((msec * 60) + 999) / 1000; + if( sleepTime < 1 ) sleepTime = 1; + endTime = TickCount() + sleepTime; + do{ + DBUGX(("Sleep for %d ticks.\n", sleepTime )); + WaitNextEvent( 0, NULL, sleepTime, NULL ); /* Use this just to sleep without getting events. */ + sleepTime = endTime - TickCount(); + } while( sleepTime > 0 ); + #elif WINDOWS + Sleep( msec ); + #endif +} + +/*************************************************************************/ +const PaDeviceInfo* Pa_GetDeviceInfo( PaDeviceID id ) +{ + if( (id < 0) || ( id >= Pa_CountDevices()) ) return NULL; + return &sDevices[id].pad_Info; +} + +/*************************************************************************/ +PaDeviceID Pa_GetDefaultInputDeviceID( void ) +{ + return (sNumDevices > 0) ? sDefaultInputDeviceID : paNoDevice; +} + +/*************************************************************************/ +PaDeviceID Pa_GetDefaultOutputDeviceID( void ) +{ + return (sNumDevices > 0) ? sDefaultOutputDeviceID : paNoDevice; +} + +/*************************************************************************/ +int Pa_GetMinNumBuffers( int framesPerUserBuffer, double sampleRate ) +{ + // TO BE IMPLEMENTED : using the ASIOGetLatency call?? + return 2; +} + +/*************************************************************************/ +int32 Pa_GetHostError( void ) +{ + int32 err = sPaHostError; + sPaHostError = 0; + return err; +} + + +#ifdef MAC + +/**************************************************************************/ +static void Pa_StartUsageCalculation( internalPortAudioStream *past ) +{ + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + UnsignedWide widePad; + if( pahsc == NULL ) return; +/* Query system timer for usage analysis and to prevent overuse of CPU. */ + Microseconds( &widePad ); + pahsc->pahsc_EntryCount = UnsignedWideToUInt64( widePad ); +} +/**************************************************************************/ +static void Pa_EndUsageCalculation( internalPortAudioStream *past ) +{ + UnsignedWide widePad; + UInt64 CurrentCount; + long InsideCount; + long TotalCount; + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + if( pahsc == NULL ) return; +/* Measure CPU utilization during this callback. Note that this calculation +** assumes that we had the processor the whole time. +*/ +#define LOWPASS_COEFFICIENT_0 (0.9) +#define LOWPASS_COEFFICIENT_1 (0.99999 - LOWPASS_COEFFICIENT_0) + Microseconds( &widePad ); + CurrentCount = UnsignedWideToUInt64( widePad ); + if( past->past_IfLastExitValid ) + { + InsideCount = (long) U64Subtract(CurrentCount, pahsc->pahsc_EntryCount); + TotalCount = (long) U64Subtract(CurrentCount, pahsc->pahsc_LastExitCount); +/* Low pass filter the result because sometimes we get called several times in a row. +* That can cause the TotalCount to be very low which can cause the usage to appear +* unnaturally high. So we must filter numerator and denominator separately!!! +*/ + past->past_AverageInsideCount = (( LOWPASS_COEFFICIENT_0 * past->past_AverageInsideCount) + + (LOWPASS_COEFFICIENT_1 * InsideCount)); + past->past_AverageTotalCount = (( LOWPASS_COEFFICIENT_0 * past->past_AverageTotalCount) + + (LOWPASS_COEFFICIENT_1 * TotalCount)); + past->past_Usage = past->past_AverageInsideCount / past->past_AverageTotalCount; + } + pahsc->pahsc_LastExitCount = CurrentCount; + past->past_IfLastExitValid = 1; +} + +#elif WINDOWS + +/********************************* BEGIN CPU UTILIZATION MEASUREMENT ****/ +static void Pa_StartUsageCalculation( internalPortAudioStream *past ) +{ + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + if( pahsc == NULL ) return; +/* Query system timer for usage analysis and to prevent overuse of CPU. */ + QueryPerformanceCounter( &pahsc->pahsc_EntryCount ); +} + +static void Pa_EndUsageCalculation( internalPortAudioStream *past ) +{ + LARGE_INTEGER CurrentCount = { 0, 0 }; + LONGLONG InsideCount; + LONGLONG TotalCount; +/* +** Measure CPU utilization during this callback. Note that this calculation +** assumes that we had the processor the whole time. +*/ +#define LOWPASS_COEFFICIENT_0 (0.9) +#define LOWPASS_COEFFICIENT_1 (0.99999 - LOWPASS_COEFFICIENT_0) + + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + if( pahsc == NULL ) return; + + if( QueryPerformanceCounter( &CurrentCount ) ) + { + if( past->past_IfLastExitValid ) + { + InsideCount = CurrentCount.QuadPart - pahsc->pahsc_EntryCount.QuadPart; + TotalCount = CurrentCount.QuadPart - pahsc->pahsc_LastExitCount.QuadPart; +/* Low pass filter the result because sometimes we get called several times in a row. + * That can cause the TotalCount to be very low which can cause the usage to appear + * unnaturally high. So we must filter numerator and denominator separately!!! + */ + past->past_AverageInsideCount = (( LOWPASS_COEFFICIENT_0 * past->past_AverageInsideCount) + + (LOWPASS_COEFFICIENT_1 * InsideCount)); + past->past_AverageTotalCount = (( LOWPASS_COEFFICIENT_0 * past->past_AverageTotalCount) + + (LOWPASS_COEFFICIENT_1 * TotalCount)); + past->past_Usage = past->past_AverageInsideCount / past->past_AverageTotalCount; + } + pahsc->pahsc_LastExitCount = CurrentCount; + past->past_IfLastExitValid = 1; + } +} + +#endif + + + + diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_asio/readme_asio_sdk_patch.txt b/mozilla/zap/zmk/portaudio_v18_1/pa_asio/readme_asio_sdk_patch.txt new file mode 100755 index 00000000000..848ecdfe7f8 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_asio/readme_asio_sdk_patch.txt @@ -0,0 +1,25 @@ +There is a bug in the ASIO SDK that causes the Macintosh version to often fail during initialization. Here is a patch that you can apply. + +In codefragments.cpp replace getFrontProcessDirectory function with +the following one (GetFrontProcess replaced by GetCurrentProcess) + + +bool CodeFragments::getFrontProcessDirectory(void *specs) +{ + FSSpec *fss = (FSSpec *)specs; + ProcessInfoRec pif; + ProcessSerialNumber psn; + + memset(&psn,0,(long)sizeof(ProcessSerialNumber)); + // if(GetFrontProcess(&psn) == noErr) // wrong !!! + if(GetCurrentProcess(&psn) == noErr) // correct !!! + { + pif.processName = 0; + pif.processAppSpec = fss; + pif.processInfoLength = sizeof(ProcessInfoRec); + if(GetProcessInformation(&psn, &pif) == noErr) + return true; + } + return false; +} + diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_beos/PlaybackNode.cc b/mozilla/zap/zmk/portaudio_v18_1/pa_beos/PlaybackNode.cc new file mode 100755 index 00000000000..1caee74e66e --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_beos/PlaybackNode.cc @@ -0,0 +1,538 @@ +/* + * $Id: PlaybackNode.cc,v 1.1.2.1 2005-08-16 20:04:01 alex%croczilla.com Exp $ + * PortAudio Portable Real-Time Audio Library + * Latest Version at: http://www.portaudio.com + * BeOS Media Kit Implementation by Joshua Haberman + * + * Copyright (c) 2001 Joshua Haberman + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * --- + * + * Significant portions of this file are based on sample code from Be. The + * Be Sample Code Licence follows: + * + * Copyright 1991-1999, Be Incorporated. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions, and the following disclaimer. + * + * 2. 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. + * + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. + */ + +#include + +#include +#include +#include + +#include "PlaybackNode.h" + +#define PRINT(x) { printf x; fflush(stdout); } + +#ifdef DEBUG +#define DBUG(x) PRINT(x) +#else +#define DBUG(x) +#endif + + +PaPlaybackNode::PaPlaybackNode(uint32 channels, float frame_rate, uint32 frames_per_buffer, + PortAudioCallback* callback, void *user_data) : + BMediaNode("PortAudio input node"), + BBufferProducer(B_MEDIA_RAW_AUDIO), + BMediaEventLooper(), + mAborted(false), + mRunning(false), + mBufferGroup(NULL), + mDownstreamLatency(0), + mStartTime(0), + mCallback(callback), + mUserData(user_data), + mFramesPerBuffer(frames_per_buffer) +{ + DBUG(("Constructor called.\n")); + + mPreferredFormat.type = B_MEDIA_RAW_AUDIO; + mPreferredFormat.u.raw_audio.channel_count = channels; + mPreferredFormat.u.raw_audio.frame_rate = frame_rate; + mPreferredFormat.u.raw_audio.byte_order = + (B_HOST_IS_BENDIAN) ? B_MEDIA_BIG_ENDIAN : B_MEDIA_LITTLE_ENDIAN; + mPreferredFormat.u.raw_audio.buffer_size = + media_raw_audio_format::wildcard.buffer_size; + + mOutput.destination = media_destination::null; + mOutput.format = mPreferredFormat; + + /* The amount of time it takes for this node to produce a buffer when + * asked. Essentially, it is how long the user's callback takes to run. + * We set this to be the length of the sound data each buffer of the + * requested size can hold. */ + //mInternalLatency = (bigtime_t)(1000000 * frames_per_buffer / frame_rate); + + /* ACK! it seems that the mixer (at least on my machine) demands that IT + * specify the buffer size, so for now I'll just make a generic guess here */ + mInternalLatency = 1000000 / 20; +} + + + +PaPlaybackNode::~PaPlaybackNode() +{ + DBUG(("Destructor called.\n")); + Quit(); /* Stop the BMediaEventLooper thread */ +} + + +/************************* + * + * Local methods + * + */ + +bool PaPlaybackNode::IsRunning() +{ + return mRunning; +} + + +PaTimestamp PaPlaybackNode::GetStreamTime() +{ + BTimeSource *timeSource = TimeSource(); + PaTimestamp time = (timeSource->Now() - mStartTime) * + mPreferredFormat.u.raw_audio.frame_rate / 1000000; + return time; +} + + +void PaPlaybackNode::SetSampleFormat(PaSampleFormat inFormat, + PaSampleFormat outFormat) +{ + uint32 beOutFormat; + + switch(outFormat) + { + case paFloat32: + beOutFormat = media_raw_audio_format::B_AUDIO_FLOAT; + mOutputSampleWidth = 4; + break; + + case paInt16: + beOutFormat = media_raw_audio_format::B_AUDIO_SHORT; + mOutputSampleWidth = 2; + break; + + case paInt32: + beOutFormat = media_raw_audio_format::B_AUDIO_INT; + mOutputSampleWidth = 4; + break; + + case paInt8: + beOutFormat = media_raw_audio_format::B_AUDIO_CHAR; + mOutputSampleWidth = 1; + break; + + case paUInt8: + beOutFormat = media_raw_audio_format::B_AUDIO_UCHAR; + mOutputSampleWidth = 1; + break; + + case paInt24: + case paPackedInt24: + case paCustomFormat: + DBUG(("Unsupported output format: %x\n", outFormat)); + break; + + default: + DBUG(("Unknown output format: %x\n", outFormat)); + } + + mPreferredFormat.u.raw_audio.format = beOutFormat; + mFramesPerBuffer * mPreferredFormat.u.raw_audio.channel_count * mOutputSampleWidth; +} + +BBuffer *PaPlaybackNode::FillNextBuffer(bigtime_t time) +{ + /* Get a buffer from the buffer group */ + BBuffer *buf = mBufferGroup->RequestBuffer( + mOutput.format.u.raw_audio.buffer_size, BufferDuration()); + unsigned long frames = mOutput.format.u.raw_audio.buffer_size / + mOutputSampleWidth / mOutput.format.u.raw_audio.channel_count; + bigtime_t start_time; + int ret; + + if( !buf ) + { + DBUG(("Unable to allocate a buffer\n")); + return NULL; + } + + start_time = mStartTime + + (bigtime_t)((double)mSamplesSent / + (double)mOutput.format.u.raw_audio.frame_rate / + (double)mOutput.format.u.raw_audio.channel_count * + 1000000.0); + + /* Now call the user callback to get the data */ + ret = mCallback(NULL, /* Input buffer */ + buf->Data(), /* Output buffer */ + frames, /* Frames per buffer */ + mSamplesSent / mOutput.format.u.raw_audio.channel_count, /* timestamp */ + mUserData); + + if( ret ) + mAborted = true; + + media_header *hdr = buf->Header(); + + hdr->type = B_MEDIA_RAW_AUDIO; + hdr->size_used = mOutput.format.u.raw_audio.buffer_size; + hdr->time_source = TimeSource()->ID(); + hdr->start_time = start_time; + + return buf; +} + + + + +/************************* + * + * BMediaNode methods + * + */ + +BMediaAddOn *PaPlaybackNode::AddOn( int32 * ) const +{ + DBUG(("AddOn() called.\n")); + return NULL; /* we don't provide service to outside applications */ +} + + +status_t PaPlaybackNode::HandleMessage( int32 message, const void *data, + size_t size ) +{ + DBUG(("HandleMessage() called.\n")); + return B_ERROR; /* we don't define any custom messages */ +} + + + + +/************************* + * + * BMediaEventLooper methods + * + */ + +void PaPlaybackNode::NodeRegistered() +{ + DBUG(("NodeRegistered() called.\n")); + + /* Start the BMediaEventLooper thread */ + SetPriority(B_REAL_TIME_PRIORITY); + Run(); + + /* set up as much information about our output as we can */ + mOutput.source.port = ControlPort(); + mOutput.source.id = 0; + mOutput.node = Node(); + ::strcpy(mOutput.name, "PortAudio Playback"); +} + + +void PaPlaybackNode::HandleEvent( const media_timed_event *event, + bigtime_t lateness, bool realTimeEvent ) +{ + // DBUG(("HandleEvent() called.\n")); + status_t err; + + switch(event->type) + { + case BTimedEventQueue::B_START: + DBUG((" Handling a B_START event\n")); + if( RunState() != B_STARTED ) + { + mStartTime = event->event_time + EventLatency(); + mSamplesSent = 0; + mAborted = false; + mRunning = true; + media_timed_event firstEvent( mStartTime, + BTimedEventQueue::B_HANDLE_BUFFER ); + EventQueue()->AddEvent( firstEvent ); + } + break; + + case BTimedEventQueue::B_STOP: + DBUG((" Handling a B_STOP event\n")); + mRunning = false; + EventQueue()->FlushEvents( 0, BTimedEventQueue::B_ALWAYS, true, + BTimedEventQueue::B_HANDLE_BUFFER ); + break; + + case BTimedEventQueue::B_HANDLE_BUFFER: + //DBUG((" Handling a B_HANDLE_BUFFER event\n")); + + /* make sure we're started and connected */ + if( RunState() != BMediaEventLooper::B_STARTED || + mOutput.destination == media_destination::null ) + break; + + BBuffer *buffer = FillNextBuffer(event->event_time); + + /* make sure we weren't aborted while this routine was running. + * this can happen in one of two ways: either the callback returned + * nonzero (in which case mAborted is set in FillNextBuffer() ) or + * the client called AbortStream */ + if( mAborted ) + { + if( buffer ) + buffer->Recycle(); + Stop(0, true); + break; + } + + if( buffer ) + { + err = SendBuffer(buffer, mOutput.destination); + if( err != B_OK ) + buffer->Recycle(); + } + + mSamplesSent += mOutput.format.u.raw_audio.buffer_size / mOutputSampleWidth; + + /* Now schedule the next buffer event, so we can send another + * buffer when this one runs out. We calculate when it should + * happen by calculating when the data we just sent will finish + * playing. + * + * NOTE, however, that the event will actually get generated + * earlier than we specify, to account for the latency it will + * take to produce the buffer. It uses the latency value we + * specified in SetEventLatency() to determine just how early + * to generate it. */ + + /* totalPerformanceTime includes the time represented by the buffer + * we just sent */ + bigtime_t totalPerformanceTime = (bigtime_t)((double)mSamplesSent / + (double)mOutput.format.u.raw_audio.channel_count / + (double)mOutput.format.u.raw_audio.frame_rate * 1000000.0); + + bigtime_t nextEventTime = mStartTime + totalPerformanceTime; + + media_timed_event nextBufferEvent(nextEventTime, + BTimedEventQueue::B_HANDLE_BUFFER); + EventQueue()->AddEvent(nextBufferEvent); + + break; + + } +} + + + + +/************************* + * + * BBufferProducer methods + * + */ + +status_t PaPlaybackNode::FormatSuggestionRequested( media_type type, + int32 /*quality*/, media_format* format ) +{ + /* the caller wants to know this node's preferred format and provides + * a suggestion, asking if we support it */ + DBUG(("FormatSuggestionRequested() called.\n")); + + if(!format) + return B_BAD_VALUE; + + *format = mPreferredFormat; + + /* we only support raw audio (a wildcard is okay too) */ + if ( type == B_MEDIA_UNKNOWN_TYPE || type == B_MEDIA_RAW_AUDIO ) + return B_OK; + else + return B_MEDIA_BAD_FORMAT; +} + + +status_t PaPlaybackNode::FormatProposal( const media_source& output, + media_format* format ) +{ + /* This is similar to FormatSuggestionRequested(), but it is actually part + * of the negotiation process. We're given the opportunity to specify any + * properties that are wildcards (ie. properties that the other node doesn't + * care one way or another about) */ + DBUG(("FormatProposal() called.\n")); + + /* Make sure this proposal really applies to our output */ + if( output != mOutput.source ) + return B_MEDIA_BAD_SOURCE; + + /* We return two things: whether we support the proposed format, and our own + * preferred format */ + *format = mPreferredFormat; + + if( format->type == B_MEDIA_UNKNOWN_TYPE || format->type == B_MEDIA_RAW_AUDIO ) + return B_OK; + else + return B_MEDIA_BAD_FORMAT; +} + + +status_t PaPlaybackNode::FormatChangeRequested( const media_source& source, + const media_destination& destination, media_format* io_format, int32* ) +{ + /* we refuse to change formats, supporting only 1 */ + DBUG(("FormatChangeRequested() called.\n")); + + return B_ERROR; +} + + +status_t PaPlaybackNode::GetNextOutput( int32* cookie, media_output* out_output ) +{ + /* this is where we allow other to enumerate our outputs -- the cookie is + * an integer we can use to keep track of where we are in enumeration. */ + DBUG(("GetNextOutput() called.\n")); + + if( *cookie == 0 ) + { + *out_output = mOutput; + *cookie = 1; + return B_OK; + } + + return B_BAD_INDEX; +} + + +status_t PaPlaybackNode::DisposeOutputCookie( int32 cookie ) +{ + DBUG(("DisposeOutputCookie() called.\n")); + return B_OK; +} + + +void PaPlaybackNode::LateNoticeReceived( const media_source& what, + bigtime_t how_much, bigtime_t performance_time ) +{ + /* This function is called as notification that a buffer we sent wasn't + * received by the time we stamped it with -- it got there late. Basically, + * it means we underestimated our own latency, so we should increase it */ + DBUG(("LateNoticeReceived() called.\n")); + + if( what != mOutput.source ) + return; + + if( RunMode() == B_INCREASE_LATENCY ) + { + mInternalLatency += how_much; + SetEventLatency( mDownstreamLatency + mInternalLatency ); + DBUG(("Increasing latency to %Ld\n", mDownstreamLatency + mInternalLatency)); + } + else + DBUG(("I don't know what to do with this notice!")); +} + + +void PaPlaybackNode::EnableOutput( const media_source& what, bool enabled, + int32* ) +{ + DBUG(("EnableOutput() called.\n")); + /* stub -- we don't support this yet */ +} + + +status_t PaPlaybackNode::PrepareToConnect( const media_source& what, + const media_destination& where, media_format* format, + media_source* out_source, char* out_name ) +{ + /* the final stage of format negotiations. here we _must_ make specific any + * remaining wildcards */ + DBUG(("PrepareToConnect() called.\n")); + + /* make sure this really refers to our source */ + if( what != mOutput.source ) + return B_MEDIA_BAD_SOURCE; + + /* make sure we're not already connected */ + if( mOutput.destination != media_destination::null ) + return B_MEDIA_ALREADY_CONNECTED; + + if( format->type != B_MEDIA_RAW_AUDIO ) + return B_MEDIA_BAD_FORMAT; + + if( format->u.raw_audio.format != mPreferredFormat.u.raw_audio.format ) + return B_MEDIA_BAD_FORMAT; + + if( format->u.raw_audio.buffer_size == + media_raw_audio_format::wildcard.buffer_size ) + { + DBUG(("We were left to decide buffer size: choosing 2048")); + format->u.raw_audio.buffer_size = 2048; + } + else + DBUG(("Using consumer specified buffer size of %lu.\n", + format->u.raw_audio.buffer_size)); + + /* Reserve the connection, return the information */ + mOutput.destination = where; + mOutput.format = *format; + *out_source = mOutput.source; + strncpy( out_name, mOutput.name, B_MEDIA_NAME_LENGTH ); + + return B_OK; +} + + +void PaPlaybackNode::Connect(status_t error, const media_source& source, + const media_destination& destination, const media_format& format, char* io_name) +{ + DBUG(("Connect() called.\n")); + diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_beos/PlaybackNode.h b/mozilla/zap/zmk/portaudio_v18_1/pa_beos/PlaybackNode.h new file mode 100755 index 00000000000..df285965e33 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_beos/PlaybackNode.h @@ -0,0 +1,108 @@ +/* + * $Id: PlaybackNode.h,v 1.1.2.1 2005-08-16 20:04:01 alex%croczilla.com Exp $ + * PortAudio Portable Real-Time Audio Library + * Latest Version at: http://www.portaudio.com + * BeOS Media Kit Implementation by Joshua Haberman + * + * Copyright (c) 2001 Joshua Haberman + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +#include +#include +#include + +#include "portaudio.h" + +class PaPlaybackNode : + public BBufferProducer, + public BMediaEventLooper +{ + +public: + PaPlaybackNode( uint32 channels, float frame_rate, uint32 frames_per_buffer, + PortAudioCallback *callback, void *user_data ); + ~PaPlaybackNode(); + + + /* Local methods ******************************************/ + + BBuffer *FillNextBuffer(bigtime_t time); + void SetSampleFormat(PaSampleFormat inFormat, PaSampleFormat outFormat); + bool IsRunning(); + PaTimestamp GetStreamTime(); + + /* BMediaNode methods *************************************/ + + BMediaAddOn* AddOn( int32 * ) const; + status_t HandleMessage( int32 message, const void *data, size_t size ); + + /* BMediaEventLooper methods ******************************/ + + void HandleEvent( const media_timed_event *event, bigtime_t lateness, + bool realTimeEvent ); + void NodeRegistered(); + + /* BBufferProducer methods ********************************/ + + status_t FormatSuggestionRequested( media_type type, int32 quality, + media_format* format ); + status_t FormatProposal( const media_source& output, media_format* format ); + status_t FormatChangeRequested( const media_source& source, + const media_destination& destination, media_format* io_format, int32* ); + + status_t GetNextOutput( int32* cookie, media_output* out_output ); + status_t DisposeOutputCookie( int32 cookie ); + + void LateNoticeReceived( const media_source& what, bigtime_t how_much, + bigtime_t performance_time ); + void EnableOutput( const media_source& what, bool enabled, int32* _deprecated_ ); + + status_t PrepareToConnect( const media_source& what, + const media_destination& where, media_format* format, + media_source* out_source, char* out_name ); + void Connect(status_t error, const media_source& source, + const media_destination& destination, const media_format& format, + char* io_name); + void Disconnect(const media_source& what, const media_destination& where); + + status_t SetBufferGroup(const media_source& for_source, BBufferGroup* newGroup); + + bool mAborted; + +private: + media_output mOutput; + media_format mPreferredFormat; + uint32 mOutputSampleWidth, mFramesPerBuffer; + BBufferGroup *mBufferGroup; + bigtime_t mDownstreamLatency, mInternalLatency, mStartTime; + uint64 mSamplesSent; + PortAudioCallback *mCallback; + void *mUserData; + bool mRunning; + +}; + diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_beos/pa_beos_mk.cc b/mozilla/zap/zmk/portaudio_v18_1/pa_beos/pa_beos_mk.cc new file mode 100755 index 00000000000..f52c7813927 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_beos/pa_beos_mk.cc @@ -0,0 +1,441 @@ +/* + * $Id: pa_beos_mk.cc,v 1.1.2.1 2005-08-16 20:04:01 alex%croczilla.com Exp $ + * PortAudio Portable Real-Time Audio Library + * Latest Version at: http://www.portaudio.com + * BeOS Media Kit Implementation by Joshua Haberman + * + * Copyright (c) 2001 Joshua Haberman + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +#include +#include +#include +#include +#include + +#include +#include + +#include "portaudio.h" +#include "pa_host.h" + +#include "PlaybackNode.h" + +#define PRINT(x) { printf x; fflush(stdout); } + +#ifdef DEBUG +#define DBUG(x) PRINT(x) +#else +#define DBUG(x) +#endif + +typedef struct PaHostSoundControl +{ + /* These members are common to all modes of operation */ + media_node pahsc_TimeSource; /* the sound card's DAC. */ + media_format pahsc_Format; + + /* These methods are specific to playing mode */ + media_node pahsc_OutputNode; /* output to the mixer */ + media_node pahsc_InputNode; /* reads data from user callback -- PA specific */ + + media_input pahsc_MixerInput; /* input jack on the soundcard's mixer. */ + media_output pahsc_PaOutput; /* output jack from the PA node */ + + PaPlaybackNode *pahsc_InputNodeInstance; + +} +PaHostSoundControl; + +/*************************************************************************/ +PaDeviceID Pa_GetDefaultOutputDeviceID( void ) +{ + /* stub */ + return 0; +} + +/*************************************************************************/ +PaDeviceID Pa_GetDefaultInputDeviceID( void ) +{ + /* stub */ + return 0; +} + +/*************************************************************************/ +const PaDeviceInfo* Pa_GetDeviceInfo( PaDeviceID id ) +{ + /* stub */ + return NULL; +} + +/*************************************************************************/ +int Pa_CountDevices() +{ + /* stub */ + return 1; +} + +/*************************************************************************/ +PaError PaHost_Init( void ) +{ + /* we have to create this in order to use BMediaRoster. I hope it doesn't + * cause problems */ + be_app = new BApplication("application/x-vnd.portaudio-app"); + + return paNoError; +} + +PaError PaHost_Term( void ) +{ + delete be_app; + return paNoError; +} + +/*************************************************************************/ +PaError PaHost_StreamActive( internalPortAudioStream *past ) +{ + PaHostSoundControl *pahsc = (PaHostSoundControl *)past->past_DeviceData; + DBUG(("IsRunning returning: %s\n", + pahsc->pahsc_InputNodeInstance->IsRunning() ? "true" : "false")); + + return (PaError)pahsc->pahsc_InputNodeInstance->IsRunning(); +} + +PaError PaHost_StartOutput( internalPortAudioStream *past ) +{ + return paNoError; +} + +/*************************************************************************/ +PaError PaHost_StartInput( internalPortAudioStream *past ) +{ + return paNoError; +} + +/*************************************************************************/ +PaError PaHost_StopInput( internalPortAudioStream *past, int abort ) +{ + return paNoError; +} + +/*************************************************************************/ +PaError PaHost_StopOutput( internalPortAudioStream *past, int abort ) +{ + return paNoError; +} + + +/*************************************************************************/ +PaError PaHost_StartEngine( internalPortAudioStream *past ) +{ + bigtime_t very_soon, start_latency; + status_t err; + BMediaRoster *roster = BMediaRoster::Roster(&err); + PaHostSoundControl *pahsc = (PaHostSoundControl *)past->past_DeviceData; + + /* for some reason, err indicates an error (though nothing it wrong) + * when the DBUG macro in pa_lib.c is enabled. It's reproducably + * linked. Weird. */ + if( !roster /* || err != B_OK */ ) + { + DBUG(("No media server! err=%d, roster=%x\n", err, roster)); + return paHostError; + } + + /* tell the node when to start -- since there aren't any other nodes + * starting that we have to wait for, just tell it to start now + */ + + BTimeSource *timeSource = roster->MakeTimeSourceFor(pahsc->pahsc_TimeSource); + very_soon = timeSource->PerformanceTimeFor( BTimeSource::RealTime() ); + timeSource->Release(); + + /* Add the latency of starting the network of nodes */ + err = roster->GetStartLatencyFor( pahsc->pahsc_TimeSource, &start_latency ); + very_soon += start_latency; + + err = roster->StartNode( pahsc->pahsc_InputNode, very_soon ); + /* No need to start the mixer -- it's always running */ + + return paNoError; +} + + +/*************************************************************************/ +PaError PaHost_StopEngine( internalPortAudioStream *past, int abort ) +{ + PaHostSoundControl *pahsc = (PaHostSoundControl *)past->past_DeviceData; + BMediaRoster *roster = BMediaRoster::Roster(); + + if( !roster ) + { + DBUG(("No media roster!\n")); + return paHostError; + } + + if( !pahsc ) + return paHostError; + + /* this crashes, and I don't know why yet */ + // if( abort ) + // pahsc->pahsc_InputNodeInstance->mAborted = true; + + roster->StopNode(pahsc->pahsc_InputNode, 0, /* immediate = */ true); + + return paNoError; +} + + +/*************************************************************************/ +PaError PaHost_OpenStream( internalPortAudioStream *past ) +{ + status_t err; + BMediaRoster *roster = BMediaRoster::Roster(&err); + PaHostSoundControl *pahsc; + + /* Allocate and initialize host data. */ + pahsc = (PaHostSoundControl *) PaHost_AllocateFastMemory(sizeof(PaHostSoundControl)); + if( pahsc == NULL ) + { + goto error; + } + memset( pahsc, 0, sizeof(PaHostSoundControl) ); + past->past_DeviceData = (void *) pahsc; + + if( !roster /* || err != B_OK */ ) + { + /* no media server! */ + DBUG(("No media server.\n")); + goto error; + } + + if ( past->past_NumInputChannels > 0 && past->past_NumOutputChannels > 0 ) + { + /* filter -- not implemented yet */ + goto error; + } + else if ( past->past_NumInputChannels > 0 ) + { + /* recorder -- not implemented yet */ + goto error; + } + else + { + /* player ****************************************************************/ + + status_t err; + int32 num; + + /* First we need to create the three components (like components in a stereo + * system). The mixer component is our interface to the sound card, data + * we write there will get played. The BePA_InputNode component is the node + * which represents communication with the PA client (it is what calls the + * client's callbacks). The time source component is the sound card's DAC, + * which allows us to slave the other components to it instead of the system + * clock. */ + err = roster->GetAudioMixer( &pahsc->pahsc_OutputNode ); + if( err != B_OK ) + { + DBUG(("Couldn't get default mixer.\n")); + goto error; + } + + err = roster->GetTimeSource( &pahsc->pahsc_TimeSource ); + if( err != B_OK ) + { + DBUG(("Couldn't get time source.\n")); + goto error; + } + + pahsc->pahsc_InputNodeInstance = new PaPlaybackNode(2, 44100, + past->past_FramesPerUserBuffer, past->past_Callback, past->past_UserData ); + pahsc->pahsc_InputNodeInstance->SetSampleFormat(0, + past->past_OutputSampleFormat); + err = roster->RegisterNode( pahsc->pahsc_InputNodeInstance ); + if( err != B_OK ) + { + DBUG(("Unable to register node.\n")); + goto error; + } + + roster->GetNodeFor( pahsc->pahsc_InputNodeInstance->Node().node, + &pahsc->pahsc_InputNode ); + if( err != B_OK ) + { + DBUG(("Unable to get input node.\n")); + goto error; + } + + /* Now we have three components (nodes) sitting next to each other. The + * next step is to look at them and find their inputs and outputs so we can + * wire them together. */ + err = roster->GetFreeInputsFor( pahsc->pahsc_OutputNode, + &pahsc->pahsc_MixerInput, 1, &num, B_MEDIA_RAW_AUDIO ); + if( err != B_OK || num < 1 ) + { + DBUG(("Couldn't get the mixer input.\n")); + goto error; + } + + err = roster->GetFreeOutputsFor( pahsc->pahsc_InputNode, + &pahsc->pahsc_PaOutput, 1, &num, B_MEDIA_RAW_AUDIO ); + if( err != B_OK || num < 1 ) + { + DBUG(("Couldn't get PortAudio output.\n")); + goto error; + } + + + /* We've found the input and output -- the final step is to run a wire + * between them so they are connected. */ + + /* try to make the mixer input adapt to what PA sends it */ + pahsc->pahsc_Format = pahsc->pahsc_PaOutput.format; + roster->Connect( pahsc->pahsc_PaOutput.source, + pahsc->pahsc_MixerInput.destination, &pahsc->pahsc_Format, + &pahsc->pahsc_PaOutput, &pahsc->pahsc_MixerInput ); + + + /* Actually, there's one final step -- tell them all to sync to the + * sound card's DAC */ + roster->SetTimeSourceFor( pahsc->pahsc_InputNode.node, + pahsc->pahsc_TimeSource.node ); + roster->SetTimeSourceFor( pahsc->pahsc_OutputNode.node, + pahsc->pahsc_TimeSource.node ); + + } + + return paNoError; + +error: + PaHost_CloseStream( past ); + return paHostError; +} + +/*************************************************************************/ +PaError PaHost_CloseStream( internalPortAudioStream *past ) +{ + PaHostSoundControl *pahsc = (PaHostSoundControl *)past->past_DeviceData; + status_t err; + BMediaRoster *roster = BMediaRoster::Roster(&err); + + if( !roster ) + { + DBUG(("Couldn't get media roster\n")); + return paHostError; + } + + if( !pahsc ) + return paHostError; + + /* Disconnect all the connections we made when opening the stream */ + + roster->Disconnect(pahsc->pahsc_InputNode.node, pahsc->pahsc_PaOutput.source, + pahsc->pahsc_OutputNode.node, pahsc->pahsc_MixerInput.destination); + + DBUG(("Calling ReleaseNode()")); + roster->ReleaseNode(pahsc->pahsc_InputNode); + + /* deleting the node shouldn't be necessary -- it is reference counted, and will + * delete itself when its references drop to zero. the call to ReleaseNode() + * above should decrease its reference count */ + pahsc->pahsc_InputNodeInstance = NULL; + + return paNoError; +} + +/*************************************************************************/ +PaTimestamp Pa_StreamTime( PortAudioStream *stream ) +{ + internalPortAudioStream *past = (internalPortAudioStream *) stream; + PaHostSoundControl *pahsc = (PaHostSoundControl *)past->past_DeviceData; + + return pahsc->pahsc_InputNodeInstance->GetStreamTime(); +} + +/*************************************************************************/ +void Pa_Sleep( long msec ) +{ + /* snooze() takes microseconds */ + snooze( msec * 1000 ); +} + +/************************************************************************* + * Allocate memory that can be accessed in real-time. + * This may need to be held in physical memory so that it is not + * paged to virtual memory. + * This call MUST be balanced with a call to PaHost_FreeFastMemory(). + * Memory will be set to zero. + */ +void *PaHost_AllocateFastMemory( long numBytes ) +{ + /* BeOS supports non-pagable memory through pools -- a pool is an area + * of physical memory that is locked. It would be best to pre-allocate + * that pool and then hand out memory from it, but we don't know in + * advance how much we'll need. So for now, we'll allocate a pool + * for every request we get, storing a pointer to the pool at the + * beginning of the allocated memory */ + rtm_pool *pool; + void *addr; + long size = numBytes + sizeof(rtm_pool *); + static int counter = 0; + char pool_name[100]; + + /* Every pool needs a unique name. */ + sprintf(pool_name, "PaPoolNumber%d", counter++); + + if( rtm_create_pool( &pool, size, pool_name ) != B_OK ) + return 0; + + addr = rtm_alloc( pool, size ); + if( addr == NULL ) + return 0; + + memset( addr, 0, numBytes ); + *((rtm_pool **)addr) = pool; // store the pointer to the pool + addr = (rtm_pool **)addr + 1; // and return the next location in memory + + return addr; +} + +/************************************************************************* + * Free memory that could be accessed in real-time. + * This call MUST be balanced with a call to PaHost_AllocateFastMemory(). + */ +void PaHost_FreeFastMemory( void *addr, long numBytes ) +{ + rtm_pool *pool; + + if( addr == NULL ) + return; + + addr = (rtm_pool **)addr - 1; + pool = *((rtm_pool **)addr); + + rtm_free( addr ); + rtm_delete_pool( pool ); +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_common/pa_convert.c b/mozilla/zap/zmk/portaudio_v18_1/pa_common/pa_convert.c new file mode 100755 index 00000000000..871c13665e8 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_common/pa_convert.c @@ -0,0 +1,470 @@ +/* + * pa_conversions.c + * portaudio + * + * Created by Phil Burk on Mon Mar 18 2002. + * + */ +#include + +#include "portaudio.h" +#include "pa_host.h" + +#define CLIP( val, min, max ) { val = ((val) < (min)) ? min : (((val) < (max)) ? (max) : (val)); } + +/*************************************************************************/ +static void PaConvert_Float32_Int16( + float *sourceBuffer, int sourceStride, + short *targetBuffer, int targetStride, + int numSamples ) +{ + int i; + for( i=0; ipast_NativeInputSampleFormat = nativeInputSampleFormat; + past->past_InputConversionSourceStride = 1; + past->past_InputConversionTargetStride = 1; + + if( nativeInputSampleFormat != past->past_InputSampleFormat ) + { + int ifDither = (past->past_Flags & paDitherOff) == 0; + past->past_InputConversionProc = PaConvert_SelectProc( nativeInputSampleFormat, + past->past_InputSampleFormat, 0, ifDither ); + if( past->past_InputConversionProc == NULL ) return paSampleFormatNotSupported; + } + else + { + past->past_InputConversionProc = NULL; /* no conversion necessary */ + } + + return paNoError; +} + +/*************************************************************************/ +PaError PaConvert_SetupOutput( internalPortAudioStream *past, + PaSampleFormat nativeOutputSampleFormat ) +{ + + past->past_NativeOutputSampleFormat = nativeOutputSampleFormat; + past->past_OutputConversionSourceStride = 1; + past->past_OutputConversionTargetStride = 1; + + if( nativeOutputSampleFormat != past->past_OutputSampleFormat ) + { + int ifDither = (past->past_Flags & paDitherOff) == 0; + int ifClip = (past->past_Flags & paClipOff) == 0; + + past->past_OutputConversionProc = PaConvert_SelectProc( past->past_OutputSampleFormat, + nativeOutputSampleFormat, ifClip, ifDither ); + if( past->past_OutputConversionProc == NULL ) return paSampleFormatNotSupported; + } + else + { + past->past_OutputConversionProc = NULL; /* no conversion necessary */ + } + + return paNoError; +} + +/************************************************************************* +** Called by host code. +** Convert input from native format to user format, +** call user code, +** then convert output to native format. +** Returns result from user callback. +*/ +long PaConvert_Process( internalPortAudioStream *past, + void *nativeInputBuffer, + void *nativeOutputBuffer ) +{ + int userResult; + void *inputBuffer = NULL; + void *outputBuffer = NULL; + + /* Get native input data. */ + if( (past->past_NumInputChannels > 0) && (nativeInputBuffer != NULL) ) + { + if( past->past_InputSampleFormat == past->past_NativeInputSampleFormat ) + { + /* Already in native format so just read directly from native buffer. */ + inputBuffer = nativeInputBuffer; + } + else + { + inputBuffer = past->past_InputBuffer; + /* Convert input data to user format. */ + (*past->past_InputConversionProc)(nativeInputBuffer, past->past_InputConversionSourceStride, + inputBuffer, past->past_InputConversionTargetStride, + past->past_FramesPerUserBuffer * past->past_NumInputChannels ); + } + } + + /* Are we doing output? */ + if( (past->past_NumOutputChannels > 0) && (nativeOutputBuffer != NULL) ) + { + outputBuffer = (past->past_OutputConversionProc == NULL) ? + nativeOutputBuffer : past->past_OutputBuffer; + } + /* + AddTraceMessage("Pa_CallConvertInt16: inputBuffer = ", (int) inputBuffer ); + AddTraceMessage("Pa_CallConvertInt16: outputBuffer = ", (int) outputBuffer ); + */ + /* Call user callback routine. */ + userResult = past->past_Callback( + inputBuffer, + outputBuffer, + past->past_FramesPerUserBuffer, + past->past_FrameCount, + past->past_UserData ); + + /* Advance frame counter for timestamp. */ + past->past_FrameCount += past->past_FramesPerUserBuffer; // FIXME - should this be in here? + + /* Convert to native format if necessary. */ + if( (past->past_OutputConversionProc != NULL ) && (outputBuffer != NULL) ) + { + (*past->past_OutputConversionProc)( outputBuffer, past->past_OutputConversionSourceStride, + nativeOutputBuffer, past->past_OutputConversionTargetStride, + past->past_FramesPerUserBuffer * past->past_NumOutputChannels ); + } + + return userResult; +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_common/pa_host.h b/mozilla/zap/zmk/portaudio_v18_1/pa_common/pa_host.h new file mode 100755 index 00000000000..a1db4ccdca0 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_common/pa_host.h @@ -0,0 +1,189 @@ +#ifndef PA_HOST_H +#define PA_HOST_H + +/* + * $Id: pa_host.h,v 1.1.2.1 2005-08-16 20:04:01 alex%croczilla.com Exp $ + * Host dependant internal API for PortAudio + * + * Author: Phil Burk + * + * PortAudio Portable Real-Time Audio Library + * Latest Version at: http://www.softsynth.com/portaudio/ + * DirectSound and Macintosh Implementation + * Copyright (c) 1999-2000 Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +#include "portaudio.h" + +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#ifndef SUPPORT_AUDIO_CAPTURE +#define SUPPORT_AUDIO_CAPTURE (1) +#endif + +#ifndef int32 + typedef long int32; +#endif +#ifndef uint32 + typedef unsigned long uint32; +#endif +#ifndef int16 + typedef short int16; +#endif +#ifndef uint16 + typedef unsigned short uint16; +#endif + +/* Used to convert between various sample formats. */ +typedef void (PortAudioConverter)( + void *inputBuffer, int inputStride, + void *outputBuffer, int outputStride, + int numSamples ); + +#define PA_MAGIC (0x18273645) + +/************************************************************************************/ +/****************** Structures ******************************************************/ +/************************************************************************************/ + +typedef struct internalPortAudioStream +{ + uint32 past_Magic; /* ID for struct to catch bugs. */ + + /* Begin user specified information. */ + uint32 past_FramesPerUserBuffer; + uint32 past_NumUserBuffers; + double past_SampleRate; /* Closest supported sample rate. */ + int past_NumInputChannels; + int past_NumOutputChannels; + PaDeviceID past_InputDeviceID; + PaDeviceID past_OutputDeviceID; + PaSampleFormat past_InputSampleFormat; + PaSampleFormat past_OutputSampleFormat; + PortAudioCallback *past_Callback; + void *past_UserData; + uint32 past_Flags; + /* End user specified information. */ + + void *past_DeviceData; + PaSampleFormat past_NativeOutputSampleFormat; + PaSampleFormat past_NativeInputSampleFormat; + + /* Flags for communicating between foreground and background. */ + volatile int past_IsActive; /* Background is still playing. */ + volatile int past_StopSoon; /* Background should keep playing when buffers empty. */ + volatile int past_StopNow; /* Background should stop playing now. */ + /* These buffers are used when the native format does not match the user format. */ + void *past_InputBuffer; + uint32 past_InputBufferSize; /* Size in bytes of the input buffer. */ + void *past_OutputBuffer; + uint32 past_OutputBufferSize; + /* Measurements */ + uint32 past_NumCallbacks; + PaTimestamp past_FrameCount; /* Frames output to buffer. */ + /* For measuring CPU utilization. */ + double past_AverageInsideCount; + double past_AverageTotalCount; + double past_Usage; + int past_IfLastExitValid; + /* Format Conversion */ + /* These are setup by PaConversion_Setup() */ + PortAudioConverter *past_InputConversionProc; + int past_InputConversionSourceStride; + int past_InputConversionTargetStride; + PortAudioConverter *past_OutputConversionProc; + int past_OutputConversionSourceStride; + int past_OutputConversionTargetStride; +} +internalPortAudioStream; + +/************************************************************************************/ +/******** These functions must be provided by a platform implementation. ************/ +/************************************************************************************/ + +PaError PaHost_Init( void ); +PaError PaHost_Term( void ); + +PaError PaHost_OpenStream( internalPortAudioStream *past ); +PaError PaHost_CloseStream( internalPortAudioStream *past ); + +PaError PaHost_StartOutput( internalPortAudioStream *past ); +PaError PaHost_StopOutput( internalPortAudioStream *past, int abort ); +PaError PaHost_StartInput( internalPortAudioStream *past ); +PaError PaHost_StopInput( internalPortAudioStream *past, int abort ); +PaError PaHost_StartEngine( internalPortAudioStream *past ); +PaError PaHost_StopEngine( internalPortAudioStream *past, int abort ); +PaError PaHost_StreamActive( internalPortAudioStream *past ); + +void *PaHost_AllocateFastMemory( long numBytes ); +void PaHost_FreeFastMemory( void *addr, long numBytes ); + +/* This only called if PA_VALIDATE_RATE IS CALLED. */ +PaError PaHost_ValidateSampleRate( PaDeviceID id, double requestedFrameRate, + double *closestFrameRatePtr ); + +/**********************************************************************/ +/************ Common Utility Routines provided by PA ******************/ +/**********************************************************************/ + +/* PaHost_IsInitialized() returns non-zero if PA is initialized, 0 otherwise */ +int PaHost_IsInitialized( void ); + +internalPortAudioStream* PaHost_GetStreamRepresentation( PortAudioStream *stream ); + +int PaHost_FindClosestTableEntry( double allowableError, const double *rateTable, + int numRates, double frameRate ); + +long Pa_CallConvertInt16( internalPortAudioStream *past, + short *nativeInputBuffer, + short *nativeOutputBuffer ); + +/* Calculate 2 LSB dither signal with a triangular distribution. +** Ranged properly for adding to a 32 bit 1.31 fixed point value prior to >>15. +** Range of output is +/- 65535 +** Multiply by PA_DITHER_SCALE to get a float between -2.0 and 2.0. */ +#define PA_DITHER_BITS (15) +#define PA_DITHER_SCALE (1.0f / ((1< +#include +#include +#include + +/* PLB20010422 - "memory.h" doesn't work on CodeWarrior for PC. Thanks Mike Berry for the mod. */ +#ifdef _WIN32 +#ifndef __MWERKS__ +#include +#endif /* __MWERKS__ */ +#else /* !_WIN32 */ +#include +#endif /* _WIN32 */ + +#include "portaudio.h" +#include "pa_host.h" +#include "pa_trace.h" + +/* The reason we might NOT want to validate the rate before opening the stream + * is because many DirectSound drivers lie about the rates they actually support. + */ +#define PA_VALIDATE_RATE (0) /* If true validate sample rate against driver info. */ + +/* +O- maybe not allocate past_InputBuffer and past_OutputBuffer if not needed for conversion +*/ + +#ifndef FALSE + #define FALSE (0) + #define TRUE (!FALSE) +#endif + +#define PRINT(x) { printf x; fflush(stdout); } +#define ERR_RPT(x) PRINT(x) +#define DBUG(x) /* PRINT(x) */ +#define DBUGX(x) /* PRINT(x) */ + +static int gInitCount = 0; /* Count number of times Pa_Initialize() called to allow nesting and overlapping. */ + +static PaError Pa_KillStream( PortAudioStream *stream, int abort ); + +/***********************************************************************/ +int PaHost_FindClosestTableEntry( double allowableError, const double *rateTable, int numRates, double frameRate ) +{ + double err, minErr = allowableError; + int i, bestFit = -1; + + for( i=0; inumSampleRates == -1 ) + { + /* Is it out of range? */ + if( (requestedFrameRate < pdi->sampleRates[0]) || + (requestedFrameRate > pdi->sampleRates[1]) ) + { + return paInvalidSampleRate; + } + + *closestFrameRatePtr = requestedFrameRate; + } + else + { + bestRateIndex = PaHost_FindClosestTableEntry( 1.0, pdi->sampleRates, pdi->numSampleRates, requestedFrameRate ); + if( bestRateIndex < 0 ) return paInvalidSampleRate; + *closestFrameRatePtr = pdi->sampleRates[bestRateIndex]; + } + return paNoError; +} + +/*************************************************************************/ +PaError Pa_OpenStream( + PortAudioStream** streamPtrPtr, + PaDeviceID inputDeviceID, + int numInputChannels, + PaSampleFormat inputSampleFormat, + void *inputDriverInfo, + PaDeviceID outputDeviceID, + int numOutputChannels, + PaSampleFormat outputSampleFormat, + void *outputDriverInfo, + double sampleRate, + unsigned long framesPerBuffer, + unsigned long numberOfBuffers, + unsigned long streamFlags, + PortAudioCallback *callback, + void *userData ) +{ + internalPortAudioStream *past = NULL; + PaError result = paNoError; + int bitsPerInputSample; + int bitsPerOutputSample; + /* Print passed parameters. */ + DBUG(("Pa_OpenStream( %p, %d, %d, %d, %p, /* input */ \n", + streamPtrPtr, inputDeviceID, numInputChannels, + inputSampleFormat, inputDriverInfo )); + DBUG((" %d, %d, %d, %p, /* output */\n", + outputDeviceID, numOutputChannels, + outputSampleFormat, outputDriverInfo )); + DBUG((" %g, %d, %d, 0x%x, , %p )\n", + sampleRate, framesPerBuffer, numberOfBuffers, + streamFlags, userData )); + + /* Check for parameter errors. */ + if( (streamFlags & ~(paClipOff | paDitherOff)) != 0 ) return paInvalidFlag; + if( streamPtrPtr == NULL ) return paBadStreamPtr; + if( inputDriverInfo != NULL ) return paHostError; /* REVIEW */ + if( outputDriverInfo != NULL ) return paHostError; /* REVIEW */ + if( (inputDeviceID < 0) && ( outputDeviceID < 0) ) return paInvalidDeviceId; + if( (outputDeviceID >= Pa_CountDevices()) || (inputDeviceID >= Pa_CountDevices()) ) + { + return paInvalidDeviceId; + } + if( (numInputChannels <= 0) && ( numOutputChannels <= 0) ) return paInvalidChannelCount; + +#if SUPPORT_AUDIO_CAPTURE + if( inputDeviceID >= 0 ) + { + PaError size = Pa_GetSampleSize( inputSampleFormat ); + if( size < 0 ) return size; + bitsPerInputSample = 8 * size; + if( (numInputChannels <= 0) ) return paInvalidChannelCount; + } +#else + if( inputDeviceID >= 0 ) + { + return paInvalidChannelCount; + } +#endif /* SUPPORT_AUDIO_CAPTURE */ + else + { + if( numInputChannels > 0 ) return paInvalidChannelCount; + bitsPerInputSample = 0; + } + + if( outputDeviceID >= 0 ) + { + PaError size = Pa_GetSampleSize( outputSampleFormat ); + if( size < 0 ) return size; + bitsPerOutputSample = 8 * size; + if( (numOutputChannels <= 0) ) return paInvalidChannelCount; + } + else + { + if( numOutputChannels > 0 ) return paInvalidChannelCount; + bitsPerOutputSample = 0; + } + + if( callback == NULL ) return paNullCallback; + + /* Allocate and clear stream structure. */ + past = (internalPortAudioStream *) PaHost_AllocateFastMemory( sizeof(internalPortAudioStream) ); + if( past == NULL ) return paInsufficientMemory; + memset( past, 0, sizeof(internalPortAudioStream) ); + AddTraceMessage("Pa_OpenStream: past", (long) past ); + + past->past_Magic = PA_MAGIC; /* Set ID to catch bugs. */ + past->past_FramesPerUserBuffer = framesPerBuffer; + past->past_NumUserBuffers = numberOfBuffers; /* NOTE - PaHost_OpenStream() MUST CHECK FOR ZERO! */ + past->past_Callback = callback; + past->past_UserData = userData; + past->past_OutputSampleFormat = outputSampleFormat; + past->past_InputSampleFormat = inputSampleFormat; + past->past_OutputDeviceID = outputDeviceID; + past->past_InputDeviceID = inputDeviceID; + past->past_NumInputChannels = numInputChannels; + past->past_NumOutputChannels = numOutputChannels; + past->past_Flags = streamFlags; + + /* Check for absurd sample rates. */ + if( (sampleRate < 1000.0) || (sampleRate > 200000.0) ) + { + result = paInvalidSampleRate; + goto cleanup; + } + + /* Allocate buffers that may be used for format conversion from user to native buffers. */ + if( numInputChannels > 0 ) + { + +#if PA_VALIDATE_RATE + result = PaHost_ValidateSampleRate( inputDeviceID, sampleRate, &past->past_SampleRate ); + if( result < 0 ) + { + goto cleanup; + } +#else + past->past_SampleRate = sampleRate; +#endif + /* Allocate single Input buffer for passing formatted samples to user callback. */ + past->past_InputBufferSize = framesPerBuffer * numInputChannels * ((bitsPerInputSample+7) / 8); + past->past_InputBuffer = PaHost_AllocateFastMemory(past->past_InputBufferSize); + if( past->past_InputBuffer == NULL ) + { + result = paInsufficientMemory; + goto cleanup; + } + } + else + { + past->past_InputBuffer = NULL; + } + + /* Allocate single Output buffer. */ + if( numOutputChannels > 0 ) + { +#if PA_VALIDATE_RATE + result = PaHost_ValidateSampleRate( outputDeviceID, sampleRate, &past->past_SampleRate ); + if( result < 0 ) + { + goto cleanup; + } +#else + past->past_SampleRate = sampleRate; +#endif + past->past_OutputBufferSize = framesPerBuffer * numOutputChannels * ((bitsPerOutputSample+7) / 8); + past->past_OutputBuffer = PaHost_AllocateFastMemory(past->past_OutputBufferSize); + if( past->past_OutputBuffer == NULL ) + { + result = paInsufficientMemory; + goto cleanup; + } + } + else + { + past->past_OutputBuffer = NULL; + } + + result = PaHost_OpenStream( past ); + if( result < 0 ) goto cleanup; + + *streamPtrPtr = (void *) past; + + return result; + +cleanup: + if( past != NULL ) Pa_CloseStream( past ); + *streamPtrPtr = NULL; + return result; +} + + +/*************************************************************************/ +PaError Pa_OpenDefaultStream( PortAudioStream** stream, + int numInputChannels, + int numOutputChannels, + PaSampleFormat sampleFormat, + double sampleRate, + unsigned long framesPerBuffer, + unsigned long numberOfBuffers, + PortAudioCallback *callback, + void *userData ) +{ + return Pa_OpenStream( + stream, + ((numInputChannels > 0) ? Pa_GetDefaultInputDeviceID() : paNoDevice), + numInputChannels, sampleFormat, NULL, + ((numOutputChannels > 0) ? Pa_GetDefaultOutputDeviceID() : paNoDevice), + numOutputChannels, sampleFormat, NULL, + sampleRate, framesPerBuffer, numberOfBuffers, paNoFlag, callback, userData ); +} + +/*************************************************************************/ +PaError Pa_CloseStream( PortAudioStream* stream) +{ + PaError result; + internalPortAudioStream *past; + + DBUG(("Pa_CloseStream()\n")); + if( stream == NULL ) return paBadStreamPtr; + past = (internalPortAudioStream *) stream; + + Pa_AbortStream( past ); + result = PaHost_CloseStream( past ); + + if( past->past_InputBuffer ) PaHost_FreeFastMemory( past->past_InputBuffer, past->past_InputBufferSize ); + if( past->past_OutputBuffer ) PaHost_FreeFastMemory( past->past_OutputBuffer, past->past_OutputBufferSize ); + PaHost_FreeFastMemory( past, sizeof(internalPortAudioStream) ); + + return result; +} + +/*************************************************************************/ +PaError Pa_StartStream( PortAudioStream *stream ) +{ + PaError result = paHostError; + internalPortAudioStream *past; + + if( stream == NULL ) return paBadStreamPtr; + past = (internalPortAudioStream *) stream; + + past->past_FrameCount = 0.0; + + if( past->past_NumInputChannels > 0 ) + { + result = PaHost_StartInput( past ); + DBUG(("Pa_StartStream: PaHost_StartInput returned = 0x%X.\n", result)); + if( result < 0 ) goto error; + } + + if( past->past_NumOutputChannels > 0 ) + { + result = PaHost_StartOutput( past ); + DBUG(("Pa_StartStream: PaHost_StartOutput returned = 0x%X.\n", result)); + if( result < 0 ) goto error; + } + + result = PaHost_StartEngine( past ); + DBUG(("Pa_StartStream: PaHost_StartEngine returned = 0x%X.\n", result)); + if( result < 0 ) goto error; + + return paNoError; + +error: + return result; +} + +/*************************************************************************/ +PaError Pa_StopStream( PortAudioStream *stream ) +{ + return Pa_KillStream( stream, 0 ); +} + +/*************************************************************************/ +PaError Pa_AbortStream( PortAudioStream *stream ) +{ + return Pa_KillStream( stream, 1 ); +} + +/*************************************************************************/ +static PaError Pa_KillStream( PortAudioStream *stream, int abort ) +{ + PaError result = paNoError; + internalPortAudioStream *past; + + DBUG(("Pa_StopStream().\n")); + if( stream == NULL ) return paBadStreamPtr; + past = (internalPortAudioStream *) stream; + + if( (past->past_NumInputChannels > 0) || (past->past_NumOutputChannels > 0) ) + { + result = PaHost_StopEngine( past, abort ); + DBUG(("Pa_StopStream: PaHost_StopEngine returned = 0x%X.\n", result)); + if( result < 0 ) goto error; + } + + if( past->past_NumInputChannels > 0 ) + { + result = PaHost_StopInput( past, abort ); + DBUG(("Pa_StopStream: PaHost_StopInput returned = 0x%X.\n", result)); + if( result != paNoError ) goto error; + } + + if( past->past_NumOutputChannels > 0 ) + { + result = PaHost_StopOutput( past, abort ); + DBUG(("Pa_StopStream: PaHost_StopOutput returned = 0x%X.\n", result)); + if( result != paNoError ) goto error; + } + +error: + past->past_Usage = 0; + past->past_IfLastExitValid = 0; + + return result; +} + +/*************************************************************************/ +PaError Pa_StreamActive( PortAudioStream *stream ) +{ + internalPortAudioStream *past; + if( stream == NULL ) return paBadStreamPtr; + past = (internalPortAudioStream *) stream; + return PaHost_StreamActive( past ); +} + +/*************************************************************************/ +const char *Pa_GetErrorText( PaError errnum ) +{ + const char *msg; + + switch(errnum) + { + case paNoError: msg = "Success"; break; + case paHostError: msg = "Host error."; break; + case paInvalidChannelCount: msg = "Invalid number of channels."; break; + case paInvalidSampleRate: msg = "Invalid sample rate."; break; + case paInvalidDeviceId: msg = "Invalid device ID."; break; + case paInvalidFlag: msg = "Invalid flag."; break; + case paSampleFormatNotSupported: msg = "Sample format not supported"; break; + case paBadIODeviceCombination: msg = "Illegal combination of I/O devices."; break; + case paInsufficientMemory: msg = "Insufficient memory."; break; + case paBufferTooBig: msg = "Buffer too big."; break; + case paBufferTooSmall: msg = "Buffer too small."; break; + case paNullCallback: msg = "No callback routine specified."; break; + case paBadStreamPtr: msg = "Invalid stream pointer."; break; + case paTimedOut : msg = "Wait Timed Out."; break; + case paInternalError: msg = "Internal PortAudio Error."; break; + case paDeviceUnavailable: msg = "Device Unavailable."; break; + default: msg = "Illegal error number."; break; + } + return msg; +} + +/* + Get CPU Load as a fraction of total CPU time. + A value of 0.5 would imply that PortAudio and the sound generating + callback was consuming roughly 50% of the available CPU time. + The amount may vary depending on CPU load. + This function may be called from the callback function. +*/ +double Pa_GetCPULoad( PortAudioStream* stream) +{ + internalPortAudioStream *past; + if( stream == NULL ) return (double) paBadStreamPtr; + past = (internalPortAudioStream *) stream; + return past->past_Usage; +} + +/*************************************************************************/ +internalPortAudioStream* PaHost_GetStreamRepresentation( PortAudioStream *stream ) +{ + internalPortAudioStream* result = (internalPortAudioStream*) stream; + + if( result == NULL || result->past_Magic != PA_MAGIC ) + return NULL; + else + return result; +} + +/************************************************************* +** Calculate 2 LSB dither signal with a triangular distribution. +** Ranged properly for adding to a 32 bit integer prior to >>15. +** Range of output is +/- 32767 +*/ +#define PA_DITHER_BITS (15) +#define PA_DITHER_SCALE (1.0f / ((1<>DITHER_SHIFT) + (((long)randSeed2)>>DITHER_SHIFT); + /* High pass filter to reduce audibility. */ + highPass = current - previous; + previous = current; + return highPass; +} + +/************************************************************************* +** Called by host code. +** Convert input from Int16, call user code, then convert output +** to Int16 format for native use. +** Assumes host native format is paInt16. +** Returns result from user callback. +*/ +long Pa_CallConvertInt16( internalPortAudioStream *past, + short *nativeInputBuffer, + short *nativeOutputBuffer ) +{ + long temp; + int userResult; + unsigned int i; + void *inputBuffer = NULL; + void *outputBuffer = NULL; + +#if SUPPORT_AUDIO_CAPTURE + /* Get native data from DirectSound. */ + if( (past->past_NumInputChannels > 0) && (nativeInputBuffer != NULL) ) + { + /* Convert from native format to PA format. */ + unsigned int samplesPerBuffer = past->past_FramesPerUserBuffer * past->past_NumInputChannels; + switch(past->past_InputSampleFormat) + { + + case paFloat32: + { + float *inBufPtr = (float *) past->past_InputBuffer; + inputBuffer = past->past_InputBuffer; + for( i=0; ipast_InputBuffer; + inputBuffer = past->past_InputBuffer; + for( i=0; ipast_InputBuffer; + inputBuffer = past->past_InputBuffer; + if( past->past_Flags & paDitherOff ) + { + for( i=0; i> 8); + } + } + else + { + for( i=0; i> 8; /* PLB20010820 */ + temp = ((temp < -0x8000) ? -0x8000 : ((temp > 0x7FFF) ? 0x7FFF : temp)); + inBufPtr[i] = (char)(temp >> 8); + } + } + break; + } + + case paUInt8: + { + /* Convert 16 bit data to 8 bit unsigned chars */ + unsigned char *inBufPtr = (unsigned char *) past->past_InputBuffer; + inputBuffer = past->past_InputBuffer; + if( past->past_Flags & paDitherOff ) + { + for( i=0; i> 8) + 0x80); + } + } + else + { + /* If you dither then you have to clip because dithering could push the signal out of range! */ + for( i=0; i> 8; /* PLB20010820 */ + temp = ((temp < -0x8000) ? -0x8000 : ((temp > 0x7FFF) ? 0x7FFF : temp)); + inBufPtr[i] = (unsigned char)((temp>>8) + 0x80); /* PLB20010820 */ + } + } + break; + } + + default: + break; + } + } +#endif /* SUPPORT_AUDIO_CAPTURE */ + + /* Are we doing output time? */ + if( (past->past_NumOutputChannels > 0) && (nativeOutputBuffer != NULL) ) + { + /* May already be in native format so just write directly to native buffer. */ + outputBuffer = (past->past_OutputSampleFormat == paInt16) ? + (void*)nativeOutputBuffer : past->past_OutputBuffer; + } + /* + AddTraceMessage("Pa_CallConvertInt16: inputBuffer = ", (int) inputBuffer ); + AddTraceMessage("Pa_CallConvertInt16: outputBuffer = ", (int) outputBuffer ); + */ + /* Call user callback routine. */ + userResult = past->past_Callback( + inputBuffer, + outputBuffer, + past->past_FramesPerUserBuffer, + past->past_FrameCount, + past->past_UserData ); + + past->past_FrameCount += (PaTimestamp) past->past_FramesPerUserBuffer; + + /* Convert to native format if necessary. */ + if( outputBuffer != NULL ) + { + unsigned int samplesPerBuffer = past->past_FramesPerUserBuffer * past->past_NumOutputChannels; + switch(past->past_OutputSampleFormat) + { + case paFloat32: + { + float *outBufPtr = (float *) past->past_OutputBuffer; + if( past->past_Flags & paDitherOff ) + { + if( past->past_Flags & paClipOff ) /* NOTHING */ + { + for( i=0; i 0x7FFF) ? 0x7FFF : temp)); + } + } + } + else + { + /* If you dither then you have to clip because dithering could push the signal out of range! */ + for( i=0; i 0x7FFF) ? 0x7FFF : temp)); + } + } + break; + } + + case paInt32: + { + int *outBufPtr = (int *) past->past_OutputBuffer; + if( past->past_Flags & paDitherOff ) + { + for( i=0; i> 16 ); + } + } + else + { + for( i=0; i> 1) + PaConvert_TriangularDither(); + temp = temp >> 15; + *nativeOutputBuffer++ = (short)((temp < -0x8000) ? -0x8000 : ((temp > 0x7FFF) ? 0x7FFF : temp)); + } + } + break; + } + + case paInt8: + { + char *outBufPtr = (char *) past->past_OutputBuffer; + for( i=0; ipast_OutputBuffer; + for( i=0; i 0 ) return paNoError; + ResetTraceMessages(); + return PaHost_Init(); +} + +PaError Pa_Terminate( void ) +{ + PaError result = paNoError; + + if( gInitCount == 0 ) return paNoError; + else if( --gInitCount == 0 ) + { + result = PaHost_Term(); + DumpTraceMessages(); + } + return result; +} + +int PaHost_IsInitialized() +{ + return gInitCount; +} + +/*************************************************************************/ +PaError Pa_GetSampleSize( PaSampleFormat format ) +{ + int size; + switch(format ) + { + + case paUInt8: + case paInt8: + size = 1; + break; + + case paInt16: + size = 2; + break; + + case paPackedInt24: + size = 3; + break; + + case paFloat32: + case paInt32: + case paInt24: + size = 4; + break; + + default: + size = paSampleFormatNotSupported; + break; + } + return (PaError) size; +} + + diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_common/pa_trace.c b/mozilla/zap/zmk/portaudio_v18_1/pa_common/pa_trace.c new file mode 100755 index 00000000000..3bcda4fa377 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_common/pa_trace.c @@ -0,0 +1,83 @@ +/* + * $Id: pa_trace.c,v 1.1.2.1 2005-08-16 20:04:01 alex%croczilla.com Exp $ + * Portable Audio I/O Library Trace Facility + * Store trace information in real-time for later printing. + * + * Based on the Open Source API proposed by Ross Bencina + * Copyright (c) 1999-2000 Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#include +#include +#include +#include "pa_trace.h" + +#if TRACE_REALTIME_EVENTS + +static char *traceTextArray[MAX_TRACE_RECORDS]; +static int traceIntArray[MAX_TRACE_RECORDS]; +static int traceIndex = 0; +static int traceBlock = 0; + +/*********************************************************************/ +void ResetTraceMessages() +{ + traceIndex = 0; +} + +/*********************************************************************/ +void DumpTraceMessages() +{ + int i; + int numDump = (traceIndex < MAX_TRACE_RECORDS) ? traceIndex : MAX_TRACE_RECORDS; + + printf("DumpTraceMessages: traceIndex = %d\n", traceIndex ); + for( i=0; i +#include +#include +#include + +/* PLB20010422 - "memory.h" doesn't work on CodeWarrior for PC. Thanks Mike Berry for the mod. */ +#ifdef _WIN32 +#ifndef __MWERKS__ +#include +#endif /* __MWERKS__ */ +#else /* !_WIN32 */ +#include +#endif /* _WIN32 */ + +#include "portaudio.h" +#include "pa_host.h" +#include "pa_trace.h" + +/* The reason we might NOT want to validate the rate before opening the stream + * is because many DirectSound drivers lie about the rates they actually support. + */ +#define PA_VALIDATE_RATE (0) /* If true validate sample rate against driver info. */ + +/* +O- maybe not allocate past_InputBuffer and past_OutputBuffer if not needed for conversion +*/ + +#ifndef FALSE + #define FALSE (0) + #define TRUE (!FALSE) +#endif + +#define PRINT(x) { printf x; fflush(stdout); } +#define ERR_RPT(x) PRINT(x) +#define DBUG(x) /* PRINT(x) */ +#define DBUGX(x) /* PRINT(x) */ + +static int gInitCount = 0; /* Count number of times Pa_Initialize() called to allow nesting and overlapping. */ + +static PaError Pa_KillStream( PortAudioStream *stream, int abort ); + +/***********************************************************************/ +int PaHost_FindClosestTableEntry( double allowableError, const double *rateTable, int numRates, double frameRate ) +{ + double err, minErr = allowableError; + int i, bestFit = -1; + + for( i=0; inumSampleRates == -1 ) + { + /* Is it out of range? */ + if( (requestedFrameRate < pdi->sampleRates[0]) || + (requestedFrameRate > pdi->sampleRates[1]) ) + { + return paInvalidSampleRate; + } + + *closestFrameRatePtr = requestedFrameRate; + } + else + { + bestRateIndex = PaHost_FindClosestTableEntry( 1.0, pdi->sampleRates, pdi->numSampleRates, requestedFrameRate ); + if( bestRateIndex < 0 ) return paInvalidSampleRate; + *closestFrameRatePtr = pdi->sampleRates[bestRateIndex]; + } + return paNoError; +} + +/*************************************************************************/ +DLL_API PaError Pa_OpenStream( + PortAudioStream** streamPtrPtr, + PaDeviceID inputDeviceID, + int numInputChannels, + PaSampleFormat inputSampleFormat, + void *inputDriverInfo, + PaDeviceID outputDeviceID, + int numOutputChannels, + PaSampleFormat outputSampleFormat, + void *outputDriverInfo, + double sampleRate, + unsigned long framesPerBuffer, + unsigned long numberOfBuffers, + unsigned long streamFlags, + PortAudioCallback *callback, + void *userData ) +{ + internalPortAudioStream *past = NULL; + PaError result = paNoError; + int bitsPerInputSample; + int bitsPerOutputSample; + /* Print passed parameters. */ + DBUG(("Pa_OpenStream( %p, %d, %d, %d, %p, /* input */ \n", + streamPtrPtr, inputDeviceID, numInputChannels, + inputSampleFormat, inputDriverInfo )); + DBUG((" %d, %d, %d, %p, /* output */\n", + outputDeviceID, numOutputChannels, + outputSampleFormat, outputDriverInfo )); + DBUG((" %g, %d, %d, 0x%x, , %p )\n", + sampleRate, framesPerBuffer, numberOfBuffers, + streamFlags, userData )); + + /* Check for parameter errors. */ + if( (streamFlags & ~(paClipOff | paDitherOff)) != 0 ) return paInvalidFlag; + if( streamPtrPtr == NULL ) return paBadStreamPtr; + if( inputDriverInfo != NULL ) return paHostError; /* REVIEW */ + if( outputDriverInfo != NULL ) return paHostError; /* REVIEW */ + if( (inputDeviceID < 0) && ( outputDeviceID < 0) ) return paInvalidDeviceId; + if( (outputDeviceID >= Pa_CountDevices()) || (inputDeviceID >= Pa_CountDevices()) ) return paInvalidDeviceId; + if( (numInputChannels <= 0) && ( numOutputChannels <= 0) ) return paInvalidChannelCount; + +#if SUPPORT_AUDIO_CAPTURE + if( inputDeviceID >= 0 ) + { + PaError size = Pa_GetSampleSize( inputSampleFormat ); + if( size < 0 ) return size; + bitsPerInputSample = 8 * size; + if( (numInputChannels <= 0) ) return paInvalidChannelCount; + } +#else + if( inputDeviceID >= 0 ) + { + return paInvalidChannelCount; + } +#endif /* SUPPORT_AUDIO_CAPTURE */ + else + { + if( numInputChannels > 0 ) return paInvalidChannelCount; + bitsPerInputSample = 0; + } + + if( outputDeviceID >= 0 ) + { + PaError size = Pa_GetSampleSize( outputSampleFormat ); + if( size < 0 ) return size; + bitsPerOutputSample = 8 * size; + if( (numOutputChannels <= 0) ) return paInvalidChannelCount; + } + else + { + if( numOutputChannels > 0 ) return paInvalidChannelCount; + bitsPerOutputSample = 0; + } + + if( callback == NULL ) return paNullCallback; + + /* Allocate and clear stream structure. */ + past = (internalPortAudioStream *) PaHost_AllocateFastMemory( sizeof(internalPortAudioStream) ); + if( past == NULL ) return paInsufficientMemory; + memset( past, 0, sizeof(internalPortAudioStream) ); + AddTraceMessage("Pa_OpenStream: past", (long) past ); + + past->past_Magic = PA_MAGIC; /* Set ID to catch bugs. */ + past->past_FramesPerUserBuffer = framesPerBuffer; + past->past_NumUserBuffers = numberOfBuffers; /* NOTE - PaHost_OpenStream() NMUST CHECK FOR ZERO! */ + past->past_Callback = callback; + past->past_UserData = userData; + past->past_OutputSampleFormat = outputSampleFormat; + past->past_InputSampleFormat = inputSampleFormat; + past->past_OutputDeviceID = outputDeviceID; + past->past_InputDeviceID = inputDeviceID; + past->past_NumInputChannels = numInputChannels; + past->past_NumOutputChannels = numOutputChannels; + past->past_Flags = streamFlags; + + /* Check for absurd sample rates. */ + if( (sampleRate < 1000.0) || (sampleRate > 200000.0) ) + { + result = paInvalidSampleRate; + goto cleanup; + } + + /* Allocate buffers that may be used for format conversion from user to native buffers. */ + if( numInputChannels > 0 ) + { + +#if PA_VALIDATE_RATE + result = PaHost_ValidateSampleRate( inputDeviceID, sampleRate, &past->past_SampleRate ); + if( result < 0 ) + { + goto cleanup; + } +#else + past->past_SampleRate = sampleRate; +#endif + /* Allocate single Input buffer. */ + past->past_InputBufferSize = framesPerBuffer * numInputChannels * ((bitsPerInputSample+7) / 8); + past->past_InputBuffer = PaHost_AllocateFastMemory(past->past_InputBufferSize); + if( past->past_InputBuffer == NULL ) + { + result = paInsufficientMemory; + goto cleanup; + } + } + else + { + past->past_InputBuffer = NULL; + } + + /* Allocate single Output buffer. */ + if( numOutputChannels > 0 ) + { +#if PA_VALIDATE_RATE + result = PaHost_ValidateSampleRate( outputDeviceID, sampleRate, &past->past_SampleRate ); + if( result < 0 ) + { + goto cleanup; + } +#else + past->past_SampleRate = sampleRate; +#endif + past->past_OutputBufferSize = framesPerBuffer * numOutputChannels * ((bitsPerOutputSample+7) / 8); + past->past_OutputBuffer = PaHost_AllocateFastMemory(past->past_OutputBufferSize); + if( past->past_OutputBuffer == NULL ) + { + result = paInsufficientMemory; + goto cleanup; + } + } + else + { + past->past_OutputBuffer = NULL; + } + + result = PaHost_OpenStream( past ); + if( result < 0 ) goto cleanup; + + *streamPtrPtr = (void *) past; + + return result; + +cleanup: + if( past != NULL ) Pa_CloseStream( past ); + *streamPtrPtr = NULL; + return result; +} + + +/*************************************************************************/ +DLL_API PaError Pa_OpenDefaultStream( PortAudioStream** stream, + int numInputChannels, + int numOutputChannels, + PaSampleFormat sampleFormat, + double sampleRate, + unsigned long framesPerBuffer, + unsigned long numberOfBuffers, + PortAudioCallback *callback, + void *userData ) +{ + return Pa_OpenStream( + stream, + ((numInputChannels > 0) ? Pa_GetDefaultInputDeviceID() : paNoDevice), + numInputChannels, sampleFormat, NULL, + ((numOutputChannels > 0) ? Pa_GetDefaultOutputDeviceID() : paNoDevice), + numOutputChannels, sampleFormat, NULL, + sampleRate, framesPerBuffer, numberOfBuffers, paNoFlag, callback, userData ); +} + +/*************************************************************************/ +DLL_API PaError Pa_CloseStream( PortAudioStream* stream) +{ + PaError result; + internalPortAudioStream *past; + + DBUG(("Pa_CloseStream()\n")); + if( stream == NULL ) return paBadStreamPtr; + past = (internalPortAudioStream *) stream; + + Pa_AbortStream( past ); + result = PaHost_CloseStream( past ); + + if( past->past_InputBuffer ) PaHost_FreeFastMemory( past->past_InputBuffer, past->past_InputBufferSize ); + if( past->past_OutputBuffer ) PaHost_FreeFastMemory( past->past_OutputBuffer, past->past_OutputBufferSize ); + PaHost_FreeFastMemory( past, sizeof(internalPortAudioStream) ); + + return result; +} + +/*************************************************************************/ +DLL_API PaError Pa_StartStream( PortAudioStream *stream ) +{ + PaError result = paHostError; + internalPortAudioStream *past; + + if( stream == NULL ) return paBadStreamPtr; + past = (internalPortAudioStream *) stream; + + past->past_FrameCount = 0.0; + + if( past->past_NumInputChannels > 0 ) + { + result = PaHost_StartInput( past ); + DBUG(("Pa_StartStream: PaHost_StartInput returned = 0x%X.\n", result)); + if( result < 0 ) goto error; + } + + if( past->past_NumOutputChannels > 0 ) + { + result = PaHost_StartOutput( past ); + DBUG(("Pa_StartStream: PaHost_StartOutput returned = 0x%X.\n", result)); + if( result < 0 ) goto error; + } + + result = PaHost_StartEngine( past ); + DBUG(("Pa_StartStream: PaHost_StartEngine returned = 0x%X.\n", result)); + if( result < 0 ) goto error; + + return paNoError; + +error: + return result; +} + +/*************************************************************************/ +DLL_API PaError Pa_StopStream( PortAudioStream *stream ) +{ + return Pa_KillStream( stream, 0 ); +} + +/*************************************************************************/ +DLL_API PaError Pa_AbortStream( PortAudioStream *stream ) +{ + return Pa_KillStream( stream, 1 ); +} + +/*************************************************************************/ +static PaError Pa_KillStream( PortAudioStream *stream, int abort ) +{ + PaError result = paNoError; + internalPortAudioStream *past; + + DBUG(("Pa_StopStream().\n")); + if( stream == NULL ) return paBadStreamPtr; + past = (internalPortAudioStream *) stream; + + if( (past->past_NumInputChannels > 0) || (past->past_NumOutputChannels > 0) ) + { + result = PaHost_StopEngine( past, abort ); + DBUG(("Pa_StopStream: PaHost_StopEngine returned = 0x%X.\n", result)); + if( result < 0 ) goto error; + } + + if( past->past_NumInputChannels > 0 ) + { + result = PaHost_StopInput( past, abort ); + DBUG(("Pa_StopStream: PaHost_StopInput returned = 0x%X.\n", result)); + if( result != paNoError ) goto error; + } + + if( past->past_NumOutputChannels > 0 ) + { + result = PaHost_StopOutput( past, abort ); + DBUG(("Pa_StopStream: PaHost_StopOutput returned = 0x%X.\n", result)); + if( result != paNoError ) goto error; + } + +error: + past->past_Usage = 0; + past->past_IfLastExitValid = 0; + + return result; +} + +/*************************************************************************/ +DLL_API PaError Pa_StreamActive( PortAudioStream *stream ) +{ + internalPortAudioStream *past; + if( stream == NULL ) return paBadStreamPtr; + past = (internalPortAudioStream *) stream; + return PaHost_StreamActive( past ); +} + +/*************************************************************************/ +DLL_API const char *Pa_GetErrorText( PaError errnum ) +{ + const char *msg; + + switch(errnum) + { + case paNoError: msg = "Success"; break; + case paHostError: msg = "Host error."; break; + case paInvalidChannelCount: msg = "Invalid number of channels."; break; + case paInvalidSampleRate: msg = "Invalid sample rate."; break; + case paInvalidDeviceId: msg = "Invalid device ID."; break; + case paInvalidFlag: msg = "Invalid flag."; break; + case paSampleFormatNotSupported: msg = "Sample format not supported"; break; + case paBadIODeviceCombination: msg = "Illegal combination of I/O devices."; break; + case paInsufficientMemory: msg = "Insufficient memory."; break; + case paBufferTooBig: msg = "Buffer too big."; break; + case paBufferTooSmall: msg = "Buffer too small."; break; + case paNullCallback: msg = "No callback routine specified."; break; + case paBadStreamPtr: msg = "Invalid stream pointer."; break; + case paTimedOut : msg = "Wait Timed Out."; break; + case paInternalError: msg = "Internal PortAudio Error."; break; + default: msg = "Illegal error number."; break; + } + return msg; +} + +/* + Get CPU Load as a fraction of total CPU time. + A value of 0.5 would imply that PortAudio and the sound generating + callback was consuming roughly 50% of the available CPU time. + The amount may vary depending on CPU load. + This function may be called from the callback function. +*/ +DLL_API double Pa_GetCPULoad( PortAudioStream* stream) +{ + internalPortAudioStream *past; + if( stream == NULL ) return (double) paBadStreamPtr; + past = (internalPortAudioStream *) stream; + return past->past_Usage; +} + +/************************************************************* +** Calculate 2 LSB dither signal with a triangular distribution. +** Ranged properly for adding to a 32 bit integer prior to >>15. +*/ +#define DITHER_BITS (15) +#define DITHER_SCALE (1.0f / ((1<>(32-DITHER_BITS)) + (((long)randSeed2)>>(32-DITHER_BITS)); + /* High pass filter to reduce audibility. */ + highPass = current - previous; + previous = current; + return highPass; +} + +/************************************************************************* +** Called by host code. +** Convert input from Int16, call user code, then convert output +** to Int16 format for native use. +** Assumes host native format is paInt16. +** Returns result from user callback. +*/ +long Pa_CallConvertInt16( internalPortAudioStream *past, + short *nativeInputBuffer, + short *nativeOutputBuffer ) +{ + long temp; + long bytesEmpty = 0; + long bytesFilled = 0; + int userResult; + unsigned int i; + void *inputBuffer = NULL; + void *outputBuffer = NULL; + +#if SUPPORT_AUDIO_CAPTURE + /* Get native data from DirectSound. */ + if( (past->past_NumInputChannels > 0) && (nativeInputBuffer != NULL) ) + { + /* Convert from native format to PA format. */ + unsigned int samplesPerBuffer = past->past_FramesPerUserBuffer * past->past_NumInputChannels; + switch(past->past_InputSampleFormat) + { + + case paFloat32: + { + float *inBufPtr = (float *) past->past_InputBuffer; + inputBuffer = past->past_InputBuffer; + for( i=0; ipast_InputBuffer; + inputBuffer = past->past_InputBuffer; + for( i=0; ipast_InputBuffer; + inputBuffer = past->past_InputBuffer; + if( past->past_Flags & paDitherOff ) + { + for( i=0; i> 8); + } + } + else + { + for( i=0; i> 7; + temp = ((temp < -0x8000) ? -0x8000 : ((temp > 0x7FFF) ? 0x7FFF : temp)); + inBufPtr[i] = (char)(temp >> 8); + } + } + break; + } + + case paUInt8: + { + /* Convert 16 bit data to 8 bit unsigned chars */ + unsigned char *inBufPtr = (unsigned char *) past->past_InputBuffer; + inputBuffer = past->past_InputBuffer; + if( past->past_Flags & paDitherOff ) + { + for( i=0; i> 8)) + 0x80; + } + } + else + { + /* If you dither then you have to clip because dithering could push the signal out of range! */ + for( i=0; i> 7; + temp = ((temp < -0x8000) ? -0x8000 : ((temp > 0x7FFF) ? 0x7FFF : temp)); + inBufPtr[i] = (unsigned char)(temp + 0x80); + } + } + break; + } + + default: + break; + } + } +#endif /* SUPPORT_AUDIO_CAPTURE */ + + /* Are we doing output time? */ + if( (past->past_NumOutputChannels > 0) && (nativeOutputBuffer != NULL) ) + { + /* May already be in native format so just write directly to native buffer. */ + outputBuffer = (past->past_OutputSampleFormat == paInt16) ? + nativeOutputBuffer : past->past_OutputBuffer; + } + /* + AddTraceMessage("Pa_CallConvertInt16: inputBuffer = ", (int) inputBuffer ); + AddTraceMessage("Pa_CallConvertInt16: outputBuffer = ", (int) outputBuffer ); + */ + /* Call user callback routine. */ + userResult = past->past_Callback( + inputBuffer, + outputBuffer, + past->past_FramesPerUserBuffer, + past->past_FrameCount, + past->past_UserData ); + + past->past_FrameCount += (PaTimestamp) past->past_FramesPerUserBuffer; + + /* Convert to native format if necessary. */ + if( outputBuffer != NULL ) + { + unsigned int samplesPerBuffer = past->past_FramesPerUserBuffer * past->past_NumOutputChannels; + switch(past->past_OutputSampleFormat) + { + case paFloat32: + { + float *outBufPtr = (float *) past->past_OutputBuffer; + if( past->past_Flags & paDitherOff ) + { + if( past->past_Flags & paClipOff ) /* NOTHING */ + { + for( i=0; i 0x7FFF) ? 0x7FFF : temp)); + } + } + } + else + { + /* If you dither then you have to clip because dithering could push the signal out of range! */ + for( i=0; i 0x7FFF) ? 0x7FFF : temp)); + } + } + break; + } + + case paInt32: + { + int *outBufPtr = (int *) past->past_OutputBuffer; + if( past->past_Flags & paDitherOff ) + { + for( i=0; i> 16 ); + } + } + else + { + for( i=0; i> 1) + Pa_TriangularDither(); + temp = temp >> 15; + *nativeOutputBuffer++ = (short)((temp < -0x8000) ? -0x8000 : ((temp > 0x7FFF) ? 0x7FFF : temp)); + } + } + break; + } + + case paInt8: + { + char *outBufPtr = (char *) past->past_OutputBuffer; + for( i=0; ipast_OutputBuffer; + for( i=0; ipast_NumInputChannels > 0) && (nativeInputBuffer != NULL) ) + { + inputBuffer = nativeInputBuffer; // FIXME + } + + /* Are we doing output time? */ + if( (past->past_NumOutputChannels > 0) && (nativeOutputBuffer != NULL) ) + { + /* May already be in native format so just write directly to native buffer. */ + outputBuffer = (past->past_OutputSampleFormat == paFloat32) ? + nativeOutputBuffer : past->past_OutputBuffer; + } + /* + AddTraceMessage("Pa_CallConvertInt16: inputBuffer = ", (int) inputBuffer ); + AddTraceMessage("Pa_CallConvertInt16: outputBuffer = ", (int) outputBuffer ); + */ + /* Call user callback routine. */ + userResult = past->past_Callback( + inputBuffer, + outputBuffer, + past->past_FramesPerUserBuffer, + past->past_FrameCount, + past->past_UserData ); + + past->past_FrameCount += (PaTimestamp) past->past_FramesPerUserBuffer; + + /* Convert to native format if necessary. */ // FIXME + return userResult; +} + +/*************************************************************************/ +DLL_API PaError Pa_Initialize( void ) +{ + if( gInitCount++ > 0 ) return paNoError; + ResetTraceMessages(); + return PaHost_Init(); +} + +DLL_API PaError Pa_Terminate( void ) +{ + PaError result = paNoError; + + if( gInitCount == 0 ) return paNoError; + else if( --gInitCount == 0 ) + { + result = PaHost_Term(); + DumpTraceMessages(); + } + return result; +} + +/*************************************************************************/ +DLL_API PaError Pa_GetSampleSize( PaSampleFormat format ) +{ + int size; + switch(format ) + { + + case paUInt8: + case paInt8: + size = 1; + break; + + case paInt16: + size = 2; + break; + + case paPackedInt24: + size = 3; + break; + + case paFloat32: + case paInt32: + case paInt24: + size = 4; + break; + + default: + size = paSampleFormatNotSupported; + break; + } + return (PaError) size; +} + + diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_dll_switch/portaudio.h b/mozilla/zap/zmk/portaudio_v18_1/pa_dll_switch/portaudio.h new file mode 100755 index 00000000000..3c30b23f90c --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_dll_switch/portaudio.h @@ -0,0 +1,439 @@ +#ifndef PORT_AUDIO_H +#define PORT_AUDIO_H + +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +/* + * PortAudio Portable Real-Time Audio Library + * PortAudio API Header File + * Latest version available at: http://www.audiomulch.com/portaudio/ + * + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +// added by zplane.developement in order to generate a DLL + +#if defined(PA_MME_EXPORTS) || defined(PA_DX_EXPORTS) +#define DLL_API __declspec( dllexport ) +#elif defined(_LIB) || defined(_STATIC_LINK) || defined(_STATIC_APP) +#define DLL_API +#else +#define DLL_API __declspec(dllexport) +#endif + + +typedef int PaError; +typedef enum { + paNoError = 0, + + paHostError = -10000, + paInvalidChannelCount, + paInvalidSampleRate, + paInvalidDeviceId, + paInvalidFlag, + paSampleFormatNotSupported, + paBadIODeviceCombination, + paInsufficientMemory, + paBufferTooBig, + paBufferTooSmall, + paNullCallback, + paBadStreamPtr, + paTimedOut, + paInternalError +} PaErrorNum; + +/* + Pa_Initialize() is the library initialisation function - call this before + using the library. +*/ + +DLL_API PaError Pa_Initialize( void ); + +/* + Pa_Terminate() is the library termination function - call this after + using the library. +*/ + +DLL_API PaError Pa_Terminate( void ); + +/* + Return host specific error. + This can be called after receiving a paHostError. +*/ +DLL_API long Pa_GetHostError( void ); + +/* + Translate the error number into a human readable message. +*/ +DLL_API const char *Pa_GetErrorText( PaError errnum ); + +/* + Sample formats + + These are formats used to pass sound data between the callback and the + stream. Each device has a "native" format which may be used when optimum + efficiency or control over conversion is required. + + Formats marked "always available" are supported (emulated) by all devices. + + The floating point representation uses +1.0 and -1.0 as the respective + maximum and minimum. + +*/ + +typedef unsigned long PaSampleFormat; +#define paFloat32 ((PaSampleFormat) (1<<0)) /*always available*/ +#define paInt16 ((PaSampleFormat) (1<<1)) /*always available*/ +#define paInt32 ((PaSampleFormat) (1<<2)) /*always available*/ +#define paInt24 ((PaSampleFormat) (1<<3)) +#define paPackedInt24 ((PaSampleFormat) (1<<4)) +#define paInt8 ((PaSampleFormat) (1<<5)) +#define paUInt8 ((PaSampleFormat) (1<<6)) /* unsigned 8 bit, 128 is "ground" */ +#define paCustomFormat ((PaSampleFormat) (1<<16)) + +/* + Device enumeration mechanism. + + Device ids range from 0 to Pa_CountDevices()-1. + + Devices may support input, output or both. Device 0 is always the "default" + device and should support at least stereo in and out if that is available + on the taget platform _even_ if this involves kludging an input/output + device on platforms that usually separate input from output. Other platform + specific devices are specified by positive device ids. +*/ + +typedef int PaDeviceID; +#define paNoDevice -1 + +typedef struct +{ + int structVersion; + const char *name; + int maxInputChannels; + int maxOutputChannels; + /* Number of discrete rates, or -1 if range supported. */ + int numSampleRates; + /* Array of supported sample rates, or {min,max} if range supported. */ + const double *sampleRates; + PaSampleFormat nativeSampleFormats; +} +PaDeviceInfo; + + +DLL_API int Pa_CountDevices(); +/* + Pa_GetDefaultInputDeviceID(), Pa_GetDefaultOutputDeviceID() + + Return the default device ID or paNoDevice if there is no devices. + The result can be passed to Pa_OpenStream(). + + On the PC, the user can specify a default device by + setting an environment variable. For example, to use device #1. + + set PA_RECOMMENDED_OUTPUT_DEVICE=1 + + The user should first determine the available device ID by using + the supplied application "pa_devs". +*/ +DLL_API PaDeviceID Pa_GetDefaultInputDeviceID( void ); +DLL_API PaDeviceID Pa_GetDefaultOutputDeviceID( void ); + +/* + PaTimestamp is used to represent a continuous sample clock with arbitrary + start time useful for syncronisation. The type is used in the outTime + argument to the callback function and the result of Pa_StreamTime() +*/ + +typedef double PaTimestamp; + +/* + Pa_GetDeviceInfo() returns a pointer to an immutable PaDeviceInfo structure + referring to the device specified by id. + If id is out of range the function returns NULL. + + The returned structure is owned by the PortAudio implementation and must + not be manipulated or freed. The pointer is guaranteed to be valid until + between calls to Pa_Initialize() and Pa_Terminate(). +*/ + +DLL_API const PaDeviceInfo* Pa_GetDeviceInfo( PaDeviceID id ); + +/* + PortAudioCallback is implemented by clients of the portable audio api. + + inputBuffer and outputBuffer are arrays of interleaved samples, + the format, packing and number of channels used by the buffers are + determined by parameters to Pa_OpenStream() (see below). + + framesPerBuffer is the number of sample frames to be processed by the callback. + + outTime is the time in samples when the buffer(s) processed by + this callback will begin being played at the audio output. + See also Pa_StreamTime() + + userData is the value of a user supplied pointer passed to Pa_OpenStream() + intended for storing synthesis data etc. + + return value: + The callback can return a nonzero value to stop the stream. This may be + useful in applications such as soundfile players where a specific duration + of output is required. However, it is not necessary to utilise this mechanism + as StopStream() will also terminate the stream. A callback returning a + nonzero value must fill the entire outputBuffer. + + NOTE: None of the other stream functions may be called from within the + callback function except for Pa_GetCPULoad(). + +*/ + +typedef int (PortAudioCallback)( + void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ); + + +/* + Stream flags + + These flags may be supplied (ored together) in the streamFlags argument to + the Pa_OpenStream() function. + + [ suggestions? ] +*/ + +#define paNoFlag (0) +#define paClipOff (1<<0) /* disable defult clipping of out of range samples */ +#define paDitherOff (1<<1) /* disable default dithering */ +#define paPlatformSpecificFlags (0x00010000) +typedef unsigned long PaStreamFlags; + +/* + A single PortAudioStream provides multiple channels of real-time + input and output audio streaming to a client application. + Pointers to PortAudioStream objects are passed between PortAudio functions. +*/ + +typedef void PortAudioStream; +#define PaStream PortAudioStream + +/* + Pa_OpenStream() opens a stream for either input, output or both. + + stream is the address of a PortAudioStream pointer which will receive + a pointer to the newly opened stream. + + inputDevice is the id of the device used for input (see PaDeviceID above.) + inputDevice may be paNoDevice to indicate that an input device is not required. + + numInputChannels is the number of channels of sound to be delivered to the + callback. It can range from 1 to the value of maxInputChannels in the + device input record for the device specified in the inputDevice parameter. + If inputDevice is paNoDevice numInputChannels is ignored. + + inputSampleFormat is the format of inputBuffer provided to the callback + function. inputSampleFormat may be any of the formats described by the + PaSampleFormat enumeration (see above). PortAudio guarantees support for + the sound devices native formats (nativeSampleFormats in the device info + record) and additionally 16 and 32 bit integer and 32 bit floating point + formats. Support for other formats is implementation defined. + + inputDriverInfo is a pointer to an optional driver specific data structure + containing additional information for device setup or stream processing. + inputDriverInfo is never required for correct operation. If not used + inputDriverInfo should be NULL. + + outputDevice is the id of the device used for output (see PaDeviceID above.) + outputDevice may be paNoDevice to indicate that an output device is not required. + + numOutputChannels is the number of channels of sound to be supplied by the + callback. See the definition of numInputChannels above for more details. + + outputSampleFormat is the sample format of the outputBuffer filled by the + callback function. See the definition of inputSampleFormat above for more + details. + + outputDriverInfo is a pointer to an optional driver specific data structure + containing additional information for device setup or stream processing. + outputDriverInfo is never required for correct operation. If not used + outputDriverInfo should be NULL. + + sampleRate is the desired sampleRate for input and output + + framesPerBuffer is the length in sample frames of all internal sample buffers + used for communication with platform specific audio routines. Wherever + possible this corresponds to the framesPerBuffer parameter passed to the + callback function. + + numberOfBuffers is the number of buffers used for multibuffered + communication with the platform specific audio routines. This parameter is + provided only as a guide - and does not imply that an implementation must + use multibuffered i/o when reliable double buffering is available (such as + SndPlayDoubleBuffer() on the Macintosh.) + + streamFlags may contain a combination of flags ORed together. + These flags modify the behavior of the + streaming process. Some flags may only be relevant to certain buffer formats. + + callback is a pointer to a client supplied function that is responsible + for processing and filling input and output buffers (see above for details.) + + userData is a client supplied pointer which is passed to the callback + function. It could for example, contain a pointer to instance data necessary + for processing the audio buffers. + + return value: + Apon success Pa_OpenStream() returns PaNoError and places a pointer to a + valid PortAudioStream in the stream argument. The stream is inactive (stopped). + If a call to Pa_OpenStream() fails a nonzero error code is returned (see + PAError above) and the value of stream is invalid. + +*/ + +DLL_API PaError Pa_OpenStream( PortAudioStream** stream, + PaDeviceID inputDevice, + int numInputChannels, + PaSampleFormat inputSampleFormat, + void *inputDriverInfo, + PaDeviceID outputDevice, + int numOutputChannels, + PaSampleFormat outputSampleFormat, + void *outputDriverInfo, + double sampleRate, + unsigned long framesPerBuffer, + unsigned long numberOfBuffers, + PaStreamFlags streamFlags, + PortAudioCallback *callback, + void *userData ); + + +/* + Pa_OpenDefaultStream() is a simplified version of Pa_OpenStream() that + opens the default input and/or ouput devices. Most parameters have + identical meaning to their Pa_OpenStream() counterparts, with the following + exceptions: + + If either numInputChannels or numOutputChannels is 0 the respective device + is not opened (same as passing paNoDevice in the device arguments to Pa_OpenStream() ) + + sampleFormat applies to both the input and output buffers. +*/ + +DLL_API PaError Pa_OpenDefaultStream( PortAudioStream** stream, + int numInputChannels, + int numOutputChannels, + PaSampleFormat sampleFormat, + double sampleRate, + unsigned long framesPerBuffer, + unsigned long numberOfBuffers, + PortAudioCallback *callback, + void *userData ); + +/* + Pa_CloseStream() closes an audio stream, flushing any pending buffers. +*/ + +DLL_API PaError Pa_CloseStream( PortAudioStream* ); + +/* + Pa_StartStream() and Pa_StopStream() begin and terminate audio processing. + When Pa_StopStream() returns, all pending audio buffers have been played. + Pa_AbortStream() stops playing immediately without waiting for pending + buffers to complete. +*/ + +DLL_API PaError Pa_StartStream( PortAudioStream *stream ); + +DLL_API PaError Pa_StopStream( PortAudioStream *stream ); + +DLL_API PaError Pa_AbortStream( PortAudioStream *stream ); + +/* + Pa_StreamActive() returns one when the stream is playing audio, + zero when not playing, or a negative error number if the + stream is invalid. + The stream is active between calls to Pa_StartStream() and Pa_StopStream(), + but may also become inactive if the callback returns a non-zero value. + In the latter case, the stream is considered inactive after the last + buffer has finished playing. +*/ + +DLL_API PaError Pa_StreamActive( PortAudioStream *stream ); + +/* + Pa_StreamTime() returns the current output time for the stream in samples. + This time may be used as a time reference (for example syncronising audio to + MIDI). +*/ + +DLL_API PaTimestamp Pa_StreamTime( PortAudioStream *stream ); + +/* + The "CPU Load" is a fraction of total CPU time consumed by the + stream's audio processing. + A value of 0.5 would imply that PortAudio and the sound generating + callback was consuming roughly 50% of the available CPU time. + This function may be called from the callback function or the application. +*/ +DLL_API double Pa_GetCPULoad( PortAudioStream* stream ); + +/* + Use Pa_GetMinNumBuffers() to determine minimum number of buffers required for + the current host based on minimum latency. + On the PC, for the DirectSound implementation, latency can be optionally set + by user by setting an environment variable. + For example, to set latency to 200 msec, put: + + set PA_MIN_LATENCY_MSEC=200 + + in the AUTOEXEC.BAT file and reboot. + If the environment variable is not set, then the latency will be determined + based on the OS. Windows NT has higher latency than Win95. +*/ + +DLL_API int Pa_GetMinNumBuffers( int framesPerBuffer, double sampleRate ); + +/* + Sleep for at least 'msec' milliseconds. + You may sleep longer than the requested time so don't rely + on this for accurate musical timing. +*/ +DLL_API void Pa_Sleep( long msec ); + +/* + Return size in bytes of a single sample in a given PaSampleFormat + or paSampleFormatNotSupported. +*/ +DLL_API PaError Pa_GetSampleSize( PaSampleFormat format ); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ +#endif /* PORT_AUDIO_H */ diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_mac/pa_mac.c b/mozilla/zap/zmk/portaudio_v18_1/pa_mac/pa_mac.c new file mode 100755 index 00000000000..ab3fb6be612 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_mac/pa_mac.c @@ -0,0 +1,1687 @@ +/* + * $Id: pa_mac.c,v 1.1.2.1 2005-08-16 20:04:09 alex%croczilla.com Exp $ + * Portable Audio I/O Library for Macintosh + * + * Based on the Open Source API proposed by Ross Bencina + * Copyright (c) 1999-2000 Phil Burk + * + * Special thanks to Chris Rolfe for his many helpful suggestions, bug fixes, + * and code contributions. + * Thanks also to Tue Haste Andersen, Alberto Ricci, Nico Wald, + * Roelf Toxopeus and Tom Erbe for testing the code and making + * numerous suggestions. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +/* Modification History + PLB20010415 - ScanInputDevices was setting sDefaultOutputDeviceID instead of sDefaultInputDeviceID + PLB20010415 - Device Scan was crashing for anything other than siBadSoundInDevice, but some Macs may return other errors! + PLB20010420 - Fix TIMEOUT in record mode. + PLB20010420 - Change CARBON_COMPATIBLE to TARGET_API_MAC_CARBON + PLB20010907 - Pass unused event to WaitNextEvent to prevent Mac OSX crash. Thanks Dominic Mazzoni. + PLB20010908 - Use requested number of input channels. Thanks Dominic Mazzoni. + PLB20011009 - Use NewSndCallBackUPP() for CARBON + PLB20020417 - I used to call Pa_GetMinNumBuffers() which doesn't take into account the + variable minFramesPerHostBuffer. Now I call PaMac_GetMinNumBuffers() which will + give lower latency when virtual memory is turned off. + Thanks Kristoffer Jensen and Georgios Marentakis for spotting this bug. + PLB20020423 - Use new method to calculate CPU load similar to other ports. Based on num frames calculated. + Fixed Pa_StreamTime(). Now estimates how many frames have played based on MicroSecond timer. + Added PA_MAX_USAGE_ALLOWED to prevent Mac from hanging when CPU load approaches 100%. + PLB20020424 - Fixed return value in Pa_StreamTime + PLB20020612 - Fix allocation error on Mac 8600 by casting *nameH as uchar* so that we get a proper Str255 length. +*/ + +/* +COMPATIBILITY +This Macintosh implementation is designed for use with Mac OS 7, 8 and +9 on PowerMacs, and OS X if compiled with CARBON + +OUTPUT +A circular array of CmpSoundHeaders is used as a queue. For low latency situations +there will only be two small buffers used. For higher latency, more and larger buffers +may be used. +To play the sound we use SndDoCommand() with bufferCmd. Each buffer is followed +by a callbackCmd which informs us when the buffer has been processsed. + +INPUT +The SndInput Manager SPBRecord call is used for sound input. If only +input is used, then the PA user callback is called from the Input completion proc. +For full-duplex, or output only operation, the PA callback is called from the +HostBuffer output completion proc. In that case, input sound is passed to the +callback by a simple FIFO. + +TODO: +O- Add support for native sample data formats other than int16. +O- Review buffer sizing. Should it be based on result of siDeviceBufferInfo query? +O- Determine default devices somehow. +*/ +#include +#include +#include +#include +#include + +/* Mac specific includes */ +#include "OSUtils.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "portaudio.h" +#include "pa_host.h" +#include "pa_trace.h" + +#ifndef FALSE + #define FALSE (0) + #define TRUE (!FALSE) +#endif + +/* #define TARGET_API_MAC_CARBON (1) */ + +/* + * Define maximum CPU load that will be allowed. User callback will + * be skipped if load exceeds this limit. This is to prevent the Mac + * from hanging when the CPU is hogged by the sound thread. + * On my PowerBook G3, the mac hung when I used 94% of CPU ( usage = 0.94 ). + */ +#define PA_MAX_USAGE_ALLOWED (0.92) + +/* Debugging output macros. */ +#define PRINT(x) { printf x; fflush(stdout); } +#define ERR_RPT(x) PRINT(x) +#define DBUG(x) /* PRINT(x) */ +#define DBUGX(x) /* PRINT(x) */ + +#define MAC_PHYSICAL_FRAMES_PER_BUFFER (512) /* Minimum number of stereo frames per SoundManager double buffer. */ +#define MAC_VIRTUAL_FRAMES_PER_BUFFER (4096) /* Need this many when using Virtual Memory for recording. */ +#define PA_MIN_NUM_HOST_BUFFERS (2) +#define PA_MAX_NUM_HOST_BUFFERS (16) /* Do not exceed!! */ +#define PA_MAX_DEVICE_INFO (32) + +/* Conversions for 16.16 fixed point code. */ +#define DoubleToUnsignedFixed(x) ((UnsignedFixed) ((x) * 65536.0)) +#define UnsignedFixedToDouble(fx) (((double)(fx)) * (1.0/(1<<16))) + +/************************************************************************************/ +/****************** Structures ******************************************************/ +/************************************************************************************/ +/* Use for passing buffers from input callback to output callback for processing. */ +typedef struct MultiBuffer +{ + char *buffers[PA_MAX_NUM_HOST_BUFFERS]; + int numBuffers; + int nextWrite; + int nextRead; +} +MultiBuffer; + +/* Define structure to contain all Macintosh specific data. */ +typedef struct PaHostSoundControl +{ + UInt64 pahsc_EntryCount; + double pahsc_InverseMicrosPerHostBuffer; /* 1/Microseconds of real-time audio per user buffer. */ + + /* Use char instead of Boolean for atomic operation. */ + volatile char pahsc_IsRecording; /* Recording in progress. Set by foreground. Cleared by background. */ + volatile char pahsc_StopRecording; /* Signal sent to background. */ + volatile char pahsc_IfInsideCallback; + /* Input */ + SPB pahsc_InputParams; + SICompletionUPP pahsc_InputCompletionProc; + MultiBuffer pahsc_InputMultiBuffer; + int32 pahsc_BytesPerInputHostBuffer; + int32 pahsc_InputRefNum; + /* Output */ + CmpSoundHeader pahsc_SoundHeaders[PA_MAX_NUM_HOST_BUFFERS]; + int32 pahsc_BytesPerOutputHostBuffer; + SndChannelPtr pahsc_Channel; + SndCallBackUPP pahsc_OutputCompletionProc; + int32 pahsc_NumOutsQueued; + int32 pahsc_NumOutsPlayed; + PaTimestamp pahsc_NumFramesDone; + UInt64 pahsc_WhenFramesDoneIncremented; + /* Init Time -------------- */ + int32 pahsc_NumHostBuffers; + int32 pahsc_FramesPerHostBuffer; + int32 pahsc_UserBuffersPerHostBuffer; + int32 pahsc_MinFramesPerHostBuffer; /* Can vary depending on virtual memory usage. */ +} +PaHostSoundControl; + +/* Mac specific device information. */ +typedef struct internalPortAudioDevice +{ + long pad_DeviceRefNum; + long pad_DeviceBufferSize; + Component pad_Identifier; + PaDeviceInfo pad_Info; +} +internalPortAudioDevice; + +/************************************************************************************/ +/****************** Data ************************************************************/ +/************************************************************************************/ +static int sNumDevices = 0; +static internalPortAudioDevice sDevices[PA_MAX_DEVICE_INFO] = { 0 }; +static int32 sPaHostError = 0; +static int sDefaultOutputDeviceID; +static int sDefaultInputDeviceID; + +/************************************************************************************/ +/****************** Prototypes ******************************************************/ +/************************************************************************************/ +static PaError PaMac_TimeSlice( internalPortAudioStream *past, int16 *macOutputBufPtr ); +static PaError PaMac_CallUserLoop( internalPortAudioStream *past, int16 *outPtr ); +static PaError PaMac_RecordNext( internalPortAudioStream *past ); +static void PaMac_StartLoadCalculation( internalPortAudioStream *past ); +static int PaMac_GetMinNumBuffers( int minFramesPerHostBuffer, int framesPerBuffer, double sampleRate ); +static double *PaMac_GetSampleRatesFromHandle ( int numRates, Handle h ); +static PaError PaMac_ScanInputDevices( void ); +static PaError PaMac_ScanOutputDevices( void ); +static PaError PaMac_QueryOutputDeviceInfo( Component identifier, internalPortAudioDevice *ipad ); +static PaError PaMac_QueryInputDeviceInfo( Str255 deviceName, internalPortAudioDevice *ipad ); +static void PaMac_InitSoundHeader( internalPortAudioStream *past, CmpSoundHeader *sndHeader ); +static void PaMac_EndLoadCalculation( internalPortAudioStream *past ); +static void PaMac_PlayNext ( internalPortAudioStream *past, int index ); +static long PaMac_FillNextOutputBuffer( internalPortAudioStream *past, int index ); +static pascal void PaMac_InputCompletionProc(SPBPtr recParams); +static pascal void PaMac_OutputCompletionProc (SndChannelPtr theChannel, SndCommand * theCmd); +static PaError PaMac_BackgroundManager( internalPortAudioStream *past, int index ); +long PaHost_GetTotalBufferFrames( internalPortAudioStream *past ); +static int Mac_IsVirtualMemoryOn( void ); +static void PToCString(unsigned char* inString, char* outString); +static void CToPString(char *inString, unsigned char* outString); +char *MultiBuffer_GetNextWriteBuffer( MultiBuffer *mbuf ); +char *MultiBuffer_GetNextReadBuffer( MultiBuffer *mbuf ); +int MultiBuffer_GetNextReadIndex( MultiBuffer *mbuf ); +int MultiBuffer_GetNextWriteIndex( MultiBuffer *mbuf ); +int MultiBuffer_IsWriteable( MultiBuffer *mbuf ); +int MultiBuffer_IsReadable( MultiBuffer *mbuf ); +void MultiBuffer_AdvanceReadIndex( MultiBuffer *mbuf ); +void MultiBuffer_AdvanceWriteIndex( MultiBuffer *mbuf ); + +/************************************************************************* +** Simple FIFO index control for multiple buffers. +** Read and Write indices range from 0 to 2N-1. +** This allows us to distinguish between full and empty. +*/ +char *MultiBuffer_GetNextWriteBuffer( MultiBuffer *mbuf ) +{ + return mbuf->buffers[mbuf->nextWrite % mbuf->numBuffers]; +} +char *MultiBuffer_GetNextReadBuffer( MultiBuffer *mbuf ) +{ + return mbuf->buffers[mbuf->nextRead % mbuf->numBuffers]; +} +int MultiBuffer_GetNextReadIndex( MultiBuffer *mbuf ) +{ + return mbuf->nextRead % mbuf->numBuffers; +} +int MultiBuffer_GetNextWriteIndex( MultiBuffer *mbuf ) +{ + return mbuf->nextWrite % mbuf->numBuffers; +} + +int MultiBuffer_IsWriteable( MultiBuffer *mbuf ) +{ + int bufsFull = mbuf->nextWrite - mbuf->nextRead; + if( bufsFull < 0 ) bufsFull += (2 * mbuf->numBuffers); + return (bufsFull < mbuf->numBuffers); +} +int MultiBuffer_IsReadable( MultiBuffer *mbuf ) +{ + int bufsFull = mbuf->nextWrite - mbuf->nextRead; + if( bufsFull < 0 ) bufsFull += (2 * mbuf->numBuffers); + return (bufsFull > 0); +} +void MultiBuffer_AdvanceReadIndex( MultiBuffer *mbuf ) +{ + int temp = mbuf->nextRead + 1; + mbuf->nextRead = (temp >= (2 * mbuf->numBuffers)) ? 0 : temp; +} +void MultiBuffer_AdvanceWriteIndex( MultiBuffer *mbuf ) +{ + int temp = mbuf->nextWrite + 1; + mbuf->nextWrite = (temp >= (2 * mbuf->numBuffers)) ? 0 : temp; +} + +/************************************************************************* +** String Utility by Chris Rolfe +*/ +static void PToCString(unsigned char* inString, char* outString) +{ + long i; + for(i=0; i 255) + len = 255; + + /* Length is stored in first char of Pascal string */ + outString[0] = (unsigned char)len; + for(i=0; isampleRates; + if( (rates != NULL) ) free( rates ); /* MEM_011 */ + dev->sampleRates = NULL; + if( dev->name != NULL ) free( (void *) dev->name ); /* MEM_010 */ + dev->name = NULL; + } + sNumDevices = 0; + return paNoError; +} + +/************************************************************************* + PaHost_Init() is the library initialization function - call this before + using the library. +*/ +PaError PaHost_Init( void ) +{ + PaError err; + NumVersionVariant version; + + version.parts = SndSoundManagerVersion(); + DBUG(("SndSoundManagerVersion = 0x%x\n", version.whole)); + + /* Have we already initialized the device info? */ + err = (PaError) Pa_CountDevices(); + if( err < 0 ) return err; + else return paNoError; +} + +/************************************************************************* + PaMac_ScanOutputDevices() queries the properties of all output devices. +*/ +static PaError PaMac_ScanOutputDevices( void ) +{ + PaError err; + Component identifier=0; + ComponentDescription criteria = { kSoundOutputDeviceType, 0, 0, 0, 0 }; + long numComponents, i; + + /* Search the system linked list for output components */ + numComponents = CountComponents (&criteria); + identifier = 0; + sDefaultOutputDeviceID = sNumDevices; /* FIXME - query somehow */ + for (i = 0; i < numComponents; i++) + { + /* passing nil returns first matching component. */ + identifier = FindNextComponent( identifier, &criteria); + sDevices[sNumDevices].pad_Identifier = identifier; + + /* Set up for default OUTPUT devices. */ + err = PaMac_QueryOutputDeviceInfo( identifier, &sDevices[sNumDevices] ); + if( err < 0 ) return err; + else sNumDevices++; + + } + + return paNoError; +} + +/************************************************************************* + PaMac_ScanInputDevices() queries the properties of all input devices. +*/ +static PaError PaMac_ScanInputDevices( void ) +{ + Str255 deviceName; + int count; + Handle iconHandle; + PaError err; + OSErr oserr; + count = 1; + sDefaultInputDeviceID = sNumDevices; /* FIXME - query somehow */ /* PLB20010415 - was setting sDefaultOutputDeviceID */ + while(true) + { + /* Thanks Chris Rolfe and Alberto Ricci for this trick. */ + oserr = SPBGetIndexedDevice(count++, deviceName, &iconHandle); + DBUG(("PaMac_ScanInputDevices: SPBGetIndexedDevice returned %d\n", oserr )); +#if 1 + /* PLB20010415 - was giving error for anything other than siBadSoundInDevice, but some Macs may return other errors! */ + if(oserr != noErr) break; /* Some type of error is expected when count > devices */ +#else + if(oserr == siBadSoundInDevice) + { /* it's expected when count > devices */ + oserr = noErr; + break; + } + if(oserr != noErr) + { + ERR_RPT(("ERROR: SPBGetIndexedDevice(%d,,) returned %d\n", count-1, oserr )); + sPaHostError = oserr; + return paHostError; + } +#endif + DisposeHandle(iconHandle); /* Don't need the icon */ + + err = PaMac_QueryInputDeviceInfo( deviceName, &sDevices[sNumDevices] ); + DBUG(("PaMac_ScanInputDevices: PaMac_QueryInputDeviceInfo returned %d\n", err )); + if( err < 0 ) return err; + else if( err == 1 ) sNumDevices++; + } + + return paNoError; +} + +/* Sample rate info returned by using siSampleRateAvailable selector in SPBGetDeviceInfo() */ +/* Thanks to Chris Rolfe for help with this query. */ +#pragma options align=mac68k +typedef struct +{ + int16 numRates; + UnsignedFixed (**rates)[]; /* Handle created by SPBGetDeviceInfo */ +} +SRateInfo; +#pragma options align=reset + +/************************************************************************* +** PaMac_QueryOutputDeviceInfo() +** Query information about a named output device. +** Clears contents of ipad and writes info based on queries. +** Return one if OK, +** zero if device cannot be used, +** or negative error. +*/ +static PaError PaMac_QueryOutputDeviceInfo( Component identifier, internalPortAudioDevice *ipad ) +{ + int len; + OSErr err; + PaDeviceInfo *dev = &ipad->pad_Info; + SRateInfo srinfo = {0}; + int numRates; + ComponentDescription tempD; + Handle nameH=nil, infoH=nil, iconH=nil; + + memset( ipad, 0, sizeof(internalPortAudioDevice) ); + + dev->structVersion = 1; + dev->maxInputChannels = 0; + dev->maxOutputChannels = 2; + dev->nativeSampleFormats = paInt16; /* FIXME - query to see if 24 or 32 bit data can be handled. */ + + /* Get sample rates supported. */ + err = GetSoundOutputInfo(identifier, siSampleRateAvailable, (Ptr) &srinfo); + if(err != noErr) + { + ERR_RPT(("Error in PaMac_QueryOutputDeviceInfo: GetSoundOutputInfo siSampleRateAvailable returned %d\n", err )); + goto error; + } + numRates = srinfo.numRates; + DBUG(("PaMac_QueryOutputDeviceInfo: srinfo.numRates = %d\n", srinfo.numRates )); + if( numRates == 0 ) + { + dev->numSampleRates = -1; + numRates = 2; + } + else + { + dev->numSampleRates = numRates; + } + dev->sampleRates = PaMac_GetSampleRatesFromHandle( numRates, (Handle) srinfo.rates ); + if(dev->sampleRates == NULL) + { + DBUG(("PaMac_QueryOutputDeviceInfo: PaMac_GetSampleRatesFromHandle alloc failed.\n")); + return paInsufficientMemory; + } + + /* SPBGetDeviceInfo created the handle, but it's OUR job to release it. */ + DisposeHandle((Handle) srinfo.rates); + + /* Device name */ + /* we pass an existing handle for the component name; + we don't care about the info (type, subtype, etc.) or icon, so set them to nil */ + DBUG(("PaMac_QueryOutputDeviceInfo: get component name.\n")); + infoH = nil; + iconH = nil; + nameH = NewHandle(0); + if(nameH == nil) return paInsufficientMemory; + err = GetComponentInfo(identifier, &tempD, nameH, infoH, iconH); + if (err) + { + ERR_RPT(("Error in PaMac_QueryOutputDeviceInfo: GetComponentInfo returned %d\n", err )); + goto error; + } + /* Cast as uchar* so that we get a proper pascal string length. */ + len = ((unsigned char *)(*nameH))[0] + 1; /* PLB20020612 - fix allocation error on Mac 8600 */ + DBUG(("PaMac_QueryOutputDeviceInfo: new len = %d\n", len )); + + dev->name = (char *) malloc(len); /* MEM_010 */ + if( dev->name == NULL ) + { + DisposeHandle(nameH); + return paInsufficientMemory; + } + else + { + PToCString((unsigned char *)(*nameH), (char *) dev->name); + DisposeHandle(nameH); + } + + DBUG(("PaMac_QueryOutputDeviceInfo: dev->name = %s\n", dev->name )); + return paNoError; + +error: + sPaHostError = err; + return paHostError; + +} + +/************************************************************************* +** PaMac_QueryInputDeviceInfo() +** Query information about a named input device. +** Clears contents of ipad and writes info based on queries. +** Return one if OK, +** zero if device cannot be used, +** or negative error. +*/ +static PaError PaMac_QueryInputDeviceInfo( Str255 deviceName, internalPortAudioDevice *ipad ) +{ + PaError result = paNoError; + int len; + OSErr err; + long mRefNum = 0; + long tempL; + int16 tempS; + Fixed tempF; + PaDeviceInfo *dev = &ipad->pad_Info; + SRateInfo srinfo = {0}; + int numRates; + + memset( ipad, 0, sizeof(internalPortAudioDevice) ); + dev->maxOutputChannels = 0; + + /* Open device based on name. If device is in use, it may not be able to open in write mode. */ + err = SPBOpenDevice( deviceName, siWritePermission, &mRefNum); + if (err) + { + /* If device is in use, it may not be able to open in write mode so try read mode. */ + err = SPBOpenDevice( deviceName, siReadPermission, &mRefNum); + if (err) + { + ERR_RPT(("Error in PaMac_QueryInputDeviceInfo: SPBOpenDevice returned %d\n", err )); + sPaHostError = err; + return paHostError; + } + } + + /* Define macros for printing out device info. */ +#define PrintDeviceInfo(selector,var) \ + err = SPBGetDeviceInfo(mRefNum, selector, (Ptr) &var); \ + if (err) { \ + DBUG(("query %s failed\n", #selector )); \ + }\ + else { \ + DBUG(("query %s = 0x%x\n", #selector, var )); \ + } + + PrintDeviceInfo( siContinuous, tempS ); + PrintDeviceInfo( siAsync, tempS ); + PrintDeviceInfo( siNumberChannels, tempS ); + PrintDeviceInfo( siSampleSize, tempS ); + PrintDeviceInfo( siSampleRate, tempF ); + PrintDeviceInfo( siChannelAvailable, tempS ); + PrintDeviceInfo( siActiveChannels, tempL ); + PrintDeviceInfo( siDeviceBufferInfo, tempL ); + + err = SPBGetDeviceInfo(mRefNum, siActiveChannels, (Ptr) &tempL); + if (err == 0) DBUG(("%s = 0x%x\n", "siActiveChannels", tempL )); + /* Can we use this device? */ + err = SPBGetDeviceInfo(mRefNum, siAsync, (Ptr) &tempS); + if (err) + { + ERR_RPT(("Error in PaMac_QueryInputDeviceInfo: SPBGetDeviceInfo siAsync returned %d\n", err )); + goto error; + } + if( tempS == 0 ) goto useless; /* Does not support async recording so forget about it. */ + + err = SPBGetDeviceInfo(mRefNum, siChannelAvailable, (Ptr) &tempS); + if (err) + { + ERR_RPT(("Error in PaMac_QueryInputDeviceInfo: SPBGetDeviceInfo siChannelAvailable returned %d\n", err )); + goto error; + } + dev->maxInputChannels = tempS; + + /* Get sample rates supported. */ + err = SPBGetDeviceInfo(mRefNum, siSampleRateAvailable, (Ptr) &srinfo); + if (err) + { + ERR_RPT(("Error in PaMac_QueryInputDeviceInfo: SPBGetDeviceInfo siSampleRateAvailable returned %d\n", err )); + goto error; + } + + numRates = srinfo.numRates; + DBUG(("numRates = 0x%x\n", numRates )); + if( numRates == 0 ) + { + dev->numSampleRates = -1; + numRates = 2; + } + else + { + dev->numSampleRates = numRates; + } + dev->sampleRates = PaMac_GetSampleRatesFromHandle( numRates, (Handle) srinfo.rates ); + /* SPBGetDeviceInfo created the handle, but it's OUR job to release it. */ + DisposeHandle((Handle) srinfo.rates); + + /* Get size of device buffer. */ + err = SPBGetDeviceInfo(mRefNum, siDeviceBufferInfo, (Ptr) &tempL); + if (err) + { + ERR_RPT(("Error in PaMac_QueryInputDeviceInfo: SPBGetDeviceInfo siDeviceBufferInfo returned %d\n", err )); + goto error; + } + ipad->pad_DeviceBufferSize = tempL; + DBUG(("siDeviceBufferInfo = %d\n", tempL )); + + /* Set format based on sample size. */ + err = SPBGetDeviceInfo(mRefNum, siSampleSize, (Ptr) &tempS); + if (err) + { + ERR_RPT(("Error in PaMac_QueryInputDeviceInfo: SPBGetDeviceInfo siSampleSize returned %d\n", err )); + goto error; + } + switch( tempS ) + { + case 0x0020: + dev->nativeSampleFormats = paInt32; /* FIXME - warning, code probably won't support this! */ + break; + case 0x0010: + default: /* FIXME - What about other formats? */ + dev->nativeSampleFormats = paInt16; + break; + } + DBUG(("nativeSampleFormats = %d\n", dev->nativeSampleFormats )); + + /* Device name */ + len = deviceName[0] + 1; /* Get length of Pascal string */ + dev->name = (char *) malloc(len); /* MEM_010 */ + if( dev->name == NULL ) + { + result = paInsufficientMemory; + goto cleanup; + } + PToCString(deviceName, (char *) dev->name); + DBUG(("deviceName = %s\n", dev->name )); + result = (PaError) 1; + /* All done so close up device. */ +cleanup: + if( mRefNum ) SPBCloseDevice(mRefNum); + return result; + +error: + if( mRefNum ) SPBCloseDevice(mRefNum); + sPaHostError = err; + return paHostError; + +useless: + if( mRefNum ) SPBCloseDevice(mRefNum); + return (PaError) 0; +} + +/************************************************************************* +** Allocate a double array and fill it with listed sample rates. +*/ +static double * PaMac_GetSampleRatesFromHandle ( int numRates, Handle h ) +{ + OSErr err = noErr; + SInt8 hState; + int i; + UnsignedFixed *fixedRates; + double *rates = (double *) malloc( numRates * sizeof(double) ); /* MEM_011 */ + if( rates == NULL ) return NULL; + /* Save and restore handle state as suggested by TechNote at: + http://developer.apple.com/technotes/tn/tn1122.html + */ + hState = HGetState (h); + if (!(err = MemError ())) + { + HLock (h); + if (!(err = MemError ( ))) + { + fixedRates = (UInt32 *) *h; + for( i=0; i= Pa_CountDevices()) ) return NULL; + return &sDevices[id].pad_Info; +} +/*************************************************************************/ +PaDeviceID Pa_GetDefaultInputDeviceID( void ) +{ + return sDefaultInputDeviceID; +} + +/*************************************************************************/ +PaDeviceID Pa_GetDefaultOutputDeviceID( void ) +{ + return sDefaultOutputDeviceID; +} + +/********************************* BEGIN CPU UTILIZATION MEASUREMENT ****/ +static void PaMac_StartLoadCalculation( internalPortAudioStream *past ) +{ + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + UnsignedWide widePad; + if( pahsc == NULL ) return; + /* Query system timer for usage analysis and to prevent overuse of CPU. */ + Microseconds( &widePad ); + pahsc->pahsc_EntryCount = UnsignedWideToUInt64( widePad ); +} + +/****************************************************************************** +** Measure fractional CPU load based on real-time it took to calculate +** buffers worth of output. +*/ +/**************************************************************************/ +static void PaMac_EndLoadCalculation( internalPortAudioStream *past ) +{ + UnsignedWide widePad; + UInt64 currentCount; + long usecsElapsed; + double newUsage; + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + if( pahsc == NULL ) return; + + /* Measure CPU utilization during this callback. Note that this calculation + ** assumes that we had the processor the whole time. + */ +#define LOWPASS_COEFFICIENT_0 (0.95) +#define LOWPASS_COEFFICIENT_1 (0.99999 - LOWPASS_COEFFICIENT_0) + Microseconds( &widePad ); + currentCount = UnsignedWideToUInt64( widePad ); + + usecsElapsed = (long) U64Subtract(currentCount, pahsc->pahsc_EntryCount); + + /* Use inverse because it is faster than the divide. */ + newUsage = usecsElapsed * pahsc->pahsc_InverseMicrosPerHostBuffer; + + past->past_Usage = (LOWPASS_COEFFICIENT_0 * past->past_Usage) + + (LOWPASS_COEFFICIENT_1 * newUsage); + +} + +/*********************************************************************** +** Called by Pa_StartStream() +*/ +PaError PaHost_StartInput( internalPortAudioStream *past ) +{ + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + pahsc->pahsc_IsRecording = 0; + pahsc->pahsc_StopRecording = 0; + pahsc->pahsc_InputMultiBuffer.nextWrite = 0; + pahsc->pahsc_InputMultiBuffer.nextRead = 0; + return PaMac_RecordNext( past ); +} + +/*********************************************************************** +** Called by Pa_StopStream(). +** May be called during error recovery or cleanup code +** so protect against NULL pointers. +*/ +PaError PaHost_StopInput( internalPortAudioStream *past, int abort ) +{ + int32 timeOutMsec; + PaError result = paNoError; + OSErr err = 0; + long mRefNum; + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + if( pahsc == NULL ) return paNoError; + + (void) abort; + + mRefNum = pahsc->pahsc_InputRefNum; + + DBUG(("PaHost_StopInput: mRefNum = %d\n", mRefNum )); + if( mRefNum ) + { + DBUG(("PaHost_StopInput: pahsc_IsRecording = %d\n", pahsc->pahsc_IsRecording )); + if( pahsc->pahsc_IsRecording ) + { + /* PLB20010420 - Fix TIMEOUT in record mode. */ + pahsc->pahsc_StopRecording = 1; /* Request that we stop recording. */ + err = SPBStopRecording(mRefNum); + DBUG(("PaHost_StopInput: then pahsc_IsRecording = %d\n", pahsc->pahsc_IsRecording )); + + /* Calculate timeOut longer than longest time it could take to play one buffer. */ + timeOutMsec = (int32) ((1500.0 * pahsc->pahsc_FramesPerHostBuffer) / past->past_SampleRate); + /* Keep querying sound channel until it is no longer busy playing. */ + while( !err && pahsc->pahsc_IsRecording && (timeOutMsec > 0)) + { + Pa_Sleep(20); + timeOutMsec -= 20; + } + if( timeOutMsec <= 0 ) + { + ERR_RPT(("PaHost_StopInput: timed out!\n")); + return paTimedOut; + } + } + } + if( err ) + { + sPaHostError = err; + result = paHostError; + } + + DBUG(("PaHost_StopInput: finished.\n", mRefNum )); + return result; +} + +/***********************************************************************/ +static void PaMac_InitSoundHeader( internalPortAudioStream *past, CmpSoundHeader *sndHeader ) +{ + sndHeader->numChannels = past->past_NumOutputChannels; + sndHeader->sampleRate = DoubleToUnsignedFixed(past->past_SampleRate); + sndHeader->loopStart = 0; + sndHeader->loopEnd = 0; + sndHeader->encode = cmpSH; + sndHeader->baseFrequency = kMiddleC; + sndHeader->markerChunk = nil; + sndHeader->futureUse2 = nil; + sndHeader->stateVars = nil; + sndHeader->leftOverSamples = nil; + sndHeader->compressionID = 0; + sndHeader->packetSize = 0; + sndHeader->snthID = 0; + sndHeader->sampleSize = 8 * sizeof(int16); // FIXME - might be 24 or 32 bits some day; + sndHeader->sampleArea[0] = 0; + sndHeader->format = kSoundNotCompressed; +} + +static void SetFramesDone( PaHostSoundControl *pahsc, PaTimestamp framesDone ) +{ + UnsignedWide now; + Microseconds( &now ); + pahsc->pahsc_NumFramesDone = framesDone; + pahsc->pahsc_WhenFramesDoneIncremented = UnsignedWideToUInt64( now ); +} + +/***********************************************************************/ +PaError PaHost_StartOutput( internalPortAudioStream *past ) +{ + SndCommand pauseCommand; + SndCommand resumeCommand; + int i; + OSErr error; + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + if( pahsc == NULL ) return paInternalError; + if( pahsc->pahsc_Channel == NULL ) return paInternalError; + + past->past_StopSoon = 0; + past->past_IsActive = 1; + pahsc->pahsc_NumOutsQueued = 0; + pahsc->pahsc_NumOutsPlayed = 0; + + SetFramesDone( pahsc, 0.0 ); + + /* Pause channel so it does not do back ground processing while we are still filling the queue. */ + pauseCommand.cmd = pauseCmd; + pauseCommand.param1 = pauseCommand.param2 = 0; + error = SndDoCommand (pahsc->pahsc_Channel, &pauseCommand, true); + if (noErr != error) goto exit; + + /* Queue all of the buffers so we start off full. */ + for (i = 0; ipahsc_NumHostBuffers; i++) + { + PaMac_PlayNext( past, i ); + } + + /* Resume channel now that the queue is full. */ + resumeCommand.cmd = resumeCmd; + resumeCommand.param1 = resumeCommand.param2 = 0; + error = SndDoImmediate( pahsc->pahsc_Channel, &resumeCommand ); + if (noErr != error) goto exit; + + return paNoError; +exit: + past->past_IsActive = 0; + sPaHostError = error; + ERR_RPT(("Error in PaHost_StartOutput: SndDoCommand returned %d\n", error )); + return paHostError; +} + +/*******************************************************************/ +long PaHost_GetTotalBufferFrames( internalPortAudioStream *past ) +{ + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + return (long) (pahsc->pahsc_NumHostBuffers * pahsc->pahsc_FramesPerHostBuffer); +} + +/*********************************************************************** +** Called by Pa_StopStream(). +** May be called during error recovery or cleanup code +** so protect against NULL pointers. +*/ +PaError PaHost_StopOutput( internalPortAudioStream *past, int abort ) +{ + int32 timeOutMsec; + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + if( pahsc == NULL ) return paNoError; + if( pahsc->pahsc_Channel == NULL ) return paNoError; + + DBUG(("PaHost_StopOutput()\n")); + if( past->past_IsActive == 0 ) return paNoError; + + /* Set flags for callback function to see. */ + if( abort ) past->past_StopNow = 1; + past->past_StopSoon = 1; + /* Calculate timeOut longer than longest time it could take to play all buffers. */ + timeOutMsec = (int32) ((1500.0 * PaHost_GetTotalBufferFrames( past )) / past->past_SampleRate); + /* Keep querying sound channel until it is no longer busy playing. */ + while( past->past_IsActive && (timeOutMsec > 0)) + { + Pa_Sleep(20); + timeOutMsec -= 20; + } + if( timeOutMsec <= 0 ) + { + ERR_RPT(("PaHost_StopOutput: timed out!\n")); + return paTimedOut; + } + else return paNoError; +} + +/***********************************************************************/ +PaError PaHost_StartEngine( internalPortAudioStream *past ) +{ + (void) past; /* Prevent unused variable warnings. */ + return paNoError; +} + +/***********************************************************************/ +PaError PaHost_StopEngine( internalPortAudioStream *past, int abort ) +{ + (void) past; /* Prevent unused variable warnings. */ + (void) abort; /* Prevent unused variable warnings. */ + return paNoError; +} +/***********************************************************************/ +PaError PaHost_StreamActive( internalPortAudioStream *past ) +{ + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + return (PaError) ( past->past_IsActive + pahsc->pahsc_IsRecording ); +} +int Mac_IsVirtualMemoryOn( void ) +{ + long attr; + OSErr result = Gestalt( gestaltVMAttr, &attr ); + DBUG(("gestaltVMAttr : 0x%x\n", attr )); + return ((attr >> gestaltVMHasPagingControl ) & 1); +} + +/******************************************************************* +* Determine number of host Buffers +* and how many User Buffers we can put into each host buffer. +*/ +static void PaHost_CalcNumHostBuffers( internalPortAudioStream *past ) +{ + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + int32 minNumBuffers; + int32 minFramesPerHostBuffer; + int32 minTotalFrames; + int32 userBuffersPerHostBuffer; + int32 framesPerHostBuffer; + int32 numHostBuffers; + + minFramesPerHostBuffer = pahsc->pahsc_MinFramesPerHostBuffer; + minFramesPerHostBuffer = (minFramesPerHostBuffer + 7) & ~7; + DBUG(("PaHost_CalcNumHostBuffers: minFramesPerHostBuffer = %d\n", minFramesPerHostBuffer )); + + /* Determine number of user buffers based on minimum latency. */ + /* PLB20020417 I used to call Pa_GetMinNumBuffers() which doesn't take into account the + ** variable minFramesPerHostBuffer. Now I call PaMac_GetMinNumBuffers() which will + ** gove lower latency when virtual memory is turned off. */ + /* minNumBuffers = Pa_GetMinNumBuffers( past->past_FramesPerUserBuffer, past->past_SampleRate ); WRONG */ + minNumBuffers = PaMac_GetMinNumBuffers( minFramesPerHostBuffer, past->past_FramesPerUserBuffer, past->past_SampleRate ); + + past->past_NumUserBuffers = ( minNumBuffers > past->past_NumUserBuffers ) ? minNumBuffers : past->past_NumUserBuffers; + DBUG(("PaHost_CalcNumHostBuffers: min past_NumUserBuffers = %d\n", past->past_NumUserBuffers )); + minTotalFrames = past->past_NumUserBuffers * past->past_FramesPerUserBuffer; + + /* We cannot make the buffers too small because they may not get serviced quickly enough. */ + if( (int32) past->past_FramesPerUserBuffer < minFramesPerHostBuffer ) + { + userBuffersPerHostBuffer = + (minFramesPerHostBuffer + past->past_FramesPerUserBuffer - 1) / + past->past_FramesPerUserBuffer; + } + else + { + userBuffersPerHostBuffer = 1; + } + framesPerHostBuffer = past->past_FramesPerUserBuffer * userBuffersPerHostBuffer; + + /* Calculate number of host buffers needed. Round up to cover minTotalFrames. */ + numHostBuffers = (minTotalFrames + framesPerHostBuffer - 1) / framesPerHostBuffer; + /* Make sure we have enough host buffers. */ + if( numHostBuffers < PA_MIN_NUM_HOST_BUFFERS) + { + numHostBuffers = PA_MIN_NUM_HOST_BUFFERS; + } + else + { + /* If we have too many host buffers, try to put more user buffers in a host buffer. */ + while(numHostBuffers > PA_MAX_NUM_HOST_BUFFERS) + { + userBuffersPerHostBuffer += 1; + framesPerHostBuffer = past->past_FramesPerUserBuffer * userBuffersPerHostBuffer; + numHostBuffers = (minTotalFrames + framesPerHostBuffer - 1) / framesPerHostBuffer; + } + } + + pahsc->pahsc_UserBuffersPerHostBuffer = userBuffersPerHostBuffer; + pahsc->pahsc_FramesPerHostBuffer = framesPerHostBuffer; + pahsc->pahsc_NumHostBuffers = numHostBuffers; + DBUG(("PaHost_CalcNumHostBuffers: pahsc_UserBuffersPerHostBuffer = %d\n", pahsc->pahsc_UserBuffersPerHostBuffer )); + DBUG(("PaHost_CalcNumHostBuffers: pahsc_NumHostBuffers = %d\n", pahsc->pahsc_NumHostBuffers )); + DBUG(("PaHost_CalcNumHostBuffers: pahsc_FramesPerHostBuffer = %d\n", pahsc->pahsc_FramesPerHostBuffer )); + DBUG(("PaHost_CalcNumHostBuffers: past_NumUserBuffers = %d\n", past->past_NumUserBuffers )); +} + +/*******************************************************************/ +PaError PaHost_OpenStream( internalPortAudioStream *past ) +{ + OSErr err; + PaError result = paHostError; + PaHostSoundControl *pahsc; + int i; + /* Allocate and initialize host data. */ + pahsc = (PaHostSoundControl *) PaHost_AllocateFastMemory(sizeof(PaHostSoundControl)); + if( pahsc == NULL ) + { + return paInsufficientMemory; + } + past->past_DeviceData = (void *) pahsc; + + /* If recording, and virtual memory is turned on, then use bigger buffers to prevent glitches. */ + if( (past->past_NumInputChannels > 0) && Mac_IsVirtualMemoryOn() ) + { + pahsc->pahsc_MinFramesPerHostBuffer = MAC_VIRTUAL_FRAMES_PER_BUFFER; + } + else + { + pahsc->pahsc_MinFramesPerHostBuffer = MAC_PHYSICAL_FRAMES_PER_BUFFER; + } + + PaHost_CalcNumHostBuffers( past ); + + /* Setup constants for CPU load measurement. */ + pahsc->pahsc_InverseMicrosPerHostBuffer = past->past_SampleRate / (1000000.0 * pahsc->pahsc_FramesPerHostBuffer); + + /* ------------------ OUTPUT */ + if( past->past_NumOutputChannels > 0 ) + { + /* Create sound channel to which we can send commands. */ + pahsc->pahsc_Channel = 0L; + err = SndNewChannel(&pahsc->pahsc_Channel, sampledSynth, 0, nil); /* FIXME - use kUseOptionalOutputDevice if not default. */ + if(err != 0) + { + ERR_RPT(("Error in PaHost_OpenStream: SndNewChannel returned 0x%x\n", err )); + goto error; + } + + /* Install our callback function pointer straight into the sound channel structure */ + /* Use new CARBON name for callback procedure. */ +#if TARGET_API_MAC_CARBON + pahsc->pahsc_OutputCompletionProc = NewSndCallBackUPP(PaMac_OutputCompletionProc); +#else + pahsc->pahsc_OutputCompletionProc = NewSndCallBackProc(PaMac_OutputCompletionProc); +#endif + + pahsc->pahsc_Channel->callBack = pahsc->pahsc_OutputCompletionProc; + + pahsc->pahsc_BytesPerOutputHostBuffer = pahsc->pahsc_FramesPerHostBuffer * past->past_NumOutputChannels * sizeof(int16); + for (i = 0; ipahsc_NumHostBuffers; i++) + { + char *buf = (char *)PaHost_AllocateFastMemory(pahsc->pahsc_BytesPerOutputHostBuffer); + if (buf == NULL) + { + ERR_RPT(("Error in PaHost_OpenStream: could not allocate output buffer. Size = \n", pahsc->pahsc_BytesPerOutputHostBuffer )); + goto memerror; + } + + PaMac_InitSoundHeader( past, &pahsc->pahsc_SoundHeaders[i] ); + pahsc->pahsc_SoundHeaders[i].samplePtr = buf; + pahsc->pahsc_SoundHeaders[i].numFrames = (unsigned long) pahsc->pahsc_FramesPerHostBuffer; + + } + } +#ifdef SUPPORT_AUDIO_CAPTURE + /* ------------------ INPUT */ + /* Use double buffer scheme that matches output. */ + if( past->past_NumInputChannels > 0 ) + { + int16 tempS; + long tempL; + Fixed tempF; + long mRefNum; + Str255 namePString; +#if TARGET_API_MAC_CARBON + pahsc->pahsc_InputCompletionProc = NewSICompletionUPP((SICompletionProcPtr)PaMac_InputCompletionProc); +#else + pahsc->pahsc_InputCompletionProc = NewSICompletionProc((ProcPtr)PaMac_InputCompletionProc); +#endif + pahsc->pahsc_BytesPerInputHostBuffer = pahsc->pahsc_FramesPerHostBuffer * past->past_NumInputChannels * sizeof(int16); + for (i = 0; ipahsc_NumHostBuffers; i++) + { + char *buf = (char *) PaHost_AllocateFastMemory(pahsc->pahsc_BytesPerInputHostBuffer); + if ( buf == NULL ) + { + ERR_RPT(("PaHost_OpenStream: could not allocate input buffer. Size = \n", pahsc->pahsc_BytesPerInputHostBuffer )); + goto memerror; + } + pahsc->pahsc_InputMultiBuffer.buffers[i] = buf; + } + pahsc->pahsc_InputMultiBuffer.numBuffers = pahsc->pahsc_NumHostBuffers; + + // err = SPBOpenDevice( (const unsigned char *) &noname, siWritePermission, &mRefNum); + CToPString((char *)sDevices[past->past_InputDeviceID].pad_Info.name, namePString); + err = SPBOpenDevice(namePString, siWritePermission, &mRefNum); + + if (err) goto error; + pahsc->pahsc_InputRefNum = mRefNum; + DBUG(("PaHost_OpenStream: mRefNum = %d\n", mRefNum )); + + /* Set input device characteristics. */ + tempS = 1; + err = SPBSetDeviceInfo(mRefNum, siContinuous, (Ptr) &tempS); + if (err) + { + ERR_RPT(("Error in PaHost_OpenStream: SPBSetDeviceInfo siContinuous returned %d\n", err )); + goto error; + } + + tempL = 0x03; + err = SPBSetDeviceInfo(mRefNum, siActiveChannels, (Ptr) &tempL); + if (err) + { + DBUG(("PaHost_OpenStream: setting siActiveChannels returned 0x%x. Error ignored.\n", err )); + } + + /* PLB20010908 - Use requested number of input channels. Thanks Dominic Mazzoni. */ + tempS = past->past_NumInputChannels; + err = SPBSetDeviceInfo(mRefNum, siNumberChannels, (Ptr) &tempS); + if (err) + { + ERR_RPT(("Error in PaHost_OpenStream: SPBSetDeviceInfo siNumberChannels returned %d\n", err )); + goto error; + } + + tempF = ((unsigned long)past->past_SampleRate) << 16; + err = SPBSetDeviceInfo(mRefNum, siSampleRate, (Ptr) &tempF); + if (err) + { + ERR_RPT(("Error in PaHost_OpenStream: SPBSetDeviceInfo siSampleRate returned %d\n", err )); + goto error; + } + + /* Setup record-parameter block */ + pahsc->pahsc_InputParams.inRefNum = mRefNum; + pahsc->pahsc_InputParams.milliseconds = 0; // not used + pahsc->pahsc_InputParams.completionRoutine = pahsc->pahsc_InputCompletionProc; + pahsc->pahsc_InputParams.interruptRoutine = 0; + pahsc->pahsc_InputParams.userLong = (long) past; + pahsc->pahsc_InputParams.unused1 = 0; + } +#endif /* SUPPORT_AUDIO_CAPTURE */ + DBUG(("PaHost_OpenStream: complete.\n")); + return paNoError; + +error: + PaHost_CloseStream( past ); + ERR_RPT(("PaHost_OpenStream: sPaHostError = 0x%x.\n", err )); + sPaHostError = err; + return paHostError; + +memerror: + PaHost_CloseStream( past ); + return paInsufficientMemory; +} + +/*********************************************************************** +** Called by Pa_CloseStream(). +** May be called during error recovery or cleanup code +** so protect against NULL pointers. +*/ +PaError PaHost_CloseStream( internalPortAudioStream *past ) +{ + PaError result = paNoError; + OSErr err = 0; + int i; + PaHostSoundControl *pahsc; + + DBUG(("PaHost_CloseStream( 0x%x )\n", past )); + + if( past == NULL ) return paBadStreamPtr; + + pahsc = (PaHostSoundControl *) past->past_DeviceData; + if( pahsc == NULL ) return paNoError; + + if( past->past_NumOutputChannels > 0 ) + { + /* TRUE means flush now instead of waiting for quietCmd to be processed. */ + if( pahsc->pahsc_Channel != NULL ) SndDisposeChannel(pahsc->pahsc_Channel, TRUE); + { + for (i = 0; ipahsc_NumHostBuffers; i++) + { + Ptr p = (Ptr) pahsc->pahsc_SoundHeaders[i].samplePtr; + if( p != NULL ) PaHost_FreeFastMemory( p, pahsc->pahsc_BytesPerOutputHostBuffer ); + } + } + } + + if( past->past_NumInputChannels > 0 ) + { + if( pahsc->pahsc_InputRefNum ) + { + err = SPBCloseDevice(pahsc->pahsc_InputRefNum); + pahsc->pahsc_InputRefNum = 0; + if( err ) + { + sPaHostError = err; + result = paHostError; + } + } + { + for (i = 0; ipahsc_InputMultiBuffer.numBuffers; i++) + { + Ptr p = (Ptr) pahsc->pahsc_InputMultiBuffer.buffers[i]; + if( p != NULL ) PaHost_FreeFastMemory( p, pahsc->pahsc_BytesPerInputHostBuffer ); + } + } + } + + past->past_DeviceData = NULL; + PaHost_FreeFastMemory( pahsc, sizeof(PaHostSoundControl) ); + + DBUG(("PaHost_CloseStream: complete.\n", past )); + return result; +} +/*************************************************************************/ +int Pa_GetMinNumBuffers( int framesPerUserBuffer, double sampleRate ) +{ +/* We use the MAC_VIRTUAL_FRAMES_PER_BUFFER because we might be recording. +** This routine doesn't have enough information to determine the best value +** and is being depracated. */ + return PaMac_GetMinNumBuffers( MAC_VIRTUAL_FRAMES_PER_BUFFER, framesPerUserBuffer, sampleRate ); +} +/*************************************************************************/ +static int PaMac_GetMinNumBuffers( int minFramesPerHostBuffer, int framesPerUserBuffer, double sampleRate ) +{ + int minUserPerHost = ( minFramesPerHostBuffer + framesPerUserBuffer - 1) / framesPerUserBuffer; + int numBufs = PA_MIN_NUM_HOST_BUFFERS * minUserPerHost; + if( numBufs < PA_MIN_NUM_HOST_BUFFERS ) numBufs = PA_MIN_NUM_HOST_BUFFERS; + (void) sampleRate; + return numBufs; +} + +/*************************************************************************/ +void Pa_Sleep( int32 msec ) +{ + EventRecord event; + int32 sleepTime, endTime; + /* Convert to ticks. Round up so we sleep a MINIMUM of msec time. */ + sleepTime = ((msec * 60) + 999) / 1000; + if( sleepTime < 1 ) sleepTime = 1; + endTime = TickCount() + sleepTime; + do + { + DBUGX(("Sleep for %d ticks.\n", sleepTime )); + /* Use WaitNextEvent() to sleep without getting events. */ + /* PLB20010907 - Pass unused event to WaitNextEvent instead of NULL to prevent + * Mac OSX crash. Thanks Dominic Mazzoni. */ + WaitNextEvent( 0, &event, sleepTime, NULL ); + sleepTime = endTime - TickCount(); + } + while( sleepTime > 0 ); +} +/*************************************************************************/ +int32 Pa_GetHostError( void ) +{ + int32 err = sPaHostError; + sPaHostError = 0; + return err; +} + +/************************************************************************* + * Allocate memory that can be accessed in real-time. + * This may need to be held in physical memory so that it is not + * paged to virtual memory. + * This call MUST be balanced with a call to PaHost_FreeFastMemory(). + */ +void *PaHost_AllocateFastMemory( long numBytes ) +{ + void *addr = NewPtrClear( numBytes ); + if( (addr == NULL) || (MemError () != 0) ) return NULL; + +#if (TARGET_API_MAC_CARBON == 0) + if( HoldMemory( addr, numBytes ) != noErr ) + { + DisposePtr( (Ptr) addr ); + return NULL; + } +#endif + return addr; +} + +/************************************************************************* + * Free memory that could be accessed in real-time. + * This call MUST be balanced with a call to PaHost_AllocateFastMemory(). + */ +void PaHost_FreeFastMemory( void *addr, long numBytes ) +{ + if( addr == NULL ) return; +#if TARGET_API_MAC_CARBON + (void) numBytes; +#else + UnholdMemory( addr, numBytes ); +#endif + DisposePtr( (Ptr) addr ); +} + +/*************************************************************************/ +PaTimestamp Pa_StreamTime( PortAudioStream *stream ) +{ + PaTimestamp framesDone1; + PaTimestamp framesDone2; + UInt64 whenIncremented; + UnsignedWide now; + UInt64 now64; + long microsElapsed; + long framesElapsed; + + PaHostSoundControl *pahsc; + internalPortAudioStream *past = (internalPortAudioStream *) stream; + if( past == NULL ) return paBadStreamPtr; + pahsc = (PaHostSoundControl *) past->past_DeviceData; + +/* Capture information from audio thread. + * We have to be careful that we don't get interrupted in the middle. + * So we grab the pahsc_NumFramesDone twice and make sure it didn't change. + */ + do + { + framesDone1 = pahsc->pahsc_NumFramesDone; + whenIncremented = pahsc->pahsc_WhenFramesDoneIncremented; + framesDone2 = pahsc->pahsc_NumFramesDone; + } while( framesDone1 != framesDone2 ); + + /* Calculate how many microseconds have elapsed and convert to frames. */ + Microseconds( &now ); + now64 = UnsignedWideToUInt64( now ); + microsElapsed = U64Subtract( now64, whenIncremented ); + framesElapsed = microsElapsed * past->past_SampleRate * 0.000001; + + return framesDone1 + framesElapsed; +} + +/************************************************************************** +** Callback for Input, SPBRecord() +*/ +int gRecordCounter = 0; +int gPlayCounter = 0; +pascal void PaMac_InputCompletionProc(SPBPtr recParams) +{ + PaError result = paNoError; + int finished = 1; + internalPortAudioStream *past; + PaHostSoundControl *pahsc; + + gRecordCounter += 1; /* debug hack to see if engine running */ + + /* Get our PA data from Mac structure. */ + past = (internalPortAudioStream *) recParams->userLong; + if( past == NULL ) return; + + if( past->past_Magic != PA_MAGIC ) + { + AddTraceMessage("PaMac_InputCompletionProc: bad MAGIC, past", (long) past ); + AddTraceMessage("PaMac_InputCompletionProc: bad MAGIC, magic", (long) past->past_Magic ); + goto error; + } + pahsc = (PaHostSoundControl *) past->past_DeviceData; + past->past_NumCallbacks += 1; + + /* Have we been asked to stop recording? */ + if( (recParams->error == abortErr) || pahsc->pahsc_StopRecording ) goto error; + + /* If there are no output channels, then we need to call the user callback function from here. + * Otherwise we will call the user code during the output completion routine. + */ + if(past->past_NumOutputChannels == 0) + { + SetFramesDone( pahsc, + pahsc->pahsc_NumFramesDone + pahsc->pahsc_FramesPerHostBuffer ); + result = PaMac_CallUserLoop( past, NULL ); + } + + /* Did user code ask us to stop? If not, issue another recording request. */ + if( (result == paNoError) && (pahsc->pahsc_StopRecording == 0) ) + { + result = PaMac_RecordNext( past ); + if( result != paNoError ) pahsc->pahsc_IsRecording = 0; + } + else goto error; + + return; + +error: + pahsc->pahsc_IsRecording = 0; + pahsc->pahsc_StopRecording = 0; + return; +} + +/*********************************************************************** +** Called by either input or output completion proc. +** Grabs input data if any present, and calls PA conversion code, +** that in turn calls user code. +*/ +static PaError PaMac_CallUserLoop( internalPortAudioStream *past, int16 *outPtr ) +{ + PaError result = paNoError; + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + int16 *inPtr = NULL; + int i; + + + /* Advance read index for sound input FIFO here, independantly of record/write process. */ + if(past->past_NumInputChannels > 0) + { + if( MultiBuffer_IsReadable( &pahsc->pahsc_InputMultiBuffer ) ) + { + inPtr = (int16 *) MultiBuffer_GetNextReadBuffer( &pahsc->pahsc_InputMultiBuffer ); + MultiBuffer_AdvanceReadIndex( &pahsc->pahsc_InputMultiBuffer ); + } + } + + /* Call user code enough times to fill buffer. */ + if( (inPtr != NULL) || (outPtr != NULL) ) + { + PaMac_StartLoadCalculation( past ); /* CPU usage */ + +#ifdef PA_MAX_USAGE_ALLOWED + /* If CPU usage exceeds limit, skip user callback to prevent hanging CPU. */ + if( past->past_Usage > PA_MAX_USAGE_ALLOWED ) + { + past->past_FrameCount += (PaTimestamp) pahsc->pahsc_FramesPerHostBuffer; + } + else +#endif + { + + for( i=0; ipahsc_UserBuffersPerHostBuffer; i++ ) + { + result = (PaError) Pa_CallConvertInt16( past, inPtr, outPtr ); + if( result != 0) + { + /* Recording might be in another process, so tell it to stop with a flag. */ + pahsc->pahsc_StopRecording = pahsc->pahsc_IsRecording; + break; + } + /* Advance sample pointers. */ + if(inPtr != NULL) inPtr += past->past_FramesPerUserBuffer * past->past_NumInputChannels; + if(outPtr != NULL) outPtr += past->past_FramesPerUserBuffer * past->past_NumOutputChannels; + } + } + + PaMac_EndLoadCalculation( past ); + } + return result; +} + +/*********************************************************************** +** Setup next recording buffer in FIFO and issue recording request to Snd Input Manager. +*/ +static PaError PaMac_RecordNext( internalPortAudioStream *past ) +{ + PaError result = paNoError; + OSErr err; + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + /* Get pointer to next buffer to record into. */ + pahsc->pahsc_InputParams.bufferPtr = MultiBuffer_GetNextWriteBuffer( &pahsc->pahsc_InputMultiBuffer ); + + /* Advance write index if there is room. Otherwise keep writing same buffer. */ + if( MultiBuffer_IsWriteable( &pahsc->pahsc_InputMultiBuffer ) ) + { + MultiBuffer_AdvanceWriteIndex( &pahsc->pahsc_InputMultiBuffer ); + } + + AddTraceMessage("PaMac_RecordNext: bufferPtr", (long) pahsc->pahsc_InputParams.bufferPtr ); + AddTraceMessage("PaMac_RecordNext: nextWrite", pahsc->pahsc_InputMultiBuffer.nextWrite ); + + /* Setup parameters and issue an asynchronous recording request. */ + pahsc->pahsc_InputParams.bufferLength = pahsc->pahsc_BytesPerInputHostBuffer; + pahsc->pahsc_InputParams.count = pahsc->pahsc_BytesPerInputHostBuffer; + err = SPBRecord(&pahsc->pahsc_InputParams, true); + if( err ) + { + AddTraceMessage("PaMac_RecordNext: SPBRecord error ", err ); + sPaHostError = err; + result = paHostError; + } + else + { + pahsc->pahsc_IsRecording = 1; + } + return result; +} + +/************************************************************************** +** Callback for Output Playback() +** Return negative error, 0 to continue, 1 to stop. +*/ +long PaMac_FillNextOutputBuffer( internalPortAudioStream *past, int index ) +{ + PaHostSoundControl *pahsc; + long result = 0; + int finished = 1; + char *outPtr; + + gPlayCounter += 1; /* debug hack */ + + past->past_NumCallbacks += 1; + pahsc = (PaHostSoundControl *) past->past_DeviceData; + if( pahsc == NULL ) return -1; + /* Are we nested?! */ + if( pahsc->pahsc_IfInsideCallback ) return 0; + pahsc->pahsc_IfInsideCallback = 1; + /* Get pointer to buffer to fill. */ + outPtr = pahsc->pahsc_SoundHeaders[index].samplePtr; + /* Combine with any sound input, and call user callback. */ + result = PaMac_CallUserLoop( past, (int16 *) outPtr ); + + pahsc->pahsc_IfInsideCallback = 0; + return result; +} + +/************************************************************************************* +** Called by SoundManager when ready for another buffer. +*/ +static pascal void PaMac_OutputCompletionProc (SndChannelPtr theChannel, SndCommand * theCallBackCmd) +{ + internalPortAudioStream *past; + PaHostSoundControl *pahsc; + (void) theChannel; + (void) theCallBackCmd; + + /* Get our data from Mac structure. */ + past = (internalPortAudioStream *) theCallBackCmd->param2; + if( past == NULL ) return; + + pahsc = (PaHostSoundControl *) past->past_DeviceData; + pahsc->pahsc_NumOutsPlayed += 1; + + SetFramesDone( pahsc, + pahsc->pahsc_NumFramesDone + pahsc->pahsc_FramesPerHostBuffer ); + + PaMac_BackgroundManager( past, theCallBackCmd->param1 ); +} + +/*******************************************************************/ +static PaError PaMac_BackgroundManager( internalPortAudioStream *past, int index ) +{ + PaError result = paNoError; + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + /* Has someone asked us to abort by calling Pa_AbortStream()? */ + if( past->past_StopNow ) + { + SndCommand command; + /* Clear the queue of any pending commands. */ + command.cmd = flushCmd; + command.param1 = command.param2 = 0; + SndDoImmediate( pahsc->pahsc_Channel, &command ); + /* Then stop currently playing buffer, if any. */ + command.cmd = quietCmd; + SndDoImmediate( pahsc->pahsc_Channel, &command ); + past->past_IsActive = 0; + } + /* Has someone asked us to stop by calling Pa_StopStream() + * OR has a user callback returned '1' to indicate finished. + */ + else if( past->past_StopSoon ) + { + if( (pahsc->pahsc_NumOutsQueued - pahsc->pahsc_NumOutsPlayed) <= 0 ) + { + past->past_IsActive = 0; /* We're finally done. */ + } + } + else + { + PaMac_PlayNext( past, index ); + } + return result; +} + +/************************************************************************************* +** Fill next buffer with sound and queue it for playback. +*/ +static void PaMac_PlayNext ( internalPortAudioStream *past, int index ) +{ + OSErr error; + long result; + SndCommand playCmd; + SndCommand callbackCmd; + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + + /* If this was the last buffer, or abort requested, then just be done. */ + if ( past->past_StopSoon ) goto done; + + /* Load buffer with sound. */ + result = PaMac_FillNextOutputBuffer ( past, index ); + if( result > 0 ) past->past_StopSoon = 1; /* Stop generating audio but wait until buffers play. */ + else if( result < 0 ) goto done; + + /* Play the next buffer. */ + playCmd.cmd = bufferCmd; + playCmd.param1 = 0; + playCmd.param2 = (long) &pahsc->pahsc_SoundHeaders[ index ]; + error = SndDoCommand (pahsc->pahsc_Channel, &playCmd, true ); + if( error != noErr ) goto gotError; + + /* Ask for a callback when it is done. */ + callbackCmd.cmd = callBackCmd; + callbackCmd.param1 = index; + callbackCmd.param2 = (long)past; + error = SndDoCommand (pahsc->pahsc_Channel, &callbackCmd, true ); + if( error != noErr ) goto gotError; + pahsc->pahsc_NumOutsQueued += 1; + + return; + +gotError: + sPaHostError = error; +done: + return; +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_mac_core/notes.txt b/mozilla/zap/zmk/portaudio_v18_1/pa_mac_core/notes.txt new file mode 100755 index 00000000000..19d3422c362 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_mac_core/notes.txt @@ -0,0 +1,34 @@ +Notes on Core Audio Implementation of PortAudio + +by Phil Burk and Darren Gibbs + +Document last updated October 18, 2002 + +WHAT WORKS + +Output with very low latency, <10 msec. +Half duplex input or output. +Full duplex +The paFLoat32, paInt16, paInt8, paUInt8 sample formats. +Pa_GetCPULoad() +Pa_StreamTime() + +KNOWN BUGS OR LIMITATIONS + +The iMic supports multiple sample rates. +But there is a bug when changing sample rates: + Run patest_record.c at rate A - it works. + Then run patest_record.c at rate B - it FAIL! + Then run patest_record.c again at rate B - it works! + + +DEVICE MAPPING + +CoreAudio devices can support both input and output. But the sample +rates supported may be different. So we have map one or two PortAudio +device to each CoreAudio device depending on whether it supports +input, output or both. + +When we query devices, we first get a list of CoreAudio devices. Then +we scan the list and add a PortAudio device for each CoreAudio device +that supports input. Then we make a scan for output devices. diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_mac_core/pa_mac_core.c b/mozilla/zap/zmk/portaudio_v18_1/pa_mac_core/pa_mac_core.c new file mode 100755 index 00000000000..83192fe9bbf --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_mac_core/pa_mac_core.c @@ -0,0 +1,2203 @@ +/* + * $Id: pa_mac_core.c,v 1.1.2.1 2005-08-16 20:04:10 alex%croczilla.com Exp $ + * pa_mac_core.c + * Implementation of PortAudio for Mac OS X Core Audio + * + * PortAudio Portable Real-Time Audio Library + * Latest Version at: http://www.portaudio.com + * + * Authors: Ross Bencina and Phil Burk + * Copyright (c) 1999-2002 Ross Bencina and Phil Burk + * + * Theory of Operation + * + * This code uses the HAL (Hardware Access Layer) of the Apple CoreAudio library. + * This is the layer closes to the hardware. + * The HAL layer only supports the native HW supported sample rates. + * So if the chip only supports 44100 Hz, then the HAL only supports 44100. + * To provide other rates we use the handy Apple AudioConverter which provides + * sample rate conversion, mono-to-stereo conversion, and buffer size adaptation. + * + * There are four modes of operation: + * PA_MODE_OUTPUT_ONLY, + * PA_MODE_INPUT_ONLY, + * PA_MODE_IO_ONE_DEVICE, + * PA_MODE_IO_TWO_DEVICES + * + * The processing pipeline for PA_MODE_IO_ONE_DEVICE is in one thread: + * + * PaOSX_CoreAudioIOCallback() input buffers -> RingBuffer -> input.AudioConverter -> + * PortAudio callback -> output.AudioConverter -> PaOSX_CoreAudioIOCallback() output buffers + * + * For two separate devices, we have to use two separate callbacks. + * We pass data between them using a RingBuffer FIFO. + * The processing pipeline for PA_MODE_IO_TWO_DEVICES is split into two threads: + * + * PaOSX_CoreAudioInputCallback() input buffers -> RingBuffer + * + * RingBuffer -> input.AudioConverter -> + * PortAudio callback -> output.AudioConverter -> PaOSX_CoreAudioIOCallback() output buffers + * + * License + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * CHANGE HISTORY: + + 3.29.2001 - Phil Burk - First pass... converted from Window MME code with help from Darren. + 3.30.2001 - Darren Gibbs - Added more support for dynamically querying device info. + 12.7.2001 - Gord Peters - Tweaks to compile on PA V17 and OS X 10.1 + 2.7.2002 - Darren and Phil - fixed isInput so GetProperty works better, + fixed device queries for numChannels and sampleRates, + one CoreAudio device now maps to separate input and output PaDevices, + audio input works if using same CoreAudio device (some HW devices make separate CoreAudio devices). + 2.22.2002 - Stephane Letz - Explicit cast needed for compilation with Code Warrior 7 + 3.19.2002 - Phil Burk - Added paInt16, paInt8, format using new "pa_common/pa_convert.c" file. + Return error if opened in mono mode cuz not supported. [Supported 10.12.2002] + Add support for Pa_GetCPULoad(); + Fixed timestamp in callback and Pa_StreamTime() (Thanks n++k for the advice!) + Check for invalid sample rates and return an error. + Check for getenv("PA_MIN_LATENCY_MSEC") to set latency externally. + Better error checking for invalid channel counts and invalid devices. + 3.29.2002 - Phil Burk - Fixed Pa_GetCPULoad() for small buffers. + 3.31.2002 - Phil Burk - Use getrusage() instead of gettimeofday() for CPU Load calculation. + 10.12.2002 - Phil Burk - Use AudioConverter to allow wide range of sample rates, and mono. + Use FIFO (from pablio/rinbuffer.h) so that we can pull data through converter. + Added PaOSX_FixVolumeScalar() to make iMic audible. + 10.17.2002 - Phil Burk - Support full duplex between two different devices. + Name internal functions PaOSX_* + Dumped useless PA_MIN_LATENCY_MSEC environment variable. + Use kAudioDevicePropertyStreamFormatMatch to determine max channels. + 02.03.2003 - Phil Burk - always use AudioConverters so that we can adapt when format changes. + Synchronize with device when format changes. + 02.13.2003 - Phil Burk - scan for maxChannels because FormatMatch won't tell us. + 03.05.2003 - Phil Burk and Dominic Mazzoni - interleave and deinterleave multiple + CoreAudio buffers. Needed for MOTU828 and some other N>2 channel devices. + See code related to "streamInterleavingBuffer". + 03.06.2003 - Phil Burk and Ryan Francesconi - fixed numChannels query for MOTU828. + Handle fact that MOTU828 gives you 8 channels even when you ask for 2! + 04.06.2003 - Phil Burk - Combine Dominic Mazzoni's technique of using Configuration to query maxChannels + with old technique of scanning for mormat. + Increase channel scan by 1 to handle mono USB microphones. + Do not merge or split channels in AudioConverter to handle 2+2 channels + of Quattro which has a format of 2 channels. + 04.07.2003 - Phil Burk - use AudioGetCurrentHostTime instead of getrusage() which can lock threads. + 04.10.2003 - Phil Burk - fixed pointer bug with input deinterleaving loop. + Detect and ignore NULL inputData and outputData in CodeAudio callback. + Overlap creation and deletion of AudioConverters to prevent thread death when device rate changes. + 04.16.2003 - Phil Burk - Fixed input channel scrambling when numChannels != 2^N. Caused by alignment + error when filling RingBuffer with 2^N zero bytes. +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "portaudio.h" +#include "pa_host.h" +#include "pa_trace.h" +#include "ringbuffer.h" + +/************************************************* Configuration ********/ +#define PA_ENABLE_LOAD_MEASUREMENT (1) + +/************************************************* Constants ********/ +#define SET_DEVICE_BUFFER_SIZE (1) + +/* To trace program, enable TRACE_REALTIME_EVENTS in pa_trace.h */ +#define PA_TRACE_RUN (0) +#define PA_TRACE_START_STOP (0) + +#define PA_MIN_LATENCY_MSEC (20) /* FIXME */ +#define MIN_TIMEOUT_MSEC (3000) + +#define PRINT(x) { printf x; fflush(stdout); } +#define PRINT_ERR( msg, err ) PRINT(( msg ": error = 0x%0lX = '%s'\n", (err), ErrorToString(err)) ) +#define DBUG(x) /* PRINT(x) */ +#define DBUGBACK(x) /* if( sMaxBackgroundErrorMessages-- > 0 ) PRINT(x) */ +#define DBUGX(x) + +// define value of isInput passed to CoreAudio routines +#define IS_INPUT (true) +#define IS_OUTPUT (false) + +typedef enum PaDeviceMode +{ + PA_MODE_OUTPUT_ONLY, + PA_MODE_INPUT_ONLY, + PA_MODE_IO_ONE_DEVICE, + PA_MODE_IO_TWO_DEVICES +} PaDeviceMode; + +#define PA_USING_OUTPUT (pahsc->mode != PA_MODE_INPUT_ONLY) +#define PA_USING_INPUT (pahsc->mode != PA_MODE_OUTPUT_ONLY) + +/************************************************************** + * Information needed by PortAudio specific to a CoreAudio device. + */ +typedef struct PaHostInOut_s +{ + AudioDeviceID audioDeviceID; /* CoreAudio specific ID */ + int bytesPerUserNativeBuffer; /* User buffer size in native host format. Depends on numChannels. */ + AudioConverterRef converter; + void *converterBuffer; + int numChannels; + /** Used for interleaving or de-interleaving multiple streams for devices like MOTU828. */ + int streamInterleavingBufferLen; /**< size in bytes */ + Float32 *streamInterleavingBuffer; +} PaHostInOut; + +/************************************************************** + * Structure for internal host specific stream data. + * This is allocated on a per stream basis. + */ +typedef struct PaHostSoundControl +{ + PaHostInOut input; + PaHostInOut output; + AudioDeviceID primaryDeviceID; + PaDeviceMode mode; + RingBuffer ringBuffer; + char *ringBufferData; + Boolean formatListenerCalled; + /* For measuring CPU utilization. */ + UInt64 entryTime; + double inverseHostTicksPerBuffer; /* 1/Ticks of real-time audio per user buffer. */ +} PaHostSoundControl; + +/************************************************************** + * Structure for internal extended device info query. + * There will be one or two PortAudio devices for each Core Audio device: + * one input and or one output. + */ +typedef struct PaHostDeviceInfo +{ + PaDeviceInfo paInfo; + AudioDeviceID audioDeviceID; +} +PaHostDeviceInfo; + +/************************************************* Shared Data ********/ +/* FIXME - put Mutex around this shared data. */ +static int sNumPaDevices = 0; /* Total number of PaDeviceInfos */ +static int sNumInputDevices = 0; /* Total number of input PaDeviceInfos */ +static int sNumOutputDevices = 0; +static int sNumCoreDevices = 0; +static AudioDeviceID *sCoreDeviceIDs; // Array of Core AudioDeviceIDs +static PaHostDeviceInfo *sDeviceInfos = NULL; +static int sDefaultInputDeviceID = paNoDevice; +static int sDefaultOutputDeviceID = paNoDevice; +static int sSavedHostError = 0; + +static const double supportedSampleRateRange[] = { 8000.0, 96000.0 }; /* FIXME - go to double HW rate. */ +static const char sMapperSuffixInput[] = " - Input"; +static const char sMapperSuffixOutput[] = " - Output"; + +/* Debug support. */ +//static int sMaxBackgroundErrorMessages = 100; +//static int sCoverageCounter = 1; // used to check code coverage during validation + +/* We index the input devices first, then the output devices. */ +#define LOWEST_INPUT_DEVID (0) +#define HIGHEST_INPUT_DEVID (sNumInputDevices - 1) +#define LOWEST_OUTPUT_DEVID (sNumInputDevices) +#define HIGHEST_OUTPUT_DEVID (sNumPaDevices - 1) + +/************************************************* Macros ********/ + +/************************************************* Prototypes **********/ + +static PaError PaOSX_QueryDevices( void ); +static int PaOSX_ScanDevices( Boolean isInput ); +static int PaOSX_QueryDeviceInfo( PaHostDeviceInfo *hostDeviceInfo, int coreDeviceIndex, Boolean isInput ); +static PaDeviceID PaOSX_QueryDefaultInputDevice( void ); +static PaDeviceID PaOSX_QueryDefaultOutputDevice( void ); +static void PaOSX_CalcHostBufferSize( internalPortAudioStream *past ); + +static OSStatus PAOSX_DevicePropertyListener (AudioDeviceID inDevice, + UInt32 inChannel, + Boolean isInput, + AudioDevicePropertyID inPropertyID, + void* inClientData); + +/**********************************************************************/ +/* OS X errors are 4 character ID that can be printed. + * Note that uses a static pad so result must be printed immediately. + */ +static OSStatus statusText[2] = { 0, 0 }; +static const char *ErrorToString( OSStatus err ) +{ + const char *str; + + switch (err) + { + case kAudioHardwareUnspecifiedError: + str = "kAudioHardwareUnspecifiedError"; + break; + case kAudioHardwareNotRunningError: + str = "kAudioHardwareNotRunningError"; + break; + case kAudioHardwareUnknownPropertyError: + str = "kAudioHardwareUnknownPropertyError"; + break; + case kAudioDeviceUnsupportedFormatError: + str = "kAudioDeviceUnsupportedFormatError"; + break; + case kAudioHardwareBadPropertySizeError: + str = "kAudioHardwareBadPropertySizeError"; + break; + case kAudioHardwareIllegalOperationError: + str = "kAudioHardwareIllegalOperationError"; + break; + default: + statusText[0] = err; + str = (const char *)statusText; + break; + } + + return str; +} + +/**********************************************************************/ +static unsigned long RoundUpToNextPowerOf2( unsigned long n ) +{ + long numBits = 0; + if( ((n-1) & n) == 0) return n; /* Already Power of two. */ + while( n > 0 ) + { + n= n>>1; + numBits++; + } + return (1<past_DeviceData; + if( pahsc == NULL ) return; + /* Query user CPU timer for usage analysis and to prevent overuse of CPU. */ + pahsc->entryTime = AudioGetCurrentHostTime(); +} + +/****************************************************************************** +** Measure fractional CPU load based on real-time it took to calculate +** buffers worth of output. +*/ +static void Pa_EndUsageCalculation( internalPortAudioStream *past ) +{ + UInt64 exitTime; + UInt64 ticksElapsed; + double newUsage; + +#define LOWPASS_COEFFICIENT_0 (0.95) +#define LOWPASS_COEFFICIENT_1 (0.99999 - LOWPASS_COEFFICIENT_0) + + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + if( pahsc == NULL ) return; + + exitTime = AudioGetCurrentHostTime(); + + ticksElapsed = exitTime - pahsc->entryTime; + + /* Use inverse because it is faster than the divide. */ + newUsage = ticksElapsed * pahsc->inverseHostTicksPerBuffer; + /* Low pass filter result. */ + past->past_Usage = (LOWPASS_COEFFICIENT_0 * past->past_Usage) + + (LOWPASS_COEFFICIENT_1 * newUsage); +} +/****************************************** END CPU UTILIZATION *******/ + +/************************************************************************/ +static PaDeviceID PaOSX_QueryDefaultInputDevice( void ) +{ + OSStatus err = noErr; + UInt32 count; + int i; + AudioDeviceID tempDeviceID = kAudioDeviceUnknown; + PaDeviceID defaultDeviceID = paNoDevice; + + // get the default output device for the HAL + // it is required to pass the size of the data to be returned + count = sizeof(tempDeviceID); + err = AudioHardwareGetProperty( kAudioHardwarePropertyDefaultInputDevice, &count, (void *) &tempDeviceID); + if (err != noErr) goto error; + + // scan input devices to see which one matches this device + defaultDeviceID = paNoDevice; + for( i=LOWEST_INPUT_DEVID; i<=HIGHEST_INPUT_DEVID; i++ ) + { + DBUG(("PaOSX_QueryDefaultInputDevice: i = %d, aDevId = %ld\n", i, sDeviceInfos[i].audioDeviceID )); + if( sDeviceInfos[i].audioDeviceID == tempDeviceID ) + { + defaultDeviceID = i; + break; + } + } +error: + return defaultDeviceID; +} + +/************************************************************************/ +static PaDeviceID PaOSX_QueryDefaultOutputDevice( void ) +{ + OSStatus err = noErr; + UInt32 count; + int i; + AudioDeviceID tempDeviceID = kAudioDeviceUnknown; + PaDeviceID defaultDeviceID = paNoDevice; + + // get the default output device for the HAL + // it is required to pass the size of the data to be returned + count = sizeof(tempDeviceID); + err = AudioHardwareGetProperty( kAudioHardwarePropertyDefaultOutputDevice, &count, (void *) &tempDeviceID); + if (err != noErr) goto error; + + // scan output devices to see which one matches this device + defaultDeviceID = paNoDevice; + for( i=LOWEST_OUTPUT_DEVID; i<=HIGHEST_OUTPUT_DEVID; i++ ) + { + DBUG(("PaOSX_QueryDefaultOutputDevice: i = %d, aDevId = %ld\n", i, sDeviceInfos[i].audioDeviceID )); + if( sDeviceInfos[i].audioDeviceID == tempDeviceID ) + { + defaultDeviceID = i; + break; + } + } +error: + return defaultDeviceID; +} + +/******************************************************************/ +static PaError PaOSX_QueryDevices( void ) +{ + OSStatus err = noErr; + UInt32 outSize; + Boolean outWritable; + int numBytes; + + // find out how many Core Audio devices there are, if any + outSize = sizeof(outWritable); + err = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &outSize, &outWritable); + if (err != noErr) + { + PRINT_ERR("Couldn't get info about list of audio devices", err); + sSavedHostError = err; + return paHostError; + } + + // calculate the number of device available + sNumCoreDevices = outSize / sizeof(AudioDeviceID); + + // Bail if there aren't any devices + if (sNumCoreDevices < 1) + { + PRINT(("No Devices Available")); + return paHostError; + } + + // make space for the devices we are about to get + sCoreDeviceIDs = (AudioDeviceID *)malloc(outSize); + + // get an array of AudioDeviceIDs + err = AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &outSize, (void *)sCoreDeviceIDs); + if (err != noErr) + { + PRINT_ERR("Couldn't get list of audio device IDs", err); + sSavedHostError = err; + return paHostError; + } + + // Allocate structures to hold device info pointers. + // There will be a maximum of two Pa devices per Core Audio device, input and/or output. + numBytes = sNumCoreDevices * 2 * sizeof(PaHostDeviceInfo); + sDeviceInfos = (PaHostDeviceInfo *) PaHost_AllocateFastMemory( numBytes ); + if( sDeviceInfos == NULL ) return paInsufficientMemory; + + // Scan all the Core Audio devices to see which support input and allocate a + // PaHostDeviceInfo structure for each one. + DBUG(("PaOSX_QueryDevices: scan for input ======================\n")); + PaOSX_ScanDevices( IS_INPUT ); + sNumInputDevices = sNumPaDevices; + // Now scan all the output devices. + DBUG(("PaOSX_QueryDevices: scan for output ======================\n")); + PaOSX_ScanDevices( IS_OUTPUT ); + sNumOutputDevices = sNumPaDevices - sNumInputDevices; + + // Figure out which of the devices that we scanned is the default device. + sDefaultInputDeviceID = PaOSX_QueryDefaultInputDevice(); + sDefaultOutputDeviceID = PaOSX_QueryDefaultOutputDevice(); + + return paNoError; +} + + +/*************************************************************************/ +/* Query a device for its sample rate. + * @return positive rate or 0.0 on error. + */ +static Float64 PaOSX_GetDeviceSampleRate( AudioDeviceID deviceID, Boolean isInput ) +{ + OSStatus err = noErr; + AudioStreamBasicDescription formatDesc; + UInt32 dataSize; + dataSize = sizeof(formatDesc); + err = AudioDeviceGetProperty( deviceID, 0, isInput, + kAudioDevicePropertyStreamFormat, &dataSize, &formatDesc); + if( err != noErr ) return 0.0; + else return formatDesc.mSampleRate; +} + +/*************************************************************************/ +/* Allocate a string containing the device name. */ +static char *PaOSX_DeviceNameFromID(AudioDeviceID deviceID, Boolean isInput ) +{ + OSStatus err = noErr; + UInt32 outSize; + Boolean outWritable; + char *deviceName = nil; + + // query size of name + err = AudioDeviceGetPropertyInfo(deviceID, 0, isInput, kAudioDevicePropertyDeviceName, &outSize, &outWritable); + if (err == noErr) + { + deviceName = (char*)malloc( outSize + 1); + if( deviceName ) + { + err = AudioDeviceGetProperty(deviceID, 0, isInput, kAudioDevicePropertyDeviceName, &outSize, deviceName); + if (err != noErr) + PRINT_ERR("Couldn't get audio device name", err); + } + } + + return deviceName; +} + +/************************************************************************* +** Scan all of the Core Audio devices to see which support selected +** input or output mode. +** Changes sNumDevices, and fills in sDeviceInfos. +*/ +static int PaOSX_ScanDevices( Boolean isInput ) +{ + int coreDeviceIndex; + int result; + PaHostDeviceInfo *hostDeviceInfo; + int numAdded = 0; + + for( coreDeviceIndex=0; coreDeviceIndex 0 ) + { + sNumPaDevices += 1; // bump global counter if we got one + numAdded += 1; + } + else if( result < 0 ) return result; + } + return numAdded; +} + +/************************************************************************* +** Determine the maximum number of channels based on the configuration. +** @return maxChannels or negative error. +*/ +static int PaOSX_GetMaxChannels_Config( AudioDeviceID devID, Boolean isInput ) +{ + OSStatus err; + UInt32 outSize; + Boolean outWritable; + AudioBufferList *list; + int numChannels; + int i; + + // Determine maximum number of channels supported. + // dmazzoni: new method + + outSize = 0; + err = AudioDeviceGetPropertyInfo(devID, 0, isInput, + kAudioDevicePropertyStreamConfiguration, + &outSize, &outWritable); + if ( err != noErr ) + { + PRINT_ERR("PaOSX_GetMaxChannels_Config: Could not get stream configuration info", err); + sSavedHostError = err; + return paHostError; + } + + list = (AudioBufferList *)PaHost_AllocateFastMemory( outSize ); + err = AudioDeviceGetProperty(devID, 0, isInput, + kAudioDevicePropertyStreamConfiguration, + &outSize, list); + if ( err != noErr ) + { + PRINT_ERR("PaOSX_GetMaxChannels_Config: Could not get stream configuration", err); + sSavedHostError = err; + return paHostError; + } + + numChannels = 0; + for( i=0; imNumberBuffers; i++ ) + { + int bufChannels = list->mBuffers[i].mNumberChannels; + DBUG(("PaOSX_GetMaxChannels_Config: buffer %d has %d channels.\n", i, bufChannels )); + numChannels += bufChannels; + } + + PaHost_FreeFastMemory( list, outSize ); + + return numChannels; +} + +/************************************************************************* +** Determine the maximum number of channels a device will support based on scanning the format. +** @return maxChannels or negative error. +*/ +static int PaOSX_GetMaxChannels_Format( AudioDeviceID devID, Boolean isInput ) +{ + OSStatus err; + UInt32 outSize; + AudioStreamBasicDescription formatDesc; + int maxChannels; + int numChannels; + Boolean gotMax; + + // Scan to find highest matching format. + // Unfortunately some devices won't just return maxChannels for the match. + // For example, some 8 channel devices return 2 when given 256 as input. + gotMax = false; + maxChannels = 0; + numChannels = 0; + while( !gotMax ) + { + + memset( &formatDesc, 0, sizeof(formatDesc)); + numChannels = numChannels + 1; + DBUG(("PaOSX_GetMaxChannels: try numChannels = %d = %d + 1\n", + numChannels, numChannels )); + formatDesc.mChannelsPerFrame = numChannels; + outSize = sizeof(formatDesc); + + err = AudioDeviceGetProperty( devID, 0, + isInput, kAudioDevicePropertyStreamFormatMatch, &outSize, &formatDesc); + + DBUG(("PaOSX_GetMaxChannels: err 0x%0x, formatDesc.mChannelsPerFrame= %d\n", + err, formatDesc.mChannelsPerFrame )); + if( err != noErr ) + { + if (numChannels > (maxChannels + 4)) // Try several possibilities above current max + { + gotMax = true; + } + } + else + { + // This value worked so we have a new candidate for maxChannels. + if (formatDesc.mChannelsPerFrame > numChannels) + { + maxChannels = formatDesc.mChannelsPerFrame; + } + else if(formatDesc.mChannelsPerFrame < numChannels) + { + if (numChannels > (maxChannels + 4)) // Try several possibilities above current max + { + gotMax = true; + } + } + else + { + maxChannels = numChannels; + } + } + } + return maxChannels; +} + + + +/************************************************************************* +** Determine the maximum number of channels a device will support. +** It is not clear at this point which the better technique so +** we do both and use the biggest result. +** +** @return maxChannels or negative error. +*/ +static int PaOSX_GetMaxChannels( AudioDeviceID devID, Boolean isInput ) +{ + int maxChannelsFormat; + int maxChannelsConfig; + maxChannelsFormat = PaOSX_GetMaxChannels_Format( devID, isInput ); + maxChannelsConfig = PaOSX_GetMaxChannels_Config( devID, isInput ); + return (maxChannelsFormat > maxChannelsConfig) ? maxChannelsFormat : maxChannelsConfig; +} + +/************************************************************************* +** Try to fill in the device info for this device. +** Return 1 if a good device that PA can use. +** Return 0 if not appropriate +** or return negative error. +** +*/ +static int PaOSX_QueryDeviceInfo( PaHostDeviceInfo *hostDeviceInfo, int coreDeviceIndex, Boolean isInput ) +{ + OSStatus err; + UInt32 outSize; + AudioStreamBasicDescription formatDesc; + AudioDeviceID devID; + PaDeviceInfo *deviceInfo = &hostDeviceInfo->paInfo; + int maxChannels; + + deviceInfo->structVersion = 1; + deviceInfo->maxInputChannels = 0; + deviceInfo->maxOutputChannels = 0; + + deviceInfo->sampleRates = supportedSampleRateRange; // because we use sample rate converter to get continuous rates + deviceInfo->numSampleRates = -1; + + devID = sCoreDeviceIDs[ coreDeviceIndex ]; + hostDeviceInfo->audioDeviceID = devID; + DBUG(("PaOSX_QueryDeviceInfo: coreDeviceIndex = %d, devID = %d, isInput = %d\n", + coreDeviceIndex, (int) devID, isInput )); + + // Get data format info from the device. + outSize = sizeof(formatDesc); + err = AudioDeviceGetProperty(devID, 0, isInput, kAudioDevicePropertyStreamFormat, &outSize, &formatDesc); + // This just may not be an appropriate device for input or output so leave quietly. + if( (err != noErr) || (formatDesc.mChannelsPerFrame == 0) ) goto error; + + DBUG(("PaOSX_QueryDeviceInfo: mFormatID = 0x%x\n", (unsigned int) formatDesc.mFormatID)); + DBUG(("PaOSX_QueryDeviceInfo: mFormatFlags = 0x%x\n",(unsigned int) formatDesc.mFormatFlags)); + + // Right now the Core Audio headers only define one formatID: LinearPCM + // Apparently LinearPCM must be Float32 for now. + if( (formatDesc.mFormatID == kAudioFormatLinearPCM) && + ((formatDesc.mFormatFlags & kLinearPCMFormatFlagIsFloat) != 0) ) + { + deviceInfo->nativeSampleFormats = paFloat32; + } + else + { + PRINT(("PaOSX_QueryDeviceInfo: ERROR - not LinearPCM & Float32!!!\n")); + return paSampleFormatNotSupported; + } + + maxChannels = PaOSX_GetMaxChannels( devID, isInput ); + if( maxChannels <= 0 ) goto error; + if( isInput ) + { + deviceInfo->maxInputChannels = maxChannels; + } + else + { + deviceInfo->maxOutputChannels = maxChannels; + } + + // Get the device name + deviceInfo->name = PaOSX_DeviceNameFromID( devID, isInput ); + DBUG(("PaOSX_QueryDeviceInfo: name = %s\n", deviceInfo->name )); + return 1; + +error: + return 0; +} + +/**********************************************************************/ +static PaError PaOSX_MaybeQueryDevices( void ) +{ + if( sNumPaDevices == 0 ) + { + return PaOSX_QueryDevices(); + } + return 0; +} + +static char zeroPad[256] = { 0 }; + +/********************************************************************** +** This is the proc that supplies the data to the AudioConverterFillBuffer call. +** We can pass back arbitrarily sized blocks so if the FIFO region is split +** just pass back the first half. +*/ +static OSStatus PaOSX_InputConverterCallbackProc (AudioConverterRef inAudioConverter, + UInt32* outDataSize, + void** outData, + void* inUserData) +{ + internalPortAudioStream *past = (internalPortAudioStream *) inUserData; + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + void *dataPtr1; + long size1; + void *dataPtr2; + long size2; + + /* Pass contiguous region from FIFO directly to converter. */ + RingBuffer_GetReadRegions( &pahsc->ringBuffer, *outDataSize, + &dataPtr1, &size1, &dataPtr2, &size2 ); + + if( size1 > 0 ) + { + *outData = dataPtr1; + *outDataSize = size1; + RingBuffer_AdvanceReadIndex( &pahsc->ringBuffer, size1 ); + DBUGX(("PaOSX_InputConverterCallbackProc: read %ld bytes from FIFO.\n", size1 )); + } + else + { + DBUGBACK(("PaOSX_InputConverterCallbackProc: got no data!\n")); + *outData = zeroPad; /* Give it zero data to keep it happy. */ + *outDataSize = sizeof(zeroPad); + } + return noErr; +} + +/***************************************************************************** +** Get audio input, if any, from passed in buffer, or from converter or from FIFO, +** then run PA callback and output data. +*/ +static OSStatus PaOSX_LoadAndProcess( internalPortAudioStream *past, + void *inputBuffer, void *outputBuffer ) +{ + OSStatus err = noErr; + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + + if( past->past_StopSoon ) + { + if( outputBuffer ) + { + /* Clear remainder of audio buffer if we are waiting for stop. */ + AddTraceMessage("PaOSX_LoadAndProcess: zero rest of wave buffer ", i ); + memset( outputBuffer, 0, pahsc->output.bytesPerUserNativeBuffer ); + } + } + else + { + /* Do we need data from the converted input? */ + if( PA_USING_INPUT ) + { + UInt32 size = pahsc->input.bytesPerUserNativeBuffer; + err = AudioConverterFillBuffer( + pahsc->input.converter, + PaOSX_InputConverterCallbackProc, + past, + &size, + pahsc->input.converterBuffer); + if( err != noErr ) return err; + inputBuffer = pahsc->input.converterBuffer; + } + + /* Measure CPU load. */ +#if PA_ENABLE_LOAD_MEASUREMENT + Pa_StartUsageCalculation( past ); +#endif + + /* Fill part of audio converter buffer by converting input to user format, + * calling user callback, then converting output to native format. */ + if( PaConvert_Process( past, inputBuffer, outputBuffer )) + { + past->past_StopSoon = 1; + } + +#if PA_ENABLE_LOAD_MEASUREMENT + Pa_EndUsageCalculation( past ); +#endif + + } + return err; +} + +/***************************************************************************** +** This is the proc that supplies the data to the AudioConverterFillBuffer call +*/ +static OSStatus PaOSX_OutputConverterCallbackProc (AudioConverterRef inAudioConverter, + UInt32* outDataSize, + void** outData, + void* inUserData) +{ + internalPortAudioStream *past = (internalPortAudioStream *) inUserData; + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + + *outData = pahsc->output.converterBuffer; + *outDataSize = pahsc->output.bytesPerUserNativeBuffer; + + return PaOSX_LoadAndProcess ( past, pahsc->input.converterBuffer, pahsc->output.converterBuffer ); +} + +/********************************************************************** +** If data available, write it to the Ring Buffer so we can +** pull it from the other side. +*/ +static OSStatus PaOSX_WriteInputRingBuffer( internalPortAudioStream *past, + const AudioBufferList* inInputData ) +{ + int numBytes = 0; + int currentInterleavedChannelIndex; + int numFramesInInputBuffer; + int numInterleavedChannels; + int numChannelsRemaining; + int i; + long writeRoom; + char *inputNativeBufferfPtr = NULL; + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + + /* Do we need to deinterleave the buffers first? */ + if( past->past_NumInputChannels != inInputData->mBuffers[0].mNumberChannels ) + { + numFramesInInputBuffer = inInputData->mBuffers[0].mDataByteSize / + (sizeof(float) * inInputData->mBuffers[0].mNumberChannels); + + numBytes = numFramesInInputBuffer * sizeof(float) * past->past_NumInputChannels; + + /* Allocate temporary buffer if needed. */ + if ( (pahsc->input.streamInterleavingBuffer != NULL) && + (pahsc->input.streamInterleavingBufferLen < numBytes) ) + { + PaHost_FreeFastMemory( pahsc->input.streamInterleavingBuffer, pahsc->input.streamInterleavingBufferLen ); + pahsc->input.streamInterleavingBuffer = NULL; + } + if ( pahsc->input.streamInterleavingBuffer == NULL ) + { + pahsc->input.streamInterleavingBufferLen = numBytes; + pahsc->input.streamInterleavingBuffer = (float *)PaHost_AllocateFastMemory( pahsc->input.streamInterleavingBufferLen ); + } + + /* Perform interleaving by writing to temp buffer. */ + currentInterleavedChannelIndex = 0; + numInterleavedChannels = past->past_NumInputChannels; + numChannelsRemaining = numInterleavedChannels; + + for( i=0; imNumberBuffers; i++ ) + { + int j; + int numBufChannels = inInputData->mBuffers[i].mNumberChannels; + /* Don't use more than we need or more than we have. */ + int numChannelsUsedInThisBuffer = (numChannelsRemaining < numBufChannels ) ? + numChannelsRemaining : numBufChannels; + for( j=0; jinput.streamInterleavingBuffer[ currentInterleavedChannelIndex ]; + float *src = &((float *)inInputData->mBuffers[i].mData)[ j ]; + /* Move one channel from CoreAudio buffer to interleaved buffer. */ + for( k=0; kinput.streamInterleavingBuffer; + } + else + { + inputNativeBufferfPtr = (char*)inInputData->mBuffers[0].mData; + numBytes = inInputData->mBuffers[0].mDataByteSize; + } + + writeRoom = RingBuffer_GetWriteAvailable( &pahsc->ringBuffer ); + + if( numBytes <= writeRoom ) + { + RingBuffer_Write( &pahsc->ringBuffer, inputNativeBufferfPtr, numBytes ); + DBUGBACK(("PaOSX_WriteInputRingBuffer: wrote %ld bytes to FIFO.\n", numBytes)); + } // FIXME else drop samples on floor, remember overflow??? + + return noErr; +} + +/********************************************************************** +** Use any available input buffers by writing to RingBuffer. +** Process input if PA_MODE_INPUT_ONLY. +*/ +static OSStatus PaOSX_HandleInput( internalPortAudioStream *past, + const AudioBufferList* inInputData ) +{ + OSStatus err = noErr; + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + + if( inInputData == NULL ) + { + DBUG(("PaOSX_HandleInput: inInputData == NULL\n")); + return noErr; + } + + if( inInputData->mNumberBuffers > 0 ) + { + /* Write to FIFO here if we are only using this callback. */ + if( (pahsc->mode == PA_MODE_INPUT_ONLY) || (pahsc->mode == PA_MODE_IO_ONE_DEVICE) ) + { + err = PaOSX_WriteInputRingBuffer( past, inInputData ); + if( err != noErr ) goto error; + } + } + + if( pahsc->mode == PA_MODE_INPUT_ONLY ) + { + /* Generate user buffers as long as we have a half full input FIFO. */ + long halfSize = pahsc->ringBuffer.bufferSize / 2; + while( (RingBuffer_GetReadAvailable( &pahsc->ringBuffer ) >= halfSize) && + (past->past_StopSoon == 0) ) + { + err = PaOSX_LoadAndProcess ( past, NULL, NULL ); + if( err != noErr ) goto error; + } + } + +error: + return err; +} + +/********************************************************************** +** Fill any available output buffers. +*/ +static OSStatus PaOSX_HandleOutput( internalPortAudioStream *past, + AudioBufferList* outOutputData ) +{ + OSStatus err = noErr; + void *outputNativeBufferfPtr = NULL; + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + UInt32 numBytes = 0; + int numChannelsRemaining; + Boolean deinterleavingNeeded; + int numFramesInOutputBuffer; + + if( outOutputData == NULL ) + { + DBUG(("PaOSX_HandleOutput: outOutputData == NULL\n")); + return noErr; + } + + deinterleavingNeeded = past->past_NumOutputChannels != outOutputData->mBuffers[0].mNumberChannels; + + numFramesInOutputBuffer = outOutputData->mBuffers[0].mDataByteSize / + (sizeof(float) * outOutputData->mBuffers[0].mNumberChannels); + + if( pahsc->mode != PA_MODE_INPUT_ONLY ) + { + /* If we are using output, then we need an empty output buffer. */ + if( outOutputData->mNumberBuffers > 0 ) + { + + /* If we have multiple CoreAudio buffers, then we will need to deinterleave after conversion. */ + if( deinterleavingNeeded ) + { + numBytes = numFramesInOutputBuffer * sizeof(float) * past->past_NumOutputChannels; + + /* Free old buffer if we are allocating new one. */ + if ( (pahsc->output.streamInterleavingBuffer != NULL) && + (pahsc->output.streamInterleavingBufferLen < numBytes) ) + { + PaHost_FreeFastMemory( pahsc->output.streamInterleavingBuffer, pahsc->output.streamInterleavingBufferLen ); + pahsc->output.streamInterleavingBuffer = NULL; + } + /* Allocate interleaving buffer if needed. */ + if ( pahsc->output.streamInterleavingBuffer == NULL ) + { + pahsc->output.streamInterleavingBufferLen = numBytes; + pahsc->output.streamInterleavingBuffer = (float *)PaHost_AllocateFastMemory( pahsc->output.streamInterleavingBufferLen ); + } + + outputNativeBufferfPtr = (void*)pahsc->output.streamInterleavingBuffer; + } + else + { + numBytes = outOutputData->mBuffers[0].mDataByteSize; + outputNativeBufferfPtr = (void*)outOutputData->mBuffers[0].mData; + } + + /* Pull data from PA user through converter. */ + err = AudioConverterFillBuffer( + pahsc->output.converter, + PaOSX_OutputConverterCallbackProc, + past, + &numBytes, + outputNativeBufferfPtr); + if( err != noErr ) + { + PRINT_ERR("PaOSX_HandleOutput: AudioConverterFillBuffer failed", err); + goto error; + } + + /* Deinterleave data from PortAudio and write to multiple CoreAudio buffers. */ + if( deinterleavingNeeded ) + { + int numInterleavedChannels = past->past_NumOutputChannels; + int i, currentInterleavedChannelIndex = 0; + numChannelsRemaining = numInterleavedChannels; + + for( i=0; imNumberBuffers; i++ ) + { + int numBufChannels = outOutputData->mBuffers[i].mNumberChannels; + int j; + /* Don't use more than we need or more than we have. */ + int numChannelsUsedInThisBuffer = (numChannelsRemaining < numBufChannels ) ? + numChannelsRemaining : numBufChannels; + + for( j=0; jmBuffers[i].mData)[ j ]; + float *src = &pahsc->output.streamInterleavingBuffer[ currentInterleavedChannelIndex ]; + /* Move one channel from interleaved buffer to CoreAudio buffer. */ + for( k=0; kpast_DeviceData; + + /* If there is a FIFO for input then write to it. */ + if( (pahsc->ringBufferData != NULL) && (inInputData != NULL) ) + { + err = PaOSX_WriteInputRingBuffer( past, inInputData ); + if( err != noErr ) goto error; + } +error: + return err; +} + +/****************************************************************** + * This is the primary callback for CoreAudio. + * It can handle input and/or output for a single device. + * It takes input from CoreAudio, converts it and passes it to the + * PortAudio user callback. Then takes the PA results and passes it + * back to CoreAudio. + */ +static OSStatus PaOSX_CoreAudioIOCallback (AudioDeviceID inDevice, const AudioTimeStamp* inNow, + const AudioBufferList* inInputData, const AudioTimeStamp* inInputTime, + AudioBufferList* outOutputData, const AudioTimeStamp* inOutputTime, + void* contextPtr) +{ + OSStatus err = noErr; + internalPortAudioStream *past; + PaHostSoundControl *pahsc; + past = (internalPortAudioStream *) contextPtr; + pahsc = (PaHostSoundControl *) past->past_DeviceData; + + /* Has someone asked us to abort by calling Pa_AbortStream()? */ + if( past->past_StopNow ) + { + past->past_IsActive = 0; /* Will cause thread to return. */ + } + /* Has someone asked us to stop by calling Pa_StopStream() + * OR has a user callback returned '1' to indicate finished. + */ + else if( past->past_StopSoon ) + { + // FIXME - Pretend all done. Should wait for audio to play out but CoreAudio latency very low. + past->past_IsActive = 0; /* Will cause thread to return. */ + } + else + { + /* use time stamp from CoreAudio if valid */ + if( inOutputTime->mFlags & kAudioTimeStampSampleTimeValid) + { + past->past_FrameCount = inOutputTime->mSampleTime; + } + else if( inInputTime->mFlags & kAudioTimeStampSampleTimeValid) + { + past->past_FrameCount = inInputTime->mSampleTime; + } + + past->past_NumCallbacks += 1; + + /* Process full input buffer. */ + err = PaOSX_HandleInput( past, inInputData ); + if( err != 0 ) goto error; + + /* Fill up empty output buffers. */ + err = PaOSX_HandleOutput( past, outOutputData ); + if( err != 0 ) goto error; + } + + if( err != 0 ) DBUG(("PaOSX_CoreAudioIOCallback: returns %ld.\n", err )); + +error: + return err; +} + +/*******************************************************************/ +/** Attempt to set device sample rate. + * This is not critical because we use an AudioConverter but we may + * get better fidelity if we can avoid resampling. + * + * Only set format once because some devices take time to settle. + * Return flag indicating whether format changed so we know whether to wait + * for DevicePropertyListener to get called. + * + * @return negative error, zero if no change, or one if changed successfully. + */ +static PaError PaOSX_SetFormat( AudioDeviceID devID, Boolean isInput, + double desiredRate, int desiredNumChannels ) +{ + AudioStreamBasicDescription formatDesc; + PaError result = 0; + OSStatus err; + UInt32 dataSize; + Float64 originalRate; + int originalChannels; + + /* Get current device format. This is critical because if we pass + * zeros for unspecified fields then the iMic device gets switched to a 16 bit + * integer format!!! I don't know if this is a Mac bug or not. But it only + * started happening when I upgraded from OS X V10.1 to V10.2 (Jaguar). + */ + dataSize = sizeof(formatDesc); + err = AudioDeviceGetProperty( devID, 0, isInput, + kAudioDevicePropertyStreamFormat, &dataSize, &formatDesc); + if( err != noErr ) + { + PRINT_ERR("PaOSX_SetFormat: Could not get format.", err); + sSavedHostError = err; + return paHostError; + } + + originalRate = formatDesc.mSampleRate; + originalChannels = formatDesc.mChannelsPerFrame; + + // Is it already set to the correct format? + if( (originalRate != desiredRate) || (originalChannels != desiredNumChannels) ) + { + DBUG(("PaOSX_SetFormat: try to change sample rate to %f.\n", desiredRate )); + DBUG(("PaOSX_SetFormat: try to set number of channels to %d\n", desiredNumChannels)); + + formatDesc.mSampleRate = desiredRate; + formatDesc.mChannelsPerFrame = desiredNumChannels; + formatDesc.mBytesPerFrame = formatDesc.mChannelsPerFrame * sizeof(float); + formatDesc.mBytesPerPacket = formatDesc.mBytesPerFrame * formatDesc.mFramesPerPacket; + + err = AudioDeviceSetProperty( devID, 0, 0, + isInput, kAudioDevicePropertyStreamFormat, sizeof(formatDesc), &formatDesc); + if (err != noErr) + { + /* Could not set to desired rate so query for closest match. */ + dataSize = sizeof(formatDesc); + err = AudioDeviceGetProperty( devID, 0, + isInput, kAudioDevicePropertyStreamFormatMatch, &dataSize, &formatDesc); + + DBUG(("PaOSX_SetFormat: closest rate is %f.\n", formatDesc.mSampleRate )); + DBUG(("PaOSX_SetFormat: closest numChannels is %d.\n", (int)formatDesc.mChannelsPerFrame )); + // Set to closest if different from original. + if( (err == noErr) && + ((originalRate != formatDesc.mSampleRate) || + (originalChannels != formatDesc.mChannelsPerFrame)) ) + { + err = AudioDeviceSetProperty( devID, 0, 0, + isInput, kAudioDevicePropertyStreamFormat, sizeof(formatDesc), &formatDesc); + if( err == noErr ) result = 1; + } + } + else result = 1; + } + + return result; +} + +/******************************************************************* + * Check volume level of device. If below threshold, then set to newLevel. + * Using volume instead of decibels because decibel range varies by device. + */ +static void PaOSX_FixVolumeScalars( AudioDeviceID devID, Boolean isInput, + int numChannels, double threshold, double newLevel ) +{ + OSStatus err = noErr; + UInt32 dataSize; + int iChannel; + +/* The master channel is 0. Left and right are channels 1 and 2. */ +/* Fix volume. */ + for( iChannel = 0; iChannel<=numChannels; iChannel++ ) + { + Float32 fdata32; + dataSize = sizeof( fdata32 ); + err = AudioDeviceGetProperty( devID, iChannel, isInput, + kAudioDevicePropertyVolumeScalar, &dataSize, &fdata32 ); + if( err == noErr ) + { + DBUG(("kAudioDevicePropertyVolumeScalar for channel %d = %f\n", iChannel, fdata32)); + if( fdata32 <= (Float32) threshold ) + { + dataSize = sizeof( fdata32 ); + fdata32 = (Float32) newLevel; + err = AudioDeviceSetProperty( devID, 0, iChannel, isInput, + kAudioDevicePropertyVolumeScalar, dataSize, &fdata32 ); + if( err != noErr ) + { + PRINT(("Warning: audio volume is very low and could not be turned up.\n")); + } + else + { + PRINT(("Volume for audio channel %d was <= %4.2f so set to %4.2f by PortAudio!\n", + iChannel, threshold, newLevel )); + } + } + } + } +/* Unmute if muted. */ + for( iChannel = 0; iChannel<=numChannels; iChannel++ ) + { + UInt32 uidata32; + dataSize = sizeof( uidata32 ); + err = AudioDeviceGetProperty( devID, iChannel, isInput, + kAudioDevicePropertyMute, &dataSize, &uidata32 ); + if( err == noErr ) + { + DBUG(("mute for channel %d = %ld\n", iChannel, uidata32)); + if( uidata32 == 1 ) // muted? + { + dataSize = sizeof( uidata32 ); + uidata32 = 0; // unmute + err = AudioDeviceSetProperty( devID, 0, iChannel, isInput, + kAudioDevicePropertyMute, dataSize, &uidata32 ); + if( err != noErr ) + { + PRINT(("Warning: audio is muted and could not be unmuted!\n")); + } + else + { + PRINT(("Audio channel %d was unmuted by PortAudio!\n", iChannel )); + } + } + } + } + +} + +#if 0 +static void PaOSX_DumpDeviceInfo( AudioDeviceID devID, Boolean isInput ) +{ + OSStatus err = noErr; + UInt32 dataSize; + UInt32 uidata32; + Float32 fdata32; + AudioValueRange audioRange; + + dataSize = sizeof( uidata32 ); + err = AudioDeviceGetProperty( devID, 0, isInput, + kAudioDevicePropertyLatency, &dataSize, &uidata32 ); + if( err != noErr ) + { + PRINT_ERR("Error reading kAudioDevicePropertyLatency", err); + return; + } + PRINT(("kAudioDevicePropertyLatency = %d\n", (int)uidata32 )); + + dataSize = sizeof( fdata32 ); + err = AudioDeviceGetProperty( devID, 1, isInput, + kAudioDevicePropertyVolumeScalar, &dataSize, &fdata32 ); + if( err != noErr ) + { + PRINT_ERR("Error reading kAudioDevicePropertyVolumeScalar", err); + return; + } + PRINT(("kAudioDevicePropertyVolumeScalar = %f\n", fdata32 )); + + dataSize = sizeof( uidata32 ); + err = AudioDeviceGetProperty( devID, 0, isInput, + kAudioDevicePropertyBufferSize, &dataSize, &uidata32 ); + if( err != noErr ) + { + PRINT_ERR("Error reading buffer size", err); + return; + } + PRINT(("kAudioDevicePropertyBufferSize = %d bytes\n", (int)uidata32 )); + + dataSize = sizeof( audioRange ); + err = AudioDeviceGetProperty( devID, 0, isInput, + kAudioDevicePropertyBufferSizeRange, &dataSize, &audioRange ); + if( err != noErr ) + { + PRINT_ERR("Error reading buffer size range", err); + return; + } + PRINT(("kAudioDevicePropertyBufferSizeRange = %g to %g bytes\n", audioRange.mMinimum, audioRange.mMaximum )); + + dataSize = sizeof( uidata32 ); + err = AudioDeviceGetProperty( devID, 0, isInput, + kAudioDevicePropertyBufferFrameSize, &dataSize, &uidata32 ); + if( err != noErr ) + { + PRINT_ERR("Error reading buffer size", err); + return; + } + PRINT(("kAudioDevicePropertyBufferFrameSize = %d frames\n", (int)uidata32 )); + + dataSize = sizeof( audioRange ); + err = AudioDeviceGetProperty( devID, 0, isInput, + kAudioDevicePropertyBufferFrameSizeRange, &dataSize, &audioRange ); + if( err != noErr ) + { + PRINT_ERR("Error reading buffer size range", err); + return; + } + PRINT(("kAudioDevicePropertyBufferFrameSizeRange = %g to %g frames\n", audioRange.mMinimum, audioRange.mMaximum )); + + return; +} +#endif + +/*******************************************************************/ +static OSStatus PAOSX_DevicePropertyListener (AudioDeviceID inDevice, + UInt32 inChannel, + Boolean isInput, + AudioDevicePropertyID inPropertyID, + void* inClientData) +{ + PaHostSoundControl *pahsc; + internalPortAudioStream *past; + UInt32 dataSize; + OSStatus err = noErr; + AudioStreamBasicDescription userStreamFormat, hardwareStreamFormat; + PaHostInOut *hostInOut; + AudioStreamBasicDescription *destFormatPtr, *srcFormatPtr; + + past = (internalPortAudioStream *) inClientData; + pahsc = (PaHostSoundControl *) past->past_DeviceData; + + DBUG(("PAOSX_DevicePropertyListener: called with propertyID = 0x%0X\n", (unsigned int) inPropertyID )); + + if(inPropertyID == kAudioDevicePropertyStreamFormat) + { + /* Get target device format */ + dataSize = sizeof(hardwareStreamFormat); + err = AudioDeviceGetProperty(inDevice, 0, isInput, + kAudioDevicePropertyStreamFormat, &dataSize, &hardwareStreamFormat); + if( err != noErr ) + { + PRINT_ERR("PAOSX_DevicePropertyListener: Could not get device format", err); + sSavedHostError = err; + goto error; + } + + DBUG(("PAOSX_DevicePropertyListener: HW mChannelsPerFrame = %d\n", (int)hardwareStreamFormat.mChannelsPerFrame )); + + /* Set source user format. */ + userStreamFormat = hardwareStreamFormat; + userStreamFormat.mSampleRate = past->past_SampleRate; // sample rate of the user synthesis code + userStreamFormat.mChannelsPerFrame = (isInput) ? past->past_NumInputChannels : past->past_NumOutputChannels; // the number of channels in each frame + DBUG(("PAOSX_DevicePropertyListener: User mChannelsPerFrame = %d\n", (int)userStreamFormat.mChannelsPerFrame )); + + userStreamFormat.mBytesPerFrame = userStreamFormat.mChannelsPerFrame * sizeof(float); + userStreamFormat.mBytesPerPacket = userStreamFormat.mBytesPerFrame * userStreamFormat.mFramesPerPacket; + + /* Don't use AudioConverter for merging or splitting channels. */ + hardwareStreamFormat.mChannelsPerFrame = userStreamFormat.mChannelsPerFrame; + hardwareStreamFormat.mBytesPerFrame = userStreamFormat.mBytesPerFrame; + hardwareStreamFormat.mBytesPerPacket = userStreamFormat.mBytesPerPacket; + + if( isInput ) + { + hostInOut = &pahsc->input; + srcFormatPtr = &hardwareStreamFormat; + destFormatPtr = &userStreamFormat; + } + else + { + hostInOut = &pahsc->output; + srcFormatPtr = &userStreamFormat; + destFormatPtr = &hardwareStreamFormat; + } + DBUG(("PAOSX_DevicePropertyListener: source rate = %f\n", srcFormatPtr->mSampleRate )); + DBUG(("PAOSX_DevicePropertyListener: dest rate = %f\n", destFormatPtr->mSampleRate )); + + // Don't delete old converter until we create new one so we don't pull + // the rug out from under other audio threads. + AudioConverterRef oldConverter = hostInOut->converter; + + // Make converter to change sample rate. + err = AudioConverterNew ( + srcFormatPtr, + destFormatPtr, + &hostInOut->converter ); + if( err != noErr ) + { + PRINT_ERR("Could not create format converter", err); + sSavedHostError = err; + goto error; + } + + if( oldConverter != NULL ) + { + verify_noerr( AudioConverterDispose( oldConverter ) ); + } + } + +error: + pahsc->formatListenerCalled = true; + return err; +} + +/* Allocate FIFO between Device callback and Converter callback so that device can push data +* and converter can pull data. +*/ +static PaError PaOSX_CreateInputRingBuffer( internalPortAudioStream *past ) +{ + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + OSStatus err = noErr; + UInt32 dataSize; + double sampleRateRatio; + long numBytes; + UInt32 framesPerHostBuffer; + UInt32 bytesForDevice; + UInt32 bytesForUser; + UInt32 bytesPerFrame; + AudioStreamBasicDescription formatDesc; + + dataSize = sizeof(formatDesc); + err = AudioDeviceGetProperty( pahsc->input.audioDeviceID, 0, IS_INPUT, + kAudioDevicePropertyStreamFormat, &dataSize, &formatDesc); + if( err != noErr ) + { + PRINT_ERR("PaOSX_CreateInputRingBuffer: Could not get input format.\n", err); + sSavedHostError = err; + return paHostError; + } + + // If device is delivering audio faster than being consumed then buffer must be bigger. + sampleRateRatio = formatDesc.mSampleRate / past->past_SampleRate; + + // Get size of CoreAudio IO buffers. + dataSize = sizeof(framesPerHostBuffer); + err = AudioDeviceGetProperty( pahsc->input.audioDeviceID, 0, IS_INPUT, + kAudioDevicePropertyBufferFrameSize, &dataSize, + &framesPerHostBuffer); + if( err != noErr ) + { + PRINT_ERR("PaOSX_CreateInputRingBuffer: Could not get input buffer size.\n", err); + sSavedHostError = err; + return paHostError; + } + + bytesPerFrame = past->past_NumInputChannels * sizeof(Float32); + + bytesForDevice = framesPerHostBuffer * bytesPerFrame * 2; + bytesForUser = past->past_FramesPerUserBuffer * bytesPerFrame * 3 * sampleRateRatio; + + // Ring buffer should be large enough to consume audio input from device, + // and to deliver a complete user buffer. + numBytes = (bytesForDevice > bytesForUser) ? bytesForDevice : bytesForUser; + + numBytes = RoundUpToNextPowerOf2( numBytes ); + + DBUG(("PaOSX_CreateInputRingBuffer: FIFO numBytes = %ld\n", numBytes)); + pahsc->ringBufferData = PaHost_AllocateFastMemory( numBytes ); + if( pahsc->ringBufferData == NULL ) + { + return paInsufficientMemory; + } + RingBuffer_Init( &pahsc->ringBuffer, numBytes, pahsc->ringBufferData ); + // Make it look almost full at beginning. We must advance by an integral number of frames + // so that the channels don't get scrambled when numChannels is not a power of 2. + { + int numZeroFrames = numBytes / bytesPerFrame; + int numZeroBytes = numZeroFrames * bytesPerFrame; + RingBuffer_AdvanceWriteIndex( &pahsc->ringBuffer, numZeroBytes ); + } + + return paNoError; +} + +/****************************************************************** + * Try to set the I/O bufferSize of the device. + * Scale the size by the ratio of the sample rates so that the converter will have + * enough data to operate on. + */ +static OSStatus PaOSX_SetDeviceBufferSize( AudioDeviceID devID, Boolean isInput, int framesPerUserBuffer, Float64 sampleRateRatio ) +{ + UInt32 dataSize; + UInt32 ioBufferSize; + int scaler; + + scaler = (int) sampleRateRatio; + if( sampleRateRatio > (Float64) scaler ) scaler += 1; + DBUG(("PaOSX_SetDeviceBufferSize: buffer size scaler = %d\n", scaler )); + ioBufferSize = framesPerUserBuffer * scaler; + + // Limit buffer size to reasonable value. + if( ioBufferSize < 128 ) ioBufferSize = 128; + + dataSize = sizeof(ioBufferSize); + return AudioDeviceSetProperty( devID, 0, 0, isInput, + kAudioDevicePropertyBufferFrameSize, dataSize, + &ioBufferSize); +} + + +/*******************************************************************/ +static PaError PaOSX_OpenCommonDevice( internalPortAudioStream *past, + PaHostInOut *inOut, Boolean isInput ) +{ + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + PaError result = paNoError; + OSStatus err = noErr; + Float64 deviceRate; + + PaOSX_FixVolumeScalars( inOut->audioDeviceID, isInput, + inOut->numChannels, 0.1, 0.9 ); + + // The HW device format changes are asynchronous. + // So we don't know when or if the PAOSX_DevicePropertyListener() will + // get called. To be safe, call the listener now to forcibly create the converter. + if( inOut->converter == NULL ) + { + err = PAOSX_DevicePropertyListener (inOut->audioDeviceID, + 0, isInput, kAudioDevicePropertyStreamFormat, past); + if (err != kAudioHardwareNoError) + { + PRINT_ERR("PaOSX_OpenCommonDevice: PAOSX_DevicePropertyListener failed.\n", err); + sSavedHostError = err; + return paHostError; + } + } + + // Add listener for when format changed by other apps. + DBUG(("PaOSX_OpenCommonDevice: call AudioDeviceAddPropertyListener()\n" )); + err = AudioDeviceAddPropertyListener( inOut->audioDeviceID, 0, isInput, + kAudioDevicePropertyStreamFormat, + (AudioDevicePropertyListenerProc) PAOSX_DevicePropertyListener, past ); + if (err != noErr) + { + return -1; // FIXME + } + + // Only change format if current HW format is different. + // Don't bother to check result because we are going to use an AudioConverter anyway. + pahsc->formatListenerCalled = false; + result = PaOSX_SetFormat( inOut->audioDeviceID, isInput, past->past_SampleRate, inOut->numChannels ); + // Synchronize with device because format changes put some devices into unusable mode. + if( result > 0 ) + { + const int sleepDurMsec = 50; + int spinCount = MIN_TIMEOUT_MSEC / sleepDurMsec; + while( !pahsc->formatListenerCalled && (spinCount > 0) ) + { + Pa_Sleep( sleepDurMsec ); // FIXME - use a semaphore or signal + spinCount--; + } + if( !pahsc->formatListenerCalled ) + { + PRINT(("PaOSX_OpenCommonDevice: timed out waiting for device format to settle.\n")); + } + result = 0; + } + +#if SET_DEVICE_BUFFER_SIZE + // Try to set the I/O bufferSize of the device. + { + Float64 ratio; + deviceRate = PaOSX_GetDeviceSampleRate( inOut->audioDeviceID, isInput ); + if( deviceRate <= 0.0 ) deviceRate = past->past_SampleRate; + ratio = deviceRate / past->past_SampleRate ; + err = PaOSX_SetDeviceBufferSize( inOut->audioDeviceID, isInput, + past->past_FramesPerUserBuffer, ratio ); + if( err != noErr ) + { + DBUG(("PaOSX_OpenCommonDevice: Could not set I/O buffer size.\n")); + } + } +#endif + + /* Allocate an input buffer because we need it between the user callback and the converter. */ + inOut->converterBuffer = PaHost_AllocateFastMemory( inOut->bytesPerUserNativeBuffer ); + if( inOut->converterBuffer == NULL ) + { + return paInsufficientMemory; + } + + return result; +} + +/*******************************************************************/ +static PaError PaOSX_OpenInputDevice( internalPortAudioStream *past ) +{ + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + const PaHostDeviceInfo *hostDeviceInfo; + PaError result = paNoError; + + DBUG(("PaOSX_OpenInputDevice: -------------\n")); + + if( (past->past_InputDeviceID < LOWEST_INPUT_DEVID) || + (past->past_InputDeviceID > HIGHEST_INPUT_DEVID) ) + { + return paInvalidDeviceId; + } + hostDeviceInfo = &sDeviceInfos[past->past_InputDeviceID]; + + if( past->past_NumInputChannels > hostDeviceInfo->paInfo.maxInputChannels ) + { + return paInvalidChannelCount; /* Too many channels! */ + } + pahsc->input.numChannels = past->past_NumInputChannels; + + // setup PA conversion procedure + result = PaConvert_SetupInput( past, paFloat32 ); + + result = PaOSX_OpenCommonDevice( past, &pahsc->input, IS_INPUT ); + if( result != paNoError ) goto error; + + // Allocate a ring buffer so we can push in data from device, and pull through AudioConverter. + result = PaOSX_CreateInputRingBuffer( past ); + if( result != paNoError ) goto error; + +error: + return result; +} + +/*******************************************************************/ +static PaError PaOSX_OpenOutputDevice( internalPortAudioStream *past ) +{ + PaHostSoundControl *pahsc; + const PaHostDeviceInfo *hostDeviceInfo; + PaError result = paNoError; + + DBUG(("PaOSX_OpenOutputDevice: -------------\n")); + pahsc = (PaHostSoundControl *) past->past_DeviceData; + + // Validate DeviceID + DBUG(("PaOSX_OpenOutputDevice: deviceID = 0x%x\n", past->past_OutputDeviceID)); + if( (past->past_OutputDeviceID < LOWEST_OUTPUT_DEVID) || + (past->past_OutputDeviceID > HIGHEST_OUTPUT_DEVID) ) + { + return paInvalidDeviceId; + } + hostDeviceInfo = &sDeviceInfos[past->past_OutputDeviceID]; + + // Validate number of channels. + if( past->past_NumOutputChannels > hostDeviceInfo->paInfo.maxOutputChannels ) + { + return paInvalidChannelCount; /* Too many channels! */ + } + pahsc->output.numChannels = past->past_NumOutputChannels; + + // setup conversion procedure + result = PaConvert_SetupOutput( past, paFloat32 ); + if( result != paNoError ) goto error; + + result = PaOSX_OpenCommonDevice( past, &pahsc->output, IS_OUTPUT ); + if( result != paNoError ) goto error; + +error: + return result; +} + +/******************************************************************* +* Determine how many User Buffers we can put into our CoreAudio stream buffer. +* Uses: +* past->past_FramesPerUserBuffer, etc. +* Sets: +* past->past_NumUserBuffers +* pahsc->input.bytesPerUserNativeBuffer +* pahsc->output.bytesPerUserNativeBuffer +*/ +static void PaOSX_CalcHostBufferSize( internalPortAudioStream *past ) +{ + PaHostSoundControl *pahsc = ( PaHostSoundControl *)past->past_DeviceData; + + // Determine number of user buffers based strictly on minimum reasonable buffer size. + // We ignore the Pa_OpenStream numBuffer parameter because CoreAudio has a big + // mix buffer and handles latency automatically. + past->past_NumUserBuffers = Pa_GetMinNumBuffers( past->past_FramesPerUserBuffer, past->past_SampleRate ); + + // calculate buffer sizes in bytes + pahsc->input.bytesPerUserNativeBuffer = past->past_FramesPerUserBuffer * + Pa_GetSampleSize(paFloat32) * past->past_NumInputChannels; + pahsc->output.bytesPerUserNativeBuffer = past->past_FramesPerUserBuffer * + Pa_GetSampleSize(paFloat32) * past->past_NumOutputChannels; + + DBUG(("PaOSX_CalcNumHostBuffers: past_NumUserBuffers = %ld\n", past->past_NumUserBuffers )); + DBUG(("PaOSX_CalcNumHostBuffers: input.bytesPerUserNativeBuffer = %d\n", pahsc->input.bytesPerUserNativeBuffer )); + DBUG(("PaOSX_CalcNumHostBuffers: output.bytesPerUserNativeBuffer = %d\n", pahsc->output.bytesPerUserNativeBuffer )); +} + +/*****************************************************************************/ +/************** Internal Host API ********************************************/ +/*****************************************************************************/ +PaError PaHost_OpenStream( internalPortAudioStream *past ) +{ + PaError result = paNoError; + PaHostSoundControl *pahsc; + Boolean useInput; + Boolean useOutput; + + assert( past->past_Magic == PA_MAGIC ); + + /* Allocate and initialize host data. */ + pahsc = (PaHostSoundControl *) malloc(sizeof(PaHostSoundControl)); + if( pahsc == NULL ) + { + result = paInsufficientMemory; + goto error; + } + memset( pahsc, 0, sizeof(PaHostSoundControl) ); + past->past_DeviceData = (void *) pahsc; + pahsc->primaryDeviceID = kAudioDeviceUnknown; + pahsc->input.audioDeviceID = kAudioDeviceUnknown; + pahsc->output.audioDeviceID = kAudioDeviceUnknown; + + PaOSX_CalcHostBufferSize( past ); + + useOutput = (past->past_OutputDeviceID != paNoDevice) && (past->past_NumOutputChannels > 0); + useInput = (past->past_InputDeviceID != paNoDevice) && (past->past_NumInputChannels > 0); + + // Set device IDs and determine IO Device mode. + if( useOutput ) + { + pahsc->output.audioDeviceID = sDeviceInfos[past->past_OutputDeviceID].audioDeviceID; + pahsc->primaryDeviceID = pahsc->output.audioDeviceID; + if( useInput ) + { + pahsc->input.audioDeviceID = sDeviceInfos[past->past_InputDeviceID].audioDeviceID; + pahsc->mode = ( pahsc->input.audioDeviceID != pahsc->primaryDeviceID ) ? + PA_MODE_IO_TWO_DEVICES : PA_MODE_IO_ONE_DEVICE; + } + else + { + pahsc->mode = PA_MODE_OUTPUT_ONLY; + } + } + else + { + /* Just input, not output. */ + pahsc->input.audioDeviceID = sDeviceInfos[past->past_InputDeviceID].audioDeviceID; + pahsc->primaryDeviceID = pahsc->input.audioDeviceID; + pahsc->mode = PA_MODE_INPUT_ONLY; + } + + DBUG(("outputDeviceID = %ld\n", pahsc->output.audioDeviceID )); + DBUG(("inputDeviceID = %ld\n", pahsc->input.audioDeviceID )); + DBUG(("primaryDeviceID = %ld\n", pahsc->primaryDeviceID )); + + /* ------------------ OUTPUT */ + if( useOutput ) + { + result = PaOSX_OpenOutputDevice( past ); + if( result < 0 ) goto error; + } + + /* ------------------ INPUT */ + if( useInput ) + { + result = PaOSX_OpenInputDevice( past ); + if( result < 0 ) goto error; + } + +#if PA_ENABLE_LOAD_MEASUREMENT + pahsc->inverseHostTicksPerBuffer = past->past_SampleRate / + (AudioGetHostClockFrequency() * past->past_FramesPerUserBuffer); + DBUG(("inverseHostTicksPerBuffer based on buffer size of %d frames.\n", past->past_FramesPerUserBuffer )); +#else + PRINT(("WARNING - Pa_GetCPULoad() mesaurement disabled in pa_mac_core.c.\n")); +#endif + + return result; + +error: + PaHost_CloseStream( past ); + return result; +} + +/*************************************************************************/ +PaError PaHost_StartOutput( internalPortAudioStream *past ) +{ + return 0; +} + +/*************************************************************************/ +PaError PaHost_StartInput( internalPortAudioStream *past ) +{ + return 0; +} + +/*************************************************************************/ +PaError PaHost_StartEngine( internalPortAudioStream *past ) +{ + OSStatus err = noErr; + PaError result = paNoError; + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + + past->past_StopSoon = 0; + past->past_StopNow = 0; + past->past_IsActive = 1; + +/* If full duplex and using two separate devices then start input device. */ + if( pahsc->mode == PA_MODE_IO_TWO_DEVICES ) + { + // Associate an IO proc with the device and pass a pointer to the audio data context + err = AudioDeviceAddIOProc(pahsc->input.audioDeviceID, (AudioDeviceIOProc)PaOSX_CoreAudioInputCallback, past); + if (err != noErr) + { + PRINT_ERR("PaHost_StartEngine: AudioDeviceAddIOProc secondary failed", err ); + goto error; + } + + // start playing sound through the device + err = AudioDeviceStart(pahsc->input.audioDeviceID, (AudioDeviceIOProc)PaOSX_CoreAudioInputCallback); + if (err != noErr) + { + PRINT_ERR("PaHost_StartEngine: AudioDeviceStart secondary failed", err ); + PRINT(("The program may succeed if you run it again!\n")); + goto error; + } + } + + // Associate an IO proc with the device and pass a pointer to the audio data context + err = AudioDeviceAddIOProc(pahsc->primaryDeviceID, (AudioDeviceIOProc)PaOSX_CoreAudioIOCallback, past); + if (err != noErr) + { + PRINT_ERR("PaHost_StartEngine: AudioDeviceAddIOProc primary failed", err ); + goto error; + } + + // start playing sound through the device + err = AudioDeviceStart(pahsc->primaryDeviceID, (AudioDeviceIOProc)PaOSX_CoreAudioIOCallback); + if (err != noErr) + { + PRINT_ERR("PaHost_StartEngine: AudioDeviceStart primary failed", err ); + PRINT(("The program may succeed if you run it again!\n")); + goto error; + } + + return result; + +error: + sSavedHostError = err; + return paHostError; +} + +/*************************************************************************/ +PaError PaHost_StopEngine( internalPortAudioStream *past, int abort ) +{ + OSStatus err = noErr; + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + if( pahsc == NULL ) return paNoError; + (void) abort; + + /* Tell background thread to stop generating more data and to let current data play out. */ + past->past_StopSoon = 1; + /* If aborting, tell background thread to stop NOW! */ + if( abort ) past->past_StopNow = 1; + past->past_IsActive = 0; + +#if PA_TRACE_START_STOP + AddTraceMessage( "PaHost_StopOutput: pahsc_HWaveOut ", (int) pahsc->pahsc_HWaveOut ); +#endif + + // FIXME - we should ask proc to stop instead of stopping abruptly + err = AudioDeviceStop(pahsc->primaryDeviceID, (AudioDeviceIOProc)PaOSX_CoreAudioIOCallback); + if (err != noErr) + { + goto error; + } + + err = AudioDeviceRemoveIOProc(pahsc->primaryDeviceID, (AudioDeviceIOProc)PaOSX_CoreAudioIOCallback); + if (err != noErr) goto error; + +/* If full duplex and using two separate devices then stop second input device. */ + if( pahsc->mode == PA_MODE_IO_TWO_DEVICES ) + { + err = AudioDeviceStop(pahsc->input.audioDeviceID, (AudioDeviceIOProc)PaOSX_CoreAudioInputCallback); + if (err != noErr) goto error; + err = AudioDeviceRemoveIOProc(pahsc->input.audioDeviceID, (AudioDeviceIOProc)PaOSX_CoreAudioInputCallback); + if (err != noErr) goto error; + } + + return paNoError; + +error: + sSavedHostError = err; + return paHostError; +} + +/*************************************************************************/ +PaError PaHost_StopInput( internalPortAudioStream *past, int abort ) +{ + return paNoError; +} + +/*************************************************************************/ +PaError PaHost_StopOutput( internalPortAudioStream *past, int abort ) +{ + return paNoError; +} + +/*******************************************************************/ +PaError PaHost_CloseStream( internalPortAudioStream *past ) +{ + PaHostSoundControl *pahsc; + + if( past == NULL ) return paBadStreamPtr; + pahsc = (PaHostSoundControl *) past->past_DeviceData; + if( pahsc == NULL ) return paNoError; + + //PaOSX_DumpDeviceInfo( sDeviceInfos[past->past_OutputDeviceID].audioDeviceID, IS_OUTPUT ); + +#if PA_TRACE_START_STOP + AddTraceMessage( "PaHost_CloseStream: pahsc_HWaveOut ", (int) pahsc->pahsc_HWaveOut ); +#endif + // Stop Listener callbacks ASAP before dismantling stream. + if( PA_USING_INPUT ) + { + AudioDeviceRemovePropertyListener( pahsc->input.audioDeviceID, 0, IS_INPUT, + kAudioDevicePropertyStreamFormat, + (AudioDevicePropertyListenerProc) PAOSX_DevicePropertyListener ); + } + + if( PA_USING_OUTPUT ) + { + AudioDeviceRemovePropertyListener( pahsc->output.audioDeviceID, 0, IS_OUTPUT, + kAudioDevicePropertyStreamFormat, + (AudioDevicePropertyListenerProc) PAOSX_DevicePropertyListener ); + } + + if( pahsc->output.converterBuffer != NULL ) + { + PaHost_FreeFastMemory( pahsc->output.converterBuffer, pahsc->output.bytesPerUserNativeBuffer ); + } + if( pahsc->input.converterBuffer != NULL ) + { + PaHost_FreeFastMemory( pahsc->input.converterBuffer, pahsc->input.bytesPerUserNativeBuffer ); + } + if( pahsc->ringBufferData != NULL ) + { + PaHost_FreeFastMemory( pahsc->ringBufferData, pahsc->ringBuffer.bufferSize ); + } + if( pahsc->output.converter != NULL ) + { + verify_noerr(AudioConverterDispose (pahsc->output.converter)); + } + if( pahsc->input.converter != NULL ) + { + verify_noerr(AudioConverterDispose (pahsc->input.converter)); + } + if ( pahsc->input.streamInterleavingBuffer != NULL ) + { + PaHost_FreeFastMemory( pahsc->input.streamInterleavingBuffer, pahsc->input.streamInterleavingBufferLen ); + } + if ( pahsc->output.streamInterleavingBuffer != NULL ) + { + PaHost_FreeFastMemory( pahsc->output.streamInterleavingBuffer, pahsc->output.streamInterleavingBufferLen ); + } + + free( pahsc ); + past->past_DeviceData = NULL; + + return paNoError; +} + +/********************************************************************** +** Initialize Host dependant part of API. +*/ +PaError PaHost_Init( void ) +{ + return PaOSX_MaybeQueryDevices(); +} + +/************************************************************************* +** Cleanup device info. +*/ +PaError PaHost_Term( void ) +{ + int i; + + if( sDeviceInfos != NULL ) + { + for( i=0; ipast_DeviceData; + if( pahsc == NULL ) return paInternalError; + return (PaError) past->past_IsActive; +} + +/*****************************************************************************/ +/************** External User API ********************************************/ +/*****************************************************************************/ + +/********************************************************************** +** Query devices and use result. +*/ +PaDeviceID Pa_GetDefaultInputDeviceID( void ) +{ + PaError result = PaOSX_MaybeQueryDevices(); + if( result < 0 ) return result; + return sDefaultInputDeviceID; +} + +PaDeviceID Pa_GetDefaultOutputDeviceID( void ) +{ + PaError result = PaOSX_MaybeQueryDevices(); + if( result < 0 ) return result; + return sDefaultOutputDeviceID; +} + + +/************************************************************************* +** Determine minimum number of buffers required for this host based +** on minimum latency. Because CoreAudio manages latency, this just selects +** a reasonably small number of buffers. +*/ +int Pa_GetMinNumBuffers( int framesPerBuffer, double framesPerSecond ) +{ + int minBuffers; + double denominator; + int minLatencyMsec = PA_MIN_LATENCY_MSEC; + denominator = 1000.0 * framesPerBuffer; + minBuffers = (int) (((minLatencyMsec * framesPerSecond) + denominator - 1) / denominator ); + if( minBuffers < 1 ) minBuffers = 1; + return minBuffers; +} + +/*************************************************************************/ +void Pa_Sleep( long msec ) +{ + usleep( msec * 1000 ); +} + +/*************************************************************************/ +PaTimestamp Pa_StreamTime( PortAudioStream *stream ) +{ + AudioTimeStamp timeStamp; + PaTimestamp streamTime; + PaHostSoundControl *pahsc; + internalPortAudioStream *past = (internalPortAudioStream *) stream; + if( past == NULL ) return paBadStreamPtr; + pahsc = (PaHostSoundControl *) past->past_DeviceData; + + AudioDeviceGetCurrentTime(pahsc->primaryDeviceID, &timeStamp); + + streamTime = ( timeStamp.mFlags & kAudioTimeStampSampleTimeValid) ? + timeStamp.mSampleTime : past->past_FrameCount; + + return streamTime; +} + +/************************************************************************************/ +long Pa_GetHostError() +{ + return sSavedHostError; +} + +/*************************************************************************/ +int Pa_CountDevices() +{ + if( sNumPaDevices <= 0 ) Pa_Initialize(); + return sNumPaDevices; +} + +/************************************************************************* +** PaDeviceInfo structures have already been created +** so just return the pointer. +** +*/ +const PaDeviceInfo* Pa_GetDeviceInfo( PaDeviceID id ) +{ + if( id < 0 || id >= sNumPaDevices ) + return NULL; + + return &sDeviceInfos[id].paInfo; +} + + diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_sgi/pa_sgi.c b/mozilla/zap/zmk/portaudio_v18_1/pa_sgi/pa_sgi.c new file mode 100755 index 00000000000..256b17142f8 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_sgi/pa_sgi.c @@ -0,0 +1,1069 @@ +/* + * $Id: pa_sgi.c,v 1.1.2.1 2005-08-16 20:04:10 alex%croczilla.com Exp $ + * PortAudio Portable Real-Time Audio Library. Copyright (c) 1999-2001 Phil Burk. + * Latest Version at: http://www.portaudio.com + * + * Silicon Graphics (SGI) IRIX implementation by Pieter Suurmond. + * This implementation uses sproc()-spawning, not the POSIX-threads. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * +MODIFICATIONS: + 8/12/2001 - Pieter Suurmond - took the v15 pa_linux_oss.c file and started to adapt for IRIX 6.2. + 8/17/2001 - v15, first unstable alpha release for IRIX, sent to Phil & Ross. + 9/23/2001 - Many fixes and changes: POLLIN for input, not POLLOUT! + 7/04/2002 - Implemented multiple user buffers per host buffer to allow clients that + request smaller buffersizes. + 3/13/2003 - Fixed clicks in full-duplex (wire) mode. Fixed some uninitialised vars, got rid of + all GCC-warnings (-Wall). Tested with MIPS compiler and GCC 3.0.4. on IRIX 6.5 (AL v7). +TODO: + - Dynamically switch to 32 bit float as native format when appropriate (let SGI do the conversion), + and maybe also the other natively supported formats? (might increase performance) + - Implement fancy callback block adapter as described in the PDF by Stephane Letz in the ASIO dir. + +REFERENCES: + - IRIX 6.2 man pages regarding SGI AL library. + - IRIS Digital Media Programming Guide (online books and man-pages come + with IRIX 6.2 and may not be publically available on the internet). +*/ + +#include /* Standard libraries. */ +#include + +#include "../pa_common/portaudio.h" /* (Makefile fails to find in subdirs, -I doesn't work?). */ +#include "../pa_common/pa_host.h" +#include "../pa_common/pa_trace.h" + +#include /* Needed for int oserror(void);. */ +#include +#include +#include +#include /* For schedctl(NDPRI, NDPHIMIN). */ +#include /* fcntl.h needed. */ +#include /* For streams, ioctl(), etc. */ +#include +#include +#include /* System specific (IRIX 6.2-6.5). */ + +/*----------------- MACROS --------------------*/ +#define PRINT(x) { printf x; fflush(stdout); } +#define ERR_RPT(x) PRINT(x) +#define DBUG(x) /* PRINT(x) */ +#define DBUGX(x) /* PRINT(x) */ + +#define MAX_CHARS_DEVNAME (16) +#define MAX_SAMPLE_RATES (8) /* Known from SGI AL there are 7. */ + /* Constants used in 'Pa_GetMinNumBuffers()' below: */ +#define MIN_LATENCY_MSEC (200) /* Used if 'getenv("PA_MIN_LATENCY_MSEC")' fails. */ +#define PA_LATENCY_ENV_NAME ("PA_MIN_LATENCY_MSEC") /* Same names as in file pa_unix.h. */ + +/*------------------------------- IRIX AL specific device info: --------------------------------------*/ +typedef struct internalPortAudioDevice +{ + PaDeviceID pad_DeviceID; /* THIS "ID" IS NEW HERE. */ + long pad_ALdevice; /* SGI-number! */ + double pad_SampleRates[MAX_SAMPLE_RATES]; /* For pointing to from pad_Info */ + char pad_DeviceName[MAX_CHARS_DEVNAME+1]; /* +1 for \0, one more than OSS. */ + PaDeviceInfo pad_Info; /* pad_Info (v15) contains: */ + struct internalPortAudioDevice* pad_Next; /* Singly linked list (NULL=end). */ +} internalPortAudioDevice; + +/*----------------- Structure containing all SGI IRIX specific data: ---------------------------------------*/ +typedef struct PaHostSoundControl +{ + ALconfig pahsc_ALconfigIN, /* IRIX-audio-library-datatype. Configuration */ + pahsc_ALconfigOUT; /* stucts separate for input and output ports. */ + ALport pahsc_ALportIN, /* IRIX-audio-library-datatype. ALports can only be */ + pahsc_ALportOUT; /* unidirectional, so we sometimes need 2 of them. */ + int pahsc_threadPID; /* Sproc()-result, written by PaHost_StartEngine(). */ + + unsigned int pahsc_UserBuffersPerHostBuffer, + pahsc_SamplesPerInputHostBuffer, /* Channels per frame are accounted for. */ + pahsc_SamplesPerOutputHostBuffer, + pahsc_BytesPerInputHostBuffer, /* Size per sample are accounted for. */ + pahsc_BytesPerOutputHostBuffer; + short *pahsc_InputHostBuffer, /* Allocated here, in this file, if necessary. */ + *pahsc_OutputHostBuffer; + + struct itimerval pahsc_EntryTime, /* For measuring CPU utilization (same as linux). */ + pahsc_LastExitTime; + long pahsc_InsideCountSum, + pahsc_TotalCountSum; +} PaHostSoundControl; + +/*-------------------------------------------------------- Shared Data -------------------------------*/ +static internalPortAudioDevice* sDeviceList = NULL; /* FIXME - put Mutex around this shared data. */ +static int sPaHostError = 0; /* Maybe more than one process writing errs!? */ +usema_t *SendSema, /* These variables are shared between the */ + *RcvSema; /* audio handling process and main process. */ +/*--------------------------*/ +long Pa_GetHostError(void) +{ + return (long)sPaHostError; +} + +/*----------------------------- BEGIN CPU UTILIZATION MEASUREMENT -----------------*/ +/* (copied from source pa_linux_oss/pa_linux_oss.c) */ +static void Pa_StartUsageCalculation( internalPortAudioStream *past ) +{ + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + if( pahsc == NULL ) return; + /* Query system timer for usage analysis and to prevent overuse of CPU. */ + getitimer( ITIMER_REAL, &pahsc->pahsc_EntryTime ); +} + +static long SubtractTime_AminusB( struct itimerval *timeA, struct itimerval *timeB ) +{ + long secs = timeA->it_value.tv_sec - timeB->it_value.tv_sec; + long usecs = secs * 1000000; + usecs += (timeA->it_value.tv_usec - timeB->it_value.tv_usec); + return usecs; +} + +static void Pa_EndUsageCalculation( internalPortAudioStream *past ) +{ + struct itimerval currentTime; + long insideCount; + long totalCount; /* Measure CPU utilization during this callback. */ + +#define LOWPASS_COEFFICIENT_0 (0.95) +#define LOWPASS_COEFFICIENT_1 (0.99999 - LOWPASS_COEFFICIENT_0) + + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + if (pahsc == NULL) + return; + if (getitimer( ITIMER_REAL, ¤tTime ) == 0 ) + { + if (past->past_IfLastExitValid) + { + insideCount = SubtractTime_AminusB( &pahsc->pahsc_EntryTime, ¤tTime ); + pahsc->pahsc_InsideCountSum += insideCount; + totalCount = SubtractTime_AminusB( &pahsc->pahsc_LastExitTime, ¤tTime ); + pahsc->pahsc_TotalCountSum += totalCount; + /* DBUG(("insideCount = %d, totalCount = %d\n", insideCount, totalCount )); */ + /* Low pass filter the result because sometimes we get called several times in a row. */ + /* That can cause the TotalCount to be very low which can cause the usage to appear */ + /* unnaturally high. So we must filter numerator and denominator separately!!! */ + if (pahsc->pahsc_InsideCountSum > 0) + { + past->past_AverageInsideCount = ((LOWPASS_COEFFICIENT_0 * past->past_AverageInsideCount) + + (LOWPASS_COEFFICIENT_1 * pahsc->pahsc_InsideCountSum)); + past->past_AverageTotalCount = ((LOWPASS_COEFFICIENT_0 * past->past_AverageTotalCount) + + (LOWPASS_COEFFICIENT_1 * pahsc->pahsc_TotalCountSum)); + past->past_Usage = past->past_AverageInsideCount / past->past_AverageTotalCount; + pahsc->pahsc_InsideCountSum = 0; + pahsc->pahsc_TotalCountSum = 0; + } + } + past->past_IfLastExitValid = 1; + } + pahsc->pahsc_LastExitTime.it_value.tv_sec = 100; + pahsc->pahsc_LastExitTime.it_value.tv_usec = 0; + setitimer( ITIMER_REAL, &pahsc->pahsc_LastExitTime, NULL ); + past->past_IfLastExitValid = 1; +} /*----------- END OF CPU UTILIZATION CODE (from pa_linux_oss/pa_linux_oss.c v15)--------------------*/ + + +/*--------------------------------------------------------------------------------------*/ +PaError translateSGIerror(void) /* Calls oserror(), may be used after an SGI AL-library */ +{ /* call to report via ERR_RPT(), yields a PaError-num. */ + const char* a = "SGI AL "; /* (Not absolutely sure errno came from THIS thread! */ + switch(oserror()) /* Read IRIX man-pages about the _SGI_MP_SOURCE macro.) */ + { + case AL_BAD_OUT_OF_MEM: + ERR_RPT(("%sout of memory.\n", a)); + return paInsufficientMemory; /* Known PaError. */ + case AL_BAD_CONFIG: + ERR_RPT(("%sconfiguration invalid or NULL.\n", a)); + return paHostError; /* Generic PaError. */ + case AL_BAD_CHANNELS: + ERR_RPT(("%schannels not 1,2 or 4.\n", a)); + return paHostError; /* Generic PaError. */ + case AL_BAD_NO_PORTS: + ERR_RPT(("%sout of audio ports.\n", a)); + return paHostError; /* Generic PaError. */ + case AL_BAD_DEVICE: + ERR_RPT(("%swrong device number.\n", a)); + return paHostError; /* Generic PaError. */ + case AL_BAD_DEVICE_ACCESS: + ERR_RPT(("%swrong device access.\n", a)); + return paHostError; /* Generic PaError. */ + case AL_BAD_DIRECTION: + ERR_RPT(("%sinvalid direction.\n", a)); + return paHostError; /* Generic PaError. */ + case AL_BAD_SAMPFMT: + ERR_RPT(("%sdoesn't accept sampleformat.\n", a)); + return paHostError; /* Generic PaError. */ + case AL_BAD_FLOATMAX: + ERR_RPT(("%smax float value is zero.\n", a)); + return paHostError; /* Generic PaError. */ + case AL_BAD_WIDTH: + ERR_RPT(("%sunsupported samplewidth.\n", a)); + return paHostError; /* Generic PaError. */ + case AL_BAD_QSIZE: + ERR_RPT(("%sinvalid queue size.\n", a)); + return paHostError; /* Generic PaError. */ + case AL_BAD_PVBUFFER: + ERR_RPT(("%sPVbuffer null.\n", a)); + return paHostError; /* Generic PaError. */ + case AL_BAD_BUFFERLENGTH_NEG: + ERR_RPT(("%snegative bufferlength.\n", a)); + return paHostError; /* Generic PaError. */ + case AL_BAD_BUFFERLENGTH_ODD: + ERR_RPT(("%sodd bufferlength.\n", a)); + return paHostError; /* Generic PaError. */ + case AL_BAD_PARAM: + ERR_RPT(("%sparameter not valid for device.\n", a)); + return paHostError; /* Generic PaError. */ + default: + ERR_RPT(("%sunknown error.\n", a)); + return paHostError; /* Generic PaError. */ + } +} + +/*------------------------------------------------------------------------------------------*/ +/* Tries to set various rates and formats and fill in the device info structure. */ +static PaError Pa_sgiQueryDevice(long ALdev, /* (AL_DEFAULT_DEVICE) */ + PaDeviceID id, /* (DefaultI|ODeviceID()) */ + char* name, /* (for example "SGI AL") */ + internalPortAudioDevice* pad) /* Result written to pad. */ +{ + long min, max; /* To catch hardware characteristics. */ + ALseterrorhandler(0); /* 0 = turn off the default error handler. */ + /*--------------------------------------------------------------------------------------*/ + pad->pad_ALdevice = ALdev; /* Set the AL device number. */ + pad->pad_DeviceID = id; /* Set the PA device number. */ + if (strlen(name) > MAX_CHARS_DEVNAME) /* MAX_CHARS defined above. */ + { + ERR_RPT(("Pa_QueryDevice(): name too long (%s).\n", name)); + return paHostError; + } + strcpy(pad->pad_DeviceName, name); /* Write name-string. */ + pad->pad_Info.name = pad->pad_DeviceName; /* Set pointer,..hmmm. */ + /*--------------------------------- natively supported sample formats: -----------------*/ + pad->pad_Info.nativeSampleFormats = paInt16; /* Later also include paFloat32 | ..| etc. */ + /* Then also choose other CallConvertXX()! */ + /*--------------------------------- number of available i/o channels: ------------------*/ + if (ALgetminmax(ALdev, AL_INPUT_COUNT, &min, &max)) + return translateSGIerror(); + pad->pad_Info.maxInputChannels = max; + DBUG(("Pa_QueryDevice: maxInputChannels = %d\n", pad->pad_Info.maxInputChannels)) + if (ALgetminmax(ALdev, AL_OUTPUT_COUNT, &min, &max)) + return translateSGIerror(); + pad->pad_Info.maxOutputChannels = max; + DBUG(("Pa_QueryDevice: maxOutputChannels = %d\n", pad->pad_Info.maxOutputChannels)) + /*--------------------------------- supported samplerates: ----------------------*/ + pad->pad_Info.numSampleRates = 7; + pad->pad_Info.sampleRates = pad->pad_SampleRates; + pad->pad_SampleRates[0] = (double)AL_RATE_8000; /* long -> double. */ + pad->pad_SampleRates[1] = (double)AL_RATE_11025; + pad->pad_SampleRates[2] = (double)AL_RATE_16000; + pad->pad_SampleRates[3] = (double)AL_RATE_22050; + pad->pad_SampleRates[4] = (double)AL_RATE_32000; + pad->pad_SampleRates[5] = (double)AL_RATE_44100; + pad->pad_SampleRates[6] = (double)AL_RATE_48000; + if (ALgetminmax(ALdev, AL_INPUT_RATE, &min, &max)) /* Ask INPUT rate-max. */ + return translateSGIerror(); /* double -> long. */ + if (max != (long)(0.5 + pad->pad_SampleRates[6])) /* FP-compare not recommndd. */ + goto weird; + if (ALgetminmax(ALdev, AL_OUTPUT_RATE, &min, &max)) /* Ask OUTPUT rate-max. */ + return translateSGIerror(); + if (max != (long)(0.5 + pad->pad_SampleRates[6])) + { +weird: ERR_RPT(("Pa_sgiQueryDevice() did not confirm max samplerate (%ld)\n",max)); + return paHostError; /* Or make it a warning and just carry on... */ + } + /*-------------------------------------------------------------------------------*/ + return paNoError; +} + + +/*--------------------------------------------------------------------------------*/ +int Pa_CountDevices() /* Name of this function suggests it only counts and */ +{ /* is NOT destructive, it however resets whole PA ! */ + int numDevices = 0; /* Let 's not do that here. */ + internalPortAudioDevice* currentDevice = sDeviceList; /* COPY GLOBAL VAR. */ +#if 0 /* Remains from linux_oss v15: Pa_Initialize(), on */ + if (!currentDevice) /* its turn, calls PaHost_Init() via file pa_lib.c. */ + Pa_Initialize(); /* Isn't that a bit too 'rude'? Don't be too */ +#endif /* friendly to clients that forgot to initialize PA. */ + while (currentDevice) /* Slower but more elegant than the sNumDevices-way: */ + { + numDevices++; + currentDevice = currentDevice->pad_Next; + } + return numDevices; +} + +/*-------------------------------------------------------------------------------*/ +static internalPortAudioDevice *Pa_GetInternalDevice(PaDeviceID id) +{ + int numDevices = 0; + internalPortAudioDevice *res = (internalPortAudioDevice*)NULL; + internalPortAudioDevice *pad = sDeviceList; /* COPY GLOBAL VAR. */ + while (pad) /* pad may be NULL, that's ok, return 0. */ + { /* (Added ->pad_DeviceID field to the pad-struct, Pieter, 2001.) */ + if (pad->pad_DeviceID == id) /* This the device we were looking for? */ + res = pad; /* But keep on(!) counting so we don't */ + numDevices++; /* have to call Pa_CountDevices() later. */ + pad = pad->pad_Next; /* Advance to the next device or NULL. */ + } /* No assumptions about order of ID's in */ + if (!res) /* the list. */ + ERR_RPT(("Pa_GetInternalDevice() could not find specified ID (%d).\n",id)); + if ((id < 0) || (id >= numDevices)) + { + ERR_RPT(("Pa_GetInternalDevice() supplied with an illegal ID (%d).\n",id)); +#if 1 /* Be strict, even when found, */ + res = (internalPortAudioDevice*)NULL; /* do not accept illegal ID's. */ +#endif + } + return res; +} + +/*----------------------------------------------------------------------*/ +const PaDeviceInfo* Pa_GetDeviceInfo(PaDeviceID id) +{ + PaDeviceInfo* res = (PaDeviceInfo*)NULL; + internalPortAudioDevice* pad = Pa_GetInternalDevice(id); /* Call. */ + if (pad) + res = &pad->pad_Info; /* Not finding the specified ID is not */ + if (!res) /* the same as &pad->pad_Info == NULL. */ + ERR_RPT(("Pa_GetDeviceInfo() could not find it (ID=%d).\n", id)); + return res; /* So (maybe) a second/third ERR_RPT(). */ +} + +/*------------------------------------------------*/ +PaDeviceID Pa_GetDefaultInputDeviceID(void) +{ + return 0; /* 0 is the default device ID. */ +} +/*------------------------------------------------*/ +PaDeviceID Pa_GetDefaultOutputDeviceID(void) +{ + return 0; +} + +/*-------------------------------------------------------------------------------------------------*/ +/* Build linked a list with all the available audio devices on this SGI machine (only 1 for now). */ +PaError PaHost_Init(void) /* Called by Pa_Initialize() from pa_lib.c. */ +{ + internalPortAudioDevice* pad; + PaError r = paNoError; + int audioLibFileID; /* To test for the presence of audio. */ + + if (sDeviceList) /* Allow re-init, only warn, no error. */ + { + ERR_RPT(("Warning: PaHost_Init() did not really re-init PA.\n")); + return r; + } + /*------------- ADD THE SGI DEFAULT DEVICE TO THE LIST: ---------------------------------------*/ + audioLibFileID = open("/dev/hdsp/hdsp0master", O_RDONLY); /* Try to open Indigo style audio */ + if (audioLibFileID < 0) /* IO port. On failure, machine */ + { /* has no audio ability. */ + ERR_RPT(("PaHost_Init(): This machine has no (Indigo-style) audio abilities.\n")); + return paHostError; + } + close(audioLibFileID); /* Allocate fast mem to hold device info. */ + pad = PaHost_AllocateFastMemory(sizeof(internalPortAudioDevice)); + if (pad == NULL) + return paInsufficientMemory; + memset(pad, 0, sizeof(internalPortAudioDevice)); /* "pad->pad_Next = NULL" is more elegant. */ + r = Pa_sgiQueryDevice(AL_DEFAULT_DEVICE, /* Set AL device num (AL_DEFAULT_DEVICE). */ + Pa_GetDefaultOutputDeviceID(),/* Set PA device num (or InputDeviceID()). */ + "AL default", /* A suitable name. */ + pad); /* Write args and queried info into pad. */ + if (r != paNoError) + { + ERR_RPT(("Pa_QueryDevice for '%s' returned: %d\n", pad->pad_DeviceName, r)); + PaHost_FreeFastMemory(pad, sizeof(internalPortAudioDevice)); /* sDeviceList still NULL ! */ + } + else + sDeviceList = pad; /* First element in linked list. pad->pad_Next already NULL. */ + /*------------- QUERY AND ADD MORE POSSIBLE SGI DEVICES TO THE LINKED LIST: -------------------*/ + /*---------------------------------------------------------------------------------------------*/ + return r; +} + +/*--------------------------------------------------------------------------------------------*/ +#define MIN(a,b) ((a)<(b)?(a):(b)) /* MIN()-function is used below. */ +#define kPollSEMA 0 /* To index the pollfd-array, reads nicer than just */ +#define kPollOUT 1 /* numbers. */ +#define kPollIN 2 +void Pa_SgiAudioProcess(void *v) /* This function is sproc-ed by PaHost_StartEngine() */ +{ /* as a separate thread. (Argument must be void*). */ + short evtLoop; /* Reset by parent indirectly, or at local errors. */ + PaError result; + struct pollfd PollFD[3]; /* To catch kPollSEMA-, kPollOUT- and kPollIN-events. */ + internalPortAudioStream *past = (internalPortAudioStream*)v; /* Copy void-ptr-argument. */ + PaHostSoundControl *pahsc; + short n, inputEvent, outputEvent, ioEvent, semaEvent = 0; + short *inBuffer, *outBuffer; /* Only 16 bit for now, may change... */ + unsigned int samplesPerInputUserBuffer, samplesPerOutputUserBuffer; + + DBUG(("Entering sproc-thread.\n")); + if (!past) + { + sPaHostError = paInternalError; /* Or paBadStreamPtr ? */ + ERR_RPT(("argument NULL!\n")); + goto noPast; + } + pahsc = (PaHostSoundControl*)past->past_DeviceData; + if (!pahsc) + { + sPaHostError = paInternalError; /* The only way is to signal error to shared area?! */ + ERR_RPT(("past_DeviceData NULL!\n")); + goto noPahsc; /* Sproc-ed threads MAY NOT RETURN paInternalError. */ + } + /*----------------------------- open AL-ports here, after sproc(): -----------------------*/ + if (past->past_NumInputChannels > 0) /* Open input port. */ + { + pahsc->pahsc_ALportIN = ALopenport("PA sgi in", "r", pahsc->pahsc_ALconfigIN); + if (!pahsc->pahsc_ALportIN) + { + ERR_RPT(("Failed to open AL input port.\n")); + sPaHostError = paInternalError; + goto skip; + } + DBUG(("Opened %d input channel(s).\n", past->past_NumInputChannels)); + samplesPerInputUserBuffer = pahsc->pahsc_SamplesPerInputHostBuffer / + pahsc->pahsc_UserBuffersPerHostBuffer; + } + else + samplesPerInputUserBuffer = 0; /* Added 2003. */ + if (past->past_NumOutputChannels > 0) /* Open output port. */ + { + pahsc->pahsc_ALportOUT = ALopenport("PA sgi out", "w", pahsc->pahsc_ALconfigOUT); + if (!pahsc->pahsc_ALportOUT) + { + ERR_RPT(("Failed to open AL output port.\n")); + sPaHostError = paInternalError; /* Assume pahsc_ALconfigs are the */ + goto skip; /* same for IN and OUT in case */ + } /* both ports are opened (bidir). */ + DBUG(("Opened %d output channel(s).\n", past->past_NumOutputChannels)); + samplesPerOutputUserBuffer = pahsc->pahsc_SamplesPerOutputHostBuffer / + pahsc->pahsc_UserBuffersPerHostBuffer; + DBUG(("samplesPerOutputUserBuffer = %d\n", samplesPerOutputUserBuffer)); + } + else + samplesPerOutputUserBuffer = 0; /* Added 2003. */ + /*-----------------------------------------------------------------------*/ + past->past_IsActive = 1; /* Wasn't this already done by the calling parent?! */ + PollFD[kPollIN].fd = ALgetfd(pahsc->pahsc_ALportIN); /* ALgetfd returns -1 on failures */ + PollFD[kPollIN].events = POLLIN; /* such as ALport not there. */ + PollFD[kPollOUT].fd = ALgetfd(pahsc->pahsc_ALportOUT); + PollFD[kPollOUT].events = POLLOUT; /* .events = POLLOUT is OK. */ + schedctl(NDPRI, NDPHIMIN); /* Sets non-degrading priority for this process. */ + PollFD[kPollSEMA].fd = usopenpollsema(SendSema, 0777); /* To communicate with parent. */ + PollFD[kPollSEMA].events = POLLIN; /* .events = POLLIN is OK. */ + uspsema(SendSema); /* Blocks until ... MUST be here, this uspsema(). */ + evtLoop = ((past->past_StopNow | past->past_StopSoon) == 0); + while (evtLoop) + { + /*----------------------------- SET FILLPOINTS AND WAIT UNTIL SOMETHING HAPPENS: ---------*/ + if (pahsc->pahsc_InputHostBuffer) /* Then pahsc_ALportIN should also be there. */ + { + /* For input port, fill point is number of locations in the sample queue that must be */ + /* filled in order to trigger a return from select(). (or poll()) */ + /* Notice IRIX docs mention number of samples as argument, not number of sampleframes.*/ + if (ALsetfillpoint(pahsc->pahsc_ALportIN, pahsc->pahsc_SamplesPerInputHostBuffer)) + { /* Multiple amount as transferred per time. */ + ERR_RPT(("ALsetfillpoint() for ALportIN failed.\n")); + sPaHostError = paInternalError; /* (Using exit(-1) would be a bit rude.) */ + goto skip; + } + } + /* 'else' added march 2003: set only one of both fillpoints: input or output. When */ + /* setting both fillpoints (as in earlier version) clicks occur at full duplex-mode. */ + else if (pahsc->pahsc_OutputHostBuffer) /* Then pahsc_ALportOUT should also be there. */ + { + /* For output port, fill point is number of locations that must be free in order to */ + /* wake up from select(). (or poll()) */ + if (ALsetfillpoint(pahsc->pahsc_ALportOUT, pahsc->pahsc_SamplesPerOutputHostBuffer)) + { + ERR_RPT(("ALsetfillpoint() for ALportOUT failed.\n")); + sPaHostError = paInternalError; + goto skip; + } + } /* poll() with timeout=-1 makes it block until a requested */ + poll(PollFD, 3, -1); /* event occurs or until call is interrupted. If fd-value in */ + /* array <0, events is ignored and revents is set to 0. */ + /*---------------------------- MESSAGE-EVENT FROM PARENT THREAD: -------------------------*/ + semaEvent = PollFD[kPollSEMA].revents & POLLIN; + if (semaEvent) + { + if (past->past_StopSoon) + evtLoop = 0; + if (past->past_StopNow) + goto skip; + } + /*------------------------------------- FILLED-EVENT FROM INPUT BUFFER: --------------------------*/ + inputEvent = PollFD[kPollIN].revents & POLLIN; + if (inputEvent) /* Don't need to check (pahsc->pahsc_InputHostBuffer): */ + { /* if buffer was not there, ALport not there, no events! */ + if (ALreadsamps(pahsc->pahsc_ALportIN, (void*)pahsc->pahsc_InputHostBuffer, + pahsc->pahsc_SamplesPerInputHostBuffer)) + { /* Here again: number of samples instead of number of frames. */ + ERR_RPT(("ALreadsamps() failed.\n")); + sPaHostError = paInternalError; + goto skip; + } + } + outputEvent = PollFD[kPollOUT].revents & POLLOUT; + ioEvent = (inputEvent | outputEvent); /* Binary or is ok. */ + /*------------------------------------- USER-CALLBACK-ROUTINE: -----------------------------------*/ + if (ioEvent) /* Always true? Or can some other system-event awaken the */ + { /* poll? Sure it wasn't just a "sema"- (i.e. user)-event? */ + Pa_StartUsageCalculation(past); /* Convert 16 bit native data to */ + /* user data and call user routine. */ + inBuffer = pahsc->pahsc_InputHostBuffer; /* Short pointers for now, care! */ + outBuffer = pahsc->pahsc_OutputHostBuffer; + n = pahsc->pahsc_UserBuffersPerHostBuffer; /* 'n' may never start at NULL ! */ + do { + result = Pa_CallConvertInt16(past, inBuffer, outBuffer); + if (result) /* This is apparently NOT an error! Just letting the userCallBack stop us. */ + { DBUG(("Pa_CallConvertInt16() returned %d, stopping...\n", result)); goto skip; } + inBuffer += samplesPerInputUserBuffer; /* Num channels is accounted for. */ + outBuffer += samplesPerOutputUserBuffer; + } while (--n); + Pa_EndUsageCalculation(past); + } + /*------------------------------------ FREE-EVENT FROM OUTPUT BUFFER: ---------------------------*/ + if (pahsc->pahsc_OutputHostBuffer && ioEvent) /* Don't wait for outputEvent solely (that may cause clicks). */ + { /* Just assume it's time to write, outputEvent may not yet be there. */ + if (ALwritesamps(pahsc->pahsc_ALportOUT, (void*)pahsc->pahsc_OutputHostBuffer, + pahsc->pahsc_SamplesPerOutputHostBuffer)) + { + ERR_RPT(("ALwritesamps() failed.\n")); /* Better use SEMAS for messaging back to parent! */ + sPaHostError = paInternalError; + goto skip; + } + } + } +skip: + /*------------------------------- close AL-ports ----------------------------*/ + if (pahsc->pahsc_ALportIN) + { + if (ALcloseport(pahsc->pahsc_ALportIN)) + translateSGIerror(); /* Translates SGI AL-code to PA-code and ERR_RPTs string. */ + else /* But go on anyway... to release other stuff... */ + pahsc->pahsc_ALportIN = (ALport)0; + } + if (pahsc->pahsc_ALportOUT) + { + if (ALcloseport(pahsc->pahsc_ALportOUT)) + translateSGIerror(); + else + pahsc->pahsc_ALportOUT = (ALport)0; + } +noPahsc: + past->past_IsActive = 0; + if (semaEvent) + { + uspsema(SendSema); /* StopEngine() was still waiting for this acknowledgement. */ + usvsema(RcvSema); /* (semaEvent initialized with 0.) */ + } +noPast: + DBUG(("Leaving sproc-thread.\n")); +} + + +/*--------------------------------------------------------------------------------------*/ +PaError PaHost_OpenStream(internalPortAudioStream *past) +{ + PaError result = paNoError; + PaHostSoundControl *pahsc; + unsigned int minNumBuffers; + internalPortAudioDevice *padIN, *padOUT; /* For looking up native AL-numbers. */ + long pvbuf[8], sr, alq; /* To get/set hardware configs. */ + + DBUG(("PaHost_OpenStream() called.\n")); /* Alloc FASTMEM and init host data. */ + if (!past) + { + ERR_RPT(("Streampointer NULL!\n")); + result = paBadStreamPtr; goto done; + } + pahsc = (PaHostSoundControl*)PaHost_AllocateFastMemory(sizeof(PaHostSoundControl)); + if (pahsc == NULL) + { + ERR_RPT(("FAST Memory allocation failed.\n")); /* Pass trough some ERR_RPT-exit- */ + result = paInsufficientMemory; goto done; /* code (nothing will be freed). */ + } + memset(pahsc, 0, sizeof(PaHostSoundControl)); + pahsc->pahsc_threadPID = -1; /* Should pahsc_threadPID be inited to */ + past->past_DeviceData = (void*)pahsc; /* -1 instead of 0 ?? */ + /*------------------------------------------ Manipulate hardware if necessary and allowed: --*/ + ALseterrorhandler(0); /* 0 = turn off the default error handler. */ + pvbuf[0] = AL_INPUT_RATE; + pvbuf[2] = AL_INPUT_COUNT; + pvbuf[4] = AL_OUTPUT_RATE; /* TO FIX: rates may be logically, not always in Hz! */ + pvbuf[6] = AL_OUTPUT_COUNT; + sr = (long)(past->past_SampleRate + 0.5); /* Common for both input and output :-) */ + /*-----------------------------------------------------------------------------*/ + /* OVERWRITE 'past_NumUserBuffers'-field in the struct supplied by the caller. */ + /* This field may be set to zero by a client application to ask for minimum */ + /* latency. It is used below, to set both input- and output-AL-queuesizes. */ + minNumBuffers = Pa_GetMinNumBuffers(past->past_FramesPerUserBuffer, + past->past_SampleRate); /* Take biggest. */ + past->past_NumUserBuffers = (minNumBuffers > past->past_NumUserBuffers) ? + minNumBuffers : past->past_NumUserBuffers; + DBUG(("past->past_NumUserBuffers=%d\n", past->past_NumUserBuffers)); + /*----------------------------------------------------------------------------------*/ + pahsc->pahsc_UserBuffersPerHostBuffer = past->past_NumUserBuffers >> 1; + DBUG(("pahsc_UserBuffersPerHostBuffer=%d\n",pahsc->pahsc_UserBuffersPerHostBuffer)); + /* 1 is minimum because Pa_GetMinNumBuffers() returns >= 2. + Callback will be called 'pahsc_UserBuffersPerHostBuffer' times (with 'past_FramesPerUserBuffer') + per host transfer. */ + /*---------------------------------------------------- SET INPUT CONFIGURATION: ---------------------*/ + if (past->past_NumInputChannels > 0) /* We need to lookup the corre- */ + { /* sponding native AL-number(s). */ + /*--------------------------------------------------- Allocate native buffers: --------------*/ + pahsc->pahsc_SamplesPerInputHostBuffer = pahsc->pahsc_UserBuffersPerHostBuffer * + past->past_FramesPerUserBuffer * /* Needed by the */ + past->past_NumInputChannels; /* audio-thread. */ + DBUG(("pahsc_SamplesPerInputHostBuffer=%d\n", pahsc->pahsc_SamplesPerInputHostBuffer)); + pahsc->pahsc_BytesPerInputHostBuffer = pahsc->pahsc_SamplesPerInputHostBuffer * sizeof(short); + pahsc->pahsc_InputHostBuffer = (short*)PaHost_AllocateFastMemory(pahsc->pahsc_BytesPerInputHostBuffer); + if (!pahsc->pahsc_InputHostBuffer) + { + ERR_RPT(("Fast memory allocation failed (in).\n")); + result = paInsufficientMemory; + goto done; + } + padIN = Pa_GetInternalDevice(past->past_InputDeviceID); + if (!padIN) + { + ERR_RPT(("Pa_GetInternalDevice() for input failed.\n")); + result = paHostError; + goto done; + } + if (ALgetparams(padIN->pad_ALdevice, &pvbuf[0], 4)) /* Although input and output will both be on */ + goto sgiError; /* the same AL-device, the AL-library might */ + if (pvbuf[1] != sr) /* contain more than AL_DEFAULT_DEVICE in */ + { /* Rate different from current harware-rate? the future. Therefore 2 seperate queries. */ + if (pvbuf[3] > 0) /* Means, there's other clients using AL-input-ports */ + { + ERR_RPT(("Sorry, not allowed to switch input-hardware to %ld Hz because \ +another process is currently using input at %ld Hz.\n", sr, pvbuf[1])); + result = paHostError; + goto done; + } + pvbuf[1] = sr; /* Then set input-rate. */ + if (ALsetparams(padIN->pad_ALdevice, &pvbuf[0], 2)) + goto sgiError; /* WHETHER THIS SAMPLERATE WAS REALLY PRESENT IN OUR ARRAY OF RATES, */ + } /* IS NOT CHECKED, AT LEAST NOT BY ME, WITHIN THIS FILE! Does PA do? */ + pahsc->pahsc_ALconfigIN = ALnewconfig(); /* Released at PaHost_CloseStream(). */ + if (pahsc->pahsc_ALconfigIN == (ALconfig)0) + goto sgiError; + if (ALsetsampfmt(pahsc->pahsc_ALconfigIN, AL_SAMPFMT_TWOSCOMP))/* Choose paInt16 as native i/o-format. */ + goto sgiError; + if (ALsetwidth (pahsc->pahsc_ALconfigIN, AL_SAMPLE_16)) /* Only meaningful when sample format for */ + goto sgiError; /* config is set to two's complement format. */ + /************************ Future versions might (dynamically) switch to 32-bit floats? ******* + if (ALsetsampfmt(pahsc_ALconfigIN, AL_SAMPFMT_FLOAT)) (Then also call another CallConvert-func.) + goto sgiError; + if (ALsetfloatmax (pahsc_ALconfigIN, 1.0)) Only meaningful when sample format for config + goto sgiError; is set to AL_SAMPFMT_FLOAT or AL_SAMPFMT_DOUBLE. */ + /*--------- Set internal AL queuesize (in samples, not in frames!) -------------------------------*/ + alq = (long)past->past_NumUserBuffers * past->past_FramesPerUserBuffer * past->past_NumInputChannels; + DBUG(("AL input queuesize = %ld samples.\n", alq)); + if (ALsetqueuesize(pahsc->pahsc_ALconfigIN, alq)) + goto sgiError; + if (ALsetchannels (pahsc->pahsc_ALconfigIN, (long)(past->past_NumInputChannels))) + goto sgiError; /* Returns 0 on success, -1 on failure. */ + } + else + pahsc->pahsc_InputHostBuffer = (short*)NULL; /* Added 2003! Is checked in callback-routine. */ + /*---------------------------------------------------- SET OUTPUT CONFIGURATION: ------------------------*/ + if (past->past_NumOutputChannels > 0) /* CARE: padOUT/IN may NOT be NULL if Channels <= 0! */ + { /* We use padOUT/IN later on, or at least 1 of both. */ + pahsc->pahsc_SamplesPerOutputHostBuffer = pahsc->pahsc_UserBuffersPerHostBuffer * + past->past_FramesPerUserBuffer * /* Needed by the */ + past->past_NumOutputChannels; /* audio-thread. */ + DBUG(("pahsc_SamplesPerOutputHostBuffer=%d\n", pahsc->pahsc_SamplesPerOutputHostBuffer)); + pahsc->pahsc_BytesPerOutputHostBuffer = pahsc->pahsc_SamplesPerOutputHostBuffer * sizeof(short); + pahsc->pahsc_OutputHostBuffer = (short*)PaHost_AllocateFastMemory(pahsc->pahsc_BytesPerOutputHostBuffer); + if (!pahsc->pahsc_OutputHostBuffer) + { + ERR_RPT(("Fast memory allocation failed (out).\n")); + result = paInsufficientMemory; + goto done; + } + padOUT = Pa_GetInternalDevice(past->past_OutputDeviceID); + if (!padOUT) + { + ERR_RPT(("Pa_GetInternalDevice() for output failed.\n")); + result = paHostError; + goto done; + } + if (ALgetparams(padOUT->pad_ALdevice,&pvbuf[4], 4)) + goto sgiError; + if (pvbuf[5] != sr) + { /* Output needed and rate different from current harware-rate. */ + if (pvbuf[7] > 0) /* Means, there's other clients using AL-output-ports */ + { + ERR_RPT(("Sorry, not allowed to switch output-hardware to %ld Hz because \ +another process is currently using output at %ld Hz.\n", sr, pvbuf[5])); + result = paHostError; + goto done; /* Will free again the inputbuffer */ + } /* that was just created above. */ + pvbuf[5] = sr; /* Then set output-rate. */ + if (ALsetparams(padOUT->pad_ALdevice, &pvbuf[4], 2)) + goto sgiError; + } + pahsc->pahsc_ALconfigOUT = ALnewconfig(); /* Released at PaHost_CloseStream(). */ + if (pahsc->pahsc_ALconfigOUT == (ALconfig)0) + goto sgiError; + if (ALsetsampfmt(pahsc->pahsc_ALconfigOUT, AL_SAMPFMT_TWOSCOMP)) /* Choose paInt16 as native i/o-format. */ + goto sgiError; + if (ALsetwidth (pahsc->pahsc_ALconfigOUT, AL_SAMPLE_16)) /* Only meaningful when sample format for */ + goto sgiError; /* config is set to two's complement format. */ + /** Future versions might (dynamically) switch to 32-bit floats. **/ + alq = (long)past->past_NumUserBuffers * past->past_FramesPerUserBuffer * past->past_NumOutputChannels; + DBUG(("AL output queuesize = %ld samples.\n", alq)); + if (ALsetqueuesize(pahsc->pahsc_ALconfigOUT, alq)) + goto sgiError; + if (ALsetchannels (pahsc->pahsc_ALconfigOUT, (long)(past->past_NumOutputChannels))) + goto sgiError; + } + else + pahsc->pahsc_OutputHostBuffer = (short*)NULL; + /*----------------------------------------------- TEST DEVICE ID's: --------------------*/ + if ((past->past_OutputDeviceID != past->past_InputDeviceID) && /* Who SETS these devive-numbers? */ + (past->past_NumOutputChannels > 0) && (past->past_NumInputChannels > 0)) + { + ERR_RPT(("Cannot setup bidirectional stream between different devices.\n")); + result = paHostError; + goto done; + } + goto done; /* (no errors occured) */ +sgiError: + result = translateSGIerror(); /* Translates SGI AL-code to PA-code and ERR_RPTs string. */ +done: + if (result != paNoError) + PaHost_CloseStream(past); /* Frees memory (only if really allocated!). */ + return result; +} + +/*-----------------------------------------------------*/ +PaError PaHost_StartOutput(internalPortAudioStream *past) +{ + return paNoError; /* Hmm, not implemented yet? */ +} +PaError PaHost_StartInput(internalPortAudioStream *past) +{ + return paNoError; +} + +/*------------------------------------------------------------------------------*/ +PaError PaHost_StartEngine(internalPortAudioStream *past) +{ + PaHostSoundControl *pahsc; + usptr_t *arena; + if (!past) /* Test argument. */ + { + ERR_RPT(("PaHost_StartEngine(NULL)!\n")); + return paBadStreamPtr; + } + pahsc = (PaHostSoundControl*)past->past_DeviceData; + if (!pahsc) + { + ERR_RPT(("PaHost_StartEngine(arg): arg->past_DeviceData = NULL!\n")); + return paHostError; + } + past->past_StopSoon = 0; /* Assume SGI ALport is already opened! */ + past->past_StopNow = 0; /* Why don't we check pahsc for NULL? */ + past->past_IsActive = 1; + + /* Although the pthread_create() function, as well as , may be */ + /* available in IRIX, use sproc() on SGI to create audio-background-thread. */ + /* (Linux/oss uses pthread_create() instead of __clone() because: */ + /* - pthread_create also works for other UNIX systems like Solaris, */ + /* - Java HotSpot VM crashes in pthread_setcanceltype() using __clone().) */ + + usconfig(CONF_ARENATYPE, US_SHAREDONLY); /* (From SGI-AL-examples, file */ + arena = usinit(tmpnam(0)); /* motifexample.c, function */ + SendSema = usnewpollsema(arena, 0); /* InitializeAudioProcess().) */ + RcvSema = usnewsema(arena, 1); /* 1= common mutual exclusion semaphore, where 1 and only 1 process + will be permitted through a semaphore at a time. Values > 1 + imply that up to val resources may be simultaneously used, but requests + for more than val resources cause the calling process to block until a + resource comes free (by a process holding a resource performing a + usvsema(). IS THIS usnewsema() TOO PLATFORM SPECIFIC? */ + prctl(PR_SETEXITSIG, 0); /* No not (void*)9, but 0, which doesn't kill the parent! */ + /* PR_SETEXITSIG controls whether all members of a share group will be + signaled if any one of them leaves the share group (either via exit() + or exec()). If 2nd arg, interpreted as an int is 0, then normal IRIX + process termination rules apply, namely that the parent is sent a + SIGCLD upon death of child, but no indication of death of parent is + given. If the second argument is a valid signal number then if any + member of a share group leaves the share group, a signal is + sent to ALL surviving members of the share group. */ + /* SPAWN AUDIO-CHILD: */ + pahsc->pahsc_threadPID = sproc(Pa_SgiAudioProcess, /* Returns process ID of */ + PR_SALL, /* new process, or -1. */ + (void*)past); /* Pass past as optional */ /* IS THIS SAFE, will past never */ + if (pahsc->pahsc_threadPID == -1) /* third void-ptr-arg. */ /* be moved around in memory???? */ + { + ERR_RPT(("PaHost_StartEngine() failed to spawn audio-thread.\n")); + sPaHostError = oserror(); /* Pass native error-number to shared area. */ + return paHostError; /* But return the generic error-number. */ + } + return paNoError; /* Hmmm, errno may come from other threads in same group! */ +} /* ("man sproc" in IRIX6.2 to read about _SGI_MP_SOURCE.) */ + +/*------------------------------------------------------------------------------*/ +PaError PaHost_StopEngine(internalPortAudioStream *past, int abort) +{ + PaError result = paNoError; + PaHostSoundControl *pahsc; + + DBUG(("PaHost_StopEngine() called.\n")); + if (!past) + return paBadStreamPtr; + pahsc = (PaHostSoundControl*)past->past_DeviceData; + /* Prevent from doing this twice!! */ + if ((!pahsc) || /* Some tests call this CLOSE twice!! */ + (!past->past_IsActive) || + past->past_StopSoon || past->past_StopNow) + return result; /* paNoError (already stopped, no err?). */ + past->past_StopSoon = 1; /* Tell background thread to stop generating */ + if (abort) /* more and to let current data play out. If */ + past->past_StopNow = 1; /* aborting, tell backgrnd thread to stop NOW! */ + /*---- USE SEMAPHORE LOCK TO COMMUNICATE: -----*/ + usvsema(SendSema); /* Increments count associated with SendSema. */ + /* Wait for the response. */ + uspsema(RcvSema); /* Decrements count of previously allocated */ + /* semaphore specified by RcvSema. */ + while (past->past_IsActive) /* REALLY WAIT. */ + { + /* DBUG(("wait 1 ms for audio-thread to stop.\n")); */ + Pa_Sleep(1); + } + +#if 0 /* We don't need to KILL(), just COMMUNICATE and be patient... */ + if (pahsc->pahsc_threadPID != -1) /* Did we really init it to -1 somewhere? */ + { + DBUG(("PaHost_StopEngine() is about to kill(SIGKILL) audio-thread.\n")); + if (kill(pahsc->pahsc_threadPID, SIGKILL)) /* Or SIGTERM or SIGQUIT(core) */ + { /* Returns -1 in case of error. */ + result = paHostError; + sPaHostError = oserror(); /* Hmmm, other threads may also write here! */ + ERR_RPT(("PaHost_StopEngine() failed to kill audio-thread.\n")); + } + else + pahsc->pahsc_threadPID = -1; /* Notify that we've killed this thread. */ + } +#endif + past->past_IsActive = 0; /* Even when kill() failed and pahsc_threadPID still there??? */ + return result; +} + +/*---------------------------------------------------------------*/ +PaError PaHost_StopOutput(internalPortAudioStream *past, int abort) +{ + return paNoError; /* Not implemented yet? */ +} +PaError PaHost_StopInput(internalPortAudioStream *past, int abort ) +{ + return paNoError; +} + +/*******************************************************************/ +PaError PaHost_CloseStream(internalPortAudioStream *past) +{ + PaHostSoundControl *pahsc; + PaError result = paNoError; + + DBUG(("PaHost_CloseStream() called.\n")); + if (!past) + return paBadStreamPtr; + pahsc = (PaHostSoundControl *) past->past_DeviceData; + if (!pahsc) /* If pahsc not NULL, past_DeviceData will be freed, and set to NULL. */ + return result; /* This test prevents from freeing NULL-pointers. */ + + if (pahsc->pahsc_ALconfigIN) + { /* Release configuration structs, only if allocated. */ + ALfreeconfig(pahsc->pahsc_ALconfigIN); + pahsc->pahsc_ALconfigIN = NULL; + } + if (pahsc->pahsc_ALconfigOUT) + { + ALfreeconfig(pahsc->pahsc_ALconfigOUT); /* (Al-ports were already closed by audioProcess). */ + pahsc->pahsc_ALconfigOUT = NULL; + } + if (pahsc->pahsc_InputHostBuffer) + { + PaHost_FreeFastMemory(pahsc->pahsc_InputHostBuffer, pahsc->pahsc_BytesPerInputHostBuffer); + pahsc->pahsc_InputHostBuffer = NULL; + } + if (pahsc->pahsc_OutputHostBuffer) + { + PaHost_FreeFastMemory(pahsc->pahsc_OutputHostBuffer, pahsc->pahsc_BytesPerOutputHostBuffer); + pahsc->pahsc_OutputHostBuffer = NULL; + } + PaHost_FreeFastMemory(pahsc, sizeof(PaHostSoundControl)); + past->past_DeviceData = NULL; /* PaHost_OpenStream() allocated FAST MEM. */ + return result; +} + + +/*------------------------------------------------------------------------*/ +/* Determine minimum number of buffers required for (SGI) host based on */ +/* minimum latency. Latency can be optionally set by user by setting an */ +/* environment variable. For example, to set my latency to 200 msec, I've */ +/* put this line in my '.cshrc' file: setenv PA_MIN_LATENCY_MSEC 200 */ +/* It always calls the 'PRINT' macro. */ +/* The minimum number that is returned is 2. */ +/* This number is directly proportional to the AL-queue sizes to set up. */ +/* It is one more than the number of user buffers per host buffer - in */ +/* case minimum is returned, or, twice the user buffers per host buffer. */ +/*------------------------------------------------------------------------*/ +int Pa_GetMinNumBuffers(int framesPerUserBuffer, double framesPerSecond) +{ + int minBuffers, minLatencyMsec; + char *minLatencyText; + double actualLatency; + + minLatencyText = getenv(PA_LATENCY_ENV_NAME); /* Defined at top of file. */ + if (minLatencyText) + { + minLatencyMsec = atoi(minLatencyText); + if (minLatencyMsec < 10) + { /* 10 is the minimum. */ + minLatencyMsec = 10; + PRINT (("Environment variable 'PA_MIN_LATENCY_MSEC' below minimum of %d milliseconds.\n", + minLatencyMsec)); + } + else if (minLatencyMsec > 4000) + { /* 4000 is the maximum. */ + minLatencyMsec = 4000; + PRINT (("Environment variable 'PA_MIN_LATENCY_MSEC' above maximum of %d milliseconds.\n", + minLatencyMsec)); + } + else + PRINT (("Using environment variable 'PA_MIN_LATENCY_MSEC' (set to %d milliseconds).\n", + minLatencyMsec)); + } + else + { + minLatencyMsec = MIN_LATENCY_MSEC; /* Defined at top of this file. */ + PRINT (("Environment variable 'PA_MIN_LATENCY_MSEC' not found.\nUsing default of %d milliseconds\n", + minLatencyMsec)); + } + minBuffers = (int)((minLatencyMsec * framesPerSecond) / + (1000.0 * framesPerUserBuffer)); + if (minBuffers < 2) + minBuffers = 2; + actualLatency = 1000.0 * minBuffers * framesPerUserBuffer / framesPerSecond; + PRINT (("Actual AL latency set to %.2f milliseconds\n", actualLatency)); + return minBuffers; +} + +/*---------------------------------------------------------------------*/ +PaError PaHost_Term(void) /* Frees all of the linked audio-devices. */ +{ /* Called by Pa_Terminate() from pa_lib.c. */ + internalPortAudioDevice *pad = sDeviceList, + *nxt; + while (pad) + { + DBUG(("PaHost_Term: freeing %s\n", pad->pad_DeviceName)); + nxt = pad->pad_Next; + PaHost_FreeFastMemory(pad, sizeof(internalPortAudioDevice)); + pad = nxt; /* PaHost_Init allocated this fast mem.*/ + } + sDeviceList = (internalPortAudioDevice*)NULL; + return 0; +} + +/***********************************************************************/ +void Pa_Sleep( long msec ) /* Sleep requested number of milliseconds. */ +{ +#if 0 + struct timeval timeout; + timeout.tv_sec = msec / 1000; + timeout.tv_usec = (msec % 1000) * 1000; + select(0, NULL, NULL, NULL, &timeout); +#else + long usecs = msec * 1000; + usleep( usecs ); +#endif +} + +/*---------------------------------------------------------------------------------------*/ +/* Allocate memory that can be accessed in real-time. This may need to be held in physi- */ +/* cal memory so that it is not paged to virtual memory. This call MUST be balanced with */ +/* a call to PaHost_FreeFastMemory(). */ +void *PaHost_AllocateFastMemory(long numBytes) +{ + void *addr = malloc(numBytes); /* mpin() reads into memory all pages over the given */ + if (addr) /* range and locks the pages into memory. A counter */ + { /* is incremented each time the page is locked. The */ + if (mpin(addr, numBytes)) /* superuser can lock as many pages as it wishes, */ + { /* others are limited to the configurable PLOCK_MA. */ + ERR_RPT(("PaHost_AllocateFastMemory() failed to mpin() memory.\n")); +#if 1 + free(addr); /* You MAY cut out these 2 lines to be less strict, */ + addr = NULL; /* you then only get the warning but PA goes on... */ +#endif /* Only problem then may be corresponding munpin() */ + } /* call at PaHost_FreeFastMemory(), below. */ + memset(addr, 0, numBytes); /* Locks established with mlock are not inherited by */ + } /* a child process after a fork. Furthermore, IRIX- */ + return addr; /* man-pages warn against mixing both mpin and mlock */ +} /* in 1 piece of code, so stick to mpin()/munpin() ! */ + + +/*---------------------------------------------------------------------------------------*/ +/* Free memory that could be accessed in real-time. This call MUST be balanced with a */ +/* call to PaHost_AllocateFastMemory(). */ +void PaHost_FreeFastMemory(void *addr, long numBytes) +{ + if (addr) + { + if (munpin(addr, numBytes)) /* Will munpin() fail when it was never mpinned? */ + ERR_RPT(("WARNING: PaHost_FreeFastMemory() failed to munpin() memory.\n")); + free(addr); /* But go on, try to release it, just warn... */ + } +} + +/*----------------------------------------------------------*/ +PaError PaHost_StreamActive( internalPortAudioStream *past ) +{ + PaHostSoundControl *pahsc; + if (past == NULL) + return paBadStreamPtr; + pahsc = (PaHostSoundControl *) past->past_DeviceData; + if (pahsc == NULL) + return paInternalError; + return (PaError)(past->past_IsActive != 0); +} + +/*-------------------------------------------------------------------*/ +PaTimestamp Pa_StreamTime( PortAudioStream *stream ) +{ + internalPortAudioStream *past = (internalPortAudioStream *) stream; +/* FIXME - return actual frames played, not frames generated. +** Need to query the output device somehow. +*/ + return past->past_FrameCount; +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_sgi/pthread-Makefile b/mozilla/zap/zmk/portaudio_v18_1/pa_sgi/pthread-Makefile new file mode 100755 index 00000000000..f207d22dd4c --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_sgi/pthread-Makefile @@ -0,0 +1,52 @@ +# Make PortAudio for Silicon Graphics IRIX (6.2) +# Pieter suurmond, september 22, 2001. (v15 pa_sgi sub-version #0.18) + +# pthread, math (as with linux) and SGI audio library: +# SGI-books say -lpthread should be the last on the line. +LIBS = -lm -laudio -lpthread + +CDEFINES = -I../pa_common + +# Possible CFLAGS with MIPSpro compiler are: -32, -o32, -n32, -64, +# -mips1, -mips2, -mips3, -mips4, etc. Use -g, -g2, -g3 for debugging. +# And use for example -O2 or -O3 for better optimization: +CFLAGS = -O2 +PASRC = ../pa_common/pa_lib.c pa_sgi.c +PAINC = ../pa_common/portaudio.h + +# Tests that work (SGI Indy with R5000 @ 180MHz running IRIX 6.2). +#TESTC = $(PASRC) ../pa_tests/patest_record.c # OK +#TESTC = $(PASRC) ../pa_tests/patest_many.c # OK +#TESTC = $(PASRC) ../pa_tests/patest_latency.c # OK +#TESTC = $(PASRC) ../pa_tests/patest_longsine.c # OK but needs more than 4 buffers to do without glitches. +TESTC = $(PASRC) ../pa_tests/patest_saw.c # Seems OK (does it gracefully exit?). +#TESTC = $(PASRC) ../pa_tests/patest_wire.c # OK +#TESTC = $(PASRC) ../pa_tests/pa_devs.c # OK +#TESTC = $(PASRC) ../pa_tests/patest_sine.c # OK +#TESTC = $(PASRC) ../pa_tests/patest_sine_time.c # OK +#TESTC = $(PASRC) ../pa_tests/patest_sine8.c # OK +#TESTC = $(PASRC) ../pa_tests/patest_leftright.c # OK +#TESTC = $(PASRC) ../pa_tests/patest_pink.c # OK +#TESTC = $(PASRC) ../pa_tests/patest_clip.c # OK +#TESTC = $(PASRC) ../pa_tests/patest_stop.c # OK +#TESTC = $(PASRC) ../pa_tests/patest_dither.c # OK +#TESTC = $(PASRC) ../pa_tests/patest_sync.c # BEEPS and delta's, no crashes anymore. + +# Tests that do not yet work. +#TESTC = $(PASRC) ../pa_tests/paqa_devs.c # Heavy crash with core-dump after PaHost_OpenStream: opening 1 output channel(s) on AL default +#TESTC = $(PASRC) ../pa_tests/paqa_errs.c # Heavy crash with core-dump after PaHost_OpenStream: opening 2 output channel(s) on AL default +#TESTC = $(PASRC) ../pa_tests/pa_fuzz.c # THIS FUZZ CRASHED MY WHOLE IRIX SYSTEM after "ENTER"! :-( + # PROCESS IN ITSELF RUNS OK, WITH LARGER BUFFSIZES THOUGH. + # OH MAYBE IT WAS BECAUSE DEBUGGING WAS ON??? + # ANYWAY, I'M NOT GONNA RUN THAT AGAIN... WAY TOO DANGEROUS! +TESTH = $(PAINC) + +all: patest + +# "cc" for the MIPSpro compiler, may be changed to "gcc": +patest: $(TESTC) $(TESTH) Makefile + cc $(CFLAGS) $(TESTC) $(CDEFINES) $(LIBS) -o patest + +run: patest + ./patest + diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_sgi/pthread-pa_sgi.c b/mozilla/zap/zmk/portaudio_v18_1/pa_sgi/pthread-pa_sgi.c new file mode 100755 index 00000000000..c010c1d62d5 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_sgi/pthread-pa_sgi.c @@ -0,0 +1,908 @@ +/* + * PortAudio Portable Real-Time Audio Library + * Latest Version at: http://www.portaudio.com + * SGI IRIX implementation by Pieter Suurmond, september 22, 2001 (#0.18). + * + * Copyright (c) 1999-2001 Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +/* +Modfication History: + 8/12/2001 - Pieter Suurmond - took the v15 pa_linux_oss.c file and started to adapt for IRIX 6.2. + 8/17/2001 - alpha release with IRIX sproc()-method, may sometimes let IRIX6.2 crash at closing audiostream. + 9/22/2001 - #0.18 pthread starts to work a bit: + BUT UNDER IRIX6.2, I DON'T GET IT TO WORK REALLY CORRECTLY, + this POSIX-attempt, + DON'T USE THIS FILE FOR RELIABLE OPERATION, IT IS HERE JUST + FOR DOCUMENTATION/ARCHIVE... OR FOR ANYONE WHO WANTS TO FIX...... +TODO: + - Test under IRIX 6.5. + - Dynamically switch to 32 bit float as native format when appropriate (let SGI do the conversion), + and maybe also the other natively supported formats? (might increase performance) + - Not sure whether CPU UTILIZATION MEASUREMENT (from OSS/linux) really works. Changed nothing yet, + seems ok, but I've not yet tested it thoroughly. (maybe utilization-code may be made _unix_common_ then?) + - The minimal number of buffers setting... I do not yet fully understand it.. I now just take *4. +REFERENCES: + - IRIX 6.2 man pages regarding SGI AL library. + - IRIS Digital MediaProgramming Guide (online books as well as man-pages come with IRIX 6.2 and + may not be publically available on the internet). +*/ + +#include /* Standard libraries. */ +#include + +#include "../pa_common/portaudio.h" /* Portaudio headers. */ +#include "../pa_common/pa_host.h" +#include "../pa_common/pa_trace.h" + +/* +#include +#include +#include Not needed +#include +#include +#include +#include Needed? +#include +#include sched_param struct and related functions + used in setting thread priorities. +#include Some POSIX constants such as _POSIX_THREAD_THREADS_MAX +*/ + +#include /* Pthreads are supported by IRIX 6.2 after */ + /* patches 1361, 1367, and 1429 are applied. */ + +#include /* fcntl.h needed for "O_RDONLY". */ +#include /* For usleep() and constants used when calling sysconf() */ + /* to query POSIX limits (see the sysconf(3) ref. page. */ + +#include /* SGI-specific audio library. */ + + +/*--------------------------------------------*/ +#define PRINT(x) { printf x; fflush(stdout); } +#define ERR_RPT(x) PRINT(x) +#define DBUG(x) PRINT(x) +#define DBUGX(x) /* PRINT(x) */ + +#define MAX_CHARS_DEVNAME (16) /* Was 32 in OSS (20 for AL but "in"/"out" is concat. */ +#define MAX_SAMPLE_RATES (8) /* Known from SGI AL there are 7 (was 10 in OSS v15). */ + +typedef struct internalPortAudioDevice /* IRIX specific device info: */ +{ + PaDeviceID /* NEW: */ pad_DeviceID; /* THIS "ID" IS NEW HERE (Pieter)! */ + long pad_ALdevice; /* SGI-number! */ + double pad_SampleRates[MAX_SAMPLE_RATES]; /* for pointing to from pad_Info */ + char pad_DeviceName[MAX_CHARS_DEVNAME+1]; /* +1 for \0, one more than OSS. */ + PaDeviceInfo pad_Info; /* pad_Info (v15) contains: */ + /* int structVersion; */ + /* const char* name; */ + /* int maxInputChannels, maxOutputChannels; */ + /* int numSampleRates; Num rates, or -1 if range supprtd. */ + /* const double* sampleRates; Array of supported sample rates, */ + /* PaSampleFormat nativeSampleFormats; or {min,max} if range supported. */ + struct internalPortAudioDevice* pad_Next; /* Singly linked list, (NULL=end). */ +} internalPortAudioDevice; + +typedef struct PaHostSoundControl /* Structure to contain all SGI IRIX specific data. */ +{ + ALport pahsc_ALportIN, /* IRIX-audio-library-datatype. ALports can only be */ + pahsc_ALportOUT; /* unidirectional, so we sometimes need 2 of them. */ + pthread_t pahsc_ThreadPID; + short *pahsc_NativeInputBuffer, /* Allocated here, in this file, if necessary. */ + *pahsc_NativeOutputBuffer; + unsigned int pahsc_BytesPerInputBuffer, /* Native buffer sizes in bytes, really needed here */ + pahsc_BytesPerOutputBuffer; /* to free FAST memory, if buffs were alloctd FAST. */ + unsigned int pahsc_SamplesPerInputBuffer, /* These amounts are needed again and again in the */ + pahsc_SamplesPerOutputBuffer; /* audio-thread (don't need to be kept globally). */ + struct itimerval pahsc_EntryTime, /* For measuring CPU utilization (same as linux). */ + pahsc_LastExitTime; + long pahsc_InsideCountSum, + pahsc_TotalCountSum; +} PaHostSoundControl; + +/*----------------------------- Shared Data ------------------------------------------------------*/ +static internalPortAudioDevice* sDeviceList = NULL; /* FIXME - put Mutex around this shared data. */ +static int sPaHostError = 0; /* Maybe more than one process writing errs!? */ + +long Pa_GetHostError(void) +{ + return (long)sPaHostError; +} + +/*----------------------------- BEGIN CPU UTILIZATION MEASUREMENT -----------------*/ +/* (copied from source pa_linux_oss/pa_linux_oss.c) */ +static void Pa_StartUsageCalculation( internalPortAudioStream *past ) +{ + struct itimerval itimer; + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + if( pahsc == NULL ) return; +/* Query system timer for usage analysis and to prevent overuse of CPU. */ + getitimer( ITIMER_REAL, &pahsc->pahsc_EntryTime ); +} + +static long SubtractTime_AminusB( struct itimerval *timeA, struct itimerval *timeB ) +{ + long secs = timeA->it_value.tv_sec - timeB->it_value.tv_sec; + long usecs = secs * 1000000; + usecs += (timeA->it_value.tv_usec - timeB->it_value.tv_usec); + return usecs; +} + +static void Pa_EndUsageCalculation( internalPortAudioStream *past ) +{ + struct itimerval currentTime; + long insideCount; + long totalCount; /* Measure CPU utilization during this callback. */ + +#define LOWPASS_COEFFICIENT_0 (0.95) +#define LOWPASS_COEFFICIENT_1 (0.99999 - LOWPASS_COEFFICIENT_0) + + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + if (pahsc == NULL) + return; + if (getitimer( ITIMER_REAL, ¤tTime ) == 0 ) + { + if (past->past_IfLastExitValid) + { + insideCount = SubtractTime_AminusB( &pahsc->pahsc_EntryTime, ¤tTime ); + pahsc->pahsc_InsideCountSum += insideCount; + totalCount = SubtractTime_AminusB( &pahsc->pahsc_LastExitTime, ¤tTime ); + pahsc->pahsc_TotalCountSum += totalCount; + /* DBUG(("insideCount = %d, totalCount = %d\n", insideCount, totalCount )); */ + /* Low pass filter the result because sometimes we get called several times in a row. */ + /* That can cause the TotalCount to be very low which can cause the usage to appear */ + /* unnaturally high. So we must filter numerator and denominator separately!!! */ + if (pahsc->pahsc_InsideCountSum > 0) + { + past->past_AverageInsideCount = ((LOWPASS_COEFFICIENT_0 * past->past_AverageInsideCount) + + (LOWPASS_COEFFICIENT_1 * pahsc->pahsc_InsideCountSum)); + past->past_AverageTotalCount = ((LOWPASS_COEFFICIENT_0 * past->past_AverageTotalCount) + + (LOWPASS_COEFFICIENT_1 * pahsc->pahsc_TotalCountSum)); + past->past_Usage = past->past_AverageInsideCount / past->past_AverageTotalCount; + pahsc->pahsc_InsideCountSum = 0; + pahsc->pahsc_TotalCountSum = 0; + } + } + past->past_IfLastExitValid = 1; + } + pahsc->pahsc_LastExitTime.it_value.tv_sec = 100; + pahsc->pahsc_LastExitTime.it_value.tv_usec = 0; + setitimer( ITIMER_REAL, &pahsc->pahsc_LastExitTime, NULL ); + past->past_IfLastExitValid = 1; +} /*----------- END OF CPU UTILIZATION CODE (from pa_linux_oss/pa_linux_oss.c v15)--------------------*/ + + +/*--------------------------------------------------------------------------------------*/ +PaError translateSGIerror(void) /* Calls oserror(), may be used after an SGI AL-library */ +{ /* call to report via ERR_RPT(), yields a PaError-num. */ + const char* a = "SGI AL "; /* (Not absolutely sure errno came from THIS thread! */ + switch(oserror()) /* Read IRIX man-pages about the _SGI_MP_SOURCE macro.) */ + { + case AL_BAD_OUT_OF_MEM: + ERR_RPT(("%sout of memory.\n", a)); + return paInsufficientMemory; /* Known PaError. */ + case AL_BAD_CONFIG: + ERR_RPT(("%sconfiguration invalid or NULL.\n", a)); + return paHostError; /* Generic PaError. */ + case AL_BAD_CHANNELS: + ERR_RPT(("%schannels not 1,2 or 4.\n", a)); + return paHostError; /* Generic PaError. */ + case AL_BAD_NO_PORTS: + ERR_RPT(("%sout of audio ports.\n", a)); + return paHostError; /* Generic PaError. */ + case AL_BAD_DEVICE: + ERR_RPT(("%swrong device number.\n", a)); + return paHostError; /* Generic PaError. */ + case AL_BAD_DEVICE_ACCESS: + ERR_RPT(("%swrong device access.\n", a)); + return paHostError; /* Generic PaError. */ + case AL_BAD_DIRECTION: + ERR_RPT(("%sinvalid direction.\n", a)); + return paHostError; /* Generic PaError. */ + case AL_BAD_SAMPFMT: + ERR_RPT(("%sdoesn't accept sampleformat.\n", a)); + return paHostError; /* Generic PaError. */ + case AL_BAD_FLOATMAX: + ERR_RPT(("%smax float value is zero.\n", a)); + return paHostError; /* Generic PaError. */ + case AL_BAD_WIDTH: + ERR_RPT(("%sunsupported samplewidth.\n", a)); + return paHostError; /* Generic PaError. */ + case AL_BAD_QSIZE: + ERR_RPT(("%sinvalid queue size.\n", a)); + return paHostError; /* Generic PaError. */ + case AL_BAD_PVBUFFER: + ERR_RPT(("%sPVbuffer null.\n", a)); + return paHostError; /* Generic PaError. */ + case AL_BAD_BUFFERLENGTH_NEG: + ERR_RPT(("%snegative bufferlength.\n", a)); + return paHostError; /* Generic PaError. */ + case AL_BAD_BUFFERLENGTH_ODD: + ERR_RPT(("%sodd bufferlength.\n", a)); + return paHostError; /* Generic PaError. */ + case AL_BAD_PARAM: + ERR_RPT(("%sparameter not valid for device.\n", a)); + return paHostError; /* Generic PaError. */ + default: + ERR_RPT(("%sunknown error.\n", a)); + return paHostError; /* Generic PaError. */ + } +} + +/*------------------------------------------------------------------------------------------*/ +/* Tries to set various rates and formats and fill in the device info structure. */ +static PaError Pa_sgiQueryDevice(long ALdev, /* (AL_DEFAULT_DEVICE) */ + PaDeviceID id, /* (DefaultI|ODeviceID()) */ + char* name, /* (for example "SGI AL") */ + internalPortAudioDevice* pad) /* Result written to pad. */ +{ + int format; + long min, max; /* To catch hardware characteristics. */ + ALseterrorhandler(0); /* 0 = turn off the default error handler. */ + /*--------------------------------------------------------------------------------------*/ + pad->pad_ALdevice = ALdev; /* Set the AL device number. */ + pad->pad_DeviceID = id; /* Set the PA device number. */ + if (strlen(name) > MAX_CHARS_DEVNAME) /* MAX_CHARS defined above. */ + { + ERR_RPT(("Pa_QueryDevice(): name too long (%s).\n", name)); + return paHostError; + } + strcpy(pad->pad_DeviceName, name); /* Write name-string. */ + pad->pad_Info.name = pad->pad_DeviceName; /* Set pointer,..hmmm. */ + /*--------------------------------- natively supported sample formats: -----------------*/ + pad->pad_Info.nativeSampleFormats = paInt16; /* Later also include paFloat32 | ..| etc. */ + /* Then also choose other CallConvertXX()! */ + /*--------------------------------- number of available i/o channels: ------------------*/ + if (ALgetminmax(ALdev, AL_INPUT_COUNT, &min, &max)) + return translateSGIerror(); + pad->pad_Info.maxInputChannels = max; + DBUG(("Pa_QueryDevice: maxInputChannels = %d\n", pad->pad_Info.maxInputChannels)) + if (ALgetminmax(ALdev, AL_OUTPUT_COUNT, &min, &max)) + return translateSGIerror(); + pad->pad_Info.maxOutputChannels = max; + DBUG(("Pa_QueryDevice: maxOutputChannels = %d\n", pad->pad_Info.maxOutputChannels)) + /*--------------------------------- supported samplerates: ----------------------*/ + pad->pad_Info.numSampleRates = 7; + pad->pad_Info.sampleRates = pad->pad_SampleRates; + pad->pad_SampleRates[0] = (double)AL_RATE_8000; /* long -> double. */ + pad->pad_SampleRates[1] = (double)AL_RATE_11025; + pad->pad_SampleRates[2] = (double)AL_RATE_16000; + pad->pad_SampleRates[3] = (double)AL_RATE_22050; + pad->pad_SampleRates[4] = (double)AL_RATE_32000; + pad->pad_SampleRates[5] = (double)AL_RATE_44100; + pad->pad_SampleRates[6] = (double)AL_RATE_48000; + if (ALgetminmax(ALdev, AL_INPUT_RATE, &min, &max)) /* Ask INPUT rate-max. */ + return translateSGIerror(); /* double -> long. */ + if (max != (long)(0.5 + pad->pad_SampleRates[6])) /* FP-compare not recommndd. */ + goto weird; + if (ALgetminmax(ALdev, AL_OUTPUT_RATE, &min, &max)) /* Ask OUTPUT rate-max. */ + return translateSGIerror(); + if (max != (long)(0.5 + pad->pad_SampleRates[6])) + { +weird: ERR_RPT(("Pa_sgiQueryDevice() did not confirm max samplerate (%ld)\n",max)); + return paHostError; /* Or make it a warning and just carry on... */ + } + /*-------------------------------------------------------------------------------*/ + return paNoError; +} + + +/*--------------------------------------------------------------------------------*/ +int Pa_CountDevices() /* Name of this function suggests it only counts and */ +{ /* is NOT destructive, it however resets whole PA ! */ + int numDevices = 0; /* Let 's not do that here. */ + internalPortAudioDevice* currentDevice = sDeviceList; /* COPY GLOBAL VAR. */ +#if 0 /* Remains from linux_oss v15: Pa_Initialize(), on */ + if (!currentDevice) /* its turn, calls PaHost_Init() via file pa_lib.c. */ + Pa_Initialize(); /* Isn't that a bit too 'rude'? Don't be too */ +#endif /* friendly to clients that forgot to initialize PA. */ + while (currentDevice) /* Slower but more elegant than the sNumDevices-way: */ + { + numDevices++; + currentDevice = currentDevice->pad_Next; + } + return numDevices; +} + +/*-------------------------------------------------------------------------------*/ +static internalPortAudioDevice *Pa_GetInternalDevice(PaDeviceID id) +{ + int numDevices = 0; + internalPortAudioDevice *res = (internalPortAudioDevice*)NULL; + internalPortAudioDevice *pad = sDeviceList; /* COPY GLOBAL VAR. */ + while (pad) /* pad may be NULL, that's ok, return 0. */ + { /* (Added ->pad_DeviceID field to the pad-struct, Pieter, 2001.) */ + if (pad->pad_DeviceID == id) /* This the device we were looking for? */ + res = pad; /* But keep on(!) counting so we don't */ + numDevices++; /* have to call Pa_CountDevices() later. */ + pad = pad->pad_Next; /* Advance to the next device or NULL. */ + } /* No assumptions about order of ID's in */ + if (!res) /* the list. */ + ERR_RPT(("Pa_GetInternalDevice() could not find specified ID (%d).\n",id)); + if ((id < 0) || (id >= numDevices)) + { + ERR_RPT(("Pa_GetInternalDevice() supplied with an illegal ID (%d).\n",id)); +#if 1 /* Be strict, even when found, */ + res = (internalPortAudioDevice*)NULL; /* do not accept illegal ID's. */ +#endif + } + return res; +} + +/*----------------------------------------------------------------------*/ +const PaDeviceInfo* Pa_GetDeviceInfo(PaDeviceID id) +{ + PaDeviceInfo* res = (PaDeviceInfo*)NULL; + internalPortAudioDevice* pad = Pa_GetInternalDevice(id); /* Call. */ + if (pad) + res = &pad->pad_Info; /* Not finding the specified ID is not */ + if (!res) /* the same as &pad->pad_Info == NULL. */ + ERR_RPT(("Pa_GetDeviceInfo() could not find it (ID=%d).\n", id)); + return res; /* So (maybe) a second/third ERR_RPT(). */ +} + +/*------------------------------------------------*/ +PaDeviceID Pa_GetDefaultInputDeviceID(void) +{ + return 0; /* 0 is the default device ID. */ +} +/*------------------------------------------------*/ +PaDeviceID Pa_GetDefaultOutputDeviceID(void) +{ + return 0; +} + +/*-------------------------------------------------------------------------------------------------*/ +/* Build linked a list with all the available audio devices on this SGI machine (only 1 for now). */ +PaError PaHost_Init(void) /* Called by Pa_Initialize() from pa_lib.c. */ +{ + internalPortAudioDevice* pad; + PaError r = paNoError; + int audioLibFileID; /* To test for the presence of audio. */ + + if (sDeviceList) /* Allow re-init, only warn, no error. */ + { + ERR_RPT(("Warning: PaHost_Init() did not really re-init PA.\n")); + return r; + } + /*------------- ADD THE SGI DEFAULT DEVICE TO THE LIST: ---------------------------------------*/ + audioLibFileID = open("/dev/hdsp/hdsp0master", O_RDONLY); /* Try to open Indigo style audio */ + if (audioLibFileID < 0) /* IO port. On failure, machine */ + { /* has no audio ability. */ + ERR_RPT(("PaHost_Init(): This machine has no (Indigo-style) audio abilities.\n")); + return paHostError; + } + close(audioLibFileID); /* Allocate fast mem to hold device info. */ + pad = PaHost_AllocateFastMemory(sizeof(internalPortAudioDevice)); + if (pad == NULL) + return paInsufficientMemory; + memset(pad, 0, sizeof(internalPortAudioDevice)); /* "pad->pad_Next = NULL" is more elegant. */ + r = Pa_sgiQueryDevice(AL_DEFAULT_DEVICE, /* Set AL device num (AL_DEFAULT_DEVICE). */ + Pa_GetDefaultOutputDeviceID(),/* Set PA device num (or InputDeviceID()). */ + "AL default", /* A suitable name. */ + pad); /* Write args and queried info into pad. */ + if (r != paNoError) + { + ERR_RPT(("Pa_QueryDevice for '%s' returned: %d\n", pad->pad_DeviceName, r)); + PaHost_FreeFastMemory(pad, sizeof(internalPortAudioDevice)); /* sDeviceList still NULL ! */ + } + else + sDeviceList = pad; /* First element in linked list. pad->pad_Next already NULL. */ + /*------------- QUERY AND ADD MORE POSSIBLE SGI DEVICES TO THE LINKED LIST: -------------------*/ + /*---------------------------------------------------------------------------------------------*/ + return r; +} + +/*---------------------------------------------------------------------------------------------------*/ +static PaError Pa_SgiAudioProcess(internalPortAudioStream *past) /* Spawned by PaHost_StartEngine(). */ +{ + PaError result = paNoError; + PaHostSoundControl *pahsc; + + if (!past) + return paBadStreamPtr; + pahsc = (PaHostSoundControl*)past->past_DeviceData; + if (!pahsc) + return paInternalError; + past->past_IsActive = 1; /* Wasn't this already done by the calling parent?! */ + DBUG(("entering thread.\n")); + + while (!past->past_StopSoon) /* OR-ing StopSoon and StopNow here gives problems! */ + { + /*---------------------------------------- INPUT: ------------------------------------*/ + if (pahsc->pahsc_NativeInputBuffer) /* Then pahsc_ALportIN should also be there! */ + { + while (ALgetfilled(pahsc->pahsc_ALportIN) < pahsc->pahsc_SamplesPerInputBuffer) + { + /* Trying sginap(1); and usleep(); here... things get blocked under IRIX6.2. */ + if (past->past_StopNow) /* Don't let ALreadsamps() block */ + goto done; + } + if (ALreadsamps(pahsc->pahsc_ALportIN, (void*)pahsc->pahsc_NativeInputBuffer, + pahsc->pahsc_SamplesPerInputBuffer)) /* Number of samples instead */ + { /* of number of frames. */ + ERR_RPT(("ALreadsamps() failed.\n")); + result = paInternalError; + goto done; + } + } + /*---------------------------------------------------- USER CALLBACK ROUTINE: ----------*/ + /* DBUG(("Calling Pa_CallConvertInt16()...\n")); */ + Pa_StartUsageCalculation(past); /* Convert 16 bit native data to */ + result = Pa_CallConvertInt16(past, /* user data and call user routine. */ + pahsc->pahsc_NativeInputBuffer, pahsc->pahsc_NativeOutputBuffer); + Pa_EndUsageCalculation(past); + if (result) + { + DBUG(("Pa_CallConvertInt16() returned %d, stopping...\n", result)); + goto done; /* This is apparently NOT an error! */ + } /* Just letting the userCallBack stop us. */ + /*---------------------------------------- OUTPUT: ------------------------------------*/ + if (pahsc->pahsc_NativeOutputBuffer) /* Then pahsc_ALportOUT should also be there! */ + { + while (ALgetfillable(pahsc->pahsc_ALportOUT) < pahsc->pahsc_SamplesPerOutputBuffer) + { + /* Trying sginap(1); and usleep(); here... things get blocked under IRIX6.2. */ + if (past->past_StopNow) /* Don't let ALwritesamps() block */ + goto done; + } + if (ALwritesamps(pahsc->pahsc_ALportOUT, (void*)pahsc->pahsc_NativeOutputBuffer, + pahsc->pahsc_SamplesPerOutputBuffer)) + { + ERR_RPT(("ALwritesamps() failed.\n")); + result = paInternalError; + goto done; + } + } + /*-------------------------------------------------------------------------------------*/ + } +done: + /* pahsc->pahsc_ThreadPID = -1; Hu? doesn't help!! (added by Pieter) */ + past->past_IsActive = 0; + DBUG(("leaving thread.\n")); + return result; +} + + +/*--------------------------------------------------------------------------------------*/ +PaError PaHost_OpenStream(internalPortAudioStream *past) +{ + PaError result = paNoError; + PaHostSoundControl *pahsc; + unsigned int minNumBuffers; + internalPortAudioDevice *padIN, *padOUT; /* For looking up native AL-numbers. */ + ALconfig sgiALconfig = NULL; /* IRIX-datatype. */ + long pvbuf[8]; /* To get/set hardware configs. */ + long sr, ALqsize; + DBUG(("PaHost_OpenStream() called.\n")); /* Alloc FASTMEM and init host data. */ + if (!past) + { + ERR_RPT(("Streampointer NULL!\n")); + result = paBadStreamPtr; goto done; + } + pahsc = (PaHostSoundControl*)PaHost_AllocateFastMemory(sizeof(PaHostSoundControl)); + if (pahsc == NULL) + { + ERR_RPT(("FAST Memory allocation failed.\n")); /* Pass trough some ERR_RPT-exit- */ + result = paInsufficientMemory; goto done; /* code (nothing will be freed). */ + } + memset(pahsc, 0, sizeof(PaHostSoundControl)); +/* pahsc->pahsc_threadPID = -1; Should pahsc_threadPID be inited to */ + past->past_DeviceData = (void*)pahsc; /* -1 instead of 0 ?? */ + /*--------------------------------------------------- Allocate native buffers: --------*/ + pahsc->pahsc_SamplesPerInputBuffer = past->past_FramesPerUserBuffer * /* Needed by the */ + past->past_NumInputChannels; /* audio-thread. */ + pahsc->pahsc_BytesPerInputBuffer = pahsc->pahsc_SamplesPerInputBuffer * sizeof(short); + if (past->past_NumInputChannels > 0) /* Assumes short = 16 bits! */ + { + pahsc->pahsc_NativeInputBuffer = (short*)PaHost_AllocateFastMemory(pahsc->pahsc_BytesPerInputBuffer); + if( pahsc->pahsc_NativeInputBuffer == NULL ) + { + ERR_RPT(("Fast memory allocation for input-buffer failed.\n")); + result = paInsufficientMemory; goto done; + } + } + pahsc->pahsc_SamplesPerOutputBuffer = past->past_FramesPerUserBuffer * /* Needed by the */ + past->past_NumOutputChannels; /* audio-thread. */ + pahsc->pahsc_BytesPerOutputBuffer = pahsc->pahsc_SamplesPerOutputBuffer * sizeof(short); + if (past->past_NumOutputChannels > 0) /* Assumes short = 16 bits! */ + { + pahsc->pahsc_NativeOutputBuffer = (short*)PaHost_AllocateFastMemory(pahsc->pahsc_BytesPerOutputBuffer); + if (pahsc->pahsc_NativeOutputBuffer == NULL) + { + ERR_RPT(("Fast memory allocation for output-buffer failed.\n")); + result = paInsufficientMemory; goto done; + } + } + /*------------------------------------------ Manipulate hardware if necessary and allowed: --*/ + ALseterrorhandler(0); /* 0 = turn off the default error handler. */ + pvbuf[0] = AL_INPUT_RATE; + pvbuf[2] = AL_INPUT_COUNT; + pvbuf[4] = AL_OUTPUT_RATE; /* TO FIX: rates may be logically, not always in Hz! */ + pvbuf[6] = AL_OUTPUT_COUNT; + sr = (long)(past->past_SampleRate + 0.5); /* Common for input and output :-) */ + if (past->past_NumInputChannels > 0) /* We need to lookup the corre- */ + { /* sponding native AL-number(s). */ + padIN = Pa_GetInternalDevice(past->past_InputDeviceID); + if (!padIN) + { + ERR_RPT(("Pa_GetInternalDevice() for input failed.\n")); + result = paHostError; goto done; + } + if (ALgetparams(padIN->pad_ALdevice, &pvbuf[0], 4)) /* Although input and output will both be on */ + goto sgiError; /* the same AL-device, the AL-library might */ + if (pvbuf[1] != sr) /* contain more than AL_DEFAULT_DEVICE in */ + { /* Rate different from current harware-rate? the future. Therefore 2 seperate queries. */ + if (pvbuf[3] > 0) /* Means, there's other clients using AL-input-ports */ + { + ERR_RPT(("Sorry, not allowed to switch input-hardware to %ld Hz because \ +another process is currently using input at %ld kHz.\n", sr, pvbuf[1])); + result = paHostError; goto done; + } + pvbuf[1] = sr; /* Then set input-rate. */ + if (ALsetparams(padIN->pad_ALdevice, &pvbuf[0], 2)) + goto sgiError; /* WHETHER THIS SAMPLERATE WAS REALLY PRESENT IN OUR ARRAY OF RATES, */ + } /* IS NOT CHECKED, AT LEAST NOT BY ME, WITHIN THIS FILE! Does PA do? */ + } + if (past->past_NumOutputChannels > 0) /* CARE: padOUT/IN may NOT be NULL if Channels <= 0! */ + { /* We use padOUT/IN later on, or at least 1 of both. */ + padOUT = Pa_GetInternalDevice(past->past_OutputDeviceID); + if (!padOUT) + { + ERR_RPT(("Pa_GetInternalDevice() for output failed.\n")); + result = paHostError; goto done; + } + if (ALgetparams(padOUT->pad_ALdevice,&pvbuf[4], 4)) + goto sgiError; + if ((past->past_NumOutputChannels > 0) && (pvbuf[5] != sr)) + { /* Output needed and rate different from current harware-rate. */ + if (pvbuf[7] > 0) /* Means, there's other clients using AL-output-ports */ + { + ERR_RPT(("Sorry, not allowed to switch output-hardware to %ld Hz because \ +another process is currently using output at %ld kHz.\n", sr, pvbuf[5])); + result = paHostError; goto done; /* Will free again the inputbuffer */ + } /* that was just created above. */ + pvbuf[5] = sr; /* Then set output-rate. */ + if (ALsetparams(padOUT->pad_ALdevice, &pvbuf[4], 2)) + goto sgiError; + } + } + /*------------------------------------------ Construct an audio-port-configuration ----------*/ + sgiALconfig = ALnewconfig(); /* Change the SGI-AL-default-settings. */ + if (sgiALconfig == (ALconfig)0) /* sgiALconfig is released here after use! */ + goto sgiError; /* See that sgiALconfig is NOT released! */ + if (ALsetsampfmt(sgiALconfig, AL_SAMPFMT_TWOSCOMP)) /* Choose paInt16 as native i/o-format. */ + goto sgiError; + if (ALsetwidth (sgiALconfig, AL_SAMPLE_16)) /* Only meaningful when sample format for */ + goto sgiError; /* config is set to two's complement format. */ + /************************ Future versions might (dynamically) switch to 32-bit floats? ******* + if (ALsetsampfmt(sgiALconfig, AL_SAMPFMT_FLOAT)) (Then also call another CallConvert-func.) + goto sgiError; + if (ALsetfloatmax (sgiALconfig, 1.0)) Only meaningful when sample format for config + goto sgiError; is set to AL_SAMPFMT_FLOAT or AL_SAMPFMT_DOUBLE. */ + /*---------- ?? --------------------*/ + /* DBUG(("PaHost_OpenStream: pahsc_MinFramesPerHostBuffer = %d\n", pahsc->pahsc_MinFramesPerHostBuffer )); */ + minNumBuffers = Pa_GetMinNumBuffers(past->past_FramesPerUserBuffer, past->past_SampleRate); + past->past_NumUserBuffers = (minNumBuffers > past->past_NumUserBuffers) ? + minNumBuffers : past->past_NumUserBuffers; + /*------------------------------------------------ Set internal AL queuesize (in samples) ----*/ + if (pahsc->pahsc_SamplesPerInputBuffer >= pahsc->pahsc_SamplesPerOutputBuffer) + ALqsize = (long)pahsc->pahsc_SamplesPerInputBuffer; + else /* Take the largest of the two amounts. */ + ALqsize = (long)pahsc->pahsc_SamplesPerOutputBuffer; + ALqsize *= 4; /* 4 times as large as amount per transfer! */ + if (ALsetqueuesize(sgiALconfig, ALqsize)) /* Or should we use past_NumUserBuffers here? */ + goto sgiError; /* Using 2 times may give glitches... */ + /* Have to work on ALsetqueuesize() above. */ + + /* Do ALsetchannels() later, apart per input and/or output. */ + /*----------------------------------------------- OPEN 1 OR 2 AL-DEVICES: --------------------*/ + if (past->past_OutputDeviceID == past->past_InputDeviceID) /* Who SETS these devive-numbers? */ + { + if ((past->past_NumOutputChannels > 0) && (past->past_NumInputChannels > 0)) + { + DBUG(("PaHost_OpenStream: opening both input and output channels.\n")); + /*------------------------- open output port: ----------------------------------*/ + if (ALsetchannels (sgiALconfig, (long)(past->past_NumOutputChannels))) + goto sgiError; /* Returns 0 on success, -1 on failure. */ + pahsc->pahsc_ALportOUT = ALopenport("PA sgi out", "w", sgiALconfig); + if (pahsc->pahsc_ALportOUT == (ALport)0) + goto sgiError; + /*------------------------- open input port: -----------------------------------*/ + if (ALsetchannels (sgiALconfig, (long)(past->past_NumInputChannels))) + goto sgiError; /* Returns 0 on success, -1 on failure. */ + pahsc->pahsc_ALportIN = ALopenport("PA sgi in", "r", sgiALconfig); + if (pahsc->pahsc_ALportIN == (ALport)0) + goto sgiError; /* For some reason the "patest_wire.c"-test crashes! */ + } /* Probably due to too small buffersizes?.... */ + else + { + ERR_RPT(("Cannot setup bidirectional stream between different devices.\n")); + result = paHostError; + goto done; + } + } + else /* (OutputDeviceID != InputDeviceID) */ + { + if (past->past_NumOutputChannels > 0) /* WRITE-ONLY: */ + { + /*------------------------- open output port: ----------------------------------*/ + DBUG(("PaHost_OpenStream: opening %d output channel(s) on %s.\n", + past->past_NumOutputChannels, padOUT->pad_DeviceName)); + if (ALsetchannels (sgiALconfig, (long)(past->past_NumOutputChannels))) + goto sgiError; /* Returns 0 on success, -1 on failure. */ + pahsc->pahsc_ALportOUT = ALopenport("PA sgi out", "w", sgiALconfig); + if (pahsc->pahsc_ALportOUT == (ALport)0) + goto sgiError; + } + if (past->past_NumInputChannels > 0) /* READ-ONLY: */ + { + /*------------------------- open input port: -----------------------------------*/ + DBUG(("PaHost_OpenStream: opening %d input channel(s) on %s.\n", + past->past_NumInputChannels, padIN->pad_DeviceName)); + if (ALsetchannels (sgiALconfig, (long)(past->past_NumInputChannels))) + goto sgiError; /* Returns 0 on success, -1 on failure. */ + pahsc->pahsc_ALportIN = ALopenport("PA sgi in", "r", sgiALconfig); + if (pahsc->pahsc_ALportIN == (ALport)0) + goto sgiError; + } + } + DBUG(("PaHost_OpenStream() succeeded.\n")); + goto done; /* (no errors occured) */ +sgiError: + result = translateSGIerror(); /* Translates SGI AL-code to PA-code and ERR_RPTs string. */ +done: + if (sgiALconfig) + ALfreeconfig(sgiALconfig); /* We don't need that struct anymore. */ + if (result != paNoError) + PaHost_CloseStream(past); /* Frees memory (only if really allocated!). */ + return result; +} + +/*-----------------------------------------------------*/ +PaError PaHost_StartOutput(internalPortAudioStream *past) +{ + return paNoError; /* Hmm, not implemented yet? */ +} +PaError PaHost_StartInput(internalPortAudioStream *past) +{ + return paNoError; +} + +/*------------------------------------------------------------------------------*/ +PaError PaHost_StartEngine(internalPortAudioStream *past) +{ + PaHostSoundControl *pahsc; + int hres; + PaError result = paNoError; + + if (!past) /* Test argument. */ + { + ERR_RPT(("PaHost_StartEngine(NULL)!\n")); + return paBadStreamPtr; + } + pahsc = (PaHostSoundControl*)past->past_DeviceData; + if (!pahsc) + { + ERR_RPT(("PaHost_StartEngine(arg): arg->past_DeviceData == NULL!\n")); + return paHostError; + } + past->past_StopSoon = 0; /* Assume SGI ALport is already opened! */ + past->past_StopNow = 0; + past->past_IsActive = 1; + DBUG(("PaHost_StartEngine() called.\n")); + /* Use pthread_create() instead of __clone() because: */ + /* - pthread_create also works for other UNIX systems like Solaris, */ + /* - Java HotSpot VM crashes in pthread_setcanceltype() when using __clone(). */ + hres = pthread_create(&(pahsc->pahsc_ThreadPID), /* SPAWN AUDIO-CHILD. */ + NULL, /* pthread_attr_t * attr */ + (void*)Pa_SgiAudioProcess, + past); + if (hres) + { + result = paHostError; + sPaHostError = hres; + ERR_RPT(("PaHost_StartEngine() failed to spawn audio-thread.\n")); + } + return result; +} + +/*------------------------------------------------------------------------------*/ +PaError PaHost_StopEngine(internalPortAudioStream *past, int abort) +{ + int hres; + PaError result = paNoError; + PaHostSoundControl *pahsc; + + DBUG(("PaHost_StopEngine() called.\n")); + if (!past) + return paBadStreamPtr; + pahsc = (PaHostSoundControl*)past->past_DeviceData; + if (pahsc == NULL) + return result; /* paNoError (already stopped, no err?). */ + past->past_StopSoon = 1; /* Tell background thread to stop generating */ + if (abort) /* more and to let current data play out. If */ + past->past_StopNow = 1; /* aborting, tell backgrnd thread to stop NOW! */ + if (pahsc->pahsc_ThreadPID != -1) /* Join thread to recover memory resources. */ + { + DBUG(("pthread_join() called.\n")); + hres = pthread_join(pahsc->pahsc_ThreadPID, NULL); + if (hres) + { + result = paHostError; + sPaHostError = hres; + ERR_RPT(("PaHost_StopEngine() failed pthread_join().\n")); + } + pahsc->pahsc_ThreadPID = -1; + } + past->past_IsActive = 0; + return result; +} + +/*---------------------------------------------------------------*/ +PaError PaHost_StopOutput(internalPortAudioStream *past, int abort) +{ + return paNoError; /* Not implemented yet? */ +} +PaError PaHost_StopInput(internalPortAudioStream *past, int abort ) +{ + return paNoError; +} + +/*******************************************************************/ +PaError PaHost_CloseStream(internalPortAudioStream *past) +{ + PaHostSoundControl *pahsc; + PaError result = paNoError; + + DBUG(("PaHost_CloseStream() called.\n")); + if (past == NULL) + return paBadStreamPtr; + pahsc = (PaHostSoundControl *) past->past_DeviceData; + if (pahsc == NULL) /* If pahsc not NULL, past_DeviceData will be freed, and set to NULL. */ + return result; /* This test prevents from freeing NULL-pointers. */ + + if (pahsc->pahsc_ALportIN) + { + if (ALcloseport(pahsc->pahsc_ALportIN)) + result = translateSGIerror(); /* Translates SGI AL-code to PA-code and ERR_RPTs string. */ + else /* But go on anyway... to release other stuff... */ + pahsc->pahsc_ALportIN = (ALport)0; + } + if (pahsc->pahsc_ALportOUT) + { + if (ALcloseport(pahsc->pahsc_ALportOUT)) + result = translateSGIerror(); + else + pahsc->pahsc_ALportOUT = (ALport)0; + } + if (pahsc->pahsc_NativeInputBuffer) + { + PaHost_FreeFastMemory(pahsc->pahsc_NativeInputBuffer, pahsc->pahsc_BytesPerInputBuffer); + pahsc->pahsc_NativeInputBuffer = NULL; + } + if (pahsc->pahsc_NativeOutputBuffer) + { + PaHost_FreeFastMemory(pahsc->pahsc_NativeOutputBuffer, pahsc->pahsc_BytesPerOutputBuffer); + pahsc->pahsc_NativeOutputBuffer = NULL; + } + PaHost_FreeFastMemory(pahsc, sizeof(PaHostSoundControl)); + past->past_DeviceData = NULL; /* PaHost_OpenStream() allocated FAST. */ + return result; +} + +/************************************************************************* +** Determine minimum number of buffers required for this host based +** on minimum latency. Latency can be optionally set by user by setting +** an environment variable. For example, to set latency to 200 msec, put: +** set PA_MIN_LATENCY_MSEC=200 +** in the AUTOEXEC.BAT file and reboot. +** If the environment variable is not set, then the latency will be +** determined based on the OS. Windows NT has higher latency than Win95. +*/ +#define PA_LATENCY_ENV_NAME ("PA_MIN_LATENCY_MSEC") + +int Pa_GetMinNumBuffers( int framesPerBuffer, double sampleRate ) +{ + return 2; +} +/* Hmmm, the note above isn't appropriate for SGI I'm afraid... */ +/* Do we HAVE to do it this way under IRIX???.... */ +/*--------------------------------------------------------------*/ + + +/*---------------------------------------------------------------------*/ +PaError PaHost_Term(void) /* Frees all of the linked audio-devices. */ +{ /* Called by Pa_Terminate() from pa_lib.c. */ + internalPortAudioDevice *pad = sDeviceList, + *nxt; + while (pad) + { + DBUG(("PaHost_Term: freeing %s\n", pad->pad_DeviceName)); + nxt = pad->pad_Next; + PaHost_FreeFastMemory(pad, sizeof(internalPortAudioDevice)); + pad = nxt; /* PaHost_Init allocated this FAST MEM.*/ + } + sDeviceList = (internalPortAudioDevice*)NULL; + return 0; /* Got rid of sNumDevices=0; */ +} + +/***********************************************************************/ +void Pa_Sleep( long msec ) /* Sleep requested number of milliseconds. */ +{ +#if 0 + struct timeval timeout; + timeout.tv_sec = msec / 1000; + timeout.tv_usec = (msec % 1000) * 1000; + select(0, NULL, NULL, NULL, &timeout); +#else + long usecs = msec * 1000; + usleep( usecs ); +#endif +} + +/*---------------------------------------------------------------------------------------*/ +/* Allocate memory that can be accessed in real-time. This may need to be held in physi- */ +/* cal memory so that it is not paged to virtual memory. This call MUST be balanced with */ +/* a call to PaHost_FreeFastMemory(). */ +void *PaHost_AllocateFastMemory(long numBytes) +{ + void *addr = malloc(numBytes); + if (addr) + memset(addr, 0, numBytes); + return addr; +} + +/*---------------------------------------------------------------------------------------*/ +/* Free memory that could be accessed in real-time. This call MUST be balanced with a */ +/* call to PaHost_AllocateFastMemory(). */ +void PaHost_FreeFastMemory(void *addr, long numBytes) +{ + if (addr) + free(addr); +} + +/*----------------------------------------------------------*/ +PaError PaHost_StreamActive (internalPortAudioStream *past) +{ + PaHostSoundControl *pahsc; + if (past == NULL) + return paBadStreamPtr; + pahsc = (PaHostSoundControl *) past->past_DeviceData; + if (pahsc == NULL) + return paInternalError; + return (PaError)(past->past_IsActive != 0); +} + +/*-------------------------------------------------------------------*/ +PaTimestamp Pa_StreamTime( PortAudioStream *stream ) +{ + internalPortAudioStream *past = (internalPortAudioStream *) stream; +/* FIXME - return actual frames played, not frames generated. +** Need to query the output device somehow. +*/ + return past->past_FrameCount; +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_tests/debug_convert.c b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/debug_convert.c new file mode 100755 index 00000000000..264bb1c5f49 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/debug_convert.c @@ -0,0 +1,131 @@ +/* + * $Id: debug_convert.c,v 1.1.2.1 2005-08-16 20:04:10 alex%croczilla.com Exp $ + * Convert tagged values. + * + * Author: Phil Burk + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.portaudio.com + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +#include +#include +#include "portaudio.h" +#define OUTPUT_DEVICE (Pa_GetDefaultOutputDeviceID()) +//#define OUTPUT_DEVICE (11) +#define NUM_SECONDS (8) +#define SLEEP_DUR (800) +#define SAMPLE_RATE (44100) +#define FRAMES_PER_BUFFER (256) + +#define NUM_BUFFERS (0) + +typedef struct +{ + unsigned int framesToGo; +} +paTestData; +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patestCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + short *out = (short*)outputBuffer; + int i; + int finished = 0; + (void) outTime; /* Prevent unused variable warnings. */ + (void) inputBuffer; + + if( data->framesToGo < framesPerBuffer ) finished = 1; + + for( i=0; i +#include +#include "portaudio.h" +#include "pa_host.h" + +/*******************************************************************/ +int main(void); +int main(void) +{ + long max,min; + int i; + + for( i=0; i<10000; i++ ) + { + long dither = PaConvert_TriangularDither(); + // printf("dither = 0x%08X\n", dither ); + if( dither < min ) min = dither; + else if( dither > max ) max = dither; + } + printf("min = 0x%08X = %d, max = 0x%08X = %d\n", min, min, max, max ); +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_tests/debug_dual.c b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/debug_dual.c new file mode 100755 index 00000000000..eb763989fae --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/debug_dual.c @@ -0,0 +1,183 @@ +/* + * $Id: debug_dual.c,v 1.1.2.1 2005-08-16 20:04:10 alex%croczilla.com Exp $ + * debug_dual.c + * Try to open TWO streams on separate cards. + * Play a sine sweep using the Portable Audio api for several seconds. + * Hacked test for debugging PA. + * + * Author: Phil Burk + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.portaudio.com + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +#include +#include +#include "portaudio.h" +#define DEV_ID_1 (13) +#define DEV_ID_2 (15) +#define NUM_SECONDS (8) +#define SLEEP_DUR (800) +#define SAMPLE_RATE (44100) +#define FRAMES_PER_BUFFER (256) +#if 0 +#define MIN_LATENCY_MSEC (200) +#define NUM_BUFFERS ((MIN_LATENCY_MSEC * SAMPLE_RATE) / (FRAMES_PER_BUFFER * 1000)) +#else +#define NUM_BUFFERS (0) +#endif +#define MIN_FREQ (100.0f) +#define MAX_FREQ (4000.0f) +#define FREQ_SCALAR (1.00002f) +#define CalcPhaseIncrement(freq) (freq/SAMPLE_RATE) +#ifndef M_PI +#define M_PI (3.14159265) +#endif +#define TABLE_SIZE (400) +typedef struct +{ + float sine[TABLE_SIZE + 1]; // add one for guard point for interpolation + float phase_increment; + float left_phase; + float right_phase; +} +paTestData; +/* Convert phase between and 1.0 to sine value + * using linear interpolation. + */ +float LookupSine( paTestData *data, float phase ); +float LookupSine( paTestData *data, float phase ) +{ + float fIndex = phase*TABLE_SIZE; + int index = (int) fIndex; + float fract = fIndex - index; + float lo = data->sine[index]; + float hi = data->sine[index+1]; + float val = lo + fract*(hi-lo); + return val; +} +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patestCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + float *out = (float*)outputBuffer; + unsigned long i; + int finished = 0; + (void) outTime; /* Prevent unused variable warnings. */ + (void) inputBuffer; + + + for( i=0; ileft_phase); /* left */ + *out++ = LookupSine(data, data->right_phase); /* right */ + data->left_phase += data->phase_increment; + if( data->left_phase >= 1.0f ) data->left_phase -= 1.0f; + data->right_phase += (data->phase_increment * 1.5f); /* fifth above */ + if( data->right_phase >= 1.0f ) data->right_phase -= 1.0f; + /* sweep frequency then start over. */ + data->phase_increment *= FREQ_SCALAR; + if( data->phase_increment > CalcPhaseIncrement(MAX_FREQ) ) data->phase_increment = CalcPhaseIncrement(MIN_FREQ); + } + return 0; +} + +PaError TestStart( PortAudioStream **streamPtr, PaDeviceID devID, + paTestData *data ); +/*******************************************************************/ +int main(void); +int main(void) +{ + PortAudioStream *stream1, *stream2; + PaError err; + paTestData DATA1, DATA2; + printf("PortAudio Test: DUAL sine sweep. ask for %d buffers\n", NUM_BUFFERS ); + err = Pa_Initialize(); + if( err != paNoError ) goto error; + err = TestStart( &stream1, DEV_ID_1, &DATA1 ); + if( err != paNoError ) goto error; + err = TestStart( &stream2, DEV_ID_2, &DATA2 ); + if( err != paNoError ) goto error; + printf("Hit ENTER\n"); + getchar(); + err = Pa_StopStream( stream1 ); + if( err != paNoError ) goto error; + err = Pa_StopStream( stream2 ); + if( err != paNoError ) goto error; + Pa_Terminate(); + printf("Test finished.\n"); + return err; +error: + Pa_Terminate(); + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + return err; +} +PaError TestStart( PortAudioStream **streamPtr, PaDeviceID devID, paTestData *data ) +{ + PortAudioStream *stream; + PaError err; + int i; + /* initialise sinusoidal wavetable */ + for( i=0; isine[i] = (float) sin( ((double)i/(double)TABLE_SIZE) * M_PI * 2. ); + } + data->sine[TABLE_SIZE] = data->sine[0]; // set guard point + data->left_phase = data->right_phase = 0.0; + data->phase_increment = CalcPhaseIncrement(MIN_FREQ); + printf("PortAudio Test: output device = %d\n", devID ); + err = Pa_OpenStream( + &stream, + paNoDevice, + 0, /* no input */ + paFloat32, /* 32 bit floating point input */ + NULL, + devID, + 2, /* stereo output */ + paFloat32, /* 32 bit floating point output */ + NULL, + SAMPLE_RATE, + FRAMES_PER_BUFFER, + NUM_BUFFERS, /* number of buffers, if zero then use default minimum */ + paClipOff|paDitherOff, /* we won't output out of range samples so don't bother clipping them */ + patestCallback, + data ); + if( err != paNoError ) goto error; + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + *streamPtr = stream; + return 0; +error: + return err; +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_tests/debug_multi_in.c b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/debug_multi_in.c new file mode 100755 index 00000000000..3357fa72a6a --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/debug_multi_in.c @@ -0,0 +1,187 @@ +/* + * $Id: debug_multi_in.c,v 1.1.2.1 2005-08-16 20:04:10 alex%croczilla.com Exp $ + * debug_multi_in.c + * Pass output from each of multiple channels + * to a stereo output using the Portable Audio api. + * Hacked test for debugging PA. + * + * Author: Phil Burk http://www.softsynth.com + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.portaudio.com + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +#include +#include +#include +#include "portaudio.h" +//#define INPUT_DEVICE_NAME ("EWS88 MT Interleaved Rec") +#define OUTPUT_DEVICE (Pa_GetDefaultOutputDeviceID()) +//#define OUTPUT_DEVICE (18) +#define SAMPLE_RATE (44100) +#define FRAMES_PER_BUFFER (256) +#define MIN_LATENCY_MSEC (400) +#define MAX_INPUT_CHANNELS (9999) +#define NUM_BUFFERS ((MIN_LATENCY_MSEC * SAMPLE_RATE) / (FRAMES_PER_BUFFER * 1000)) +#ifndef M_PI +#define M_PI (3.14159265) +#endif +typedef struct +{ + int liveChannel; + int numChannels; +} +paTestData; +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patestCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + float *out = (float*)outputBuffer; + float *in = (float*)inputBuffer; + int i; + (void) outTime; /* Prevent unused variable warnings. */ + (void) inputBuffer; + + if( in == NULL ) return 0; + for( i=0; i<(int)framesPerBuffer; i++ ) + { + /* Copy one channel of input to stereo output. */ + *out++ = in[data->liveChannel]; + *out++ = in[data->liveChannel]; + in += data->numChannels; + } + return 0; +} +/*******************************************************************/ +int PaFindDeviceByName( const char *name ) +{ + int i; + int numDevices; + const PaDeviceInfo *pdi; + int len = strlen( name ); + PaDeviceID result = paNoDevice; + numDevices = Pa_CountDevices(); + for( i=0; iname, len ) == 0 ) + { + result = i; + break; + } + } + return result; +} +/*******************************************************************/ +int main(void); +int main(void) +{ + PortAudioStream *stream; + PaError err; + paTestData data; + int i; + PaDeviceID inputDevice; + const PaDeviceInfo *pdi; + printf("PortAudio Test: input signal from each channel. %d buffers\n", NUM_BUFFERS ); + data.liveChannel = 0; + err = Pa_Initialize(); + if( err != paNoError ) goto error; +#ifdef INPUT_DEVICE_NAME + printf("Try to use device: %s\n", INPUT_DEVICE_NAME ); + inputDevice = PaFindDeviceByName(INPUT_DEVICE_NAME); + if( inputDevice == paNoDevice ) + { + printf("Could not find %s. Using default instead.\n", INPUT_DEVICE_NAME ); + inputDevice = Pa_GetDefaultInputDeviceID(); + } +#else + printf("Using default input device.\n"); + inputDevice = Pa_GetDefaultInputDeviceID(); +#endif + pdi = Pa_GetDeviceInfo( inputDevice ); + if( pdi == NULL ) + { + printf("Could not get device info!\n"); + goto error; + } + printf("Input Device name is %s\n", pdi->name ); + printf("Input Device has %d channels.\n", pdi->maxInputChannels); + if( pdi->maxInputChannels <= MAX_INPUT_CHANNELS ) + { + data.numChannels = pdi->maxInputChannels; + } + else + { + data.numChannels = MAX_INPUT_CHANNELS; + printf("Only use %d channels.\n", MAX_INPUT_CHANNELS ); + } + err = Pa_OpenStream( + &stream, + inputDevice, + data.numChannels, + paFloat32, /* 32 bit floating point input */ + NULL, + OUTPUT_DEVICE, + 2, + paFloat32, /* 32 bit floating point output */ + NULL, + SAMPLE_RATE, + FRAMES_PER_BUFFER, /* frames per buffer */ + NUM_BUFFERS, /* number of buffers, if zero then use default minimum */ + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + patestCallback, + &data ); + if( err != paNoError ) goto error; + data.liveChannel = 0; + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + for( i=0; i +#include +#include "portaudio.h" + +#define OUTPUT_DEVICE (Pa_GetDefaultOutputDeviceID()) +#define SAMPLE_RATE (44100) +#define FRAMES_PER_BUFFER (256) +#define FREQ_INCR (300.0 / SAMPLE_RATE) +#define MAX_CHANNELS (64) + +#ifndef M_PI +#define M_PI (3.14159265) +#endif + +typedef struct +{ + int numChannels; +} +paTestData; + +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patestCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + float *out = (float*)outputBuffer; + int frameIndex, channelIndex; + int finished = 0; + (void) outTime; /* Prevent unused variable warnings. */ + (void) inputBuffer; + + for( frameIndex=0; frameIndex<(int)framesPerBuffer; frameIndex++ ) + { + for( channelIndex=0; channelIndexnumChannels; channelIndex++ ) + { + /* Output sine wave on every channel. */ + *out++ = (float) ((channelIndex + 1) * 0.1); + } + } + + return 0; +} +/*******************************************************************/ +int main(void); +int main(void) +{ + PortAudioStream *stream; + PaError err; + const PaDeviceInfo *pdi; + paTestData data = {0}; + printf("PortAudio Test: output channel number on each channel.\n" ); + + err = Pa_Initialize(); + if( err != paNoError ) goto error; + + pdi = Pa_GetDeviceInfo( OUTPUT_DEVICE ); + data.numChannels = pdi->maxOutputChannels; + if( data.numChannels > MAX_CHANNELS ) data.numChannels = MAX_CHANNELS; + printf("Number of Channels = %d\n", data.numChannels ); + + err = Pa_OpenStream( + &stream, + paNoDevice, /* default input device */ + 0, /* no input */ + paFloat32, /* 32 bit floating point input */ + NULL, + OUTPUT_DEVICE, + data.numChannels, + paFloat32, /* 32 bit floating point output */ + NULL, + SAMPLE_RATE, + FRAMES_PER_BUFFER, /* frames per buffer */ + 0, /* number of buffers, if zero then use default minimum */ + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + patestCallback, + &data ); + if( err != paNoError ) goto error; + + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + + printf("Hit ENTER to stop sound.\n"); + fflush(stdout); + getchar(); + + err = Pa_StopStream( stream ); + if( err != paNoError ) goto error; + + Pa_CloseStream( stream ); + Pa_Terminate(); + printf("Test finished.\n"); + return err; +error: + Pa_Terminate(); + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + return err; +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_tests/debug_record.c b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/debug_record.c new file mode 100755 index 00000000000..6e25ae3c230 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/debug_record.c @@ -0,0 +1,338 @@ +/* + * $Id: debug_record.c,v 1.1.2.1 2005-08-16 20:04:10 alex%croczilla.com Exp $ + * patest_record.c + * Record input into an array. + * Save array to a file. + * Playback recorded data. + * + * Author: Phil Burk http://www.softsynth.com + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.portaudio.com + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +#include +#include +#include "portaudio.h" + +#define SAMPLE_RATE (44100) +#define NUM_SECONDS (6) +#define NUM_CHANNELS (2) +#define FRAMES_PER_BUFFER (64) +/* #define DITHER_FLAG (paDitherOff) */ +#define DITHER_FLAG (0) + +/* Select sample format. */ +#if 1 +#define PA_SAMPLE_TYPE paFloat32 +typedef float SAMPLE; +#define SAMPLE_SILENCE (0.0f) + +#elif 0 +#define PA_SAMPLE_TYPE paInt32 +typedef long SAMPLE; +#define SAMPLE_SILENCE (0) + +#elif 0 +#define PA_SAMPLE_TYPE paInt16 +typedef short SAMPLE; +#define SAMPLE_SILENCE (0) + +#elif 0 +#define PA_SAMPLE_TYPE paInt8 +typedef char SAMPLE; +#define SAMPLE_SILENCE (0) + +#else +#define PA_SAMPLE_TYPE paUInt8 +typedef unsigned char SAMPLE; +#define SAMPLE_SILENCE (128) + +#endif + +typedef struct +{ + int frameIndex; /* Index into sample array. */ + int maxFrameIndex; + SAMPLE *recordedSamples; +} +paTestData; +/* This routine will be called by the PortAudio engine when audio is needed. +** It may be called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int recordCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + SAMPLE *rptr = (SAMPLE*)inputBuffer; + SAMPLE *wptr = &data->recordedSamples[data->frameIndex * NUM_CHANNELS]; + long framesToCalc; + long i; + int finished; + unsigned long framesLeft = data->maxFrameIndex - data->frameIndex; + + (void) outputBuffer; /* Prevent unused variable warnings. */ + (void) outTime; + + if( framesLeft < framesPerBuffer ) + { + framesToCalc = framesLeft; + finished = 1; + } + else + { + framesToCalc = framesPerBuffer; + finished = 0; + } + if( inputBuffer == NULL ) + { + for( i=0; iframeIndex += framesToCalc; + return finished; +} + +/* This routine will be called by the PortAudio engine when audio is needed. +** It may be called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int playCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + SAMPLE *rptr = &data->recordedSamples[data->frameIndex * NUM_CHANNELS]; + SAMPLE *wptr = (SAMPLE*)outputBuffer; + unsigned int i; + int finished; + unsigned int framesLeft = data->maxFrameIndex - data->frameIndex; + (void) inputBuffer; /* Prevent unused variable warnings. */ + (void) outTime; + + if( framesLeft < framesPerBuffer ) + { + /* final buffer... */ + for( i=0; iframeIndex += framesLeft; + finished = 1; + } + else + { + for( i=0; iframeIndex += framesPerBuffer; + finished = 0; + } + return finished; +} + +/*******************************************************************/ +int main(void); +int main(void) +{ + PortAudioStream *stream; + PaError err; + paTestData data; + int i; + int totalFrames; + int numSamples; + int numBytes; + SAMPLE max, average, val; + + printf("debug_record.c, sampleRate = %d, numChannels = %d\n", + SAMPLE_RATE, NUM_CHANNELS ); + fflush(stdout); + + data.maxFrameIndex = totalFrames = NUM_SECONDS * SAMPLE_RATE; /* Record for a few seconds. */ + data.frameIndex = 0; + numSamples = totalFrames * NUM_CHANNELS; + + numBytes = numSamples * sizeof(SAMPLE); + data.recordedSamples = (SAMPLE *) malloc( numBytes ); + if( data.recordedSamples == NULL ) + { + printf("Could not allocate record array.\n"); + exit(1); + } + for( i=0; i max ) + { + max = val; + } + average += val; + } + + average = average / numSamples; + + if( PA_SAMPLE_TYPE == paFloat32 ) + { + printf("sample max amplitude = %f\n", (double) max ); + printf("sample average = %f\n", (double) average ); + } + else + { + printf("sample max amplitude = %d\n", (int) max ); + printf("sample average = %d\n", (int) average ); + } + + /* Write recorded data to a file. */ +#if 0 + { + FILE *fid; + fid = fopen("recorded.raw", "wb"); + if( fid == NULL ) + { + printf("Could not open file."); + } + else + { + fwrite( data.recordedSamples, NUM_CHANNELS * sizeof(SAMPLE), totalFrames, fid ); + fclose( fid ); + printf("Wrote data to 'recorded.raw'\n"); + } + } +#endif + + /* Playback recorded data. -------------------------------------------- */ + data.frameIndex = 0; + printf("Begin playback.\n"); fflush(stdout); + err = Pa_OpenStream( + &stream, + paNoDevice, + 0, /* NO input */ + PA_SAMPLE_TYPE, + NULL, + Pa_GetDefaultOutputDeviceID(), + NUM_CHANNELS, /* stereo output */ + PA_SAMPLE_TYPE, + NULL, + SAMPLE_RATE, + FRAMES_PER_BUFFER, /* frames per buffer */ + 0, /* number of buffers, if zero then use default minimum */ + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + playCallback, + &data ); + if( err != paNoError ) goto error; + + if( stream ) + { + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + printf("Start playback!!\n"); fflush(stdout); + + while( Pa_StreamActive( stream ) ) + { + Pa_Sleep(1000); + printf("index = %d\n", data.frameIndex ); fflush(stdout); + } + + printf("Stop playback!!\n"); fflush(stdout); + err = Pa_CloseStream( stream ); + if( err != paNoError ) goto error; + printf("Done.\n"); fflush(stdout); + } + free( data.recordedSamples ); + + Pa_Terminate(); + return 0; + +error: + Pa_Terminate(); + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + return -1; +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_tests/debug_record_reuse.c b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/debug_record_reuse.c new file mode 100755 index 00000000000..23ffd886df9 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/debug_record_reuse.c @@ -0,0 +1,351 @@ +/* + * $Id: debug_record_reuse.c,v 1.1.2.1 2005-08-16 20:04:10 alex%croczilla.com Exp $ + * debug_record_reuse.c + * Record input into an array. + * Save array to a file. + * Based on patest_record.c but with various ugly debug hacks thrown in. + * Loop twice and reuse same streams. + * + * Author: Phil Burk http://www.softsynth.com + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.portaudio.com + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +#include +#include +#include +#include "portaudio.h" +#define SAMPLE_RATE (22050) +#define NUM_SECONDS (4) +#define SLEEP_DUR_MSEC (200) +#define FRAMES_PER_BUFFER (256) +#define NUM_REC_BUFS (0) + +#if 1 +#define PA_SAMPLE_TYPE paFloat32 +typedef float SAMPLE; +#else +#define PA_SAMPLE_TYPE paInt16 +typedef short SAMPLE; +#endif + +typedef struct +{ + long frameIndex; /* Index into sample array. */ + long maxFrameIndex; + long samplesPerFrame; + long numSamples; + PortAudioStream *outputStream; + PortAudioStream *inputStream; + SAMPLE *recordedSamples; +} +paTestData; + +/* This routine will be called by the PortAudio engine when audio is needed. +** It may be called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int recordCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + SAMPLE *rptr = (SAMPLE*)inputBuffer; + SAMPLE *wptr = &data->recordedSamples[data->frameIndex * data->samplesPerFrame]; + long framesToCalc; + unsigned long i; + int finished; + unsigned long framesLeft = data->maxFrameIndex - data->frameIndex; + + (void) outputBuffer; /* Prevent unused variable warnings. */ + (void) outTime; + + if( framesLeft < framesPerBuffer ) + { + framesToCalc = framesLeft; + finished = 1; + } + else + { + framesToCalc = framesPerBuffer; + finished = 0; + } + if( inputBuffer == NULL ) + { + for( i=0; iframeIndex += framesToCalc; + return finished; +} + +/* This routine will be called by the PortAudio engine when audio is needed. +** It may be called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int playCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + SAMPLE *rptr = &data->recordedSamples[data->frameIndex * data->samplesPerFrame]; + SAMPLE *wptr = (SAMPLE*)outputBuffer; + unsigned long i; + int finished; + unsigned int framesLeft = data->maxFrameIndex - data->frameIndex; + if( outputBuffer == NULL ) return 0; + (void) inputBuffer; /* Prevent unused variable warnings. */ + (void) outTime; + + if( framesLeft < framesPerBuffer ) + { + /* final buffer... */ + for( i=0; iframeIndex += framesLeft; + finished = 1; + } + else + { + for( i=0; iframeIndex += framesPerBuffer; + finished = 0; + } + return finished; +} + +/****************************************************************/ +PaError TestRecording( paTestData *dataPtr ) +{ + PaError err; + int i; + int lastIndex = 0; + +/* Open input stream if not already open. */ + if( dataPtr->inputStream == NULL ) + { + /* Record some audio. */ + err = Pa_OpenStream( + &dataPtr->inputStream, + Pa_GetDefaultInputDeviceID(), + dataPtr->samplesPerFrame, /* stereo input */ + PA_SAMPLE_TYPE, + NULL, + paNoDevice, + 0, + PA_SAMPLE_TYPE, + NULL, + SAMPLE_RATE, + FRAMES_PER_BUFFER, /* frames per buffer */ + NUM_REC_BUFS, /* number of buffers, if zero then use default minimum */ + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + recordCallback, + dataPtr ); + if( err != paNoError ) goto error; + } + + dataPtr->frameIndex = 0; + + err = Pa_StartStream( dataPtr->inputStream ); + if( err != paNoError ) goto error; + + printf("Now recording!\n"); fflush(stdout); + for( i=0; i<(NUM_SECONDS*1000/SLEEP_DUR_MSEC); i++ ) + { + int frameIndex, delta; + Pa_Sleep(SLEEP_DUR_MSEC); + + frameIndex = dataPtr->frameIndex; + if( Pa_StreamActive( dataPtr->inputStream ) <= 0) + { + printf("Stream inactive!\n"); + break; + } + if( dataPtr->maxFrameIndex <= frameIndex ) + { + printf("Buffer recording complete.\n"); + break; + } + + delta = frameIndex - lastIndex; + lastIndex = frameIndex; + printf("index = %d, delta = %d\n", frameIndex, delta ); fflush(stdout); + } + + err = Pa_StopStream( dataPtr->inputStream ); + if( err != paNoError ) goto error; + + printf("Done.\n"); fflush(stdout); + +error: + return err; +} + +/****************************************************************/ +PaError TestPlayback( paTestData *dataPtr ) +{ + PaError err; + int i; + int lastIndex = 0; + + /* Playback recorded data. */ + dataPtr->frameIndex = 0; + printf("Begin playback.\n"); fflush(stdout); + +/* Open output stream if not already open. */ + if( dataPtr->outputStream == NULL ) + { + err = Pa_OpenStream( + &dataPtr->outputStream, + paNoDevice, + 0, /* NO input */ + PA_SAMPLE_TYPE, + NULL, + Pa_GetDefaultOutputDeviceID(), + dataPtr->samplesPerFrame, /* stereo output */ + PA_SAMPLE_TYPE, + NULL, + SAMPLE_RATE, + FRAMES_PER_BUFFER, /* frames per buffer */ + 0, /* number of buffers, if zero then use default minimum */ + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + playCallback, + dataPtr ); + if( err != paNoError ) goto error; + } + + err = Pa_StartStream( dataPtr->outputStream ); + if( err != paNoError ) goto error; + + printf("Waiting for playback to finish.\n"); fflush(stdout); + for( i=0; i<(NUM_SECONDS*1000/SLEEP_DUR_MSEC); i++ ) + { + int frameIndex, delta; + Pa_Sleep(SLEEP_DUR_MSEC); + frameIndex = dataPtr->frameIndex; + delta = frameIndex - lastIndex; + lastIndex = frameIndex; + printf("index = %d, delta = %d\n", frameIndex, delta ); fflush(stdout); + } + + err = Pa_StopStream( dataPtr->outputStream ); + if( err != paNoError ) goto error; + +error: + return err; +} +/*******************************************************************/ +int main(void); +int main(void) +{ + PaError err; + paTestData data = { 0 }; + long totalFrames; + long numBytes; + long i; + printf("patest_record.c\n"); fflush(stdout); + +/* Set up test data structure and sample array. */ + data.frameIndex = 0; + data.samplesPerFrame = 2; + data.maxFrameIndex = totalFrames = NUM_SECONDS*SAMPLE_RATE; + + printf("totalFrames = %d\n", totalFrames ); fflush(stdout); + data.numSamples = totalFrames * data.samplesPerFrame; + + numBytes = data.numSamples * sizeof(SAMPLE); + data.recordedSamples = (SAMPLE *) malloc( numBytes ); + if( data.recordedSamples == NULL ) + { + printf("Could not allocate record array.\n"); + exit(1); + } + for( i=0; i + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.portaudio.com + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +#include +#include +#include "portaudio.h" +#define OUTPUT_DEVICE (Pa_GetDefaultOutputDeviceID()) +//#define OUTPUT_DEVICE (11) +#define NUM_SECONDS (8) +#define SLEEP_DUR (800) +#define SAMPLE_RATE (44100) +#define FRAMES_PER_BUFFER (256) + +#define MSEC_PER_BUFFER (1000 * FRAMES_PER_BUFFER / SAMPLE_RATE) + +#if 0 +#define MIN_LATENCY_MSEC (200) +#define NUM_BUFFERS ((MIN_LATENCY_MSEC * SAMPLE_RATE) / (FRAMES_PER_BUFFER * 1000)) +#else +#define NUM_BUFFERS (0) +#endif + +#define MIN_FREQ (100.0f) +#define MAX_FREQ (4000.0f) +#define FREQ_SCALAR (1.00002f) +#define CalcPhaseIncrement(freq) (freq/SAMPLE_RATE) +#ifndef M_PI +#define M_PI (3.14159265) +#endif +#define TABLE_SIZE (400) +typedef struct +{ + float sine[TABLE_SIZE + 1]; // add one for guard point for interpolation + float phase_increment; + float left_phase; + float right_phase; + unsigned int framesToGo; +} +paTestData; +/* Convert phase between and 1.0 to sine value + * using linear interpolation. + */ +float LookupSine( paTestData *data, float phase ); +float LookupSine( paTestData *data, float phase ) +{ + float fIndex = phase*TABLE_SIZE; + int index = (int) fIndex; + float fract = fIndex - index; + float lo = data->sine[index]; + float hi = data->sine[index+1]; + float val = lo + fract*(hi-lo); + return val; +} +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patestCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + float *out = (float*)outputBuffer; + int framesToCalc; + int i; + int finished = 0; + (void) outTime; /* Prevent unused variable warnings. */ + (void) inputBuffer; + + if( data->framesToGo < framesPerBuffer ) + { + framesToCalc = data->framesToGo; + data->framesToGo = 0; + finished = 1; + } + else + { + framesToCalc = framesPerBuffer; + data->framesToGo -= framesPerBuffer; + } + + for( i=0; ileft_phase); /* left */ + *out++ = LookupSine(data, data->right_phase); /* right */ + data->left_phase += data->phase_increment; + if( data->left_phase >= 1.0f ) data->left_phase -= 1.0f; + data->right_phase += (data->phase_increment * 1.5f); /* fifth above */ + if( data->right_phase >= 1.0f ) data->right_phase -= 1.0f; + /* sweep frequency then start over. */ + data->phase_increment *= FREQ_SCALAR; + if( data->phase_increment > CalcPhaseIncrement(MAX_FREQ) ) data->phase_increment = CalcPhaseIncrement(MIN_FREQ); + } + /* zero remainder of final buffer */ + for( ; i<(int)framesPerBuffer; i++ ) + { + *out++ = 0; /* left */ + *out++ = 0; /* right */ + } + // Pa_Sleep( 3 * MSEC_PER_BUFFER / 4 ); + // Pa_Sleep( MSEC_PER_BUFFER / 3 ); + + return finished; +} +/*******************************************************************/ +int main(void); +int main(void) +{ + PortAudioStream *stream; + PaError err; + paTestData data; + int i; + int totalSamps; + printf("PortAudio Test: output sine sweep. ask for %d buffers\n", NUM_BUFFERS ); + printf("MSEC_PER_BUFFER = %d\n", MSEC_PER_BUFFER ); + + /* initialise sinusoidal wavetable */ + for( i=0; i +#include +#include "portaudio.h" + +#define OUTPUT_DEVICE (Pa_GetDefaultOutputDeviceID()) +#define SAMPLE_RATE (44100) +#define FRAMES_PER_BUFFER (256) +#define FREQ_INCR (300.0 / SAMPLE_RATE) +#define MAX_CHANNELS (64) + +#ifndef M_PI +#define M_PI (3.14159265) +#endif + +typedef struct +{ + int numChannels; + double phases[MAX_CHANNELS]; + float amplitude; +} +paTestData; + +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patestCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + float *out = (float*)outputBuffer; + int frameIndex, channelIndex; + (void) outTime; /* Prevent unused variable warnings. */ + (void) inputBuffer; + + for( frameIndex=0; frameIndex<(int)framesPerBuffer; frameIndex++ ) + { + for( channelIndex=0; channelIndexnumChannels; channelIndex++ ) + { + /* Output sine wave on every channel. */ + *out++ = (float) ( data->amplitude * sin(data->phases[channelIndex]) ); + + /* Play each channel at a higher frequency. */ + data->phases[channelIndex] += FREQ_INCR * (4 + channelIndex); + if( data->phases[channelIndex] >= (2.0 * M_PI) ) data->phases[channelIndex] -= (2.0 * M_PI); + } + } + + return 0; +} +/*******************************************************************/ +int main(void); +int main(void) +{ + char pad[256]; + PortAudioStream *stream; + PaError err; + const PaDeviceInfo *pdi; + paTestData data = {0}; + printf("PortAudio Test: output sine wave on each channel.\n" ); + + err = Pa_Initialize(); + if( err != paNoError ) goto error; + + pdi = Pa_GetDeviceInfo( OUTPUT_DEVICE ); + data.numChannels = pdi->maxOutputChannels; + if( data.numChannels > MAX_CHANNELS ) data.numChannels = MAX_CHANNELS; + printf("Number of Channels = %d\n", data.numChannels ); + data.amplitude = 1.0; + + err = Pa_OpenStream( + &stream, + paNoDevice, /* default input device */ + 0, /* no input */ + paFloat32, /* 32 bit floating point input */ + NULL, + OUTPUT_DEVICE, + data.numChannels, + paFloat32, /* 32 bit floating point output */ + NULL, + SAMPLE_RATE, + FRAMES_PER_BUFFER, /* frames per buffer */ + 0, /* number of buffers, if zero then use default minimum */ + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + patestCallback, + &data ); + if( err != paNoError ) goto error; + + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + + do + { + printf("Current amplitude = %f\n", data.amplitude ); + printf("Enter new amplitude or 'q' to quit.\n"); + fflush(stdout); + gets( pad ); + if( pad[0] != 'q' ) + { + // I tried to use atof but it seems to be broken on Mac OS X 10.1 + float amp; + sscanf( pad, "%f", & ); + data.amplitude = amp; + } + } while( pad[0] != 'q' ); + + err = Pa_StopStream( stream ); + if( err != paNoError ) goto error; + + Pa_CloseStream( stream ); + Pa_Terminate(); + printf("Test finished.\n"); + return err; +error: + Pa_Terminate(); + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + return err; +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_tests/debug_sine_formats.c b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/debug_sine_formats.c new file mode 100755 index 00000000000..9e0476ea453 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/debug_sine_formats.c @@ -0,0 +1,202 @@ +/* + * $Id: debug_sine_formats.c,v 1.1.2.1 2005-08-16 20:04:10 alex%croczilla.com Exp $ + * patest_sine_formats.c + * Play a sine wave using the Portable Audio api for several seconds. + * Test various data formats. + * + * Author: Phil Burk + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.audiomulch.com/portaudio/ + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +#include +#include +#include "portaudio.h" + +#define NUM_SECONDS (10) +#define SAMPLE_RATE (44100) +#define FRAMES_PER_BUFFER (256) + +#define LEFT_FREQ (SAMPLE_RATE/512.0) /* So we hit 1.0 */ +#define RIGHT_FREQ (500.0) + +#define AMPLITUDE (1.0) + +/* Select ONE format for testing. */ +#define TEST_UINT8 (1) +#define TEST_INT8 (0) +#define TEST_INT16 (0) +#define TEST_FLOAT32 (0) + +#if TEST_UINT8 +#define TEST_FORMAT paUInt8 +typedef unsigned char SAMPLE_t; +#define SAMPLE_ZERO (0x80) +#define DOUBLE_TO_SAMPLE(x) (SAMPLE_ZERO + (SAMPLE_t)(127.0 * (x))) +#define FORMAT_NAME "Unsigned 8 Bit" + +#elif TEST_INT8 +#define TEST_FORMAT paInt8 +typedef char SAMPLE_t; +#define SAMPLE_ZERO (0) +#define DOUBLE_TO_SAMPLE(x) (SAMPLE_ZERO + (SAMPLE_t)(127.0 * (x))) +#define FORMAT_NAME "Signed 8 Bit" + +#elif TEST_INT16 +#define TEST_FORMAT paInt16 +typedef short SAMPLE_t; +#define SAMPLE_ZERO (0) +#define DOUBLE_TO_SAMPLE(x) (SAMPLE_ZERO + (SAMPLE_t)(32767 * (x))) +#define FORMAT_NAME "Signed 16 Bit" + +#elif TEST_FLOAT32 +#define TEST_FORMAT paFloat32 +typedef float SAMPLE_t; +#define SAMPLE_ZERO (0.0) +#define DOUBLE_TO_SAMPLE(x) ((SAMPLE_t)(x)) +#define FORMAT_NAME "Float 32 Bit" +#endif + +#ifndef M_PI +#define M_PI (3.14159265) +#endif + + +typedef struct +{ + double left_phase; + double right_phase; + unsigned int framesToGo; +} +paTestData; +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patestCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + SAMPLE_t *out = (SAMPLE_t *)outputBuffer; + SAMPLE_t sample; + int i; + int framesToCalc; + int finished = 0; + (void) outTime; /* Prevent unused variable warnings. */ + (void) inputBuffer; + + if( data->framesToGo < framesPerBuffer ) + { + framesToCalc = data->framesToGo; + data->framesToGo = 0; + finished = 1; + } + else + { + framesToCalc = framesPerBuffer; + data->framesToGo -= framesPerBuffer; + } + + for( i=0; ileft_phase += (LEFT_FREQ / SAMPLE_RATE); + if( data->left_phase > 1.0) data->left_phase -= 1.0; + sample = DOUBLE_TO_SAMPLE( AMPLITUDE * sin( (data->left_phase * M_PI * 2. ))); /**/ + *out++ = sample; +/* *out++ = sample; /**/ +/* *out++ = 0; /**/ + + data->right_phase += (RIGHT_FREQ / SAMPLE_RATE); + if( data->right_phase > 1.0) data->right_phase -= 1.0; + *out++ = DOUBLE_TO_SAMPLE( AMPLITUDE * sin( (data->right_phase * M_PI * 2. ))); /**/ +/* *out++ = 0; /* */ + } + /* zero remainder of final buffer */ + for( ; i<(int)framesPerBuffer; i++ ) + { + *out++ = SAMPLE_ZERO; /* left */ + *out++ = SAMPLE_ZERO; /* right */ + } + return finished; +} +/*******************************************************************/ +int main(void); +int main(void) +{ + PortAudioStream *stream; + PaError err; + paTestData data; + int totalSamps; + + printf("PortAudio Test: output " FORMAT_NAME "\n"); + + + data.left_phase = data.right_phase = 0.0; + data.framesToGo = totalSamps = NUM_SECONDS * SAMPLE_RATE; /* Play for a few seconds. */ + err = Pa_Initialize(); + if( err != paNoError ) goto error; + + err = Pa_OpenStream( + &stream, + paNoDevice,/* default input device */ + 0, /* no input */ + TEST_FORMAT, + NULL, + Pa_GetDefaultOutputDeviceID(), /* default output device */ + 2, /* stereo output */ + TEST_FORMAT, + NULL, + SAMPLE_RATE, + FRAMES_PER_BUFFER, + 0, /* number of buffers, if zero then use default minimum */ + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + patestCallback, + &data ); + if( err != paNoError ) goto error; + + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + + printf("Waiting %d seconds for sound to finish.\n", NUM_SECONDS ); + while( Pa_StreamActive( stream ) ) Pa_Sleep(10); + + err = Pa_CloseStream( stream ); + if( err != paNoError ) goto error; + Pa_Terminate(); + + printf("PortAudio Test Finished: " FORMAT_NAME "\n"); + + return err; +error: + Pa_Terminate(); + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + return err; +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_tests/debug_sine_getchar.c b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/debug_sine_getchar.c new file mode 100755 index 00000000000..88f9dce630f --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/debug_sine_getchar.c @@ -0,0 +1,140 @@ +/* + * $Id: debug_sine_getchar.c,v 1.1.2.1 2005-08-16 20:04:10 alex%croczilla.com Exp $ + * + * Play a sine wave using the Portable Audio api until ENTER hit. + * + * Authors: + * Ross Bencina + * Phil Burk + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.audiomulch.com/portaudio/ + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +#include +#include +#include "portaudio.h" + +#define SAMPLE_RATE (48000) +#define AMPLITUDE (0.3) +#define FRAMES_PER_BUFFER (64) +#define OUTPUT_DEVICE Pa_GetDefaultOutputDeviceID() +//#define OUTPUT_DEVICE (2) + +#ifndef M_PI +#define M_PI (3.14159265) +#endif + +#define TABLE_SIZE (200) +typedef struct +{ + float sine[TABLE_SIZE]; + int left_phase; + int right_phase; +} +paTestData; + +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patestCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + float *out = (float*)outputBuffer; + unsigned long i; + int finished = 0; + (void) outTime; /* Prevent unused variable warnings. */ + (void) inputBuffer; + for( i=0; isine[data->left_phase]; /* left */ + *out++ = data->sine[data->right_phase]; /* right */ + data->left_phase += 1; + if( data->left_phase >= TABLE_SIZE ) data->left_phase -= TABLE_SIZE; + data->right_phase += 3; /* higher pitch so we can distinguish left and right. */ + if( data->right_phase >= TABLE_SIZE ) data->right_phase -= TABLE_SIZE; + } + return finished; +} + +/*******************************************************************/ +int main(void); +int main(void) +{ + PortAudioStream *stream; + PaError err; + paTestData data; + int i; + printf("PortAudio Test: output sine wave. SR = %d, BufSize = %d, devID = %d\n", + SAMPLE_RATE, FRAMES_PER_BUFFER, OUTPUT_DEVICE); + /* initialise sinusoidal wavetable */ + for( i=0; i +#include +#include +#include "portaudio.h" + +#define EWS88MT_12_REC (1) +#define EWS88MT_12_PLAY (10) +#define SBLIVE_REC (2) +#define SBLIVE_PLAY (11) + +#if 0 +#define INPUT_DEVICE_ID Pa_GetDefaultInputDeviceID() +#define OUTPUT_DEVICE_ID Pa_GetDefaultOutputDeviceID() +#else +#define INPUT_DEVICE_ID (EWS88MT_12_REC) +#define OUTPUT_DEVICE_ID (SBLIVE_PLAY) +#endif + +#define INPUT_SAMPLE_RATE (22050.0) +#define OUTPUT_SAMPLE_RATE (22050.0) +#define NUM_SECONDS (4) +#define SLEEP_DUR_MSEC (1000) +#define FRAMES_PER_BUFFER (64) +#define NUM_REC_BUFS (0) +#define SAMPLES_PER_FRAME (2) + +#define PA_SAMPLE_TYPE paInt16 +typedef short SAMPLE; + +typedef struct +{ + long frameIndex; /* Index into sample array. */ +} +paTestData; + +/* This routine will be called by the PortAudio engine when audio is needed. +** It may be called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int recordCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData *) userData; + (void) outputBuffer; /* Prevent unused variable warnings. */ + (void) outTime; + + if( inputBuffer != NULL ) + { + data->frameIndex += framesPerBuffer; + } + return 0; +} + +/* This routine will be called by the PortAudio engine when audio is needed. +** It may be called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int playCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData *) userData; + (void) inputBuffer; /* Prevent unused variable warnings. */ + (void) outTime; + + if( outputBuffer != NULL ) + { + data->frameIndex += framesPerBuffer; + } + return 0; +} + +/****************************************************************/ +PaError MeasureStreamRate( PortAudioStream *stream, paTestData *dataPtr, double *ratePtr ) +{ + PaError err; + int i; + int totalFrames = 0; + int totalMSec = 0; + + dataPtr->frameIndex = 0; + + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + + for( i=0; i<(NUM_SECONDS*1000/SLEEP_DUR_MSEC); i++ ) + { + int delta, endIndex; + + int startIndex = dataPtr->frameIndex; + Pa_Sleep(SLEEP_DUR_MSEC); + endIndex = dataPtr->frameIndex; + + delta = endIndex - startIndex; + totalFrames += delta; + totalMSec += SLEEP_DUR_MSEC; + + printf("index = %d, delta = %d\n", endIndex, delta ); fflush(stdout); + } + + err = Pa_StopStream( stream ); + if( err != paNoError ) goto error; + + *ratePtr = (totalFrames * 1000.0) / totalMSec; + +error: + return err; +} + +void ReportRate( double measuredRate, double expectedRate ) +{ + double error; + + error = (measuredRate - expectedRate) / expectedRate; + error = (error < 0 ) ? -error : error; + + printf("Measured rate = %6.1f, expected rate = %6.1f\n", + measuredRate, expectedRate ); + if( error > 0.1 ) + { + printf("ERROR: unexpected rate! --------------------- ERROR!\n"); + } + else + { + printf("SUCCESS: rate within tolerance!\n"); + } +} + +/*******************************************************************/ +int main(void); +int main(void) +{ + PaError err; + paTestData data = { 0 }; + long i; + double rate; + const PaDeviceInfo *pdi; + + PortAudioStream *outputStream; + PortAudioStream *inputStream; + + err = Pa_Initialize(); + if( err != paNoError ) goto error; + + + pdi = Pa_GetDeviceInfo( INPUT_DEVICE_ID ); + printf("Input device = %s\n", pdi->name ); + pdi = Pa_GetDeviceInfo( OUTPUT_DEVICE_ID ); + printf("Output device = %s\n", pdi->name ); + +/* Open input stream. */ + err = Pa_OpenStream( + &inputStream, + INPUT_DEVICE_ID, + SAMPLES_PER_FRAME, /* stereo input */ + PA_SAMPLE_TYPE, + NULL, + paNoDevice, + 0, + PA_SAMPLE_TYPE, + NULL, + INPUT_SAMPLE_RATE, + FRAMES_PER_BUFFER, /* frames per buffer */ + NUM_REC_BUFS, /* number of buffers, if zero then use default minimum */ + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + recordCallback, + &data ); + if( err != paNoError ) goto error; + + err = Pa_OpenStream( + &outputStream, + paNoDevice, + 0, /* NO input */ + PA_SAMPLE_TYPE, + NULL, + OUTPUT_DEVICE_ID, + SAMPLES_PER_FRAME, /* stereo output */ + PA_SAMPLE_TYPE, + NULL, + OUTPUT_SAMPLE_RATE, + FRAMES_PER_BUFFER, /* frames per buffer */ + 0, /* number of buffers, if zero then use default minimum */ + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + playCallback, + &data ); + if( err != paNoError ) goto error; + +/* Record and playback multiple times. */ + for( i=0; i<2; i++ ) + { + printf("Measuring INPUT ------------------------- \n"); + err = MeasureStreamRate( inputStream, &data, &rate ); + if( err != paNoError ) goto error; + ReportRate( rate, INPUT_SAMPLE_RATE ); + + printf("Measuring OUTPUT ------------------------- \n"); + err = MeasureStreamRate( outputStream, &data, &rate ); + if( err != paNoError ) goto error; + ReportRate( rate, OUTPUT_SAMPLE_RATE ); + } + +/* Clean up. */ + err = Pa_CloseStream( inputStream ); + if( err != paNoError ) goto error; + + err = Pa_CloseStream( outputStream ); + if( err != paNoError ) goto error; + + if( err != paNoError ) goto error; + + Pa_Terminate(); + + printf("Test complete.\n"); fflush(stdout); + return 0; + +error: + Pa_Terminate(); + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + if( err == paHostError ) + { + fprintf( stderr, "Host Error number: %d\n", Pa_GetHostError() ); + } + return -1; +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_tests/debug_test1.c b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/debug_test1.c new file mode 100755 index 00000000000..041323f64e8 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/debug_test1.c @@ -0,0 +1,114 @@ +/* + * $Id: debug_test1.c,v 1.1.2.1 2005-08-16 20:04:10 alex%croczilla.com Exp $ + patest1.c + Ring modulate the audio input with a 441hz sine wave for 20 seconds + using the Portable Audio api + Author: Ross Bencina + Modifications: + April 5th, 2001 - PLB - Check for NULL inputBuffer. +*/ +#include +#include +#include "portaudio.h" +#ifndef M_PI +#define M_PI (3.14159265) +#endif +typedef struct +{ + float sine[100]; + int phase; + int sampsToGo; +} +patest1data; +static int patest1Callback( void *inputBuffer, void *outputBuffer, + unsigned long bufferFrames, + PaTimestamp outTime, void *userData ) +{ + patest1data *data = (patest1data*)userData; + float *in = (float*)inputBuffer; + float *out = (float*)outputBuffer; + int framesToCalc = bufferFrames; + unsigned long i; + int finished = 0; + if(inputBuffer == NULL) return 0; + if( data->sampsToGo < bufferFrames ) + { + finished = 1; + } + for( i=0; iphase >= 100 ) + data->phase = 0; + } + data->sampsToGo -= bufferFrames; + /* zero remainder of final buffer if not already done */ + for( ; i +#include +#include "portaudio.h" + +/*******************************************************************/ +int main(void); +int main(void) +{ + int i,j; + int numDevices; + const PaDeviceInfo *pdi; + PaError err; + Pa_Initialize(); + numDevices = Pa_CountDevices(); + if( numDevices < 0 ) + { + printf("ERROR: Pa_CountDevices returned 0x%x\n", numDevices ); + err = numDevices; + goto error; + } + printf("Number of devices = %d\n", numDevices ); + for( i=0; iname ); + printf("Max Inputs = %d", pdi->maxInputChannels ); + printf(", Max Outputs = %d\n", pdi->maxOutputChannels ); + if( pdi->numSampleRates == -1 ) + { + printf("Sample Rate Range = %f to %f\n", pdi->sampleRates[0], pdi->sampleRates[1] ); + } + else + { + printf("Sample Rates ="); + for( j=0; jnumSampleRates; j++ ) + { + printf(" %8.2f,", pdi->sampleRates[j] ); + } + printf("\n"); + } + printf("Native Sample Formats = "); + if( pdi->nativeSampleFormats & paInt8 ) printf("paInt8, "); + if( pdi->nativeSampleFormats & paUInt8 ) printf("paUInt8, "); + if( pdi->nativeSampleFormats & paInt16 ) printf("paInt16, "); + if( pdi->nativeSampleFormats & paInt32 ) printf("paInt32, "); + if( pdi->nativeSampleFormats & paFloat32 ) printf("paFloat32, "); + if( pdi->nativeSampleFormats & paInt24 ) printf("paInt24, "); + if( pdi->nativeSampleFormats & paPackedInt24 ) printf("paPackedInt24, "); + printf("\n"); + } + Pa_Terminate(); + + printf("----------------------------------------------\n"); + return 0; +error: + Pa_Terminate(); + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + return err; +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_tests/pa_fuzz.c b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/pa_fuzz.c new file mode 100755 index 00000000000..e04954a2395 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/pa_fuzz.c @@ -0,0 +1,156 @@ +/* + * $Id: pa_fuzz.c,v 1.1.2.1 2005-08-16 20:04:10 alex%croczilla.com Exp $ + * pa_fuzz.c + * Distort input like a fuzz boz. + * + * Author: Phil Burk http://www.softsynth.com + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.portaudio.com + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +#include +#include +#include "portaudio.h" +/* +** Note that many of the older ISA sound cards on PCs do NOT support +** full duplex audio (simultaneous record and playback). +** And some only support full duplex at lower sample rates. +*/ +#define SAMPLE_RATE (44100) +#define PA_SAMPLE_TYPE paFloat32 +#define FRAMES_PER_BUFFER (64) + +typedef float SAMPLE; + +float CubicAmplifier( float input ); +static int fuzzCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ); + +/* Non-linear amplifier with soft distortion curve. */ +float CubicAmplifier( float input ) +{ + float output, temp; + if( input < 0.0 ) + { + temp = input + 1.0f; + output = (temp * temp * temp) - 1.0f; + } + else + { + temp = input - 1.0f; + output = (temp * temp * temp) + 1.0f; + } + + return output; +} +#define FUZZ(x) CubicAmplifier(CubicAmplifier(CubicAmplifier(CubicAmplifier(x)))) + +static int gNumNoInputs = 0; +/* This routine will be called by the PortAudio engine when audio is needed. +** It may be called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int fuzzCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + SAMPLE *out = (SAMPLE*)outputBuffer; + SAMPLE *in = (SAMPLE*)inputBuffer; + unsigned int i; + (void) outTime; /* Prevent unused variable warnings. */ + (void) userData; + + if( inputBuffer == NULL ) + { + for( i=0; i +#include +#include +#include "portaudio.h" + +#ifndef M_PI +#define M_PI (3.14159265) +#endif +#define TWOPI (M_PI * 2.0) + +#define DEFAULT_BUFFER_SIZE (64) + +typedef struct +{ + double left_phase; + double right_phase; +} +paTestData; + +/* Very simple synthesis routine to generate two sine waves. */ +static int paminlatCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + float *out = (float*)outputBuffer; + unsigned int i; + double left_phaseInc = 0.02; + double right_phaseInc = 0.06; + + double left_phase = data->left_phase; + double right_phase = data->right_phase; + + for( i=0; i TWOPI ) left_phase -= TWOPI; + *out++ = (float) sin( left_phase ); + + right_phase += right_phaseInc; + if( right_phase > TWOPI ) right_phase -= TWOPI; + *out++ = (float) sin( right_phase ); + } + + data->left_phase = left_phase; + data->right_phase = right_phase; + return 0; +} +void main( int argc, char **argv ); +void main( int argc, char **argv ) +{ + PortAudioStream *stream; + PaError err; + paTestData data; + int go; + int numBuffers = 0; + int minBuffers = 0; + int framesPerBuffer; + double sampleRate = 44100.0; + char str[256]; + printf("paminlat - Determine minimum latency for your computer.\n"); + printf(" usage: paminlat {framesPerBuffer}\n"); + printf(" for example: paminlat 256\n"); + printf("Adjust your stereo until you hear a smooth tone in each speaker.\n"); + printf("Then try to find the smallest number of buffers that still sounds smooth.\n"); + printf("Note that the sound will stop momentarily when you change the number of buffers.\n"); + /* Get bufferSize from command line. */ + framesPerBuffer = ( argc > 1 ) ? atol( argv[1] ) : DEFAULT_BUFFER_SIZE; + printf("Frames per buffer = %d\n", framesPerBuffer ); + + data.left_phase = data.right_phase = 0.0; + err = Pa_Initialize(); + if( err != paNoError ) goto error; + /* Ask PortAudio for the recommended minimum number of buffers. */ + numBuffers = minBuffers = Pa_GetMinNumBuffers( framesPerBuffer, sampleRate ); + printf("NumBuffers set to %d based on a call to Pa_GetMinNumBuffers()\n", numBuffers ); + /* Try different numBuffers in a loop. */ + go = 1; + while( go ) + { + + printf("Latency = framesPerBuffer * numBuffers = %d * %d = %d frames = %d msecs.\n", + framesPerBuffer, numBuffers, framesPerBuffer*numBuffers, + (int)((1000 * framesPerBuffer * numBuffers) / sampleRate) ); + err = Pa_OpenStream( + &stream, + paNoDevice, + 0, /* no input */ + paFloat32, /* 32 bit floating point input */ + NULL, + Pa_GetDefaultOutputDeviceID(), /* default output device */ + 2, /* stereo output */ + paFloat32, /* 32 bit floating point output */ + NULL, + sampleRate, + framesPerBuffer, + numBuffers, /* number of buffers */ + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + paminlatCallback, + &data ); + if( err != paNoError ) goto error; + if( stream == NULL ) goto error; + /* Start audio. */ + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + /* Ask user for a new number of buffers. */ + printf("\nMove windows around to see if the sound glitches.\n"); + printf("NumBuffers currently %d, enter new number, or 'q' to quit: ", numBuffers ); + gets( str ); + if( str[0] == 'q' ) go = 0; + else + { + numBuffers = atol( str ); + if( numBuffers < minBuffers ) + { + printf( "numBuffers below minimum of %d! Set to minimum!!!\n", minBuffers ); + numBuffers = minBuffers; + } + } + /* Stop sound until ENTER hit. */ + err = Pa_StopStream( stream ); + if( err != paNoError ) goto error; + err = Pa_CloseStream( stream ); + if( err != paNoError ) goto error; + } + printf("A good setting for latency would be somewhat higher than\n"); + printf("the minimum latency that worked.\n"); + printf("PortAudio: Test finished.\n"); + Pa_Terminate(); + return; +error: + Pa_Terminate(); + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_tests/paqa_devs.c b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/paqa_devs.c new file mode 100755 index 00000000000..4103705d0d3 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/paqa_devs.c @@ -0,0 +1,322 @@ +/* + * $Id: paqa_devs.c,v 1.1.2.1 2005-08-16 20:04:10 alex%croczilla.com Exp $ + * paqa_devs.c + * Self Testing Quality Assurance app for PortAudio + * Try to open each device and run through all the + * possible configurations. + * + * Author: Phil Burk http://www.softsynth.com + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.portaudio.com + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +#include +#include +#include "portaudio.h" +#include "pa_trace.h" +/****************************************** Definitions ***********/ +#define MODE_INPUT (0) +#define MODE_OUTPUT (1) +typedef struct PaQaData +{ + unsigned long framesLeft; + int numChannels; + int bytesPerSample; + int mode; + short sawPhase; + PaSampleFormat format; +} PaQaData; + +/****************************************** Prototypes ***********/ +static void TestDevices( int mode ); +static void TestFormats( int mode, PaDeviceID deviceID, double sampleRate, + int numChannels ); +static int TestAdvance( int mode, PaDeviceID deviceID, double sampleRate, + int numChannels, PaSampleFormat format ); +static int QaCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ); + +/****************************************** Globals ***********/ +static int gNumPassed = 0; +static int gNumFailed = 0; + +/****************************************** Macros ***********/ +/* Print ERROR if it fails. Tally success or failure. */ +/* Odd do-while wrapper seems to be needed for some compilers. */ +#define EXPECT(_exp) \ + do \ + { \ + if ((_exp)) {\ + /* printf("SUCCESS for %s\n", #_exp ); */ \ + gNumPassed++; \ + } \ + else { \ + printf("ERROR - 0x%x - %s for %s\n", result, \ + ((result == 0) ? "-" : Pa_GetErrorText(result)), \ + #_exp ); \ + gNumFailed++; \ + goto error; \ + } \ + } while(0) +/*******************************************************************/ +/* This routine will be called by the PortAudio engine when audio is needed. +** It may be called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int QaCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + unsigned long i; + short phase; + PaQaData *data = (PaQaData *) userData; + (void) inputBuffer; + (void) outTime; + + /* Play simple sawtooth wave. */ + if( data->mode == MODE_OUTPUT ) + { + phase = data->sawPhase; + switch( data->format ) + { + case paFloat32: + { + float *out = (float *) outputBuffer; + for( i=0; inumChannels == 2 ) + { + *out++ = (float) (phase * (1.0 / 32768.0)); + } + } + } + break; + + case paInt32: + { + int *out = (int *) outputBuffer; + for( i=0; inumChannels == 2 ) + { + *out++ = ((int) phase ) << 16; + } + } + } + break; + case paInt16: + { + short *out = (short *) outputBuffer; + for( i=0; inumChannels == 2 ) + { + *out++ = phase; + } + } + } + break; + + default: + { + unsigned char *out = (unsigned char *) outputBuffer; + unsigned long numBytes = framesPerBuffer * data->numChannels * data->bytesPerSample; + for( i=0; isawPhase = phase; + } + /* Are we through yet? */ + if( data->framesLeft > framesPerBuffer ) + { + AddTraceMessage("QaCallback: running. framesLeft", data->framesLeft ); + data->framesLeft -= framesPerBuffer; + return 0; + } + else + { + AddTraceMessage("QaCallback: DONE! framesLeft", data->framesLeft ); + data->framesLeft = 0; + return 1; + } +} +/*******************************************************************/ +int main(void); +int main(void) +{ + PaError result; + EXPECT( ((result=Pa_Initialize()) == 0) ); + printf("Test OUTPUT ---------------\n"); + TestDevices( MODE_OUTPUT ); + printf("Test INPUT ---------------\n"); + TestDevices( MODE_INPUT ); +error: + Pa_Terminate(); + printf("QA Report: %d passed, %d failed.\n", gNumPassed, gNumFailed ); +} +/******************************************************************* +* Try each output device, through its full range of capabilities. */ +static void TestDevices( int mode ) +{ + int id,jc,kr; + int maxChannels; + const PaDeviceInfo *pdi; + int numDevices = Pa_CountDevices(); + /* Iterate through all devices. */ + for( id=0; idmaxInputChannels : pdi->maxOutputChannels; + for( jc=1; jc<=maxChannels; jc++ ) + { + printf("Name = %s\n", pdi->name ); + /* Try each legal sample rate. */ + if( pdi->numSampleRates == -1 ) + { + double low, high; + low = pdi->sampleRates[0]; + high = pdi->sampleRates[1]; + if( low < 8000.0 ) low = 8000.0; + TestFormats( mode, id, low, jc ); +#define TESTSR(sr) {if(((sr)>=low) && ((sr)<=high)) TestFormats( mode, id, (sr), jc ); } + + TESTSR(11025.0); + TESTSR(22050.0); + TESTSR(34567.0); + TESTSR(44100.0); + TestFormats( mode, id, high, jc ); + } + else + { + for( kr=0; krnumSampleRates; kr++ ) + { + TestFormats( mode, id, pdi->sampleRates[kr], jc ); + } + } + } + } +} +/*******************************************************************/ +static void TestFormats( int mode, PaDeviceID deviceID, double sampleRate, + int numChannels ) +{ + TestAdvance( mode, deviceID, sampleRate, numChannels, paFloat32 ); /* */ + TestAdvance( mode, deviceID, sampleRate, numChannels, paInt16 ); /* */ + TestAdvance( mode, deviceID, sampleRate, numChannels, paInt32 ); /* */ +} +/*******************************************************************/ +static int TestAdvance( int mode, PaDeviceID deviceID, double sampleRate, + int numChannels, PaSampleFormat format ) +{ + PortAudioStream *stream = NULL; + PaError result; + PaQaData myData; +#define FRAMES_PER_BUFFER (64) + printf("------ TestAdvance: %s, device = %d, rate = %g, numChannels = %d, format = %d -------\n", + ( mode == MODE_INPUT ) ? "INPUT" : "OUTPUT", + deviceID, sampleRate, numChannels, format); + fflush(stdout); + /* Setup data for synthesis thread. */ + myData.framesLeft = (unsigned long) (sampleRate * 100); /* 100 seconds */ + myData.numChannels = numChannels; + myData.mode = mode; + myData.format = format; + switch( format ) + { + case paFloat32: + case paInt32: + case paInt24: + myData.bytesPerSample = 4; + break; + case paPackedInt24: + myData.bytesPerSample = 3; + break; + default: + myData.bytesPerSample = 2; + break; + } + EXPECT( ((result = Pa_OpenStream( + &stream, + ( mode == MODE_INPUT ) ? deviceID : paNoDevice, + ( mode == MODE_INPUT ) ? numChannels : 0, + format, + NULL, + ( mode == MODE_OUTPUT ) ? deviceID : paNoDevice, + ( mode == MODE_OUTPUT ) ? numChannels : 0, + format, + NULL, + sampleRate, + FRAMES_PER_BUFFER, /* frames per buffer */ + 0, /* number of buffers, if zero then use default minimum */ + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + QaCallback, + &myData ) + ) == 0) ); + if( stream ) + { + PaTimestamp oldStamp, newStamp; + unsigned long oldFrames; + int minDelay = ( mode == MODE_INPUT ) ? 1000 : 400; + int minNumBuffers = Pa_GetMinNumBuffers( FRAMES_PER_BUFFER, sampleRate ); + int msec = (int) ((minNumBuffers * 3 * 1000.0 * FRAMES_PER_BUFFER) / sampleRate); + if( msec < minDelay ) msec = minDelay; + printf("msec = %d\n", msec); /**/ + EXPECT( ((result=Pa_StartStream( stream )) == 0) ); + /* Check to make sure PortAudio is advancing timeStamp. */ + result = paNoError; + oldStamp = Pa_StreamTime(stream); + fflush(stdout); + Pa_Sleep(msec); + newStamp = Pa_StreamTime(stream); + printf("oldStamp = %g,newStamp = %g\n", oldStamp, newStamp ); /**/ + EXPECT( (oldStamp < newStamp) ); + /* Check to make sure callback is decrementing framesLeft. */ + oldFrames = myData.framesLeft; + Pa_Sleep(msec); + printf("oldFrames = %d, myData.framesLeft = %d\n", oldFrames, myData.framesLeft ); /**/ + EXPECT( (oldFrames > myData.framesLeft) ); + EXPECT( ((result=Pa_CloseStream( stream )) == 0) ); + stream = NULL; + } +error: + if( stream != NULL ) Pa_CloseStream( stream ); + fflush(stdout); + return result; +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_tests/paqa_errs.c b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/paqa_errs.c new file mode 100755 index 00000000000..a95e796c162 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/paqa_errs.c @@ -0,0 +1,330 @@ +/* + * $Id: paqa_errs.c,v 1.1.2.1 2005-08-16 20:04:10 alex%croczilla.com Exp $ + * paqa_devs.c + * Self Testing Quality Assurance app for PortAudio + * Do lots of bad things to test error reporting. + * + * Author: Phil Burk http://www.softsynth.com + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.portaudio.com + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +#include +#include +#include "portaudio.h" +/****************************************** Definitions ***********/ +#define MODE_INPUT (0) +#define MODE_OUTPUT (1) +#define FRAMES_PER_BUFFER (64) +#define SAMPLE_RATE (44100.0) +#define NUM_BUFFERS (0) +typedef struct PaQaData +{ + unsigned long framesLeft; + int numChannels; + int bytesPerSample; + int mode; +} +PaQaData; +/****************************************** Prototypes ***********/ +static void TestDevices( int mode ); +static void TestFormats( int mode, PaDeviceID deviceID, double sampleRate, + int numChannels ); +static int TestBadOpens( void ); +static int TestBadActions( void ); +static int QaCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ); +/****************************************** Globals ***********/ +static int gNumPassed = 0; +static int gNumFailed = 0; +/****************************************** Macros ***********/ +/* Print ERROR if it fails. Tally success or failure. */ +/* Odd do-while wrapper seems to be needed for some compilers. */ +#define EXPECT( msg, _exp) \ + do \ + { \ + if ((_exp)) {\ + gNumPassed++; \ + } \ + else { \ + printf("\nERROR %s\n - 0x%x - %s for %s\n", (msg), result, Pa_GetErrorText(result), #_exp ); \ + gNumFailed++; \ + goto error; \ + } \ + } while(0) +#define HOPEFOR( msg, _exp) \ + do \ + { \ + if ((_exp)) {\ + gNumPassed++; \ + } \ + else { \ + printf("\nERROR %s\n - 0x%x - %s for %s\n", (msg), result, Pa_GetErrorText(result), #_exp ); \ + gNumFailed++; \ + } \ + } while(0) +/*******************************************************************/ +/* This routine will be called by the PortAudio engine when audio is needed. +** It may be called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int QaCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + unsigned long i; + unsigned char *out = (unsigned char *) outputBuffer; + PaQaData *data = (PaQaData *) userData; + (void) inputBuffer; /* Prevent "unused variable" warnings. */ + (void) outTime; + + /* Zero out buffer so we don't hear terrible noise. */ + if( data->mode == MODE_OUTPUT ) + { + unsigned long numBytes = framesPerBuffer * data->numChannels * data->bytesPerSample; + for( i=0; iframesLeft > framesPerBuffer ) + { + data->framesLeft -= framesPerBuffer; + return 0; + } + else + { + data->framesLeft = 0; + return 1; + } +} +/*******************************************************************/ +int main(void); +int main(void) +{ + PaError result; + EXPECT( "init", ((result=Pa_Initialize()) == 0) ); + TestBadActions(); + TestBadOpens(); +error: + Pa_Terminate(); + printf("QA Report: %d passed, %d failed.\n", gNumPassed, gNumFailed ); + return 0; +} +/*******************************************************************/ +static int TestBadOpens( void ) +{ + PortAudioStream *stream = NULL; + PaError result; + PaQaData myData; + /* Setup data for synthesis thread. */ + myData.framesLeft = (unsigned long) (SAMPLE_RATE * 100); /* 100 seconds */ + myData.numChannels = 1; + myData.mode = MODE_OUTPUT; + HOPEFOR( "No devices specified.",( + (result = Pa_OpenStream( + &stream, + paNoDevice, 0, paFloat32, NULL, + paNoDevice, 0, paFloat32, NULL, + SAMPLE_RATE, FRAMES_PER_BUFFER, NUM_BUFFERS, + paClipOff, + QaCallback, + &myData ) + ) == paInvalidDeviceId) ); + HOPEFOR( "Out of range input device specified.",( + (result = Pa_OpenStream( + &stream, + Pa_CountDevices(), 0, paFloat32, NULL, + paNoDevice, 0, paFloat32, NULL, + SAMPLE_RATE, FRAMES_PER_BUFFER, NUM_BUFFERS, + paClipOff, + QaCallback, + &myData ) + ) == paInvalidDeviceId) ); + + HOPEFOR( "Out of range output device specified.",( + (result = Pa_OpenStream( + &stream, + paNoDevice, 0, paFloat32, NULL, + Pa_CountDevices(), 0, paFloat32, NULL, + SAMPLE_RATE, FRAMES_PER_BUFFER, NUM_BUFFERS, + paClipOff, + QaCallback, + &myData ) + ) == paInvalidDeviceId) ); + HOPEFOR( "Zero input channels.",( + (result = Pa_OpenStream( + &stream, + Pa_GetDefaultInputDeviceID(), 0, paFloat32, NULL, + paNoDevice, 0, paFloat32, NULL, + SAMPLE_RATE, FRAMES_PER_BUFFER, NUM_BUFFERS, + paClipOff, + QaCallback, + &myData ) + ) == paInvalidChannelCount) ); + HOPEFOR( "Zero output channels.",( + (result = Pa_OpenStream( + &stream, + paNoDevice, 0, paFloat32, NULL, + Pa_GetDefaultOutputDeviceID(), 0, paFloat32, NULL, + SAMPLE_RATE, FRAMES_PER_BUFFER, NUM_BUFFERS, + paClipOff, + QaCallback, + &myData ) + ) == paInvalidChannelCount) ); + HOPEFOR( "Nonzero input channels but no device.",( + (result = Pa_OpenStream( + &stream, + Pa_GetDefaultInputDeviceID(), 2, paFloat32, NULL, + paNoDevice, 2, paFloat32, NULL, + SAMPLE_RATE, FRAMES_PER_BUFFER, NUM_BUFFERS, + paClipOff, + QaCallback, + &myData ) + ) == paInvalidChannelCount) ); + + HOPEFOR( "Nonzero output channels but no device.",( + (result = Pa_OpenStream( + &stream, + paNoDevice, 2, paFloat32, NULL, + Pa_GetDefaultOutputDeviceID(), 2, paFloat32, NULL, + SAMPLE_RATE, FRAMES_PER_BUFFER, NUM_BUFFERS, + paClipOff, + QaCallback, + &myData ) + ) == paInvalidChannelCount) ); + HOPEFOR( "NULL stream pointer.",( + (result = Pa_OpenStream( + NULL, + paNoDevice, 0, paFloat32, NULL, + Pa_GetDefaultOutputDeviceID(), 2, paFloat32, NULL, + SAMPLE_RATE, FRAMES_PER_BUFFER, NUM_BUFFERS, + paClipOff, + QaCallback, + &myData ) + ) == paBadStreamPtr) ); + HOPEFOR( "Low sample rate.",( + (result = Pa_OpenStream( + &stream, + paNoDevice, 0, paFloat32, NULL, + Pa_GetDefaultOutputDeviceID(), 2, paFloat32, NULL, + 1.0, FRAMES_PER_BUFFER, NUM_BUFFERS, + paClipOff, + QaCallback, + &myData ) + ) == paInvalidSampleRate) ); + HOPEFOR( "High sample rate.",( + (result = Pa_OpenStream( + &stream, + paNoDevice, 0, paFloat32, NULL, + Pa_GetDefaultOutputDeviceID(), 2, paFloat32, NULL, + 10000000.0, FRAMES_PER_BUFFER, NUM_BUFFERS, + paClipOff, + QaCallback, + &myData ) + ) == paInvalidSampleRate) ); + HOPEFOR( "NULL callback.",( + (result = Pa_OpenStream( + &stream, + paNoDevice, 0, paFloat32, NULL, + Pa_GetDefaultOutputDeviceID(), 2, paFloat32, NULL, + SAMPLE_RATE, FRAMES_PER_BUFFER, NUM_BUFFERS, + paClipOff, + NULL, + &myData ) + ) == paNullCallback) ); + HOPEFOR( "Bad flag.",( + (result = Pa_OpenStream( + &stream, + paNoDevice, 0, paFloat32, NULL, + Pa_GetDefaultOutputDeviceID(), 2, paFloat32, NULL, + SAMPLE_RATE, FRAMES_PER_BUFFER, NUM_BUFFERS, + (1<<3), + QaCallback, + &myData ) + ) == paInvalidFlag) ); + +#if 1 /* FIXME - this is legal for some implementations. */ + HOPEFOR( "Use input device as output device.",( + (result = Pa_OpenStream( + &stream, + paNoDevice, 0, paFloat32, NULL, + Pa_GetDefaultInputDeviceID(), 2, paFloat32, NULL, + SAMPLE_RATE, FRAMES_PER_BUFFER, NUM_BUFFERS, + paClipOff, + QaCallback, + &myData ) + ) == paInvalidDeviceId) ); + + HOPEFOR( "Use output device as input device.",( + (result = Pa_OpenStream( + &stream, + Pa_GetDefaultOutputDeviceID(), 2, paFloat32, NULL, + paNoDevice, 0, paFloat32, NULL, + SAMPLE_RATE, FRAMES_PER_BUFFER, NUM_BUFFERS, + paClipOff, + QaCallback, + &myData ) + ) == paInvalidDeviceId) ); +#endif + + if( stream != NULL ) Pa_CloseStream( stream ); + return result; +} +/*******************************************************************/ +static int TestBadActions( void ) +{ + PortAudioStream *stream = NULL; + PaError result; + PaQaData myData; + /* Setup data for synthesis thread. */ + myData.framesLeft = (unsigned long) (SAMPLE_RATE * 100); /* 100 seconds */ + myData.numChannels = 1; + myData.mode = MODE_OUTPUT; + /* Default output. */ + EXPECT( "TestBadActions", ((result = Pa_OpenStream( + &stream, + paNoDevice, 0, paFloat32, NULL, + Pa_GetDefaultOutputDeviceID(), 2, paFloat32, NULL, + SAMPLE_RATE, FRAMES_PER_BUFFER, NUM_BUFFERS, + paClipOff, + QaCallback, + &myData ) + ) == 0) ); + HOPEFOR( "start", ((result = Pa_StartStream( NULL )) == paBadStreamPtr) ); + HOPEFOR( "stop", ((result = Pa_StopStream( NULL )) == paBadStreamPtr) ); + HOPEFOR( "active?", ((result = Pa_StreamActive( NULL )) == paBadStreamPtr) ); + HOPEFOR( "close", ((result = Pa_CloseStream( NULL )) == paBadStreamPtr) ); + HOPEFOR( "time?", ((result = (PaError)Pa_StreamTime( NULL )) != 0) ); + HOPEFOR( "CPULoad?", ((result = (PaError)Pa_GetCPULoad( NULL )) != 0) ); +error: + if( stream != NULL ) Pa_CloseStream( stream ); + return result; +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest1.c b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest1.c new file mode 100755 index 00000000000..ddc82d77fd5 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest1.c @@ -0,0 +1,114 @@ +/* + $Id: patest1.c,v 1.1.2.1 2005-08-16 20:04:10 alex%croczilla.com Exp $ + patest1.c + Ring modulate the audio input with a sine wave for 20 seconds + using the Portable Audio api + Author: Ross Bencina + Modifications: + April 5th, 2001 - PLB - Check for NULL inputBuffer. +*/ +#include +#include +#include "portaudio.h" +#ifndef M_PI +#define M_PI (3.14159265) +#endif +typedef struct +{ + float sine[100]; + int phase; + int sampsToGo; +} +patest1data; +static int patest1Callback( void *inputBuffer, void *outputBuffer, + unsigned long bufferFrames, + PaTimestamp outTime, void *userData ) +{ + patest1data *data = (patest1data*)userData; + float *in = (float*)inputBuffer; + float *out = (float*)outputBuffer; + int framesToCalc = bufferFrames; + unsigned long i; + int finished = 0; + /* Check to see if any input data is available. */ + if(inputBuffer == NULL) return 0; + if( data->sampsToGo < bufferFrames ) + { + framesToCalc = data->sampsToGo; + finished = 1; + } + for( i=0; isine[data->phase]; /* left */ + *out++ = *in++ * data->sine[data->phase++]; /* right */ + if( data->phase >= 100 ) + data->phase = 0; + } + data->sampsToGo -= framesToCalc; + /* zero remainder of final buffer if not already done */ + for( ; i +#include +#include +#include "portaudio.h" +#define NUM_SECONDS (1) +#define SAMPLE_RATE (44100) +#ifndef M_PI +#define M_PI (3.14159265) +#endif +#define TABLE_SIZE (200) + +#define BUFFER_TABLE 9 +long buffer_table[] = {200,256,500,512,600, 723, 1000, 1024, 2345}; + +typedef struct +{ + short sine[TABLE_SIZE]; + int left_phase; + int right_phase; + unsigned int sampsToGo; +} +paTestData; +PaError TestOnce( int buffersize ); + +static int paSineCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ); +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int paSineCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + short *out = (short*)outputBuffer; + unsigned int i; + int finished = 0; + (void) inputBuffer; /* Prevent "unused variable" warnings. */ + (void) outTime; + + if( data->sampsToGo < framesPerBuffer ) + { + for( i=0; isampsToGo; i++ ) + { + *out++ = data->sine[data->left_phase]; /* left */ + *out++ = data->sine[data->right_phase]; /* right */ + data->left_phase += 1; + if( data->left_phase >= TABLE_SIZE ) data->left_phase -= TABLE_SIZE; + data->right_phase += 3; /* higher pitch so we can distinguish left and right. */ + if( data->right_phase >= TABLE_SIZE ) data->right_phase -= TABLE_SIZE; + } + /* zero remainder of final buffer */ + for( ; isine[data->left_phase]; /* left */ + *out++ = data->sine[data->right_phase]; /* right */ + data->left_phase += 1; + if( data->left_phase >= TABLE_SIZE ) data->left_phase -= TABLE_SIZE; + data->right_phase += 3; /* higher pitch so we can distinguish left and right. */ + if( data->right_phase >= TABLE_SIZE ) data->right_phase -= TABLE_SIZE; + } + data->sampsToGo -= framesPerBuffer; + } + return finished; +} +/*******************************************************************/ +int main(void); +int main(void) +{ + int i; + PaError err; + printf("Test opening streams with different buffer sizes\n\n"); + + for (i = 0 ; i < BUFFER_TABLE; i++) + { + printf("Buffer size %d\n", buffer_table[i]); + err = TestOnce(buffer_table[i]); + if( err < 0 ) return 0; + + } +} + + +PaError TestOnce( int buffersize ) +{ + PortAudioStream *stream; + PaError err; + paTestData data; + int i; + int totalSamps; + /* initialise sinusoidal wavetable */ + for( i=0; i +#include +#include "portaudio.h" +#define NUM_SECONDS (4) +#define SAMPLE_RATE (44100) +#ifndef M_PI +#define M_PI (3.14159265) +#endif +#define TABLE_SIZE (200) +typedef struct paTestData +{ + float sine[TABLE_SIZE]; + float amplitude; + int left_phase; + int right_phase; +} +paTestData; +PaError PlaySine( paTestData *data, unsigned long flags, float amplitude ); +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int sineCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + float *out = (float*)outputBuffer; + float amplitude = data->amplitude; + unsigned int i; + (void) inputBuffer; /* Prevent "unused variable" warnings. */ + (void) outTime; + + for( i=0; isine[data->left_phase]; /* left */ + *out++ = amplitude * data->sine[data->right_phase]; /* right */ + data->left_phase += 1; + if( data->left_phase >= TABLE_SIZE ) data->left_phase -= TABLE_SIZE; + data->right_phase += 3; /* higher pitch so we can distinguish left and right. */ + if( data->right_phase >= TABLE_SIZE ) data->right_phase -= TABLE_SIZE; + } + return 0; +} +/*******************************************************************/ +int main(void); +int main(void) +{ + PaError err; + paTestData DATA; + int i; + printf("PortAudio Test: output sine wave with and without clipping.\n"); + /* initialise sinusoidal wavetable */ + for( i=0; ileft_phase = data->right_phase = 0; + data->amplitude = amplitude; + err = Pa_Initialize(); + if( err != paNoError ) goto error; + err = Pa_OpenStream( + &stream, + paNoDevice,/* default input device */ + 0, /* no input */ + paFloat32, /* 32 bit floating point input */ + NULL, + Pa_GetDefaultOutputDeviceID(), /* default output device */ + 2, /* stereo output */ + paFloat32, /* 32 bit floating point output */ + NULL, + SAMPLE_RATE, + 1024, + 0, /* number of buffers, if zero then use default minimum */ + flags, /* we won't output out of range samples so don't bother clipping them */ + sineCallback, + data ); + if( err != paNoError ) goto error; + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + Pa_Sleep( NUM_SECONDS * 1000 ); + printf("CPULoad = %8.6f\n", Pa_GetCPULoad( stream ) ); + err = Pa_CloseStream( stream ); + if( err != paNoError ) goto error; + Pa_Terminate(); + return paNoError; +error: + return err; +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_dither.c b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_dither.c new file mode 100755 index 00000000000..ff38ab88f6f --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_dither.c @@ -0,0 +1,152 @@ +/* + * $Id: patest_dither.c,v 1.1.2.1 2005-08-16 20:04:10 alex%croczilla.com Exp $ + * patest_dither.c + * Attempt to hear difference between dithered and non-dithered signal. + * This only has an effect if the native format is 16 bit. + * + * Author: Phil Burk http://www.softsynth.com + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.portaudio.com + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +#include +#include +#include "portaudio.h" +#define NUM_SECONDS (4) +#define SAMPLE_RATE (44100) +#ifndef M_PI +#define M_PI (3.14159265) +#endif +#define TABLE_SIZE (200) +typedef struct paTestData +{ + float sine[TABLE_SIZE]; + float amplitude; + int left_phase; + int right_phase; +} +paTestData; +PaError PlaySine( paTestData *data, PaStreamFlags flags, float amplitude ); +static int sineCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ); +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int sineCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + float *out = (float*)outputBuffer; + float amplitude = data->amplitude; + unsigned int i; + (void) outTime; + (void) inputBuffer; + for( i=0; isine[data->left_phase]; /* left */ + *out++ = amplitude * data->sine[data->right_phase]; /* right */ + data->left_phase += 1; + if( data->left_phase >= TABLE_SIZE ) data->left_phase -= TABLE_SIZE; + data->right_phase += 3; /* higher pitch so we can distinguish left and right. */ + if( data->right_phase >= TABLE_SIZE ) data->right_phase -= TABLE_SIZE; + } + return 0; +} +/*******************************************************************/ +int main(void); +int main(void) +{ + PaError err; + paTestData DATA; + int i; + float amplitude = 32.0 / (1<<15); + printf("PortAudio Test: output EXTREMELY QUIET sine wave with and without dithering.\n"); + /* initialise sinusoidal wavetable */ + for( i=0; ileft_phase = data->right_phase = 0; + data->amplitude = amplitude; + err = Pa_Initialize(); + if( err != paNoError ) goto error; + err = Pa_OpenStream( + &stream, + paNoDevice,/* default input device */ + 0, /* no input */ + paFloat32, /* 32 bit floating point input */ + NULL, + Pa_GetDefaultOutputDeviceID(), /* default output device */ + 2, /* stereo output */ + paFloat32, /* 32 bit floating point output */ + NULL, + SAMPLE_RATE, + 1024, + 0, /* number of buffers, if zero then use default minimum */ + flags, /* we won't output out of range samples so don't bother clipping them */ + sineCallback, + (void *)data ); + if( err != paNoError ) goto error; + + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + Pa_Sleep( NUM_SECONDS * 1000 ); + printf("CPULoad = %8.6f\n", Pa_GetCPULoad( stream ) ); + err = Pa_CloseStream( stream ); + if( err != paNoError ) goto error; + Pa_Terminate(); + return paNoError; +error: + return err; +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_hang.c b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_hang.c new file mode 100755 index 00000000000..04db3f84b94 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_hang.c @@ -0,0 +1,153 @@ +/* + * $Id: patest_hang.c,v 1.1.2.1 2005-08-16 20:04:10 alex%croczilla.com Exp $ + * Play a sine then hang audio callback to test watchdog. + * + * Authors: + * Ross Bencina + * Phil Burk + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.audiomulch.com/portaudio/ + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +#include +#include +#include "portaudio.h" + + +#define SAMPLE_RATE (44100) +#define FRAMES_PER_BUFFER (1024) +#ifndef M_PI +#define M_PI (3.14159265) +#endif +#define TWOPI (M_PI * 2.0) + +typedef struct paTestData +{ + int sleepFor; + double phase; +} +paTestData; + +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patestCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + float *out = (float*)outputBuffer; + unsigned long i; + int finished = 0; + double phaseInc = 0.02; + double phase = data->phase; + + (void) outTime; /* Prevent unused variable warnings. */ + (void) inputBuffer; + + for( i=0; i TWOPI ) phase -= TWOPI; + /* This is not a very efficient way to calc sines. */ + *out++ = (float) sin( phase ); /* mono */ + } + + if( data->sleepFor > 0 ) + { + Pa_Sleep( data->sleepFor ); + } + + data->phase = phase; + return finished; +} + +/*******************************************************************/ +int main(void); +int main(void) +{ + PortAudioStream *stream; + PaError err; + int i; + paTestData data = {0}; + + printf("PortAudio Test: output sine wave. SR = %d, BufSize = %d\n", + SAMPLE_RATE, FRAMES_PER_BUFFER ); + + err = Pa_Initialize(); + if( err != paNoError ) goto error; + + err = Pa_OpenStream( + &stream, + paNoDevice,/* default input device */ + 0, /* no input */ + paFloat32, /* 32 bit floating point input */ + NULL, + Pa_GetDefaultOutputDeviceID(), /* default output device */ + 1, /* mono output */ + paFloat32, /* 32 bit floating point output */ + NULL, + SAMPLE_RATE, + FRAMES_PER_BUFFER, /* frames per buffer */ + 0, /* number of buffers, if zero then use default minimum */ + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + patestCallback, + &data ); + if( err != paNoError ) goto error; + + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + +/* Gradually increase sleep time. */ + for( i=0; i<10000; i+= 1000 ) + { + printf("Sleep for %d milliseconds in audio callback.\n", i ); + data.sleepFor = i; + fflush(stdout); + Pa_Sleep( ((i<1000) ? 1000 : i) ); + } + + printf("Suffer for 10 seconds.\n"); + fflush(stdout); + Pa_Sleep( 10000 ); + + err = Pa_StopStream( stream ); + if( err != paNoError ) goto error; + err = Pa_CloseStream( stream ); + if( err != paNoError ) goto error; + Pa_Terminate(); + printf("Test finished.\n"); + return err; +error: + Pa_Terminate(); + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + return err; +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_latency.c b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_latency.c new file mode 100755 index 00000000000..54dfd5b9255 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_latency.c @@ -0,0 +1,176 @@ +/* + * $Id: patest_latency.c,v 1.1.2.1 2005-08-16 20:04:10 alex%croczilla.com Exp $ + * Hear the latency caused by big buffers. + * Play a sine wave and change frequency based on letter input. + * + * Author: Phil Burk , and Darren Gibbs + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.portaudio.com + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +#include +#include +#include "portaudio.h" + +#define OUTPUT_DEVICE (Pa_GetDefaultOutputDeviceID()) +#define SAMPLE_RATE (44100) +#define FRAMES_PER_BUFFER (64) + +#if 0 +#define MIN_LATENCY_MSEC (2000) +#define NUM_BUFFERS ((MIN_LATENCY_MSEC * SAMPLE_RATE) / (FRAMES_PER_BUFFER * 1000)) +#else +#define NUM_BUFFERS (0) +#endif + +#define MIN_FREQ (100.0f) +#define CalcPhaseIncrement(freq) ((freq)/SAMPLE_RATE) +#ifndef M_PI +#define M_PI (3.14159265) +#endif +#define TABLE_SIZE (400) +typedef struct +{ + float sine[TABLE_SIZE + 1]; // add one for guard point for interpolation + float phase_increment; + float left_phase; + float right_phase; +} +paTestData; +float LookupSine( paTestData *data, float phase ); +/* Convert phase between and 1.0 to sine value + * using linear interpolation. + */ +float LookupSine( paTestData *data, float phase ) +{ + float fIndex = phase*TABLE_SIZE; + int index = (int) fIndex; + float fract = fIndex - index; + float lo = data->sine[index]; + float hi = data->sine[index+1]; + float val = lo + fract*(hi-lo); + return val; +} +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patestCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + float *out = (float*)outputBuffer; + int i; + int finished = 0; + (void) outTime; /* Prevent unused variable warnings. */ + (void) inputBuffer; + + for( i=0; ileft_phase); /* left */ + *out++ = LookupSine(data, data->right_phase); /* right */ + data->left_phase += data->phase_increment; + if( data->left_phase >= 1.0f ) data->left_phase -= 1.0f; + data->right_phase += (data->phase_increment * 1.5f); /* fifth above */ + if( data->right_phase >= 1.0f ) data->right_phase -= 1.0f; + } + return 0; +} +/*******************************************************************/ +int main(void); +int main(void) +{ + PortAudioStream *stream; + PaError err; + paTestData data; + int i; + int done = 0; + printf("PortAudio Test: enter letter then hit ENTER. numBuffers = %d\n", NUM_BUFFERS ); + /* initialise sinusoidal wavetable */ + for( i=0; i + * Phil Burk + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.audiomulch.com/portaudio/ + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +#include +#include +#include "portaudio.h" +#define NUM_SECONDS (8) +#define SAMPLE_RATE (44100) +#define FRAMES_PER_BUFFER (512) +#ifndef M_PI +#define M_PI (3.14159265) +#endif +#define TABLE_SIZE (200) +typedef struct +{ + float sine[TABLE_SIZE]; + int left_phase; + int right_phase; + int toggle; + int countDown; +} +paTestData; +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patestCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + float *out = (float*)outputBuffer; + unsigned long i; + int finished = 0; + (void) outTime; /* Prevent unused variable warnings. */ + (void) inputBuffer; + + for( i=0; itoggle ) + { + *out++ = data->sine[data->left_phase]; /* left */ + *out++ = 0; /* right */ + } + else + { + *out++ = 0; /* left */ + *out++ = data->sine[data->right_phase]; /* right */ + } + + data->left_phase += 1; + if( data->left_phase >= TABLE_SIZE ) data->left_phase -= TABLE_SIZE; + data->right_phase += 3; /* higher pitch so we can distinguish left and right. */ + if( data->right_phase >= TABLE_SIZE ) data->right_phase -= TABLE_SIZE; + } + + if( data->countDown < 0 ) + { + data->countDown = SAMPLE_RATE; + data->toggle = !data->toggle; + } + data->countDown -= framesPerBuffer; + + return finished; +} + +/*******************************************************************/ +int main(void); +int main(void) +{ + PortAudioStream *stream; + PaError err; + paTestData data; + int i; + int timeout; + + printf("Play different tone sine waves that alternate between left and right channel.\n"); + printf("The low tone should be on the left channel.\n"); + + /* initialise sinusoidal wavetable */ + for( i=0; i 0 ) + { + Pa_Sleep( 300 ); + timeout -= 1; + } + + err = Pa_StopStream( stream ); + if( err != paNoError ) goto error; + err = Pa_CloseStream( stream ); + if( err != paNoError ) goto error; + Pa_Terminate(); + printf("Test finished.\n"); + return err; +error: + Pa_Terminate(); + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + return err; +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_longsine.c b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_longsine.c new file mode 100755 index 00000000000..b21f7daf986 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_longsine.c @@ -0,0 +1,137 @@ +/* + * $Id: patest_longsine.c,v 1.1.2.1 2005-08-16 20:04:11 alex%croczilla.com Exp $ + * patest_longsine.c + * Play a sine wave using the Portable Audio api until ENTER hit. + * + * Author: Phil Burk http://www.softsynth.com + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.portaudio.com + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +#include +#include +#include "portaudio.h" + +#define SAMPLE_RATE (44100) + +#ifndef M_PI +#define M_PI (3.14159265) +#endif + +#define TABLE_SIZE (200) +typedef struct +{ + float sine[TABLE_SIZE]; + int left_phase; + int right_phase; +} +paTestData; + +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patestCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + float *out = (float*)outputBuffer; + unsigned int i; + (void) outTime; /* Prevent unused variable warnings. */ + (void) inputBuffer; + for( i=0; isine[data->left_phase]; /* left */ + *out++ = data->sine[data->right_phase]; /* right */ + data->left_phase += 1; + if( data->left_phase >= TABLE_SIZE ) data->left_phase -= TABLE_SIZE; + data->right_phase += 3; /* higher pitch so we can distinguish left and right. */ + if( data->right_phase >= TABLE_SIZE ) data->right_phase -= TABLE_SIZE; + } + return 0; +} + +/*******************************************************************/ +int main(void); +int main(void) +{ + PortAudioStream *stream; + PaError err; + paTestData data; + int i; + printf("PortAudio Test: output sine wave.\n"); + + /* initialise sinusoidal wavetable */ + for( i=0; i +#include +#include +#include "portaudio.h" +#define NUM_SECONDS (1) +#define SAMPLE_RATE (44100) +#ifndef M_PI +#define M_PI (3.14159265) +#endif +#define TABLE_SIZE (200) +typedef struct +{ + short sine[TABLE_SIZE]; + int left_phase; + int right_phase; + unsigned int sampsToGo; +} +paTestData; +PaError TestOnce( void ); +static int patest1Callback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ); +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patest1Callback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + short *out = (short*)outputBuffer; + unsigned int i; + int finished = 0; + (void) inputBuffer; /* Prevent "unused variable" warnings. */ + (void) outTime; + + if( data->sampsToGo < framesPerBuffer ) + { + /* final buffer... */ + + for( i=0; isampsToGo; i++ ) + { + *out++ = data->sine[data->left_phase]; /* left */ + *out++ = data->sine[data->right_phase]; /* right */ + data->left_phase += 1; + if( data->left_phase >= TABLE_SIZE ) data->left_phase -= TABLE_SIZE; + data->right_phase += 3; /* higher pitch so we can distinguish left and right. */ + if( data->right_phase >= TABLE_SIZE ) data->right_phase -= TABLE_SIZE; + } + /* zero remainder of final buffer */ + for( ; isine[data->left_phase]; /* left */ + *out++ = data->sine[data->right_phase]; /* right */ + data->left_phase += 1; + if( data->left_phase >= TABLE_SIZE ) data->left_phase -= TABLE_SIZE; + data->right_phase += 3; /* higher pitch so we can distinguish left and right. */ + if( data->right_phase >= TABLE_SIZE ) data->right_phase -= TABLE_SIZE; + } + data->sampsToGo -= framesPerBuffer; + } + return finished; +} +/*******************************************************************/ +#ifdef MACINTOSH +int main(void); +int main(void) +{ + int i; + PaError err; + int numLoops = 10; + printf("Loop %d times.\n", numLoops ); + for( i=0; i 1 ) + { + numLoops = atoi(argv[1]); + } + for( i=0; i + * Phil Burk + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.audiomulch.com/portaudio/ + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +#include +#include +#include "portaudio.h" + +#define MAX_SINES (500) +#define MAX_USAGE (0.8) +#define SAMPLE_RATE (44100) +#define FREQ_TO_PHASE_INC(freq) (freq/(float)SAMPLE_RATE) + +#define MIN_PHASE_INC FREQ_TO_PHASE_INC(200.0f) +#define MAX_PHASE_INC (MIN_PHASE_INC * (1 << 5)) + +#define FRAMES_PER_BUFFER (512) +#ifndef M_PI +#define M_PI (3.14159265) +#endif +#define TWOPI (M_PI * 2.0) + +#define TABLE_SIZE (512) + +typedef struct paTestData +{ + int numSines; + float sine[TABLE_SIZE + 1]; /* add one for guard point for interpolation */ + float phases[MAX_SINES]; +} +paTestData; + +/* Convert phase between and 1.0 to sine value + * using linear interpolation. + */ +float LookupSine( paTestData *data, float phase ); +float LookupSine( paTestData *data, float phase ) +{ + float fIndex = phase*TABLE_SIZE; + int index = (int) fIndex; + float fract = fIndex - index; + float lo = data->sine[index]; + float hi = data->sine[index+1]; + float val = lo + fract*(hi-lo); + return val; +} + +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patestCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + float *out = (float*)outputBuffer; + float outSample; + float scaler; + int numForScale; + unsigned long i; + int j; + int finished = 0; + (void) outTime; /* Prevent unused variable warnings. */ + (void) inputBuffer; + +/* Detemine amplitude scaling factor */ + numForScale = data->numSines; + if( numForScale < 8 ) numForScale = 8; /* prevent pops at beginning */ + scaler = 1.0f / numForScale; + + for( i=0; inumSines; j++ ) + { + /* Advance phase of next oscillator. */ + phase = data->phases[j]; + phase += phaseInc; + if( phase >= 1.0 ) phase -= 1.0; + + output += LookupSine(data, phase); + data->phases[j] = phase; + + phaseInc *= 1.02f; + if( phaseInc > MAX_PHASE_INC ) phaseInc = MIN_PHASE_INC; + } + + outSample = (float) (output * scaler); + *out++ = outSample; /* Left */ + *out++ = outSample; /* Right */ + } + return finished; +} + +/*******************************************************************/ +int main(void); +int main(void) +{ + int i; + PortAudioStream *stream; + PaError err; + paTestData data = {0}; + double load; + printf("PortAudio Test: output sine wave. SR = %d, BufSize = %d\n", SAMPLE_RATE, FRAMES_PER_BUFFER); + + /* initialise sinusoidal wavetable */ + for( i=0; i + * Phil Burk + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.audiomulch.com/portaudio/ + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +#include +#include +#include "portaudio.h" + +#define NUM_SECONDS (10) +#define SAMPLE_RATE (44100) +#define AMPLITUDE (0.8) +#define FRAMES_PER_BUFFER (64) +#define OUTPUT_DEVICE Pa_GetDefaultOutputDeviceID() + +#ifndef M_PI +#define M_PI (3.14159265) +#endif + +#define TABLE_SIZE (200) +typedef struct +{ + float sine[TABLE_SIZE]; + int phase; +} +paTestData; + +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patestCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + float *out = (float*)outputBuffer; + unsigned long i; + int finished = 0; + (void) outTime; /* Prevent unused variable warnings. */ + (void) inputBuffer; + for( i=0; isine[data->phase]; /* left */ + data->phase += 1; + if( data->phase >= TABLE_SIZE ) data->phase -= TABLE_SIZE; + } + return finished; +} + +/*******************************************************************/ +int main(void); +int main(void) +{ + PortAudioStream *stream; + PaError err; + paTestData data; + int i; + printf("PortAudio Test: output MONO sine wave. SR = %d, BufSize = %d\n", SAMPLE_RATE, FRAMES_PER_BUFFER); + /* initialise sinusoidal wavetable */ + for( i=0; i +#include +#include "portaudio.h" + +#define OUTPUT_DEVICE (Pa_GetDefaultOutputDeviceID()) +#define SAMPLE_RATE (44100) +#define FRAMES_PER_BUFFER (256) +#define FREQ_INCR (300.0 / SAMPLE_RATE) +#define MAX_CHANNELS (64) + +#ifndef M_PI +#define M_PI (3.14159265) +#endif + +typedef struct +{ + int numChannels; + double phases[MAX_CHANNELS]; +} +paTestData; + +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patestCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + float *out = (float*)outputBuffer; + int frameIndex, channelIndex; + (void) outTime; /* Prevent unused variable warnings. */ + (void) inputBuffer; + + for( frameIndex=0; frameIndex<(int)framesPerBuffer; frameIndex++ ) + { + for( channelIndex=0; channelIndexnumChannels; channelIndex++ ) + { + /* Output sine wave on every channel. */ + *out++ = (float) (0.7 * sin(data->phases[channelIndex])); + + /* Play each channel at a higher frequency. */ + data->phases[channelIndex] += FREQ_INCR * (4 + channelIndex); + if( data->phases[channelIndex] >= (2.0 * M_PI) ) data->phases[channelIndex] -= (2.0 * M_PI); + } + } + + return 0; +} + +/*******************************************************************/ +int main(void); +int main(void) +{ + PortAudioStream *stream; + PaError err; + const PaDeviceInfo *pdi; + paTestData data = {0}; + printf("PortAudio Test: output sine wave on each channel.\n" ); + + err = Pa_Initialize(); + if( err != paNoError ) goto error; + + pdi = Pa_GetDeviceInfo( OUTPUT_DEVICE ); + data.numChannels = pdi->maxOutputChannels; + if( data.numChannels > MAX_CHANNELS ) data.numChannels = MAX_CHANNELS; + printf("Number of Channels = %d\n", data.numChannels ); + + err = Pa_OpenStream( + &stream, + paNoDevice, /* default input device */ + 0, /* no input */ + paFloat32, /* 32 bit floating point input */ + NULL, + OUTPUT_DEVICE, + data.numChannels, + paFloat32, /* 32 bit floating point output */ + NULL, + SAMPLE_RATE, + FRAMES_PER_BUFFER, /* frames per buffer */ + 0, /* number of buffers, if zero then use default minimum */ + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + patestCallback, + &data ); + if( err != paNoError ) goto error; + + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + + printf("Hit ENTER to stop sound.\n"); + fflush(stdout); + getchar(); + + err = Pa_StopStream( stream ); + if( err != paNoError ) goto error; + + Pa_CloseStream( stream ); + Pa_Terminate(); + printf("Test finished.\n"); + return err; +error: + Pa_Terminate(); + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + return err; +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_pink.c b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_pink.c new file mode 100755 index 00000000000..0025e6221c5 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_pink.c @@ -0,0 +1,245 @@ +/* + * $Id: patest_pink.c,v 1.1.2.1 2005-08-16 20:04:11 alex%croczilla.com Exp $ + patest_pink.c + Generate Pink Noise using Gardner method. + Optimization suggested by James McCartney uses a tree + to select which random value to replace. + x x x x x x x x x x x x x x x x + x x x x x x x x + x x x x + x x + x + Tree is generated by counting trailing zeros in an increasing index. + When the index is zero, no random number is selected. + * + * Author: Phil Burk http://www.softsynth.com + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.portaudio.com + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +#include +#include +#include "portaudio.h" +#define PINK_MAX_RANDOM_ROWS (30) +#define PINK_RANDOM_BITS (24) +#define PINK_RANDOM_SHIFT ((sizeof(long)*8)-PINK_RANDOM_BITS) +typedef struct +{ + long pink_Rows[PINK_MAX_RANDOM_ROWS]; + long pink_RunningSum; /* Used to optimize summing of generators. */ + int pink_Index; /* Incremented each sample. */ + int pink_IndexMask; /* Index wrapped by ANDing with this mask. */ + float pink_Scalar; /* Used to scale within range of -1.0 to +1.0 */ +} +PinkNoise; +/* Prototypes */ +static unsigned long GenerateRandomNumber( void ); +void InitializePinkNoise( PinkNoise *pink, int numRows ); +float GeneratePinkNoise( PinkNoise *pink ); +/************************************************************/ +/* Calculate pseudo-random 32 bit number based on linear congruential method. */ +static unsigned long GenerateRandomNumber( void ) +{ + /* Change this seed for different random sequences. */ + static unsigned long randSeed = 22222; + randSeed = (randSeed * 196314165) + 907633515; + return randSeed; +} +/************************************************************/ +/* Setup PinkNoise structure for N rows of generators. */ +void InitializePinkNoise( PinkNoise *pink, int numRows ) +{ + int i; + long pmax; + pink->pink_Index = 0; + pink->pink_IndexMask = (1<pink_Scalar = 1.0f / pmax; + /* Initialize rows. */ + for( i=0; ipink_Rows[i] = 0; + pink->pink_RunningSum = 0; +} +#define PINK_MEASURE +#ifdef PINK_MEASURE +float pinkMax = -999.0; +float pinkMin = 999.0; +#endif +/* Generate Pink noise values between -1.0 and +1.0 */ +float GeneratePinkNoise( PinkNoise *pink ) +{ + long newRandom; + long sum; + float output; + /* Increment and mask index. */ + pink->pink_Index = (pink->pink_Index + 1) & pink->pink_IndexMask; + /* If index is zero, don't update any random values. */ + if( pink->pink_Index != 0 ) + { + /* Determine how many trailing zeros in PinkIndex. */ + /* This algorithm will hang if n==0 so test first. */ + int numZeros = 0; + int n = pink->pink_Index; + while( (n & 1) == 0 ) + { + n = n >> 1; + numZeros++; + } + /* Replace the indexed ROWS random value. + * Subtract and add back to RunningSum instead of adding all the random + * values together. Only one changes each time. + */ + pink->pink_RunningSum -= pink->pink_Rows[numZeros]; + newRandom = ((long)GenerateRandomNumber()) >> PINK_RANDOM_SHIFT; + pink->pink_RunningSum += newRandom; + pink->pink_Rows[numZeros] = newRandom; + } + + /* Add extra white noise value. */ + newRandom = ((long)GenerateRandomNumber()) >> PINK_RANDOM_SHIFT; + sum = pink->pink_RunningSum + newRandom; + /* Scale to range of -1.0 to 0.9999. */ + output = pink->pink_Scalar * sum; +#ifdef PINK_MEASURE + /* Check Min/Max */ + if( output > pinkMax ) pinkMax = output; + else if( output < pinkMin ) pinkMin = output; +#endif + return output; +} +/*******************************************************************/ +#define PINK_TEST +#ifdef PINK_TEST +/* Context for callback routine. */ +typedef struct +{ + PinkNoise leftPink; + PinkNoise rightPink; + unsigned int sampsToGo; +} +paTestData; +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patestCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + int finished; + int i; + int numFrames; + paTestData *data = (paTestData*)userData; + float *out = (float*)outputBuffer; + (void) inputBuffer; /* Prevent "unused variable" warnings. */ + (void) outTime; + + /* Are we almost at end. */ + if( data->sampsToGo < framesPerBuffer ) + { + numFrames = data->sampsToGo; + finished = 1; + } + else + { + numFrames = framesPerBuffer; + finished = 0; + } + for( i=0; ileftPink ); + *out++ = GeneratePinkNoise( &data->rightPink ); + } + data->sampsToGo -= numFrames; + return finished; +} +/*******************************************************************/ +int main(void); +int main(void) +{ + PortAudioStream *stream; + PaError err; + paTestData data; + int totalSamps; + /* Initialize two pink noise signals with different numbers of rows. */ + InitializePinkNoise( &data.leftPink, 12 ); + InitializePinkNoise( &data.rightPink, 16 ); + /* Look at a few values. */ + { + int i; + float pink; + for( i=0; i<20; i++ ) + { + pink = GeneratePinkNoise( &data.leftPink ); + printf("Pink = %f\n", pink ); + } + } + data.sampsToGo = totalSamps = 8*44100; /* Play for a few seconds. */ + err = Pa_Initialize(); + if( err != paNoError ) goto error; + /* Open a stereo PortAudio stream so we can hear the result. */ + err = Pa_OpenStream( + &stream, + paNoDevice, + 0, /* no input */ + paFloat32, /* 32 bit floating point input */ + NULL, + Pa_GetDefaultOutputDeviceID(), /* default output device */ + 2, /* stereo output */ + paFloat32, /* 32 bit floating point output */ + NULL, + 44100., + 2048, /* 46 msec buffers */ + 0, /* number of buffers, if zero then use default minimum */ + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + patestCallback, + &data ); + if( err != paNoError ) goto error; + + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + printf("Waiting for sound to finish.\n"); + while( Pa_StreamActive( stream ) ) + { + Pa_Sleep(100); /* SPIN! */ + } + err = Pa_CloseStream( stream ); + if( err != paNoError ) goto error; +#ifdef PINK_MEASURE + printf("Pink min = %f, max = %f\n", pinkMin, pinkMax ); +#endif + Pa_Terminate(); + return 0; +error: + Pa_Terminate(); + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + return 0; +} +#endif /* PINK_TEST */ diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_record.c b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_record.c new file mode 100755 index 00000000000..2ce24023a40 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_record.c @@ -0,0 +1,325 @@ +/* + * $Id: patest_record.c,v 1.1.2.1 2005-08-16 20:04:11 alex%croczilla.com Exp $ + * patest_record.c + * Record input into an array. + * Optionally save array to a file. + * Playback recorded data. + * + * Author: Phil Burk http://www.softsynth.com + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.portaudio.com + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +#include +#include +#include "portaudio.h" + +/* #define SAMPLE_RATE (17932) // Test failure to open with this value. */ +#define SAMPLE_RATE (44100) +#define NUM_SECONDS (5) +#define NUM_CHANNELS (2) +/* #define DITHER_FLAG (paDitherOff) */ +#define DITHER_FLAG (0) /**/ +#define FRAMES_PER_BUFFER (1024) + +/* Select sample format. */ +#if 1 +#define PA_SAMPLE_TYPE paFloat32 +typedef float SAMPLE; +#define SAMPLE_SILENCE (0.0f) +#elif 0 +#define PA_SAMPLE_TYPE paInt16 +typedef short SAMPLE; +#define SAMPLE_SILENCE (0) +#elif 0 +#define PA_SAMPLE_TYPE paInt8 +typedef char SAMPLE; +#define SAMPLE_SILENCE (0) +#else +#define PA_SAMPLE_TYPE paUInt8 +typedef unsigned char SAMPLE; +#define SAMPLE_SILENCE (128) + +#endif + +typedef struct +{ + int frameIndex; /* Index into sample array. */ + int maxFrameIndex; + SAMPLE *recordedSamples; +} +paTestData; +/* This routine will be called by the PortAudio engine when audio is needed. +** It may be called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int recordCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + SAMPLE *rptr = (SAMPLE*)inputBuffer; + SAMPLE *wptr = &data->recordedSamples[data->frameIndex * NUM_CHANNELS]; + long framesToRecord; + long i; + int finished; + unsigned long framesLeft = data->maxFrameIndex - data->frameIndex; + int samplesToRecord; + + (void) outputBuffer; /* Prevent unused variable warnings. */ + (void) outTime; + + if( framesLeft < framesPerBuffer ) + { + framesToRecord = framesLeft; + finished = 1; + } + else + { + framesToRecord = framesPerBuffer; + finished = 0; + } + + samplesToRecord = framesToRecord * NUM_CHANNELS; + + if( inputBuffer == NULL ) + { + for( i=0; iframeIndex += framesToRecord; + return finished; +} + +/* This routine will be called by the PortAudio engine when audio is needed. +** It may be called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int playCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + SAMPLE *rptr = &data->recordedSamples[data->frameIndex * NUM_CHANNELS]; + SAMPLE *wptr = (SAMPLE*)outputBuffer; + unsigned int i; + int finished; + unsigned int framesLeft = data->maxFrameIndex - data->frameIndex; + int framesToPlay, samplesToPlay, samplesPerBuffer; + (void) inputBuffer; /* Prevent unused variable warnings. */ + (void) outTime; + + if( framesLeft < framesPerBuffer ) + { + framesToPlay = framesLeft; + finished = 1; + } + else + { + framesToPlay = framesPerBuffer; + finished = 0; + } + + samplesToPlay = framesToPlay * NUM_CHANNELS; + samplesPerBuffer = framesPerBuffer * NUM_CHANNELS; + + for( i=0; iframeIndex += framesToPlay; + + return finished; +} + +/*******************************************************************/ +int main(void); +int main(void) +{ + PortAudioStream *stream; + PaError err; + paTestData data; + int i; + int totalFrames; + int numSamples; + int numBytes; + SAMPLE max, average, val; + printf("patest_record.c\n"); fflush(stdout); + + data.maxFrameIndex = totalFrames = NUM_SECONDS * SAMPLE_RATE; /* Record for a few seconds. */ + data.frameIndex = 0; + numSamples = totalFrames * NUM_CHANNELS; + + numBytes = numSamples * sizeof(SAMPLE); + data.recordedSamples = (SAMPLE *) malloc( numBytes ); + if( data.recordedSamples == NULL ) + { + printf("Could not allocate record array.\n"); + exit(1); + } + for( i=0; i max ) + { + max = val; + } + average += val; + } + + average = average / numSamples; + + if( PA_SAMPLE_TYPE == paFloat32 ) /* This should be done at compile-time with "#if" ?? */ + { /* MIPS-compiler warns at the int-version below. */ + printf("sample max amplitude = %f\n", max ); + printf("sample average = %f\n", average ); + } + else + { + printf("sample max amplitude = %d\n", max ); /* <-- This IS compiled anyhow. */ + printf("sample average = %d\n", average ); + } + + /* Write recorded data to a file. */ +#if 0 + { + FILE *fid; + fid = fopen("recorded.raw", "wb"); + if( fid == NULL ) + { + printf("Could not open file."); + } + else + { + fwrite( data.recordedSamples, NUM_CHANNELS * sizeof(SAMPLE), totalFrames, fid ); + fclose( fid ); + printf("Wrote data to 'recorded.raw'\n"); + } + } +#endif + + /* Playback recorded data. -------------------------------------------- */ + data.frameIndex = 0; + printf("Begin playback.\n"); fflush(stdout); + err = Pa_OpenStream( + &stream, + paNoDevice, + 0, /* NO input */ + PA_SAMPLE_TYPE, + NULL, + Pa_GetDefaultOutputDeviceID(), + NUM_CHANNELS, + PA_SAMPLE_TYPE, + NULL, + SAMPLE_RATE, + FRAMES_PER_BUFFER, /* frames per buffer */ + 0, /* number of buffers, if zero then use default minimum */ + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + playCallback, + &data ); + if( err != paNoError ) goto error; + + if( stream ) + { + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + printf("Waiting for playback to finish.\n"); fflush(stdout); + + while( Pa_StreamActive( stream ) ) Pa_Sleep(100); + + err = Pa_CloseStream( stream ); + if( err != paNoError ) goto error; + printf("Done.\n"); fflush(stdout); + } + free( data.recordedSamples ); + + Pa_Terminate(); + return 0; + +error: + Pa_Terminate(); + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + return -1; +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_ringmix.c b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_ringmix.c new file mode 100755 index 00000000000..b1f5086e60a --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_ringmix.c @@ -0,0 +1,41 @@ +/* $Id: patest_ringmix.c,v 1.1.2.1 2005-08-16 20:04:11 alex%croczilla.com Exp $ */ + +#include "stdio.h" +#include "portaudio.h" +/* This will be called asynchronously by the PortAudio engine. */ +static int myCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, PaTimestamp outTime, void *userData ) +{ + float *out = (float *) outputBuffer; + float *in = (float *) inputBuffer; + float leftInput, rightInput; + unsigned int i; + if( inputBuffer == NULL ) return 0; + /* Read input buffer, process data, and fill output buffer. */ + for( i=0; i +#include +#include "portaudio.h" +#define NUM_SECONDS (4) +#define SAMPLE_RATE (44100) +typedef struct +{ + float left_phase; + float right_phase; +} +paTestData; +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patestCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + /* Cast data passed through stream to our structure. */ + paTestData *data = (paTestData*)userData; + float *out = (float*)outputBuffer; + unsigned int i; + (void) outTime; /* Prevent unused variable warnings. */ + (void) inputBuffer; + + for( i=0; ileft_phase; /* left */ + *out++ = data->right_phase; /* right */ + /* Generate simple sawtooth phaser that ranges between -1.0 and 1.0. */ + data->left_phase += 0.01f; + /* When signal reaches top, drop back down. */ + if( data->left_phase >= 1.0f ) data->left_phase -= 2.0f; + /* higher pitch so we can distinguish left and right. */ + data->right_phase += 0.03f; + if( data->right_phase >= 1.0f ) data->right_phase -= 2.0f; + } + return 0; +} +/*******************************************************************/ +static paTestData data; +int main(void); +int main(void) +{ + PortAudioStream *stream; + PaError err; + printf("PortAudio Test: output sawtooth wave.\n"); + /* Initialize our data for use by callback. */ + data.left_phase = data.right_phase = 0.0; + /* Initialize library before making any other calls. */ + err = Pa_Initialize(); + if( err != paNoError ) goto error; + /* Open an audio I/O stream. */ + err = Pa_OpenDefaultStream( + &stream, + 0, /* no input channels */ + 2, /* stereo output */ + paFloat32, /* 32 bit floating point output */ + SAMPLE_RATE, + 256, /* frames per buffer */ + 0, /* number of buffers, if zero then use default minimum */ + patestCallback, + &data ); + if( err != paNoError ) goto error; + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + /* Sleep for several seconds. */ + Pa_Sleep(NUM_SECONDS*1000); + err = Pa_StopStream( stream ); + if( err != paNoError ) goto error; + err = Pa_CloseStream( stream ); + if( err != paNoError ) goto error; + Pa_Terminate(); + printf("Test finished.\n"); + return err; +error: + Pa_Terminate(); + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + return err; +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_sine.c b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_sine.c new file mode 100755 index 00000000000..6b4134ba720 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_sine.c @@ -0,0 +1,141 @@ +/* + * $Id: patest_sine.c,v 1.1.2.1 2005-08-16 20:04:11 alex%croczilla.com Exp $ + * patest_sine.c + * Play a sine wave using the Portable Audio api for several seconds. + * + * Authors: + * Ross Bencina + * Phil Burk + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.audiomulch.com/portaudio/ + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +#include +#include +#include "portaudio.h" + +#define NUM_SECONDS (10) +#define SAMPLE_RATE (44100) +#define AMPLITUDE (0.9) +#define FRAMES_PER_BUFFER (64) +#define OUTPUT_DEVICE Pa_GetDefaultOutputDeviceID() +//#define OUTPUT_DEVICE (2) + +#ifndef M_PI +#define M_PI (3.14159265) +#endif + +#define TABLE_SIZE (200) +typedef struct +{ + float sine[TABLE_SIZE]; + int left_phase; + int right_phase; +} +paTestData; + +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patestCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + float *out = (float*)outputBuffer; + unsigned long i; + int finished = 0; + (void) outTime; /* Prevent unused variable warnings. */ + (void) inputBuffer; + for( i=0; isine[data->left_phase]; /* left */ + *out++ = data->sine[data->right_phase]; /* right */ + data->left_phase += 1; + if( data->left_phase >= TABLE_SIZE ) data->left_phase -= TABLE_SIZE; + data->right_phase += 3; /* higher pitch so we can distinguish left and right. */ + if( data->right_phase >= TABLE_SIZE ) data->right_phase -= TABLE_SIZE; + } + return finished; +} + +/*******************************************************************/ +int main(void); +int main(void) +{ + PortAudioStream *stream; + PaError err; + paTestData data; + int i; + printf("PortAudio Test: output sine wave. SR = %d, BufSize = %d, devID = %d\n", + SAMPLE_RATE, FRAMES_PER_BUFFER, OUTPUT_DEVICE); + /* initialise sinusoidal wavetable */ + for( i=0; i + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.audiomulch.com/portaudio/ + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +#include +#include +#include "portaudio.h" +#define NUM_SECONDS (8) +#define SAMPLE_RATE (44100) +#define TEST_UNSIGNED (1) +#if TEST_UNSIGNED +#define TEST_FORMAT paUInt8 +#else +#define TEST_FORMAT paInt8 +#endif +#ifndef M_PI +#define M_PI (3.14159265) +#endif +#define TABLE_SIZE (200) +typedef struct +{ +#if TEST_UNSIGNED + unsigned char sine[TABLE_SIZE]; +#else + char sine[TABLE_SIZE]; +#endif + int left_phase; + int right_phase; + unsigned int framesToGo; +} +paTestData; +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patestCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + char *out = (char*)outputBuffer; + int i; + int framesToCalc; + int finished = 0; + (void) outTime; /* Prevent unused variable warnings. */ + (void) inputBuffer; + + if( data->framesToGo < framesPerBuffer ) + { + framesToCalc = data->framesToGo; + data->framesToGo = 0; + finished = 1; + } + else + { + framesToCalc = framesPerBuffer; + data->framesToGo -= framesPerBuffer; + } + + for( i=0; isine[data->left_phase]; /* left */ + *out++ = data->sine[data->right_phase]; /* right */ + data->left_phase += 1; + if( data->left_phase >= TABLE_SIZE ) data->left_phase -= TABLE_SIZE; + data->right_phase += 3; /* higher pitch so we can distinguish left and right. */ + if( data->right_phase >= TABLE_SIZE ) data->right_phase -= TABLE_SIZE; + } + /* zero remainder of final buffer */ + for( ; i<(int)framesPerBuffer; i++ ) + { +#if TEST_UNSIGNED + *out++ = (unsigned char) 0x80; /* left */ + *out++ = (unsigned char) 0x80; /* right */ +#else + *out++ = 0; /* left */ + *out++ = 0; /* right */ +#endif + + } + return finished; +} +/*******************************************************************/ +int main(void); +int main(void) +{ + PortAudioStream *stream; + PaError err; + paTestData data; + int i; + int totalSamps; +#if TEST_UNSIGNED + printf("PortAudio Test: output UNsigned 8 bit sine wave.\n"); +#else + printf("PortAudio Test: output signed 8 bit sine wave.\n"); +#endif + /* initialise sinusoidal wavetable */ + for( i=0; i +#include +#include "portaudio.h" + +#define NUM_SECONDS (5) +#define SAMPLE_RATE (44100) +#define FRAMES_PER_BUFFER (512) +#define LEFT_FREQ ((2 * SAMPLE_RATE)/FRAMES_PER_BUFFER) /* So we hit 1.0 */ +#define RIGHT_FREQ (500.0) +#define AMPLITUDE (0.9) + +/* Select ONE format for testing. */ +#define TEST_UINT8 (0) +#define TEST_INT8 (0) +#define TEST_INT16 (0) +#define TEST_INT32 (1) +#define TEST_FLOAT32 (0) + +#if TEST_UINT8 +#define TEST_FORMAT paUInt8 +typedef unsigned char SAMPLE_t; +#define SAMPLE_ZERO (0x80) +#define DOUBLE_TO_SAMPLE(x) (SAMPLE_ZERO + (SAMPLE_t)(127.0 * (x))) +#define FORMAT_NAME "Unsigned 8 Bit" + +#elif TEST_INT8 +#define TEST_FORMAT paInt8 +typedef char SAMPLE_t; +#define SAMPLE_ZERO (0) +#define DOUBLE_TO_SAMPLE(x) (SAMPLE_ZERO + (SAMPLE_t)(127.0 * (x))) +#define FORMAT_NAME "Signed 8 Bit" + +#elif TEST_INT16 +#define TEST_FORMAT paInt16 +typedef short SAMPLE_t; +#define SAMPLE_ZERO (0) +#define DOUBLE_TO_SAMPLE(x) (SAMPLE_ZERO + (SAMPLE_t)(32767 * (x))) +#define FORMAT_NAME "Signed 16 Bit" + +#elif TEST_INT32 +#define TEST_FORMAT paInt32 +typedef long SAMPLE_t; +#define SAMPLE_ZERO (0) +#define DOUBLE_TO_SAMPLE(x) (SAMPLE_ZERO + (SAMPLE_t)(0x7FFFFFFF * (x))) +#define FORMAT_NAME "Signed 32 Bit" + +#elif TEST_FLOAT32 +#define TEST_FORMAT paFloat32 +typedef float SAMPLE_t; +#define SAMPLE_ZERO (0.0) +#define DOUBLE_TO_SAMPLE(x) ((SAMPLE_t)(x)) +#define FORMAT_NAME "Float 32 Bit" +#endif + +#ifndef M_PI +#define M_PI (3.14159265) +#endif + + +typedef struct +{ + double left_phase; + double right_phase; + unsigned int framesToGo; +} +paTestData; +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patestCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + SAMPLE_t *out = (SAMPLE_t *)outputBuffer; + int i; + int framesToCalc; + int finished = 0; + (void) outTime; /* Prevent unused variable warnings. */ + (void) inputBuffer; + + if( data->framesToGo < framesPerBuffer ) + { + framesToCalc = data->framesToGo; + data->framesToGo = 0; + finished = 1; + } + else + { + framesToCalc = framesPerBuffer; + data->framesToGo -= framesPerBuffer; + } + + for( i=0; ileft_phase += (LEFT_FREQ / SAMPLE_RATE); + if( data->left_phase > 1.0) data->left_phase -= 1.0; + *out++ = DOUBLE_TO_SAMPLE( AMPLITUDE * sin( (data->left_phase * M_PI * 2. ))); + + data->right_phase += (RIGHT_FREQ / SAMPLE_RATE); + if( data->right_phase > 1.0) data->right_phase -= 1.0; + *out++ = DOUBLE_TO_SAMPLE( AMPLITUDE * sin( (data->right_phase * M_PI * 2. ))); + } + /* zero remainder of final buffer */ + for( ; i<(int)framesPerBuffer; i++ ) + { + *out++ = SAMPLE_ZERO; /* left */ + *out++ = SAMPLE_ZERO; /* right */ + } + return finished; +} +/*******************************************************************/ +int main(void); +int main(void) +{ + PortAudioStream *stream; + PaError err; + paTestData data; + int totalSamps; + + printf("PortAudio Test: output " FORMAT_NAME "\n"); + + + data.left_phase = data.right_phase = 0.0; + data.framesToGo = totalSamps = NUM_SECONDS * SAMPLE_RATE; /* Play for a few seconds. */ + err = Pa_Initialize(); + if( err != paNoError ) goto error; + + err = Pa_OpenStream( + &stream, + paNoDevice,/* default input device */ + 0, /* no input */ + TEST_FORMAT, + NULL, + Pa_GetDefaultOutputDeviceID(), /* default output device */ + 2, /* stereo output */ + TEST_FORMAT, + NULL, + SAMPLE_RATE, + FRAMES_PER_BUFFER, + 0, /* number of buffers, if zero then use default minimum */ + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + patestCallback, + &data ); + if( err != paNoError ) goto error; + + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + + printf("Waiting %d seconds for sound to finish.\n", NUM_SECONDS ); fflush(stdout); + while( Pa_StreamActive( stream ) ) Pa_Sleep(10); + + err = Pa_CloseStream( stream ); + if( err != paNoError ) goto error; + Pa_Terminate(); + + printf("PortAudio Test Finished: " FORMAT_NAME "\n"); + + return err; +error: + Pa_Terminate(); + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + return err; +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_sine_time.c b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_sine_time.c new file mode 100755 index 00000000000..e76c5753437 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_sine_time.c @@ -0,0 +1,205 @@ +/* + * $Id: patest_sine_time.c,v 1.1.2.1 2005-08-16 20:04:11 alex%croczilla.com Exp $ + * patest_sine_time.c + * Play a sine wave using the Portable Audio api for several seconds. + * Pausing in the middle. + * use the Pa_StreamTime() and Pa_StreamActive() calls. + * + * Authors: + * Ross Bencina + * Phil Burk + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.audiomulch.com/portaudio/ + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +#include +#include +#include "portaudio.h" +#define NUM_SECONDS (8) +#define SAMPLE_RATE (44100) +#define FRAMES_PER_BUFFER (64) +#define NUM_BUFFERS (0) +#ifndef M_PI +#define M_PI (3.14159265) +#endif +#define TABLE_SIZE (200) +typedef struct +{ + float sine[TABLE_SIZE]; + int left_phase; + int right_phase; + int framesToGo; + volatile PaTimestamp outTime; +} +paTestData; +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patestCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + float *out = (float*)outputBuffer; + int i; + int framesToCalc; + int finished = 0; + (void) outTime; /* Prevent unused variable warnings. */ + (void) inputBuffer; + + data->outTime = outTime; + + if( data->framesToGo < framesPerBuffer ) + { + framesToCalc = data->framesToGo; + data->framesToGo = 0; + finished = 1; + } + else + { + framesToCalc = framesPerBuffer; + data->framesToGo -= framesPerBuffer; + } + + for( i=0; isine[data->left_phase]; /* left */ + *out++ = data->sine[data->right_phase]; /* right */ + data->left_phase += 1; + if( data->left_phase >= TABLE_SIZE ) data->left_phase -= TABLE_SIZE; + data->right_phase += 3; /* higher pitch so we can distinguish left and right. */ + if( data->right_phase >= TABLE_SIZE ) data->right_phase -= TABLE_SIZE; + } + /* zero remainder of final buffer */ + for( ; i<(int)framesPerBuffer; i++ ) + { + *out++ = 0; /* left */ + *out++ = 0; /* right */ + } + return finished; +} +/*******************************************************************/ +static void ReportStreamTime( PortAudioStream *stream, paTestData *data ); +static void ReportStreamTime( PortAudioStream *stream, paTestData *data ) +{ + PaTimestamp streamTime, latency, outTime; + + streamTime = Pa_StreamTime( stream ); + outTime = data->outTime; + if( outTime < 0.0 ) + { + printf("Stream time = %8.1f\n", streamTime ); + } + else + { + latency = outTime - streamTime; + printf("Stream time = %8.1f, outTime = %8.1f, latency = %8.1f\n", + streamTime, outTime, latency ); + } + fflush(stdout); +} + +/*******************************************************************/ +int main(void); +int main(void) +{ + PortAudioStream *stream; + PaError err; + paTestData DATA; + int i; + int totalSamps; + printf("PortAudio Test: output sine wave. SR = %d, BufSize = %d\n", SAMPLE_RATE, FRAMES_PER_BUFFER); + /* initialise sinusoidal wavetable */ + for( i=0; i + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.portaudio.com + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +#include +#include +#include "portaudio.h" +#define OUTPUT_DEVICE (Pa_GetDefaultOutputDeviceID()) +#define SLEEP_DUR (200) +#define SAMPLE_RATE (44100) +#define FRAMES_PER_BUFFER (256) +#define LATENCY_MSEC (3000) +#define NUM_BUFFERS ((LATENCY_MSEC * SAMPLE_RATE) / (FRAMES_PER_BUFFER * 1000)) +#define FRAMES_PER_NOTE (SAMPLE_RATE/2) +#define MAX_REPEATS (2) +#define FUNDAMENTAL (400.0f / SAMPLE_RATE) +#define NOTE_0 (FUNDAMENTAL * 1.0f / 1.0f) +#define NOTE_1 (FUNDAMENTAL * 5.0f / 4.0f) +#define NOTE_2 (FUNDAMENTAL * 4.0f / 3.0f) +#define NOTE_3 (FUNDAMENTAL * 3.0f / 2.0f) +#define NOTE_4 (FUNDAMENTAL * 2.0f / 1.0f) +#define MODE_FINISH (0) +#define MODE_STOP (1) +#define MODE_ABORT (2) +#ifndef M_PI +#define M_PI (3.14159265) +#endif +#define TABLE_SIZE (400) +typedef struct +{ + float waveform[TABLE_SIZE + 1]; // add one for guard point for interpolation + float phase_increment; + float phase; + float *tune; + int notesPerTune; + int frameCounter; + int noteCounter; + int repeatCounter; + PaTimestamp outTime; + int stopMode; + int done; +} +paTestData; +/************* Prototypes *****************************/ +int TestStopMode( paTestData *data ); +float LookupWaveform( paTestData *data, float phase ); +/****************************************************** + * Convert phase between 0.0 and 1.0 to waveform value + * using linear interpolation. + */ +float LookupWaveform( paTestData *data, float phase ) +{ + float fIndex = phase*TABLE_SIZE; + int index = (int) fIndex; + float fract = fIndex - index; + float lo = data->waveform[index]; + float hi = data->waveform[index+1]; + float val = lo + fract*(hi-lo); + return val; +} +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patestCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + float *out = (float*)outputBuffer; + float value; + unsigned int i = 0; + int finished = 0; + (void) outTime; /* Prevent unused variable warnings. */ + (void) inputBuffer; + + data->outTime = outTime; + if( !data->done ) + { + for( i=0; iframeCounter >= FRAMES_PER_NOTE ) + { + data->noteCounter += 1; + data->frameCounter = 0; + /* Are we done with this tune? */ + if( data->noteCounter >= data->notesPerTune ) + { + data->noteCounter = 0; + data->repeatCounter += 1; + /* Are we totally done? */ + if( data->repeatCounter >= MAX_REPEATS ) + { + data->done = 1; + if( data->stopMode == MODE_FINISH ) + { + finished = 1; + break; + } + } + } + data->phase_increment = data->tune[data->noteCounter]; + } + value = LookupWaveform(data, data->phase); + *out++ = value; /* left */ + *out++ = value; /* right */ + data->phase += data->phase_increment; + if( data->phase >= 1.0f ) data->phase -= 1.0f; + + data->frameCounter += 1; + } + } + /* zero remainder of final buffer */ + for( ; idone = 0; + data->phase = 0.0; + data->frameCounter = 0; + data->noteCounter = 0; + data->repeatCounter = 0; + data->phase_increment = data->tune[data->noteCounter]; + err = Pa_Initialize(); + if( err != paNoError ) goto error; + err = Pa_OpenStream( + &stream, + paNoDevice,/* default input device */ + 0, /* no input */ + paFloat32, /* 32 bit floating point input */ + NULL, + OUTPUT_DEVICE, + 2, /* stereo output */ + paFloat32, /* 32 bit floating point output */ + NULL, + SAMPLE_RATE, + FRAMES_PER_BUFFER, /* frames per buffer */ + NUM_BUFFERS, /* number of buffers, if zero then use default minimum */ + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + patestCallback, + data ); + if( err != paNoError ) goto error; + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + if( data->stopMode == MODE_FINISH ) + { + while( Pa_StreamActive( stream ) ) + { + /*printf("outTime = %g, note# = %d, repeat# = %d\n", data->outTime, + data->noteCounter, data->repeatCounter ); + fflush(stdout); /**/ + Pa_Sleep( SLEEP_DUR ); + } + } + else + { + while( data->repeatCounter < MAX_REPEATS ) + { + /*printf("outTime = %g, note# = %d, repeat# = %d\n", data->outTime, + data->noteCounter, data->repeatCounter ); + fflush(stdout); /**/ + Pa_Sleep( SLEEP_DUR ); + } + } + if( data->stopMode == MODE_ABORT ) + { + printf("Call Pa_AbortStream()\n"); + err = Pa_AbortStream( stream ); + } + else + { + printf("Call Pa_StopStream()\n"); + err = Pa_StopStream( stream ); + } + if( err != paNoError ) goto error; + printf("Call Pa_CloseStream()\n"); fflush(stdout); + err = Pa_CloseStream( stream ); + if( err != paNoError ) goto error; + Pa_Terminate(); + printf("Test finished.\n"); + return err; +error: + Pa_Terminate(); + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + return err; +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_sync.c b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_sync.c new file mode 100755 index 00000000000..b4fbdf298c4 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_sync.c @@ -0,0 +1,227 @@ +/* + * $Id: patest_sync.c,v 1.1.2.1 2005-08-16 20:04:11 alex%croczilla.com Exp $ + * patest_sync.c + * Test time stamping and synchronization of audio and video. + * A high latency is used so we can hear the difference in time. + * Random durations are used so we know we are hearing the right beep + * and not the one before or after. + * + * Sequence of events: + * Foreground requests a beep. + * Background randomly schedules a beep. + * Foreground waits for the beep to be heard based on Pa_StreamTime(). + * Foreground outputs video (printf) in sync with audio. + * Repeat. + * + * Author: Phil Burk http://www.softsynth.com + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.portaudio.com + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +#include +#include +#include "portaudio.h" +#define NUM_BEEPS (6) +#define SAMPLE_RATE (44100) +#define FRAMES_PER_BUFFER (256) +#define BEEP_DURATION (1000) +#define LATENCY_MSEC (2000) +#define SLEEP_MSEC (10) +#define TIMEOUT_MSEC ((3 * LATENCY_MSEC) / (2 * SLEEP_MSEC)) +#define NUM_BUFFERS ((LATENCY_MSEC * SAMPLE_RATE) / (FRAMES_PER_BUFFER * 1000)) +#define STATE_BKG_IDLE (0) +#define STATE_BKG_PENDING (1) +#define STATE_BKG_BEEPING (2) +typedef struct +{ + float left_phase; + float right_phase; + int state; + int requestBeep; /* Set by foreground, cleared by background. */ + PaTimestamp beepTime; + int beepCount; +} +paTestData; +static unsigned long GenerateRandomNumber( void ); +/************************************************************/ +/* Calculate pseudo-random 32 bit number based on linear congruential method. */ +static unsigned long GenerateRandomNumber( void ) +{ + static unsigned long randSeed = 22222; /* Change this for different random sequences. */ + randSeed = (randSeed * 196314165) + 907633515; + return randSeed; +} +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patestCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + /* Cast data passed through stream to our structure. */ + paTestData *data = (paTestData*)userData; + float *out = (float*)outputBuffer; + unsigned int i; + (void) inputBuffer; + + for( i=0; istate ) + { + case STATE_BKG_IDLE: + /* Schedule beep at some random time in the future. */ + if( data->requestBeep ) + { + int random = GenerateRandomNumber() >> 14; + data->beepTime = outTime + (i + random + (SAMPLE_RATE/4)); + data->state = STATE_BKG_PENDING; + data->requestBeep = 0; + data->left_phase = data->right_phase = 0.0; + } + *out++ = 0.0; /* left */ + *out++ = 0.0; /* right */ + break; + case STATE_BKG_PENDING: + if( (outTime + i) >= data->beepTime ) + { + data->state = STATE_BKG_BEEPING; + data->beepCount = BEEP_DURATION; + } + *out++ = 0.0; /* left */ + *out++ = 0.0; /* right */ + break; + case STATE_BKG_BEEPING: + if( data->beepCount <= 0 ) + { + data->state = STATE_BKG_IDLE; + *out++ = 0.0; /* left */ + *out++ = 0.0; /* right */ + } + else + { + /* Play sawtooth wave. */ + *out++ = data->left_phase; /* left */ + *out++ = data->right_phase; /* right */ + /* Generate simple sawtooth phaser that ranges between -1.0 and 1.0. */ + data->left_phase += 0.01f; + /* When signal reaches top, drop back down. */ + if( data->left_phase >= 1.0f ) data->left_phase -= 2.0f; + /* higher pitch so we can distinguish left and right. */ + data->right_phase += 0.03f; + if( data->right_phase >= 1.0f ) data->right_phase -= 2.0f; + } + data->beepCount -= 1; + break; + default: + data->state = STATE_BKG_IDLE; + break; + } + } + return 0; +} +/*******************************************************************/ +int main(void); +int main(void) +{ + PortAudioStream *stream; + PaError err; + paTestData DATA; + int i, timeout; + PaTimestamp previousTime; + printf("PortAudio Test: you should see BEEP at the same time you hear it.\n"); + printf("Wait for a few seconds random delay between BEEPs.\n"); + printf("BEEP %d times.\n", NUM_BEEPS ); + /* Initialize our DATA for use by callback. */ + DATA.left_phase = DATA.right_phase = 0.0; + DATA.state = STATE_BKG_IDLE; + DATA.requestBeep = 0; + /* Initialize library before making any other calls. */ + err = Pa_Initialize(); + if( err != paNoError ) goto error; + /* Open an audio I/O stream. */ + err = Pa_OpenDefaultStream( + &stream, + 0, /* no input channels */ + 2, /* stereo output */ + paFloat32, /* 32 bit floating point output */ + SAMPLE_RATE, + FRAMES_PER_BUFFER, + NUM_BUFFERS, + patestCallback, + &DATA ); + if( err != paNoError ) goto error; + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + previousTime = Pa_StreamTime( stream ); + for( i=0; i 0 ) ) Pa_Sleep(SLEEP_MSEC); + if( timeout <= 0 ) + { + fprintf( stderr, "Timed out waiting for background to acknowledge request.\n" ); + goto error; + } + /* Wait for scheduled beep time. */ + timeout = TIMEOUT_MSEC + (10000/SLEEP_MSEC); + while( (Pa_StreamTime( stream ) < DATA.beepTime) && (timeout-- > 0 ) ) + { + Pa_Sleep(SLEEP_MSEC); + } + if( timeout <= 0 ) + { + fprintf( stderr, "Timed out waiting for time. Now = %g, Beep for %g.\n", + Pa_StreamTime( stream ), DATA.beepTime ); + goto error; + } + /* Beep should be sounding now so print synchronized BEEP. */ + printf("BEEP"); + fflush(stdout); + printf(" at %d, delta = %d\n", + (long) DATA.beepTime, (long) (DATA.beepTime - previousTime) ); + fflush(stdout); + previousTime = DATA.beepTime; + } + err = Pa_StopStream( stream ); + if( err != paNoError ) goto error; + err = Pa_CloseStream( stream ); + if( err != paNoError ) goto error; + Pa_Terminate(); + printf("Test finished.\n"); + return err; +error: + Pa_Terminate(); + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + return err; +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_toomanysines.c b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_toomanysines.c new file mode 100755 index 00000000000..f616c05934a --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_toomanysines.c @@ -0,0 +1,175 @@ +/* + * $Id: patest_toomanysines.c,v 1.1.2.1 2005-08-16 20:04:11 alex%croczilla.com Exp $ + * Play more sine waves than we can handle in real time as a stress test, + * + * Authors: + * Ross Bencina + * Phil Burk + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.audiomulch.com/portaudio/ + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +#include +#include +#include "portaudio.h" + +#define MAX_SINES (500) +#define MAX_LOAD (1.2) +#define SAMPLE_RATE (44100) +#define FRAMES_PER_BUFFER (512) +#ifndef M_PI +#define M_PI (3.14159265) +#endif +#define TWOPI (M_PI * 2.0) + +typedef struct paTestData +{ + int numSines; + double phases[MAX_SINES]; +} +paTestData; + +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patestCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + float *out = (float*)outputBuffer; + unsigned long i; + int j; + int finished = 0; + (void) outTime; /* Prevent unused variable warnings. */ + (void) inputBuffer; + + for( i=0; inumSines; j++ ) + { + /* Advance phase of next oscillator. */ + phase = data->phases[j]; + phase += phaseInc; + if( phase > TWOPI ) phase -= TWOPI; + + phaseInc *= 1.02; + if( phaseInc > 0.5 ) phaseInc *= 0.5; + + /* This is not a very efficient way to calc sines. */ + output += (float) sin( phase ); + data->phases[j] = phase; + } + + + *out++ = (float) (output / data->numSines); + } + return finished; +} + +/*******************************************************************/ +int main(void); +int main(void) +{ + PortAudioStream *stream; + PaError err; + int numStress; + paTestData data = {0}; + double load; + printf("PortAudio Test: output sine wave. SR = %d, BufSize = %d. MAX_LOAD = %f\n", + SAMPLE_RATE, FRAMES_PER_BUFFER, MAX_LOAD ); + + err = Pa_Initialize(); + if( err != paNoError ) goto error; + err = Pa_OpenStream( + &stream, + paNoDevice,/* default input device */ + 0, /* no input */ + paFloat32, /* 32 bit floating point input */ + NULL, + Pa_GetDefaultOutputDeviceID(), /* default output device */ + 1, /* mono output */ + paFloat32, /* 32 bit floating point output */ + NULL, + SAMPLE_RATE, + FRAMES_PER_BUFFER, /* frames per buffer */ + 0, /* number of buffers, if zero then use default minimum */ + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + patestCallback, + &data ); + if( err != paNoError ) goto error; + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + + /* Determine number of sines required to get to 50% */ + do + { + data.numSines++; + Pa_Sleep( 100 ); + + load = Pa_GetCPULoad( stream ); + printf("numSines = %d, CPU load = %f\n", data.numSines, load ); + fflush(stdout); + } + while( load < 0.5 ); + + /* Calculate target stress value then ramp up to that level*/ + numStress = (int) (2.0 * data.numSines * MAX_LOAD ); + for( ; data.numSines < numStress; data.numSines++ ) + { + Pa_Sleep( 200 ); + load = Pa_GetCPULoad( stream ); + printf("STRESSING: numSines = %d, CPU load = %f\n", data.numSines, load ); + fflush(stdout); + + } + + printf("Suffer for 5 seconds.\n"); + Pa_Sleep( 5000 ); + + printf("Stop stream.\n"); + err = Pa_StopStream( stream ); + if( err != paNoError ) goto error; + + err = Pa_CloseStream( stream ); + if( err != paNoError ) goto error; + + Pa_Terminate(); + printf("Test finished.\n"); + return err; +error: + Pa_Terminate(); + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + return err; +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_two_rates.c b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_two_rates.c new file mode 100755 index 00000000000..4f66041c283 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_two_rates.c @@ -0,0 +1,168 @@ +/* + * $Id: patest_two_rates.c,v 1.1.2.1 2005-08-16 20:04:11 alex%croczilla.com Exp $ + * patest_two_rates.c + * Play two streams at different rates to make sure they don't interfere. + * + * Author: Phil Burk http://www.softsynth.com + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.portaudio.com + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +#include +#include +#include "portaudio.h" + +#define OUTPUT_DEVICE (Pa_GetDefaultOutputDeviceID()) +#define SAMPLE_RATE_1 (44100) +#define SAMPLE_RATE_2 (44100) +#define FRAMES_PER_BUFFER (256) +#define FREQ_INCR (0.1) + +#ifndef M_PI +#define M_PI (3.14159265) +#endif + +typedef struct +{ + double phase; + double numFrames; +} paTestData; + +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patestCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + float *out = (float*)outputBuffer; + int frameIndex, channelIndex; + int finished = 0; + (void) outTime; /* Prevent unused variable warnings. */ + (void) inputBuffer; + + for( frameIndex=0; frameIndex<(int)framesPerBuffer; frameIndex++ ) + { + /* Generate sine wave. */ + float value = (float) 0.3 * sin(data->phase); + /* Stereo - two channels. */ + *out++ = value; + *out++ = value; + + data->phase += FREQ_INCR; + if( data->phase >= (2.0 * M_PI) ) data->phase -= (2.0 * M_PI); + } + + return 0; +} + +/*******************************************************************/ +int main(void); +int main(void) +{ + PaError err; + PortAudioStream *stream1; + PortAudioStream *stream2; + paTestData data1 = {0}; + paTestData data2 = {0}; + printf("PortAudio Test: two rates.\n" ); + + err = Pa_Initialize(); + if( err != paNoError ) goto error; + + /* Start first stream. **********************/ + err = Pa_OpenStream( + &stream1, + paNoDevice, /* default input device */ + 0, /* no input */ + paFloat32, /* 32 bit floating point input */ + NULL, + OUTPUT_DEVICE, + 2, /* Stereo */ + paFloat32, /* 32 bit floating point output */ + NULL, + SAMPLE_RATE_1, + FRAMES_PER_BUFFER, /* frames per buffer */ + 0, /* number of buffers, if zero then use default minimum */ + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + patestCallback, + &data1 ); + if( err != paNoError ) goto error; + + err = Pa_StartStream( stream1 ); + if( err != paNoError ) goto error; + + Pa_Sleep( 3 * 1000 ); + + /* Start second stream. **********************/ + err = Pa_OpenStream( + &stream2, + paNoDevice, /* default input device */ + 0, /* no input */ + paFloat32, /* 32 bit floating point input */ + NULL, + OUTPUT_DEVICE, + 2, /* Stereo */ + paFloat32, /* 32 bit floating point output */ + NULL, + SAMPLE_RATE_2, + FRAMES_PER_BUFFER, /* frames per buffer */ + 0, /* number of buffers, if zero then use default minimum */ + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + patestCallback, + &data2 ); + if( err != paNoError ) goto error; + + err = Pa_StartStream( stream2 ); + if( err != paNoError ) goto error; + + Pa_Sleep( 3 * 1000 ); + + err = Pa_StopStream( stream2 ); + if( err != paNoError ) goto error; + + Pa_Sleep( 3 * 1000 ); + + err = Pa_StopStream( stream1 ); + if( err != paNoError ) goto error; + + Pa_CloseStream( stream2 ); + Pa_CloseStream( stream1 ); + + Pa_Terminate(); + printf("Test finished.\n"); + return err; +error: + Pa_Terminate(); + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + return err; +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_underflow.c b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_underflow.c new file mode 100755 index 00000000000..6e83d0d0252 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_tests/patest_underflow.c @@ -0,0 +1,151 @@ +/* + * $Id: patest_underflow.c,v 1.1.2.1 2005-08-16 20:04:11 alex%croczilla.com Exp $ + * patest_underflow.c + * Simulate an output buffer underflow condition. + * Tests whether the stream can be stopped when underflowing buffers. + * + * Authors: + * Ross Bencina + * Phil Burk + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.audiomulch.com/portaudio/ + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +#include +#include +#include "portaudio.h" + +#define NUM_SECONDS (20) +#define SAMPLE_RATE (44100) +#define FRAMES_PER_BUFFER (2048) +#define MSEC_PER_BUFFER ( (FRAMES_PER_BUFFER * 1000) / SAMPLE_RATE ) + +#ifndef M_PI +#define M_PI (3.14159265) +#endif + +#define TABLE_SIZE (200) +typedef struct +{ + float sine[TABLE_SIZE]; + int left_phase; + int right_phase; + int sleepTime; +} +paTestData; + +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patestCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + float *out = (float*)outputBuffer; + unsigned long i; + int finished = 0; + (void) outTime; /* Prevent unused variable warnings. */ + (void) inputBuffer; + for( i=0; isine[data->left_phase]; /* left */ + *out++ = data->sine[data->right_phase]; /* right */ + data->left_phase += 1; + if( data->left_phase >= TABLE_SIZE ) data->left_phase -= TABLE_SIZE; + data->right_phase += 3; /* higher pitch so we can distinguish left and right. */ + if( data->right_phase >= TABLE_SIZE ) data->right_phase -= TABLE_SIZE; + } + + /* Cause underflow to occur. */ + if( data->sleepTime > 0 ) Pa_Sleep( data->sleepTime ); + data->sleepTime += 1; + + return finished; +} + +/*******************************************************************/ +int main(void); +int main(void) +{ + PortAudioStream *stream; + PaError err; + paTestData data; + int i; + printf("PortAudio Test: output sine wave. SR = %d, BufSize = %d\n", SAMPLE_RATE, FRAMES_PER_BUFFER); + /* initialise sinusoidal wavetable */ + for( i=0; i +#include +#include "portaudio.h" + +#define INPUT_DEVICE Pa_GetDefaultInputDeviceID() +#define OUTPUT_DEVICE Pa_GetDefaultOutputDeviceID() + +/* +** Note that many of the older ISA sound cards on PCs do NOT support +** full duplex audio (simultaneous record and playback). +** And some only support full duplex at lower sample rates. +*/ +#define SAMPLE_RATE (44100) +#define FRAMES_PER_BUFFER (64) + +#if 1 +#define PA_SAMPLE_TYPE paFloat32 +typedef float SAMPLE; +#else +#define PA_SAMPLE_TYPE paInt16 +typedef short SAMPLE; +#endif +static int wireCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ); + +/* This routine will be called by the PortAudio engine when audio is needed. +** It may be called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int wireCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + SAMPLE *out = (SAMPLE*)outputBuffer; + SAMPLE *in = (SAMPLE*)inputBuffer; + unsigned int i; + int samplesPerFrame; + int numSamples; + (void) outTime; + + samplesPerFrame = (int) userData; + numSamples = framesPerBuffer * samplesPerFrame; + + /* This may get called with NULL inputBuffer during initial setup. */ + if( inputBuffer == NULL ) + { + for( i=0; imaxInputChannels < outputInfo->maxOutputChannels) ? + inputInfo->maxInputChannels : outputInfo->maxOutputChannels; + + printf("maxInputChannels channels = %d\n", inputInfo->maxInputChannels ); + printf("maxOutputChannels channels = %d\n", outputInfo->maxOutputChannels ); + if( numChannels > 0 ) + { + printf("Using %d channels.\n", numChannels ); + + err = Pa_OpenStream( + &stream, + INPUT_DEVICE, + numChannels, + PA_SAMPLE_TYPE, + NULL, + OUTPUT_DEVICE, + numChannels, + PA_SAMPLE_TYPE, + NULL, + SAMPLE_RATE, + FRAMES_PER_BUFFER, /* frames per buffer */ + 0, /* number of buffers, if zero then use default minimum */ + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + wireCallback, + (void *) numChannels ); /* pass numChannels to callback */ + if( err != paNoError ) goto error; + + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + + printf("Full duplex sound test in progress.\n"); + printf("Hit ENTER to exit test.\n"); fflush(stdout); + getchar(); + + printf("Closing stream.\n"); + err = Pa_CloseStream( stream ); + if( err != paNoError ) goto error; + } + else + { + printf("Sorry, not enough channels.\n"); + } + Pa_Terminate(); + + printf("Full duplex sound test complete.\n"); fflush(stdout); + return 0; +error: + Pa_Terminate(); + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + return -1; +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_unix_oss/Makefile_freebsd b/mozilla/zap/zmk/portaudio_v18_1/pa_unix_oss/Makefile_freebsd new file mode 100755 index 00000000000..099e4bfcf78 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_unix_oss/Makefile_freebsd @@ -0,0 +1,36 @@ +# Make PortAudio for FreeBSD + +LIBS = -lm -pthread + +CDEFINES = -I../pa_common +CFLAGS = -g +PASRC = ../pa_common/pa_lib.c pa_freebsd.c +PAINC = ../pa_common/portaudio.h + +# Tests that work. +#TESTC = $(PASRC) ../pa_tests/patest_sine.c +TESTC = $(PASRC) ../pa_tests/patest_sine_time.c +#TESTC = $(PASRC) ../pa_tests/patest_stop.c +#TESTC = $(PASRC) ../pa_tests/patest_sync.c +#TESTC = $(PASRC) ../pa_tests/patest_pink.c +#TESTC = $(PASRC) ../pa_tests/patest_leftright.c +#TESTC = $(PASRC) ../pa_tests/patest_clip.c +#TESTC = $(PASRC) ../pa_tests/patest_dither.c +#TESTC = $(PASRC) ../pa_tests/pa_devs.c +#TESTC = $(PASRC) ../pa_tests/patest_many.c +#TESTC = $(PASRC) ../pa_tests/patest_record.c +#TESTC = $(PASRC) ../pa_tests/patest_wire.c +#TESTC = $(PASRC) ../pa_tests/paqa_devs.c + +# Tests that do not yet work. + +TESTH = $(PAINC) + +all: patest + +patest: $(TESTC) $(TESTH) Makefile + gcc $(CFLAGS) $(TESTC) $(CDEFINES) $(LIBS) -o patest + +run: patest + ./patest + diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_unix_oss/low_latency_tip.txt b/mozilla/zap/zmk/portaudio_v18_1/pa_unix_oss/low_latency_tip.txt new file mode 100755 index 00000000000..78ea9d50894 Binary files /dev/null and b/mozilla/zap/zmk/portaudio_v18_1/pa_unix_oss/low_latency_tip.txt differ diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_unix_oss/pa_unix.c b/mozilla/zap/zmk/portaudio_v18_1/pa_unix_oss/pa_unix.c new file mode 100755 index 00000000000..5af70bc20a5 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_unix_oss/pa_unix.c @@ -0,0 +1,1122 @@ +/* + * PortAudio Portable Real-Time Audio Library + * Latest Version at: http://www.portaudio.com + * Linux OSS Implementation by douglas repetto and Phil Burk + * + * Copyright (c) 1999-2000 Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +/* +Modification History + 1/2001 - Phil Burk - initial hack for Linux + 2/2001 - Douglas Repetto - many improvements, initial query support + 4/2/2001 - Phil - stop/abort thread control, separate in/out native buffers + 5/28/2001 - Phil - use pthread_create() instead of clone(). Thanks Stephen Brandon! + use pthread_join() after thread shutdown. + 5/29/2001 - Phil - query for multiple devices, multiple formats, + input mode and input+output mode working, + Pa_GetCPULoad() implemented. + PLB20010817 - Phil & Janos Haber - don't halt if test of sample rate fails. + SB20010904 - Stephen Brandon - mods needed for GNUSTEP and SndKit + JH20010905 - Janos Haber - FreeBSD mods + 2001-09-22 - Heiko - (i.e. Heiko Purnhagen ;-) + added 24k and 16k to ratesToTry[] + fixed Pa_GetInternalDevice() + changed DEVICE_NAME_BASE from /dev/audio to /dev/dsp + handled SNDCTL_DSP_SPEED in Pq_QueryDevice() more graceful + fixed Pa_StreamTime() for paqa_errs.c + fixed numCannel=2 oddity and error handling in Pa_SetupDeviceFormat() + grep also for HP20010922 ... + PLB20010924 - Phil - merged Heiko's changes + removed sNumDevices and potential related bugs, + use getenv("PA_MIN_LATENCY_MSEC") to set desired latency, + simplify CPU Load calculation by comparing real-time to framesPerBuffer, + always close device when querying even if error occurs, + PLB20010927 - Phil - Improved negotiation for numChannels. + SG20011005 - Stewart Greenhill - set numChannels back to reasonable value after query. + DH20010115 - David Herring - fixed uninitialized handle. + + DM20020218 - Dominic Mazzoni - Try to open in nonblocking mode first, in case + the device is already open. New implementation of + Pa_StreamTime that uses SNDCTL_DSP_GETOPTR but + uses our own counter to avoid wraparound. + PLB20020222 - Phil Burk - Added WatchDog proc if audio running at high priority. + Check error return from read() and write(). + Check CPU endianness instead of assuming Little Endian. + 20020621 - pa_unix_oss.c split into pa_unix.c, pa_unix.h, pa_unix_oss.c by + Augustus Saunders. Return values from usleep() ignored by Sam Bayer + because not cross-platform compatible (at least until we get configure + going). Pa_SetupDeviceFormat split into input and output sides to + reflect capabilities of Solaris. + + 20030206 - Martin Rohrbach - various mods for Solaris + + 20030410 - Bjorn Dittmer-Roche - fixed numerous problems associated with pthread_t + + 20030630 - Thomas Richter - eliminated unused variable warnings. + +TODO +O- put semaphore lock around shared data? +O- handle native formats better +O- handle stereo-only device better ??? +O- what if input and output of a device capabilities differ (e.g. es1371) ??? +*/ + + +#include "pa_unix.h" + +typedef void *(*pthread_function_t)(void *); + +/************************************************* Shared Data ********/ +/* FIXME - put Mutex around this shared data. */ +static internalPortAudioDevice *sDeviceList = NULL; +static int sDefaultInputDeviceID = paNoDevice; +static int sDefaultOutputDeviceID = paNoDevice; +static int sPaHostError = 0; + +/********************************* BEGIN CPU UTILIZATION MEASUREMENT ****/ +static void Pa_StartUsageCalculation( internalPortAudioStream *past ) +{ + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + if( pahsc == NULL ) return; + /* Query system timer for usage analysis and to prevent overuse of CPU. */ + gettimeofday( &pahsc->pahsc_EntryTime, NULL ); +} + +static long SubtractTime_AminusB( struct timeval *timeA, struct timeval *timeB ) +{ + long secs = timeA->tv_sec - timeB->tv_sec; + long usecs = secs * 1000000; + usecs += (timeA->tv_usec - timeB->tv_usec); + return usecs; +} + +/****************************************************************************** +** Measure fractional CPU load based on real-time it took to calculate +** buffers worth of output. +*/ +static void Pa_EndUsageCalculation( internalPortAudioStream *past ) +{ + struct timeval currentTime; + long usecsElapsed; + double newUsage; + +#define LOWPASS_COEFFICIENT_0 (0.95) +#define LOWPASS_COEFFICIENT_1 (0.99999 - LOWPASS_COEFFICIENT_0) + + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + if( pahsc == NULL ) return; + + if( gettimeofday( ¤tTime, NULL ) == 0 ) + { + usecsElapsed = SubtractTime_AminusB( ¤tTime, &pahsc->pahsc_EntryTime ); + /* Use inverse because it is faster than the divide. */ + newUsage = usecsElapsed * pahsc->pahsc_InverseMicrosPerBuffer; + + past->past_Usage = (LOWPASS_COEFFICIENT_0 * past->past_Usage) + + (LOWPASS_COEFFICIENT_1 * newUsage); + + } +} +/****************************************** END CPU UTILIZATION *******/ + +/********************************************************************* + * Determines the number of available devices by trying to open + * each "/dev/dsp#" or "/dsp/audio#" in order until it fails. + * Add each working device to a singly linked list of devices. + */ +PaError Pa_QueryDevices( void ) +{ + internalPortAudioDevice *pad, *lastPad; + int go = 1; + int numDevices = 0; + PaError testResult; + PaError result = paNoError; + char *envdev; + + sDefaultInputDeviceID = paNoDevice; + sDefaultOutputDeviceID = paNoDevice; + + lastPad = NULL; + + while( go ) + { + /* Allocate structure to hold device info. */ + pad = (internalPortAudioDevice *) + PaHost_AllocateFastMemory( sizeof(internalPortAudioDevice) ); + if( pad == NULL ) return paInsufficientMemory; + memset( pad, 0, sizeof(internalPortAudioDevice) ); + + /* Build name for device. */ + if( numDevices == 0 ) + { + sprintf( pad->pad_DeviceName, DEVICE_NAME_BASE); + } + else + { + sprintf( pad->pad_DeviceName, DEVICE_NAME_BASE "%d", numDevices ); + } + + DBUG(("Try device %s\n", pad->pad_DeviceName )); + testResult = Pa_QueryDevice( pad->pad_DeviceName, pad ); + DBUG(("Pa_QueryDevice returned %d\n", testResult )); + if( testResult != paNoError ) + { + if( lastPad == NULL ) + { + result = testResult; /* No good devices! */ + } + go = 0; + PaHost_FreeFastMemory( pad, sizeof(internalPortAudioDevice) ); + } + else + { + numDevices += 1; + /* Add to linked list of devices. */ + if( lastPad ) + { + lastPad->pad_Next = pad; + } + else + { + sDeviceList = pad; /* First element in linked list. */ + } + lastPad = pad; + } + } + + /* I'm sitting at a SunRay1 and I neither have /dev/audio# nor /dev/dsp#. + Instead, the correct audio device is stored in the environment variable + AUDIODEV and/or UTAUDIODEV, so check these devices as well if we haven't + checked them yet above - MR */ + + DBUG(("Checking for AUDIODEV and UTAUDIODEV\n")); + envdev = getenv("AUDIODEV"); + if (envdev != NULL && !strstr(envdev, DEVICE_NAME_BASE)) { + result = paNoError; + + /* Allocate structure to hold device info. */ + pad = (internalPortAudioDevice *) + PaHost_AllocateFastMemory( sizeof(internalPortAudioDevice) ); + if( pad == NULL ) return paInsufficientMemory; + memset( pad, 0, sizeof(internalPortAudioDevice) ); + + /* Build name for device. */ + strcpy(pad->pad_DeviceName, envdev); + + DBUG(("Try device %s\n", pad->pad_DeviceName )); + testResult = Pa_QueryDevice( pad->pad_DeviceName, pad ); + DBUG(("Pa_QueryDevice returned %d\n", testResult )); + if( testResult != paNoError ) + { + if( lastPad == NULL ) + { + result = testResult; /* No good devices! */ + } + PaHost_FreeFastMemory( pad, sizeof(internalPortAudioDevice) ); + } + else + { + numDevices += 1; + /* Add to linked list of devices. */ + if( lastPad ) + { + lastPad->pad_Next = pad; + } + else + { + sDeviceList = pad; /* First element in linked list. */ + } + lastPad = pad; + } + } + + envdev = getenv("UTAUDIODEV"); + if (envdev != NULL && !strstr(envdev, DEVICE_NAME_BASE) && getenv("AUDIODEV") != NULL && strcmp(envdev, getenv("AUDIODEV"))) { + result = paNoError; + + /* Allocate structure to hold device info. */ + pad = (internalPortAudioDevice *) + PaHost_AllocateFastMemory( sizeof(internalPortAudioDevice) ); + if( pad == NULL ) return paInsufficientMemory; + memset( pad, 0, sizeof(internalPortAudioDevice) ); + + /* Build name for device. */ + strcpy(pad->pad_DeviceName, envdev); + + DBUG(("Try device %s\n", pad->pad_DeviceName )); + testResult = Pa_QueryDevice( pad->pad_DeviceName, pad ); + DBUG(("Pa_QueryDevice returned %d\n", testResult )); + if( testResult != paNoError ) + { + if( lastPad == NULL ) + { + result = testResult; /* No good devices! */ + } + PaHost_FreeFastMemory( pad, sizeof(internalPortAudioDevice) ); + } + else + { + numDevices += 1; + /* Add to linked list of devices. */ + if( lastPad ) + { + lastPad->pad_Next = pad; + } + else + { + sDeviceList = pad; /* First element in linked list. */ + } + lastPad = pad; + } + } + + return result; +} + +/*************************************************************************/ +int Pa_CountDevices() +{ + int numDevices = 0; + internalPortAudioDevice *pad; + + if( sDeviceList == NULL ) Pa_Initialize(); + /* Count devices in list. */ + pad = sDeviceList; + while( pad != NULL ) + { + pad = pad->pad_Next; + numDevices++; + } + + return numDevices; +} + +/*************************************************************************/ +internalPortAudioDevice *Pa_GetInternalDevice( PaDeviceID id ) +{ + internalPortAudioDevice *pad; + if( (id < 0) || ( id >= Pa_CountDevices()) ) return NULL; + pad = sDeviceList; + while( id > 0 ) + { + pad = pad->pad_Next; + id--; + } + return pad; +} + +/*************************************************************************/ +const PaDeviceInfo* Pa_GetDeviceInfo( PaDeviceID id ) +{ + internalPortAudioDevice *pad; + if( (id < 0) || ( id >= Pa_CountDevices()) ) return NULL; + pad = Pa_GetInternalDevice( id ); + return &pad->pad_Info ; +} + +static PaError Pa_MaybeQueryDevices( void ) +{ + if( sDeviceList == NULL ) + { + return Pa_QueryDevices(); + } + return 0; +} + +PaDeviceID Pa_GetDefaultInputDeviceID( void ) +{ + /* return paNoDevice; */ + return 0; +} + +PaDeviceID Pa_GetDefaultOutputDeviceID( void ) +{ + return 0; +} + +/********************************************************************** +** Make sure that we have queried the device capabilities. +*/ + +PaError PaHost_Init( void ) +{ + return Pa_MaybeQueryDevices(); +} + +/******************************************************************************************* + * The ol' Canary in a Coal Mine trick. + * Just update the time periodically. + * Runs at low priority so if audio thread runs wild, this thread will get starved + * and the watchdog will detect it. + */ + +#define SCHEDULER_POLICY SCHED_RR +#define WATCHDOG_MAX_SECONDS (3) +#define WATCHDOG_INTERVAL_USEC (1000000) + +static int PaHost_CanaryProc( PaHostSoundControl *pahsc ) +{ + int result = 0; + +#ifdef GNUSTEP + GSRegisterCurrentThread(); /* SB20010904 */ +#endif + + while( pahsc->pahsc_CanaryRun) { + usleep( WATCHDOG_INTERVAL_USEC ); + gettimeofday( &pahsc->pahsc_CanaryTime, NULL ); + } + + DBUG(("PaHost_CanaryProc: exiting.\n")); + +#ifdef GNUSTEP + GSUnregisterCurrentThread(); /* SB20010904 */ +#endif + + return result; +} + +/******************************************************************************************* + * Monitor audio thread and lower its it if it hogs the CPU. + * To prevent getting killed, the audio thread must update a + * variable with a timer value. + * If the value is not recent enough, then the + * thread will get killed. + */ + +static PaError PaHost_WatchDogProc( PaHostSoundControl *pahsc ) +{ + struct sched_param schp = { 0 }; + int maxPri; + +#ifdef GNUSTEP + GSRegisterCurrentThread(); /* SB20010904 */ +#endif + +/* Run at a priority level above audio thread so we can still run if it hangs. */ +/* Rise more than 1 because of rumored off-by-one scheduler bugs. */ + schp.sched_priority = pahsc->pahsc_AudioPriority + 4; + maxPri = sched_get_priority_max(SCHEDULER_POLICY); + if( schp.sched_priority > maxPri ) schp.sched_priority = maxPri; + + if (sched_setscheduler(0, SCHEDULER_POLICY, &schp) != 0) + { + ERR_RPT(("PaHost_WatchDogProc: cannot set watch dog priority!\n")); + goto killAudio; + } + + /* Compare watchdog time with audio and canary thread times. */ + /* Sleep for a while or until thread cancelled. */ + while( pahsc->pahsc_WatchDogRun ) + { + + int delta; + struct timeval currentTime; + + usleep( WATCHDOG_INTERVAL_USEC ); + gettimeofday( ¤tTime, NULL ); + + /* If audio thread is not advancing, then it must be hung so kill it. */ + delta = currentTime.tv_sec - pahsc->pahsc_EntryTime.tv_sec; + DBUG(("PaHost_WatchDogProc: audio delta = %d\n", delta )); + if( delta > WATCHDOG_MAX_SECONDS ) + { + goto killAudio; + } + + /* If canary died, then lower audio priority and halt canary. */ + delta = currentTime.tv_sec - pahsc->pahsc_CanaryTime.tv_sec; + if( delta > WATCHDOG_MAX_SECONDS ) + { + ERR_RPT(("PaHost_WatchDogProc: canary died!\n")); + goto lowerAudio; + } + } + + DBUG(("PaHost_WatchDogProc: exiting.\n")); +#ifdef GNUSTEP + GSUnregisterCurrentThread(); /* SB20010904 */ +#endif + return 0; + +lowerAudio: + { + struct sched_param schat = { 0 }; + if( sched_setscheduler(pahsc->pahsc_AudioThreadPID, SCHED_OTHER, &schat) != 0) + { + ERR_RPT(("PaHost_WatchDogProc: failed to lower audio priority. errno = %d\n", errno )); + /* Fall through into killing audio thread. */ + } + else + { + ERR_RPT(("PaHost_WatchDogProc: lowered audio priority to prevent hogging of CPU.\n")); + goto cleanup; + } + } + +killAudio: + ERR_RPT(("PaHost_WatchDogProc: killing hung audio thread!\n")); + pthread_kill( pahsc->pahsc_AudioThread, SIGKILL ); + +cleanup: + pahsc->pahsc_CanaryRun = 0; + DBUG(("PaHost_WatchDogProc: cancel Canary\n")); + pthread_cancel( pahsc->pahsc_CanaryThread ); + DBUG(("PaHost_WatchDogProc: join Canary\n")); + pthread_join( pahsc->pahsc_CanaryThread, NULL ); + DBUG(("PaHost_WatchDogProc: forget Canary\n")); + pahsc->pahsc_IsCanaryThreadValid = 0; + +#ifdef GNUSTEP + GSUnregisterCurrentThread(); /* SB20010904 */ +#endif + return 0; +} + +/*******************************************************************************************/ +static void PaHost_StopWatchDog( PaHostSoundControl *pahsc ) +{ +/* Cancel WatchDog thread if there is one. */ + if( pahsc->pahsc_IsWatchDogThreadValid ) + { + pahsc->pahsc_WatchDogRun = 0; + DBUG(("PaHost_StopWatchDog: cancel WatchDog\n")); + pthread_cancel( pahsc->pahsc_WatchDogThread ); + pthread_join( pahsc->pahsc_WatchDogThread, NULL ); + pahsc->pahsc_IsWatchDogThreadValid = 0; + } +/* Cancel Canary thread if there is one. */ + if( pahsc->pahsc_IsCanaryThreadValid ) + { + pahsc->pahsc_CanaryRun = 0; + DBUG(("PaHost_StopWatchDog: cancel Canary\n")); + pthread_cancel( pahsc->pahsc_CanaryThread ); + DBUG(("PaHost_StopWatchDog: join Canary\n")); + pthread_join( pahsc->pahsc_CanaryThread, NULL ); + pahsc->pahsc_IsCanaryThreadValid = 0; + } +} + +/*******************************************************************************************/ +static PaError PaHost_StartWatchDog( PaHostSoundControl *pahsc ) +{ + int hres; + PaError result = 0; + + /* The watch dog watches for these timer updates */ + gettimeofday( &pahsc->pahsc_EntryTime, NULL ); + gettimeofday( &pahsc->pahsc_CanaryTime, NULL ); + + /* Launch a canary thread to detect priority abuse. */ + pahsc->pahsc_CanaryRun = 1; + hres = pthread_create(&(pahsc->pahsc_CanaryThread), + NULL /*pthread_attr_t * attr*/, + (pthread_function_t)PaHost_CanaryProc, pahsc); + if( hres != 0 ) + { + pahsc->pahsc_IsCanaryThreadValid = 0; + result = paHostError; + sPaHostError = hres; + goto error; + } + pahsc->pahsc_IsCanaryThreadValid = 1; + + /* Launch a watchdog thread to prevent runaway audio thread. */ + pahsc->pahsc_WatchDogRun = 1; + hres = pthread_create(&(pahsc->pahsc_WatchDogThread), + NULL /*pthread_attr_t * attr*/, + (pthread_function_t)PaHost_WatchDogProc, pahsc); + if( hres != 0 ) + { + pahsc->pahsc_IsWatchDogThreadValid = 0; + result = paHostError; + sPaHostError = hres; + goto error; + } + pahsc->pahsc_IsWatchDogThreadValid = 1; + return result; + +error: + PaHost_StopWatchDog( pahsc ); + return result; +} + +/******************************************************************************************* + * Bump priority of audio thread if running with superuser priveledges. + * if priority bumped then launch a watchdog. + */ +static PaError PaHost_BoostPriority( internalPortAudioStream *past ) +{ + PaHostSoundControl *pahsc; + PaError result = paNoError; + struct sched_param schp = { 0 }; + + pahsc = (PaHostSoundControl *) past->past_DeviceData; + if( pahsc == NULL ) return paInternalError; + + pahsc->pahsc_AudioThreadPID = getpid(); + DBUG(("PaHost_BoostPriority: audio PID = %d\n", pahsc->pahsc_AudioThreadPID )); + + /* Choose a priority in the middle of the range. */ + pahsc->pahsc_AudioPriority = (sched_get_priority_max(SCHEDULER_POLICY) - + sched_get_priority_min(SCHEDULER_POLICY)) / 2; + schp.sched_priority = pahsc->pahsc_AudioPriority; + + if (sched_setscheduler(0, SCHEDULER_POLICY, &schp) != 0) + { + DBUG(("PortAudio: only superuser can use real-time priority.\n")); + } + else + { + DBUG(("PortAudio: audio callback priority set to level %d!\n", schp.sched_priority)); + /* We are running at high priority so we should have a watchdog in case audio goes wild. */ + result = PaHost_StartWatchDog( pahsc ); + } + + return result; +} + +/*******************************************************************************************/ +static PaError Pa_AudioThreadProc( internalPortAudioStream *past ) +{ + PaError result; + PaHostSoundControl *pahsc; + ssize_t bytes_read, bytes_written; + + pahsc = (PaHostSoundControl *) past->past_DeviceData; + if( pahsc == NULL ) return paInternalError; + +#ifdef GNUSTEP + GSRegisterCurrentThread(); /* SB20010904 */ +#endif + + result = PaHost_BoostPriority( past ); + if( result < 0 ) goto error; + + past->past_IsActive = 1; + DBUG(("entering thread.\n")); + + while( (past->past_StopNow == 0) && (past->past_StopSoon == 0) ) + { + /* Read data from device */ + if(pahsc->pahsc_NativeInputBuffer) + { + unsigned int totalread = 0; + DBUG(("Pa_AudioThreadProc: attempt to read %d bytes\n", pahsc->pahsc_BytesPerInputBuffer)); + do + { + bytes_read = read(pahsc->pahsc_InputHandle, + (char *)pahsc->pahsc_NativeInputBuffer + totalread, + pahsc->pahsc_BytesPerInputBuffer - totalread); + + if (bytes_read < 0) + { + ERR_RPT(("PortAudio: read interrupted!\n")); + break; + } + + totalread += bytes_read; + } while( totalread < pahsc->pahsc_BytesPerInputBuffer); + } + + /* Convert 16 bit native data to user data and call user routine. */ + DBUG(("converting...\n")); + Pa_StartUsageCalculation( past ); + result = Pa_CallConvertInt16( past, + pahsc->pahsc_NativeInputBuffer, + pahsc->pahsc_NativeOutputBuffer ); + Pa_EndUsageCalculation( past ); + if( result != 0) + { + DBUG(("hmm, Pa_CallConvertInt16() says: %d. i'm bailing.\n", + result)); + break; + } + + /* Write data to device. */ + if( pahsc->pahsc_NativeOutputBuffer ) + { + unsigned int totalwritten = 0; + do + { + bytes_written = write(pahsc->pahsc_OutputHandle, + (void *)pahsc->pahsc_NativeOutputBuffer, + pahsc->pahsc_BytesPerOutputBuffer); + if( bytes_written < 0 ) + { + ERR_RPT(("PortAudio: write interrupted!")); + break; + } + + totalwritten += bytes_written; + } while( totalwritten < pahsc->pahsc_BytesPerOutputBuffer); + } + + Pa_UpdateStreamTime(pahsc); + } + DBUG(("Pa_AudioThreadProc: left audio loop.\n")); + + past->past_IsActive = 0; + PaHost_StopWatchDog( pahsc ); + +error: + DBUG(("leaving audio thread.\n")); +#ifdef GNUSTEP + GSUnregisterCurrentThread(); /* SB20010904 */ +#endif + return result; +} + +/************************************************************************* +** Determine minimum number of buffers required for this host based +** on minimum latency. Latency can be optionally set by user by setting +** an environment variable. For example, to set latency to 200 msec, put: +** +** set PA_MIN_LATENCY_MSEC=200 +** +** in the cshrc file. +*/ +#define PA_LATENCY_ENV_NAME ("PA_MIN_LATENCY_MSEC") + +int Pa_GetMinNumBuffers( int framesPerBuffer, double framesPerSecond ) +{ + int minBuffers; + int minLatencyMsec = MIN_LATENCY_MSEC; + char *minLatencyText = getenv(PA_LATENCY_ENV_NAME); + if( minLatencyText != NULL ) + { + PRINT(("PA_MIN_LATENCY_MSEC = %s\n", minLatencyText )); + minLatencyMsec = atoi( minLatencyText ); + if( minLatencyMsec < 1 ) minLatencyMsec = 1; + else if( minLatencyMsec > 5000 ) minLatencyMsec = 5000; + } + + minBuffers = (int) ((minLatencyMsec * framesPerSecond) / ( 1000.0 * framesPerBuffer )); + if( minBuffers < 2 ) minBuffers = 2; + return minBuffers; +} + +/*******************************************************************/ +PaError PaHost_OpenStream( internalPortAudioStream *past ) +{ + PaError result = paNoError; + PaHostSoundControl *pahsc; + unsigned int minNumBuffers; + internalPortAudioDevice *pad; + DBUG(("PaHost_OpenStream() called.\n" )); + + /* Allocate and initialize host data. */ + pahsc = (PaHostSoundControl *) malloc(sizeof(PaHostSoundControl)); + if( pahsc == NULL ) + { + result = paInsufficientMemory; + goto error; + } + memset( pahsc, 0, sizeof(PaHostSoundControl) ); + past->past_DeviceData = (void *) pahsc; + + pahsc->pahsc_OutputHandle = BAD_DEVICE_ID; /* No device currently opened. */ + pahsc->pahsc_InputHandle = BAD_DEVICE_ID; + pahsc->pahsc_IsAudioThreadValid = 0; + pahsc->pahsc_IsWatchDogThreadValid = 0; + + /* Allocate native buffers. */ + pahsc->pahsc_BytesPerInputBuffer = past->past_FramesPerUserBuffer * + past->past_NumInputChannels * sizeof(short); + if( past->past_NumInputChannels > 0) + { + pahsc->pahsc_NativeInputBuffer = (short *) malloc(pahsc->pahsc_BytesPerInputBuffer); + if( pahsc->pahsc_NativeInputBuffer == NULL ) + { + result = paInsufficientMemory; + goto error; + } + } + pahsc->pahsc_BytesPerOutputBuffer = past->past_FramesPerUserBuffer * + past->past_NumOutputChannels * sizeof(short); + if( past->past_NumOutputChannels > 0) + { + pahsc->pahsc_NativeOutputBuffer = (short *) malloc(pahsc->pahsc_BytesPerOutputBuffer); + if( pahsc->pahsc_NativeOutputBuffer == NULL ) + { + result = paInsufficientMemory; + goto error; + } + } + + /* DBUG(("PaHost_OpenStream: pahsc_MinFramesPerHostBuffer = %d\n", pahsc->pahsc_MinFramesPerHostBuffer )); */ + minNumBuffers = Pa_GetMinNumBuffers( past->past_FramesPerUserBuffer, past->past_SampleRate ); + past->past_NumUserBuffers = ( minNumBuffers > past->past_NumUserBuffers ) ? minNumBuffers : past->past_NumUserBuffers; + + pahsc->pahsc_InverseMicrosPerBuffer = past->past_SampleRate / (1000000.0 * past->past_FramesPerUserBuffer); + DBUG(("past_SampleRate = %g\n", past->past_SampleRate )); + DBUG(("past_FramesPerUserBuffer = %d\n", past->past_FramesPerUserBuffer )); + DBUG(("pahsc_InverseMicrosPerBuffer = %g\n", pahsc->pahsc_InverseMicrosPerBuffer )); + + /* ------------------------- OPEN DEVICE -----------------------*/ + + /* just output */ + if (past->past_OutputDeviceID == past->past_InputDeviceID) + { + + if ((past->past_NumOutputChannels > 0) && (past->past_NumInputChannels > 0) ) + { + pad = Pa_GetInternalDevice( past->past_OutputDeviceID ); + DBUG(("PaHost_OpenStream: attempt to open %s for O_RDWR\n", pad->pad_DeviceName )); + + /* dmazzoni: test it first in nonblocking mode to + make sure the device is not busy */ + pahsc->pahsc_InputHandle = open(pad->pad_DeviceName,O_RDWR|O_NONBLOCK); + if(pahsc->pahsc_InputHandle==-1) + { + ERR_RPT(("PaHost_OpenStream: could not open %s for O_RDWR\n", pad->pad_DeviceName )); + result = paHostError; + goto error; + } + close(pahsc->pahsc_InputHandle); + + pahsc->pahsc_OutputHandle = pahsc->pahsc_InputHandle = + open(pad->pad_DeviceName,O_RDWR); + if(pahsc->pahsc_InputHandle==-1) + { + ERR_RPT(("PaHost_OpenStream: could not open %s for O_RDWR\n", pad->pad_DeviceName )); + result = paHostError; + goto error; + } + Pa_SetLatency( pahsc->pahsc_OutputHandle, + past->past_NumUserBuffers, past->past_FramesPerUserBuffer, + past->past_NumOutputChannels ); + result = Pa_SetupDeviceFormat( pahsc->pahsc_OutputHandle, + past->past_NumOutputChannels, (int)past->past_SampleRate ); + } + } + else + { + if (past->past_NumOutputChannels > 0) + { + pad = Pa_GetInternalDevice( past->past_OutputDeviceID ); + DBUG(("PaHost_OpenStream: attempt to open %s for O_WRONLY\n", pad->pad_DeviceName )); + /* dmazzoni: test it first in nonblocking mode to + make sure the device is not busy */ + pahsc->pahsc_OutputHandle = open(pad->pad_DeviceName,O_WRONLY|O_NONBLOCK); + if(pahsc->pahsc_OutputHandle==-1) + { + ERR_RPT(("PaHost_OpenStream: could not open %s for O_WRONLY\n", pad->pad_DeviceName )); + result = paHostError; + goto error; + } + close(pahsc->pahsc_OutputHandle); + + pahsc->pahsc_OutputHandle = open(pad->pad_DeviceName,O_WRONLY); + if(pahsc->pahsc_OutputHandle==-1) + { + ERR_RPT(("PaHost_OpenStream: could not open %s for O_WRONLY\n", pad->pad_DeviceName )); + result = paHostError; + goto error; + } + Pa_SetLatency( pahsc->pahsc_OutputHandle, + past->past_NumUserBuffers, past->past_FramesPerUserBuffer, + past->past_NumOutputChannels ); + result = Pa_SetupOutputDeviceFormat( pahsc->pahsc_OutputHandle, + past->past_NumOutputChannels, (int)past->past_SampleRate ); + } + + if (past->past_NumInputChannels > 0) + { + pad = Pa_GetInternalDevice( past->past_InputDeviceID ); + DBUG(("PaHost_OpenStream: attempt to open %s for O_RDONLY\n", pad->pad_DeviceName )); + /* dmazzoni: test it first in nonblocking mode to + make sure the device is not busy */ + pahsc->pahsc_InputHandle = open(pad->pad_DeviceName,O_RDONLY|O_NONBLOCK); + if(pahsc->pahsc_InputHandle==-1) + { + ERR_RPT(("PaHost_OpenStream: could not open %s for O_RDONLY\n", pad->pad_DeviceName )); + result = paHostError; + goto error; + } + close(pahsc->pahsc_InputHandle); + + pahsc->pahsc_InputHandle = open(pad->pad_DeviceName,O_RDONLY); + if(pahsc->pahsc_InputHandle==-1) + { + ERR_RPT(("PaHost_OpenStream: could not open %s for O_RDONLY\n", pad->pad_DeviceName )); + result = paHostError; + goto error; + } + Pa_SetLatency( pahsc->pahsc_InputHandle, /* DH20010115 - was OutputHandle! */ + past->past_NumUserBuffers, past->past_FramesPerUserBuffer, + past->past_NumInputChannels ); + result = Pa_SetupInputDeviceFormat( pahsc->pahsc_InputHandle, + past->past_NumInputChannels, (int)past->past_SampleRate ); + } + } + + + DBUG(("PaHost_OpenStream: SUCCESS - result = %d\n", result )); + return result; + +error: + ERR_RPT(("PaHost_OpenStream: ERROR - result = %d\n", result )); + PaHost_CloseStream( past ); + return result; +} + +/*************************************************************************/ +PaError PaHost_StartOutput( internalPortAudioStream *past ) +{ + past = past; /* unused */ + return paNoError; +} + +/*************************************************************************/ +PaError PaHost_StartInput( internalPortAudioStream *past ) +{ + past = past; /* unused */ + return paNoError; +} + +/*************************************************************************/ +PaError PaHost_StartEngine( internalPortAudioStream *past ) +{ + PaHostSoundControl *pahsc; + PaError result = paNoError; + int hres; + + pahsc = (PaHostSoundControl *) past->past_DeviceData; + + past->past_StopSoon = 0; + past->past_StopNow = 0; + past->past_IsActive = 1; + + /* Use pthread_create() instead of __clone() because: + * - pthread_create also works for other UNIX systems like Solaris, + * - the Java HotSpot VM crashes in pthread_setcanceltype() when using __clone() + */ + hres = pthread_create(&(pahsc->pahsc_AudioThread), + NULL /*pthread_attr_t * attr*/, + (pthread_function_t)Pa_AudioThreadProc, past); + if( hres != 0 ) + { + result = paHostError; + sPaHostError = hres; + pahsc->pahsc_IsAudioThreadValid = 0; + goto error; + } + pahsc->pahsc_IsAudioThreadValid = 1; + +error: + return result; +} + +/*************************************************************************/ +PaError PaHost_StopEngine( internalPortAudioStream *past, int abort ) +{ + int hres; + PaError result = paNoError; + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + + if( pahsc == NULL ) return paNoError; + + /* Tell background thread to stop generating more data and to let current data play out. */ + past->past_StopSoon = 1; + /* If aborting, tell background thread to stop NOW! */ + if( abort ) past->past_StopNow = 1; + + /* Join thread to recover memory resources. */ + if( pahsc->pahsc_IsAudioThreadValid ) + { + /* This check is needed for GNUSTEP - SB20010904 */ + if ( !pthread_equal( pahsc->pahsc_AudioThread, pthread_self() ) ) + { + hres = pthread_join( pahsc->pahsc_AudioThread, NULL ); + } + else + { + DBUG(("Play thread was stopped from itself - can't do pthread_join()\n")); + hres = 0; + } + + if( hres != 0 ) + { + result = paHostError; + sPaHostError = hres; + } + pahsc->pahsc_IsAudioThreadValid = 0; + } + + past->past_IsActive = 0; + + return result; +} + +/*************************************************************************/ +PaError PaHost_StopInput( internalPortAudioStream *past, int abort ) +{ + past = past; /* unused */ + abort = abort; /* unused */ + return paNoError; +} + +/*************************************************************************/ +PaError PaHost_StopOutput( internalPortAudioStream *past, int abort ) +{ + past = past; /* unused */ + abort = abort; /* unused */ + return paNoError; +} + +/*******************************************************************/ +PaError PaHost_CloseStream( internalPortAudioStream *past ) +{ + PaHostSoundControl *pahsc; + + if( past == NULL ) return paBadStreamPtr; + pahsc = (PaHostSoundControl *) past->past_DeviceData; + if( pahsc == NULL ) return paNoError; + + if( pahsc->pahsc_OutputHandle != BAD_DEVICE_ID ) + { + int err = 0; + DBUG(("PaHost_CloseStream: attempt to close output device handle = %d\n", + pahsc->pahsc_OutputHandle )); + + Pa_FlushStream(pahsc->pahsc_OutputHandle); + + err = close(pahsc->pahsc_OutputHandle); + if( err < 0 ) + { + ERR_RPT(("PaHost_CloseStream: warning, closing output device failed.\n")); + } + } + + if( (pahsc->pahsc_InputHandle != BAD_DEVICE_ID) && + (pahsc->pahsc_InputHandle != pahsc->pahsc_OutputHandle) ) + { + int err = 0; + DBUG(("PaHost_CloseStream: attempt to close input device handle = %d\n", + pahsc->pahsc_InputHandle )); + + Pa_FlushStream(pahsc->pahsc_InputHandle); + + err = close(pahsc->pahsc_InputHandle); + if( err < 0 ) + { + ERR_RPT(("PaHost_CloseStream: warning, closing input device failed.\n")); + } + } + pahsc->pahsc_OutputHandle = BAD_DEVICE_ID; + pahsc->pahsc_InputHandle = BAD_DEVICE_ID; + + if( pahsc->pahsc_NativeInputBuffer ) + { + free( pahsc->pahsc_NativeInputBuffer ); + pahsc->pahsc_NativeInputBuffer = NULL; + } + if( pahsc->pahsc_NativeOutputBuffer ) + { + free( pahsc->pahsc_NativeOutputBuffer ); + pahsc->pahsc_NativeOutputBuffer = NULL; + } + + free( pahsc ); + past->past_DeviceData = NULL; + return paNoError; +} + +/*************************************************************************/ +PaError PaHost_Term( void ) +{ + /* Free all of the linked devices. */ + internalPortAudioDevice *pad, *nextPad; + pad = sDeviceList; + while( pad != NULL ) + { + nextPad = pad->pad_Next; + DBUG(("PaHost_Term: freeing %s\n", pad->pad_DeviceName )); + PaHost_FreeFastMemory( pad, sizeof(internalPortAudioDevice) ); + pad = nextPad; + } + sDeviceList = NULL; + return 0; +} + +/************************************************************************* + * Sleep for the requested number of milliseconds. + */ +void Pa_Sleep( long msec ) +{ +#if 0 + struct timeval timeout; + timeout.tv_sec = msec / 1000; + timeout.tv_usec = (msec % 1000) * 1000; + select( 0, NULL, NULL, NULL, &timeout ); +#else + long usecs = msec * 1000; + usleep( usecs ); +#endif +} + +/************************************************************************* + * Allocate memory that can be accessed in real-time. + * This may need to be held in physical memory so that it is not + * paged to virtual memory. + * This call MUST be balanced with a call to PaHost_FreeFastMemory(). + */ +void *PaHost_AllocateFastMemory( long numBytes ) +{ + void *addr = malloc( numBytes ); /* FIXME - do we need physical, wired, non-virtual memory? */ + if( addr != NULL ) memset( addr, 0, numBytes ); + return addr; +} + +/************************************************************************* + * Free memory that could be accessed in real-time. + * This call MUST be balanced with a call to PaHost_AllocateFastMemory(). + */ +void PaHost_FreeFastMemory( void *addr, long numBytes ) +{ + numBytes = numBytes; /* unused */ + if( addr != NULL ) free( addr ); +} + + +/***********************************************************************/ +PaError PaHost_StreamActive( internalPortAudioStream *past ) +{ + PaHostSoundControl *pahsc; + if( past == NULL ) return paBadStreamPtr; + pahsc = (PaHostSoundControl *) past->past_DeviceData; + if( pahsc == NULL ) return paInternalError; + return (PaError) (past->past_IsActive != 0); +} + +/***********************************************************************/ +long Pa_GetHostError( void ) +{ + return (long) sPaHostError; +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_unix_oss/pa_unix.h b/mozilla/zap/zmk/portaudio_v18_1/pa_unix_oss/pa_unix.h new file mode 100755 index 00000000000..ee339925fec --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_unix_oss/pa_unix.h @@ -0,0 +1,141 @@ +/* + * PortAudio Portable Real-Time Audio Library + * Latest Version at: http://www.portaudio.com + * Linux OSS Implementation by douglas repetto and Phil Burk + * + * Copyright (c) 1999-2000 Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +/* Modification history: + 20020621: pa_unix_oss.c split into pa_unix.c, pa_unix.h, pa_unix_oss.c by + Augustus Saunders. See pa_unix.c for previous history. */ + +/* + PROPOSED - should we add this to "portaudio.h". Problem with + Pa_QueryDevice() not having same driver name os Pa_OpenStream(). + + A PaDriverInfo structure can be passed to the underlying device + on the Pa_OpenStream() call. The contents and interpretation of + the structure is determined by the PA implementation. +*/ +typedef struct PaDriverInfo /* PROPOSED */ +{ + /* Size of structure. Allows driver to extend the structure without breaking existing applications. */ + int size; + /* Can be used to request a specific device name. */ + const char *name; + unsigned long data; +} +PaDriverInfo; + +#include +#include +//#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "portaudio.h" +#include "pa_host.h" +#include "pa_trace.h" + +#define PRINT(x) { printf x; fflush(stdout); } +#define ERR_RPT(x) PRINT(x) +#define DBUG(x) /* PRINT(x) */ +#define DBUGX(x) /* PRINT(x) */ + +#define BAD_DEVICE_ID (-1) + +#define MIN_LATENCY_MSEC (100) +#define MIN_TIMEOUT_MSEC (100) +#define MAX_TIMEOUT_MSEC (1000) + +/************************************************* Definitions ********/ +#ifdef __linux__ + #define DEVICE_NAME_BASE "/dev/dsp" +#else + #define DEVICE_NAME_BASE "/dev/audio" +#endif + +#define MAX_CHARS_DEVNAME (32) +#define MAX_SAMPLE_RATES (10) +typedef struct internalPortAudioDevice +{ + struct internalPortAudioDevice *pad_Next; /* Singly linked list. */ + double pad_SampleRates[MAX_SAMPLE_RATES]; /* for pointing to from pad_Info */ + char pad_DeviceName[MAX_CHARS_DEVNAME]; + PaDeviceInfo pad_Info; +} +internalPortAudioDevice; + +/* Define structure to contain all OSS and Linux specific data. */ +typedef struct PaHostSoundControl +{ + int pahsc_OutputHandle; + int pahsc_InputHandle; + int pahsc_AudioPriority; /* priority of background audio thread */ + pthread_t pahsc_AudioThread; /* background audio thread */ + int pahsc_IsAudioThreadValid; /* Is pahsc_AudioThread valid?*/ pid_t pahsc_AudioThreadPID; /* background audio thread */ + pthread_t pahsc_WatchDogThread; /* highest priority thread that protects system */ + int pahsc_IsWatchDogThreadValid; /* Is pahsc_WatchDogThread valid?*/ + int pahsc_WatchDogRun; /* Ask WatchDog to stop. */ + pthread_t pahsc_CanaryThread; /* low priority thread that detects abuse by audio */ + int pahsc_IsCanaryThreadValid; /* Is pahsc_CanaryThread valid?*/ + struct timeval pahsc_CanaryTime; + int pahsc_CanaryRun; /* Ask Canary to stop. */ + short *pahsc_NativeInputBuffer; + short *pahsc_NativeOutputBuffer; + unsigned int pahsc_BytesPerInputBuffer; /* native buffer size in bytes */ + unsigned int pahsc_BytesPerOutputBuffer; /* native buffer size in bytes */ + /* For measuring CPU utilization. */ + struct timeval pahsc_EntryTime; + double pahsc_InverseMicrosPerBuffer; /* 1/Microseconds of real-time audio per user buffer. */ + + /* For calculating stream time */ + int pahsc_LastPosPtr; + double pahsc_LastStreamBytes; +} +PaHostSoundControl; + +/************************************************* Prototypes **********/ + +internalPortAudioDevice *Pa_GetInternalDevice( PaDeviceID id ); +PaError Pa_QueryDevices( void ); +PaError Pa_QueryDevice( const char *deviceName, internalPortAudioDevice *pad ); +PaError Pa_SetupDeviceFormat( int devHandle, int numChannels, int sampleRate ); +PaError Pa_SetupInputDeviceFormat( int devHandle, int numChannels, int sampleRate ); +PaError Pa_SetupOutputDeviceFormat( int devHandle, int numChannels, int sampleRate ); +void Pa_SetLatency( int devHandle, int numBuffers, int framesPerBuffer, int channelsPerFrame ); +void Pa_UpdateStreamTime(PaHostSoundControl *pahsc); +int Pa_FlushStream(int devHandle); diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_unix_oss/pa_unix_oss.c b/mozilla/zap/zmk/portaudio_v18_1/pa_unix_oss/pa_unix_oss.c new file mode 100755 index 00000000000..127f0350f48 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_unix_oss/pa_unix_oss.c @@ -0,0 +1,385 @@ +/* + * PortAudio Portable Real-Time Audio Library + * Latest Version at: http://www.portaudio.com + * Linux OSS Implementation by douglas repetto and Phil Burk + * + * Copyright (c) 1999-2000 Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +/* Modification history: + 20020621: pa_unix_oss.c split into pa_unix.c, pa_unix.h, pa_unix_oss.c by + Augustus Saunders. See pa_unix.c for previous history. Pa_FlushStream + added by Augustus Saunders for Solaris compatibility. + PLB20021018 - Fill device info table with actual sample rates instead of wished for rates. + - Allow stream to open if sample rate within 10% of desired rate. + 20030630 - Thomas Richter - eliminated unused variable warnings. +*/ + +#include "pa_unix.h" + +#ifdef __linux__ +#include +#else +#include /* JH20010905 */ +#endif + + +#ifndef AFMT_S16_NE +#define AFMT_S16_NE Get_AFMT_S16_NE() +/********************************************************************* + * Some versions of OSS do not define AFMT_S16_NE. So check CPU. + * PowerPC is Big Endian. X86 is Little Endian. + */ +int Get_AFMT_S16_NE( void ) +{ + long testData = 1; + char *ptr = (char *) &testData; + int isLittle = ( *ptr == 1 ); /* Does address point to least significant byte? */ + return isLittle ? AFMT_S16_LE : AFMT_S16_BE; +} +#endif /* AFMT_S16_NE */ + + +/********************************************************************* + * Try to open the named device. + * If it opens, try to set various rates and formats and fill in + * the device info structure. + */ +PaError Pa_QueryDevice( const char *deviceName, internalPortAudioDevice *pad ) +{ + int result = paHostError; + int tempDevHandle; + int numChannels, maxNumChannels; + int format; + int numSampleRates; + int sampleRate; + int numRatesToTry; + int lastRate; + int ratesToTry[9] = {96000, 48000, 44100, 32000, 24000, 22050, 16000, 11025, 8000}; + int i; + + /* douglas: + we have to do this querying in a slightly different order. apparently + some sound cards will give you different info based on their settings. + e.g. a card might give you stereo at 22kHz but only mono at 44kHz. + the correct order for OSS is: format, channels, sample rate + + */ + if ( (tempDevHandle = open(deviceName,O_WRONLY|O_NONBLOCK)) == -1 ) + { + DBUG(("Pa_QueryDevice: could not open %s\n", deviceName )); + return paHostError; + } + + /* Ask OSS what formats are supported by the hardware. */ + pad->pad_Info.nativeSampleFormats = 0; + + if (ioctl(tempDevHandle, SNDCTL_DSP_GETFMTS, &format) == -1) + { + ERR_RPT(("Pa_QueryDevice: could not get format info\n" )); + goto error; + } + if( format & AFMT_U8 ) pad->pad_Info.nativeSampleFormats |= paUInt8; + if( format & AFMT_S16_NE ) pad->pad_Info.nativeSampleFormats |= paInt16; + + /* Negotiate for the maximum number of channels for this device. PLB20010927 + * Consider up to 16 as the upper number of channels. + * Variable numChannels should contain the actual upper limit after the call. + * Thanks to John Lazzaro and Heiko Purnhagen for suggestions. + */ + maxNumChannels = 0; + for( numChannels = 1; numChannels <= 16; numChannels++ ) + { + int temp = numChannels; + DBUG(("Pa_QueryDevice: use SNDCTL_DSP_CHANNELS, numChannels = %d\n", numChannels )) + if(ioctl(tempDevHandle, SNDCTL_DSP_CHANNELS, &temp) < 0 ) + { + /* ioctl() failed so bail out if we already have stereo */ + if( numChannels > 2 ) break; + } + else + { + /* ioctl() worked but bail out if it does not support numChannels. + * We don't want to leave gaps in the numChannels supported. + */ + if( (numChannels > 2) && (temp != numChannels) ) break; + DBUG(("Pa_QueryDevice: temp = %d\n", temp )) + if( temp > maxNumChannels ) maxNumChannels = temp; /* Save maximum. */ + } + } + + /* The above negotiation may fail for an old driver so try this older technique. */ + if( maxNumChannels < 1 ) + { + int stereo = 1; + if(ioctl(tempDevHandle, SNDCTL_DSP_STEREO, &stereo) < 0) + { + maxNumChannels = 1; + } + else + { + maxNumChannels = (stereo) ? 2 : 1; + } + DBUG(("Pa_QueryDevice: use SNDCTL_DSP_STEREO, maxNumChannels = %d\n", maxNumChannels )) + } + + pad->pad_Info.maxOutputChannels = maxNumChannels; + DBUG(("Pa_QueryDevice: maxNumChannels = %d\n", maxNumChannels)) + + /* During channel negotiation, the last ioctl() may have failed. This can + * also cause sample rate negotiation to fail. Hence the following, to return + * to a supported number of channels. SG20011005 */ + { + int temp = maxNumChannels; + if( temp > 2 ) temp = 2; /* use most reasonable default value */ + ioctl(tempDevHandle, SNDCTL_DSP_CHANNELS, &temp); + } + + /* FIXME - for now, assume maxInputChannels = maxOutputChannels. + * Eventually do separate queries for O_WRONLY and O_RDONLY + */ + pad->pad_Info.maxInputChannels = pad->pad_Info.maxOutputChannels; + + DBUG(("Pa_QueryDevice: maxInputChannels = %d\n", + pad->pad_Info.maxInputChannels)) + + + /* Determine available sample rates by trying each one and seeing result. + * OSS often supports funky rates such as 44188 instead of 44100! + */ + numSampleRates = 0; + lastRate = 0; + numRatesToTry = sizeof(ratesToTry)/sizeof(int); + for (i = 0; i < numRatesToTry; i++) + { + sampleRate = ratesToTry[i]; + + if (ioctl(tempDevHandle, SNDCTL_DSP_SPEED, &sampleRate) >= 0 ) /* PLB20010817 */ + { + /* Use whatever rate OSS tells us. PLB20021018 */ + if (sampleRate != lastRate) + { + DBUG(("Pa_QueryDevice: adding sample rate: %d\n", sampleRate)) + pad->pad_SampleRates[numSampleRates] = (float)sampleRate; + numSampleRates++; + lastRate = sampleRate; + } + else + { + DBUG(("Pa_QueryDevice: dang - got sample rate %d again!\n", sampleRate)) + } + } + } + + DBUG(("Pa_QueryDevice: final numSampleRates = %d\n", numSampleRates)) + if (numSampleRates==0) /* HP20010922 */ + { + /* Desparate attempt to keep running even though no good rates found! */ + ERR_RPT(("Pa_QueryDevice: no supported sample rate (or SNDCTL_DSP_SPEED ioctl call failed). Force 44100 Hz\n" )); + pad->pad_SampleRates[numSampleRates++] = 44100; + } + + pad->pad_Info.numSampleRates = numSampleRates; + pad->pad_Info.sampleRates = pad->pad_SampleRates; /* use pointer to embedded array */ + + pad->pad_Info.name = deviceName; + + result = paNoError; + +error: + /* We MUST close the handle here or we won't be able to reopen it later!!! */ + close(tempDevHandle); + + return result; +} + +/*******************************************************************************************/ +PaError Pa_SetupDeviceFormat( int devHandle, int numChannels, int sampleRate ) +{ + PaError result = paNoError; + int tmp; + + /* Set format, channels, and rate in this order to keep OSS happy. */ + /* Set data format. FIXME - handle more native formats. */ + tmp = AFMT_S16_NE; + if( ioctl(devHandle,SNDCTL_DSP_SETFMT,&tmp) == -1) + { + ERR_RPT(("Pa_SetupDeviceFormat: could not SNDCTL_DSP_SETFMT\n" )); + return paHostError; + } + if( tmp != AFMT_S16_NE ) + { + ERR_RPT(("Pa_SetupDeviceFormat: HW does not support AFMT_S16_NE\n" )); + return paHostError; + } + + + /* Set number of channels. */ + tmp = numChannels; + if (ioctl(devHandle, SNDCTL_DSP_CHANNELS, &numChannels) == -1) + { + ERR_RPT(("Pa_SetupDeviceFormat: could not SNDCTL_DSP_CHANNELS\n" )); + return paHostError; + } + if( tmp != numChannels) + { + ERR_RPT(("Pa_SetupDeviceFormat: HW does not support %d channels\n", numChannels )); + return paHostError; + } + + /* Set playing frequency. */ + tmp = sampleRate; + if( ioctl(devHandle,SNDCTL_DSP_SPEED,&tmp) == -1) + { + ERR_RPT(("Pa_SetupDeviceFormat: could not SNDCTL_DSP_SPEED\n" )); + return paHostError; + } + else if( tmp != sampleRate ) + { + int percentError = abs( (100 * (sampleRate - tmp)) / sampleRate ); + PRINT(("Pa_SetupDeviceFormat: warning - requested sample rate = %d Hz - closest = %d\n", + sampleRate, tmp )); + /* Allow sample rate within 10% off of requested rate. PLB20021018 + * Sometimes OSS uses a funky rate like 44188 instead of 44100. + */ + if( percentError > 10 ) + { + ERR_RPT(("Pa_SetupDeviceFormat: HW does not support %d Hz sample rate\n",sampleRate )); + return paHostError; + } + } + + return result; +} + +PaError Pa_SetupOutputDeviceFormat( int devHandle, int numChannels, int sampleRate ) +{ + return Pa_SetupDeviceFormat(devHandle, numChannels, sampleRate); +} + +PaError Pa_SetupInputDeviceFormat( int devHandle, int numChannels, int sampleRate ) +{ + return Pa_SetupDeviceFormat(devHandle, numChannels, sampleRate); +} + + +/******************************************************************************************* +** Set number of fragments and size of fragments to achieve desired latency. +*/ + +static int CalcHigherLogTwo( int n ) +{ + int log2 = 0; + while( (1< 8 ) + { + numBuffers = (numBuffers + 1) >> 1; + framesPerBuffer = framesPerBuffer << 1; + } + + /* calculate size of buffers in bytes */ + bufferSize = framesPerBuffer * channelsPerFrame * sizeof(short); /* FIXME - other sizes? */ + + /* Calculate next largest power of two */ + powerOfTwo = CalcHigherLogTwo( bufferSize ); + DBUG(("Pa_SetLatency: numBuffers = %d, framesPerBuffer = %d, powerOfTwo = %d\n", + numBuffers, framesPerBuffer, powerOfTwo )); + + /* Encode info into a single int */ + tmp=(numBuffers<<16) + powerOfTwo; + + if(ioctl(devHandle,SNDCTL_DSP_SETFRAGMENT,&tmp) == -1) + { + ERR_RPT(("Pa_SetLatency: could not SNDCTL_DSP_SETFRAGMENT\n" )); + /* Don't return an error. Best to just continue and hope for the best. */ + ERR_RPT(("Pa_SetLatency: numBuffers = %d, framesPerBuffer = %d, powerOfTwo = %d\n", + numBuffers, framesPerBuffer, powerOfTwo )); + } +} + +/***********************************************************************/ +PaTimestamp Pa_StreamTime( PortAudioStream *stream ) +{ + internalPortAudioStream *past = (internalPortAudioStream *) stream; + PaHostSoundControl *pahsc; + + count_info info; + int delta; + + if( past == NULL ) return paBadStreamPtr; + + pahsc = (PaHostSoundControl *) past->past_DeviceData; + + if( pahsc->pahsc_NativeOutputBuffer ) + { + ioctl(pahsc->pahsc_OutputHandle, SNDCTL_DSP_GETOPTR, &info); + delta = (info.bytes - pahsc->pahsc_LastPosPtr) & 0x000FFFFF; + return (pahsc->pahsc_LastStreamBytes + delta) / (past->past_NumOutputChannels * sizeof(short)); + } + else + { + ioctl(pahsc->pahsc_InputHandle, SNDCTL_DSP_GETIPTR, &info); + delta = (info.bytes - pahsc->pahsc_LastPosPtr) & 0x000FFFFF; + return (pahsc->pahsc_LastStreamBytes + delta) / (past->past_NumInputChannels * sizeof(short)); + } +} + +void Pa_UpdateStreamTime(PaHostSoundControl *pahsc) +{ + count_info info; + int delta; + + /* Update current stream time (using a double so that + we don't wrap around like info.bytes does) */ + if( pahsc->pahsc_NativeOutputBuffer ) + { + ioctl(pahsc->pahsc_OutputHandle, SNDCTL_DSP_GETOPTR, &info); + } + else + { + ioctl(pahsc->pahsc_InputHandle, SNDCTL_DSP_GETIPTR, &info); + } + delta = (info.bytes - pahsc->pahsc_LastPosPtr) & 0x000FFFFF; + pahsc->pahsc_LastStreamBytes += delta; + pahsc->pahsc_LastPosPtr = info.bytes; +} + +PaError Pa_FlushStream(int devHandle) +{ + /* AS: This doesn't do anything under OSS; it was added for Solaris.*/ + devHandle = devHandle; /* unused */ + return paNoError; +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_unix_oss/pa_unix_solaris.c b/mozilla/zap/zmk/portaudio_v18_1/pa_unix_oss/pa_unix_solaris.c new file mode 100755 index 00000000000..ec00fe855fb --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_unix_oss/pa_unix_solaris.c @@ -0,0 +1,397 @@ +/* + * PortAudio Portable Real-Time Audio Library + * Latest Version at: http://www.portaudio.com + * Linux OSS Implementation by douglas repetto and Phil Burk + * + * Copyright (c) 1999-2000 Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +/* Modification history: + 20020621: Initial cut at Solaris modifications jointly by Sam Bayer + and Augustus Saunders. + 20030206 - Martin Rohrbach - various mods for Solaris + */ + +#define __solaris_native__ + +#include "pa_unix.h" + +/* SAM 6/2/02: Docs say we should include sys/audio.h, but + that doesn't exist pre Solaris 2.8. These headers work fine. */ + +#include +#include + +/********************************************************************* + * Try to open the named device. + * If it opens, try to set various rates and formats and fill in + * the device info structure. + */ +PaError Pa_QueryDevice( const char *deviceName, internalPortAudioDevice *pad ) +{ + int result = paHostError; + int tempDevHandle; + int numChannels, maxNumChannels; + int numSampleRates; + int sampleRate; + int numRatesToTry; + int ratesToTry[9] = {96000, 48000, 44100, 32000, 24000, 22050, 16000, 11025, 8000}; + int i; + audio_info_t solaris_info; + audio_device_t device_info; + + /* douglas: + we have to do this querying in a slightly different order. apparently + some sound cards will give you different info based on their settins. + e.g. a card might give you stereo at 22kHz but only mono at 44kHz. + the correct order for OSS is: format, channels, sample rate + + */ + /* + to check a device for it's capabilities, it's probably better to use the + equivalent "-ctl"-descriptor - MR + */ + char devname[strlen(deviceName) + 4]; + if ( (tempDevHandle = open(strcat(strcpy(devname, deviceName), "ctl"), O_WRONLY|O_NONBLOCK)) == -1 ) + { + DBUG(("Pa_QueryDevice: could not open %s\n", deviceName )); + return paHostError; + } + + /* Ask OSS what formats are supported by the hardware. */ + pad->pad_Info.nativeSampleFormats = 0; + AUDIO_INITINFO(&solaris_info); + + /* SAM 12/31/01: Sparc native does mulaw, alaw and PCM. + I think PCM is signed. */ + + for (i = 8; i <= 32; i += 8) { + solaris_info.play.precision = i; + solaris_info.play.encoding = AUDIO_ENCODING_LINEAR; + /* If there are no errors, add the format. */ + if (ioctl(tempDevHandle, AUDIO_SETINFO, &solaris_info) > -1) { + switch (i) { + case 8: + pad->pad_Info.nativeSampleFormats |= paInt8; + break; + case 16: + pad->pad_Info.nativeSampleFormats |= paInt16; + break; + case 24: + pad->pad_Info.nativeSampleFormats |= paInt24; + break; + case 32: + pad->pad_Info.nativeSampleFormats |= paInt32; + break; + } + } + } + + maxNumChannels = 0; + for( numChannels = 1; numChannels <= 16; numChannels++ ) + { + int temp = numChannels; + DBUG(("Pa_QueryDevice: use SNDCTL_DSP_CHANNELS, numChannels = %d\n", numChannels )) + AUDIO_INITINFO(&solaris_info); + solaris_info.play.channels = temp; + if (ioctl(tempDevHandle, AUDIO_SETINFO, &solaris_info) < 0) + { + /* ioctl() failed so bail out if we already have stereo */ + if( numChannels > 2 ) break; + } + else + { + /* ioctl() worked but bail out if it does not support numChannels. + * We don't want to leave gaps in the numChannels supported. + */ + if( (numChannels > 2) && (temp != numChannels) ) break; + DBUG(("Pa_QueryDevice: temp = %d\n", temp )) + if( temp > maxNumChannels ) maxNumChannels = temp; /* Save maximum. */ + } + } + + pad->pad_Info.maxOutputChannels = maxNumChannels; + DBUG(("Pa_QueryDevice: maxNumChannels = %d\n", maxNumChannels)) + + /* FIXME - for now, assume maxInputChannels = maxOutputChannels. + * Eventually do separate queries for O_WRONLY and O_RDONLY + */ + pad->pad_Info.maxInputChannels = pad->pad_Info.maxOutputChannels; + + DBUG(("Pa_QueryDevice: maxInputChannels = %d\n", + pad->pad_Info.maxInputChannels)) + + + /* Determine available sample rates by trying each one and seeing result. + */ + numSampleRates = 0; + + AUDIO_INITINFO(&solaris_info); + + numRatesToTry = sizeof(ratesToTry)/sizeof(int); + for (i = 0; i < numRatesToTry; i++) + { + sampleRate = ratesToTry[i]; + + solaris_info.play.sample_rate = sampleRate; /* AS: We opened for Write, so set play */ + if (ioctl(tempDevHandle, AUDIO_SETINFO, &solaris_info) >= 0 ) /* PLB20010817 */ + { + if (sampleRate == ratesToTry[i]) + { + DBUG(("Pa_QueryDevice: got sample rate: %d\n", sampleRate)) + pad->pad_SampleRates[numSampleRates] = (float)ratesToTry[i]; + numSampleRates++; + } + } + } + + DBUG(("Pa_QueryDevice: final numSampleRates = %d\n", numSampleRates)) + if (numSampleRates==0) /* HP20010922 */ + { + ERR_RPT(("Pa_QueryDevice: no supported sample rate (or SNDCTL_DSP_SPEED ioctl call failed).\n" )); + goto error; + } + + pad->pad_Info.numSampleRates = numSampleRates; + pad->pad_Info.sampleRates = pad->pad_SampleRates; + + /* query for the device name instead of using the filesystem-device - MR */ + if (ioctl(tempDevHandle, AUDIO_GETDEV, &device_info) == -1) { + pad->pad_Info.name = deviceName; + } else { + char *pt = (char *)PaHost_AllocateFastMemory(strlen(device_info.name)); + strcpy(pt, device_info.name); + pad->pad_Info.name = pt; + } + + result = paNoError; + +error: + /* We MUST close the handle here or we won't be able to reopen it later!!! */ + close(tempDevHandle); + + return result; +} + +/*******************************************************************************************/ + +PaError Pa_SetupInputDeviceFormat( int devHandle, int numChannels, int sampleRate ) +{ + audio_info_t solaris_info; + AUDIO_INITINFO(&solaris_info); + + /* Sam Bayer/Bryan George 1/10/02: Various folks have + reported that on Solaris Ultra II, the not-right thing + happens on read unless you make sure the audio device is + flushed. The folks who wrote the Robust Audio Tool say: + + XXX driver issue - on Ultra II's if you don't drain + * the device before reading commences then the device + * reads in blocks of 500ms irrespective of the + * blocksize set. After a minute or so it flips into the + * correct mode, but obviously this is too late to be + * useful for most apps. grrr. + */ + /* AS: And the Solaris man audio pages say you should flush before changing formats + anyway. So there you go. */ + if (Pa_FlushStream(devHandle) != paNoError) + return paHostError; + + solaris_info.record.encoding = AUDIO_ENCODING_LINEAR; + solaris_info.record.sample_rate = sampleRate; + solaris_info.record.precision = 16; + solaris_info.record.channels = numChannels; + + if (ioctl(devHandle, AUDIO_SETINFO, &solaris_info) == -1) + { + ERR_RPT(("Pa_SetupDeviceFormat: could not set audio info\n" )); + return paHostError; + } + + return paNoError; +} + +PaError Pa_SetupOutputDeviceFormat( int devHandle, int numChannels, int sampleRate ) +{ + audio_info_t solaris_info; + AUDIO_INITINFO(&solaris_info); + + /* Sam Bayer/Bryan George 1/10/02: Various folks have + reported that on Solaris Ultra II, the not-right thing + happens on read unless you make sure the audio device is + flushed. The folks who wrote the Robust Audio Tool say: + + XXX driver issue - on Ultra II's if you don't drain + * the device before reading commences then the device + * reads in blocks of 500ms irrespective of the + * blocksize set. After a minute or so it flips into the + * correct mode, but obviously this is too late to be + * useful for most apps. grrr. + */ + /* AS: And the Solaris man audio pages say you should flush before changing formats + anyway. So there you go. */ + if (Pa_FlushStream(devHandle) != paNoError) + return paHostError; + + solaris_info.play.encoding = AUDIO_ENCODING_LINEAR; + solaris_info.play.sample_rate = sampleRate; + solaris_info.play.precision = 16; + solaris_info.play.channels = numChannels; + + if (ioctl(devHandle, AUDIO_SETINFO, &solaris_info) == -1) + { + ERR_RPT(("Pa_SetupDeviceFormat: could not set audio info\n" )); + return paHostError; + } + + return paNoError; +} + +PaError Pa_SetupDeviceFormat( int devHandle, int numChannels, int sampleRate ) +{ + PaError result = paNoError; + + result = Pa_SetupOutputDeviceFormat(devHandle, numChannels, sampleRate); + if (result != paNoError) + return result; + return Pa_SetupInputDeviceFormat(devHandle, numChannels, sampleRate); +} + +/******************************************************************************************* +** Set number of fragments and size of fragments to achieve desired latency. +*/ + +static PaError Pa_Unpause(int devHandle); +static PaError Pa_PauseAndFlush(int devHandle); + +void Pa_SetLatency( int devHandle, int numBuffers, int framesPerBuffer, int channelsPerFrame ) +{ + int bufferSize; + audio_info_t solaris_info; + + /* Increase size of buffers and reduce number of buffers to reduce latency inside driver. */ + while( numBuffers > 8 ) + { + numBuffers = (numBuffers + 1) >> 1; + framesPerBuffer = framesPerBuffer << 1; + } + + /* calculate size of buffers in bytes */ + bufferSize = framesPerBuffer * channelsPerFrame * sizeof(short); /* FIXME - other sizes? */ + + DBUG(("Pa_SetLatency: numBuffers = %d, framesPerBuffer = %d\n", + numBuffers, framesPerBuffer)); + + /* SAM 6/6/02: Documentation says to pause and flush before + changing buffer size. */ + + if (Pa_PauseAndFlush(devHandle) != paNoError) { + ERR_RPT(("Pa_SetLatency: could not pause audio\n" )); + return; + } + + AUDIO_INITINFO(&solaris_info); + + /* AS: Doesn't look like solaris has multiple buffers, + so I'm being conservative and + making one buffer. Might not be what we want... */ + + solaris_info.play.buffer_size = solaris_info.record.buffer_size = bufferSize; + + if (ioctl(devHandle, AUDIO_SETINFO, &solaris_info) == -1) + { + ERR_RPT(("Pa_SetLatency: could not set audio info\n" )); + } + Pa_Unpause(devHandle); +} + +/***********************************************************************/ +PaTimestamp Pa_StreamTime( PortAudioStream *stream ) +{ + internalPortAudioStream *past = (internalPortAudioStream *) stream; + PaHostSoundControl *pahsc; + audio_info_t solaris_info; + + if( past == NULL ) return paBadStreamPtr; + + pahsc = (PaHostSoundControl *) past->past_DeviceData; + + ioctl(pahsc->pahsc_OutputHandle, AUDIO_GETINFO, &solaris_info); + return solaris_info.play.samples; +} + +void Pa_UpdateStreamTime(PaHostSoundControl *pahsc) +{ + /* AS: Don't need to do anytying for this under Solaris.*/ +} + +static PaError Pa_PauseAndFlush(int devHandle) +{ + audio_info_t solaris_info; + AUDIO_INITINFO(&solaris_info); + + solaris_info.play.pause = solaris_info.record.pause = 1; + + if (ioctl(devHandle, AUDIO_SETINFO, &solaris_info) == -1) + { + ERR_RPT(("Pa_FlushStream failed.\n")); + return paHostError; + } + + if (ioctl(devHandle, I_FLUSH, FLUSHRW) == -1) + { + ERR_RPT(("Pa_FlushStream failed.\n")); + + /* Unpause! */ + AUDIO_INITINFO(&solaris_info); + solaris_info.play.pause = solaris_info.record.pause = 0; + ioctl(devHandle, AUDIO_SETINFO, &solaris_info); + + return paHostError; + } + return paNoError; +} + +static PaError Pa_Unpause(int devHandle) +{ + audio_info_t solaris_info; + AUDIO_INITINFO(&solaris_info); + + solaris_info.play.pause = solaris_info.record.pause = 0; + + if (ioctl(devHandle, AUDIO_SETINFO, &solaris_info) == -1) + { + ERR_RPT(("Pa_FlushStream failed.\n")); + return paHostError; + } + + return paNoError; +} + +PaError Pa_FlushStream(int devHandle) +{ + PaError res = Pa_PauseAndFlush(devHandle); + if (res == paNoError) + return Pa_Unpause(devHandle); + else return res; +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_unix_oss/recplay.c b/mozilla/zap/zmk/portaudio_v18_1/pa_unix_oss/recplay.c new file mode 100755 index 00000000000..09ca01e5e19 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_unix_oss/recplay.c @@ -0,0 +1,114 @@ +/* + * recplay.c + * Phil Burk + * Minimal record and playback test. + * + */ +#include +#include +#include +#ifndef __STDC__ +/* #include */ +#endif /* __STDC__ */ +#include +#ifdef __STDC__ +#include +#else /* __STDC__ */ +#include +#endif /* __STDC__ */ +#include + +#define NUM_BYTES (64*1024) +#define BLOCK_SIZE (4*1024) + +#define AUDIO "/dev/dsp" + +char buffer[NUM_BYTES]; + +int audioDev = 0; + +main (int argc, char *argv[]) +{ + int numLeft; + char *ptr; + int num; + int samplesize; + + /********** RECORD ********************/ + /* Open audio device. */ + audioDev = open (AUDIO, O_RDONLY, 0); + if (audioDev == -1) + { + perror (AUDIO); + exit (-1); + } + + /* Set to 16 bit samples. */ + samplesize = 16; + ioctl(audioDev, SNDCTL_DSP_SAMPLESIZE, &samplesize); + if (samplesize != 16) + { + perror("Unable to set the sample size."); + exit(-1); + } + + /* Record in blocks */ + printf("Begin recording.\n"); + numLeft = NUM_BYTES; + ptr = buffer; + while( numLeft >= BLOCK_SIZE ) + { + if ( (num = read (audioDev, ptr, BLOCK_SIZE)) < 0 ) + { + perror (AUDIO); + exit (-1); + } + else + { + printf("Read %d bytes\n", num); + ptr += num; + numLeft -= num; + } + } + + close( audioDev ); + + /********** PLAYBACK ********************/ + /* Open audio device for writing. */ + audioDev = open (AUDIO, O_WRONLY, 0); + if (audioDev == -1) + { + perror (AUDIO); + exit (-1); + } + + /* Set to 16 bit samples. */ + samplesize = 16; + ioctl(audioDev, SNDCTL_DSP_SAMPLESIZE, &samplesize); + if (samplesize != 16) + { + perror("Unable to set the sample size."); + exit(-1); + } + + /* Play in blocks */ + printf("Begin playing.\n"); + numLeft = NUM_BYTES; + ptr = buffer; + while( numLeft >= BLOCK_SIZE ) + { + if ( (num = write (audioDev, ptr, BLOCK_SIZE)) < 0 ) + { + perror (AUDIO); + exit (-1); + } + else + { + printf("Wrote %d bytes\n", num); + ptr += num; + numLeft -= num; + } + } + + close( audioDev ); +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_win_ds/dsound_wrapper.c b/mozilla/zap/zmk/portaudio_v18_1/pa_win_ds/dsound_wrapper.c new file mode 100755 index 00000000000..f44c36fea38 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_win_ds/dsound_wrapper.c @@ -0,0 +1,466 @@ +/* + * $Id: dsound_wrapper.c,v 1.1.2.1 2005-08-16 20:04:18 alex%croczilla.com Exp $ + * Simplified DirectSound interface. + * + * Author: Phil Burk & Robert Marsanyi + * + * PortAudio Portable Real-Time Audio Library + * For more information see: http://www.softsynth.com/portaudio/ + * DirectSound Implementation + * Copyright (c) 1999-2000 Phil Burk & Robert Marsanyi + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +#include +#include +#include +#define INITGUID // Needed to build IID_IDirectSoundNotify. See objbase.h for info. +#include +#include +#include "dsound_wrapper.h" +#include "pa_trace.h" + +/************************************************************************************/ +void DSW_Term( DSoundWrapper *dsw ) +{ + // Cleanup the sound buffers + if (dsw->dsw_OutputBuffer) + { + IDirectSoundBuffer_Stop( dsw->dsw_OutputBuffer ); + IDirectSoundBuffer_Release( dsw->dsw_OutputBuffer ); + dsw->dsw_OutputBuffer = NULL; + } +#if SUPPORT_AUDIO_CAPTURE + if (dsw->dsw_InputBuffer) + { + IDirectSoundCaptureBuffer_Stop( dsw->dsw_InputBuffer ); + IDirectSoundCaptureBuffer_Release( dsw->dsw_InputBuffer ); + dsw->dsw_InputBuffer = NULL; + } + if (dsw->dsw_pDirectSoundCapture) + { + IDirectSoundCapture_Release( dsw->dsw_pDirectSoundCapture ); + dsw->dsw_pDirectSoundCapture = NULL; + } +#endif /* SUPPORT_AUDIO_CAPTURE */ + if (dsw->dsw_pDirectSound) + { + IDirectSound_Release( dsw->dsw_pDirectSound ); + dsw->dsw_pDirectSound = NULL; + } +} +/************************************************************************************/ +HRESULT DSW_Init( DSoundWrapper *dsw ) +{ + memset( dsw, 0, sizeof(DSoundWrapper) ); + return 0; +} +/************************************************************************************/ +HRESULT DSW_InitOutputDevice( DSoundWrapper *dsw, LPGUID lpGUID ) +{ + // Create the DS object + HRESULT hr = DirectSoundCreate( lpGUID, &dsw->dsw_pDirectSound, NULL ); + if( hr != DS_OK ) return hr; + return hr; +} + +/************************************************************************************/ +HRESULT DSW_InitOutputBuffer( DSoundWrapper *dsw, unsigned long nFrameRate, int nChannels, int bytesPerBuffer ) +{ + DWORD dwDataLen; + DWORD playCursor; + HRESULT result; + LPDIRECTSOUNDBUFFER pPrimaryBuffer; + HWND hWnd; + HRESULT hr; + WAVEFORMATEX wfFormat; + DSBUFFERDESC primaryDesc; + DSBUFFERDESC secondaryDesc; + unsigned char* pDSBuffData; + LARGE_INTEGER counterFrequency; + dsw->dsw_OutputSize = bytesPerBuffer; + dsw->dsw_OutputRunning = FALSE; + dsw->dsw_OutputUnderflows = 0; + dsw->dsw_FramesWritten = 0; + dsw->dsw_BytesPerFrame = nChannels * sizeof(short); + // We were using getForegroundWindow() but sometimes the ForegroundWindow may not be the + // applications's window. Also if that window is closed before the Buffer is closed + // then DirectSound can crash. (Thanks for Scott Patterson for reporting this.) + // So we will use GetDesktopWindow() which was suggested by Miller Puckette. + // hWnd = GetForegroundWindow(); + hWnd = GetDesktopWindow(); + // Set cooperative level to DSSCL_EXCLUSIVE so that we can get 16 bit output, 44.1 KHz. + // Exclusize also prevents unexpected sounds from other apps during a performance. + if ((hr = IDirectSound_SetCooperativeLevel( dsw->dsw_pDirectSound, + hWnd, DSSCL_EXCLUSIVE)) != DS_OK) + { + return hr; + } + // ----------------------------------------------------------------------- + // Create primary buffer and set format just so we can specify our custom format. + // Otherwise we would be stuck with the default which might be 8 bit or 22050 Hz. + // Setup the primary buffer description + ZeroMemory(&primaryDesc, sizeof(DSBUFFERDESC)); + primaryDesc.dwSize = sizeof(DSBUFFERDESC); + primaryDesc.dwFlags = DSBCAPS_PRIMARYBUFFER; // all panning, mixing, etc done by synth + primaryDesc.dwBufferBytes = 0; + primaryDesc.lpwfxFormat = NULL; + // Create the buffer + if ((result = IDirectSound_CreateSoundBuffer( dsw->dsw_pDirectSound, + &primaryDesc, &pPrimaryBuffer, NULL)) != DS_OK) return result; + // Define the buffer format + wfFormat.wFormatTag = WAVE_FORMAT_PCM; + wfFormat.nChannels = nChannels; + wfFormat.nSamplesPerSec = nFrameRate; + wfFormat.wBitsPerSample = 8 * sizeof(short); + wfFormat.nBlockAlign = wfFormat.nChannels * wfFormat.wBitsPerSample / 8; + wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign; + wfFormat.cbSize = 0; /* No extended format info. */ + // Set the primary buffer's format + if((result = IDirectSoundBuffer_SetFormat( pPrimaryBuffer, &wfFormat)) != DS_OK) return result; + // ---------------------------------------------------------------------- + // Setup the secondary buffer description + ZeroMemory(&secondaryDesc, sizeof(DSBUFFERDESC)); + secondaryDesc.dwSize = sizeof(DSBUFFERDESC); + secondaryDesc.dwFlags = DSBCAPS_GLOBALFOCUS | DSBCAPS_GETCURRENTPOSITION2; + secondaryDesc.dwBufferBytes = bytesPerBuffer; + secondaryDesc.lpwfxFormat = &wfFormat; + // Create the secondary buffer + if ((result = IDirectSound_CreateSoundBuffer( dsw->dsw_pDirectSound, + &secondaryDesc, &dsw->dsw_OutputBuffer, NULL)) != DS_OK) return result; + // Lock the DS buffer + if ((result = IDirectSoundBuffer_Lock( dsw->dsw_OutputBuffer, 0, dsw->dsw_OutputSize, (LPVOID*)&pDSBuffData, + &dwDataLen, NULL, 0, 0)) != DS_OK) return result; + // Zero the DS buffer + ZeroMemory(pDSBuffData, dwDataLen); + // Unlock the DS buffer + if ((result = IDirectSoundBuffer_Unlock( dsw->dsw_OutputBuffer, pDSBuffData, dwDataLen, NULL, 0)) != DS_OK) return result; + if( QueryPerformanceFrequency( &counterFrequency ) ) + { + int framesInBuffer = bytesPerBuffer / (nChannels * sizeof(short)); + dsw->dsw_CounterTicksPerBuffer.QuadPart = (counterFrequency.QuadPart * framesInBuffer) / nFrameRate; + AddTraceMessage("dsw_CounterTicksPerBuffer = %d\n", dsw->dsw_CounterTicksPerBuffer.LowPart ); + } + else + { + dsw->dsw_CounterTicksPerBuffer.QuadPart = 0; + } + // Let DSound set the starting write position because if we set it to zero, it looks like the + // buffer is full to begin with. This causes a long pause before sound starts when using large buffers. + hr = IDirectSoundBuffer_GetCurrentPosition( dsw->dsw_OutputBuffer, &playCursor, &dsw->dsw_WriteOffset ); + if( hr != DS_OK ) + { + return hr; + } + dsw->dsw_FramesWritten = dsw->dsw_WriteOffset / dsw->dsw_BytesPerFrame; + /* printf("DSW_InitOutputBuffer: playCursor = %d, writeCursor = %d\n", playCursor, dsw->dsw_WriteOffset ); */ + return DS_OK; +} + +/************************************************************************************/ +HRESULT DSW_StartOutput( DSoundWrapper *dsw ) +{ + HRESULT hr; + QueryPerformanceCounter( &dsw->dsw_LastPlayTime ); + dsw->dsw_LastPlayCursor = 0; + dsw->dsw_FramesPlayed = 0; + hr = IDirectSoundBuffer_SetCurrentPosition( dsw->dsw_OutputBuffer, 0 ); + if( hr != DS_OK ) + { + return hr; + } + // Start the buffer playback in a loop. + if( dsw->dsw_OutputBuffer != NULL ) + { + hr = IDirectSoundBuffer_Play( dsw->dsw_OutputBuffer, 0, 0, DSBPLAY_LOOPING ); + if( hr != DS_OK ) + { + return hr; + } + dsw->dsw_OutputRunning = TRUE; + } + + return 0; +} +/************************************************************************************/ +HRESULT DSW_StopOutput( DSoundWrapper *dsw ) +{ + // Stop the buffer playback + if( dsw->dsw_OutputBuffer != NULL ) + { + dsw->dsw_OutputRunning = FALSE; + return IDirectSoundBuffer_Stop( dsw->dsw_OutputBuffer ); + } + else return 0; +} + +/************************************************************************************/ +HRESULT DSW_QueryOutputSpace( DSoundWrapper *dsw, long *bytesEmpty ) +{ + HRESULT hr; + DWORD playCursor; + DWORD writeCursor; + long numBytesEmpty; + long playWriteGap; + // Query to see how much room is in buffer. + // Note: Even though writeCursor is not used, it must be passed to prevent DirectSound from dieing + // under WinNT. The Microsoft documentation says we can pass NULL but apparently not. + // Thanks to Max Rheiner for the fix. + hr = IDirectSoundBuffer_GetCurrentPosition( dsw->dsw_OutputBuffer, &playCursor, &writeCursor ); + if( hr != DS_OK ) + { + return hr; + } + AddTraceMessage("playCursor", playCursor); + AddTraceMessage("dsw_WriteOffset", dsw->dsw_WriteOffset); + // Determine size of gap between playIndex and WriteIndex that we cannot write into. + playWriteGap = writeCursor - playCursor; + if( playWriteGap < 0 ) playWriteGap += dsw->dsw_OutputSize; // unwrap + /* DirectSound doesn't have a large enough playCursor so we cannot detect wrap-around. */ + /* Attempt to detect playCursor wrap-around and correct it. */ + if( dsw->dsw_OutputRunning && (dsw->dsw_CounterTicksPerBuffer.QuadPart != 0) ) + { + /* How much time has elapsed since last check. */ + LARGE_INTEGER currentTime; + LARGE_INTEGER elapsedTime; + long bytesPlayed; + long bytesExpected; + long buffersWrapped; + QueryPerformanceCounter( ¤tTime ); + elapsedTime.QuadPart = currentTime.QuadPart - dsw->dsw_LastPlayTime.QuadPart; + dsw->dsw_LastPlayTime = currentTime; + /* How many bytes does DirectSound say have been played. */ + bytesPlayed = playCursor - dsw->dsw_LastPlayCursor; + if( bytesPlayed < 0 ) bytesPlayed += dsw->dsw_OutputSize; // unwrap + dsw->dsw_LastPlayCursor = playCursor; + /* Calculate how many bytes we would have expected to been played by now. */ + bytesExpected = (long) ((elapsedTime.QuadPart * dsw->dsw_OutputSize) / dsw->dsw_CounterTicksPerBuffer.QuadPart); + buffersWrapped = (bytesExpected - bytesPlayed) / dsw->dsw_OutputSize; + if( buffersWrapped > 0 ) + { + AddTraceMessage("playCursor wrapped! bytesPlayed", bytesPlayed ); + AddTraceMessage("playCursor wrapped! bytesExpected", bytesExpected ); + playCursor += (buffersWrapped * dsw->dsw_OutputSize); + bytesPlayed += (buffersWrapped * dsw->dsw_OutputSize); + } + /* Maintain frame output cursor. */ + dsw->dsw_FramesPlayed += (bytesPlayed / dsw->dsw_BytesPerFrame); + } + numBytesEmpty = playCursor - dsw->dsw_WriteOffset; + if( numBytesEmpty < 0 ) numBytesEmpty += dsw->dsw_OutputSize; // unwrap offset + /* Have we underflowed? */ + if( numBytesEmpty > (dsw->dsw_OutputSize - playWriteGap) ) + { + if( dsw->dsw_OutputRunning ) + { + dsw->dsw_OutputUnderflows += 1; + AddTraceMessage("underflow detected! numBytesEmpty", numBytesEmpty ); + } + dsw->dsw_WriteOffset = writeCursor; + numBytesEmpty = dsw->dsw_OutputSize - playWriteGap; + } + *bytesEmpty = numBytesEmpty; + return hr; +} + +/************************************************************************************/ +HRESULT DSW_ZeroEmptySpace( DSoundWrapper *dsw ) +{ + HRESULT hr; + LPBYTE lpbuf1 = NULL; + LPBYTE lpbuf2 = NULL; + DWORD dwsize1 = 0; + DWORD dwsize2 = 0; + long bytesEmpty; + hr = DSW_QueryOutputSpace( dsw, &bytesEmpty ); // updates dsw_FramesPlayed + if (hr != DS_OK) return hr; + if( bytesEmpty == 0 ) return DS_OK; + // Lock free space in the DS + hr = IDirectSoundBuffer_Lock( dsw->dsw_OutputBuffer, dsw->dsw_WriteOffset, bytesEmpty, (void **) &lpbuf1, &dwsize1, + (void **) &lpbuf2, &dwsize2, 0); + if (hr == DS_OK) + { + // Copy the buffer into the DS + ZeroMemory(lpbuf1, dwsize1); + if(lpbuf2 != NULL) + { + ZeroMemory(lpbuf2, dwsize2); + } + // Update our buffer offset and unlock sound buffer + dsw->dsw_WriteOffset = (dsw->dsw_WriteOffset + dwsize1 + dwsize2) % dsw->dsw_OutputSize; + IDirectSoundBuffer_Unlock( dsw->dsw_OutputBuffer, lpbuf1, dwsize1, lpbuf2, dwsize2); + dsw->dsw_FramesWritten += bytesEmpty / dsw->dsw_BytesPerFrame; + } + return hr; +} + +/************************************************************************************/ +HRESULT DSW_WriteBlock( DSoundWrapper *dsw, char *buf, long numBytes ) +{ + HRESULT hr; + LPBYTE lpbuf1 = NULL; + LPBYTE lpbuf2 = NULL; + DWORD dwsize1 = 0; + DWORD dwsize2 = 0; + // Lock free space in the DS + hr = IDirectSoundBuffer_Lock( dsw->dsw_OutputBuffer, dsw->dsw_WriteOffset, numBytes, (void **) &lpbuf1, &dwsize1, + (void **) &lpbuf2, &dwsize2, 0); + if (hr == DS_OK) + { + // Copy the buffer into the DS + CopyMemory(lpbuf1, buf, dwsize1); + if(lpbuf2 != NULL) + { + CopyMemory(lpbuf2, buf+dwsize1, dwsize2); + } + // Update our buffer offset and unlock sound buffer + dsw->dsw_WriteOffset = (dsw->dsw_WriteOffset + dwsize1 + dwsize2) % dsw->dsw_OutputSize; + IDirectSoundBuffer_Unlock( dsw->dsw_OutputBuffer, lpbuf1, dwsize1, lpbuf2, dwsize2); + dsw->dsw_FramesWritten += numBytes / dsw->dsw_BytesPerFrame; + } + return hr; +} + +/************************************************************************************/ +DWORD DSW_GetOutputStatus( DSoundWrapper *dsw ) +{ + DWORD status; + if (IDirectSoundBuffer_GetStatus( dsw->dsw_OutputBuffer, &status ) != DS_OK) + return( DSERR_INVALIDPARAM ); + else + return( status ); +} + +#if SUPPORT_AUDIO_CAPTURE +/* These routines are used to support audio input. + * Do NOT compile these calls when using NT4 because it does + * not support the entry points. + */ +/************************************************************************************/ +HRESULT DSW_InitInputDevice( DSoundWrapper *dsw, LPGUID lpGUID ) +{ + HRESULT hr = DirectSoundCaptureCreate( lpGUID, &dsw->dsw_pDirectSoundCapture, NULL ); + if( hr != DS_OK ) return hr; + return hr; +} +/************************************************************************************/ +HRESULT DSW_InitInputBuffer( DSoundWrapper *dsw, unsigned long nFrameRate, int nChannels, int bytesPerBuffer ) +{ + DSCBUFFERDESC captureDesc; + WAVEFORMATEX wfFormat; + HRESULT result; + // Define the buffer format + wfFormat.wFormatTag = WAVE_FORMAT_PCM; + wfFormat.nChannels = nChannels; + wfFormat.nSamplesPerSec = nFrameRate; + wfFormat.wBitsPerSample = 8 * sizeof(short); + wfFormat.nBlockAlign = wfFormat.nChannels * (wfFormat.wBitsPerSample / 8); + wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign; + wfFormat.cbSize = 0; /* No extended format info. */ + dsw->dsw_InputSize = bytesPerBuffer; + // ---------------------------------------------------------------------- + // Setup the secondary buffer description + ZeroMemory(&captureDesc, sizeof(DSCBUFFERDESC)); + captureDesc.dwSize = sizeof(DSCBUFFERDESC); + captureDesc.dwFlags = 0; + captureDesc.dwBufferBytes = bytesPerBuffer; + captureDesc.lpwfxFormat = &wfFormat; + // Create the capture buffer + if ((result = IDirectSoundCapture_CreateCaptureBuffer( dsw->dsw_pDirectSoundCapture, + &captureDesc, &dsw->dsw_InputBuffer, NULL)) != DS_OK) return result; + dsw->dsw_ReadOffset = 0; // reset last read position to start of buffer + return DS_OK; +} + +/************************************************************************************/ +HRESULT DSW_StartInput( DSoundWrapper *dsw ) +{ + // Start the buffer playback + if( dsw->dsw_InputBuffer != NULL ) + { + return IDirectSoundCaptureBuffer_Start( dsw->dsw_InputBuffer, DSCBSTART_LOOPING ); + } + else return 0; +} + +/************************************************************************************/ +HRESULT DSW_StopInput( DSoundWrapper *dsw ) +{ + // Stop the buffer playback + if( dsw->dsw_InputBuffer != NULL ) + { + return IDirectSoundCaptureBuffer_Stop( dsw->dsw_InputBuffer ); + } + else return 0; +} + +/************************************************************************************/ +HRESULT DSW_QueryInputFilled( DSoundWrapper *dsw, long *bytesFilled ) +{ + HRESULT hr; + DWORD capturePos; + DWORD readPos; + long filled; + // Query to see how much data is in buffer. + // We don't need the capture position but sometimes DirectSound doesn't handle NULLS correctly + // so let's pass a pointer just to be safe. + hr = IDirectSoundCaptureBuffer_GetCurrentPosition( dsw->dsw_InputBuffer, &capturePos, &readPos ); + if( hr != DS_OK ) + { + return hr; + } + filled = readPos - dsw->dsw_ReadOffset; + if( filled < 0 ) filled += dsw->dsw_InputSize; // unwrap offset + *bytesFilled = filled; + return hr; +} + +/************************************************************************************/ +HRESULT DSW_ReadBlock( DSoundWrapper *dsw, char *buf, long numBytes ) +{ + HRESULT hr; + LPBYTE lpbuf1 = NULL; + LPBYTE lpbuf2 = NULL; + DWORD dwsize1 = 0; + DWORD dwsize2 = 0; + // Lock free space in the DS + hr = IDirectSoundCaptureBuffer_Lock ( dsw->dsw_InputBuffer, dsw->dsw_ReadOffset, numBytes, (void **) &lpbuf1, &dwsize1, + (void **) &lpbuf2, &dwsize2, 0); + if (hr == DS_OK) + { + // Copy from DS to the buffer + CopyMemory( buf, lpbuf1, dwsize1); + if(lpbuf2 != NULL) + { + CopyMemory( buf+dwsize1, lpbuf2, dwsize2); + } + // Update our buffer offset and unlock sound buffer + dsw->dsw_ReadOffset = (dsw->dsw_ReadOffset + dwsize1 + dwsize2) % dsw->dsw_InputSize; + IDirectSoundCaptureBuffer_Unlock ( dsw->dsw_InputBuffer, lpbuf1, dwsize1, lpbuf2, dwsize2); + } + return hr; +} + +#endif /* SUPPORT_AUDIO_CAPTURE */ diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_win_ds/dsound_wrapper.h b/mozilla/zap/zmk/portaudio_v18_1/pa_win_ds/dsound_wrapper.h new file mode 100755 index 00000000000..b89b29fd86c --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_win_ds/dsound_wrapper.h @@ -0,0 +1,107 @@ +#ifndef __DSOUND_WRAPPER_H +#define __DSOUND_WRAPPER_H +/* + * $Id: dsound_wrapper.h,v 1.1.2.1 2005-08-16 20:04:18 alex%croczilla.com Exp $ + * Simplified DirectSound interface. + * + * Author: Phil Burk & Robert Marsanyi + * + * For PortAudio Portable Real-Time Audio Library + * For more information see: http://www.softsynth.com/portaudio/ + * DirectSound Implementation + * Copyright (c) 1999-2000 Phil Burk & Robert Marsanyi + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +#include // XXX include needed to fix Mozilla build +#include +#if !defined(BOOL) +#define BOOL short +#endif +#ifndef SUPPORT_AUDIO_CAPTURE +#define SUPPORT_AUDIO_CAPTURE (1) +#endif + +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#define DSW_NUM_POSITIONS (4) +#define DSW_NUM_EVENTS (5) +#define DSW_TERMINATION_EVENT (DSW_NUM_POSITIONS) + +typedef struct +{ + /* Output */ + LPDIRECTSOUND dsw_pDirectSound; + LPDIRECTSOUNDBUFFER dsw_OutputBuffer; + DWORD dsw_WriteOffset; /* last write position */ + INT dsw_OutputSize; + INT dsw_BytesPerFrame; + /* Try to detect play buffer underflows. */ + LARGE_INTEGER dsw_CounterTicksPerBuffer; /* counter ticks it should take to play a full buffer */ + LARGE_INTEGER dsw_LastPlayTime; + UINT dsw_LastPlayCursor; + UINT dsw_OutputUnderflows; + BOOL dsw_OutputRunning; + /* use double which lets us can play for several thousand years with enough precision */ + double dsw_FramesWritten; + double dsw_FramesPlayed; +#if SUPPORT_AUDIO_CAPTURE + /* Input */ + LPDIRECTSOUNDCAPTURE dsw_pDirectSoundCapture; + LPDIRECTSOUNDCAPTUREBUFFER dsw_InputBuffer; + UINT dsw_ReadOffset; /* last read position */ + UINT dsw_InputSize; +#endif /* SUPPORT_AUDIO_CAPTURE */ + +} +DSoundWrapper; +HRESULT DSW_Init( DSoundWrapper *dsw ); +void DSW_Term( DSoundWrapper *dsw ); +HRESULT DSW_InitOutputBuffer( DSoundWrapper *dsw, unsigned long nFrameRate, + int nChannels, int bufSize ); +HRESULT DSW_StartOutput( DSoundWrapper *dsw ); +HRESULT DSW_StopOutput( DSoundWrapper *dsw ); +DWORD DSW_GetOutputStatus( DSoundWrapper *dsw ); +HRESULT DSW_WriteBlock( DSoundWrapper *dsw, char *buf, long numBytes ); +HRESULT DSW_ZeroEmptySpace( DSoundWrapper *dsw ); +HRESULT DSW_QueryOutputSpace( DSoundWrapper *dsw, long *bytesEmpty ); +HRESULT DSW_Enumerate( DSoundWrapper *dsw ); + +#if SUPPORT_AUDIO_CAPTURE +HRESULT DSW_InitInputBuffer( DSoundWrapper *dsw, unsigned long nFrameRate, + int nChannels, int bufSize ); +HRESULT DSW_StartInput( DSoundWrapper *dsw ); +HRESULT DSW_StopInput( DSoundWrapper *dsw ); +HRESULT DSW_ReadBlock( DSoundWrapper *dsw, char *buf, long numBytes ); +HRESULT DSW_QueryInputFilled( DSoundWrapper *dsw, long *bytesFilled ); +#endif /* SUPPORT_AUDIO_CAPTURE */ + +#ifdef __cplusplus +} +#endif /* __cplusplus */ +#endif /* __DSOUND_WRAPPER_H */ diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_win_ds/pa_dsound.c b/mozilla/zap/zmk/portaudio_v18_1/pa_win_ds/pa_dsound.c new file mode 100755 index 00000000000..877891a0178 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_win_ds/pa_dsound.c @@ -0,0 +1,1042 @@ +/* + * $Id: pa_dsound.c,v 1.1.2.1 2005-08-16 20:04:18 alex%croczilla.com Exp $ + * PortAudio Portable Real-Time Audio Library + * Latest Version at: http://www.softsynth.com/portaudio/ + * DirectSound Implementation + * + * Copyright (c) 1999-2000 Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +/* Modifications + * 7/19/01 Mike Berry - casts for compiling with __MWERKS__ CodeWarrior + * 9/27/01 Phil Burk - use number of frames instead of real-time for CPULoad calculation. + * 4/19/02 Phil Burk - Check for Win XP for system latency calculation. + */ +/* Compiler flags: + SUPPORT_AUDIO_CAPTURE - define this flag if you want to SUPPORT_AUDIO_CAPTURE + */ + +#include +#include +#ifndef __MWERKS__ +#include +#include +#endif //__MWERKS__ +#include +#include "portaudio.h" +#include "pa_host.h" +#include "pa_trace.h" +#include "dsound_wrapper.h" + +#define PRINT(x) { printf x; fflush(stdout); } +#define ERR_RPT(x) PRINT(x) +#define DBUG(x) /* PRINT(x) */ +#define DBUGX(x) /* PRINT(x) */ + +#define PA_USE_HIGH_LATENCY (0) +#if PA_USE_HIGH_LATENCY +#define PA_WIN_9X_LATENCY (500) +#define PA_WIN_NT_LATENCY (600) +#else +#define PA_WIN_9X_LATENCY (140) +#define PA_WIN_NT_LATENCY (280) +#endif + +#define PA_WIN_WDM_LATENCY (120) + +/* Trigger an underflow for testing purposes. Should normally be (0). */ +#define PA_SIMULATE_UNDERFLOW (0) +#if PA_SIMULATE_UNDERFLOW +static gUnderCallbackCounter = 0; +#define UNDER_START_GAP (10) +#define UNDER_STOP_GAP (UNDER_START_GAP + 4) +#endif + +/************************************************* Definitions ********/ +typedef struct internalPortAudioStream internalPortAudioStream; +typedef struct internalPortAudioDevice +{ + GUID pad_GUID; + GUID *pad_lpGUID; + double pad_SampleRates[10]; /* for pointing to from pad_Info FIXME?!*/ + PaDeviceInfo pad_Info; +} +internalPortAudioDevice; + +/* Define structure to contain all DirectSound and Windows specific data. */ +typedef struct PaHostSoundControl +{ + DSoundWrapper pahsc_DSoundWrapper; + MMRESULT pahsc_TimerID; + BOOL pahsc_IfInsideCallback; /* Test for reentrancy. */ + short *pahsc_NativeBuffer; + unsigned int pahsc_BytesPerBuffer; /* native buffer size in bytes */ + double pahsc_ValidFramesWritten; + int pahsc_FramesPerDSBuffer; + /* For measuring CPU utilization. */ + LARGE_INTEGER pahsc_EntryCount; + double pahsc_InverseTicksPerUserBuffer; +} +PaHostSoundControl; + +/************************************************* Shared Data ********/ +/* FIXME - put Mutex around this shared data. */ +static int sNumDevices = 0; +static int sDeviceIndex = 0; +static internalPortAudioDevice *sDevices = NULL; +static int sDefaultInputDeviceID = paNoDevice; +static int sDefaultOutputDeviceID = paNoDevice; +static int sEnumerationError; +static int sPaHostError = 0; +/************************************************* Prototypes **********/ +static internalPortAudioDevice *Pa_GetInternalDevice( PaDeviceID id ); +static BOOL CALLBACK Pa_EnumProc(LPGUID lpGUID, + LPCTSTR lpszDesc, + LPCTSTR lpszDrvName, + LPVOID lpContext ); +static BOOL CALLBACK Pa_CountDevProc(LPGUID lpGUID, + LPCTSTR lpszDesc, + LPCTSTR lpszDrvName, + LPVOID lpContext ); +static Pa_QueryDevices( void ); +static void CALLBACK Pa_TimerCallback(UINT uID, UINT uMsg, + DWORD dwUser, DWORD dw1, DWORD dw2); + +/********************************* BEGIN CPU UTILIZATION MEASUREMENT ****/ +static void Pa_StartUsageCalculation( internalPortAudioStream *past ) +{ + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + if( pahsc == NULL ) return; + /* Query system timer for usage analysis and to prevent overuse of CPU. */ + QueryPerformanceCounter( &pahsc->pahsc_EntryCount ); +} + +static void Pa_EndUsageCalculation( internalPortAudioStream *past ) +{ + LARGE_INTEGER CurrentCount = { 0, 0 }; + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + if( pahsc == NULL ) return; + /* + ** Measure CPU utilization during this callback. Note that this calculation + ** assumes that we had the processor the whole time. + */ +#define LOWPASS_COEFFICIENT_0 (0.9) +#define LOWPASS_COEFFICIENT_1 (0.99999 - LOWPASS_COEFFICIENT_0) + if( QueryPerformanceCounter( &CurrentCount ) ) + { + LONGLONG InsideCount = CurrentCount.QuadPart - pahsc->pahsc_EntryCount.QuadPart; + double newUsage = InsideCount * pahsc->pahsc_InverseTicksPerUserBuffer; + past->past_Usage = (LOWPASS_COEFFICIENT_0 * past->past_Usage) + + (LOWPASS_COEFFICIENT_1 * newUsage); + } +} + +/****************************************** END CPU UTILIZATION *******/ +static PaError Pa_QueryDevices( void ) +{ + int numBytes; + sDefaultInputDeviceID = paNoDevice; + sDefaultOutputDeviceID = paNoDevice; + /* Enumerate once just to count devices. */ + sNumDevices = 0; // for default device + DirectSoundEnumerate( (LPDSENUMCALLBACK)Pa_CountDevProc, NULL ); +#if SUPPORT_AUDIO_CAPTURE + DirectSoundCaptureEnumerate( (LPDSENUMCALLBACK)Pa_CountDevProc, NULL ); +#endif /* SUPPORT_AUDIO_CAPTURE */ + /* Allocate structures to hold device info. */ + numBytes = sNumDevices * sizeof(internalPortAudioDevice); + sDevices = (internalPortAudioDevice *)PaHost_AllocateFastMemory( numBytes ); /* MEM */ + if( sDevices == NULL ) return paInsufficientMemory; + /* Enumerate again to fill in structures. */ + sDeviceIndex = 0; + sEnumerationError = 0; + DirectSoundEnumerate( (LPDSENUMCALLBACK)Pa_EnumProc, (void *)0 ); +#if SUPPORT_AUDIO_CAPTURE + if( sEnumerationError != paNoError ) return sEnumerationError; + sEnumerationError = 0; + DirectSoundCaptureEnumerate( (LPDSENUMCALLBACK)Pa_EnumProc, (void *)1 ); +#endif /* SUPPORT_AUDIO_CAPTURE */ + return sEnumerationError; +} +/************************************************************************************/ +long Pa_GetHostError() +{ + return sPaHostError; +} +/************************************************************************************ +** Just count devices so we know how much memory to allocate. +*/ +static BOOL CALLBACK Pa_CountDevProc(LPGUID lpGUID, + LPCTSTR lpszDesc, + LPCTSTR lpszDrvName, + LPVOID lpContext ) +{ + sNumDevices++; + return TRUE; +} +/************************************************************************************ +** Extract capabilities info from each device. +*/ +static BOOL CALLBACK Pa_EnumProc(LPGUID lpGUID, + LPCTSTR lpszDesc, + LPCTSTR lpszDrvName, + LPVOID lpContext ) +{ + HRESULT hr; + LPDIRECTSOUND lpDirectSound; +#if SUPPORT_AUDIO_CAPTURE + LPDIRECTSOUNDCAPTURE lpDirectSoundCapture; +#endif /* SUPPORT_AUDIO_CAPTURE */ + int isInput = (int) lpContext; /* Passed from Pa_CountDevices() */ + internalPortAudioDevice *pad; + + if( sDeviceIndex >= sNumDevices ) + { + sEnumerationError = paInternalError; + return FALSE; + } + pad = &sDevices[sDeviceIndex]; + /* Copy GUID to static array. Set pointer. */ + if( lpGUID == NULL ) + { + pad->pad_lpGUID = NULL; + } + else + { + memcpy( &pad->pad_GUID, lpGUID, sizeof(GUID) ); + pad->pad_lpGUID = &pad->pad_GUID; + } + pad->pad_Info.sampleRates = pad->pad_SampleRates; /* Point to array. */ + /* Allocate room for descriptive name. */ + if( lpszDesc != NULL ) + { + int len = strlen(lpszDesc); + pad->pad_Info.name = (char *)malloc( len+1 ); + if( pad->pad_Info.name == NULL ) + { + sEnumerationError = paInsufficientMemory; + return FALSE; + } + memcpy( (void *) pad->pad_Info.name, lpszDesc, len+1 ); + } +#if SUPPORT_AUDIO_CAPTURE + if( isInput ) + { + /********** Input ******************************/ + DSCCAPS caps; + if( lpGUID == NULL ) sDefaultInputDeviceID = sDeviceIndex; + hr = DirectSoundCaptureCreate( lpGUID, &lpDirectSoundCapture, NULL ); + if( hr != DS_OK ) + { + pad->pad_Info.maxInputChannels = 0; + DBUG(("Cannot create Capture for %s. Result = 0x%x\n", lpszDesc, hr )); + } + else + { + /* Query device characteristics. */ + caps.dwSize = sizeof(caps); + IDirectSoundCapture_GetCaps( lpDirectSoundCapture, &caps ); + /* printf("caps.dwFormats = 0x%x\n", caps.dwFormats ); */ + pad->pad_Info.maxInputChannels = caps.dwChannels; + /* Determine sample rates from flags. */ + if( caps.dwChannels == 2 ) + { + int index = 0; + if( caps.dwFormats & WAVE_FORMAT_1S16) pad->pad_SampleRates[index++] = 11025.0; + if( caps.dwFormats & WAVE_FORMAT_2S16) pad->pad_SampleRates[index++] = 22050.0; + if( caps.dwFormats & WAVE_FORMAT_4S16) pad->pad_SampleRates[index++] = 44100.0; + pad->pad_Info.numSampleRates = index; + } + else if( caps.dwChannels == 1 ) + { + int index = 0; + if( caps.dwFormats & WAVE_FORMAT_1M16) pad->pad_SampleRates[index++] = 11025.0; + if( caps.dwFormats & WAVE_FORMAT_2M16) pad->pad_SampleRates[index++] = 22050.0; + if( caps.dwFormats & WAVE_FORMAT_4M16) pad->pad_SampleRates[index++] = 44100.0; + pad->pad_Info.numSampleRates = index; + } + else pad->pad_Info.numSampleRates = 0; + IDirectSoundCapture_Release( lpDirectSoundCapture ); + } + } + else +#endif /* SUPPORT_AUDIO_CAPTURE */ + + { + /********** Output ******************************/ + DSCAPS caps; + if( lpGUID == NULL ) sDefaultOutputDeviceID = sDeviceIndex; + /* Create interfaces for each object. */ + hr = DirectSoundCreate( lpGUID, &lpDirectSound, NULL ); + if( hr != DS_OK ) + { + pad->pad_Info.maxOutputChannels = 0; + DBUG(("Cannot create dsound for %s. Result = 0x%x\n", lpszDesc, hr )); + } + else + { + /* Query device characteristics. */ + caps.dwSize = sizeof(caps); + IDirectSound_GetCaps( lpDirectSound, &caps ); + pad->pad_Info.maxOutputChannels = ( caps.dwFlags & DSCAPS_PRIMARYSTEREO ) ? 2 : 1; + /* Get sample rates. */ + pad->pad_SampleRates[0] = (double) caps.dwMinSecondarySampleRate; + pad->pad_SampleRates[1] = (double) caps.dwMaxSecondarySampleRate; + if( caps.dwFlags & DSCAPS_CONTINUOUSRATE ) pad->pad_Info.numSampleRates = -1; + else if( caps.dwMinSecondarySampleRate == caps.dwMaxSecondarySampleRate ) + { + if( caps.dwMinSecondarySampleRate == 0 ) + { + /* + ** On my Thinkpad 380Z, DirectSoundV6 returns min-max=0 !! + ** But it supports continuous sampling. + ** So fake range of rates, and hope it really supports it. + */ + pad->pad_SampleRates[0] = 11025.0f; + pad->pad_SampleRates[1] = 48000.0f; + pad->pad_Info.numSampleRates = -1; /* continuous range */ + + DBUG(("PA - Reported rates both zero. Setting to fake values for device #%d\n", sDeviceIndex )); + } + else + { + pad->pad_Info.numSampleRates = 1; + } + } + else if( (caps.dwMinSecondarySampleRate < 1000.0) && (caps.dwMaxSecondarySampleRate > 50000.0) ) + { + /* The EWS88MT drivers lie, lie, lie. The say they only support two rates, 100 & 100000. + ** But we know that they really support a range of rates! + ** So when we see a ridiculous set of rates, assume it is a range. + */ + pad->pad_Info.numSampleRates = -1; + DBUG(("PA - Sample rate range used instead of two odd values for device #%d\n", sDeviceIndex )); + } + else pad->pad_Info.numSampleRates = 2; + IDirectSound_Release( lpDirectSound ); + } + } + pad->pad_Info.nativeSampleFormats = paInt16; + sDeviceIndex++; + return( TRUE ); +} +/*************************************************************************/ +int Pa_CountDevices() +{ + if( sNumDevices <= 0 ) Pa_Initialize(); + return sNumDevices; +} +static internalPortAudioDevice *Pa_GetInternalDevice( PaDeviceID id ) +{ + if( (id < 0) || ( id >= Pa_CountDevices()) ) return NULL; + return &sDevices[id]; +} +/*************************************************************************/ +const PaDeviceInfo* Pa_GetDeviceInfo( PaDeviceID id ) +{ + internalPortAudioDevice *pad; + if( (id < 0) || ( id >= Pa_CountDevices()) ) return NULL; + pad = Pa_GetInternalDevice( id ); + return &pad->pad_Info ; +} +static PaError Pa_MaybeQueryDevices( void ) +{ + if( sNumDevices == 0 ) + { + return Pa_QueryDevices(); + } + return 0; +} +/************************************************************************* +** Returns recommended device ID. +** On the PC, the recommended device can be specified by the user by +** setting an environment variable. For example, to use device #1. +** +** set PA_RECOMMENDED_OUTPUT_DEVICE=1 +** +** The user should first determine the available device ID by using +** the supplied application "pa_devs". +*/ +#define PA_ENV_BUF_SIZE (32) +#define PA_REC_IN_DEV_ENV_NAME ("PA_RECOMMENDED_INPUT_DEVICE") +#define PA_REC_OUT_DEV_ENV_NAME ("PA_RECOMMENDED_OUTPUT_DEVICE") +static PaDeviceID PaHost_GetEnvDefaultDeviceID( char *envName ) +{ + DWORD hresult; + char envbuf[PA_ENV_BUF_SIZE]; + PaDeviceID recommendedID = paNoDevice; + /* Let user determine default device by setting environment variable. */ + hresult = GetEnvironmentVariable( envName, envbuf, PA_ENV_BUF_SIZE ); + if( (hresult > 0) && (hresult < PA_ENV_BUF_SIZE) ) + { + recommendedID = atoi( envbuf ); + } + return recommendedID; +} +PaDeviceID Pa_GetDefaultInputDeviceID( void ) +{ + PaError result; + result = PaHost_GetEnvDefaultDeviceID( PA_REC_IN_DEV_ENV_NAME ); + if( result < 0 ) + { + result = Pa_MaybeQueryDevices(); + if( result < 0 ) return result; + result = sDefaultInputDeviceID; + } + return result; +} +PaDeviceID Pa_GetDefaultOutputDeviceID( void ) +{ + PaError result; + result = PaHost_GetEnvDefaultDeviceID( PA_REC_OUT_DEV_ENV_NAME ); + if( result < 0 ) + { + result = Pa_MaybeQueryDevices(); + if( result < 0 ) return result; + result = sDefaultOutputDeviceID; + } + return result; +} +/********************************************************************** +** Make sure that we have queried the device capabilities. +*/ +PaError PaHost_Init( void ) +{ +#if PA_SIMULATE_UNDERFLOW + PRINT(("WARNING - Underflow Simulation Enabled - Expect a Big Glitch!!!\n")); +#endif + return Pa_MaybeQueryDevices(); +} +static PaError Pa_TimeSlice( internalPortAudioStream *past ) +{ + PaError result = 0; + long bytesEmpty = 0; + long bytesFilled = 0; + long bytesToXfer = 0; + long numChunks; + HRESULT hresult; + PaHostSoundControl *pahsc; + short *nativeBufPtr; + past->past_NumCallbacks += 1; + pahsc = (PaHostSoundControl *) past->past_DeviceData; + if( pahsc == NULL ) return paInternalError; + /* How much input data is available? */ +#if SUPPORT_AUDIO_CAPTURE + if( past->past_NumInputChannels > 0 ) + { + DSW_QueryInputFilled( &pahsc->pahsc_DSoundWrapper, &bytesFilled ); + bytesToXfer = bytesFilled; + } +#endif /* SUPPORT_AUDIO_CAPTURE */ + /* How much output room is available? */ + if( past->past_NumOutputChannels > 0 ) + { + DSW_QueryOutputSpace( &pahsc->pahsc_DSoundWrapper, &bytesEmpty ); + bytesToXfer = bytesEmpty; + } + AddTraceMessage( "bytesEmpty ", bytesEmpty ); + /* Choose smallest value if both are active. */ + if( (past->past_NumInputChannels > 0) && (past->past_NumOutputChannels > 0) ) + { + bytesToXfer = ( bytesFilled < bytesEmpty ) ? bytesFilled : bytesEmpty; + } + /* printf("bytesFilled = %d, bytesEmpty = %d, bytesToXfer = %d\n", + bytesFilled, bytesEmpty, bytesToXfer); + */ + /* Quantize to multiples of a buffer. */ + numChunks = bytesToXfer / pahsc->pahsc_BytesPerBuffer; + if( numChunks > (long)(past->past_NumUserBuffers/2) ) + { + numChunks = (long)past->past_NumUserBuffers/2; + } + else if( numChunks < 0 ) + { + numChunks = 0; + } + AddTraceMessage( "numChunks ", numChunks ); + nativeBufPtr = pahsc->pahsc_NativeBuffer; + if( numChunks > 0 ) + { + while( numChunks-- > 0 ) + { + /* Measure usage based on time to process one user buffer. */ + Pa_StartUsageCalculation( past ); +#if SUPPORT_AUDIO_CAPTURE + /* Get native data from DirectSound. */ + if( past->past_NumInputChannels > 0 ) + { + hresult = DSW_ReadBlock( &pahsc->pahsc_DSoundWrapper, (char *) nativeBufPtr, pahsc->pahsc_BytesPerBuffer ); + if( hresult < 0 ) + { + ERR_RPT(("DirectSound ReadBlock failed, hresult = 0x%x\n",hresult)); + sPaHostError = hresult; + break; + } + } +#endif /* SUPPORT_AUDIO_CAPTURE */ + /* Convert 16 bit native data to user data and call user routine. */ + result = Pa_CallConvertInt16( past, nativeBufPtr, nativeBufPtr ); + if( result != 0) break; + /* Pass native data to DirectSound. */ + if( past->past_NumOutputChannels > 0 ) + { + /* static short DEBUGHACK = 0; + DEBUGHACK += 0x0049; + nativeBufPtr[0] = DEBUGHACK; /* Make buzz to see if DirectSound still running. */ + hresult = DSW_WriteBlock( &pahsc->pahsc_DSoundWrapper, (char *) nativeBufPtr, pahsc->pahsc_BytesPerBuffer ); + if( hresult < 0 ) + { + ERR_RPT(("DirectSound WriteBlock failed, result = 0x%x\n",hresult)); + sPaHostError = hresult; + break; + } + } + Pa_EndUsageCalculation( past ); + } + } + return result; +} +/*******************************************************************/ +static void CALLBACK Pa_TimerCallback(UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2) +{ + internalPortAudioStream *past; + PaHostSoundControl *pahsc; +#if PA_SIMULATE_UNDERFLOW + gUnderCallbackCounter++; + if( (gUnderCallbackCounter >= UNDER_START_GAP) && + (gUnderCallbackCounter <= UNDER_STOP_GAP) ) + { + if( gUnderCallbackCounter == UNDER_START_GAP) + { + AddTraceMessage("Begin stall: gUnderCallbackCounter =======", gUnderCallbackCounter ); + } + if( gUnderCallbackCounter == UNDER_STOP_GAP) + { + AddTraceMessage("End stall: gUnderCallbackCounter =======", gUnderCallbackCounter ); + } + return; + } +#endif + past = (internalPortAudioStream *) dwUser; + if( past == NULL ) return; + pahsc = (PaHostSoundControl *) past->past_DeviceData; + if( pahsc == NULL ) return; + if( !pahsc->pahsc_IfInsideCallback && past->past_IsActive ) + { + if( past->past_StopNow ) + { + past->past_IsActive = 0; + } + else if( past->past_StopSoon ) + { + DSoundWrapper *dsw = &pahsc->pahsc_DSoundWrapper; + if( past->past_NumOutputChannels > 0 ) + { + DSW_ZeroEmptySpace( dsw ); + AddTraceMessage("Pa_TimerCallback: waiting - written ", (int) dsw->dsw_FramesWritten ); + AddTraceMessage("Pa_TimerCallback: waiting - played ", (int) dsw->dsw_FramesPlayed ); + /* clear past_IsActive when all sound played */ + if( dsw->dsw_FramesPlayed >= past->past_FrameCount ) + { + past->past_IsActive = 0; + } + } + else + { + past->past_IsActive = 0; + } + } + else + { + pahsc->pahsc_IfInsideCallback = 1; + if( Pa_TimeSlice( past ) != 0) /* Call time slice independant of timing method. */ + { + past->past_StopSoon = 1; + } + pahsc->pahsc_IfInsideCallback = 0; + } + } +} +/*******************************************************************/ +PaError PaHost_OpenStream( internalPortAudioStream *past ) +{ + HRESULT hr; + PaError result = paNoError; + PaHostSoundControl *pahsc; + int numBytes, maxChannels; + unsigned int minNumBuffers; + internalPortAudioDevice *pad; + DSoundWrapper *dsw; + /* Allocate and initialize host data. */ + pahsc = (PaHostSoundControl *) PaHost_AllocateFastMemory(sizeof(PaHostSoundControl)); /* MEM */ + if( pahsc == NULL ) + { + result = paInsufficientMemory; + goto error; + } + memset( pahsc, 0, sizeof(PaHostSoundControl) ); + past->past_DeviceData = (void *) pahsc; + pahsc->pahsc_TimerID = 0; + dsw = &pahsc->pahsc_DSoundWrapper; + DSW_Init( dsw ); + /* Allocate native buffer. */ + maxChannels = ( past->past_NumOutputChannels > past->past_NumInputChannels ) ? + past->past_NumOutputChannels : past->past_NumInputChannels; + pahsc->pahsc_BytesPerBuffer = past->past_FramesPerUserBuffer * maxChannels * sizeof(short); + if( maxChannels > 0 ) + { + pahsc->pahsc_NativeBuffer = (short *) PaHost_AllocateFastMemory(pahsc->pahsc_BytesPerBuffer); /* MEM */ + if( pahsc->pahsc_NativeBuffer == NULL ) + { + result = paInsufficientMemory; + goto error; + } + } + else + { + result = paInvalidChannelCount; + goto error; + } + + DBUG(("PaHost_OpenStream: pahsc_MinFramesPerHostBuffer = %d\n", pahsc->pahsc_MinFramesPerHostBuffer )); + minNumBuffers = Pa_GetMinNumBuffers( past->past_FramesPerUserBuffer, past->past_SampleRate ); + past->past_NumUserBuffers = ( minNumBuffers > past->past_NumUserBuffers ) ? minNumBuffers : past->past_NumUserBuffers; + numBytes = pahsc->pahsc_BytesPerBuffer * past->past_NumUserBuffers; + if( numBytes < DSBSIZE_MIN ) + { + result = paBufferTooSmall; + goto error; + } + if( numBytes > DSBSIZE_MAX ) + { + result = paBufferTooBig; + goto error; + } + pahsc->pahsc_FramesPerDSBuffer = past->past_FramesPerUserBuffer * past->past_NumUserBuffers; + { + int msecLatency = (int) ((pahsc->pahsc_FramesPerDSBuffer * 1000) / past->past_SampleRate); + PRINT(("PortAudio on DirectSound - Latency = %d frames, %d msec\n", pahsc->pahsc_FramesPerDSBuffer, msecLatency )); + } + /* ------------------ OUTPUT */ + if( (past->past_OutputDeviceID >= 0) && (past->past_NumOutputChannels > 0) ) + { + DBUG(("PaHost_OpenStream: deviceID = 0x%x\n", past->past_OutputDeviceID)); + pad = Pa_GetInternalDevice( past->past_OutputDeviceID ); + hr = DirectSoundCreate( pad->pad_lpGUID, &dsw->dsw_pDirectSound, NULL ); + /* If this fails, then try each output device until we find one that works. */ + if( hr != DS_OK ) + { + int i; + ERR_RPT(("Creation of requested Audio Output device '%s' failed.\n", + ((pad->pad_lpGUID == NULL) ? "Default" : pad->pad_Info.name) )); + for( i=0; ipad_Info.maxOutputChannels >= past->past_NumOutputChannels ) + { + DBUG(("Try device '%s' instead.\n", pad->pad_Info.name )); + hr = DirectSoundCreate( pad->pad_lpGUID, &dsw->dsw_pDirectSound, NULL ); + if( hr == DS_OK ) + { + ERR_RPT(("Using device '%s' instead.\n", pad->pad_Info.name )); + break; + } + } + } + } + if( hr != DS_OK ) + { + ERR_RPT(("PortAudio: DirectSoundCreate() failed!\n")); + result = paHostError; + sPaHostError = hr; + goto error; + } + hr = DSW_InitOutputBuffer( dsw, + (unsigned long) (past->past_SampleRate + 0.5), + past->past_NumOutputChannels, numBytes ); + DBUG(("DSW_InitOutputBuffer() returns %x\n", hr)); + if( hr != DS_OK ) + { + result = paHostError; + sPaHostError = hr; + goto error; + } + past->past_FrameCount = pahsc->pahsc_DSoundWrapper.dsw_FramesWritten; + } +#if SUPPORT_AUDIO_CAPTURE + /* ------------------ INPUT */ + if( (past->past_InputDeviceID >= 0) && (past->past_NumInputChannels > 0) ) + { + pad = Pa_GetInternalDevice( past->past_InputDeviceID ); + hr = DirectSoundCaptureCreate( pad->pad_lpGUID, &dsw->dsw_pDirectSoundCapture, NULL ); + /* If this fails, then try each input device until we find one that works. */ + if( hr != DS_OK ) + { + int i; + ERR_RPT(("Creation of requested Audio Capture device '%s' failed.\n", + ((pad->pad_lpGUID == NULL) ? "Default" : pad->pad_Info.name) )); + for( i=0; ipad_Info.maxInputChannels >= past->past_NumInputChannels ) + { + PRINT(("Try device '%s' instead.\n", pad->pad_Info.name )); + hr = DirectSoundCaptureCreate( pad->pad_lpGUID, &dsw->dsw_pDirectSoundCapture, NULL ); + if( hr == DS_OK ) break; + } + } + } + if( hr != DS_OK ) + { + ERR_RPT(("PortAudio: DirectSoundCaptureCreate() failed!\n")); + result = paHostError; + sPaHostError = hr; + goto error; + } + hr = DSW_InitInputBuffer( dsw, + (unsigned long) (past->past_SampleRate + 0.5), + past->past_NumInputChannels, numBytes ); + DBUG(("DSW_InitInputBuffer() returns %x\n", hr)); + if( hr != DS_OK ) + { + ERR_RPT(("PortAudio: DSW_InitInputBuffer() returns %x\n", hr)); + result = paHostError; + sPaHostError = hr; + goto error; + } + } +#endif /* SUPPORT_AUDIO_CAPTURE */ + /* Calculate scalar used in CPULoad calculation. */ + { + LARGE_INTEGER frequency; + if( QueryPerformanceFrequency( &frequency ) == 0 ) + { + pahsc->pahsc_InverseTicksPerUserBuffer = 0.0; + } + else + { + pahsc->pahsc_InverseTicksPerUserBuffer = past->past_SampleRate / + ( (double)frequency.QuadPart * past->past_FramesPerUserBuffer ); + DBUG(("pahsc_InverseTicksPerUserBuffer = %g\n", pahsc->pahsc_InverseTicksPerUserBuffer )); + } + } + return result; +error: + PaHost_CloseStream( past ); + return result; +} +/*************************************************************************/ +PaError PaHost_StartOutput( internalPortAudioStream *past ) +{ + HRESULT hr; + PaHostSoundControl *pahsc; + PaError result = paNoError; + pahsc = (PaHostSoundControl *) past->past_DeviceData; + /* Give user callback a chance to pre-fill buffer. */ + result = Pa_TimeSlice( past ); + if( result != paNoError ) return result; // FIXME - what if finished? + hr = DSW_StartOutput( &pahsc->pahsc_DSoundWrapper ); + DBUG(("PaHost_StartOutput: DSW_StartOutput returned = 0x%X.\n", hr)); + if( hr != DS_OK ) + { + result = paHostError; + sPaHostError = hr; + goto error; + } +error: + return result; +} +/*************************************************************************/ +PaError PaHost_StartInput( internalPortAudioStream *past ) +{ + PaError result = paNoError; +#if SUPPORT_AUDIO_CAPTURE + HRESULT hr; + PaHostSoundControl *pahsc; + pahsc = (PaHostSoundControl *) past->past_DeviceData; + hr = DSW_StartInput( &pahsc->pahsc_DSoundWrapper ); + DBUG(("Pa_StartStream: DSW_StartInput returned = 0x%X.\n", hr)); + if( hr != DS_OK ) + { + result = paHostError; + sPaHostError = hr; + goto error; + } +error: +#endif /* SUPPORT_AUDIO_CAPTURE */ + return result; +} +/*************************************************************************/ +PaError PaHost_StartEngine( internalPortAudioStream *past ) +{ + PaHostSoundControl *pahsc; + PaError result = paNoError; + pahsc = (PaHostSoundControl *) past->past_DeviceData; + past->past_StopNow = 0; + past->past_StopSoon = 0; + past->past_IsActive = 1; + /* Create timer that will wake us up so we can fill the DSound buffer. */ + { + int msecPerBuffer; + int resolution; + int bufsPerInterrupt; + + DBUG(("PaHost_StartEngine: past_NumUserBuffers = %d\n", past->past_NumUserBuffers)); + /* Decide how often to wake up and fill the buffers. */ + if( past->past_NumUserBuffers == 2 ) + { + /* Generate two timer interrupts per user buffer. */ + msecPerBuffer = (500 * past->past_FramesPerUserBuffer) / (int) past->past_SampleRate; + } + else + { + if ( past->past_NumUserBuffers >= 16 ) bufsPerInterrupt = past->past_NumUserBuffers/8; + else if ( past->past_NumUserBuffers >= 8 ) bufsPerInterrupt = 2; + else bufsPerInterrupt = 1; + + msecPerBuffer = 1000 * (bufsPerInterrupt * past->past_FramesPerUserBuffer) / (int) past->past_SampleRate; + + DBUG(("PaHost_StartEngine: bufsPerInterrupt = %d\n", bufsPerInterrupt)); + } + + DBUG(("PaHost_StartEngine: msecPerBuffer = %d\n", msecPerBuffer)); + + if( msecPerBuffer < 10 ) msecPerBuffer = 10; + else if( msecPerBuffer > 100 ) msecPerBuffer = 100; + DBUG(("PaHost_StartEngine: clipped msecPerBuffer = %d\n", msecPerBuffer)); + + resolution = msecPerBuffer/4; + pahsc->pahsc_TimerID = timeSetEvent( msecPerBuffer, resolution, (LPTIMECALLBACK) Pa_TimerCallback, + (DWORD) past, TIME_PERIODIC ); + } + if( pahsc->pahsc_TimerID == 0 ) + { + past->past_IsActive = 0; + result = paHostError; + sPaHostError = 0; + goto error; + } +error: + return result; +} +/*************************************************************************/ +PaError PaHost_StopEngine( internalPortAudioStream *past, int abort ) +{ + int timeoutMsec; + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + if( pahsc == NULL ) return paNoError; + if( abort ) past->past_StopNow = 1; + past->past_StopSoon = 1; + /* Set timeout at 20% beyond maximum time we might wait. */ + timeoutMsec = (int) (1200.0 * pahsc->pahsc_FramesPerDSBuffer / past->past_SampleRate); + while( past->past_IsActive && (timeoutMsec > 0) ) + { + Sleep(10); + timeoutMsec -= 10; + } + if( pahsc->pahsc_TimerID != 0 ) + { + timeKillEvent(pahsc->pahsc_TimerID); /* Stop callback timer. */ + pahsc->pahsc_TimerID = 0; + } + return paNoError; +} +/*************************************************************************/ +PaError PaHost_StopInput( internalPortAudioStream *past, int abort ) +{ +#if SUPPORT_AUDIO_CAPTURE + HRESULT hr; + PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + if( pahsc == NULL ) return paNoError; + (void) abort; + hr = DSW_StopInput( &pahsc->pahsc_DSoundWrapper ); + DBUG(("DSW_StopInput() result is %x\n", hr)); +#endif /* SUPPORT_AUDIO_CAPTURE */ + return paNoError; +} +/*************************************************************************/ +PaError PaHost_StopOutput( internalPortAudioStream *past, int abort ) +{ + HRESULT hr; + PaHostSoundControl *pahsc; + pahsc = (PaHostSoundControl *) past->past_DeviceData; + if( pahsc == NULL ) return paNoError; + (void) abort; + hr = DSW_StopOutput( &pahsc->pahsc_DSoundWrapper ); + DBUG(("DSW_StopOutput() result is %x\n", hr)); + return paNoError; +} +/*******************************************************************/ +PaError PaHost_CloseStream( internalPortAudioStream *past ) +{ + PaHostSoundControl *pahsc; + if( past == NULL ) return paBadStreamPtr; + pahsc = (PaHostSoundControl *) past->past_DeviceData; + if( pahsc == NULL ) return paNoError; + DSW_Term( &pahsc->pahsc_DSoundWrapper ); + if( pahsc->pahsc_NativeBuffer ) + { + PaHost_FreeFastMemory( pahsc->pahsc_NativeBuffer, pahsc->pahsc_BytesPerBuffer ); /* MEM */ + pahsc->pahsc_NativeBuffer = NULL; + } + PaHost_FreeFastMemory( pahsc, sizeof(PaHostSoundControl) ); /* MEM */ + past->past_DeviceData = NULL; + return paNoError; +} + +/* Set minimal latency based on whether NT or Win95. + * NT has higher latency. + */ +static int PaHost_GetMinSystemLatency( void ) +{ + int minLatencyMsec; + /* Set minimal latency based on whether NT or other OS. + * NT has higher latency. + */ + OSVERSIONINFO osvi; + osvi.dwOSVersionInfoSize = sizeof( osvi ); + GetVersionEx( &osvi ); + DBUG(("PA - PlatformId = 0x%x\n", osvi.dwPlatformId )); + DBUG(("PA - MajorVersion = 0x%x\n", osvi.dwMajorVersion )); + DBUG(("PA - MinorVersion = 0x%x\n", osvi.dwMinorVersion )); + /* Check for NT */ + if( (osvi.dwMajorVersion == 4) && (osvi.dwPlatformId == 2) ) + { + minLatencyMsec = PA_WIN_NT_LATENCY; + } + else if(osvi.dwMajorVersion >= 5) + { + minLatencyMsec = PA_WIN_WDM_LATENCY; + } + else + { + minLatencyMsec = PA_WIN_9X_LATENCY; + } + return minLatencyMsec; +} + +/************************************************************************* +** Determine minimum number of buffers required for this host based +** on minimum latency. Latency can be optionally set by user by setting +** an environment variable. For example, to set latency to 200 msec, put: +** +** set PA_MIN_LATENCY_MSEC=200 +** +** in the AUTOEXEC.BAT file and reboot. +** If the environment variable is not set, then the latency will be determined +** based on the OS. Windows NT has higher latency than Win95. +*/ +#define PA_LATENCY_ENV_NAME ("PA_MIN_LATENCY_MSEC") +int Pa_GetMinNumBuffers( int framesPerBuffer, double sampleRate ) +{ + char envbuf[PA_ENV_BUF_SIZE]; + DWORD hresult; + int minLatencyMsec = 0; + double msecPerBuffer = (1000.0 * framesPerBuffer) / sampleRate; + int minBuffers; + /* Let user determine minimal latency by setting environment variable. */ + hresult = GetEnvironmentVariable( PA_LATENCY_ENV_NAME, envbuf, PA_ENV_BUF_SIZE ); + if( (hresult > 0) && (hresult < PA_ENV_BUF_SIZE) ) + { + minLatencyMsec = atoi( envbuf ); + } + else + { + minLatencyMsec = PaHost_GetMinSystemLatency(); +#if PA_USE_HIGH_LATENCY + PRINT(("PA - Minimum Latency set to %d msec!\n", minLatencyMsec )); +#endif + + } + minBuffers = (int) (1.0 + ((double)minLatencyMsec / msecPerBuffer)); + if( minBuffers < 2 ) minBuffers = 2; + return minBuffers; +} +/*************************************************************************/ +PaError PaHost_Term( void ) +{ + int i; + /* Free names allocated during enumeration. */ + for( i=0; ipast_DeviceData; + if( pahsc == NULL ) return paInternalError; + return (PaError) (past->past_IsActive); +} +/*************************************************************************/ +PaTimestamp Pa_StreamTime( PortAudioStream *stream ) +{ + DSoundWrapper *dsw; + internalPortAudioStream *past = (internalPortAudioStream *) stream; + PaHostSoundControl *pahsc; + if( past == NULL ) return paBadStreamPtr; + pahsc = (PaHostSoundControl *) past->past_DeviceData; + dsw = &pahsc->pahsc_DSoundWrapper; + return dsw->dsw_FramesPlayed; +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_win_ds/portaudio.def b/mozilla/zap/zmk/portaudio_v18_1/pa_win_ds/portaudio.def new file mode 100755 index 00000000000..e1b8cc8b0ce --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_win_ds/portaudio.def @@ -0,0 +1,28 @@ +LIBRARY PortAudio +DESCRIPTION 'PortAudio Portable interface to audio HW' + +EXPORTS + ; Explicit exports can go here + Pa_Initialize @1 + Pa_Terminate @2 + Pa_GetHostError @3 + Pa_GetErrorText @4 + Pa_CountDevices @5 + Pa_GetDefaultInputDeviceID @6 + Pa_GetDefaultOutputDeviceID @7 + Pa_GetDeviceInfo @8 + Pa_OpenStream @9 + Pa_OpenDefaultStream @10 + Pa_CloseStream @11 + Pa_StartStream @12 + Pa_StopStream @13 + Pa_StreamActive @14 + Pa_StreamTime @15 + Pa_GetCPULoad @16 + Pa_GetMinNumBuffers @17 + Pa_Sleep @18 + + ;123456789012345678901234567890123456 + ;000000000111111111122222222223333333 + + diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_win_wmme/Makefile.cygwin b/mozilla/zap/zmk/portaudio_v18_1/pa_win_wmme/Makefile.cygwin new file mode 100755 index 00000000000..737aae70e33 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_win_wmme/Makefile.cygwin @@ -0,0 +1,34 @@ + +# Makefile for PortAudio on cygwin +# Contributed by Bill Eldridge on 6/13/2001 + +ARCH= pa_win_wmme + +TESTS:= $(wildcard pa_tests/pa*.c pa_tests/debug*.c) + +.c.o: + -gcc -c -I./pa_common $< -o $*.o + -gcc $*.o -o $*.exe -L/usr/local/lib -L$(ARCH) -lportaudio.dll -lwinmm + +all: sharedlib tests + +sharedlib: ./pa_common/pa_lib.c + gcc -c -I./pa_common pa_common/pa_lib.c -o pa_common/pa_lib.o + gcc -c -I./pa_common pa_win_wmme/pa_win_wmme.c -o pa_win_wmme/pa_win_wmme.o + dlltool --export-all --output-def pa_win_wmme/pa_lib.def pa_common/pa_lib.o pa_win_wmme/pa_win_wmme.o + gcc -shared -Wl,--enable-auto-image-base -o pa_win_wmme/portaudio.dll -Wl,--out-implib=pa_win_wmme/libportaudio.dll.a pa_win_wmme/pa_lib.def pa_common/pa_lib.o pa_win_wmme/pa_win_wmme.o -L/usr/lib/w32api -lwinmm + cp pa_win_wmme/portaudio.dll /usr/local/bin + +tests: $(TESTS:.c=.o) + +sine: + gcc -c -I./pa_common pa_tests/patest_sine.c -o pa_tests/patest_sine.o + gcc pa_tests/patest_sine.o -o pa_tests/patest_sine.exe -L/usr/local/lib -lportaudio.dll -lwinmm + +clean: + -rm ./pa_tests/*.exe + +nothing: + gcc pa_tests/patest_sine.o -L/usr/lib/w32api -L./pa_win_wmme -lportaudio.dll -lwinmm + + diff --git a/mozilla/zap/zmk/portaudio_v18_1/pa_win_wmme/pa_win_wmme.c b/mozilla/zap/zmk/portaudio_v18_1/pa_win_wmme/pa_win_wmme.c new file mode 100755 index 00000000000..6ec82e660e8 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pa_win_wmme/pa_win_wmme.c @@ -0,0 +1,1714 @@ +/* + * $Id: pa_win_wmme.c,v 1.1.2.1 2005-08-16 20:04:18 alex%croczilla.com Exp $ + * pa_win_wmme.c + * Implementation of PortAudio for Windows MultiMedia Extensions (WMME) + * + * PortAudio Portable Real-Time Audio Library + * Latest Version at: http://www.portaudio.com + * + * Authors: Ross Bencina and Phil Burk + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +/* + All memory allocations and frees are marked with MEM for quick review. +*/ + +/* Modification History: + PLB = Phil Burk + JM = Julien Maillard + RDB = Ross Bencina + PLB20010402 - sDevicePtrs now allocates based on sizeof(pointer) + PLB20010413 - check for excessive numbers of channels + PLB20010422 - apply Mike Berry's changes for CodeWarrior on PC + including condition including of memory.h, + and explicit typecasting on memory allocation + PLB20010802 - use GlobalAlloc for sDevicesPtr instead of PaHost_AllocFastMemory + PLB20010816 - pass process instead of thread to SetPriorityClass() + PLB20010927 - use number of frames instead of real-time for CPULoad calculation. + JM20020118 - prevent hung thread when buffers underflow. + PLB20020321 - detect Win XP versus NT, 9x; fix DBUG typo; removed init of CurrentCount + RDB20020411 - various renaming cleanups, factored streamData alloc and cpu usage init + RDB20020417 - stopped counting WAVE_MAPPER when there were no real devices + refactoring, renaming and fixed a few edge case bugs + PLB20020612 - added 8000.0 Hz to custom sampling rates array +*/ +#pragma warning (disable: 4115) +#include +#include +#include +#include +#include +#include +/* PLB20010422 - "memory.h" doesn't work on CodeWarrior for PC. Thanks Mike Berry for the mod. */ +#ifndef __MWERKS__ +#include +#include +#endif /* __MWERKS__ */ +#include "portaudio.h" +#include "pa_host.h" +#include "pa_trace.h" + +/************************************************* Constants ********/ +#define PA_TRACK_MEMORY (0) + +#define PA_USE_TIMER_CALLBACK (0) /* Select between two options for background task. 0=thread, 1=timer */ +/* Switches for debugging. */ +#define PA_SIMULATE_UNDERFLOW (0) /* Set to one to force an underflow of the output buffer. */ + +/* To trace program, enable TRACE_REALTIME_EVENTS in pa_trace.h */ +#define PA_TRACE_RUN (0) +#define PA_TRACE_START_STOP (1) + +#define PA_USE_HIGH_LATENCY (0) /* For debugging glitches. */ + +#if PA_USE_HIGH_LATENCY + #define PA_MIN_MSEC_PER_HOST_BUFFER (100) + #define PA_MAX_MSEC_PER_HOST_BUFFER (300) /* Do not exceed unless user buffer exceeds */ + #define PA_MIN_NUM_HOST_BUFFERS (4) + #define PA_MAX_NUM_HOST_BUFFERS (16) /* OK to exceed if necessary */ + #define PA_WIN_9X_LATENCY (400) +#else + #define PA_MIN_MSEC_PER_HOST_BUFFER (10) + #define PA_MAX_MSEC_PER_HOST_BUFFER (100) /* Do not exceed unless user buffer exceeds */ + #define PA_MIN_NUM_HOST_BUFFERS (3) + #define PA_MAX_NUM_HOST_BUFFERS (16) /* OK to exceed if necessary */ + #define PA_WIN_9X_LATENCY (200) +#endif +#define MIN_TIMEOUT_MSEC (1000) + +/* +** Use higher latency for NT because it is even worse at real-time +** operation than Win9x. +*/ +#define PA_WIN_NT_LATENCY (PA_WIN_9X_LATENCY * 2) +#define PA_WIN_WDM_LATENCY (PA_WIN_9X_LATENCY) + +#if PA_SIMULATE_UNDERFLOW +static gUnderCallbackCounter = 0; +#define UNDER_SLEEP_AT (40) +#define UNDER_SLEEP_FOR (500) +#endif + +#define PRINT(x) { printf x; fflush(stdout); } +#define ERR_RPT(x) PRINT(x) +#define DBUG(x) /* PRINT(x) */ +#define DBUGX(x) /* PRINT(x) */ +/************************************************* Definitions ********/ +/************************************************************** + * Structure for internal host specific stream data. + * This is allocated on a per stream basis. + */ +typedef struct PaWMMEStreamData +{ + /* Input -------------- */ + HWAVEIN hWaveIn; + WAVEHDR *inputBuffers; + int currentInputBuffer; + int bytesPerHostInputBuffer; + int bytesPerUserInputBuffer; /* native buffer size in bytes */ + /* Output -------------- */ + HWAVEOUT hWaveOut; + WAVEHDR *outputBuffers; + int currentOutputBuffer; + int bytesPerHostOutputBuffer; + int bytesPerUserOutputBuffer; /* native buffer size in bytes */ + /* Run Time -------------- */ + PaTimestamp framesPlayed; + long lastPosition; /* used to track frames played. */ + /* For measuring CPU utilization. */ + LARGE_INTEGER entryCount; + double inverseTicksPerHostBuffer; + /* Init Time -------------- */ + int numHostBuffers; + int framesPerHostBuffer; + int userBuffersPerHostBuffer; + CRITICAL_SECTION streamLock; /* Mutext to prevent threads from colliding. */ + INT streamLockInited; +#if PA_USE_TIMER_CALLBACK + BOOL ifInsideCallback; /* Test for reentrancy. */ + MMRESULT timerID; +#else + HANDLE abortEvent; + int abortEventInited; + HANDLE bufferEvent; + int bufferEventInited; + HANDLE engineThread; + DWORD engineThreadID; +#endif +} +PaWMMEStreamData; +/************************************************* Shared Data ********/ +/* FIXME - put Mutex around this shared data. */ +static int sNumInputDevices = 0; +static int sNumOutputDevices = 0; +static int sNumDevices = 0; +static PaDeviceInfo **sDevicePtrs = NULL; +static int sDefaultInputDeviceID = paNoDevice; +static int sDefaultOutputDeviceID = paNoDevice; +static int sPaHostError = 0; +static const char sMapperSuffixInput[] = " - Input"; +static const char sMapperSuffixOutput[] = " - Output"; + +#if PA_TRACK_MEMORY +static int sNumAllocations = 0; +#endif + +/************************************************* Macros ********/ +/* Convert external PA ID to an internal ID that includes WAVE_MAPPER */ +#define PaDeviceIdToWinId(id) (((id) < sNumInputDevices) ? (id - 1) : (id - sNumInputDevices - 1)) +/************************************************* Prototypes **********/ + +void Pa_InitializeNumDevices( void ); +PaError Pa_AllocateDevicePtrs( void ); + +static void CALLBACK Pa_TimerCallback(UINT uID, UINT uMsg, + DWORD dwUser, DWORD dw1, DWORD dw2); +PaError PaHost_GetTotalBufferFrames( internalPortAudioStream *past ); +static PaError PaHost_UpdateStreamTime( PaWMMEStreamData *wmmeStreamData ); +static PaError PaHost_BackgroundManager( internalPortAudioStream *past ); + +static void *PaHost_AllocateTrackedMemory( long numBytes ); +static void PaHost_FreeTrackedMemory( void *addr ); + +/*******************************************************************/ +static PaError PaHost_AllocateWMMEStreamData( internalPortAudioStream *stream ) +{ + PaError result = paNoError; + PaWMMEStreamData *wmmeStreamData; + + wmmeStreamData = (PaWMMEStreamData *) PaHost_AllocateFastMemory(sizeof(PaWMMEStreamData)); /* MEM */ + if( wmmeStreamData == NULL ) + { + result = paInsufficientMemory; + goto error; + } + memset( wmmeStreamData, 0, sizeof(PaWMMEStreamData) ); + stream->past_DeviceData = (void *) wmmeStreamData; + + return result; + +error: + return result; +} + +/*******************************************************************/ +static void PaHost_FreeWMMEStreamData( internalPortAudioStream *internalStream ) +{ + PaWMMEStreamData *wmmeStreamData = (PaWMMEStreamData *) internalStream->past_DeviceData; + + PaHost_FreeFastMemory( wmmeStreamData, sizeof(PaWMMEStreamData) ); /* MEM */ + internalStream->past_DeviceData = NULL; +} +/*************************************************************************/ +static PaWMMEStreamData* PaHost_GetWMMEStreamData( internalPortAudioStream* internalStream ) +{ + PaWMMEStreamData *result = NULL; + + if( internalStream != NULL ) + { + result = (PaWMMEStreamData *) internalStream->past_DeviceData; + } + return result; +} +/********************************* BEGIN CPU UTILIZATION MEASUREMENT ****/ +/* FIXME: the cpu usage code should be factored out into a common module */ +static void Pa_InitializeCpuUsageScalar( internalPortAudioStream *stream ) +{ + PaWMMEStreamData *wmmeStreamData = (PaWMMEStreamData *) stream->past_DeviceData; + + LARGE_INTEGER frequency; + if( QueryPerformanceFrequency( &frequency ) == 0 ) + { + wmmeStreamData->inverseTicksPerHostBuffer = 0.0; + } + else + { + wmmeStreamData->inverseTicksPerHostBuffer = stream->past_SampleRate / + ( (double)frequency.QuadPart * stream->past_FramesPerUserBuffer * wmmeStreamData->userBuffersPerHostBuffer ); + DBUG(("inverseTicksPerHostBuffer = %g\n", wmmeStreamData->inverseTicksPerHostBuffer )); + } +} +static void Pa_StartUsageCalculation( internalPortAudioStream *stream ) +{ + PaWMMEStreamData *wmmeStreamData = (PaWMMEStreamData *) stream->past_DeviceData; + + if( wmmeStreamData == NULL ) return; + /* Query system timer for usage analysis and to prevent overuse of CPU. */ + QueryPerformanceCounter( &wmmeStreamData->entryCount ); +} +static void Pa_EndUsageCalculation( internalPortAudioStream *stream ) +{ + LARGE_INTEGER CurrentCount; + PaWMMEStreamData *wmmeStreamData = (PaWMMEStreamData *) stream->past_DeviceData; + + if( wmmeStreamData == NULL ) return; + /* + * Measure CPU utilization during this callback. Note that this calculation + * assumes that we had the processor the whole time. + */ +#define LOWPASS_COEFFICIENT_0 (0.9) +#define LOWPASS_COEFFICIENT_1 (0.99999 - LOWPASS_COEFFICIENT_0) + if( QueryPerformanceCounter( &CurrentCount ) ) + { + LONGLONG InsideCount = CurrentCount.QuadPart - wmmeStreamData->entryCount.QuadPart; + double newUsage = InsideCount * wmmeStreamData->inverseTicksPerHostBuffer; + stream->past_Usage = (LOWPASS_COEFFICIENT_0 * stream->past_Usage) + + (LOWPASS_COEFFICIENT_1 * newUsage); + } +} +/****************************************** END CPU UTILIZATION *******/ + +static void Pa_InitializeNumDevices( void ) +{ + sNumInputDevices = waveInGetNumDevs(); + if( sNumInputDevices > 0 ) + { + sNumInputDevices += 1; /* add one extra for the WAVE_MAPPER */ + sDefaultInputDeviceID = 0; + } + else + { + sDefaultInputDeviceID = paNoDevice; + } + + sNumOutputDevices = waveOutGetNumDevs(); + if( sNumOutputDevices > 0 ) + { + sNumOutputDevices += 1; /* add one extra for the WAVE_MAPPER */ + sDefaultOutputDeviceID = sNumInputDevices; + } + else + { + sDefaultOutputDeviceID = paNoDevice; + } + + sNumDevices = sNumInputDevices + sNumOutputDevices; +} + +static PaError Pa_AllocateDevicePtrs( void ) +{ + int numBytes; + int i; + + /* Allocate structures to hold device info. */ + /* PLB20010402 - was allocating too much memory. */ + /* numBytes = sNumDevices * sizeof(PaDeviceInfo); // PLB20010402 */ + + if( sNumDevices > 0 ) + { + numBytes = sNumDevices * sizeof(PaDeviceInfo *); /* PLB20010402 */ + sDevicePtrs = (PaDeviceInfo **) PaHost_AllocateTrackedMemory( numBytes ); /* MEM */ + if( sDevicePtrs == NULL ) return paInsufficientMemory; + + for( i = 0; i < sNumDevices; i++ ) + sDevicePtrs[i] = NULL; /* RDB20020417 explicitly set each ptr to NULL */ + } + else + { + sDevicePtrs = NULL; + } + + return paNoError; +} +/*************************************************************************/ +long Pa_GetHostError() +{ + return sPaHostError; +} +/*************************************************************************/ +int Pa_CountDevices() +{ + if( PaHost_IsInitialized() ) + return sNumDevices; + else + return 0; +} +/************************************************************************* + * If a PaDeviceInfo structure has not already been created, + * then allocate one and fill it in for the selected device. + * + * We create one extra input and one extra output device for the WAVE_MAPPER. + * [Does anyone know how to query the default device and get its name?] + */ +const PaDeviceInfo* Pa_GetDeviceInfo( PaDeviceID id ) +{ +#define NUM_STANDARDSAMPLINGRATES 3 /* 11025, 22050, 44100 */ + static DWORD customSamplingRates[] = { 8000, 32000, 48000, 64000, 88200, 96000 }; +#define NUM_CUSTOMSAMPLINGRATES (sizeof(customSamplingRates)/sizeof(DWORD)) +#define MAX_NUMSAMPLINGRATES (NUM_STANDARDSAMPLINGRATES+NUM_CUSTOMSAMPLINGRATES) + + PaDeviceInfo *deviceInfo; + double *sampleRates; /* non-const ptr */ + int i; + char *s; + + DBUG(( "Pa_GetDeviceInfo( %d )\n", id )); + if( id < 0 || id >= sNumDevices ) + return NULL; + if( sDevicePtrs[ id ] != NULL ) + { + return sDevicePtrs[ id ]; + } + deviceInfo = (PaDeviceInfo *)PaHost_AllocateTrackedMemory( sizeof(PaDeviceInfo) ); /* MEM */ + if( deviceInfo == NULL ) return NULL; + deviceInfo->structVersion = 1; + deviceInfo->maxInputChannels = 0; + deviceInfo->maxOutputChannels = 0; + deviceInfo->numSampleRates = 0; + sampleRates = (double*)PaHost_AllocateTrackedMemory( MAX_NUMSAMPLINGRATES * sizeof(double) ); /* MEM */ + deviceInfo->sampleRates = sampleRates; + deviceInfo->nativeSampleFormats = paInt16; /* should query for higher bit depths below */ + if( id < sNumInputDevices ) + { + /* input device */ + int inputMmID = PaDeviceIdToWinId(id); + WAVEINCAPS wic; + if( waveInGetDevCaps( inputMmID, &wic, sizeof( WAVEINCAPS ) ) != MMSYSERR_NOERROR ) + goto error; + + /* Append I/O suffix to WAVE_MAPPER device. */ + if( inputMmID == WAVE_MAPPER ) + { + s = (char *) PaHost_AllocateTrackedMemory( strlen( wic.szPname ) + 1 + sizeof(sMapperSuffixInput) ); /* MEM */ + strcpy( s, wic.szPname ); + strcat( s, sMapperSuffixInput ); + } + else + { + s = (char *) PaHost_AllocateTrackedMemory( strlen( wic.szPname ) + 1 ); /* MEM */ + strcpy( s, wic.szPname ); + } + deviceInfo->name = s; + deviceInfo->maxInputChannels = wic.wChannels; + DBUG(( "Pa_GetDeviceInfo: input %s, maxChannels = %d\n", deviceInfo->name, deviceInfo->maxInputChannels )); + /* Sometimes a device can return a rediculously large number of channels. + * This happened with an SBLive card on a Windows ME box. + * If that happens, then force it to 2 channels. PLB20010413 + */ + if( (deviceInfo->maxInputChannels < 1) || (deviceInfo->maxInputChannels > 256) ) + { + ERR_RPT(("Pa_GetDeviceInfo: Num input channels reported as %d! Changed to 2.\n", deviceInfo->maxOutputChannels )); + deviceInfo->maxInputChannels = 2; + } + /* Add a sample rate to the list if we can do stereo 16 bit at that rate + * based on the format flags. */ + if( wic.dwFormats & WAVE_FORMAT_1M16 ||wic.dwFormats & WAVE_FORMAT_1S16 ) + sampleRates[ deviceInfo->numSampleRates++ ] = 11025.; + if( wic.dwFormats & WAVE_FORMAT_2M16 ||wic.dwFormats & WAVE_FORMAT_2S16 ) + sampleRates[ deviceInfo->numSampleRates++ ] = 22050.; + if( wic.dwFormats & WAVE_FORMAT_4M16 ||wic.dwFormats & WAVE_FORMAT_4S16 ) + sampleRates[ deviceInfo->numSampleRates++ ] = 44100.; + /* Add a sample rate to the list if we can do stereo 16 bit at that rate + * based on opening the device successfully. */ + for( i=0; i < NUM_CUSTOMSAMPLINGRATES; i++ ) + { + WAVEFORMATEX wfx; + wfx.wFormatTag = WAVE_FORMAT_PCM; + wfx.nSamplesPerSec = customSamplingRates[i]; + wfx.wBitsPerSample = 16; + wfx.cbSize = 0; /* ignored */ + wfx.nChannels = (WORD)deviceInfo->maxInputChannels; + wfx.nAvgBytesPerSec = wfx.nChannels * wfx.nSamplesPerSec * sizeof(short); + wfx.nBlockAlign = (WORD)(wfx.nChannels * sizeof(short)); + if( waveInOpen( NULL, inputMmID, &wfx, 0, 0, WAVE_FORMAT_QUERY ) == MMSYSERR_NOERROR ) + { + sampleRates[ deviceInfo->numSampleRates++ ] = customSamplingRates[i]; + } + } + + } + else if( id - sNumInputDevices < sNumOutputDevices ) + { + /* output device */ + int outputMmID = PaDeviceIdToWinId(id); + WAVEOUTCAPS woc; + if( waveOutGetDevCaps( outputMmID, &woc, sizeof( WAVEOUTCAPS ) ) != MMSYSERR_NOERROR ) + goto error; + /* Append I/O suffix to WAVE_MAPPER device. */ + if( outputMmID == WAVE_MAPPER ) + { + s = (char *) PaHost_AllocateTrackedMemory( strlen( woc.szPname ) + 1 + sizeof(sMapperSuffixOutput) ); /* MEM */ + strcpy( s, woc.szPname ); + strcat( s, sMapperSuffixOutput ); + } + else + { + s = (char *) PaHost_AllocateTrackedMemory( strlen( woc.szPname ) + 1 ); /* MEM */ + strcpy( s, woc.szPname ); + } + deviceInfo->name = s; + deviceInfo->maxOutputChannels = woc.wChannels; + DBUG(( "Pa_GetDeviceInfo: output %s, maxChannels = %d\n", deviceInfo->name, deviceInfo->maxOutputChannels )); + /* Sometimes a device can return a rediculously large number of channels. + * This happened with an SBLive card on a Windows ME box. + * It also happens on Win XP! + */ + if( (deviceInfo->maxOutputChannels < 1) || (deviceInfo->maxOutputChannels > 256) ) + { +#if 1 + deviceInfo->maxOutputChannels = 2; +#else + /* If channel max is goofy, then query for max channels. PLB20020228 + * This doesn't seem to help. Disable code for now. Remove it later. + */ + ERR_RPT(("Pa_GetDeviceInfo: Num output channels reported as %d!", deviceInfo->maxOutputChannels )); + deviceInfo->maxOutputChannels = 0; + /* Attempt to find the correct maximum by querying the device. */ + for( i=2; i<16; i += 2 ) + { + WAVEFORMATEX wfx; + wfx.wFormatTag = WAVE_FORMAT_PCM; + wfx.nSamplesPerSec = 44100; + wfx.wBitsPerSample = 16; + wfx.cbSize = 0; /* ignored */ + wfx.nChannels = (WORD) i; + wfx.nAvgBytesPerSec = wfx.nChannels * wfx.nSamplesPerSec * sizeof(short); + wfx.nBlockAlign = (WORD)(wfx.nChannels * sizeof(short)); + if( waveOutOpen( NULL, outputMmID, &wfx, 0, 0, WAVE_FORMAT_QUERY ) == MMSYSERR_NOERROR ) + { + deviceInfo->maxOutputChannels = i; + } + else + { + break; + } + } +#endif + ERR_RPT((" Changed to %d.\n", deviceInfo->maxOutputChannels )); + } + + /* Add a sample rate to the list if we can do stereo 16 bit at that rate + * based on the format flags. */ + if( woc.dwFormats & WAVE_FORMAT_1M16 ||woc.dwFormats & WAVE_FORMAT_1S16 ) + sampleRates[ deviceInfo->numSampleRates++ ] = 11025.; + if( woc.dwFormats & WAVE_FORMAT_2M16 ||woc.dwFormats & WAVE_FORMAT_2S16 ) + sampleRates[ deviceInfo->numSampleRates++ ] = 22050.; + if( woc.dwFormats & WAVE_FORMAT_4M16 ||woc.dwFormats & WAVE_FORMAT_4S16 ) + sampleRates[ deviceInfo->numSampleRates++ ] = 44100.; + + /* Add a sample rate to the list if we can do stereo 16 bit at that rate + * based on opening the device successfully. */ + for( i=0; i < NUM_CUSTOMSAMPLINGRATES; i++ ) + { + WAVEFORMATEX wfx; + wfx.wFormatTag = WAVE_FORMAT_PCM; + wfx.nSamplesPerSec = customSamplingRates[i]; + wfx.wBitsPerSample = 16; + wfx.cbSize = 0; /* ignored */ + wfx.nChannels = (WORD)deviceInfo->maxOutputChannels; + wfx.nAvgBytesPerSec = wfx.nChannels * wfx.nSamplesPerSec * sizeof(short); + wfx.nBlockAlign = (WORD)(wfx.nChannels * sizeof(short)); + DBUG(( "Pa_GetDeviceInfo: waveOutOpen( ... WAVE_FORMAT_QUERY at SR = %d\n", customSamplingRates[i] )); + if( waveOutOpen( NULL, outputMmID, &wfx, 0, 0, WAVE_FORMAT_QUERY ) == MMSYSERR_NOERROR ) + { + sampleRates[ deviceInfo->numSampleRates++ ] = customSamplingRates[i]; + } + } + } + DBUG(( "Pa_GetDeviceInfo: done.\n" )); + sDevicePtrs[ id ] = deviceInfo; + return deviceInfo; + +error: + PaHost_FreeTrackedMemory( sampleRates ); /* MEM */ + PaHost_FreeTrackedMemory( deviceInfo ); /* MEM */ + + return NULL; +} +/************************************************************************* + * Returns recommended device ID. + * On the PC, the recommended device can be specified by the user by + * setting an environment variable. For example, to use device #1. + * + * set PA_RECOMMENDED_OUTPUT_DEVICE=1 + * + * The user should first determine the available device ID by using + * the supplied application "pa_devs". + */ +#define PA_ENV_BUF_SIZE (32) +#define PA_REC_IN_DEV_ENV_NAME ("PA_RECOMMENDED_INPUT_DEVICE") +#define PA_REC_OUT_DEV_ENV_NAME ("PA_RECOMMENDED_OUTPUT_DEVICE") +static PaDeviceID PaHost_GetEnvDefaultDeviceID( char *envName ) +{ + DWORD hresult; + char envbuf[PA_ENV_BUF_SIZE]; + PaDeviceID recommendedID = paNoDevice; + + /* Let user determine default device by setting environment variable. */ + hresult = GetEnvironmentVariable( envName, envbuf, PA_ENV_BUF_SIZE ); + if( (hresult > 0) && (hresult < PA_ENV_BUF_SIZE) ) + { + recommendedID = atoi( envbuf ); + } + return recommendedID; +} +/********************************************************************** + * Check for environment variable, else query devices and use result. + */ +PaDeviceID Pa_GetDefaultInputDeviceID( void ) +{ + PaDeviceID result; + + result = PaHost_GetEnvDefaultDeviceID( PA_REC_IN_DEV_ENV_NAME ); + if( result == paNoDevice || result < 0 || result >= sNumInputDevices ) + { + result = sDefaultInputDeviceID; + } + return result; +} +PaDeviceID Pa_GetDefaultOutputDeviceID( void ) +{ + PaDeviceID result; + + result = PaHost_GetEnvDefaultDeviceID( PA_REC_OUT_DEV_ENV_NAME ); + if( result == paNoDevice || result < sNumInputDevices || result >= sNumDevices ) + { + result = sDefaultOutputDeviceID; + } + return result; +} +/********************************************************************** + * Initialize Host dependant part of API. + */ +PaError PaHost_Init( void ) +{ + +#if PA_TRACK_MEMORY + PRINT(("PaHost_Init: sNumAllocations = %d\n", sNumAllocations )); +#endif + +#if PA_SIMULATE_UNDERFLOW + PRINT(("WARNING - Underflow Simulation Enabled - Expect a Big Glitch!!!\n")); +#endif + + + Pa_InitializeNumDevices(); + + return Pa_AllocateDevicePtrs(); +} + +/********************************************************************** + * Check WAVE buffers to see if they are done. + * Fill any available output buffers and use any available + * input buffers by calling user callback. + * + * This routine will loop until: + * user callback returns !=0 OR + * all output buffers are filled OR + * past->past_StopSoon is set OR + * an error occurs when calling WMME. + * + * Returns >0 when user requests a stop, <0 on error. + * + */ +static PaError Pa_TimeSlice( internalPortAudioStream *stream ) +{ + PaError result = paNoError; + MMRESULT mmresult; + char *inBufPtr; + char *outBufPtr; + int gotInput = 0; + int gotOutput = 0; + int i; + int buffersProcessed = 0; + int done = 0; + PaWMMEStreamData *wmmeStreamData = (PaWMMEStreamData *) stream->past_DeviceData; + + if( wmmeStreamData == NULL ) return paInternalError; + + stream->past_NumCallbacks += 1; +#if PA_TRACE_RUN + AddTraceMessage("Pa_TimeSlice: past_NumCallbacks ", stream->past_NumCallbacks ); +#endif + + /* JM20020118 - prevent hung thread when buffers underflow. */ + /* while( !done ) /* BAD */ + while( !done && !stream->past_StopSoon ) /* GOOD */ + { +#if PA_SIMULATE_UNDERFLOW + if(gUnderCallbackCounter++ == UNDER_SLEEP_AT) + { + Sleep(UNDER_SLEEP_FOR); + } +#endif + + /* If we are using output, then we need an empty output buffer. */ + gotOutput = 0; + outBufPtr = NULL; + if( stream->past_NumOutputChannels > 0 ) + { + if((wmmeStreamData->outputBuffers[ wmmeStreamData->currentOutputBuffer ].dwFlags & WHDR_DONE) == 0) + { + break; /* If none empty then bail and try again later. */ + } + else + { + outBufPtr = wmmeStreamData->outputBuffers[ wmmeStreamData->currentOutputBuffer ].lpData; + gotOutput = 1; + } + } + /* Use an input buffer if one is available. */ + gotInput = 0; + inBufPtr = NULL; + if( ( stream->past_NumInputChannels > 0 ) && + (wmmeStreamData->inputBuffers[ wmmeStreamData->currentInputBuffer ].dwFlags & WHDR_DONE) ) + { + inBufPtr = wmmeStreamData->inputBuffers[ wmmeStreamData->currentInputBuffer ].lpData; + gotInput = 1; +#if PA_TRACE_RUN + AddTraceMessage("Pa_TimeSlice: got input buffer at ", (int)inBufPtr ); + AddTraceMessage("Pa_TimeSlice: got input buffer # ", wmmeStreamData->currentInputBuffer ); +#endif + + } + /* If we can't do anything then bail out. */ + if( !gotInput && !gotOutput ) break; + buffersProcessed += 1; + /* Each Wave buffer contains multiple user buffers so do them all now. */ + /* Base Usage on time it took to process one host buffer. */ + Pa_StartUsageCalculation( stream ); + for( i=0; iuserBuffersPerHostBuffer; i++ ) + { + if( done ) + { + if( gotOutput ) + { + /* Clear remainder of wave buffer if we are waiting for stop. */ + AddTraceMessage("Pa_TimeSlice: zero rest of wave buffer ", i ); + memset( outBufPtr, 0, wmmeStreamData->bytesPerUserOutputBuffer ); + } + } + else + { + /* Convert 16 bit native data to user data and call user routine. */ + result = Pa_CallConvertInt16( stream, (short *) inBufPtr, (short *) outBufPtr ); + if( result != 0) done = 1; + } + if( gotInput ) inBufPtr += wmmeStreamData->bytesPerUserInputBuffer; + if( gotOutput) outBufPtr += wmmeStreamData->bytesPerUserOutputBuffer; + } + Pa_EndUsageCalculation( stream ); + /* Send WAVE buffer to Wave Device to be refilled. */ + if( gotInput ) + { + mmresult = waveInAddBuffer( wmmeStreamData->hWaveIn, + &wmmeStreamData->inputBuffers[ wmmeStreamData->currentInputBuffer ], + sizeof(WAVEHDR) ); + if( mmresult != MMSYSERR_NOERROR ) + { + sPaHostError = mmresult; + result = paHostError; + break; + } + wmmeStreamData->currentInputBuffer = (wmmeStreamData->currentInputBuffer+1 >= wmmeStreamData->numHostBuffers) ? + 0 : wmmeStreamData->currentInputBuffer+1; + } + /* Write WAVE buffer to Wave Device. */ + if( gotOutput ) + { +#if PA_TRACE_START_STOP + AddTraceMessage( "Pa_TimeSlice: writing buffer ", wmmeStreamData->currentOutputBuffer ); +#endif + mmresult = waveOutWrite( wmmeStreamData->hWaveOut, + &wmmeStreamData->outputBuffers[ wmmeStreamData->currentOutputBuffer ], + sizeof(WAVEHDR) ); + if( mmresult != MMSYSERR_NOERROR ) + { + sPaHostError = mmresult; + result = paHostError; + break; + } + wmmeStreamData->currentOutputBuffer = (wmmeStreamData->currentOutputBuffer+1 >= wmmeStreamData->numHostBuffers) ? + 0 : wmmeStreamData->currentOutputBuffer+1; + } + + } + +#if PA_TRACE_RUN + AddTraceMessage("Pa_TimeSlice: buffersProcessed ", buffersProcessed ); +#endif + return (result != 0) ? result : done; +} + +/*******************************************************************/ +static PaError PaHost_BackgroundManager( internalPortAudioStream *stream ) +{ + PaError result = paNoError; + int i; + int numQueuedoutputBuffers = 0; + PaWMMEStreamData *wmmeStreamData = (PaWMMEStreamData *) stream->past_DeviceData; + + /* Has someone asked us to abort by calling Pa_AbortStream()? */ + if( stream->past_StopNow ) + { + stream->past_IsActive = 0; /* Will cause thread to return. */ + } + /* Has someone asked us to stop by calling Pa_StopStream() + * OR has a user callback returned '1' to indicate finished. + */ + else if( stream->past_StopSoon ) + { + /* Poll buffer and when all have played then exit thread. */ + /* Count how many output buffers are queued. */ + numQueuedoutputBuffers = 0; + if( stream->past_NumOutputChannels > 0 ) + { + for( i=0; inumHostBuffers; i++ ) + { + if( !( wmmeStreamData->outputBuffers[ i ].dwFlags & WHDR_DONE) ) + { +#if PA_TRACE_START_STOP + AddTraceMessage( "PaHost_BackgroundManager: waiting for buffer ", i ); +#endif + numQueuedoutputBuffers++; + } + } + } +#if PA_TRACE_START_STOP + AddTraceMessage( "PaHost_BackgroundManager: numQueuedoutputBuffers ", numQueuedoutputBuffers ); +#endif + if( numQueuedoutputBuffers == 0 ) + { + stream->past_IsActive = 0; /* Will cause thread to return. */ + } + } + else + { + /* Process full input buffer and fill up empty output buffers. */ + if( (result = Pa_TimeSlice( stream )) != 0) + { + /* User callback has asked us to stop. */ +#if PA_TRACE_START_STOP + AddTraceMessage( "PaHost_BackgroundManager: TimeSlice() returned ", result ); +#endif + stream->past_StopSoon = 1; /* Request that audio play out then stop. */ + result = paNoError; + } + } + + PaHost_UpdateStreamTime( wmmeStreamData ); + return result; +} + +#if PA_USE_TIMER_CALLBACK +/*******************************************************************/ +static void CALLBACK Pa_TimerCallback(UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2) +{ + internalPortAudioStream *stream; + PaWMMEStreamData *wmmeStreamData; + PaError result; + + stream = (internalPortAudioStream *) dwUser; + if( stream == NULL ) return; + wmmeStreamData = (PaWMMEStreamData *) stream->past_DeviceData; + if( wmmeStreamData == NULL ) return; + if( wmmeStreamData->ifInsideCallback ) + { + if( wmmeStreamData->timerID != 0 ) + { + timeKillEvent(wmmeStreamData->timerID); /* Stop callback timer. */ + wmmeStreamData->timerID = 0; + } + return; + } + wmmeStreamData->ifInsideCallback = 1; + /* Manage flags and audio processing. */ + result = PaHost_BackgroundManager( stream ); + if( result != paNoError ) + { + stream->past_IsActive = 0; + } + wmmeStreamData->ifInsideCallback = 0; +} +#else /* PA_USE_TIMER_CALLBACK */ +/*******************************************************************/ +static DWORD WINAPI WinMMPa_OutputThreadProc( void *pArg ) +{ + internalPortAudioStream *stream; + PaWMMEStreamData *wmmeStreamData; + HANDLE events[2]; + int numEvents = 0; + DWORD result = 0; + DWORD waitResult; + DWORD numTimeouts = 0; + DWORD timeOut; + stream = (internalPortAudioStream *) pArg; + wmmeStreamData = (PaWMMEStreamData *) stream->past_DeviceData; +#if PA_TRACE_START_STOP + AddTraceMessage( "WinMMPa_OutputThreadProc: timeoutPeriod", timeoutPeriod ); + AddTraceMessage( "WinMMPa_OutputThreadProc: past_NumUserBuffers", stream->past_NumUserBuffers ); +#endif + /* Calculate timeOut as half the time it would take to play all buffers. */ + timeOut = (DWORD) (500.0 * PaHost_GetTotalBufferFrames( stream ) / stream->past_SampleRate); + /* Get event(s) ready for wait. */ + events[numEvents++] = wmmeStreamData->bufferEvent; + if( wmmeStreamData->abortEventInited ) events[numEvents++] = wmmeStreamData->abortEvent; + /* Stay in this thread as long as we are "active". */ + while( stream->past_IsActive ) + { + /*******************************************************************/ + /******** WAIT here for an event from WMME or PA *******************/ + /*******************************************************************/ + waitResult = WaitForMultipleObjects( numEvents, events, FALSE, timeOut ); + /* Error? */ + if( waitResult == WAIT_FAILED ) + { + sPaHostError = GetLastError(); + result = paHostError; + stream->past_IsActive = 0; + } + /* Timeout? Don't stop. Just keep polling for DONE.*/ + else if( waitResult == WAIT_TIMEOUT ) + { +#if PA_TRACE_START_STOP + AddTraceMessage( "WinMMPa_OutputThreadProc: timed out ", numQueuedoutputBuffers ); +#endif + numTimeouts += 1; + } + /* Manage flags and audio processing. */ + result = PaHost_BackgroundManager( stream ); + if( result != paNoError ) + { + stream->past_IsActive = 0; + } + } + return result; +} +#endif + +/*******************************************************************/ +PaError PaHost_OpenInputStream( internalPortAudioStream *stream ) +{ + PaError result = paNoError; + MMRESULT mmresult; + PaWMMEStreamData *wmmeStreamData; + int i; + int inputMmId; + int bytesPerInputFrame; + WAVEFORMATEX wfx; + const PaDeviceInfo *deviceInfo; + + wmmeStreamData = (PaWMMEStreamData *) stream->past_DeviceData; + DBUG(("PaHost_OpenStream: deviceID = 0x%x\n", stream->past_InputDeviceID)); + deviceInfo = Pa_GetDeviceInfo( stream->past_InputDeviceID ); + if( deviceInfo == NULL ) return paInternalError; + + switch( deviceInfo->nativeSampleFormats ) + { + case paInt32: + case paFloat32: + bytesPerInputFrame = sizeof(float) * stream->past_NumInputChannels; + break; + default: + bytesPerInputFrame = sizeof(short) * stream->past_NumInputChannels; + break; + } + wfx.wFormatTag = WAVE_FORMAT_PCM; + wfx.nChannels = (WORD) stream->past_NumInputChannels; + wfx.nSamplesPerSec = (DWORD) stream->past_SampleRate; + wfx.nAvgBytesPerSec = (DWORD)(bytesPerInputFrame * stream->past_SampleRate); + wfx.nBlockAlign = (WORD)bytesPerInputFrame; + wfx.wBitsPerSample = (WORD)((bytesPerInputFrame/stream->past_NumInputChannels) * 8); + wfx.cbSize = 0; + inputMmId = PaDeviceIdToWinId( stream->past_InputDeviceID ); +#if PA_USE_TIMER_CALLBACK + mmresult = waveInOpen( &wmmeStreamData->hWaveIn, inputMmId, &wfx, + 0, 0, CALLBACK_NULL ); +#else + mmresult = waveInOpen( &wmmeStreamData->hWaveIn, inputMmId, &wfx, + (DWORD)wmmeStreamData->bufferEvent, (DWORD) stream, CALLBACK_EVENT ); +#endif + if( mmresult != MMSYSERR_NOERROR ) + { + ERR_RPT(("PortAudio: PaHost_OpenInputStream() failed!\n")); + result = paHostError; + sPaHostError = mmresult; + goto error; + } + /* Allocate an array to hold the buffer pointers. */ + wmmeStreamData->inputBuffers = (WAVEHDR *) PaHost_AllocateTrackedMemory( sizeof(WAVEHDR)*wmmeStreamData->numHostBuffers ); /* MEM */ + if( wmmeStreamData->inputBuffers == NULL ) + { + result = paInsufficientMemory; + goto error; + } + /* Allocate each buffer. */ + for( i=0; inumHostBuffers; i++ ) + { + wmmeStreamData->inputBuffers[i].lpData = (char *)PaHost_AllocateTrackedMemory( wmmeStreamData->bytesPerHostInputBuffer ); /* MEM */ + if( wmmeStreamData->inputBuffers[i].lpData == NULL ) + { + result = paInsufficientMemory; + goto error; + } + wmmeStreamData->inputBuffers[i].dwBufferLength = wmmeStreamData->bytesPerHostInputBuffer; + wmmeStreamData->inputBuffers[i].dwUser = i; + if( ( mmresult = waveInPrepareHeader( wmmeStreamData->hWaveIn, &wmmeStreamData->inputBuffers[i], sizeof(WAVEHDR) )) != MMSYSERR_NOERROR ) + { + result = paHostError; + sPaHostError = mmresult; + goto error; + } + } + return result; + +error: + return result; +} +/*******************************************************************/ +PaError PaHost_OpenOutputStream( internalPortAudioStream *stream ) +{ + PaError result = paNoError; + MMRESULT mmresult; + PaWMMEStreamData *wmmeStreamData; + int i; + int outputMmID; + int bytesPerOutputFrame; + WAVEFORMATEX wfx; + const PaDeviceInfo *deviceInfo; + + wmmeStreamData = (PaWMMEStreamData *) stream->past_DeviceData; + DBUG(("PaHost_OpenStream: deviceID = 0x%x\n", stream->past_OutputDeviceID)); + + deviceInfo = Pa_GetDeviceInfo( stream->past_OutputDeviceID ); + if( deviceInfo == NULL ) return paInternalError; + + switch( deviceInfo->nativeSampleFormats ) + { + case paInt32: + case paFloat32: + bytesPerOutputFrame = sizeof(float) * stream->past_NumOutputChannels; + break; + default: + bytesPerOutputFrame = sizeof(short) * stream->past_NumOutputChannels; + break; + } + wfx.wFormatTag = WAVE_FORMAT_PCM; + wfx.nChannels = (WORD) stream->past_NumOutputChannels; + wfx.nSamplesPerSec = (DWORD) stream->past_SampleRate; + wfx.nAvgBytesPerSec = (DWORD)(bytesPerOutputFrame * stream->past_SampleRate); + wfx.nBlockAlign = (WORD)bytesPerOutputFrame; + wfx.wBitsPerSample = (WORD)((bytesPerOutputFrame/stream->past_NumOutputChannels) * 8); + wfx.cbSize = 0; + outputMmID = PaDeviceIdToWinId( stream->past_OutputDeviceID ); +#if PA_USE_TIMER_CALLBACK + mmresult = waveOutOpen( &wmmeStreamData->hWaveOut, outputMmID, &wfx, + 0, 0, CALLBACK_NULL ); +#else + + wmmeStreamData->abortEvent = CreateEvent( NULL, TRUE, FALSE, NULL ); + if( wmmeStreamData->abortEvent == NULL ) + { + result = paHostError; + sPaHostError = GetLastError(); + goto error; + } + wmmeStreamData->abortEventInited = 1; + mmresult = waveOutOpen( &wmmeStreamData->hWaveOut, outputMmID, &wfx, + (DWORD)wmmeStreamData->bufferEvent, (DWORD) stream, CALLBACK_EVENT ); +#endif + if( mmresult != MMSYSERR_NOERROR ) + { + ERR_RPT(("PortAudio: PaHost_OpenOutputStream() failed!\n")); + result = paHostError; + sPaHostError = mmresult; + goto error; + } + /* Allocate an array to hold the buffer pointers. */ + wmmeStreamData->outputBuffers = (WAVEHDR *) PaHost_AllocateTrackedMemory( sizeof(WAVEHDR)*wmmeStreamData->numHostBuffers ); /* MEM */ + if( wmmeStreamData->outputBuffers == NULL ) + { + result = paInsufficientMemory; + goto error; + } + /* Allocate each buffer. */ + for( i=0; inumHostBuffers; i++ ) + { + wmmeStreamData->outputBuffers[i].lpData = (char *) PaHost_AllocateTrackedMemory( wmmeStreamData->bytesPerHostOutputBuffer ); /* MEM */ + if( wmmeStreamData->outputBuffers[i].lpData == NULL ) + { + result = paInsufficientMemory; + goto error; + } + wmmeStreamData->outputBuffers[i].dwBufferLength = wmmeStreamData->bytesPerHostOutputBuffer; + wmmeStreamData->outputBuffers[i].dwUser = i; + if( (mmresult = waveOutPrepareHeader( wmmeStreamData->hWaveOut, &wmmeStreamData->outputBuffers[i], sizeof(WAVEHDR) )) != MMSYSERR_NOERROR ) + { + result = paHostError; + sPaHostError = mmresult; + goto error; + } + } + return result; + +error: + return result; +} +/*******************************************************************/ +PaError PaHost_GetTotalBufferFrames( internalPortAudioStream *stream ) +{ + PaWMMEStreamData *wmmeStreamData = (PaWMMEStreamData *) stream->past_DeviceData; + return wmmeStreamData->numHostBuffers * wmmeStreamData->framesPerHostBuffer; +} +/******************************************************************* + * Determine number of WAVE Buffers + * and how many User Buffers we can put into each WAVE buffer. + */ +static void PaHost_CalcNumHostBuffers( internalPortAudioStream *stream ) +{ + PaWMMEStreamData *wmmeStreamData = (PaWMMEStreamData *) stream->past_DeviceData; + unsigned int minNumBuffers; + int minframesPerHostBuffer; + int maxframesPerHostBuffer; + int minTotalFrames; + int userBuffersPerHostBuffer; + int framesPerHostBuffer; + int numHostBuffers; + + /* Calculate minimum and maximum sizes based on timing and sample rate. */ + minframesPerHostBuffer = (int) (PA_MIN_MSEC_PER_HOST_BUFFER * stream->past_SampleRate * 0.001); + minframesPerHostBuffer = (minframesPerHostBuffer + 7) & ~7; + DBUG(("PaHost_CalcNumHostBuffers: minframesPerHostBuffer = %d\n", minframesPerHostBuffer )); + maxframesPerHostBuffer = (int) (PA_MAX_MSEC_PER_HOST_BUFFER * stream->past_SampleRate * 0.001); + maxframesPerHostBuffer = (maxframesPerHostBuffer + 7) & ~7; + DBUG(("PaHost_CalcNumHostBuffers: maxframesPerHostBuffer = %d\n", maxframesPerHostBuffer )); + /* Determine number of user buffers based on minimum latency. */ + minNumBuffers = Pa_GetMinNumBuffers( stream->past_FramesPerUserBuffer, stream->past_SampleRate ); + stream->past_NumUserBuffers = ( minNumBuffers > stream->past_NumUserBuffers ) ? minNumBuffers : stream->past_NumUserBuffers; + DBUG(("PaHost_CalcNumHostBuffers: min past_NumUserBuffers = %d\n", stream->past_NumUserBuffers )); + minTotalFrames = stream->past_NumUserBuffers * stream->past_FramesPerUserBuffer; + /* We cannot make the WAVE buffers too small because they may not get serviced quickly enough. */ + if( (int) stream->past_FramesPerUserBuffer < minframesPerHostBuffer ) + { + userBuffersPerHostBuffer = + (minframesPerHostBuffer + stream->past_FramesPerUserBuffer - 1) / + stream->past_FramesPerUserBuffer; + } + else + { + userBuffersPerHostBuffer = 1; + } + framesPerHostBuffer = stream->past_FramesPerUserBuffer * userBuffersPerHostBuffer; + /* Calculate number of WAVE buffers needed. Round up to cover minTotalFrames. */ + numHostBuffers = (minTotalFrames + framesPerHostBuffer - 1) / framesPerHostBuffer; + /* Make sure we have anough WAVE buffers. */ + if( numHostBuffers < PA_MIN_NUM_HOST_BUFFERS) + { + numHostBuffers = PA_MIN_NUM_HOST_BUFFERS; + } + else if( (numHostBuffers > PA_MAX_NUM_HOST_BUFFERS) && + ((int) stream->past_FramesPerUserBuffer < (maxframesPerHostBuffer/2) ) ) + { + /* If we have too many WAVE buffers, try to put more user buffers in a wave buffer. */ + while(numHostBuffers > PA_MAX_NUM_HOST_BUFFERS) + { + userBuffersPerHostBuffer += 1; + framesPerHostBuffer = stream->past_FramesPerUserBuffer * userBuffersPerHostBuffer; + numHostBuffers = (minTotalFrames + framesPerHostBuffer - 1) / framesPerHostBuffer; + /* If we have gone too far, back up one. */ + if( (framesPerHostBuffer > maxframesPerHostBuffer) || + (numHostBuffers < PA_MAX_NUM_HOST_BUFFERS) ) + { + userBuffersPerHostBuffer -= 1; + framesPerHostBuffer = stream->past_FramesPerUserBuffer * userBuffersPerHostBuffer; + numHostBuffers = (minTotalFrames + framesPerHostBuffer - 1) / framesPerHostBuffer; + break; + } + } + } + + wmmeStreamData->userBuffersPerHostBuffer = userBuffersPerHostBuffer; + wmmeStreamData->framesPerHostBuffer = framesPerHostBuffer; + wmmeStreamData->numHostBuffers = numHostBuffers; + DBUG(("PaHost_CalcNumHostBuffers: userBuffersPerHostBuffer = %d\n", wmmeStreamData->userBuffersPerHostBuffer )); + DBUG(("PaHost_CalcNumHostBuffers: numHostBuffers = %d\n", wmmeStreamData->numHostBuffers )); + DBUG(("PaHost_CalcNumHostBuffers: framesPerHostBuffer = %d\n", wmmeStreamData->framesPerHostBuffer )); + DBUG(("PaHost_CalcNumHostBuffers: past_NumUserBuffers = %d\n", stream->past_NumUserBuffers )); +} +/*******************************************************************/ +PaError PaHost_OpenStream( internalPortAudioStream *stream ) +{ + PaError result = paNoError; + PaWMMEStreamData *wmmeStreamData; + + result = PaHost_AllocateWMMEStreamData( stream ); + if( result != paNoError ) return result; + + wmmeStreamData = PaHost_GetWMMEStreamData( stream ); + + /* Figure out how user buffers fit into WAVE buffers. */ + PaHost_CalcNumHostBuffers( stream ); + { + int msecLatency = (int) ((PaHost_GetTotalBufferFrames(stream) * 1000) / stream->past_SampleRate); + DBUG(("PortAudio on WMME - Latency = %d frames, %d msec\n", PaHost_GetTotalBufferFrames(stream), msecLatency )); + } + InitializeCriticalSection( &wmmeStreamData->streamLock ); + wmmeStreamData->streamLockInited = 1; + +#if (PA_USE_TIMER_CALLBACK == 0) + wmmeStreamData->bufferEventInited = 0; + wmmeStreamData->bufferEvent = CreateEvent( NULL, FALSE, FALSE, NULL ); + if( wmmeStreamData->bufferEvent == NULL ) + { + result = paHostError; + sPaHostError = GetLastError(); + goto error; + } + wmmeStreamData->bufferEventInited = 1; +#endif /* (PA_USE_TIMER_CALLBACK == 0) */ + /* ------------------ OUTPUT */ + wmmeStreamData->bytesPerUserOutputBuffer = stream->past_FramesPerUserBuffer * stream->past_NumOutputChannels * sizeof(short); + wmmeStreamData->bytesPerHostOutputBuffer = wmmeStreamData->userBuffersPerHostBuffer * wmmeStreamData->bytesPerUserOutputBuffer; + if( (stream->past_OutputDeviceID != paNoDevice) && (stream->past_NumOutputChannels > 0) ) + { + result = PaHost_OpenOutputStream( stream ); + if( result < 0 ) goto error; + } + /* ------------------ INPUT */ + wmmeStreamData->bytesPerUserInputBuffer = stream->past_FramesPerUserBuffer * stream->past_NumInputChannels * sizeof(short); + wmmeStreamData->bytesPerHostInputBuffer = wmmeStreamData->userBuffersPerHostBuffer * wmmeStreamData->bytesPerUserInputBuffer; + if( (stream->past_InputDeviceID != paNoDevice) && (stream->past_NumInputChannels > 0) ) + { + result = PaHost_OpenInputStream( stream ); + if( result < 0 ) goto error; + } + + Pa_InitializeCpuUsageScalar( stream ); + + return result; + +error: + PaHost_CloseStream( stream ); + return result; +} +/*************************************************************************/ +PaError PaHost_StartOutput( internalPortAudioStream *stream ) +{ + PaError result = paNoError; + MMRESULT mmresult; + int i; + PaWMMEStreamData *wmmeStreamData = PaHost_GetWMMEStreamData( stream ); + + if( wmmeStreamData == NULL ) return paInternalError; + + if( stream->past_OutputDeviceID != paNoDevice ) + { + if( (mmresult = waveOutPause( wmmeStreamData->hWaveOut )) != MMSYSERR_NOERROR ) + { + result = paHostError; + sPaHostError = mmresult; + goto error; + } + for( i=0; inumHostBuffers; i++ ) + { + ZeroMemory( wmmeStreamData->outputBuffers[i].lpData, wmmeStreamData->outputBuffers[i].dwBufferLength ); + mmresult = waveOutWrite( wmmeStreamData->hWaveOut, &wmmeStreamData->outputBuffers[i], sizeof(WAVEHDR) ); + if( mmresult != MMSYSERR_NOERROR ) + { + result = paHostError; + sPaHostError = mmresult; + goto error; + } + stream->past_FrameCount += wmmeStreamData->framesPerHostBuffer; + } + wmmeStreamData->currentOutputBuffer = 0; + if( (mmresult = waveOutRestart( wmmeStreamData->hWaveOut )) != MMSYSERR_NOERROR ) + { + result = paHostError; + sPaHostError = mmresult; + goto error; + } + } + +error: + DBUG(("PaHost_StartOutput: wave returned mmresult = 0x%X.\n", mmresult)); + return result; +} +/*************************************************************************/ +PaError PaHost_StartInput( internalPortAudioStream *internalStream ) +{ + PaError result = paNoError; + MMRESULT mmresult; + int i; + PaWMMEStreamData *wmmeStreamData = PaHost_GetWMMEStreamData( internalStream ); + + if( wmmeStreamData == NULL ) return paInternalError; + + if( internalStream->past_InputDeviceID != paNoDevice ) + { + for( i=0; inumHostBuffers; i++ ) + { + mmresult = waveInAddBuffer( wmmeStreamData->hWaveIn, &wmmeStreamData->inputBuffers[i], sizeof(WAVEHDR) ); + if( mmresult != MMSYSERR_NOERROR ) + { + result = paHostError; + sPaHostError = mmresult; + goto error; + } + } + wmmeStreamData->currentInputBuffer = 0; + mmresult = waveInStart( wmmeStreamData->hWaveIn ); + DBUG(("Pa_StartStream: waveInStart returned = 0x%X.\n", mmresult)); + if( mmresult != MMSYSERR_NOERROR ) + { + result = paHostError; + sPaHostError = mmresult; + goto error; + } + } + +error: + return result; +} +/*************************************************************************/ +PaError PaHost_StartEngine( internalPortAudioStream *stream ) +{ + PaError result = paNoError; + PaWMMEStreamData *wmmeStreamData = PaHost_GetWMMEStreamData( stream ); +#if PA_USE_TIMER_CALLBACK + int resolution; + int bufsPerTimerCallback; + int msecPerBuffer; +#endif /* PA_USE_TIMER_CALLBACK */ + + if( wmmeStreamData == NULL ) return paInternalError; + + stream->past_StopSoon = 0; + stream->past_StopNow = 0; + stream->past_IsActive = 1; + wmmeStreamData->framesPlayed = 0.0; + wmmeStreamData->lastPosition = 0; +#if PA_TRACE_START_STOP + AddTraceMessage( "PaHost_StartEngine: TimeSlice() returned ", result ); +#endif +#if PA_USE_TIMER_CALLBACK + /* Create timer that will wake us up so we can fill the DSound buffer. */ + bufsPerTimerCallback = wmmeStreamData->numHostBuffers/4; + if( bufsPerTimerCallback < 1 ) bufsPerTimerCallback = 1; + if( bufsPerTimerCallback < 1 ) bufsPerTimerCallback = 1; + msecPerBuffer = (1000 * bufsPerTimerCallback * + wmmeStreamData->userBuffersPerHostBuffer * + internalStream->past_FramesPerUserBuffer ) / (int) internalStream->past_SampleRate; + if( msecPerBuffer < 10 ) msecPerBuffer = 10; + else if( msecPerBuffer > 100 ) msecPerBuffer = 100; + resolution = msecPerBuffer/4; + wmmeStreamData->timerID = timeSetEvent( msecPerBuffer, resolution, + (LPTIMECALLBACK) Pa_TimerCallback, + (DWORD) stream, TIME_PERIODIC ); + if( wmmeStreamData->timerID == 0 ) + { + result = paHostError; + sPaHostError = GetLastError();; + goto error; + } +#else /* PA_USE_TIMER_CALLBACK */ + ResetEvent( wmmeStreamData->abortEvent ); + /* Create thread that waits for audio buffers to be ready for processing. */ + wmmeStreamData->engineThread = CreateThread( 0, 0, WinMMPa_OutputThreadProc, stream, 0, &wmmeStreamData->engineThreadID ); + if( wmmeStreamData->engineThread == NULL ) + { + result = paHostError; + sPaHostError = GetLastError();; + goto error; + } +#if PA_TRACE_START_STOP + AddTraceMessage( "PaHost_StartEngine: thread ", (int) wmmeStreamData->engineThread ); +#endif + /* I used to pass the thread which was failing. I now pass GetCurrentProcess(). + * This fix could improve latency for some applications. It could also result in CPU + * starvation if the callback did too much processing. + * I also added result checks, so we might see more failures at initialization. + * Thanks to Alberto di Bene for spotting this. + */ + if( !SetPriorityClass( GetCurrentProcess(), HIGH_PRIORITY_CLASS ) ) /* PLB20010816 */ + { + result = paHostError; + sPaHostError = GetLastError();; + goto error; + } + if( !SetThreadPriority( wmmeStreamData->engineThread, THREAD_PRIORITY_HIGHEST ) ) + { + result = paHostError; + sPaHostError = GetLastError();; + goto error; + } +#endif + +error: + return result; +} +/*************************************************************************/ +PaError PaHost_StopEngine( internalPortAudioStream *internalStream, int abort ) +{ + int timeOut; + PaWMMEStreamData *wmmeStreamData = PaHost_GetWMMEStreamData( internalStream ); + + if( wmmeStreamData == NULL ) return paNoError; + + /* Tell background thread to stop generating more data and to let current data play out. */ + internalStream->past_StopSoon = 1; + /* If aborting, tell background thread to stop NOW! */ + if( abort ) internalStream->past_StopNow = 1; + + /* Calculate timeOut longer than longest time it could take to play all buffers. */ + timeOut = (DWORD) (1500.0 * PaHost_GetTotalBufferFrames( internalStream ) / internalStream->past_SampleRate); + if( timeOut < MIN_TIMEOUT_MSEC ) timeOut = MIN_TIMEOUT_MSEC; + +#if PA_USE_TIMER_CALLBACK + if( (internalStream->past_OutputDeviceID != paNoDevice) && + internalStream->past_IsActive && + (wmmeStreamData->timerID != 0) ) + { + /* Wait for IsActive to drop. */ + while( (internalStream->past_IsActive) && (timeOut > 0) ) + { + Sleep(10); + timeOut -= 10; + } + timeKillEvent( wmmeStreamData->timerID ); /* Stop callback timer. */ + wmmeStreamData->timerID = 0; + } +#else /* PA_USE_TIMER_CALLBACK */ +#if PA_TRACE_START_STOP + AddTraceMessage( "PaHost_StopEngine: thread ", (int) wmmeStreamData->engineThread ); +#endif + if( (internalStream->past_OutputDeviceID != paNoDevice) && + (internalStream->past_IsActive) && + (wmmeStreamData->engineThread != NULL) ) + { + DWORD got; + /* Tell background thread to stop generating more data and to let current data play out. */ + DBUG(("PaHost_StopEngine: waiting for background thread.\n")); + got = WaitForSingleObject( wmmeStreamData->engineThread, timeOut ); + if( got == WAIT_TIMEOUT ) + { + ERR_RPT(("PaHost_StopEngine: timed out while waiting for background thread to finish.\n")); + return paTimedOut; + } + CloseHandle( wmmeStreamData->engineThread ); + wmmeStreamData->engineThread = NULL; + } +#endif /* PA_USE_TIMER_CALLBACK */ + + internalStream->past_IsActive = 0; + return paNoError; +} +/*************************************************************************/ +PaError PaHost_StopInput( internalPortAudioStream *stream, int abort ) +{ + MMRESULT mmresult; + PaWMMEStreamData *wmmeStreamData = PaHost_GetWMMEStreamData( stream ); + + if( wmmeStreamData == NULL ) return paNoError; /* FIXME: why return paNoError? */ + (void) abort; /* unused parameter */ + + if( wmmeStreamData->hWaveIn != NULL ) + { + mmresult = waveInReset( wmmeStreamData->hWaveIn ); + if( mmresult != MMSYSERR_NOERROR ) + { + sPaHostError = mmresult; + return paHostError; + } + } + return paNoError; +} +/*************************************************************************/ +PaError PaHost_StopOutput( internalPortAudioStream *internalStream, int abort ) +{ + MMRESULT mmresult; + PaWMMEStreamData *wmmeStreamData = PaHost_GetWMMEStreamData( internalStream ); + + if( wmmeStreamData == NULL ) return paNoError; /* FIXME: why return paNoError? */ + (void) abort; /* unused parameter */ + +#if PA_TRACE_START_STOP + AddTraceMessage( "PaHost_StopOutput: hWaveOut ", (int) wmmeStreamData->hWaveOut ); +#endif + if( wmmeStreamData->hWaveOut != NULL ) + { + mmresult = waveOutReset( wmmeStreamData->hWaveOut ); + if( mmresult != MMSYSERR_NOERROR ) + { + sPaHostError = mmresult; + return paHostError; + } + } + return paNoError; +} +/*******************************************************************/ +PaError PaHost_CloseStream( internalPortAudioStream *stream ) +{ + int i; + PaWMMEStreamData *wmmeStreamData = PaHost_GetWMMEStreamData( stream ); + + if( stream == NULL ) return paBadStreamPtr; + if( wmmeStreamData == NULL ) return paNoError; /* FIXME: why return no error? */ + +#if PA_TRACE_START_STOP + AddTraceMessage( "PaHost_CloseStream: hWaveOut ", (int) wmmeStreamData->hWaveOut ); +#endif + /* Free data and device for output. */ + if( wmmeStreamData->hWaveOut ) + { + if( wmmeStreamData->outputBuffers ) + { + for( i=0; inumHostBuffers; i++ ) + { + waveOutUnprepareHeader( wmmeStreamData->hWaveOut, &wmmeStreamData->outputBuffers[i], sizeof(WAVEHDR) ); + PaHost_FreeTrackedMemory( wmmeStreamData->outputBuffers[i].lpData ); /* MEM */ + } + PaHost_FreeTrackedMemory( wmmeStreamData->outputBuffers ); /* MEM */ + } + waveOutClose( wmmeStreamData->hWaveOut ); + } + /* Free data and device for input. */ + if( wmmeStreamData->hWaveIn ) + { + if( wmmeStreamData->inputBuffers ) + { + for( i=0; inumHostBuffers; i++ ) + { + waveInUnprepareHeader( wmmeStreamData->hWaveIn, &wmmeStreamData->inputBuffers[i], sizeof(WAVEHDR) ); + PaHost_FreeTrackedMemory( wmmeStreamData->inputBuffers[i].lpData ); /* MEM */ + } + PaHost_FreeTrackedMemory( wmmeStreamData->inputBuffers ); /* MEM */ + } + waveInClose( wmmeStreamData->hWaveIn ); + } +#if (PA_USE_TIMER_CALLBACK == 0) + if( wmmeStreamData->abortEventInited ) CloseHandle( wmmeStreamData->abortEvent ); + if( wmmeStreamData->bufferEventInited ) CloseHandle( wmmeStreamData->bufferEvent ); +#endif + if( wmmeStreamData->streamLockInited ) + DeleteCriticalSection( &wmmeStreamData->streamLock ); + + PaHost_FreeWMMEStreamData( stream ); + + return paNoError; +} +/************************************************************************* + * Determine minimum number of buffers required for this host based + * on minimum latency. Latency can be optionally set by user by setting + * an environment variable. For example, to set latency to 200 msec, put: + * + * set PA_MIN_LATENCY_MSEC=200 + * + * in the AUTOEXEC.BAT file and reboot. + * If the environment variable is not set, then the latency will be determined + * based on the OS. Windows NT has higher latency than Win95. + */ +#define PA_LATENCY_ENV_NAME ("PA_MIN_LATENCY_MSEC") +int Pa_GetMinNumBuffers( int framesPerBuffer, double sampleRate ) +{ + char envbuf[PA_ENV_BUF_SIZE]; + DWORD hresult; + int minLatencyMsec = 0; + double msecPerBuffer = (1000.0 * framesPerBuffer) / sampleRate; + int minBuffers; + + /* Let user determine minimal latency by setting environment variable. */ + hresult = GetEnvironmentVariable( PA_LATENCY_ENV_NAME, envbuf, PA_ENV_BUF_SIZE ); + if( (hresult > 0) && (hresult < PA_ENV_BUF_SIZE) ) + { + minLatencyMsec = atoi( envbuf ); /* REVIEW: will we crash if the environment variable contains some nasty value? */ + } + else + { + /* Set minimal latency based on whether NT or other OS. + * NT has higher latency. + */ + OSVERSIONINFO osvi; + osvi.dwOSVersionInfoSize = sizeof( osvi ); + GetVersionEx( &osvi ); + DBUG(("PA - PlatformId = 0x%x\n", osvi.dwPlatformId )); + DBUG(("PA - MajorVersion = 0x%x\n", osvi.dwMajorVersion )); + DBUG(("PA - MinorVersion = 0x%x\n", osvi.dwMinorVersion )); + /* Check for NT */ + if( (osvi.dwMajorVersion == 4) && (osvi.dwPlatformId == 2) ) + { + minLatencyMsec = PA_WIN_NT_LATENCY; + } + else if(osvi.dwMajorVersion >= 5) + { + minLatencyMsec = PA_WIN_WDM_LATENCY; + } + else + { + minLatencyMsec = PA_WIN_9X_LATENCY; + } +#if PA_USE_HIGH_LATENCY + PRINT(("PA - Minimum Latency set to %d msec!\n", minLatencyMsec )); +#endif + + } + DBUG(("PA - Minimum Latency set to %d msec!\n", minLatencyMsec )); + minBuffers = (int) (1.0 + ((double)minLatencyMsec / msecPerBuffer)); + if( minBuffers < 2 ) minBuffers = 2; + return minBuffers; +} +/************************************************************************* + * Cleanup device info. + */ +PaError PaHost_Term( void ) +{ + int i; + + if( sNumDevices > 0 ) + { + if( sDevicePtrs != NULL ) + { + for( i=0; iname ); /* MEM */ + PaHost_FreeTrackedMemory( (void*)sDevicePtrs[i]->sampleRates ); /* MEM */ + PaHost_FreeTrackedMemory( sDevicePtrs[i] ); /* MEM */ + } + } + PaHost_FreeTrackedMemory( sDevicePtrs ); /* MEM */ + sDevicePtrs = NULL; + } + sNumDevices = 0; + } + +#if PA_TRACK_MEMORY + PRINT(("PaHost_Term: sNumAllocations = %d\n", sNumAllocations )); +#endif + + return paNoError; +} +/*************************************************************************/ +void Pa_Sleep( long msec ) +{ + Sleep( msec ); +} +/************************************************************************* +FIXME: the following memory allocation routines should not be declared here + * Allocate memory that can be accessed in real-time. + * This may need to be held in physical memory so that it is not + * paged to virtual memory. + * This call MUST be balanced with a call to PaHost_FreeFastMemory(). + * Memory will be set to zero. + */ +void *PaHost_AllocateFastMemory( long numBytes ) +{ + return PaHost_AllocateTrackedMemory( numBytes ); /* FIXME - do we need physical memory? Use VirtualLock() */ /* MEM */ +} +/************************************************************************* + * Free memory that could be accessed in real-time. + * This call MUST be balanced with a call to PaHost_AllocateFastMemory(). + */ +void PaHost_FreeFastMemory( void *addr, long numBytes ) +{ + (void) numBytes; /* unused parameter */ + + PaHost_FreeTrackedMemory( addr ); /* MEM */ +} + +/************************************************************************* + * Track memory allocations to avoid leaks. + */ +static void *PaHost_AllocateTrackedMemory( long numBytes ) +{ + void *result = GlobalAlloc( GPTR, numBytes ); /* MEM */ + +#if PA_TRACK_MEMORY + if( result != NULL ) sNumAllocations += 1; +#endif + return result; +} + +static void PaHost_FreeTrackedMemory( void *addr ) +{ + if( addr != NULL ) + { + GlobalFree( addr ); /* MEM */ +#if PA_TRACK_MEMORY + sNumAllocations -= 1; +#endif + } +} + +/***********************************************************************/ +PaError PaHost_StreamActive( internalPortAudioStream *internalStream ) +{ + if( internalStream == NULL ) return paBadStreamPtr; + + return (PaError) internalStream->past_IsActive; +} +/************************************************************************* + * This must be called periodically because mmtime.u.sample + * is a DWORD and can wrap and lose sync after a few hours. + */ +static PaError PaHost_UpdateStreamTime( PaWMMEStreamData *wmmeStreamData ) +{ + MMRESULT mmresult; + MMTIME mmtime; + mmtime.wType = TIME_SAMPLES; + + if( wmmeStreamData->hWaveOut != NULL ) + { + mmresult = waveOutGetPosition( wmmeStreamData->hWaveOut, &mmtime, sizeof(mmtime) ); + } + else + { + mmresult = waveInGetPosition( wmmeStreamData->hWaveIn, &mmtime, sizeof(mmtime) ); + } + + if( mmresult != MMSYSERR_NOERROR ) + { + sPaHostError = mmresult; + return paHostError; + } + + /* This data has two variables and is shared by foreground and background. + * So we need to make it thread safe. */ + EnterCriticalSection( &wmmeStreamData->streamLock ); + wmmeStreamData->framesPlayed += ((long)mmtime.u.sample) - wmmeStreamData->lastPosition; + wmmeStreamData->lastPosition = (long)mmtime.u.sample; + LeaveCriticalSection( &wmmeStreamData->streamLock ); + + return paNoError; +} +/*************************************************************************/ +PaTimestamp Pa_StreamTime( PortAudioStream *stream ) +{ + internalPortAudioStream *internalStream = PaHost_GetStreamRepresentation( stream ); + PaWMMEStreamData *wmmeStreamData = PaHost_GetWMMEStreamData( internalStream ); + + if( internalStream == NULL ) return paBadStreamPtr; + if( wmmeStreamData == NULL ) return paInternalError; + + PaHost_UpdateStreamTime( wmmeStreamData ); + return wmmeStreamData->framesPlayed; +} +/*************************************************************************/ + + + diff --git a/mozilla/zap/zmk/portaudio_v18_1/pablio/README.txt b/mozilla/zap/zmk/portaudio_v18_1/pablio/README.txt new file mode 100755 index 00000000000..294adcb4db0 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pablio/README.txt @@ -0,0 +1,39 @@ +README for PABLIO +Portable Audio Blocking I/O Library +Author: Phil Burk + +PABLIO is a simplified interface to PortAudio that provide +read/write style blocking I/O. + +Please see the .DOC file for documentation. + +/* + * More information on PortAudio at: http://www.portaudio.com + * Copyright (c) 1999-2000 Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + + diff --git a/mozilla/zap/zmk/portaudio_v18_1/pablio/pablio.c b/mozilla/zap/zmk/portaudio_v18_1/pablio/pablio.c new file mode 100755 index 00000000000..d987c4b24dc --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pablio/pablio.c @@ -0,0 +1,327 @@ +/* + * $Id: pablio.c,v 1.1.2.1 2005-08-16 20:04:19 alex%croczilla.com Exp $ + * pablio.c + * Portable Audio Blocking Input/Output utility. + * + * Author: Phil Burk, http://www.softsynth.com + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.audiomulch.com/portaudio/ + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +/* History: + * PLB021214 - check for valid stream in CloseAudioStream() to prevent hang. + * add timeOutMSec to CloseAudioStream() to prevent hang. + */ +#include +#include +#include +#include "portaudio.h" +#include "ringbuffer.h" +#include "pablio.h" +#include + +/************************************************************************/ +/******** Constants *****************************************************/ +/************************************************************************/ + +#define FRAMES_PER_BUFFER (256) + +/************************************************************************/ +/******** Prototypes ****************************************************/ +/************************************************************************/ + +static int blockingIOCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ); +static PaError PABLIO_InitFIFO( RingBuffer *rbuf, long numFrames, long bytesPerFrame ); +static PaError PABLIO_TermFIFO( RingBuffer *rbuf ); + +/************************************************************************/ +/******** Functions *****************************************************/ +/************************************************************************/ + +/* Called from PortAudio. + * Read and write data only if there is room in FIFOs. + */ +static int blockingIOCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + PABLIO_Stream *data = (PABLIO_Stream*)userData; + long numBytes = data->bytesPerFrame * framesPerBuffer; + (void) outTime; + + /* This may get called with NULL inputBuffer during initial setup. */ + if( inputBuffer != NULL ) + { + RingBuffer_Write( &data->inFIFO, inputBuffer, numBytes ); + } + if( outputBuffer != NULL ) + { + int i; + int numRead = RingBuffer_Read( &data->outFIFO, outputBuffer, numBytes ); + /* Zero out remainder of buffer if we run out of data. */ + for( i=numRead; ibuffer ) free( rbuf->buffer ); + rbuf->buffer = NULL; + return paNoError; +} + +/************************************************************ + * Write data to ring buffer. + * Will not return until all the data has been written. + */ +long WriteAudioStream( PABLIO_Stream *aStream, void *data, long numFrames ) +{ + long bytesWritten; + char *p = (char *) data; + long numBytes = aStream->bytesPerFrame * numFrames; + while( numBytes > 0) + { + bytesWritten = RingBuffer_Write( &aStream->outFIFO, p, numBytes ); + numBytes -= bytesWritten; + p += bytesWritten; + if( numBytes > 0) Pa_Sleep(10); + } + return numFrames; +} + +/************************************************************ + * Read data from ring buffer. + * Will not return until all the data has been read. + */ +long ReadAudioStream( PABLIO_Stream *aStream, void *data, long numFrames ) +{ + long bytesRead; + char *p = (char *) data; + long numBytes = aStream->bytesPerFrame * numFrames; + while( numBytes > 0) + { + bytesRead = RingBuffer_Read( &aStream->inFIFO, p, numBytes ); + numBytes -= bytesRead; + p += bytesRead; + if( numBytes > 0) Pa_Sleep(10); + } + return numFrames; +} + +/************************************************************ + * Return the number of frames that could be written to the stream without + * having to wait. + */ +long GetAudioStreamWriteable( PABLIO_Stream *aStream ) +{ + int bytesEmpty = RingBuffer_GetWriteAvailable( &aStream->outFIFO ); + return bytesEmpty / aStream->bytesPerFrame; +} + +/************************************************************ + * Return the number of frames that are available to be read from the + * stream without having to wait. + */ +long GetAudioStreamReadable( PABLIO_Stream *aStream ) +{ + int bytesFull = RingBuffer_GetReadAvailable( &aStream->inFIFO ); + return bytesFull / aStream->bytesPerFrame; +} + +/************************************************************/ +static unsigned long RoundUpToNextPowerOf2( unsigned long n ) +{ + long numBits = 0; + if( ((n-1) & n) == 0) return n; /* Already Power of two. */ + while( n > 0 ) + { + n= n>>1; + numBits++; + } + return (1<samplesPerFrame = ((flags&PABLIO_MONO) != 0) ? 1 : 2; + aStream->bytesPerFrame = bytesPerSample * aStream->samplesPerFrame; + + /* Initialize PortAudio */ + err = Pa_Initialize(); + if( err != paNoError ) goto error; + + /* Warning: numFrames must be larger than amount of data processed per interrupt + * inside PA to prevent glitches. Just to be safe, adjust size upwards. + */ + minNumBuffers = 2 * Pa_GetMinNumBuffers( FRAMES_PER_BUFFER, sampleRate ); + numFrames = minNumBuffers * FRAMES_PER_BUFFER; + /* The PortAudio callback runs in a high priority thread. But PABLIO + * runs in a normal foreground thread. So we may have much worse + * latency in PABLIO. So adjust latency to a safe level. + */ + { + const int safeLatencyMSec = 200; + int minLatencyMSec = (int) ((1000 * numFrames) / sampleRate); + if( minLatencyMSec < safeLatencyMSec ) + { + numFrames = (int) ((safeLatencyMSec * sampleRate) / 1000); + } + } + numFrames = RoundUpToNextPowerOf2( numFrames ); + + /* Initialize Ring Buffers */ + doRead = ((flags & PABLIO_READ) != 0); + doWrite = ((flags & PABLIO_WRITE) != 0); + if(doRead) + { + err = PABLIO_InitFIFO( &aStream->inFIFO, numFrames, aStream->bytesPerFrame ); + if( err != paNoError ) goto error; + } + if(doWrite) + { + long numBytes; + err = PABLIO_InitFIFO( &aStream->outFIFO, numFrames, aStream->bytesPerFrame ); + if( err != paNoError ) goto error; + /* Make Write FIFO appear full initially. */ + numBytes = RingBuffer_GetWriteAvailable( &aStream->outFIFO ); + RingBuffer_AdvanceWriteIndex( &aStream->outFIFO, numBytes ); + } + + /* Open a PortAudio stream that we will use to communicate with the underlying + * audio drivers. */ + err = Pa_OpenStream( + &aStream->stream, + (doRead ? Pa_GetDefaultInputDeviceID() : paNoDevice), + (doRead ? aStream->samplesPerFrame : 0 ), + format, + NULL, + (doWrite ? Pa_GetDefaultOutputDeviceID() : paNoDevice), + (doWrite ? aStream->samplesPerFrame : 0 ), + format, + NULL, + sampleRate, + FRAMES_PER_BUFFER, + minNumBuffers, + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + blockingIOCallback, + aStream ); + if( err != paNoError ) goto error; + + err = Pa_StartStream( aStream->stream ); + if( err != paNoError ) goto error; + + *rwblPtr = aStream; + return paNoError; + +error: + CloseAudioStream( aStream ); + *rwblPtr = NULL; + return err; +} + +/************************************************************/ +PaError CloseAudioStream( PABLIO_Stream *aStream ) +{ + PaError err = paNoError; + int bytesEmpty; + int byteSize = aStream->outFIFO.bufferSize; + + if( aStream->stream != NULL ) /* Make sure stream was opened. PLB021214 */ + { + /* If we are writing data, make sure we play everything written. */ + if( byteSize > 0 ) + { + int timeOutMSec = 2000; + bytesEmpty = RingBuffer_GetWriteAvailable( &aStream->outFIFO ); + while( (bytesEmpty < byteSize) && (timeOutMSec > 0) ) + { + Pa_Sleep( 20 ); + timeOutMSec -= 20; + bytesEmpty = RingBuffer_GetWriteAvailable( &aStream->outFIFO ); + } + } + err = Pa_StopStream( aStream->stream ); + if( err != paNoError ) goto error; + err = Pa_CloseStream( aStream->stream ); + } + +error: + Pa_Terminate(); + PABLIO_TermFIFO( &aStream->inFIFO ); + PABLIO_TermFIFO( &aStream->outFIFO ); + free( aStream ); + return err; +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pablio/pablio.def b/mozilla/zap/zmk/portaudio_v18_1/pablio/pablio.def new file mode 100755 index 00000000000..d2aea4058e8 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pablio/pablio.def @@ -0,0 +1,35 @@ +LIBRARY PABLIOV18 +DESCRIPTION 'PABLIO Portable Audio Blocking I/O' + +EXPORTS + ; Explicit exports can go here + Pa_Initialize @1 + Pa_Terminate @2 + Pa_GetHostError @3 + Pa_GetErrorText @4 + Pa_CountDevices @5 + Pa_GetDefaultInputDeviceID @6 + Pa_GetDefaultOutputDeviceID @7 + Pa_GetDeviceInfo @8 + Pa_OpenStream @9 + Pa_OpenDefaultStream @10 + Pa_CloseStream @11 + Pa_StartStream @12 + Pa_StopStream @13 + Pa_StreamActive @14 + Pa_StreamTime @15 + Pa_GetCPULoad @16 + Pa_GetMinNumBuffers @17 + Pa_Sleep @18 + + OpenAudioStream @19 + CloseAudioStream @20 + WriteAudioStream @21 + ReadAudioStream @22 + + Pa_GetSampleSize @23 + + ;123456789012345678901234567890123456 + ;000000000111111111122222222223333333 + + diff --git a/mozilla/zap/zmk/portaudio_v18_1/pablio/pablio.h b/mozilla/zap/zmk/portaudio_v18_1/pablio/pablio.h new file mode 100755 index 00000000000..3df771a812e --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pablio/pablio.h @@ -0,0 +1,109 @@ +#ifndef _PABLIO_H +#define _PABLIO_H + +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +/* + * $Id: pablio.h,v 1.1.2.1 2005-08-16 20:04:19 alex%croczilla.com Exp $ + * PABLIO.h + * Portable Audio Blocking read/write utility. + * + * Author: Phil Burk, http://www.softsynth.com/portaudio/ + * + * Include file for PABLIO, the Portable Audio Blocking I/O Library. + * PABLIO is built on top of PortAudio, the Portable Audio Library. + * For more information see: http://www.audiomulch.com/portaudio/ + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +#include +#include +#include +#include "portaudio.h" +#include "ringbuffer.h" +#include + +typedef struct +{ + RingBuffer inFIFO; + RingBuffer outFIFO; + PortAudioStream *stream; + int bytesPerFrame; + int samplesPerFrame; +} +PABLIO_Stream; + +/* Values for flags for OpenAudioStream(). */ +#define PABLIO_READ (1<<0) +#define PABLIO_WRITE (1<<1) +#define PABLIO_READ_WRITE (PABLIO_READ|PABLIO_WRITE) +#define PABLIO_MONO (1<<2) +#define PABLIO_STEREO (1<<3) + +/************************************************************ + * Write data to ring buffer. + * Will not return until all the data has been written. + */ +long WriteAudioStream( PABLIO_Stream *aStream, void *data, long numFrames ); + +/************************************************************ + * Read data from ring buffer. + * Will not return until all the data has been read. + */ +long ReadAudioStream( PABLIO_Stream *aStream, void *data, long numFrames ); + +/************************************************************ + * Return the number of frames that could be written to the stream without + * having to wait. + */ +long GetAudioStreamWriteable( PABLIO_Stream *aStream ); + +/************************************************************ + * Return the number of frames that are available to be read from the + * stream without having to wait. + */ +long GetAudioStreamReadable( PABLIO_Stream *aStream ); + +/************************************************************ + * Opens a PortAudio stream with default characteristics. + * Allocates PABLIO_Stream structure. + * + * flags parameter can be an ORed combination of: + * PABLIO_READ, PABLIO_WRITE, or PABLIO_READ_WRITE, + * and either PABLIO_MONO or PABLIO_STEREO + */ +PaError OpenAudioStream( PABLIO_Stream **aStreamPtr, double sampleRate, + PaSampleFormat format, long flags ); + +PaError CloseAudioStream( PABLIO_Stream *aStream ); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ +#endif /* _PABLIO_H */ diff --git a/mozilla/zap/zmk/portaudio_v18_1/pablio/ringbuffer.c b/mozilla/zap/zmk/portaudio_v18_1/pablio/ringbuffer.c new file mode 100755 index 00000000000..237765e3dd3 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pablio/ringbuffer.c @@ -0,0 +1,199 @@ +/* + * $Id: ringbuffer.c,v 1.1.2.1 2005-08-16 20:04:19 alex%croczilla.com Exp $ + * ringbuffer.c + * Ring Buffer utility.. + * + * Author: Phil Burk, http://www.softsynth.com + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.audiomulch.com/portaudio/ + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +#include +#include +#include +#include "ringbuffer.h" +#include + +/*************************************************************************** + * Initialize FIFO. + * numBytes must be power of 2, returns -1 if not. + */ +long RingBuffer_Init( RingBuffer *rbuf, long numBytes, void *dataPtr ) +{ + if( ((numBytes-1) & numBytes) != 0) return -1; /* Not Power of two. */ + rbuf->bufferSize = numBytes; + rbuf->buffer = (char *)dataPtr; + RingBuffer_Flush( rbuf ); + rbuf->bigMask = (numBytes*2)-1; + rbuf->smallMask = (numBytes)-1; + return 0; +} +/*************************************************************************** +** Return number of bytes available for reading. */ +long RingBuffer_GetReadAvailable( RingBuffer *rbuf ) +{ + return ( (rbuf->writeIndex - rbuf->readIndex) & rbuf->bigMask ); +} +/*************************************************************************** +** Return number of bytes available for writing. */ +long RingBuffer_GetWriteAvailable( RingBuffer *rbuf ) +{ + return ( rbuf->bufferSize - RingBuffer_GetReadAvailable(rbuf)); +} + +/*************************************************************************** +** Clear buffer. Should only be called when buffer is NOT being read. */ +void RingBuffer_Flush( RingBuffer *rbuf ) +{ + rbuf->writeIndex = rbuf->readIndex = 0; +} + +/*************************************************************************** +** Get address of region(s) to which we can write data. +** If the region is contiguous, size2 will be zero. +** If non-contiguous, size2 will be the size of second region. +** Returns room available to be written or numBytes, whichever is smaller. +*/ +long RingBuffer_GetWriteRegions( RingBuffer *rbuf, long numBytes, + void **dataPtr1, long *sizePtr1, + void **dataPtr2, long *sizePtr2 ) +{ + long index; + long available = RingBuffer_GetWriteAvailable( rbuf ); + if( numBytes > available ) numBytes = available; + /* Check to see if write is not contiguous. */ + index = rbuf->writeIndex & rbuf->smallMask; + if( (index + numBytes) > rbuf->bufferSize ) + { + /* Write data in two blocks that wrap the buffer. */ + long firstHalf = rbuf->bufferSize - index; + *dataPtr1 = &rbuf->buffer[index]; + *sizePtr1 = firstHalf; + *dataPtr2 = &rbuf->buffer[0]; + *sizePtr2 = numBytes - firstHalf; + } + else + { + *dataPtr1 = &rbuf->buffer[index]; + *sizePtr1 = numBytes; + *dataPtr2 = NULL; + *sizePtr2 = 0; + } + return numBytes; +} + + +/*************************************************************************** +*/ +long RingBuffer_AdvanceWriteIndex( RingBuffer *rbuf, long numBytes ) +{ + return rbuf->writeIndex = (rbuf->writeIndex + numBytes) & rbuf->bigMask; +} + +/*************************************************************************** +** Get address of region(s) from which we can read data. +** If the region is contiguous, size2 will be zero. +** If non-contiguous, size2 will be the size of second region. +** Returns room available to be written or numBytes, whichever is smaller. +*/ +long RingBuffer_GetReadRegions( RingBuffer *rbuf, long numBytes, + void **dataPtr1, long *sizePtr1, + void **dataPtr2, long *sizePtr2 ) +{ + long index; + long available = RingBuffer_GetReadAvailable( rbuf ); + if( numBytes > available ) numBytes = available; + /* Check to see if read is not contiguous. */ + index = rbuf->readIndex & rbuf->smallMask; + if( (index + numBytes) > rbuf->bufferSize ) + { + /* Write data in two blocks that wrap the buffer. */ + long firstHalf = rbuf->bufferSize - index; + *dataPtr1 = &rbuf->buffer[index]; + *sizePtr1 = firstHalf; + *dataPtr2 = &rbuf->buffer[0]; + *sizePtr2 = numBytes - firstHalf; + } + else + { + *dataPtr1 = &rbuf->buffer[index]; + *sizePtr1 = numBytes; + *dataPtr2 = NULL; + *sizePtr2 = 0; + } + return numBytes; +} +/*************************************************************************** +*/ +long RingBuffer_AdvanceReadIndex( RingBuffer *rbuf, long numBytes ) +{ + return rbuf->readIndex = (rbuf->readIndex + numBytes) & rbuf->bigMask; +} + +/*************************************************************************** +** Return bytes written. */ +long RingBuffer_Write( RingBuffer *rbuf, void *data, long numBytes ) +{ + long size1, size2, numWritten; + void *data1, *data2; + numWritten = RingBuffer_GetWriteRegions( rbuf, numBytes, &data1, &size1, &data2, &size2 ); + if( size2 > 0 ) + { + + memcpy( data1, data, size1 ); + data = ((char *)data) + size1; + memcpy( data2, data, size2 ); + } + else + { + memcpy( data1, data, size1 ); + } + RingBuffer_AdvanceWriteIndex( rbuf, numWritten ); + return numWritten; +} + +/*************************************************************************** +** Return bytes read. */ +long RingBuffer_Read( RingBuffer *rbuf, void *data, long numBytes ) +{ + long size1, size2, numRead; + void *data1, *data2; + numRead = RingBuffer_GetReadRegions( rbuf, numBytes, &data1, &size1, &data2, &size2 ); + if( size2 > 0 ) + { + memcpy( data, data1, size1 ); + data = ((char *)data) + size1; + memcpy( data, data2, size2 ); + } + else + { + memcpy( data, data1, size1 ); + } + RingBuffer_AdvanceReadIndex( rbuf, numRead ); + return numRead; +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pablio/ringbuffer.h b/mozilla/zap/zmk/portaudio_v18_1/pablio/ringbuffer.h new file mode 100755 index 00000000000..ae6e07fc646 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pablio/ringbuffer.h @@ -0,0 +1,102 @@ +#ifndef _RINGBUFFER_H +#define _RINGBUFFER_H +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +/* + * $Id: ringbuffer.h,v 1.1.2.1 2005-08-16 20:04:19 alex%croczilla.com Exp $ + * ringbuffer.h + * Ring Buffer utility.. + * + * Author: Phil Burk, http://www.softsynth.com + * + * This program is distributed with the PortAudio Portable Audio Library. + * For more information see: http://www.audiomulch.com/portaudio/ + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +#include +#include +#include +#include "ringbuffer.h" +#include + +typedef struct +{ + long bufferSize; /* Number of bytes in FIFO. Power of 2. Set by RingBuffer_Init. */ +/* These are declared volatile because they are written by a different thread than the reader. */ + volatile long writeIndex; /* Index of next writable byte. Set by RingBuffer_AdvanceWriteIndex. */ + volatile long readIndex; /* Index of next readable byte. Set by RingBuffer_AdvanceReadIndex. */ + long bigMask; /* Used for wrapping indices with extra bit to distinguish full/empty. */ + long smallMask; /* Used for fitting indices to buffer. */ + char *buffer; +} +RingBuffer; +/* + * Initialize Ring Buffer. + * numBytes must be power of 2, returns -1 if not. + */ +long RingBuffer_Init( RingBuffer *rbuf, long numBytes, void *dataPtr ); + +/* Clear buffer. Should only be called when buffer is NOT being read. */ +void RingBuffer_Flush( RingBuffer *rbuf ); + +/* Return number of bytes available for writing. */ +long RingBuffer_GetWriteAvailable( RingBuffer *rbuf ); +/* Return number of bytes available for read. */ +long RingBuffer_GetReadAvailable( RingBuffer *rbuf ); +/* Return bytes written. */ +long RingBuffer_Write( RingBuffer *rbuf, void *data, long numBytes ); +/* Return bytes read. */ +long RingBuffer_Read( RingBuffer *rbuf, void *data, long numBytes ); + +/* Get address of region(s) to which we can write data. +** If the region is contiguous, size2 will be zero. +** If non-contiguous, size2 will be the size of second region. +** Returns room available to be written or numBytes, whichever is smaller. +*/ +long RingBuffer_GetWriteRegions( RingBuffer *rbuf, long numBytes, + void **dataPtr1, long *sizePtr1, + void **dataPtr2, long *sizePtr2 ); +long RingBuffer_AdvanceWriteIndex( RingBuffer *rbuf, long numBytes ); + +/* Get address of region(s) from which we can read data. +** If the region is contiguous, size2 will be zero. +** If non-contiguous, size2 will be the size of second region. +** Returns room available to be read or numBytes, whichever is smaller. +*/ +long RingBuffer_GetReadRegions( RingBuffer *rbuf, long numBytes, + void **dataPtr1, long *sizePtr1, + void **dataPtr2, long *sizePtr2 ); + +long RingBuffer_AdvanceReadIndex( RingBuffer *rbuf, long numBytes ); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ +#endif /* _RINGBUFFER_H */ diff --git a/mozilla/zap/zmk/portaudio_v18_1/pablio/test_rw.c b/mozilla/zap/zmk/portaudio_v18_1/pablio/test_rw.c new file mode 100755 index 00000000000..94afaade1cf --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pablio/test_rw.c @@ -0,0 +1,99 @@ +/* + * $Id: test_rw.c,v 1.1.2.1 2005-08-16 20:04:19 alex%croczilla.com Exp $ + * test_rw.c + * Read input from one stream and write it to another. + * + * Author: Phil Burk, http://www.softsynth.com/portaudio/ + * + * This program uses PABLIO, the Portable Audio Blocking I/O Library. + * PABLIO is built on top of PortAudio, the Portable Audio Library. + * For more information see: http://www.audiomulch.com/portaudio/ + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +#include +#include +#include "pablio.h" + +/* +** Note that many of the older ISA sound cards on PCs do NOT support +** full duplex audio (simultaneous record and playback). +** And some only support full duplex at lower sample rates. +*/ +#define SAMPLE_RATE (44100) +#define NUM_SECONDS (5) +#define SAMPLES_PER_FRAME (2) +#define FRAMES_PER_BLOCK (64) + +/* Select whether we will use floats or shorts. */ +#if 1 +#define SAMPLE_TYPE paFloat32 +typedef float SAMPLE; +#else +#define SAMPLE_TYPE paInt16 +typedef short SAMPLE; +#endif + +/*******************************************************************/ +int main(void); +int main(void) +{ + int i; + SAMPLE samples[SAMPLES_PER_FRAME * FRAMES_PER_BLOCK]; + PaError err; + PABLIO_Stream *aStream; + + printf("Full duplex sound test using PortAudio and RingBuffers\n"); + fflush(stdout); + + /* Open simplified blocking I/O layer on top of PortAudio. */ + err = OpenAudioStream( &aStream, SAMPLE_RATE, SAMPLE_TYPE, + (PABLIO_READ_WRITE | PABLIO_STEREO) ); + if( err != paNoError ) goto error; + + /* Process samples in the foreground. */ + for( i=0; i<(NUM_SECONDS * SAMPLE_RATE); i += FRAMES_PER_BLOCK ) + { + /* Read one block of data into sample array from audio input. */ + ReadAudioStream( aStream, samples, FRAMES_PER_BLOCK ); + /* Write that same block of data to output. */ + WriteAudioStream( aStream, samples, FRAMES_PER_BLOCK ); + } + + CloseAudioStream( aStream ); + + printf("Full duplex sound test complete.\n" ); + fflush(stdout); + return 0; + +error: + Pa_Terminate(); + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + return -1; +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pablio/test_rw_echo.c b/mozilla/zap/zmk/portaudio_v18_1/pablio/test_rw_echo.c new file mode 100755 index 00000000000..c00f85a2f05 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pablio/test_rw_echo.c @@ -0,0 +1,123 @@ +/* + * $Id: test_rw_echo.c,v 1.1.2.1 2005-08-16 20:04:19 alex%croczilla.com Exp $ + * test_rw_echo.c + * Echo delayed input to output. + * + * Author: Phil Burk, http://www.softsynth.com/portaudio/ + * + * This program uses PABLIO, the Portable Audio Blocking I/O Library. + * PABLIO is built on top of PortAudio, the Portable Audio Library. + * + * Note that if you need low latency, you should not use PABLIO. + * Use the PA_OpenStream callback technique which is lower level + * than PABLIO. + * + * For more information see: http://www.audiomulch.com/portaudio/ + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +#include +#include +#include +#include "pablio.h" +#include + +/* +** Note that many of the older ISA sound cards on PCs do NOT support +** full duplex audio (simultaneous record and playback). +** And some only support full duplex at lower sample rates. +*/ +#define SAMPLE_RATE (22050) +#define NUM_SECONDS (20) +#define SAMPLES_PER_FRAME (2) + +/* Select whether we will use floats or shorts. */ +#if 1 +#define SAMPLE_TYPE paFloat32 +typedef float SAMPLE; +#else +#define SAMPLE_TYPE paInt16 +typedef short SAMPLE; +#endif + +#define NUM_ECHO_FRAMES (2*SAMPLE_RATE) +SAMPLE samples[NUM_ECHO_FRAMES][SAMPLES_PER_FRAME] = {0.0}; + +/*******************************************************************/ +int main(void); +int main(void) +{ + int i; + PaError err; + PABLIO_Stream *aInStream; + PABLIO_Stream *aOutStream; + int index; + + printf("Full duplex sound test using PABLIO\n"); + fflush(stdout); + + /* Open simplified blocking I/O layer on top of PortAudio. */ + /* Open input first so it can start to fill buffers. */ + err = OpenAudioStream( &aInStream, SAMPLE_RATE, SAMPLE_TYPE, + (PABLIO_READ | PABLIO_STEREO) ); + if( err != paNoError ) goto error; + /* printf("opened input\n"); fflush(stdout); /**/ + + err = OpenAudioStream( &aOutStream, SAMPLE_RATE, SAMPLE_TYPE, + (PABLIO_WRITE | PABLIO_STEREO) ); + if( err != paNoError ) goto error; + /* printf("opened output\n"); fflush(stdout); /**/ + + /* Process samples in the foreground. */ + index = 0; + for( i=0; i<(NUM_SECONDS * SAMPLE_RATE); i++ ) + { + /* Write old frame of data to output. */ + /* samples[index][1] = (i&256) * (1.0f/256.0f); /* sawtooth */ + WriteAudioStream( aOutStream, &samples[index][0], 1 ); + + /* Read one frame of data into sample array for later output. */ + ReadAudioStream( aInStream, &samples[index][0], 1 ); + index += 1; + if( index >= NUM_ECHO_FRAMES ) index = 0; + + if( (i & 0xFFFF) == 0 ) printf("i = %d\n", i ); fflush(stdout); /**/ + } + + CloseAudioStream( aOutStream ); + CloseAudioStream( aInStream ); + + printf("R/W echo sound test complete.\n" ); + fflush(stdout); + return 0; + +error: + fprintf( stderr, "An error occured while using PortAudio\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + return -1; +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pablio/test_w_saw.c b/mozilla/zap/zmk/portaudio_v18_1/pablio/test_w_saw.c new file mode 100755 index 00000000000..657117af232 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pablio/test_w_saw.c @@ -0,0 +1,108 @@ +/* + * $Id: test_w_saw.c,v 1.1.2.1 2005-08-16 20:04:19 alex%croczilla.com Exp $ + * test_w_saw.c + * Generate stereo sawtooth waveforms. + * + * Author: Phil Burk, http://www.softsynth.com + * + * This program uses PABLIO, the Portable Audio Blocking I/O Library. + * PABLIO is built on top of PortAudio, the Portable Audio Library. + * + * For more information see: http://www.audiomulch.com/portaudio/ + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +#include +#include +#include +#include "pablio.h" +#include + +#define SAMPLE_RATE (44100) +#define NUM_SECONDS (15) +#define SAMPLES_PER_FRAME (2) + +#define FREQUENCY (220.0f) +#define PHASE_INCREMENT (2.0f * FREQUENCY / SAMPLE_RATE) +#define FRAMES_PER_BLOCK (100) + +float samples[FRAMES_PER_BLOCK][SAMPLES_PER_FRAME]; +float phases[SAMPLES_PER_FRAME]; + +/*******************************************************************/ +int main(void); +int main(void) +{ + int i,j; + PaError err; + PABLIO_Stream *aOutStream; + + printf("Generate sawtooth waves using PABLIO.\n"); + fflush(stdout); + + /* Open simplified blocking I/O layer on top of PortAudio. */ + err = OpenAudioStream( &aOutStream, SAMPLE_RATE, paFloat32, + (PABLIO_WRITE | PABLIO_STEREO) ); + if( err != paNoError ) goto error; + + /* Initialize oscillator phases. */ + phases[0] = 0.0; + phases[1] = 0.0; + + for( i=0; i<(NUM_SECONDS * SAMPLE_RATE); i += FRAMES_PER_BLOCK ) + { + /* Generate sawtooth waveforms in a block for efficiency. */ + for( j=0; j 1.0f ) phases[0] -= 2.0f; + samples[j][0] = phases[0]; + + /* On the second channel, generate a sawtooth wave a fifth higher. */ + phases[1] += PHASE_INCREMENT * (3.0f / 2.0f); + if( phases[1] > 1.0f ) phases[1] -= 2.0f; + samples[j][1] = phases[1]; + } + + /* Write samples to output. */ + WriteAudioStream( aOutStream, samples, FRAMES_PER_BLOCK ); + } + + CloseAudioStream( aOutStream ); + + printf("Sawtooth sound test complete.\n" ); + fflush(stdout); + return 0; + +error: + fprintf( stderr, "An error occured while using PABLIO\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + return -1; +} diff --git a/mozilla/zap/zmk/portaudio_v18_1/pablio/test_w_saw8.c b/mozilla/zap/zmk/portaudio_v18_1/pablio/test_w_saw8.c new file mode 100755 index 00000000000..a6536d15bc7 --- /dev/null +++ b/mozilla/zap/zmk/portaudio_v18_1/pablio/test_w_saw8.c @@ -0,0 +1,106 @@ +/* + * $Id: test_w_saw8.c,v 1.1.2.1 2005-08-16 20:04:19 alex%croczilla.com Exp $ + * test_w_saw8.c + * Generate stereo 8 bit sawtooth waveforms. + * + * Author: Phil Burk, http://www.softsynth.com + * + * This program uses PABLIO, the Portable Audio Blocking I/O Library. + * PABLIO is built on top of PortAudio, the Portable Audio Library. + * + * For more information see: http://www.audiomulch.com/portaudio/ + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +#include +#include +#include +#include "pablio.h" +#include + +#define SAMPLE_RATE (22050) +#define NUM_SECONDS (6) +#define SAMPLES_PER_FRAME (2) + + +#define FRAMES_PER_BLOCK (100) + +unsigned char samples[FRAMES_PER_BLOCK][SAMPLES_PER_FRAME]; +unsigned char phases[SAMPLES_PER_FRAME]; + +/*******************************************************************/ +int main(void); +int main(void) +{ + int i,j; + PaError err; + PABLIO_Stream *aOutStream; + + printf("Generate unsigned 8 bit sawtooth waves using PABLIO.\n"); + fflush(stdout); + + /* Open simplified blocking I/O layer on top of PortAudio. */ + err = OpenAudioStream( &aOutStream, SAMPLE_RATE, paUInt8, + (PABLIO_WRITE | PABLIO_STEREO) ); + if( err != paNoError ) goto error; + + /* Initialize oscillator phases to "ground" level for paUInt8. */ + phases[0] = 128; + phases[1] = 128; + + for( i=0; i<(NUM_SECONDS * SAMPLE_RATE); i += FRAMES_PER_BLOCK ) + { + /* Generate sawtooth waveforms in a block for efficiency. */ + for( j=0; j + All the code except the following + +David Rowe via VoiceTronix + lsp.c lsp.h + Also ideas and feedback + +John Francis Edwards: + wave_out.[ch], some #ifdefs for windows port and MSVC project files + +Segher Boessenkool + Misc. optimizations (for QMF in particular) + +Atsuhiko Yamanaka : + Patch to speexenc.c to add Vorbis comment format + +Radim Kolar : + Patch to speexenc.c for supporting more input formats diff --git a/mozilla/zap/zmk/speex-1.1.10/COPYING b/mozilla/zap/zmk/speex-1.1.10/COPYING new file mode 100755 index 00000000000..56606babd7c --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/COPYING @@ -0,0 +1,33 @@ +Copyright 2002-2005 + Xiph.org Foundation + Jean-Marc Valin + David Rowe + EpicGames + Analog Devices + +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. + +- Neither the name of the Xiph.org Foundation nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +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. diff --git a/mozilla/zap/zmk/speex-1.1.10/ChangeLog b/mozilla/zap/zmk/speex-1.1.10/ChangeLog new file mode 100755 index 00000000000..18f4400b18e --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/ChangeLog @@ -0,0 +1,15 @@ +2004-02-18 Jean-Marc Valin + Patch for compiling with mingw32 sent by j@thing.net + +2004-02-18 Jean-Marc Valin + Integrated IRIX patch (getopt stuff) from Michael Pruett + +2004-02-18 Jean-Marc Valin + Changed the Makefile.am so that KDevelop can parse SUBDIRS correctly + +2002/03/27 Jean-Marc Valin: +Working encoder and decoder for both narrowband and wideband. + +2002/02/27 Jean-Marc Valin: +Got the basic encoder working as a demo with quantization only on some +parameters. diff --git a/mozilla/zap/zmk/speex-1.1.10/INSTALL b/mozilla/zap/zmk/speex-1.1.10/INSTALL new file mode 100755 index 00000000000..29271b20fbd --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/INSTALL @@ -0,0 +1,8 @@ +Installing Speex is as easy as: + +% ./configure [--prefix=] +% make +% make install + +Note that if you are using the code from SVN, you will need to run "autogen.sh" +instead of "configure". diff --git a/mozilla/zap/zmk/speex-1.1.10/Makefile.am b/mozilla/zap/zmk/speex-1.1.10/Makefile.am new file mode 100755 index 00000000000..36b6cfba2c8 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/Makefile.am @@ -0,0 +1,21 @@ +## Process this file with automake to produce Makefile.in. -*-Makefile-*- + +# To disable automatic dependency tracking if using other tools than +# gcc and gmake, add the option 'no-dependencies' +AUTOMAKE_OPTIONS = 1.8 + +m4datadir = $(datadir)/aclocal +m4data_DATA = speex.m4 + +pkgconfigdir = $(libdir)/pkgconfig +pkgconfig_DATA = speex.pc + +EXTRA_DIST = Speex.spec Speex.spec.in Speex.kdevelop speex.m4 speex.pc.in + +#Fools KDevelop into including all files +SUBDIRS = libspeex include @src@ doc win32 symbian + +DIST_SUBDIRS = libspeex include src doc win32 symbian + +rpm: dist + rpmbuild -ta ${PACKAGE}-${VERSION}.tar.gz diff --git a/mozilla/zap/zmk/speex-1.1.10/Makefile.in b/mozilla/zap/zmk/speex-1.1.10/Makefile.in new file mode 100644 index 00000000000..522e9f53372 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/Makefile.in @@ -0,0 +1,11 @@ +DEPTH = ../../.. +topsrcdir = @top_srcdir@ +srcdir = @srcdir@ +VPATH = @srcdir@ + +DIRS = libspeex + +include $(DEPTH)/config/autoconf.mk + +include $(topsrcdir)/config/rules.mk + diff --git a/mozilla/zap/zmk/speex-1.1.10/Makefile.in.speex b/mozilla/zap/zmk/speex-1.1.10/Makefile.in.speex new file mode 100755 index 00000000000..30fd258b69b --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/Makefile.in.speex @@ -0,0 +1,669 @@ +# Makefile.in generated by automake 1.8.5 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004 Free Software Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +top_builddir = . +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +INSTALL = @INSTALL@ +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +host_triplet = @host@ +DIST_COMMON = README $(am__configure_deps) $(srcdir)/Makefile.am \ + $(srcdir)/Makefile.in $(srcdir)/Speex.spec.in \ + $(srcdir)/config.h.in $(srcdir)/speex.pc.in \ + $(top_srcdir)/configure AUTHORS COPYING ChangeLog INSTALL NEWS \ + TODO config.guess config.sub depcomp install-sh ltmain.sh \ + missing mkinstalldirs +subdir = . +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ + $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +am__CONFIG_DISTCLEAN_FILES = config.status config.cache config.log \ + configure.lineno configure.status.lineno +mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs +CONFIG_HEADER = config.h +CONFIG_CLEAN_FILES = Speex.spec speex.pc +SOURCES = +DIST_SOURCES = +RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \ + html-recursive info-recursive install-data-recursive \ + install-exec-recursive install-info-recursive \ + install-recursive installcheck-recursive installdirs-recursive \ + pdf-recursive ps-recursive uninstall-info-recursive \ + uninstall-recursive +am__installdirs = "$(DESTDIR)$(m4datadir)" "$(DESTDIR)$(pkgconfigdir)" +m4dataDATA_INSTALL = $(INSTALL_DATA) +pkgconfigDATA_INSTALL = $(INSTALL_DATA) +DATA = $(m4data_DATA) $(pkgconfig_DATA) +ETAGS = etags +CTAGS = ctags +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +distdir = $(PACKAGE)-$(VERSION) +top_distdir = $(distdir) +am__remove_distdir = \ + { test ! -d $(distdir) \ + || { find $(distdir) -type d ! -perm -200 -exec chmod u+w {} ';' \ + && rm -fr $(distdir); }; } +DIST_ARCHIVES = $(distdir).tar.gz +GZIP_ENV = --best +distuninstallcheck_listfiles = find . -type f -print +distcleancheck_listfiles = find . -type f -print +ACLOCAL = @ACLOCAL@ +AMDEP_FALSE = @AMDEP_FALSE@ +AMDEP_TRUE = @AMDEP_TRUE@ +AMTAR = @AMTAR@ +AR = @AR@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CXX = @CXX@ +CXXCPP = @CXXCPP@ +CXXDEPMODE = @CXXDEPMODE@ +CXXFLAGS = @CXXFLAGS@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +ECHO = @ECHO@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +F77 = @F77@ +FFLAGS = @FFLAGS@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +LDFLAGS = @LDFLAGS@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +MAINT = @MAINT@ +MAINTAINER_MODE_FALSE = @MAINTAINER_MODE_FALSE@ +MAINTAINER_MODE_TRUE = @MAINTAINER_MODE_TRUE@ +MAKEINFO = @MAKEINFO@ +OBJEXT = @OBJEXT@ +OGG_CFLAGS = @OGG_CFLAGS@ +OGG_LIBS = @OGG_LIBS@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +RANLIB = @RANLIB@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +SIZE16 = @SIZE16@ +SIZE32 = @SIZE32@ +SPEEX_LT_AGE = @SPEEX_LT_AGE@ +SPEEX_LT_CURRENT = @SPEEX_LT_CURRENT@ +SPEEX_LT_REVISION = @SPEEX_LT_REVISION@ +SPEEX_VERSION = @SPEEX_VERSION@ +STRIP = @STRIP@ +VERSION = @VERSION@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_CXX = @ac_ct_CXX@ +ac_ct_F77 = @ac_ct_F77@ +ac_ct_RANLIB = @ac_ct_RANLIB@ +ac_ct_STRIP = @ac_ct_STRIP@ +am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ +am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ +am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ +am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +datadir = @datadir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +src = @src@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ + +# To disable automatic dependency tracking if using other tools than +# gcc and gmake, add the option 'no-dependencies' +AUTOMAKE_OPTIONS = 1.8 +m4datadir = $(datadir)/aclocal +m4data_DATA = speex.m4 +pkgconfigdir = $(libdir)/pkgconfig +pkgconfig_DATA = speex.pc +EXTRA_DIST = Speex.spec Speex.spec.in Speex.kdevelop speex.m4 speex.pc.in + +#Fools KDevelop into including all files +SUBDIRS = libspeex include @src@ doc win32 symbian +DIST_SUBDIRS = libspeex include src doc win32 symbian +all: config.h + $(MAKE) $(AM_MAKEFLAGS) all-recursive + +.SUFFIXES: +am--refresh: + @: +$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + echo ' cd $(srcdir) && $(AUTOMAKE) --gnu '; \ + cd $(srcdir) && $(AUTOMAKE) --gnu \ + && exit 0; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu Makefile'; \ + cd $(top_srcdir) && \ + $(AUTOMAKE) --gnu Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + echo ' $(SHELL) ./config.status'; \ + $(SHELL) ./config.status;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + $(SHELL) ./config.status --recheck + +$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) + cd $(srcdir) && $(AUTOCONF) +$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) + cd $(srcdir) && $(ACLOCAL) $(ACLOCAL_AMFLAGS) + +config.h: stamp-h1 + @if test ! -f $@; then \ + rm -f stamp-h1; \ + $(MAKE) stamp-h1; \ + else :; fi + +stamp-h1: $(srcdir)/config.h.in $(top_builddir)/config.status + @rm -f stamp-h1 + cd $(top_builddir) && $(SHELL) ./config.status config.h +$(srcdir)/config.h.in: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) + cd $(top_srcdir) && $(AUTOHEADER) + rm -f stamp-h1 + touch $@ + +distclean-hdr: + -rm -f config.h stamp-h1 +Speex.spec: $(top_builddir)/config.status $(srcdir)/Speex.spec.in + cd $(top_builddir) && $(SHELL) ./config.status $@ +speex.pc: $(top_builddir)/config.status $(srcdir)/speex.pc.in + cd $(top_builddir) && $(SHELL) ./config.status $@ + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +distclean-libtool: + -rm -f libtool +uninstall-info-am: +install-m4dataDATA: $(m4data_DATA) + @$(NORMAL_INSTALL) + test -z "$(m4datadir)" || $(mkdir_p) "$(DESTDIR)$(m4datadir)" + @list='$(m4data_DATA)'; for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + f="`echo $$p | sed -e 's|^.*/||'`"; \ + echo " $(m4dataDATA_INSTALL) '$$d$$p' '$(DESTDIR)$(m4datadir)/$$f'"; \ + $(m4dataDATA_INSTALL) "$$d$$p" "$(DESTDIR)$(m4datadir)/$$f"; \ + done + +uninstall-m4dataDATA: + @$(NORMAL_UNINSTALL) + @list='$(m4data_DATA)'; for p in $$list; do \ + f="`echo $$p | sed -e 's|^.*/||'`"; \ + echo " rm -f '$(DESTDIR)$(m4datadir)/$$f'"; \ + rm -f "$(DESTDIR)$(m4datadir)/$$f"; \ + done +install-pkgconfigDATA: $(pkgconfig_DATA) + @$(NORMAL_INSTALL) + test -z "$(pkgconfigdir)" || $(mkdir_p) "$(DESTDIR)$(pkgconfigdir)" + @list='$(pkgconfig_DATA)'; for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + f="`echo $$p | sed -e 's|^.*/||'`"; \ + echo " $(pkgconfigDATA_INSTALL) '$$d$$p' '$(DESTDIR)$(pkgconfigdir)/$$f'"; \ + $(pkgconfigDATA_INSTALL) "$$d$$p" "$(DESTDIR)$(pkgconfigdir)/$$f"; \ + done + +uninstall-pkgconfigDATA: + @$(NORMAL_UNINSTALL) + @list='$(pkgconfig_DATA)'; for p in $$list; do \ + f="`echo $$p | sed -e 's|^.*/||'`"; \ + echo " rm -f '$(DESTDIR)$(pkgconfigdir)/$$f'"; \ + rm -f "$(DESTDIR)$(pkgconfigdir)/$$f"; \ + done + +# This directory's subdirectories are mostly independent; you can cd +# into them and run `make' without going through this Makefile. +# To change the values of `make' variables: instead of editing Makefiles, +# (1) if the variable is set in `config.status', edit `config.status' +# (which will cause the Makefiles to be regenerated when you run `make'); +# (2) otherwise, pass the desired values on the `make' command line. +$(RECURSIVE_TARGETS): + @set fnord $$MAKEFLAGS; amf=$$2; \ + dot_seen=no; \ + target=`echo $@ | sed s/-recursive//`; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + dot_seen=yes; \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || case "$$amf" in *=*) exit 1;; *k*) fail=yes;; *) exit 1;; esac; \ + done; \ + if test "$$dot_seen" = "no"; then \ + $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ + fi; test -z "$$fail" + +mostlyclean-recursive clean-recursive distclean-recursive \ +maintainer-clean-recursive: + @set fnord $$MAKEFLAGS; amf=$$2; \ + dot_seen=no; \ + case "$@" in \ + distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ + *) list='$(SUBDIRS)' ;; \ + esac; \ + rev=''; for subdir in $$list; do \ + if test "$$subdir" = "."; then :; else \ + rev="$$subdir $$rev"; \ + fi; \ + done; \ + rev="$$rev ."; \ + target=`echo $@ | sed s/-recursive//`; \ + for subdir in $$rev; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || case "$$amf" in *=*) exit 1;; *k*) fail=yes;; *) exit 1;; esac; \ + done && test -z "$$fail" +tags-recursive: + list='$(SUBDIRS)'; for subdir in $$list; do \ + test "$$subdir" = . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \ + done +ctags-recursive: + list='$(SUBDIRS)'; for subdir in $$list; do \ + test "$$subdir" = . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \ + done + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: tags-recursive $(HEADERS) $(SOURCES) config.h.in $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + tags=; \ + here=`pwd`; \ + if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ + include_option=--etags-include; \ + empty_fix=.; \ + else \ + include_option=--include; \ + empty_fix=; \ + fi; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test ! -f $$subdir/TAGS || \ + tags="$$tags $$include_option=$$here/$$subdir/TAGS"; \ + fi; \ + done; \ + list='$(SOURCES) $(HEADERS) config.h.in $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$tags $$unique; \ + fi +ctags: CTAGS +CTAGS: ctags-recursive $(HEADERS) $(SOURCES) config.h.in $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + tags=; \ + here=`pwd`; \ + list='$(SOURCES) $(HEADERS) config.h.in $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + test -z "$(CTAGS_ARGS)$$tags$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$tags $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && cd $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) $$here + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + $(am__remove_distdir) + mkdir $(distdir) + $(mkdir_p) $(distdir)/. $(distdir)/include/speex + @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ + list='$(DISTFILES)'; for file in $$list; do \ + case $$file in \ + $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ + $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ + esac; \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test "$$dir" != "$$file" && test "$$dir" != "."; then \ + dir="/$$dir"; \ + $(mkdir_p) "$(distdir)$$dir"; \ + else \ + dir=''; \ + fi; \ + if test -d $$d/$$file; then \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + fi; \ + cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + else \ + test -f $(distdir)/$$file \ + || cp -p $$d/$$file $(distdir)/$$file \ + || exit 1; \ + fi; \ + done + list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test -d "$(distdir)/$$subdir" \ + || mkdir "$(distdir)/$$subdir" \ + || exit 1; \ + (cd $$subdir && \ + $(MAKE) $(AM_MAKEFLAGS) \ + top_distdir="../$(top_distdir)" \ + distdir="../$(distdir)/$$subdir" \ + distdir) \ + || exit 1; \ + fi; \ + done + -find $(distdir) -type d ! -perm -777 -exec chmod a+rwx {} \; -o \ + ! -type d ! -perm -444 -links 1 -exec chmod a+r {} \; -o \ + ! -type d ! -perm -400 -exec chmod a+r {} \; -o \ + ! -type d ! -perm -444 -exec $(SHELL) $(install_sh) -c -m a+r {} {} \; \ + || chmod -R a+r $(distdir) +dist-gzip: distdir + $(AMTAR) chof - $(distdir) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz + $(am__remove_distdir) + +dist-bzip2: distdir + $(AMTAR) chof - $(distdir) | bzip2 -9 -c >$(distdir).tar.bz2 + $(am__remove_distdir) + +dist-tarZ: distdir + $(AMTAR) chof - $(distdir) | compress -c >$(distdir).tar.Z + $(am__remove_distdir) + +dist-shar: distdir + shar $(distdir) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).shar.gz + $(am__remove_distdir) + +dist-zip: distdir + -rm -f $(distdir).zip + zip -rq $(distdir).zip $(distdir) + $(am__remove_distdir) + +dist dist-all: distdir + $(AMTAR) chof - $(distdir) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz + $(am__remove_distdir) + +# This target untars the dist file and tries a VPATH configuration. Then +# it guarantees that the distribution is self-contained by making another +# tarfile. +distcheck: dist + case '$(DIST_ARCHIVES)' in \ + *.tar.gz*) \ + GZIP=$(GZIP_ENV) gunzip -c $(distdir).tar.gz | $(AMTAR) xf - ;;\ + *.tar.bz2*) \ + bunzip2 -c $(distdir).tar.bz2 | $(AMTAR) xf - ;;\ + *.tar.Z*) \ + uncompress -c $(distdir).tar.Z | $(AMTAR) xf - ;;\ + *.shar.gz*) \ + GZIP=$(GZIP_ENV) gunzip -c $(distdir).shar.gz | unshar ;;\ + *.zip*) \ + unzip $(distdir).zip ;;\ + esac + chmod -R a-w $(distdir); chmod a+w $(distdir) + mkdir $(distdir)/_build + mkdir $(distdir)/_inst + chmod a-w $(distdir) + dc_install_base=`$(am__cd) $(distdir)/_inst && pwd | sed -e 's,^[^:\\/]:[\\/],/,'` \ + && dc_destdir="$${TMPDIR-/tmp}/am-dc-$$$$/" \ + && cd $(distdir)/_build \ + && ../configure --srcdir=.. --prefix="$$dc_install_base" \ + $(DISTCHECK_CONFIGURE_FLAGS) \ + && $(MAKE) $(AM_MAKEFLAGS) \ + && $(MAKE) $(AM_MAKEFLAGS) dvi \ + && $(MAKE) $(AM_MAKEFLAGS) check \ + && $(MAKE) $(AM_MAKEFLAGS) install \ + && $(MAKE) $(AM_MAKEFLAGS) installcheck \ + && $(MAKE) $(AM_MAKEFLAGS) uninstall \ + && $(MAKE) $(AM_MAKEFLAGS) distuninstallcheck_dir="$$dc_install_base" \ + distuninstallcheck \ + && chmod -R a-w "$$dc_install_base" \ + && ({ \ + (cd ../.. && umask 077 && mkdir "$$dc_destdir") \ + && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" install \ + && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" uninstall \ + && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" \ + distuninstallcheck_dir="$$dc_destdir" distuninstallcheck; \ + } || { rm -rf "$$dc_destdir"; exit 1; }) \ + && rm -rf "$$dc_destdir" \ + && $(MAKE) $(AM_MAKEFLAGS) dist \ + && rm -rf $(DIST_ARCHIVES) \ + && $(MAKE) $(AM_MAKEFLAGS) distcleancheck + $(am__remove_distdir) + @(echo "$(distdir) archives ready for distribution: "; \ + list='$(DIST_ARCHIVES)'; for i in $$list; do echo $$i; done) | \ + sed -e '1{h;s/./=/g;p;x;}' -e '$${p;x;}' +distuninstallcheck: + @cd $(distuninstallcheck_dir) \ + && test `$(distuninstallcheck_listfiles) | wc -l` -le 1 \ + || { echo "ERROR: files left after uninstall:" ; \ + if test -n "$(DESTDIR)"; then \ + echo " (check DESTDIR support)"; \ + fi ; \ + $(distuninstallcheck_listfiles) ; \ + exit 1; } >&2 +distcleancheck: distclean + @if test '$(srcdir)' = . ; then \ + echo "ERROR: distcleancheck can only run from a VPATH build" ; \ + exit 1 ; \ + fi + @test `$(distcleancheck_listfiles) | wc -l` -eq 0 \ + || { echo "ERROR: files left in build directory after distclean:" ; \ + $(distcleancheck_listfiles) ; \ + exit 1; } >&2 +check-am: all-am +check: check-recursive +all-am: Makefile $(DATA) config.h +installdirs: installdirs-recursive +installdirs-am: + for dir in "$(DESTDIR)$(m4datadir)" "$(DESTDIR)$(pkgconfigdir)"; do \ + test -z "$$dir" || $(mkdir_p) "$$dir"; \ + done +install: install-recursive +install-exec: install-exec-recursive +install-data: install-data-recursive +uninstall: uninstall-recursive + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-recursive +install-strip: + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + `test -z '$(STRIP)' || \ + echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -rm -f $(CONFIG_CLEAN_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-recursive + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-recursive + -rm -f $(am__CONFIG_DISTCLEAN_FILES) + -rm -f Makefile +distclean-am: clean-am distclean-generic distclean-hdr \ + distclean-libtool distclean-tags + +dvi: dvi-recursive + +dvi-am: + +html: html-recursive + +info: info-recursive + +info-am: + +install-data-am: install-m4dataDATA install-pkgconfigDATA + +install-exec-am: + +install-info: install-info-recursive + +install-man: + +installcheck-am: + +maintainer-clean: maintainer-clean-recursive + -rm -f $(am__CONFIG_DISTCLEAN_FILES) + -rm -rf $(top_srcdir)/autom4te.cache + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-recursive + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-recursive + +pdf-am: + +ps: ps-recursive + +ps-am: + +uninstall-am: uninstall-info-am uninstall-m4dataDATA \ + uninstall-pkgconfigDATA + +uninstall-info: uninstall-info-recursive + +.PHONY: $(RECURSIVE_TARGETS) CTAGS GTAGS all all-am am--refresh check \ + check-am clean clean-generic clean-libtool clean-recursive \ + ctags ctags-recursive dist dist-all dist-bzip2 dist-gzip \ + dist-shar dist-tarZ dist-zip distcheck distclean \ + distclean-generic distclean-hdr distclean-libtool \ + distclean-recursive distclean-tags distcleancheck distdir \ + distuninstallcheck dvi dvi-am html html-am info info-am \ + install install-am install-data install-data-am install-exec \ + install-exec-am install-info install-info-am \ + install-m4dataDATA install-man install-pkgconfigDATA \ + install-strip installcheck installcheck-am installdirs \ + installdirs-am maintainer-clean maintainer-clean-generic \ + maintainer-clean-recursive mostlyclean mostlyclean-generic \ + mostlyclean-libtool mostlyclean-recursive pdf pdf-am ps ps-am \ + tags tags-recursive uninstall uninstall-am uninstall-info-am \ + uninstall-m4dataDATA uninstall-pkgconfigDATA + + +rpm: dist + rpmbuild -ta ${PACKAGE}-${VERSION}.tar.gz +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/mozilla/zap/zmk/speex-1.1.10/NEWS b/mozilla/zap/zmk/speex-1.1.10/NEWS new file mode 100755 index 00000000000..2efbf9181e8 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/NEWS @@ -0,0 +1 @@ +2002/02/13: Creation of the "Speex" project diff --git a/mozilla/zap/zmk/speex-1.1.10/README b/mozilla/zap/zmk/speex-1.1.10/README new file mode 100755 index 00000000000..2861f195b07 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/README @@ -0,0 +1,9 @@ +See INSTALL file for instruction on how to install Speex. + +The Speex is a patent-free, Open Source/Free Software voice codec. Unlike other codecs like MP3 and Ogg Vorbis, Speex is designed to compress voice at bitrates in the 2-45 kbps range. Possible applications include VoIP, internet audio streaming, archiving of speech data (e.g. voice mail), and audio books. In some sense, it is meant to be complementary to the Ogg Vorbis codec. + +To use the Speex command line tools: + +% speexenc [options] input_file.wav compressed_file.spx + +% speexdec [options] compressed_file.spx output_file.wav diff --git a/mozilla/zap/zmk/speex-1.1.10/Speex.kdevelop b/mozilla/zap/zmk/speex-1.1.10/Speex.kdevelop new file mode 100755 index 00000000000..d10552e9504 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/Speex.kdevelop @@ -0,0 +1,123 @@ + + + + Jean-Marc Valin + jean-marc.valin@usherbrooke.ca + $VERSION$ + KDevAutoProject + C + + . + false + + + + + + src/Speex + default + + + src/Speex + executable + / + + false + true + + + + + optimized + GccOptions + GppOptions + G77Options + -O2 -g0 + + + --enable-debug=full + debug + GccOptions + GppOptions + G77Options + -O0 -g3 + + + + + + + + false + 1 + false + + + + + + libtool + + + + + + true + false + false + + + false + true + + + + + + + + + + + + + true + true + true + false + true + true + true + 250 + 400 + 250 + + + + + false + false + + + *.o,*.lo,CVS + true + + + + + html/ + html/ + + + + + + + + + + .h + .cpp + + + diff --git a/mozilla/zap/zmk/speex-1.1.10/Speex.spec b/mozilla/zap/zmk/speex-1.1.10/Speex.spec new file mode 100755 index 00000000000..3d0b3777180 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/Speex.spec @@ -0,0 +1,70 @@ +%define name speex +%define ver 1.1.10 +%define rel 1 + +Summary: An open-source, patent-free speech codec +Name: %name +Version: %ver +Release: %rel +Copyright: BSD +Group: Application/Devel +Source: http://www.speex.org/download/%{name}-%{ver}.tar.gz +URL: http://www.speex.org/ +Vendor: Speex +Packager: Jean-Marc Valin (jean-marc.valin@hermes.usherb.ca) +BuildRoot: /var/tmp/%{name}-build-root +Docdir: /usr/share/doc + +%description +Speex is a patent-free audio codec designed especially for voice (unlike +Vorbis which targets general audio) signals and providing good narrowband +and wideband quality. This project aims to be complementary to the Vorbis +codec. + +%package devel +Summary: Speex development files +Group: Development/Libraries +Requires: %{name} = %{version} + +%description devel +Speex development files. + +%changelog +* Thu Oct 03 2002 Jean-Marc Valin +- Added devel package inspired from PLD spec file + +* Tue Jul 30 2002 Fredrik Rambris 0.5.2 +- Added buildroot and docdir and ldconfig. Makes it builadble by non-roots + and also doesn't write to actual library paths when building. + +%prep +%setup + +%build +export CFLAGS='-O3' +./configure --prefix=/usr --enable-shared --enable-static +make + +%install +rm -rf $RPM_BUILD_ROOT +make DESTDIR=$RPM_BUILD_ROOT install + +%post -p /sbin/ldconfig +%postun -p /sbin/ldconfig + +%files +%defattr(644,root,root,755) +%doc COPYING AUTHORS ChangeLog NEWS README +%doc doc/manual.pdf +/usr/share/man/man1/speexenc.1* +/usr/share/man/man1/speexdec.1* +%attr(755,root,root) %{_bindir}/speex* +%attr(755,root,root) %{_libdir}/libspeex*.so* + +%files devel +%defattr(644,root,root,755) +%attr(755,root,root) %{_libdir}/libspeex*.la +%{_includedir}/speex/speex*.h +/usr/share/aclocal/speex.m4 +%{_libdir}/pkgconfig/speex.pc +%{_libdir}/libspeex*.a diff --git a/mozilla/zap/zmk/speex-1.1.10/Speex.spec.in b/mozilla/zap/zmk/speex-1.1.10/Speex.spec.in new file mode 100755 index 00000000000..5c8a126063a --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/Speex.spec.in @@ -0,0 +1,70 @@ +%define name @PACKAGE@ +%define ver @VERSION@ +%define rel 1 + +Summary: An open-source, patent-free speech codec +Name: %name +Version: %ver +Release: %rel +Copyright: BSD +Group: Application/Devel +Source: http://www.speex.org/download/%{name}-%{ver}.tar.gz +URL: http://www.speex.org/ +Vendor: Speex +Packager: Jean-Marc Valin (jean-marc.valin@hermes.usherb.ca) +BuildRoot: /var/tmp/%{name}-build-root +Docdir: /usr/share/doc + +%description +Speex is a patent-free audio codec designed especially for voice (unlike +Vorbis which targets general audio) signals and providing good narrowband +and wideband quality. This project aims to be complementary to the Vorbis +codec. + +%package devel +Summary: Speex development files +Group: Development/Libraries +Requires: %{name} = %{version} + +%description devel +Speex development files. + +%changelog +* Thu Oct 03 2002 Jean-Marc Valin +- Added devel package inspired from PLD spec file + +* Tue Jul 30 2002 Fredrik Rambris 0.5.2 +- Added buildroot and docdir and ldconfig. Makes it builadble by non-roots + and also doesn't write to actual library paths when building. + +%prep +%setup + +%build +export CFLAGS='-O3' +./configure --prefix=/usr --enable-shared --enable-static +make + +%install +rm -rf $RPM_BUILD_ROOT +make DESTDIR=$RPM_BUILD_ROOT install + +%post -p /sbin/ldconfig +%postun -p /sbin/ldconfig + +%files +%defattr(644,root,root,755) +%doc COPYING AUTHORS ChangeLog NEWS README +%doc doc/manual.pdf +/usr/share/man/man1/speexenc.1* +/usr/share/man/man1/speexdec.1* +%attr(755,root,root) %{_bindir}/speex* +%attr(755,root,root) %{_libdir}/libspeex*.so* + +%files devel +%defattr(644,root,root,755) +%attr(755,root,root) %{_libdir}/libspeex*.la +%{_includedir}/speex/speex*.h +/usr/share/aclocal/speex.m4 +%{_libdir}/pkgconfig/speex.pc +%{_libdir}/libspeex*.a diff --git a/mozilla/zap/zmk/speex-1.1.10/TODO b/mozilla/zap/zmk/speex-1.1.10/TODO new file mode 100755 index 00000000000..3cf83a4314a --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/TODO @@ -0,0 +1,35 @@ +Allocator override (speex_lib_ctl) +Support alloca/variable size arrays +Better error handling +Fixed-point: + - Packet-loss concealment + - Wideband + - Initialization + - Jitter buffer +Echo cancellation: + - Re-enable denoiser hooks + - Improve doubletalk detector +Denoiser: + - Fix hyper-geometric approximation + - Do some tuning +VAD-NG: + - Use median filtering instead of "non-linear mean" + + + +Features +-Add maximum/minimum bit-rate control for VBR +-Get the encoder to use the rate of packet loss (more conservative pitch gains) +-Improve error handling (with perror-like call?) + +Long-term quality improvements +-Improve perceptual enhancement (including wideband) + +Standards +-Complete Speex RTP profile +-MIME type registration + +ideas: +Peelable stream (double codebook, higher bands, stereo) +LPC from spectral domain +Better psycho-acoustic model. Masking curve from Vorbis? diff --git a/mozilla/zap/zmk/speex-1.1.10/acinclude.m4 b/mozilla/zap/zmk/speex-1.1.10/acinclude.m4 new file mode 100755 index 00000000000..e964a8cd087 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/acinclude.m4 @@ -0,0 +1,102 @@ +# Configure paths for libogg +# Jack Moffitt 10-21-2000 +# Shamelessly stolen from Owen Taylor and Manish Singh + +dnl XIPH_PATH_OGG([ACTION-IF-FOUND [, ACTION-IF-NOT-FOUND]]) +dnl Test for libogg, and define OGG_CFLAGS and OGG_LIBS +dnl +AC_DEFUN([XIPH_PATH_OGG], +[dnl +dnl Get the cflags and libraries +dnl +AC_ARG_WITH(ogg,[ --with-ogg=PFX Prefix where libogg is installed (optional)], ogg_prefix="$withval", ogg_prefix="") +AC_ARG_WITH(ogg-libraries,[ --with-ogg-libraries=DIR Directory where libogg library is installed (optional)], ogg_libraries="$withval", ogg_libraries="") +AC_ARG_WITH(ogg-includes,[ --with-ogg-includes=DIR Directory where libogg header files are installed (optional)], ogg_includes="$withval", ogg_includes="") +AC_ARG_ENABLE(oggtest, [ --disable-oggtest Do not try to compile and run a test Ogg program],, enable_oggtest=yes) + + if test "x$ogg_libraries" != "x" ; then + OGG_LIBS="-L$ogg_libraries" + elif test "x$ogg_prefix" != "x" ; then + OGG_LIBS="-L$ogg_prefix/lib" + elif test "x$prefix" != "xNONE" ; then + OGG_LIBS="-L$prefix/lib" + fi + + OGG_LIBS="$OGG_LIBS -logg" + + if test "x$ogg_includes" != "x" ; then + OGG_CFLAGS="-I$ogg_includes" + elif test "x$ogg_prefix" != "x" ; then + OGG_CFLAGS="-I$ogg_prefix/include" + elif test "x$prefix" != "xNONE"; then + OGG_CFLAGS="-I$prefix/include" + fi + + AC_MSG_CHECKING(for Ogg) + no_ogg="" + + + if test "x$enable_oggtest" = "xyes" ; then + ac_save_CFLAGS="$CFLAGS" + ac_save_LIBS="$LIBS" + CFLAGS="$CFLAGS $OGG_CFLAGS" + LIBS="$LIBS $OGG_LIBS" +dnl +dnl Now check if the installed Ogg is sufficiently new. +dnl + rm -f conf.oggtest + AC_TRY_RUN([ +#include +#include +#include +#include + +int main () +{ + system("touch conf.oggtest"); + return 0; +} + +],, no_ogg=yes,[echo $ac_n "cross compiling; assumed OK... $ac_c"]) + CFLAGS="$ac_save_CFLAGS" + LIBS="$ac_save_LIBS" + fi + + if test "x$no_ogg" = "x" ; then + AC_MSG_RESULT(yes) + ifelse([$1], , :, [$1]) + else + AC_MSG_RESULT(no) + if test -f conf.oggtest ; then + : + else + echo "*** Could not run Ogg test program, checking why..." + CFLAGS="$CFLAGS $OGG_CFLAGS" + LIBS="$LIBS $OGG_LIBS" + AC_TRY_LINK([ +#include +#include +], [ return 0; ], + [ echo "*** The test program compiled, but did not run. This usually means" + echo "*** that the run-time linker is not finding Ogg or finding the wrong" + echo "*** version of Ogg. If it is not finding Ogg, you'll need to set your" + echo "*** LD_LIBRARY_PATH environment variable, or edit /etc/ld.so.conf to point" + echo "*** to the installed location Also, make sure you have run ldconfig if that" + echo "*** is required on your system" + echo "***" + echo "*** If you have an old version installed, it is best to remove it, although" + echo "*** you may also be able to get things to work by modifying LD_LIBRARY_PATH"], + [ echo "*** The test program failed to compile or link. See the file config.log for the" + echo "*** exact error that occured. This usually means Ogg was incorrectly installed" + echo "*** or that you have moved Ogg since it was installed." ]) + CFLAGS="$ac_save_CFLAGS" + LIBS="$ac_save_LIBS" + fi + OGG_CFLAGS="" + OGG_LIBS="" + ifelse([$2], , :, [$2]) + fi + AC_SUBST(OGG_CFLAGS) + AC_SUBST(OGG_LIBS) + rm -f conf.oggtest +]) diff --git a/mozilla/zap/zmk/speex-1.1.10/config.guess b/mozilla/zap/zmk/speex-1.1.10/config.guess new file mode 100755 index 00000000000..e86f51e0519 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/config.guess @@ -0,0 +1,1465 @@ +#! /bin/sh +# Attempt to guess a canonical system name. +# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, +# 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc. + +timestamp='2005-04-22' + +# This file is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +# +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + +# Originally written by Per Bothner . +# Please send patches to . Submit a context +# diff and a properly formatted ChangeLog entry. +# +# This script attempts to guess a canonical system name similar to +# config.sub. If it succeeds, it prints the system name on stdout, and +# exits with 0. Otherwise, it exits with 1. +# +# The plan is that this can be called by configure scripts if you +# don't specify an explicit build system type. + +me=`echo "$0" | sed -e 's,.*/,,'` + +usage="\ +Usage: $0 [OPTION] + +Output the configuration name of the system \`$me' is run on. + +Operation modes: + -h, --help print this help, then exit + -t, --time-stamp print date of last modification, then exit + -v, --version print version number, then exit + +Report bugs and patches to ." + +version="\ +GNU config.guess ($timestamp) + +Originally written by Per Bothner. +Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005 +Free Software Foundation, Inc. + +This is free software; see the source for copying conditions. There is NO +warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." + +help=" +Try \`$me --help' for more information." + +# Parse command line +while test $# -gt 0 ; do + case $1 in + --time-stamp | --time* | -t ) + echo "$timestamp" ; exit 0 ;; + --version | -v ) + echo "$version" ; exit 0 ;; + --help | --h* | -h ) + echo "$usage"; exit 0 ;; + -- ) # Stop option processing + shift; break ;; + - ) # Use stdin as input. + break ;; + -* ) + echo "$me: invalid option $1$help" >&2 + exit 1 ;; + * ) + break ;; + esac +done + +if test $# != 0; then + echo "$me: too many arguments$help" >&2 + exit 1 +fi + +trap 'exit 1' 1 2 15 + +# CC_FOR_BUILD -- compiler used by this script. Note that the use of a +# compiler to aid in system detection is discouraged as it requires +# temporary files to be created and, as you can see below, it is a +# headache to deal with in a portable fashion. + +# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still +# use `HOST_CC' if defined, but it is deprecated. + +# Portable tmp directory creation inspired by the Autoconf team. + +set_cc_for_build=' +trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ; +trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ; +: ${TMPDIR=/tmp} ; + { tmp=`(umask 077 && mktemp -d -q "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } || + { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } || + { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } || + { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ; +dummy=$tmp/dummy ; +tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ; +case $CC_FOR_BUILD,$HOST_CC,$CC in + ,,) echo "int x;" > $dummy.c ; + for c in cc gcc c89 c99 ; do + if ($c -c -o $dummy.o $dummy.c) >/dev/null 2>&1 ; then + CC_FOR_BUILD="$c"; break ; + fi ; + done ; + if test x"$CC_FOR_BUILD" = x ; then + CC_FOR_BUILD=no_compiler_found ; + fi + ;; + ,,*) CC_FOR_BUILD=$CC ;; + ,*,*) CC_FOR_BUILD=$HOST_CC ;; +esac ;' + +# This is needed to find uname on a Pyramid OSx when run in the BSD universe. +# (ghazi@noc.rutgers.edu 1994-08-24) +if (test -f /.attbin/uname) >/dev/null 2>&1 ; then + PATH=$PATH:/.attbin ; export PATH +fi + +UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown +UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown +UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown +UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown + +# Note: order is significant - the case branches are not exclusive. + +case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in + *:NetBSD:*:*) + # NetBSD (nbsd) targets should (where applicable) match one or + # more of the tupples: *-*-netbsdelf*, *-*-netbsdaout*, + # *-*-netbsdecoff* and *-*-netbsd*. For targets that recently + # switched to ELF, *-*-netbsd* would select the old + # object file format. This provides both forward + # compatibility and a consistent mechanism for selecting the + # object file format. + # + # Note: NetBSD doesn't particularly care about the vendor + # portion of the name. We always set it to "unknown". + sysctl="sysctl -n hw.machine_arch" + UNAME_MACHINE_ARCH=`(/sbin/$sysctl 2>/dev/null || \ + /usr/sbin/$sysctl 2>/dev/null || echo unknown)` + case "${UNAME_MACHINE_ARCH}" in + armeb) machine=armeb-unknown ;; + arm*) machine=arm-unknown ;; + sh3el) machine=shl-unknown ;; + sh3eb) machine=sh-unknown ;; + *) machine=${UNAME_MACHINE_ARCH}-unknown ;; + esac + # The Operating System including object format, if it has switched + # to ELF recently, or will in the future. + case "${UNAME_MACHINE_ARCH}" in + arm*|i386|m68k|ns32k|sh3*|sparc|vax) + eval $set_cc_for_build + if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \ + | grep __ELF__ >/dev/null + then + # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout). + # Return netbsd for either. FIX? + os=netbsd + else + os=netbsdelf + fi + ;; + *) + os=netbsd + ;; + esac + # The OS release + # Debian GNU/NetBSD machines have a different userland, and + # thus, need a distinct triplet. However, they do not need + # kernel version information, so it can be replaced with a + # suitable tag, in the style of linux-gnu. + case "${UNAME_VERSION}" in + Debian*) + release='-gnu' + ;; + *) + release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'` + ;; + esac + # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM: + # contains redundant information, the shorter form: + # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used. + echo "${machine}-${os}${release}" + exit 0 ;; + amd64:OpenBSD:*:*) + echo x86_64-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + amiga:OpenBSD:*:*) + echo m68k-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + cats:OpenBSD:*:*) + echo arm-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + hp300:OpenBSD:*:*) + echo m68k-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + luna88k:OpenBSD:*:*) + echo m88k-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + mac68k:OpenBSD:*:*) + echo m68k-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + macppc:OpenBSD:*:*) + echo powerpc-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + mvme68k:OpenBSD:*:*) + echo m68k-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + mvme88k:OpenBSD:*:*) + echo m88k-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + mvmeppc:OpenBSD:*:*) + echo powerpc-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + sgi:OpenBSD:*:*) + echo mips64-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + sun3:OpenBSD:*:*) + echo m68k-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + *:OpenBSD:*:*) + echo ${UNAME_MACHINE}-unknown-openbsd${UNAME_RELEASE} + exit 0 ;; + *:ekkoBSD:*:*) + echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE} + exit 0 ;; + macppc:MirBSD:*:*) + echo powerppc-unknown-mirbsd${UNAME_RELEASE} + exit 0 ;; + *:MirBSD:*:*) + echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE} + exit 0 ;; + alpha:OSF1:*:*) + case $UNAME_RELEASE in + *4.0) + UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'` + ;; + *5.*) + UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'` + ;; + esac + # According to Compaq, /usr/sbin/psrinfo has been available on + # OSF/1 and Tru64 systems produced since 1995. I hope that + # covers most systems running today. This code pipes the CPU + # types through head -n 1, so we only detect the type of CPU 0. + ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^ The alpha \(.*\) processor.*$/\1/p' | head -n 1` + case "$ALPHA_CPU_TYPE" in + "EV4 (21064)") + UNAME_MACHINE="alpha" ;; + "EV4.5 (21064)") + UNAME_MACHINE="alpha" ;; + "LCA4 (21066/21068)") + UNAME_MACHINE="alpha" ;; + "EV5 (21164)") + UNAME_MACHINE="alphaev5" ;; + "EV5.6 (21164A)") + UNAME_MACHINE="alphaev56" ;; + "EV5.6 (21164PC)") + UNAME_MACHINE="alphapca56" ;; + "EV5.7 (21164PC)") + UNAME_MACHINE="alphapca57" ;; + "EV6 (21264)") + UNAME_MACHINE="alphaev6" ;; + "EV6.7 (21264A)") + UNAME_MACHINE="alphaev67" ;; + "EV6.8CB (21264C)") + UNAME_MACHINE="alphaev68" ;; + "EV6.8AL (21264B)") + UNAME_MACHINE="alphaev68" ;; + "EV6.8CX (21264D)") + UNAME_MACHINE="alphaev68" ;; + "EV6.9A (21264/EV69A)") + UNAME_MACHINE="alphaev69" ;; + "EV7 (21364)") + UNAME_MACHINE="alphaev7" ;; + "EV7.9 (21364A)") + UNAME_MACHINE="alphaev79" ;; + esac + # A Pn.n version is a patched version. + # A Vn.n version is a released version. + # A Tn.n version is a released field test version. + # A Xn.n version is an unreleased experimental baselevel. + # 1.2 uses "1.2" for uname -r. + echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + exit 0 ;; + Alpha\ *:Windows_NT*:*) + # How do we know it's Interix rather than the generic POSIX subsystem? + # Should we change UNAME_MACHINE based on the output of uname instead + # of the specific Alpha model? + echo alpha-pc-interix + exit 0 ;; + 21064:Windows_NT:50:3) + echo alpha-dec-winnt3.5 + exit 0 ;; + Amiga*:UNIX_System_V:4.0:*) + echo m68k-unknown-sysv4 + exit 0;; + *:[Aa]miga[Oo][Ss]:*:*) + echo ${UNAME_MACHINE}-unknown-amigaos + exit 0 ;; + *:[Mm]orph[Oo][Ss]:*:*) + echo ${UNAME_MACHINE}-unknown-morphos + exit 0 ;; + *:OS/390:*:*) + echo i370-ibm-openedition + exit 0 ;; + *:z/VM:*:*) + echo s390-ibm-zvmoe + exit 0 ;; + *:OS400:*:*) + echo powerpc-ibm-os400 + exit 0 ;; + arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*) + echo arm-acorn-riscix${UNAME_RELEASE} + exit 0;; + SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*) + echo hppa1.1-hitachi-hiuxmpp + exit 0;; + Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*) + # akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE. + if test "`(/bin/universe) 2>/dev/null`" = att ; then + echo pyramid-pyramid-sysv3 + else + echo pyramid-pyramid-bsd + fi + exit 0 ;; + NILE*:*:*:dcosx) + echo pyramid-pyramid-svr4 + exit 0 ;; + DRS?6000:unix:4.0:6*) + echo sparc-icl-nx6 + exit 0 ;; + DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*) + case `/usr/bin/uname -p` in + sparc) echo sparc-icl-nx7 && exit 0 ;; + esac ;; + sun4H:SunOS:5.*:*) + echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit 0 ;; + sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*) + echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit 0 ;; + i86pc:SunOS:5.*:*) + echo i386-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit 0 ;; + sun4*:SunOS:6*:*) + # According to config.sub, this is the proper way to canonicalize + # SunOS6. Hard to guess exactly what SunOS6 will be like, but + # it's likely to be more like Solaris than SunOS4. + echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit 0 ;; + sun4*:SunOS:*:*) + case "`/usr/bin/arch -k`" in + Series*|S4*) + UNAME_RELEASE=`uname -v` + ;; + esac + # Japanese Language versions have a version number like `4.1.3-JL'. + echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'` + exit 0 ;; + sun3*:SunOS:*:*) + echo m68k-sun-sunos${UNAME_RELEASE} + exit 0 ;; + sun*:*:4.2BSD:*) + UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null` + test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3 + case "`/bin/arch`" in + sun3) + echo m68k-sun-sunos${UNAME_RELEASE} + ;; + sun4) + echo sparc-sun-sunos${UNAME_RELEASE} + ;; + esac + exit 0 ;; + aushp:SunOS:*:*) + echo sparc-auspex-sunos${UNAME_RELEASE} + exit 0 ;; + # The situation for MiNT is a little confusing. The machine name + # can be virtually everything (everything which is not + # "atarist" or "atariste" at least should have a processor + # > m68000). The system name ranges from "MiNT" over "FreeMiNT" + # to the lowercase version "mint" (or "freemint"). Finally + # the system name "TOS" denotes a system which is actually not + # MiNT. But MiNT is downward compatible to TOS, so this should + # be no problem. + atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*) + echo m68k-atari-mint${UNAME_RELEASE} + exit 0 ;; + atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*) + echo m68k-atari-mint${UNAME_RELEASE} + exit 0 ;; + *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*) + echo m68k-atari-mint${UNAME_RELEASE} + exit 0 ;; + milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*) + echo m68k-milan-mint${UNAME_RELEASE} + exit 0 ;; + hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*) + echo m68k-hades-mint${UNAME_RELEASE} + exit 0 ;; + *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*) + echo m68k-unknown-mint${UNAME_RELEASE} + exit 0 ;; + m68k:machten:*:*) + echo m68k-apple-machten${UNAME_RELEASE} + exit 0 ;; + powerpc:machten:*:*) + echo powerpc-apple-machten${UNAME_RELEASE} + exit 0 ;; + RISC*:Mach:*:*) + echo mips-dec-mach_bsd4.3 + exit 0 ;; + RISC*:ULTRIX:*:*) + echo mips-dec-ultrix${UNAME_RELEASE} + exit 0 ;; + VAX*:ULTRIX*:*:*) + echo vax-dec-ultrix${UNAME_RELEASE} + exit 0 ;; + 2020:CLIX:*:* | 2430:CLIX:*:*) + echo clipper-intergraph-clix${UNAME_RELEASE} + exit 0 ;; + mips:*:*:UMIPS | mips:*:*:RISCos) + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c +#ifdef __cplusplus +#include /* for printf() prototype */ + int main (int argc, char *argv[]) { +#else + int main (argc, argv) int argc; char *argv[]; { +#endif + #if defined (host_mips) && defined (MIPSEB) + #if defined (SYSTYPE_SYSV) + printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0); + #endif + #if defined (SYSTYPE_SVR4) + printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0); + #endif + #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD) + printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0); + #endif + #endif + exit (-1); + } +EOF + $CC_FOR_BUILD -o $dummy $dummy.c \ + && $dummy `echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` \ + && exit 0 + echo mips-mips-riscos${UNAME_RELEASE} + exit 0 ;; + Motorola:PowerMAX_OS:*:*) + echo powerpc-motorola-powermax + exit 0 ;; + Motorola:*:4.3:PL8-*) + echo powerpc-harris-powermax + exit 0 ;; + Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*) + echo powerpc-harris-powermax + exit 0 ;; + Night_Hawk:Power_UNIX:*:*) + echo powerpc-harris-powerunix + exit 0 ;; + m88k:CX/UX:7*:*) + echo m88k-harris-cxux7 + exit 0 ;; + m88k:*:4*:R4*) + echo m88k-motorola-sysv4 + exit 0 ;; + m88k:*:3*:R3*) + echo m88k-motorola-sysv3 + exit 0 ;; + AViiON:dgux:*:*) + # DG/UX returns AViiON for all architectures + UNAME_PROCESSOR=`/usr/bin/uname -p` + if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ] + then + if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \ + [ ${TARGET_BINARY_INTERFACE}x = x ] + then + echo m88k-dg-dgux${UNAME_RELEASE} + else + echo m88k-dg-dguxbcs${UNAME_RELEASE} + fi + else + echo i586-dg-dgux${UNAME_RELEASE} + fi + exit 0 ;; + M88*:DolphinOS:*:*) # DolphinOS (SVR3) + echo m88k-dolphin-sysv3 + exit 0 ;; + M88*:*:R3*:*) + # Delta 88k system running SVR3 + echo m88k-motorola-sysv3 + exit 0 ;; + XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3) + echo m88k-tektronix-sysv3 + exit 0 ;; + Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD) + echo m68k-tektronix-bsd + exit 0 ;; + *:IRIX*:*:*) + echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'` + exit 0 ;; + ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX. + echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id + exit 0 ;; # Note that: echo "'`uname -s`'" gives 'AIX ' + i*86:AIX:*:*) + echo i386-ibm-aix + exit 0 ;; + ia64:AIX:*:*) + if [ -x /usr/bin/oslevel ] ; then + IBM_REV=`/usr/bin/oslevel` + else + IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} + fi + echo ${UNAME_MACHINE}-ibm-aix${IBM_REV} + exit 0 ;; + *:AIX:2:3) + if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #include + + main() + { + if (!__power_pc()) + exit(1); + puts("powerpc-ibm-aix3.2.5"); + exit(0); + } +EOF + $CC_FOR_BUILD -o $dummy $dummy.c && $dummy && exit 0 + echo rs6000-ibm-aix3.2.5 + elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then + echo rs6000-ibm-aix3.2.4 + else + echo rs6000-ibm-aix3.2 + fi + exit 0 ;; + *:AIX:*:[45]) + IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'` + if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then + IBM_ARCH=rs6000 + else + IBM_ARCH=powerpc + fi + if [ -x /usr/bin/oslevel ] ; then + IBM_REV=`/usr/bin/oslevel` + else + IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} + fi + echo ${IBM_ARCH}-ibm-aix${IBM_REV} + exit 0 ;; + *:AIX:*:*) + echo rs6000-ibm-aix + exit 0 ;; + ibmrt:4.4BSD:*|romp-ibm:BSD:*) + echo romp-ibm-bsd4.4 + exit 0 ;; + ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and + echo romp-ibm-bsd${UNAME_RELEASE} # 4.3 with uname added to + exit 0 ;; # report: romp-ibm BSD 4.3 + *:BOSX:*:*) + echo rs6000-bull-bosx + exit 0 ;; + DPX/2?00:B.O.S.:*:*) + echo m68k-bull-sysv3 + exit 0 ;; + 9000/[34]??:4.3bsd:1.*:*) + echo m68k-hp-bsd + exit 0 ;; + hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*) + echo m68k-hp-bsd4.4 + exit 0 ;; + 9000/[34678]??:HP-UX:*:*) + HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` + case "${UNAME_MACHINE}" in + 9000/31? ) HP_ARCH=m68000 ;; + 9000/[34]?? ) HP_ARCH=m68k ;; + 9000/[678][0-9][0-9]) + if [ -x /usr/bin/getconf ]; then + sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null` + sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null` + case "${sc_cpu_version}" in + 523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0 + 528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1 + 532) # CPU_PA_RISC2_0 + case "${sc_kernel_bits}" in + 32) HP_ARCH="hppa2.0n" ;; + 64) HP_ARCH="hppa2.0w" ;; + '') HP_ARCH="hppa2.0" ;; # HP-UX 10.20 + esac ;; + esac + fi + if [ "${HP_ARCH}" = "" ]; then + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + + #define _HPUX_SOURCE + #include + #include + + int main () + { + #if defined(_SC_KERNEL_BITS) + long bits = sysconf(_SC_KERNEL_BITS); + #endif + long cpu = sysconf (_SC_CPU_VERSION); + + switch (cpu) + { + case CPU_PA_RISC1_0: puts ("hppa1.0"); break; + case CPU_PA_RISC1_1: puts ("hppa1.1"); break; + case CPU_PA_RISC2_0: + #if defined(_SC_KERNEL_BITS) + switch (bits) + { + case 64: puts ("hppa2.0w"); break; + case 32: puts ("hppa2.0n"); break; + default: puts ("hppa2.0"); break; + } break; + #else /* !defined(_SC_KERNEL_BITS) */ + puts ("hppa2.0"); break; + #endif + default: puts ("hppa1.0"); break; + } + exit (0); + } +EOF + (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy` + test -z "$HP_ARCH" && HP_ARCH=hppa + fi ;; + esac + if [ ${HP_ARCH} = "hppa2.0w" ] + then + # avoid double evaluation of $set_cc_for_build + test -n "$CC_FOR_BUILD" || eval $set_cc_for_build + if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E -) | grep __LP64__ >/dev/null + then + HP_ARCH="hppa2.0w" + else + HP_ARCH="hppa64" + fi + fi + echo ${HP_ARCH}-hp-hpux${HPUX_REV} + exit 0 ;; + ia64:HP-UX:*:*) + HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` + echo ia64-hp-hpux${HPUX_REV} + exit 0 ;; + 3050*:HI-UX:*:*) + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #include + int + main () + { + long cpu = sysconf (_SC_CPU_VERSION); + /* The order matters, because CPU_IS_HP_MC68K erroneously returns + true for CPU_PA_RISC1_0. CPU_IS_PA_RISC returns correct + results, however. */ + if (CPU_IS_PA_RISC (cpu)) + { + switch (cpu) + { + case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break; + case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break; + case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break; + default: puts ("hppa-hitachi-hiuxwe2"); break; + } + } + else if (CPU_IS_HP_MC68K (cpu)) + puts ("m68k-hitachi-hiuxwe2"); + else puts ("unknown-hitachi-hiuxwe2"); + exit (0); + } +EOF + $CC_FOR_BUILD -o $dummy $dummy.c && $dummy && exit 0 + echo unknown-hitachi-hiuxwe2 + exit 0 ;; + 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* ) + echo hppa1.1-hp-bsd + exit 0 ;; + 9000/8??:4.3bsd:*:*) + echo hppa1.0-hp-bsd + exit 0 ;; + *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*) + echo hppa1.0-hp-mpeix + exit 0 ;; + hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* ) + echo hppa1.1-hp-osf + exit 0 ;; + hp8??:OSF1:*:*) + echo hppa1.0-hp-osf + exit 0 ;; + i*86:OSF1:*:*) + if [ -x /usr/sbin/sysversion ] ; then + echo ${UNAME_MACHINE}-unknown-osf1mk + else + echo ${UNAME_MACHINE}-unknown-osf1 + fi + exit 0 ;; + parisc*:Lites*:*:*) + echo hppa1.1-hp-lites + exit 0 ;; + C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*) + echo c1-convex-bsd + exit 0 ;; + C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*) + if getsysinfo -f scalar_acc + then echo c32-convex-bsd + else echo c2-convex-bsd + fi + exit 0 ;; + C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*) + echo c34-convex-bsd + exit 0 ;; + C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*) + echo c38-convex-bsd + exit 0 ;; + C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*) + echo c4-convex-bsd + exit 0 ;; + CRAY*Y-MP:*:*:*) + echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit 0 ;; + CRAY*[A-Z]90:*:*:*) + echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \ + | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \ + -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \ + -e 's/\.[^.]*$/.X/' + exit 0 ;; + CRAY*TS:*:*:*) + echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit 0 ;; + CRAY*T3E:*:*:*) + echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit 0 ;; + CRAY*SV1:*:*:*) + echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit 0 ;; + *:UNICOS/mp:*:*) + echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit 0 ;; + F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*) + FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` + FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'` + echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" + exit 0 ;; + 5000:UNIX_System_V:4.*:*) + FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` + FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'` + echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" + exit 0 ;; + i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*) + echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE} + exit 0 ;; + sparc*:BSD/OS:*:*) + echo sparc-unknown-bsdi${UNAME_RELEASE} + exit 0 ;; + *:BSD/OS:*:*) + echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE} + exit 0 ;; + *:FreeBSD:*:*) + echo ${UNAME_MACHINE}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` + exit 0 ;; + i*:CYGWIN*:*) + echo ${UNAME_MACHINE}-pc-cygwin + exit 0 ;; + i*:MINGW*:*) + echo ${UNAME_MACHINE}-pc-mingw32 + exit 0 ;; + i*:PW*:*) + echo ${UNAME_MACHINE}-pc-pw32 + exit 0 ;; + x86:Interix*:[34]*) + echo i586-pc-interix${UNAME_RELEASE}|sed -e 's/\..*//' + exit 0 ;; + [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*) + echo i${UNAME_MACHINE}-pc-mks + exit 0 ;; + i*:Windows_NT*:* | Pentium*:Windows_NT*:*) + # How do we know it's Interix rather than the generic POSIX subsystem? + # It also conflicts with pre-2.0 versions of AT&T UWIN. Should we + # UNAME_MACHINE based on the output of uname instead of i386? + echo i586-pc-interix + exit 0 ;; + i*:UWIN*:*) + echo ${UNAME_MACHINE}-pc-uwin + exit 0 ;; + amd64:CYGWIN*:*:*) + echo x86_64-unknown-cygwin + exit 0 ;; + p*:CYGWIN*:*) + echo powerpcle-unknown-cygwin + exit 0 ;; + prep*:SunOS:5.*:*) + echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit 0 ;; + *:GNU:*:*) + # the GNU system + echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-gnu`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'` + exit 0 ;; + *:GNU/*:*:*) + # other systems with GNU libc and userland + echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-gnu + exit 0 ;; + i*86:Minix:*:*) + echo ${UNAME_MACHINE}-pc-minix + exit 0 ;; + arm*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit 0 ;; + cris:Linux:*:*) + echo cris-axis-linux-gnu + exit 0 ;; + crisv32:Linux:*:*) + echo crisv32-axis-linux-gnu + exit 0 ;; + frv:Linux:*:*) + echo frv-unknown-linux-gnu + exit 0 ;; + ia64:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit 0 ;; + m32r*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit 0 ;; + m68*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit 0 ;; + mips:Linux:*:*) + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #undef CPU + #undef mips + #undef mipsel + #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL) + CPU=mipsel + #else + #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB) + CPU=mips + #else + CPU= + #endif + #endif +EOF + eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep ^CPU=` + test x"${CPU}" != x && echo "${CPU}-unknown-linux-gnu" && exit 0 + ;; + mips64:Linux:*:*) + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #undef CPU + #undef mips64 + #undef mips64el + #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL) + CPU=mips64el + #else + #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB) + CPU=mips64 + #else + CPU= + #endif + #endif +EOF + eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep ^CPU=` + test x"${CPU}" != x && echo "${CPU}-unknown-linux-gnu" && exit 0 + ;; + ppc:Linux:*:*) + echo powerpc-unknown-linux-gnu + exit 0 ;; + ppc64:Linux:*:*) + echo powerpc64-unknown-linux-gnu + exit 0 ;; + alpha:Linux:*:*) + case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in + EV5) UNAME_MACHINE=alphaev5 ;; + EV56) UNAME_MACHINE=alphaev56 ;; + PCA56) UNAME_MACHINE=alphapca56 ;; + PCA57) UNAME_MACHINE=alphapca56 ;; + EV6) UNAME_MACHINE=alphaev6 ;; + EV67) UNAME_MACHINE=alphaev67 ;; + EV68*) UNAME_MACHINE=alphaev68 ;; + esac + objdump --private-headers /bin/sh | grep ld.so.1 >/dev/null + if test "$?" = 0 ; then LIBC="libc1" ; else LIBC="" ; fi + echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC} + exit 0 ;; + parisc:Linux:*:* | hppa:Linux:*:*) + # Look for CPU level + case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in + PA7*) echo hppa1.1-unknown-linux-gnu ;; + PA8*) echo hppa2.0-unknown-linux-gnu ;; + *) echo hppa-unknown-linux-gnu ;; + esac + exit 0 ;; + parisc64:Linux:*:* | hppa64:Linux:*:*) + echo hppa64-unknown-linux-gnu + exit 0 ;; + s390:Linux:*:* | s390x:Linux:*:*) + echo ${UNAME_MACHINE}-ibm-linux + exit 0 ;; + sh64*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit 0 ;; + sh*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit 0 ;; + sparc:Linux:*:* | sparc64:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit 0 ;; + x86_64:Linux:*:*) + echo x86_64-unknown-linux-gnu + exit 0 ;; + i*86:Linux:*:*) + # The BFD linker knows what the default object file format is, so + # first see if it will tell us. cd to the root directory to prevent + # problems with other programs or directories called `ld' in the path. + # Set LC_ALL=C to ensure ld outputs messages in English. + ld_supported_targets=`cd /; LC_ALL=C ld --help 2>&1 \ + | sed -ne '/supported targets:/!d + s/[ ][ ]*/ /g + s/.*supported targets: *// + s/ .*// + p'` + case "$ld_supported_targets" in + elf32-i386) + TENTATIVE="${UNAME_MACHINE}-pc-linux-gnu" + ;; + a.out-i386-linux) + echo "${UNAME_MACHINE}-pc-linux-gnuaout" + exit 0 ;; + coff-i386) + echo "${UNAME_MACHINE}-pc-linux-gnucoff" + exit 0 ;; + "") + # Either a pre-BFD a.out linker (linux-gnuoldld) or + # one that does not give us useful --help. + echo "${UNAME_MACHINE}-pc-linux-gnuoldld" + exit 0 ;; + esac + # Determine whether the default compiler is a.out or elf + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #include + #ifdef __ELF__ + # ifdef __GLIBC__ + # if __GLIBC__ >= 2 + LIBC=gnu + # else + LIBC=gnulibc1 + # endif + # else + LIBC=gnulibc1 + # endif + #else + #ifdef __INTEL_COMPILER + LIBC=gnu + #else + LIBC=gnuaout + #endif + #endif + #ifdef __dietlibc__ + LIBC=dietlibc + #endif +EOF + eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep ^LIBC=` + test x"${LIBC}" != x && echo "${UNAME_MACHINE}-pc-linux-${LIBC}" && exit 0 + test x"${TENTATIVE}" != x && echo "${TENTATIVE}" && exit 0 + ;; + i*86:DYNIX/ptx:4*:*) + # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there. + # earlier versions are messed up and put the nodename in both + # sysname and nodename. + echo i386-sequent-sysv4 + exit 0 ;; + i*86:UNIX_SV:4.2MP:2.*) + # Unixware is an offshoot of SVR4, but it has its own version + # number series starting with 2... + # I am not positive that other SVR4 systems won't match this, + # I just have to hope. -- rms. + # Use sysv4.2uw... so that sysv4* matches it. + echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION} + exit 0 ;; + i*86:OS/2:*:*) + # If we were able to find `uname', then EMX Unix compatibility + # is probably installed. + echo ${UNAME_MACHINE}-pc-os2-emx + exit 0 ;; + i*86:XTS-300:*:STOP) + echo ${UNAME_MACHINE}-unknown-stop + exit 0 ;; + i*86:atheos:*:*) + echo ${UNAME_MACHINE}-unknown-atheos + exit 0 ;; + i*86:syllable:*:*) + echo ${UNAME_MACHINE}-pc-syllable + exit 0 ;; + i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.0*:*) + echo i386-unknown-lynxos${UNAME_RELEASE} + exit 0 ;; + i*86:*DOS:*:*) + echo ${UNAME_MACHINE}-pc-msdosdjgpp + exit 0 ;; + i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*) + UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'` + if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then + echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL} + else + echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL} + fi + exit 0 ;; + i*86:*:5:[78]*) + case `/bin/uname -X | grep "^Machine"` in + *486*) UNAME_MACHINE=i486 ;; + *Pentium) UNAME_MACHINE=i586 ;; + *Pent*|*Celeron) UNAME_MACHINE=i686 ;; + esac + echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION} + exit 0 ;; + i*86:*:3.2:*) + if test -f /usr/options/cb.name; then + UNAME_REL=`sed -n 's/.*Version //p' /dev/null >/dev/null ; then + UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')` + (/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486 + (/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \ + && UNAME_MACHINE=i586 + (/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \ + && UNAME_MACHINE=i686 + (/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \ + && UNAME_MACHINE=i686 + echo ${UNAME_MACHINE}-pc-sco$UNAME_REL + else + echo ${UNAME_MACHINE}-pc-sysv32 + fi + exit 0 ;; + pc:*:*:*) + # Left here for compatibility: + # uname -m prints for DJGPP always 'pc', but it prints nothing about + # the processor, so we play safe by assuming i386. + echo i386-pc-msdosdjgpp + exit 0 ;; + Intel:Mach:3*:*) + echo i386-pc-mach3 + exit 0 ;; + paragon:*:*:*) + echo i860-intel-osf1 + exit 0 ;; + i860:*:4.*:*) # i860-SVR4 + if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then + echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4 + else # Add other i860-SVR4 vendors below as they are discovered. + echo i860-unknown-sysv${UNAME_RELEASE} # Unknown i860-SVR4 + fi + exit 0 ;; + mini*:CTIX:SYS*5:*) + # "miniframe" + echo m68010-convergent-sysv + exit 0 ;; + mc68k:UNIX:SYSTEM5:3.51m) + echo m68k-convergent-sysv + exit 0 ;; + M680?0:D-NIX:5.3:*) + echo m68k-diab-dnix + exit 0 ;; + M68*:*:R3V[5678]*:*) + test -r /sysV68 && echo 'm68k-motorola-sysv' && exit 0 ;; + 3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0) + OS_REL='' + test -r /etc/.relid \ + && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` + /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ + && echo i486-ncr-sysv4.3${OS_REL} && exit 0 + /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ + && echo i586-ncr-sysv4.3${OS_REL} && exit 0 ;; + 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*) + /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ + && echo i486-ncr-sysv4 && exit 0 ;; + m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*) + echo m68k-unknown-lynxos${UNAME_RELEASE} + exit 0 ;; + mc68030:UNIX_System_V:4.*:*) + echo m68k-atari-sysv4 + exit 0 ;; + TSUNAMI:LynxOS:2.*:*) + echo sparc-unknown-lynxos${UNAME_RELEASE} + exit 0 ;; + rs6000:LynxOS:2.*:*) + echo rs6000-unknown-lynxos${UNAME_RELEASE} + exit 0 ;; + PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.0*:*) + echo powerpc-unknown-lynxos${UNAME_RELEASE} + exit 0 ;; + SM[BE]S:UNIX_SV:*:*) + echo mips-dde-sysv${UNAME_RELEASE} + exit 0 ;; + RM*:ReliantUNIX-*:*:*) + echo mips-sni-sysv4 + exit 0 ;; + RM*:SINIX-*:*:*) + echo mips-sni-sysv4 + exit 0 ;; + *:SINIX-*:*:*) + if uname -p 2>/dev/null >/dev/null ; then + UNAME_MACHINE=`(uname -p) 2>/dev/null` + echo ${UNAME_MACHINE}-sni-sysv4 + else + echo ns32k-sni-sysv + fi + exit 0 ;; + PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort + # says + echo i586-unisys-sysv4 + exit 0 ;; + *:UNIX_System_V:4*:FTX*) + # From Gerald Hewes . + # How about differentiating between stratus architectures? -djm + echo hppa1.1-stratus-sysv4 + exit 0 ;; + *:*:*:FTX*) + # From seanf@swdc.stratus.com. + echo i860-stratus-sysv4 + exit 0 ;; + i*86:VOS:*:*) + # From Paul.Green@stratus.com. + echo ${UNAME_MACHINE}-stratus-vos + exit 0 ;; + *:VOS:*:*) + # From Paul.Green@stratus.com. + echo hppa1.1-stratus-vos + exit 0 ;; + mc68*:A/UX:*:*) + echo m68k-apple-aux${UNAME_RELEASE} + exit 0 ;; + news*:NEWS-OS:6*:*) + echo mips-sony-newsos6 + exit 0 ;; + R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*) + if [ -d /usr/nec ]; then + echo mips-nec-sysv${UNAME_RELEASE} + else + echo mips-unknown-sysv${UNAME_RELEASE} + fi + exit 0 ;; + BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only. + echo powerpc-be-beos + exit 0 ;; + BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only. + echo powerpc-apple-beos + exit 0 ;; + BePC:BeOS:*:*) # BeOS running on Intel PC compatible. + echo i586-pc-beos + exit 0 ;; + SX-4:SUPER-UX:*:*) + echo sx4-nec-superux${UNAME_RELEASE} + exit 0 ;; + SX-5:SUPER-UX:*:*) + echo sx5-nec-superux${UNAME_RELEASE} + exit 0 ;; + SX-6:SUPER-UX:*:*) + echo sx6-nec-superux${UNAME_RELEASE} + exit 0 ;; + Power*:Rhapsody:*:*) + echo powerpc-apple-rhapsody${UNAME_RELEASE} + exit 0 ;; + *:Rhapsody:*:*) + echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE} + exit 0 ;; + *:Darwin:*:*) + UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown + case $UNAME_PROCESSOR in + *86) UNAME_PROCESSOR=i686 ;; + unknown) UNAME_PROCESSOR=powerpc ;; + esac + echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE} + exit 0 ;; + *:procnto*:*:* | *:QNX:[0123456789]*:*) + UNAME_PROCESSOR=`uname -p` + if test "$UNAME_PROCESSOR" = "x86"; then + UNAME_PROCESSOR=i386 + UNAME_MACHINE=pc + fi + echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE} + exit 0 ;; + *:QNX:*:4*) + echo i386-pc-qnx + exit 0 ;; + NSE-?:NONSTOP_KERNEL:*:*) + echo nse-tandem-nsk${UNAME_RELEASE} + exit 0 ;; + NSR-?:NONSTOP_KERNEL:*:*) + echo nsr-tandem-nsk${UNAME_RELEASE} + exit 0 ;; + *:NonStop-UX:*:*) + echo mips-compaq-nonstopux + exit 0 ;; + BS2000:POSIX*:*:*) + echo bs2000-siemens-sysv + exit 0 ;; + DS/*:UNIX_System_V:*:*) + echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE} + exit 0 ;; + *:Plan9:*:*) + # "uname -m" is not consistent, so use $cputype instead. 386 + # is converted to i386 for consistency with other x86 + # operating systems. + if test "$cputype" = "386"; then + UNAME_MACHINE=i386 + else + UNAME_MACHINE="$cputype" + fi + echo ${UNAME_MACHINE}-unknown-plan9 + exit 0 ;; + *:TOPS-10:*:*) + echo pdp10-unknown-tops10 + exit 0 ;; + *:TENEX:*:*) + echo pdp10-unknown-tenex + exit 0 ;; + KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*) + echo pdp10-dec-tops20 + exit 0 ;; + XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*) + echo pdp10-xkl-tops20 + exit 0 ;; + *:TOPS-20:*:*) + echo pdp10-unknown-tops20 + exit 0 ;; + *:ITS:*:*) + echo pdp10-unknown-its + exit 0 ;; + SEI:*:*:SEIUX) + echo mips-sei-seiux${UNAME_RELEASE} + exit 0 ;; + *:DragonFly:*:*) + echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` + exit 0 ;; + *:*VMS:*:*) + UNAME_MACHINE=`(uname -p) 2>/dev/null` + case "${UNAME_MACHINE}" in + A*) echo alpha-dec-vms && exit 0 ;; + I*) echo ia64-dec-vms && exit 0 ;; + V*) echo vax-dec-vms && exit 0 ;; + esac ;; + *:XENIX:*:SysV) + echo i386-pc-xenix + exit 0 ;; +esac + +#echo '(No uname command or uname output not recognized.)' 1>&2 +#echo "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" 1>&2 + +eval $set_cc_for_build +cat >$dummy.c < +# include +#endif +main () +{ +#if defined (sony) +#if defined (MIPSEB) + /* BFD wants "bsd" instead of "newsos". Perhaps BFD should be changed, + I don't know.... */ + printf ("mips-sony-bsd\n"); exit (0); +#else +#include + printf ("m68k-sony-newsos%s\n", +#ifdef NEWSOS4 + "4" +#else + "" +#endif + ); exit (0); +#endif +#endif + +#if defined (__arm) && defined (__acorn) && defined (__unix) + printf ("arm-acorn-riscix"); exit (0); +#endif + +#if defined (hp300) && !defined (hpux) + printf ("m68k-hp-bsd\n"); exit (0); +#endif + +#if defined (NeXT) +#if !defined (__ARCHITECTURE__) +#define __ARCHITECTURE__ "m68k" +#endif + int version; + version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`; + if (version < 4) + printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version); + else + printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version); + exit (0); +#endif + +#if defined (MULTIMAX) || defined (n16) +#if defined (UMAXV) + printf ("ns32k-encore-sysv\n"); exit (0); +#else +#if defined (CMU) + printf ("ns32k-encore-mach\n"); exit (0); +#else + printf ("ns32k-encore-bsd\n"); exit (0); +#endif +#endif +#endif + +#if defined (__386BSD__) + printf ("i386-pc-bsd\n"); exit (0); +#endif + +#if defined (sequent) +#if defined (i386) + printf ("i386-sequent-dynix\n"); exit (0); +#endif +#if defined (ns32000) + printf ("ns32k-sequent-dynix\n"); exit (0); +#endif +#endif + +#if defined (_SEQUENT_) + struct utsname un; + + uname(&un); + + if (strncmp(un.version, "V2", 2) == 0) { + printf ("i386-sequent-ptx2\n"); exit (0); + } + if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */ + printf ("i386-sequent-ptx1\n"); exit (0); + } + printf ("i386-sequent-ptx\n"); exit (0); + +#endif + +#if defined (vax) +# if !defined (ultrix) +# include +# if defined (BSD) +# if BSD == 43 + printf ("vax-dec-bsd4.3\n"); exit (0); +# else +# if BSD == 199006 + printf ("vax-dec-bsd4.3reno\n"); exit (0); +# else + printf ("vax-dec-bsd\n"); exit (0); +# endif +# endif +# else + printf ("vax-dec-bsd\n"); exit (0); +# endif +# else + printf ("vax-dec-ultrix\n"); exit (0); +# endif +#endif + +#if defined (alliant) && defined (i860) + printf ("i860-alliant-bsd\n"); exit (0); +#endif + + exit (1); +} +EOF + +$CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && $dummy && exit 0 + +# Apollos put the system type in the environment. + +test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit 0; } + +# Convex versions that predate uname can use getsysinfo(1) + +if [ -x /usr/convex/getsysinfo ] +then + case `getsysinfo -f cpu_type` in + c1*) + echo c1-convex-bsd + exit 0 ;; + c2*) + if getsysinfo -f scalar_acc + then echo c32-convex-bsd + else echo c2-convex-bsd + fi + exit 0 ;; + c34*) + echo c34-convex-bsd + exit 0 ;; + c38*) + echo c38-convex-bsd + exit 0 ;; + c4*) + echo c4-convex-bsd + exit 0 ;; + esac +fi + +cat >&2 < in order to provide the needed +information to handle your system. + +config.guess timestamp = $timestamp + +uname -m = `(uname -m) 2>/dev/null || echo unknown` +uname -r = `(uname -r) 2>/dev/null || echo unknown` +uname -s = `(uname -s) 2>/dev/null || echo unknown` +uname -v = `(uname -v) 2>/dev/null || echo unknown` + +/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null` +/bin/uname -X = `(/bin/uname -X) 2>/dev/null` + +hostinfo = `(hostinfo) 2>/dev/null` +/bin/universe = `(/bin/universe) 2>/dev/null` +/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null` +/bin/arch = `(/bin/arch) 2>/dev/null` +/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null` +/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null` + +UNAME_MACHINE = ${UNAME_MACHINE} +UNAME_RELEASE = ${UNAME_RELEASE} +UNAME_SYSTEM = ${UNAME_SYSTEM} +UNAME_VERSION = ${UNAME_VERSION} +EOF + +exit 1 + +# Local variables: +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "timestamp='" +# time-stamp-format: "%:y-%02m-%02d" +# time-stamp-end: "'" +# End: diff --git a/mozilla/zap/zmk/speex-1.1.10/config.h.in b/mozilla/zap/zmk/speex-1.1.10/config.h.in new file mode 100755 index 00000000000..07c40880e64 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/config.h.in @@ -0,0 +1,147 @@ +/* config.h.in. Generated from configure.ac by autoheader. */ + +/* Make use of ARM4 assembly optimizations */ +#undef ARM4_ASM + +/* Make use of ARM5E assembly optimizations */ +#undef ARM5_ASM + +/* Make use of Blackfin assembly optimizations */ +#undef BFIN_ASM + +/* Disable wideband codec */ +#undef DISABLE_WIDEBAND + +/* Enable valgrind extra checks */ +#undef ENABLE_VALGRIND + +/* Enable support for Epic 4.8 kbps mode */ +#undef EPIC_48K + +/* Debug fixed-point implementation */ +#undef FIXED_DEBUG + +/* Compile as fixed-point */ +#undef FIXED_POINT + +/* Define to 1 if you have the header file. */ +#undef HAVE_DLFCN_H + +/* Define to 1 if you have the `getopt_long' function. */ +#undef HAVE_GETOPT_LONG + +/* Define to 1 if you have the header file. */ +#undef HAVE_INTTYPES_H + +/* Define to 1 if you have the `m' library (-lm). */ +#undef HAVE_LIBM + +/* Define to 1 if you have the `winmm' library (-lwinmm). */ +#undef HAVE_LIBWINMM + +/* Define to 1 if you have the header file. */ +#undef HAVE_MEMORY_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_STDINT_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_STDLIB_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_STRINGS_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_STRING_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_AUDIOIO_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_SOUNDCARD_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_STAT_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_TYPES_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_UNISTD_H + +/* Define to the address where bug reports for this package should be sent. */ +#undef PACKAGE_BUGREPORT + +/* Define to the full name of this package. */ +#undef PACKAGE_NAME + +/* Define to the full name and version of this package. */ +#undef PACKAGE_STRING + +/* Define to the one symbol short name of this package. */ +#undef PACKAGE_TARNAME + +/* Define to the version of this package. */ +#undef PACKAGE_VERSION + +/* Reduce precision to 16 bits (EXPERIMENTAL) */ +#undef PRECISION16 + +/* The size of a `int', as computed by sizeof. */ +#undef SIZEOF_INT + +/* The size of a `long', as computed by sizeof. */ +#undef SIZEOF_LONG + +/* The size of a `long long', as computed by sizeof. */ +#undef SIZEOF_LONG_LONG + +/* The size of a `short', as computed by sizeof. */ +#undef SIZEOF_SHORT + +/* Version extra */ +#undef SPEEX_EXTRA_VERSION + +/* Version major */ +#undef SPEEX_MAJOR_VERSION + +/* Version micro */ +#undef SPEEX_MICRO_VERSION + +/* Version minor */ +#undef SPEEX_MINOR_VERSION + +/* Complete version string */ +#undef SPEEX_VERSION + +/* Define to 1 if you have the ANSI C header files. */ +#undef STDC_HEADERS + +/* Enable support for TI C55X DSP */ +#undef TI_C55X + +/* Make use of alloca */ +#undef USE_ALLOCA + +/* Use C99 variable-size arrays */ +#undef VAR_ARRAYS + +/* Define to 1 if your processor stores words with the most significant byte + first (like Motorola and SPARC, unlike Intel and VAX). */ +#undef WORDS_BIGENDIAN + +/* Enable SSE support */ +#undef _USE_SSE + +/* Define to empty if `const' does not conform to ANSI C. */ +#undef const + +/* Define to `__inline__' or `__inline' if that's what the C compiler + calls it, or to nothing if 'inline' is not supported under any name. */ +#ifndef __cplusplus +#undef inline +#endif + +/* Define to equivalent of C99 restrict keyword, or to nothing if this is not + supported. Do not define if restrict is supported directly. */ +#undef restrict diff --git a/mozilla/zap/zmk/speex-1.1.10/config.sub b/mozilla/zap/zmk/speex-1.1.10/config.sub new file mode 100755 index 00000000000..aec005f2dcc --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/config.sub @@ -0,0 +1,1569 @@ +#! /bin/sh +# Configuration validation subroutine script. +# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, +# 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc. + +timestamp='2005-04-22' + +# This file is (in principle) common to ALL GNU software. +# The presence of a machine in this file suggests that SOME GNU software +# can handle that machine. It does not imply ALL GNU software can. +# +# This file is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, +# Boston, MA 02111-1307, USA. + +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + +# Please send patches to . Submit a context +# diff and a properly formatted ChangeLog entry. +# +# Configuration subroutine to validate and canonicalize a configuration type. +# Supply the specified configuration type as an argument. +# If it is invalid, we print an error message on stderr and exit with code 1. +# Otherwise, we print the canonical config type on stdout and succeed. + +# This file is supposed to be the same for all GNU packages +# and recognize all the CPU types, system types and aliases +# that are meaningful with *any* GNU software. +# Each package is responsible for reporting which valid configurations +# it does not support. The user should be able to distinguish +# a failure to support a valid configuration from a meaningless +# configuration. + +# The goal of this file is to map all the various variations of a given +# machine specification into a single specification in the form: +# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM +# or in some cases, the newer four-part form: +# CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM +# It is wrong to echo any other type of specification. + +me=`echo "$0" | sed -e 's,.*/,,'` + +usage="\ +Usage: $0 [OPTION] CPU-MFR-OPSYS + $0 [OPTION] ALIAS + +Canonicalize a configuration name. + +Operation modes: + -h, --help print this help, then exit + -t, --time-stamp print date of last modification, then exit + -v, --version print version number, then exit + +Report bugs and patches to ." + +version="\ +GNU config.sub ($timestamp) + +Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005 +Free Software Foundation, Inc. + +This is free software; see the source for copying conditions. There is NO +warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." + +help=" +Try \`$me --help' for more information." + +# Parse command line +while test $# -gt 0 ; do + case $1 in + --time-stamp | --time* | -t ) + echo "$timestamp" ; exit 0 ;; + --version | -v ) + echo "$version" ; exit 0 ;; + --help | --h* | -h ) + echo "$usage"; exit 0 ;; + -- ) # Stop option processing + shift; break ;; + - ) # Use stdin as input. + break ;; + -* ) + echo "$me: invalid option $1$help" + exit 1 ;; + + *local*) + # First pass through any local machine types. + echo $1 + exit 0;; + + * ) + break ;; + esac +done + +case $# in + 0) echo "$me: missing argument$help" >&2 + exit 1;; + 1) ;; + *) echo "$me: too many arguments$help" >&2 + exit 1;; +esac + +# Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any). +# Here we must recognize all the valid KERNEL-OS combinations. +maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'` +case $maybe_os in + nto-qnx* | linux-gnu* | linux-dietlibc | linux-uclibc* | uclinux-uclibc* | uclinux-gnu* | \ + kfreebsd*-gnu* | knetbsd*-gnu* | netbsd*-gnu* | storm-chaos* | os2-emx* | rtmk-nova*) + os=-$maybe_os + basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'` + ;; + *) + basic_machine=`echo $1 | sed 's/-[^-]*$//'` + if [ $basic_machine != $1 ] + then os=`echo $1 | sed 's/.*-/-/'` + else os=; fi + ;; +esac + +### Let's recognize common machines as not being operating systems so +### that things like config.sub decstation-3100 work. We also +### recognize some manufacturers as not being operating systems, so we +### can provide default operating systems below. +case $os in + -sun*os*) + # Prevent following clause from handling this invalid input. + ;; + -dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \ + -att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \ + -unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \ + -convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\ + -c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \ + -harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \ + -apple | -axis | -knuth | -cray) + os= + basic_machine=$1 + ;; + -sim | -cisco | -oki | -wec | -winbond) + os= + basic_machine=$1 + ;; + -scout) + ;; + -wrs) + os=-vxworks + basic_machine=$1 + ;; + -chorusos*) + os=-chorusos + basic_machine=$1 + ;; + -chorusrdb) + os=-chorusrdb + basic_machine=$1 + ;; + -hiux*) + os=-hiuxwe2 + ;; + -sco5) + os=-sco3.2v5 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco4) + os=-sco3.2v4 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco3.2.[4-9]*) + os=`echo $os | sed -e 's/sco3.2./sco3.2v/'` + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco3.2v[4-9]*) + # Don't forget version if it is 3.2v4 or newer. + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco*) + os=-sco3.2v2 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -udk*) + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -isc) + os=-isc2.2 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -clix*) + basic_machine=clipper-intergraph + ;; + -isc*) + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -lynx*) + os=-lynxos + ;; + -ptx*) + basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'` + ;; + -windowsnt*) + os=`echo $os | sed -e 's/windowsnt/winnt/'` + ;; + -psos*) + os=-psos + ;; + -mint | -mint[0-9]*) + basic_machine=m68k-atari + os=-mint + ;; +esac + +# Decode aliases for certain CPU-COMPANY combinations. +case $basic_machine in + # Recognize the basic CPU types without company name. + # Some are omitted here because they have special meanings below. + 1750a | 580 \ + | a29k \ + | alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \ + | alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \ + | am33_2.0 \ + | arc | arm | arm[bl]e | arme[lb] | armv[2345] | armv[345][lb] | avr \ + | bfin \ + | c4x | clipper \ + | d10v | d30v | dlx | dsp16xx \ + | fr30 | frv \ + | h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \ + | i370 | i860 | i960 | ia64 \ + | ip2k | iq2000 \ + | m32r | m32rle | m68000 | m68k | m88k | maxq | mcore \ + | mips | mipsbe | mipseb | mipsel | mipsle \ + | mips16 \ + | mips64 | mips64el \ + | mips64vr | mips64vrel \ + | mips64orion | mips64orionel \ + | mips64vr4100 | mips64vr4100el \ + | mips64vr4300 | mips64vr4300el \ + | mips64vr5000 | mips64vr5000el \ + | mipsisa32 | mipsisa32el \ + | mipsisa32r2 | mipsisa32r2el \ + | mipsisa64 | mipsisa64el \ + | mipsisa64r2 | mipsisa64r2el \ + | mipsisa64sb1 | mipsisa64sb1el \ + | mipsisa64sr71k | mipsisa64sr71kel \ + | mipstx39 | mipstx39el \ + | mn10200 | mn10300 \ + | msp430 \ + | ns16k | ns32k \ + | openrisc | or32 \ + | pdp10 | pdp11 | pj | pjl \ + | powerpc | powerpc64 | powerpc64le | powerpcle | ppcbe \ + | pyramid \ + | sh | sh[1234] | sh[23]e | sh[34]eb | shbe | shle | sh[1234]le | sh3ele \ + | sh64 | sh64le \ + | sparc | sparc64 | sparc64b | sparc86x | sparclet | sparclite \ + | sparcv8 | sparcv9 | sparcv9b \ + | strongarm \ + | tahoe | thumb | tic4x | tic80 | tron \ + | v850 | v850e \ + | we32k \ + | x86 | xscale | xscalee[bl] | xstormy16 | xtensa \ + | z8k) + basic_machine=$basic_machine-unknown + ;; + m6811 | m68hc11 | m6812 | m68hc12) + # Motorola 68HC11/12. + basic_machine=$basic_machine-unknown + os=-none + ;; + m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k) + ;; + + # We use `pc' rather than `unknown' + # because (1) that's what they normally are, and + # (2) the word "unknown" tends to confuse beginning users. + i*86 | x86_64) + basic_machine=$basic_machine-pc + ;; + # Object if more than one company name word. + *-*-*) + echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 + exit 1 + ;; + # Recognize the basic CPU types with company name. + 580-* \ + | a29k-* \ + | alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \ + | alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \ + | alphapca5[67]-* | alpha64pca5[67]-* | arc-* \ + | arm-* | armbe-* | armle-* | armeb-* | armv*-* \ + | avr-* \ + | bfin-* | bs2000-* \ + | c[123]* | c30-* | [cjt]90-* | c4x-* | c54x-* | c55x-* | c6x-* \ + | clipper-* | craynv-* | cydra-* \ + | d10v-* | d30v-* | dlx-* \ + | elxsi-* \ + | f30[01]-* | f700-* | fr30-* | frv-* | fx80-* \ + | h8300-* | h8500-* \ + | hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \ + | i*86-* | i860-* | i960-* | ia64-* \ + | ip2k-* | iq2000-* \ + | m32r-* | m32rle-* \ + | m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \ + | m88110-* | m88k-* | maxq-* | mcore-* \ + | mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \ + | mips16-* \ + | mips64-* | mips64el-* \ + | mips64vr-* | mips64vrel-* \ + | mips64orion-* | mips64orionel-* \ + | mips64vr4100-* | mips64vr4100el-* \ + | mips64vr4300-* | mips64vr4300el-* \ + | mips64vr5000-* | mips64vr5000el-* \ + | mipsisa32-* | mipsisa32el-* \ + | mipsisa32r2-* | mipsisa32r2el-* \ + | mipsisa64-* | mipsisa64el-* \ + | mipsisa64r2-* | mipsisa64r2el-* \ + | mipsisa64sb1-* | mipsisa64sb1el-* \ + | mipsisa64sr71k-* | mipsisa64sr71kel-* \ + | mipstx39-* | mipstx39el-* \ + | mmix-* \ + | msp430-* \ + | none-* | np1-* | ns16k-* | ns32k-* \ + | orion-* \ + | pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \ + | powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* | ppcbe-* \ + | pyramid-* \ + | romp-* | rs6000-* \ + | sh-* | sh[1234]-* | sh[23]e-* | sh[34]eb-* | shbe-* \ + | shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \ + | sparc-* | sparc64-* | sparc64b-* | sparc86x-* | sparclet-* \ + | sparclite-* \ + | sparcv8-* | sparcv9-* | sparcv9b-* | strongarm-* | sv1-* | sx?-* \ + | tahoe-* | thumb-* \ + | tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \ + | tron-* \ + | v850-* | v850e-* | vax-* \ + | we32k-* \ + | x86-* | x86_64-* | xps100-* | xscale-* | xscalee[bl]-* \ + | xstormy16-* | xtensa-* \ + | ymp-* \ + | z8k-*) + ;; + # Recognize the various machine names and aliases which stand + # for a CPU type and a company and sometimes even an OS. + 386bsd) + basic_machine=i386-unknown + os=-bsd + ;; + 3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc) + basic_machine=m68000-att + ;; + 3b*) + basic_machine=we32k-att + ;; + a29khif) + basic_machine=a29k-amd + os=-udi + ;; + abacus) + basic_machine=abacus-unknown + ;; + adobe68k) + basic_machine=m68010-adobe + os=-scout + ;; + alliant | fx80) + basic_machine=fx80-alliant + ;; + altos | altos3068) + basic_machine=m68k-altos + ;; + am29k) + basic_machine=a29k-none + os=-bsd + ;; + amd64) + basic_machine=x86_64-pc + ;; + amd64-*) + basic_machine=x86_64-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + amdahl) + basic_machine=580-amdahl + os=-sysv + ;; + amiga | amiga-*) + basic_machine=m68k-unknown + ;; + amigaos | amigados) + basic_machine=m68k-unknown + os=-amigaos + ;; + amigaunix | amix) + basic_machine=m68k-unknown + os=-sysv4 + ;; + apollo68) + basic_machine=m68k-apollo + os=-sysv + ;; + apollo68bsd) + basic_machine=m68k-apollo + os=-bsd + ;; + aux) + basic_machine=m68k-apple + os=-aux + ;; + balance) + basic_machine=ns32k-sequent + os=-dynix + ;; + c90) + basic_machine=c90-cray + os=-unicos + ;; + convex-c1) + basic_machine=c1-convex + os=-bsd + ;; + convex-c2) + basic_machine=c2-convex + os=-bsd + ;; + convex-c32) + basic_machine=c32-convex + os=-bsd + ;; + convex-c34) + basic_machine=c34-convex + os=-bsd + ;; + convex-c38) + basic_machine=c38-convex + os=-bsd + ;; + cray | j90) + basic_machine=j90-cray + os=-unicos + ;; + craynv) + basic_machine=craynv-cray + os=-unicosmp + ;; + cr16c) + basic_machine=cr16c-unknown + os=-elf + ;; + crds | unos) + basic_machine=m68k-crds + ;; + crisv32 | crisv32-* | etraxfs*) + basic_machine=crisv32-axis + ;; + cris | cris-* | etrax*) + basic_machine=cris-axis + ;; + crx) + basic_machine=crx-unknown + os=-elf + ;; + da30 | da30-*) + basic_machine=m68k-da30 + ;; + decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn) + basic_machine=mips-dec + ;; + decsystem10* | dec10*) + basic_machine=pdp10-dec + os=-tops10 + ;; + decsystem20* | dec20*) + basic_machine=pdp10-dec + os=-tops20 + ;; + delta | 3300 | motorola-3300 | motorola-delta \ + | 3300-motorola | delta-motorola) + basic_machine=m68k-motorola + ;; + delta88) + basic_machine=m88k-motorola + os=-sysv3 + ;; + djgpp) + basic_machine=i586-pc + os=-msdosdjgpp + ;; + dpx20 | dpx20-*) + basic_machine=rs6000-bull + os=-bosx + ;; + dpx2* | dpx2*-bull) + basic_machine=m68k-bull + os=-sysv3 + ;; + ebmon29k) + basic_machine=a29k-amd + os=-ebmon + ;; + elxsi) + basic_machine=elxsi-elxsi + os=-bsd + ;; + encore | umax | mmax) + basic_machine=ns32k-encore + ;; + es1800 | OSE68k | ose68k | ose | OSE) + basic_machine=m68k-ericsson + os=-ose + ;; + fx2800) + basic_machine=i860-alliant + ;; + genix) + basic_machine=ns32k-ns + ;; + gmicro) + basic_machine=tron-gmicro + os=-sysv + ;; + go32) + basic_machine=i386-pc + os=-go32 + ;; + h3050r* | hiux*) + basic_machine=hppa1.1-hitachi + os=-hiuxwe2 + ;; + h8300hms) + basic_machine=h8300-hitachi + os=-hms + ;; + h8300xray) + basic_machine=h8300-hitachi + os=-xray + ;; + h8500hms) + basic_machine=h8500-hitachi + os=-hms + ;; + harris) + basic_machine=m88k-harris + os=-sysv3 + ;; + hp300-*) + basic_machine=m68k-hp + ;; + hp300bsd) + basic_machine=m68k-hp + os=-bsd + ;; + hp300hpux) + basic_machine=m68k-hp + os=-hpux + ;; + hp3k9[0-9][0-9] | hp9[0-9][0-9]) + basic_machine=hppa1.0-hp + ;; + hp9k2[0-9][0-9] | hp9k31[0-9]) + basic_machine=m68000-hp + ;; + hp9k3[2-9][0-9]) + basic_machine=m68k-hp + ;; + hp9k6[0-9][0-9] | hp6[0-9][0-9]) + basic_machine=hppa1.0-hp + ;; + hp9k7[0-79][0-9] | hp7[0-79][0-9]) + basic_machine=hppa1.1-hp + ;; + hp9k78[0-9] | hp78[0-9]) + # FIXME: really hppa2.0-hp + basic_machine=hppa1.1-hp + ;; + hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893) + # FIXME: really hppa2.0-hp + basic_machine=hppa1.1-hp + ;; + hp9k8[0-9][13679] | hp8[0-9][13679]) + basic_machine=hppa1.1-hp + ;; + hp9k8[0-9][0-9] | hp8[0-9][0-9]) + basic_machine=hppa1.0-hp + ;; + hppa-next) + os=-nextstep3 + ;; + hppaosf) + basic_machine=hppa1.1-hp + os=-osf + ;; + hppro) + basic_machine=hppa1.1-hp + os=-proelf + ;; + i370-ibm* | ibm*) + basic_machine=i370-ibm + ;; +# I'm not sure what "Sysv32" means. Should this be sysv3.2? + i*86v32) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-sysv32 + ;; + i*86v4*) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-sysv4 + ;; + i*86v) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-sysv + ;; + i*86sol2) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-solaris2 + ;; + i386mach) + basic_machine=i386-mach + os=-mach + ;; + i386-vsta | vsta) + basic_machine=i386-unknown + os=-vsta + ;; + iris | iris4d) + basic_machine=mips-sgi + case $os in + -irix*) + ;; + *) + os=-irix4 + ;; + esac + ;; + isi68 | isi) + basic_machine=m68k-isi + os=-sysv + ;; + m88k-omron*) + basic_machine=m88k-omron + ;; + magnum | m3230) + basic_machine=mips-mips + os=-sysv + ;; + merlin) + basic_machine=ns32k-utek + os=-sysv + ;; + mingw32) + basic_machine=i386-pc + os=-mingw32 + ;; + miniframe) + basic_machine=m68000-convergent + ;; + *mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*) + basic_machine=m68k-atari + os=-mint + ;; + mips3*-*) + basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'` + ;; + mips3*) + basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown + ;; + monitor) + basic_machine=m68k-rom68k + os=-coff + ;; + morphos) + basic_machine=powerpc-unknown + os=-morphos + ;; + msdos) + basic_machine=i386-pc + os=-msdos + ;; + mvs) + basic_machine=i370-ibm + os=-mvs + ;; + ncr3000) + basic_machine=i486-ncr + os=-sysv4 + ;; + netbsd386) + basic_machine=i386-unknown + os=-netbsd + ;; + netwinder) + basic_machine=armv4l-rebel + os=-linux + ;; + news | news700 | news800 | news900) + basic_machine=m68k-sony + os=-newsos + ;; + news1000) + basic_machine=m68030-sony + os=-newsos + ;; + news-3600 | risc-news) + basic_machine=mips-sony + os=-newsos + ;; + necv70) + basic_machine=v70-nec + os=-sysv + ;; + next | m*-next ) + basic_machine=m68k-next + case $os in + -nextstep* ) + ;; + -ns2*) + os=-nextstep2 + ;; + *) + os=-nextstep3 + ;; + esac + ;; + nh3000) + basic_machine=m68k-harris + os=-cxux + ;; + nh[45]000) + basic_machine=m88k-harris + os=-cxux + ;; + nindy960) + basic_machine=i960-intel + os=-nindy + ;; + mon960) + basic_machine=i960-intel + os=-mon960 + ;; + nonstopux) + basic_machine=mips-compaq + os=-nonstopux + ;; + np1) + basic_machine=np1-gould + ;; + nsr-tandem) + basic_machine=nsr-tandem + ;; + op50n-* | op60c-*) + basic_machine=hppa1.1-oki + os=-proelf + ;; + or32 | or32-*) + basic_machine=or32-unknown + os=-coff + ;; + os400) + basic_machine=powerpc-ibm + os=-os400 + ;; + OSE68000 | ose68000) + basic_machine=m68000-ericsson + os=-ose + ;; + os68k) + basic_machine=m68k-none + os=-os68k + ;; + pa-hitachi) + basic_machine=hppa1.1-hitachi + os=-hiuxwe2 + ;; + paragon) + basic_machine=i860-intel + os=-osf + ;; + pbd) + basic_machine=sparc-tti + ;; + pbb) + basic_machine=m68k-tti + ;; + pc532 | pc532-*) + basic_machine=ns32k-pc532 + ;; + pentium | p5 | k5 | k6 | nexgen | viac3) + basic_machine=i586-pc + ;; + pentiumpro | p6 | 6x86 | athlon | athlon_*) + basic_machine=i686-pc + ;; + pentiumii | pentium2 | pentiumiii | pentium3) + basic_machine=i686-pc + ;; + pentium4) + basic_machine=i786-pc + ;; + pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*) + basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pentiumpro-* | p6-* | 6x86-* | athlon-*) + basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*) + basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pentium4-*) + basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pn) + basic_machine=pn-gould + ;; + power) basic_machine=power-ibm + ;; + ppc) basic_machine=powerpc-unknown + ;; + ppc-*) basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ppcle | powerpclittle | ppc-le | powerpc-little) + basic_machine=powerpcle-unknown + ;; + ppcle-* | powerpclittle-*) + basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ppc64) basic_machine=powerpc64-unknown + ;; + ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ppc64le | powerpc64little | ppc64-le | powerpc64-little) + basic_machine=powerpc64le-unknown + ;; + ppc64le-* | powerpc64little-*) + basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ps2) + basic_machine=i386-ibm + ;; + pw32) + basic_machine=i586-unknown + os=-pw32 + ;; + rom68k) + basic_machine=m68k-rom68k + os=-coff + ;; + rm[46]00) + basic_machine=mips-siemens + ;; + rtpc | rtpc-*) + basic_machine=romp-ibm + ;; + s390 | s390-*) + basic_machine=s390-ibm + ;; + s390x | s390x-*) + basic_machine=s390x-ibm + ;; + sa29200) + basic_machine=a29k-amd + os=-udi + ;; + sb1) + basic_machine=mipsisa64sb1-unknown + ;; + sb1el) + basic_machine=mipsisa64sb1el-unknown + ;; + sei) + basic_machine=mips-sei + os=-seiux + ;; + sequent) + basic_machine=i386-sequent + ;; + sh) + basic_machine=sh-hitachi + os=-hms + ;; + sh64) + basic_machine=sh64-unknown + ;; + sparclite-wrs | simso-wrs) + basic_machine=sparclite-wrs + os=-vxworks + ;; + sps7) + basic_machine=m68k-bull + os=-sysv2 + ;; + spur) + basic_machine=spur-unknown + ;; + st2000) + basic_machine=m68k-tandem + ;; + stratus) + basic_machine=i860-stratus + os=-sysv4 + ;; + sun2) + basic_machine=m68000-sun + ;; + sun2os3) + basic_machine=m68000-sun + os=-sunos3 + ;; + sun2os4) + basic_machine=m68000-sun + os=-sunos4 + ;; + sun3os3) + basic_machine=m68k-sun + os=-sunos3 + ;; + sun3os4) + basic_machine=m68k-sun + os=-sunos4 + ;; + sun4os3) + basic_machine=sparc-sun + os=-sunos3 + ;; + sun4os4) + basic_machine=sparc-sun + os=-sunos4 + ;; + sun4sol2) + basic_machine=sparc-sun + os=-solaris2 + ;; + sun3 | sun3-*) + basic_machine=m68k-sun + ;; + sun4) + basic_machine=sparc-sun + ;; + sun386 | sun386i | roadrunner) + basic_machine=i386-sun + ;; + sv1) + basic_machine=sv1-cray + os=-unicos + ;; + symmetry) + basic_machine=i386-sequent + os=-dynix + ;; + t3e) + basic_machine=alphaev5-cray + os=-unicos + ;; + t90) + basic_machine=t90-cray + os=-unicos + ;; + tic54x | c54x*) + basic_machine=tic54x-unknown + os=-coff + ;; + tic55x | c55x*) + basic_machine=tic55x-unknown + os=-coff + ;; + tic6x | c6x*) + basic_machine=tic6x-unknown + os=-coff + ;; + tx39) + basic_machine=mipstx39-unknown + ;; + tx39el) + basic_machine=mipstx39el-unknown + ;; + toad1) + basic_machine=pdp10-xkl + os=-tops20 + ;; + tower | tower-32) + basic_machine=m68k-ncr + ;; + tpf) + basic_machine=s390x-ibm + os=-tpf + ;; + udi29k) + basic_machine=a29k-amd + os=-udi + ;; + ultra3) + basic_machine=a29k-nyu + os=-sym1 + ;; + v810 | necv810) + basic_machine=v810-nec + os=-none + ;; + vaxv) + basic_machine=vax-dec + os=-sysv + ;; + vms) + basic_machine=vax-dec + os=-vms + ;; + vpp*|vx|vx-*) + basic_machine=f301-fujitsu + ;; + vxworks960) + basic_machine=i960-wrs + os=-vxworks + ;; + vxworks68) + basic_machine=m68k-wrs + os=-vxworks + ;; + vxworks29k) + basic_machine=a29k-wrs + os=-vxworks + ;; + w65*) + basic_machine=w65-wdc + os=-none + ;; + w89k-*) + basic_machine=hppa1.1-winbond + os=-proelf + ;; + xbox) + basic_machine=i686-pc + os=-mingw32 + ;; + xps | xps100) + basic_machine=xps100-honeywell + ;; + ymp) + basic_machine=ymp-cray + os=-unicos + ;; + z8k-*-coff) + basic_machine=z8k-unknown + os=-sim + ;; + none) + basic_machine=none-none + os=-none + ;; + +# Here we handle the default manufacturer of certain CPU types. It is in +# some cases the only manufacturer, in others, it is the most popular. + w89k) + basic_machine=hppa1.1-winbond + ;; + op50n) + basic_machine=hppa1.1-oki + ;; + op60c) + basic_machine=hppa1.1-oki + ;; + romp) + basic_machine=romp-ibm + ;; + mmix) + basic_machine=mmix-knuth + ;; + rs6000) + basic_machine=rs6000-ibm + ;; + vax) + basic_machine=vax-dec + ;; + pdp10) + # there are many clones, so DEC is not a safe bet + basic_machine=pdp10-unknown + ;; + pdp11) + basic_machine=pdp11-dec + ;; + we32k) + basic_machine=we32k-att + ;; + sh3 | sh4 | sh[34]eb | sh[1234]le | sh[23]ele) + basic_machine=sh-unknown + ;; + sh64) + basic_machine=sh64-unknown + ;; + sparc | sparcv8 | sparcv9 | sparcv9b) + basic_machine=sparc-sun + ;; + cydra) + basic_machine=cydra-cydrome + ;; + orion) + basic_machine=orion-highlevel + ;; + orion105) + basic_machine=clipper-highlevel + ;; + mac | mpw | mac-mpw) + basic_machine=m68k-apple + ;; + pmac | pmac-mpw) + basic_machine=powerpc-apple + ;; + *-unknown) + # Make sure to match an already-canonicalized machine name. + ;; + *) + echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 + exit 1 + ;; +esac + +# Here we canonicalize certain aliases for manufacturers. +case $basic_machine in + *-digital*) + basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'` + ;; + *-commodore*) + basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'` + ;; + *) + ;; +esac + +# Decode manufacturer-specific aliases for certain operating systems. + +if [ x"$os" != x"" ] +then +case $os in + # First match some system type aliases + # that might get confused with valid system types. + # -solaris* is a basic system type, with this one exception. + -solaris1 | -solaris1.*) + os=`echo $os | sed -e 's|solaris1|sunos4|'` + ;; + -solaris) + os=-solaris2 + ;; + -svr4*) + os=-sysv4 + ;; + -unixware*) + os=-sysv4.2uw + ;; + -gnu/linux*) + os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'` + ;; + # First accept the basic system types. + # The portable systems comes first. + # Each alternative MUST END IN A *, to match a version number. + # -sysv* is not here because it comes later, after sysvr4. + -gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \ + | -*vms* | -sco* | -esix* | -isc* | -aix* | -sunos | -sunos[34]*\ + | -hpux* | -unos* | -osf* | -luna* | -dgux* | -solaris* | -sym* \ + | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \ + | -aos* \ + | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \ + | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \ + | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* | -openbsd* \ + | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \ + | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \ + | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \ + | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \ + | -chorusos* | -chorusrdb* \ + | -cygwin* | -pe* | -psos* | -moss* | -proelf* | -rtems* \ + | -mingw32* | -linux-gnu* | -linux-uclibc* | -uxpv* | -beos* | -mpeix* | -udk* \ + | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \ + | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \ + | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \ + | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \ + | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \ + | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly*) + # Remember, each alternative MUST END IN *, to match a version number. + ;; + -qnx*) + case $basic_machine in + x86-* | i*86-*) + ;; + *) + os=-nto$os + ;; + esac + ;; + -nto-qnx*) + ;; + -nto*) + os=`echo $os | sed -e 's|nto|nto-qnx|'` + ;; + -sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \ + | -windows* | -osx | -abug | -netware* | -os9* | -beos* \ + | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*) + ;; + -mac*) + os=`echo $os | sed -e 's|mac|macos|'` + ;; + -linux-dietlibc) + os=-linux-dietlibc + ;; + -linux*) + os=`echo $os | sed -e 's|linux|linux-gnu|'` + ;; + -sunos5*) + os=`echo $os | sed -e 's|sunos5|solaris2|'` + ;; + -sunos6*) + os=`echo $os | sed -e 's|sunos6|solaris3|'` + ;; + -opened*) + os=-openedition + ;; + -os400*) + os=-os400 + ;; + -wince*) + os=-wince + ;; + -osfrose*) + os=-osfrose + ;; + -osf*) + os=-osf + ;; + -utek*) + os=-bsd + ;; + -dynix*) + os=-bsd + ;; + -acis*) + os=-aos + ;; + -atheos*) + os=-atheos + ;; + -syllable*) + os=-syllable + ;; + -386bsd) + os=-bsd + ;; + -ctix* | -uts*) + os=-sysv + ;; + -nova*) + os=-rtmk-nova + ;; + -ns2 ) + os=-nextstep2 + ;; + -nsk*) + os=-nsk + ;; + # Preserve the version number of sinix5. + -sinix5.*) + os=`echo $os | sed -e 's|sinix|sysv|'` + ;; + -sinix*) + os=-sysv4 + ;; + -tpf*) + os=-tpf + ;; + -triton*) + os=-sysv3 + ;; + -oss*) + os=-sysv3 + ;; + -svr4) + os=-sysv4 + ;; + -svr3) + os=-sysv3 + ;; + -sysvr4) + os=-sysv4 + ;; + # This must come after -sysvr4. + -sysv*) + ;; + -ose*) + os=-ose + ;; + -es1800*) + os=-ose + ;; + -xenix) + os=-xenix + ;; + -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) + os=-mint + ;; + -aros*) + os=-aros + ;; + -kaos*) + os=-kaos + ;; + -zvmoe) + os=-zvmoe + ;; + -none) + ;; + *) + # Get rid of the `-' at the beginning of $os. + os=`echo $os | sed 's/[^-]*-//'` + echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2 + exit 1 + ;; +esac +else + +# Here we handle the default operating systems that come with various machines. +# The value should be what the vendor currently ships out the door with their +# machine or put another way, the most popular os provided with the machine. + +# Note that if you're going to try to match "-MANUFACTURER" here (say, +# "-sun"), then you have to tell the case statement up towards the top +# that MANUFACTURER isn't an operating system. Otherwise, code above +# will signal an error saying that MANUFACTURER isn't an operating +# system, and we'll never get to this point. + +case $basic_machine in + *-acorn) + os=-riscix1.2 + ;; + arm*-rebel) + os=-linux + ;; + arm*-semi) + os=-aout + ;; + c4x-* | tic4x-*) + os=-coff + ;; + # This must come before the *-dec entry. + pdp10-*) + os=-tops20 + ;; + pdp11-*) + os=-none + ;; + *-dec | vax-*) + os=-ultrix4.2 + ;; + m68*-apollo) + os=-domain + ;; + i386-sun) + os=-sunos4.0.2 + ;; + m68000-sun) + os=-sunos3 + # This also exists in the configure program, but was not the + # default. + # os=-sunos4 + ;; + m68*-cisco) + os=-aout + ;; + mips*-cisco) + os=-elf + ;; + mips*-*) + os=-elf + ;; + or32-*) + os=-coff + ;; + *-tti) # must be before sparc entry or we get the wrong os. + os=-sysv3 + ;; + sparc-* | *-sun) + os=-sunos4.1.1 + ;; + *-be) + os=-beos + ;; + *-ibm) + os=-aix + ;; + *-knuth) + os=-mmixware + ;; + *-wec) + os=-proelf + ;; + *-winbond) + os=-proelf + ;; + *-oki) + os=-proelf + ;; + *-hp) + os=-hpux + ;; + *-hitachi) + os=-hiux + ;; + i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent) + os=-sysv + ;; + *-cbm) + os=-amigaos + ;; + *-dg) + os=-dgux + ;; + *-dolphin) + os=-sysv3 + ;; + m68k-ccur) + os=-rtu + ;; + m88k-omron*) + os=-luna + ;; + *-next ) + os=-nextstep + ;; + *-sequent) + os=-ptx + ;; + *-crds) + os=-unos + ;; + *-ns) + os=-genix + ;; + i370-*) + os=-mvs + ;; + *-next) + os=-nextstep3 + ;; + *-gould) + os=-sysv + ;; + *-highlevel) + os=-bsd + ;; + *-encore) + os=-bsd + ;; + *-sgi) + os=-irix + ;; + *-siemens) + os=-sysv4 + ;; + *-masscomp) + os=-rtu + ;; + f30[01]-fujitsu | f700-fujitsu) + os=-uxpv + ;; + *-rom68k) + os=-coff + ;; + *-*bug) + os=-coff + ;; + *-apple) + os=-macos + ;; + *-atari*) + os=-mint + ;; + *) + os=-none + ;; +esac +fi + +# Here we handle the case where we know the os, and the CPU type, but not the +# manufacturer. We pick the logical manufacturer. +vendor=unknown +case $basic_machine in + *-unknown) + case $os in + -riscix*) + vendor=acorn + ;; + -sunos*) + vendor=sun + ;; + -aix*) + vendor=ibm + ;; + -beos*) + vendor=be + ;; + -hpux*) + vendor=hp + ;; + -mpeix*) + vendor=hp + ;; + -hiux*) + vendor=hitachi + ;; + -unos*) + vendor=crds + ;; + -dgux*) + vendor=dg + ;; + -luna*) + vendor=omron + ;; + -genix*) + vendor=ns + ;; + -mvs* | -opened*) + vendor=ibm + ;; + -os400*) + vendor=ibm + ;; + -ptx*) + vendor=sequent + ;; + -tpf*) + vendor=ibm + ;; + -vxsim* | -vxworks* | -windiss*) + vendor=wrs + ;; + -aux*) + vendor=apple + ;; + -hms*) + vendor=hitachi + ;; + -mpw* | -macos*) + vendor=apple + ;; + -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) + vendor=atari + ;; + -vos*) + vendor=stratus + ;; + esac + basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"` + ;; +esac + +echo $basic_machine$os +exit 0 + +# Local variables: +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "timestamp='" +# time-stamp-format: "%:y-%02m-%02d" +# time-stamp-end: "'" +# End: diff --git a/mozilla/zap/zmk/speex-1.1.10/configure.ac b/mozilla/zap/zmk/speex-1.1.10/configure.ac new file mode 100755 index 00000000000..5aa77763aec --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/configure.ac @@ -0,0 +1,194 @@ +dnl Process this file with autoconf to produce a configure script. -*-m4-*- + +AC_INIT(libspeex/speex.c) + +AM_CONFIG_HEADER([config.h]) + +SPEEX_MAJOR_VERSION=1 +SPEEX_MINOR_VERSION=1 +SPEEX_MICRO_VERSION=10 +SPEEX_EXTRA_VERSION= +#SPEEX_VERSION= +SPEEX_VERSION=$SPEEX_MAJOR_VERSION.$SPEEX_MINOR_VERSION.$SPEEX_MICRO_VERSION$SPEEX_EXTRA_VERSION + +SPEEX_LT_CURRENT=3 +SPEEX_LT_REVISION=0 +SPEEX_LT_AGE=2 + +AC_SUBST(SPEEX_LT_CURRENT) +AC_SUBST(SPEEX_LT_REVISION) +AC_SUBST(SPEEX_LT_AGE) + +# For automake. +VERSION=$SPEEX_VERSION +PACKAGE=speex + +AC_SUBST(SPEEX_VERSION) + +AM_INIT_AUTOMAKE($PACKAGE, $VERSION, no-define) +AM_MAINTAINER_MODE + +AC_CANONICAL_HOST +AM_PROG_LIBTOOL + +AC_C_BIGENDIAN +AC_C_CONST +AC_C_INLINE +AC_C_RESTRICT + + +AC_MSG_CHECKING(for C99 variable-size arrays) +AC_TRY_COMPILE( , [ +int foo=10; +int array[foo]; +], +[has_var_arrays=yes;AC_DEFINE([VAR_ARRAYS], [], [Use C99 variable-size arrays]) +], +has_var_arrays=no +) +AC_MSG_RESULT($has_var_arrays) + +AC_MSG_CHECKING(for alloca) +AC_TRY_COMPILE( [#include ], [ +int foo=10; +int *array = alloca(foo); +], +[ +has_alloca=yes; +if test x$has_var_arrays = "xno" ; then +AC_DEFINE([USE_ALLOCA], [], [Make use of alloca]) +fi +], +has_alloca=no +) +AC_MSG_RESULT($has_alloca) + + +AC_CHECK_HEADERS(sys/soundcard.h sys/audioio.h) + +XIPH_PATH_OGG([src="src"], [src=""]) +AC_SUBST(src) + +AC_CHECK_LIB(m, sin) + +# Check for getopt_long; if not found, use included source. +AC_CHECK_FUNCS([getopt_long],, +[# FreeBSD has a gnugetopt library. + AC_CHECK_LIB([gnugetopt],[getopt_long], +[AC_DEFINE([HAVE_GETOPT_LONG])], +[# Use the GNU replacement. +AC_LIBOBJ(getopt) +AC_LIBOBJ(getopt1)])]) + +AC_CHECK_LIB(winmm, main) + +AC_DEFINE_UNQUOTED(SPEEX_VERSION, "${SPEEX_VERSION}", [Complete version string]) +AC_DEFINE_UNQUOTED(SPEEX_MAJOR_VERSION, ${SPEEX_MAJOR_VERSION}, [Version major]) +AC_DEFINE_UNQUOTED(SPEEX_MINOR_VERSION, ${SPEEX_MINOR_VERSION}, [Version minor]) +AC_DEFINE_UNQUOTED(SPEEX_MICRO_VERSION, ${SPEEX_MICRO_VERSION}, [Version micro]) +AC_DEFINE_UNQUOTED(SPEEX_EXTRA_VERSION, "${SPEEX_EXTRA_VERSION}", [Version extra]) + +AC_ARG_ENABLE(wideband, [ --disable-wideband Disable wideband codec], +[if test "$enableval" = no; then + AC_DEFINE([DISABLE_WIDEBAND], , [Disable wideband codec]) +fi]) + +AC_ARG_ENABLE(valgrind, [ --enable-valgrind Enable valgrind extra checks], +[if test "$enableval" = yes; then + AC_DEFINE([ENABLE_VALGRIND], , [Enable valgrind extra checks]) +fi]) + +AC_ARG_ENABLE(sse, [ --enable-sse Enable SSE support], [if test "$enableval" = yes; then +AC_DEFINE([_USE_SSE], , [Enable SSE support]) +CFLAGS="$CFLAGS -O3 -msse" +fi +]) + +AC_ARG_ENABLE(fixed-point, [ --enable-fixed-point Compile as fixed-point], +[if test "$enableval" = yes; then + AC_DEFINE([FIXED_POINT], , [Compile as fixed-point]) +fi]) + +AC_ARG_ENABLE(arm4-asm, [ --enable-arm4-asm Make use of ARM4 assembly optimizations], +[if test "$enableval" = yes; then + AC_DEFINE([ARM4_ASM], , [Make use of ARM4 assembly optimizations]) +fi]) + +AC_ARG_ENABLE(arm5e-asm, [ --enable-arm5e-asm Make use of ARM5E assembly optimizations], +[if test "$enableval" = yes; then + AC_DEFINE([ARM5_ASM], , [Make use of ARM5E assembly optimizations]) +fi]) + +AC_ARG_ENABLE(blackfin-asm, [ --enable-blackfin-asm Make use of Blackfin assembly optimizations], +[if test "$enableval" = yes; then + AC_DEFINE([BFIN_ASM], , [Make use of Blackfin assembly optimizations]) +fi]) + +AC_ARG_ENABLE(fixed-point-debug, [ --enable-fixed-point-debug Debug fixed-point implementation], +[if test "$enableval" = yes; then + AC_DEFINE([FIXED_DEBUG], , [Debug fixed-point implementation]) +fi]) + +AC_ARG_ENABLE(epic-48k, [ --enable-epic-48k Enable support for Epic 4.8 kbps mode], +[if test "$enableval" = yes; then + AC_DEFINE([EPIC_48K], , [Enable support for Epic 4.8 kbps mode]) +fi]) + +AC_ARG_ENABLE(ti-c55x, [ --enable-ti-c55x Enable support for TI C55X DSP], +[if test "$enableval" = yes; then + has_char16=yes; + AC_DEFINE([TI_C55X], , [Enable support for TI C55X DSP]) +fi]) + +AC_ARG_ENABLE(16bit-precision, [ --enable-16bit-precision Reduce precision to 16 bits (EXPERIMENTAL)], +[if test "$enableval" = yes; then + AC_DEFINE([PRECISION16], , [Reduce precision to 16 bits (EXPERIMENTAL)]) +fi]) + +AC_CHECK_SIZEOF(short) +AC_CHECK_SIZEOF(int) +AC_CHECK_SIZEOF(long) +AC_CHECK_SIZEOF(long long) + +if test x$has_char16 = "xyes" ; then + case 1 in + $ac_cv_sizeof_short) SIZE16="short";; + $ac_cv_sizeof_int) SIZE16="int";; + esac +else + case 2 in + $ac_cv_sizeof_short) SIZE16="short";; + $ac_cv_sizeof_int) SIZE16="int";; + esac +fi + +if test x$has_char16 = "xyes" ; then + case 2 in + $ac_cv_sizeof_int) SIZE32="int";; + $ac_cv_sizeof_long) SIZE32="long";; + $ac_cv_sizeof_short) SIZE32="short";; + esac +else + case 4 in + $ac_cv_sizeof_int) SIZE32="int";; + $ac_cv_sizeof_long) SIZE32="long";; + $ac_cv_sizeof_short) SIZE32="short";; + esac +fi + +AC_SUBST(SIZE16) +AC_SUBST(SIZE32) + +AC_OUTPUT([Makefile libspeex/Makefile src/Makefile doc/Makefile Speex.spec + include/Makefile include/speex/Makefile speex.pc + win32/Makefile win32/libspeex/Makefile win32/speexenc/Makefile + win32/speexdec/Makefile symbian/Makefile + include/speex/speex_config_types.h ]) + +if test "x$src" = "x"; then +echo "**IMPORTANT**" +echo "You don't seem to have the development package for libogg (libogg-devel) installed. Only the Speex library (libspeex) will be built (no encoder/decoder executable)" +echo "You can download libogg from http://www.vorbis.com/download.psp" +fi + +echo "Type \"make; make install\" to compile and install Speex"; diff --git a/mozilla/zap/zmk/speex-1.1.10/depcomp b/mozilla/zap/zmk/speex-1.1.10/depcomp new file mode 100755 index 00000000000..1dfa0858ae4 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/depcomp @@ -0,0 +1,423 @@ +#! /bin/sh + +# depcomp - compile a program generating dependencies as side-effects +# Copyright 1999, 2000 Free Software Foundation, Inc. + +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2, or (at your option) +# any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA +# 02111-1307, USA. + +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + +# Originally written by Alexandre Oliva . + +if test -z "$depmode" || test -z "$source" || test -z "$object"; then + echo "depcomp: Variables source, object and depmode must be set" 1>&2 + exit 1 +fi +# `libtool' can also be set to `yes' or `no'. + +if test -z "$depfile"; then + base=`echo "$object" | sed -e 's,^.*/,,' -e 's,\.\([^.]*\)$,.P\1,'` + dir=`echo "$object" | sed 's,/.*$,/,'` + if test "$dir" = "$object"; then + dir= + fi + # FIXME: should be _deps on DOS. + depfile="$dir.deps/$base" +fi + +tmpdepfile=${tmpdepfile-`echo "$depfile" | sed 's/\.\([^.]*\)$/.T\1/'`} + +rm -f "$tmpdepfile" + +# Some modes work just like other modes, but use different flags. We +# parameterize here, but still list the modes in the big case below, +# to make depend.m4 easier to write. Note that we *cannot* use a case +# here, because this file can only contain one case statement. +if test "$depmode" = hp; then + # HP compiler uses -M and no extra arg. + gccflag=-M + depmode=gcc +fi + +if test "$depmode" = dashXmstdout; then + # This is just like dashmstdout with a different argument. + dashmflag=-xM + depmode=dashmstdout +fi + +case "$depmode" in +gcc3) +## gcc 3 implements dependency tracking that does exactly what +## we want. Yay! Note: for some reason libtool 1.4 doesn't like +## it if -MD -MP comes after the -MF stuff. Hmm. + "$@" -MT "$object" -MD -MP -MF "$tmpdepfile" + stat=$? + if test $stat -eq 0; then : + else + rm -f "$tmpdepfile" + exit $stat + fi + mv "$tmpdepfile" "$depfile" + ;; + +gcc) +## There are various ways to get dependency output from gcc. Here's +## why we pick this rather obscure method: +## - Don't want to use -MD because we'd like the dependencies to end +## up in a subdir. Having to rename by hand is ugly. +## (We might end up doing this anyway to support other compilers.) +## - The DEPENDENCIES_OUTPUT environment variable makes gcc act like +## -MM, not -M (despite what the docs say). +## - Using -M directly means running the compiler twice (even worse +## than renaming). + if test -z "$gccflag"; then + gccflag=-MD, + fi + "$@" -Wp,"$gccflag$tmpdepfile" + stat=$? + if test $stat -eq 0; then : + else + rm -f "$tmpdepfile" + exit $stat + fi + rm -f "$depfile" + echo "$object : \\" > "$depfile" + alpha=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz +## The second -e expression handles DOS-style file names with drive letters. + sed -e 's/^[^:]*: / /' \ + -e 's/^['$alpha']:\/[^:]*: / /' < "$tmpdepfile" >> "$depfile" +## This next piece of magic avoids the `deleted header file' problem. +## The problem is that when a header file which appears in a .P file +## is deleted, the dependency causes make to die (because there is +## typically no way to rebuild the header). We avoid this by adding +## dummy dependencies for each header file. Too bad gcc doesn't do +## this for us directly. + tr ' ' ' +' < "$tmpdepfile" | +## Some versions of gcc put a space before the `:'. On the theory +## that the space means something, we add a space to the output as +## well. +## Some versions of the HPUX 10.20 sed can't process this invocation +## correctly. Breaking it into two sed invocations is a workaround. + sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile" + rm -f "$tmpdepfile" + ;; + +hp) + # This case exists only to let depend.m4 do its work. It works by + # looking at the text of this script. This case will never be run, + # since it is checked for above. + exit 1 + ;; + +sgi) + if test "$libtool" = yes; then + "$@" "-Wp,-MDupdate,$tmpdepfile" + else + "$@" -MDupdate "$tmpdepfile" + fi + stat=$? + if test $stat -eq 0; then : + else + rm -f "$tmpdepfile" + exit $stat + fi + rm -f "$depfile" + + if test -f "$tmpdepfile"; then # yes, the sourcefile depend on other files + echo "$object : \\" > "$depfile" + + # Clip off the initial element (the dependent). Don't try to be + # clever and replace this with sed code, as IRIX sed won't handle + # lines with more than a fixed number of characters (4096 in + # IRIX 6.2 sed, 8192 in IRIX 6.5). We also remove comment lines; + # the IRIX cc adds comments like `#:fec' to the end of the + # dependency line. + tr ' ' ' +' < "$tmpdepfile" \ + | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' | \ + tr ' +' ' ' >> $depfile + echo >> $depfile + + # The second pass generates a dummy entry for each header file. + tr ' ' ' +' < "$tmpdepfile" \ + | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' -e 's/$/:/' \ + >> $depfile + else + # The sourcefile does not contain any dependencies, so just + # store a dummy comment line, to avoid errors with the Makefile + # "include basename.Plo" scheme. + echo "#dummy" > "$depfile" + fi + rm -f "$tmpdepfile" + ;; + +aix) + # The C for AIX Compiler uses -M and outputs the dependencies + # in a .u file. This file always lives in the current directory. + # Also, the AIX compiler puts `$object:' at the start of each line; + # $object doesn't have directory information. + stripped=`echo "$object" | sed -e 's,^.*/,,' -e 's/\(.*\)\..*$/\1/'` + tmpdepfile="$stripped.u" + outname="$stripped.o" + if test "$libtool" = yes; then + "$@" -Wc,-M + else + "$@" -M + fi + + stat=$? + if test $stat -eq 0; then : + else + rm -f "$tmpdepfile" + exit $stat + fi + + if test -f "$tmpdepfile"; then + # Each line is of the form `foo.o: dependent.h'. + # Do two passes, one to just change these to + # `$object: dependent.h' and one to simply `dependent.h:'. + sed -e "s,^$outname:,$object :," < "$tmpdepfile" > "$depfile" + sed -e "s,^$outname: \(.*\)$,\1:," < "$tmpdepfile" >> "$depfile" + else + # The sourcefile does not contain any dependencies, so just + # store a dummy comment line, to avoid errors with the Makefile + # "include basename.Plo" scheme. + echo "#dummy" > "$depfile" + fi + rm -f "$tmpdepfile" + ;; + +tru64) + # The Tru64 compiler uses -MD to generate dependencies as a side + # effect. `cc -MD -o foo.o ...' puts the dependencies into `foo.o.d'. + # At least on Alpha/Redhat 6.1, Compaq CCC V6.2-504 seems to put + # dependencies in `foo.d' instead, so we check for that too. + # Subdirectories are respected. + dir=`echo "$object" | sed -e 's|/[^/]*$|/|'` + test "x$dir" = "x$object" && dir= + base=`echo "$object" | sed -e 's|^.*/||' -e 's/\.o$//' -e 's/\.lo$//'` + + if test "$libtool" = yes; then + tmpdepfile1="$dir.libs/$base.lo.d" + tmpdepfile2="$dir.libs/$base.d" + "$@" -Wc,-MD + else + tmpdepfile1="$dir$base.o.d" + tmpdepfile2="$dir$base.d" + "$@" -MD + fi + + stat=$? + if test $stat -eq 0; then : + else + rm -f "$tmpdepfile1" "$tmpdepfile2" + exit $stat + fi + + if test -f "$tmpdepfile1"; then + tmpdepfile="$tmpdepfile1" + else + tmpdepfile="$tmpdepfile2" + fi + if test -f "$tmpdepfile"; then + sed -e "s,^.*\.[a-z]*:,$object:," < "$tmpdepfile" > "$depfile" + # That's a space and a tab in the []. + sed -e 's,^.*\.[a-z]*:[ ]*,,' -e 's,$,:,' < "$tmpdepfile" >> "$depfile" + else + echo "#dummy" > "$depfile" + fi + rm -f "$tmpdepfile" + ;; + +#nosideeffect) + # This comment above is used by automake to tell side-effect + # dependency tracking mechanisms from slower ones. + +dashmstdout) + # Important note: in order to support this mode, a compiler *must* + # always write the proprocessed file to stdout, regardless of -o. + "$@" || exit $? + + # Remove the call to Libtool. + if test "$libtool" = yes; then + while test $1 != '--mode=compile'; do + shift + done + shift + fi + + # Remove `-o $object'. We will use -o /dev/null later, + # however we can't do the remplacement now because + # `-o $object' might simply not be used + IFS=" " + for arg + do + case $arg in + -o) + shift + ;; + $object) + shift + ;; + *) + set fnord "$@" "$arg" + shift # fnord + shift # $arg + ;; + esac + done + + test -z "$dashmflag" && dashmflag=-M + "$@" -o /dev/null $dashmflag | sed 's:^[^:]*\:[ ]*:'"$object"'\: :' > "$tmpdepfile" + rm -f "$depfile" + cat < "$tmpdepfile" > "$depfile" + tr ' ' ' +' < "$tmpdepfile" | \ +## Some versions of the HPUX 10.20 sed can't process this invocation +## correctly. Breaking it into two sed invocations is a workaround. + sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile" + rm -f "$tmpdepfile" + ;; + +dashXmstdout) + # This case only exists to satisfy depend.m4. It is never actually + # run, as this mode is specially recognized in the preamble. + exit 1 + ;; + +makedepend) + "$@" || exit $? + # X makedepend + shift + cleared=no + for arg in "$@"; do + case $cleared in + no) + set ""; shift + cleared=yes ;; + esac + case "$arg" in + -D*|-I*) + set fnord "$@" "$arg"; shift ;; + -*) + ;; + *) + set fnord "$@" "$arg"; shift ;; + esac + done + obj_suffix="`echo $object | sed 's/^.*\././'`" + touch "$tmpdepfile" + ${MAKEDEPEND-makedepend} -o"$obj_suffix" -f"$tmpdepfile" "$@" + rm -f "$depfile" + cat < "$tmpdepfile" > "$depfile" + sed '1,2d' "$tmpdepfile" | tr ' ' ' +' | \ +## Some versions of the HPUX 10.20 sed can't process this invocation +## correctly. Breaking it into two sed invocations is a workaround. + sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile" + rm -f "$tmpdepfile" "$tmpdepfile".bak + ;; + +cpp) + # Important note: in order to support this mode, a compiler *must* + # always write the proprocessed file to stdout. + "$@" || exit $? + + # Remove the call to Libtool. + if test "$libtool" = yes; then + while test $1 != '--mode=compile'; do + shift + done + shift + fi + + # Remove `-o $object'. + IFS=" " + for arg + do + case $arg in + -o) + shift + ;; + $object) + shift + ;; + *) + set fnord "$@" "$arg" + shift # fnord + shift # $arg + ;; + esac + done + + "$@" -E | + sed -n '/^# [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' | + sed '$ s: \\$::' > "$tmpdepfile" + rm -f "$depfile" + echo "$object : \\" > "$depfile" + cat < "$tmpdepfile" >> "$depfile" + sed < "$tmpdepfile" '/^$/d;s/^ //;s/ \\$//;s/$/ :/' >> "$depfile" + rm -f "$tmpdepfile" + ;; + +msvisualcpp) + # Important note: in order to support this mode, a compiler *must* + # always write the proprocessed file to stdout, regardless of -o, + # because we must use -o when running libtool. + "$@" || exit $? + IFS=" " + for arg + do + case "$arg" in + "-Gm"|"/Gm"|"-Gi"|"/Gi"|"-ZI"|"/ZI") + set fnord "$@" + shift + shift + ;; + *) + set fnord "$@" "$arg" + shift + shift + ;; + esac + done + "$@" -E | + sed -n '/^#line [0-9][0-9]* "\([^"]*\)"/ s::echo "`cygpath -u \\"\1\\"`":p' | sort | uniq > "$tmpdepfile" + rm -f "$depfile" + echo "$object : \\" > "$depfile" + . "$tmpdepfile" | sed 's% %\\ %g' | sed -n '/^\(.*\)$/ s:: \1 \\:p' >> "$depfile" + echo " " >> "$depfile" + . "$tmpdepfile" | sed 's% %\\ %g' | sed -n '/^\(.*\)$/ s::\1\::p' >> "$depfile" + rm -f "$tmpdepfile" + ;; + +none) + exec "$@" + ;; + +*) + echo "Unknown depmode $depmode" 1>&2 + exit 1 + ;; +esac + +exit 0 diff --git a/mozilla/zap/zmk/speex-1.1.10/doc/Makefile.am b/mozilla/zap/zmk/speex-1.1.10/doc/Makefile.am new file mode 100755 index 00000000000..5bf427bb9d5 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/doc/Makefile.am @@ -0,0 +1,5 @@ +docdir=$(prefix)/share/doc/@PACKAGE@-@VERSION@ + +doc_DATA = manual.pdf + +EXTRA_DIST = $(doc_DATA) diff --git a/mozilla/zap/zmk/speex-1.1.10/doc/Makefile.in b/mozilla/zap/zmk/speex-1.1.10/doc/Makefile.in new file mode 100755 index 00000000000..c8219914727 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/doc/Makefile.in @@ -0,0 +1,345 @@ +# Makefile.in generated by automake 1.8.5 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004 Free Software Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +top_builddir = .. +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +INSTALL = @INSTALL@ +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +host_triplet = @host@ +subdir = doc +DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ + $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = +SOURCES = +DIST_SOURCES = +am__installdirs = "$(DESTDIR)$(docdir)" +docDATA_INSTALL = $(INSTALL_DATA) +DATA = $(doc_DATA) +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +AMDEP_FALSE = @AMDEP_FALSE@ +AMDEP_TRUE = @AMDEP_TRUE@ +AMTAR = @AMTAR@ +AR = @AR@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CXX = @CXX@ +CXXCPP = @CXXCPP@ +CXXDEPMODE = @CXXDEPMODE@ +CXXFLAGS = @CXXFLAGS@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +ECHO = @ECHO@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +F77 = @F77@ +FFLAGS = @FFLAGS@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +LDFLAGS = @LDFLAGS@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +MAINT = @MAINT@ +MAINTAINER_MODE_FALSE = @MAINTAINER_MODE_FALSE@ +MAINTAINER_MODE_TRUE = @MAINTAINER_MODE_TRUE@ +MAKEINFO = @MAKEINFO@ +OBJEXT = @OBJEXT@ +OGG_CFLAGS = @OGG_CFLAGS@ +OGG_LIBS = @OGG_LIBS@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +RANLIB = @RANLIB@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +SIZE16 = @SIZE16@ +SIZE32 = @SIZE32@ +SPEEX_LT_AGE = @SPEEX_LT_AGE@ +SPEEX_LT_CURRENT = @SPEEX_LT_CURRENT@ +SPEEX_LT_REVISION = @SPEEX_LT_REVISION@ +SPEEX_VERSION = @SPEEX_VERSION@ +STRIP = @STRIP@ +VERSION = @VERSION@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_CXX = @ac_ct_CXX@ +ac_ct_F77 = @ac_ct_F77@ +ac_ct_RANLIB = @ac_ct_RANLIB@ +ac_ct_STRIP = @ac_ct_STRIP@ +am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ +am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ +am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ +am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +datadir = @datadir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +src = @src@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +docdir = $(prefix)/share/doc/@PACKAGE@-@VERSION@ +doc_DATA = manual.pdf +EXTRA_DIST = $(doc_DATA) +all: all-am + +.SUFFIXES: +$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ + && exit 0; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu doc/Makefile'; \ + cd $(top_srcdir) && \ + $(AUTOMAKE) --gnu doc/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +distclean-libtool: + -rm -f libtool +uninstall-info-am: +install-docDATA: $(doc_DATA) + @$(NORMAL_INSTALL) + test -z "$(docdir)" || $(mkdir_p) "$(DESTDIR)$(docdir)" + @list='$(doc_DATA)'; for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + f="`echo $$p | sed -e 's|^.*/||'`"; \ + echo " $(docDATA_INSTALL) '$$d$$p' '$(DESTDIR)$(docdir)/$$f'"; \ + $(docDATA_INSTALL) "$$d$$p" "$(DESTDIR)$(docdir)/$$f"; \ + done + +uninstall-docDATA: + @$(NORMAL_UNINSTALL) + @list='$(doc_DATA)'; for p in $$list; do \ + f="`echo $$p | sed -e 's|^.*/||'`"; \ + echo " rm -f '$(DESTDIR)$(docdir)/$$f'"; \ + rm -f "$(DESTDIR)$(docdir)/$$f"; \ + done +tags: TAGS +TAGS: + +ctags: CTAGS +CTAGS: + + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ + list='$(DISTFILES)'; for file in $$list; do \ + case $$file in \ + $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ + $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ + esac; \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test "$$dir" != "$$file" && test "$$dir" != "."; then \ + dir="/$$dir"; \ + $(mkdir_p) "$(distdir)$$dir"; \ + else \ + dir=''; \ + fi; \ + if test -d $$d/$$file; then \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + fi; \ + cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + else \ + test -f $(distdir)/$$file \ + || cp -p $$d/$$file $(distdir)/$$file \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile $(DATA) +installdirs: + for dir in "$(DESTDIR)$(docdir)"; do \ + test -z "$$dir" || $(mkdir_p) "$$dir"; \ + done +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + `test -z '$(STRIP)' || \ + echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -rm -f $(CONFIG_CLEAN_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-am + -rm -f Makefile +distclean-am: clean-am distclean-generic distclean-libtool + +dvi: dvi-am + +dvi-am: + +html: html-am + +info: info-am + +info-am: + +install-data-am: install-docDATA + +install-exec-am: + +install-info: install-info-am + +install-man: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-docDATA uninstall-info-am + +.PHONY: all all-am check check-am clean clean-generic clean-libtool \ + distclean distclean-generic distclean-libtool distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-docDATA install-exec \ + install-exec-am install-info install-info-am install-man \ + install-strip installcheck installcheck-am installdirs \ + maintainer-clean maintainer-clean-generic mostlyclean \ + mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ + uninstall uninstall-am uninstall-docDATA uninstall-info-am + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/mozilla/zap/zmk/speex-1.1.10/doc/manual.pdf b/mozilla/zap/zmk/speex-1.1.10/doc/manual.pdf new file mode 100755 index 00000000000..69bff9fe12b Binary files /dev/null and b/mozilla/zap/zmk/speex-1.1.10/doc/manual.pdf differ diff --git a/mozilla/zap/zmk/speex-1.1.10/include/Makefile.am b/mozilla/zap/zmk/speex-1.1.10/include/Makefile.am new file mode 100755 index 00000000000..c428043110e --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/include/Makefile.am @@ -0,0 +1,2 @@ + +SUBDIRS = speex diff --git a/mozilla/zap/zmk/speex-1.1.10/include/Makefile.in b/mozilla/zap/zmk/speex-1.1.10/include/Makefile.in new file mode 100755 index 00000000000..2971223ca83 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/include/Makefile.in @@ -0,0 +1,462 @@ +# Makefile.in generated by automake 1.8.5 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004 Free Software Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +top_builddir = .. +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +INSTALL = @INSTALL@ +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +host_triplet = @host@ +subdir = include +DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ + $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = +SOURCES = +DIST_SOURCES = +RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \ + html-recursive info-recursive install-data-recursive \ + install-exec-recursive install-info-recursive \ + install-recursive installcheck-recursive installdirs-recursive \ + pdf-recursive ps-recursive uninstall-info-recursive \ + uninstall-recursive +ETAGS = etags +CTAGS = ctags +DIST_SUBDIRS = $(SUBDIRS) +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +AMDEP_FALSE = @AMDEP_FALSE@ +AMDEP_TRUE = @AMDEP_TRUE@ +AMTAR = @AMTAR@ +AR = @AR@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CXX = @CXX@ +CXXCPP = @CXXCPP@ +CXXDEPMODE = @CXXDEPMODE@ +CXXFLAGS = @CXXFLAGS@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +ECHO = @ECHO@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +F77 = @F77@ +FFLAGS = @FFLAGS@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +LDFLAGS = @LDFLAGS@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +MAINT = @MAINT@ +MAINTAINER_MODE_FALSE = @MAINTAINER_MODE_FALSE@ +MAINTAINER_MODE_TRUE = @MAINTAINER_MODE_TRUE@ +MAKEINFO = @MAKEINFO@ +OBJEXT = @OBJEXT@ +OGG_CFLAGS = @OGG_CFLAGS@ +OGG_LIBS = @OGG_LIBS@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +RANLIB = @RANLIB@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +SIZE16 = @SIZE16@ +SIZE32 = @SIZE32@ +SPEEX_LT_AGE = @SPEEX_LT_AGE@ +SPEEX_LT_CURRENT = @SPEEX_LT_CURRENT@ +SPEEX_LT_REVISION = @SPEEX_LT_REVISION@ +SPEEX_VERSION = @SPEEX_VERSION@ +STRIP = @STRIP@ +VERSION = @VERSION@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_CXX = @ac_ct_CXX@ +ac_ct_F77 = @ac_ct_F77@ +ac_ct_RANLIB = @ac_ct_RANLIB@ +ac_ct_STRIP = @ac_ct_STRIP@ +am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ +am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ +am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ +am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +datadir = @datadir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +src = @src@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +SUBDIRS = speex +all: all-recursive + +.SUFFIXES: +$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ + && exit 0; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu include/Makefile'; \ + cd $(top_srcdir) && \ + $(AUTOMAKE) --gnu include/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +distclean-libtool: + -rm -f libtool +uninstall-info-am: + +# This directory's subdirectories are mostly independent; you can cd +# into them and run `make' without going through this Makefile. +# To change the values of `make' variables: instead of editing Makefiles, +# (1) if the variable is set in `config.status', edit `config.status' +# (which will cause the Makefiles to be regenerated when you run `make'); +# (2) otherwise, pass the desired values on the `make' command line. +$(RECURSIVE_TARGETS): + @set fnord $$MAKEFLAGS; amf=$$2; \ + dot_seen=no; \ + target=`echo $@ | sed s/-recursive//`; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + dot_seen=yes; \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || case "$$amf" in *=*) exit 1;; *k*) fail=yes;; *) exit 1;; esac; \ + done; \ + if test "$$dot_seen" = "no"; then \ + $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ + fi; test -z "$$fail" + +mostlyclean-recursive clean-recursive distclean-recursive \ +maintainer-clean-recursive: + @set fnord $$MAKEFLAGS; amf=$$2; \ + dot_seen=no; \ + case "$@" in \ + distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ + *) list='$(SUBDIRS)' ;; \ + esac; \ + rev=''; for subdir in $$list; do \ + if test "$$subdir" = "."; then :; else \ + rev="$$subdir $$rev"; \ + fi; \ + done; \ + rev="$$rev ."; \ + target=`echo $@ | sed s/-recursive//`; \ + for subdir in $$rev; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || case "$$amf" in *=*) exit 1;; *k*) fail=yes;; *) exit 1;; esac; \ + done && test -z "$$fail" +tags-recursive: + list='$(SUBDIRS)'; for subdir in $$list; do \ + test "$$subdir" = . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \ + done +ctags-recursive: + list='$(SUBDIRS)'; for subdir in $$list; do \ + test "$$subdir" = . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \ + done + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: tags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + tags=; \ + here=`pwd`; \ + if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ + include_option=--etags-include; \ + empty_fix=.; \ + else \ + include_option=--include; \ + empty_fix=; \ + fi; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test ! -f $$subdir/TAGS || \ + tags="$$tags $$include_option=$$here/$$subdir/TAGS"; \ + fi; \ + done; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$tags $$unique; \ + fi +ctags: CTAGS +CTAGS: ctags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + tags=; \ + here=`pwd`; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + test -z "$(CTAGS_ARGS)$$tags$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$tags $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && cd $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) $$here + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ + list='$(DISTFILES)'; for file in $$list; do \ + case $$file in \ + $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ + $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ + esac; \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test "$$dir" != "$$file" && test "$$dir" != "."; then \ + dir="/$$dir"; \ + $(mkdir_p) "$(distdir)$$dir"; \ + else \ + dir=''; \ + fi; \ + if test -d $$d/$$file; then \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + fi; \ + cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + else \ + test -f $(distdir)/$$file \ + || cp -p $$d/$$file $(distdir)/$$file \ + || exit 1; \ + fi; \ + done + list='$(SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test -d "$(distdir)/$$subdir" \ + || mkdir "$(distdir)/$$subdir" \ + || exit 1; \ + (cd $$subdir && \ + $(MAKE) $(AM_MAKEFLAGS) \ + top_distdir="../$(top_distdir)" \ + distdir="../$(distdir)/$$subdir" \ + distdir) \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-recursive +all-am: Makefile +installdirs: installdirs-recursive +installdirs-am: +install: install-recursive +install-exec: install-exec-recursive +install-data: install-data-recursive +uninstall: uninstall-recursive + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-recursive +install-strip: + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + `test -z '$(STRIP)' || \ + echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -rm -f $(CONFIG_CLEAN_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-recursive + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-recursive + -rm -f Makefile +distclean-am: clean-am distclean-generic distclean-libtool \ + distclean-tags + +dvi: dvi-recursive + +dvi-am: + +html: html-recursive + +info: info-recursive + +info-am: + +install-data-am: + +install-exec-am: + +install-info: install-info-recursive + +install-man: + +installcheck-am: + +maintainer-clean: maintainer-clean-recursive + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-recursive + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-recursive + +pdf-am: + +ps: ps-recursive + +ps-am: + +uninstall-am: uninstall-info-am + +uninstall-info: uninstall-info-recursive + +.PHONY: $(RECURSIVE_TARGETS) CTAGS GTAGS all all-am check check-am \ + clean clean-generic clean-libtool clean-recursive ctags \ + ctags-recursive distclean distclean-generic distclean-libtool \ + distclean-recursive distclean-tags distdir dvi dvi-am html \ + html-am info info-am install install-am install-data \ + install-data-am install-exec install-exec-am install-info \ + install-info-am install-man install-strip installcheck \ + installcheck-am installdirs installdirs-am maintainer-clean \ + maintainer-clean-generic maintainer-clean-recursive \ + mostlyclean mostlyclean-generic mostlyclean-libtool \ + mostlyclean-recursive pdf pdf-am ps ps-am tags tags-recursive \ + uninstall uninstall-am uninstall-info-am + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/mozilla/zap/zmk/speex-1.1.10/include/speex/Makefile.am b/mozilla/zap/zmk/speex-1.1.10/include/speex/Makefile.am new file mode 100755 index 00000000000..6bf7a4c0f35 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/include/speex/Makefile.am @@ -0,0 +1,15 @@ +# Disable automatic dependency tracking if using other tools than gcc and gmake +#AUTOMAKE_OPTIONS = no-dependencies + +nodist_pkginclude_HEADERS = speex_config_types.h + +pkginclude_HEADERS = speex.h \ + speex_types.h \ + speex_bits.h \ + speex_header.h \ + speex_callbacks.h \ + speex_stereo.h \ + speex_preprocess.h \ + speex_jitter.h \ + speex_echo.h + diff --git a/mozilla/zap/zmk/speex-1.1.10/include/speex/Makefile.in b/mozilla/zap/zmk/speex-1.1.10/include/speex/Makefile.in new file mode 100755 index 00000000000..fd45d66c459 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/include/speex/Makefile.in @@ -0,0 +1,427 @@ +# Makefile.in generated by automake 1.8.5 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004 Free Software Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +# Disable automatic dependency tracking if using other tools than gcc and gmake +#AUTOMAKE_OPTIONS = no-dependencies + +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +top_builddir = ../.. +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +INSTALL = @INSTALL@ +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +host_triplet = @host@ +subdir = include/speex +DIST_COMMON = $(pkginclude_HEADERS) $(srcdir)/Makefile.am \ + $(srcdir)/Makefile.in $(srcdir)/speex_config_types.h.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ + $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = speex_config_types.h +SOURCES = +DIST_SOURCES = +am__installdirs = "$(DESTDIR)$(pkgincludedir)" "$(DESTDIR)$(pkgincludedir)" +nodist_pkgincludeHEADERS_INSTALL = $(INSTALL_HEADER) +pkgincludeHEADERS_INSTALL = $(INSTALL_HEADER) +HEADERS = $(nodist_pkginclude_HEADERS) $(pkginclude_HEADERS) +ETAGS = etags +CTAGS = ctags +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +AMDEP_FALSE = @AMDEP_FALSE@ +AMDEP_TRUE = @AMDEP_TRUE@ +AMTAR = @AMTAR@ +AR = @AR@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CXX = @CXX@ +CXXCPP = @CXXCPP@ +CXXDEPMODE = @CXXDEPMODE@ +CXXFLAGS = @CXXFLAGS@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +ECHO = @ECHO@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +F77 = @F77@ +FFLAGS = @FFLAGS@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +LDFLAGS = @LDFLAGS@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +MAINT = @MAINT@ +MAINTAINER_MODE_FALSE = @MAINTAINER_MODE_FALSE@ +MAINTAINER_MODE_TRUE = @MAINTAINER_MODE_TRUE@ +MAKEINFO = @MAKEINFO@ +OBJEXT = @OBJEXT@ +OGG_CFLAGS = @OGG_CFLAGS@ +OGG_LIBS = @OGG_LIBS@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +RANLIB = @RANLIB@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +SIZE16 = @SIZE16@ +SIZE32 = @SIZE32@ +SPEEX_LT_AGE = @SPEEX_LT_AGE@ +SPEEX_LT_CURRENT = @SPEEX_LT_CURRENT@ +SPEEX_LT_REVISION = @SPEEX_LT_REVISION@ +SPEEX_VERSION = @SPEEX_VERSION@ +STRIP = @STRIP@ +VERSION = @VERSION@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_CXX = @ac_ct_CXX@ +ac_ct_F77 = @ac_ct_F77@ +ac_ct_RANLIB = @ac_ct_RANLIB@ +ac_ct_STRIP = @ac_ct_STRIP@ +am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ +am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ +am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ +am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +datadir = @datadir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +src = @src@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +nodist_pkginclude_HEADERS = speex_config_types.h +pkginclude_HEADERS = speex.h \ + speex_types.h \ + speex_bits.h \ + speex_header.h \ + speex_callbacks.h \ + speex_stereo.h \ + speex_preprocess.h \ + speex_jitter.h \ + speex_echo.h + +all: all-am + +.SUFFIXES: +$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ + && exit 0; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu include/speex/Makefile'; \ + cd $(top_srcdir) && \ + $(AUTOMAKE) --gnu include/speex/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +speex_config_types.h: $(top_builddir)/config.status $(srcdir)/speex_config_types.h.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +distclean-libtool: + -rm -f libtool +uninstall-info-am: +install-nodist_pkgincludeHEADERS: $(nodist_pkginclude_HEADERS) + @$(NORMAL_INSTALL) + test -z "$(pkgincludedir)" || $(mkdir_p) "$(DESTDIR)$(pkgincludedir)" + @list='$(nodist_pkginclude_HEADERS)'; for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + f="`echo $$p | sed -e 's|^.*/||'`"; \ + echo " $(nodist_pkgincludeHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(pkgincludedir)/$$f'"; \ + $(nodist_pkgincludeHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(pkgincludedir)/$$f"; \ + done + +uninstall-nodist_pkgincludeHEADERS: + @$(NORMAL_UNINSTALL) + @list='$(nodist_pkginclude_HEADERS)'; for p in $$list; do \ + f="`echo $$p | sed -e 's|^.*/||'`"; \ + echo " rm -f '$(DESTDIR)$(pkgincludedir)/$$f'"; \ + rm -f "$(DESTDIR)$(pkgincludedir)/$$f"; \ + done +install-pkgincludeHEADERS: $(pkginclude_HEADERS) + @$(NORMAL_INSTALL) + test -z "$(pkgincludedir)" || $(mkdir_p) "$(DESTDIR)$(pkgincludedir)" + @list='$(pkginclude_HEADERS)'; for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + f="`echo $$p | sed -e 's|^.*/||'`"; \ + echo " $(pkgincludeHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(pkgincludedir)/$$f'"; \ + $(pkgincludeHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(pkgincludedir)/$$f"; \ + done + +uninstall-pkgincludeHEADERS: + @$(NORMAL_UNINSTALL) + @list='$(pkginclude_HEADERS)'; for p in $$list; do \ + f="`echo $$p | sed -e 's|^.*/||'`"; \ + echo " rm -f '$(DESTDIR)$(pkgincludedir)/$$f'"; \ + rm -f "$(DESTDIR)$(pkgincludedir)/$$f"; \ + done + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + tags=; \ + here=`pwd`; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$tags $$unique; \ + fi +ctags: CTAGS +CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + tags=; \ + here=`pwd`; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + test -z "$(CTAGS_ARGS)$$tags$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$tags $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && cd $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) $$here + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ + list='$(DISTFILES)'; for file in $$list; do \ + case $$file in \ + $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ + $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ + esac; \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test "$$dir" != "$$file" && test "$$dir" != "."; then \ + dir="/$$dir"; \ + $(mkdir_p) "$(distdir)$$dir"; \ + else \ + dir=''; \ + fi; \ + if test -d $$d/$$file; then \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + fi; \ + cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + else \ + test -f $(distdir)/$$file \ + || cp -p $$d/$$file $(distdir)/$$file \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile $(HEADERS) +installdirs: + for dir in "$(DESTDIR)$(pkgincludedir)" "$(DESTDIR)$(pkgincludedir)"; do \ + test -z "$$dir" || $(mkdir_p) "$$dir"; \ + done +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + `test -z '$(STRIP)' || \ + echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -rm -f $(CONFIG_CLEAN_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-am + -rm -f Makefile +distclean-am: clean-am distclean-generic distclean-libtool \ + distclean-tags + +dvi: dvi-am + +dvi-am: + +html: html-am + +info: info-am + +info-am: + +install-data-am: install-nodist_pkgincludeHEADERS \ + install-pkgincludeHEADERS + +install-exec-am: + +install-info: install-info-am + +install-man: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-info-am uninstall-nodist_pkgincludeHEADERS \ + uninstall-pkgincludeHEADERS + +.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ + clean-libtool ctags distclean distclean-generic \ + distclean-libtool distclean-tags distdir dvi dvi-am html \ + html-am info info-am install install-am install-data \ + install-data-am install-exec install-exec-am install-info \ + install-info-am install-man install-nodist_pkgincludeHEADERS \ + install-pkgincludeHEADERS install-strip installcheck \ + installcheck-am installdirs maintainer-clean \ + maintainer-clean-generic mostlyclean mostlyclean-generic \ + mostlyclean-libtool pdf pdf-am ps ps-am tags uninstall \ + uninstall-am uninstall-info-am \ + uninstall-nodist_pkgincludeHEADERS uninstall-pkgincludeHEADERS + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/mozilla/zap/zmk/speex-1.1.10/include/speex/speex.h b/mozilla/zap/zmk/speex-1.1.10/include/speex/speex.h new file mode 100755 index 00000000000..265b334fe92 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/include/speex/speex.h @@ -0,0 +1,410 @@ +/* Copyright (C) 2002 Jean-Marc Valin*/ +/** + @file speex.h + @brief Describes the different modes of the codec +*/ +/* + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 SPEEX_H +#define SPEEX_H + +#include "speex/speex_bits.h" +#include "speex/speex_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* Values allowed for *ctl() requests */ + +/** Set enhancement on/off (decoder only) */ +#define SPEEX_SET_ENH 0 +/** Get enhancement state (decoder only) */ +#define SPEEX_GET_ENH 1 + +/*Would be SPEEX_SET_FRAME_SIZE, but it's (currently) invalid*/ +/** Obtain frame size used by encoder/decoder */ +#define SPEEX_GET_FRAME_SIZE 3 + +/** Set quality value */ +#define SPEEX_SET_QUALITY 4 +/** Get current quality setting */ +/* #define SPEEX_GET_QUALITY 5 -- Doesn't make much sense, does it? */ + +/** Set sub-mode to use */ +#define SPEEX_SET_MODE 6 +/** Get current sub-mode in use */ +#define SPEEX_GET_MODE 7 + +/** Set low-band sub-mode to use (wideband only)*/ +#define SPEEX_SET_LOW_MODE 8 +/** Get current low-band mode in use (wideband only)*/ +#define SPEEX_GET_LOW_MODE 9 + +/** Set high-band sub-mode to use (wideband only)*/ +#define SPEEX_SET_HIGH_MODE 10 +/** Get current high-band mode in use (wideband only)*/ +#define SPEEX_GET_HIGH_MODE 11 + +/** Set VBR on (1) or off (0) */ +#define SPEEX_SET_VBR 12 +/** Get VBR status (1 for on, 0 for off) */ +#define SPEEX_GET_VBR 13 + +/** Set quality value for VBR encoding (0-10) */ +#define SPEEX_SET_VBR_QUALITY 14 +/** Get current quality value for VBR encoding (0-10) */ +#define SPEEX_GET_VBR_QUALITY 15 + +/** Set complexity of the encoder (0-10) */ +#define SPEEX_SET_COMPLEXITY 16 +/** Get current complexity of the encoder (0-10) */ +#define SPEEX_GET_COMPLEXITY 17 + +/** Set bit-rate used by the encoder (or lower) */ +#define SPEEX_SET_BITRATE 18 +/** Get current bit-rate used by the encoder or decoder */ +#define SPEEX_GET_BITRATE 19 + +/**Define a handler function for in-band Speex request*/ +#define SPEEX_SET_HANDLER 20 + +/**Define a handler function for in-band user-defined request*/ +#define SPEEX_SET_USER_HANDLER 22 + +/** Set sampling rate used in bit-rate computation */ +#define SPEEX_SET_SAMPLING_RATE 24 +/** Get sampling rate used in bit-rate computation */ +#define SPEEX_GET_SAMPLING_RATE 25 + +/** Reset the encoder/decoder memories to zero*/ +#define SPEEX_RESET_STATE 26 + +/** Get VBR info (mostly used internally) */ +#define SPEEX_GET_RELATIVE_QUALITY 29 + +/** Set VAD status (1 for on, 0 for off) */ +#define SPEEX_SET_VAD 30 + +/** Get VAD status (1 for on, 0 for off) */ +#define SPEEX_GET_VAD 31 + +/** Set Average Bit-Rate (ABR) to n bits per seconds */ +#define SPEEX_SET_ABR 32 +/** Get Average Bit-Rate (ABR) setting (in bps) */ +#define SPEEX_GET_ABR 33 + +/** Set DTX status (1 for on, 0 for off) */ +#define SPEEX_SET_DTX 34 +/** Get DTX status (1 for on, 0 for off) */ +#define SPEEX_GET_DTX 35 + +/** Set submode encoding in each frame (1 for yes, 0 for no, setting to no breaks the standard) */ +#define SPEEX_SET_SUBMODE_ENCODING 36 +/** */ +#define SPEEX_GET_SUBMODE_ENCODING 37 + +/*#define SPEEX_SET_LOOKAHEAD 38*/ +/** Returns the lookahead used by Speex */ +#define SPEEX_GET_LOOKAHEAD 39 + +/** Sets tuning for packet-loss concealment (expected loss rate) */ +#define SPEEX_SET_PLC_TUNING 40 +/** Gets tuning for PLC */ +#define SPEEX_GET_PLC_TUNING 41 + +/* Used internally, not to be used in applications */ +/** Used internally*/ +#define SPEEX_GET_PI_GAIN 100 +/** Used internally*/ +#define SPEEX_GET_EXC 101 +/** Used internally*/ +#define SPEEX_GET_INNOV 102 +/** Used internally*/ +#define SPEEX_GET_DTX_STATUS 103 + + +/* Preserving compatibility:*/ +/** Equivalent to SPEEX_SET_ENH */ +#define SPEEX_SET_PF 0 +/** Equivalent to SPEEX_GET_ENH */ +#define SPEEX_GET_PF 1 + + + + +/* Values allowed for mode queries */ +/** Query the frame size of a mode */ +#define SPEEX_MODE_FRAME_SIZE 0 + +/** Query the size of an encoded frame for a particular sub-mode */ +#define SPEEX_SUBMODE_BITS_PER_FRAME 1 + + + +#define SPEEX_LIB_GET_MAJOR_VERSION 1 +#define SPEEX_LIB_GET_MINOR_VERSION 3 +#define SPEEX_LIB_GET_MICRO_VERSION 5 +#define SPEEX_LIB_GET_EXTRA_VERSION 7 +#define SPEEX_LIB_GET_VERSION_STRING 9 + +/*#define SPEEX_LIB_SET_ALLOC_FUNC 10 +#define SPEEX_LIB_GET_ALLOC_FUNC 11 +#define SPEEX_LIB_SET_FREE_FUNC 12 +#define SPEEX_LIB_GET_FREE_FUNC 13 + +#define SPEEX_LIB_SET_WARNING_FUNC 14 +#define SPEEX_LIB_GET_WARNING_FUNC 15 +#define SPEEX_LIB_SET_ERROR_FUNC 16 +#define SPEEX_LIB_GET_ERROR_FUNC 17 +*/ + +/** Number of defined modes in Speex */ +#define SPEEX_NB_MODES 3 + +/** modeID for the defined narrowband mode */ +#define SPEEX_MODEID_NB 0 + +/** modeID for the defined wideband mode */ +#define SPEEX_MODEID_WB 1 + +/** modeID for the defined ultra-wideband mode */ +#define SPEEX_MODEID_UWB 2 + +#ifdef EPIC_48K +/** modeID for the Epic 48K mode */ +#define SPEEX_MODEID_NB_48K 1000 +#endif + +struct SpeexMode; + + +/* Prototypes for mode function pointers */ + +/** Encoder state initialization function */ +typedef void *(*encoder_init_func)(const struct SpeexMode *mode); + +/** Encoder state destruction function */ +typedef void (*encoder_destroy_func)(void *st); + +/** Main encoding function */ +typedef int (*encode_func)(void *state, void *in, SpeexBits *bits); + +/** Function for controlling the encoder options */ +typedef int (*encoder_ctl_func)(void *state, int request, void *ptr); + +/** Decoder state initialization function */ +typedef void *(*decoder_init_func)(const struct SpeexMode *mode); + +/** Decoder state destruction function */ +typedef void (*decoder_destroy_func)(void *st); + +/** Main decoding function */ +typedef int (*decode_func)(void *state, SpeexBits *bits, void *out); + +/** Function for controlling the decoder options */ +typedef int (*decoder_ctl_func)(void *state, int request, void *ptr); + + +/** Query function for a mode */ +typedef int (*mode_query_func)(const void *mode, int request, void *ptr); + +/** Struct defining a Speex mode */ +typedef struct SpeexMode { + /** Pointer to the low-level mode data */ + const void *mode; + + /** Pointer to the mode query function */ + mode_query_func query; + + /** The name of the mode (you should not rely on this to identify the mode)*/ + const char *modeName; + + /**ID of the mode*/ + int modeID; + + /**Version number of the bitstream (incremented every time we break + bitstream compatibility*/ + int bitstream_version; + + /** Pointer to encoder initialization function */ + encoder_init_func enc_init; + + /** Pointer to encoder destruction function */ + encoder_destroy_func enc_destroy; + + /** Pointer to frame encoding function */ + encode_func enc; + + /** Pointer to decoder initialization function */ + decoder_init_func dec_init; + + /** Pointer to decoder destruction function */ + decoder_destroy_func dec_destroy; + + /** Pointer to frame decoding function */ + decode_func dec; + + /** ioctl-like requests for encoder */ + encoder_ctl_func enc_ctl; + + /** ioctl-like requests for decoder */ + decoder_ctl_func dec_ctl; + +} SpeexMode; + +/** + * Returns a handle to a newly created Speex encoder state structure. For now, + * the "mode" argument can be &nb_mode or &wb_mode . In the future, more modes + * may be added. Note that for now if you have more than one channels to + * encode, you need one state per channel. + * + * @param mode The mode to use (either speex_nb_mode or speex_wb.mode) + * @return A newly created encoder + */ +void *speex_encoder_init(const SpeexMode *mode); + +/** Frees all resources associated to an existing Speex encoder state. + * @param state Encoder state to be destroyed */ +void speex_encoder_destroy(void *state); + +/** Uses an existing encoder state to encode one frame of speech pointed to by + "in". The encoded bit-stream is saved in "bits". + @param state Encoder state + @param in Frame that will be encoded with a +-2^15 range + @param bits Bit-stream where the data will be written + */ +int speex_encode(void *state, float *in, SpeexBits *bits); + +/** Uses an existing encoder state to encode one frame of speech pointed to by + "in". The encoded bit-stream is saved in "bits". + @param state Encoder state + @param in Frame that will be encoded with a +-2^15 range + @param bits Bit-stream where the data will be written + */ +int speex_encode_int(void *state, spx_int16_t *in, SpeexBits *bits); + +/** Used like the ioctl function to control the encoder parameters + * + * @param state Encoder state + * @param request ioctl-type request (one of the SPEEX_* macros) + * @param ptr Data exchanged to-from function + * @return 0 if frame needs not be transmitted (DTX only), 1 otherwise + */ +int speex_encoder_ctl(void *state, int request, void *ptr); + + +/** Returns a handle to a newly created decoder state structure. For now, + * the mode argument can be &nb_mode or &wb_mode . In the future, more modes + * may be added. Note that for now if you have more than one channels to + * decode, you need one state per channel. + * + * @param mode Speex mode (one of speex_nb_mode or speex_wb_mode) + * @return A newly created decoder state + */ +void *speex_decoder_init(const SpeexMode *mode); + +/** Frees all resources associated to an existing decoder state. + * + * @param state State to be destroyed + */ +void speex_decoder_destroy(void *state); + +/** Uses an existing decoder state to decode one frame of speech from + * bit-stream bits. The output speech is saved written to out. + * + * @param state Decoder state + * @param bits Bit-stream from which to decode the frame (NULL if the packet was lost) + * @param out Where to write the decoded frame + * @return return status (0 for no error, -1 for end of stream, -2 other) + */ +int speex_decode(void *state, SpeexBits *bits, float *out); + +/** Uses an existing decoder state to decode one frame of speech from + * bit-stream bits. The output speech is saved written to out. + * + * @param state Decoder state + * @param bits Bit-stream from which to decode the frame (NULL if the packet was lost) + * @param out Where to write the decoded frame + * @return return status (0 for no error, -1 for end of stream, -2 other) + */ +int speex_decode_int(void *state, SpeexBits *bits, spx_int16_t *out); + +/** Used like the ioctl function to control the encoder parameters + * + * @param state Decoder state + * @param request ioctl-type request (one of the SPEEX_* macros) + * @param ptr Data exchanged to-from function + * @return 0 for no error, 1 if a terminator is reached, 2 for another error + */ +int speex_decoder_ctl(void *state, int request, void *ptr); + + +/** Query function for mode information + * + * @param mode Speex mode + * @param request ioctl-type request (one of the SPEEX_* macros) + * @param ptr Data exchanged to-from function + */ +int speex_mode_query(const SpeexMode *mode, int request, void *ptr); + +/** Functions for controlling the behavior of libspeex + * @param request ioctl-type request (one of the SPEEX_LIB_* macros) + * @param ptr Data exchanged to-from function + */ +int speex_lib_ctl(int request, void *ptr); + +/** Default narrowband mode */ +extern const SpeexMode speex_nb_mode; + +/** Default wideband mode */ +extern const SpeexMode speex_wb_mode; + +/** Default "ultra-wideband" mode */ +extern const SpeexMode speex_uwb_mode; + +#ifdef EPIC_48K +/** 4.8 kbps narrowband mode */ +extern const SpeexMode speex_nb_48k_mode; +#endif + +/** List of all modes available */ +extern const SpeexMode * const speex_mode_list[SPEEX_NB_MODES]; + +/** Obtain one of the modes available */ +const SpeexMode * speex_lib_get_mode (int mode); + +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/mozilla/zap/zmk/speex-1.1.10/include/speex/speex_bits.h b/mozilla/zap/zmk/speex-1.1.10/include/speex/speex_bits.h new file mode 100755 index 00000000000..a9fc8f7d4a3 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/include/speex/speex_bits.h @@ -0,0 +1,151 @@ +/* Copyright (C) 2002 Jean-Marc Valin */ +/** + @file speex_bits.h + @brief Handles bit packing/unpacking +*/ +/* + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 BITS_H +#define BITS_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** Bit-packing data structure representing (part of) a bit-stream. */ +typedef struct SpeexBits { + char *chars; /**< "raw" data */ + int nbBits; /**< Total number of bits stored in the stream*/ + int charPtr; /**< Position of the byte "cursor" */ + int bitPtr; /**< Position of the bit "cursor" within the current char */ + int owner; /**< Does the struct "own" the "raw" buffer (member "chars") */ + int overflow;/**< Set to one if we try to read past the valid data */ + int buf_size;/**< Allocated size for buffer */ + int reserved1; /**< Reserved for future use */ + void *reserved2; /**< Reserved for future use */ +} SpeexBits; + +/** Initializes and allocates resources for a SpeexBits struct */ +void speex_bits_init(SpeexBits *bits); + +/** Initializes SpeexBits struct using a pre-allocated buffer*/ +void speex_bits_init_buffer(SpeexBits *bits, void *buff, int buf_size); + +/** Frees all resources associated to a SpeexBits struct. Right now this does nothing since no resources are allocated, but this could change in the future.*/ +void speex_bits_destroy(SpeexBits *bits); + +/** Resets bits to initial value (just after initialization, erasing content)*/ +void speex_bits_reset(SpeexBits *bits); + +/** Rewind the bit-stream to the beginning (ready for read) without erasing the content */ +void speex_bits_rewind(SpeexBits *bits); + +/** Initializes the bit-stream from the data in an area of memory */ +void speex_bits_read_from(SpeexBits *bits, char *bytes, int len); + +/** Append bytes to the bit-stream + * @param bits Bit-stream to operate on + * @param bytes pointer to the bytes what will be appended + * @param len Number of bytes of append + */ +void speex_bits_read_whole_bytes(SpeexBits *bits, char *bytes, int len); + +/** Write the content of a bit-stream to an area of memory */ +int speex_bits_write(SpeexBits *bits, char *bytes, int max_len); + +/** Like speex_bits_write, but writes only the complete bytes in the stream. Also removes the written bytes from the stream */ +int speex_bits_write_whole_bytes(SpeexBits *bits, char *bytes, int max_len); + +/** Append bits to the bit-stream + * @param bits Bit-stream to operate on + * @param data Value to append as integer + * @param nbBits number of bits to consider in "data" + */ +void speex_bits_pack(SpeexBits *bits, int data, int nbBits); + +/** Interpret the next bits in the bit-stream as a signed integer + * + * @param bits Bit-stream to operate on + * @param nbBits Number of bits to interpret + * @return A signed integer represented by the bits read + */ +int speex_bits_unpack_signed(SpeexBits *bits, int nbBits); + +/** Interpret the next bits in the bit-stream as an unsigned integer + * + * @param bits Bit-stream to operate on + * @param nbBits Number of bits to interpret + * @return An unsigned integer represented by the bits read + */ +unsigned int speex_bits_unpack_unsigned(SpeexBits *bits, int nbBits); + +/** Returns the number of bytes in the bit-stream, including the last one even if it is not "full" + * + * @param bits Bit-stream to operate on + * @return Number of bytes in the stream + */ +int speex_bits_nbytes(SpeexBits *bits); + +/** Same as speex_bits_unpack_unsigned, but without modifying the cursor position */ +unsigned int speex_bits_peek_unsigned(SpeexBits *bits, int nbBits); + +/** Get the value of the next bit in the stream, without modifying the + * "cursor" position + * + * @param bits Bit-stream to operate on + */ +int speex_bits_peek(SpeexBits *bits); + +/** Advances the position of the "bit cursor" in the stream + * + * @param bits Bit-stream to operate on + * @param n Number of bits to advance + */ +void speex_bits_advance(SpeexBits *bits, int n); + +/** Returns the number of bits remaining to be read in a stream + * + * @param bits Bit-stream to operate on + */ +int speex_bits_remaining(SpeexBits *bits); + +/** Insert a terminator so that the data can be sent as a packet while auto-detecting + * the number of frames in each packet + * + * @param bits Bit-stream to operate on + */ +void speex_bits_insert_terminator(SpeexBits *bits); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/mozilla/zap/zmk/speex-1.1.10/include/speex/speex_callbacks.h b/mozilla/zap/zmk/speex-1.1.10/include/speex/speex_callbacks.h new file mode 100755 index 00000000000..faddfb45830 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/include/speex/speex_callbacks.h @@ -0,0 +1,128 @@ +/* Copyright (C) 2002 Jean-Marc Valin*/ +/** + @file speex_callbacks.h + @brief Describes callback handling and in-band signalling +*/ +/* + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 SPEEX_CALLBACKS_H +#define SPEEX_CALLBACKS_H + +#include "speex.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** Total number of callbacks */ +#define SPEEX_MAX_CALLBACKS 16 + +/* Describes all the in-band requests */ + +/*These are 1-bit requests*/ +/** Request for perceptual enhancement (1 for on, 0 for off) */ +#define SPEEX_INBAND_ENH_REQUEST 0 +/** Reserved */ +#define SPEEX_INBAND_RESERVED1 1 + +/*These are 4-bit requests*/ +/** Request for a mode change */ +#define SPEEX_INBAND_MODE_REQUEST 2 +/** Request for a low mode change */ +#define SPEEX_INBAND_LOW_MODE_REQUEST 3 +/** Request for a high mode change */ +#define SPEEX_INBAND_HIGH_MODE_REQUEST 4 +/** Request for VBR (1 on, 0 off) */ +#define SPEEX_INBAND_VBR_QUALITY_REQUEST 5 +/** Request to be sent acknowledge */ +#define SPEEX_INBAND_ACKNOWLEDGE_REQUEST 6 +/** Request for VBR (1 for on, 0 for off) */ +#define SPEEX_INBAND_VBR_REQUEST 7 + +/*These are 8-bit requests*/ +/** Send a character in-band */ +#define SPEEX_INBAND_CHAR 8 +/** Intensity stereo information */ +#define SPEEX_INBAND_STEREO 9 + +/*These are 16-bit requests*/ +/** Transmit max bit-rate allowed */ +#define SPEEX_INBAND_MAX_BITRATE 10 + +/*These are 32-bit requests*/ +/** Acknowledge packet reception */ +#define SPEEX_INBAND_ACKNOWLEDGE 12 + +/** Callback function type */ +typedef int (*speex_callback_func)(SpeexBits *bits, void *state, void *data); + +/** Callback information */ +typedef struct SpeexCallback { + int callback_id; /**< ID associated to the callback */ + speex_callback_func func; /**< Callback handler function */ + void *data; /**< Data that will be sent to the handler */ + void *reserved1; /**< Reserved for future use */ + int reserved2; /**< Reserved for future use */ +} SpeexCallback; + +/** Handle in-band request */ +int speex_inband_handler(SpeexBits *bits, SpeexCallback *callback_list, void *state); + +/** Standard handler for mode request (change mode, no questions asked) */ +int speex_std_mode_request_handler(SpeexBits *bits, void *state, void *data); + +/** Standard handler for high mode request (change high mode, no questions asked) */ +int speex_std_high_mode_request_handler(SpeexBits *bits, void *state, void *data); + +/** Standard handler for in-band characters (write to stderr) */ +int speex_std_char_handler(SpeexBits *bits, void *state, void *data); + +/** Default handler for user-defined requests: in this case, just ignore */ +int speex_default_user_handler(SpeexBits *bits, void *state, void *data); + + + + +int speex_std_low_mode_request_handler(SpeexBits *bits, void *state, void *data); + +int speex_std_vbr_request_handler(SpeexBits *bits, void *state, void *data); + +int speex_std_enh_request_handler(SpeexBits *bits, void *state, void *data); + +int speex_std_vbr_quality_request_handler(SpeexBits *bits, void *state, void *data); + + +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/mozilla/zap/zmk/speex-1.1.10/include/speex/speex_config_types.h.in b/mozilla/zap/zmk/speex-1.1.10/include/speex/speex_config_types.h.in new file mode 100755 index 00000000000..d557576bf46 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/include/speex/speex_config_types.h.in @@ -0,0 +1,11 @@ +#ifndef __SPEEX_TYPES_H__ +#define __SPEEX_TYPES_H__ + +/* these are filled in by configure */ +typedef @SIZE16@ spx_int16_t; +typedef unsigned @SIZE16@ spx_uint16_t; +typedef @SIZE32@ spx_int32_t; +typedef unsigned @SIZE32@ spx_uint32_t; + +#endif + diff --git a/mozilla/zap/zmk/speex-1.1.10/include/speex/speex_echo.h b/mozilla/zap/zmk/speex-1.1.10/include/speex/speex_echo.h new file mode 100755 index 00000000000..96ba37fee6d --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/include/speex/speex_echo.h @@ -0,0 +1,98 @@ +/* Copyright (C) Jean-Marc Valin + + File: speex_echo.h + + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. 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. + + 3. The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 SPEEX_ECHO_H +#define SPEEX_ECHO_H + +#ifdef __cplusplus +extern "C" { +#endif + +struct drft_lookup; + +typedef struct SpeexEchoState { + int frame_size; /**< Number of samples processed each time */ + int window_size; + int M; + int cancel_count; + int adapted; + float adapt_rate; + float sum_adapt; + float Sey; + float Syy; + float See; + + float *x; + float *X; + float *d; + float *D; + float *y; + float *y2; + float *last_y; + float *Yps; + float *Y; + float *Y2; + float *E; + float *PHI; + float * restrict W; + float *power; + float *power_1; + float *grad; + float *Rf; + float *Yf; + float *Xf; + float *fratio; + float *regul; + + struct drft_lookup *fft_lookup; + + +} SpeexEchoState; + + +/** Creates a new echo canceller state */ +SpeexEchoState *speex_echo_state_init(int frame_size, int filter_length); + +/** Destroys an echo canceller state */ +void speex_echo_state_destroy(SpeexEchoState *st); + +/** Performs echo cancellation a frame */ +void speex_echo_cancel(SpeexEchoState *st, short *ref, short *echo, short *out, float *Y); + +/** Reset the echo canceller state */ +void speex_echo_state_reset(SpeexEchoState *st); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/mozilla/zap/zmk/speex-1.1.10/include/speex/speex_header.h b/mozilla/zap/zmk/speex-1.1.10/include/speex/speex_header.h new file mode 100755 index 00000000000..fa97f7a307c --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/include/speex/speex_header.h @@ -0,0 +1,86 @@ +/* Copyright (C) 2002 Jean-Marc Valin */ +/** + @file speex_header.h + @brief Describes the Speex header +*/ +/* + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 SPEEX_HEADER_H +#define SPEEX_HEADER_H + +#include "speex/speex_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct SpeexMode; + +#define SPEEX_HEADER_STRING_LENGTH 8 + +/** Maximum number of characters for encoding the Speex version number in the header */ +#define SPEEX_HEADER_VERSION_LENGTH 20 + +/** Speex header info for file-based formats */ +typedef struct SpeexHeader { + char speex_string[SPEEX_HEADER_STRING_LENGTH]; /**< Identifies a Speex bit-stream, always set to "Speex " */ + char speex_version[SPEEX_HEADER_VERSION_LENGTH]; /**< Speex version */ + spx_int32_t speex_version_id; /**< Version for Speex (for checking compatibility) */ + spx_int32_t header_size; /**< Total size of the header ( sizeof(SpeexHeader) ) */ + spx_int32_t rate; /**< Sampling rate used */ + spx_int32_t mode; /**< Mode used (0 for narrowband, 1 for wideband) */ + spx_int32_t mode_bitstream_version; /**< Version ID of the bit-stream */ + spx_int32_t nb_channels; /**< Number of channels encoded */ + spx_int32_t bitrate; /**< Bit-rate used */ + spx_int32_t frame_size; /**< Size of frames */ + spx_int32_t vbr; /**< 1 for a VBR encoding, 0 otherwise */ + spx_int32_t frames_per_packet; /**< Number of frames stored per Ogg packet */ + spx_int32_t extra_headers; /**< Number of additional headers after the comments */ + spx_int32_t reserved1; /**< Reserved for future use, must be zero */ + spx_int32_t reserved2; /**< Reserved for future use, must be zero */ +} SpeexHeader; + +/** Initializes a SpeexHeader using basic information */ +void speex_init_header(SpeexHeader *header, int rate, int nb_channels, const struct SpeexMode *m); + +/** Creates the header packet from the header itself (mostly involves endianness conversion) */ +char *speex_header_to_packet(SpeexHeader *header, int *size); + +/** Creates a SpeexHeader from a packet */ +SpeexHeader *speex_packet_to_header(char *packet, int size); + +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/mozilla/zap/zmk/speex-1.1.10/include/speex/speex_jitter.h b/mozilla/zap/zmk/speex-1.1.10/include/speex/speex_jitter.h new file mode 100755 index 00000000000..efe68901387 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/include/speex/speex_jitter.h @@ -0,0 +1,87 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: speex_jitter.h + + Adaptive jitter buffer for Speex + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 SPEEX_JITTER_H +#define SPEEX_JITTER_H + +#include "speex.h" +#include "speex_bits.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define SPEEX_JITTER_MAX_PACKET_SIZE 1500 +#define SPEEX_JITTER_MAX_BUFFER_SIZE 20 + +#define MAX_MARGIN 12 + +typedef struct SpeexJitter { + int buffer_size; + int pointer_timestamp; + + SpeexBits current_packet; + int valid_bits; + + char buf[SPEEX_JITTER_MAX_BUFFER_SIZE][SPEEX_JITTER_MAX_PACKET_SIZE]; + int timestamp[SPEEX_JITTER_MAX_BUFFER_SIZE]; + int len[SPEEX_JITTER_MAX_BUFFER_SIZE]; + + void *dec; + int frame_size; + int frame_time; + int reset_state; + + int lost_count; + float shortterm_margin[MAX_MARGIN]; + float longterm_margin[MAX_MARGIN]; + float loss_rate; +} SpeexJitter; + +void speex_jitter_init(SpeexJitter *jitter, void *decoder, int sampling_rate); + +void speex_jitter_destroy(SpeexJitter *jitter); + +void speex_jitter_put(SpeexJitter *jitter, char *packet, int len, int time); + +void speex_jitter_get(SpeexJitter *jitter, short *out, int *current_timestamp); + +int speex_jitter_get_pointer_timestamp(SpeexJitter *jitter); + +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/mozilla/zap/zmk/speex-1.1.10/include/speex/speex_preprocess.h b/mozilla/zap/zmk/speex-1.1.10/include/speex/speex_preprocess.h new file mode 100755 index 00000000000..50b5bbf274c --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/include/speex/speex_preprocess.h @@ -0,0 +1,147 @@ +/* Copyright (C) 2003 Epic Games + Written by Jean-Marc Valin + + File: speex_preprocess.h + + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. 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. + + 3. The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 SPEEX_PREPROCESS_H +#define SPEEX_PREPROCESS_H + +#include "speex/speex_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct drft_lookup; + +typedef struct SpeexPreprocessState { + int frame_size; /**< Number of samples processed each time */ + int ps_size; /**< Number of points in the power spectrum */ + int sampling_rate; /**< Sampling rate of the input/output */ + + /* parameters */ + int denoise_enabled; + int agc_enabled; + float agc_level; + int vad_enabled; + int dereverb_enabled; + float reverb_decay; + float reverb_level; + + float *frame; /**< Processing frame (2*ps_size) */ + float *ps; /**< Current power spectrum */ + float *gain2; /**< Adjusted gains */ + float *window; /**< Analysis/Synthesis window */ + float *noise; /**< Noise estimate */ + float *reverb_estimate; /**< Estimate of reverb energy */ + float *old_ps; /**< Power spectrum for last frame */ + float *gain; /**< Ephraim Malah gain */ + float *prior; /**< A-priori SNR */ + float *post; /**< A-posteriori SNR */ + + float *S; /**< Smoothed power spectrum */ + float *Smin; /**< See Cohen paper */ + float *Stmp; /**< See Cohen paper */ + float *update_prob; /**< Propability of speech presence for noise update */ + + float *zeta; /**< Smoothed a priori SNR */ + float Zpeak; + float Zlast; + + float *loudness_weight; /**< Perceptual loudness curve */ + + float *echo_noise; + + float *noise_bands; + float *noise_bands2; + int noise_bandsN; + float *speech_bands; + float *speech_bands2; + int speech_bandsN; + + float *inbuf; /**< Input buffer (overlapped analysis) */ + float *outbuf; /**< Output buffer (for overlap and add) */ + + float speech_prob; + int last_speech; + float loudness; /**< loudness estimate */ + float loudness2; /**< loudness estimate */ + int nb_adapt; /**< Number of frames used for adaptation so far */ + int nb_loudness_adapt; /**< Number of frames used for loudness adaptation so far */ + int consec_noise; /**< Number of consecutive noise frames */ + int nb_preprocess; /**< Number of frames processed so far */ + struct drft_lookup *fft_lookup; /**< Lookup table for the FFT */ + +} SpeexPreprocessState; + +/** Creates a new preprocessing state */ +SpeexPreprocessState *speex_preprocess_state_init(int frame_size, int sampling_rate); + +/** Destroys a denoising state */ +void speex_preprocess_state_destroy(SpeexPreprocessState *st); + +/** Preprocess a frame */ +int speex_preprocess(SpeexPreprocessState *st, spx_int16_t *x, float *echo); + +/** Preprocess a frame */ +void speex_preprocess_estimate_update(SpeexPreprocessState *st, spx_int16_t *x, float *echo); + +/** Used like the ioctl function to control the preprocessor parameters */ +int speex_preprocess_ctl(SpeexPreprocessState *st, int request, void *ptr); + + + +#define SPEEX_PREPROCESS_SET_DENOISE 0 +#define SPEEX_PREPROCESS_GET_DENOISE 1 + +#define SPEEX_PREPROCESS_SET_AGC 2 +#define SPEEX_PREPROCESS_GET_AGC 3 + +#define SPEEX_PREPROCESS_SET_VAD 4 +#define SPEEX_PREPROCESS_GET_VAD 5 + +#define SPEEX_PREPROCESS_SET_AGC_LEVEL 6 +#define SPEEX_PREPROCESS_GET_AGC_LEVEL 7 + +#define SPEEX_PREPROCESS_SET_DEREVERB 8 +#define SPEEX_PREPROCESS_GET_DEREVERB 9 + +#define SPEEX_PREPROCESS_SET_DEREVERB_LEVEL 10 +#define SPEEX_PREPROCESS_GET_DEREVERB_LEVEL 11 + +#define SPEEX_PREPROCESS_SET_DEREVERB_DECAY 12 +#define SPEEX_PREPROCESS_GET_DEREVERB_DECAY 13 + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/mozilla/zap/zmk/speex-1.1.10/include/speex/speex_stereo.h b/mozilla/zap/zmk/speex-1.1.10/include/speex/speex_stereo.h new file mode 100755 index 00000000000..9ed7c17595f --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/include/speex/speex_stereo.h @@ -0,0 +1,78 @@ +/* Copyright (C) 2002 Jean-Marc Valin*/ +/** + @file speex_stereo.h + @brief Describes the handling for intensity stereo +*/ +/* + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 STEREO_H +#define STEREO_H + +#include "speex/speex_types.h" +#include "speex/speex_bits.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** State used for decoding (intensity) stereo information */ +typedef struct SpeexStereoState { + float balance; /**< Left/right balance info */ + float e_ratio; /**< Ratio of energies: E(left+right)/[E(left)+E(right)] */ + float smooth_left; /**< Smoothed left channel gain */ + float smooth_right; /**< Smoothed right channel gain */ + float reserved1; /**< Reserved for future use */ + float reserved2; /**< Reserved for future use */ +} SpeexStereoState; + +/** Initialization value for a stereo state */ +#define SPEEX_STEREO_STATE_INIT {1,.5,1,1} + +/** Transforms a stereo frame into a mono frame and stores intensity stereo info in 'bits' */ +void speex_encode_stereo(float *data, int frame_size, SpeexBits *bits); + +/** Transforms a stereo frame into a mono frame and stores intensity stereo info in 'bits' */ +void speex_encode_stereo_int(spx_int16_t *data, int frame_size, SpeexBits *bits); + +/** Transforms a mono frame into a stereo frame using intensity stereo info */ +void speex_decode_stereo(float *data, int frame_size, SpeexStereoState *stereo); + +/** Transforms a mono frame into a stereo frame using intensity stereo info */ +void speex_decode_stereo_int(spx_int16_t *data, int frame_size, SpeexStereoState *stereo); + +/** Callback handler for intensity stereo info */ +int speex_std_stereo_request_handler(SpeexBits *bits, void *state, void *data); + +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/mozilla/zap/zmk/speex-1.1.10/include/speex/speex_types.h b/mozilla/zap/zmk/speex-1.1.10/include/speex/speex_types.h new file mode 100755 index 00000000000..e981f20d3c1 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/include/speex/speex_types.h @@ -0,0 +1,120 @@ +/* speex_types.h taken from libogg */ +/******************************************************************** + * * + * 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: speex_types.h,v 1.1.2.1 2005-08-16 20:04:29 alex%croczilla.com Exp $ + + ********************************************************************/ +#ifndef _SPEEX_TYPES_H +#define _SPEEX_TYPES_H + +#if defined(_WIN32) + +# if defined(__CYGWIN__) +# include <_G_config.h> + typedef _G_int64_t spx_int64_t; + typedef _G_int32_t spx_int32_t; + typedef _G_uint32_t spx_uint32_t; + typedef _G_int16_t spx_int16_t; + typedef _G_uint16_t spx_uint16_t; +# elif defined(__MINGW32__) + typedef short spx_int16_t; + typedef unsigned short spx_uint16_t; + typedef int spx_int32_t; + typedef unsigned int spx_uint32_t; + typedef long long spx_int64_t; + typedef unsigned long long spx_uint64_t; +# elif defined(__MWERKS__) + typedef long long spx_int64_t; + typedef int spx_int32_t; + typedef unsigned int spx_uint32_t; + typedef short spx_int16_t; + typedef unsigned short spx_uint16_t; +# else + /* MSVC/Borland */ + typedef __int64 spx_int64_t; + typedef __int32 spx_int32_t; + typedef unsigned __int32 spx_uint32_t; + typedef __int16 spx_int16_t; + typedef unsigned __int16 spx_uint16_t; +# endif + +#elif defined(__MACOS__) + +# include + typedef SInt16 spx_int16_t; + typedef UInt16 spx_uint16_t; + typedef SInt32 spx_int32_t; + typedef UInt32 spx_uint32_t; + typedef SInt64 spx_int64_t; + +#elif defined(__MACOSX__) /* MacOS X Framework build */ + +# include + typedef int16_t spx_int16_t; + typedef u_int16_t spx_uint16_t; + typedef int32_t spx_int32_t; + typedef u_int32_t spx_uint32_t; + typedef int64_t spx_int64_t; + +#elif defined(__BEOS__) + + /* Be */ +# include + typedef int16_t spx_int16_t; + typedef u_int16_t spx_uint16_t; + typedef int32_t spx_int32_t; + typedef u_int32_t spx_uint32_t; + typedef int64_t spx_int64_t; + +#elif defined (__EMX__) + + /* OS/2 GCC */ + typedef short spx_int16_t; + typedef unsigned short spx_uint16_t; + typedef int spx_int32_t; + typedef unsigned int spx_uint32_t; + typedef long long spx_int64_t; + +#elif defined (DJGPP) + + /* DJGPP */ + typedef short spx_int16_t; + typedef int spx_int32_t; + typedef unsigned int spx_uint32_t; + typedef long long spx_int64_t; + +#elif defined(R5900) + + /* PS2 EE */ + typedef long spx_int64_t; + typedef int spx_int32_t; + typedef unsigned spx_uint32_t; + typedef short spx_int16_t; + +#elif defined(__SYMBIAN32__) + + /* Symbian GCC */ + typedef signed short spx_int16_t; + typedef unsigned short spx_uint16_t; + typedef signed int spx_int32_t; + typedef unsigned int spx_uint32_t; + typedef long long int spx_int64_t; + +#else + +# include + +#endif + +#endif /* _SPEEX_TYPES_H */ diff --git a/mozilla/zap/zmk/speex-1.1.10/install-sh b/mozilla/zap/zmk/speex-1.1.10/install-sh new file mode 100755 index 00000000000..f55bdc0e84f --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/install-sh @@ -0,0 +1,269 @@ +#!/bin/sh +# +# install - install a program, script, or datafile +# +# This originates from X11R5 (mit/util/scripts/install.sh), which was +# later released in X11R6 (xc/config/util/install.sh) with the +# following copyright and license. +# +# Copyright (C) 1994 X Consortium +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN +# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC- +# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +# +# Except as contained in this notice, the name of the X Consortium shall not +# be used in advertising or otherwise to promote the sale, use or other deal- +# ings in this Software without prior written authorization from the X Consor- +# tium. +# +# +# FSF changes to this file are in the public domain. +# +# Calling this script install-sh is preferred over install.sh, to prevent +# `make' implicit rules from creating a file called install from it +# when there is no Makefile. +# +# This script is compatible with the BSD install script, but was written +# from scratch. It can only install one file at a time, a restriction +# shared with many OS's install programs. + + +# set DOITPROG to echo to test this script + +# Don't use :- since 4.3BSD and earlier shells don't like it. +doit="${DOITPROG-}" + + +# put in absolute paths if you don't have them in your path; or use env. vars. + +mvprog="${MVPROG-mv}" +cpprog="${CPPROG-cp}" +chmodprog="${CHMODPROG-chmod}" +chownprog="${CHOWNPROG-chown}" +chgrpprog="${CHGRPPROG-chgrp}" +stripprog="${STRIPPROG-strip}" +rmprog="${RMPROG-rm}" +mkdirprog="${MKDIRPROG-mkdir}" + +transformbasename="" +transform_arg="" +instcmd="$mvprog" +chmodcmd="$chmodprog 0755" +chowncmd="" +chgrpcmd="" +stripcmd="" +rmcmd="$rmprog -f" +mvcmd="$mvprog" +src="" +dst="" +dir_arg="" + +while [ x"$1" != x ]; do + case $1 in + -c) instcmd="$cpprog" + shift + continue;; + + -d) dir_arg=true + shift + continue;; + + -m) chmodcmd="$chmodprog $2" + shift + shift + continue;; + + -o) chowncmd="$chownprog $2" + shift + shift + continue;; + + -g) chgrpcmd="$chgrpprog $2" + shift + shift + continue;; + + -s) stripcmd="$stripprog" + shift + continue;; + + -t=*) transformarg=`echo $1 | sed 's/-t=//'` + shift + continue;; + + -b=*) transformbasename=`echo $1 | sed 's/-b=//'` + shift + continue;; + + *) if [ x"$src" = x ] + then + src=$1 + else + # this colon is to work around a 386BSD /bin/sh bug + : + dst=$1 + fi + shift + continue;; + esac +done + +if [ x"$src" = x ] +then + echo "install: no input file specified" + exit 1 +else + : +fi + +if [ x"$dir_arg" != x ]; then + dst=$src + src="" + + if [ -d $dst ]; then + instcmd=: + chmodcmd="" + else + instcmd=$mkdirprog + fi +else + +# Waiting for this to be detected by the "$instcmd $src $dsttmp" command +# might cause directories to be created, which would be especially bad +# if $src (and thus $dsttmp) contains '*'. + + if [ -f "$src" ] || [ -d "$src" ] + then + : + else + echo "install: $src does not exist" + exit 1 + fi + + if [ x"$dst" = x ] + then + echo "install: no destination specified" + exit 1 + else + : + fi + +# If destination is a directory, append the input filename; if your system +# does not like double slashes in filenames, you may need to add some logic + + if [ -d $dst ] + then + dst="$dst"/`basename $src` + else + : + fi +fi + +## this sed command emulates the dirname command +dstdir=`echo $dst | sed -e 's,[^/]*$,,;s,/$,,;s,^$,.,'` + +# Make sure that the destination directory exists. +# this part is taken from Noah Friedman's mkinstalldirs script + +# Skip lots of stat calls in the usual case. +if [ ! -d "$dstdir" ]; then +defaultIFS=' + ' +IFS="${IFS-${defaultIFS}}" + +oIFS="${IFS}" +# Some sh's can't handle IFS=/ for some reason. +IFS='%' +set - `echo ${dstdir} | sed -e 's@/@%@g' -e 's@^%@/@'` +IFS="${oIFS}" + +pathcomp='' + +while [ $# -ne 0 ] ; do + pathcomp="${pathcomp}${1}" + shift + + if [ ! -d "${pathcomp}" ] ; + then + $mkdirprog "${pathcomp}" + else + : + fi + + pathcomp="${pathcomp}/" +done +fi + +if [ x"$dir_arg" != x ] +then + $doit $instcmd $dst && + + if [ x"$chowncmd" != x ]; then $doit $chowncmd $dst; else : ; fi && + if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dst; else : ; fi && + if [ x"$stripcmd" != x ]; then $doit $stripcmd $dst; else : ; fi && + if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dst; else : ; fi +else + +# If we're going to rename the final executable, determine the name now. + + if [ x"$transformarg" = x ] + then + dstfile=`basename $dst` + else + dstfile=`basename $dst $transformbasename | + sed $transformarg`$transformbasename + fi + +# don't allow the sed command to completely eliminate the filename + + if [ x"$dstfile" = x ] + then + dstfile=`basename $dst` + else + : + fi + +# Make a temp file name in the proper directory. + + dsttmp=$dstdir/#inst.$$# + +# Move or copy the file name to the temp name + + $doit $instcmd $src $dsttmp && + + trap "rm -f ${dsttmp}" 0 && + +# and set any options; do chmod last to preserve setuid bits + +# If any of these fail, we abort the whole thing. If we want to +# ignore errors from any of these, just make sure not to ignore +# errors from the above "$doit $instcmd $src $dsttmp" command. + + if [ x"$chowncmd" != x ]; then $doit $chowncmd $dsttmp; else :;fi && + if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dsttmp; else :;fi && + if [ x"$stripcmd" != x ]; then $doit $stripcmd $dsttmp; else :;fi && + if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dsttmp; else :;fi && + +# Now rename the file to the real destination. + + $doit $rmcmd -f $dstdir/$dstfile && + $doit $mvcmd $dsttmp $dstdir/$dstfile + +fi && + + +exit 0 diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/Makefile.am b/mozilla/zap/zmk/speex-1.1.10/libspeex/Makefile.am new file mode 100755 index 00000000000..b2b2e8550ef --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/Makefile.am @@ -0,0 +1,86 @@ +# Disable automatic dependency tracking if using other tools than gcc and gmake +#AUTOMAKE_OPTIONS = no-dependencies + + +EXTRA_DIST=testenc.c testenc_wb.c testenc_uwb.c testdenoise.c testecho.c + +INCLUDES = -I$(top_srcdir)/include -I$(top_builddir)/include -I$(top_builddir) @OGG_CFLAGS@ + +lib_LTLIBRARIES = libspeex.la + +# Sources for compilation in the library +libspeex_la_SOURCES = nb_celp.c \ + sb_celp.c \ + lpc.c \ + ltp.c \ + lsp.c \ + quant_lsp.c \ + lsp_tables_nb.c \ + gain_table.c \ + gain_table_lbr.c \ + cb_search.c \ + filters.c \ + bits.c \ + modes.c \ + speex.c \ + vq.c \ + high_lsp_tables.c \ + vbr.c \ + hexc_table.c \ + exc_5_256_table.c \ + exc_5_64_table.c \ + exc_8_128_table.c \ + exc_10_32_table.c \ + exc_10_16_table.c \ + exc_20_32_table.c \ + hexc_10_32_table.c \ + misc.c \ + speex_header.c \ + speex_callbacks.c \ + math_approx.c \ + stereo.c \ + preprocess.c \ + smallft.c \ + lbr_48k_tables.c \ + jitter.c \ + mdf.c + +noinst_HEADERS = lsp.h \ + nb_celp.h \ + lpc.h \ + lpc_bfin.h \ + ltp.h \ + quant_lsp.h \ + cb_search.h \ + filters.h \ + stack_alloc.h \ + vq.h \ + vq_sse.h \ + vq_arm4.h \ + vq_bfin.h \ + modes.h \ + sb_celp.h \ + vbr.h \ + misc.h \ + misc_bfin.h \ + ltp_sse.h \ + ltp_arm4.h \ + ltp_bfin.h \ + filters_sse.h \ + filters_arm4.h \ + filters_bfin.h \ + math_approx.h \ + smallft.h \ + arch.h \ + fixed_arm4.h \ + fixed_arm5e.h \ + fixed_bfin.h \ + fixed_debug.h \ + fixed_generic.h \ + cb_search_sse.h \ + cb_search_arm4.h \ + cb_search_bfin.h + + +libspeex_la_LDFLAGS = -version-info @SPEEX_LT_CURRENT@:@SPEEX_LT_REVISION@:@SPEEX_LT_AGE@ + diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/Makefile.in b/mozilla/zap/zmk/speex-1.1.10/libspeex/Makefile.in new file mode 100644 index 00000000000..0858e58a9ac --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/Makefile.in @@ -0,0 +1,58 @@ +DEPTH = ../../../.. +topsrcdir = @top_srcdir@ +srcdir = @srcdir@ +VPATH = @srcdir@ + +include $(DEPTH)/config/autoconf.mk + + +MODULE = speex +LIBRARY_NAME = moz_speex_v1_1_10 +#LIB_IS_C_ONLY = 1 +FORCE_STATIC_LIB= 1 + +CSRCS = \ + nb_celp.c \ + sb_celp.c \ + lpc.c \ + ltp.c \ + lsp.c \ + quant_lsp.c \ + lsp_tables_nb.c \ + gain_table.c \ + gain_table_lbr.c \ + cb_search.c \ + filters.c \ + bits.c \ + modes.c \ + speex.c \ + vq.c \ + high_lsp_tables.c \ + vbr.c \ + hexc_table.c \ + exc_5_256_table.c \ + exc_5_64_table.c \ + exc_8_128_table.c \ + exc_10_32_table.c \ + exc_10_16_table.c \ + exc_20_32_table.c \ + hexc_10_32_table.c \ + misc.c \ + speex_header.c \ + speex_callbacks.c \ + math_approx.c \ + stereo.c \ + preprocess.c \ + smallft.c \ + lbr_48k_tables.c \ + jitter.c \ + mdf.c \ + $(NULL) + +DEFINES += -Dinline= -Drestrict= + +include $(topsrcdir)/config/rules.mk + +INCLUDES += \ + -I$(srcdir)/../include \ + $(NULL) diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/Makefile.in.speex b/mozilla/zap/zmk/speex-1.1.10/libspeex/Makefile.in.speex new file mode 100755 index 00000000000..643071099f5 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/Makefile.in.speex @@ -0,0 +1,606 @@ +# Makefile.in generated by automake 1.8.5 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004 Free Software Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +# Disable automatic dependency tracking if using other tools than gcc and gmake +#AUTOMAKE_OPTIONS = no-dependencies + + +SOURCES = $(libspeex_la_SOURCES) + +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +top_builddir = .. +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +INSTALL = @INSTALL@ +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +host_triplet = @host@ +subdir = libspeex +DIST_COMMON = $(noinst_HEADERS) $(srcdir)/Makefile.am \ + $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ + $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = +am__installdirs = "$(DESTDIR)$(libdir)" +libLTLIBRARIES_INSTALL = $(INSTALL) +LTLIBRARIES = $(lib_LTLIBRARIES) +libspeex_la_LIBADD = +am_libspeex_la_OBJECTS = nb_celp.lo sb_celp.lo lpc.lo ltp.lo lsp.lo \ + quant_lsp.lo lsp_tables_nb.lo gain_table.lo gain_table_lbr.lo \ + cb_search.lo filters.lo bits.lo modes.lo speex.lo vq.lo \ + high_lsp_tables.lo vbr.lo hexc_table.lo exc_5_256_table.lo \ + exc_5_64_table.lo exc_8_128_table.lo exc_10_32_table.lo \ + exc_10_16_table.lo exc_20_32_table.lo hexc_10_32_table.lo \ + misc.lo speex_header.lo speex_callbacks.lo math_approx.lo \ + stereo.lo preprocess.lo smallft.lo lbr_48k_tables.lo jitter.lo \ + mdf.lo +libspeex_la_OBJECTS = $(am_libspeex_la_OBJECTS) +DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir) +depcomp = $(SHELL) $(top_srcdir)/depcomp +am__depfiles_maybe = depfiles +@AMDEP_TRUE@DEP_FILES = ./$(DEPDIR)/bits.Plo ./$(DEPDIR)/cb_search.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/exc_10_16_table.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/exc_10_32_table.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/exc_20_32_table.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/exc_5_256_table.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/exc_5_64_table.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/exc_8_128_table.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/filters.Plo ./$(DEPDIR)/gain_table.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/gain_table_lbr.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/hexc_10_32_table.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/hexc_table.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/high_lsp_tables.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/jitter.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/lbr_48k_tables.Plo ./$(DEPDIR)/lpc.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/lsp.Plo ./$(DEPDIR)/lsp_tables_nb.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/ltp.Plo ./$(DEPDIR)/math_approx.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/mdf.Plo ./$(DEPDIR)/misc.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/modes.Plo ./$(DEPDIR)/nb_celp.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/preprocess.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/quant_lsp.Plo ./$(DEPDIR)/sb_celp.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/smallft.Plo ./$(DEPDIR)/speex.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/speex_callbacks.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/speex_header.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/stereo.Plo ./$(DEPDIR)/vbr.Plo \ +@AMDEP_TRUE@ ./$(DEPDIR)/vq.Plo +COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ + $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) +LTCOMPILE = $(LIBTOOL) --mode=compile $(CC) $(DEFS) \ + $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ + $(AM_CFLAGS) $(CFLAGS) +CCLD = $(CC) +LINK = $(LIBTOOL) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ + $(AM_LDFLAGS) $(LDFLAGS) -o $@ +SOURCES = $(libspeex_la_SOURCES) +DIST_SOURCES = $(libspeex_la_SOURCES) +HEADERS = $(noinst_HEADERS) +ETAGS = etags +CTAGS = ctags +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +AMDEP_FALSE = @AMDEP_FALSE@ +AMDEP_TRUE = @AMDEP_TRUE@ +AMTAR = @AMTAR@ +AR = @AR@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CXX = @CXX@ +CXXCPP = @CXXCPP@ +CXXDEPMODE = @CXXDEPMODE@ +CXXFLAGS = @CXXFLAGS@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +ECHO = @ECHO@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +F77 = @F77@ +FFLAGS = @FFLAGS@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +LDFLAGS = @LDFLAGS@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +MAINT = @MAINT@ +MAINTAINER_MODE_FALSE = @MAINTAINER_MODE_FALSE@ +MAINTAINER_MODE_TRUE = @MAINTAINER_MODE_TRUE@ +MAKEINFO = @MAKEINFO@ +OBJEXT = @OBJEXT@ +OGG_CFLAGS = @OGG_CFLAGS@ +OGG_LIBS = @OGG_LIBS@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +RANLIB = @RANLIB@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +SIZE16 = @SIZE16@ +SIZE32 = @SIZE32@ +SPEEX_LT_AGE = @SPEEX_LT_AGE@ +SPEEX_LT_CURRENT = @SPEEX_LT_CURRENT@ +SPEEX_LT_REVISION = @SPEEX_LT_REVISION@ +SPEEX_VERSION = @SPEEX_VERSION@ +STRIP = @STRIP@ +VERSION = @VERSION@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_CXX = @ac_ct_CXX@ +ac_ct_F77 = @ac_ct_F77@ +ac_ct_RANLIB = @ac_ct_RANLIB@ +ac_ct_STRIP = @ac_ct_STRIP@ +am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ +am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ +am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ +am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +datadir = @datadir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +src = @src@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +EXTRA_DIST = testenc.c testenc_wb.c testenc_uwb.c testdenoise.c testecho.c +INCLUDES = -I$(top_srcdir)/include -I$(top_builddir)/include -I$(top_builddir) @OGG_CFLAGS@ +lib_LTLIBRARIES = libspeex.la + +# Sources for compilation in the library +libspeex_la_SOURCES = nb_celp.c \ + sb_celp.c \ + lpc.c \ + ltp.c \ + lsp.c \ + quant_lsp.c \ + lsp_tables_nb.c \ + gain_table.c \ + gain_table_lbr.c \ + cb_search.c \ + filters.c \ + bits.c \ + modes.c \ + speex.c \ + vq.c \ + high_lsp_tables.c \ + vbr.c \ + hexc_table.c \ + exc_5_256_table.c \ + exc_5_64_table.c \ + exc_8_128_table.c \ + exc_10_32_table.c \ + exc_10_16_table.c \ + exc_20_32_table.c \ + hexc_10_32_table.c \ + misc.c \ + speex_header.c \ + speex_callbacks.c \ + math_approx.c \ + stereo.c \ + preprocess.c \ + smallft.c \ + lbr_48k_tables.c \ + jitter.c \ + mdf.c + +noinst_HEADERS = lsp.h \ + nb_celp.h \ + lpc.h \ + lpc_bfin.h \ + ltp.h \ + quant_lsp.h \ + cb_search.h \ + filters.h \ + stack_alloc.h \ + vq.h \ + vq_sse.h \ + vq_arm4.h \ + vq_bfin.h \ + modes.h \ + sb_celp.h \ + vbr.h \ + misc.h \ + misc_bfin.h \ + ltp_sse.h \ + ltp_arm4.h \ + ltp_bfin.h \ + filters_sse.h \ + filters_arm4.h \ + filters_bfin.h \ + math_approx.h \ + smallft.h \ + arch.h \ + fixed_arm4.h \ + fixed_arm5e.h \ + fixed_bfin.h \ + fixed_debug.h \ + fixed_generic.h \ + cb_search_sse.h \ + cb_search_arm4.h \ + cb_search_bfin.h + +libspeex_la_LDFLAGS = -version-info @SPEEX_LT_CURRENT@:@SPEEX_LT_REVISION@:@SPEEX_LT_AGE@ +all: all-am + +.SUFFIXES: +.SUFFIXES: .c .lo .o .obj +$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ + && exit 0; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu libspeex/Makefile'; \ + cd $(top_srcdir) && \ + $(AUTOMAKE) --gnu libspeex/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +install-libLTLIBRARIES: $(lib_LTLIBRARIES) + @$(NORMAL_INSTALL) + test -z "$(libdir)" || $(mkdir_p) "$(DESTDIR)$(libdir)" + @list='$(lib_LTLIBRARIES)'; for p in $$list; do \ + if test -f $$p; then \ + f="`echo $$p | sed -e 's|^.*/||'`"; \ + echo " $(LIBTOOL) --mode=install $(libLTLIBRARIES_INSTALL) $(INSTALL_STRIP_FLAG) '$$p' '$(DESTDIR)$(libdir)/$$f'"; \ + $(LIBTOOL) --mode=install $(libLTLIBRARIES_INSTALL) $(INSTALL_STRIP_FLAG) "$$p" "$(DESTDIR)$(libdir)/$$f"; \ + else :; fi; \ + done + +uninstall-libLTLIBRARIES: + @$(NORMAL_UNINSTALL) + @list='$(lib_LTLIBRARIES)'; for p in $$list; do \ + p="`echo $$p | sed -e 's|^.*/||'`"; \ + echo " $(LIBTOOL) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$p'"; \ + $(LIBTOOL) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$p"; \ + done + +clean-libLTLIBRARIES: + -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES) + @list='$(lib_LTLIBRARIES)'; for p in $$list; do \ + dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \ + test "$$dir" != "$$p" || dir=.; \ + echo "rm -f \"$${dir}/so_locations\""; \ + rm -f "$${dir}/so_locations"; \ + done +libspeex.la: $(libspeex_la_OBJECTS) $(libspeex_la_DEPENDENCIES) + $(LINK) -rpath $(libdir) $(libspeex_la_LDFLAGS) $(libspeex_la_OBJECTS) $(libspeex_la_LIBADD) $(LIBS) + +mostlyclean-compile: + -rm -f *.$(OBJEXT) + +distclean-compile: + -rm -f *.tab.c + +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/bits.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/cb_search.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/exc_10_16_table.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/exc_10_32_table.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/exc_20_32_table.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/exc_5_256_table.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/exc_5_64_table.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/exc_8_128_table.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/filters.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gain_table.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gain_table_lbr.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/hexc_10_32_table.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/hexc_table.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/high_lsp_tables.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/jitter.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/lbr_48k_tables.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/lpc.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/lsp.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/lsp_tables_nb.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ltp.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/math_approx.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/mdf.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/misc.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/modes.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/nb_celp.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/preprocess.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/quant_lsp.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sb_celp.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/smallft.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/speex.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/speex_callbacks.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/speex_header.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/stereo.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/vbr.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/vq.Plo@am__quote@ + +.c.o: +@am__fastdepCC_TRUE@ if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ +@am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi +@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ depfile='$(DEPDIR)/$*.Po' tmpdepfile='$(DEPDIR)/$*.TPo' @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(COMPILE) -c $< + +.c.obj: +@am__fastdepCC_TRUE@ if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ `$(CYGPATH_W) '$<'`; \ +@am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi +@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ depfile='$(DEPDIR)/$*.Po' tmpdepfile='$(DEPDIR)/$*.TPo' @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(COMPILE) -c `$(CYGPATH_W) '$<'` + +.c.lo: +@am__fastdepCC_TRUE@ if $(LTCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ +@am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Plo"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi +@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ depfile='$(DEPDIR)/$*.Plo' tmpdepfile='$(DEPDIR)/$*.TPlo' @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(LTCOMPILE) -c -o $@ $< + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +distclean-libtool: + -rm -f libtool +uninstall-info-am: + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + tags=; \ + here=`pwd`; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$tags $$unique; \ + fi +ctags: CTAGS +CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + tags=; \ + here=`pwd`; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + test -z "$(CTAGS_ARGS)$$tags$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$tags $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && cd $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) $$here + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ + list='$(DISTFILES)'; for file in $$list; do \ + case $$file in \ + $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ + $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ + esac; \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test "$$dir" != "$$file" && test "$$dir" != "."; then \ + dir="/$$dir"; \ + $(mkdir_p) "$(distdir)$$dir"; \ + else \ + dir=''; \ + fi; \ + if test -d $$d/$$file; then \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + fi; \ + cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + else \ + test -f $(distdir)/$$file \ + || cp -p $$d/$$file $(distdir)/$$file \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile $(LTLIBRARIES) $(HEADERS) +installdirs: + for dir in "$(DESTDIR)$(libdir)"; do \ + test -z "$$dir" || $(mkdir_p) "$$dir"; \ + done +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + `test -z '$(STRIP)' || \ + echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -rm -f $(CONFIG_CLEAN_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libLTLIBRARIES clean-libtool \ + mostlyclean-am + +distclean: distclean-am + -rm -rf ./$(DEPDIR) + -rm -f Makefile +distclean-am: clean-am distclean-compile distclean-generic \ + distclean-libtool distclean-tags + +dvi: dvi-am + +dvi-am: + +html: html-am + +info: info-am + +info-am: + +install-data-am: + +install-exec-am: install-libLTLIBRARIES + +install-info: install-info-am + +install-man: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -rf ./$(DEPDIR) + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-compile mostlyclean-generic \ + mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-info-am uninstall-libLTLIBRARIES + +.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ + clean-libLTLIBRARIES clean-libtool ctags distclean \ + distclean-compile distclean-generic distclean-libtool \ + distclean-tags distdir dvi dvi-am html html-am info info-am \ + install install-am install-data install-data-am install-exec \ + install-exec-am install-info install-info-am \ + install-libLTLIBRARIES install-man install-strip installcheck \ + installcheck-am installdirs maintainer-clean \ + maintainer-clean-generic mostlyclean mostlyclean-compile \ + mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ + tags uninstall uninstall-am uninstall-info-am \ + uninstall-libLTLIBRARIES + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/arch.h b/mozilla/zap/zmk/speex-1.1.10/libspeex/arch.h new file mode 100755 index 00000000000..c606840e4d9 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/arch.h @@ -0,0 +1,187 @@ +/* Copyright (C) 2003 Jean-Marc Valin */ +/** + @file arch.h + @brief Various architecture definitions Speex +*/ +/* + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 ARCH_H +#define ARCH_H + +#include "speex/speex_types.h" + +#define ABS(x) ((x) < 0 ? (-(x)) : (x)) +#define ABS16(x) ((x) < 0 ? (-(x)) : (x)) +#define MAX16(a,b) ((a) > (b) ? (a) : (b)) +#define ABS32(x) ((x) < 0 ? (-(x)) : (x)) + +#ifdef FIXED_POINT + +typedef spx_int16_t spx_word16_t; +typedef spx_int32_t spx_word32_t; +#ifdef _MSC_VER +typedef __int64 spx_word64_t; +#else +typedef long long spx_word64_t; +#endif +typedef spx_word32_t spx_mem_t; +typedef spx_word16_t spx_coef_t; +typedef spx_word16_t spx_lsp_t; +typedef spx_word32_t spx_sig_t; + +#define Q15ONE 32767 + +#define LPC_SCALING 8192 +#define SIG_SCALING 16384 +#define LSP_SCALING 8192. +#define GAMMA_SCALING 32768. +#define GAIN_SCALING 64 +#define GAIN_SCALING_1 0.015625 + +#define LPC_SHIFT 13 +#define LSP_SHIFT 13 +#define SIG_SHIFT 14 + +#define VERY_SMALL 0 +#define VERY_LARGE32 ((spx_word32_t)2147483647) +#define VERY_LARGE16 ((spx_word16_t)32767) + + +#ifdef FIXED_DEBUG +#include "fixed_debug.h" +#else + +#include "fixed_generic.h" + +#ifdef ARM5E_ASM +#include "fixed_arm5e.h" +#elif defined (ARM4_ASM) +#include "fixed_arm4.h" +#elif defined (ARM5E_ASM) +#include "fixed_arm5e.h" +#elif defined (BFIN_ASM) +#include "fixed_bfin.h" +#endif + +#endif + + +#else + +typedef float spx_mem_t; +typedef float spx_coef_t; +typedef float spx_lsp_t; +typedef float spx_sig_t; +typedef float spx_word16_t; +typedef float spx_word32_t; +typedef float spx_word64_t; + +#define Q15ONE 1.0f +#define LPC_SCALING 1.f +#define SIG_SCALING 1.f +#define LSP_SCALING 1.f +#define GAMMA_SCALING 1.f +#define GAIN_SCALING 1.f +#define GAIN_SCALING_1 1.f + +#define LPC_SHIFT 0 +#define LSP_SHIFT 0 +#define SIG_SHIFT 0 + +#define VERY_SMALL 1e-15f +#define VERY_LARGE32 1e15f +#define VERY_LARGE16 1e15f + +#define NEG16(x) (-(x)) +#define NEG32(x) (-(x)) +#define EXTRACT16(x) (x) +#define EXTEND32(x) (x) +#define SHR16(a,shift) (a) +#define SHL16(a,shift) (a) +#define SHR32(a,shift) (a) +#define SHL32(a,shift) (a) +#define PSHR16(a,shift) (a) +#define PSHR32(a,shift) (a) +#define SATURATE16(x,a) (x) +#define SATURATE32(x,a) (x) + +#define PSHR(a,shift) (a) +#define SHR(a,shift) (a) +#define SHL(a,shift) (a) +#define SATURATE(x,a) (x) + +#define ADD16(a,b) ((a)+(b)) +#define SUB16(a,b) ((a)-(b)) +#define ADD32(a,b) ((a)+(b)) +#define SUB32(a,b) ((a)-(b)) +#define ADD64(a,b) ((a)+(b)) +#define MULT16_16_16(a,b) ((a)*(b)) +#define MULT16_16(a,b) ((spx_word32_t)(a)*(spx_word32_t)(b)) +#define MAC16_16(c,a,b) ((c)+(spx_word32_t)(a)*(spx_word32_t)(b)) + +#define MULT16_32_Q11(a,b) ((a)*(b)) +#define MULT16_32_Q13(a,b) ((a)*(b)) +#define MULT16_32_Q14(a,b) ((a)*(b)) +#define MULT16_32_Q15(a,b) ((a)*(b)) + +#define MAC16_32_Q11(c,a,b) ((c)+(a)*(b)) +#define MAC16_32_Q15(c,a,b) ((c)+(a)*(b)) + +#define MAC16_16_Q11(c,a,b) ((c)+(a)*(b)) +#define MAC16_16_Q13(c,a,b) ((c)+(a)*(b)) +#define MULT16_16_Q11_32(a,b) ((a)*(b)) +#define MULT16_16_Q13(a,b) ((a)*(b)) +#define MULT16_16_Q14(a,b) ((a)*(b)) +#define MULT16_16_Q15(a,b) ((a)*(b)) +#define MULT16_16_P15(a,b) ((a)*(b)) + +#define DIV32_16(a,b) ((a)/(b)) +#define DIV32(a,b) ((a)/(b)) + + +#endif + + +#ifdef CONFIG_TI_C55X + +/* 2 on TI C5x DSP */ +#define BYTES_PER_CHAR 2 +#define BITS_PER_CHAR 16 +#define LOG2_BITS_PER_CHAR 4 + +#else + +#define BYTES_PER_CHAR 1 +#define BITS_PER_CHAR 8 +#define LOG2_BITS_PER_CHAR 3 + +#endif + +#endif diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/bits.c b/mozilla/zap/zmk/speex-1.1.10/libspeex/bits.c new file mode 100755 index 00000000000..e749690a8f9 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/bits.c @@ -0,0 +1,357 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: speex_bits.c + + Handles bit packing/unpacking + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 +#include "misc.h" + +/** Maximum size of the bit-stream (for fixed-size allocation) */ +#define MAX_BYTES_PER_FRAME (2000/BYTES_PER_CHAR) + +void speex_bits_init(SpeexBits *bits) +{ + bits->chars = (char*)speex_alloc(MAX_BYTES_PER_FRAME); + if (!bits->chars) + return; + + bits->buf_size = MAX_BYTES_PER_FRAME; + + bits->owner=1; + + speex_bits_reset(bits); +} + +void speex_bits_init_buffer(SpeexBits *bits, void *buff, int buf_size) +{ + bits->chars = (char*)buff; + bits->buf_size = buf_size; + + bits->owner=0; + + speex_bits_reset(bits); +} + +void speex_bits_destroy(SpeexBits *bits) +{ + if (bits->owner) + speex_free(bits->chars); + /* Will do something once the allocation is dynamic */ +} + +void speex_bits_reset(SpeexBits *bits) +{ + bits->chars[0]=0; + bits->nbBits=0; + bits->charPtr=0; + bits->bitPtr=0; + bits->overflow=0; +} + +void speex_bits_rewind(SpeexBits *bits) +{ + bits->charPtr=0; + bits->bitPtr=0; + bits->overflow=0; +} + +void speex_bits_read_from(SpeexBits *bits, char *chars, int len) +{ + int i; + if (len > bits->buf_size) + { + speex_warning_int("Packet is larger than allocated buffer: ", len); + if (bits->owner) + { + char *tmp = (char*)speex_realloc(bits->chars, len); + if (tmp) + { + bits->buf_size=len; + bits->chars=tmp; + } else { + len=bits->buf_size; + speex_warning("Could not resize input buffer: truncating input"); + } + } else { + speex_warning("Do not own input buffer: truncating input"); + len=bits->buf_size; + } + } + for (i=0;ichars[i]=chars[i]; + bits->nbBits=len<<3; + bits->charPtr=0; + bits->bitPtr=0; + bits->overflow=0; +} + +static void speex_bits_flush(SpeexBits *bits) +{ + int i; + int nchars = ((bits->nbBits+BITS_PER_CHAR-1)>>LOG2_BITS_PER_CHAR); + if (bits->charPtr>0) + { + for (i=bits->charPtr;ichars[i-bits->charPtr]=bits->chars[i]; + } + bits->nbBits -= bits->charPtr<charPtr=0; +} + +void speex_bits_read_whole_bytes(SpeexBits *bits, char *chars, int nbytes) +{ + int i,pos; + int nchars = nbytes/BYTES_PER_CHAR; + + if (((bits->nbBits+BITS_PER_CHAR-1)>>LOG2_BITS_PER_CHAR)+nchars > bits->buf_size) + { + /* Packet is larger than allocated buffer */ + if (bits->owner) + { + char *tmp = (char*)speex_realloc(bits->chars, (bits->nbBits>>LOG2_BITS_PER_CHAR)+nchars+1); + if (tmp) + { + bits->buf_size=(bits->nbBits>>LOG2_BITS_PER_CHAR)+nchars+1; + bits->chars=tmp; + } else { + nchars=bits->buf_size-(bits->nbBits>>LOG2_BITS_PER_CHAR)-1; + speex_warning("Could not resize input buffer: truncating input"); + } + } else { + speex_warning("Do not own input buffer: truncating input"); + nchars=bits->buf_size; + } + } + + speex_bits_flush(bits); + pos=bits->nbBits>>LOG2_BITS_PER_CHAR; + for (i=0;ichars[pos+i]=chars[i]; + bits->nbBits+=nchars<bitPtr; + charPtr=bits->charPtr; + nbBits=bits->nbBits; + speex_bits_insert_terminator(bits); + bits->bitPtr=bitPtr; + bits->charPtr=charPtr; + bits->nbBits=nbBits; + + if (max_nchars > ((bits->nbBits+BITS_PER_CHAR-1)>>LOG2_BITS_PER_CHAR)) + max_nchars = ((bits->nbBits+BITS_PER_CHAR-1)>>LOG2_BITS_PER_CHAR); +#if BYTES_PER_CHAR==1 +#define HTOLS(A) (A) +#else +#define HTOLS(A) ((((A) >> 8)&0xff)|(((A) & 0xff)<<8)) +#endif + for (i=0;ichars[i]); + return max_nchars*BYTES_PER_CHAR; +} + +int speex_bits_write_whole_bytes(SpeexBits *bits, char *chars, int max_nbytes) +{ + int max_nchars = max_nbytes/BYTES_PER_CHAR; + int i; + if (max_nchars > ((bits->nbBits)>>LOG2_BITS_PER_CHAR)) + max_nchars = ((bits->nbBits)>>LOG2_BITS_PER_CHAR); + for (i=0;ichars[i]; + + if (bits->bitPtr>0) + bits->chars[0]=bits->chars[max_nchars]; + else + bits->chars[0]=0; + for (i=1;i<((bits->nbBits)>>LOG2_BITS_PER_CHAR)+1;i++) + bits->chars[i]=0; + bits->charPtr=0; + bits->nbBits &= (BITS_PER_CHAR-1); + return max_nchars*BYTES_PER_CHAR; +} + +void speex_bits_pack(SpeexBits *bits, int data, int nbBits) +{ + unsigned int d=data; + + if (bits->charPtr+((nbBits+bits->bitPtr)>>LOG2_BITS_PER_CHAR) >= bits->buf_size) + { + speex_warning("Buffer too small to pack bits"); + if (bits->owner) + { + int new_nchars = ((bits->buf_size+5)*3)>>1; + char *tmp = (char*)speex_realloc(bits->chars, new_nchars); + if (tmp) + { + speex_memset_bytes(tmp, 0, new_nchars); + bits->buf_size=new_nchars; + bits->chars=tmp; + } else { + speex_warning("Could not resize input buffer: not packing"); + return; + } + } else { + speex_warning("Do not own input buffer: not packing"); + return; + } + } + + while(nbBits) + { + int bit; + bit = (d>>(nbBits-1))&1; + bits->chars[bits->charPtr] |= bit<<(BITS_PER_CHAR-1-bits->bitPtr); + bits->bitPtr++; + + if (bits->bitPtr==BITS_PER_CHAR) + { + bits->bitPtr=0; + bits->charPtr++; + bits->chars[bits->charPtr] = 0; + } + bits->nbBits++; + nbBits--; + } +} + +int speex_bits_unpack_signed(SpeexBits *bits, int nbBits) +{ + unsigned int d=speex_bits_unpack_unsigned(bits,nbBits); + /* If number is negative */ + if (d>>(nbBits-1)) + { + d |= (-1)<charPtr<bitPtr+nbBits>bits->nbBits) + bits->overflow=1; + if (bits->overflow) + return 0; + while(nbBits) + { + d<<=1; + d |= (bits->chars[bits->charPtr]>>(BITS_PER_CHAR-1 - bits->bitPtr))&1; + bits->bitPtr++; + if (bits->bitPtr==BITS_PER_CHAR) + { + bits->bitPtr=0; + bits->charPtr++; + } + nbBits--; + } + return d; +} + +unsigned int speex_bits_peek_unsigned(SpeexBits *bits, int nbBits) +{ + unsigned int d=0; + int bitPtr, charPtr; + char *chars; + + if ((bits->charPtr<bitPtr+nbBits>bits->nbBits) + bits->overflow=1; + if (bits->overflow) + return 0; + + bitPtr=bits->bitPtr; + charPtr=bits->charPtr; + chars = bits->chars; + while(nbBits) + { + d<<=1; + d |= (chars[charPtr]>>(BITS_PER_CHAR-1 - bitPtr))&1; + bitPtr++; + if (bitPtr==BITS_PER_CHAR) + { + bitPtr=0; + charPtr++; + } + nbBits--; + } + return d; +} + +int speex_bits_peek(SpeexBits *bits) +{ + if ((bits->charPtr<bitPtr+1>bits->nbBits) + bits->overflow=1; + if (bits->overflow) + return 0; + return (bits->chars[bits->charPtr]>>(BITS_PER_CHAR-1 - bits->bitPtr))&1; +} + +void speex_bits_advance(SpeexBits *bits, int n) +{ + if (((bits->charPtr<bitPtr+n>bits->nbBits) || bits->overflow){ + bits->overflow=1; + return; + } + bits->charPtr += (bits->bitPtr+n) >> LOG2_BITS_PER_CHAR; /* divide by BITS_PER_CHAR */ + bits->bitPtr = (bits->bitPtr+n) & (BITS_PER_CHAR-1); /* modulo by BITS_PER_CHAR */ +} + +int speex_bits_remaining(SpeexBits *bits) +{ + if (bits->overflow) + return -1; + else + return bits->nbBits-((bits->charPtr<bitPtr); +} + +int speex_bits_nbytes(SpeexBits *bits) +{ + return ((bits->nbBits+BITS_PER_CHAR-1)>>LOG2_BITS_PER_CHAR); +} + +void speex_bits_insert_terminator(SpeexBits *bits) +{ + if (bits->bitPtrbitPtr10) + N=10; + if (N<1) + N=1; + + params = (const split_cb_params *) par; + subvect_size = params->subvect_size; + nb_subvect = params->nb_subvect; + shape_cb_size = 1<shape_bits; + shape_cb = params->shape_cb; + have_sign = params->have_sign; + ALLOC(resp, shape_cb_size*subvect_size, spx_word16_t); +#ifdef _USE_SSE + ALLOC(resp2, (shape_cb_size*subvect_size)>>2, __m128); + ALLOC(E, shape_cb_size>>2, __m128); +#else + resp2 = resp; + ALLOC(E, shape_cb_size, spx_word32_t); +#endif + ALLOC(t, nsf, spx_word16_t); + ALLOC(e, nsf, spx_sig_t); + + /* FIXME: make that adaptive? */ + for (i=0;ishape_bits+have_sign); + + { + int rind; + spx_word16_t *res; + spx_word16_t sign=1; + rind = best_index; + if (rind>=shape_cb_size) + { + sign=-1; + rind-=shape_cb_size; + } + res = resp+rind*subvect_size; + if (sign>0) + for (m=0;m=shape_cb_size) + { + sign=-1; + rind-=shape_cb_size; + } + + q=subvect_size-m; +#ifdef FIXED_POINT + g=sign*shape_cb[rind*subvect_size+m]; + target_update(t+subvect_size*(i+1), g, r+q, nsf-subvect_size*(i+1)); +#else + g=sign*0.03125*shape_cb[rind*subvect_size+m]; + /*FIXME: I think that one too can be replaced by target_update */ + for (n=subvect_size*(i+1);n10) + N=10; + if (N<1) + N=1; + + if (N==1) + { + split_cb_search_shape_sign_N1(target,ak,awk1,awk2,par,p,nsf,exc,r,bits,stack,complexity,update_target); + return; + } + ALLOC(ot2, N, spx_word16_t*); + ALLOC(nt2, N, spx_word16_t*); + ALLOC(oind, N, int*); + ALLOC(nind, N, int*); + + params = (const split_cb_params *) par; + subvect_size = params->subvect_size; + nb_subvect = params->nb_subvect; + shape_cb_size = 1<shape_bits; + shape_cb = params->shape_cb; + have_sign = params->have_sign; + ALLOC(resp, shape_cb_size*subvect_size, spx_word16_t); +#ifdef _USE_SSE + ALLOC(resp2, (shape_cb_size*subvect_size)>>2, __m128); + ALLOC(E, shape_cb_size>>2, __m128); +#else + resp2 = resp; + ALLOC(E, shape_cb_size, spx_word32_t); +#endif + ALLOC(t, nsf, spx_word16_t); + ALLOC(e, nsf, spx_sig_t); + ALLOC(r2, nsf, spx_sig_t); + ALLOC(ind, nb_subvect, int); + + ALLOC(tmp, 2*N*nsf, spx_word16_t); + for (i=0;im;n--) + { + ndist[n] = ndist[n-1]; + best_nind[n] = best_nind[n-1]; + best_ntarget[n] = best_ntarget[n-1]; + } + ndist[m] = err; + best_nind[n] = best_index[k]; + best_ntarget[n] = j; + break; + } + } + } + } + if (i==0) + break; + } + for (j=0;j=shape_cb_size) + { + sign=-1; + rind-=shape_cb_size; + } + + q=subvect_size-m; +#ifdef FIXED_POINT + g=sign*shape_cb[rind*subvect_size+m]; + target_update(nt[j]+subvect_size*(i+1), g, r+q, nsf-subvect_size*(i+1)); +#else + g=sign*0.03125*shape_cb[rind*subvect_size+m]; + /*FIXME: I think that one too can be replaced by target_update */ + for (n=subvect_size*(i+1);nshape_bits+have_sign); + } + + /* Put everything back together */ + for (i=0;i=shape_cb_size) + { + sign=-1; + rind-=shape_cb_size; + } +#ifdef FIXED_POINT + if (sign==1) + { + for (j=0;jsubvect_size; + nb_subvect = params->nb_subvect; + shape_cb_size = 1<shape_bits; + shape_cb = params->shape_cb; + have_sign = params->have_sign; + + ALLOC(ind, nb_subvect, int); + ALLOC(signs, nb_subvect, int); + + /* Decode codewords and gains */ + for (i=0;ishape_bits); + } + /* Compute decoded excitation */ + for (i=0;i +#include "misc.h" + +typedef struct split_cb_params { + int subvect_size; + int nb_subvect; + const signed char *shape_cb; + int shape_bits; + int have_sign; +} split_cb_params; + + +void split_cb_search_shape_sign( +spx_sig_t target[], /* target vector */ +spx_coef_t ak[], /* LPCs for this subframe */ +spx_coef_t awk1[], /* Weighted LPCs for this subframe */ +spx_coef_t awk2[], /* Weighted LPCs for this subframe */ +const void *par, /* Codebook/search parameters*/ +int p, /* number of LPC coeffs */ +int nsf, /* number of samples in subframe */ +spx_sig_t *exc, +spx_word16_t *r, +SpeexBits *bits, +char *stack, +int complexity, +int update_target +); + +void split_cb_shape_sign_unquant( +spx_sig_t *exc, +const void *par, /* non-overlapping codebook */ +int nsf, /* number of samples in subframe */ +SpeexBits *bits, +char *stack +); + + +void noise_codebook_quant( +spx_sig_t target[], /* target vector */ +spx_coef_t ak[], /* LPCs for this subframe */ +spx_coef_t awk1[], /* Weighted LPCs for this subframe */ +spx_coef_t awk2[], /* Weighted LPCs for this subframe */ +const void *par, /* Codebook/search parameters*/ +int p, /* number of LPC coeffs */ +int nsf, /* number of samples in subframe */ +spx_sig_t *exc, +spx_word16_t *r, +SpeexBits *bits, +char *stack, +int complexity, +int update_target +); + + +void noise_codebook_unquant( +spx_sig_t *exc, +const void *par, /* non-overlapping codebook */ +int nsf, /* number of samples in subframe */ +SpeexBits *bits, +char *stack +); + +#endif diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/cb_search_arm4.h b/mozilla/zap/zmk/speex-1.1.10/libspeex/cb_search_arm4.h new file mode 100755 index 00000000000..c2d306bf3fc --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/cb_search_arm4.h @@ -0,0 +1,130 @@ +/* Copyright (C) 2004 Jean-Marc Valin + File: cb_search.c (ARM4 version) + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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. +*/ + +#define OVERRIDE_COMPUTE_WEIGHTED_CODEBOOK +static void compute_weighted_codebook(const signed char *shape_cb, const spx_sig_t *r, spx_word16_t *resp, spx_word16_t *resp2, spx_word32_t *E, int shape_cb_size, int subvect_size, char *stack) +{ + int i, j, k; + //const signed char *shape; + for (i=0;i>>= 11;\n\t" + "A1 += R0.L*R0.L (IS);\n\t" + "W[P3++] = R0;\n\t" + "P0 += 1;\n\t" + "P2 += 2;\n\t" + "LOOP_END outter%=;\n\t" + "P4 = %4;\n\t" + "R1 = A1;\n\t" + "[P4] = R1;\n\t" + : + : "m" (subvect_size), "m" (shape_cb), "m" (r), "m" (resp), "m" (E) + : "A0", "P0", "P1", "P2", "P3", "P4", "R0", "R1", "R2", "I0", "I1", "L0", "L1", "A0", "A1", "memory" + ); + shape_cb += subvect_size; + resp += subvect_size; + E++; + } +} + +#define OVERRIDE_TARGET_UPDATE +static inline void target_update(spx_word16_t *t, spx_word16_t g, spx_word16_t *r, int len) +{ + __asm__ __volatile__ + ( + "I0 = %0;\n\t" + "I1 = %1;\n\t" + "L0 = 0;\n\t" + "L1 = 0;\n\t" + "LOOP tupdate%= LC0 = %3;\n\t" + "LOOP_BEGIN tupdate%=;\n\t" + "R0.L = W[I0] || R1.L = W[I1++];\n\t" + "R1 = (A1 = R1.L*%2.L) (IS);\n\t" + "R1 >>>= 11;\n\t" + "R0.L = R0.L - R1.L;\n\t" + "W[I0++] = R0.L;\n\t" + "LOOP_END tupdate%=;\n\t" + : + : "a" (t), "a" (r), "d" (g), "a" (len) + : "R0", "R1", "A1", "I0", "I1", "L0", "L1" + ); +} + diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/cb_search_sse.h b/mozilla/zap/zmk/speex-1.1.10/libspeex/cb_search_sse.h new file mode 100755 index 00000000000..24ab2dea185 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/cb_search_sse.h @@ -0,0 +1,81 @@ +/* Copyright (C) 2004 Jean-Marc Valin + File: cb_search.c (SSE version) + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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. +*/ + +#include + +static inline void _spx_mm_getr_ps (__m128 U, float *__Z, float *__Y, float *__X, float *__W) +{ + union { + float __a[4]; + __m128 __v; + } __u; + + __u.__v = U; + + *__Z = __u.__a[0]; + *__Y = __u.__a[1]; + *__X = __u.__a[2]; + *__W = __u.__a[3]; + +} + +#define OVERRIDE_COMPUTE_WEIGHTED_CODEBOOK +static void compute_weighted_codebook(const signed char *shape_cb, const spx_sig_t *_r, float *resp, __m128 *resp2, __m128 *E, int shape_cb_size, int subvect_size, char *stack) +{ + int i, j, k; + __m128 resj, EE; + VARDECL(__m128 *r); + VARDECL(__m128 *shape); + ALLOC(r, subvect_size, __m128); + ALLOC(shape, subvect_size, __m128); + for(j=0;j>2] = EE; + } +} diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/exc_10_16_table.c b/mozilla/zap/zmk/speex-1.1.10/libspeex/exc_10_16_table.c new file mode 100755 index 00000000000..809522a2fad --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/exc_10_16_table.c @@ -0,0 +1,50 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: exc_10_16_table.c + Codebook for excitation in narrowband CELP mode (3200 bps) + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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. +*/ + + +const signed char exc_10_16_table[160] = { +22,39,14,44,11,35,-2,23,-4,6, +46,-28,13,-27,-23,12,4,20,-5,9, +37,-18,-23,23,0,9,-6,-20,4,-1, +-17,-5,-4,17,0,1,9,-2,1,2, +2,-12,8,-25,39,15,9,16,-55,-11, +9,11,5,10,-2,-60,8,13,-6,11, +-16,27,-47,-12,11,1,16,-7,9,-3, +-29,9,-14,25,-19,34,36,12,40,-10, +-3,-24,-14,-37,-21,-35,-2,-36,3,-6, +67,28,6,-17,-3,-12,-16,-15,-17,-7, +-59,-36,-13,1,7,1,2,10,2,11, +13,10,8,-2,7,3,5,4,2,2, +-3,-8,4,-5,6,7,-42,15,35,-2, +-46,38,28,-20,-9,1,7,-3,0,-2, +0,0,0,0,0,0,0,0,0,0, +-15,-28,52,32,5,-5,-17,-20,-10,-1}; diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/exc_10_32_table.c b/mozilla/zap/zmk/speex-1.1.10/libspeex/exc_10_32_table.c new file mode 100755 index 00000000000..900f2f1a02a --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/exc_10_32_table.c @@ -0,0 +1,66 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: exc_10_32_table.c + Codebook for excitation in narrowband CELP mode (4000 bps) + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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. +*/ + + +const signed char exc_10_32_table[320] = { +7,17,17,27,25,22,12,4,-3,0, +28,-36,39,-24,-15,3,-9,15,-5,10, +31,-28,11,31,-21,9,-11,-11,-2,-7, +-25,14,-22,31,4,-14,19,-12,14,-5, +4,-7,4,-5,9,0,-2,42,-47,-16, +1,8,0,9,23,-57,0,28,-11,6, +-31,55,-45,3,-5,4,2,-2,4,-7, +-3,6,-2,7,-3,12,5,8,54,-10, +8,-7,-8,-24,-25,-27,-14,-5,8,5, +44,23,5,-9,-11,-11,-13,-9,-12,-8, +-29,-8,-22,6,-15,3,-12,-1,-5,-3, +34,-1,29,-16,17,-4,12,2,1,4, +-2,-4,2,-1,11,-3,-52,28,30,-9, +-32,25,44,-20,-24,4,6,-1,0,0, +0,0,0,0,0,0,0,0,0,0, +-25,-10,22,29,13,-13,-22,-13,-4,0, +-4,-16,10,15,-36,-24,28,25,-1,-3, +66,-33,-11,-15,6,0,3,4,-2,5, +24,-20,-47,29,19,-2,-4,-1,0,-1, +-2,3,1,8,-11,5,5,-57,28,28, +0,-16,4,-4,12,-6,-1,2,-20,61, +-9,24,-22,-42,29,6,17,8,4,2, +-65,15,8,10,5,6,5,3,2,-2, +-3,5,-9,4,-5,23,13,23,-3,-63, +3,-5,-4,-6,0,-3,23,-36,-46,9, +5,5,8,4,9,-5,1,-3,10,1, +-6,10,-11,24,-47,31,22,-12,14,-10, +6,11,-7,-7,7,-31,51,-12,-6,7, +6,-17,9,-11,-20,52,-19,3,-6,-6, +-8,-5,23,-41,37,1,-21,10,-14,8, +7,5,-15,-15,23,39,-26,-33,7,2, +-32,-30,-21,-8,4,12,17,15,14,11}; diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/exc_20_32_table.c b/mozilla/zap/zmk/speex-1.1.10/libspeex/exc_20_32_table.c new file mode 100755 index 00000000000..46947254e6f --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/exc_20_32_table.c @@ -0,0 +1,66 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: exc_20_32_table.c + Codebook for excitation in narrowband CELP mode (2000 bps) + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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. +*/ + + +const signed char exc_20_32_table[640] = { +12,32,25,46,36,33,9,14,-3,6,1,-8,0,-10,-5,-7,-7,-7,-5,-5, +31,-27,24,-32,-4,10,-11,21,-3,19,23,-9,22,24,-10,-1,-10,-13,-7,-11, +42,-33,31,19,-8,0,-10,-16,1,-21,-17,10,-8,14,8,4,11,-2,5,-2, +-33,11,-16,33,11,-4,9,-4,11,2,6,-5,8,-5,11,-4,-6,26,-36,-16, +0,4,-2,-8,12,6,-1,34,-46,-22,9,9,21,9,5,-66,-5,26,2,10, +13,2,19,9,12,-81,3,13,13,0,-14,22,-35,6,-7,-4,6,-6,10,-6, +-31,38,-33,0,-10,-11,5,-12,12,-17,5,0,-6,13,-9,10,8,25,33,2, +-12,8,-6,10,-2,21,7,17,43,5,11,-7,-9,-20,-36,-20,-23,-4,-4,-3, +27,-9,-9,-49,-39,-38,-11,-9,6,5,23,25,5,3,3,4,1,2,-3,-1, +87,39,17,-21,-9,-19,-9,-15,-13,-14,-17,-11,-10,-11,-8,-6,-1,-3,-3,-1, +-54,-34,-27,-8,-11,-4,-5,0,0,4,8,6,9,7,9,7,6,5,5,5, +48,10,19,-10,12,-1,9,-3,2,5,-3,2,-2,-2,0,-2,-26,6,9,-7, +-16,-9,2,7,7,-5,-43,11,22,-11,-9,34,37,-15,-13,-6,1,-1,1,1, +-64,56,52,-11,-27,5,4,3,1,2,1,3,-1,-4,-4,-10,-7,-4,-4,2, +-1,-7,-7,-12,-10,-15,-9,-5,-5,-11,-16,-13,6,16,4,-13,-16,-10,-4,2, +-47,-13,25,47,19,-14,-20,-8,-17,0,-3,-13,1,6,-17,-14,15,1,10,6, +-24,0,-10,19,-69,-8,14,49,17,-5,33,-29,3,-4,0,2,-8,5,-6,2, +120,-56,-12,-47,23,-9,6,-5,1,2,-5,1,-10,4,-1,-1,4,-1,0,-3, +30,-52,-67,30,22,11,-1,-4,3,0,7,2,0,1,-10,-4,-8,-13,5,1, +1,-1,5,13,-9,-3,-10,-62,22,48,-4,-6,2,3,5,1,1,4,1,13, +3,-20,10,-9,13,-2,-4,9,-20,44,-1,20,-32,-67,19,0,28,11,8,2, +-11,15,-19,-53,31,2,34,10,6,-4,-58,8,10,13,14,1,12,2,0,0, +-128,37,-8,44,-9,26,-3,18,2,6,11,-1,9,1,5,3,0,1,1,2, +12,3,-2,-3,7,25,9,18,-6,-37,3,-8,-16,3,-10,-7,17,-34,-44,11, +17,-15,-3,-16,-1,-13,11,-46,-65,-2,8,13,2,4,4,5,15,5,9,6, +0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, +-9,19,-12,12,-28,38,29,-1,12,2,5,23,-10,3,4,-15,21,-4,3,3, +6,17,-9,-4,-8,-20,26,5,-10,6,1,-19,18,-15,-12,47,-6,-2,-7,-9, +-1,-17,-2,-2,-14,30,-14,2,-7,-4,-1,-12,11,-25,16,-3,-12,11,-7,7, +-17,1,19,-28,31,-7,-10,7,-10,3,12,5,-16,6,24,41,-29,-54,0,1, +7,-1,5,-6,13,10,-4,-8,8,-9,-27,-53,-38,-1,10,19,17,16,12,12, +0,3,-7,-4,13,12,-31,-14,6,-5,3,5,17,43,50,25,10,1,-6,-2}; diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/exc_5_256_table.c b/mozilla/zap/zmk/speex-1.1.10/libspeex/exc_5_256_table.c new file mode 100755 index 00000000000..0bdd3fa3bb3 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/exc_5_256_table.c @@ -0,0 +1,290 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: exc_5_256_table.c + Codebook for excitation in narrowband CELP mode (12800 bps) + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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. +*/ + + +const signed char exc_5_256_table[1280] = { +-8,-37,5,-43,5, +73,61,39,12,-3, +-61,-32,2,42,30, +-3,17,-27,9,34, +20,-1,-5,2,23, +-7,-46,26,53,-47, +20,-2,-33,-89,-51, +-64,27,11,15,-34, +-5,-56,25,-9,-1, +-29,1,40,67,-23, +-16,16,33,19,7, +14,85,22,-10,-10, +-12,-7,-1,52,89, +29,11,-20,-37,-46, +-15,17,-24,-28,24, +2,1,0,23,-101, +23,14,-1,-23,-18, +9,5,-13,38,1, +-28,-28,4,27,51, +-26,34,-40,35,47, +54,38,-54,-26,-6, +42,-25,13,-30,-36, +18,41,-4,-33,23, +-32,-7,-4,51,-3, +17,-52,56,-47,36, +-2,-21,36,10,8, +-33,31,19,9,-5, +-40,10,-9,-21,19, +18,-78,-18,-5,0, +-26,-36,-47,-51,-44, +18,40,27,-2,29, +49,-26,2,32,-54, +30,-73,54,3,-5, +36,22,53,10,-1, +-84,-53,-29,-5,3, +-44,53,-51,4,22, +71,-35,-1,33,-5, +-27,-7,36,17,-23, +-39,16,-9,-55,-15, +-20,39,-35,6,-39, +-14,18,48,-64,-17, +-15,9,39,81,37, +-68,37,47,-21,-6, +-104,13,6,9,-2, +35,8,-23,18,42, +45,21,33,-5,-49, +9,-6,-43,-56,39, +2,-16,-25,87,1, +-3,-9,17,-25,-11, +-9,-1,10,2,-14, +-14,4,-1,-10,28, +-23,40,-32,26,-9, +26,4,-27,-23,3, +42,-60,1,49,-3, +27,10,-52,-40,-2, +18,45,-23,17,-44, +3,-3,17,-46,52, +-40,-47,25,75,31, +-49,53,30,-30,-32, +-36,38,-6,-15,-16, +54,-27,-48,3,38, +-29,-32,-22,-14,-4, +-23,-13,32,-39,9, +8,-45,-13,34,-16, +49,40,32,31,28, +23,23,32,47,59, +-68,8,62,44,25, +-14,-24,-65,-16,36, +67,-25,-38,-21,4, +-33,-2,42,5,-63, +40,11,26,-42,-23, +-61,79,-31,23,-20, +10,-32,53,-25,-36, +10,-26,-5,3,0, +-71,5,-10,-37,1, +-24,21,-54,-17,1, +-29,-25,-15,-27,32, +68,45,-16,-37,-18, +-5,1,0,-77,71, +-6,3,-20,71,-67, +29,-35,10,-30,19, +4,16,17,5,0, +-14,19,2,28,26, +59,3,2,24,39, +55,-50,-45,-18,-17, +33,-35,14,-1,1, +8,87,-35,-29,0, +-27,13,-7,23,-13, +37,-40,50,-35,14, +19,-7,-14,49,54, +-5,22,-2,-29,-8, +-27,38,13,27,48, +12,-41,-21,-15,28, +7,-16,-24,-19,-20, +11,-20,9,2,13, +23,-20,11,27,-27, +71,-69,8,2,-6, +22,12,16,16,9, +-16,-8,-17,1,25, +1,40,-37,-33,66, +94,53,4,-22,-25, +-41,-42,25,35,-16, +-15,57,31,-29,-32, +21,16,-60,45,15, +-1,7,57,-26,-47, +-29,11,8,15,19, +-105,-8,54,27,10, +-17,6,-12,-1,-10, +4,0,23,-10,31, +13,11,10,12,-64, +23,-3,-8,-19,16, +52,24,-40,16,10, +40,5,9,0,-13, +-7,-21,-8,-6,-7, +-21,59,16,-53,18, +-60,11,-47,14,-18, +25,-13,-24,4,-39, +16,-28,54,26,-67, +30,27,-20,-52,20, +-12,55,12,18,-16, +39,-14,-6,-26,56, +-88,-55,12,25,26, +-37,6,75,0,-34, +-81,54,-30,1,-7, +49,-23,-14,21,10, +-62,-58,-57,-47,-34, +15,-4,34,-78,31, +25,-11,7,50,-10, +42,-63,14,-36,-4, +57,55,57,53,42, +-42,-1,15,40,37, +15,25,-11,6,1, +31,-2,-6,-1,-7, +-64,34,28,30,-1, +3,21,0,-88,-12, +-56,25,-28,40,8, +-28,-14,9,12,2, +-6,-17,22,49,-6, +-26,14,28,-20,4, +-12,50,35,40,13, +-38,-58,-29,17,30, +22,60,26,-54,-39, +-12,58,-28,-63,10, +-21,-8,-12,26,-62, +6,-10,-11,-22,-6, +-7,4,1,18,2, +-70,11,14,4,13, +19,-24,-34,24,67, +17,51,-21,13,23, +54,-30,48,1,-13, +80,26,-16,-2,13, +-4,6,-30,29,-24, +73,-58,30,-27,20, +-2,-21,41,45,30, +-27,-3,-5,-18,-20, +-49,-3,-35,10,42, +-19,-67,-53,-11,9, +13,-15,-33,-51,-30, +15,7,25,-30,4, +28,-22,-34,54,-29, +39,-46,20,16,34, +-4,47,75,1,-44, +-55,-24,7,-1,9, +-42,50,-8,-36,41, +68,0,-4,-10,-23, +-15,-50,64,36,-9, +-27,12,25,-38,-47, +-37,32,-49,51,-36, +2,-4,69,-26,19, +7,45,67,46,13, +-63,46,15,-47,4, +-41,13,-6,5,-21, +37,26,-55,-7,33, +-1,-28,10,-17,-64, +-14,0,-36,-17,93, +-3,-9,-66,44,-21, +3,-12,38,-6,-13, +-12,19,13,43,-43, +-10,-12,6,-5,9, +-49,32,-5,2,4, +5,15,-16,10,-21, +8,-62,-8,64,8, +79,-1,-66,-49,-18, +5,40,-5,-30,-45, +1,-6,21,-32,93, +-18,-30,-21,32,21, +-18,22,8,5,-41, +-54,80,22,-10,-7, +-8,-23,-64,66,56, +-14,-30,-41,-46,-14, +-29,-37,27,-14,42, +-2,-9,-29,34,14, +33,-14,22,4,10, +26,26,28,32,23, +-72,-32,3,0,-14, +35,-42,-78,-32,6, +29,-18,-45,-5,7, +-33,-45,-3,-22,-34, +8,-8,4,-51,-25, +-9,59,-78,21,-5, +-25,-48,66,-15,-17, +-24,-49,-13,25,-23, +-64,-6,40,-24,-19, +-11,57,-33,-8,1, +10,-52,-54,28,39, +49,34,-11,-61,-41, +-43,10,15,-15,51, +30,15,-51,32,-34, +-2,-34,14,18,16, +1,1,-3,-3,1, +1,-18,6,16,48, +12,-5,-42,7,36, +48,7,-20,-10,7, +12,2,54,39,-38, +37,54,4,-11,-8, +-46,-10,5,-10,-34, +46,-12,29,-37,39, +36,-11,24,56,17, +14,20,25,0,-25, +-28,55,-7,-5,27, +3,9,-26,-8,6, +-24,-10,-30,-31,-34, +18,4,22,21,40, +-1,-29,-37,-8,-21, +92,-29,11,-3,11, +73,23,22,7,4, +-44,-9,-11,21,-13, +11,9,-78,-1,47, +114,-12,-37,-19,-5, +-11,-22,19,12,-30, +7,38,45,-21,-8, +-9,55,-45,56,-21, +7,17,46,-57,-87, +-6,27,31,31,7, +-56,-12,46,21,-5, +-12,36,3,3,-21, +43,19,12,-7,9, +-14,0,-9,-33,-91, +7,26,3,-11,64, +83,-31,-46,25,2, +9,5,2,2,-1, +20,-17,10,-5,-27, +-8,20,8,-19,16, +-21,-13,-31,5,5, +42,24,9,34,-20, +28,-61,22,11,-39, +64,-20,-1,-30,-9, +-20,24,-25,-24,-29, +22,-60,6,-5,41, +-9,-87,14,34,15, +-57,52,69,15,-3, +-102,58,16,3,6, +60,-75,-32,26,7, +-57,-27,-32,-24,-21, +-29,-16,62,-46,31, +30,-27,-15,7,15}; diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/exc_5_64_table.c b/mozilla/zap/zmk/speex-1.1.10/libspeex/exc_5_64_table.c new file mode 100755 index 00000000000..3d99d7b6ea8 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/exc_5_64_table.c @@ -0,0 +1,98 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: exc_5_64_table.c + Codebook for excitation in narrowband CELP mode (9600 bps) + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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. +*/ + + +const signed char exc_5_64_table[320]={ +1,5,-15,49,-66, +-48,-4,50,-44,7, +37,16,-18,25,-26, +-26,-15,19,19,-27, +-47,28,57,5,-17, +-32,-41,68,21,-2, +64,56,8,-16,-13, +-26,-9,-16,11,6, +-39,25,-19,22,-31, +20,-45,55,-43,10, +-16,47,-40,40,-20, +-51,3,-17,-14,-15, +-24,53,-20,-46,46, +27,-68,32,3,-18, +-5,9,-31,16,-9, +-10,-1,-23,48,95, +47,25,-41,-32,-3, +15,-25,-55,36,41, +-27,20,5,13,14, +-22,5,2,-23,18, +46,-15,17,-18,-34, +-5,-8,27,-55,73, +16,2,-1,-17,40, +-78,33,0,2,19, +4,53,-16,-15,-16, +-28,-3,-13,49,8, +-7,-29,27,-13,32, +20,32,-61,16,14, +41,44,40,24,20, +7,4,48,-60,-77, +17,-6,-48,65,-15, +32,-30,-71,-10,-3, +-6,10,-2,-7,-29, +-56,67,-30,7,-5, +86,-6,-10,0,5, +-31,60,34,-38,-3, +24,10,-2,30,23, +24,-41,12,70,-43, +15,-17,6,13,16, +-13,8,30,-15,-8, +5,23,-34,-98,-4, +-13,13,-48,-31,70, +12,31,25,24,-24, +26,-7,33,-16,8, +5,-11,-14,-8,-65, +13,10,-2,-9,0, +-3,-68,5,35,7, +0,-31,-1,-17,-9, +-9,16,-37,-18,-1, +69,-48,-28,22,-21, +-11,5,49,55,23, +-86,-36,16,2,13, +63,-51,30,-11,13, +24,-18,-6,14,-19, +1,41,9,-5,27, +-36,-44,-34,-37,-21, +-26,31,-39,15,43, +5,-8,29,20,-8, +-20,-52,-28,-1,13, +26,-34,-10,-9,27, +-8,8,27,-66,4, +12,-22,49,10,-77, +32,-18,3,-38,12, +-3,-1,2,2,0}; diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/exc_8_128_table.c b/mozilla/zap/zmk/speex-1.1.10/libspeex/exc_8_128_table.c new file mode 100755 index 00000000000..d4a30ed119f --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/exc_8_128_table.c @@ -0,0 +1,162 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: exc_8_128_table.c + Codebook for excitation in narrowband CELP mode (7000 bps) + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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. +*/ + + +const signed char exc_8_128_table[1024] = { +-14,9,13,-32,2,-10,31,-10, +-8,-8,6,-4,-1,10,-64,23, +6,20,13,6,8,-22,16,34, +7,42,-49,-28,5,26,4,-15, +41,34,41,32,33,24,23,14, +8,40,34,4,-24,-41,-19,-15, +13,-13,33,-54,24,27,-44,33, +27,-15,-15,24,-19,14,-36,14, +-9,24,-12,-4,37,-5,16,-34, +5,10,33,-15,-54,-16,12,25, +12,1,2,0,3,-1,-4,-4, +11,2,-56,54,27,-20,13,-6, +-46,-41,-33,-11,-5,7,12,14, +-14,-5,8,20,6,3,4,-8, +-5,-42,11,8,-14,25,-2,2, +13,11,-22,39,-9,9,5,-45, +-9,7,-9,12,-7,34,-17,-102, +7,2,-42,18,35,-9,-34,11, +-5,-2,3,22,46,-52,-25,-9, +-94,8,11,-5,-5,-5,4,-7, +-35,-7,54,5,-32,3,24,-9, +-22,8,65,37,-1,-12,-23,-6, +-9,-28,55,-33,14,-3,2,18, +-60,41,-17,8,-16,17,-11,0, +-11,29,-28,37,9,-53,33,-14, +-9,7,-25,-7,-11,26,-32,-8, +24,-21,22,-19,19,-10,29,-14, +0,0,0,0,0,0,0,0, +-5,-52,10,41,6,-30,-4,16, +32,22,-27,-22,32,-3,-28,-3, +3,-35,6,17,23,21,8,2, +4,-45,-17,14,23,-4,-31,-11, +-3,14,1,19,-11,2,61,-8, +9,-12,7,-10,12,-3,-24,99, +-48,23,50,-37,-5,-23,0,8, +-14,35,-64,-5,46,-25,13,-1, +-49,-19,-15,9,34,50,25,11, +-6,-9,-16,-20,-32,-33,-32,-27, +10,-8,12,-15,56,-14,-32,33, +3,-9,1,65,-9,-9,-10,-2, +-6,-23,9,17,3,-28,13,-32, +4,-2,-10,4,-16,76,12,-52, +6,13,33,-6,4,-14,-9,-3, +1,-15,-16,28,1,-15,11,16, +9,4,-21,-37,-40,-6,22,12, +-15,-23,-14,-17,-16,-9,-10,-9, +13,-39,41,5,-9,16,-38,25, +46,-47,4,49,-14,17,-2,6, +18,5,-6,-33,-22,44,50,-2, +1,3,-6,7,7,-3,-21,38, +-18,34,-14,-41,60,-13,6,16, +-24,35,19,-13,-36,24,3,-17, +-14,-10,36,44,-44,-29,-3,3, +-54,-8,12,55,26,4,-2,-5, +2,-11,22,-23,2,22,1,-25, +-39,66,-49,21,-8,-2,10,-14, +-60,25,6,10,27,-25,16,5, +-2,-9,26,-13,-20,58,-2,7, +52,-9,2,5,-4,-15,23,-1, +-38,23,8,27,-6,0,-27,-7, +39,-10,-14,26,11,-45,-12,9, +-5,34,4,-35,10,43,-22,-11, +56,-7,20,1,10,1,-26,9, +94,11,-27,-14,-13,1,-11,0, +14,-5,-6,-10,-4,-15,-8,-41, +21,-5,1,-28,-8,22,-9,33, +-23,-4,-4,-12,39,4,-7,3, +-60,80,8,-17,2,-6,12,-5, +1,9,15,27,31,30,27,23, +61,47,26,10,-5,-8,-12,-13, +5,-18,25,-15,-4,-15,-11,12, +-2,-2,-16,-2,-6,24,12,11, +-4,9,1,-9,14,-45,57,12, +20,-35,26,11,-64,32,-10,-10, +42,-4,-9,-16,32,24,7,10, +52,-11,-57,29,0,8,0,-6, +17,-17,-56,-40,7,20,18,12, +-6,16,5,7,-1,9,1,10, +29,12,16,13,-2,23,7,9, +-3,-4,-5,18,-64,13,55,-25, +9,-9,24,14,-25,15,-11,-40, +-30,37,1,-19,22,-5,-31,13, +-2,0,7,-4,16,-67,12,66, +-36,24,-8,18,-15,-23,19,0, +-45,-7,4,3,-13,13,35,5, +13,33,10,27,23,0,-7,-11, +43,-74,36,-12,2,5,-8,6, +-33,11,-16,-14,-5,-7,-3,17, +-34,27,-16,11,-9,15,33,-31, +8,-16,7,-6,-7,63,-55,-17, +11,-1,20,-46,34,-30,6,9, +19,28,-9,5,-24,-8,-23,-2, +31,-19,-16,-5,-15,-18,0,26, +18,37,-5,-15,-2,17,5,-27, +21,-33,44,12,-27,-9,17,11, +25,-21,-31,-7,13,33,-8,-25, +-7,7,-10,4,-6,-9,48,-82, +-23,-8,6,11,-23,3,-3,49, +-29,25,31,4,14,16,9,-4, +-18,10,-26,3,5,-44,-9,9, +-47,-55,15,9,28,1,4,-3, +46,6,-6,-38,-29,-31,-15,-6, +3,0,14,-6,8,-54,-50,33, +-5,1,-14,33,-48,26,-4,-5, +-3,-5,-3,-5,-28,-22,77,55, +-1,2,10,10,-9,-14,-66,-49, +11,-36,-6,-20,10,-10,16,12, +4,-1,-16,45,-44,-50,31,-2, +25,42,23,-32,-22,0,11,20, +-40,-35,-40,-36,-32,-26,-21,-13, +52,-22,6,-24,-20,17,-5,-8, +36,-25,-11,21,-26,6,34,-8, +7,20,-3,5,-25,-8,18,-5, +-9,-4,1,-9,20,20,39,48, +-24,9,5,-65,22,29,4,3, +-43,-11,32,-6,9,19,-27,-10, +-47,-14,24,10,-7,-36,-7,-1, +-4,-5,-5,16,53,25,-26,-29, +-4,-12,45,-58,-34,33,-5,2, +-1,27,-48,31,-15,22,-5,4, +7,7,-25,-3,11,-22,16,-12, +8,-3,7,-11,45,14,-73,-19, +56,-46,24,-20,28,-12,-2,-1, +-36,-3,-33,19,-6,7,2,-15, +5,-31,-45,8,35,13,20,0, +-9,48,-13,-43,-3,-13,2,-5, +72,-68,-27,2,1,-2,-7,5, +36,33,-40,-12,-4,-5,23,19}; diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/filters.c b/mozilla/zap/zmk/speex-1.1.10/libspeex/filters.c new file mode 100755 index 00000000000..c8b342bcc46 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/filters.c @@ -0,0 +1,607 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: filters.c + Various analysis/synthesis filters + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 "filters.h" +#include "stack_alloc.h" +#include "misc.h" +#include "math_approx.h" +#include "ltp.h" +#include + +#ifdef _USE_SSE +#include "filters_sse.h" +#elif defined (ARM4_ASM) || defined(ARM5E_ASM) +#include "filters_arm4.h" +#elif defined (BFIN_ASM) +#include "filters_bfin.h" +#endif + + + +void bw_lpc(spx_word16_t gamma, const spx_coef_t *lpc_in, spx_coef_t *lpc_out, int order) +{ + int i; + spx_word16_t tmp=gamma; + for (i=0;i SHL32(EXTEND32(SIG_SCALING), 8)) + { + spx_word16_t scale_1; + scale = PSHR32(scale, SIG_SHIFT); + scale_1 = EXTRACT16(DIV32_16(SHL32(EXTEND32(SIG_SCALING),7),scale)); + for (i=0;i max_val) + max_val = tmp; + } + + sig_shift=0; + while (max_val>16383) + { + sig_shift++; + max_val >>= 1; + } + + for (i=0;i= max_val) + max_val = tmp; + } + + sig_shift=0; + while (max_val>max_scale) + { + sig_shift++; + max_val >>= 1; + } + + for (i=0;i>1; + for (i=0;ilast_pitch=0; + mem->last_pitch_gain[0]=mem->last_pitch_gain[1]=mem->last_pitch_gain[2]=0; + mem->smooth_gain=1; +} + +#ifdef FIXED_POINT +#define COMB_STEP 32767 +#else +#define COMB_STEP 1.0 +#endif + +void comb_filter( +spx_sig_t *exc, /*decoded excitation*/ +spx_sig_t *new_exc, /*enhanced excitation*/ +spx_coef_t *ak, /*LPC filter coefs*/ +int p, /*LPC order*/ +int nsf, /*sub-frame size*/ +int pitch, /*pitch period*/ +spx_word16_t *pitch_gain, /*pitch gain (3-tap)*/ +spx_word16_t comb_gain, /*gain of comb filter*/ +CombFilterMem *mem +) +{ + int i; + spx_word16_t exc_energy=0, new_exc_energy=0; + spx_word16_t gain; + spx_word16_t step; + spx_word16_t fact; + + /*Compute excitation amplitude prior to enhancement*/ + exc_energy = compute_rms(exc, nsf); + /*for (i=0;ilast_pitch_gain); + if (g > 166) + comb_gain = MULT16_16_Q15(DIV32_16(SHL32(EXTEND32(165),15),g), comb_gain); + if (g < 64) + comb_gain = MULT16_16_Q15(SHL16(g, 9), comb_gain); + } +#else + { + float g=0; + g = GAIN_SCALING_1*.5*(gain_3tap_to_1tap(pitch_gain)+gain_3tap_to_1tap(mem->last_pitch_gain)); + if (g>1.3) + comb_gain*=1.3/g; + if (g<.5) + comb_gain*=2.*g; + } +#endif + step = DIV32(COMB_STEP, nsf); + fact=0; + + /*Apply pitch comb-filter (filter out noise between pitch harmonics)*/ + for (i=0;ilast_pitch_gain[0],7),exc[i-mem->last_pitch+1]) + + MULT16_32_Q15(SHL16(mem->last_pitch_gain[1],7),exc[i-mem->last_pitch]) + + MULT16_32_Q15(SHL16(mem->last_pitch_gain[2],7),exc[i-mem->last_pitch-1]),2); + + new_exc[i] = exc[i] + MULT16_32_Q15(comb_gain, ADD32(MULT16_32_Q15(fact,exc1), MULT16_32_Q15(SUB16(COMB_STEP,fact), exc2))); + } + + mem->last_pitch_gain[0] = pitch_gain[0]; + mem->last_pitch_gain[1] = pitch_gain[1]; + mem->last_pitch_gain[2] = pitch_gain[2]; + mem->last_pitch = pitch; + + /*Amplitude after enhancement*/ + new_exc_energy = compute_rms(new_exc, nsf); + + if (exc_energy > new_exc_energy) + exc_energy = new_exc_energy; + + gain = DIV32_16(SHL32(EXTEND32(exc_energy),15),ADD16(1,new_exc_energy)); + +#ifdef FIXED_POINT + if (gain < 16384) + gain = 16384; +#else + if (gain < .5) + gain=.5; +#endif + +#ifdef FIXED_POINT + for (i=0;ismooth_gain = ADD16(MULT16_16_Q15(31457,mem->smooth_gain), MULT16_16_Q15(1311,gain)); + new_exc[i] = MULT16_32_Q15(mem->smooth_gain, new_exc[i]); + } +#else + for (i=0;ismooth_gain = .96*mem->smooth_gain + .04*gain; + new_exc[i] *= mem->smooth_gain; + } +#endif +} diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/filters.h b/mozilla/zap/zmk/speex-1.1.10/libspeex/filters.h new file mode 100755 index 00000000000..a546b666a4b --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/filters.h @@ -0,0 +1,89 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: filters.h + Various analysis/synthesis filters + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 FILTERS_H +#define FILTERS_H + +#include "misc.h" + +spx_word16_t compute_rms(const spx_sig_t *x, int len); +void signal_mul(const spx_sig_t *x, spx_sig_t *y, spx_word32_t scale, int len); +void signal_div(const spx_sig_t *x, spx_sig_t *y, spx_word32_t scale, int len); + +#ifdef FIXED_POINT + +int normalize16(const spx_sig_t *x, spx_word16_t *y, spx_sig_t max_scale, int len); + +#endif + +typedef struct CombFilterMem { + int last_pitch; + spx_word16_t last_pitch_gain[3]; + spx_word16_t smooth_gain; +} CombFilterMem; + + +void qmf_decomp(const spx_word16_t *xx, const spx_word16_t *aa, spx_sig_t *, spx_sig_t *y2, int N, int M, spx_word16_t *mem, char *stack); +void fir_mem_up(const spx_sig_t *x, const spx_word16_t *a, spx_sig_t *y, int N, int M, spx_word32_t *mem, char *stack); + + +void filter_mem2(const spx_sig_t *x, const spx_coef_t *num, const spx_coef_t *den, spx_sig_t *y, int N, int ord, spx_mem_t *mem); +void fir_mem2(const spx_sig_t *x, const spx_coef_t *num, spx_sig_t *y, int N, int ord, spx_mem_t *mem); +void iir_mem2(const spx_sig_t *x, const spx_coef_t *den, spx_sig_t *y, int N, int ord, spx_mem_t *mem); + +/* Apply bandwidth expansion on LPC coef */ +void bw_lpc(spx_word16_t , const spx_coef_t *lpc_in, spx_coef_t *lpc_out, int order); + + + +void syn_percep_zero(const spx_sig_t *x, const spx_coef_t *ak, const spx_coef_t *awk1, const spx_coef_t *awk2, spx_sig_t *y, int N, int ord, char *stack); + +void residue_percep_zero(const spx_sig_t *xx, const spx_coef_t *ak, const spx_coef_t *awk1, const spx_coef_t *awk2, spx_sig_t *y, int N, int ord, char *stack); + +void compute_impulse_response(const spx_coef_t *ak, const spx_coef_t *awk1, const spx_coef_t *awk2, spx_word16_t *y, int N, int ord, char *stack); + +void comb_filter_mem_init (CombFilterMem *mem); + +void comb_filter( +spx_sig_t *exc, /*decoded excitation*/ +spx_sig_t *new_exc, /*enhanced excitation*/ +spx_coef_t *ak, /*LPC filter coefs*/ +int p, /*LPC order*/ +int nsf, /*sub-frame size*/ +int pitch, /*pitch period*/ +spx_word16_t *pitch_gain, /*pitch gain (3-tap)*/ +spx_word16_t comb_gain, /*gain of comb filter*/ +CombFilterMem *mem +); + + +#endif diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/filters_arm4.h b/mozilla/zap/zmk/speex-1.1.10/libspeex/filters_arm4.h new file mode 100755 index 00000000000..7065b5f26f9 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/filters_arm4.h @@ -0,0 +1,377 @@ +/* Copyright (C) 2004 Jean-Marc Valin + File: filters_arm4.h + ARM4-optimized filtering routines + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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. +*/ + +#define OVERRIDE_NORMALIZE16 +int normalize16(const spx_sig_t *x, spx_word16_t *y, int max_scale, int len) +{ + int i; + spx_sig_t max_val=1; + int sig_shift; + int dead1, dead2, dead3, dead4, dead5, dead6; + + __asm__ __volatile__ ( + "\tmov %1, #1 \n" + "\tmov %3, #0 \n" + + ".normalize16loop1%=: \n" + + "\tldr %4, [%0], #4 \n" + "\tcmps %4, %1 \n" + "\tmovgt %1, %4 \n" + "\tcmps %4, %3 \n" + "\tmovlt %3, %4 \n" + + "\tsubs %2, %2, #1 \n" + "\tbne .normalize16loop1%=\n" + + "\trsb %3, %3, #0 \n" + "\tcmp %1, %3 \n" + "\tmovlt %1, %3 \n" + : "=r" (dead1), "=r" (max_val), "=r" (dead3), "=r" (dead4), + "=r" (dead5), "=r" (dead6) + : "0" (x), "2" (len) + : "cc"); + + sig_shift=0; + while (max_val>max_scale) + { + sig_shift++; + max_val >>= 1; + } + + __asm__ __volatile__ ( + ".normalize16loop%=: \n" + + "\tldr %4, [%0], #4 \n" + "\tldr %5, [%0], #4 \n" + "\tmov %4, %4, asr %3 \n" + "\tstrh %4, [%1], #2 \n" + "\tldr %4, [%0], #4 \n" + "\tmov %5, %5, asr %3 \n" + "\tstrh %5, [%1], #2 \n" + "\tldr %5, [%0], #4 \n" + "\tmov %4, %4, asr %3 \n" + "\tstrh %4, [%1], #2 \n" + "\tsubs %2, %2, #1 \n" + "\tmov %5, %5, asr %3 \n" + "\tstrh %5, [%1], #2 \n" + + "\tbge .normalize16loop%=\n" + : "=r" (dead1), "=r" (dead2), "=r" (dead3), "=r" (dead4), + "=r" (dead5), "=r" (dead6) + : "0" (x), "1" (y), "2" (len>>2), "3" (sig_shift) + : "cc", "memory"); + return sig_shift; +} + +#define OVERRIDE_FILTER_MEM2 +void filter_mem2(const spx_sig_t *x, const spx_coef_t *num, const spx_coef_t *den, spx_sig_t *y, int N, int ord, spx_mem_t *mem) +{ + int i,j; + spx_sig_t xi,yi,nyi; + + for (i=0;i + +#define OVERRIDE_NORMALIZE16 +int normalize16(const spx_sig_t *x, spx_word16_t *y, spx_sig_t max_scale, int len) +{ + spx_sig_t max_val=1; + int sig_shift; + + __asm__ + ( + "%0 = 0;\n\t" + "I0 = %1;\n\t" + "L0 = 0;\n\t" + "R1 = [I0++];\n\t" + "LOOP norm_max%= LC0 = %2;\n\t" + "LOOP_BEGIN norm_max%=;\n\t" + "R2 = ABS R1 || R1 = [I0++];\n\t" + "%0 = MAX(%0, R2);\n\t" + "LOOP_END norm_max%=;\n\t" + : "=&d" (max_val) + : "a" (x), "a" (len) + : "R1", "R2" + ); + + sig_shift=0; + while (max_val>max_scale) + { + sig_shift++; + max_val >>= 1; + } + + __asm__ __volatile__ + ( + "I0 = %0;\n\t" + "L0 = 0;\n\t" + "I1 = %1;\n\t" + "L1 = 0;\n\t" + "R0 = [I0++];\n\t" + "LOOP norm_shift%= LC0 = %3 >> 1;\n\t" + "LOOP_BEGIN norm_shift%=;\n\t" + "R1 = ASHIFT R0 by %2.L || R2 = [I0++];\n\t" + "R3 = ASHIFT R2 by %2.L || R0 = [I0++];\n\t" + "R3 = PACK(R3.L, R1.L);\n\t" + "[I1++] = R3;\n\t" + "LOOP_END norm_shift%=;\n\t" + : : "a" (x), "a" (y), "d" (-sig_shift), "a" (len) + : "I0", "L0", "I1", "L1", "R0", "R1", "R2", "R3", "memory" + ); + return sig_shift; +} + +#define OVERRIDE_FILTER_MEM2 +void filter_mem2(const spx_sig_t *_x, const spx_coef_t *num, const spx_coef_t *den, spx_sig_t *_y, int N, int ord, spx_mem_t *mem) +{ + spx_word32_t xy2[N+1]; + spx_word32_t *xy = xy2+1; + spx_word32_t numden_a[2*ord+2]; + spx_word16_t *numden = (spx_word16_t*) numden_a; + int i; + for (i=0;i>> 13;\n\t" + "W[%0] = R3.L;\n\t" + "R0 <<= 1;\n\t" + "R1 = R1 + R0;\n\t" + "R1 >>>= 13;\n\t" + "W[%1] = R1.L;\n\t" + "LOOP_END samples%=;\n\t" + : "=a" (ytmp2), "=a" (y) + : "a" (awk2), "a" (ak), "d" (ord), "m" (N), "0" (ytmp2), "1" (y) + : "A0", "A1", "R0", "R1", "R2", "R3", "I0", "I1", "I2", "I3", "L0", "L1", "L2", "L3", "A0", "A1" + ); +} + + + +#if 0 /* Equivalent C function for filter_mem2 and compute_impulse_response */ +#define min(a,b) ((a)<(b) ? (a):(b)) + +void compute_impulse_response(const spx_coef_t *ak, const spx_coef_t *awk1, const spx_coef_t *awk2, spx_word16_t *y, int N, int ord, char *stack) +{ + int i,j; + VARDECL(spx_word16_t *ytmp); + ALLOC(ytmp, N, spx_word16_t); + + y[0] = LPC_SCALING; + for (i=0;i + +void filter_mem2_10(const float *x, const float *_num, const float *_den, float *y, int N, int ord, float *_mem) +{ + __m128 num[3], den[3], mem[3]; + + int i; + + /* Copy numerator, denominator and memory to aligned xmm */ + for (i=0;i<2;i++) + { + mem[i] = _mm_loadu_ps(_mem+4*i); + num[i] = _mm_loadu_ps(_num+4*i); + den[i] = _mm_loadu_ps(_den+4*i); + } + mem[2] = _mm_setr_ps(_mem[8], _mem[9], 0, 0); + num[2] = _mm_setr_ps(_num[9], _num[10], 0, 0); + den[2] = _mm_setr_ps(_den[9], _den[10], 0, 0); + + for (i=0;i>> 16;\n\t" + "R1 = (A1 += %2.L*%1.H) (IS);\n\t" + "%0 = R1;\n\t" + : "=&d" (res), "=&d" (b) + : "d" (a), "1" (b) + : "A1", "R1" + ); + return res; +} + +#undef MAC16_32_Q15 +static inline spx_word32_t MAC16_32_Q15(spx_word32_t c, spx_word16_t a, spx_word32_t b) +{ + spx_word32_t res; + __asm__ + ( + "%1 <<= 1;\n\t" + "A1 = %2.L*%1.L (M,IS);\n\t" + "A1 = A1 >>> 16;\n\t" + "R1 = (A1 += %2.L*%1.H) (IS);\n\t" + "%0 = R1 + %4;\n\t" + : "=&d" (res), "=&d" (b) + : "d" (a), "1" (b), "d" (c) + : "A1", "R1" + ); + return res; +} + +#undef MULT16_32_Q14 +static inline spx_word32_t MULT16_32_Q14(spx_word16_t a, spx_word32_t b) +{ + spx_word32_t res; + __asm__ + ( + "%2 <<= 2;\n\t" + "A1 = %1.L*%2.L (M,IS);\n\t" + "A1 = A1 >>> 16;\n\t" + "R1 = (A1 += %1.L*%2.H) (IS);\n\t" + "%0 = R1;\n\t" + : "=d" (res), "=d" (a), "=d" (b) + : "1" (a), "2" (b) + : "A1", "R1" + ); + return res; +} + +#undef MAC16_32_Q14 +static inline spx_word32_t MAC16_32_Q14(spx_word32_t c, spx_word16_t a, spx_word32_t b) +{ + spx_word32_t res; + __asm__ + ( + "%1 <<= 2;\n\t" + "A1 = %2.L*%1.L (M,IS);\n\t" + "A1 = A1 >>> 16;\n\t" + "R1 = (A1 += %2.L*%1.H) (IS);\n\t" + "%0 = R1 + %4;\n\t" + : "=&d" (res), "=&d" (b) + : "d" (a), "1" (b), "d" (c) + : "A1", "R1" + ); + return res; +} + +#endif diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/fixed_debug.h b/mozilla/zap/zmk/speex-1.1.10/libspeex/fixed_debug.h new file mode 100755 index 00000000000..23ad2672bd0 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/fixed_debug.h @@ -0,0 +1,440 @@ +/* Copyright (C) 2003 Jean-Marc Valin */ +/** + @file fixed_debug.h + @brief Fixed-point operations with debugging +*/ +/* + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 FIXED_DEBUG_H +#define FIXED_DEBUG_H + +#include + +extern long long spx_mips; +#define MIPS_INC spx_mips++, + +#define VERIFY_SHORT(x) ((x)<=32767&&(x)>=-32768) +#define VERIFY_INT(x) ((x)<=2147483647LL&&(x)>=-2147483648LL) + +static inline short NEG16(int x) +{ + int res; + if (!VERIFY_SHORT(x)) + { + fprintf (stderr, "NEG16: input is not short: %d\n", (int)x); + } + res = -x; + if (!VERIFY_SHORT(res)) + fprintf (stderr, "NEG16: output is not short: %d\n", (int)res); + spx_mips++; + return res; +} +static inline int NEG32(long long x) +{ + long long res; + if (!VERIFY_INT(x)) + { + fprintf (stderr, "NEG16: input is not int: %d\n", (int)x); + } + res = -x; + if (!VERIFY_INT(res)) + fprintf (stderr, "NEG16: output is not int: %d\n", (int)res); + spx_mips++; + return res; +} + +static inline short EXTRACT16(int x) +{ + int res; + if (!VERIFY_SHORT(x)) + { + fprintf (stderr, "EXTRACT16: input is not short: %d\n", x); + } + res = x; + spx_mips++; + return res; +} + +static inline int EXTEND32(int x) +{ + int res; + if (!VERIFY_SHORT(x)) + { + fprintf (stderr, "EXTRACT16: input is not short: %d\n", x); + } + res = x; + spx_mips++; + return res; +} + +static inline short SHR16(int a, int shift) +{ + int res; + if (!VERIFY_SHORT(a) || !VERIFY_SHORT(shift)) + { + fprintf (stderr, "SHR16: inputs are not short: %d %d\n", a, shift); + } + res = a>>shift; + if (!VERIFY_SHORT(res)) + fprintf (stderr, "SHR16: output is not short: %d\n", res); + spx_mips++; + return res; +} +static inline short SHL16(int a, int shift) +{ + int res; + if (!VERIFY_SHORT(a) || !VERIFY_SHORT(shift)) + { + fprintf (stderr, "SHR16: inputs are not short: %d %d\n", a, shift); + } + res = a<>shift; + if (!VERIFY_INT(res)) + fprintf (stderr, "SHR32: output is not int: %d\n", (int)res); + spx_mips++; + return res; +} +static inline int SHL32(long long a, int shift) +{ + long long res; + if (!VERIFY_INT(a) || !VERIFY_SHORT(shift)) + { + fprintf (stderr, "SHR32: inputs are not int: %d %d\n", (int)a, shift); + } + res = a<(a) ? (a) : (x)<-(a) ? -(a) : (x))) +#define SATURATE32(x,a) (((x)>(a) ? (a) : (x)<-(a) ? -(a) : (x))) + +#define SHR(a,shift) ((a) >> (shift)) +#define SHL(a,shift) ((a) << (shift)) + +static inline short ADD16(int a, int b) +{ + int res; + if (!VERIFY_SHORT(a) || !VERIFY_SHORT(b)) + { + fprintf (stderr, "ADD16: inputs are not short: %d %d\n", a, b); + } + res = a+b; + if (!VERIFY_SHORT(res)) + fprintf (stderr, "ADD16: output is not short: %d\n", res); + spx_mips++; + return res; +} +static inline short SUB16(int a, int b) +{ + int res; + if (!VERIFY_SHORT(a) || !VERIFY_SHORT(b)) + { + fprintf (stderr, "SUB16: inputs are not short: %d %d\n", a, b); + } + res = a-b; + if (!VERIFY_SHORT(res)) + fprintf (stderr, "SUB16: output is not short: %d\n", res); + spx_mips++; + return res; +} + +static inline int ADD32(long long a, long long b) +{ + long long res; + if (!VERIFY_INT(a) || !VERIFY_INT(b)) + { + fprintf (stderr, "ADD32: inputs are not int: %d %d\n", (int)a, (int)b); + } + res = a+b; + if (!VERIFY_INT(res)) + fprintf (stderr, "ADD32: output is not int: %d\n", (int)res); + spx_mips++; + return res; +} + +static inline int SUB32(long long a, long long b) +{ + long long res; + if (!VERIFY_INT(a) || !VERIFY_INT(b)) + { + fprintf (stderr, "SUB32: inputs are not int: %d %d\n", (int)a, (int)b); + } + res = a-b; + if (!VERIFY_INT(res)) + fprintf (stderr, "SUB32: output is not int: %d\n", (int)res); + spx_mips++; + return res; +} + +#define ADD64(a,b) (MIPS_INC(a)+(b)) + +#define PSHR(a,shift) (SHR((a)+(1<<((shift)-1)),shift)) + +/* result fits in 16 bits */ +static inline short MULT16_16_16(int a, int b) +{ + int res; + if (!VERIFY_SHORT(a) || !VERIFY_SHORT(b)) + { + fprintf (stderr, "MULT16_16_16: inputs are not short: %d %d\n", a, b); + } + res = a*b; + if (!VERIFY_SHORT(res)) + fprintf (stderr, "MULT16_16_16: output is not short: %d\n", res); + spx_mips++; + return res; +} + +static inline int MULT16_16(int a, int b) +{ + long long res; + if (!VERIFY_SHORT(a) || !VERIFY_SHORT(b)) + { + fprintf (stderr, "MULT16_16: inputs are not short: %d %d\n", a, b); + } + res = ((long long)a)*b; + if (!VERIFY_INT(res)) + fprintf (stderr, "MULT16_16: output is not int: %d\n", (int)res); + spx_mips++; + return res; +} + +#define MAC16_16(c,a,b) (spx_mips--,ADD32((c),MULT16_16((a),(b)))) +#define MAC16_16_Q11(c,a,b) (ADD16((c),EXTRACT16(SHR32(MULT16_16((a),(b)),11)))) +#define MAC16_16_Q13(c,a,b) (ADD16((c),EXTRACT16(SHR32(MULT16_16((a),(b)),13)))) + +static inline int MULT16_32_QX(int a, long long b, int Q) +{ + long long res; + if (!VERIFY_SHORT(a) || !VERIFY_INT(b)) + { + fprintf (stderr, "MULT16_32_Q%d: inputs are not short+int: %d %d\n", Q, (int)a, (int)b); + } + res = (((long long)a)*(long long)b) >> Q; + if (!VERIFY_INT(res)) + fprintf (stderr, "MULT16_32_Q%d: output is not int: %d*%d=%d\n", Q, (int)a, (int)b,(int)res); + spx_mips+=5; + return res; +} + + +#define MULT16_32_Q11(a,b) MULT16_32_QX(a,b,11) +#define MAC16_32_Q11(c,a,b) ADD32((c),MULT16_32_Q11((a),(b))) +#define MULT16_32_Q12(a,b) MULT16_32_QX(a,b,12) +#define MULT16_32_Q13(a,b) MULT16_32_QX(a,b,13) +#define MULT16_32_Q14(a,b) MULT16_32_QX(a,b,14) +#define MULT16_32_Q15(a,b) MULT16_32_QX(a,b,15) +#define MAC16_32_Q15(c,a,b) ADD32((c),MULT16_32_Q15((a),(b))) + +static inline int SATURATE(int a, int b) +{ + if (a>b) + a=b; + if (a<-b) + a = -b; + return a; +} + +static inline int MULT16_16_Q11_32(int a, int b) +{ + long long res; + if (!VERIFY_SHORT(a) || !VERIFY_SHORT(b)) + { + fprintf (stderr, "MULT16_16_Q11: inputs are not short: %d %d\n", a, b); + } + res = ((long long)a)*b; + res >>= 11; + if (!VERIFY_INT(res)) + fprintf (stderr, "MULT16_16_Q11: output is not short: %d*%d=%d\n", (int)a, (int)b, (int)res); + spx_mips+=3; + return res; +} +static inline short MULT16_16_Q13(int a, int b) +{ + long long res; + if (!VERIFY_SHORT(a) || !VERIFY_SHORT(b)) + { + fprintf (stderr, "MULT16_16_Q13: inputs are not short: %d %d\n", a, b); + } + res = ((long long)a)*b; + res >>= 13; + if (!VERIFY_SHORT(res)) + fprintf (stderr, "MULT16_16_Q13: output is not short: %d*%d=%d\n", a, b, (int)res); + spx_mips+=3; + return res; +} +static inline short MULT16_16_Q14(int a, int b) +{ + long long res; + if (!VERIFY_SHORT(a) || !VERIFY_SHORT(b)) + { + fprintf (stderr, "MULT16_16_Q14: inputs are not short: %d %d\n", a, b); + } + res = ((long long)a)*b; + res >>= 14; + if (!VERIFY_SHORT(res)) + fprintf (stderr, "MULT16_16_Q14: output is not short: %d\n", (int)res); + spx_mips+=3; + return res; +} +static inline short MULT16_16_Q15(int a, int b) +{ + long long res; + if (!VERIFY_SHORT(a) || !VERIFY_SHORT(b)) + { + fprintf (stderr, "MULT16_16_Q15: inputs are not short: %d %d\n", a, b); + } + res = ((long long)a)*b; + res >>= 15; + if (!VERIFY_SHORT(res)) + fprintf (stderr, "MULT16_16_Q15: output is not short: %d\n", (int)res); + spx_mips+=3; + return res; +} + +static inline short MULT16_16_P13(int a, int b) +{ + long long res; + if (!VERIFY_SHORT(a) || !VERIFY_SHORT(b)) + { + fprintf (stderr, "MULT16_16_P13: inputs are not short: %d %d\n", a, b); + } + res = ((long long)a)*b; + res += 4096; + if (!VERIFY_INT(res)) + fprintf (stderr, "MULT16_16_P13: overflow: %d*%d=%d\n", a, b, (int)res); + res >>= 13; + if (!VERIFY_SHORT(res)) + fprintf (stderr, "MULT16_16_P13: output is not short: %d*%d=%d\n", a, b, (int)res); + spx_mips+=4; + return res; +} +static inline short MULT16_16_P14(int a, int b) +{ + long long res; + if (!VERIFY_SHORT(a) || !VERIFY_SHORT(b)) + { + fprintf (stderr, "MULT16_16_P14: inputs are not short: %d %d\n", a, b); + } + res = ((long long)a)*b; + res += 8192; + if (!VERIFY_INT(res)) + fprintf (stderr, "MULT16_16_P14: overflow: %d*%d=%d\n", a, b, (int)res); + res >>= 14; + if (!VERIFY_SHORT(res)) + fprintf (stderr, "MULT16_16_P14: output is not short: %d*%d=%d\n", a, b, (int)res); + spx_mips+=4; + return res; +} +static inline short MULT16_16_P15(int a, int b) +{ + long long res; + if (!VERIFY_SHORT(a) || !VERIFY_SHORT(b)) + { + fprintf (stderr, "MULT16_16_P15: inputs are not short: %d %d\n", a, b); + } + res = ((long long)a)*b; + res += 16384; + if (!VERIFY_INT(res)) + fprintf (stderr, "MULT16_16_P15: overflow: %d*%d=%d\n", a, b, (int)res); + res >>= 15; + if (!VERIFY_SHORT(res)) + fprintf (stderr, "MULT16_16_P15: output is not short: %d*%d=%d\n", a, b, (int)res); + spx_mips+=4; + return res; +} + + +static inline int DIV32_16(long long a, long long b) +{ + long long res; + if (b==0) + { + fprintf(stderr, "DIV32_16: divide by zero: %d/%d\n", (int)a, (int)b); + return 0; + } + if (!VERIFY_INT(a) || !VERIFY_SHORT(b)) + { + fprintf (stderr, "DIV32_16: inputs are not int/short: %d %d\n", (int)a, (int)b); + } + res = a/b; + if (!VERIFY_SHORT(res)) + { + fprintf (stderr, "DIV32_16: output is not short: %d / %d = %d\n", (int)a,(int)b,(int)res); + if (res>32767) + res = 32767; + if (res<-32768) + res = -32768; + } + spx_mips+=20; + return res; +} +static inline int DIV32(long long a, long long b) +{ + long long res; + if (b==0) + { + fprintf(stderr, "DIV32: divide by zero: %d/%d\n", (int)a, (int)b); + return 0; + } + + if (!VERIFY_INT(a) || !VERIFY_INT(b)) + { + fprintf (stderr, "DIV32: inputs are not int/short: %d %d\n", (int)a, (int)b); + } + res = a/b; + if (!VERIFY_INT(res)) + fprintf (stderr, "DIV32: output is not int: %d\n", (int)res); + spx_mips+=36; + return res; +} + + + +#endif diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/fixed_generic.h b/mozilla/zap/zmk/speex-1.1.10/libspeex/fixed_generic.h new file mode 100755 index 00000000000..a9b537714d2 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/fixed_generic.h @@ -0,0 +1,99 @@ +/* Copyright (C) 2003 Jean-Marc Valin */ +/** + @file fixed_generic.h + @brief Generic fixed-point operations +*/ +/* + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 FIXED_GENERIC_H +#define FIXED_GENERIC_H + +#define NEG16(x) (-(x)) +#define NEG32(x) (-(x)) +#define EXTRACT16(x) ((spx_word16_t)x) +#define EXTEND32(x) ((spx_word32_t)x) +#define SHR16(a,shift) ((a) >> (shift)) +#define SHL16(a,shift) ((a) << (shift)) +#define SHR32(a,shift) ((a) >> (shift)) +#define SHL32(a,shift) ((a) << (shift)) +#define PSHR16(a,shift) (SHR16((a)+(1<<((shift)-1)),shift)) +#define PSHR32(a,shift) (SHR32((a)+(1<<((shift)-1)),shift)) +#define SATURATE16(x,a) (((x)>(a) ? (a) : (x)<-(a) ? -(a) : (x))) +#define SATURATE32(x,a) (((x)>(a) ? (a) : (x)<-(a) ? -(a) : (x))) + +#define SHR(a,shift) ((a) >> (shift)) +#define SHL(a,shift) ((spx_word32_t)(a) << (shift)) +#define PSHR(a,shift) (SHR((a)+(1<<((shift)-1)),shift)) +#define SATURATE(x,a) (((x)>(a) ? (a) : (x)<-(a) ? -(a) : (x))) + + +#define ADD16(a,b) ((spx_word16_t)((spx_word16_t)(a)+(spx_word16_t)(b))) +#define SUB16(a,b) ((spx_word16_t)(a)-(spx_word16_t)(b)) +#define ADD32(a,b) ((spx_word32_t)(a)+(spx_word32_t)(b)) +#define SUB32(a,b) ((spx_word32_t)(a)-(spx_word32_t)(b)) +#define ADD64(a,b) ((spx_word64_t)(a)+(spx_word64_t)(b)) + + +/* result fits in 16 bits */ +#define MULT16_16_16(a,b) ((((spx_word16_t)(a))*((spx_word16_t)(b)))) + +/* (spx_word32_t)(spx_word16_t) gives TI compiler a hint that it's 16x16->32 multiply */ +#define MULT16_16(a,b) (((spx_word32_t)(spx_word16_t)(a))*((spx_word32_t)(spx_word16_t)(b))) + +#define MAC16_16(c,a,b) (ADD32((c),MULT16_16((a),(b)))) +#define MULT16_32_Q12(a,b) ADD32(MULT16_16((a),SHR((b),12)), SHR(MULT16_16((a),((b)&0x00000fff)),12)) +#define MULT16_32_Q13(a,b) ADD32(MULT16_16((a),SHR((b),13)), SHR(MULT16_16((a),((b)&0x00001fff)),13)) +#define MULT16_32_Q14(a,b) ADD32(MULT16_16((a),SHR((b),14)), SHR(MULT16_16((a),((b)&0x00003fff)),14)) + +#define MULT16_32_Q11(a,b) ADD32(MULT16_16((a),SHR((b),11)), SHR(MULT16_16((a),((b)&0x000007ff)),11)) +#define MAC16_32_Q11(c,a,b) ADD32(c,ADD32(MULT16_16((a),SHR((b),11)), SHR(MULT16_16((a),((b)&0x000007ff)),11))) + +#define MULT16_32_Q15(a,b) ADD32(MULT16_16((a),SHR((b),15)), SHR(MULT16_16((a),((b)&0x00007fff)),15)) +#define MAC16_32_Q15(c,a,b) ADD32(c,ADD32(MULT16_16((a),SHR((b),15)), SHR(MULT16_16((a),((b)&0x00007fff)),15))) + + +#define MAC16_16_Q11(c,a,b) (ADD32((c),SHR(MULT16_16((a),(b)),11))) +#define MAC16_16_Q13(c,a,b) (ADD32((c),SHR(MULT16_16((a),(b)),13))) + +#define MULT16_16_Q11_32(a,b) (SHR(MULT16_16((a),(b)),11)) +#define MULT16_16_Q13(a,b) (SHR(MULT16_16((a),(b)),13)) +#define MULT16_16_Q14(a,b) (SHR(MULT16_16((a),(b)),14)) +#define MULT16_16_Q15(a,b) (SHR(MULT16_16((a),(b)),15)) + +#define MULT16_16_P13(a,b) (SHR(ADD32(4096,MULT16_16((a),(b))),13)) +#define MULT16_16_P14(a,b) (SHR(ADD32(8192,MULT16_16((a),(b))),14)) +#define MULT16_16_P15(a,b) (SHR(ADD32(16384,MULT16_16((a),(b))),15)) + +#define MUL_16_32_R15(a,bh,bl) ADD32(MULT16_16((a),(bh)), SHR(MULT16_16((a),(bl)),15)) + +#define DIV32_16(a,b) ((spx_word16_t)(((spx_word32_t)(a))/((spx_word16_t)(b)))) +#define DIV32(a,b) (((spx_word32_t)(a))/((spx_word32_t)(b))) + +#endif diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/gain_table.c b/mozilla/zap/zmk/speex-1.1.10/libspeex/gain_table.c new file mode 100755 index 00000000000..a7d2bc242d9 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/gain_table.c @@ -0,0 +1,160 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: gain_table.c + Codebook for 3-tap pitch prediction gain (128 entries) + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. 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. + + 3. The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. +*/ + +const signed char gain_cdbk_nb[384] = { +-32,-32,-32, +-28,-67,-5, +-42,-6,-32, +-57,-10,-54, +-16,27,-41, +19,-19,-40, +-45,24,-21, +-8,-14,-18, +1,14,-58, +-18,-88,-39, +-38,21,-18, +-19,20,-43, +10,17,-48, +-52,-58,-13, +-44,-1,-11, +-12,-11,-34, +14,0,-46, +-37,-35,-34, +-25,44,-30, +6,-4,-63, +-31,43,-41, +-23,30,-43, +-43,26,-14, +-33,1,-13, +-13,18,-37, +-46,-73,-45, +-36,24,-25, +-36,-11,-20, +-25,12,-18, +-36,-69,-59, +-45,6,8, +-22,-14,-24, +-1,13,-44, +-39,-48,-26, +-32,31,-37, +-33,15,-46, +-24,30,-36, +-41,31,-23, +-50,22,-4, +-22,2,-21, +-17,30,-34, +-7,-60,-28, +-38,42,-28, +-44,-11,21, +-16,8,-44, +-39,-55,-43, +-11,-35,26, +-9,0,-34, +-8,121,-81, +7,-16,-22, +-37,33,-31, +-27,-7,-36, +-34,70,-57, +-37,-11,-48, +-40,17,-1, +-33,6,-6, +-9,0,-20, +-21,69,-33, +-29,33,-31, +-55,12,-1, +-33,27,-22, +-50,-33,-47, +-50,54,51, +-1,-5,-44, +-4,22,-40, +-39,-66,-25, +-33,1,-26, +-24,-23,-25, +-11,21,-45, +-25,-45,-19, +-43,105,-16, +5,-21,1, +-16,11,-33, +-13,-99,-4, +-37,33,-15, +-25,37,-63, +-36,24,-31, +-53,-56,-38, +-41,-4,4, +-33,13,-30, +49,52,-94, +-5,-30,-15, +1,38,-40, +-23,12,-36, +-17,40,-47, +-37,-41,-39, +-49,34,0, +-18,-7,-4, +-16,17,-27, +30,5,-62, +4,48,-68, +-43,11,-11, +-18,19,-15, +-23,-62,-39, +-42,10,-2, +-21,-13,-13, +-9,13,-47, +-23,-62,-24, +-44,60,-21, +-18,-3,-52, +-22,22,-36, +-75,57,16, +-19,3,10, +-29,23,-38, +-5,-62,-51, +-51,40,-18, +-42,13,-24, +-34,14,-20, +-56,-75,-26, +-26,32,15, +-26,17,-29, +-7,28,-52, +-12,-30,5, +-5,-48,-5, +2,2,-43, +21,16,16, +-25,-45,-32, +-43,18,-10, +9,0,-1, +-1,7,-30, +19,-48,-4, +-28,25,-29, +-22,0,-31, +-32,17,-10, +-64,-41,-62, +-52,15,16, +-30,-22,-32, +-7,9,-38}; diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/gain_table_lbr.c b/mozilla/zap/zmk/speex-1.1.10/libspeex/gain_table_lbr.c new file mode 100755 index 00000000000..e22de777fcd --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/gain_table_lbr.c @@ -0,0 +1,64 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: gain_table_lbr.c + Codebook for 3-tap pitch prediction gain (32 entries) + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. 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. + + 3. The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. +*/ + +const signed char gain_cdbk_lbr[96] = { +-32,-32,-32, +-31,-58,-16, +-41,-24,-43, +-56,-22,-55, +-13,33,-41, +-4,-39,-9, +-41,15,-12, +-8,-15,-12, +1,2,-44, +-22,-66,-42, +-38,28,-23, +-21,14,-37, +0,21,-50, +-53,-71,-27, +-37,-1,-19, +-19,-5,-28, +6,65,-44, +-33,-48,-33, +-40,57,-14, +-17,4,-45, +-31,38,-33, +-23,28,-40, +-43,29,-12, +-34,13,-23, +-16,15,-27, +-14,-82,-15, +-31,25,-32, +-21,5,-5, +-47,-63,-51, +-46,12,3, +-28,-17,-29, +-10,14,-40}; diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/hexc_10_32_table.c b/mozilla/zap/zmk/speex-1.1.10/libspeex/hexc_10_32_table.c new file mode 100755 index 00000000000..4e258f80318 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/hexc_10_32_table.c @@ -0,0 +1,66 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: hexc_10_32_table.c + Codebook for high-band excitation in SB-CELP mode (4000 bps) + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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. +*/ + +const signed char hexc_10_32_table[320] = { +-3, -2, -1, 0, -4, 5, 35, -40, -9, 13, +-44, 5, -27, -1, -7, 6, -11, 7, -8, 7, +19, -14, 15, -4, 9, -10, 10, -8, 10, -9, +-1, 1, 0, 0, 2, 5, -18, 22, -53, 50, +1, -23, 50, -36, 15, 3, -13, 14, -10, 6, +1, 5, -3, 4, -2, 5, -32, 25, 5, -2, +-1, -4, 1, 11, -29, 26, -6, -15, 30, -18, +0, 15, -17, 40, -41, 3, 9, -2, -2, 3, +-3, -1, -5, 2, 21, -6, -16, -21, 23, 2, +60, 15, 16, -16, -9, 14, 9, -1, 7, -9, +0, 1, 1, 0, -1, -6, 17, -28, 54, -45, +-1, 1, -1, -6, -6, 2, 11, 26, -29, -2, +46, -21, 34, 12, -23, 32, -23, 16, -10, 3, +66, 19, -20, 24, 7, 11, -3, 0, -3, -1, +-50, -46, 2, -18, -3, 4, -1, -2, 3, -3, +-19, 41, -36, 9, 11, -24, 21, -16, 9, -3, +-25, -3, 10, 18, -9, -2, -5, -1, -5, 6, +-4, -3, 2, -26, 21, -19, 35, -15, 7, -13, +17, -19, 39, -43, 48, -31, 16, -9, 7, -2, +-5, 3, -4, 9, -19, 27, -55, 63, -35, 10, +26, -44, -2, 9, 4, 1, -6, 8, -9, 5, +-8, -1, -3, -16, 45, -42, 5, 15, -16, 10, +0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +-16, 24, -55, 47, -38, 27, -19, 7, -3, 1, +16, 27, 20, -19, 18, 5, -7, 1, -5, 2, +-6, 8, -22, 0, -3, -3, 8, -1, 7, -8, +1, -3, 5, 0, 17, -48, 58, -52, 29, -7, +-2, 3, -10, 6, -26, 58, -31, 1, -6, 3, +93, -29, 39, 3, 17, 5, 6, -1, -1, -1, +27, 13, 10, 19, -7, -34, 12, 10, -4, 9, +-76, 9, 8, -28, -2, -11, 2, -1, 3, 1, +-83, 38, -39, 4, -16, -6, -2, -5, 5, -2, +}; diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/hexc_table.c b/mozilla/zap/zmk/speex-1.1.10/libspeex/hexc_table.c new file mode 100755 index 00000000000..b8c623a2a06 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/hexc_table.c @@ -0,0 +1,162 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: hexc_table.c + Codebook for high-band excitation in SB-CELP mode (8000 bps with sign) + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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. +*/ + +const signed char hexc_table[1024] = { +-24, 21, -20, 5, -5, -7, 14, -10, +2, -27, 16, -20, 0, -32, 26, 19, +8, -11, -41, 31, 28, -27, -32, 34, +42, 34, -17, 22, -10, 13, -29, 18, +-12, -26, -24, 11, 22, 5, -5, -5, +54, -68, -43, 57, -25, 24, 4, 4, +26, -8, -12, -17, 54, 30, -45, 1, +10, -15, 18, -41, 11, 68, -67, 37, +-16, -24, -16, 38, -22, 6, -29, 30, +66, -27, 5, 7, -16, 13, 2, -12, +-7, -3, -20, 36, 4, -28, 9, 3, +32, 48, 26, 39, 3, 0, 7, -21, +-13, 5, -82, -7, 73, -20, 34, -9, +-5, 1, -1, 10, -5, -10, -1, 9, +1, -9, 10, 0, -14, 11, -1, -2, +-1, 11, 20, 96, -81, -22, -12, -9, +-58, 9, 24, -30, 26, -35, 27, -12, +13, -18, 56, -59, 15, -7, 23, -15, +-1, 6, -25, 14, -22, -20, 47, -11, +16, 2, 38, -23, -19, -30, -9, 40, +-11, 5, 4, -6, 8, 26, -21, -11, +127, 4, 1, 6, -9, 2, -7, -2, +-3, 7, -5, 10, -19, 7, -106, 91, +-3, 9, -4, 21, -8, 26, -80, 8, +1, -2, -10, -17, -17, -27, 32, 71, +6, -29, 11, -23, 54, -38, 29, -22, +39, 87, -31, -12, -20, 3, -2, -2, +2, 20, 0, -1, -35, 27, 9, -6, +-12, 3, -12, -6, 13, 1, 14, -22, +-59, -15, -17, -25, 13, -7, 7, 3, +0, 1, -7, 6, -3, 61, -37, -23, +-23, -29, 38, -31, 27, 1, -8, 2, +-27, 23, -26, 36, -34, 5, 24, -24, +-6, 7, 3, -59, 78, -62, 44, -16, +1, 6, 0, 17, 8, 45, 0, -110, +6, 14, -2, 32, -77, -56, 62, -3, +3, -13, 4, -16, 102, -15, -36, -1, +9, -113, 6, 23, 0, 9, 9, 5, +-8, -1, -14, 5, -12, 121, -53, -27, +-8, -9, 22, -13, 3, 2, -3, 1, +-2, -71, 95, 38, -19, 15, -16, -5, +71, 10, 2, -32, -13, -5, 15, -1, +-2, -14, -85, 30, 29, 6, 3, 2, +0, 0, 0, 0, 0, 0, 0, 0, +2, -65, -56, -9, 18, 18, 23, -14, +-2, 0, 12, -29, 26, -12, 1, 2, +-12, -64, 90, -6, 4, 1, 5, -5, +-110, -3, -31, 22, -29, 9, 0, 8, +-40, -5, 21, -5, -5, 13, 10, -18, +40, 1, 35, -20, 30, -28, 11, -6, +19, 7, 14, 18, -64, 9, -6, 16, +51, 68, 8, 16, 12, -8, 0, -9, +20, -22, 25, 7, -4, -13, 41, -35, +93, -18, -54, 11, -1, 1, -9, 4, +-66, 66, -31, 20, -22, 25, -23, 11, +10, 9, 19, 15, 11, -5, -31, -10, +-23, -28, -6, -6, -3, -4, 5, 3, +-28, 22, -11, -42, 25, -25, -16, 41, +34, 47, -6, 2, 42, -19, -22, 5, +-39, 32, 6, -35, 22, 17, -30, 8, +-26, -11, -11, 3, -12, 33, 33, -37, +21, -1, 6, -4, 3, 0, -5, 5, +12, -12, 57, 27, -61, -3, 20, -17, +2, 0, 4, 0, -2, -33, -58, 81, +-23, 39, -10, -5, 2, 6, -7, 5, +4, -3, -2, -13, -23, -72, 107, 15, +-5, 0, -7, -3, -6, 5, -4, 15, +47, 12, -31, 25, -16, 8, 22, -25, +-62, -56, -18, 14, 28, 12, 2, -11, +74, -66, 41, -20, -7, 16, -20, 16, +-8, 0, -16, 4, -19, 92, 12, -59, +-14, -39, 49, -25, -16, 23, -27, 19, +-3, -33, 19, 85, -29, 6, -7, -10, +16, -7, -12, 1, -6, 2, 4, -2, +64, 10, -25, 41, -2, -31, 15, 0, +110, 50, 69, 35, 28, 19, -10, 2, +-43, -49, -56, -15, -16, 10, 3, 12, +-1, -8, 1, 26, -12, -1, 7, -11, +-27, 41, 25, 1, -11, -18, 22, -7, +-1, -47, -8, 23, -3, -17, -7, 18, +-125, 59, -5, 3, 18, 1, 2, 3, +27, -35, 65, -53, 50, -46, 37, -21, +-28, 7, 14, -37, -5, -5, 12, 5, +-8, 78, -19, 21, -6, -16, 8, -7, +5, 2, 7, 2, 10, -6, 12, -60, +44, 11, -36, -32, 31, 0, 2, -2, +2, 1, -3, 7, -10, 17, -21, 10, +6, -2, 19, -2, 59, -38, -86, 38, +8, -41, -30, -45, -33, 7, 15, 28, +29, -7, 24, -40, 7, 7, 5, -2, +9, 24, -23, -18, 6, -29, 30, 2, +28, 49, -11, -46, 10, 43, -13, -9, +-1, -3, -7, -7, -17, -6, 97, -33, +-21, 3, 5, 1, 12, -43, -8, 28, +7, -43, -7, 17, -20, 19, -1, 2, +-13, 9, 54, 34, 9, -28, -11, -9, +-17, 110, -59, 44, -26, 0, 3, -12, +-47, 73, -34, -43, 38, -33, 16, -5, +-46, -4, -6, -2, -25, 19, -29, 28, +-13, 5, 14, 27, -40, -43, 4, 32, +-13, -2, -35, -4, 112, -42, 9, -12, +37, -28, 17, 14, -19, 35, -39, 23, +3, -14, -1, -57, -5, 94, -9, 3, +-39, 5, 30, -10, -32, 42, -13, -14, +-97, -63, 30, -9, 1, -7, 12, 5, +20, 17, -9, -36, -30, 25, 47, -9, +-15, 12, -22, 98, -8, -50, 15, -27, +21, -16, -11, 2, 12, -10, 10, -3, +33, 36, -96, 0, -17, 31, -9, 9, +3, -20, 13, -11, 8, -4, 10, -10, +9, 1, 112, -70, -27, 5, -21, 2, +-57, -3, -29, 10, 19, -21, 21, -10, +-66, -3, 91, -35, 30, -12, 0, -7, +59, -28, 26, 2, 14, -18, 1, 1, +11, 17, 20, -54, -59, 27, 4, 29, +32, 5, 19, 12, -4, 1, 7, -10, +5, -2, 10, 0, 23, -5, 28, -104, +46, 11, 16, 3, 29, 1, -8, -14, +1, 7, -50, 88, -62, 26, 8, -17, +-14, 50, 0, 32, -12, -3, -27, 18, +-8, -5, 8, 3, -20, -11, 37, -12, +9, 33, 46, -101, -1, -4, 1, 6, +-1, 28, -42, -15, 16, 5, -1, -2, +-55, 85, 38, -9, -4, 11, -2, -9, +-6, 3, -20, -10, -77, 89, 24, -3, +-104, -57, -26, -31, -20, -6, -9, 14, +20, -23, 46, -15, -31, 28, 1, -15, +-2, 6, -2, 31, 45, -76, 23, -25, +}; diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/high_lsp_tables.c b/mozilla/zap/zmk/speex-1.1.10/libspeex/high_lsp_tables.c new file mode 100755 index 00000000000..6bc6634fcb1 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/high_lsp_tables.c @@ -0,0 +1,163 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: high_lsp_tables.c + Codebooks for high-band LSPs in SB-CELP mode + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. 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. + + 3. The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. +*/ + +const signed char high_lsp_cdbk[512]={ +39,12,-14,-20,-29,-61,-67,-76, +-32,-71,-67,68,77,46,34,5, +-13,-48,-46,-72,-81,-84,-60,-58, +-40,-28,82,93,68,45,29,3, +-19,-47,-28,-43,-35,-30,-8,-13, +-39,-91,-91,-123,-96,10,10,-6, +-18,-55,-60,-91,-56,-36,-27,-16, +-48,-75,40,28,-10,-28,35,9, +37,19,1,-20,-31,-41,-18,-25, +-35,-68,-80,45,27,-1,47,13, +0,-29,-35,-57,-50,-79,-73,-38, +-19,5,35,14,-10,-23,16,-8, +5,-24,-40,-62,-23,-27,-22,-16, +-18,-46,-72,-77,43,21,33,1, +-80,-70,-70,-64,-56,-52,-39,-33, +-31,-38,-19,-19,-15,32,33,-2, +7,-15,-15,-24,-23,-33,-41,-56, +-24,-57,5,89,64,41,27,5, +-9,-47,-60,-97,-97,-124,-20,-9, +-44,-73,31,29,-4,64,48,7, +-35,-57,0,-3,-26,-47,-3,-6, +-40,-76,-79,-48,12,81,55,10, +9,-24,-43,-73,-57,-69,16,5, +-28,-53,18,29,20,0,-4,-11, +6,-13,23,7,-17,-35,-37,-37, +-30,-68,-63,6,24,-9,-14,3, +21,-13,-27,-57,-49,-80,-24,-41, +-5,-16,-5,1,45,25,12,-7, +3,-15,-6,-16,-15,-8,6,-13, +-42,-81,-80,-87,14,1,-10,-3, +-43,-69,-46,-24,-28,-29,36,6, +-43,-56,-12,12,54,79,43,9, +54,22,2,8,-12,-43,-46,-52, +-38,-69,-89,-5,75,38,33,5, +-13,-53,-62,-87,-89,-113,-99,-55, +-34,-37,62,55,33,16,21,-2, +-17,-46,-29,-38,-38,-48,-39,-42, +-36,-75,-72,-88,-48,-30,21,2, +-15,-57,-64,-98,-84,-76,25,1, +-46,-80,-12,18,-7,3,34,6, +38,31,23,4,-1,20,14,-15, +-43,-78,-91,-24,14,-3,54,16, +0,-27,-28,-44,-56,-83,-92,-89, +-3,34,56,41,36,22,20,-8, +-7,-35,-42,-62,-49,3,12,-10, +-50,-87,-96,-66,92,70,38,9, +-70,-71,-62,-42,-39,-43,-11,-7, +-50,-79,-58,-50,-31,32,31,-6, +-4,-25,7,-17,-38,-70,-58,-27, +-43,-83,-28,59,36,20,31,2, +-27,-71,-80,-109,-98,-75,-33,-32, +-31,-2,33,15,-6,43,33,-5, +0,-22,-10,-27,-34,-49,-11,-20, +-41,-91,-100,-121,-39,57,41,10, +-19,-50,-38,-59,-60,-70,-18,-20, +-8,-31,-8,-15,1,-14,-26,-25, +33,21,32,17,1,-19,-19,-26, +-58,-81,-35,-22,45,30,11,-11, +3,-26,-48,-87,-67,-83,-58,3, +-1,-26,-20,44,10,25,39,5, +-9,-35,-27,-38,7,10,4,-9, +-42,-85,-102,-127,52,44,28,10, +-47,-61,-40,-39,-17,-1,-10,-33, +-42,-74,-48,21,-4,70,52,10}; + + +const signed char high_lsp_cdbk2[512]={ +-36,-62,6,-9,-10,-14,-56,23, +1,-26,23,-48,-17,12,8,-7, +23,29,-36,-28,-6,-29,-17,-5, +40,23,10,10,-46,-13,36,6, +4,-30,-29,62,32,-32,-1,22, +-14,1,-4,-22,-45,2,54,4, +-30,-57,-59,-12,27,-3,-31,8, +-9,5,10,-14,32,66,19,9, +2,-25,-37,23,-15,18,-38,-31, +5,-9,-21,15,0,22,62,30, +15,-12,-14,-46,77,21,33,3, +34,29,-19,50,2,11,9,-38, +-12,-37,62,1,-15,54,32,6, +2,-24,20,35,-21,2,19,24, +-13,55,4,9,39,-19,30,-1, +-21,73,54,33,8,18,3,15, +6,-19,-47,6,-3,-48,-50,1, +26,20,8,-23,-50,65,-14,-55, +-17,-31,-37,-28,53,-1,-17,-53, +1,57,11,-8,-25,-30,-37,64, +5,-52,-45,15,23,31,15,14, +-25,24,33,-2,-44,-56,-18,6, +-21,-43,4,-12,17,-37,20,-10, +34,15,2,15,55,21,-11,-31, +-6,46,25,16,-9,-25,-8,-62, +28,17,20,-32,-29,26,30,25, +-19,2,-16,-17,26,-51,2,50, +42,19,-66,23,29,-2,3,19, +-19,-37,32,15,6,30,-34,13, +11,-5,40,31,10,-42,4,-9, +26,-9,-70,17,-2,-23,20,-22, +-55,51,-24,-31,22,-22,15,-13, +3,-10,-28,-16,56,4,-63,11, +-18,-15,-18,-38,-35,16,-7,34, +-1,-21,-49,-47,9,-37,7,8, +69,55,20,6,-33,-45,-10,-9, +6,-9,12,71,15,-3,-42,-7, +-24,32,-35,-2,-42,-17,-5,0, +-2,-33,-54,13,-12,-34,47,23, +19,55,7,-8,74,31,14,16, +-23,-26,19,12,-18,-49,-28,-31, +-20,2,-14,-20,-47,78,40,13, +-23,-11,21,-6,18,1,47,5, +38,35,32,46,22,8,13,16, +-14,18,51,19,40,39,11,-26, +-1,-17,47,2,-53,-15,31,-22, +38,21,-15,-16,5,-33,53,15, +-38,86,11,-3,-24,49,13,-4, +-11,-18,28,20,-12,-27,-26,35, +-25,-35,-3,-20,-61,30,10,-55, +-12,-22,-52,-54,-14,19,-32,-12, +45,15,-8,-48,-9,11,-32,8, +-16,-34,-13,51,18,38,-2,-32, +-17,22,-2,-18,-28,-70,59,27, +-28,-19,-10,-20,-9,-9,-8,-21, +21,-8,35,-2,45,-3,-9,12, +0,30,7,-39,43,27,-38,-91, +30,26,19,-55,-4,63,14,-17, +13,9,13,2,7,4,6,61, +72,-1,-17,29,-1,-22,-17,8, +-28,-37,63,44,41,3,2,14, +9,-6,75,-8,-7,-12,-15,-12, +13,9,-4,30,-22,-65,15,0, +-45,4,-4,1,5,22,11,23}; diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/jitter.c b/mozilla/zap/zmk/speex-1.1.10/libspeex/jitter.c new file mode 100755 index 00000000000..d40b0279f9e --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/jitter.c @@ -0,0 +1,315 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: speex_jitter.h + + Adaptive jitter buffer for Speex + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 + +#ifndef NULL +#define NULL 0 +#endif + +#include "misc.h" +#include +#include +#include +#include + +#define LATE_BINS 4 + +void speex_jitter_init(SpeexJitter *jitter, void *decoder, int sampling_rate) +{ + int i; + for (i=0;ilen[i]=-1; + jitter->timestamp[i]=-1; + } + + jitter->dec = decoder; + speex_decoder_ctl(decoder, SPEEX_GET_FRAME_SIZE, &jitter->frame_size); + jitter->frame_time = 1000*jitter->frame_size / sampling_rate; + + speex_bits_init(&jitter->current_packet); + jitter->valid_bits = 0; + + jitter->buffer_size = 4; + + jitter->pointer_timestamp = -jitter->frame_time * jitter->buffer_size; + jitter->reset_state = 1; + jitter->lost_count = 0; + jitter->loss_rate = 0; +} + +void speex_jitter_destroy(SpeexJitter *jitter) +{ +} + + +void speex_jitter_put(SpeexJitter *jitter, char *packet, int len, int timestamp) +{ + int i,j; + int arrival_margin; + + if (jitter->reset_state) + { + jitter->reset_state=0; + jitter->pointer_timestamp = timestamp-jitter->frame_time * jitter->buffer_size; + for (i=0;ishortterm_margin[i] = 0; + jitter->longterm_margin[i] = 0; + } + for (i=0;ilen[i]=-1; + jitter->timestamp[i]=-1; + } + fprintf(stderr, "reset to %d\n", timestamp); + } + + /* Cleanup buffer (remove old packets that weren't played) */ + for (i=0;itimestamp[i]pointer_timestamp) + { + jitter->len[i]=-1; + /*if (jitter->timestamp[i] != -1) + fprintf (stderr, "discarding %d %d\n", jitter->timestamp[i], jitter->pointer_timestamp);*/ + } + } + + /*Find an empty slot in the buffer*/ + for (i=0;ilen[i]==-1) + break; + } + + /*fprintf(stderr, "%d %d %f\n", timestamp, jitter->pointer_timestamp, jitter->drift_average);*/ + if (i==SPEEX_JITTER_MAX_BUFFER_SIZE) + { + int earliest=jitter->timestamp[0]; + i=0; + for (j=1;jtimestamp[j]timestamp[j]; + i=j; + } + } + /*fprintf (stderr, "Buffer is full, discarding earliest frame %d (currently at %d)\n", timestamp, jitter->pointer_timestamp);*/ + /*No place left in the buffer*/ + + /*skip some frame(s) */ + /*return;*/ + } + + /* Copy packet in buffer */ + if (len>SPEEX_JITTER_MAX_PACKET_SIZE) + len=SPEEX_JITTER_MAX_PACKET_SIZE; + for (j=0;jbuf[i][j]=packet[j]; + jitter->timestamp[i]=timestamp; + jitter->len[i]=len; + + /* Don't count late packets when adjusting the synchro (we're taking care of them elsewhere) */ + /*if (timestamp <= jitter->pointer_timestamp) + { + fprintf (stderr, "frame for timestamp %d arrived too late (at time %d)\n", timestamp, jitter->pointer_timestamp); + }*/ + + /* Adjust the buffer size depending on network conditions */ + arrival_margin = (timestamp - jitter->pointer_timestamp - jitter->frame_time); + + if (arrival_margin >= -LATE_BINS*jitter->frame_time) + { + int int_margin; + for (i=0;ishortterm_margin[i] *= .98; + jitter->longterm_margin[i] *= .995; + } + int_margin = (arrival_margin + LATE_BINS*jitter->frame_time)/jitter->frame_time; + if (int_margin>MAX_MARGIN-1) + int_margin = MAX_MARGIN-1; + if (int_margin>=0) + { + jitter->shortterm_margin[int_margin] += .02; + jitter->longterm_margin[int_margin] += .005; + } + } + + /*fprintf (stderr, "margin : %d %d %f %f %f %f\n", arrival_margin, jitter->buffer_size, 100*jitter->loss_rate, 100*jitter->late_ratio, 100*jitter->ontime_ratio, 100*jitter->early_ratio);*/ +} + +void speex_jitter_get(SpeexJitter *jitter, short *out, int *current_timestamp) +{ + int i; + int ret; + float late_ratio_short; + float late_ratio_long; + float ontime_ratio_short; + float ontime_ratio_long; + float early_ratio_short; + float early_ratio_long; + + late_ratio_short = 0; + late_ratio_long = 0; + for (i=0;ishortterm_margin[i]; + late_ratio_long += jitter->longterm_margin[i]; + } + ontime_ratio_short = jitter->shortterm_margin[LATE_BINS]; + ontime_ratio_long = jitter->longterm_margin[LATE_BINS]; + early_ratio_short = early_ratio_long = 0; + for (i=LATE_BINS+1;ishortterm_margin[i]; + early_ratio_long += jitter->longterm_margin[i]; + } + if (0&&jitter->pointer_timestamp%1000==0) + { + fprintf (stderr, "%f %f %f %f %f %f\n", early_ratio_short, early_ratio_long, ontime_ratio_short, ontime_ratio_long, late_ratio_short, late_ratio_long); + /*fprintf (stderr, "%f %f\n", early_ratio_short + ontime_ratio_short + late_ratio_short, early_ratio_long + ontime_ratio_long + late_ratio_long);*/ + } + + if (late_ratio_short > .1 || late_ratio_long > .03) + { + jitter->shortterm_margin[MAX_MARGIN-1] += jitter->shortterm_margin[MAX_MARGIN-2]; + jitter->longterm_margin[MAX_MARGIN-1] += jitter->longterm_margin[MAX_MARGIN-2]; + for (i=MAX_MARGIN-2;i>=0;i--) + { + jitter->shortterm_margin[i+1] = jitter->shortterm_margin[i]; + jitter->longterm_margin[i+1] = jitter->longterm_margin[i]; + } + jitter->shortterm_margin[0] = 0; + jitter->longterm_margin[0] = 0; + /*fprintf (stderr, "interpolate frame\n");*/ + speex_decode_int(jitter->dec, NULL, out); + if (current_timestamp) + *current_timestamp = jitter->pointer_timestamp; + return; + } + + /* Increment timestamp */ + jitter->pointer_timestamp += jitter->frame_time; + + if (late_ratio_short + ontime_ratio_short < .005 && late_ratio_long + ontime_ratio_long < .01 && early_ratio_short > .8) + { + jitter->shortterm_margin[0] += jitter->shortterm_margin[1]; + jitter->longterm_margin[0] += jitter->longterm_margin[1]; + for (i=1;ishortterm_margin[i] = jitter->shortterm_margin[i+1]; + jitter->longterm_margin[i] = jitter->longterm_margin[i+1]; + } + jitter->shortterm_margin[MAX_MARGIN-1] = 0; + jitter->longterm_margin[MAX_MARGIN-1] = 0; + /*fprintf (stderr, "drop frame\n");*/ + jitter->pointer_timestamp += jitter->frame_time; + } + + if (current_timestamp) + *current_timestamp = jitter->pointer_timestamp; + + /* Send zeros while we fill in the buffer */ + if (jitter->pointer_timestamp<0) + { + for (i=0;iframe_size;i++) + out[i]=0; + return; + } + + /* Search the buffer for a packet with the right timestamp */ + for (i=0;ilen[i]!=-1 && jitter->timestamp[i]==jitter->pointer_timestamp) + break; + } + + if (i==SPEEX_JITTER_MAX_BUFFER_SIZE) + { + /* No packet found */ + if (jitter->valid_bits) + { + /* Try decoding last received packet */ + ret = speex_decode_int(jitter->dec, &jitter->current_packet, out); + if (ret == 0) + { + jitter->lost_count = 0; + return; + } else { + jitter->valid_bits = 0; + } + } + + /*fprintf (stderr, "lost/late frame %d\n", jitter->pointer_timestamp);*/ + /*Packet is late or lost*/ + speex_decode_int(jitter->dec, NULL, out); + jitter->lost_count++; + if (jitter->lost_count>=25) + { + jitter->lost_count = 0; + jitter->reset_state = 1; + speex_decoder_ctl(jitter->dec, SPEEX_RESET_STATE, NULL); + } + jitter->loss_rate = .999*jitter->loss_rate + .001; + } else { + jitter->lost_count = 0; + /* Found the right packet */ + speex_bits_read_from(&jitter->current_packet, jitter->buf[i], jitter->len[i]); + jitter->len[i]=-1; + /* Decode packet */ + ret = speex_decode_int(jitter->dec, &jitter->current_packet, out); + if (ret == 0) + { + jitter->valid_bits = 1; + } else { + /* Error while decoding */ + for (i=0;iframe_size;i++) + out[i]=0; + } + jitter->loss_rate = .999*jitter->loss_rate; + } + + +} + +int speex_jitter_get_pointer_timestamp(SpeexJitter *jitter) +{ + return jitter->pointer_timestamp; +} diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/lbr_48k_tables.c b/mozilla/zap/zmk/speex-1.1.10/libspeex/lbr_48k_tables.c new file mode 100755 index 00000000000..493de765ad1 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/lbr_48k_tables.c @@ -0,0 +1,678 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: lbr_48k_tables.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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 + + +int dummy_epic_48k_variable=0; +#ifdef EPIC_48K + +const signed char gain_cdbk_ulbr[192] = { +-31, -48, -30, +-19, -10, -18, +-33, -22, -45, +-5, -56, -43, +-30, -56, -3, +-59, -17, -52, +-41, -60, -58, +-64, -47, -22, +-30, -31, -31, +-29, -14, -31, +-22, -37, -58, +-31, -44, 13, +-37, 0, 1, +-46, -55, -35, +-56, -14, -53, +-8, 1, -36, +-29, -15, -27, +-29, -39, -28, +-43, -5, 3, +-51, -27, -54, +10, -46, -36, +3, -3, -42, +-27, 16, -22, +-34, -52, 13, +-31, -21, -28, +-34, -45, -40, +-20, -48, 4, +-40, -27, 16, +-6, 11, -44, +-35, 12, -5, +19, -33, -37, +-29, 18, -32, +-29, -23, -19, +16, -47, -28, +-34, -30, 17, +-20, 2, -26, +-38, -40, -36, +15, -14, -40, +-39, 14, -9, +-15, 25, -39, +-26, 19, -32, +-39, 17, -14, +10, -36, -26, +14, -13, -40, +-29, -21, -12, +-8, 19, -39, +-36, -18, 15, +-32, -38, -38, +-19, 4, -23, +-38, -7, 11, +9, -10, -39, +-37, 24, -19, +-34, -5, -8, +-20, 23, -41, +-4, 17, -31, +-17, -26, -26, +-24, 28, -36, +-7, 15, -39, +-42, 16, -11, +-29, 14, -6, +-36, 28, -27, +-21, 5, -26, +11, -9, -39, +-38, -7, 13, +}; + + +const signed char exc_12_32_table[384] = { +34, 55, 9, 55, 4, 44, -2, 25, 4, -6, 13, -22, +20, 26, -13, -56, -37, 18, 5, 28, 4, 10, 6, -7, +37, -24, -31, 22, 12, -6, -4, -7, 2, 0, -3, -2, +-16, -13, -1, 9, -2, 4, 6, 5, -3, 3, 8, -1, +-1, -6, -2, -1, 8, 24, 19, 33, -73, -53, 6, -18, +14, 7, 11, 8, -33, -94, -5, 7, 0, 44, 1, 19, +-9, -7, -34, -16, 8, 2, 5, 0, 3, 1, -2, 3, +-22, 6, -2, 12, 16, 30, 39, 25, 25, 2, 10, -2, +-1, -40, -6, -51, -5, -48, -9, -33, -14, -1, -24, 15, +104, 39, 12, -9, -20, -12, -30, -10, -31, -7, -30, -8, +-71, -53, -4, -11, 9, -10, 7, -10, 10, -1, 11, 8, +24, 14, 6, -3, 10, 8, 8, 11, -6, 11, 0, -2, +-6, -2, 1, -1, -3, 8, -41, 27, 57, -7, 11, -16, +-61, 50, 10, -10, 4, -13, 14, -7, 1, 5, -4, 4, +0, 2, -1, -2, -1, 1, 1, 0, -1, -1, -2, -3, +-3, -15, 69, 60, 10, -10, -10, -29, -21, -7, -16, 2, +24, -32, 24, -18, -14, -2, -11, 11, -6, 10, 1, 3, +24, -10, 14, 18, -13, 17, -16, 4, -3, -21, -3, -11, +-19, 12, -14, 26, 20, -9, 24, -15, 18, 1, -32, -2, +-1, 8, -3, 4, 11, -47, 7, 46, -4, -10, -10, -2, +-24, 29, -33, 6, -20, -3, 0, -12, 5, -30, 8, -13, +28, 9, 5, -11, 0, -14, -13, -22, -12, -8, -4, 1, +-6, 28, 45, -18, -31, -5, 1, 2, 1, 5, 0, -3, +-19, -10, 10, 27, 8, -16, -28, -9, 2, -5, 8, -1, +100, -49, 4, -43, 25, -7, 1, 9, -13, 13, -18, 13, +-1, -1, 0, 2, -2, -8, 9, -46, -7, 70, 23, 7, +-103, 20, 8, 42, -5, 21, -4, 4, 1, -8, 16, -8, +3, 3, 8, 4, 7, -3, -3, -4, 9, 6, 2, 13, +6, 3, -15, 11, -43, 31, 40, -13, 12, -21, -2, -3, +-10, -9, 16, -35, 31, -3, -12, 8, -34, 7, 12, 22, +-3, -4, -7, -12, 24, 53, -19, -43, 4, -3, -4, 6, +-18, -30, -58, -17, -11, 17, 23, 34, 30, 28, 28, 15, +}; + + +const signed char cdbk_lsp_vlbr[5120]={ +23, 34, 108, 100, 102, 82, 69, 48, 52, 25, +0, -37, -55, -78, -111, -79, 58, 57, 45, 32, +27, -9, -12, -14, -41, -29, -17, -41, 44, 35, +-24, -68, -72, 61, 100, 73, 100, 80, 70, 37, +12, -5, 22, 11, -10, -40, -33, -17, 19, 12, +-20, -57, -94, -92, 56, 71, 48, 31, 22, -5, +41, 28, 6, -6, -12, -39, -18, -16, -30, -23, +65, 54, 41, 28, 23, 9, 26, 18, 22, 6, +17, -16, -33, -54, -87, -79, 8, -8, 44, 35, +-20, -62, -78, 22, 78, 47, 44, 33, 26, 14, +8, 1, 45, 47, 72, 68, 55, 31, 36, 17, +-27, -68, -86, -65, -10, 23, 8, -22, -31, 25, +-4, -38, -55, -68, -96, -118, -39, 30, 28, 31, +-21, -66, -47, 99, 91, 68, 78, 56, 64, 36, +33, 22, 13, -13, -36, -22, 44, 37, 54, 33, +-31, -76, -106, -100, -5, 21, 7, -17, 13, 48, +-26, -65, -84, -84, -46, 67, 97, 66, 58, 31, +-20, -52, -32, -20, 3, 16, 27, 40, 54, 29, +-6, -35, -56, -64, -8, -31, -36, 21, 26, -3, +32, 23, 1, -23, -19, -44, -45, -7, 10, -10, +-24, -55, 2, 67, 72, 85, 90, 74, 77, 45, +-21, -58, -45, -49, 16, 34, 13, -15, -16, 16, +8, -31, -34, -61, -83, 10, 24, 8, 56, 25, +-8, -49, -74, -95, -123, -77, 6, 40, 46, 42, +-21, -60, -59, -34, -12, 27, 8, -19, -48, -17, +-25, -66, -78, -73, -81, -16, 14, 0, -2, 33, +78, 79, 69, 49, 44, 32, 50, 44, 46, 22, +24, 9, -4, -18, -37, -56, 22, 34, 22, 11, +-19, -59, -85, -41, 46, 72, 60, 33, 29, -3, +-21, -66, -70, 65, 92, 57, 61, 41, 40, 23, +-4, -41, -60, -72, -102, -106, 4, 56, 57, 31, +-5, -48, -62, -91, -109, 1, 76, 54, 72, 39, +-21, -61, -86, -46, -34, -39, 42, 25, 15, 12, +5, -16, -36, -56, 5, 18, 11, 13, 52, 23, +12, -6, 30, 40, 59, 40, 27, 8, 19, 6, +25, 8, -9, -19, -25, -53, -40, -38, -46, -4, +-17, -59, -83, 2, 58, 29, 18, -2, -17, -5, +-35, -80, -111, -117, -41, -9, 14, 23, 36, 56, +48, 67, 93, 71, 77, 91, 110, 95, 83, 47, +-25, -62, -97, -93, 76, 96, 73, 52, 61, 28, +-9, -55, -46, 49, 33, 8, 1, -25, 28, 23, +-10, -47, -60, -45, -62, -58, 56, 57, 48, 28, +34, 12, -9, 0, 34, 4, 6, 11, 3, -18, +21, -9, -16, -13, -39, -41, 14, -8, 33, 28, +-7, -49, -61, 15, 34, 3, 2, -13, -28, -17, +-14, -50, -46, -65, -76, -13, -10, -29, -30, 22, +-28, -68, -97, -98, -8, 38, 36, 26, 25, 15, +6, -33, -9, 1, -28, -11, -19, -24, 61, 36, +-15, -60, -19, 81, 58, 52, 42, 28, 66, 36, +-15, -52, -71, -15, 11, -13, 38, 28, 11, -4, +34, 1, -9, -27, -57, -19, 36, 6, 14, 0, +-1, -43, -14, 16, -12, -5, -14, -29, -33, -32, +-13, -57, -75, -100, -111, 1, 2, 13, 48, 33, +12, 16, 100, 85, 69, 49, 40, 29, 46, 23, +-4, -26, -41, -44, -7, -26, -39, -27, 18, 0, +-4, -47, -51, 17, 7, -19, 13, -10, -16, 9, +-24, -63, -93, -53, 25, 14, 73, 51, 35, 8, +-34, -77, -106, -83, -51, -47, 2, 12, 41, 53, +-13, -47, -67, -44, 42, 20, 24, 33, 21, -3, +11, -15, -29, -51, -79, -88, 22, 56, 43, 20, +11, -22, -37, -1, 61, 40, 28, 24, 22, -6, +-3, -33, -50, -66, -93, -100, -16, -16, 3, 41, +-18, -58, -82, -5, 95, 78, 56, 39, 30, 1, +-6, -47, -28, -26, -36, 49, 55, 51, 71, 35, +-6, -50, -42, -4, -32, -1, -1, -18, 67, 40, +-23, -63, -56, -48, -32, 0, -14, -43, -46, 25, +-17, -61, -63, 13, -1, 28, 23, 10, 67, 36, +45, 92, 124, 111, 108, 86, 77, 56, 57, 28, +50, 35, 13, 3, -2, -32, 3, 14, 6, -8, +12, -17, -24, -42, -67, -23, 67, 49, 64, 38, +-21, -60, -90, -45, 32, 6, 7, -3, -15, 9, +-16, -62, -73, 50, 46, 18, 7, -13, 63, 39, +19, -16, -19, 20, 5, -15, 16, -9, 5, 8, +-11, -46, -42, -39, -55, -68, -62, -27, -18, 23, +-23, -61, -67, -71, -29, 44, 32, 10, -15, -12, +-6, -45, -43, -40, -67, -22, 42, 19, 61, 38, +9, -13, -38, -37, 40, 30, 15, 9, 11, -16, +0, -18, -29, -34, -17, -44, -50, -3, 47, 15, +-3, -46, -26, 20, -10, 16, 20, -2, 43, 18, +-23, -46, 46, 91, 99, 100, 99, 79, 72, 42, +-1, -44, -33, -36, -56, 22, 17, 4, 71, 37, +0, -38, -49, 0, -1, -30, -21, -35, -44, -6, +-32, -74, -101, -98, -14, -21, -23, 7, 26, 45, +8, -28, -44, -63, -96, -84, 34, 21, 13, 23, +10, -24, -38, -17, -29, -53, -16, -41, -14, 23, +-19, -61, -76, -12, 97, 99, 79, 60, 59, 25, +5, -11, -26, -54, -26, -8, -13, 3, 25, 4, +17, 16, 4, -24, -1, 42, 60, 63, 70, 37, +10, -27, -22, -43, -62, -7, -16, 10, 75, 40, +-26, -64, -96, -106, -3, 73, 73, 46, 55, 29, +-2, -45, -43, 45, 46, 17, 37, 10, 30, 32, +21, -2, -18, -28, -47, -63, -38, -56, -3, 27, +-17, -48, -9, 9, 3, 28, 50, 58, 73, 44, +8, -14, -32, -56, -81, -106, -35, 41, 53, 26, +1, -38, -51, -66, -100, -61, 32, 17, 66, 42, +17, 5, -6, -21, -26, -52, -36, 23, 56, 22, +6, -20, -31, -22, -19, -48, 16, 38, 22, -2, +-25, -67, -93, -51, 82, 62, 71, 69, 63, 35, +-12, -51, -71, -60, -76, -91, -14, 41, 35, 20, +-16, -31, 22, 32, 55, 80, 98, 91, 85, 49, +-21, -63, -92, -6, 57, 27, 36, 11, 60, 39, +-7, -45, -67, -81, -114, -110, 0, 24, 23, 45, +-18, -55, -61, -56, -60, -64, -32, -2, 58, 36, +-3, -33, -51, -24, 19, -10, -19, 4, 14, -15, +-19, -59, -81, -12, 7, -12, 36, 16, 48, 36, +17, -13, -32, -49, -78, -95, -1, -3, -10, 25, +15, 5, 41, 59, 108, 101, 103, 81, 70, 35, +-14, -52, -37, 15, 93, 83, 66, 50, 47, 15, +-3, -31, -49, -52, -9, -31, -10, 37, 62, 27, +-15, -56, -82, -17, 75, 56, 36, 22, 7, -16, +-24, -63, -93, -84, 25, 94, 98, 65, 60, 31, +-2, -45, -39, -61, -61, 48, 35, 32, 54, 18, +-19, -51, -45, -57, -28, -8, 10, 14, 38, 26, +-2, -46, -38, 45, 26, 22, 48, 21, 63, 40, +-22, -61, -73, -75, -67, -31, 13, 18, 51, 34, +-12, -2, -1, -17, -3, -27, -3, 6, -1, -15, +-16, -59, -78, 10, 36, 9, 4, -18, 33, 22, +-25, -62, -97, -107, 39, 87, 69, 46, 42, 12, +11, -7, -30, -36, 19, 2, -10, -7, -4, -24, +11, -8, 25, 28, 28, 5, -4, -10, 5, -2, +-10, -48, -37, -17, -38, -9, -2, -19, -30, -22, +-23, -61, -79, -81, -2, 15, -4, 17, 20, 2, +25, -14, -3, -10, -38, 1, 14, -14, -9, -27, +2, -18, -38, -36, -11, -39, -36, -28, -36, -11, +32, 59, 127, 124, 127, 108, 91, 68, 64, 34, +3, -32, -37, -10, -25, -46, 12, 1, -17, -24, +-29, -69, -102, -100, 2, -7, 11, 14, 1, 31, +30, -6, -4, -16, -44, -5, 3, -9, 66, 40, +-9, -45, -52, -5, 37, 19, 26, 6, 51, 32, +-31, -73, -96, -45, -25, -37, -15, -16, 32, 39, +3, -15, 18, 21, 28, 33, 58, 58, 69, 42, +-31, -73, -99, -99, -48, 14, 21, 5, 2, 39, +7, -35, -20, 29, 2, -8, -8, -28, 38, 26, +-5, -39, -64, -36, 15, -15, -11, -21, -23, 5, +-8, -51, -56, 15, -1, -14, -8, -31, 36, 22, +-8, -53, -68, -98, -101, 42, 49, 38, 41, 12, +10, -27, -22, 4, -23, -21, 30, -1, 22, 26, +-13, -56, -42, 31, 9, -1, -10, -2, 22, -4, +15, 8, 56, 57, 45, 55, 57, 46, 72, 44, +-7, -53, -26, 53, 21, 17, 0, 0, 74, 41, +3, -18, -2, 0, 19, 17, 42, 36, 47, 26, +24, -7, -23, -34, -62, -60, 6, -22, 18, 25, +-11, -42, -46, -61, -83, -99, -67, -11, 28, 39, +30, -3, -10, -1, -24, -30, -1, -28, 15, 18, +19, -15, -10, -6, -35, -26, 33, 10, 56, 39, +-13, -53, -82, -42, 53, 37, 18, 10, -3, -21, +-21, -60, -89, -46, 89, 94, 71, 46, 42, 9, +-2, -34, -44, -46, -64, -84, -1, 37, 16, 0, +-17, -51, -65, -64, -7, -17, -29, -11, 52, 27, +22, -15, -16, -39, -55, 26, 36, 21, 62, 28, +-2, -26, -38, -49, -55, -80, -75, 8, 20, 9, +-6, -47, -61, -82, -103, -17, -15, -25, 53, 40, +-8, -47, -66, -18, 56, 43, 25, 29, 39, 3, +-27, -66, -86, -69, -50, -59, -34, -1, 19, 42, +3, -20, 2, 21, 72, 57, 52, 36, 31, 7, +-12, -49, -61, -13, -1, -33, 5, 37, 26, 2, +-27, -69, -92, -62, 2, 43, 88, 67, 64, 36, +0, -40, -4, -6, -20, 43, 33, 25, 50, 20, +14, -20, -30, -44, -73, -37, -24, -47, 26, 20, +31, 53, 111, 118, 127, 126, 121, 99, 85, 46, +-14, -45, -51, -39, 24, 5, -6, 17, 46, 14, +-4, -43, -45, -70, -63, 8, 14, 58, 78, 39, +-8, -47, -66, -84, -114, -55, 10, -8, 32, 40, +28, 22, 42, 26, 8, -21, -16, -6, 22, 10, +24, 10, 34, 31, 35, 31, 46, 39, 59, 36, +-4, -43, -62, -10, 20, -14, 2, 14, -6, -19, +-21, -62, -89, -22, 62, 33, 30, 16, 15, 15, +0, -22, -31, -45, -58, -80, -66, 13, 68, 34, +-16, -45, -6, 7, -6, -17, -14, -15, 2, 2, +10, -5, -22, -38, -40, -70, -60, -15, -23, 0, +22, -11, -22, -39, -67, -25, 30, 5, 58, 37, +-21, -47, 6, 43, 37, 45, 65, 66, 73, 43, +2, -25, -40, -53, -72, -94, -35, 24, 9, 8, +-3, 0, -3, -9, 4, -23, -10, 20, 43, 14, +-2, -41, -60, -9, 57, 32, 17, 16, 6, -19, +1, -31, -36, -36, -54, -68, -77, -75, 21, 37, +-19, -32, 79, 90, 92, 81, 67, 47, 52, 28, +-6, -36, -57, -62, 27, 40, 21, 11, 9, -19, +-10, -47, -49, -59, -74, -18, -14, -30, 25, 18, +-23, -69, -82, 60, 66, 40, 75, 54, 65, 38, +-19, -57, -92, -68, 66, 58, 34, 18, 1, -16, +-29, -68, -99, -88, -37, -38, 13, 8, 5, 40, +-22, -63, -75, 14, 15, 7, 75, 58, 59, 34, +-23, -62, -82, -39, -31, -53, -27, 5, -3, 20, +13, -26, -20, 22, 2, -3, 35, 13, 54, 39, +32, 5, -13, -22, -45, -58, -1, -20, -19, 7, +30, 46, 70, 55, 89, 88, 91, 67, 56, 28, +-13, -50, -63, -25, -28, -50, -23, -32, -34, 19, +-13, -54, -65, -9, -20, -37, 29, 6, 11, 25, +0, -40, -55, -78, -107, -25, 47, 20, 34, 16, +-20, -58, -96, -103, 38, 43, 27, 30, 15, -1, +-16, -49, -52, -66, -80, -57, -44, -39, 6, 38, +0, -38, 5, 13, -8, 23, 24, 1, 7, -9, +-18, -56, -64, -7, 38, 13, 11, 32, 28, 0, +14, -3, -20, -17, 4, -26, -34, -8, 19, -9, +-23, -60, -83, -38, -8, -32, 11, 19, -1, -5, +-5, -47, -12, 56, 38, 22, 18, -8, -5, -8, +18, -4, -24, -16, 27, 2, -6, 5, 25, -5, +13, 0, -19, -35, -23, -45, -59, -30, 19, 3, +19, -12, -23, 1, -7, -35, -14, -32, -23, 4, +-23, -64, -67, -22, -27, -5, -5, -20, 20, 5, +20, 11, 83, 92, 85, 89, 69, 53, 80, 48, +15, -2, -21, -29, -18, -48, -52, -12, -11, -21, +-6, -38, -55, -68, -9, 33, 22, 19, 25, -1, +-8, -46, -49, -67, -64, 16, 8, -6, 32, 15, +3, -25, -46, -46, 39, 50, 34, 21, 46, 14, +8, -33, -37, -68, -82, 31, 34, 13, 19, -6, +33, 0, 5, -7, -32, 2, 22, -3, 35, 17, +-23, -62, -91, -64, 6, 3, 36, 26, 7, -3, +-12, -54, -60, 26, 46, 16, 30, 22, 8, -4, +-23, -61, -40, 31, 58, 73, 88, 77, 74, 41, +-2, -42, -49, 13, 5, -15, 22, -4, 26, 27, +-13, -54, -39, 18, 2, -8, -12, 34, 56, 23, +-20, -31, 27, 23, 24, 28, 39, 33, 47, 27, +36, 17, -4, -20, -30, -61, -8, 20, 0, -15, +-10, -51, -72, -82, -111, -73, 34, 25, 19, 38, +-10, -45, -63, -55, -46, -75, -45, 34, 34, 12, +6, -18, 29, 26, 7, -9, 0, 5, 38, 22, +-7, -52, -16, 69, 43, 26, 23, 2, 51, 34, +-12, -51, -59, -78, -88, 15, 20, 0, -14, 12, +-3, -36, -59, -45, 60, 49, 28, 20, 16, -13, +-28, -70, -90, 9, 67, 48, 90, 77, 70, 38, +-10, -39, -58, -54, 15, -12, 3, 35, 27, -3, +12, -1, 28, 29, 55, 53, 80, 65, 51, 23, +-17, -61, -39, 74, 56, 43, 75, 51, 58, 36, +-30, -71, -93, -43, -29, -26, 4, -19, -14, 37, +3, -13, -31, -38, 11, -5, -22, -11, 43, 14, +-25, -65, -80, -79, -71, 3, 37, 32, 20, 9, +-20, -60, -77, -26, 18, 43, 44, 24, 22, -3, +-4, -42, -22, -19, -45, -32, -35, -39, -46, 1, +-25, -59, -27, -10, -7, -4, 7, 13, 25, 12, +8, -25, -32, -47, -74, -32, 27, 6, 25, 7, +41, 40, 62, 64, 64, 50, 54, 42, 49, 25, +-21, -63, -88, -21, 16, -3, -4, -26, 57, 38, +8, -25, -34, 2, -8, -28, 2, -22, 12, 23, +-19, -49, 10, 71, 84, 71, 66, 48, 42, 22, +-20, -58, -89, -57, 62, 44, 33, 36, 25, -1, +-22, -55, -27, 1, 43, 37, 46, 50, 51, 26, +1, -38, -46, 22, 34, 4, 20, -2, 3, 9, +-4, -42, -49, -75, -89, -24, -25, 19, 71, 39, +5, -28, -45, -43, -63, -75, -17, -38, 14, 30, +-4, -36, -62, -59, -29, -43, -4, -16, 11, 23, +-19, -57, -82, -39, 26, 2, -2, 20, 11, -10, +-28, -68, -92, -70, 9, -1, -15, -30, 11, 31, +1, -22, -41, -49, -30, -58, -48, 8, 4, -9, +38, 41, 108, 115, 96, 98, 103, 84, 86, 51, +15, 1, 58, 46, 26, 6, 16, 18, 41, 24, +4, -34, -14, -27, -42, 20, 18, 2, 23, 1, +-22, -59, -83, -70, -22, -42, -26, 29, 29, 15, +-14, -34, 11, -1, -21, -35, -3, 1, 29, 16, +-16, -57, -78, -7, 17, -13, 8, -13, -6, 22, +-22, -32, -21, -20, 20, -4, 10, 13, 12, -4, +8, -30, -30, -46, -71, -4, 3, -11, 4, -11, +16, 5, -15, -21, 3, -23, -25, -19, -28, -32, +-28, -68, -98, -101, -34, 19, 71, 52, 49, 30, +-18, -57, -82, -56, -56, -66, 15, 12, 1, 29, +-21, -62, -76, -27, -33, -38, 18, 30, 54, 32, +3, -36, -10, -17, -34, -3, -8, 32, 63, 27, +1, -30, -44, -20, -13, -49, -25, 3, -14, -18, +-26, -68, -80, -46, -28, 17, 42, 37, 58, 34, +30, 26, 57, 55, 49, 25, 16, 3, 24, 11, +35, 35, 67, 57, 60, 82, 114, 103, 93, 55, +18, -8, -23, -32, -53, -68, 15, 11, -6, -7, +-2, -43, -29, 0, -28, -5, -5, -15, 25, -1, +4, -13, -35, -45, 14, -6, -2, 19, 16, -9, +-30, -72, -93, -93, -73, -10, -15, 6, 30, 45, +-23, -58, -50, -55, -74, -60, -23, 0, 6, 21, +-4, -40, -63, -24, 7, -19, 4, -18, 27, 28, +-12, 1, 88, 76, 74, 88, 93, 90, 80, 44, +-13, -59, -43, 52, 27, 21, 15, 12, 42, 11, +22, -14, -17, -33, -57, -4, 5, -18, 40, 18, +-3, -23, -43, -44, 8, -16, -14, -4, -20, -29, +35, 45, 75, 82, 111, 117, 125, 105, 89, 51, +-3, -38, -57, -30, 79, 71, 48, 33, 33, 0, +-17, -62, -57, 66, 67, 35, 29, 5, 22, 17, +3, -31, -34, -21, -44, -49, 42, 23, 24, 26, +-23, -62, -74, -49, -30, -30, -37, -50, 9, 35, +-17, -57, -71, -81, -45, 61, 58, 37, 31, 9, +3, -7, 28, 14, -2, 0, 40, 41, 58, 33, +-11, -51, -74, -17, 40, 12, 8, 13, -4, -22, +-16, -46, -31, -35, -49, -49, -26, -9, -7, -7, +17, -9, -24, -41, -68, -73, 38, 33, 19, 16, +-15, -50, -47, -16, -24, -21, 59, 56, 53, 30, +-14, -54, -57, 2, -17, -33, -34, -21, 4, -4, +-23, -62, -93, -72, 48, 31, 21, 6, 3, 17, +-18, -63, -79, 44, 68, 36, 45, 20, 57, 37, +-29, -72, -99, -111, -86, -31, 7, 25, 39, 55, +-14, -49, -53, -63, -80, -31, 24, 13, 1, -1, +-9, -45, -55, -27, -31, -63, -23, 25, 13, -5, +-20, -61, -80, 7, 44, 16, 54, 40, 32, 17, +24, 7, -8, -43, -62, -54, -11, 7, 35, 27, +-12, -55, -59, -48, -69, -4, -1, -12, 68, 39, +-12, -31, 52, 63, 53, 34, 29, 22, 36, 19, +-26, -66, -97, -79, 50, 41, 40, 48, 54, 28, +-2, -37, -41, -2, -11, -30, 29, 16, 4, -2, +40, 49, 56, 37, 39, 40, 64, 59, 67, 39, +11, -5, 20, 14, 25, 16, 25, 22, 37, 17, +-3, -43, -46, -10, -35, -38, -35, -39, 67, 43, +-7, -47, -33, -39, -60, -12, -18, 11, 43, 11, +-25, -65, -91, -76, -91, -81, 0, 13, 34, 50, +-9, -50, -52, 17, 0, -4, 43, 18, 63, 42, +-8, -15, 15, 41, 56, 35, 51, 45, 51, 29, +0, -14, -24, -36, -43, -70, -39, 27, 33, 5, +-25, -62, -81, -66, -12, -26, -16, -4, -13, 21, +-29, -68, -60, -24, -3, 11, 18, 19, 30, 20, +1, -35, -42, -30, -57, -51, 13, -17, 3, 22, +-8, -27, -12, -2, -7, -21, 36, 41, 34, 12, +-17, -56, -62, -72, -73, -17, -26, 9, 16, 13, +11, -21, -37, -3, 16, -17, 1, -3, -18, -19, +15, -20, -19, -22, -49, -30, -7, -29, 3, -2, +17, -4, 11, 6, 51, 40, 36, 34, 48, 22, +-19, -55, -29, 37, 68, 49, 45, 33, 42, 23, +7, -30, -22, 3, -22, -36, -36, -54, 20, 22, +20, 2, -15, -39, -59, -85, -10, 37, 21, 2, +-15, -54, -77, -54, 74, 70, 48, 32, 51, 20, +-25, -64, -70, -75, -52, 17, 6, -20, -30, 26, +-13, -55, -15, 39, 16, 42, 30, 33, 62, 28, +-21, -56, -30, -35, 6, 13, -4, -29, 33, 27, +-17, -55, -75, -31, 3, -28, -26, 16, 18, -4, +-13, -44, -60, -52, -9, -36, -38, 1, -9, -9, +-12, -50, -77, -70, 43, 47, 28, 13, 43, 16, +-13, -57, -80, -104, -113, -30, 43, 45, 52, 39, +3, -28, -42, -37, -58, -67, 23, 4, 38, 33, +-21, -64, -74, -22, 43, 83, 81, 56, 62, 32, +34, 26, 23, 9, 14, 17, 26, 16, 37, 19, +-5, -48, -49, -75, -65, 9, -6, 41, 45, 15, +32, 30, 63, 83, 90, 91, 100, 84, 85, 52, +-19, -54, -68, -71, 11, 30, 13, 1, 63, 37, +44, 76, 99, 87, 117, 113, 103, 77, 64, 32, +-16, -45, -12, 30, 27, 15, 57, 49, 42, 22, +9, -15, -31, -28, -36, -61, -13, -18, -33, -5, +-12, -55, -8, 82, 64, 47, 42, 21, 27, 9, +-15, -56, -74, -12, -19, -28, 7, -16, 53, 38, +-7, -45, -64, -55, -74, -80, 35, 45, 24, 15, +-25, -48, -34, -42, -6, -27, -9, 9, 13, -7, +-25, -65, -84, -35, 30, 14, 24, 39, 48, 28, +-22, -62, -86, -51, 64, 104, 94, 61, 62, 31, +16, -15, -25, -28, -55, -56, -10, -23, 52, 36, +10, -10, -22, -46, -71, -92, -45, -13, 16, 26, +-22, -65, -84, 17, 85, 55, 66, 48, 55, 31, +-1, -38, -33, -25, -49, -15, 18, -10, 41, 30, +-3, -24, -47, -60, -30, -46, -17, -13, -27, 1, +-7, -41, -61, -54, -50, -78, -28, 5, -2, 20, +17, -12, -27, -4, 8, -27, -5, 23, 14, -12, +-36, -81, -111, -75, -17, -9, 9, 9, 39, 49, +-13, -59, -54, 68, 51, 32, 35, 14, 64, 38, +-11, -44, -69, -57, 11, -11, -5, 3, -16, -15, +34, 36, 41, 16, -8, -24, 11, 23, 48, 28, +-17, -42, 8, 17, 45, 69, 71, 55, 49, 23, +3, -30, -46, -64, -95, -109, 2, 39, 19, 19, +25, -13, -7, 16, -11, -5, 8, -11, 52, 33, +-8, -37, -57, -60, 13, 7, -14, -4, 20, -7, +7, -31, 9, 44, 20, 22, 29, 10, 52, 31, +3, -22, -36, -53, -80, -77, -35, -41, 54, 41, +-21, -59, -87, -83, 12, 69, 57, 36, 32, 2, +6, -14, -34, -42, -4, -32, -27, 10, 4, -20, +-11, -56, -59, 25, 8, -5, -9, -26, 68, 43, +22, 13, 40, 39, 73, 81, 95, 88, 82, 45, +-18, -62, -79, 28, 60, 28, 29, 3, 23, 25, +6, -31, -39, -55, -85, -32, 7, -17, 48, 30, +7, -24, -42, -8, 39, 10, 7, 11, 1, -20, +-1, -36, -26, -30, -48, 2, 46, 26, 35, 14, +-17, -57, -56, -10, -4, 26, 22, 6, -4, -16, +-18, -55, -59, -67, -86, -50, 3, 29, 29, 16, +-25, -61, -33, 2, 26, 25, 23, 10, 24, 16, +26, 15, -8, -20, 6, -21, -16, 3, 0, -22, +13, -17, -26, -12, -31, -48, 15, -3, 1, 14, +4, -27, -33, -21, -29, -53, -52, -64, -42, 22, +-11, -41, -42, -40, -42, -64, 0, 48, 50, 19, +-13, -47, -42, -56, -50, 10, 3, -9, -30, -16, +-4, -47, -12, 14, -13, 21, 13, 6, 73, 40, +-15, -50, -63, -41, -31, -55, -60, -13, 28, 15, +-6, -50, -56, -81, -95, 30, 29, 21, 71, 35, +-14, -58, -65, 37, 40, 9, 18, -10, -4, 20, +31, 33, 79, 106, 119, 103, 100, 77, 64, 33, +14, 7, 56, 81, 97, 85, 85, 61, 45, 20, +-24, -66, -74, -51, -17, 16, 5, -21, 22, 26, +-1, -25, -38, -24, -2, -35, -26, 21, 34, 1, +20, 15, 75, 59, 39, 26, 48, 43, 50, 29, +26, 1, -15, -4, -9, -38, 9, 2, -9, -8, +20, 14, 19, 13, 2, -16, 24, 25, 19, 3, +-8, -41, -58, -78, -109, -106, -27, 9, 53, 46, +17, 5, -13, -25, -24, -54, -20, 2, -21, -25, +-11, -50, -48, 19, 10, -7, 46, 26, 24, 17, +-28, -68, -69, -50, -49, -33, -7, 10, 20, 21, +4, -36, -21, 38, 19, 1, 25, -3, 20, 22, +-18, -58, -87, -44, 82, 73, 49, 31, 19, -7, +-21, -61, -78, -44, -58, -66, -9, -23, 10, 40, +-25, -66, -76, -33, -33, 6, 16, -6, -21, 5, +-27, -69, -77, 5, -2, -7, 6, 9, 24, 6, +1, -41, -41, -58, -79, 25, 69, 43, 68, 36, +-28, -67, -85, -71, -34, 0, 14, 12, -2, 4, +-2, -33, -55, -37, 37, 25, 6, 6, 29, -4, +-8, -25, -11, -9, 40, 23, 17, 25, 37, 12, +-21, -27, 52, 60, 47, 58, 76, 70, 69, 38, +23, 15, 22, -8, -32, -50, -10, 3, 31, 21, +-10, -44, -67, -61, -29, -54, 8, 39, 21, 4, +31, 18, 30, 36, 46, 28, 50, 42, 35, 13, +-21, -57, -24, -16, -15, 14, 3, -25, -17, 20, +23, 6, 24, 35, 90, 72, 64, 55, 55, 23, +7, -28, -42, -19, -36, -50, -15, -40, 29, 28, +-21, -59, -66, -59, -6, 85, 83, 53, 54, 26, +2, -20, -42, -52, -27, -49, 5, 9, -9, -8, +-18, -56, -84, -72, 24, 51, 32, 20, 13, -10, +-13, -53, -64, -39, -63, -40, 24, 0, 34, 29, +0, -31, -45, -63, -90, -53, 3, -18, -9, 24, +-13, -57, -71, 27, 19, -3, 25, -3, 45, 35, +12, -9, -26, -40, -51, -78, -24, 11, -9, -6, +-12, -49, -45, -33, -50, -48, -46, -52, 2, 25, +-14, -56, -84, -108, -122, -50, 4, 22, 42, 53, +-6, -44, -54, -28, -41, -61, 19, 25, 6, 1, +-32, -75, -95, -38, -1, -15, 7, 14, 23, 23, +11, 12, 37, 30, 38, 51, 80, 80, 82, 47, +-19, -56, -69, -82, -98, -64, -29, 2, 28, 42, +-18, -49, 3, 34, 41, 39, 32, 18, 21, 7, +-8, 23, 39, 30, 30, 27, 41, 36, 44, 23, +-16, -49, -69, -46, 1, -27, 41, 48, 35, 15, +6, -32, -36, 5, -17, -30, 2, -16, 51, 35, +-23, -64, -91, -21, 71, 44, 52, 44, 40, 21, +-22, -55, -40, -20, 62, 52, 38, 29, 27, 5, +-27, -69, -75, -6, -8, 3, -2, -30, -42, 13, +2, -29, -42, -10, 29, 2, 15, 30, 26, 0, +-27, -69, -85, -75, -54, -8, -14, -31, 16, 42, +-2, -44, -54, -75, -101, -6, 4, -3, 32, 13, +7, -3, -22, -43, -14, -27, -24, -11, -14, -12, +-18, -57, -85, -66, 47, 86, 75, 45, 42, 10, +18, 3, 39, 76, 80, 48, 48, 41, 44, 21, +-13, -51, -73, -22, -15, -41, 3, -4, -22, 3, +-10, -50, -63, -9, -23, -42, -6, -30, 11, 28, +15, -11, -29, -39, -57, -71, -23, -40, -33, 20, +-2, -40, -48, -5, -21, -25, 31, 7, 53, 35, +-19, -63, -72, 39, 34, 16, 37, 17, 54, 31, +-18, -49, -28, -27, -40, -29, 4, 4, 19, 11, +-1, -43, -41, 24, 15, -12, -4, -31, -4, 23, +-11, -46, -79, -74, 34, 21, 9, 15, 3, -13, +-16, -51, -56, -55, 8, 62, 50, 30, 43, 14, +-1, -25, -27, -32, -46, -62, -66, -36, 53, 32, +-12, -49, -77, -50, 2, -21, 23, 6, 14, 21, +-5, -47, -58, -77, -105, -14, 30, 9, 73, 44, +-24, -52, -4, 10, 13, 13, 27, 27, 42, 24, +-10, -38, -27, -15, -24, -52, -53, 1, 14, -6, +-17, -45, -13, 2, 19, 53, 83, 79, 76, 43, +-21, -62, -86, -48, 40, 17, 14, -9, 40, 30, +-1, -32, -51, -33, -3, -35, 2, 17, -2, -12, +-21, -60, -85, -70, 33, 73, 58, 37, 67, 36, +-1, -45, -39, 37, 17, 3, 18, -8, 53, 35, +-8, -47, -65, -61, -87, -93, 9, 9, 2, 33, +-13, -55, -56, -19, -29, 14, 17, 6, 55, 28, +5, 1, -7, -23, -26, -56, -39, 14, 11, -13, +-28, -69, -89, -74, -83, -45, 1, 0, 16, 45, +-3, 5, 91, 104, 119, 111, 97, 76, 72, 39, +19, 5, -12, -34, -41, -72, -67, 14, 21, 1, +-17, -49, 15, 27, 13, 6, 2, 12, 27, 10, +-10, -30, 18, 36, 93, 87, 87, 69, 58, 26, +37, 32, 64, 54, 53, 67, 78, 73, 80, 48, +48, 46, 38, 9, -1, 8, 47, 44, 58, 33, +-23, -61, -88, -76, 27, 14, 9, 36, 36, 10, +-24, -66, -88, -97, -55, 20, 19, 16, 52, 31, +4, -16, -1, -8, 2, 0, 15, 13, 29, 14, +-9, -44, -66, -72, 8, 32, 37, 38, 46, 16, +-22, -65, -62, 30, 22, 51, 57, 45, 68, 38, +-4, -42, -53, -33, -54, -53, -4, -18, 62, 40, +-5, -37, -61, -41, 35, 15, -2, -3, -12, -28, +-18, -65, -55, 90, 80, 49, 44, 21, 59, 36, +5, -16, -31, -32, -37, -62, -19, -11, 9, 16, +-22, -60, -67, -51, -61, -35, -5, -18, -27, 24, +-18, -55, -39, -42, -40, 20, 25, 6, 6, 7, +0, -25, -42, -50, -59, -84, -31, -13, -22, 17, +-32, -73, -100, -89, -21, -10, 18, 38, 31, 23, +-15, -54, -57, -13, -18, -41, -32, 17, 50, 21, +-16, -57, -71, -10, -8, -26, -38, -47, 42, 25, +-17, -58, -82, -7, 33, 3, 30, 11, 13, 24, +-23, -61, -97, -83, 82, 81, 57, 39, 31, 2, +26, 32, 104, 86, 62, 55, 77, 70, 74, 43, +-8, -29, -33, -52, -74, -73, -17, 14, 39, 25, +-21, -60, -68, -22, 43, 37, 51, 54, 64, 36, +-5, -30, -50, -52, 22, 7, 10, 13, 0, -20, +-15, -53, -61, -34, -50, -25, 15, 6, 0, -14, +-10, -51, -60, 20, 77, 50, 34, 22, 8, -8, +-8, -45, -52, -59, -76, -35, -43, -49, 47, 40, +41, 44, 53, 40, 41, 30, 38, 31, 46, 24, +19, 3, -15, -26, -16, -45, -13, 24, 18, -5, +-3, -39, -54, -35, -49, -70, 2, -6, -19, 15, +-13, -53, -36, 6, -3, 45, 50, 30, 33, 10, +15, -25, -16, -4, -32, 7, 23, 6, 67, 36, +-21, -58, -87, -71, 10, -12, -16, 19, 10, 0, +9, -15, -6, 25, 31, 7, 30, 28, 20, 2, +2, -28, -42, -50, -67, -75, 12, 12, -4, 8, +-17, -63, -58, 56, 49, 36, 60, 38, 37, 14, +-13, -48, -38, -29, -44, -25, -20, -33, 38, 20, +2, -37, -42, -1, -18, -42, 3, -17, -19, 12, +-20, -60, -73, -7, 12, -13, -22, -38, 4, 10, +-8, -41, -63, -65, 42, 63, 45, 31, 31, 0, +-4, -46, -38, -9, -35, 15, 50, 27, 67, 39, +3, -7, -13, -34, -51, -47, 9, 39, 54, 29, +-29, -71, -89, -52, -39, -6, 3, 2, 38, 28, +-14, -42, -13, -15, -19, 0, 20, 12, 37, 25, +11, -26, -24, -40, -65, -11, -13, -27, 65, 37, +0, -31, -46, -17, -21, -45, 11, -2, 25, 24, +51, 91, 102, 87, 85, 63, 57, 42, 48, 23, +-4, -34, -56, -70, -10, -14, 4, 18, 3, -8, +-23, -59, -39, -44, -42, -14, -10, -23, -4, 17, +-2, 4, 35, 63, 69, 75, 82, 63, 78, 48, +-17, -55, -60, -3, -4, -19, 4, -4, -18, -29, +2, -20, -36, -50, -32, -59, -16, 30, 16, -6, +-12, -47, 24, 68, 45, 46, 41, 32, 65, 37, +-4, -40, -54, -67, -96, -66, -9, -25, 42, 38, +-15, 13, 58, 58, 84, 104, 119, 104, 89, 51, +-15, -24, -9, -24, -27, -50, -7, 28, 29, 6, +-7, -33, -35, -49, -65, -53, -37, -10, 33, 14, +31, 19, 46, 72, 67, 45, 83, 68, 63, 41, +-14, -53, -59, -17, 55, 79, 64, 39, 43, 10, +}; + +const signed char cdbk_lsp2_vlbr[160]={ +-20, -30, -24, 17, 7, -13, -21, 61, 56, 16, +12, 1, 10, 77, 32, 3, 7, 3, -25, -31, +-4, 2, -36, -83, 18, 5, -5, 5, 11, 23, +-2, -1, -11, -12, -20, -28, 68, 50, -17, -20, +5, 2, 1, 20, 17, 4, -52, -66, 36, 24, +-4, -10, 7, -15, -32, 80, 37, 8, -13, -29, +33, 37, 28, 15, 8, 14, 35, 18, 50, 36, +-4, -1, 4, -7, 3, 3, -11, -58, -75, 13, +13, 21, 24, -11, -12, -38, -72, 33, 15, -12, +-44, -17, 83, 21, 2, 7, 0, 4, 0, -1, +-25, -42, -51, 33, 20, 15, 30, -13, 9, 32, +6, 2, -8, 7, -38, -77, 6, -13, -7, 32, +48, 57, 32, -12, -10, -4, 2, -15, -29, -29, +2, 10, -9, -16, 79, 44, 7, 12, -5, -18, +-23, -29, -35, -3, -3, -18, -34, -3, -39, -50, +-5, -10, -8, -37, -76, 11, -4, -19, 30, 16, +}; + +#endif diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/lpc.c b/mozilla/zap/zmk/speex-1.1.10/libspeex/lpc.c new file mode 100755 index 00000000000..3ce783bc3c1 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/lpc.c @@ -0,0 +1,201 @@ +/* + Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann, + Technische Universitaet Berlin + + Any use of this software is permitted provided that this notice is not + removed and that neither the authors nor the Technische Universitaet Berlin + are deemed to have made any representations as to the suitability of this + software for any purpose nor are held responsible for any defects of + this software. THERE IS ABSOLUTELY NO WARRANTY FOR THIS SOFTWARE. + + As a matter of courtesy, the authors request to be informed about uses + this software has found, about bugs in this software, and about any + improvements that may be of general interest. + + Berlin, 28.11.1994 + Jutta Degener + Carsten Bormann + + + Code modified by Jean-Marc Valin + + Speex License: + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 "lpc.h" + +#ifdef BFIN_ASM +#include "lpc_bfin.h" +#endif + +/* LPC analysis + * + * The next two functions calculate linear prediction coefficients + * and/or the related reflection coefficients from the first P_MAX+1 + * values of the autocorrelation function. + */ + +/* Invented by N. Levinson in 1947, modified by J. Durbin in 1959. + */ + +/* returns minimum mean square error */ +spx_word32_t _spx_lpc( +spx_coef_t *lpc, /* out: [0...p-1] LPC coefficients */ +const spx_word16_t *ac, /* in: [0...p] autocorrelation values */ +int p +) +{ + int i, j; + spx_word16_t r; + spx_word16_t error = ac[0]; + + if (ac[0] == 0) + { + for (i = 0; i < p; i++) + lpc[i] = 0; + return 0; + } + + for (i = 0; i < p; i++) { + + /* Sum up this iteration's reflection coefficient */ + spx_word32_t rr = NEG32(SHL32(EXTEND32(ac[i + 1]),13)); + for (j = 0; j < i; j++) + rr = SUB32(rr,MULT16_16(lpc[j],ac[i - j])); +#ifdef FIXED_POINT + r = DIV32_16(rr,ADD16(error,16)); +#else + r = rr/(error+.003*ac[0]); +#endif + /* Update LPC coefficients and total error */ + lpc[i] = r; + for (j = 0; j < i>>1; j++) + { + spx_word16_t tmp = lpc[j]; + lpc[j] = MAC16_16_Q13(lpc[j],r,lpc[i-1-j]); + lpc[i-1-j] = MAC16_16_Q13(lpc[i-1-j],r,tmp); + } + if (i & 1) + lpc[j] = MAC16_16_Q13(lpc[j],lpc[j],r); + + error = SUB16(error,MULT16_16_Q13(r,MULT16_16_Q13(error,r))); + } + return error; +} + + +#ifdef FIXED_POINT + +/* Compute the autocorrelation + * ,--, + * ac(i) = > x(n) * x(n-i) for all n + * `--' + * for lags between 0 and lag-1, and x == 0 outside 0...n-1 + */ + +#ifndef OVERRIDE_SPEEX_AUTOCORR +void _spx_autocorr( +const spx_word16_t *x, /* in: [0...n-1] samples x */ +spx_word16_t *ac, /* out: [0...lag-1] ac values */ +int lag, +int n +) +{ + spx_word32_t d; + int i, j; + spx_word32_t ac0=1; + int shift, ac_shift; + + for (j=0;j x(n) * x(n-i) for all n + * `--' + * for lags between 0 and lag-1, and x == 0 outside 0...n-1 + */ +void _spx_autocorr( +const spx_word16_t *x, /* in: [0...n-1] samples x */ +float *ac, /* out: [0...lag-1] ac values */ +int lag, +int n +) +{ + float d; + int i; + while (lag--) + { + for (i = lag, d = 0; i < n; i++) + d += x[i] * x[i-lag]; + ac[lag] = d; + } + ac[0] += 10; +} + +#endif + + diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/lpc.h b/mozilla/zap/zmk/speex-1.1.10/libspeex/lpc.h new file mode 100755 index 00000000000..d0930b634d0 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/lpc.h @@ -0,0 +1,51 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: lpc.h + Functions for LPC (Linear Prediction Coefficients) analysis + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 LPC_H +#define LPC_H + +#include "misc.h" + +void _spx_autocorr( + const spx_word16_t * x, /* in: [0...n-1] samples x */ + spx_word16_t *ac, /* out: [0...lag-1] ac values */ + int lag, int n); + +spx_word32_t /* returns minimum mean square error */ +_spx_lpc( + spx_coef_t * lpc, /* [0...p-1] LPC coefficients */ + const spx_word16_t * ac, /* in: [0...p] autocorrelation values */ + int p + ); + + +#endif diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/lpc_bfin.h b/mozilla/zap/zmk/speex-1.1.10/libspeex/lpc_bfin.h new file mode 100755 index 00000000000..1bfbc9c0ac9 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/lpc_bfin.h @@ -0,0 +1,129 @@ +/* Copyright (C) 2005 Analog Devices + Author: Jean-Marc Valin + File: lpc_bfin.h + LPC stuff (Blackfin version) + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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. +*/ + +#define OVERRIDE_SPEEX_AUTOCORR +void _spx_autocorr( +const spx_word16_t *x, /* in: [0...n-1] samples x */ +spx_word16_t *ac, /* out: [0...lag-1] ac values */ +int lag, +int n + ) +{ + spx_word32_t d; + const spx_word16_t *xs; + int i, j; + spx_word32_t ac0=1; + spx_word32_t ac32[11], *ac32top; + int shift, ac_shift; + ac32top = ac32+10; + int lag_1, N_lag; + int nshift; + lag_1 = lag-1; + N_lag = n-lag_1; + for (j=0;j> 1;\n\t" + "LOOP_BEGIN pitch%=;\n\t" + "I1 = P0;\n\t" + "A1 = A0 = 0;\n\t" + "R1 = [I1++];\n\t" + "LOOP inner_prod%= LC1 = P3 >> 1;\n\t" + "LOOP_BEGIN inner_prod%=;\n\t" + "A0 += R0.L*R1.L , A1 += R0.L*R1.H (is) || R1.L = W[I1++];\n\t" + "A0 += R0.H*R1.H , A1 += R0.H*R1.L (is) || R1.H = W[I1++] || R0 = [I0++];\n\t" + "LOOP_END inner_prod%=;\n\t" + "A0 = ASHIFT A0 by R4.L;\n\t" + "A1 = ASHIFT A1 by R4.L;\n\t" + + "R2 = A0, R3 = A1;\n\t" + "[P1--] = R2;\n\t" + "[P1--] = R3;\n\t" + "P0 += 4;\n\t" + "LOOP_END pitch%=;\n\t" + : : "m" (xs), "m" (x), "m" (ac32top), "m" (N_lag), "m" (lag_1), "m" (nshift) + : "A0", "A1", "P0", "P1", "P2", "P3", "P4", "R0", "R1", "R2", "R3", "R4", "I0", "I1", "L0", "L1", "B0", "B1", "memory" + ); + d=0; + for (j=0;j +#include "lsp.h" +#include "stack_alloc.h" +#include "math_approx.h" + +#ifndef M_PI +#define M_PI 3.14159265358979323846 /* pi */ +#endif + +#ifndef NULL +#define NULL 0 +#endif + +#ifdef FIXED_POINT + +#define C1 8192 +#define C2 -4096 +#define C3 340 +#define C4 -10 + +static spx_word16_t spx_cos(spx_word16_t x) +{ + spx_word16_t x2; + + if (x<12868) + { + x2 = MULT16_16_P13(x,x); + return ADD32(C1, MULT16_16_P13(x2, ADD32(C2, MULT16_16_P13(x2, ADD32(C3, MULT16_16_P13(C4, x2)))))); + } else { + x = SUB16(25736,x); + x2 = MULT16_16_P13(x,x); + return SUB32(-C1, MULT16_16_P13(x2, ADD32(C2, MULT16_16_P13(x2, ADD32(C3, MULT16_16_P13(C4, x2)))))); + /*return SUB32(-C1, MULT16_16_Q13(x2, ADD32(C2, MULT16_16_Q13(C3, x2))));*/ + } +} + + +#define FREQ_SCALE 16384 + +/*#define ANGLE2X(a) (32768*cos(((a)/8192.)))*/ +#define ANGLE2X(a) (SHL16(spx_cos(a),2)) + +/*#define X2ANGLE(x) (acos(.00006103515625*(x))*LSP_SCALING)*/ +#define X2ANGLE(x) (spx_acos(x)) + +#else + +/*#define C1 0.99940307 +#define C2 -0.49558072 +#define C3 0.03679168*/ + +#define C1 0.9999932946f +#define C2 -0.4999124376f +#define C3 0.0414877472f +#define C4 -0.0012712095f + + +#define SPX_PI_2 1.5707963268 +static inline spx_word16_t spx_cos(spx_word16_t x) +{ + if (x>1; + VARDECL(spx_word16_t *coefn); + + /*Prevents overflows*/ + if (x>16383) + x = 16383; + if (x<-16383) + x = -16383; + + /* Allocate memory for Chebyshev series formulation */ + ALLOC(T, m2+1, spx_word16_t); + ALLOC(coefn, m2+1, spx_word16_t); + + for (i=0;i>1; + + /* Allocate memory for Chebyshev series formulation */ + ALLOC(T, m2+1, float); + + /* Initialise values */ + T[0]=1; + T[1]=x; + + /* Evaluate Chebyshev series formulation using iterative approach */ + /* Evaluate polynomial and return value also free memory space */ + sum = coef[m2] + coef[m2-1]*x; + x *= 2; + for(i=2;i<=m2;i++) + { + T[i] = x*T[i-1] - T[i-2]; + sum += coef[m2-i] * T[i]; + } + + return sum; +} +#endif + +/*---------------------------------------------------------------------------*\ + + FUNCTION....: lpc_to_lsp() + + AUTHOR......: David Rowe + DATE CREATED: 24/2/93 + + This function converts LPC coefficients to LSP + coefficients. + +\*---------------------------------------------------------------------------*/ + +#ifdef FIXED_POINT +#define SIGN_CHANGE(a,b) (((a)&0x70000000)^((b)&0x70000000)||(b==0)) +#else +#define SIGN_CHANGE(a,b) (((a)*(b))<0.0) +#endif + + +int lpc_to_lsp (spx_coef_t *a,int lpcrdr,spx_lsp_t *freq,int nb,spx_word16_t delta, char *stack) +/* float *a lpc coefficients */ +/* int lpcrdr order of LPC coefficients (10) */ +/* float *freq LSP frequencies in the x domain */ +/* int nb number of sub-intervals (4) */ +/* float delta grid spacing interval (0.02) */ + + +{ + spx_word16_t temp_xr,xl,xr,xm=0; + spx_word32_t psuml,psumr,psumm,temp_psumr/*,temp_qsumr*/; + int i,j,m,flag,k; + VARDECL(spx_word32_t *Q); /* ptrs for memory allocation */ + VARDECL(spx_word32_t *P); + spx_word32_t *px; /* ptrs of respective P'(z) & Q'(z) */ + spx_word32_t *qx; + spx_word32_t *p; + spx_word32_t *q; + spx_word32_t *pt; /* ptr used for cheb_poly_eval() + whether P' or Q' */ + int roots=0; /* DR 8/2/94: number of roots found */ + flag = 1; /* program is searching for a root when, + 1 else has found one */ + m = lpcrdr/2; /* order of P'(z) & Q'(z) polynomials */ + + /* Allocate memory space for polynomials */ + ALLOC(Q, (m+1), spx_word32_t); + ALLOC(P, (m+1), spx_word32_t); + + /* determine P'(z)'s and Q'(z)'s coefficients where + P'(z) = P(z)/(1 + z^(-1)) and Q'(z) = Q(z)/(1-z^(-1)) */ + + px = P; /* initialise ptrs */ + qx = Q; + p = px; + q = qx; + +#ifdef FIXED_POINT + *px++ = LPC_SCALING; + *qx++ = LPC_SCALING; + for(i=0;i=32768) + speex_warning_int("px", *px); + if (fabs(*qx)>=32768) + speex_warning_int("qx", *qx);*/ + *px = PSHR32(*px,2); + *qx = PSHR32(*qx,2); + px++; + qx++; + } + /* The reason for this lies in the way cheb_poly_eva() is implemented for fixed-point */ + P[m] = PSHR32(P[m],3); + Q[m] = PSHR32(Q[m],3); +#else + *px++ = LPC_SCALING; + *qx++ = LPC_SCALING; + for(i=0;i= -FREQ_SCALE)){ + spx_word16_t dd; + /* Modified by JMV to provide smaller steps around x=+-1 */ +#ifdef FIXED_POINT + dd = MULT16_16_Q15(delta,SUB16(FREQ_SCALE, MULT16_16_Q14(MULT16_16_Q14(xl,xl),14000))); + if (psuml<512 && psuml>-512) + dd = PSHR16(dd,1); +#else + dd=delta*(1-.9*xl*xl); + if (fabs(psuml)<.2) + dd *= .5; +#endif + xr = SUB16(xl, dd); /* interval spacing */ + psumr = cheb_poly_eva(pt,xr,lpcrdr,stack);/* poly(xl-delta_x) */ + temp_psumr = psumr; + temp_xr = xr; + + /* if no sign change increment xr and re-evaluate poly(xr). Repeat til + sign change. + if a sign change has occurred the interval is bisected and then + checked again for a sign change which determines in which + interval the zero lies in. + If there is no sign change between poly(xm) and poly(xl) set interval + between xm and xr else set interval between xl and xr and repeat till + root is located within the specified limits */ + + if(SIGN_CHANGE(psumr,psuml)) + { + roots++; + + psumm=psuml; + for(k=0;k<=nb;k++){ +#ifdef FIXED_POINT + xm = ADD16(PSHR16(xl,1),PSHR16(xr,1)); /* bisect the interval */ +#else + xm = .5*(xl+xr); /* bisect the interval */ +#endif + psumm=cheb_poly_eva(pt,xm,lpcrdr,stack); + /*if(psumm*psuml>0.)*/ + if(!SIGN_CHANGE(psumm,psuml)) + { + psuml=psumm; + xl=xm; + } else { + psumr=psumm; + xr=xm; + } + } + + /* once zero is found, reset initial interval to xr */ + freq[j] = X2ANGLE(xm); + xl = xm; + flag = 0; /* reset flag for next search */ + } + else{ + psuml=temp_psumr; + xl=temp_xr; + } + } + } + return(roots); +} + + +/*---------------------------------------------------------------------------*\ + + FUNCTION....: lsp_to_lpc() + + AUTHOR......: David Rowe + DATE CREATED: 24/2/93 + + lsp_to_lpc: This function converts LSP coefficients to LPC + coefficients. + +\*---------------------------------------------------------------------------*/ + +#ifdef FIXED_POINT + +void lsp_to_lpc(spx_lsp_t *freq,spx_coef_t *ak,int lpcrdr, char *stack) +/* float *freq array of LSP frequencies in the x domain */ +/* float *ak array of LPC coefficients */ +/* int lpcrdr order of LPC coefficients */ + + +{ + int i,j; + spx_word32_t xout1,xout2,xin1,xin2; + VARDECL(spx_word32_t *Wp); + spx_word32_t *pw,*n1,*n2,*n3,*n4=NULL; + VARDECL(spx_word16_t *freqn); + int m = lpcrdr>>1; + + ALLOC(freqn, lpcrdr, spx_word16_t); + for (i=0;i0) + { + if (xout1 + xout2>SHL32(EXTEND32(32766),8)) + ak[j-1] = 32767; + else if (xout1 + xout2 < -SHL32(EXTEND32(32766),8)) + ak[j-1] = -32767; + else + ak[j-1] = EXTRACT16(PSHR32(ADD32(xout1,xout2),8)); + } else {/*speex_warning_int("ak[0] = ", EXTRACT16(PSHR32(ADD32(xout1,xout2),8)));*/} + *(n4+1) = xin1; + *(n4+2) = xin2; + + xin1 = 0; + xin2 = 0; + } +} +#else + +void lsp_to_lpc(spx_lsp_t *freq,spx_coef_t *ak,int lpcrdr, char *stack) +/* float *freq array of LSP frequencies in the x domain */ +/* float *ak array of LPC coefficients */ +/* int lpcrdr order of LPC coefficients */ + + +{ + int i,j; + float xout1,xout2,xin1,xin2; + VARDECL(float *Wp); + float *pw,*n1,*n2,*n3,*n4=NULL; + VARDECL(float *x_freq); + int m = lpcrdr>>1; + + ALLOC(Wp, 4*m+2, float); + pw = Wp; + + /* initialise contents of array */ + + for(i=0;i<=4*m+1;i++){ /* set contents of buffer to 0 */ + *pw++ = 0.0; + } + + /* Set pointers up */ + + pw = Wp; + xin1 = 1.0; + xin2 = 1.0; + + ALLOC(x_freq, lpcrdr, float); + for (i=0;i0) + ak[j-1] = (xout1 + xout2)*0.5f; + *(n4+1) = xin1; + *(n4+2) = xin2; + + xin1 = 0.0; + xin2 = 0.0; + } + +} +#endif + + +#ifdef FIXED_POINT + +/*Makes sure the LSPs are stable*/ +void lsp_enforce_margin(spx_lsp_t *lsp, int len, spx_word16_t margin) +{ + int i; + spx_word16_t m = margin; + spx_word16_t m2 = 25736-margin; + + if (lsp[0]m2) + lsp[len-1]=m2; + for (i=1;ilsp[i+1]-m) + lsp[i]= SHR16(lsp[i],1) + SHR16(lsp[i+1]-m,1); + } +} + + +void lsp_interpolate(spx_lsp_t *old_lsp, spx_lsp_t *new_lsp, spx_lsp_t *interp_lsp, int len, int subframe, int nb_subframes) +{ + int i; + spx_word16_t tmp = DIV32_16(SHL32(EXTEND32(1 + subframe),14),nb_subframes); + spx_word16_t tmp2 = 16384-tmp; + for (i=0;iLSP_SCALING*(M_PI-margin)) + lsp[len-1]=LSP_SCALING*(M_PI-margin); + for (i=1;ilsp[i+1]-LSP_SCALING*margin) + lsp[i]= .5f* (lsp[i] + lsp[i+1]-LSP_SCALING*margin); + } +} + + +void lsp_interpolate(spx_lsp_t *old_lsp, spx_lsp_t *new_lsp, spx_lsp_t *interp_lsp, int len, int subframe, int nb_subframes) +{ + int i; + float tmp = (1.0f + subframe)/nb_subframes; + for (i=0;i +#include "ltp.h" +#include "stack_alloc.h" +#include "filters.h" +#include +#include "math_approx.h" + +#ifndef NULL +#define NULL 0 +#endif + + +#ifdef _USE_SSE +#include "ltp_sse.h" +#elif defined (ARM4_ASM) || defined(ARM5E_ASM) +#include "ltp_arm4.h" +#elif defined (BFIN_ASM) +#include "ltp_bfin.h" +#endif + +#ifndef OVERRIDE_INNER_PROD +static spx_word32_t inner_prod(const spx_word16_t *x, const spx_word16_t *y, int len) +{ + spx_word32_t sum=0; + len >>= 2; + while(len--) + { + spx_word32_t part=0; + part = MAC16_16(part,*x++,*y++); + part = MAC16_16(part,*x++,*y++); + part = MAC16_16(part,*x++,*y++); + part = MAC16_16(part,*x++,*y++); + /* HINT: If you had a 40-bit accumulator, you could shift only at the end */ + sum = ADD32(sum,SHR32(part,6)); + } + return sum; +} +#endif + +#ifndef OVERRIDE_PITCH_XCORR +#if 0 /* HINT: Enable this for machines with enough registers (i.e. not x86) */ +static void pitch_xcorr(const spx_word16_t *_x, const spx_word16_t *_y, spx_word32_t *corr, int len, int nb_pitch, char *stack) +{ + int i,j; + for (i=0;i0) + { + if (SHR16(corr16[i-start],4)>ener16[i-start]) + tmp = SHL32(EXTEND32(ener16[i-start]),14); + else if (-SHR16(corr16[i-start],4)>ener16[i-start]) + tmp = -SHL32(EXTEND32(ener16[i-start]),14); + else + tmp = SHL32(tmp,10); + g = DIV32_16(tmp, 8+ener16[i-start]); + score[i-start] = MULT16_16(corr16[i-start],g); + } else + { + score[i-start] = 1; + } + } + } +#else + for (i=start;i<=end;i++) + { + float g = corr[i-start]/(1+energy[i-start]); + if (g>16) + g = 16; + else if (g<-16) + g = -16; + score[i-start] = g*corr[i-start]; + } +#endif + + /* Extract best scores */ + for (i=start;i<=end;i++) + { + if (score[i-start]>best_score[N-1]) + { + for (j=0;j best_score[j]) + { + for (k=N-1;k>j;k--) + { + best_score[k]=best_score[k-1]; + pitch[k]=pitch[k-1]; + } + best_score[j]=score[i-start]; + pitch[j]=i; + break; + } + } + } + } + + /* Compute open-loop gain */ + if (gain) + { + for (j=0;jgain_bits; + gain_cdbk = params->gain_cdbk + 3*gain_cdbk_size*cdbk_offset; + ALLOC(tmp1, 3*nsf, spx_sig_t); + ALLOC(tmp2, 3*nsf, spx_sig_t); + + x[0]=tmp1; + x[1]=tmp1+nsf; + x[2]=tmp1+2*nsf; + + e[0]=tmp2; + e[1]=tmp2+nsf; + e[2]=tmp2+2*nsf; + for (i=2;i>=0;i--) + { + int pp=pitch+1-i; + for (j=0;j max_val) + max_val = tmp; + } + } + for (i=0;i max_val) + max_val = tmp; + } + + sig_shift=0; + while (max_val>16384) + { + sig_shift++; + max_val >>= 1; + } + + for (j=0;j<3;j++) + { + for (i=0;i 64) + { + gain_sum = SUB16(gain_sum, 64); + if (gain_sum > 127) + gain_sum = 127; +#ifdef FIXED_POINT + pitch_control = SUB16(64,EXTRACT16(PSHR32(MULT16_16(64,MULT16_16_16(plc_tuning, gain_sum)),10))); +#else + pitch_control = 64*(1.-.001*plc_tuning*gain_sum); +#endif + if (pitch_control < 0) + pitch_control = 0; + } + + sum = compute_pitch_error(C, g, pitch_control); + + if (sum>best_sum || i==0) + { + best_sum=sum; + best_cdbk=i; + } + } +#ifdef FIXED_POINT + gain[0] = ADD16(32,(spx_word16_t)gain_cdbk[best_cdbk*3]); + gain[1] = ADD16(32,(spx_word16_t)gain_cdbk[best_cdbk*3+1]); + gain[2] = ADD16(32,(spx_word16_t)gain_cdbk[best_cdbk*3+2]); + /*printf ("%d %d %d %d\n",gain[0],gain[1],gain[2], best_cdbk);*/ +#else + gain[0] = 0.015625*gain_cdbk[best_cdbk*3] + .5; + gain[1] = 0.015625*gain_cdbk[best_cdbk*3+1]+ .5; + gain[2] = 0.015625*gain_cdbk[best_cdbk*3+2]+ .5; +#endif + *cdbk_index=best_cdbk; + } + +#ifdef FIXED_POINT + for (i=0;i10) + N=10; + if (N<1) + N=1; + + ALLOC(nbest, N, int); + params = (const ltp_params*) par; + + if (endpitch_bits); + speex_bits_pack(bits, 0, params->gain_bits); + for (i=0;iend-start+1) + N=end-start+1; + if (end != start) + open_loop_nbest_pitch(sw, start, end, nsf, nbest, NULL, N, stack); + else + nbest[0] = start; + for (i=0;ipitch_bits); + speex_bits_pack(bits, best_gain_index, params->gain_bits); + /*printf ("encode pitch: %d %d\n", best_pitch, best_gain_index);*/ + for (i=0;igain_bits; + gain_cdbk = params->gain_cdbk + 3*gain_cdbk_size*cdbk_offset; + + pitch = speex_bits_unpack_unsigned(bits, params->pitch_bits); + pitch += start; + gain_index = speex_bits_unpack_unsigned(bits, params->gain_bits); + /*printf ("decode pitch: %d %d\n", pitch, gain_index);*/ +#ifdef FIXED_POINT + gain[0] = ADD16(32,(spx_word16_t)gain_cdbk[gain_index*3]); + gain[1] = ADD16(32,(spx_word16_t)gain_cdbk[gain_index*3+1]); + gain[2] = ADD16(32,(spx_word16_t)gain_cdbk[gain_index*3+2]); +#else + gain[0] = 0.015625*gain_cdbk[gain_index*3]+.5; + gain[1] = 0.015625*gain_cdbk[gain_index*3+1]+.5; + gain[2] = 0.015625*gain_cdbk[gain_index*3+2]+.5; +#endif + + if (count_lost && pitch > subframe_offset) + { + spx_word16_t gain_sum; + if (1) { +#ifdef FIXED_POINT + spx_word16_t tmp = count_lost < 4 ? last_pitch_gain : SHR16(last_pitch_gain,1); + if (tmp>62) + tmp=62; +#else + spx_word16_t tmp = count_lost < 4 ? last_pitch_gain : 0.5 * last_pitch_gain; + if (tmp>.95) + tmp=.95; +#endif + gain_sum = gain_3tap_to_1tap(gain); + + if (gain_sum > tmp) + { + spx_word16_t fact = DIV32_16(SHL32(EXTEND32(tmp),14),gain_sum); + for (i=0;i<3;i++) + gain[i]=MULT16_16_Q14(fact,gain[i]); + } + + } + + } + + *pitch_val = pitch; + gain_val[0]=gain[0]; + gain_val[1]=gain[1]; + gain_val[2]=gain[2]; + + { + spx_sig_t *e[3]; + VARDECL(spx_sig_t *tmp2); + ALLOC(tmp2, 3*nsf, spx_sig_t); + e[0]=tmp2; + e[1]=tmp2+nsf; + e[2]=tmp2+2*nsf; + + for (i=0;i<3;i++) + { + int j; + int pp=pitch+1-i; +#if 0 + for (j=0;jpp) + tmp1=pp; + for (j=0;jpp+pitch) + tmp3=pp+pitch; + for (j=tmp1;j.99) + coef=.99; + for (i=0;i.99) + coef=.99; + for (i=0;i +#include "misc.h" + +typedef struct ltp_params { + const signed char *gain_cdbk; + int gain_bits; + int pitch_bits; +} ltp_params; + +#ifdef FIXED_POINT +#define gain_3tap_to_1tap(g) (ABS(g[1]) + (g[0]>0 ? g[0] : -SHR16(g[0],1)) + (g[2]>0 ? g[2] : -SHR16(g[2],1))) +#else +#define gain_3tap_to_1tap(g) (ABS(g[1]) + (g[0]>0 ? g[0] : -.5*g[0]) + (g[2]>0 ? g[2] : -.5*g[2])) +#endif + +void open_loop_nbest_pitch(spx_sig_t *sw, int start, int end, int len, int *pitch, spx_word16_t *gain, int N, char *stack); + + +/** Finds the best quantized 3-tap pitch predictor by analysis by synthesis */ +int pitch_search_3tap( +spx_sig_t target[], /* Target vector */ +spx_sig_t *sw, +spx_coef_t ak[], /* LPCs for this subframe */ +spx_coef_t awk1[], /* Weighted LPCs #1 for this subframe */ +spx_coef_t awk2[], /* Weighted LPCs #2 for this subframe */ +spx_sig_t exc[], /* Overlapping codebook */ +const void *par, +int start, /* Smallest pitch value allowed */ +int end, /* Largest pitch value allowed */ +spx_word16_t pitch_coef, /* Voicing (pitch) coefficient */ +int p, /* Number of LPC coeffs */ +int nsf, /* Number of samples in subframe */ +SpeexBits *bits, +char *stack, +spx_sig_t *exc2, +spx_word16_t *r, +int complexity, +int cdbk_offset, +int plc_tuning +); + +/*Unquantize adaptive codebook and update pitch contribution*/ +void pitch_unquant_3tap( +spx_sig_t exc[], /* Excitation */ +int start, /* Smallest pitch value allowed */ +int end, /* Largest pitch value allowed */ +spx_word16_t pitch_coef, /* Voicing (pitch) coefficient */ +const void *par, +int nsf, /* Number of samples in subframe */ +int *pitch_val, +spx_word16_t *gain_val, +SpeexBits *bits, +char *stack, +int lost, +int subframe_offset, +spx_word16_t last_pitch_gain, +int cdbk_offset +); + +/** Forced pitch delay and gain */ +int forced_pitch_quant( +spx_sig_t target[], /* Target vector */ +spx_sig_t *sw, +spx_coef_t ak[], /* LPCs for this subframe */ +spx_coef_t awk1[], /* Weighted LPCs #1 for this subframe */ +spx_coef_t awk2[], /* Weighted LPCs #2 for this subframe */ +spx_sig_t exc[], /* Excitation */ +const void *par, +int start, /* Smallest pitch value allowed */ +int end, /* Largest pitch value allowed */ +spx_word16_t pitch_coef, /* Voicing (pitch) coefficient */ +int p, /* Number of LPC coeffs */ +int nsf, /* Number of samples in subframe */ +SpeexBits *bits, +char *stack, +spx_sig_t *exc2, +spx_word16_t *r, +int complexity, +int cdbk_offset, +int plc_tuning +); + +/** Unquantize forced pitch delay and gain */ +void forced_pitch_unquant( +spx_sig_t exc[], /* Excitation */ +int start, /* Smallest pitch value allowed */ +int end, /* Largest pitch value allowed */ +spx_word16_t pitch_coef, /* Voicing (pitch) coefficient */ +const void *par, +int nsf, /* Number of samples in subframe */ +int *pitch_val, +spx_word16_t *gain_val, +SpeexBits *bits, +char *stack, +int lost, +int subframe_offset, +spx_word16_t last_pitch_gain, +int cdbk_offset +); diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/ltp_arm4.h b/mozilla/zap/zmk/speex-1.1.10/libspeex/ltp_arm4.h new file mode 100755 index 00000000000..981294a7114 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/ltp_arm4.h @@ -0,0 +1,186 @@ +/* Copyright (C) 2004 Jean-Marc Valin + File: ltp.c + Lont-Term Prediction functions (SSE version) + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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. +*/ + +#define OVERRIDE_INNER_PROD +static spx_word32_t inner_prod(const spx_word16_t *x, const spx_word16_t *y, int len) +{ + spx_word32_t sum1=0,sum2=0; + spx_word16_t *deadx, *deady; + int deadlen, dead1, dead2, dead3, dead4, dead5, dead6; + __asm__ __volatile__ ( + "\tldrsh %5, [%0], #2 \n" + "\tldrsh %6, [%1], #2 \n" + ".inner_prod_loop%=:\n" + "\tsub %7, %7, %7\n" + "\tsub %10, %10, %10\n" + + "\tldrsh %8, [%0], #2 \n" + "\tldrsh %9, [%1], #2 \n" + "\tmla %7, %5, %6, %7\n" + "\tldrsh %5, [%0], #2 \n" + "\tldrsh %6, [%1], #2 \n" + "\tmla %10, %8, %9, %10\n" + "\tldrsh %8, [%0], #2 \n" + "\tldrsh %9, [%1], #2 \n" + "\tmla %7, %5, %6, %7\n" + "\tldrsh %5, [%0], #2 \n" + "\tldrsh %6, [%1], #2 \n" + "\tmla %10, %8, %9, %10\n" + + "\tldrsh %8, [%0], #2 \n" + "\tldrsh %9, [%1], #2 \n" + "\tmla %7, %5, %6, %7\n" + "\tldrsh %5, [%0], #2 \n" + "\tldrsh %6, [%1], #2 \n" + "\tmla %10, %8, %9, %10\n" + "\tldrsh %8, [%0], #2 \n" + "\tldrsh %9, [%1], #2 \n" + "\tmla %7, %5, %6, %7\n" + "\tldrsh %5, [%0], #2 \n" + "\tldrsh %6, [%1], #2 \n" + "\tmla %10, %8, %9, %10\n" + + "\tsubs %4, %4, #1\n" + "\tadd %2, %2, %7, asr #5\n" + "\tadd %3, %3, %10, asr #5\n" + "\tbne .inner_prod_loop%=\n" + : "=r" (deadx), "=r" (deady), "=r" (sum1), "=r" (sum2), "=r" (deadlen), + "=r" (dead1), "=r" (dead2), "=r" (dead3), "=r" (dead4), "=r" (dead5), "=r" (dead6) + : "0" (x), "1" (y), "2" (sum1), "3" (sum2), "4" (len>>3) + : "cc" + ); + return (sum1+sum2)>>1; +} + +#define OVERRIDE_PITCH_XCORR +static void pitch_xcorr(const spx_word16_t *_x, const spx_word16_t *_y, spx_word32_t *corr, int len, int nb_pitch, char *stack) +{ + int i,j; + for (i=0;i>> 6;\n\t" + "R0 = A0;\n\t" + "%0 = R0;\n\t" + : "=m" (sum) + : "m" (x), "m" (y), "d" (len-1) + : "P0", "P1", "P2", "R0", "R1", "A0", "I0", "I1", "L0", "L1", "R3" + ); + return sum; +} + +#define OVERRIDE_PITCH_XCORR +static void pitch_xcorr(const spx_word16_t *_x, const spx_word16_t *_y, spx_word32_t *corr, int len, int nb_pitch, char *stack) +{ + corr += nb_pitch - 1; + __asm__ __volatile__ ( + "P2 = %0;\n\t" + "I0 = P2;\n\t" /* x in I0 */ + "B0 = P2;\n\t" /* x in B0 */ + "R0 = %3;\n\t" /* len in R0 */ + "P3 = %3;\n\t" + "P3 += -2;\n\t" /* len in R0 */ + "P4 = %4;\n\t" /* nb_pitch in R0 */ + "R1 = R0 << 1;\n\t" /* number of bytes in x */ + "L0 = R1;\n\t" + "P0 = %1;\n\t" + + "P1 = %2;\n\t" + "B1 = P1;\n\t" + "L1 = 0;\n\t" /*Disable looping on I1*/ + + "r0 = [I0++];\n\t" + "LOOP pitch%= LC0 = P4 >> 1;\n\t" + "LOOP_BEGIN pitch%=;\n\t" + "I1 = P0;\n\t" + "A1 = A0 = 0;\n\t" + "R1 = [I1++];\n\t" + "LOOP inner_prod%= LC1 = P3 >> 1;\n\t" + "LOOP_BEGIN inner_prod%=;\n\t" + "A0 += R0.L*R1.L , A1 += R0.L*R1.H (is) || R1.L = W[I1++];\n\t" + "A0 += R0.H*R1.H , A1 += R0.H*R1.L (is) || R1.H = W[I1++] || R0 = [I0++];\n\t" + "LOOP_END inner_prod%=;\n\t" + "A0 += R0.L*R1.L , A1 += R0.L*R1.H (is) || R1.L = W[I1++];\n\t" + "A0 += R0.H*R1.H , A1 += R0.H*R1.L (is) || R0 = [I0++];\n\t" + "A0 = A0 >>> 6;\n\t" + "A1 = A1 >>> 6;\n\t" + "R2 = A0, R3 = A1;\n\t" + "[P1--] = r2;\n\t" + "[P1--] = r3;\n\t" + "P0 += 4;\n\t" + "LOOP_END pitch%=;\n\t" + "L0 = 0;\n\t" + : : "m" (_x), "m" (_y), "m" (corr), "m" (len), "m" (nb_pitch) + : "A0", "A1", "P0", "P1", "P2", "P3", "P4", "R0", "R1", "R2", "R3", "I0", "I1", "L0", "L1", "B0", "B1", "memory" + ); +} + +#define OVERRIDE_COMPUTE_PITCH_ERROR +static inline spx_word32_t compute_pitch_error(spx_word32_t *C, spx_word16_t *g, spx_word16_t pitch_control) +{ + spx_word32_t sum; + __asm__ __volatile__ + ( + "A0 = A1 = 0;\n\t" + + "R0 = [%1++];\n\t" + "R1.L = %2.L*%5.L (IS);\n\t" + "R0 <<= 1;\n\t" + "A0 += R1.L*R0.H (IS), A1 += R1.L*R0.L (M,IS) || R0 = [%1++];\n\t" + + "R1.L = %3.L*%5.L (IS);\n\t" + "R0 <<= 1;\n\t" + "A0 += R1.L*R0.H (IS), A1 += R1.L*R0.L (M,IS) || R0 = [%1++];\n\t" + + "R1.L = %4.L*%5.L (IS);\n\t" + "R0 <<= 1;\n\t" + "A0 += R1.L*R0.H (IS), A1 += R1.L*R0.L (M,IS) || R0 = [%1++];\n\t" + + "R1.L = %2.L*%3.L (IS);\n\t" + "R0 <<= 1;\n\t" + "A0 -= R1.L*R0.H (IS), A1 -= R1.L*R0.L (M,IS) || R0 = [%1++];\n\t" + + "R1.L = %4.L*%3.L (IS);\n\t" + "R0 <<= 1;\n\t" + "A0 -= R1.L*R0.H (IS), A1 -= R1.L*R0.L (M,IS) || R0 = [%1++];\n\t" + + "R1.L = %4.L*%2.L (IS);\n\t" + "R0 <<= 1;\n\t" + "A0 -= R1.L*R0.H (IS), A1 -= R1.L*R0.L (M,IS) || R0 = [%1++];\n\t" + + "R1.L = %2.L*%2.L (IS);\n\t" + "R0 <<= 1;\n\t" + "A0 -= R1.L*R0.H (IS), A1 -= R1.L*R0.L (M,IS) || R0 = [%1++];\n\t" + + "R1.L = %3.L*%3.L (IS);\n\t" + "R0 <<= 1;\n\t" + "A0 -= R1.L*R0.H (IS), A1 -= R1.L*R0.L (M,IS) || R0 = [%1++];\n\t" + + "R1.L = %4.L*%4.L (IS);\n\t" + "R0 <<= 1;\n\t" + "A0 -= R1.L*R0.H (IS), A1 -= R1.L*R0.L (M,IS);\n\t" + + "A1 = A1 >>> 16;\n\t" + "A0 += A1;\n\t" + "%0 = A0;\n\t" + : "=&D" (sum), "=a" (C) + : "d" (g[0]), "d" (g[1]), "d" (g[2]), "d" (pitch_control), "1" (C) + : "R0", "R1", "R2", "A0" + ); + return sum; +} + diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/ltp_sse.h b/mozilla/zap/zmk/speex-1.1.10/libspeex/ltp_sse.h new file mode 100755 index 00000000000..09a94dfb318 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/ltp_sse.h @@ -0,0 +1,90 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: ltp.c + Lont-Term Prediction functions (SSE version) + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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. +*/ + +#include + +#define OVERRIDE_INNER_PROD +static float inner_prod(const float *a, const float *b, int len) +{ + int i; + float ret; + __m128 sum = _mm_setzero_ps(); + for (i=0;i<(len>>2);i+=2) + { + sum = _mm_add_ps(sum, _mm_mul_ps(_mm_loadu_ps(a+0), _mm_loadu_ps(b+0))); + sum = _mm_add_ps(sum, _mm_mul_ps(_mm_loadu_ps(a+4), _mm_loadu_ps(b+4))); + a += 8; + b += 8; + } + sum = _mm_add_ps(sum, _mm_movehl_ps(sum, sum)); + sum = _mm_add_ss(sum, _mm_shuffle_ps(sum, sum, 0x55)); + _mm_store_ss(&ret, sum); + return ret; +} + +#define OVERRIDE_PITCH_XCORR +static void pitch_xcorr(const float *_x, const float *_y, float *corr, int len, int nb_pitch, char *stack) +{ + int i, offset; + VARDECL(__m128 *x); + VARDECL(__m128 *y); + int N, L; + N = len>>2; + L = nb_pitch>>2; + ALLOC(x, N, __m128); + ALLOC(y, N+L, __m128); + for (i=0;i16777216) + { + x>>=10; + k+=5; + } + if (x>1048576) + { + x>>=6; + k+=3; + } + if (x>262144) + { + x>>=4; + k+=2; + } + if (x>32768) + { + x>>=2; + k+=1; + } + if (x>16384) + { + x>>=2; + k+=1; + } +#else + while (x>16384) + { + x>>=2; + k++; + } +#endif + while (x<4096) + { + x<<=2; + k--; + } + rt = ADD16(C0, MULT16_16_Q14(x, ADD16(C1, MULT16_16_Q14(x, ADD16(C2, MULT16_16_Q14(x, (C3))))))); + if (k>0) + rt <<= k; + else + rt >>= -k; + rt >>=7; + return rt; +} + +/* log(x) ~= -2.18151 + 4.20592*x - 2.88938*x^2 + 0.86535*x^3 (for .5 < x < 1) */ + + +#define A1 16469 +#define A2 2242 +#define A3 1486 + +spx_word16_t spx_acos(spx_word16_t x) +{ + int s=0; + spx_word16_t ret; + spx_word16_t sq; + if (x<0) + { + s=1; + x = NEG16(x); + } + x = SUB16(16384,x); + + x = x >> 1; + sq = MULT16_16_Q13(x, ADD16(A1, MULT16_16_Q13(x, ADD16(A2, MULT16_16_Q13(x, (A3)))))); + ret = spx_sqrt(SHL32(EXTEND32(sq),13)); + + /*ret = spx_sqrt(67108864*(-1.6129e-04 + 2.0104e+00*f + 2.7373e-01*f*f + 1.8136e-01*f*f*f));*/ + if (s) + ret = SUB16(25736,ret); + return ret; +} + +#endif diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/math_approx.h b/mozilla/zap/zmk/speex-1.1.10/libspeex/math_approx.h new file mode 100755 index 00000000000..a35a666b6d3 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/math_approx.h @@ -0,0 +1,46 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: math_approx.c + Various math approximation functions for Speex + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 MATH_APPROX_H +#define MATH_APPROX_H + +#include "misc.h" + +#ifdef FIXED_POINT +spx_word16_t spx_sqrt(spx_word32_t x); +spx_word16_t spx_acos(spx_word16_t x); +#else +#define spx_sqrt sqrt +#define spx_acos acos +#endif + +#endif diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/mdf.c b/mozilla/zap/zmk/speex-1.1.10/libspeex/mdf.c new file mode 100755 index 00000000000..e3129e0b5c1 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/mdf.c @@ -0,0 +1,539 @@ +/* Copyright (C) 2003-2005 Jean-Marc Valin + + File: speex_echo.c + Echo cancelling based on the MDF algorithm described in: + + J. S. Soo, K. K. Pang Multidelay block frequency adaptive filter, + IEEE Trans. Acoust. Speech Signal Process., Vol. ASSP-38, No. 2, + February 1990. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. 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. + + 3. The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "misc.h" +#include "speex/speex_echo.h" +#include "smallft.h" +#include + +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif + +#undef BETA +#define BETA .65 + +#define min(a,b) ((a)<(b) ? (a) : (b)) +#define max(a,b) ((a)>(b) ? (a) : (b)) + +/** Compute inner product of two real vectors */ +static inline float inner_prod(float *x, float *y, int N) +{ + int i; + float ret=0; + for (i=0;iframe_size = frame_size; + st->window_size = 2*frame_size; + N = st->window_size; + M = st->M = (filter_length+st->frame_size-1)/frame_size; + st->cancel_count=0; + st->adapt_rate = .01f; + st->sum_adapt = 0; + st->Sey = 0; + st->Syy = 0; + st->See = 0; + + st->fft_lookup = (struct drft_lookup*)speex_alloc(sizeof(struct drft_lookup)); + spx_drft_init(st->fft_lookup, N); + + st->x = (float*)speex_alloc(N*sizeof(float)); + st->d = (float*)speex_alloc(N*sizeof(float)); + st->y = (float*)speex_alloc(N*sizeof(float)); + st->y2 = (float*)speex_alloc(N*sizeof(float)); + st->Yps = (float*)speex_alloc(N*sizeof(float)); + st->last_y = (float*)speex_alloc(N*sizeof(float)); + st->Yf = (float*)speex_alloc((st->frame_size+1)*sizeof(float)); + st->Rf = (float*)speex_alloc((st->frame_size+1)*sizeof(float)); + st->Xf = (float*)speex_alloc((st->frame_size+1)*sizeof(float)); + st->fratio = (float*)speex_alloc((st->frame_size+1)*sizeof(float)); + st->regul = (float*)speex_alloc(N*sizeof(float)); + + st->X = (float*)speex_alloc(M*N*sizeof(float)); + st->D = (float*)speex_alloc(N*sizeof(float)); + st->Y = (float*)speex_alloc(N*sizeof(float)); + st->Y2 = (float*)speex_alloc(N*sizeof(float)); + st->E = (float*)speex_alloc(N*sizeof(float)); + st->W = (float*)speex_alloc(M*N*sizeof(float)); + st->PHI = (float*)speex_alloc(M*N*sizeof(float)); + st->power = (float*)speex_alloc((frame_size+1)*sizeof(float)); + st->power_1 = (float*)speex_alloc((frame_size+1)*sizeof(float)); + st->grad = (float*)speex_alloc(N*M*sizeof(float)); + + for (i=0;iW[i] = st->PHI[i] = 0; + } + + st->regul[0] = (.01+(10.)/((4.)*(4.)))/M; + for (i=1,j=1;iregul[i] = .01+((10.)/((j+4.)*(j+4.)))/M; + st->regul[i+1] = .01+((10.)/((j+4.)*(j+4.)))/M; + } + st->regul[i] = .01+((10.)/((j+4.)*(j+4.)))/M; + + st->adapted = 0; + return st; +} + +/** Resets echo canceller state */ +void speex_echo_state_reset(SpeexEchoState *st) +{ + int i, M, N; + st->cancel_count=0; + st->adapt_rate = .01f; + N = st->window_size; + M = st->M; + for (i=0;iW[i] = 0; + st->X[i] = 0; + } + for (i=0;i<=st->frame_size;i++) + st->power[i] = 0; + + st->adapted = 0; + st->adapt_rate = .01f; + st->sum_adapt = 0; + st->Sey = 0; + st->Syy = 0; + st->See = 0; + +} + +/** Destroys an echo canceller state */ +void speex_echo_state_destroy(SpeexEchoState *st) +{ + spx_drft_clear(st->fft_lookup); + speex_free(st->fft_lookup); + speex_free(st->x); + speex_free(st->d); + speex_free(st->y); + speex_free(st->last_y); + speex_free(st->Yps); + speex_free(st->Yf); + speex_free(st->Rf); + speex_free(st->Xf); + speex_free(st->fratio); + speex_free(st->regul); + + speex_free(st->X); + speex_free(st->D); + speex_free(st->Y); + speex_free(st->E); + speex_free(st->W); + speex_free(st->PHI); + speex_free(st->power); + speex_free(st->power_1); + speex_free(st->grad); + + speex_free(st); +} + + +/** Performs echo cancellation on a frame */ +void speex_echo_cancel(SpeexEchoState *st, short *ref, short *echo, short *out, float *Yout) +{ + int i,j,m; + int N,M; + float scale; + float ESR; + float SER; + float Sry=0,Srr=0,Syy=0,Sey=0,See=0,Sxx=0; + float leak_estimate; + + /*leak_estimate = .1+(.9/(1+2*st->sum_adapt));*/ + leak_estimate = (.1 + (1-st->sum_adapt)*(1-st->sum_adapt))/(.9*st->sum_adapt*st->sum_adapt + .1); + + N = st->window_size; + M = st->M; + scale = 1.0f/N; + st->cancel_count++; + + /* Copy input data to buffer */ + for (i=0;iframe_size;i++) + { + st->x[i] = st->x[i+st->frame_size]; + st->x[i+st->frame_size] = echo[i]; + + st->d[i] = st->d[i+st->frame_size]; + st->d[i+st->frame_size] = ref[i]; + } + + /* Shift memory: this could be optimized eventually*/ + for (i=0;iX[i]=st->X[i+N]; + + /* Copy new echo frame */ + for (i=0;iX[(M-1)*N+i]=st->x[i]; + + /* Convert x (echo input) to frequency domain */ + spx_drft_forward(st->fft_lookup, &st->X[(M-1)*N]); + + /* Compute filter response Y */ + for (i=0;iY[i] = 0; + for (j=0;jX[j*N], &st->W[j*N], st->Y, N); + + /* Convert Y (filter response) to time domain */ + for (i=0;iy[i] = st->Y[i]; + spx_drft_backward(st->fft_lookup, st->y); + for (i=0;iy[i] *= scale; + + /* Transform d (reference signal) to frequency domain */ + for (i=0;iD[i]=st->d[i]; + spx_drft_forward(st->fft_lookup, st->D); + + /* Compute error signal (signal with echo removed) */ + for (i=0;iframe_size;i++) + { + float tmp_out; + tmp_out = (float)ref[i] - st->y[i+st->frame_size]; + + st->E[i] = 0; + st->E[i+st->frame_size] = tmp_out; + + /* Saturation */ + if (tmp_out>32767) + tmp_out = 32767; + else if (tmp_out<-32768) + tmp_out = -32768; + out[i] = tmp_out; + } + + /* This bit of code is optional and provides faster adaptation by doing a projection + of the previous gradient on the "MMSE surface" */ + if (1) + { + float Sge, Sgg, Syy; + float gain; + Syy = inner_prod(st->y+st->frame_size, st->y+st->frame_size, st->frame_size); + for (i=0;iY2[i] = 0; + for (j=0;jX[j*N], &st->PHI[j*N], st->Y2, N); + for (i=0;iy2[i] = st->Y2[i]; + spx_drft_backward(st->fft_lookup, st->y2); + for (i=0;iy2[i] *= scale; + Sge = inner_prod(st->y2+st->frame_size, st->E+st->frame_size, st->frame_size); + Sgg = inner_prod(st->y2+st->frame_size, st->y2+st->frame_size, st->frame_size); + /* Compute projection gain */ + gain = Sge/(N+.03*Syy+Sgg); + if (gain>2) + gain = 2; + if (gain < -2) + gain = -2; + + /* Apply gain to weights, echo estimates, output */ + for (i=0;iY[i] += gain*st->Y2[i]; + for (i=0;iframe_size;i++) + { + st->y[i+st->frame_size] += gain*st->y2[i+st->frame_size]; + st->E[i+st->frame_size] -= gain*st->y2[i+st->frame_size]; + } + for (i=0;iW[i] += gain*st->PHI[i]; + } + + /* Compute power spectrum of output (D-Y) and filter response (Y) */ + for (i=0;iD[i] -= st->Y[i]; + power_spectrum(st->D, st->Rf, N); + power_spectrum(st->Y, st->Yf, N); + + /* Compute frequency-domain adaptation mask */ + for (j=0;j<=st->frame_size;j++) + { + float r; + r = leak_estimate*st->Yf[j] / (1+st->Rf[j]); + if (r>1) + r = 1; + st->fratio[j] = r; + } + + /* Compute a bunch of correlations */ + Sry = inner_prod(st->y+st->frame_size, st->d+st->frame_size, st->frame_size); + Sey = inner_prod(st->y+st->frame_size, st->E+st->frame_size, st->frame_size); + See = inner_prod(st->E+st->frame_size, st->E+st->frame_size, st->frame_size); + Syy = inner_prod(st->y+st->frame_size, st->y+st->frame_size, st->frame_size); + Srr = inner_prod(st->d+st->frame_size, st->d+st->frame_size, st->frame_size); + Sxx = inner_prod(st->x+st->frame_size, st->x+st->frame_size, st->frame_size); + + /* Compute smoothed cross-correlation and energy */ + st->Sey = .98*st->Sey + .02*Sey; + st->Syy = .98*st->Syy + .02*Syy; + st->See = .98*st->See + .02*See; + + /* Check if filter is completely mis-adapted (if so, reset filter) */ + if (st->Sey/(1+st->Syy + .01*st->See) < -1) + { + /*fprintf (stderr, "reset at %d\n", st->cancel_count);*/ + speex_echo_state_reset(st); + return; + } + + SER = Srr / (1+Sxx); + ESR = leak_estimate*Syy / (1+See); + if (ESR>1) + ESR = 1; +#if 1 + /* If over-cancellation (creating echo with 180 phase) damp filter */ + if (st->Sey/(1+st->Syy) < -.1 && (ESR > .3)) + { + for (i=0;iW[i] *= .95; + st->Sey *= .5; + st->sum_adapt*= .95; + /*fprintf (stderr, "corrected down\n");*/ + } +#endif +#if 1 + /* If under-cancellation (leaving echo with 0 phase) scale filter up */ + if (st->Sey/(1+st->Syy) > .1 && (ESR > .1 || SER < 10)) + { + for (i=0;iW[i] *= 1.05; + st->Sey *= .5; + /*fprintf (stderr, "corrected up %d\n", st->cancel_count);*/ + } +#endif + + /* We consider that the filter is adapted if the following is true*/ + if (ESR>.6 && st->sum_adapt > .7 && !st->adapted) + { + /*fprintf(stderr, "Adapted at %d %f\n", st->cancel_count, st->sum_adapt);*/ + st->adapted = 1; + } else if (st->sum_adapt < .5 && st->adapted) + { + /*fprintf(stderr, "Un-adapted at %d %f\n", st->cancel_count, st->sum_adapt);*/ + st->adapted = 0; + } + + /* Update frequency-dependent energy ratio with the total energy ratio */ + for (i=0;i<=st->frame_size;i++) + { + st->fratio[i] = (.2*ESR+.8*min(ESR,st->fratio[i])); + } + + if (st->adapted) + { + st->adapt_rate = .95f/(2+M); + /* How much have we adapted so far? */ + st->sum_adapt = (1-st->adapt_rate)*st->sum_adapt + st->adapt_rate; + } else { + /* Temporary adaption rate if filter is not adapted correctly */ + if (SER<.1) + st->adapt_rate =.5/(2+M); + else if (SER<1) + st->adapt_rate =.3/(2+M); + else if (SER<10) + st->adapt_rate =.2/(2+M); + else if (SER<30) + st->adapt_rate =.08/(2+M); + else + st->adapt_rate = 0; + /* How much have we adapted so far? */ + st->sum_adapt = (1-ESR*st->adapt_rate)*st->sum_adapt + ESR*st->adapt_rate; + } + + /* How much have we adapted so far? */ + /*st->sum_adapt += st->adapt_rate;*/ + + /* Compute echo power in each frequency bin */ + { + float ss = 1.0f/st->cancel_count; + if (ss < .3/M) + ss=.3/M; + power_spectrum(&st->X[(M-1)*N], st->Xf, N); + /* Smooth echo energy estimate over time */ + for (j=0;j<=st->frame_size;j++) + st->power[j] = (1-ss)*st->power[j] + ss*st->Xf[j]; + + + /* Combine adaptation rate to the the inverse energy estimate */ + if (st->adapted) + { + /* If filter is adapted, include the frequency-dependent ratio too */ + for (i=0;i<=st->frame_size;i++) + st->power_1[i] = st->adapt_rate*st->fratio[i] /(1.f+st->power[i]); + } else { + for (i=0;i<=st->frame_size;i++) + st->power_1[i] = st->adapt_rate/(1.f+st->power[i]); + } + } + + + /* Convert error to frequency domain */ + spx_drft_forward(st->fft_lookup, st->E); + + /* Do some regularization (prevents problems when system is ill-conditoned) */ + for (m=0;mW[m*N+i] *= 1-st->regul[i]*ESR; + + /* Compute weight gradient */ + for (j=0;jpower_1, &st->X[j*N], st->E, st->PHI+N*j, N); + } + + /* Gradient descent */ + for (i=0;iW[i] += st->PHI[i]; + + /* AUMDF weight constraint */ + for (j=0;jcancel_count%M == j) + { + spx_drft_backward(st->fft_lookup, &st->W[j*N]); + for (i=0;iW[j*N+i]*=scale; + for (i=st->frame_size;iW[j*N+i]=0; + } + spx_drft_forward(st->fft_lookup, &st->W[j*N]); + } + } + + /* Compute spectrum of estimated echo for use in an echo post-filter (if necessary)*/ + if (Yout) + { + if (st->adapted) + { + /* If the filter is adapted, take the filtered echo */ + for (i=0;iframe_size;i++) + st->last_y[i] = st->last_y[st->frame_size+i]; + for (i=0;iframe_size;i++) + st->last_y[st->frame_size+i] = st->y[st->frame_size+i]; + } else { + /* If filter isn't adapted yet, all we can do is take the echo signal directly */ + for (i=0;ilast_y[i] = st->x[i]; + } + + /* Apply hanning window (should pre-compute it)*/ + for (i=0;iYps[i] = (.5-.5*cos(2*M_PI*i/N))*st->last_y[i]; + + /* Compute power spectrum of the echo */ + spx_drft_forward(st->fft_lookup, st->Yps); + power_spectrum(st->Yps, st->Yps, N); + + /* Estimate residual echo */ + for (i=0;i<=st->frame_size;i++) + Yout[i] = 2*leak_estimate*st->Yps[i]; + } + +} + diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/misc.c b/mozilla/zap/zmk/speex-1.1.10/libspeex/misc.c new file mode 100755 index 00000000000..43dac34c51c --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/misc.c @@ -0,0 +1,212 @@ +/* Copyright (C) 2002-2005 Jean-Marc Valin + File: mics.c + Various utility routines for Speex + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 +#include +#include +#include "misc.h" + +#ifdef BFIN_ASM +#include "misc_bfin.h" +#endif + +#ifndef RELEASE +void print_vec(float *vec, int len, char *name) +{ + int i; + printf ("%s ", name); + for (i=0;i>24; + ret += (i>>8)&0x0000ff00; + ret += (i<<8)&0x00ff0000; + ret += (i<<24); +#endif + return ret; +} + +spx_uint32_t le_int(spx_uint32_t i) +{ + spx_uint32_t ret=i; +#ifdef WORDS_BIGENDIAN + ret = i>>24; + ret += (i>>8)&0x0000ff00; + ret += (i<<8)&0x00ff0000; + ret += (i<<24); +#endif + return ret; +} + +#if BYTES_PER_CHAR == 2 +void speex_memcpy_bytes(char *dst, char *src, int nbytes) +{ + int i; + int nchars = nbytes/BYTES_PER_CHAR; + for (i=0;i>2)-1), "0" (src), "1" (dest) + : "R0", "I0", "L0", "memory" + ); + return dest; +} diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/modes.c b/mozilla/zap/zmk/speex-1.1.10/libspeex/modes.c new file mode 100755 index 00000000000..2bc9642e79f --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/modes.c @@ -0,0 +1,722 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: modes.c + + Describes the different modes of the codec + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 "modes.h" +#include "ltp.h" +#include "quant_lsp.h" +#include "cb_search.h" +#include "sb_celp.h" +#include "nb_celp.h" +#include "vbr.h" +#include "misc.h" +#include + +#ifndef NULL +#define NULL 0 +#endif + +#define MAX_IN_SAMPLES 640 + +const SpeexMode * const speex_mode_list[SPEEX_NB_MODES] = {&speex_nb_mode, &speex_wb_mode, &speex_uwb_mode}; + +/* Extern declarations for all codebooks we use here */ +extern const signed char gain_cdbk_nb[]; +extern const signed char gain_cdbk_lbr[]; +extern const signed char hexc_table[]; +extern const signed char exc_5_256_table[]; +extern const signed char exc_5_64_table[]; +extern const signed char exc_8_128_table[]; +extern const signed char exc_10_32_table[]; +extern const signed char exc_10_16_table[]; +extern const signed char exc_20_32_table[]; +extern const signed char hexc_10_32_table[]; + + +/* Parameters for Long-Term Prediction (LTP)*/ +static const ltp_params ltp_params_nb = { + gain_cdbk_nb, + 7, + 7 +}; + +/* Parameters for Long-Term Prediction (LTP)*/ +static const ltp_params ltp_params_vlbr = { + gain_cdbk_lbr, + 5, + 0 +}; + +/* Parameters for Long-Term Prediction (LTP)*/ +static const ltp_params ltp_params_lbr = { + gain_cdbk_lbr, + 5, + 7 +}; + +/* Parameters for Long-Term Prediction (LTP)*/ +static const ltp_params ltp_params_med = { + gain_cdbk_lbr, + 5, + 7 +}; + +/* Split-VQ innovation parameters for very low bit-rate narrowband */ +static const split_cb_params split_cb_nb_vlbr = { + 10, /*subvect_size*/ + 4, /*nb_subvect*/ + exc_10_16_table, /*shape_cb*/ + 4, /*shape_bits*/ + 0, +}; + +/* Split-VQ innovation parameters for very low bit-rate narrowband */ +static const split_cb_params split_cb_nb_ulbr = { + 20, /*subvect_size*/ + 2, /*nb_subvect*/ + exc_20_32_table, /*shape_cb*/ + 5, /*shape_bits*/ + 0, +}; + +/* Split-VQ innovation parameters for low bit-rate narrowband */ +static const split_cb_params split_cb_nb_lbr = { + 10, /*subvect_size*/ + 4, /*nb_subvect*/ + exc_10_32_table, /*shape_cb*/ + 5, /*shape_bits*/ + 0, +}; + + +/* Split-VQ innovation parameters narrowband */ +static const split_cb_params split_cb_nb = { + 5, /*subvect_size*/ + 8, /*nb_subvect*/ + exc_5_64_table, /*shape_cb*/ + 6, /*shape_bits*/ + 0, +}; + +/* Split-VQ innovation parameters narrowband */ +static const split_cb_params split_cb_nb_med = { + 8, /*subvect_size*/ + 5, /*nb_subvect*/ + exc_8_128_table, /*shape_cb*/ + 7, /*shape_bits*/ + 0, +}; + +/* Split-VQ innovation for low-band wideband */ +static const split_cb_params split_cb_sb = { + 5, /*subvect_size*/ + 8, /*nb_subvect*/ + exc_5_256_table, /*shape_cb*/ + 8, /*shape_bits*/ + 0, +}; + +#ifndef DISABLE_WIDEBAND + +/* Split-VQ innovation for high-band wideband */ +static const split_cb_params split_cb_high = { + 8, /*subvect_size*/ + 5, /*nb_subvect*/ + hexc_table, /*shape_cb*/ + 7, /*shape_bits*/ + 1, +}; + + +/* Split-VQ innovation for high-band wideband */ +static const split_cb_params split_cb_high_lbr = { + 10, /*subvect_size*/ + 4, /*nb_subvect*/ + hexc_10_32_table, /*shape_cb*/ + 5, /*shape_bits*/ + 0, +}; + +#endif + +/* 2150 bps "vocoder-like" mode for comfort noise */ +static const SpeexSubmode nb_submode1 = { + 0, + 1, + 0, + 0, + /* LSP quantization */ + lsp_quant_lbr, + lsp_unquant_lbr, + /* No pitch quantization */ + forced_pitch_quant, + forced_pitch_unquant, + NULL, + /* No innovation quantization (noise only) */ + noise_codebook_quant, + noise_codebook_unquant, + NULL, +#ifdef FIXED_POINT + 22938, 22938, 0, -1, +#else + .7, .7, 0, -1, +#endif + 43 +}; + +/* 3.95 kbps very low bit-rate mode */ +static const SpeexSubmode nb_submode8 = { + 0, + 1, + 0, + 0, + /*LSP quantization*/ + lsp_quant_lbr, + lsp_unquant_lbr, + /*No pitch quantization*/ + forced_pitch_quant, + forced_pitch_unquant, + NULL, + /*Innovation quantization*/ + split_cb_search_shape_sign, + split_cb_shape_sign_unquant, + &split_cb_nb_ulbr, +#ifdef FIXED_POINT + 22938, 16384, 11796, 21299, +#else + 0.7, 0.5, .36, .65, +#endif + 79 +}; + +/* 5.95 kbps very low bit-rate mode */ +static const SpeexSubmode nb_submode2 = { + 0, + 0, + 0, + 0, + /*LSP quantization*/ + lsp_quant_lbr, + lsp_unquant_lbr, + /*No pitch quantization*/ + pitch_search_3tap, + pitch_unquant_3tap, + <p_params_vlbr, + /*Innovation quantization*/ + split_cb_search_shape_sign, + split_cb_shape_sign_unquant, + &split_cb_nb_vlbr, +#ifdef FIXED_POINT + 22938, 16384, 11796, 18022, +#else + 0.7, 0.5, .36, .55, +#endif + 119 +}; + +/* 8 kbps low bit-rate mode */ +static const SpeexSubmode nb_submode3 = { + -1, + 0, + 1, + 0, + /*LSP quantization*/ + lsp_quant_lbr, + lsp_unquant_lbr, + /*Pitch quantization*/ + pitch_search_3tap, + pitch_unquant_3tap, + <p_params_lbr, + /*Innovation quantization*/ + split_cb_search_shape_sign, + split_cb_shape_sign_unquant, + &split_cb_nb_lbr, +#ifdef FIXED_POINT + 22938, 18022, 9830, 14746, +#else + 0.7, 0.55, .30, .45, +#endif + 160 +}; + +/* 11 kbps medium bit-rate mode */ +static const SpeexSubmode nb_submode4 = { + -1, + 0, + 1, + 0, + /*LSP quantization*/ + lsp_quant_lbr, + lsp_unquant_lbr, + /*Pitch quantization*/ + pitch_search_3tap, + pitch_unquant_3tap, + <p_params_med, + /*Innovation quantization*/ + split_cb_search_shape_sign, + split_cb_shape_sign_unquant, + &split_cb_nb_med, +#ifdef FIXED_POINT + 22938, 20644, 5243, 11469, +#else + 0.7, 0.63, .16, .35, +#endif + 220 +}; + +/* 15 kbps high bit-rate mode */ +static const SpeexSubmode nb_submode5 = { + -1, + 0, + 3, + 0, + /*LSP quantization*/ + lsp_quant_nb, + lsp_unquant_nb, + /*Pitch quantization*/ + pitch_search_3tap, + pitch_unquant_3tap, + <p_params_nb, + /*Innovation quantization*/ + split_cb_search_shape_sign, + split_cb_shape_sign_unquant, + &split_cb_nb, +#ifdef FIXED_POINT + 22938, 21299, 3932, 8192, +#else + 0.7, 0.65, .12, .25, +#endif + 300 +}; + +/* 18.2 high bit-rate mode */ +static const SpeexSubmode nb_submode6 = { + -1, + 0, + 3, + 0, + /*LSP quantization*/ + lsp_quant_nb, + lsp_unquant_nb, + /*Pitch quantization*/ + pitch_search_3tap, + pitch_unquant_3tap, + <p_params_nb, + /*Innovation quantization*/ + split_cb_search_shape_sign, + split_cb_shape_sign_unquant, + &split_cb_sb, +#ifdef FIXED_POINT + 22282, 21299, 2294, 3277, +#else + 0.68, 0.65, .07, .1, +#endif + 364 +}; + +/* 24.6 kbps high bit-rate mode */ +static const SpeexSubmode nb_submode7 = { + -1, + 0, + 3, + 1, + /*LSP quantization*/ + lsp_quant_nb, + lsp_unquant_nb, + /*Pitch quantization*/ + pitch_search_3tap, + pitch_unquant_3tap, + <p_params_nb, + /*Innovation quantization*/ + split_cb_search_shape_sign, + split_cb_shape_sign_unquant, + &split_cb_nb, +#ifdef FIXED_POINT + 21299, 21299, 0, -1, +#else + 0.65, 0.65, .0, -1, +#endif + 492 +}; + + +/* Default mode for narrowband */ +static const SpeexNBMode nb_mode = { + 160, /*frameSize*/ + 40, /*subframeSize*/ + 10, /*lpcSize*/ + 17, /*pitchStart*/ + 144, /*pitchEnd*/ +#ifdef FIXED_POINT + 29491, 19661, /* gamma1, gamma2 */ +#else + 0.9, 0.6, /* gamma1, gamma2 */ +#endif + .012, /*lag_factor*/ + 1.0002, /*lpc_floor*/ +#ifdef EPIC_48K + 0, +#endif + {NULL, &nb_submode1, &nb_submode2, &nb_submode3, &nb_submode4, &nb_submode5, &nb_submode6, &nb_submode7, + &nb_submode8, NULL, NULL, NULL, NULL, NULL, NULL, NULL}, + 5, + {1, 8, 2, 3, 3, 4, 4, 5, 5, 6, 7} +}; + + +/* Default mode for narrowband */ +const SpeexMode speex_nb_mode = { + &nb_mode, + nb_mode_query, + "narrowband", + 0, + 4, + &nb_encoder_init, + &nb_encoder_destroy, + &nb_encode, + &nb_decoder_init, + &nb_decoder_destroy, + &nb_decode, + &nb_encoder_ctl, + &nb_decoder_ctl, +}; + + +/* Wideband part */ + +static const SpeexSubmode wb_submode1 = { + 0, + 0, + 1, + 0, + /*LSP quantization*/ + lsp_quant_high, + lsp_unquant_high, + /*Pitch quantization*/ + NULL, + NULL, + NULL, + /*No innovation quantization*/ + NULL, + NULL, + NULL, +#ifdef FIXED_POINT + 24576, 24576, 0, -1, +#else + .75, .75, .0, -1, +#endif + 36 +}; + + +static const SpeexSubmode wb_submode2 = { + 0, + 0, + 1, + 0, + /*LSP quantization*/ + lsp_quant_high, + lsp_unquant_high, + /*Pitch quantization*/ + NULL, + NULL, + NULL, + /*Innovation quantization*/ + split_cb_search_shape_sign, + split_cb_shape_sign_unquant, +#ifdef DISABLE_WIDEBAND + NULL, +#else + &split_cb_high_lbr, +#endif +#ifdef FIXED_POINT + 27853, 19661, 8192, -1, +#else + .85, .6, .25, -1, +#endif + 112 +}; + + +static const SpeexSubmode wb_submode3 = { + 0, + 0, + 1, + 0, + /*LSP quantization*/ + lsp_quant_high, + lsp_unquant_high, + /*Pitch quantization*/ + NULL, + NULL, + NULL, + /*Innovation quantization*/ + split_cb_search_shape_sign, + split_cb_shape_sign_unquant, +#ifdef DISABLE_WIDEBAND + NULL, +#else + &split_cb_high, +#endif + +#ifdef FIXED_POINT + 24576, 22938, 1638, -1, +#else + .75, .7, .05, -1, +#endif + 192 +}; + +static const SpeexSubmode wb_submode4 = { + 0, + 0, + 1, + 1, + /*LSP quantization*/ + lsp_quant_high, + lsp_unquant_high, + /*Pitch quantization*/ + NULL, + NULL, + NULL, + /*Innovation quantization*/ + split_cb_search_shape_sign, + split_cb_shape_sign_unquant, +#ifdef DISABLE_WIDEBAND + NULL, +#else + &split_cb_high, +#endif +#ifdef FIXED_POINT + 24576, 24576, 0, -1, +#else + .75, .75, .0, -1, +#endif + 352 +}; + + +/* Split-band wideband CELP mode*/ +static const SpeexSBMode sb_wb_mode = { + &speex_nb_mode, + 160, /*frameSize*/ + 40, /*subframeSize*/ + 8, /*lpcSize*/ + 640, /*bufSize*/ +#ifdef FIXED_POINT + 29491, 19661, /* gamma1, gamma2 */ +#else + 0.9, 0.6, /* gamma1, gamma2 */ +#endif + .001, /*lag_factor*/ + 1.0001, /*lpc_floor*/ + 0.9, + {NULL, &wb_submode1, &wb_submode2, &wb_submode3, &wb_submode4, NULL, NULL, NULL}, + 3, + {1, 8, 2, 3, 4, 5, 5, 6, 6, 7, 7}, + {1, 1, 1, 1, 1, 1, 2, 2, 3, 3, 4}, + vbr_hb_thresh, + 5 +}; + + +const SpeexMode speex_wb_mode = { + &sb_wb_mode, + wb_mode_query, + "wideband (sub-band CELP)", + 1, + 4, + &sb_encoder_init, + &sb_encoder_destroy, + &sb_encode, + &sb_decoder_init, + &sb_decoder_destroy, + &sb_decode, + &sb_encoder_ctl, + &sb_decoder_ctl, +}; + + + +/* "Ultra-wideband" mode stuff */ + + + +/* Split-band "ultra-wideband" (32 kbps) CELP mode*/ +static const SpeexSBMode sb_uwb_mode = { + &speex_wb_mode, + 320, /*frameSize*/ + 80, /*subframeSize*/ + 8, /*lpcSize*/ + 1280, /*bufSize*/ +#ifdef FIXED_POINT + 29491, 19661, /* gamma1, gamma2 */ +#else + 0.9, 0.6, /* gamma1, gamma2 */ +#endif + .002, /*lag_factor*/ + 1.0001, /*lpc_floor*/ + 0.7, + {NULL, &wb_submode1, NULL, NULL, NULL, NULL, NULL, NULL}, + 1, + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, + {0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, + vbr_uhb_thresh, + 2 +}; + + +const SpeexMode speex_uwb_mode = { + &sb_uwb_mode, + wb_mode_query, + "ultra-wideband (sub-band CELP)", + 2, + 4, + &sb_encoder_init, + &sb_encoder_destroy, + &sb_encode, + &sb_decoder_init, + &sb_decoder_destroy, + &sb_decode, + &sb_encoder_ctl, + &sb_decoder_ctl, +}; + + + + +#ifdef EPIC_48K + +extern const signed char gain_cdbk_ulbr[]; +extern const signed char exc_12_32_table[]; + +/* Parameters for Long-Term Prediction (LTP)*/ +static const ltp_params ltp_params_48k = { + gain_cdbk_ulbr, + 3, + 0 +}; + +static const split_cb_params split_cb_nb_48k = { + 12, /*subvect_size*/ + 4, /*nb_subvect*/ + exc_12_32_table, /*shape_cb*/ + 5, /*shape_bits*/ + 0, +}; + + +/* 4.8 kbps very low bit-rate mode */ +static const SpeexSubmode nb_48k_submode = { + 0, + 0, + 0, + 0, + /*LSP quantization*/ + lsp_quant_48k, + lsp_unquant_48k, + /*No pitch quantization*/ + pitch_search_3tap, + pitch_unquant_3tap, + <p_params_48k, + /*Innovation quantization*/ + split_cb_search_shape_sign, + split_cb_shape_sign_unquant, + &split_cb_nb_48k, +#ifdef FIXED_POINT + 22938, 16384, 11796, 18022, +#else + 0.7, 0.5, .36, .55, +#endif + 144 +}; + + +/* Special, non-standard 4.8 kbps mode */ +static const SpeexNBMode nb_48k_mode = { + 240, /*frameSize*/ + 48, /*subframeSize*/ + 10, /*lpcSize*/ + 640, /*bufSize*/ + 17, /*pitchStart*/ + 144, /*pitchEnd*/ + 0.9, /*gamma1*/ + 0.6, /*gamma2*/ + .01, /*lag_factor*/ + 1.0003, /*lpc_floor*/ + 1, + {NULL, NULL, &nb_48k_submode, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}, + 2, + {2,2,2,2,2,2,2,2,2,2,2} +}; + + +/* Default mode for narrowband */ +const SpeexMode speex_nb_48k_mode = { + &nb_48k_mode, + nb_mode_query, + "narrowband 4.8 kbps", + 1000, + 4, + &nb_encoder_init, + &nb_encoder_destroy, + &nb_encode, + &nb_decoder_init, + &nb_decoder_destroy, + &nb_decode, + &nb_encoder_ctl, + &nb_decoder_ctl, +}; + + +#endif + +int speex_mode_query(const SpeexMode *mode, int request, void *ptr) +{ + return mode->query(mode->mode, request, ptr); +} + +const SpeexMode * speex_lib_get_mode (int mode) +{ +#ifdef EPIC_48K + if (mode == SPEEX_MODEID_NB_48K) return &speex_nb_48k_mode; +#endif + + if (mode < 0 || mode > SPEEX_NB_MODES) return NULL; + + return speex_mode_list[mode]; +} diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/modes.h b/mozilla/zap/zmk/speex-1.1.10/libspeex/modes.h new file mode 100755 index 00000000000..4855706760c --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/modes.h @@ -0,0 +1,153 @@ +/* Copyright (C) 2002 Jean-Marc Valin */ +/** + @file modes.h + @brief Describes the different modes of the codec +*/ +/* + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 MODES_H +#define MODES_H + +#include +#include +#include "misc.h" + +#define NB_SUBMODES 16 +#define NB_SUBMODE_BITS 4 + +#define SB_SUBMODES 8 +#define SB_SUBMODE_BITS 3 + + +/** Quantizes LSPs */ +typedef void (*lsp_quant_func)(spx_lsp_t *, spx_lsp_t *, int, SpeexBits *); + +/** Decodes quantized LSPs */ +typedef void (*lsp_unquant_func)(spx_lsp_t *, int, SpeexBits *); + + +/** Long-term predictor quantization */ +typedef int (*ltp_quant_func)(spx_sig_t *, spx_sig_t *, spx_coef_t *, spx_coef_t *, + spx_coef_t *, spx_sig_t *, const void *, int, int, spx_word16_t, + int, int, SpeexBits*, char *, spx_sig_t *, spx_word16_t *, int, int, int); + +/** Long-term un-quantize */ +typedef void (*ltp_unquant_func)(spx_sig_t *, int, int, spx_word16_t, const void *, int, int *, + spx_word16_t *, SpeexBits*, char*, int, int, spx_word16_t, int); + + +/** Innovation quantization function */ +typedef void (*innovation_quant_func)(spx_sig_t *, spx_coef_t *, spx_coef_t *, spx_coef_t *, const void *, int, int, + spx_sig_t *, spx_word16_t *, SpeexBits *, char *, int, int); + +/** Innovation unquantization function */ +typedef void (*innovation_unquant_func)(spx_sig_t *, const void *, int, SpeexBits*, char *); + +/** Description of a Speex sub-mode (wither narrowband or wideband */ +typedef struct SpeexSubmode { + int lbr_pitch; /**< Set to -1 for "normal" modes, otherwise encode pitch using a global pitch and allowing a +- lbr_pitch variation (for low not-rates)*/ + int forced_pitch_gain; /**< Use the same (forced) pitch gain for all sub-frames */ + int have_subframe_gain; /**< Number of bits to use as sub-frame innovation gain */ + int double_codebook; /**< Apply innovation quantization twice for higher quality (and higher bit-rate)*/ + /*LSP functions*/ + lsp_quant_func lsp_quant; /**< LSP quantization function */ + lsp_unquant_func lsp_unquant; /**< LSP unquantization function */ + + /*Lont-term predictor functions*/ + ltp_quant_func ltp_quant; /**< Long-term predictor (pitch) quantizer */ + ltp_unquant_func ltp_unquant; /**< Long-term predictor (pitch) un-quantizer */ + const void *ltp_params; /**< Pitch parameters (options) */ + + /*Quantization of innovation*/ + innovation_quant_func innovation_quant; /**< Innovation quantization */ + innovation_unquant_func innovation_unquant; /**< Innovation un-quantization */ + const void *innovation_params; /**< Innovation quantization parameters*/ + + /*Synthesis filter enhancement*/ + spx_word16_t lpc_enh_k1; /**< Enhancer constant */ + spx_word16_t lpc_enh_k2; /**< Enhancer constant */ + spx_word16_t lpc_enh_k3; /**< Enhancer constant */ + spx_word16_t comb_gain; /**< Gain of enhancer comb filter */ + + int bits_per_frame; /**< Number of bits per frame after encoding*/ +} SpeexSubmode; + +/** Struct defining the encoding/decoding mode*/ +typedef struct SpeexNBMode { + int frameSize; /**< Size of frames used for encoding */ + int subframeSize; /**< Size of sub-frames used for encoding */ + int lpcSize; /**< Order of LPC filter */ + int pitchStart; /**< Smallest pitch value allowed */ + int pitchEnd; /**< Largest pitch value allowed */ + + spx_word16_t gamma1; /**< Perceptual filter parameter #1 */ + spx_word16_t gamma2; /**< Perceptual filter parameter #2 */ + float lag_factor; /**< Lag-windowing parameter */ + float lpc_floor; /**< Noise floor for LPC analysis */ + +#ifdef EPIC_48K + int lbr48k; /**< 1 for the special 4.8 kbps mode */ +#endif + + const SpeexSubmode *submodes[NB_SUBMODES]; /**< Sub-mode data for the mode */ + int defaultSubmode; /**< Default sub-mode to use when encoding */ + int quality_map[11]; /**< Mode corresponding to each quality setting */ +} SpeexNBMode; + + +/** Struct defining the encoding/decoding mode for SB-CELP (wideband) */ +typedef struct SpeexSBMode { + const SpeexMode *nb_mode; /**< Embedded narrowband mode */ + int frameSize; /**< Size of frames used for encoding */ + int subframeSize; /**< Size of sub-frames used for encoding */ + int lpcSize; /**< Order of LPC filter */ + int bufSize; /**< Signal buffer size in encoder */ + spx_word16_t gamma1; /**< Perceptual filter parameter #1 */ + spx_word16_t gamma2; /**< Perceptual filter parameter #1 */ + float lag_factor; /**< Lag-windowing parameter */ + float lpc_floor; /**< Noise floor for LPC analysis */ + float folding_gain; + + const SpeexSubmode *submodes[SB_SUBMODES]; /**< Sub-mode data for the mode */ + int defaultSubmode; /**< Default sub-mode to use when encoding */ + int low_quality_map[11]; /**< Mode corresponding to each quality setting */ + int quality_map[11]; /**< Mode corresponding to each quality setting */ + const float (*vbr_thresh)[11]; + int nb_modes; +} SpeexSBMode; + +int speex_encode_native(void *state, spx_word16_t *in, SpeexBits *bits); +int speex_decode_native(void *state, SpeexBits *bits, spx_word16_t *out); + +int nb_mode_query(const void *mode, int request, void *ptr); +int wb_mode_query(const void *mode, int request, void *ptr); + +#endif diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/nb_celp.c b/mozilla/zap/zmk/speex-1.1.10/libspeex/nb_celp.c new file mode 100755 index 00000000000..d6cc29d6df7 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/nb_celp.c @@ -0,0 +1,2012 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: nb_celp.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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 +#include "nb_celp.h" +#include "lpc.h" +#include "lsp.h" +#include "ltp.h" +#include "quant_lsp.h" +#include "cb_search.h" +#include "filters.h" +#include "stack_alloc.h" +#include "vq.h" +#include +#include "vbr.h" +#include "misc.h" +#include + +#ifndef M_PI +#define M_PI 3.14159265358979323846 /* pi */ +#endif + +#ifndef NULL +#define NULL 0 +#endif + +#define SUBMODE(x) st->submodes[st->submodeID]->x + +/* Default size for the encoder and decoder stack (can be changed at compile time). + This does not apply when using variable-size arrays or alloca. */ +#ifndef NB_ENC_STACK +#define NB_ENC_STACK (8000*sizeof(spx_sig_t)) +#endif + +#ifndef NB_DEC_STACK +#define NB_DEC_STACK (4000*sizeof(spx_sig_t)) +#endif + + +#ifdef FIXED_POINT +const spx_word32_t ol_gain_table[32]={18900, 25150, 33468, 44536, 59265, 78865, 104946, 139653, 185838, 247297, 329081, 437913, 582736, 775454, 1031906, 1373169, 1827293, 2431601, 3235761, 4305867, 5729870, 7624808, 10146425, 13501971, 17967238, 23909222, 31816294, 42338330, 56340132, 74972501, 99766822, 132760927}; +const spx_word16_t exc_gain_quant_scal3_bound[7]={1841, 3883, 6051, 8062, 10444, 13580, 18560}; +const spx_word16_t exc_gain_quant_scal3[8]={1002, 2680, 5086, 7016, 9108, 11781, 15380, 21740}; +const spx_word16_t exc_gain_quant_scal1_bound[1]={14385}; +const spx_word16_t exc_gain_quant_scal1[2]={11546, 17224}; + +#define LSP_MARGIN 16 +#define LSP_DELTA1 6553 +#define LSP_DELTA2 1638 + +#else + +const float exc_gain_quant_scal3_bound[7]={0.112338, 0.236980, 0.369316, 0.492054, 0.637471, 0.828874, 1.132784}; +const float exc_gain_quant_scal3[8]={0.061130, 0.163546, 0.310413, 0.428220, 0.555887, 0.719055, 0.938694, 1.326874}; +const float exc_gain_quant_scal1_bound[1]={0.87798}; +const float exc_gain_quant_scal1[2]={0.70469, 1.05127}; + +#define LSP_MARGIN .002 +#define LSP_DELTA1 .2 +#define LSP_DELTA2 .05 + +#endif + + + + +#define sqr(x) ((x)*(x)) + +void *nb_encoder_init(const SpeexMode *m) +{ + EncState *st; + const SpeexNBMode *mode; + int i; + + mode=(const SpeexNBMode *)m->mode; + st = (EncState*)speex_alloc(sizeof(EncState)); + if (!st) + return NULL; +#if defined(VAR_ARRAYS) || defined (USE_ALLOCA) + st->stack = NULL; +#else + st->stack = (char*)speex_alloc_scratch(NB_ENC_STACK); +#endif + + st->mode=m; + + st->frameSize = mode->frameSize; + st->windowSize = st->frameSize*3/2; + st->nbSubframes=mode->frameSize/mode->subframeSize; + st->subframeSize=mode->subframeSize; + st->lpcSize = mode->lpcSize; + st->gamma1=mode->gamma1; + st->gamma2=mode->gamma2; + st->min_pitch=mode->pitchStart; + st->max_pitch=mode->pitchEnd; + st->lag_factor=mode->lag_factor; + st->lpc_floor = mode->lpc_floor; + + st->submodes=mode->submodes; + st->submodeID=st->submodeSelect=mode->defaultSubmode; + st->bounded_pitch = 1; + + st->encode_submode = 1; +#ifdef EPIC_48K + st->lbr_48k=mode->lbr48k; +#endif + + /* Allocating input buffer */ + st->inBuf = speex_alloc((st->windowSize)*sizeof(spx_sig_t)); + st->frame = st->inBuf; + /* Allocating excitation buffer */ + st->excBuf = speex_alloc((mode->frameSize+mode->pitchEnd+1)*sizeof(spx_sig_t)); + st->exc = st->excBuf + mode->pitchEnd + 1; + st->swBuf = speex_alloc((mode->frameSize+mode->pitchEnd+1)*sizeof(spx_sig_t)); + st->sw = st->swBuf + mode->pitchEnd + 1; + + st->innov = speex_alloc((st->frameSize)*sizeof(spx_sig_t)); + + /* Asymmetric "pseudo-Hamming" window */ + { + int part1, part2; + part1=st->frameSize - (st->subframeSize>>1); + part2=(st->frameSize>>1) + (st->subframeSize>>1); + st->window = speex_alloc((st->windowSize)*sizeof(spx_word16_t)); + for (i=0;iwindow[i]=(spx_word16_t)(SIG_SCALING*(.54-.46*cos(M_PI*i/part1))); + for (i=0;iwindow[part1+i]=(spx_word16_t)(SIG_SCALING*(.54+.46*cos(M_PI*i/part2))); + } + /* Create the window for autocorrelation (lag-windowing) */ + st->lagWindow = speex_alloc((st->lpcSize+1)*sizeof(spx_word16_t)); + for (i=0;ilpcSize+1;i++) + st->lagWindow[i]=16384*exp(-.5*sqr(2*M_PI*st->lag_factor*i)); + + st->autocorr = speex_alloc((st->lpcSize+1)*sizeof(spx_word16_t)); + + st->lpc = speex_alloc((st->lpcSize)*sizeof(spx_coef_t)); + st->interp_lpc = speex_alloc((st->lpcSize)*sizeof(spx_coef_t)); + st->interp_qlpc = speex_alloc((st->lpcSize)*sizeof(spx_coef_t)); + st->bw_lpc1 = speex_alloc((st->lpcSize)*sizeof(spx_coef_t)); + st->bw_lpc2 = speex_alloc((st->lpcSize)*sizeof(spx_coef_t)); + + st->lsp = speex_alloc((st->lpcSize)*sizeof(spx_lsp_t)); + st->qlsp = speex_alloc((st->lpcSize)*sizeof(spx_lsp_t)); + st->old_lsp = speex_alloc((st->lpcSize)*sizeof(spx_lsp_t)); + st->old_qlsp = speex_alloc((st->lpcSize)*sizeof(spx_lsp_t)); + st->interp_lsp = speex_alloc((st->lpcSize)*sizeof(spx_lsp_t)); + st->interp_qlsp = speex_alloc((st->lpcSize)*sizeof(spx_lsp_t)); + + st->first = 1; + for (i=0;ilpcSize;i++) + { + st->lsp[i]=LSP_SCALING*(M_PI*((float)(i+1)))/(st->lpcSize+1); + } + + st->mem_sp = speex_alloc((st->lpcSize)*sizeof(spx_mem_t)); + st->mem_sw = speex_alloc((st->lpcSize)*sizeof(spx_mem_t)); + st->mem_sw_whole = speex_alloc((st->lpcSize)*sizeof(spx_mem_t)); + st->mem_exc = speex_alloc((st->lpcSize)*sizeof(spx_mem_t)); + + st->pi_gain = speex_alloc((st->nbSubframes)*sizeof(spx_word32_t)); + + st->pitch = speex_alloc((st->nbSubframes)*sizeof(int)); + + st->vbr = speex_alloc(sizeof(VBRState)); + vbr_init(st->vbr); + st->vbr_quality = 8; + st->vbr_enabled = 0; + st->vad_enabled = 0; + st->dtx_enabled = 0; + st->abr_enabled = 0; + st->abr_drift = 0; + + st->plc_tuning = 2; + st->complexity=2; + st->sampling_rate=8000; + st->dtx_count=0; + +#ifdef ENABLE_VALGRIND + VALGRIND_MAKE_READABLE(st, (st->stack-(char*)st)); +#endif + return st; +} + +void nb_encoder_destroy(void *state) +{ + EncState *st=(EncState *)state; + /* Free all allocated memory */ +#if !(defined(VAR_ARRAYS) || defined (USE_ALLOCA)) + speex_free_scratch(st->stack); +#endif + + speex_free (st->inBuf); + speex_free (st->excBuf); + speex_free (st->innov); + speex_free (st->interp_qlpc); + speex_free (st->qlsp); + speex_free (st->old_qlsp); + speex_free (st->interp_qlsp); + speex_free (st->swBuf); + + speex_free (st->window); + speex_free (st->lagWindow); + speex_free (st->autocorr); + speex_free (st->lpc); + speex_free (st->lsp); + + speex_free (st->interp_lpc); + speex_free (st->bw_lpc1); + speex_free (st->bw_lpc2); + speex_free (st->old_lsp); + speex_free (st->interp_lsp); + speex_free (st->mem_sp); + speex_free (st->mem_sw); + speex_free (st->mem_sw_whole); + speex_free (st->mem_exc); + speex_free (st->pi_gain); + speex_free (st->pitch); + + vbr_destroy(st->vbr); + speex_free (st->vbr); + + /*Free state memory... should be last*/ + speex_free(st); +} + +int nb_encode(void *state, void *vin, SpeexBits *bits) +{ + EncState *st; + int i, sub, roots; + int ol_pitch; + spx_word16_t ol_pitch_coef; + spx_word32_t ol_gain; + VARDECL(spx_sig_t *res); + VARDECL(spx_sig_t *target); + VARDECL(spx_mem_t *mem); + char *stack; + VARDECL(spx_word16_t *syn_resp); + VARDECL(spx_sig_t *real_exc); +#ifdef EPIC_48K + int pitch_half[2]; + int ol_pitch_id=0; +#endif + spx_word16_t *in = vin; + + st=(EncState *)state; + stack=st->stack; + + /* Copy new data in input buffer */ + speex_move(st->inBuf, st->inBuf+st->frameSize, (st->windowSize-st->frameSize)*sizeof(spx_sig_t)); + for (i=0;iframeSize;i++) + st->inBuf[st->windowSize-st->frameSize+i] = SHL32(EXTEND32(in[i]), SIG_SHIFT); + + /* Move signals 1 frame towards the past */ + speex_move(st->excBuf, st->excBuf+st->frameSize, (st->max_pitch+1)*sizeof(spx_sig_t)); + speex_move(st->swBuf, st->swBuf+st->frameSize, (st->max_pitch+1)*sizeof(spx_sig_t)); + + { + VARDECL(spx_word16_t *w_sig); + ALLOC(w_sig, st->windowSize, spx_word16_t); + /* Window for analysis */ + for (i=0;iwindowSize;i++) + w_sig[i] = EXTRACT16(SHR32(MULT16_16(EXTRACT16(SHR32(st->frame[i],SIG_SHIFT)),st->window[i]),SIG_SHIFT)); + + /* Compute auto-correlation */ + _spx_autocorr(w_sig, st->autocorr, st->lpcSize+1, st->windowSize); + } + st->autocorr[0] = (spx_word16_t) (st->autocorr[0]*st->lpc_floor); /* Noise floor in auto-correlation domain */ + + /* Lag windowing: equivalent to filtering in the power-spectrum domain */ + for (i=0;ilpcSize+1;i++) + st->autocorr[i] = MULT16_16_Q14(st->autocorr[i],st->lagWindow[i]); + + /* Levinson-Durbin */ + _spx_lpc(st->lpc, st->autocorr, st->lpcSize); + + /* LPC to LSPs (x-domain) transform */ + roots=lpc_to_lsp (st->lpc, st->lpcSize, st->lsp, 15, LSP_DELTA1, stack); + /* Check if we found all the roots */ + if (roots!=st->lpcSize) + { + /* Search again if we can afford it */ + if (st->complexity>1) + roots = lpc_to_lsp (st->lpc, st->lpcSize, st->lsp, 11, LSP_DELTA2, stack); + if (roots!=st->lpcSize) + { + /*If we can't find all LSP's, do some damage control and use previous filter*/ + for (i=0;ilpcSize;i++) + { + st->lsp[i]=st->old_lsp[i]; + } + } + } + + + + /* Whole frame analysis (open-loop estimation of pitch and excitation gain) */ + { + if (st->first) + for (i=0;ilpcSize;i++) + st->interp_lsp[i] = st->lsp[i]; + else + lsp_interpolate(st->old_lsp, st->lsp, st->interp_lsp, st->lpcSize, st->nbSubframes, st->nbSubframes<<1); + + lsp_enforce_margin(st->interp_lsp, st->lpcSize, LSP_MARGIN); + + /* Compute interpolated LPCs (unquantized) for whole frame*/ + lsp_to_lpc(st->interp_lsp, st->interp_lpc, st->lpcSize,stack); + + + /*Open-loop pitch*/ + if (!st->submodes[st->submodeID] || st->vbr_enabled || st->vad_enabled || SUBMODE(forced_pitch_gain) || + SUBMODE(lbr_pitch) != -1) + { + int nol_pitch[6]; + spx_word16_t nol_pitch_coef[6]; + + bw_lpc(st->gamma1, st->interp_lpc, st->bw_lpc1, st->lpcSize); + bw_lpc(st->gamma2, st->interp_lpc, st->bw_lpc2, st->lpcSize); + + filter_mem2(st->frame, st->bw_lpc1, st->bw_lpc2, st->sw, st->frameSize, st->lpcSize, st->mem_sw_whole); + + open_loop_nbest_pitch(st->sw, st->min_pitch, st->max_pitch, st->frameSize, + nol_pitch, nol_pitch_coef, 6, stack); + ol_pitch=nol_pitch[0]; + ol_pitch_coef = nol_pitch_coef[0]; + /*Try to remove pitch multiples*/ + for (i=1;i<6;i++) + { +#ifdef FIXED_POINT + if ((nol_pitch_coef[i]>MULT16_16_Q15(nol_pitch_coef[0],27853)) && +#else + if ((nol_pitch_coef[i]>.85*nol_pitch_coef[0]) && +#endif + (ABS(2*nol_pitch[i]-ol_pitch)<=2 || ABS(3*nol_pitch[i]-ol_pitch)<=3 || + ABS(4*nol_pitch[i]-ol_pitch)<=4 || ABS(5*nol_pitch[i]-ol_pitch)<=5)) + { + /*ol_pitch_coef=nol_pitch_coef[i];*/ + ol_pitch = nol_pitch[i]; + } + } + /*if (ol_pitch>50) + ol_pitch/=2;*/ + /*ol_pitch_coef = sqrt(ol_pitch_coef);*/ + +#ifdef EPIC_48K + if (st->lbr_48k) + { + if (ol_pitch < st->min_pitch+2) + ol_pitch = st->min_pitch+2; + if (ol_pitch > st->max_pitch-2) + ol_pitch = st->max_pitch-2; + open_loop_nbest_pitch(st->sw, ol_pitch-2, ol_pitch+2, st->frameSize>>1, + &pitch_half[0], nol_pitch_coef, 1, stack); + open_loop_nbest_pitch(st->sw+(st->frameSize>>1), pitch_half[0]-1, pitch_half[0]+2, st->frameSize>>1, + &pitch_half[1], nol_pitch_coef, 1, stack); + } +#endif + } else { + ol_pitch=0; + ol_pitch_coef=0; + } + /*Compute "real" excitation*/ + fir_mem2(st->frame, st->interp_lpc, st->exc, st->frameSize, st->lpcSize, st->mem_exc); + + /* Compute open-loop excitation gain */ +#ifdef EPIC_48K + if (st->lbr_48k) + { + float ol1=0,ol2=0; + float ol_gain2; + ol1 = compute_rms(st->exc, st->frameSize>>1); + ol2 = compute_rms(st->exc+(st->frameSize>>1), st->frameSize>>1); + ol1 *= ol1*(st->frameSize>>1); + ol2 *= ol2*(st->frameSize>>1); + + ol_gain2=ol1; + if (ol2>ol1) + ol_gain2=ol2; + ol_gain2 = sqrt(2*ol_gain2*(ol1+ol2))*1.3*(1-.5*GAIN_SCALING_1*GAIN_SCALING_1*ol_pitch_coef*ol_pitch_coef); + + ol_gain=SHR(sqrt(1+ol_gain2/st->frameSize),SIG_SHIFT); + + } else { +#endif + ol_gain = SHL32(EXTEND32(compute_rms(st->exc, st->frameSize)),SIG_SHIFT); +#ifdef EPIC_48K + } +#endif + } + + /*VBR stuff*/ + if (st->vbr && (st->vbr_enabled||st->vad_enabled)) + { + float lsp_dist=0; + for (i=0;ilpcSize;i++) + lsp_dist += (st->old_lsp[i] - st->lsp[i])*(st->old_lsp[i] - st->lsp[i]); + lsp_dist /= LSP_SCALING*LSP_SCALING; + + if (st->abr_enabled) + { + float qual_change=0; + if (st->abr_drift2 * st->abr_drift > 0) + { + /* Only adapt if long-term and short-term drift are the same sign */ + qual_change = -.00001*st->abr_drift/(1+st->abr_count); + if (qual_change>.05) + qual_change=.05; + if (qual_change<-.05) + qual_change=-.05; + } + st->vbr_quality += qual_change; + if (st->vbr_quality>10) + st->vbr_quality=10; + if (st->vbr_quality<0) + st->vbr_quality=0; + } + + st->relative_quality = vbr_analysis(st->vbr, in, st->frameSize, ol_pitch, GAIN_SCALING_1*ol_pitch_coef); + /*if (delta_qual<0)*/ + /* delta_qual*=.1*(3+st->vbr_quality);*/ + if (st->vbr_enabled) + { + int mode; + int choice=0; + float min_diff=100; + mode = 8; + while (mode) + { + int v1; + float thresh; + v1=(int)floor(st->vbr_quality); + if (v1==10) + thresh = vbr_nb_thresh[mode][v1]; + else + thresh = (st->vbr_quality-v1)*vbr_nb_thresh[mode][v1+1] + (1+v1-st->vbr_quality)*vbr_nb_thresh[mode][v1]; + if (st->relative_quality > thresh && + st->relative_quality-threshrelative_quality-thresh; + } + mode--; + } + mode=choice; + if (mode==0) + { + if (st->dtx_count==0 || lsp_dist>.05 || !st->dtx_enabled || st->dtx_count>20) + { + mode=1; + st->dtx_count=1; + } else { + mode=0; + st->dtx_count++; + } + } else { + st->dtx_count=0; + } + + speex_encoder_ctl(state, SPEEX_SET_MODE, &mode); + + if (st->abr_enabled) + { + int bitrate; + speex_encoder_ctl(state, SPEEX_GET_BITRATE, &bitrate); + st->abr_drift+=(bitrate-st->abr_enabled); + st->abr_drift2 = .95*st->abr_drift2 + .05*(bitrate-st->abr_enabled); + st->abr_count += 1.0; + } + + } else { + /*VAD only case*/ + int mode; + if (st->relative_quality<2) + { + if (st->dtx_count==0 || lsp_dist>.05 || !st->dtx_enabled || st->dtx_count>20) + { + st->dtx_count=1; + mode=1; + } else { + mode=0; + st->dtx_count++; + } + } else { + st->dtx_count = 0; + mode=st->submodeSelect; + } + /*speex_encoder_ctl(state, SPEEX_SET_MODE, &mode);*/ + st->submodeID=mode; + } + } else { + st->relative_quality = -1; + } + + if (st->encode_submode) + { +#ifdef EPIC_48K + if (!st->lbr_48k) { +#endif + + /* First, transmit a zero for narrowband */ + speex_bits_pack(bits, 0, 1); + + /* Transmit the sub-mode we use for this frame */ + speex_bits_pack(bits, st->submodeID, NB_SUBMODE_BITS); + +#ifdef EPIC_48K + } +#endif + } + + /* If null mode (no transmission), just set a couple things to zero*/ + if (st->submodes[st->submodeID] == NULL) + { + for (i=0;iframeSize;i++) + st->exc[i]=st->sw[i]=VERY_SMALL; + + for (i=0;ilpcSize;i++) + st->mem_sw[i]=0; + st->first=1; + st->bounded_pitch = 1; + + /* Final signal synthesis from excitation */ + iir_mem2(st->exc, st->interp_qlpc, st->frame, st->frameSize, st->lpcSize, st->mem_sp); + +#ifdef RESYNTH + for (i=0;iframeSize;i++) + in[i]=st->frame[i]; +#endif + return 0; + + } + + /* LSP Quantization */ + if (st->first) + { + for (i=0;ilpcSize;i++) + st->old_lsp[i] = st->lsp[i]; + } + + + /*Quantize LSPs*/ +#if 1 /*0 for unquantized*/ + SUBMODE(lsp_quant)(st->lsp, st->qlsp, st->lpcSize, bits); +#else + for (i=0;ilpcSize;i++) + st->qlsp[i]=st->lsp[i]; +#endif + +#ifdef EPIC_48K + if (st->lbr_48k) { + speex_bits_pack(bits, pitch_half[0]-st->min_pitch, 7); + speex_bits_pack(bits, pitch_half[1]-pitch_half[0]+1, 2); + + { + int quant = (int)floor(.5+7.4*GAIN_SCALING_1*ol_pitch_coef); + if (quant>7) + quant=7; + if (quant<0) + quant=0; + ol_pitch_id=quant; + speex_bits_pack(bits, quant, 3); + ol_pitch_coef=GAIN_SCALING*0.13514*quant; + + } + { + int qe = (int)(floor(.5+2.1*log(ol_gain*1.0/SIG_SCALING)))-2; + if (qe<0) + qe=0; + if (qe>15) + qe=15; + ol_gain = exp((qe+2)/2.1)*SIG_SCALING; + speex_bits_pack(bits, qe, 4); + } + + } else { +#endif + + /*If we use low bit-rate pitch mode, transmit open-loop pitch*/ + if (SUBMODE(lbr_pitch)!=-1) + { + speex_bits_pack(bits, ol_pitch-st->min_pitch, 7); + } + + if (SUBMODE(forced_pitch_gain)) + { + int quant; + quant = (int)floor(.5+15*ol_pitch_coef*GAIN_SCALING_1); + if (quant>15) + quant=15; + if (quant<0) + quant=0; + speex_bits_pack(bits, quant, 4); + ol_pitch_coef=GAIN_SCALING*0.066667*quant; + } + + + /*Quantize and transmit open-loop excitation gain*/ +#ifdef FIXED_POINT + { + int qe = scal_quant32(ol_gain, ol_gain_table, 32); + /*ol_gain = exp(qe/3.5)*SIG_SCALING;*/ + ol_gain = MULT16_32_Q15(28406,ol_gain_table[qe]); + speex_bits_pack(bits, qe, 5); + } +#else + { + int qe = (int)(floor(.5+3.5*log(ol_gain*1.0/SIG_SCALING))); + if (qe<0) + qe=0; + if (qe>31) + qe=31; + ol_gain = exp(qe/3.5)*SIG_SCALING; + speex_bits_pack(bits, qe, 5); + } +#endif + + +#ifdef EPIC_48K + } +#endif + + + /* Special case for first frame */ + if (st->first) + { + for (i=0;ilpcSize;i++) + st->old_qlsp[i] = st->qlsp[i]; + } + + /* Filter response */ + ALLOC(res, st->subframeSize, spx_sig_t); + /* Target signal */ + ALLOC(target, st->subframeSize, spx_sig_t); + ALLOC(syn_resp, st->subframeSize, spx_word16_t); + ALLOC(real_exc, st->subframeSize, spx_sig_t); + ALLOC(mem, st->lpcSize, spx_mem_t); + + /* Loop on sub-frames */ + for (sub=0;subnbSubframes;sub++) + { + int offset; + spx_sig_t *sp, *sw, *exc; + int pitch; + int response_bound = st->subframeSize; +#ifdef EPIC_48K + if (st->lbr_48k) + { + if (sub*2 < st->nbSubframes) + ol_pitch = pitch_half[0]; + else + ol_pitch = pitch_half[1]; + } +#endif + + /* Offset relative to start of frame */ + offset = st->subframeSize*sub; + /* Original signal */ + sp=st->frame+offset; + /* Excitation */ + exc=st->exc+offset; + /* Weighted signal */ + sw=st->sw+offset; + + /* LSP interpolation (quantized and unquantized) */ + lsp_interpolate(st->old_lsp, st->lsp, st->interp_lsp, st->lpcSize, sub, st->nbSubframes); + lsp_interpolate(st->old_qlsp, st->qlsp, st->interp_qlsp, st->lpcSize, sub, st->nbSubframes); + + /* Make sure the filters are stable */ + lsp_enforce_margin(st->interp_lsp, st->lpcSize, LSP_MARGIN); + lsp_enforce_margin(st->interp_qlsp, st->lpcSize, LSP_MARGIN); + + /* Compute interpolated LPCs (quantized and unquantized) */ + lsp_to_lpc(st->interp_lsp, st->interp_lpc, st->lpcSize,stack); + + lsp_to_lpc(st->interp_qlsp, st->interp_qlpc, st->lpcSize, stack); + + /* Compute analysis filter gain at w=pi (for use in SB-CELP) */ + { + spx_word32_t pi_g=LPC_SCALING; + for (i=0;ilpcSize;i+=2) + { + /*pi_g += -st->interp_qlpc[i] + st->interp_qlpc[i+1];*/ + pi_g = ADD32(pi_g, SUB32(st->interp_qlpc[i+1],st->interp_qlpc[i])); + } + st->pi_gain[sub] = pi_g; + } + + + /* Compute bandwidth-expanded (unquantized) LPCs for perceptual weighting */ + bw_lpc(st->gamma1, st->interp_lpc, st->bw_lpc1, st->lpcSize); + if (st->gamma2>=0) + bw_lpc(st->gamma2, st->interp_lpc, st->bw_lpc2, st->lpcSize); + else + { + st->bw_lpc2[0]=1; + for (i=1;i<=st->lpcSize;i++) + st->bw_lpc2[i]=0; + } + + for (i=0;isubframeSize;i++) + real_exc[i] = exc[i]; + + if (st->complexity==0) + response_bound >>= 1; + compute_impulse_response(st->interp_qlpc, st->bw_lpc1, st->bw_lpc2, syn_resp, response_bound, st->lpcSize, stack); + for (i=response_bound;isubframeSize;i++) + syn_resp[i]=VERY_SMALL; + + /* Reset excitation */ + for (i=0;isubframeSize;i++) + exc[i]=VERY_SMALL; + + /* Compute zero response of A(z/g1) / ( A(z/g2) * A(z) ) */ + for (i=0;ilpcSize;i++) + mem[i]=st->mem_sp[i]; +#ifdef SHORTCUTS2 + iir_mem2(exc, st->interp_qlpc, exc, response_bound, st->lpcSize, mem); + for (i=0;ilpcSize;i++) + mem[i]=st->mem_sw[i]; + filter_mem2(exc, st->bw_lpc1, st->bw_lpc2, res, response_bound, st->lpcSize, mem); + for (i=response_bound;isubframeSize;i++) + res[i]=0; +#else + iir_mem2(exc, st->interp_qlpc, exc, st->subframeSize, st->lpcSize, mem); + for (i=0;ilpcSize;i++) + mem[i]=st->mem_sw[i]; + filter_mem2(exc, st->bw_lpc1, st->bw_lpc2, res, st->subframeSize, st->lpcSize, mem); +#endif + + /* Compute weighted signal */ + for (i=0;ilpcSize;i++) + mem[i]=st->mem_sw[i]; + filter_mem2(sp, st->bw_lpc1, st->bw_lpc2, sw, st->subframeSize, st->lpcSize, mem); + + if (st->complexity==0) + for (i=0;ilpcSize;i++) + st->mem_sw[i]=mem[i]; + + /* Compute target signal */ + for (i=0;isubframeSize;i++) + target[i]=sw[i]-res[i]; + + for (i=0;isubframeSize;i++) + exc[i]=0; + + /* If we have a long-term predictor (otherwise, something's wrong) */ + if (SUBMODE(ltp_quant)) + { + int pit_min, pit_max; + /* Long-term prediction */ + if (SUBMODE(lbr_pitch) != -1) + { + /* Low bit-rate pitch handling */ + int margin; + margin = SUBMODE(lbr_pitch); + if (margin) + { + if (ol_pitch < st->min_pitch+margin-1) + ol_pitch=st->min_pitch+margin-1; + if (ol_pitch > st->max_pitch-margin) + ol_pitch=st->max_pitch-margin; + pit_min = ol_pitch-margin+1; + pit_max = ol_pitch+margin; + } else { + pit_min=pit_max=ol_pitch; + } + } else { + pit_min = st->min_pitch; + pit_max = st->max_pitch; + } + + /* Force pitch to use only the current frame if needed */ + if (st->bounded_pitch && pit_max>offset) + pit_max=offset; + +#ifdef EPIC_48K + if (st->lbr_48k) + { + pitch = SUBMODE(ltp_quant)(target, sw, st->interp_qlpc, st->bw_lpc1, st->bw_lpc2, + exc, SUBMODE(ltp_params), pit_min, pit_max, ol_pitch_coef, + st->lpcSize, st->subframeSize, bits, stack, + exc, syn_resp, st->complexity, ol_pitch_id, st->plc_tuning); + } else { +#endif + + /* Perform pitch search */ + pitch = SUBMODE(ltp_quant)(target, sw, st->interp_qlpc, st->bw_lpc1, st->bw_lpc2, + exc, SUBMODE(ltp_params), pit_min, pit_max, ol_pitch_coef, + st->lpcSize, st->subframeSize, bits, stack, + exc, syn_resp, st->complexity, 0, st->plc_tuning); +#ifdef EPIC_48K + } +#endif + + st->pitch[sub]=pitch; + } else { + speex_error ("No pitch prediction, what's wrong"); + } + + /* Quantization of innovation */ + { + spx_sig_t *innov; + spx_word32_t ener=0; + spx_word16_t fine_gain; + + innov = st->innov+sub*st->subframeSize; + for (i=0;isubframeSize;i++) + innov[i]=0; + + for (i=0;isubframeSize;i++) + real_exc[i] = SUB32(real_exc[i], exc[i]); + + ener = SHL32(EXTEND32(compute_rms(real_exc, st->subframeSize)),SIG_SHIFT); + + /*FIXME: Should use DIV32_16 and make sure result fits in 16 bits */ +#ifdef FIXED_POINT + { + spx_word32_t f = DIV32(ener,PSHR32(ol_gain,SIG_SHIFT)); + if (f<=32767) + fine_gain = f; + else + fine_gain = 32767; + } +#else + fine_gain = DIV32_16(ener,PSHR32(ol_gain,SIG_SHIFT)); +#endif + /* Calculate gain correction for the sub-frame (if any) */ + if (SUBMODE(have_subframe_gain)) + { + int qe; + if (SUBMODE(have_subframe_gain)==3) + { + qe = scal_quant(fine_gain, exc_gain_quant_scal3_bound, 8); + speex_bits_pack(bits, qe, 3); + ener=MULT16_32_Q14(exc_gain_quant_scal3[qe],ol_gain); + } else { + qe = scal_quant(fine_gain, exc_gain_quant_scal1_bound, 2); + speex_bits_pack(bits, qe, 1); + ener=MULT16_32_Q14(exc_gain_quant_scal1[qe],ol_gain); + } + } else { + ener=ol_gain; + } + + /*printf ("%f %f\n", ener, ol_gain);*/ + + /* Normalize innovation */ + signal_div(target, target, ener, st->subframeSize); + + /* Quantize innovation */ + if (SUBMODE(innovation_quant)) + { + /* Codebook search */ + SUBMODE(innovation_quant)(target, st->interp_qlpc, st->bw_lpc1, st->bw_lpc2, + SUBMODE(innovation_params), st->lpcSize, st->subframeSize, + innov, syn_resp, bits, stack, st->complexity, SUBMODE(double_codebook)); + + /* De-normalize innovation and update excitation */ + signal_mul(innov, innov, ener, st->subframeSize); + + for (i=0;isubframeSize;i++) + exc[i] = ADD32(exc[i],innov[i]); + } else { + speex_error("No fixed codebook"); + } + + /* In some (rare) modes, we do a second search (more bits) to reduce noise even more */ + if (SUBMODE(double_codebook)) { + char *tmp_stack=stack; + VARDECL(spx_sig_t *innov2); + ALLOC(innov2, st->subframeSize, spx_sig_t); + for (i=0;isubframeSize;i++) + innov2[i]=0; + for (i=0;isubframeSize;i++) + target[i]*=2.2; + SUBMODE(innovation_quant)(target, st->interp_qlpc, st->bw_lpc1, st->bw_lpc2, + SUBMODE(innovation_params), st->lpcSize, st->subframeSize, + innov2, syn_resp, bits, stack, st->complexity, 0); + signal_mul(innov2, innov2, (spx_word32_t) (ener*(1/2.2)), st->subframeSize); + for (i=0;isubframeSize;i++) + exc[i] = ADD32(exc[i],innov2[i]); + stack = tmp_stack; + } + + } + + /* Final signal synthesis from excitation */ + iir_mem2(exc, st->interp_qlpc, sp, st->subframeSize, st->lpcSize, st->mem_sp); + + /* Compute weighted signal again, from synthesized speech (not sure it's the right thing) */ + if (st->complexity!=0) + filter_mem2(sp, st->bw_lpc1, st->bw_lpc2, sw, st->subframeSize, st->lpcSize, st->mem_sw); + + } + + /* Store the LSPs for interpolation in the next frame */ + if (st->submodeID>=1) + { + for (i=0;ilpcSize;i++) + st->old_lsp[i] = st->lsp[i]; + for (i=0;ilpcSize;i++) + st->old_qlsp[i] = st->qlsp[i]; + } + + if (st->submodeID==1) + { + if (st->dtx_count) + speex_bits_pack(bits, 15, 4); + else + speex_bits_pack(bits, 0, 4); + } + + /* The next frame will not be the first (Duh!) */ + st->first = 0; + +#ifdef RESYNTH + /* Replace input by synthesized speech */ + for (i=0;iframeSize;i++) + { + spx_word32_t sig = PSHR32(st->frame[i],SIG_SHIFT); + if (sig>32767) + sig = 32767; + if (sig<-32767) + sig = -32767; + in[i]=sig; + } +#endif + + if (SUBMODE(innovation_quant) == noise_codebook_quant || st->submodeID==0) + st->bounded_pitch = 1; + else + st->bounded_pitch = 0; + + return 1; +} + + +void *nb_decoder_init(const SpeexMode *m) +{ + DecState *st; + const SpeexNBMode *mode; + int i; + + mode=(const SpeexNBMode*)m->mode; + st = (DecState *)speex_alloc(sizeof(DecState)); + if (!st) + return NULL; +#if defined(VAR_ARRAYS) || defined (USE_ALLOCA) + st->stack = NULL; +#else + st->stack = (char*)speex_alloc_scratch(NB_DEC_STACK); +#endif + + st->mode=m; + + + st->encode_submode = 1; +#ifdef EPIC_48K + st->lbr_48k=mode->lbr48k; +#endif + + st->first=1; + /* Codec parameters, should eventually have several "modes"*/ + st->frameSize = mode->frameSize; + st->nbSubframes=mode->frameSize/mode->subframeSize; + st->subframeSize=mode->subframeSize; + st->lpcSize = mode->lpcSize; + st->min_pitch=mode->pitchStart; + st->max_pitch=mode->pitchEnd; + + st->submodes=mode->submodes; + st->submodeID=mode->defaultSubmode; + + st->lpc_enh_enabled=0; + + + st->inBuf = speex_alloc((st->frameSize)*sizeof(spx_sig_t)); + st->frame = st->inBuf; + st->excBuf = speex_alloc((st->frameSize + st->max_pitch + 1)*sizeof(spx_sig_t)); + st->exc = st->excBuf + st->max_pitch + 1; + for (i=0;iframeSize;i++) + st->inBuf[i]=0; + for (i=0;iframeSize + st->max_pitch + 1;i++) + st->excBuf[i]=0; + st->innov = speex_alloc((st->frameSize)*sizeof(spx_sig_t)); + + st->interp_qlpc = speex_alloc(st->lpcSize*sizeof(spx_coef_t)); + st->qlsp = speex_alloc(st->lpcSize*sizeof(spx_lsp_t)); + st->old_qlsp = speex_alloc(st->lpcSize*sizeof(spx_lsp_t)); + st->interp_qlsp = speex_alloc(st->lpcSize*sizeof(spx_lsp_t)); + st->mem_sp = speex_alloc((5*st->lpcSize)*sizeof(spx_mem_t)); + st->comb_mem = speex_alloc(sizeof(CombFilterMem)); + comb_filter_mem_init (st->comb_mem); + + st->pi_gain = speex_alloc((st->nbSubframes)*sizeof(spx_word32_t)); + st->last_pitch = 40; + st->count_lost=0; + st->pitch_gain_buf[0] = st->pitch_gain_buf[1] = st->pitch_gain_buf[2] = 0; + st->pitch_gain_buf_idx = 0; + st->seed = 1000; + + st->sampling_rate=8000; + st->last_ol_gain = 0; + + st->user_callback.func = &speex_default_user_handler; + st->user_callback.data = NULL; + for (i=0;i<16;i++) + st->speex_callbacks[i].func = NULL; + + st->voc_m1=st->voc_m2=st->voc_mean=0; + st->voc_offset=0; + st->dtx_enabled=0; +#ifdef ENABLE_VALGRIND + VALGRIND_MAKE_READABLE(st, (st->stack-(char*)st)); +#endif + return st; +} + +void nb_decoder_destroy(void *state) +{ + DecState *st; + st=(DecState*)state; + +#if !(defined(VAR_ARRAYS) || defined (USE_ALLOCA)) + speex_free_scratch(st->stack); +#endif + + speex_free (st->inBuf); + speex_free (st->excBuf); + speex_free (st->innov); + speex_free (st->interp_qlpc); + speex_free (st->qlsp); + speex_free (st->old_qlsp); + speex_free (st->interp_qlsp); + speex_free (st->mem_sp); + speex_free (st->comb_mem); + speex_free (st->pi_gain); + + speex_free(state); +} + +#define median3(a, b, c) ((a) < (b) ? ((b) < (c) ? (b) : ((a) < (c) ? (c) : (a))) : ((c) < (b) ? (b) : ((c) < (a) ? (c) : (a)))) + +#ifdef FIXED_POINT +const spx_word16_t attenuation[10] = {32767, 31483, 27923, 22861, 17278, 12055, 7764, 4616, 2533, 1283}; +#else +const spx_word16_t attenuation[10] = {1., 0.961, 0.852, 0.698, 0.527, 0.368, 0.237, 0.141, 0.077, 0.039}; + +#endif + +static void nb_decode_lost(DecState *st, spx_word16_t *out, char *stack) +{ + int i, sub; + VARDECL(spx_coef_t *awk1); + VARDECL(spx_coef_t *awk2); + VARDECL(spx_coef_t *awk3); + spx_word16_t pitch_gain; + spx_word16_t fact; + spx_word16_t gain_med; + spx_word16_t innov_gain; + + if (st->count_lost<10) + fact = attenuation[st->count_lost]; + else + fact = 0; + + gain_med = median3(st->pitch_gain_buf[0], st->pitch_gain_buf[1], st->pitch_gain_buf[2]); + if (gain_med < st->last_pitch_gain) + st->last_pitch_gain = gain_med; + +#ifdef FIXED_POINT + pitch_gain = st->last_pitch_gain; + if (pitch_gain>62) + pitch_gain = 62; + pitch_gain = SHL(pitch_gain, 9); +#else + pitch_gain = GAIN_SCALING_1*st->last_pitch_gain; + if (pitch_gain>.95) + pitch_gain=.95; +#endif + + pitch_gain = MULT16_16_Q15(fact,pitch_gain) + VERY_SMALL; + + /* Shift all buffers by one frame */ + /*speex_move(st->inBuf, st->inBuf+st->frameSize, (st->bufSize-st->frameSize)*sizeof(spx_sig_t));*/ + speex_move(st->excBuf, st->excBuf+st->frameSize, (st->max_pitch + 1)*sizeof(spx_sig_t)); + + ALLOC(awk1, (st->lpcSize+1), spx_coef_t); + ALLOC(awk2, (st->lpcSize+1), spx_coef_t); + ALLOC(awk3, (st->lpcSize+1), spx_coef_t); + + for (sub=0;subnbSubframes;sub++) + { + int offset; + spx_sig_t *sp, *exc; + /* Offset relative to start of frame */ + offset = st->subframeSize*sub; + /* Original signal */ + sp=st->frame+offset; + /* Excitation */ + exc=st->exc+offset; + /* Excitation after post-filter*/ + + /* Calculate perceptually enhanced LPC filter */ + if (st->lpc_enh_enabled) + { + spx_word16_t k1,k2,k3; + if (st->submodes[st->submodeID] != NULL) + { + k1=SUBMODE(lpc_enh_k1); + k2=SUBMODE(lpc_enh_k2); + k3=SUBMODE(lpc_enh_k3); + } else { + k1=k2=.7*GAMMA_SCALING; + k3=.0; + } + bw_lpc(k1, st->interp_qlpc, awk1, st->lpcSize); + bw_lpc(k2, st->interp_qlpc, awk2, st->lpcSize); + bw_lpc(k3, st->interp_qlpc, awk3, st->lpcSize); + } + + /* Make up a plausible excitation */ + /* FIXME: THIS CAN BE IMPROVED */ + /*if (pitch_gain>.95) + pitch_gain=.95;*/ + innov_gain = compute_rms(st->innov, st->frameSize); + for (i=0;isubframeSize;i++) + { + exc[i]= MULT16_32_Q15(pitch_gain, (exc[i-st->last_pitch]+VERY_SMALL)) + + MULT16_32_Q15(fact, MULT16_32_Q15(sqrt(SHL(Q15ONE,15)-SHL(pitch_gain,15)),speex_rand(innov_gain, &st->seed))); + } + + for (i=0;isubframeSize;i++) + sp[i]=exc[i]; + + /* Signal synthesis */ + if (st->lpc_enh_enabled) + { + filter_mem2(sp, awk2, awk1, sp, st->subframeSize, st->lpcSize, + st->mem_sp+st->lpcSize); + filter_mem2(sp, awk3, st->interp_qlpc, sp, st->subframeSize, st->lpcSize, + st->mem_sp); + } else { + for (i=0;ilpcSize;i++) + st->mem_sp[st->lpcSize+i] = 0; + iir_mem2(sp, st->interp_qlpc, sp, st->subframeSize, st->lpcSize, + st->mem_sp); + } + } + + for (i=0;iframeSize;i++) + { + spx_word32_t sig = PSHR32(st->frame[i],SIG_SHIFT); + if (sig>32767) + sig = 32767; + if (sig<-32767) + sig = -32767; + out[i]=sig; + } + + st->first = 0; + st->count_lost++; + st->pitch_gain_buf[st->pitch_gain_buf_idx++] = PSHR(pitch_gain,9); + if (st->pitch_gain_buf_idx > 2) /* rollover */ + st->pitch_gain_buf_idx = 0; +} + +int nb_decode(void *state, SpeexBits *bits, void *vout) +{ + DecState *st; + int i, sub; + int pitch; + spx_word16_t pitch_gain[3]; + spx_word32_t ol_gain=0; + int ol_pitch=0; + spx_word16_t ol_pitch_coef=0; + int best_pitch=40; + spx_word16_t best_pitch_gain=0; + int wideband; + int m; + char *stack; + VARDECL(spx_coef_t *awk1); + VARDECL(spx_coef_t *awk2); + VARDECL(spx_coef_t *awk3); + spx_word16_t pitch_average=0; +#ifdef EPIC_48K + int pitch_half[2]; + int ol_pitch_id=0; +#endif + spx_word16_t *out = vout; + + st=(DecState*)state; + stack=st->stack; + + if (st->encode_submode) + { +#ifdef EPIC_48K + if (!st->lbr_48k) { +#endif + + /* Check if we're in DTX mode*/ + if (!bits && st->dtx_enabled) + { + st->submodeID=0; + } else + { + /* If bits is NULL, consider the packet to be lost (what could we do anyway) */ + if (!bits) + { + nb_decode_lost(st, out, stack); + return 0; + } + + /* Search for next narrowband block (handle requests, skip wideband blocks) */ + do { + if (speex_bits_remaining(bits)<5) + return -1; + wideband = speex_bits_unpack_unsigned(bits, 1); + if (wideband) /* Skip wideband block (for compatibility) */ + { + int submode; + int advance; + advance = submode = speex_bits_unpack_unsigned(bits, SB_SUBMODE_BITS); + speex_mode_query(&speex_wb_mode, SPEEX_SUBMODE_BITS_PER_FRAME, &advance); + if (advance < 0) + { + speex_warning ("Invalid wideband mode encountered. Corrupted stream?"); + return -2; + } + advance -= (SB_SUBMODE_BITS+1); + speex_bits_advance(bits, advance); + + if (speex_bits_remaining(bits)<5) + return -1; + wideband = speex_bits_unpack_unsigned(bits, 1); + if (wideband) + { + advance = submode = speex_bits_unpack_unsigned(bits, SB_SUBMODE_BITS); + speex_mode_query(&speex_wb_mode, SPEEX_SUBMODE_BITS_PER_FRAME, &advance); + if (advance < 0) + { + speex_warning ("Invalid wideband mode encountered: corrupted stream?"); + return -2; + } + advance -= (SB_SUBMODE_BITS+1); + speex_bits_advance(bits, advance); + wideband = speex_bits_unpack_unsigned(bits, 1); + if (wideband) + { + speex_warning ("More than two wideband layers found: corrupted stream?"); + return -2; + } + + } + } + if (speex_bits_remaining(bits)<4) + return -1; + /* FIXME: Check for overflow */ + m = speex_bits_unpack_unsigned(bits, 4); + if (m==15) /* We found a terminator */ + { + return -1; + } else if (m==14) /* Speex in-band request */ + { + int ret = speex_inband_handler(bits, st->speex_callbacks, state); + if (ret) + return ret; + } else if (m==13) /* User in-band request */ + { + int ret = st->user_callback.func(bits, state, st->user_callback.data); + if (ret) + return ret; + } else if (m>8) /* Invalid mode */ + { + speex_warning("Invalid mode encountered: corrupted stream?"); + return -2; + } + + } while (m>8); + + /* Get the sub-mode that was used */ + st->submodeID = m; + + } +#ifdef EPIC_48K + } +#endif + } + + /* Shift all buffers by one frame */ + speex_move(st->excBuf, st->excBuf+st->frameSize, (st->max_pitch + 1)*sizeof(spx_sig_t)); + + /* If null mode (no transmission), just set a couple things to zero*/ + if (st->submodes[st->submodeID] == NULL) + { + VARDECL(spx_coef_t *lpc); + ALLOC(lpc, st->lpcSize, spx_coef_t); + bw_lpc(GAMMA_SCALING*.93, st->interp_qlpc, lpc, st->lpcSize); + { + float innov_gain=0; + float pgain=GAIN_SCALING_1*st->last_pitch_gain; + if (pgain>.6) + pgain=.6; + innov_gain = compute_rms(st->innov, st->frameSize); + for (i=0;iframeSize;i++) + st->exc[i]=VERY_SMALL; + speex_rand_vec(innov_gain, st->exc, st->frameSize); + } + + + st->first=1; + + /* Final signal synthesis from excitation */ + iir_mem2(st->exc, lpc, st->frame, st->frameSize, st->lpcSize, st->mem_sp); + + for (i=0;iframeSize;i++) + { + spx_word32_t sig = PSHR32(st->frame[i],SIG_SHIFT); + if (sig>32767) + sig = 32767; + if (sig<-32767) + sig = -32767; + out[i]=sig; + } + + st->count_lost=0; + return 0; + } + + /* Unquantize LSPs */ + SUBMODE(lsp_unquant)(st->qlsp, st->lpcSize, bits); + + /*Damp memory if a frame was lost and the LSP changed too much*/ + if (st->count_lost) + { + spx_word16_t fact; + spx_word32_t lsp_dist=0; + for (i=0;ilpcSize;i++) + lsp_dist = ADD32(lsp_dist, EXTEND32(ABS(st->old_qlsp[i] - st->qlsp[i]))); +#ifdef FIXED_POINT + fact = SHR16(19661,SHR32(lsp_dist,LSP_SHIFT+2)); +#else + fact = .6*exp(-.2*lsp_dist); +#endif + for (i=0;i<2*st->lpcSize;i++) + st->mem_sp[i] = MULT16_32_Q15(fact,st->mem_sp[i]); + } + + + /* Handle first frame and lost-packet case */ + if (st->first || st->count_lost) + { + for (i=0;ilpcSize;i++) + st->old_qlsp[i] = st->qlsp[i]; + } + +#ifdef EPIC_48K + if (st->lbr_48k) { + pitch_half[0] = st->min_pitch+speex_bits_unpack_unsigned(bits, 7); + pitch_half[1] = pitch_half[0]+speex_bits_unpack_unsigned(bits, 2)-1; + + ol_pitch_id = speex_bits_unpack_unsigned(bits, 3); + ol_pitch_coef=GAIN_SCALING*0.13514*ol_pitch_id; + + { + int qe; + qe = speex_bits_unpack_unsigned(bits, 4); + ol_gain = SIG_SCALING*exp((qe+2)/2.1),SIG_SHIFT; + } + + } else { +#endif + + /* Get open-loop pitch estimation for low bit-rate pitch coding */ + if (SUBMODE(lbr_pitch)!=-1) + { + ol_pitch = st->min_pitch+speex_bits_unpack_unsigned(bits, 7); + } + + if (SUBMODE(forced_pitch_gain)) + { + int quant; + quant = speex_bits_unpack_unsigned(bits, 4); + ol_pitch_coef=GAIN_SCALING*0.066667*quant; + } + + /* Get global excitation gain */ + { + int qe; + qe = speex_bits_unpack_unsigned(bits, 5); +#ifdef FIXED_POINT + ol_gain = MULT16_32_Q15(28406,ol_gain_table[qe]); +#else + ol_gain = SIG_SCALING*exp(qe/3.5); +#endif + } +#ifdef EPIC_48K + } +#endif + + ALLOC(awk1, st->lpcSize+1, spx_coef_t); + ALLOC(awk2, st->lpcSize+1, spx_coef_t); + ALLOC(awk3, st->lpcSize+1, spx_coef_t); + + if (st->submodeID==1) + { + int extra; + extra = speex_bits_unpack_unsigned(bits, 4); + + if (extra==15) + st->dtx_enabled=1; + else + st->dtx_enabled=0; + } + if (st->submodeID>1) + st->dtx_enabled=0; + + /*Loop on subframes */ + for (sub=0;subnbSubframes;sub++) + { + int offset; + spx_sig_t *sp, *exc; + spx_word16_t tmp; + +#ifdef EPIC_48K + if (st->lbr_48k) + { + if (sub*2 < st->nbSubframes) + ol_pitch = pitch_half[0]; + else + ol_pitch = pitch_half[1]; + } +#endif + + /* Offset relative to start of frame */ + offset = st->subframeSize*sub; + /* Original signal */ + sp=st->frame+offset; + /* Excitation */ + exc=st->exc+offset; + /* Excitation after post-filter*/ + + /* LSP interpolation (quantized and unquantized) */ + lsp_interpolate(st->old_qlsp, st->qlsp, st->interp_qlsp, st->lpcSize, sub, st->nbSubframes); + + /* Make sure the LSP's are stable */ + lsp_enforce_margin(st->interp_qlsp, st->lpcSize, LSP_MARGIN); + + + /* Compute interpolated LPCs (unquantized) */ + lsp_to_lpc(st->interp_qlsp, st->interp_qlpc, st->lpcSize, stack); + + /* Compute enhanced synthesis filter */ + if (st->lpc_enh_enabled) + { + bw_lpc(SUBMODE(lpc_enh_k1), st->interp_qlpc, awk1, st->lpcSize); + bw_lpc(SUBMODE(lpc_enh_k2), st->interp_qlpc, awk2, st->lpcSize); + bw_lpc(SUBMODE(lpc_enh_k3), st->interp_qlpc, awk3, st->lpcSize); + } + + /* Compute analysis filter at w=pi */ + { + spx_word32_t pi_g=LPC_SCALING; + for (i=0;ilpcSize;i+=2) + { + /*pi_g += -st->interp_qlpc[i] + st->interp_qlpc[i+1];*/ + pi_g = ADD32(pi_g, SUB32(st->interp_qlpc[i+1],st->interp_qlpc[i])); + } + st->pi_gain[sub] = pi_g; + } + + /* Reset excitation */ + for (i=0;isubframeSize;i++) + exc[i]=0; + + /*Adaptive codebook contribution*/ + if (SUBMODE(ltp_unquant)) + { + int pit_min, pit_max; + /* Handle pitch constraints if any */ + if (SUBMODE(lbr_pitch) != -1) + { + int margin; + margin = SUBMODE(lbr_pitch); + if (margin) + { +/* GT - need optimization? + if (ol_pitch < st->min_pitch+margin-1) + ol_pitch=st->min_pitch+margin-1; + if (ol_pitch > st->max_pitch-margin) + ol_pitch=st->max_pitch-margin; + pit_min = ol_pitch-margin+1; + pit_max = ol_pitch+margin; +*/ + pit_min = ol_pitch-margin+1; + if (pit_min < st->min_pitch) + pit_min = st->min_pitch; + pit_max = ol_pitch+margin; + if (pit_max > st->max_pitch) + pit_max = st->max_pitch; + } else { + pit_min = pit_max = ol_pitch; + } + } else { + pit_min = st->min_pitch; + pit_max = st->max_pitch; + } + + +#ifdef EPIC_48K + if (st->lbr_48k) + { + SUBMODE(ltp_unquant)(exc, pit_min, pit_max, ol_pitch_coef, SUBMODE(ltp_params), + st->subframeSize, &pitch, &pitch_gain[0], bits, stack, + st->count_lost, offset, st->last_pitch_gain, ol_pitch_id); + } else { +#endif + + SUBMODE(ltp_unquant)(exc, pit_min, pit_max, ol_pitch_coef, SUBMODE(ltp_params), + st->subframeSize, &pitch, &pitch_gain[0], bits, stack, + st->count_lost, offset, st->last_pitch_gain, 0); + +#ifdef EPIC_48K + } +#endif + + + /* If we had lost frames, check energy of last received frame */ + if (st->count_lost && ol_gain < st->last_ol_gain) + { + /*float fact = (float)ol_gain/(st->last_ol_gain+1); + for (i=0;isubframeSize;i++) + exc[i]*=fact;*/ + spx_word16_t fact = DIV32_16(SHL32(EXTEND32(ol_gain),15),st->last_ol_gain+1); + for (i=0;isubframeSize;i++) + exc[i] = MULT16_32_Q15(fact, exc[i]); + } + + tmp = gain_3tap_to_1tap(pitch_gain); + + pitch_average += tmp; + if (tmp>best_pitch_gain) + { + best_pitch = pitch; + best_pitch_gain = tmp; + } + } else { + speex_error("No pitch prediction, what's wrong"); + } + + /* Unquantize the innovation */ + { + int q_energy; + spx_word32_t ener; + spx_sig_t *innov; + + innov = st->innov+sub*st->subframeSize; + for (i=0;isubframeSize;i++) + innov[i]=0; + + /* Decode sub-frame gain correction */ + if (SUBMODE(have_subframe_gain)==3) + { + q_energy = speex_bits_unpack_unsigned(bits, 3); + ener = MULT16_32_Q14(exc_gain_quant_scal3[q_energy],ol_gain); + } else if (SUBMODE(have_subframe_gain)==1) + { + q_energy = speex_bits_unpack_unsigned(bits, 1); + ener = MULT16_32_Q14(exc_gain_quant_scal1[q_energy],ol_gain); + } else { + ener = ol_gain; + } + + if (SUBMODE(innovation_unquant)) + { + /*Fixed codebook contribution*/ + SUBMODE(innovation_unquant)(innov, SUBMODE(innovation_params), st->subframeSize, bits, stack); + } else { + speex_error("No fixed codebook"); + } + + /* De-normalize innovation and update excitation */ +#ifdef FIXED_POINT + signal_mul(innov, innov, ener, st->subframeSize); +#else + signal_mul(innov, innov, ener, st->subframeSize); +#endif + /*Vocoder mode*/ + if (st->submodeID==1) + { + float g=ol_pitch_coef*GAIN_SCALING_1; + + + for (i=0;isubframeSize;i++) + exc[i]=0; + while (st->voc_offsetsubframeSize) + { + if (st->voc_offset>=0) + exc[st->voc_offset]=SIG_SCALING*sqrt(1.0*ol_pitch); + st->voc_offset+=ol_pitch; + } + st->voc_offset -= st->subframeSize; + + g=.5+2*(g-.6); + if (g<0) + g=0; + if (g>1) + g=1; + for (i=0;isubframeSize;i++) + { + float exci=exc[i]; + exc[i]=.8*g*exc[i]*ol_gain/SIG_SCALING + .6*g*st->voc_m1*ol_gain/SIG_SCALING + .5*g*innov[i] - .5*g*st->voc_m2 + (1-g)*innov[i]; + st->voc_m1 = exci; + st->voc_m2=innov[i]; + st->voc_mean = .95*st->voc_mean + .05*exc[i]; + exc[i]-=st->voc_mean; + } + } else { + for (i=0;isubframeSize;i++) + exc[i]=ADD32(exc[i],innov[i]); + /*print_vec(exc, 40, "innov");*/ + } + /* Decode second codebook (only for some modes) */ + if (SUBMODE(double_codebook)) + { + char *tmp_stack=stack; + VARDECL(spx_sig_t *innov2); + ALLOC(innov2, st->subframeSize, spx_sig_t); + for (i=0;isubframeSize;i++) + innov2[i]=0; + SUBMODE(innovation_unquant)(innov2, SUBMODE(innovation_params), st->subframeSize, bits, stack); + signal_mul(innov2, innov2, (spx_word32_t) (ener*(1/2.2)), st->subframeSize); + for (i=0;isubframeSize;i++) + exc[i] = ADD32(exc[i],innov2[i]); + stack = tmp_stack; + } + + } + + for (i=0;isubframeSize;i++) + sp[i]=exc[i]; + + /* Signal synthesis */ + if (st->lpc_enh_enabled && SUBMODE(comb_gain)>0) + comb_filter(exc, sp, st->interp_qlpc, st->lpcSize, st->subframeSize, + pitch, pitch_gain, SUBMODE(comb_gain), st->comb_mem); + + if (st->lpc_enh_enabled) + { + /* Use enhanced LPC filter */ + filter_mem2(sp, awk2, awk1, sp, st->subframeSize, st->lpcSize, + st->mem_sp+st->lpcSize); + filter_mem2(sp, awk3, st->interp_qlpc, sp, st->subframeSize, st->lpcSize, + st->mem_sp); + } else { + /* Use regular filter */ + for (i=0;ilpcSize;i++) + st->mem_sp[st->lpcSize+i] = 0; + iir_mem2(sp, st->interp_qlpc, sp, st->subframeSize, st->lpcSize, + st->mem_sp); + } + } + + /*Copy output signal*/ + for (i=0;iframeSize;i++) + { + spx_word32_t sig = PSHR32(st->frame[i],SIG_SHIFT); + if (sig>32767) + sig = 32767; + if (sig<-32767) + sig = -32767; + out[i]=sig; + } + + /*for (i=0;iframeSize;i++) + printf ("%d\n", (int)st->frame[i]);*/ + + /* Store the LSPs for interpolation in the next frame */ + for (i=0;ilpcSize;i++) + st->old_qlsp[i] = st->qlsp[i]; + + /* The next frame will not be the first (Duh!) */ + st->first = 0; + st->count_lost=0; + st->last_pitch = best_pitch; +#ifdef FIXED_POINT + st->last_pitch_gain = PSHR16(pitch_average,2); +#else + st->last_pitch_gain = .25*pitch_average; +#endif + st->pitch_gain_buf[st->pitch_gain_buf_idx++] = st->last_pitch_gain; + if (st->pitch_gain_buf_idx > 2) /* rollover */ + st->pitch_gain_buf_idx = 0; + + st->last_ol_gain = ol_gain; + + return 0; +} + +int nb_encoder_ctl(void *state, int request, void *ptr) +{ + EncState *st; + st=(EncState*)state; + switch(request) + { + case SPEEX_GET_FRAME_SIZE: + (*(int*)ptr) = st->frameSize; + break; + case SPEEX_SET_LOW_MODE: + case SPEEX_SET_MODE: + st->submodeSelect = st->submodeID = (*(int*)ptr); + break; + case SPEEX_GET_LOW_MODE: + case SPEEX_GET_MODE: + (*(int*)ptr) = st->submodeID; + break; + case SPEEX_SET_VBR: + st->vbr_enabled = (*(int*)ptr); + break; + case SPEEX_GET_VBR: + (*(int*)ptr) = st->vbr_enabled; + break; + case SPEEX_SET_VAD: + st->vad_enabled = (*(int*)ptr); + break; + case SPEEX_GET_VAD: + (*(int*)ptr) = st->vad_enabled; + break; + case SPEEX_SET_DTX: + st->dtx_enabled = (*(int*)ptr); + break; + case SPEEX_GET_DTX: + (*(int*)ptr) = st->dtx_enabled; + break; + case SPEEX_SET_ABR: + st->abr_enabled = (*(int*)ptr); + st->vbr_enabled = 1; + { + int i=10, rate, target; + float vbr_qual; + target = (*(int*)ptr); + while (i>=0) + { + speex_encoder_ctl(st, SPEEX_SET_QUALITY, &i); + speex_encoder_ctl(st, SPEEX_GET_BITRATE, &rate); + if (rate <= target) + break; + i--; + } + vbr_qual=i; + if (vbr_qual<0) + vbr_qual=0; + speex_encoder_ctl(st, SPEEX_SET_VBR_QUALITY, &vbr_qual); + st->abr_count=0; + st->abr_drift=0; + st->abr_drift2=0; + } + + break; + case SPEEX_GET_ABR: + (*(int*)ptr) = st->abr_enabled; + break; + case SPEEX_SET_VBR_QUALITY: + st->vbr_quality = (*(float*)ptr); + break; + case SPEEX_GET_VBR_QUALITY: + (*(float*)ptr) = st->vbr_quality; + break; + case SPEEX_SET_QUALITY: + { + int quality = (*(int*)ptr); + if (quality < 0) + quality = 0; + if (quality > 10) + quality = 10; + st->submodeSelect = st->submodeID = ((const SpeexNBMode*)(st->mode->mode))->quality_map[quality]; + } + break; + case SPEEX_SET_COMPLEXITY: + st->complexity = (*(int*)ptr); + if (st->complexity<0) + st->complexity=0; + break; + case SPEEX_GET_COMPLEXITY: + (*(int*)ptr) = st->complexity; + break; + case SPEEX_SET_BITRATE: + { + int i=10, rate, target; + target = (*(int*)ptr); + while (i>=0) + { + speex_encoder_ctl(st, SPEEX_SET_QUALITY, &i); + speex_encoder_ctl(st, SPEEX_GET_BITRATE, &rate); + if (rate <= target) + break; + i--; + } + } + break; + case SPEEX_GET_BITRATE: + if (st->submodes[st->submodeID]) + (*(int*)ptr) = st->sampling_rate*SUBMODE(bits_per_frame)/st->frameSize; + else + (*(int*)ptr) = st->sampling_rate*(NB_SUBMODE_BITS+1)/st->frameSize; + break; + case SPEEX_SET_SAMPLING_RATE: + st->sampling_rate = (*(int*)ptr); + break; + case SPEEX_GET_SAMPLING_RATE: + (*(int*)ptr)=st->sampling_rate; + break; + case SPEEX_RESET_STATE: + { + int i; + st->bounded_pitch = 1; + st->first = 1; + for (i=0;ilpcSize;i++) + st->lsp[i]=(M_PI*((float)(i+1)))/(st->lpcSize+1); + for (i=0;ilpcSize;i++) + st->mem_sw[i]=st->mem_sw_whole[i]=st->mem_sp[i]=st->mem_exc[i]=0; + for (i=0;iframeSize+st->max_pitch+1;i++) + st->excBuf[i]=st->swBuf[i]=0; + for (i=0;iwindowSize;i++) + st->inBuf[i]=0; + } + break; + case SPEEX_SET_SUBMODE_ENCODING: + st->encode_submode = (*(int*)ptr); + break; + case SPEEX_GET_SUBMODE_ENCODING: + (*(int*)ptr) = st->encode_submode; + break; + case SPEEX_GET_LOOKAHEAD: + (*(int*)ptr)=(st->windowSize-st->frameSize); + break; + case SPEEX_SET_PLC_TUNING: + st->plc_tuning = (*(int*)ptr); + if (st->plc_tuning>100) + st->plc_tuning=100; + break; + case SPEEX_GET_PLC_TUNING: + (*(int*)ptr)=(st->plc_tuning); + break; + case SPEEX_GET_PI_GAIN: + { + int i; + spx_word32_t *g = (spx_word32_t*)ptr; + for (i=0;inbSubframes;i++) + g[i]=st->pi_gain[i]; + } + break; + case SPEEX_GET_EXC: + { + int i; + spx_sig_t *e = (spx_sig_t*)ptr; + for (i=0;iframeSize;i++) + e[i]=st->exc[i]; + } + break; + case SPEEX_GET_INNOV: + { + int i; + spx_sig_t *e = (spx_sig_t*)ptr; + for (i=0;iframeSize;i++) + e[i]=st->innov[i]; + } + break; + case SPEEX_GET_RELATIVE_QUALITY: + (*(float*)ptr)=st->relative_quality; + break; + default: + speex_warning_int("Unknown nb_ctl request: ", request); + return -1; + } + return 0; +} + +int nb_decoder_ctl(void *state, int request, void *ptr) +{ + DecState *st; + st=(DecState*)state; + switch(request) + { + case SPEEX_SET_LOW_MODE: + case SPEEX_SET_MODE: + st->submodeID = (*(int*)ptr); + break; + case SPEEX_GET_LOW_MODE: + case SPEEX_GET_MODE: + (*(int*)ptr) = st->submodeID; + break; + case SPEEX_SET_ENH: + st->lpc_enh_enabled = *((int*)ptr); + break; + case SPEEX_GET_ENH: + *((int*)ptr) = st->lpc_enh_enabled; + break; + case SPEEX_GET_FRAME_SIZE: + (*(int*)ptr) = st->frameSize; + break; + case SPEEX_GET_BITRATE: + if (st->submodes[st->submodeID]) + (*(int*)ptr) = st->sampling_rate*SUBMODE(bits_per_frame)/st->frameSize; + else + (*(int*)ptr) = st->sampling_rate*(NB_SUBMODE_BITS+1)/st->frameSize; + break; + case SPEEX_SET_SAMPLING_RATE: + st->sampling_rate = (*(int*)ptr); + break; + case SPEEX_GET_SAMPLING_RATE: + (*(int*)ptr)=st->sampling_rate; + break; + case SPEEX_SET_HANDLER: + { + SpeexCallback *c = (SpeexCallback*)ptr; + st->speex_callbacks[c->callback_id].func=c->func; + st->speex_callbacks[c->callback_id].data=c->data; + st->speex_callbacks[c->callback_id].callback_id=c->callback_id; + } + break; + case SPEEX_SET_USER_HANDLER: + { + SpeexCallback *c = (SpeexCallback*)ptr; + st->user_callback.func=c->func; + st->user_callback.data=c->data; + st->user_callback.callback_id=c->callback_id; + } + break; + case SPEEX_RESET_STATE: + { + int i; + for (i=0;i<2*st->lpcSize;i++) + st->mem_sp[i]=0; + for (i=0;iframeSize + st->max_pitch + 1;i++) + st->excBuf[i]=0; + for (i=0;iframeSize;i++) + st->inBuf[i] = 0; + } + break; + case SPEEX_SET_SUBMODE_ENCODING: + st->encode_submode = (*(int*)ptr); + break; + case SPEEX_GET_SUBMODE_ENCODING: + (*(int*)ptr) = st->encode_submode; + break; + case SPEEX_GET_PI_GAIN: + { + int i; + spx_word32_t *g = (spx_word32_t*)ptr; + for (i=0;inbSubframes;i++) + g[i]=st->pi_gain[i]; + } + break; + case SPEEX_GET_EXC: + { + int i; + spx_sig_t *e = (spx_sig_t*)ptr; + for (i=0;iframeSize;i++) + e[i]=st->exc[i]; + } + break; + case SPEEX_GET_INNOV: + { + int i; + spx_sig_t *e = (spx_sig_t*)ptr; + for (i=0;iframeSize;i++) + e[i]=st->innov[i]; + } + break; + case SPEEX_GET_DTX_STATUS: + *((int*)ptr) = st->dtx_enabled; + break; + default: + speex_warning_int("Unknown nb_ctl request: ", request); + return -1; + } + return 0; +} diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/nb_celp.h b/mozilla/zap/zmk/speex-1.1.10/libspeex/nb_celp.h new file mode 100755 index 00000000000..de570cfcc45 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/nb_celp.h @@ -0,0 +1,200 @@ +/* Copyright (C) 2002 Jean-Marc Valin */ +/** + @file nb_celp.h + @brief Narrowband CELP encoder/decoder +*/ +/* + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 NB_CELP_H +#define NB_CELP_H + +#include "modes.h" +#include +#include +#include "vbr.h" +#include "filters.h" + +/**Structure representing the full state of the narrowband encoder*/ +typedef struct EncState { + const SpeexMode *mode; /**< Mode corresponding to the state */ + int first; /**< Is this the first frame? */ + int frameSize; /**< Size of frames */ + int subframeSize; /**< Size of sub-frames */ + int nbSubframes; /**< Number of sub-frames */ + int windowSize; /**< Analysis (LPC) window length */ + int lpcSize; /**< LPC order */ + int min_pitch; /**< Minimum pitch value allowed */ + int max_pitch; /**< Maximum pitch value allowed */ + + int safe_pitch; /**< Don't use too large values for pitch (in case we lose a packet) */ + int bounded_pitch; /**< Next frame should not rely on previous frames for pitch */ + int ol_pitch; /**< Open-loop pitch */ + int ol_voiced; /**< Open-loop voiced/non-voiced decision */ + int *pitch; + +#ifdef EPIC_48K + int lbr_48k; +#endif + + spx_word16_t gamma1; /**< Perceptual filter: A(z/gamma1) */ + spx_word16_t gamma2; /**< Perceptual filter: A(z/gamma2) */ + float lag_factor; /**< Lag windowing Gaussian width */ + float lpc_floor; /**< Noise floor multiplier for A[0] in LPC analysis*/ + char *stack; /**< Pseudo-stack allocation for temporary memory */ + spx_sig_t *inBuf; /**< Input buffer (original signal) */ + spx_sig_t *frame; /**< Start of original frame */ + spx_sig_t *excBuf; /**< Excitation buffer */ + spx_sig_t *exc; /**< Start of excitation frame */ + spx_sig_t *swBuf; /**< Weighted signal buffer */ + spx_sig_t *sw; /**< Start of weighted signal frame */ + spx_sig_t *innov; /**< Innovation for the frame */ + spx_word16_t *window; /**< Temporary (Hanning) window */ + spx_word16_t *autocorr; /**< auto-correlation */ + spx_word16_t *lagWindow; /**< Window applied to auto-correlation */ + spx_coef_t *lpc; /**< LPCs for current frame */ + spx_lsp_t *lsp; /**< LSPs for current frame */ + spx_lsp_t *qlsp; /**< Quantized LSPs for current frame */ + spx_lsp_t *old_lsp; /**< LSPs for previous frame */ + spx_lsp_t *old_qlsp; /**< Quantized LSPs for previous frame */ + spx_lsp_t *interp_lsp; /**< Interpolated LSPs */ + spx_lsp_t *interp_qlsp; /**< Interpolated quantized LSPs */ + spx_coef_t *interp_lpc; /**< Interpolated LPCs */ + spx_coef_t *interp_qlpc; /**< Interpolated quantized LPCs */ + spx_coef_t *bw_lpc1; /**< LPCs after bandwidth expansion by gamma1 for perceptual weighting*/ + spx_coef_t *bw_lpc2; /**< LPCs after bandwidth expansion by gamma2 for perceptual weighting*/ + spx_mem_t *mem_sp; /**< Filter memory for signal synthesis */ + spx_mem_t *mem_sw; /**< Filter memory for perceptually-weighted signal */ + spx_mem_t *mem_sw_whole; /**< Filter memory for perceptually-weighted signal (whole frame)*/ + spx_mem_t *mem_exc; /**< Filter memory for excitation (whole frame) */ + spx_word32_t *pi_gain; /**< Gain of LPC filter at theta=pi (fe/2) */ + + VBRState *vbr; /**< State of the VBR data */ + float vbr_quality; /**< Quality setting for VBR encoding */ + float relative_quality; /**< Relative quality that will be needed by VBR */ + int vbr_enabled; /**< 1 for enabling VBR, 0 otherwise */ + int vad_enabled; /**< 1 for enabling VAD, 0 otherwise */ + int dtx_enabled; /**< 1 for enabling DTX, 0 otherwise */ + int dtx_count; /**< Number of consecutive DTX frames */ + int abr_enabled; /**< ABR setting (in bps), 0 if off */ + float abr_drift; + float abr_drift2; + float abr_count; + int complexity; /**< Complexity setting (0-10 from least complex to most complex) */ + int sampling_rate; + int plc_tuning; + int encode_submode; + const SpeexSubmode * const *submodes; /**< Sub-mode data */ + int submodeID; /**< Activated sub-mode */ + int submodeSelect; /**< Mode chosen by the user (may differ from submodeID if VAD is on) */ +} EncState; + +/**Structure representing the full state of the narrowband decoder*/ +typedef struct DecState { + const SpeexMode *mode; /**< Mode corresponding to the state */ + int first; /**< Is this the first frame? */ + int count_lost; /**< Was the last frame lost? */ + int frameSize; /**< Size of frames */ + int subframeSize; /**< Size of sub-frames */ + int nbSubframes; /**< Number of sub-frames */ + int lpcSize; /**< LPC order */ + int min_pitch; /**< Minimum pitch value allowed */ + int max_pitch; /**< Maximum pitch value allowed */ + int sampling_rate; + +#ifdef EPIC_48K + int lbr_48k; +#endif + + spx_word16_t last_ol_gain; /**< Open-loop gain for previous frame */ + + char *stack; /**< Pseudo-stack allocation for temporary memory */ + spx_sig_t *inBuf; /**< Input buffer (original signal) */ + spx_sig_t *frame; /**< Start of original frame */ + spx_sig_t *excBuf; /**< Excitation buffer */ + spx_sig_t *exc; /**< Start of excitation frame */ + spx_sig_t *innov; /**< Innovation for the frame */ + spx_lsp_t *qlsp; /**< Quantized LSPs for current frame */ + spx_lsp_t *old_qlsp; /**< Quantized LSPs for previous frame */ + spx_lsp_t *interp_qlsp; /**< Interpolated quantized LSPs */ + spx_coef_t *interp_qlpc; /**< Interpolated quantized LPCs */ + spx_mem_t *mem_sp; /**< Filter memory for synthesis signal */ + spx_word32_t *pi_gain; /**< Gain of LPC filter at theta=pi (fe/2) */ + int last_pitch; /**< Pitch of last correctly decoded frame */ + spx_word16_t last_pitch_gain; /**< Pitch gain of last correctly decoded frame */ + spx_word16_t pitch_gain_buf[3]; /**< Pitch gain of last decoded frames */ + int pitch_gain_buf_idx; /**< Tail of the buffer */ + spx_int32_t seed; /** Seed used for random number generation */ + + int encode_submode; + const SpeexSubmode * const *submodes; /**< Sub-mode data */ + int submodeID; /**< Activated sub-mode */ + int lpc_enh_enabled; /**< 1 when LPC enhancer is on, 0 otherwise */ + CombFilterMem *comb_mem; + SpeexCallback speex_callbacks[SPEEX_MAX_CALLBACKS]; + + SpeexCallback user_callback; + + /*Vocoder data*/ + float voc_m1; + float voc_m2; + float voc_mean; + int voc_offset; + + int dtx_enabled; +} DecState; + +/** Initializes encoder state*/ +void *nb_encoder_init(const SpeexMode *m); + +/** De-allocates encoder state resources*/ +void nb_encoder_destroy(void *state); + +/** Encodes one frame*/ +int nb_encode(void *state, void *in, SpeexBits *bits); + + +/** Initializes decoder state*/ +void *nb_decoder_init(const SpeexMode *m); + +/** De-allocates decoder state resources*/ +void nb_decoder_destroy(void *state); + +/** Decodes one frame*/ +int nb_decode(void *state, SpeexBits *bits, void *out); + +/** ioctl-like function for controlling a narrowband encoder */ +int nb_encoder_ctl(void *state, int request, void *ptr); + +/** ioctl-like function for controlling a narrowband decoder */ +int nb_decoder_ctl(void *state, int request, void *ptr); + + +#endif diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/preprocess.c b/mozilla/zap/zmk/speex-1.1.10/libspeex/preprocess.c new file mode 100755 index 00000000000..a6e674a2f3d --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/preprocess.c @@ -0,0 +1,1045 @@ +/* Copyright (C) 2003 Epic Games + Written by Jean-Marc Valin + + File: preprocess.c + Preprocessor with denoising based on the algorithm by Ephraim and Malah + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. 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. + + 3. The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 +#include "speex/speex_preprocess.h" +#include "misc.h" +#include "smallft.h" + +#define max(a,b) ((a) > (b) ? (a) : (b)) +#define min(a,b) ((a) < (b) ? (a) : (b)) + +#ifndef M_PI +#define M_PI 3.14159263 +#endif + +#define SQRT_M_PI_2 0.88623 +#define LOUDNESS_EXP 2.5 + +#define NB_BANDS 8 + +#define ZMIN .1 +#define ZMAX .316 +#define ZMIN_1 10 +#define LOG_MIN_MAX_1 0.86859 + +static void conj_window(float *w, int len) +{ + int i; + for (i=0;i9.5) + return 1+.12/x; + + integer = floor(2*x); + frac = 2*x-integer; + ind = (int)integer; + /*if (ind > 20 || ind < 0) + fprintf (stderr, "error: %d %f\n", ind, x);*/ + return ((1-frac)*table[ind] + frac*table[ind+1])/sqrt(x+.0001f); +} + +SpeexPreprocessState *speex_preprocess_state_init(int frame_size, int sampling_rate) +{ + int i; + int N, N3, N4; + + SpeexPreprocessState *st = (SpeexPreprocessState *)speex_alloc(sizeof(SpeexPreprocessState)); + st->frame_size = frame_size; + + /* Round ps_size down to the nearest power of two */ +#if 0 + i=1; + st->ps_size = st->frame_size; + while(1) + { + if (st->ps_size & ~i) + { + st->ps_size &= ~i; + i<<=1; + } else { + break; + } + } + + + if (st->ps_size < 3*st->frame_size/4) + st->ps_size = st->ps_size * 3 / 2; +#else + st->ps_size = st->frame_size; +#endif + + N = st->ps_size; + N3 = 2*N - st->frame_size; + N4 = st->frame_size - N3; + + st->sampling_rate = sampling_rate; + st->denoise_enabled = 1; + st->agc_enabled = 0; + st->agc_level = 8000; + st->vad_enabled = 0; + st->dereverb_enabled = 0; + st->reverb_decay = .5; + st->reverb_level = .2; + + st->frame = (float*)speex_alloc(2*N*sizeof(float)); + st->ps = (float*)speex_alloc(N*sizeof(float)); + st->gain2 = (float*)speex_alloc(N*sizeof(float)); + st->window = (float*)speex_alloc(2*N*sizeof(float)); + st->noise = (float*)speex_alloc(N*sizeof(float)); + st->reverb_estimate = (float*)speex_alloc(N*sizeof(float)); + st->old_ps = (float*)speex_alloc(N*sizeof(float)); + st->gain = (float*)speex_alloc(N*sizeof(float)); + st->prior = (float*)speex_alloc(N*sizeof(float)); + st->post = (float*)speex_alloc(N*sizeof(float)); + st->loudness_weight = (float*)speex_alloc(N*sizeof(float)); + st->inbuf = (float*)speex_alloc(N3*sizeof(float)); + st->outbuf = (float*)speex_alloc(N3*sizeof(float)); + st->echo_noise = (float*)speex_alloc(N*sizeof(float)); + + st->S = (float*)speex_alloc(N*sizeof(float)); + st->Smin = (float*)speex_alloc(N*sizeof(float)); + st->Stmp = (float*)speex_alloc(N*sizeof(float)); + st->update_prob = (float*)speex_alloc(N*sizeof(float)); + + st->zeta = (float*)speex_alloc(N*sizeof(float)); + st->Zpeak = 0; + st->Zlast = 0; + + st->noise_bands = (float*)speex_alloc(NB_BANDS*sizeof(float)); + st->noise_bands2 = (float*)speex_alloc(NB_BANDS*sizeof(float)); + st->speech_bands = (float*)speex_alloc(NB_BANDS*sizeof(float)); + st->speech_bands2 = (float*)speex_alloc(NB_BANDS*sizeof(float)); + st->noise_bandsN = st->speech_bandsN = 1; + + conj_window(st->window, 2*N3); + for (i=2*N3;i<2*st->ps_size;i++) + st->window[i]=1; + + if (N4>0) + { + for (i=N3-1;i>=0;i--) + { + st->window[i+N3+N4]=st->window[i+N3]; + st->window[i+N3]=1; + } + } + for (i=0;inoise[i]=1e4; + st->reverb_estimate[i]=0.; + st->old_ps[i]=1e4; + st->gain[i]=1; + st->post[i]=1; + st->prior[i]=1; + } + + for (i=0;iinbuf[i]=0; + st->outbuf[i]=0; + } + + for (i=0;iloudness_weight[i] = .35f-.35f*ff/16000.f+.73f*exp(-.5f*(ff-3800)*(ff-3800)/9e5f); + if (st->loudness_weight[i]<.01f) + st->loudness_weight[i]=.01f; + st->loudness_weight[i] *= st->loudness_weight[i]; + } + + st->speech_prob = 0; + st->last_speech = 1000; + st->loudness = pow(6000,LOUDNESS_EXP); + st->loudness2 = 6000; + st->nb_loudness_adapt = 0; + + st->fft_lookup = (struct drft_lookup*)speex_alloc(sizeof(struct drft_lookup)); + spx_drft_init(st->fft_lookup,2*N); + + st->nb_adapt=0; + st->consec_noise=0; + st->nb_preprocess=0; + return st; +} + +void speex_preprocess_state_destroy(SpeexPreprocessState *st) +{ + speex_free(st->frame); + speex_free(st->ps); + speex_free(st->gain2); + speex_free(st->window); + speex_free(st->noise); + speex_free(st->reverb_estimate); + speex_free(st->old_ps); + speex_free(st->gain); + speex_free(st->prior); + speex_free(st->post); + speex_free(st->loudness_weight); + speex_free(st->echo_noise); + + speex_free(st->S); + speex_free(st->Smin); + speex_free(st->Stmp); + speex_free(st->update_prob); + speex_free(st->zeta); + + speex_free(st->noise_bands); + speex_free(st->noise_bands2); + speex_free(st->speech_bands); + speex_free(st->speech_bands2); + + speex_free(st->inbuf); + speex_free(st->outbuf); + + spx_drft_clear(st->fft_lookup); + speex_free(st->fft_lookup); + + speex_free(st); +} + +static void update_noise(SpeexPreprocessState *st, float *ps, float *echo) +{ + int i; + float beta; + st->nb_adapt++; + beta=1.0f/st->nb_adapt; + if (beta < .05f) + beta=.05f; + + if (!echo) + { + for (i=0;ips_size;i++) + st->noise[i] = (1.f-beta)*st->noise[i] + beta*ps[i]; + } else { + for (i=0;ips_size;i++) + st->noise[i] = (1.f-beta)*st->noise[i] + beta*max(1.f,ps[i]-echo[i]); +#if 0 + for (i=0;ips_size;i++) + st->noise[i] = 0; +#endif + } +} + +static int speex_compute_vad(SpeexPreprocessState *st, float *ps, float mean_prior, float mean_post) +{ + int i, is_speech=0; + int N = st->ps_size; + float scale=.5f/N; + + /* FIXME: Clean this up a bit */ + { + float bands[NB_BANDS]; + int j; + float p0, p1; + float tot_loudness=0; + float x = sqrt(mean_post); + + for (i=5;ips[i] * st->loudness_weight[i]; + } + + for (i=0;ispeech_prob + .01*(1-st->speech_prob); + p1 *= .01*st->speech_prob + .99*(1-st->speech_prob); + + st->speech_prob = p0/(p1+p0); + */ + + if (st->noise_bandsN < 50 || st->speech_bandsN < 50) + { + if (mean_post > 5.f) + { + float adapt = 1./st->speech_bandsN++; + if (adapt<.005f) + adapt = .005f; + for (i=0;ispeech_bands[i] = (1.f-adapt)*st->speech_bands[i] + adapt*bands[i]; + /*st->speech_bands2[i] = (1-adapt)*st->speech_bands2[i] + adapt*bands[i]*bands[i];*/ + st->speech_bands2[i] = (1.f-adapt)*st->speech_bands2[i] + adapt*(bands[i]-st->speech_bands[i])*(bands[i]-st->speech_bands[i]); + } + } else { + float adapt = 1./st->noise_bandsN++; + if (adapt<.005f) + adapt = .005f; + for (i=0;inoise_bands[i] = (1.f-adapt)*st->noise_bands[i] + adapt*bands[i]; + /*st->noise_bands2[i] = (1-adapt)*st->noise_bands2[i] + adapt*bands[i]*bands[i];*/ + st->noise_bands2[i] = (1.f-adapt)*st->noise_bands2[i] + adapt*(bands[i]-st->noise_bands[i])*(bands[i]-st->noise_bands[i]); + } + } + } + p0=p1=1; + for (i=0;inoise_bands2[i] - st->noise_bands[i]*st->noise_bands[i]; + speech_var = 1.01*st->speech_bands2[i] - st->speech_bands[i]*st->speech_bands[i];*/ + noise_var = st->noise_bands2[i]; + speech_var = st->speech_bands2[i]; + if (noise_var < .1f) + noise_var = .1f; + if (speech_var < .1f) + speech_var = .1f; + + /*speech_var = sqrt(speech_var*noise_var); + noise_var = speech_var;*/ + if (speech_var < .05f*speech_var) + noise_var = .05f*speech_var; + if (speech_var < .05f*noise_var) + speech_var = .05f*noise_var; + + if (bands[i] < st->noise_bands[i]) + speech_var = noise_var; + if (bands[i] > st->speech_bands[i]) + noise_var = speech_var; + + speech_mean = st->speech_bands[i]; + noise_mean = st->noise_bands[i]; + if (noise_mean < speech_mean - 5.f) + noise_mean = speech_mean - 5.f; + + tmp1 = exp(-.5f*(bands[i]-speech_mean)*(bands[i]-speech_mean)/speech_var)/sqrt(2.f*M_PI*speech_var); + tmp2 = exp(-.5f*(bands[i]-noise_mean)*(bands[i]-noise_mean)/noise_var)/sqrt(2.f*M_PI*noise_var); + /*fprintf (stderr, "%f ", (float)(p0/(.01+p0+p1)));*/ + /*fprintf (stderr, "%f ", (float)(bands[i]));*/ + pr = tmp1/(1e-25+tmp1+tmp2); + /*if (bands[i] < st->noise_bands[i]) + pr=.01; + if (bands[i] > st->speech_bands[i] && pr < .995) + pr=.995;*/ + if (pr>.999f) + pr=.999f; + if (pr<.001f) + pr=.001f; + /*fprintf (stderr, "%f ", pr);*/ + p0 *= pr; + p1 *= (1-pr); + } + + p0 = pow(p0,.2); + p1 = pow(p1,.2); + +#if 1 + p0 *= 2.f; + p0=p0/(p1+p0); + if (st->last_speech>20) + { + float tmp = sqrt(tot_loudness)/st->loudness2; + tmp = 1.f-exp(-10.f*tmp); + if (p0>tmp) + p0=tmp; + } + p1=1-p0; +#else + if (sqrt(tot_loudness) < .6f*st->loudness2 && p0>15.f*p1) + p0=15.f*p1; + if (sqrt(tot_loudness) < .45f*st->loudness2 && p0>7.f*p1) + p0=7.f*p1; + if (sqrt(tot_loudness) < .3f*st->loudness2 && p0>3.f*p1) + p0=3.f*p1; + if (sqrt(tot_loudness) < .15f*st->loudness2 && p0>p1) + p0=p1; + /*fprintf (stderr, "%f %f ", (float)(sqrt(tot_loudness) /( .25*st->loudness2)), p0/(p1+p0));*/ +#endif + + p0 *= .99f*st->speech_prob + .01f*(1-st->speech_prob); + p1 *= .01f*st->speech_prob + .99f*(1-st->speech_prob); + + st->speech_prob = p0/(1e-25f+p1+p0); + /*fprintf (stderr, "%f %f %f ", tot_loudness, st->loudness2, st->speech_prob);*/ + + if (st->speech_prob>.35 || (st->last_speech < 20 && st->speech_prob>.1)) + { + is_speech = 1; + st->last_speech = 0; + } else { + st->last_speech++; + if (st->last_speech<20) + is_speech = 1; + } + + if (st->noise_bandsN > 50 && st->speech_bandsN > 50) + { + if (mean_post > 5) + { + float adapt = 1./st->speech_bandsN++; + if (adapt<.005f) + adapt = .005f; + for (i=0;ispeech_bands[i] = (1-adapt)*st->speech_bands[i] + adapt*bands[i]; + /*st->speech_bands2[i] = (1-adapt)*st->speech_bands2[i] + adapt*bands[i]*bands[i];*/ + st->speech_bands2[i] = (1-adapt)*st->speech_bands2[i] + adapt*(bands[i]-st->speech_bands[i])*(bands[i]-st->speech_bands[i]); + } + } else { + float adapt = 1./st->noise_bandsN++; + if (adapt<.005f) + adapt = .005f; + for (i=0;inoise_bands[i] = (1-adapt)*st->noise_bands[i] + adapt*bands[i]; + /*st->noise_bands2[i] = (1-adapt)*st->noise_bands2[i] + adapt*bands[i]*bands[i];*/ + st->noise_bands2[i] = (1-adapt)*st->noise_bands2[i] + adapt*(bands[i]-st->noise_bands[i])*(bands[i]-st->noise_bands[i]); + } + } + } + + + } + + return is_speech; +} + +static void speex_compute_agc(SpeexPreprocessState *st, float mean_prior) +{ + int i; + int N = st->ps_size; + float scale=.5f/N; + float agc_gain; + int freq_start, freq_end; + float active_bands = 0; + + freq_start = (int)(300.0f*2*N/st->sampling_rate); + freq_end = (int)(2000.0f*2*N/st->sampling_rate); + for (i=freq_start;iS[i] > 20.f*st->Smin[i]+1000.f) + active_bands+=1; + } + active_bands /= (freq_end-freq_start+1); + + if (active_bands > .2f) + { + float loudness=0.f; + float rate, rate2=.2f; + st->nb_loudness_adapt++; + rate=2.0f/(1+st->nb_loudness_adapt); + if (rate < .05f) + rate = .05f; + if (rate < .1f && pow(loudness, LOUDNESS_EXP) > st->loudness) + rate = .1f; + if (rate < .2f && pow(loudness, LOUDNESS_EXP) > 3.f*st->loudness) + rate = .2f; + if (rate < .4f && pow(loudness, LOUDNESS_EXP) > 10.f*st->loudness) + rate = .4f; + + for (i=2;ips[i] * st->gain2[i] * st->gain2[i] * st->loudness_weight[i]; + } + loudness=sqrt(loudness); + /*if (loudness < 2*pow(st->loudness, 1.0/LOUDNESS_EXP) && + loudness*2 > pow(st->loudness, 1.0/LOUDNESS_EXP))*/ + st->loudness = (1-rate)*st->loudness + (rate)*pow(loudness, LOUDNESS_EXP); + + st->loudness2 = (1-rate2)*st->loudness2 + rate2*pow(st->loudness, 1.0f/LOUDNESS_EXP); + + loudness = pow(st->loudness, 1.0f/LOUDNESS_EXP); + + /*fprintf (stderr, "%f %f %f\n", loudness, st->loudness2, rate);*/ + } + + agc_gain = st->agc_level/st->loudness2; + /*fprintf (stderr, "%f %f %f %f\n", active_bands, st->loudness, st->loudness2, agc_gain);*/ + if (agc_gain>200) + agc_gain = 200; + + for (i=0;igain2[i] *= agc_gain; + +} + +static void preprocess_analysis(SpeexPreprocessState *st, spx_int16_t *x) +{ + int i; + int N = st->ps_size; + int N3 = 2*N - st->frame_size; + int N4 = st->frame_size - N3; + float *ps=st->ps; + + /* 'Build' input frame */ + for (i=0;iframe[i]=st->inbuf[i]; + for (i=0;iframe_size;i++) + st->frame[N3+i]=x[i]; + + /* Update inbuf */ + for (i=0;iinbuf[i]=x[N4+i]; + + /* Windowing */ + for (i=0;i<2*N;i++) + st->frame[i] *= st->window[i]; + + /* Perform FFT */ + spx_drft_forward(st->fft_lookup, st->frame); + + /* Power spectrum */ + ps[0]=1; + for (i=1;iframe[2*i-1]*st->frame[2*i-1] + st->frame[2*i]*st->frame[2*i]; + +} + +static void update_noise_prob(SpeexPreprocessState *st) +{ + int i; + int N = st->ps_size; + + for (i=1;iS[i] = 100.f+ .8f*st->S[i] + .05f*st->ps[i-1]+.1f*st->ps[i]+.05f*st->ps[i+1]; + + if (st->nb_preprocess<1) + { + for (i=1;iSmin[i] = st->Stmp[i] = st->S[i]+100.f; + } + + if (st->nb_preprocess%200==0) + { + for (i=1;iSmin[i] = min(st->Stmp[i], st->S[i]); + st->Stmp[i] = st->S[i]; + } + } else { + for (i=1;iSmin[i] = min(st->Smin[i], st->S[i]); + st->Stmp[i] = min(st->Stmp[i], st->S[i]); + } + } + for (i=1;iupdate_prob[i] *= .2f; + if (st->S[i] > 2.5*st->Smin[i]) + st->update_prob[i] += .8f; + /*fprintf (stderr, "%f ", st->S[i]/st->Smin[i]);*/ + /*fprintf (stderr, "%f ", st->update_prob[i]);*/ + } + +} + +#define NOISE_OVERCOMPENS 1.4 + +int speex_preprocess(SpeexPreprocessState *st, spx_int16_t *x, float *echo) +{ + int i; + int is_speech=1; + float mean_post=0; + float mean_prior=0; + int N = st->ps_size; + int N3 = 2*N - st->frame_size; + int N4 = st->frame_size - N3; + float scale=.5f/N; + float *ps=st->ps; + float Zframe=0, Pframe; + + preprocess_analysis(st, x); + + update_noise_prob(st); + + st->nb_preprocess++; + + /* Noise estimation always updated for the 20 first times */ + if (st->nb_adapt<10) + { + update_noise(st, ps, echo); + } + + /* Deal with residual echo if provided */ + if (echo) + for (i=1;iecho_noise[i] = (.3f*st->echo_noise[i] + echo[i]); + + /* Compute a posteriori SNR */ + for (i=1;ipost[i] = ps[i]/(1.f+NOISE_OVERCOMPENS*st->noise[i]+st->echo_noise[i]+st->reverb_estimate[i]) - 1.f; + if (st->post[i]>100.f) + st->post[i]=100.f; + /*if (st->post[i]<0) + st->post[i]=0;*/ + mean_post+=st->post[i]; + } + mean_post /= N; + if (mean_post<0.f) + mean_post=0.f; + + /* Special case for first frame */ + if (st->nb_adapt==1) + for (i=1;iold_ps[i] = ps[i]; + + /* Compute a priori SNR */ + { + /* A priori update rate */ + float gamma; + float min_gamma=0.12f; + gamma = 1.0f/st->nb_preprocess; + + /*Make update rate smaller when there's no speech*/ +#if 0 + if (mean_post<3.5 && mean_prior < 1) + min_gamma *= (mean_post+.5); + else + min_gamma *= 4.; +#else + min_gamma = .1f*fabs(mean_prior - mean_post)*fabs(mean_prior - mean_post); + if (min_gamma>.15f) + min_gamma = .15f; + if (min_gamma<.02f) + min_gamma = .02f; +#endif + /*min_gamma = .08;*/ + + /*if (gammaprior[i] = gamma*max(0.0f,st->post[i]) + + (1.f-gamma)*st->gain[i]*st->gain[i]*st->old_ps[i]/(1.f+NOISE_OVERCOMPENS*st->noise[i]+st->echo_noise[i]+st->reverb_estimate[i]); + + if (st->prior[i]>100.f) + st->prior[i]=100.f; + + mean_prior+=st->prior[i]; + } + } + mean_prior /= N; + +#if 0 + for (i=0;iprior[i]); + } + fprintf (stderr, "\n"); +#endif + /*fprintf (stderr, "%f %f\n", mean_prior,mean_post);*/ + + if (st->nb_preprocess>=20) + { + int do_update = 0; + float noise_ener=0, sig_ener=0; + /* If SNR is low (both a priori and a posteriori), update the noise estimate*/ + /*if (mean_prior<.23 && mean_post < .5)*/ + if (mean_prior<.23f && mean_post < .5f) + do_update = 1; + for (i=1;inoise[i]; + sig_ener += ps[i]; + } + if (noise_ener > 3.f*sig_ener) + do_update = 1; + /*do_update = 0;*/ + if (do_update) + { + st->consec_noise++; + } else { + st->consec_noise=0; + } + } + + if (st->vad_enabled) + is_speech = speex_compute_vad(st, ps, mean_prior, mean_post); + + + if (st->consec_noise>=3) + { + update_noise(st, st->old_ps, echo); + } else { + for (i=1;iupdate_prob[i]<.5f || st->ps[i] < st->noise[i]) + { + if (echo) + st->noise[i] = .90f*st->noise[i] + .1f*max(1.0f,st->ps[i]-echo[i]); + else + st->noise[i] = .90f*st->noise[i] + .1f*st->ps[i]; + } + } + } + + for (i=1;izeta[i] = .7f*st->zeta[i] + .3f*st->prior[i]; + } + + { + int freq_start = (int)(300.0f*2.f*N/st->sampling_rate); + int freq_end = (int)(2000.0f*2.f*N/st->sampling_rate); + for (i=freq_start;izeta[i]; + } + } + + Zframe /= N; + if (Zframe 1.5f*st->Zlast) + { + Pframe = 1.f; + st->Zpeak = Zframe; + if (st->Zpeak > 10.f) + st->Zpeak = 10.f; + if (st->Zpeak < 1.f) + st->Zpeak = 1.f; + } else { + if (Zframe < st->Zpeak*ZMIN) + { + Pframe = 0; + } else if (Zframe > st->Zpeak*ZMAX) + { + Pframe = 1; + } else { + Pframe = log(Zframe/(st->Zpeak*ZMIN)) / log(ZMAX/ZMIN); + } + } + } + st->Zlast = Zframe; + + /*fprintf (stderr, "%f\n", Pframe);*/ + /* Compute gain according to the Ephraim-Malah algorithm */ + for (i=1;iprior[i]/(1.0001f+st->prior[i]); + theta = (1.f+st->post[i])*prior_ratio; + + if (i==1 || i==N-1) + zeta1 = st->zeta[i]; + else + zeta1 = .25f*st->zeta[i-1] + .5f*st->zeta[i] + .25f*st->zeta[i+1]; + if (zeta1ZMAX) + P1 = 1.f; + else + P1 = LOG_MIN_MAX_1 * log(ZMIN_1*zeta1); + + /*P1 = log(zeta1/ZMIN)/log(ZMAX/ZMIN);*/ + + /* FIXME: add global prob (P2) */ + q = 1-Pframe*P1; + q = 1-P1; + if (q>.95f) + q=.95f; + p=1.f/(1.f + (q/(1.f-q))*(1.f+st->prior[i])*exp(-theta)); + /*p=1;*/ + +#if 0 + /* log-spectral magnitude estimator */ + if (theta<6) + MM = 0.74082*pow(theta+1,.61)/sqrt(.0001+theta); + else + MM=1; +#else + /* Optimal estimator for loudness domain */ + MM = hypergeom_gain(theta); +#endif + + st->gain[i] = prior_ratio * MM; + /*Put some (very arbitraty) limit on the gain*/ + if (st->gain[i]>2.f) + { + st->gain[i]=2.f; + } + + st->reverb_estimate[i] = st->reverb_decay*st->reverb_estimate[i] + st->reverb_decay*st->reverb_level*st->gain[i]*st->gain[i]*st->ps[i]; + if (st->denoise_enabled) + { + st->gain2[i]=p*p*st->gain[i]; + } else { + st->gain2[i]=1.f; + } + } + st->gain2[0]=st->gain[0]=0.f; + st->gain2[N-1]=st->gain[N-1]=0.f; + + if (st->agc_enabled) + speex_compute_agc(st, mean_prior); + +#if 0 + if (!is_speech) + { + for (i=0;igain2[i] = 0; + } +#if 0 + else { + for (i=0;igain2[i] = 1; + } +#endif +#endif + + /* Apply computed gain */ + for (i=1;iframe[2*i-1] *= st->gain2[i]; + st->frame[2*i] *= st->gain2[i]; + } + + /* Get rid of the DC and very low frequencies */ + st->frame[0]=0; + st->frame[1]=0; + st->frame[2]=0; + /* Nyquist frequency is mostly useless too */ + st->frame[2*N-1]=0; + + /* Inverse FFT with 1/N scaling */ + spx_drft_backward(st->fft_lookup, st->frame); + + for (i=0;i<2*N;i++) + st->frame[i] *= scale; + + { + float max_sample=0; + for (i=0;i<2*N;i++) + if (fabs(st->frame[i])>max_sample) + max_sample = fabs(st->frame[i]); + if (max_sample>28000.f) + { + float damp = 28000.f/max_sample; + for (i=0;i<2*N;i++) + st->frame[i] *= damp; + } + } + + for (i=0;i<2*N;i++) + st->frame[i] *= st->window[i]; + + /* Perform overlap and add */ + for (i=0;ioutbuf[i] + st->frame[i]; + for (i=0;iframe[N3+i]; + + /* Update outbuf */ + for (i=0;ioutbuf[i] = st->frame[st->frame_size+i]; + + /* Save old power spectrum */ + for (i=1;iold_ps[i] = ps[i]; + + return is_speech; +} + +void speex_preprocess_estimate_update(SpeexPreprocessState *st, spx_int16_t *x, float *echo) +{ + int i; + int N = st->ps_size; + int N3 = 2*N - st->frame_size; + + float *ps=st->ps; + + preprocess_analysis(st, x); + + update_noise_prob(st); + + st->nb_preprocess++; + + for (i=1;iupdate_prob[i]<.5f || st->ps[i] < st->noise[i]) + { + if (echo) + st->noise[i] = .90f*st->noise[i] + .1f*max(1.0f,st->ps[i]-echo[i]); + else + st->noise[i] = .90f*st->noise[i] + .1f*st->ps[i]; + } + } + + for (i=0;ioutbuf[i] = x[st->frame_size-N3+i]*st->window[st->frame_size+i]; + + /* Save old power spectrum */ + for (i=1;iold_ps[i] = ps[i]; + + for (i=1;ireverb_estimate[i] *= st->reverb_decay; +} + + +int speex_preprocess_ctl(SpeexPreprocessState *state, int request, void *ptr) +{ + int i; + SpeexPreprocessState *st; + st=(SpeexPreprocessState*)state; + switch(request) + { + case SPEEX_PREPROCESS_SET_DENOISE: + st->denoise_enabled = (*(int*)ptr); + break; + case SPEEX_PREPROCESS_GET_DENOISE: + (*(int*)ptr) = st->denoise_enabled; + break; + + case SPEEX_PREPROCESS_SET_AGC: + st->agc_enabled = (*(int*)ptr); + break; + case SPEEX_PREPROCESS_GET_AGC: + (*(int*)ptr) = st->agc_enabled; + break; + + case SPEEX_PREPROCESS_SET_AGC_LEVEL: + st->agc_level = (*(float*)ptr); + if (st->agc_level<1) + st->agc_level=1; + if (st->agc_level>32768) + st->agc_level=32768; + break; + case SPEEX_PREPROCESS_GET_AGC_LEVEL: + (*(float*)ptr) = st->agc_level; + break; + + case SPEEX_PREPROCESS_SET_VAD: + st->vad_enabled = (*(int*)ptr); + break; + case SPEEX_PREPROCESS_GET_VAD: + (*(int*)ptr) = st->vad_enabled; + break; + + case SPEEX_PREPROCESS_SET_DEREVERB: + st->dereverb_enabled = (*(int*)ptr); + for (i=0;ips_size;i++) + st->reverb_estimate[i]=0; + break; + case SPEEX_PREPROCESS_GET_DEREVERB: + (*(int*)ptr) = st->dereverb_enabled; + break; + + case SPEEX_PREPROCESS_SET_DEREVERB_LEVEL: + st->reverb_level = (*(float*)ptr); + break; + case SPEEX_PREPROCESS_GET_DEREVERB_LEVEL: + (*(float*)ptr) = st->reverb_level; + break; + + case SPEEX_PREPROCESS_SET_DEREVERB_DECAY: + st->reverb_decay = (*(float*)ptr); + break; + case SPEEX_PREPROCESS_GET_DEREVERB_DECAY: + (*(float*)ptr) = st->reverb_decay; + break; + + default: + speex_warning_int("Unknown speex_preprocess_ctl request: ", request); + return -1; + } + return 0; +} diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/quant_lsp.c b/mozilla/zap/zmk/speex-1.1.10/libspeex/quant_lsp.c new file mode 100755 index 00000000000..9849f777f0c --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/quant_lsp.c @@ -0,0 +1,441 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: quant_lsp.c + LSP vector quantization + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 "quant_lsp.h" +#include +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif + + +#include "misc.h" + +#ifdef FIXED_POINT + +#define LSP_LINEAR(i) (SHL16(i+1,11)) +#define LSP_LINEAR_HIGH(i) (ADD16(MULT16_16_16(i,2560),6144)) +#define LSP_DIV_256(x) (SHL16((spx_word16_t)x, 5)) +#define LSP_DIV_512(x) (SHL16((spx_word16_t)x, 4)) +#define LSP_DIV_1024(x) (SHL16((spx_word16_t)x, 3)) +#define LSP_PI 25736 + +#else + +#define LSP_LINEAR(i) (.25*(i)+.25) +#define LSP_LINEAR_HIGH(i) (.3125*(i)+.75) +#define LSP_SCALE 256. +#define LSP_DIV_256(x) (0.0039062*(x)) +#define LSP_DIV_512(x) (0.0019531*(x)) +#define LSP_DIV_1024(x) (0.00097656*(x)) +#define LSP_PI M_PI + +#endif + +static void compute_quant_weights(spx_lsp_t *qlsp, spx_word16_t *quant_weight, int order) +{ + int i; + spx_word16_t tmp1, tmp2; + for (i=0;i tmp2 ? tmp1 : tmp2; + }*/ + + for (i=0;i +#include "misc.h" + +#define MAX_LSP_SIZE 20 + +#define NB_CDBK_SIZE 64 +#define NB_CDBK_SIZE_LOW1 64 +#define NB_CDBK_SIZE_LOW2 64 +#define NB_CDBK_SIZE_HIGH1 64 +#define NB_CDBK_SIZE_HIGH2 64 + +/*Narrowband codebooks*/ +extern const signed char cdbk_nb[]; +extern const signed char cdbk_nb_low1[]; +extern const signed char cdbk_nb_low2[]; +extern const signed char cdbk_nb_high1[]; +extern const signed char cdbk_nb_high2[]; + +/* Quantizes narrowband LSPs with 30 bits */ +void lsp_quant_nb(spx_lsp_t *lsp, spx_lsp_t *qlsp, int order, SpeexBits *bits); + +/* Decodes quantized narrowband LSPs */ +void lsp_unquant_nb(spx_lsp_t *lsp, int order, SpeexBits *bits); + +/* Quantizes low bit-rate narrowband LSPs with 18 bits */ +void lsp_quant_lbr(spx_lsp_t *lsp, spx_lsp_t *qlsp, int order, SpeexBits *bits); + +/* Decodes quantized low bit-rate narrowband LSPs */ +void lsp_unquant_lbr(spx_lsp_t *lsp, int order, SpeexBits *bits); + +/* Quantizes high-band LSPs with 12 bits */ +void lsp_quant_high(spx_lsp_t *lsp, spx_lsp_t *qlsp, int order, SpeexBits *bits); + +/* Decodes high-band LSPs */ +void lsp_unquant_high(spx_lsp_t *lsp, int order, SpeexBits *bits); + +#ifdef EPIC_48K +/* Quantizes narrowband LSPs with 14 bits */ +void lsp_quant_48k(spx_lsp_t *lsp, spx_lsp_t *qlsp, int order, SpeexBits *bits); + +/* Decodes quantized narrowband LSPs (14 bits) */ +void lsp_unquant_48k(spx_lsp_t *lsp, int order, SpeexBits *bits); +#endif + + +#endif diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/sb_celp.c b/mozilla/zap/zmk/speex-1.1.10/libspeex/sb_celp.c new file mode 100755 index 00000000000..7a70cda9cc4 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/sb_celp.c @@ -0,0 +1,1592 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: sb_celp.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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 +#include "sb_celp.h" +#include "stdlib.h" +#include "filters.h" +#include "lpc.h" +#include "lsp.h" +#include "stack_alloc.h" +#include "cb_search.h" +#include "quant_lsp.h" +#include "vq.h" +#include "ltp.h" +#include "misc.h" + +/* Default size for the encoder and decoder stack (can be changed at compile time). + This does not apply when using variable-size arrays or alloca. */ +#ifndef SB_ENC_STACK +#define SB_ENC_STACK (10000*sizeof(spx_sig_t)) +#endif + +#ifndef SB_DEC_STACK +#define SB_DEC_STACK (6000*sizeof(spx_sig_t)) +#endif + + +#ifdef DISABLE_WIDEBAND +void *sb_encoder_init(const SpeexMode *m) +{ + speex_error("Wideband and Ultra-wideband are disabled"); + return NULL; +} +void sb_encoder_destroy(void *state) +{ + speex_error("Wideband and Ultra-wideband are disabled"); +} +int sb_encode(void *state, void *vin, SpeexBits *bits) +{ + speex_error("Wideband and Ultra-wideband are disabled"); + return -2; +} +void *sb_decoder_init(const SpeexMode *m) +{ + speex_error("Wideband and Ultra-wideband are disabled"); + return NULL; +} +void sb_decoder_destroy(void *state) +{ + speex_error("Wideband and Ultra-wideband are disabled"); +} +int sb_decode(void *state, SpeexBits *bits, void *vout) +{ + speex_error("Wideband and Ultra-wideband are disabled"); + return -2; +} +int sb_encoder_ctl(void *state, int request, void *ptr) +{ + speex_error("Wideband and Ultra-wideband are disabled"); + return -2; +} +int sb_decoder_ctl(void *state, int request, void *ptr) +{ + speex_error("Wideband and Ultra-wideband are disabled"); + return -2; +} +#else + + +#ifndef M_PI +#define M_PI 3.14159265358979323846 /* pi */ +#endif + +#define sqr(x) ((x)*(x)) + +#define SUBMODE(x) st->submodes[st->submodeID]->x + +#ifdef FIXED_POINT +static const spx_word16_t gc_quant_bound[16] = {125, 164, 215, 282, 370, 484, 635, 832, 1090, 1428, 1871, 2452, 3213, 4210, 5516, 7228}; +#define LSP_MARGIN 410 +#define LSP_DELTA1 6553 +#define LSP_DELTA2 1638 + +#else + +#define LSP_MARGIN .05 +#define LSP_DELTA1 .2 +#define LSP_DELTA2 .05 + +#endif + +#define QMF_ORDER 64 + +#ifdef FIXED_POINT +static const spx_word16_t h0[64] = {2, -7, -7, 18, 15, -39, -25, 75, 35, -130, -41, 212, 38, -327, -17, 483, -32, -689, 124, 956, -283, -1307, 543, 1780, -973, -2467, 1733, 3633, -3339, -6409, 9059, 30153, 30153, 9059, -6409, -3339, 3633, 1733, -2467, -973, 1780, 543, -1307, -283, 956, 124, -689, -32, 483, -17, -327, 38, 212, -41, -130, 35, 75, -25, -39, 15, 18, -7, -7, 2}; + +static const spx_word16_t h1[64] = {2, 7, -7, -18, 15, 39, -25, -75, 35, 130, -41, -212, 38, 327, -17, -483, -32, 689, 124, -956, -283, 1307, 543, -1780, -973, 2467, 1733, -3633, -3339, 6409, 9059, -30153, 30153, -9059, -6409, 3339, 3633, -1733, -2467, 973, 1780, -543, -1307, 283, 956, -124, -689, 32, 483, 17, -327, -38, 212, 41, -130, -35, 75, 25, -39, -15, 18, 7, -7, -2}; + + +#else +static const float h0[64] = { + 3.596189e-05, -0.0001123515, + -0.0001104587, 0.0002790277, + 0.0002298438, -0.0005953563, + -0.0003823631, 0.00113826, + 0.0005308539, -0.001986177, + -0.0006243724, 0.003235877, + 0.0005743159, -0.004989147, + -0.0002584767, 0.007367171, + -0.0004857935, -0.01050689, + 0.001894714, 0.01459396, + -0.004313674, -0.01994365, + 0.00828756, 0.02716055, + -0.01485397, -0.03764973, + 0.026447, 0.05543245, + -0.05095487, -0.09779096, + 0.1382363, 0.4600981, + 0.4600981, 0.1382363, + -0.09779096, -0.05095487, + 0.05543245, 0.026447, + -0.03764973, -0.01485397, + 0.02716055, 0.00828756, + -0.01994365, -0.004313674, + 0.01459396, 0.001894714, + -0.01050689, -0.0004857935, + 0.007367171, -0.0002584767, + -0.004989147, 0.0005743159, + 0.003235877, -0.0006243724, + -0.001986177, 0.0005308539, + 0.00113826, -0.0003823631, + -0.0005953563, 0.0002298438, + 0.0002790277, -0.0001104587, + -0.0001123515, 3.596189e-05 +}; + +static const float h1[64] = { + 3.596189e-05, 0.0001123515, + -0.0001104587, -0.0002790277, + 0.0002298438, 0.0005953563, + -0.0003823631, -0.00113826, + 0.0005308539, 0.001986177, + -0.0006243724, -0.003235877, + 0.0005743159, 0.004989147, + -0.0002584767, -0.007367171, + -0.0004857935, 0.01050689, + 0.001894714, -0.01459396, + -0.004313674, 0.01994365, + 0.00828756, -0.02716055, + -0.01485397, 0.03764973, + 0.026447, -0.05543245, + -0.05095487, 0.09779096, + 0.1382363, -0.4600981, + 0.4600981, -0.1382363, + -0.09779096, 0.05095487, + 0.05543245, -0.026447, + -0.03764973, 0.01485397, + 0.02716055, -0.00828756, + -0.01994365, 0.004313674, + 0.01459396, -0.001894714, + -0.01050689, 0.0004857935, + 0.007367171, 0.0002584767, + -0.004989147, -0.0005743159, + 0.003235877, 0.0006243724, + -0.001986177, -0.0005308539, + 0.00113826, 0.0003823631, + -0.0005953563, -0.0002298438, + 0.0002790277, 0.0001104587, + -0.0001123515, -3.596189e-05 +}; +#endif + +static void mix_and_saturate(spx_word32_t *x0, spx_word32_t *x1, spx_word16_t *out, int len) +{ + int i; + for (i=0;i32767) + out[i] = 32767; + else if (tmp<-32767) + out[i] = -32767; + else + out[i] = tmp; + } +} + +void *sb_encoder_init(const SpeexMode *m) +{ + int i; + SBEncState *st; + const SpeexSBMode *mode; + + st = (SBEncState*)speex_alloc(sizeof(SBEncState)); + if (!st) + return NULL; +#if defined(VAR_ARRAYS) || defined (USE_ALLOCA) + st->stack = NULL; +#else + st->stack = (char*)speex_alloc_scratch(SB_ENC_STACK); +#endif + st->mode = m; + mode = (const SpeexSBMode*)m->mode; + + + st->st_low = speex_encoder_init(mode->nb_mode); + st->full_frame_size = 2*mode->frameSize; + st->frame_size = mode->frameSize; + st->subframeSize = mode->subframeSize; + st->nbSubframes = mode->frameSize/mode->subframeSize; + st->windowSize = st->frame_size*3/2; + st->lpcSize=mode->lpcSize; + st->bufSize=mode->bufSize; + + st->encode_submode = 1; + st->submodes=mode->submodes; + st->submodeSelect = st->submodeID=mode->defaultSubmode; + + i=9; + speex_encoder_ctl(st->st_low, SPEEX_SET_QUALITY, &i); + + st->lag_factor = mode->lag_factor; + st->lpc_floor = mode->lpc_floor; + st->gamma1=mode->gamma1; + st->gamma2=mode->gamma2; + st->first=1; + + st->x0d=speex_alloc((st->frame_size)*sizeof(spx_sig_t)); + st->x1d=speex_alloc((st->frame_size)*sizeof(spx_sig_t)); + st->high=speex_alloc((st->full_frame_size)*sizeof(spx_sig_t)); + st->y0=speex_alloc((st->full_frame_size)*sizeof(spx_sig_t)); + st->y1=speex_alloc((st->full_frame_size)*sizeof(spx_sig_t)); + + st->h0_mem=speex_alloc((QMF_ORDER)*sizeof(spx_word16_t)); + st->h1_mem=speex_alloc((QMF_ORDER)*sizeof(spx_word16_t)); + st->g0_mem=speex_alloc((QMF_ORDER)*sizeof(spx_word32_t)); + st->g1_mem=speex_alloc((QMF_ORDER)*sizeof(spx_word32_t)); + + st->buf=speex_alloc((st->windowSize)*sizeof(spx_sig_t)); + st->excBuf=speex_alloc((st->bufSize)*sizeof(spx_sig_t)); + st->exc = st->excBuf + st->bufSize - st->windowSize; + + st->res=speex_alloc((st->frame_size)*sizeof(spx_sig_t)); + st->sw=speex_alloc((st->frame_size)*sizeof(spx_sig_t)); + st->target=speex_alloc((st->frame_size)*sizeof(spx_sig_t)); + /*Asymmetric "pseudo-Hamming" window*/ + { + int part1, part2; + part1 = st->subframeSize*7/2; + part2 = st->subframeSize*5/2; + st->window = speex_alloc((st->windowSize)*sizeof(spx_word16_t)); + for (i=0;iwindow[i]=(spx_word16_t)(SIG_SCALING*(.54-.46*cos(M_PI*i/part1))); + for (i=0;iwindow[part1+i]=(spx_word16_t)(SIG_SCALING*(.54+.46*cos(M_PI*i/part2))); + } + + st->lagWindow = speex_alloc((st->lpcSize+1)*sizeof(spx_word16_t)); + for (i=0;ilpcSize+1;i++) + st->lagWindow[i]=16384*exp(-.5*sqr(2*M_PI*st->lag_factor*i)); + + st->autocorr = speex_alloc((st->lpcSize+1)*sizeof(spx_word16_t)); + st->lpc = speex_alloc(st->lpcSize*sizeof(spx_coef_t)); + st->bw_lpc1 = speex_alloc(st->lpcSize*sizeof(spx_coef_t)); + st->bw_lpc2 = speex_alloc(st->lpcSize*sizeof(spx_coef_t)); + st->lsp = speex_alloc(st->lpcSize*sizeof(spx_lsp_t)); + st->qlsp = speex_alloc(st->lpcSize*sizeof(spx_lsp_t)); + st->old_lsp = speex_alloc(st->lpcSize*sizeof(spx_lsp_t)); + st->old_qlsp = speex_alloc(st->lpcSize*sizeof(spx_lsp_t)); + st->interp_lsp = speex_alloc(st->lpcSize*sizeof(spx_lsp_t)); + st->interp_qlsp = speex_alloc(st->lpcSize*sizeof(spx_lsp_t)); + st->interp_lpc = speex_alloc(st->lpcSize*sizeof(spx_coef_t)); + st->interp_qlpc = speex_alloc(st->lpcSize*sizeof(spx_coef_t)); + st->pi_gain = speex_alloc((st->nbSubframes)*sizeof(spx_word32_t)); + + st->mem_sp = speex_alloc((st->lpcSize)*sizeof(spx_mem_t)); + st->mem_sp2 = speex_alloc((st->lpcSize)*sizeof(spx_mem_t)); + st->mem_sw = speex_alloc((st->lpcSize)*sizeof(spx_mem_t)); + + st->vbr_quality = 8; + st->vbr_enabled = 0; + st->vad_enabled = 0; + st->abr_enabled = 0; + st->relative_quality=0; + + st->complexity=2; + speex_encoder_ctl(st->st_low, SPEEX_GET_SAMPLING_RATE, &st->sampling_rate); + st->sampling_rate*=2; + +#ifdef ENABLE_VALGRIND + VALGRIND_MAKE_READABLE(st, (st->stack-(char*)st)); +#endif + return st; +} + +void sb_encoder_destroy(void *state) +{ + SBEncState *st=(SBEncState*)state; + + speex_encoder_destroy(st->st_low); +#if !(defined(VAR_ARRAYS) || defined (USE_ALLOCA)) + speex_free_scratch(st->stack); +#endif + + speex_free(st->x0d); + speex_free(st->x1d); + speex_free(st->high); + speex_free(st->y0); + speex_free(st->y1); + + speex_free(st->h0_mem); + speex_free(st->h1_mem); + speex_free(st->g0_mem); + speex_free(st->g1_mem); + + speex_free(st->buf); + speex_free(st->excBuf); + speex_free(st->res); + speex_free(st->sw); + speex_free(st->target); + speex_free(st->window); + speex_free(st->lagWindow); + + speex_free(st->autocorr); + speex_free(st->lpc); + speex_free(st->bw_lpc1); + speex_free(st->bw_lpc2); + speex_free(st->lsp); + speex_free(st->qlsp); + speex_free(st->old_lsp); + speex_free(st->old_qlsp); + speex_free(st->interp_lsp); + speex_free(st->interp_qlsp); + speex_free(st->interp_lpc); + speex_free(st->interp_qlpc); + speex_free(st->pi_gain); + + speex_free(st->mem_sp); + speex_free(st->mem_sp2); + speex_free(st->mem_sw); + + + speex_free(st); +} + + +int sb_encode(void *state, void *vin, SpeexBits *bits) +{ + SBEncState *st; + int i, roots, sub; + char *stack; + VARDECL(spx_mem_t *mem); + VARDECL(spx_sig_t *innov); + VARDECL(spx_word16_t *syn_resp); + VARDECL(spx_word32_t *low_pi_gain); + VARDECL(spx_sig_t *low_exc); + VARDECL(spx_sig_t *low_innov); + const SpeexSBMode *mode; + int dtx; + spx_word16_t *in = vin; + + st = (SBEncState*)state; + stack=st->stack; + mode = (const SpeexSBMode*)(st->mode->mode); + + { + VARDECL(spx_word16_t *low); + ALLOC(low, st->frame_size, spx_word16_t); + + /* Compute the two sub-bands by filtering with h0 and h1*/ + qmf_decomp(in, h0, st->x0d, st->x1d, st->full_frame_size, QMF_ORDER, st->h0_mem, stack); + + for (i=0;iframe_size;i++) + low[i] = SATURATE(PSHR(st->x0d[i],SIG_SHIFT),32767); + + /* Encode the narrowband part*/ + speex_encode_native(st->st_low, low, bits); + + for (i=0;iframe_size;i++) + st->x0d[i] = SHL(low[i],SIG_SHIFT); + } + /* High-band buffering / sync with low band */ + for (i=0;iwindowSize-st->frame_size;i++) + st->high[i] = st->high[st->frame_size+i]; + for (i=0;iframe_size;i++) + st->high[st->windowSize-st->frame_size+i]=SATURATE(st->x1d[i],536854528); + + speex_move(st->excBuf, st->excBuf+st->frame_size, (st->bufSize-st->frame_size)*sizeof(spx_sig_t)); + + + ALLOC(low_pi_gain, st->nbSubframes, spx_word32_t); + ALLOC(low_exc, st->frame_size, spx_sig_t); + ALLOC(low_innov, st->frame_size, spx_sig_t); + speex_encoder_ctl(st->st_low, SPEEX_GET_PI_GAIN, low_pi_gain); + speex_encoder_ctl(st->st_low, SPEEX_GET_EXC, low_exc); + speex_encoder_ctl(st->st_low, SPEEX_GET_INNOV, low_innov); + + speex_encoder_ctl(st->st_low, SPEEX_GET_LOW_MODE, &dtx); + + if (dtx==0) + dtx=1; + else + dtx=0; + + { + VARDECL(spx_word16_t *w_sig); + ALLOC(w_sig, st->windowSize, spx_word16_t); + /* Window for analysis */ + for (i=0;iwindowSize;i++) + w_sig[i] = SHR(MULT16_16(SHR((spx_word32_t)(st->high[i]),SIG_SHIFT),st->window[i]),SIG_SHIFT); + + /* Compute auto-correlation */ + _spx_autocorr(w_sig, st->autocorr, st->lpcSize+1, st->windowSize); + } + + st->autocorr[0] = (spx_word16_t)(st->autocorr[0]*st->lpc_floor); /* Noise floor in auto-correlation domain */ + + /* Lag windowing: equivalent to filtering in the power-spectrum domain */ + for (i=0;ilpcSize+1;i++) + st->autocorr[i] = MULT16_16_Q14(st->autocorr[i],st->lagWindow[i]); + + /* Levinson-Durbin */ + _spx_lpc(st->lpc, st->autocorr, st->lpcSize); + + /* LPC to LSPs (x-domain) transform */ + roots=lpc_to_lsp (st->lpc, st->lpcSize, st->lsp, 15, LSP_DELTA1, stack); + if (roots!=st->lpcSize) + { + roots = lpc_to_lsp (st->lpc, st->lpcSize, st->lsp, 11, LSP_DELTA2, stack); + if (roots!=st->lpcSize) { + /*If we can't find all LSP's, do some damage control and use a flat filter*/ + for (i=0;ilpcSize;i++) + { + st->lsp[i]=M_PI*((float)(i+1))/(st->lpcSize+1); + } + } + } + + /* VBR code */ + if ((st->vbr_enabled || st->vad_enabled) && !dtx) + { + float e_low=0, e_high=0; + float ratio; + if (st->abr_enabled) + { + float qual_change=0; + if (st->abr_drift2 * st->abr_drift > 0) + { + /* Only adapt if long-term and short-term drift are the same sign */ + qual_change = -.00001*st->abr_drift/(1+st->abr_count); + if (qual_change>.1) + qual_change=.1; + if (qual_change<-.1) + qual_change=-.1; + } + st->vbr_quality += qual_change; + if (st->vbr_quality>10) + st->vbr_quality=10; + if (st->vbr_quality<0) + st->vbr_quality=0; + } + + + /*FIXME: Are the two signals (low, high) in sync? */ + e_low = compute_rms(st->x0d, st->frame_size); + e_high = compute_rms(st->high, st->frame_size); + ratio = 2*log((1+e_high)/(1+e_low)); + + speex_encoder_ctl(st->st_low, SPEEX_GET_RELATIVE_QUALITY, &st->relative_quality); + if (ratio<-4) + ratio=-4; + if (ratio>2) + ratio=2; + /*if (ratio>-2)*/ + if (st->vbr_enabled) + { + int modeid; + modeid = mode->nb_modes-1; + st->relative_quality+=1.0*(ratio+2); + if (st->relative_quality<-1) + st->relative_quality=-1; + while (modeid) + { + int v1; + float thresh; + v1=(int)floor(st->vbr_quality); + if (v1==10) + thresh = mode->vbr_thresh[modeid][v1]; + else + thresh = (st->vbr_quality-v1) * mode->vbr_thresh[modeid][v1+1] + + (1+v1-st->vbr_quality) * mode->vbr_thresh[modeid][v1]; + if (st->relative_quality >= thresh) + break; + modeid--; + } + speex_encoder_ctl(state, SPEEX_SET_HIGH_MODE, &modeid); + if (st->abr_enabled) + { + int bitrate; + speex_encoder_ctl(state, SPEEX_GET_BITRATE, &bitrate); + st->abr_drift+=(bitrate-st->abr_enabled); + st->abr_drift2 = .95*st->abr_drift2 + .05*(bitrate-st->abr_enabled); + st->abr_count += 1.0; + } + + } else { + /* VAD only */ + int modeid; + if (st->relative_quality<2.0) + modeid=1; + else + modeid=st->submodeSelect; + /*speex_encoder_ctl(state, SPEEX_SET_MODE, &mode);*/ + st->submodeID=modeid; + + } + /*fprintf (stderr, "%f %f\n", ratio, low_qual);*/ + } + + if (st->encode_submode) + { + speex_bits_pack(bits, 1, 1); + if (dtx) + speex_bits_pack(bits, 0, SB_SUBMODE_BITS); + else + speex_bits_pack(bits, st->submodeID, SB_SUBMODE_BITS); + } + + /* If null mode (no transmission), just set a couple things to zero*/ + if (dtx || st->submodes[st->submodeID] == NULL) + { + for (i=0;iframe_size;i++) + st->exc[i]=st->sw[i]=VERY_SMALL; + + for (i=0;ilpcSize;i++) + st->mem_sw[i]=0; + st->first=1; + + /* Final signal synthesis from excitation */ + iir_mem2(st->exc, st->interp_qlpc, st->high, st->frame_size, st->lpcSize, st->mem_sp); + +#ifdef RESYNTH + /* Reconstruct the original */ + fir_mem_up(st->x0d, h0, st->y0, st->full_frame_size, QMF_ORDER, st->g0_mem, stack); + fir_mem_up(st->high, h1, st->y1, st->full_frame_size, QMF_ORDER, st->g1_mem, stack); + + for (i=0;ifull_frame_size;i++) + in[i]=SHR(st->y0[i]-st->y1[i], SIG_SHIFT-1); +#endif + + if (dtx) + return 0; + else + return 1; + } + + + /* LSP quantization */ + SUBMODE(lsp_quant)(st->lsp, st->qlsp, st->lpcSize, bits); + + if (st->first) + { + for (i=0;ilpcSize;i++) + st->old_lsp[i] = st->lsp[i]; + for (i=0;ilpcSize;i++) + st->old_qlsp[i] = st->qlsp[i]; + } + + ALLOC(mem, st->lpcSize, spx_mem_t); + ALLOC(syn_resp, st->subframeSize, spx_word16_t); + ALLOC(innov, st->subframeSize, spx_sig_t); + + for (sub=0;subnbSubframes;sub++) + { + spx_sig_t *exc, *sp, *res, *target, *sw; + spx_word16_t filter_ratio; + int offset; + spx_word32_t rl, rh; + spx_word16_t eh=0; + + offset = st->subframeSize*sub; + sp=st->high+offset; + exc=st->exc+offset; + res=st->res+offset; + target=st->target+offset; + sw=st->sw+offset; + + /* LSP interpolation (quantized and unquantized) */ + lsp_interpolate(st->old_lsp, st->lsp, st->interp_lsp, st->lpcSize, sub, st->nbSubframes); + lsp_interpolate(st->old_qlsp, st->qlsp, st->interp_qlsp, st->lpcSize, sub, st->nbSubframes); + + lsp_enforce_margin(st->interp_lsp, st->lpcSize, LSP_MARGIN); + lsp_enforce_margin(st->interp_qlsp, st->lpcSize, LSP_MARGIN); + + lsp_to_lpc(st->interp_lsp, st->interp_lpc, st->lpcSize,stack); + lsp_to_lpc(st->interp_qlsp, st->interp_qlpc, st->lpcSize, stack); + + bw_lpc(st->gamma1, st->interp_lpc, st->bw_lpc1, st->lpcSize); + bw_lpc(st->gamma2, st->interp_lpc, st->bw_lpc2, st->lpcSize); + + /* Compute mid-band (4000 Hz for wideband) response of low-band and high-band + filters */ + st->pi_gain[sub]=LPC_SCALING; + rh = LPC_SCALING; + for (i=0;ilpcSize;i+=2) + { + rh += st->interp_qlpc[i+1] - st->interp_qlpc[i]; + st->pi_gain[sub] += st->interp_qlpc[i] + st->interp_qlpc[i+1]; + } + + rl = low_pi_gain[sub]; +#ifdef FIXED_POINT + filter_ratio=DIV32_16(SHL(rl+82,2),SHR(82+rh,5)); +#else + filter_ratio=(rl+.01)/(rh+.01); +#endif + + /* Compute "real excitation" */ + fir_mem2(sp, st->interp_qlpc, exc, st->subframeSize, st->lpcSize, st->mem_sp2); + /* Compute energy of low-band and high-band excitation */ + + eh = compute_rms(exc, st->subframeSize); + + if (!SUBMODE(innovation_quant)) {/* 1 for spectral folding excitation, 0 for stochastic */ + float g; + spx_word16_t el; + el = compute_rms(low_innov+offset, st->subframeSize); + + /* Gain to use if we want to use the low-band excitation for high-band */ + g=eh/(.01+el); + +#if 0 + { + char *tmp_stack=stack; + float *tmp_sig; + float g2; + ALLOC(tmp_sig, st->subframeSize, spx_sig_t); + for (i=0;ilpcSize;i++) + mem[i]=st->mem_sp[i]; + iir_mem2(low_innov+offset, st->interp_qlpc, tmp_sig, st->subframeSize, st->lpcSize, mem); + g2 = compute_rms(sp, st->subframeSize)/(.01+compute_rms(tmp_sig, st->subframeSize)); + /*fprintf (stderr, "gains: %f %f\n", g, g2);*/ + g = g2; + stack = tmp_stack; + } +#endif + +#ifdef FIXED_POINT + g *= filter_ratio/128.; +#else + g *= filter_ratio; +#endif + /*print_vec(&g, 1, "gain factor");*/ + /* Gain quantization */ + { + int quant = (int) floor(.5 + 10 + 8.0 * log((g+.0001))); + /*speex_warning_int("tata", quant);*/ + if (quant<0) + quant=0; + if (quant>31) + quant=31; + speex_bits_pack(bits, quant, 5); + } + + } else { + spx_word16_t gc; + spx_word32_t scale; + spx_word16_t el; + el = compute_rms(low_exc+offset, st->subframeSize); + + gc = DIV32_16(MULT16_16(filter_ratio,1+eh),1+el); + + /* This is a kludge that cleans up a historical bug */ + if (st->subframeSize==80) + gc *= 0.70711; + /*printf ("%f %f %f %f\n", el, eh, filter_ratio, gc);*/ +#ifdef FIXED_POINT + { + int qgc = scal_quant(gc, gc_quant_bound, 16); + speex_bits_pack(bits, qgc, 4); + gc = MULT16_32_Q15(28626,gc_quant_bound[qgc]); + } +#else + { + int qgc = (int)floor(.5+3.7*(log(gc)+0.15556)); + if (qgc<0) + qgc=0; + if (qgc>15) + qgc=15; + speex_bits_pack(bits, qgc, 4); + gc = exp((1/3.7)*qgc-0.15556); + } +#endif + if (st->subframeSize==80) + gc *= 1.4142; + + scale = SHL(MULT16_16(DIV32_16(SHL(gc,SIG_SHIFT-4),filter_ratio),(1+el)),4); + + compute_impulse_response(st->interp_qlpc, st->bw_lpc1, st->bw_lpc2, syn_resp, st->subframeSize, st->lpcSize, stack); + + + /* Reset excitation */ + for (i=0;isubframeSize;i++) + exc[i]=VERY_SMALL; + + /* Compute zero response (ringing) of A(z/g1) / ( A(z/g2) * Aq(z) ) */ + for (i=0;ilpcSize;i++) + mem[i]=st->mem_sp[i]; + iir_mem2(exc, st->interp_qlpc, exc, st->subframeSize, st->lpcSize, mem); + + for (i=0;ilpcSize;i++) + mem[i]=st->mem_sw[i]; + filter_mem2(exc, st->bw_lpc1, st->bw_lpc2, res, st->subframeSize, st->lpcSize, mem); + + /* Compute weighted signal */ + for (i=0;ilpcSize;i++) + mem[i]=st->mem_sw[i]; + filter_mem2(sp, st->bw_lpc1, st->bw_lpc2, sw, st->subframeSize, st->lpcSize, mem); + + /* Compute target signal */ + for (i=0;isubframeSize;i++) + target[i]=sw[i]-res[i]; + + for (i=0;isubframeSize;i++) + exc[i]=0; + + signal_div(target, target, scale, st->subframeSize); + + /* Reset excitation */ + for (i=0;isubframeSize;i++) + innov[i]=0; + + /*print_vec(target, st->subframeSize, "\ntarget");*/ + SUBMODE(innovation_quant)(target, st->interp_qlpc, st->bw_lpc1, st->bw_lpc2, + SUBMODE(innovation_params), st->lpcSize, st->subframeSize, + innov, syn_resp, bits, stack, (st->complexity+1)>>1, SUBMODE(double_codebook)); + /*print_vec(target, st->subframeSize, "after");*/ + + signal_mul(innov, innov, scale, st->subframeSize); + + for (i=0;isubframeSize;i++) + exc[i] = ADD32(exc[i], innov[i]); + + if (SUBMODE(double_codebook)) { + char *tmp_stack=stack; + VARDECL(spx_sig_t *innov2); + ALLOC(innov2, st->subframeSize, spx_sig_t); + for (i=0;isubframeSize;i++) + innov2[i]=0; + for (i=0;isubframeSize;i++) + target[i]*=2.5; + SUBMODE(innovation_quant)(target, st->interp_qlpc, st->bw_lpc1, st->bw_lpc2, + SUBMODE(innovation_params), st->lpcSize, st->subframeSize, + innov2, syn_resp, bits, stack, (st->complexity+1)>>1, 0); + for (i=0;isubframeSize;i++) + innov2[i]*=scale*(1/2.5)/SIG_SCALING; + for (i=0;isubframeSize;i++) + exc[i] = ADD32(exc[i],innov2[i]); + stack = tmp_stack; + } + + } + + /*Keep the previous memory*/ + for (i=0;ilpcSize;i++) + mem[i]=st->mem_sp[i]; + /* Final signal synthesis from excitation */ + iir_mem2(exc, st->interp_qlpc, sp, st->subframeSize, st->lpcSize, st->mem_sp); + + /* Compute weighted signal again, from synthesized speech (not sure it's the right thing) */ + filter_mem2(sp, st->bw_lpc1, st->bw_lpc2, sw, st->subframeSize, st->lpcSize, st->mem_sw); + } + + +#ifdef RESYNTH + /* Reconstruct the original */ + fir_mem_up(st->x0d, h0, st->y0, st->full_frame_size, QMF_ORDER, st->g0_mem, stack); + fir_mem_up(st->high, h1, st->y1, st->full_frame_size, QMF_ORDER, st->g1_mem, stack); + + for (i=0;ifull_frame_size;i++) + in[i]=SHR(st->y0[i]-st->y1[i], SIG_SHIFT-1); +#endif + for (i=0;ilpcSize;i++) + st->old_lsp[i] = st->lsp[i]; + for (i=0;ilpcSize;i++) + st->old_qlsp[i] = st->qlsp[i]; + + st->first=0; + + return 1; +} + + + + + +void *sb_decoder_init(const SpeexMode *m) +{ + SBDecState *st; + const SpeexSBMode *mode; + st = (SBDecState*)speex_alloc(sizeof(SBDecState)); + if (!st) + return NULL; +#if defined(VAR_ARRAYS) || defined (USE_ALLOCA) + st->stack = NULL; +#else + st->stack = (char*)speex_alloc_scratch(SB_DEC_STACK); +#endif + st->mode = m; + mode=(const SpeexSBMode*)m->mode; + + st->encode_submode = 1; + + + + + st->st_low = speex_decoder_init(mode->nb_mode); + st->full_frame_size = 2*mode->frameSize; + st->frame_size = mode->frameSize; + st->subframeSize = mode->subframeSize; + st->nbSubframes = mode->frameSize/mode->subframeSize; + st->lpcSize=mode->lpcSize; + speex_decoder_ctl(st->st_low, SPEEX_GET_SAMPLING_RATE, &st->sampling_rate); + st->sampling_rate*=2; + + st->submodes=mode->submodes; + st->submodeID=mode->defaultSubmode; + + st->first=1; + + + st->x0d=speex_alloc((st->frame_size)*sizeof(spx_sig_t)); + st->x1d=speex_alloc((st->frame_size)*sizeof(spx_sig_t)); + st->high=speex_alloc((st->full_frame_size)*sizeof(spx_sig_t)); + st->y0=speex_alloc((st->full_frame_size)*sizeof(spx_sig_t)); + st->y1=speex_alloc((st->full_frame_size)*sizeof(spx_sig_t)); + + st->g0_mem=speex_alloc((QMF_ORDER)*sizeof(spx_word32_t)); + st->g1_mem=speex_alloc((QMF_ORDER)*sizeof(spx_word32_t)); + + st->exc=speex_alloc((st->frame_size)*sizeof(spx_sig_t)); + + st->qlsp = speex_alloc((st->lpcSize)*sizeof(spx_lsp_t)); + st->old_qlsp = speex_alloc((st->lpcSize)*sizeof(spx_lsp_t)); + st->interp_qlsp = speex_alloc(st->lpcSize*sizeof(spx_lsp_t)); + st->interp_qlpc = speex_alloc(st->lpcSize*sizeof(spx_coef_t)); + + st->pi_gain = speex_alloc((st->nbSubframes)*sizeof(spx_word32_t)); + st->mem_sp = speex_alloc((2*st->lpcSize)*sizeof(spx_mem_t)); + + st->lpc_enh_enabled=0; + +#ifdef ENABLE_VALGRIND + VALGRIND_MAKE_READABLE(st, (st->stack-(char*)st)); +#endif + return st; +} + +void sb_decoder_destroy(void *state) +{ + SBDecState *st; + st = (SBDecState*)state; + speex_decoder_destroy(st->st_low); +#if !(defined(VAR_ARRAYS) || defined (USE_ALLOCA)) + speex_free_scratch(st->stack); +#endif + + speex_free(st->x0d); + speex_free(st->x1d); + speex_free(st->high); + speex_free(st->y0); + speex_free(st->y1); + speex_free(st->g0_mem); + speex_free(st->g1_mem); + speex_free(st->exc); + speex_free(st->qlsp); + speex_free(st->old_qlsp); + speex_free(st->interp_qlsp); + speex_free(st->interp_qlpc); + speex_free(st->pi_gain); + speex_free(st->mem_sp); + + speex_free(state); +} + +static void sb_decode_lost(SBDecState *st, spx_word16_t *out, int dtx, char *stack) +{ + int i; + VARDECL(spx_coef_t *awk1); + VARDECL(spx_coef_t *awk2); + VARDECL(spx_coef_t *awk3); + int saved_modeid=0; + + if (dtx) + { + saved_modeid=st->submodeID; + st->submodeID=1; + } else { + bw_lpc(GAMMA_SCALING*0.99, st->interp_qlpc, st->interp_qlpc, st->lpcSize); + } + + st->first=1; + + ALLOC(awk1, st->lpcSize+1, spx_coef_t); + ALLOC(awk2, st->lpcSize+1, spx_coef_t); + ALLOC(awk3, st->lpcSize+1, spx_coef_t); + + if (st->lpc_enh_enabled) + { + spx_word16_t k1,k2,k3; + if (st->submodes[st->submodeID] != NULL) + { + k1=SUBMODE(lpc_enh_k1); + k2=SUBMODE(lpc_enh_k2); + k3=SUBMODE(lpc_enh_k3); + } else { + k1=k2=.7*GAMMA_SCALING; + k3 = 0; + } + bw_lpc(k1, st->interp_qlpc, awk1, st->lpcSize); + bw_lpc(k2, st->interp_qlpc, awk2, st->lpcSize); + bw_lpc(k3, st->interp_qlpc, awk3, st->lpcSize); + /*fprintf (stderr, "%f %f %f\n", k1, k2, k3);*/ + } + + + /* Final signal synthesis from excitation */ + if (!dtx) + { + for (i=0;iframe_size;i++) + st->exc[i] *= .9; + } + + for (i=0;iframe_size;i++) + st->high[i]=st->exc[i]; + + if (st->lpc_enh_enabled) + { + /* Use enhanced LPC filter */ + filter_mem2(st->high, awk2, awk1, st->high, st->frame_size, st->lpcSize, + st->mem_sp+st->lpcSize); + filter_mem2(st->high, awk3, st->interp_qlpc, st->high, st->frame_size, st->lpcSize, + st->mem_sp); + } else { + /* Use regular filter */ + for (i=0;ilpcSize;i++) + st->mem_sp[st->lpcSize+i] = 0; + iir_mem2(st->high, st->interp_qlpc, st->high, st->frame_size, st->lpcSize, + st->mem_sp); + } + + /*iir_mem2(st->exc, st->interp_qlpc, st->high, st->frame_size, st->lpcSize, st->mem_sp);*/ + + /* Reconstruct the original */ + fir_mem_up(st->x0d, h0, st->y0, st->full_frame_size, QMF_ORDER, st->g0_mem, stack); + fir_mem_up(st->high, h1, st->y1, st->full_frame_size, QMF_ORDER, st->g1_mem, stack); + + mix_and_saturate(st->y0, st->y1, out, st->full_frame_size); + + if (dtx) + { + st->submodeID=saved_modeid; + } + + return; +} + +int sb_decode(void *state, SpeexBits *bits, void *vout) +{ + int i, sub; + SBDecState *st; + int wideband; + int ret; + char *stack; + VARDECL(spx_word32_t *low_pi_gain); + VARDECL(spx_sig_t *low_exc); + VARDECL(spx_sig_t *low_innov); + VARDECL(spx_coef_t *awk1); + VARDECL(spx_coef_t *awk2); + VARDECL(spx_coef_t *awk3); + int dtx; + const SpeexSBMode *mode; + spx_word16_t *out = vout; + + st = (SBDecState*)state; + stack=st->stack; + mode = (const SpeexSBMode*)(st->mode->mode); + + { + VARDECL(spx_word16_t *low); + ALLOC(low, st->frame_size, spx_word16_t); + + /* Decode the low-band */ + ret = speex_decode_native(st->st_low, bits, low); + + for (i=0;iframe_size;i++) + st->x0d[i] = SHL((spx_sig_t)low[i], SIG_SHIFT); + } + + speex_decoder_ctl(st->st_low, SPEEX_GET_DTX_STATUS, &dtx); + + /* If error decoding the narrowband part, propagate error */ + if (ret!=0) + { + return ret; + } + + if (!bits) + { + sb_decode_lost(st, out, dtx, stack); + return 0; + } + + if (st->encode_submode) + { + + /*Check "wideband bit"*/ + if (speex_bits_remaining(bits)>0) + wideband = speex_bits_peek(bits); + else + wideband = 0; + if (wideband) + { + /*Regular wideband frame, read the submode*/ + wideband = speex_bits_unpack_unsigned(bits, 1); + st->submodeID = speex_bits_unpack_unsigned(bits, SB_SUBMODE_BITS); + } else + { + /*Was a narrowband frame, set "null submode"*/ + st->submodeID = 0; + } + if (st->submodeID != 0 && st->submodes[st->submodeID] == NULL) + { + speex_warning("Invalid mode encountered: corrupted stream?"); + return -2; + } + } + + /* If null mode (no transmission), just set a couple things to zero*/ + if (st->submodes[st->submodeID] == NULL) + { + if (dtx) + { + sb_decode_lost(st, out, 1, stack); + return 0; + } + + for (i=0;iframe_size;i++) + st->exc[i]=VERY_SMALL; + + st->first=1; + + /* Final signal synthesis from excitation */ + iir_mem2(st->exc, st->interp_qlpc, st->high, st->frame_size, st->lpcSize, st->mem_sp); + + fir_mem_up(st->x0d, h0, st->y0, st->full_frame_size, QMF_ORDER, st->g0_mem, stack); + fir_mem_up(st->high, h1, st->y1, st->full_frame_size, QMF_ORDER, st->g1_mem, stack); + + mix_and_saturate(st->y0, st->y1, out, st->full_frame_size); + + return 0; + + } + + for (i=0;iframe_size;i++) + st->exc[i]=0; + + ALLOC(low_pi_gain, st->nbSubframes, spx_word32_t); + ALLOC(low_exc, st->frame_size, spx_sig_t); + ALLOC(low_innov, st->frame_size, spx_sig_t); + speex_decoder_ctl(st->st_low, SPEEX_GET_PI_GAIN, low_pi_gain); + speex_decoder_ctl(st->st_low, SPEEX_GET_EXC, low_exc); + speex_decoder_ctl(st->st_low, SPEEX_GET_INNOV, low_innov); + + SUBMODE(lsp_unquant)(st->qlsp, st->lpcSize, bits); + + if (st->first) + { + for (i=0;ilpcSize;i++) + st->old_qlsp[i] = st->qlsp[i]; + } + + ALLOC(awk1, st->lpcSize+1, spx_coef_t); + ALLOC(awk2, st->lpcSize+1, spx_coef_t); + ALLOC(awk3, st->lpcSize+1, spx_coef_t); + + for (sub=0;subnbSubframes;sub++) + { + spx_sig_t *exc, *sp; + spx_word16_t filter_ratio; + spx_word16_t el=0; + int offset; + spx_word32_t rl=0,rh=0; + + offset = st->subframeSize*sub; + sp=st->high+offset; + exc=st->exc+offset; + + /* LSP interpolation */ + lsp_interpolate(st->old_qlsp, st->qlsp, st->interp_qlsp, st->lpcSize, sub, st->nbSubframes); + + lsp_enforce_margin(st->interp_qlsp, st->lpcSize, LSP_MARGIN); + + /* LSP to LPC */ + lsp_to_lpc(st->interp_qlsp, st->interp_qlpc, st->lpcSize, stack); + + + if (st->lpc_enh_enabled) + { + spx_word16_t k1,k2,k3; + k1=SUBMODE(lpc_enh_k1); + k2=SUBMODE(lpc_enh_k2); + k3=SUBMODE(lpc_enh_k3); + bw_lpc(k1, st->interp_qlpc, awk1, st->lpcSize); + bw_lpc(k2, st->interp_qlpc, awk2, st->lpcSize); + bw_lpc(k3, st->interp_qlpc, awk3, st->lpcSize); + /*fprintf (stderr, "%f %f %f\n", k1, k2, k3);*/ + } + + + /* Calculate reponse ratio between the low and high filter in the middle + of the band (4000 Hz) */ + + st->pi_gain[sub]=LPC_SCALING; + rh = LPC_SCALING; + for (i=0;ilpcSize;i+=2) + { + rh += st->interp_qlpc[i+1] - st->interp_qlpc[i]; + st->pi_gain[sub] += st->interp_qlpc[i] + st->interp_qlpc[i+1]; + } + + rl = low_pi_gain[sub]; +#ifdef FIXED_POINT + filter_ratio=DIV32_16(SHL(rl+82,2),SHR(82+rh,5)); +#else + filter_ratio=(rl+.01)/(rh+.01); +#endif + + for (i=0;isubframeSize;i++) + exc[i]=0; + if (!SUBMODE(innovation_unquant)) + { + float g; + int quant; + + quant = speex_bits_unpack_unsigned(bits, 5); + g= exp(((float)quant-10)/8.0); + +#ifdef FIXED_POINT + g /= filter_ratio/128.; +#else + g /= filter_ratio; +#endif + /* High-band excitation using the low-band excitation and a gain */ + for (i=0;isubframeSize;i++) + exc[i]=mode->folding_gain*g*low_innov[offset+i]; + /*speex_rand_vec(mode->folding_gain*g*sqrt(el/st->subframeSize), exc, st->subframeSize);*/ + } else { + spx_word16_t gc; + spx_word32_t scale; + int qgc = speex_bits_unpack_unsigned(bits, 4); + + el = compute_rms(low_exc+offset, st->subframeSize); + +#ifdef FIXED_POINT + gc = MULT16_32_Q15(28626,gc_quant_bound[qgc]); +#else + gc = exp((1/3.7)*qgc-0.15556); +#endif + + if (st->subframeSize==80) + gc *= 1.4142; + + scale = SHL(MULT16_16(DIV32_16(SHL(gc,SIG_SHIFT-4),filter_ratio),(1+el)),4); + + SUBMODE(innovation_unquant)(exc, SUBMODE(innovation_params), st->subframeSize, + bits, stack); + + signal_mul(exc,exc,scale,st->subframeSize); + + if (SUBMODE(double_codebook)) { + char *tmp_stack=stack; + VARDECL(spx_sig_t *innov2); + ALLOC(innov2, st->subframeSize, spx_sig_t); + for (i=0;isubframeSize;i++) + innov2[i]=0; + SUBMODE(innovation_unquant)(innov2, SUBMODE(innovation_params), st->subframeSize, + bits, stack); + for (i=0;isubframeSize;i++) + innov2[i]*=scale/(float)SIG_SCALING*(1/2.5); + for (i=0;isubframeSize;i++) + exc[i] = ADD32(exc[i],innov2[i]); + stack = tmp_stack; + } + + } + + for (i=0;isubframeSize;i++) + sp[i]=exc[i]; + if (st->lpc_enh_enabled) + { + /* Use enhanced LPC filter */ + filter_mem2(sp, awk2, awk1, sp, st->subframeSize, st->lpcSize, + st->mem_sp+st->lpcSize); + filter_mem2(sp, awk3, st->interp_qlpc, sp, st->subframeSize, st->lpcSize, + st->mem_sp); + } else { + /* Use regular filter */ + for (i=0;ilpcSize;i++) + st->mem_sp[st->lpcSize+i] = 0; + iir_mem2(sp, st->interp_qlpc, sp, st->subframeSize, st->lpcSize, + st->mem_sp); + } + /*iir_mem2(exc, st->interp_qlpc, sp, st->subframeSize, st->lpcSize, st->mem_sp);*/ + + } + + fir_mem_up(st->x0d, h0, st->y0, st->full_frame_size, QMF_ORDER, st->g0_mem, stack); + fir_mem_up(st->high, h1, st->y1, st->full_frame_size, QMF_ORDER, st->g1_mem, stack); + + mix_and_saturate(st->y0, st->y1, out, st->full_frame_size); + + for (i=0;ilpcSize;i++) + st->old_qlsp[i] = st->qlsp[i]; + + st->first=0; + + return 0; +} + + +int sb_encoder_ctl(void *state, int request, void *ptr) +{ + SBEncState *st; + st=(SBEncState*)state; + switch(request) + { + case SPEEX_GET_FRAME_SIZE: + (*(int*)ptr) = st->full_frame_size; + break; + case SPEEX_SET_HIGH_MODE: + st->submodeSelect = st->submodeID = (*(int*)ptr); + break; + case SPEEX_SET_LOW_MODE: + speex_encoder_ctl(st->st_low, SPEEX_SET_LOW_MODE, ptr); + break; + case SPEEX_SET_DTX: + speex_encoder_ctl(st->st_low, SPEEX_SET_DTX, ptr); + break; + case SPEEX_GET_DTX: + speex_encoder_ctl(st->st_low, SPEEX_GET_DTX, ptr); + break; + case SPEEX_GET_LOW_MODE: + speex_encoder_ctl(st->st_low, SPEEX_GET_LOW_MODE, ptr); + break; + case SPEEX_SET_MODE: + speex_encoder_ctl(st, SPEEX_SET_QUALITY, ptr); + break; + case SPEEX_SET_VBR: + st->vbr_enabled = (*(int*)ptr); + speex_encoder_ctl(st->st_low, SPEEX_SET_VBR, ptr); + break; + case SPEEX_GET_VBR: + (*(int*)ptr) = st->vbr_enabled; + break; + case SPEEX_SET_VAD: + st->vad_enabled = (*(int*)ptr); + speex_encoder_ctl(st->st_low, SPEEX_SET_VAD, ptr); + break; + case SPEEX_GET_VAD: + (*(int*)ptr) = st->vad_enabled; + break; + case SPEEX_SET_VBR_QUALITY: + { + int q; + float qual = (*(float*)ptr)+.6; + st->vbr_quality = (*(float*)ptr); + if (qual>10) + qual=10; + q=(int)floor(.5+*(float*)ptr); + if (q>10) + q=10; + speex_encoder_ctl(st->st_low, SPEEX_SET_VBR_QUALITY, &qual); + speex_encoder_ctl(state, SPEEX_SET_QUALITY, &q); + break; + } + case SPEEX_GET_VBR_QUALITY: + (*(float*)ptr) = st->vbr_quality; + break; + case SPEEX_SET_ABR: + st->abr_enabled = (*(int*)ptr); + st->vbr_enabled = 1; + speex_encoder_ctl(st->st_low, SPEEX_SET_VBR, &st->vbr_enabled); + { + int i=10, rate, target; + float vbr_qual; + target = (*(int*)ptr); + while (i>=0) + { + speex_encoder_ctl(st, SPEEX_SET_QUALITY, &i); + speex_encoder_ctl(st, SPEEX_GET_BITRATE, &rate); + if (rate <= target) + break; + i--; + } + vbr_qual=i; + if (vbr_qual<0) + vbr_qual=0; + speex_encoder_ctl(st, SPEEX_SET_VBR_QUALITY, &vbr_qual); + st->abr_count=0; + st->abr_drift=0; + st->abr_drift2=0; + } + + break; + case SPEEX_GET_ABR: + (*(int*)ptr) = st->abr_enabled; + break; + case SPEEX_SET_QUALITY: + { + int nb_qual; + int quality = (*(int*)ptr); + if (quality < 0) + quality = 0; + if (quality > 10) + quality = 10; + st->submodeSelect = st->submodeID = ((const SpeexSBMode*)(st->mode->mode))->quality_map[quality]; + nb_qual = ((const SpeexSBMode*)(st->mode->mode))->low_quality_map[quality]; + speex_encoder_ctl(st->st_low, SPEEX_SET_MODE, &nb_qual); + } + break; + case SPEEX_SET_COMPLEXITY: + speex_encoder_ctl(st->st_low, SPEEX_SET_COMPLEXITY, ptr); + st->complexity = (*(int*)ptr); + if (st->complexity<1) + st->complexity=1; + break; + case SPEEX_GET_COMPLEXITY: + (*(int*)ptr) = st->complexity; + break; + case SPEEX_SET_BITRATE: + { + int i=10, rate, target; + target = (*(int*)ptr); + while (i>=0) + { + speex_encoder_ctl(st, SPEEX_SET_QUALITY, &i); + speex_encoder_ctl(st, SPEEX_GET_BITRATE, &rate); + if (rate <= target) + break; + i--; + } + } + break; + case SPEEX_GET_BITRATE: + speex_encoder_ctl(st->st_low, request, ptr); + /*fprintf (stderr, "before: %d\n", (*(int*)ptr));*/ + if (st->submodes[st->submodeID]) + (*(int*)ptr) += st->sampling_rate*SUBMODE(bits_per_frame)/st->full_frame_size; + else + (*(int*)ptr) += st->sampling_rate*(SB_SUBMODE_BITS+1)/st->full_frame_size; + /*fprintf (stderr, "after: %d\n", (*(int*)ptr));*/ + break; + case SPEEX_SET_SAMPLING_RATE: + { + int tmp=(*(int*)ptr); + st->sampling_rate = tmp; + tmp>>=1; + speex_encoder_ctl(st->st_low, SPEEX_SET_SAMPLING_RATE, &tmp); + } + break; + case SPEEX_GET_SAMPLING_RATE: + (*(int*)ptr)=st->sampling_rate; + break; + case SPEEX_RESET_STATE: + { + int i; + st->first = 1; + for (i=0;ilpcSize;i++) + st->lsp[i]=(M_PI*((float)(i+1)))/(st->lpcSize+1); + for (i=0;ilpcSize;i++) + st->mem_sw[i]=st->mem_sp[i]=st->mem_sp2[i]=0; + for (i=0;ibufSize;i++) + st->excBuf[i]=0; + for (i=0;ih0_mem[i]=st->h1_mem[i]=st->g0_mem[i]=st->g1_mem[i]=0; + } + break; + case SPEEX_SET_SUBMODE_ENCODING: + st->encode_submode = (*(int*)ptr); + speex_encoder_ctl(st->st_low, SPEEX_SET_SUBMODE_ENCODING, &ptr); + break; + case SPEEX_GET_SUBMODE_ENCODING: + (*(int*)ptr) = st->encode_submode; + break; + case SPEEX_GET_LOOKAHEAD: + speex_encoder_ctl(st->st_low, SPEEX_GET_LOOKAHEAD, ptr); + (*(int*)ptr) = 2*(*(int*)ptr) + QMF_ORDER - 1; + break; + case SPEEX_GET_PI_GAIN: + { + int i; + spx_word32_t *g = (spx_word32_t*)ptr; + for (i=0;inbSubframes;i++) + g[i]=st->pi_gain[i]; + } + break; + case SPEEX_GET_EXC: + { + int i; + spx_sig_t *e = (spx_sig_t*)ptr; + for (i=0;ifull_frame_size;i++) + e[i]=0; + for (i=0;iframe_size;i++) + e[2*i]=2*st->exc[i]; + } + break; + case SPEEX_GET_INNOV: + { + int i; + spx_sig_t *e = (spx_sig_t*)ptr; + for (i=0;ifull_frame_size;i++) + e[i]=0; + for (i=0;iframe_size;i++) + e[2*i]=2*st->exc[i]; + } + break; + case SPEEX_GET_RELATIVE_QUALITY: + (*(float*)ptr)=st->relative_quality; + break; + default: + speex_warning_int("Unknown nb_ctl request: ", request); + return -1; + } + return 0; +} + +int sb_decoder_ctl(void *state, int request, void *ptr) +{ + SBDecState *st; + st=(SBDecState*)state; + switch(request) + { + case SPEEX_SET_HIGH_MODE: + st->submodeID = (*(int*)ptr); + break; + case SPEEX_SET_LOW_MODE: + speex_decoder_ctl(st->st_low, SPEEX_SET_LOW_MODE, ptr); + break; + case SPEEX_GET_LOW_MODE: + speex_decoder_ctl(st->st_low, SPEEX_GET_LOW_MODE, ptr); + break; + case SPEEX_GET_FRAME_SIZE: + (*(int*)ptr) = st->full_frame_size; + break; + case SPEEX_SET_ENH: + speex_decoder_ctl(st->st_low, request, ptr); + st->lpc_enh_enabled = *((int*)ptr); + break; + case SPEEX_GET_ENH: + *((int*)ptr) = st->lpc_enh_enabled; + break; + case SPEEX_SET_MODE: + case SPEEX_SET_QUALITY: + { + int nb_qual; + int quality = (*(int*)ptr); + if (quality < 0) + quality = 0; + if (quality > 10) + quality = 10; + st->submodeID = ((const SpeexSBMode*)(st->mode->mode))->quality_map[quality]; + nb_qual = ((const SpeexSBMode*)(st->mode->mode))->low_quality_map[quality]; + speex_decoder_ctl(st->st_low, SPEEX_SET_MODE, &nb_qual); + } + break; + case SPEEX_GET_BITRATE: + speex_decoder_ctl(st->st_low, request, ptr); + if (st->submodes[st->submodeID]) + (*(int*)ptr) += st->sampling_rate*SUBMODE(bits_per_frame)/st->full_frame_size; + else + (*(int*)ptr) += st->sampling_rate*(SB_SUBMODE_BITS+1)/st->full_frame_size; + break; + case SPEEX_SET_SAMPLING_RATE: + { + int tmp=(*(int*)ptr); + st->sampling_rate = tmp; + tmp>>=1; + speex_decoder_ctl(st->st_low, SPEEX_SET_SAMPLING_RATE, &tmp); + } + break; + case SPEEX_GET_SAMPLING_RATE: + (*(int*)ptr)=st->sampling_rate; + break; + case SPEEX_SET_HANDLER: + speex_decoder_ctl(st->st_low, SPEEX_SET_HANDLER, ptr); + break; + case SPEEX_SET_USER_HANDLER: + speex_decoder_ctl(st->st_low, SPEEX_SET_USER_HANDLER, ptr); + break; + case SPEEX_RESET_STATE: + { + int i; + for (i=0;i<2*st->lpcSize;i++) + st->mem_sp[i]=0; + for (i=0;ig0_mem[i]=st->g1_mem[i]=0; + } + break; + case SPEEX_SET_SUBMODE_ENCODING: + st->encode_submode = (*(int*)ptr); + speex_decoder_ctl(st->st_low, SPEEX_SET_SUBMODE_ENCODING, &ptr); + break; + case SPEEX_GET_SUBMODE_ENCODING: + (*(int*)ptr) = st->encode_submode; + break; + case SPEEX_GET_PI_GAIN: + { + int i; + spx_word32_t *g = (spx_word32_t*)ptr; + for (i=0;inbSubframes;i++) + g[i]=st->pi_gain[i]; + } + break; + case SPEEX_GET_EXC: + { + int i; + spx_sig_t *e = (spx_sig_t*)ptr; + for (i=0;ifull_frame_size;i++) + e[i]=0; + for (i=0;iframe_size;i++) + e[2*i]=2*st->exc[i]; + } + break; + case SPEEX_GET_INNOV: + { + int i; + spx_sig_t *e = (spx_sig_t*)ptr; + for (i=0;ifull_frame_size;i++) + e[i]=0; + for (i=0;iframe_size;i++) + e[2*i]=2*st->exc[i]; + } + break; + case SPEEX_GET_DTX_STATUS: + speex_decoder_ctl(st->st_low, SPEEX_GET_DTX_STATUS, ptr); + break; + default: + speex_warning_int("Unknown nb_ctl request: ", request); + return -1; + } + return 0; +} + +#endif + diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/sb_celp.h b/mozilla/zap/zmk/speex-1.1.10/libspeex/sb_celp.h new file mode 100755 index 00000000000..416b334d7b4 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/sb_celp.h @@ -0,0 +1,169 @@ +/* Copyright (C) 2002 Jean-Marc Valin */ +/** + @file sb_celp.h + @brief Sub-band CELP mode used for wideband encoding +*/ +/* + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 SB_CELP_H +#define SB_CELP_H + +#include "modes.h" +#include +#include "nb_celp.h" + +/**Structure representing the full state of the sub-band encoder*/ +typedef struct SBEncState { + const SpeexMode *mode; /**< Pointer to the mode (containing for vtable info) */ + void *st_low; /**< State of the low-band (narrowband) encoder */ + int full_frame_size; /**< Length of full-band frames*/ + int frame_size; /**< Length of high-band frames*/ + int subframeSize; /**< Length of high-band sub-frames*/ + int nbSubframes; /**< Number of high-band sub-frames*/ + int windowSize; /**< Length of high-band LPC window*/ + int lpcSize; /**< Order of high-band LPC analysis */ + int bufSize; /**< Buffer size */ + int first; /**< First frame? */ + float lag_factor; /**< Lag-windowing control parameter */ + float lpc_floor; /**< Controls LPC analysis noise floor */ + spx_word16_t gamma1; /**< Perceptual weighting coef 1 */ + spx_word16_t gamma2; /**< Perceptual weighting coef 2 */ + + char *stack; /**< Temporary allocation stack */ + spx_sig_t *x0d, *x1d; /**< QMF filter signals*/ + spx_sig_t *high; /**< High-band signal (buffer) */ + spx_sig_t *y0, *y1; /**< QMF synthesis signals */ + spx_word16_t *h0_mem, *h1_mem; + spx_word32_t *g0_mem, *g1_mem; /**< QMF memories */ + + spx_sig_t *excBuf; /**< High-band excitation */ + spx_sig_t *exc; /**< High-band excitation (for QMF only)*/ + spx_sig_t *buf; /**< Temporary buffer */ + spx_sig_t *res; /**< Zero-input response (ringing) */ + spx_sig_t *sw; /**< Perceptually weighted signal */ + spx_sig_t *target; /**< Weighted target signal (analysis by synthesis) */ + spx_word16_t *window; /**< LPC analysis window */ + spx_word16_t *lagWindow; /**< Auto-correlation window */ + spx_word16_t *autocorr; /**< Auto-correlation (for LPC analysis) */ + spx_coef_t *lpc; /**< LPC coefficients */ + spx_lsp_t *lsp; /**< LSP coefficients */ + spx_lsp_t *qlsp; /**< Quantized LSPs */ + spx_lsp_t *old_lsp; /**< LSPs of previous frame */ + spx_lsp_t *old_qlsp; /**< Quantized LSPs of previous frame */ + spx_lsp_t *interp_lsp; /**< Interpolated LSPs for current sub-frame */ + spx_lsp_t *interp_qlsp; /**< Interpolated quantized LSPs for current sub-frame */ + spx_coef_t *interp_lpc; /**< Interpolated LPCs for current sub-frame */ + spx_coef_t *interp_qlpc; /**< Interpolated quantized LPCs for current sub-frame */ + spx_coef_t *bw_lpc1; /**< Bandwidth-expanded version of LPCs (#1) */ + spx_coef_t *bw_lpc2; /**< Bandwidth-expanded version of LPCs (#2) */ + + spx_mem_t *mem_sp; /**< Synthesis signal memory */ + spx_mem_t *mem_sp2; + spx_mem_t *mem_sw; /**< Perceptual signal memory */ + spx_word32_t *pi_gain; + + float vbr_quality; /**< Quality setting for VBR encoding */ + int vbr_enabled; /**< 1 for enabling VBR, 0 otherwise */ + int abr_enabled; /**< ABR setting (in bps), 0 if off */ + float abr_drift; + float abr_drift2; + float abr_count; + int vad_enabled; /**< 1 for enabling VAD, 0 otherwise */ + float relative_quality; + + int encode_submode; + const SpeexSubmode * const *submodes; + int submodeID; + int submodeSelect; + int complexity; + int sampling_rate; + +} SBEncState; + + +/**Structure representing the full state of the sub-band decoder*/ +typedef struct SBDecState { + const SpeexMode *mode; /**< Pointer to the mode (containing for vtable info) */ + void *st_low; /**< State of the low-band (narrowband) encoder */ + int full_frame_size; + int frame_size; + int subframeSize; + int nbSubframes; + int lpcSize; + int first; + int sampling_rate; + int lpc_enh_enabled; + + char *stack; + spx_sig_t *x0d, *x1d; + spx_sig_t *high; + spx_sig_t *y0, *y1; + spx_word32_t *g0_mem, *g1_mem; + + spx_sig_t *exc; + spx_lsp_t *qlsp; + spx_lsp_t *old_qlsp; + spx_lsp_t *interp_qlsp; + spx_coef_t *interp_qlpc; + + spx_mem_t *mem_sp; + spx_word32_t *pi_gain; + + int encode_submode; + const SpeexSubmode * const *submodes; + int submodeID; +} SBDecState; + + +/**Initializes encoder state*/ +void *sb_encoder_init(const SpeexMode *m); + +/**De-allocates encoder state resources*/ +void sb_encoder_destroy(void *state); + +/**Encodes one frame*/ +int sb_encode(void *state, void *in, SpeexBits *bits); + + +/**Initializes decoder state*/ +void *sb_decoder_init(const SpeexMode *m); + +/**De-allocates decoder state resources*/ +void sb_decoder_destroy(void *state); + +/**Decodes one frame*/ +int sb_decode(void *state, SpeexBits *bits, void *out); + +int sb_encoder_ctl(void *state, int request, void *ptr); + +int sb_decoder_ctl(void *state, int request, void *ptr); + +#endif diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/smallft.c b/mozilla/zap/zmk/speex-1.1.10/libspeex/smallft.c new file mode 100755 index 00000000000..d08b92e10a5 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/smallft.c @@ -0,0 +1,1260 @@ +/******************************************************************** + * * + * 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-2001 * + * by the XIPHOPHORUS Company http://www.xiph.org/ * + * * + ******************************************************************** + + function: *unnormalized* fft transform + last mod: $Id: smallft.c,v 1.1.2.1 2005-08-16 20:04:29 alex%croczilla.com Exp $ + + ********************************************************************/ + +/* FFT implementation from OggSquish, minus cosine transforms, + * minus all but radix 2/4 case. In Vorbis we only need this + * cut-down version. + * + * To do more than just power-of-two sized vectors, see the full + * version I wrote for NetLib. + * + * Note that the packing is a little strange; rather than the FFT r/i + * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, + * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the + * FORTRAN version + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include "smallft.h" +#include "misc.h" + +static void drfti1(int n, float *wa, int *ifac){ + static int ntryh[4] = { 4,2,3,5 }; + static float tpi = 6.28318530717958648f; + float arg,argh,argld,fi; + int ntry=0,i,j=-1; + int k1, l1, l2, ib; + int ld, ii, ip, is, nq, nr; + int ido, ipm, nfm1; + int nl=n; + int nf=0; + + L101: + j++; + if (j < 4) + ntry=ntryh[j]; + else + ntry+=2; + + L104: + nq=nl/ntry; + nr=nl-ntry*nq; + if (nr!=0) goto L101; + + nf++; + ifac[nf+1]=ntry; + nl=nq; + if(ntry!=2)goto L107; + if(nf==1)goto L107; + + for (i=1;i>1; + ipp2=ip; + idp2=ido; + nbd=(ido-1)>>1; + t0=l1*ido; + t10=ip*ido; + + if(ido==1)goto L119; + for(ik=0;ikl1){ + for(j=1;j>1; + ipp2=ip; + ipph=(ip+1)>>1; + if(idol1)goto L139; + + is= -ido-1; + t1=0; + for(j=1;jn==1)return; + drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache); +} + +void spx_drft_backward(struct drft_lookup *l,float *data){ + if (l->n==1)return; + drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache); +} + +void spx_drft_init(struct drft_lookup *l,int n) +{ + l->n=n; + l->trigcache=(float*)speex_alloc(3*n*sizeof(*l->trigcache)); + l->splitcache=(int*)speex_alloc(32*sizeof(*l->splitcache)); + fdrffti(n, l->trigcache, l->splitcache); +} + +void spx_drft_clear(struct drft_lookup *l) +{ + if(l) + { + if(l->trigcache) + speex_free(l->trigcache); + if(l->splitcache) + speex_free(l->splitcache); + } +} diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/smallft.h b/mozilla/zap/zmk/speex-1.1.10/libspeex/smallft.h new file mode 100755 index 00000000000..3dd3fcc3a82 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/smallft.h @@ -0,0 +1,42 @@ +/******************************************************************** + * * + * 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-2001 * + * by the XIPHOPHORUS Company http://www.xiph.org/ * + * * + ******************************************************************** + + function: fft transform + last mod: $Id: smallft.h,v 1.1.2.1 2005-08-16 20:04:29 alex%croczilla.com Exp $ + + ********************************************************************/ + +#ifndef _V_SMFT_H_ +#define _V_SMFT_H_ + +/*#include "vorbis/codec.h"*/ + +#ifdef __cplusplus +extern "C" { +#endif + +struct drft_lookup{ + int n; + float *trigcache; + int *splitcache; +}; + +extern void spx_drft_forward(struct drft_lookup *l,float *data); +extern void spx_drft_backward(struct drft_lookup *l,float *data); +extern void spx_drft_init(struct drft_lookup *l,int n); +extern void spx_drft_clear(struct drft_lookup *l); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/speex.c b/mozilla/zap/zmk/speex-1.1.10/libspeex/speex.c new file mode 100755 index 00000000000..cfce1ffa081 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/speex.c @@ -0,0 +1,268 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: speex.c + + Basic Speex functions + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 "modes.h" +#include + +#ifndef NULL +#define NULL 0 +#endif + +#define MAX_IN_SAMPLES 640 + + + +void *speex_encoder_init(const SpeexMode *mode) +{ + return mode->enc_init(mode); +} + +void *speex_decoder_init(const SpeexMode *mode) +{ + return mode->dec_init(mode); +} + +void speex_encoder_destroy(void *state) +{ + (*((SpeexMode**)state))->enc_destroy(state); +} + +void speex_decoder_destroy(void *state) +{ + (*((SpeexMode**)state))->dec_destroy(state); +} + + + +int speex_encode_native(void *state, spx_word16_t *in, SpeexBits *bits) +{ + return (*((SpeexMode**)state))->enc(state, in, bits); +} + +int speex_decode_native(void *state, SpeexBits *bits, spx_word16_t *out) +{ + return (*((SpeexMode**)state))->dec(state, bits, out); +} + + + +#ifdef FIXED_POINT + +int speex_encode(void *state, float *in, SpeexBits *bits) +{ + int i; + int N; + spx_int16_t short_in[MAX_IN_SAMPLES]; + speex_encoder_ctl(state, SPEEX_GET_FRAME_SIZE, &N); + for (i=0;i32767.f) + short_in[i] = 32767; + else if (in[i]<-32768.f) + short_in[i] = -32768; + else + short_in[i] = (spx_int16_t)floor(.5+in[i]); + } + return (*((SpeexMode**)state))->enc(state, short_in, bits); +} + +int speex_encode_int(void *state, spx_int16_t *in, SpeexBits *bits) +{ + SpeexMode *mode; + mode = *(SpeexMode**)state; + return (mode)->enc(state, in, bits); +} + +int speex_decode(void *state, SpeexBits *bits, float *out) +{ + int i, ret; + int N; + spx_int16_t short_out[MAX_IN_SAMPLES]; + speex_decoder_ctl(state, SPEEX_GET_FRAME_SIZE, &N); + ret = (*((SpeexMode**)state))->dec(state, bits, short_out); + for (i=0;idec(state, bits, out); +} + +#else + +int speex_encode(void *state, float *in, SpeexBits *bits) +{ + return (*((SpeexMode**)state))->enc(state, in, bits); +} + +int speex_encode_int(void *state, spx_int16_t *in, SpeexBits *bits) +{ + int i; + int N; + float float_in[MAX_IN_SAMPLES]; + speex_encoder_ctl(state, SPEEX_GET_FRAME_SIZE, &N); + for (i=0;ienc(state, float_in, bits); +} + +int speex_decode(void *state, SpeexBits *bits, float *out) +{ + return (*((SpeexMode**)state))->dec(state, bits, out); +} + +int speex_decode_int(void *state, SpeexBits *bits, spx_int16_t *out) +{ + int i; + int N; + float float_out[MAX_IN_SAMPLES]; + int ret; + speex_decoder_ctl(state, SPEEX_GET_FRAME_SIZE, &N); + ret = (*((SpeexMode**)state))->dec(state, bits, float_out); + for (i=0;i32767.f) + out[i] = 32767; + else if (float_out[i]<-32768.f) + out[i] = -32768; + else + out[i] = (spx_int16_t)floor(.5+float_out[i]); + } + return ret; +} +#endif + + + +int speex_encoder_ctl(void *state, int request, void *ptr) +{ + return (*((SpeexMode**)state))->enc_ctl(state, request, ptr); +} + +int speex_decoder_ctl(void *state, int request, void *ptr) +{ + return (*((SpeexMode**)state))->dec_ctl(state, request, ptr); +} + + + +int nb_mode_query(const void *mode, int request, void *ptr) +{ + const SpeexNBMode *m = (const SpeexNBMode*)mode; + + switch (request) + { + case SPEEX_MODE_FRAME_SIZE: + *((int*)ptr)=m->frameSize; + break; + case SPEEX_SUBMODE_BITS_PER_FRAME: + if (*((int*)ptr)==0) + *((int*)ptr) = NB_SUBMODE_BITS+1; + else if (m->submodes[*((int*)ptr)]==NULL) + *((int*)ptr) = -1; + else + *((int*)ptr) = m->submodes[*((int*)ptr)]->bits_per_frame; + break; + default: + speex_warning_int("Unknown nb_mode_query request: ", request); + return -1; + } + return 0; +} + +int wb_mode_query(const void *mode, int request, void *ptr) +{ + const SpeexSBMode *m = (const SpeexSBMode*)mode; + + switch (request) + { + case SPEEX_MODE_FRAME_SIZE: + *((int*)ptr)=2*m->frameSize; + break; + case SPEEX_SUBMODE_BITS_PER_FRAME: + if (*((int*)ptr)==0) + *((int*)ptr) = SB_SUBMODE_BITS+1; + else if (m->submodes[*((int*)ptr)]==NULL) + *((int*)ptr) = -1; + else + *((int*)ptr) = m->submodes[*((int*)ptr)]->bits_per_frame; + break; + default: + speex_warning_int("Unknown wb_mode_query request: ", request); + return -1; + } + return 0; +} + + +int speex_lib_ctl(int request, void *ptr) +{ + switch (request) + { + case SPEEX_LIB_GET_MAJOR_VERSION: + *((int*)ptr) = SPEEX_MAJOR_VERSION; + break; + case SPEEX_LIB_GET_MINOR_VERSION: + *((int*)ptr) = SPEEX_MINOR_VERSION; + break; + case SPEEX_LIB_GET_MICRO_VERSION: + *((int*)ptr) = SPEEX_MICRO_VERSION; + break; + case SPEEX_LIB_GET_EXTRA_VERSION: + *((const char**)ptr) = SPEEX_EXTRA_VERSION; + break; + case SPEEX_LIB_GET_VERSION_STRING: + *((const char**)ptr) = SPEEX_VERSION; + break; + /*case SPEEX_LIB_SET_ALLOC_FUNC: + break; + case SPEEX_LIB_GET_ALLOC_FUNC: + break; + case SPEEX_LIB_SET_FREE_FUNC: + break; + case SPEEX_LIB_GET_FREE_FUNC: + break;*/ + default: + speex_warning_int("Unknown wb_mode_query request: ", request); + return -1; + } + return 0; +} diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/speex_callbacks.c b/mozilla/zap/zmk/speex-1.1.10/libspeex/speex_callbacks.c new file mode 100755 index 00000000000..fba5cab69cc --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/speex_callbacks.c @@ -0,0 +1,140 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File speex_callbacks.c + Callback handling and in-band signalling + + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 +#include "misc.h" + +int speex_inband_handler(SpeexBits *bits, SpeexCallback *callback_list, void *state) +{ + int id; + SpeexCallback *callback; + /*speex_bits_advance(bits, 5);*/ + id=speex_bits_unpack_unsigned(bits, 4); + callback = callback_list+id; + + if (callback->func) + { + return callback->func(bits, state, callback->data); + } else + /*If callback is not registered, skip the right number of bits*/ + { + int adv; + if (id<2) + adv = 1; + else if (id<8) + adv = 4; + else if (id<10) + adv = 8; + else if (id<12) + adv = 16; + else if (id<14) + adv = 32; + else + adv = 64; + speex_bits_advance(bits, adv); + } + return 0; +} + +int speex_std_mode_request_handler(SpeexBits *bits, void *state, void *data) +{ + int m; + m = speex_bits_unpack_unsigned(bits, 4); + speex_encoder_ctl(data, SPEEX_SET_MODE, &m); + return 0; +} + +int speex_std_low_mode_request_handler(SpeexBits *bits, void *state, void *data) +{ + int m; + m = speex_bits_unpack_unsigned(bits, 4); + speex_encoder_ctl(data, SPEEX_SET_LOW_MODE, &m); + return 0; +} + +int speex_std_high_mode_request_handler(SpeexBits *bits, void *state, void *data) +{ + int m; + m = speex_bits_unpack_unsigned(bits, 4); + speex_encoder_ctl(data, SPEEX_SET_HIGH_MODE, &m); + return 0; +} + +int speex_std_vbr_request_handler(SpeexBits *bits, void *state, void *data) +{ + int vbr; + vbr = speex_bits_unpack_unsigned(bits, 1); + speex_encoder_ctl(data, SPEEX_SET_VBR, &vbr); + return 0; +} + +int speex_std_enh_request_handler(SpeexBits *bits, void *state, void *data) +{ + int enh; + enh = speex_bits_unpack_unsigned(bits, 1); + speex_decoder_ctl(data, SPEEX_SET_ENH, &enh); + return 0; +} + +int speex_std_vbr_quality_request_handler(SpeexBits *bits, void *state, void *data) +{ + int qual; + qual = speex_bits_unpack_unsigned(bits, 4); + speex_encoder_ctl(data, SPEEX_SET_VBR_QUALITY, &qual); + return 0; +} + + +int speex_std_char_handler(SpeexBits *bits, void *state, void *data) +{ + unsigned char ch; + ch = speex_bits_unpack_unsigned(bits, 8); + _speex_putc(ch, data); + /*printf("speex_std_char_handler ch=%x\n", ch);*/ + return 0; +} + + + +/* Default handler for user callbacks: skip it */ +int speex_default_user_handler(SpeexBits *bits, void *state, void *data) +{ + int req_size = speex_bits_unpack_unsigned(bits, 4); + speex_bits_advance(bits, 5+8*req_size); + return 0; +} diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/speex_header.c b/mozilla/zap/zmk/speex-1.1.10/libspeex/speex_header.c new file mode 100755 index 00000000000..c66271c12bf --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/speex_header.c @@ -0,0 +1,166 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: speex_header.c + Describes the Speex header + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 "misc.h" +#include +#include + +#ifndef NULL +#define NULL 0 +#endif + +#define ENDIAN_SWITCH(x) {x=le_int(x);} + + +/* +typedef struct SpeexHeader { + char speex_string[8]; + char speex_version[SPEEX_HEADER_VERSION_LENGTH]; + int speex_version_id; + int header_size; + int rate; + int mode; + int mode_bitstream_version; + int nb_channels; + int bitrate; + int frame_size; + int vbr; + int frames_per_packet; + int extra_headers; + int reserved1; + int reserved2; +} SpeexHeader; +*/ + +void speex_init_header(SpeexHeader *header, int rate, int nb_channels, const SpeexMode *m) +{ + int i; + const char *h="Speex "; + /* + strncpy(header->speex_string, "Speex ", 8); + strncpy(header->speex_version, SPEEX_VERSION, SPEEX_HEADER_VERSION_LENGTH-1); + header->speex_version[SPEEX_HEADER_VERSION_LENGTH-1]=0; + */ + for (i=0;i<8;i++) + header->speex_string[i]=h[i]; + for (i=0;ispeex_version[i]=SPEEX_VERSION[i]; + for (;ispeex_version[i]=0; + + header->speex_version_id = 1; + header->header_size = sizeof(SpeexHeader); + + header->rate = rate; + header->mode = m->modeID; + header->mode_bitstream_version = m->bitstream_version; + if (m->modeID<0) + speex_warning("This mode is meant to be used alone"); + header->nb_channels = nb_channels; + header->bitrate = -1; + speex_mode_query(m, SPEEX_MODE_FRAME_SIZE, &header->frame_size); + header->vbr = 0; + + header->frames_per_packet = 0; + header->extra_headers = 0; + header->reserved1 = 0; + header->reserved2 = 0; +} + +char *speex_header_to_packet(SpeexHeader *header, int *size) +{ + SpeexHeader *le_header; + le_header = (SpeexHeader*)speex_alloc(sizeof(SpeexHeader)); + + speex_move(le_header, header, sizeof(SpeexHeader)); + + /*Make sure everything is now little-endian*/ + ENDIAN_SWITCH(le_header->speex_version_id); + ENDIAN_SWITCH(le_header->header_size); + ENDIAN_SWITCH(le_header->rate); + ENDIAN_SWITCH(le_header->mode); + ENDIAN_SWITCH(le_header->mode_bitstream_version); + ENDIAN_SWITCH(le_header->nb_channels); + ENDIAN_SWITCH(le_header->bitrate); + ENDIAN_SWITCH(le_header->frame_size); + ENDIAN_SWITCH(le_header->vbr); + ENDIAN_SWITCH(le_header->frames_per_packet); + ENDIAN_SWITCH(le_header->extra_headers); + + *size = sizeof(SpeexHeader); + return (char *)le_header; +} + +SpeexHeader *speex_packet_to_header(char *packet, int size) +{ + int i; + SpeexHeader *le_header; + const char *h = "Speex "; + for (i=0;i<8;i++) + if (packet[i]!=h[i]) + { + speex_warning ("This doesn't look like a Speex file"); + return NULL; + } + + /*FIXME: Do we allow larger headers?*/ + if (size < sizeof(SpeexHeader)) + { + speex_warning("Speex header too small"); + return NULL; + } + + le_header = (SpeexHeader*)speex_alloc(sizeof(SpeexHeader)); + + speex_move(le_header, packet, sizeof(SpeexHeader)); + + /*Make sure everything is converted correctly from little-endian*/ + ENDIAN_SWITCH(le_header->speex_version_id); + ENDIAN_SWITCH(le_header->header_size); + ENDIAN_SWITCH(le_header->rate); + ENDIAN_SWITCH(le_header->mode); + ENDIAN_SWITCH(le_header->mode_bitstream_version); + ENDIAN_SWITCH(le_header->nb_channels); + ENDIAN_SWITCH(le_header->bitrate); + ENDIAN_SWITCH(le_header->frame_size); + ENDIAN_SWITCH(le_header->vbr); + ENDIAN_SWITCH(le_header->frames_per_packet); + ENDIAN_SWITCH(le_header->extra_headers); + + return le_header; + +} diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/stack_alloc.h b/mozilla/zap/zmk/speex-1.1.10/libspeex/stack_alloc.h new file mode 100755 index 00000000000..1559c6d077f --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/stack_alloc.h @@ -0,0 +1,79 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: stack_alloc.h + + Temporary memory allocation on stack + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 STACK_ALLOC_H +#define STACK_ALLOC_H + +#ifdef USE_ALLOCA +#include +#endif + +#ifdef ENABLE_VALGRIND + +#include +/*Aligns the stack to a 'size' boundary */ +#define ALIGN(stack, size) ((stack) += ((size) - (long)(stack)) & ((size) - 1)) + +/* Allocates 'size' elements of type 'type' on the stack */ +#define PUSH(stack, size, type) (VALGRIND_MAKE_NOACCESS(stack, 1000),ALIGN((stack),sizeof(type)),VALGRIND_MAKE_WRITABLE(stack, ((size)*sizeof(type))),(stack)+=((size)*sizeof(type)),(type*)((stack)-((size)*sizeof(type)))) + +/* Allocates a struct stack */ +#define PUSHS(stack, type) (VALGRIND_MAKE_NOACCESS(stack, 1000),ALIGN((stack),sizeof(long)),VALGRIND_MAKE_WRITABLE(stack, (sizeof(type))),(stack)+=(sizeof(type)),(type*)((stack)-(sizeof(type)))) + +#else + + +/*Aligns the stack to a 'size' boundary */ +#define ALIGN(stack, size) ((stack) += ((size) - (long)(stack)) & ((size) - 1)) + +/* Allocates 'size' elements of type 'type' on the stack */ +#define PUSH(stack, size, type) (ALIGN((stack),sizeof(type)),(stack)+=((size)*sizeof(type)),(type*)((stack)-((size)*sizeof(type)))) + +/* Allocates a struct stack */ +#define PUSHS(stack, type) (ALIGN((stack),sizeof(long)),(stack)+=(sizeof(type)),(type*)((stack)-(sizeof(type)))) + +#endif + +#if defined(VAR_ARRAYS) +#define VARDECL(var) +#define ALLOC(var, size, type) type var[size] +#elif defined(USE_ALLOCA) +#define VARDECL(var) var +#define ALLOC(var, size, type) var = alloca(sizeof(type)*size) +#else +#define VARDECL(var) var +#define ALLOC(var, size, type) var = PUSH(stack, size, type) +#endif + + +#endif diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/stereo.c b/mozilla/zap/zmk/speex-1.1.10/libspeex/stereo.c new file mode 100755 index 00000000000..d49339de673 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/stereo.c @@ -0,0 +1,192 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: stereo.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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 +#include +#include "vq.h" +#include + +/*float e_ratio_quant[4] = {1, 1.26, 1.587, 2};*/ +static const float e_ratio_quant[4] = {.25f, .315f, .397f, .5f}; + +void speex_encode_stereo(float *data, int frame_size, SpeexBits *bits) +{ + int i, tmp; + float e_left=0, e_right=0, e_tot=0; + float balance, e_ratio; + for (i=0;i0) + speex_bits_pack(bits, 0, 1); + else + speex_bits_pack(bits, 1, 1); + balance=floor(.5+fabs(balance)); + if (balance>30) + balance=31; + + speex_bits_pack(bits, (int)balance, 5); + + /*Quantize energy ratio*/ + tmp=vq_index(&e_ratio, e_ratio_quant, 1, 4); + speex_bits_pack(bits, tmp, 2); +} + +void speex_encode_stereo_int(spx_int16_t *data, int frame_size, SpeexBits *bits) +{ + int i, tmp; + float e_left=0, e_right=0, e_tot=0; + float balance, e_ratio; + for (i=0;i0) + speex_bits_pack(bits, 0, 1); + else + speex_bits_pack(bits, 1, 1); + balance=floor(.5+fabs(balance)); + if (balance>30) + balance=31; + + speex_bits_pack(bits, (int)balance, 5); + + /*Quantize energy ratio*/ + tmp=vq_index(&e_ratio, e_ratio_quant, 1, 4); + speex_bits_pack(bits, tmp, 2); +} + +void speex_decode_stereo(float *data, int frame_size, SpeexStereoState *stereo) +{ + float balance, e_ratio; + int i; + float e_tot=0, e_left, e_right, e_sum; + + balance=stereo->balance; + e_ratio=stereo->e_ratio; + for (i=frame_size-1;i>=0;i--) + { + e_tot += ((float)data[i])*data[i]; + } + e_sum=e_tot/e_ratio; + e_left = e_sum*balance / (1+balance); + e_right = e_sum-e_left; + + e_left = sqrt(e_left/(e_tot+.01)); + e_right = sqrt(e_right/(e_tot+.01)); + + for (i=frame_size-1;i>=0;i--) + { + float ftmp=data[i]; + stereo->smooth_left = .98*stereo->smooth_left + .02*e_left; + stereo->smooth_right = .98*stereo->smooth_right + .02*e_right; + data[2*i] = stereo->smooth_left*ftmp; + data[2*i+1] = stereo->smooth_right*ftmp; + } +} + +void speex_decode_stereo_int(spx_int16_t *data, int frame_size, SpeexStereoState *stereo) +{ + float balance, e_ratio; + int i; + float e_tot=0, e_left, e_right, e_sum; + + balance=stereo->balance; + e_ratio=stereo->e_ratio; + for (i=frame_size-1;i>=0;i--) + { + e_tot += ((float)data[i])*data[i]; + } + e_sum=e_tot/e_ratio; + e_left = e_sum*balance / (1+balance); + e_right = e_sum-e_left; + + e_left = sqrt(e_left/(e_tot+.01)); + e_right = sqrt(e_right/(e_tot+.01)); + + for (i=frame_size-1;i>=0;i--) + { + float ftmp=data[i]; + stereo->smooth_left = .98*stereo->smooth_left + .02*e_left; + stereo->smooth_right = .98*stereo->smooth_right + .02*e_right; + data[2*i] = stereo->smooth_left*ftmp; + data[2*i+1] = stereo->smooth_right*ftmp; + } +} + +int speex_std_stereo_request_handler(SpeexBits *bits, void *state, void *data) +{ + SpeexStereoState *stereo; + float sign=1; + int tmp; + + stereo = (SpeexStereoState*)data; + if (speex_bits_unpack_unsigned(bits, 1)) + sign=-1; + tmp = speex_bits_unpack_unsigned(bits, 5); + stereo->balance = exp(sign*.25*tmp); + + tmp = speex_bits_unpack_unsigned(bits, 2); + stereo->e_ratio = e_ratio_quant[tmp]; + + return 0; +} diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/testdenoise.c b/mozilla/zap/zmk/speex-1.1.10/libspeex/testdenoise.c new file mode 100755 index 00000000000..3fc4d62a75c --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/testdenoise.c @@ -0,0 +1,44 @@ +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include + +#define NN 160 + +int main() +{ + short in[NN]; + int i; + SpeexPreprocessState *st; + int count=0; + float f; + + st = speex_preprocess_state_init(NN, 8000); + i=1; + speex_preprocess_ctl(st, SPEEX_PREPROCESS_SET_DENOISE, &i); + i=0; + speex_preprocess_ctl(st, SPEEX_PREPROCESS_SET_AGC, &i); + f=8000; + speex_preprocess_ctl(st, SPEEX_PREPROCESS_SET_AGC_LEVEL, &f); + i=0; + speex_preprocess_ctl(st, SPEEX_PREPROCESS_SET_DEREVERB, &i); + f=.4; + speex_preprocess_ctl(st, SPEEX_PREPROCESS_SET_DEREVERB_DECAY, &f); + f=.3; + speex_preprocess_ctl(st, SPEEX_PREPROCESS_SET_DEREVERB_LEVEL, &f); + while (1) + { + int vad; + fread(in, sizeof(short), NN, stdin); + if (feof(stdin)) + break; + vad = speex_preprocess(st, in, NULL); + /*fprintf (stderr, "%d\n", vad);*/ + fwrite(in, sizeof(short), NN, stdout); + count++; + } + speex_preprocess_state_destroy(st); + return 0; +} diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/testecho.c b/mozilla/zap/zmk/speex-1.1.10/libspeex/testecho.c new file mode 100755 index 00000000000..7c466bfe404 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/testecho.c @@ -0,0 +1,50 @@ +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include +#include +#include +#include +#include +#include "speex/speex_echo.h" +#include "speex/speex_preprocess.h" + + +#define NN 160 + +int main(int argc, char **argv) +{ + int echo_fd, ref_fd, e_fd; + float noise[NN+1]; + short echo_buf[NN], ref_buf[NN], e_buf[NN]; + SpeexEchoState *st; + SpeexPreprocessState *den; + + if (argc != 4) + { + fprintf (stderr, "testecho mic_signal.sw speaker_signal.sw output.sw\n"); + exit(1); + } + echo_fd = open (argv[2], O_RDONLY); + ref_fd = open (argv[1], O_RDONLY); + e_fd = open (argv[3], O_WRONLY | O_CREAT | O_TRUNC, 0644); + + st = speex_echo_state_init(NN, 8*NN); + den = speex_preprocess_state_init(NN, 8000); + + while (read(ref_fd, ref_buf, NN*2)) + { + read(echo_fd, echo_buf, NN*2); + speex_echo_cancel(st, ref_buf, echo_buf, e_buf, noise); + speex_preprocess(den, e_buf, noise); + write(e_fd, e_buf, NN*2); + } + speex_echo_state_destroy(st); + speex_preprocess_state_destroy(den); + close(e_fd); + close(echo_fd); + close(ref_fd); + return 0; +} diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/testenc.c b/mozilla/zap/zmk/speex-1.1.10/libspeex/testenc.c new file mode 100755 index 00000000000..dcd25c2655a --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/testenc.c @@ -0,0 +1,134 @@ +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include +#include +#include + +#ifdef FIXED_DEBUG +extern long long spx_mips; +#endif + +#define FRAME_SIZE 160 +#include +int main(int argc, char **argv) +{ + char *inFile, *outFile, *bitsFile; + FILE *fin, *fout, *fbits=NULL; + short in_short[FRAME_SIZE]; + short out_short[FRAME_SIZE]; + float sigpow,errpow,snr, seg_snr=0; + int snr_frames = 0; + char cbits[200]; + int nbBits; + int i; + void *st; + void *dec; + SpeexBits bits; + int tmp; + int bitCount=0; + int skip_group_delay; + SpeexCallback callback; + + sigpow = 0; + errpow = 0; + + st = speex_encoder_init(&speex_nb_mode); + dec = speex_decoder_init(&speex_nb_mode); + + callback.callback_id = SPEEX_INBAND_CHAR; + callback.func = speex_std_char_handler; + callback.data = stderr; + speex_decoder_ctl(dec, SPEEX_SET_HANDLER, &callback); + + callback.callback_id = SPEEX_INBAND_MODE_REQUEST; + callback.func = speex_std_mode_request_handler; + callback.data = st; + speex_decoder_ctl(dec, SPEEX_SET_HANDLER, &callback); + + tmp=0; + speex_decoder_ctl(dec, SPEEX_SET_ENH, &tmp); + tmp=0; + speex_encoder_ctl(st, SPEEX_SET_VBR, &tmp); + tmp=8; + speex_encoder_ctl(st, SPEEX_SET_QUALITY, &tmp); + tmp=1; + speex_encoder_ctl(st, SPEEX_SET_COMPLEXITY, &tmp); + + speex_mode_query(&speex_nb_mode, SPEEX_MODE_FRAME_SIZE, &tmp); + fprintf (stderr, "frame size: %d\n", tmp); + skip_group_delay = tmp / 2; + + if (argc != 4 && argc != 3) + { + fprintf (stderr, "Usage: encode [in file] [out file] [bits file]\nargc = %d", argc); + exit(1); + } + inFile = argv[1]; + fin = fopen(inFile, "r"); + outFile = argv[2]; + fout = fopen(outFile, "w+"); + if (argc==4) + { + bitsFile = argv[3]; + fbits = fopen(bitsFile, "w"); + } + speex_bits_init(&bits); + while (!feof(fin)) + { + fread(in_short, sizeof(short), FRAME_SIZE, fin); + if (feof(fin)) + break; + speex_bits_reset(&bits); + + speex_encode_int(st, in_short, &bits); + nbBits = speex_bits_write(&bits, cbits, 200); + bitCount+=bits.nbBits; + + if (argc==4) + fwrite(cbits, 1, nbBits, fbits); + speex_bits_rewind(&bits); + + speex_decode_int(dec, &bits, out_short); + speex_bits_reset(&bits); + + fwrite(&out_short[skip_group_delay], sizeof(short), FRAME_SIZE-skip_group_delay, fout); + skip_group_delay = 0; + } + fprintf (stderr, "Total encoded size: %d bits\n", bitCount); + speex_encoder_destroy(st); + speex_decoder_destroy(dec); + speex_bits_destroy(&bits); + + rewind(fin); + rewind(fout); + + while ( FRAME_SIZE == fread(in_short, sizeof(short), FRAME_SIZE, fin) + && + FRAME_SIZE == fread(out_short, sizeof(short), FRAME_SIZE,fout) ) + { + float s=0, e=0; + for (i=0;i +#include +#include +#include + +#ifdef FIXED_DEBUG +extern long long spx_mips; +#endif + +#define FRAME_SIZE 640 +#include +int main(int argc, char **argv) +{ + char *inFile, *outFile, *bitsFile; + FILE *fin, *fout, *fbits=NULL; + short in_short[FRAME_SIZE]; + short out_short[FRAME_SIZE]; + float in_float[FRAME_SIZE]; + float sigpow,errpow,snr, seg_snr=0; + int snr_frames = 0; + char cbits[200]; + int nbBits; + int i; + void *st; + void *dec; + SpeexBits bits; + int tmp; + int bitCount=0; + int skip_group_delay; + SpeexCallback callback; + + sigpow = 0; + errpow = 0; + + st = speex_encoder_init(&speex_uwb_mode); + dec = speex_decoder_init(&speex_uwb_mode); + + callback.callback_id = SPEEX_INBAND_CHAR; + callback.func = speex_std_char_handler; + callback.data = stderr; + speex_decoder_ctl(dec, SPEEX_SET_HANDLER, &callback); + + callback.callback_id = SPEEX_INBAND_MODE_REQUEST; + callback.func = speex_std_mode_request_handler; + callback.data = st; + speex_decoder_ctl(dec, SPEEX_SET_HANDLER, &callback); + + tmp=0; + speex_decoder_ctl(dec, SPEEX_SET_ENH, &tmp); + tmp=0; + speex_encoder_ctl(st, SPEEX_SET_VBR, &tmp); + tmp=7; + speex_encoder_ctl(st, SPEEX_SET_QUALITY, &tmp); + tmp=1; + speex_encoder_ctl(st, SPEEX_SET_COMPLEXITY, &tmp); + + speex_mode_query(&speex_nb_mode, SPEEX_MODE_FRAME_SIZE, &tmp); + fprintf (stderr, "frame size: %d\n", tmp); + skip_group_delay = 509; + + if (argc != 4 && argc != 3) + { + fprintf (stderr, "Usage: encode [in file] [out file] [bits file]\nargc = %d", argc); + exit(1); + } + inFile = argv[1]; + fin = fopen(inFile, "r"); + outFile = argv[2]; + fout = fopen(outFile, "w+"); + if (argc==4) + { + bitsFile = argv[3]; + fbits = fopen(bitsFile, "w"); + } + speex_bits_init(&bits); + while (!feof(fin)) + { + fread(in_short, sizeof(short), FRAME_SIZE, fin); + if (feof(fin)) + break; + for (i=0;i +#include +#include +#include + +#ifdef FIXED_DEBUG +extern long long spx_mips; +#endif + +#define FRAME_SIZE 320 +#include +int main(int argc, char **argv) +{ + char *inFile, *outFile, *bitsFile; + FILE *fin, *fout, *fbits=NULL; + short in_short[FRAME_SIZE]; + short out_short[FRAME_SIZE]; + float in_float[FRAME_SIZE]; + float sigpow,errpow,snr, seg_snr=0; + int snr_frames = 0; + char cbits[200]; + int nbBits; + int i; + void *st; + void *dec; + SpeexBits bits; + int tmp; + int bitCount=0; + int skip_group_delay; + SpeexCallback callback; + + sigpow = 0; + errpow = 0; + + st = speex_encoder_init(&speex_wb_mode); + dec = speex_decoder_init(&speex_wb_mode); + + callback.callback_id = SPEEX_INBAND_CHAR; + callback.func = speex_std_char_handler; + callback.data = stderr; + speex_decoder_ctl(dec, SPEEX_SET_HANDLER, &callback); + + callback.callback_id = SPEEX_INBAND_MODE_REQUEST; + callback.func = speex_std_mode_request_handler; + callback.data = st; + speex_decoder_ctl(dec, SPEEX_SET_HANDLER, &callback); + + tmp=0; + speex_decoder_ctl(dec, SPEEX_SET_ENH, &tmp); + tmp=0; + speex_encoder_ctl(st, SPEEX_SET_VBR, &tmp); + tmp=8; + speex_encoder_ctl(st, SPEEX_SET_QUALITY, &tmp); + tmp=2; + speex_encoder_ctl(st, SPEEX_SET_COMPLEXITY, &tmp); + tmp=3; + speex_encoder_ctl(st, SPEEX_SET_HIGH_MODE, &tmp); + tmp=6; + speex_encoder_ctl(st, SPEEX_SET_LOW_MODE, &tmp); + + + speex_mode_query(&speex_wb_mode, SPEEX_MODE_FRAME_SIZE, &tmp); + fprintf (stderr, "frame size: %d\n", tmp); + skip_group_delay = 223; + + if (argc != 4 && argc != 3) + { + fprintf (stderr, "Usage: encode [in file] [out file] [bits file]\nargc = %d", argc); + exit(1); + } + inFile = argv[1]; + fin = fopen(inFile, "r"); + outFile = argv[2]; + fout = fopen(outFile, "w+"); + if (argc==4) + { + bitsFile = argv[3]; + fbits = fopen(bitsFile, "w"); + } + speex_bits_init(&bits); + while (!feof(fin)) + { + fread(in_short, sizeof(short), FRAME_SIZE, fin); + if (feof(fin)) + break; + for (i=0;i + + +#define sqr(x) ((x)*(x)) + +#define MIN_ENERGY 6000 +#define NOISE_POW .3 + + +const float vbr_nb_thresh[9][11]={ + {-1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0}, /* CNG */ + { 3.5, 2.5, 2.0, 1.2, 0.5, 0.0, -0.5, -0.7, -0.8, -0.9, -1.0}, /* 2 kbps */ + {10.0, 6.5, 5.2, 4.5, 3.9, 3.5, 3.0, 2.5, 2.3, 1.8, 1.0}, /* 6 kbps */ + {11.0, 8.8, 7.5, 6.5, 5.0, 3.9, 3.9, 3.9, 3.5, 3.0, 1.0}, /* 8 kbps */ + {11.0, 11.0, 9.9, 9.0, 8.0, 7.0, 6.5, 6.0, 5.0, 4.0, 2.0}, /* 11 kbps */ + {11.0, 11.0, 11.0, 11.0, 9.5, 9.0, 8.0, 7.0, 6.5, 5.0, 3.0}, /* 15 kbps */ + {11.0, 11.0, 11.0, 11.0, 11.0, 11.0, 9.5, 8.5, 8.0, 6.5, 4.0}, /* 18 kbps */ + {11.0, 11.0, 11.0, 11.0, 11.0, 11.0, 11.0, 11.0, 9.8, 7.5, 5.5}, /* 24 kbps */ + { 8.0, 5.0, 3.7, 3.0, 2.5, 2.0, 1.8, 1.5, 1.0, 0.0, 0.0} /* 4 kbps */ +}; + + +const float vbr_hb_thresh[5][11]={ + {-1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0}, /* silence */ + {-1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0}, /* 2 kbps */ + {11.0, 11.0, 9.5, 8.5, 7.5, 6.0, 5.0, 3.9, 3.0, 2.0, 1.0}, /* 6 kbps */ + {11.0, 11.0, 11.0, 11.0, 11.0, 9.5, 8.7, 7.8, 7.0, 6.5, 4.0}, /* 10 kbps */ + {11.0, 11.0, 11.0, 11.0, 11.0, 11.0, 11.0, 11.0, 9.8, 7.5, 5.5} /* 18 kbps */ +}; + +const float vbr_uhb_thresh[2][11]={ + {-1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0}, /* silence */ + { 3.9, 2.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0} /* 2 kbps */ +}; + +void vbr_init(VBRState *vbr) +{ + int i; + + vbr->average_energy=0; + vbr->last_energy=1; + vbr->accum_sum=0; + vbr->energy_alpha=.1; + vbr->soft_pitch=0; + vbr->last_pitch_coef=0; + vbr->last_quality=0; + + vbr->noise_accum = .05*pow(MIN_ENERGY, NOISE_POW); + vbr->noise_accum_count=.05; + vbr->noise_level=vbr->noise_accum/vbr->noise_accum_count; + vbr->consec_noise=0; + + + for (i=0;ilast_log_energy[i] = log(MIN_ENERGY); +} + + +/* + This function should analyse the signal and decide how critical the + coding error will be perceptually. The following factors should be + taken into account: + + -Attacks (positive energy derivative) should be coded with more bits + + -Stationary voiced segments should receive more bits + + -Segments with (very) low absolute energy should receive less bits (maybe + only shaped noise?) + + -DTX for near-zero energy? + + -Stationary fricative segments should have less bits + + -Temporal masking: when energy slope is decreasing, decrease the bit-rate + + -Decrease bit-rate for males (low pitch)? + + -(wideband only) less bits in the high-band when signal is very + non-stationary (harder to notice high-frequency noise)??? + +*/ + +float vbr_analysis(VBRState *vbr, spx_word16_t *sig, int len, int pitch, float pitch_coef) +{ + int i; + float ener=0, ener1=0, ener2=0; + float qual=7; + int va; + float log_energy; + float non_st=0; + float voicing; + float pow_ener; + + for (i=0;i>1;i++) + ener1 += ((float)sig[i])*sig[i]; + + for (i=len>>1;ilast_log_energy[i]); + non_st = non_st/(30*VBR_MEMORY_SIZE); + if (non_st>1) + non_st=1; + + voicing = 3*(pitch_coef-.4)*fabs(pitch_coef-.4); + vbr->average_energy = (1-vbr->energy_alpha)*vbr->average_energy + vbr->energy_alpha*ener; + vbr->noise_level=vbr->noise_accum/vbr->noise_accum_count; + pow_ener = pow(ener,NOISE_POW); + if (vbr->noise_accum_count<.06 && ener>MIN_ENERGY) + vbr->noise_accum = .05*pow_ener; + + if ((voicing<.3 && non_st < .2 && pow_ener < 1.2*vbr->noise_level) + || (voicing<.3 && non_st < .05 && pow_ener < 1.5*vbr->noise_level) + || (voicing<.4 && non_st < .05 && pow_ener < 1.2*vbr->noise_level) + || (voicing<0 && non_st < .05)) + { + float tmp; + va = 0; + vbr->consec_noise++; + if (pow_ener > 3*vbr->noise_level) + tmp = 3*vbr->noise_level; + else + tmp = pow_ener; + if (vbr->consec_noise>=4) + { + vbr->noise_accum = .95*vbr->noise_accum + .05*tmp; + vbr->noise_accum_count = .95*vbr->noise_accum_count + .05; + } + } else { + va = 1; + vbr->consec_noise=0; + } + + if (pow_ener < vbr->noise_level && ener>MIN_ENERGY) + { + vbr->noise_accum = .95*vbr->noise_accum + .05*pow_ener; + vbr->noise_accum_count = .95*vbr->noise_accum_count + .05; + } + + /* Checking for very low absolute energy */ + if (ener < 30000) + { + qual -= .7; + if (ener < 10000) + qual-=.7; + if (ener < 3000) + qual-=.7; + } else { + float short_diff, long_diff; + short_diff = log((ener+1)/(1+vbr->last_energy)); + long_diff = log((ener+1)/(1+vbr->average_energy)); + /*fprintf (stderr, "%f %f\n", short_diff, long_diff);*/ + + if (long_diff<-5) + long_diff=-5; + if (long_diff>2) + long_diff=2; + + if (long_diff>0) + qual += .6*long_diff; + if (long_diff<0) + qual += .5*long_diff; + if (short_diff>0) + { + if (short_diff>5) + short_diff=5; + qual += .5*short_diff; + } + /* Checking for energy increases */ + if (ener2 > 1.6*ener1) + qual += .5; + } + vbr->last_energy = ener; + vbr->soft_pitch = .6*vbr->soft_pitch + .4*pitch_coef; + qual += 2.2*((pitch_coef-.4) + (vbr->soft_pitch-.4)); + + if (qual < vbr->last_quality) + qual = .5*qual + .5*vbr->last_quality; + if (qual<4) + qual=4; + if (qual>10) + qual=10; + + /* + if (vbr->consec_noise>=2) + qual-=1.3; + if (vbr->consec_noise>=5) + qual-=1.3; + if (vbr->consec_noise>=12) + qual-=1.3; + */ + if (vbr->consec_noise>=3) + qual=4; + + if (vbr->consec_noise) + qual -= 1.0 * (log(3.0 + vbr->consec_noise)-log(3)); + if (qual<0) + qual=0; + + if (ener<60000) + { + if (vbr->consec_noise>2) + qual-=0.5*(log(3.0 + vbr->consec_noise)-log(3)); + if (ener<10000&&vbr->consec_noise>2) + qual-=0.5*(log(3.0 + vbr->consec_noise)-log(3)); + if (qual<0) + qual=0; + qual += .3*log(ener/60000.0); + } + if (qual<-1) + qual=-1; + + /*printf ("%f %f %f %f %d\n", qual, voicing, non_st, pow_ener/(.01+vbr->noise_level), va);*/ + + vbr->last_pitch_coef = pitch_coef; + vbr->last_quality = qual; + + for (i=VBR_MEMORY_SIZE-1;i>0;i--) + vbr->last_log_energy[i] = vbr->last_log_energy[i-1]; + vbr->last_log_energy[0] = log_energy; + + /*printf ("VBR: %f %f %f %d %f\n", (float)(log_energy-log(vbr->average_energy+MIN_ENERGY)), non_st, voicing, va, vbr->noise_level);*/ + + return qual; +} + +void vbr_destroy(VBRState *vbr) +{ +} diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/vbr.h b/mozilla/zap/zmk/speex-1.1.10/libspeex/vbr.h new file mode 100755 index 00000000000..657b42db1de --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/vbr.h @@ -0,0 +1,68 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: vbr.h + + VBR-related routines + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 VBR_H +#define VBR_H + +#include "misc.h" + +#define VBR_MEMORY_SIZE 5 + +extern const float vbr_nb_thresh[9][11]; +extern const float vbr_hb_thresh[5][11]; +extern const float vbr_uhb_thresh[2][11]; + +typedef struct VBRState { + float energy_alpha; + float average_energy; + float last_energy; + float last_log_energy[VBR_MEMORY_SIZE]; + float accum_sum; + float last_pitch_coef; + float soft_pitch; + float last_quality; + float noise_level; + float noise_accum; + float noise_accum_count; + int consec_noise; +} VBRState; + +void vbr_init(VBRState *vbr); + +float vbr_analysis(VBRState *vbr, spx_word16_t *sig, int len, int pitch, float pitch_coef); + +void vbr_destroy(VBRState *vbr); + +#endif diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/vq.c b/mozilla/zap/zmk/speex-1.1.10/libspeex/vq.c new file mode 100755 index 00000000000..f9b980be069 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/vq.c @@ -0,0 +1,169 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: vq.c + Vector quantization + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 "vq.h" +#include "stack_alloc.h" +#include "misc.h" + +#ifdef _USE_SSE +#include +#elif defined(SHORTCUTS) && (defined(ARM4_ASM) || defined(ARM5E_ASM)) +#include "vq_arm4.h" +#elif defined(BFIN_ASM) +#include "vq_bfin.h" +#endif + + +int scal_quant(spx_word16_t in, const spx_word16_t *boundary, int entries) +{ + int i=0; + while (iboundary[0]) + { + boundary++; + i++; + } + return i; +} + +int scal_quant32(spx_word32_t in, const spx_word32_t *boundary, int entries) +{ + int i=0; + while (iboundary[0]) + { + boundary++; + i++; + } + return i; +} + +/*Finds the index of the entry in a codebook that best matches the input*/ +int vq_index(float *in, const float *codebook, int len, int entries) +{ + int i,j; + float min_dist=0; + int best_index=0; + for (i=0;i= 1) && (k > used || dist < best_dist[k-1]); k--) + { + best_dist[k]=best_dist[k-1]; + nbest[k] = nbest[k-1]; + } + best_dist[k]=dist; + nbest[k]=i; + used++; + } + } +} +#endif + + + + +#ifndef OVERRIDE_VQ_NBEST_SIGN +/*Finds the indices of the n-best entries in a codebook with sign*/ +void vq_nbest_sign(spx_word16_t *in, const spx_word16_t *codebook, int len, int entries, spx_word32_t *E, int N, int *nbest, spx_word32_t *best_dist, char *stack) +{ + int i,j,k, sign, used; + used=0; + for (i=0;i0) + { + sign=0; + dist=-dist; + } else + { + sign=1; + } +#ifdef FIXED_POINT + dist = ADD32(dist,SHR32(E[i],1)); +#else + dist = ADD32(dist,.5f*E[i]); +#endif + if (i= 1) && (k > used || dist < best_dist[k-1]); k--) + { + best_dist[k]=best_dist[k-1]; + nbest[k] = nbest[k-1]; + } + best_dist[k]=dist; + nbest[k]=i; + used++; + if (sign) + nbest[k]+=entries; + } + } +} +#endif diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/vq.h b/mozilla/zap/zmk/speex-1.1.10/libspeex/vq.h new file mode 100755 index 00000000000..0b1fb407051 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/vq.h @@ -0,0 +1,53 @@ +/* Copyright (C) 2002 Jean-Marc Valin + File: vq.h + Vector quantization + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 VQ_H +#define VQ_H + +#include "misc.h" + +int scal_quant(spx_word16_t in, const spx_word16_t *boundary, int entries); +int scal_quant32(spx_word32_t in, const spx_word32_t *boundary, int entries); + +int vq_index(float *in, const float *codebook, int len, int entries); +#ifdef _USE_SSE +#include +void vq_nbest(spx_word16_t *in, const __m128 *codebook, int len, int entries, __m128 *E, int N, int *nbest, spx_word32_t *best_dist, char *stack); + +void vq_nbest_sign(spx_word16_t *in, const __m128 *codebook, int len, int entries, __m128 *E, int N, int *nbest, spx_word32_t *best_dist, char *stack); +#else +void vq_nbest(spx_word16_t *in, const spx_word16_t *codebook, int len, int entries, spx_word32_t *E, int N, int *nbest, spx_word32_t *best_dist, char *stack); + +void vq_nbest_sign(spx_word16_t *in, const spx_word16_t *codebook, int len, int entries, spx_word32_t *E, int N, int *nbest, spx_word32_t *best_dist, char *stack); +#endif + +#endif diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/vq_arm4.h b/mozilla/zap/zmk/speex-1.1.10/libspeex/vq_arm4.h new file mode 100755 index 00000000000..be3e117a390 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/vq_arm4.h @@ -0,0 +1,113 @@ +/* Copyright (C) 2004 Jean-Marc Valin + File: vq_arm4.h + ARM4-optimized vq routine + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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. +*/ + +#define OVERRIDE_VQ_NBEST +void vq_nbest(spx_word16_t *in, const spx_word16_t *codebook, int len, int entries, spx_word32_t *E, int N, int *nbest, spx_word32_t *best_dist, char *stack) +{ + int i,j; + for (i=0;i>= 1;\n\t" + "A0 = %0;\n\t" + "R0.L = W[%1++%7] || R1.L = W[I0++];\n\t" + "LOOP vq_loop%= LC1 = %5;\n\t" + "LOOP_BEGIN vq_loop%=;\n\t" + "%0 = (A0 -= R0.L*R1.L) (IS) || R0.L = W[%1++%7] || R1.L = W[I0++];\n\t" + "LOOP_END vq_loop%=;\n\t" + "%0 = (A0 -= R0.L*R1.L) (IS);\n\t" + "cc = %0 < %2;\n\t" + "if cc %2 = %0;\n\t" + "if cc %3 = R2;\n\t" + "R2 += 1;\n\t" + "LOOP_END entries_loop%=;\n\t" + : "=&D" (dist), "=&a" (codebook), "=&d" (best_dist[0]), "=&d" (nbest[0]), "=&a" (E) + : "a" (len-1), "a" (in), "a" (2), "d" (entries), "d" (len<<1), "1" (codebook), "4" (E), "2" (best_dist[0]), "3" (nbest[0]) + : "R0", "R1", "R2", "I0", "L0", "B0", "A0", "cc", "memory" + ); + } + } else { + int i,k,used; + used = 0; + for (i=0;i>= 1;\n\t" + "A0 = %0;\n\t" + "I0 = %3;\n\t" + "L0 = 0;\n\t" + "R0.L = W[%1++%4] || R1.L = W[I0++];\n\t" + "LOOP vq_loop%= LC0 = %2;\n\t" + "LOOP_BEGIN vq_loop%=;\n\t" + "%0 = (A0 -= R0.L*R1.L) (IS) || R0.L = W[%1++%4] || R1.L = W[I0++];\n\t" + "LOOP_END vq_loop%=;\n\t" + "%0 = (A0 -= R0.L*R1.L) (IS);\n\t" + : "=D" (dist), "=a" (codebook) + : "a" (len-1), "a" (in), "a" (2), "1" (codebook), "0" (E[i]) + : "R0", "R1", "I0", "L0", "A0" + ); + if (i= 1) && (k > used || dist < best_dist[k-1]); k--) + { + best_dist[k]=best_dist[k-1]; + nbest[k] = nbest[k-1]; + } + best_dist[k]=dist; + nbest[k]=i; + used++; + } + } + } +} diff --git a/mozilla/zap/zmk/speex-1.1.10/libspeex/vq_sse.h b/mozilla/zap/zmk/speex-1.1.10/libspeex/vq_sse.h new file mode 100755 index 00000000000..96ae632fa87 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/libspeex/vq_sse.h @@ -0,0 +1,118 @@ +/* Copyright (C) 2004 Jean-Marc Valin + File: vq_arm4.h + ARM4-optimized vq routine + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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. +*/ + +#define OVERRIDE_VQ_NBEST +void vq_nbest(spx_word16_t *_in, const __m128 *codebook, int len, int entries, __m128 *E, int N, int *nbest, spx_word32_t *best_dist, char *stack) +{ + int i,j,k,used; + VARDECL(float *dist); + VARDECL(__m128 *in); + __m128 half; + used = 0; + ALLOC(dist, entries, float); + half = _mm_set_ps1(.5f); + ALLOC(in, len, __m128); + for (i=0;i>2;i++) + { + __m128 d = _mm_mul_ps(E[i], half); + for (j=0;j= 1) && (k > used || dist[i] < best_dist[k-1]); k--) + { + best_dist[k]=best_dist[k-1]; + nbest[k] = nbest[k-1]; + } + best_dist[k]=dist[i]; + nbest[k]=i; + used++; + } + } +} + + + + +#define OVERRIDE_VQ_NBEST_SIGN +void vq_nbest_sign(spx_word16_t *_in, const __m128 *codebook, int len, int entries, __m128 *E, int N, int *nbest, spx_word32_t *best_dist, char *stack) +{ + int i,j,k,used; + VARDECL(float *dist); + VARDECL(__m128 *in); + __m128 half; + used = 0; + ALLOC(dist, entries, float); + half = _mm_set_ps1(.5f); + ALLOC(in, len, __m128); + for (i=0;i>2;i++) + { + __m128 d = _mm_setzero_ps(); + for (j=0;j0) + { + sign=0; + dist[i]=-dist[i]; + } else + { + sign=1; + } + dist[i] += .5f*((float*)E)[i]; + if (i= 1) && (k > used || dist[i] < best_dist[k-1]); k--) + { + best_dist[k]=best_dist[k-1]; + nbest[k] = nbest[k-1]; + } + best_dist[k]=dist[i]; + nbest[k]=i; + used++; + if (sign) + nbest[k]+=entries; + } + } +} diff --git a/mozilla/zap/zmk/speex-1.1.10/ltmain.sh b/mozilla/zap/zmk/speex-1.1.10/ltmain.sh new file mode 100755 index 00000000000..279e3687ba7 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/ltmain.sh @@ -0,0 +1,6426 @@ +# ltmain.sh - Provide generalized library-building support services. +# NOTE: Changing this file will not affect anything until you rerun configure. +# +# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004 +# Free Software Foundation, Inc. +# Originally by Gordon Matzigkeit , 1996 +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +# +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + +basename="s,^.*/,,g" + +# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh +# is ksh but when the shell is invoked as "sh" and the current value of +# the _XPG environment variable is not equal to 1 (one), the special +# positional parameter $0, within a function call, is the name of the +# function. +progpath="$0" + +# The name of this program: +progname=`echo "$progpath" | $SED $basename` +modename="$progname" + +# Global variables: +EXIT_SUCCESS=0 +EXIT_FAILURE=1 + +PROGRAM=ltmain.sh +PACKAGE=libtool +VERSION=1.5.6 +TIMESTAMP=" (1.1220.2.95 2004/04/11 05:50:42) Debian$Rev: 224 $" + + +# Check that we have a working $echo. +if test "X$1" = X--no-reexec; then + # Discard the --no-reexec flag, and continue. + shift +elif test "X$1" = X--fallback-echo; then + # Avoid inline document here, it may be left over + : +elif test "X`($echo '\t') 2>/dev/null`" = 'X\t'; then + # Yippee, $echo works! + : +else + # Restart under the correct shell, and then maybe $echo will work. + exec $SHELL "$progpath" --no-reexec ${1+"$@"} +fi + +if test "X$1" = X--fallback-echo; then + # used as fallback echo + shift + cat <&2 + $echo "Fatal configuration error. See the $PACKAGE docs for more information." 1>&2 + exit $EXIT_FAILURE +fi + +# Global variables. +mode=$default_mode +nonopt= +prev= +prevopt= +run= +show="$echo" +show_help= +execute_dlfiles= +lo2o="s/\\.lo\$/.${objext}/" +o2lo="s/\\.${objext}\$/.lo/" + +##################################### +# Shell function definitions: +# This seems to be the best place for them + +# func_win32_libid arg +# return the library type of file 'arg' +# +# Need a lot of goo to handle *both* DLLs and import libs +# Has to be a shell function in order to 'eat' the argument +# that is supplied when $file_magic_command is called. +func_win32_libid () { + win32_libid_type="unknown" + win32_fileres=`file -L $1 2>/dev/null` + case $win32_fileres in + *ar\ archive\ import\ library*) # definitely import + win32_libid_type="x86 archive import" + ;; + *ar\ archive*) # could be an import, or static + if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null | \ + $EGREP -e 'file format pe-i386(.*architecture: i386)?' >/dev/null ; then + win32_nmres=`eval $NM -f posix -A $1 | \ + sed -n -e '1,100{/ I /{x;/import/!{s/^/import/;h;p;};x;};}'` + if test "X$win32_nmres" = "Ximport" ; then + win32_libid_type="x86 archive import" + else + win32_libid_type="x86 archive static" + fi + fi + ;; + *DLL*) + win32_libid_type="x86 DLL" + ;; + *executable*) # but shell scripts are "executable" too... + case $win32_fileres in + *MS\ Windows\ PE\ Intel*) + win32_libid_type="x86 DLL" + ;; + esac + ;; + esac + $echo $win32_libid_type +} + + +# func_infer_tag arg +# Infer tagged configuration to use if any are available and +# if one wasn't chosen via the "--tag" command line option. +# Only attempt this if the compiler in the base compile +# command doesn't match the default compiler. +# arg is usually of the form 'gcc ...' +func_infer_tag () { + if test -n "$available_tags" && test -z "$tagname"; then + CC_quoted= + for arg in $CC; do + case $arg in + *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") + arg="\"$arg\"" + ;; + esac + CC_quoted="$CC_quoted $arg" + done + case $@ in + # Blanks in the command may have been stripped by the calling shell, + # but not from the CC environment variable when configure was run. + " $CC "* | "$CC "* | " `$echo $CC` "* | "`$echo $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$echo $CC_quoted` "* | "`$echo $CC_quoted` "*) ;; + # Blanks at the start of $base_compile will cause this to fail + # if we don't check for them as well. + *) + for z in $available_tags; do + if grep "^# ### BEGIN LIBTOOL TAG CONFIG: $z$" < "$progpath" > /dev/null; then + # Evaluate the configuration. + eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`" + CC_quoted= + for arg in $CC; do + # Double-quote args containing other shell metacharacters. + case $arg in + *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") + arg="\"$arg\"" + ;; + esac + CC_quoted="$CC_quoted $arg" + done + case "$@ " in + " $CC "* | "$CC "* | " `$echo $CC` "* | "`$echo $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$echo $CC_quoted` "* | "`$echo $CC_quoted` "*) + # The compiler in the base compile command matches + # the one in the tagged configuration. + # Assume this is the tagged configuration we want. + tagname=$z + break + ;; + esac + fi + done + # If $tagname still isn't set, then no tagged configuration + # was found and let the user know that the "--tag" command + # line option must be used. + if test -z "$tagname"; then + $echo "$modename: unable to infer tagged configuration" + $echo "$modename: specify a tag with \`--tag'" 1>&2 + exit $EXIT_FAILURE +# else +# $echo "$modename: using $tagname tagged configuration" + fi + ;; + esac + fi +} +# End of Shell function definitions +##################################### + +# Darwin sucks +eval std_shrext=\"$shrext_cmds\" + +# Parse our command line options once, thoroughly. +while test "$#" -gt 0 +do + arg="$1" + shift + + case $arg in + -*=*) optarg=`$echo "X$arg" | $Xsed -e 's/[-_a-zA-Z0-9]*=//'` ;; + *) optarg= ;; + esac + + # If the previous option needs an argument, assign it. + if test -n "$prev"; then + case $prev in + execute_dlfiles) + execute_dlfiles="$execute_dlfiles $arg" + ;; + tag) + tagname="$arg" + preserve_args="${preserve_args}=$arg" + + # Check whether tagname contains only valid characters + case $tagname in + *[!-_A-Za-z0-9,/]*) + $echo "$progname: invalid tag name: $tagname" 1>&2 + exit $EXIT_FAILURE + ;; + esac + + case $tagname in + CC) + # Don't test for the "default" C tag, as we know, it's there, but + # not specially marked. + ;; + *) + if grep "^# ### BEGIN LIBTOOL TAG CONFIG: $tagname$" < "$progpath" > /dev/null; then + taglist="$taglist $tagname" + # Evaluate the configuration. + eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$tagname'$/,/^# ### END LIBTOOL TAG CONFIG: '$tagname'$/p' < $progpath`" + else + $echo "$progname: ignoring unknown tag $tagname" 1>&2 + fi + ;; + esac + ;; + *) + eval "$prev=\$arg" + ;; + esac + + prev= + prevopt= + continue + fi + + # Have we seen a non-optional argument yet? + case $arg in + --help) + show_help=yes + ;; + + --version) + $echo "$PROGRAM (GNU $PACKAGE) $VERSION$TIMESTAMP" + $echo + $echo "Copyright (C) 2003 Free Software Foundation, Inc." + $echo "This is free software; see the source for copying conditions. There is NO" + $echo "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." + exit $EXIT_SUCCESS + ;; + + --config) + ${SED} -e '1,/^# ### BEGIN LIBTOOL CONFIG/d' -e '/^# ### END LIBTOOL CONFIG/,$d' $progpath + # Now print the configurations for the tags. + for tagname in $taglist; do + ${SED} -n -e "/^# ### BEGIN LIBTOOL TAG CONFIG: $tagname$/,/^# ### END LIBTOOL TAG CONFIG: $tagname$/p" < "$progpath" + done + exit $EXIT_SUCCESS + ;; + + --debug) + $echo "$progname: enabling shell trace mode" + set -x + preserve_args="$preserve_args $arg" + ;; + + --dry-run | -n) + run=: + ;; + + --features) + $echo "host: $host" + if test "$build_libtool_libs" = yes; then + $echo "enable shared libraries" + else + $echo "disable shared libraries" + fi + if test "$build_old_libs" = yes; then + $echo "enable static libraries" + else + $echo "disable static libraries" + fi + exit $EXIT_SUCCESS + ;; + + --finish) mode="finish" ;; + + --mode) prevopt="--mode" prev=mode ;; + --mode=*) mode="$optarg" ;; + + --preserve-dup-deps) duplicate_deps="yes" ;; + + --quiet | --silent) + show=: + preserve_args="$preserve_args $arg" + ;; + + --tag) prevopt="--tag" prev=tag ;; + --tag=*) + set tag "$optarg" ${1+"$@"} + shift + prev=tag + preserve_args="$preserve_args --tag" + ;; + + -dlopen) + prevopt="-dlopen" + prev=execute_dlfiles + ;; + + -*) + $echo "$modename: unrecognized option \`$arg'" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE + ;; + + *) + nonopt="$arg" + break + ;; + esac +done + +if test -n "$prevopt"; then + $echo "$modename: option \`$prevopt' requires an argument" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE +fi + +# If this variable is set in any of the actions, the command in it +# will be execed at the end. This prevents here-documents from being +# left over by shells. +exec_cmd= + +if test -z "$show_help"; then + + # Infer the operation mode. + if test -z "$mode"; then + $echo "*** Warning: inferring the mode of operation is deprecated." 1>&2 + $echo "*** Future versions of Libtool will require -mode=MODE be specified." 1>&2 + case $nonopt in + *cc | cc* | *++ | gcc* | *-gcc* | g++* | xlc*) + mode=link + for arg + do + case $arg in + -c) + mode=compile + break + ;; + esac + done + ;; + *db | *dbx | *strace | *truss) + mode=execute + ;; + *install*|cp|mv) + mode=install + ;; + *rm) + mode=uninstall + ;; + *) + # If we have no mode, but dlfiles were specified, then do execute mode. + test -n "$execute_dlfiles" && mode=execute + + # Just use the default operation mode. + if test -z "$mode"; then + if test -n "$nonopt"; then + $echo "$modename: warning: cannot infer operation mode from \`$nonopt'" 1>&2 + else + $echo "$modename: warning: cannot infer operation mode without MODE-ARGS" 1>&2 + fi + fi + ;; + esac + fi + + # Only execute mode is allowed to have -dlopen flags. + if test -n "$execute_dlfiles" && test "$mode" != execute; then + $echo "$modename: unrecognized option \`-dlopen'" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE + fi + + # Change the help message to a mode-specific one. + generic_help="$help" + help="Try \`$modename --help --mode=$mode' for more information." + + # These modes are in order of execution frequency so that they run quickly. + case $mode in + # libtool compile mode + compile) + modename="$modename: compile" + # Get the compilation command and the source file. + base_compile= + srcfile="$nonopt" # always keep a non-empty value in "srcfile" + suppress_opt=yes + suppress_output= + arg_mode=normal + libobj= + later= + + for arg + do + case "$arg_mode" in + arg ) + # do not "continue". Instead, add this to base_compile + lastarg="$arg" + arg_mode=normal + ;; + + target ) + libobj="$arg" + arg_mode=normal + continue + ;; + + normal ) + # Accept any command-line options. + case $arg in + -o) + if test -n "$libobj" ; then + $echo "$modename: you cannot specify \`-o' more than once" 1>&2 + exit $EXIT_FAILURE + fi + arg_mode=target + continue + ;; + + -static | -prefer-pic | -prefer-non-pic) + later="$later $arg" + continue + ;; + + -no-suppress) + suppress_opt=no + continue + ;; + + -Xcompiler) + arg_mode=arg # the next one goes into the "base_compile" arg list + continue # The current "srcfile" will either be retained or + ;; # replaced later. I would guess that would be a bug. + + -Wc,*) + args=`$echo "X$arg" | $Xsed -e "s/^-Wc,//"` + lastarg= + save_ifs="$IFS"; IFS=',' + for arg in $args; do + IFS="$save_ifs" + + # Double-quote args containing other shell metacharacters. + # Many Bourne shells cannot handle close brackets correctly + # in scan sets, so we specify it separately. + case $arg in + *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") + arg="\"$arg\"" + ;; + esac + lastarg="$lastarg $arg" + done + IFS="$save_ifs" + lastarg=`$echo "X$lastarg" | $Xsed -e "s/^ //"` + + # Add the arguments to base_compile. + base_compile="$base_compile $lastarg" + continue + ;; + + * ) + # Accept the current argument as the source file. + # The previous "srcfile" becomes the current argument. + # + lastarg="$srcfile" + srcfile="$arg" + ;; + esac # case $arg + ;; + esac # case $arg_mode + + # Aesthetically quote the previous argument. + lastarg=`$echo "X$lastarg" | $Xsed -e "$sed_quote_subst"` + + case $lastarg in + # Double-quote args containing other shell metacharacters. + # Many Bourne shells cannot handle close brackets correctly + # in scan sets, so we specify it separately. + *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") + lastarg="\"$lastarg\"" + ;; + esac + + base_compile="$base_compile $lastarg" + done # for arg + + case $arg_mode in + arg) + $echo "$modename: you must specify an argument for -Xcompile" + exit $EXIT_FAILURE + ;; + target) + $echo "$modename: you must specify a target with \`-o'" 1>&2 + exit $EXIT_FAILURE + ;; + *) + # Get the name of the library object. + [ -z "$libobj" ] && libobj=`$echo "X$srcfile" | $Xsed -e 's%^.*/%%'` + ;; + esac + + # Recognize several different file suffixes. + # If the user specifies -o file.o, it is replaced with file.lo + xform='[cCFSifmso]' + case $libobj in + *.ada) xform=ada ;; + *.adb) xform=adb ;; + *.ads) xform=ads ;; + *.asm) xform=asm ;; + *.c++) xform=c++ ;; + *.cc) xform=cc ;; + *.ii) xform=ii ;; + *.class) xform=class ;; + *.cpp) xform=cpp ;; + *.cxx) xform=cxx ;; + *.f90) xform=f90 ;; + *.for) xform=for ;; + *.java) xform=java ;; + esac + + libobj=`$echo "X$libobj" | $Xsed -e "s/\.$xform$/.lo/"` + + case $libobj in + *.lo) obj=`$echo "X$libobj" | $Xsed -e "$lo2o"` ;; + *) + $echo "$modename: cannot determine name of library object from \`$libobj'" 1>&2 + exit $EXIT_FAILURE + ;; + esac + + func_infer_tag $base_compile + + for arg in $later; do + case $arg in + -static) + build_old_libs=yes + continue + ;; + + -prefer-pic) + pic_mode=yes + continue + ;; + + -prefer-non-pic) + pic_mode=no + continue + ;; + esac + done + + objname=`$echo "X$obj" | $Xsed -e 's%^.*/%%'` + xdir=`$echo "X$obj" | $Xsed -e 's%/[^/]*$%%'` + if test "X$xdir" = "X$obj"; then + xdir= + else + xdir=$xdir/ + fi + lobj=${xdir}$objdir/$objname + + if test -z "$base_compile"; then + $echo "$modename: you must specify a compilation command" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE + fi + + # Delete any leftover library objects. + if test "$build_old_libs" = yes; then + removelist="$obj $lobj $libobj ${libobj}T" + else + removelist="$lobj $libobj ${libobj}T" + fi + + $run $rm $removelist + trap "$run $rm $removelist; exit $EXIT_FAILURE" 1 2 15 + + # On Cygwin there's no "real" PIC flag so we must build both object types + case $host_os in + cygwin* | mingw* | pw32* | os2*) + pic_mode=default + ;; + esac + if test "$pic_mode" = no && test "$deplibs_check_method" != pass_all; then + # non-PIC code in shared libraries is not supported + pic_mode=default + fi + + # Calculate the filename of the output object if compiler does + # not support -o with -c + if test "$compiler_c_o" = no; then + output_obj=`$echo "X$srcfile" | $Xsed -e 's%^.*/%%' -e 's%\.[^.]*$%%'`.${objext} + lockfile="$output_obj.lock" + removelist="$removelist $output_obj $lockfile" + trap "$run $rm $removelist; exit $EXIT_FAILURE" 1 2 15 + else + output_obj= + need_locks=no + lockfile= + fi + + # Lock this critical section if it is needed + # We use this script file to make the link, it avoids creating a new file + if test "$need_locks" = yes; then + until $run ln "$progpath" "$lockfile" 2>/dev/null; do + $show "Waiting for $lockfile to be removed" + sleep 2 + done + elif test "$need_locks" = warn; then + if test -f "$lockfile"; then + $echo "\ +*** ERROR, $lockfile exists and contains: +`cat $lockfile 2>/dev/null` + +This indicates that another process is trying to use the same +temporary object file, and libtool could not work around it because +your compiler does not support \`-c' and \`-o' together. If you +repeat this compilation, it may succeed, by chance, but you had better +avoid parallel builds (make -j) in this platform, or get a better +compiler." + + $run $rm $removelist + exit $EXIT_FAILURE + fi + $echo $srcfile > "$lockfile" + fi + + if test -n "$fix_srcfile_path"; then + eval srcfile=\"$fix_srcfile_path\" + fi + + $run $rm "$libobj" "${libobj}T" + + # Create a libtool object file (analogous to a ".la" file), + # but don't create it if we're doing a dry run. + test -z "$run" && cat > ${libobj}T </dev/null`" != "X$srcfile"; then + $echo "\ +*** ERROR, $lockfile contains: +`cat $lockfile 2>/dev/null` + +but it should contain: +$srcfile + +This indicates that another process is trying to use the same +temporary object file, and libtool could not work around it because +your compiler does not support \`-c' and \`-o' together. If you +repeat this compilation, it may succeed, by chance, but you had better +avoid parallel builds (make -j) in this platform, or get a better +compiler." + + $run $rm $removelist + exit $EXIT_FAILURE + fi + + # Just move the object if needed, then go on to compile the next one + if test -n "$output_obj" && test "X$output_obj" != "X$lobj"; then + $show "$mv $output_obj $lobj" + if $run $mv $output_obj $lobj; then : + else + error=$? + $run $rm $removelist + exit $error + fi + fi + + # Append the name of the PIC object to the libtool object file. + test -z "$run" && cat >> ${libobj}T <> ${libobj}T </dev/null`" != "X$srcfile"; then + $echo "\ +*** ERROR, $lockfile contains: +`cat $lockfile 2>/dev/null` + +but it should contain: +$srcfile + +This indicates that another process is trying to use the same +temporary object file, and libtool could not work around it because +your compiler does not support \`-c' and \`-o' together. If you +repeat this compilation, it may succeed, by chance, but you had better +avoid parallel builds (make -j) in this platform, or get a better +compiler." + + $run $rm $removelist + exit $EXIT_FAILURE + fi + + # Just move the object if needed + if test -n "$output_obj" && test "X$output_obj" != "X$obj"; then + $show "$mv $output_obj $obj" + if $run $mv $output_obj $obj; then : + else + error=$? + $run $rm $removelist + exit $error + fi + fi + + # Append the name of the non-PIC object the libtool object file. + # Only append if the libtool object file exists. + test -z "$run" && cat >> ${libobj}T <> ${libobj}T <&2 + fi + if test -n "$link_static_flag"; then + dlopen_self=$dlopen_self_static + fi + else + if test -z "$pic_flag" && test -n "$link_static_flag"; then + dlopen_self=$dlopen_self_static + fi + fi + build_libtool_libs=no + build_old_libs=yes + prefer_static_libs=yes + break + ;; + esac + done + + # See if our shared archives depend on static archives. + test -n "$old_archive_from_new_cmds" && build_old_libs=yes + + # Go through the arguments, transforming them on the way. + while test "$#" -gt 0; do + arg="$1" + shift + case $arg in + *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") + qarg=\"`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`\" ### testsuite: skip nested quoting test + ;; + *) qarg=$arg ;; + esac + libtool_args="$libtool_args $qarg" + + # If the previous option needs an argument, assign it. + if test -n "$prev"; then + case $prev in + output) + compile_command="$compile_command @OUTPUT@" + finalize_command="$finalize_command @OUTPUT@" + ;; + esac + + case $prev in + dlfiles|dlprefiles) + if test "$preload" = no; then + # Add the symbol object into the linking commands. + compile_command="$compile_command @SYMFILE@" + finalize_command="$finalize_command @SYMFILE@" + preload=yes + fi + case $arg in + *.la | *.lo) ;; # We handle these cases below. + force) + if test "$dlself" = no; then + dlself=needless + export_dynamic=yes + fi + prev= + continue + ;; + self) + if test "$prev" = dlprefiles; then + dlself=yes + elif test "$prev" = dlfiles && test "$dlopen_self" != yes; then + dlself=yes + else + dlself=needless + export_dynamic=yes + fi + prev= + continue + ;; + *) + if test "$prev" = dlfiles; then + dlfiles="$dlfiles $arg" + else + dlprefiles="$dlprefiles $arg" + fi + prev= + continue + ;; + esac + ;; + expsyms) + export_symbols="$arg" + if test ! -f "$arg"; then + $echo "$modename: symbol file \`$arg' does not exist" + exit $EXIT_FAILURE + fi + prev= + continue + ;; + expsyms_regex) + export_symbols_regex="$arg" + prev= + continue + ;; + inst_prefix) + inst_prefix_dir="$arg" + prev= + continue + ;; + precious_regex) + precious_files_regex="$arg" + prev= + continue + ;; + release) + release="-$arg" + prev= + continue + ;; + objectlist) + if test -f "$arg"; then + save_arg=$arg + moreargs= + for fil in `cat $save_arg` + do +# moreargs="$moreargs $fil" + arg=$fil + # A libtool-controlled object. + + # Check to see that this really is a libtool object. + if (${SED} -e '2q' $arg | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then + pic_object= + non_pic_object= + + # Read the .lo file + # If there is no directory component, then add one. + case $arg in + */* | *\\*) . $arg ;; + *) . ./$arg ;; + esac + + if test -z "$pic_object" || \ + test -z "$non_pic_object" || + test "$pic_object" = none && \ + test "$non_pic_object" = none; then + $echo "$modename: cannot find name of object for \`$arg'" 1>&2 + exit $EXIT_FAILURE + fi + + # Extract subdirectory from the argument. + xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'` + if test "X$xdir" = "X$arg"; then + xdir= + else + xdir="$xdir/" + fi + + if test "$pic_object" != none; then + # Prepend the subdirectory the object is found in. + pic_object="$xdir$pic_object" + + if test "$prev" = dlfiles; then + if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then + dlfiles="$dlfiles $pic_object" + prev= + continue + else + # If libtool objects are unsupported, then we need to preload. + prev=dlprefiles + fi + fi + + # CHECK ME: I think I busted this. -Ossama + if test "$prev" = dlprefiles; then + # Preload the old-style object. + dlprefiles="$dlprefiles $pic_object" + prev= + fi + + # A PIC object. + libobjs="$libobjs $pic_object" + arg="$pic_object" + fi + + # Non-PIC object. + if test "$non_pic_object" != none; then + # Prepend the subdirectory the object is found in. + non_pic_object="$xdir$non_pic_object" + + # A standard non-PIC object + non_pic_objects="$non_pic_objects $non_pic_object" + if test -z "$pic_object" || test "$pic_object" = none ; then + arg="$non_pic_object" + fi + fi + else + # Only an error if not doing a dry-run. + if test -z "$run"; then + $echo "$modename: \`$arg' is not a valid libtool object" 1>&2 + exit $EXIT_FAILURE + else + # Dry-run case. + + # Extract subdirectory from the argument. + xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'` + if test "X$xdir" = "X$arg"; then + xdir= + else + xdir="$xdir/" + fi + + pic_object=`$echo "X${xdir}${objdir}/${arg}" | $Xsed -e "$lo2o"` + non_pic_object=`$echo "X${xdir}${arg}" | $Xsed -e "$lo2o"` + libobjs="$libobjs $pic_object" + non_pic_objects="$non_pic_objects $non_pic_object" + fi + fi + done + else + $echo "$modename: link input file \`$save_arg' does not exist" + exit $EXIT_FAILURE + fi + arg=$save_arg + prev= + continue + ;; + rpath | xrpath) + # We need an absolute path. + case $arg in + [\\/]* | [A-Za-z]:[\\/]*) ;; + *) + $echo "$modename: only absolute run-paths are allowed" 1>&2 + exit $EXIT_FAILURE + ;; + esac + if test "$prev" = rpath; then + case "$rpath " in + *" $arg "*) ;; + *) rpath="$rpath $arg" ;; + esac + else + case "$xrpath " in + *" $arg "*) ;; + *) xrpath="$xrpath $arg" ;; + esac + fi + prev= + continue + ;; + xcompiler) + compiler_flags="$compiler_flags $qarg" + prev= + compile_command="$compile_command $qarg" + finalize_command="$finalize_command $qarg" + continue + ;; + xlinker) + linker_flags="$linker_flags $qarg" + compiler_flags="$compiler_flags $wl$qarg" + prev= + compile_command="$compile_command $wl$qarg" + finalize_command="$finalize_command $wl$qarg" + continue + ;; + xcclinker) + linker_flags="$linker_flags $qarg" + compiler_flags="$compiler_flags $qarg" + prev= + compile_command="$compile_command $qarg" + finalize_command="$finalize_command $qarg" + continue + ;; + shrext) + shrext_cmds="$arg" + prev= + continue + ;; + *) + eval "$prev=\"\$arg\"" + prev= + continue + ;; + esac + fi # test -n "$prev" + + prevarg="$arg" + + case $arg in + -all-static) + if test -n "$link_static_flag"; then + compile_command="$compile_command $link_static_flag" + finalize_command="$finalize_command $link_static_flag" + fi + continue + ;; + + -allow-undefined) + # FIXME: remove this flag sometime in the future. + $echo "$modename: \`-allow-undefined' is deprecated because it is the default" 1>&2 + continue + ;; + + -avoid-version) + avoid_version=yes + continue + ;; + + -dlopen) + prev=dlfiles + continue + ;; + + -dlpreopen) + prev=dlprefiles + continue + ;; + + -export-dynamic) + export_dynamic=yes + continue + ;; + + -export-symbols | -export-symbols-regex) + if test -n "$export_symbols" || test -n "$export_symbols_regex"; then + $echo "$modename: more than one -exported-symbols argument is not allowed" + exit $EXIT_FAILURE + fi + if test "X$arg" = "X-export-symbols"; then + prev=expsyms + else + prev=expsyms_regex + fi + continue + ;; + + -inst-prefix-dir) + prev=inst_prefix + continue + ;; + + # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:* + # so, if we see these flags be careful not to treat them like -L + -L[A-Z][A-Z]*:*) + case $with_gcc/$host in + no/*-*-irix* | /*-*-irix*) + compile_command="$compile_command $arg" + finalize_command="$finalize_command $arg" + ;; + esac + continue + ;; + + -L*) + dir=`$echo "X$arg" | $Xsed -e 's/^-L//'` + # We need an absolute path. + case $dir in + [\\/]* | [A-Za-z]:[\\/]*) ;; + *) + absdir=`cd "$dir" && pwd` + if test -z "$absdir"; then + $echo "$modename: cannot determine absolute directory name of \`$dir'" 1>&2 + exit $EXIT_FAILURE + fi + dir="$absdir" + ;; + esac + case "$deplibs " in + *" -L$dir "*) ;; + *) + deplibs="$deplibs -L$dir" + lib_search_path="$lib_search_path $dir" + ;; + esac + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*) + case :$dllsearchpath: in + *":$dir:"*) ;; + *) dllsearchpath="$dllsearchpath:$dir";; + esac + ;; + esac + continue + ;; + + -l*) + if test "X$arg" = "X-lc" || test "X$arg" = "X-lm"; then + case $host in + *-*-cygwin* | *-*-pw32* | *-*-beos*) + # These systems don't actually have a C or math library (as such) + continue + ;; + *-*-mingw* | *-*-os2*) + # These systems don't actually have a C library (as such) + test "X$arg" = "X-lc" && continue + ;; + *-*-openbsd* | *-*-freebsd*) + # Do not include libc due to us having libc/libc_r. + test "X$arg" = "X-lc" && continue + ;; + *-*-rhapsody* | *-*-darwin1.[012]) + # Rhapsody C and math libraries are in the System framework + deplibs="$deplibs -framework System" + continue + esac + elif test "X$arg" = "X-lc_r"; then + case $host in + *-*-openbsd* | *-*-freebsd*) + # Do not include libc_r directly, use -pthread flag. + continue + ;; + esac + fi + deplibs="$deplibs $arg" + continue + ;; + + -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe) + deplibs="$deplibs $arg" + continue + ;; + + -module) + module=yes + continue + ;; + + # gcc -m* arguments should be passed to the linker via $compiler_flags + # in order to pass architecture information to the linker + # (e.g. 32 vs 64-bit). This may also be accomplished via -Wl,-mfoo + # but this is not reliable with gcc because gcc may use -mfoo to + # select a different linker, different libraries, etc, while + # -Wl,-mfoo simply passes -mfoo to the linker. + -m*) + # Unknown arguments in both finalize_command and compile_command need + # to be aesthetically quoted because they are evaled later. + arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"` + case $arg in + *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") + arg="\"$arg\"" + ;; + esac + compile_command="$compile_command $arg" + finalize_command="$finalize_command $arg" + if test "$with_gcc" = "yes" ; then + compiler_flags="$compiler_flags $arg" + fi + continue + ;; + + -shrext) + prev=shrext + continue + ;; + + -no-fast-install) + fast_install=no + continue + ;; + + -no-install) + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*) + # The PATH hackery in wrapper scripts is required on Windows + # in order for the loader to find any dlls it needs. + $echo "$modename: warning: \`-no-install' is ignored for $host" 1>&2 + $echo "$modename: warning: assuming \`-no-fast-install' instead" 1>&2 + fast_install=no + ;; + *) no_install=yes ;; + esac + continue + ;; + + -no-undefined) + allow_undefined=no + continue + ;; + + -objectlist) + prev=objectlist + continue + ;; + + -o) prev=output ;; + + -precious-files-regex) + prev=precious_regex + continue + ;; + + -release) + prev=release + continue + ;; + + -rpath) + prev=rpath + continue + ;; + + -R) + prev=xrpath + continue + ;; + + -R*) + dir=`$echo "X$arg" | $Xsed -e 's/^-R//'` + # We need an absolute path. + case $dir in + [\\/]* | [A-Za-z]:[\\/]*) ;; + *) + $echo "$modename: only absolute run-paths are allowed" 1>&2 + exit $EXIT_FAILURE + ;; + esac + case "$xrpath " in + *" $dir "*) ;; + *) xrpath="$xrpath $dir" ;; + esac + continue + ;; + + -static) + # The effects of -static are defined in a previous loop. + # We used to do the same as -all-static on platforms that + # didn't have a PIC flag, but the assumption that the effects + # would be equivalent was wrong. It would break on at least + # Digital Unix and AIX. + continue + ;; + + -thread-safe) + thread_safe=yes + continue + ;; + + -version-info) + prev=vinfo + continue + ;; + -version-number) + prev=vinfo + vinfo_number=yes + continue + ;; + + -Wc,*) + args=`$echo "X$arg" | $Xsed -e "$sed_quote_subst" -e 's/^-Wc,//'` + arg= + save_ifs="$IFS"; IFS=',' + for flag in $args; do + IFS="$save_ifs" + case $flag in + *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") + flag="\"$flag\"" + ;; + esac + arg="$arg $wl$flag" + compiler_flags="$compiler_flags $flag" + done + IFS="$save_ifs" + arg=`$echo "X$arg" | $Xsed -e "s/^ //"` + ;; + + -Wl,*) + args=`$echo "X$arg" | $Xsed -e "$sed_quote_subst" -e 's/^-Wl,//'` + arg= + save_ifs="$IFS"; IFS=',' + for flag in $args; do + IFS="$save_ifs" + case $flag in + *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") + flag="\"$flag\"" + ;; + esac + arg="$arg $wl$flag" + compiler_flags="$compiler_flags $wl$flag" + linker_flags="$linker_flags $flag" + done + IFS="$save_ifs" + arg=`$echo "X$arg" | $Xsed -e "s/^ //"` + ;; + + -Xcompiler) + prev=xcompiler + continue + ;; + + -Xlinker) + prev=xlinker + continue + ;; + + -XCClinker) + prev=xcclinker + continue + ;; + + # Some other compiler flag. + -* | +*) + # Unknown arguments in both finalize_command and compile_command need + # to be aesthetically quoted because they are evaled later. + arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"` + case $arg in + *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") + arg="\"$arg\"" + ;; + esac + ;; + + *.$objext) + # A standard object. + objs="$objs $arg" + ;; + + *.lo) + # A libtool-controlled object. + + # Check to see that this really is a libtool object. + if (${SED} -e '2q' $arg | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then + pic_object= + non_pic_object= + + # Read the .lo file + # If there is no directory component, then add one. + case $arg in + */* | *\\*) . $arg ;; + *) . ./$arg ;; + esac + + if test -z "$pic_object" || \ + test -z "$non_pic_object" || + test "$pic_object" = none && \ + test "$non_pic_object" = none; then + $echo "$modename: cannot find name of object for \`$arg'" 1>&2 + exit $EXIT_FAILURE + fi + + # Extract subdirectory from the argument. + xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'` + if test "X$xdir" = "X$arg"; then + xdir= + else + xdir="$xdir/" + fi + + if test "$pic_object" != none; then + # Prepend the subdirectory the object is found in. + pic_object="$xdir$pic_object" + + if test "$prev" = dlfiles; then + if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then + dlfiles="$dlfiles $pic_object" + prev= + continue + else + # If libtool objects are unsupported, then we need to preload. + prev=dlprefiles + fi + fi + + # CHECK ME: I think I busted this. -Ossama + if test "$prev" = dlprefiles; then + # Preload the old-style object. + dlprefiles="$dlprefiles $pic_object" + prev= + fi + + # A PIC object. + libobjs="$libobjs $pic_object" + arg="$pic_object" + fi + + # Non-PIC object. + if test "$non_pic_object" != none; then + # Prepend the subdirectory the object is found in. + non_pic_object="$xdir$non_pic_object" + + # A standard non-PIC object + non_pic_objects="$non_pic_objects $non_pic_object" + if test -z "$pic_object" || test "$pic_object" = none ; then + arg="$non_pic_object" + fi + fi + else + # Only an error if not doing a dry-run. + if test -z "$run"; then + $echo "$modename: \`$arg' is not a valid libtool object" 1>&2 + exit $EXIT_FAILURE + else + # Dry-run case. + + # Extract subdirectory from the argument. + xdir=`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'` + if test "X$xdir" = "X$arg"; then + xdir= + else + xdir="$xdir/" + fi + + pic_object=`$echo "X${xdir}${objdir}/${arg}" | $Xsed -e "$lo2o"` + non_pic_object=`$echo "X${xdir}${arg}" | $Xsed -e "$lo2o"` + libobjs="$libobjs $pic_object" + non_pic_objects="$non_pic_objects $non_pic_object" + fi + fi + ;; + + *.$libext) + # An archive. + deplibs="$deplibs $arg" + old_deplibs="$old_deplibs $arg" + continue + ;; + + *.la) + # A libtool-controlled library. + + if test "$prev" = dlfiles; then + # This library was specified with -dlopen. + dlfiles="$dlfiles $arg" + prev= + elif test "$prev" = dlprefiles; then + # The library was specified with -dlpreopen. + dlprefiles="$dlprefiles $arg" + prev= + else + deplibs="$deplibs $arg" + fi + continue + ;; + + # Some other compiler argument. + *) + # Unknown arguments in both finalize_command and compile_command need + # to be aesthetically quoted because they are evaled later. + arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"` + case $arg in + *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") + arg="\"$arg\"" + ;; + esac + ;; + esac # arg + + # Now actually substitute the argument into the commands. + if test -n "$arg"; then + compile_command="$compile_command $arg" + finalize_command="$finalize_command $arg" + fi + done # argument parsing loop + + if test -n "$prev"; then + $echo "$modename: the \`$prevarg' option requires an argument" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE + fi + + if test "$export_dynamic" = yes && test -n "$export_dynamic_flag_spec"; then + eval arg=\"$export_dynamic_flag_spec\" + compile_command="$compile_command $arg" + finalize_command="$finalize_command $arg" + fi + + oldlibs= + # calculate the name of the file, without its directory + outputname=`$echo "X$output" | $Xsed -e 's%^.*/%%'` + libobjs_save="$libobjs" + + if test -n "$shlibpath_var"; then + # get the directories listed in $shlibpath_var + eval shlib_search_path=\`\$echo \"X\${$shlibpath_var}\" \| \$Xsed -e \'s/:/ /g\'\` + else + shlib_search_path= + fi + eval sys_lib_search_path=\"$sys_lib_search_path_spec\" + eval sys_lib_dlsearch_path=\"$sys_lib_dlsearch_path_spec\" + + output_objdir=`$echo "X$output" | $Xsed -e 's%/[^/]*$%%'` + if test "X$output_objdir" = "X$output"; then + output_objdir="$objdir" + else + output_objdir="$output_objdir/$objdir" + fi + # Create the object directory. + if test ! -d "$output_objdir"; then + $show "$mkdir $output_objdir" + $run $mkdir $output_objdir + status=$? + if test "$status" -ne 0 && test ! -d "$output_objdir"; then + exit $status + fi + fi + + # Determine the type of output + case $output in + "") + $echo "$modename: you must specify an output file" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE + ;; + *.$libext) linkmode=oldlib ;; + *.lo | *.$objext) linkmode=obj ;; + *.la) linkmode=lib ;; + *) linkmode=prog ;; # Anything else should be a program. + esac + + case $host in + *cygwin* | *mingw* | *pw32*) + # don't eliminate duplications in $postdeps and $predeps + duplicate_compiler_generated_deps=yes + ;; + *) + duplicate_compiler_generated_deps=$duplicate_deps + ;; + esac + specialdeplibs= + + libs= + # Find all interdependent deplibs by searching for libraries + # that are linked more than once (e.g. -la -lb -la) + for deplib in $deplibs; do + if test "X$duplicate_deps" = "Xyes" ; then + case "$libs " in + *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; + esac + fi + libs="$libs $deplib" + done + + if test "$linkmode" = lib; then + libs="$predeps $libs $compiler_lib_search_path $postdeps" + + # Compute libraries that are listed more than once in $predeps + # $postdeps and mark them as special (i.e., whose duplicates are + # not to be eliminated). + pre_post_deps= + if test "X$duplicate_compiler_generated_deps" = "Xyes" ; then + for pre_post_dep in $predeps $postdeps; do + case "$pre_post_deps " in + *" $pre_post_dep "*) specialdeplibs="$specialdeplibs $pre_post_deps" ;; + esac + pre_post_deps="$pre_post_deps $pre_post_dep" + done + fi + pre_post_deps= + fi + + deplibs= + newdependency_libs= + newlib_search_path= + need_relink=no # whether we're linking any uninstalled libtool libraries + notinst_deplibs= # not-installed libtool libraries + notinst_path= # paths that contain not-installed libtool libraries + case $linkmode in + lib) + passes="conv link" + for file in $dlfiles $dlprefiles; do + case $file in + *.la) ;; + *) + $echo "$modename: libraries can \`-dlopen' only libtool libraries: $file" 1>&2 + exit $EXIT_FAILURE + ;; + esac + done + ;; + prog) + compile_deplibs= + finalize_deplibs= + alldeplibs=no + newdlfiles= + newdlprefiles= + passes="conv scan dlopen dlpreopen link" + ;; + *) passes="conv" + ;; + esac + for pass in $passes; do + if test "$linkmode,$pass" = "lib,link" || + test "$linkmode,$pass" = "prog,scan"; then + libs="$deplibs" + deplibs= + fi + if test "$linkmode" = prog; then + case $pass in + dlopen) libs="$dlfiles" ;; + dlpreopen) libs="$dlprefiles" ;; + link) + libs="$deplibs %DEPLIBS%" + test "X$link_all_deplibs" != Xno && libs="$libs $dependency_libs" + ;; + esac + fi + if test "$pass" = dlopen; then + # Collect dlpreopened libraries + save_deplibs="$deplibs" + deplibs= + fi + for deplib in $libs; do + lib= + found=no + case $deplib in + -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe) + if test "$linkmode,$pass" = "prog,link"; then + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + else + deplibs="$deplib $deplibs" + fi + continue + ;; + -l*) + if test "$linkmode" != lib && test "$linkmode" != prog; then + $echo "$modename: warning: \`-l' is ignored for archives/objects" 1>&2 + continue + fi + name=`$echo "X$deplib" | $Xsed -e 's/^-l//'` + for searchdir in $newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path; do + for search_ext in .la $std_shrext .so .a; do + # Search the libtool library + lib="$searchdir/lib${name}${search_ext}" + if test -f "$lib"; then + if test "$search_ext" = ".la"; then + found=yes + else + found=no + fi + break 2 + fi + done + done + if test "$found" != yes; then + # deplib doesn't seem to be a libtool library + if test "$linkmode,$pass" = "prog,link"; then + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + else + deplibs="$deplib $deplibs" + test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs" + fi + continue + else # deplib is a libtool library + # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib, + # We need to do some special things here, and not later. + if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then + case " $predeps $postdeps " in + *" $deplib "*) + if (${SED} -e '2q' $lib | + grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then + library_names= + old_library= + case $lib in + */* | *\\*) . $lib ;; + *) . ./$lib ;; + esac + for l in $old_library $library_names; do + ll="$l" + done + if test "X$ll" = "X$old_library" ; then # only static version available + found=no + ladir=`$echo "X$lib" | $Xsed -e 's%/[^/]*$%%'` + test "X$ladir" = "X$lib" && ladir="." + lib=$ladir/$old_library + if test "$linkmode,$pass" = "prog,link"; then + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + else + deplibs="$deplib $deplibs" + test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs" + fi + continue + fi + fi + ;; + *) ;; + esac + fi + fi + ;; # -l + -L*) + case $linkmode in + lib) + deplibs="$deplib $deplibs" + test "$pass" = conv && continue + newdependency_libs="$deplib $newdependency_libs" + newlib_search_path="$newlib_search_path "`$echo "X$deplib" | $Xsed -e 's/^-L//'` + ;; + prog) + if test "$pass" = conv; then + deplibs="$deplib $deplibs" + continue + fi + if test "$pass" = scan; then + deplibs="$deplib $deplibs" + else + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + fi + newlib_search_path="$newlib_search_path "`$echo "X$deplib" | $Xsed -e 's/^-L//'` + ;; + *) + $echo "$modename: warning: \`-L' is ignored for archives/objects" 1>&2 + ;; + esac # linkmode + continue + ;; # -L + -R*) + if test "$pass" = link; then + dir=`$echo "X$deplib" | $Xsed -e 's/^-R//'` + # Make sure the xrpath contains only unique directories. + case "$xrpath " in + *" $dir "*) ;; + *) xrpath="$xrpath $dir" ;; + esac + fi + deplibs="$deplib $deplibs" + continue + ;; + *.la) lib="$deplib" ;; + *.$libext) + if test "$pass" = conv; then + deplibs="$deplib $deplibs" + continue + fi + case $linkmode in + lib) + if test "$deplibs_check_method" != pass_all; then + $echo + $echo "*** Warning: Trying to link with static lib archive $deplib." + $echo "*** I have the capability to make that library automatically link in when" + $echo "*** you link to this library. But I can only do this if you have a" + $echo "*** shared version of the library, which you do not appear to have" + $echo "*** because the file extensions .$libext of this argument makes me believe" + $echo "*** that it is just a static archive that I should not used here." + else + $echo + $echo "*** Warning: Linking the shared library $output against the" + $echo "*** static library $deplib is not portable!" + deplibs="$deplib $deplibs" + fi + continue + ;; + prog) + if test "$pass" != link; then + deplibs="$deplib $deplibs" + else + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + fi + continue + ;; + esac # linkmode + ;; # *.$libext + *.lo | *.$objext) + if test "$pass" = conv; then + deplibs="$deplib $deplibs" + elif test "$linkmode" = prog; then + if test "$pass" = dlpreopen || test "$dlopen_support" != yes || test "$build_libtool_libs" = no; then + # If there is no dlopen support or we're linking statically, + # we need to preload. + newdlprefiles="$newdlprefiles $deplib" + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + else + newdlfiles="$newdlfiles $deplib" + fi + fi + continue + ;; + %DEPLIBS%) + alldeplibs=yes + continue + ;; + esac # case $deplib + if test "$found" = yes || test -f "$lib"; then : + else + $echo "$modename: cannot find the library \`$lib'" 1>&2 + exit $EXIT_FAILURE + fi + + # Check to see that this really is a libtool archive. + if (${SED} -e '2q' $lib | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then : + else + $echo "$modename: \`$lib' is not a valid libtool archive" 1>&2 + exit $EXIT_FAILURE + fi + + ladir=`$echo "X$lib" | $Xsed -e 's%/[^/]*$%%'` + test "X$ladir" = "X$lib" && ladir="." + + dlname= + dlopen= + dlpreopen= + libdir= + library_names= + old_library= + # If the library was installed with an old release of libtool, + # it will not redefine variables installed, or shouldnotlink + installed=yes + shouldnotlink=no + + # Read the .la file + case $lib in + */* | *\\*) . $lib ;; + *) . ./$lib ;; + esac + + if test "$linkmode,$pass" = "lib,link" || + test "$linkmode,$pass" = "prog,scan" || + { test "$linkmode" != prog && test "$linkmode" != lib; }; then + test -n "$dlopen" && dlfiles="$dlfiles $dlopen" + test -n "$dlpreopen" && dlprefiles="$dlprefiles $dlpreopen" + fi + + if test "$pass" = conv; then + # Only check for convenience libraries + deplibs="$lib $deplibs" + if test -z "$libdir"; then + if test -z "$old_library"; then + $echo "$modename: cannot find name of link library for \`$lib'" 1>&2 + exit $EXIT_FAILURE + fi + # It is a libtool convenience library, so add in its objects. + convenience="$convenience $ladir/$objdir/$old_library" + old_convenience="$old_convenience $ladir/$objdir/$old_library" + tmp_libs= + for deplib in $dependency_libs; do + deplibs="$deplib $deplibs" + if test "X$duplicate_deps" = "Xyes" ; then + case "$tmp_libs " in + *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; + esac + fi + tmp_libs="$tmp_libs $deplib" + done + elif test "$linkmode" != prog && test "$linkmode" != lib; then + $echo "$modename: \`$lib' is not a convenience library" 1>&2 + exit $EXIT_FAILURE + fi + continue + fi # $pass = conv + + + # Get the name of the library we link against. + linklib= + for l in $old_library $library_names; do + linklib="$l" + done + if test -z "$linklib"; then + $echo "$modename: cannot find name of link library for \`$lib'" 1>&2 + exit $EXIT_FAILURE + fi + + # This library was specified with -dlopen. + if test "$pass" = dlopen; then + if test -z "$libdir"; then + $echo "$modename: cannot -dlopen a convenience library: \`$lib'" 1>&2 + exit $EXIT_FAILURE + fi + if test -z "$dlname" || + test "$dlopen_support" != yes || + test "$build_libtool_libs" = no; then + # If there is no dlname, no dlopen support or we're linking + # statically, we need to preload. We also need to preload any + # dependent libraries so libltdl's deplib preloader doesn't + # bomb out in the load deplibs phase. + dlprefiles="$dlprefiles $lib $dependency_libs" + else + newdlfiles="$newdlfiles $lib" + fi + continue + fi # $pass = dlopen + + # We need an absolute path. + case $ladir in + [\\/]* | [A-Za-z]:[\\/]*) abs_ladir="$ladir" ;; + *) + abs_ladir=`cd "$ladir" && pwd` + if test -z "$abs_ladir"; then + $echo "$modename: warning: cannot determine absolute directory name of \`$ladir'" 1>&2 + $echo "$modename: passing it literally to the linker, although it might fail" 1>&2 + abs_ladir="$ladir" + fi + ;; + esac + laname=`$echo "X$lib" | $Xsed -e 's%^.*/%%'` + + # Find the relevant object directory and library name. + if test "X$installed" = Xyes; then + if test ! -f "$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then + $echo "$modename: warning: library \`$lib' was moved." 1>&2 + dir="$ladir" + absdir="$abs_ladir" + libdir="$abs_ladir" + else + dir="$libdir" + absdir="$libdir" + fi + else + dir="$ladir/$objdir" + absdir="$abs_ladir/$objdir" + # Remove this search path later + notinst_path="$notinst_path $abs_ladir" + fi # $installed = yes + name=`$echo "X$laname" | $Xsed -e 's/\.la$//' -e 's/^lib//'` + + # This library was specified with -dlpreopen. + if test "$pass" = dlpreopen; then + if test -z "$libdir"; then + $echo "$modename: cannot -dlpreopen a convenience library: \`$lib'" 1>&2 + exit $EXIT_FAILURE + fi + # Prefer using a static library (so that no silly _DYNAMIC symbols + # are required to link). + if test -n "$old_library"; then + newdlprefiles="$newdlprefiles $dir/$old_library" + # Otherwise, use the dlname, so that lt_dlopen finds it. + elif test -n "$dlname"; then + newdlprefiles="$newdlprefiles $dir/$dlname" + else + newdlprefiles="$newdlprefiles $dir/$linklib" + fi + fi # $pass = dlpreopen + + if test -z "$libdir"; then + # Link the convenience library + if test "$linkmode" = lib; then + deplibs="$dir/$old_library $deplibs" + elif test "$linkmode,$pass" = "prog,link"; then + compile_deplibs="$dir/$old_library $compile_deplibs" + finalize_deplibs="$dir/$old_library $finalize_deplibs" + else + deplibs="$lib $deplibs" # used for prog,scan pass + fi + continue + fi + + + if test "$linkmode" = prog && test "$pass" != link; then + newlib_search_path="$newlib_search_path $ladir" + deplibs="$lib $deplibs" + + linkalldeplibs=no + if test "$link_all_deplibs" != no || test -z "$library_names" || + test "$build_libtool_libs" = no; then + linkalldeplibs=yes + fi + + tmp_libs= + for deplib in $dependency_libs; do + case $deplib in + -L*) newlib_search_path="$newlib_search_path "`$echo "X$deplib" | $Xsed -e 's/^-L//'`;; ### testsuite: skip nested quoting test + esac + # Need to link against all dependency_libs? + if test "$linkalldeplibs" = yes; then + deplibs="$deplib $deplibs" + else + # Need to hardcode shared library paths + # or/and link against static libraries + newdependency_libs="$deplib $newdependency_libs" + fi + if test "X$duplicate_deps" = "Xyes" ; then + case "$tmp_libs " in + *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; + esac + fi + tmp_libs="$tmp_libs $deplib" + done # for deplib + continue + fi # $linkmode = prog... + + if test "$linkmode,$pass" = "prog,link"; then + if test -n "$library_names" && + { test "$prefer_static_libs" = no || test -z "$old_library"; }; then + # We need to hardcode the library path + if test -n "$shlibpath_var"; then + # Make sure the rpath contains only unique directories. + case "$temp_rpath " in + *" $dir "*) ;; + *" $absdir "*) ;; + *) temp_rpath="$temp_rpath $dir" ;; + esac + fi + + # Hardcode the library path. + # Skip directories that are in the system default run-time + # search path. + case " $sys_lib_dlsearch_path " in + *" $absdir "*) ;; + *) + case "$compile_rpath " in + *" $absdir "*) ;; + *) compile_rpath="$compile_rpath $absdir" + esac + ;; + esac + case " $sys_lib_dlsearch_path " in + *" $libdir "*) ;; + *) + case "$finalize_rpath " in + *" $libdir "*) ;; + *) finalize_rpath="$finalize_rpath $libdir" + esac + ;; + esac + fi # $linkmode,$pass = prog,link... + + if test "$alldeplibs" = yes && + { test "$deplibs_check_method" = pass_all || + { test "$build_libtool_libs" = yes && + test -n "$library_names"; }; }; then + # We only need to search for static libraries + continue + fi + fi + + link_static=no # Whether the deplib will be linked statically + if test -n "$library_names" && + { test "$prefer_static_libs" = no || test -z "$old_library"; }; then + if test "$installed" = no; then + notinst_deplibs="$notinst_deplibs $lib" + need_relink=yes + fi + # This is a shared library + + # Warn about portability, can't link against -module's on + # some systems (darwin) + if test "$shouldnotlink" = yes && test "$pass" = link ; then + $echo + if test "$linkmode" = prog; then + $echo "*** Warning: Linking the executable $output against the loadable module" + else + $echo "*** Warning: Linking the shared library $output against the loadable module" + fi + $echo "*** $linklib is not portable!" + fi + if test "$linkmode" = lib && + test "$hardcode_into_libs" = yes; then + # Hardcode the library path. + # Skip directories that are in the system default run-time + # search path. + case " $sys_lib_dlsearch_path " in + *" $absdir "*) ;; + *) + case "$compile_rpath " in + *" $absdir "*) ;; + *) compile_rpath="$compile_rpath $absdir" + esac + ;; + esac + case " $sys_lib_dlsearch_path " in + *" $libdir "*) ;; + *) + case "$finalize_rpath " in + *" $libdir "*) ;; + *) finalize_rpath="$finalize_rpath $libdir" + esac + ;; + esac + fi + + if test -n "$old_archive_from_expsyms_cmds"; then + # figure out the soname + set dummy $library_names + realname="$2" + shift; shift + libname=`eval \\$echo \"$libname_spec\"` + # use dlname if we got it. it's perfectly good, no? + if test -n "$dlname"; then + soname="$dlname" + elif test -n "$soname_spec"; then + # bleh windows + case $host in + *cygwin* | mingw*) + major=`expr $current - $age` + versuffix="-$major" + ;; + esac + eval soname=\"$soname_spec\" + else + soname="$realname" + fi + + # Make a new name for the extract_expsyms_cmds to use + soroot="$soname" + soname=`$echo $soroot | ${SED} -e 's/^.*\///'` + newlib="libimp-`$echo $soname | ${SED} 's/^lib//;s/\.dll$//'`.a" + + # If the library has no export list, then create one now + if test -f "$output_objdir/$soname-def"; then : + else + $show "extracting exported symbol list from \`$soname'" + save_ifs="$IFS"; IFS='~' + cmds=$extract_expsyms_cmds + for cmd in $cmds; do + IFS="$save_ifs" + eval cmd=\"$cmd\" + $show "$cmd" + $run eval "$cmd" || exit $? + done + IFS="$save_ifs" + fi + + # Create $newlib + if test -f "$output_objdir/$newlib"; then :; else + $show "generating import library for \`$soname'" + save_ifs="$IFS"; IFS='~' + cmds=$old_archive_from_expsyms_cmds + for cmd in $cmds; do + IFS="$save_ifs" + eval cmd=\"$cmd\" + $show "$cmd" + $run eval "$cmd" || exit $? + done + IFS="$save_ifs" + fi + # make sure the library variables are pointing to the new library + dir=$output_objdir + linklib=$newlib + fi # test -n "$old_archive_from_expsyms_cmds" + + if test "$linkmode" = prog || test "$mode" != relink; then + add_shlibpath= + add_dir= + add= + lib_linked=yes + case $hardcode_action in + immediate | unsupported) + if test "$hardcode_direct" = no; then + add="$dir/$linklib" + case $host in + *-*-sco3.2v5* ) add_dir="-L$dir" ;; + *-*-darwin* ) + # if the lib is a module then we can not link against + # it, someone is ignoring the new warnings I added + if /usr/bin/file -L $add 2> /dev/null | $EGREP "bundle" >/dev/null ; then + $echo "** Warning, lib $linklib is a module, not a shared library" + if test -z "$old_library" ; then + $echo + $echo "** And there doesn't seem to be a static archive available" + $echo "** The link will probably fail, sorry" + else + add="$dir/$old_library" + fi + fi + esac + elif test "$hardcode_minus_L" = no; then + case $host in + *-*-sunos*) add_shlibpath="$dir" ;; + esac + add_dir="-L$dir" + add="-l$name" + elif test "$hardcode_shlibpath_var" = no; then + add_shlibpath="$dir" + add="-l$name" + else + lib_linked=no + fi + ;; + relink) + if test "$hardcode_direct" = yes; then + add="$dir/$linklib" + elif test "$hardcode_minus_L" = yes; then + add_dir="-L$dir" + # Try looking first in the location we're being installed to. + if test -n "$inst_prefix_dir"; then + case "$libdir" in + [\\/]*) + add_dir="$add_dir -L$inst_prefix_dir$libdir" + ;; + esac + fi + add="-l$name" + elif test "$hardcode_shlibpath_var" = yes; then + add_shlibpath="$dir" + add="-l$name" + else + lib_linked=no + fi + ;; + *) lib_linked=no ;; + esac + + if test "$lib_linked" != yes; then + $echo "$modename: configuration error: unsupported hardcode properties" + exit $EXIT_FAILURE + fi + + if test -n "$add_shlibpath"; then + case :$compile_shlibpath: in + *":$add_shlibpath:"*) ;; + *) compile_shlibpath="$compile_shlibpath$add_shlibpath:" ;; + esac + fi + if test "$linkmode" = prog; then + test -n "$add_dir" && compile_deplibs="$add_dir $compile_deplibs" + test -n "$add" && compile_deplibs="$add $compile_deplibs" + else + test -n "$add_dir" && deplibs="$add_dir $deplibs" + test -n "$add" && deplibs="$add $deplibs" + if test "$hardcode_direct" != yes && \ + test "$hardcode_minus_L" != yes && \ + test "$hardcode_shlibpath_var" = yes; then + case :$finalize_shlibpath: in + *":$libdir:"*) ;; + *) finalize_shlibpath="$finalize_shlibpath$libdir:" ;; + esac + fi + fi + fi + + if test "$linkmode" = prog || test "$mode" = relink; then + add_shlibpath= + add_dir= + add= + # Finalize command for both is simple: just hardcode it. + if test "$hardcode_direct" = yes; then + add="$libdir/$linklib" + elif test "$hardcode_minus_L" = yes; then + add_dir="-L$libdir" + add="-l$name" + elif test "$hardcode_shlibpath_var" = yes; then + case :$finalize_shlibpath: in + *":$libdir:"*) ;; + *) finalize_shlibpath="$finalize_shlibpath$libdir:" ;; + esac + add="-l$name" + elif test "$hardcode_automatic" = yes; then + if test -n "$inst_prefix_dir" && + test -f "$inst_prefix_dir$libdir/$linklib" ; then + add="$inst_prefix_dir$libdir/$linklib" + else + add="$libdir/$linklib" + fi + else + # We cannot seem to hardcode it, guess we'll fake it. + add_dir="-L$libdir" + # Try looking first in the location we're being installed to. + if test -n "$inst_prefix_dir"; then + case "$libdir" in + [\\/]*) + add_dir="$add_dir -L$inst_prefix_dir$libdir" + ;; + esac + fi + add="-l$name" + fi + + if test "$linkmode" = prog; then + test -n "$add_dir" && finalize_deplibs="$add_dir $finalize_deplibs" + test -n "$add" && finalize_deplibs="$add $finalize_deplibs" + else + test -n "$add_dir" && deplibs="$add_dir $deplibs" + test -n "$add" && deplibs="$add $deplibs" + fi + fi + elif test "$linkmode" = prog; then + # Here we assume that one of hardcode_direct or hardcode_minus_L + # is not unsupported. This is valid on all known static and + # shared platforms. + if test "$hardcode_direct" != unsupported; then + test -n "$old_library" && linklib="$old_library" + compile_deplibs="$dir/$linklib $compile_deplibs" + finalize_deplibs="$dir/$linklib $finalize_deplibs" + else + compile_deplibs="-l$name -L$dir $compile_deplibs" + finalize_deplibs="-l$name -L$dir $finalize_deplibs" + fi + elif test "$build_libtool_libs" = yes; then + # Not a shared library + if test "$deplibs_check_method" != pass_all; then + # We're trying link a shared library against a static one + # but the system doesn't support it. + + # Just print a warning and add the library to dependency_libs so + # that the program can be linked against the static library. + $echo + $echo "*** Warning: This system can not link to static lib archive $lib." + $echo "*** I have the capability to make that library automatically link in when" + $echo "*** you link to this library. But I can only do this if you have a" + $echo "*** shared version of the library, which you do not appear to have." + if test "$module" = yes; then + $echo "*** But as you try to build a module library, libtool will still create " + $echo "*** a static module, that should work as long as the dlopening application" + $echo "*** is linked with the -dlopen flag to resolve symbols at runtime." + if test -z "$global_symbol_pipe"; then + $echo + $echo "*** However, this would only work if libtool was able to extract symbol" + $echo "*** lists from a program, using \`nm' or equivalent, but libtool could" + $echo "*** not find such a program. So, this module is probably useless." + $echo "*** \`nm' from GNU binutils and a full rebuild may help." + fi + if test "$build_old_libs" = no; then + build_libtool_libs=module + build_old_libs=yes + else + build_libtool_libs=no + fi + fi + else + convenience="$convenience $dir/$old_library" + old_convenience="$old_convenience $dir/$old_library" + deplibs="$dir/$old_library $deplibs" + link_static=yes + fi + fi # link shared/static library? + + if test "$linkmode" = lib; then + if test -n "$dependency_libs" && + { test "$hardcode_into_libs" != yes || + test "$build_old_libs" = yes || + test "$link_static" = yes; }; then + # Extract -R from dependency_libs + temp_deplibs= + for libdir in $dependency_libs; do + case $libdir in + -R*) temp_xrpath=`$echo "X$libdir" | $Xsed -e 's/^-R//'` + case " $xrpath " in + *" $temp_xrpath "*) ;; + *) xrpath="$xrpath $temp_xrpath";; + esac;; + *) temp_deplibs="$temp_deplibs $libdir";; + esac + done + dependency_libs="$temp_deplibs" + fi + + newlib_search_path="$newlib_search_path $absdir" + # Link against this library + test "$link_static" = no && newdependency_libs="$abs_ladir/$laname $newdependency_libs" + # ... and its dependency_libs + tmp_libs= + for deplib in $dependency_libs; do + newdependency_libs="$deplib $newdependency_libs" + if test "X$duplicate_deps" = "Xyes" ; then + case "$tmp_libs " in + *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; + esac + fi + tmp_libs="$tmp_libs $deplib" + done + + if test "$link_all_deplibs" != no; then + # Add the search paths of all dependency libraries + for deplib in $dependency_libs; do + case $deplib in + -L*) path="$deplib" ;; + *.la) + dir=`$echo "X$deplib" | $Xsed -e 's%/[^/]*$%%'` + test "X$dir" = "X$deplib" && dir="." + # We need an absolute path. + case $dir in + [\\/]* | [A-Za-z]:[\\/]*) absdir="$dir" ;; + *) + absdir=`cd "$dir" && pwd` + if test -z "$absdir"; then + $echo "$modename: warning: cannot determine absolute directory name of \`$dir'" 1>&2 + absdir="$dir" + fi + ;; + esac + if grep "^installed=no" $deplib > /dev/null; then + path="$absdir/$objdir" + else + eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib` + if test -z "$libdir"; then + $echo "$modename: \`$deplib' is not a valid libtool archive" 1>&2 + exit $EXIT_FAILURE + fi + if test "$absdir" != "$libdir"; then + $echo "$modename: warning: \`$deplib' seems to be moved" 1>&2 + fi + path="$absdir" + fi + depdepl= + case $host in + *-*-darwin*) + # we do not want to link against static libs, + # but need to link against shared + eval deplibrary_names=`${SED} -n -e 's/^library_names=\(.*\)$/\1/p' $deplib` + if test -n "$deplibrary_names" ; then + for tmp in $deplibrary_names ; do + depdepl=$tmp + done + if test -f "$path/$depdepl" ; then + depdepl="$path/$depdepl" + fi + # do not add paths which are already there + case " $newlib_search_path " in + *" $path "*) ;; + *) newlib_search_path="$newlib_search_path $path";; + esac + fi + path="" + ;; + *) + path="-L$path" + ;; + esac + ;; + -l*) + case $host in + *-*-darwin*) + # Again, we only want to link against shared libraries + eval tmp_libs=`$echo "X$deplib" | $Xsed -e "s,^\-l,,"` + for tmp in $newlib_search_path ; do + if test -f "$tmp/lib$tmp_libs.dylib" ; then + eval depdepl="$tmp/lib$tmp_libs.dylib" + break + fi + done + path="" + ;; + *) continue ;; + esac + ;; + *) continue ;; + esac + case " $deplibs " in + *" $depdepl "*) ;; + *) deplibs="$depdepl $deplibs" ;; + esac + case " $deplibs " in + *" $path "*) ;; + *) deplibs="$deplibs $path" ;; + esac + done + fi # link_all_deplibs != no + fi # linkmode = lib + done # for deplib in $libs + dependency_libs="$newdependency_libs" + if test "$pass" = dlpreopen; then + # Link the dlpreopened libraries before other libraries + for deplib in $save_deplibs; do + deplibs="$deplib $deplibs" + done + fi + if test "$pass" != dlopen; then + if test "$pass" != conv; then + # Make sure lib_search_path contains only unique directories. + lib_search_path= + for dir in $newlib_search_path; do + case "$lib_search_path " in + *" $dir "*) ;; + *) lib_search_path="$lib_search_path $dir" ;; + esac + done + newlib_search_path= + fi + + if test "$linkmode,$pass" != "prog,link"; then + vars="deplibs" + else + vars="compile_deplibs finalize_deplibs" + fi + for var in $vars dependency_libs; do + # Add libraries to $var in reverse order + eval tmp_libs=\"\$$var\" + new_libs= + for deplib in $tmp_libs; do + # FIXME: Pedantically, this is the right thing to do, so + # that some nasty dependency loop isn't accidentally + # broken: + #new_libs="$deplib $new_libs" + # Pragmatically, this seems to cause very few problems in + # practice: + case $deplib in + -L*) new_libs="$deplib $new_libs" ;; + -R*) ;; + *) + # And here is the reason: when a library appears more + # than once as an explicit dependence of a library, or + # is implicitly linked in more than once by the + # compiler, it is considered special, and multiple + # occurrences thereof are not removed. Compare this + # with having the same library being listed as a + # dependency of multiple other libraries: in this case, + # we know (pedantically, we assume) the library does not + # need to be listed more than once, so we keep only the + # last copy. This is not always right, but it is rare + # enough that we require users that really mean to play + # such unportable linking tricks to link the library + # using -Wl,-lname, so that libtool does not consider it + # for duplicate removal. + case " $specialdeplibs " in + *" $deplib "*) new_libs="$deplib $new_libs" ;; + *) + case " $new_libs " in + *" $deplib "*) ;; + *) new_libs="$deplib $new_libs" ;; + esac + ;; + esac + ;; + esac + done + tmp_libs= + for deplib in $new_libs; do + case $deplib in + -L*) + case " $tmp_libs " in + *" $deplib "*) ;; + *) tmp_libs="$tmp_libs $deplib" ;; + esac + ;; + *) tmp_libs="$tmp_libs $deplib" ;; + esac + done + eval $var=\"$tmp_libs\" + done # for var + fi + # Last step: remove runtime libs from dependency_libs + # (they stay in deplibs) + tmp_libs= + for i in $dependency_libs ; do + case " $predeps $postdeps $compiler_lib_search_path " in + *" $i "*) + i="" + ;; + esac + if test -n "$i" ; then + tmp_libs="$tmp_libs $i" + fi + done + dependency_libs=$tmp_libs + done # for pass + if test "$linkmode" = prog; then + dlfiles="$newdlfiles" + dlprefiles="$newdlprefiles" + fi + + case $linkmode in + oldlib) + if test -n "$deplibs"; then + $echo "$modename: warning: \`-l' and \`-L' are ignored for archives" 1>&2 + fi + + if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then + $echo "$modename: warning: \`-dlopen' is ignored for archives" 1>&2 + fi + + if test -n "$rpath"; then + $echo "$modename: warning: \`-rpath' is ignored for archives" 1>&2 + fi + + if test -n "$xrpath"; then + $echo "$modename: warning: \`-R' is ignored for archives" 1>&2 + fi + + if test -n "$vinfo"; then + $echo "$modename: warning: \`-version-info/-version-number' is ignored for archives" 1>&2 + fi + + if test -n "$release"; then + $echo "$modename: warning: \`-release' is ignored for archives" 1>&2 + fi + + if test -n "$export_symbols" || test -n "$export_symbols_regex"; then + $echo "$modename: warning: \`-export-symbols' is ignored for archives" 1>&2 + fi + + # Now set the variables for building old libraries. + build_libtool_libs=no + oldlibs="$output" + objs="$objs$old_deplibs" + ;; + + lib) + # Make sure we only generate libraries of the form `libNAME.la'. + case $outputname in + lib*) + name=`$echo "X$outputname" | $Xsed -e 's/\.la$//' -e 's/^lib//'` + eval shared_ext=\"$shrext_cmds\" + eval libname=\"$libname_spec\" + ;; + *) + if test "$module" = no; then + $echo "$modename: libtool library \`$output' must begin with \`lib'" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE + fi + if test "$need_lib_prefix" != no; then + # Add the "lib" prefix for modules if required + name=`$echo "X$outputname" | $Xsed -e 's/\.la$//'` + eval shared_ext=\"$shrext_cmds\" + eval libname=\"$libname_spec\" + else + libname=`$echo "X$outputname" | $Xsed -e 's/\.la$//'` + fi + ;; + esac + + if test -n "$objs"; then + if test "$deplibs_check_method" != pass_all; then + $echo "$modename: cannot build libtool library \`$output' from non-libtool objects on this host:$objs" 2>&1 + exit $EXIT_FAILURE + else + $echo + $echo "*** Warning: Linking the shared library $output against the non-libtool" + $echo "*** objects $objs is not portable!" + libobjs="$libobjs $objs" + fi + fi + + if test "$dlself" != no; then + $echo "$modename: warning: \`-dlopen self' is ignored for libtool libraries" 1>&2 + fi + + set dummy $rpath + if test "$#" -gt 2; then + $echo "$modename: warning: ignoring multiple \`-rpath's for a libtool library" 1>&2 + fi + install_libdir="$2" + + oldlibs= + if test -z "$rpath"; then + if test "$build_libtool_libs" = yes; then + # Building a libtool convenience library. + # Some compilers have problems with a `.al' extension so + # convenience libraries should have the same extension an + # archive normally would. + oldlibs="$output_objdir/$libname.$libext $oldlibs" + build_libtool_libs=convenience + build_old_libs=yes + fi + + if test -n "$vinfo"; then + $echo "$modename: warning: \`-version-info/-version-number' is ignored for convenience libraries" 1>&2 + fi + + if test -n "$release"; then + $echo "$modename: warning: \`-release' is ignored for convenience libraries" 1>&2 + fi + else + + # Parse the version information argument. + save_ifs="$IFS"; IFS=':' + set dummy $vinfo 0 0 0 + IFS="$save_ifs" + + if test -n "$8"; then + $echo "$modename: too many parameters to \`-version-info'" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE + fi + + # convert absolute version numbers to libtool ages + # this retains compatibility with .la files and attempts + # to make the code below a bit more comprehensible + + case $vinfo_number in + yes) + number_major="$2" + number_minor="$3" + number_revision="$4" + # + # There are really only two kinds -- those that + # use the current revision as the major version + # and those that subtract age and use age as + # a minor version. But, then there is irix + # which has an extra 1 added just for fun + # + case $version_type in + darwin|linux|osf|windows) + current=`expr $number_major + $number_minor` + age="$number_minor" + revision="$number_revision" + ;; + freebsd-aout|freebsd-elf|sunos) + current="$number_major" + revision="$number_minor" + age="0" + ;; + irix|nonstopux) + current=`expr $number_major + $number_minor - 1` + age="$number_minor" + revision="$number_minor" + ;; + *) + $echo "$modename: unknown library version type \`$version_type'" 1>&2 + $echo "Fatal configuration error. See the $PACKAGE docs for more information." 1>&2 + exit $EXIT_FAILURE + ;; + esac + ;; + no) + current="$2" + revision="$3" + age="$4" + ;; + esac + + # Check that each of the things are valid numbers. + case $current in + 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; + *) + $echo "$modename: CURRENT \`$current' is not a nonnegative integer" 1>&2 + $echo "$modename: \`$vinfo' is not valid version information" 1>&2 + exit $EXIT_FAILURE + ;; + esac + + case $revision in + 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; + *) + $echo "$modename: REVISION \`$revision' is not a nonnegative integer" 1>&2 + $echo "$modename: \`$vinfo' is not valid version information" 1>&2 + exit $EXIT_FAILURE + ;; + esac + + case $age in + 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; + *) + $echo "$modename: AGE \`$age' is not a nonnegative integer" 1>&2 + $echo "$modename: \`$vinfo' is not valid version information" 1>&2 + exit $EXIT_FAILURE + ;; + esac + + if test "$age" -gt "$current"; then + $echo "$modename: AGE \`$age' is greater than the current interface number \`$current'" 1>&2 + $echo "$modename: \`$vinfo' is not valid version information" 1>&2 + exit $EXIT_FAILURE + fi + + # Calculate the version variables. + major= + versuffix= + verstring= + case $version_type in + none) ;; + + darwin) + # Like Linux, but with the current version available in + # verstring for coding it into the library header + major=.`expr $current - $age` + versuffix="$major.$age.$revision" + # Darwin ld doesn't like 0 for these options... + minor_current=`expr $current + 1` + verstring="-compatibility_version $minor_current -current_version $minor_current.$revision" + ;; + + freebsd-aout) + major=".$current" + versuffix=".$current.$revision"; + ;; + + freebsd-elf) + major=".$current" + versuffix=".$current"; + ;; + + irix | nonstopux) + major=`expr $current - $age + 1` + + case $version_type in + nonstopux) verstring_prefix=nonstopux ;; + *) verstring_prefix=sgi ;; + esac + verstring="$verstring_prefix$major.$revision" + + # Add in all the interfaces that we are compatible with. + loop=$revision + while test "$loop" -ne 0; do + iface=`expr $revision - $loop` + loop=`expr $loop - 1` + verstring="$verstring_prefix$major.$iface:$verstring" + done + + # Before this point, $major must not contain `.'. + major=.$major + versuffix="$major.$revision" + ;; + + linux) + major=.`expr $current - $age` + versuffix="$major.$age.$revision" + ;; + + osf) + major=.`expr $current - $age` + versuffix=".$current.$age.$revision" + verstring="$current.$age.$revision" + + # Add in all the interfaces that we are compatible with. + loop=$age + while test "$loop" -ne 0; do + iface=`expr $current - $loop` + loop=`expr $loop - 1` + verstring="$verstring:${iface}.0" + done + + # Make executables depend on our current version. + verstring="$verstring:${current}.0" + ;; + + sunos) + major=".$current" + versuffix=".$current.$revision" + ;; + + windows) + # Use '-' rather than '.', since we only want one + # extension on DOS 8.3 filesystems. + major=`expr $current - $age` + versuffix="-$major" + ;; + + *) + $echo "$modename: unknown library version type \`$version_type'" 1>&2 + $echo "Fatal configuration error. See the $PACKAGE docs for more information." 1>&2 + exit $EXIT_FAILURE + ;; + esac + + # Clear the version info if we defaulted, and they specified a release. + if test -z "$vinfo" && test -n "$release"; then + major= + case $version_type in + darwin) + # we can't check for "0.0" in archive_cmds due to quoting + # problems, so we reset it completely + verstring= + ;; + *) + verstring="0.0" + ;; + esac + if test "$need_version" = no; then + versuffix= + else + versuffix=".0.0" + fi + fi + + # Remove version info from name if versioning should be avoided + if test "$avoid_version" = yes && test "$need_version" = no; then + major= + versuffix= + verstring="" + fi + + # Check to see if the archive will have undefined symbols. + if test "$allow_undefined" = yes; then + if test "$allow_undefined_flag" = unsupported; then + $echo "$modename: warning: undefined symbols not allowed in $host shared libraries" 1>&2 + build_libtool_libs=no + build_old_libs=yes + fi + else + # Don't allow undefined symbols. + allow_undefined_flag="$no_undefined_flag" + fi + fi + + if test "$mode" != relink; then + # Remove our outputs, but don't remove object files since they + # may have been created when compiling PIC objects. + removelist= + tempremovelist=`$echo "$output_objdir/*"` + for p in $tempremovelist; do + case $p in + *.$objext) + ;; + $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/${libname}${release}.*) + if test "X$precious_files_regex" != "X"; then + if echo $p | $EGREP -e "$precious_files_regex" >/dev/null 2>&1 + then + continue + fi + fi + removelist="$removelist $p" + ;; + *) ;; + esac + done + if test -n "$removelist"; then + $show "${rm}r $removelist" + $run ${rm}r $removelist + fi + fi + + # Now set the variables for building old libraries. + if test "$build_old_libs" = yes && test "$build_libtool_libs" != convenience ; then + oldlibs="$oldlibs $output_objdir/$libname.$libext" + + # Transform .lo files to .o files. + oldobjs="$objs "`$echo "X$libobjs" | $SP2NL | $Xsed -e '/\.'${libext}'$/d' -e "$lo2o" | $NL2SP` + fi + + # Eliminate all temporary directories. + for path in $notinst_path; do + lib_search_path=`$echo "$lib_search_path " | ${SED} -e 's% $path % %g'` + deplibs=`$echo "$deplibs " | ${SED} -e 's% -L$path % %g'` + dependency_libs=`$echo "$dependency_libs " | ${SED} -e 's% -L$path % %g'` + done + + if test -n "$xrpath"; then + # If the user specified any rpath flags, then add them. + temp_xrpath= + for libdir in $xrpath; do + temp_xrpath="$temp_xrpath -R$libdir" + case "$finalize_rpath " in + *" $libdir "*) ;; + *) finalize_rpath="$finalize_rpath $libdir" ;; + esac + done + if test "$hardcode_into_libs" != yes || test "$build_old_libs" = yes; then + dependency_libs="$temp_xrpath $dependency_libs" + fi + fi + + # Make sure dlfiles contains only unique files that won't be dlpreopened + old_dlfiles="$dlfiles" + dlfiles= + for lib in $old_dlfiles; do + case " $dlprefiles $dlfiles " in + *" $lib "*) ;; + *) dlfiles="$dlfiles $lib" ;; + esac + done + + # Make sure dlprefiles contains only unique files + old_dlprefiles="$dlprefiles" + dlprefiles= + for lib in $old_dlprefiles; do + case "$dlprefiles " in + *" $lib "*) ;; + *) dlprefiles="$dlprefiles $lib" ;; + esac + done + + if test "$build_libtool_libs" = yes; then + if test -n "$rpath"; then + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos*) + # these systems don't actually have a c library (as such)! + ;; + *-*-rhapsody* | *-*-darwin1.[012]) + # Rhapsody C library is in the System framework + deplibs="$deplibs -framework System" + ;; + *-*-netbsd*) + # Don't link with libc until the a.out ld.so is fixed. + ;; + *-*-openbsd* | *-*-freebsd*) + # Do not include libc due to us having libc/libc_r. + test "X$arg" = "X-lc" && continue + ;; + *) + # Add libc to deplibs on all other systems if necessary. + if test "$build_libtool_need_lc" = "yes"; then + deplibs="$deplibs -lc" + fi + ;; + esac + fi + + # Transform deplibs into only deplibs that can be linked in shared. + name_save=$name + libname_save=$libname + release_save=$release + versuffix_save=$versuffix + major_save=$major + # I'm not sure if I'm treating the release correctly. I think + # release should show up in the -l (ie -lgmp5) so we don't want to + # add it in twice. Is that correct? + release="" + versuffix="" + major="" + newdeplibs= + droppeddeps=no + case $deplibs_check_method in + pass_all) + # Don't check for shared/static. Everything works. + # This might be a little naive. We might want to check + # whether the library exists or not. But this is on + # osf3 & osf4 and I'm not really sure... Just + # implementing what was already the behavior. + newdeplibs=$deplibs + ;; + test_compile) + # This code stresses the "libraries are programs" paradigm to its + # limits. Maybe even breaks it. We compile a program, linking it + # against the deplibs as a proxy for the library. Then we can check + # whether they linked in statically or dynamically with ldd. + $rm conftest.c + cat > conftest.c </dev/null` + for potent_lib in $potential_libs; do + # Follow soft links. + if ls -lLd "$potent_lib" 2>/dev/null \ + | grep " -> " >/dev/null; then + continue + fi + # The statement above tries to avoid entering an + # endless loop below, in case of cyclic links. + # We might still enter an endless loop, since a link + # loop can be closed while we follow links, + # but so what? + potlib="$potent_lib" + while test -h "$potlib" 2>/dev/null; do + potliblink=`ls -ld $potlib | ${SED} 's/.* -> //'` + case $potliblink in + [\\/]* | [A-Za-z]:[\\/]*) potlib="$potliblink";; + *) potlib=`$echo "X$potlib" | $Xsed -e 's,[^/]*$,,'`"$potliblink";; + esac + done + if eval $file_magic_cmd \"\$potlib\" 2>/dev/null \ + | ${SED} 10q \ + | $EGREP "$file_magic_regex" > /dev/null; then + newdeplibs="$newdeplibs $a_deplib" + a_deplib="" + break 2 + fi + done + done + fi + if test -n "$a_deplib" ; then + droppeddeps=yes + $echo + $echo "*** Warning: linker path does not have real file for library $a_deplib." + $echo "*** I have the capability to make that library automatically link in when" + $echo "*** you link to this library. But I can only do this if you have a" + $echo "*** shared version of the library, which you do not appear to have" + $echo "*** because I did check the linker path looking for a file starting" + if test -z "$potlib" ; then + $echo "*** with $libname but no candidates were found. (...for file magic test)" + else + $echo "*** with $libname and none of the candidates passed a file format test" + $echo "*** using a file magic. Last file checked: $potlib" + fi + fi + else + # Add a -L argument. + newdeplibs="$newdeplibs $a_deplib" + fi + done # Gone through all deplibs. + ;; + match_pattern*) + set dummy $deplibs_check_method + match_pattern_regex=`expr "$deplibs_check_method" : "$2 \(.*\)"` + for a_deplib in $deplibs; do + name="`expr $a_deplib : '-l\(.*\)'`" + # If $name is empty we are operating on a -L argument. + if test -n "$name" && test "$name" != "0"; then + if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then + case " $predeps $postdeps " in + *" $a_deplib "*) + newdeplibs="$newdeplibs $a_deplib" + a_deplib="" + ;; + esac + fi + if test -n "$a_deplib" ; then + libname=`eval \\$echo \"$libname_spec\"` + for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do + potential_libs=`ls $i/$libname[.-]* 2>/dev/null` + for potent_lib in $potential_libs; do + potlib="$potent_lib" # see symlink-check above in file_magic test + if eval $echo \"$potent_lib\" 2>/dev/null \ + | ${SED} 10q \ + | $EGREP "$match_pattern_regex" > /dev/null; then + newdeplibs="$newdeplibs $a_deplib" + a_deplib="" + break 2 + fi + done + done + fi + if test -n "$a_deplib" ; then + droppeddeps=yes + $echo + $echo "*** Warning: linker path does not have real file for library $a_deplib." + $echo "*** I have the capability to make that library automatically link in when" + $echo "*** you link to this library. But I can only do this if you have a" + $echo "*** shared version of the library, which you do not appear to have" + $echo "*** because I did check the linker path looking for a file starting" + if test -z "$potlib" ; then + $echo "*** with $libname but no candidates were found. (...for regex pattern test)" + else + $echo "*** with $libname and none of the candidates passed a file format test" + $echo "*** using a regex pattern. Last file checked: $potlib" + fi + fi + else + # Add a -L argument. + newdeplibs="$newdeplibs $a_deplib" + fi + done # Gone through all deplibs. + ;; + none | unknown | *) + newdeplibs="" + tmp_deplibs=`$echo "X $deplibs" | $Xsed -e 's/ -lc$//' \ + -e 's/ -[LR][^ ]*//g'` + if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then + for i in $predeps $postdeps ; do + # can't use Xsed below, because $i might contain '/' + tmp_deplibs=`$echo "X $tmp_deplibs" | ${SED} -e "1s,^X,," -e "s,$i,,"` + done + fi + if $echo "X $tmp_deplibs" | $Xsed -e 's/[ ]//g' \ + | grep . >/dev/null; then + $echo + if test "X$deplibs_check_method" = "Xnone"; then + $echo "*** Warning: inter-library dependencies are not supported in this platform." + else + $echo "*** Warning: inter-library dependencies are not known to be supported." + fi + $echo "*** All declared inter-library dependencies are being dropped." + droppeddeps=yes + fi + ;; + esac + versuffix=$versuffix_save + major=$major_save + release=$release_save + libname=$libname_save + name=$name_save + + case $host in + *-*-rhapsody* | *-*-darwin1.[012]) + # On Rhapsody replace the C library is the System framework + newdeplibs=`$echo "X $newdeplibs" | $Xsed -e 's/ -lc / -framework System /'` + ;; + esac + + if test "$droppeddeps" = yes; then + if test "$module" = yes; then + $echo + $echo "*** Warning: libtool could not satisfy all declared inter-library" + $echo "*** dependencies of module $libname. Therefore, libtool will create" + $echo "*** a static module, that should work as long as the dlopening" + $echo "*** application is linked with the -dlopen flag." + if test -z "$global_symbol_pipe"; then + $echo + $echo "*** However, this would only work if libtool was able to extract symbol" + $echo "*** lists from a program, using \`nm' or equivalent, but libtool could" + $echo "*** not find such a program. So, this module is probably useless." + $echo "*** \`nm' from GNU binutils and a full rebuild may help." + fi + if test "$build_old_libs" = no; then + oldlibs="$output_objdir/$libname.$libext" + build_libtool_libs=module + build_old_libs=yes + else + build_libtool_libs=no + fi + else + $echo "*** The inter-library dependencies that have been dropped here will be" + $echo "*** automatically added whenever a program is linked with this library" + $echo "*** or is declared to -dlopen it." + + if test "$allow_undefined" = no; then + $echo + $echo "*** Since this library must not contain undefined symbols," + $echo "*** because either the platform does not support them or" + $echo "*** it was explicitly requested with -no-undefined," + $echo "*** libtool will only create a static version of it." + if test "$build_old_libs" = no; then + oldlibs="$output_objdir/$libname.$libext" + build_libtool_libs=module + build_old_libs=yes + else + build_libtool_libs=no + fi + fi + fi + fi + # Done checking deplibs! + deplibs=$newdeplibs + fi + + # All the library-specific variables (install_libdir is set above). + library_names= + old_library= + dlname= + + # Test again, we may have decided not to build it any more + if test "$build_libtool_libs" = yes; then + if test "$hardcode_into_libs" = yes; then + # Hardcode the library paths + hardcode_libdirs= + dep_rpath= + rpath="$finalize_rpath" + test "$mode" != relink && rpath="$compile_rpath$rpath" + for libdir in $rpath; do + if test -n "$hardcode_libdir_flag_spec"; then + if test -n "$hardcode_libdir_separator"; then + if test -z "$hardcode_libdirs"; then + hardcode_libdirs="$libdir" + else + # Just accumulate the unique libdirs. + case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in + *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) + ;; + *) + hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir" + ;; + esac + fi + else + eval flag=\"$hardcode_libdir_flag_spec\" + dep_rpath="$dep_rpath $flag" + fi + elif test -n "$runpath_var"; then + case "$perm_rpath " in + *" $libdir "*) ;; + *) perm_rpath="$perm_rpath $libdir" ;; + esac + fi + done + # Substitute the hardcoded libdirs into the rpath. + if test -n "$hardcode_libdir_separator" && + test -n "$hardcode_libdirs"; then + libdir="$hardcode_libdirs" + if test -n "$hardcode_libdir_flag_spec_ld"; then + eval dep_rpath=\"$hardcode_libdir_flag_spec_ld\" + else + eval dep_rpath=\"$hardcode_libdir_flag_spec\" + fi + fi + if test -n "$runpath_var" && test -n "$perm_rpath"; then + # We should set the runpath_var. + rpath= + for dir in $perm_rpath; do + rpath="$rpath$dir:" + done + eval "$runpath_var='$rpath\$$runpath_var'; export $runpath_var" + fi + test -n "$dep_rpath" && deplibs="$dep_rpath $deplibs" + fi + + shlibpath="$finalize_shlibpath" + test "$mode" != relink && shlibpath="$compile_shlibpath$shlibpath" + if test -n "$shlibpath"; then + eval "$shlibpath_var='$shlibpath\$$shlibpath_var'; export $shlibpath_var" + fi + + # Get the real and link names of the library. + eval shared_ext=\"$shrext_cmds\" + eval library_names=\"$library_names_spec\" + set dummy $library_names + realname="$2" + shift; shift + + if test -n "$soname_spec"; then + eval soname=\"$soname_spec\" + else + soname="$realname" + fi + if test -z "$dlname"; then + dlname=$soname + fi + + lib="$output_objdir/$realname" + for link + do + linknames="$linknames $link" + done + + # Use standard objects if they are pic + test -z "$pic_flag" && libobjs=`$echo "X$libobjs" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP` + + # Prepare the list of exported symbols + if test -z "$export_symbols"; then + if test "$always_export_symbols" = yes || test -n "$export_symbols_regex"; then + $show "generating symbol list for \`$libname.la'" + export_symbols="$output_objdir/$libname.exp" + $run $rm $export_symbols + cmds=$export_symbols_cmds + save_ifs="$IFS"; IFS='~' + for cmd in $cmds; do + IFS="$save_ifs" + eval cmd=\"$cmd\" + if len=`expr "X$cmd" : ".*"` && + test "$len" -le "$max_cmd_len" || test "$max_cmd_len" -le -1; then + $show "$cmd" + $run eval "$cmd" || exit $? + skipped_export=false + else + # The command line is too long to execute in one step. + $show "using reloadable object file for export list..." + skipped_export=: + fi + done + IFS="$save_ifs" + if test -n "$export_symbols_regex"; then + $show "$EGREP -e \"$export_symbols_regex\" \"$export_symbols\" > \"${export_symbols}T\"" + $run eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' + $show "$mv \"${export_symbols}T\" \"$export_symbols\"" + $run eval '$mv "${export_symbols}T" "$export_symbols"' + fi + fi + fi + + if test -n "$export_symbols" && test -n "$include_expsyms"; then + $run eval '$echo "X$include_expsyms" | $SP2NL >> "$export_symbols"' + fi + + tmp_deplibs= + for test_deplib in $deplibs; do + case " $convenience " in + *" $test_deplib "*) ;; + *) + tmp_deplibs="$tmp_deplibs $test_deplib" + ;; + esac + done + deplibs="$tmp_deplibs" + + if test -n "$convenience"; then + if test -n "$whole_archive_flag_spec"; then + save_libobjs=$libobjs + eval libobjs=\"\$libobjs $whole_archive_flag_spec\" + else + gentop="$output_objdir/${outputname}x" + $show "${rm}r $gentop" + $run ${rm}r "$gentop" + $show "$mkdir $gentop" + $run $mkdir "$gentop" + status=$? + if test "$status" -ne 0 && test ! -d "$gentop"; then + exit $status + fi + generated="$generated $gentop" + + for xlib in $convenience; do + # Extract the objects. + case $xlib in + [\\/]* | [A-Za-z]:[\\/]*) xabs="$xlib" ;; + *) xabs=`pwd`"/$xlib" ;; + esac + xlib=`$echo "X$xlib" | $Xsed -e 's%^.*/%%'` + xdir="$gentop/$xlib" + + $show "${rm}r $xdir" + $run ${rm}r "$xdir" + $show "$mkdir $xdir" + $run $mkdir "$xdir" + status=$? + if test "$status" -ne 0 && test ! -d "$xdir"; then + exit $status + fi + # We will extract separately just the conflicting names and we will no + # longer touch any unique names. It is faster to leave these extract + # automatically by $AR in one run. + $show "(cd $xdir && $AR x $xabs)" + $run eval "(cd \$xdir && $AR x \$xabs)" || exit $? + if ($AR t "$xabs" | sort | sort -uc >/dev/null 2>&1); then + : + else + $echo "$modename: warning: object name conflicts; renaming object files" 1>&2 + $echo "$modename: warning: to ensure that they will not overwrite" 1>&2 + $AR t "$xabs" | sort | uniq -cd | while read -r count name + do + i=1 + while test "$i" -le "$count" + do + # Put our $i before any first dot (extension) + # Never overwrite any file + name_to="$name" + while test "X$name_to" = "X$name" || test -f "$xdir/$name_to" + do + name_to=`$echo "X$name_to" | $Xsed -e "s/\([^.]*\)/\1-$i/"` + done + $show "(cd $xdir && $AR xN $i $xabs '$name' && $mv '$name' '$name_to')" + $run eval "(cd \$xdir && $AR xN $i \$xabs '$name' && $mv '$name' '$name_to')" || exit $? + i=`expr $i + 1` + done + done + fi + + libobjs="$libobjs "`find $xdir -name \*.$objext -print -o -name \*.lo -print | $NL2SP` + done + fi + fi + + if test "$thread_safe" = yes && test -n "$thread_safe_flag_spec"; then + eval flag=\"$thread_safe_flag_spec\" + linker_flags="$linker_flags $flag" + fi + + # Make a backup of the uninstalled library when relinking + if test "$mode" = relink; then + $run eval '(cd $output_objdir && $rm ${realname}U && $mv $realname ${realname}U)' || exit $? + fi + + # Do each of the archive commands. + if test "$module" = yes && test -n "$module_cmds" ; then + if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then + eval test_cmds=\"$module_expsym_cmds\" + cmds=$module_expsym_cmds + else + eval test_cmds=\"$module_cmds\" + cmds=$module_cmds + fi + else + if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then + eval test_cmds=\"$archive_expsym_cmds\" + cmds=$archive_expsym_cmds + else + eval test_cmds=\"$archive_cmds\" + cmds=$archive_cmds + fi + fi + + if test "X$skipped_export" != "X:" && len=`expr "X$test_cmds" : ".*"` && + test "$len" -le "$max_cmd_len" || test "$max_cmd_len" -le -1; then + : + else + # The command line is too long to link in one step, link piecewise. + $echo "creating reloadable object files..." + + # Save the value of $output and $libobjs because we want to + # use them later. If we have whole_archive_flag_spec, we + # want to use save_libobjs as it was before + # whole_archive_flag_spec was expanded, because we can't + # assume the linker understands whole_archive_flag_spec. + # This may have to be revisited, in case too many + # convenience libraries get linked in and end up exceeding + # the spec. + if test -z "$convenience" || test -z "$whole_archive_flag_spec"; then + save_libobjs=$libobjs + fi + save_output=$output + + # Clear the reloadable object creation command queue and + # initialize k to one. + test_cmds= + concat_cmds= + objlist= + delfiles= + last_robj= + k=1 + output=$output_objdir/$save_output-${k}.$objext + # Loop over the list of objects to be linked. + for obj in $save_libobjs + do + eval test_cmds=\"$reload_cmds $objlist $last_robj\" + if test "X$objlist" = X || + { len=`expr "X$test_cmds" : ".*"` && + test "$len" -le "$max_cmd_len"; }; then + objlist="$objlist $obj" + else + # The command $test_cmds is almost too long, add a + # command to the queue. + if test "$k" -eq 1 ; then + # The first file doesn't have a previous command to add. + eval concat_cmds=\"$reload_cmds $objlist $last_robj\" + else + # All subsequent reloadable object files will link in + # the last one created. + eval concat_cmds=\"\$concat_cmds~$reload_cmds $objlist $last_robj\" + fi + last_robj=$output_objdir/$save_output-${k}.$objext + k=`expr $k + 1` + output=$output_objdir/$save_output-${k}.$objext + objlist=$obj + len=1 + fi + done + # Handle the remaining objects by creating one last + # reloadable object file. All subsequent reloadable object + # files will link in the last one created. + test -z "$concat_cmds" || concat_cmds=$concat_cmds~ + eval concat_cmds=\"\${concat_cmds}$reload_cmds $objlist $last_robj\" + + if ${skipped_export-false}; then + $show "generating symbol list for \`$libname.la'" + export_symbols="$output_objdir/$libname.exp" + $run $rm $export_symbols + libobjs=$output + # Append the command to create the export file. + eval concat_cmds=\"\$concat_cmds~$export_symbols_cmds\" + fi + + # Set up a command to remove the reloadale object files + # after they are used. + i=0 + while test "$i" -lt "$k" + do + i=`expr $i + 1` + delfiles="$delfiles $output_objdir/$save_output-${i}.$objext" + done + + $echo "creating a temporary reloadable object file: $output" + + # Loop through the commands generated above and execute them. + save_ifs="$IFS"; IFS='~' + for cmd in $concat_cmds; do + IFS="$save_ifs" + $show "$cmd" + $run eval "$cmd" || exit $? + done + IFS="$save_ifs" + + libobjs=$output + # Restore the value of output. + output=$save_output + + if test -n "$convenience" && test -n "$whole_archive_flag_spec"; then + eval libobjs=\"\$libobjs $whole_archive_flag_spec\" + fi + # Expand the library linking commands again to reset the + # value of $libobjs for piecewise linking. + + # Do each of the archive commands. + if test "$module" = yes && test -n "$module_cmds" ; then + if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then + cmds=$module_expsym_cmds + else + cmds=$module_cmds + fi + else + if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then + cmds=$archive_expsym_cmds + else + cmds=$archive_cmds + fi + fi + + # Append the command to remove the reloadable object files + # to the just-reset $cmds. + eval cmds=\"\$cmds~\$rm $delfiles\" + fi + save_ifs="$IFS"; IFS='~' + for cmd in $cmds; do + IFS="$save_ifs" + eval cmd=\"$cmd\" + $show "$cmd" + $run eval "$cmd" || exit $? + done + IFS="$save_ifs" + + # Restore the uninstalled library and exit + if test "$mode" = relink; then + $run eval '(cd $output_objdir && $rm ${realname}T && $mv $realname ${realname}T && $mv "$realname"U $realname)' || exit $? + exit $EXIT_SUCCESS + fi + + # Create links to the real library. + for linkname in $linknames; do + if test "$realname" != "$linkname"; then + $show "(cd $output_objdir && $rm $linkname && $LN_S $realname $linkname)" + $run eval '(cd $output_objdir && $rm $linkname && $LN_S $realname $linkname)' || exit $? + fi + done + + # If -module or -export-dynamic was specified, set the dlname. + if test "$module" = yes || test "$export_dynamic" = yes; then + # On all known operating systems, these are identical. + dlname="$soname" + fi + fi + ;; + + obj) + if test -n "$deplibs"; then + $echo "$modename: warning: \`-l' and \`-L' are ignored for objects" 1>&2 + fi + + if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then + $echo "$modename: warning: \`-dlopen' is ignored for objects" 1>&2 + fi + + if test -n "$rpath"; then + $echo "$modename: warning: \`-rpath' is ignored for objects" 1>&2 + fi + + if test -n "$xrpath"; then + $echo "$modename: warning: \`-R' is ignored for objects" 1>&2 + fi + + if test -n "$vinfo"; then + $echo "$modename: warning: \`-version-info' is ignored for objects" 1>&2 + fi + + if test -n "$release"; then + $echo "$modename: warning: \`-release' is ignored for objects" 1>&2 + fi + + case $output in + *.lo) + if test -n "$objs$old_deplibs"; then + $echo "$modename: cannot build library object \`$output' from non-libtool objects" 1>&2 + exit $EXIT_FAILURE + fi + libobj="$output" + obj=`$echo "X$output" | $Xsed -e "$lo2o"` + ;; + *) + libobj= + obj="$output" + ;; + esac + + # Delete the old objects. + $run $rm $obj $libobj + + # Objects from convenience libraries. This assumes + # single-version convenience libraries. Whenever we create + # different ones for PIC/non-PIC, this we'll have to duplicate + # the extraction. + reload_conv_objs= + gentop= + # reload_cmds runs $LD directly, so let us get rid of + # -Wl from whole_archive_flag_spec + wl= + + if test -n "$convenience"; then + if test -n "$whole_archive_flag_spec"; then + eval reload_conv_objs=\"\$reload_objs $whole_archive_flag_spec\" + else + gentop="$output_objdir/${obj}x" + $show "${rm}r $gentop" + $run ${rm}r "$gentop" + $show "$mkdir $gentop" + $run $mkdir "$gentop" + status=$? + if test "$status" -ne 0 && test ! -d "$gentop"; then + exit $status + fi + generated="$generated $gentop" + + for xlib in $convenience; do + # Extract the objects. + case $xlib in + [\\/]* | [A-Za-z]:[\\/]*) xabs="$xlib" ;; + *) xabs=`pwd`"/$xlib" ;; + esac + xlib=`$echo "X$xlib" | $Xsed -e 's%^.*/%%'` + xdir="$gentop/$xlib" + + $show "${rm}r $xdir" + $run ${rm}r "$xdir" + $show "$mkdir $xdir" + $run $mkdir "$xdir" + status=$? + if test "$status" -ne 0 && test ! -d "$xdir"; then + exit $status + fi + # We will extract separately just the conflicting names and we will no + # longer touch any unique names. It is faster to leave these extract + # automatically by $AR in one run. + $show "(cd $xdir && $AR x $xabs)" + $run eval "(cd \$xdir && $AR x \$xabs)" || exit $? + if ($AR t "$xabs" | sort | sort -uc >/dev/null 2>&1); then + : + else + $echo "$modename: warning: object name conflicts; renaming object files" 1>&2 + $echo "$modename: warning: to ensure that they will not overwrite" 1>&2 + $AR t "$xabs" | sort | uniq -cd | while read -r count name + do + i=1 + while test "$i" -le "$count" + do + # Put our $i before any first dot (extension) + # Never overwrite any file + name_to="$name" + while test "X$name_to" = "X$name" || test -f "$xdir/$name_to" + do + name_to=`$echo "X$name_to" | $Xsed -e "s/\([^.]*\)/\1-$i/"` + done + $show "(cd $xdir && $AR xN $i $xabs '$name' && $mv '$name' '$name_to')" + $run eval "(cd \$xdir && $AR xN $i \$xabs '$name' && $mv '$name' '$name_to')" || exit $? + i=`expr $i + 1` + done + done + fi + + reload_conv_objs="$reload_objs "`find $xdir -name \*.$objext -print -o -name \*.lo -print | $NL2SP` + done + fi + fi + + # Create the old-style object. + reload_objs="$objs$old_deplibs "`$echo "X$libobjs" | $SP2NL | $Xsed -e '/\.'${libext}$'/d' -e '/\.lib$/d' -e "$lo2o" | $NL2SP`" $reload_conv_objs" ### testsuite: skip nested quoting test + + output="$obj" + cmds=$reload_cmds + save_ifs="$IFS"; IFS='~' + for cmd in $cmds; do + IFS="$save_ifs" + eval cmd=\"$cmd\" + $show "$cmd" + $run eval "$cmd" || exit $? + done + IFS="$save_ifs" + + # Exit if we aren't doing a library object file. + if test -z "$libobj"; then + if test -n "$gentop"; then + $show "${rm}r $gentop" + $run ${rm}r $gentop + fi + + exit $EXIT_SUCCESS + fi + + if test "$build_libtool_libs" != yes; then + if test -n "$gentop"; then + $show "${rm}r $gentop" + $run ${rm}r $gentop + fi + + # Create an invalid libtool object if no PIC, so that we don't + # accidentally link it into a program. + # $show "echo timestamp > $libobj" + # $run eval "echo timestamp > $libobj" || exit $? + exit $EXIT_SUCCESS + fi + + if test -n "$pic_flag" || test "$pic_mode" != default; then + # Only do commands if we really have different PIC objects. + reload_objs="$libobjs $reload_conv_objs" + output="$libobj" + cmds=$reload_cmds + save_ifs="$IFS"; IFS='~' + for cmd in $cmds; do + IFS="$save_ifs" + eval cmd=\"$cmd\" + $show "$cmd" + $run eval "$cmd" || exit $? + done + IFS="$save_ifs" + fi + + if test -n "$gentop"; then + $show "${rm}r $gentop" + $run ${rm}r $gentop + fi + + exit $EXIT_SUCCESS + ;; + + prog) + case $host in + *cygwin*) output=`$echo $output | ${SED} -e 's,.exe$,,;s,$,.exe,'` ;; + esac + if test -n "$vinfo"; then + $echo "$modename: warning: \`-version-info' is ignored for programs" 1>&2 + fi + + if test -n "$release"; then + $echo "$modename: warning: \`-release' is ignored for programs" 1>&2 + fi + + if test "$preload" = yes; then + if test "$dlopen_support" = unknown && test "$dlopen_self" = unknown && + test "$dlopen_self_static" = unknown; then + $echo "$modename: warning: \`AC_LIBTOOL_DLOPEN' not used. Assuming no dlopen support." + fi + fi + + case $host in + *-*-rhapsody* | *-*-darwin1.[012]) + # On Rhapsody replace the C library is the System framework + compile_deplibs=`$echo "X $compile_deplibs" | $Xsed -e 's/ -lc / -framework System /'` + finalize_deplibs=`$echo "X $finalize_deplibs" | $Xsed -e 's/ -lc / -framework System /'` + ;; + esac + + case $host in + *darwin*) + # Don't allow lazy linking, it breaks C++ global constructors + if test "$tagname" = CXX ; then + compile_command="$compile_command ${wl}-bind_at_load" + finalize_command="$finalize_command ${wl}-bind_at_load" + fi + ;; + esac + + compile_command="$compile_command $compile_deplibs" + finalize_command="$finalize_command $finalize_deplibs" + + if test -n "$rpath$xrpath"; then + # If the user specified any rpath flags, then add them. + for libdir in $rpath $xrpath; do + # This is the magic to use -rpath. + case "$finalize_rpath " in + *" $libdir "*) ;; + *) finalize_rpath="$finalize_rpath $libdir" ;; + esac + done + fi + + # Now hardcode the library paths + rpath= + hardcode_libdirs= + for libdir in $compile_rpath $finalize_rpath; do + if test -n "$hardcode_libdir_flag_spec"; then + if test -n "$hardcode_libdir_separator"; then + if test -z "$hardcode_libdirs"; then + hardcode_libdirs="$libdir" + else + # Just accumulate the unique libdirs. + case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in + *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) + ;; + *) + hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir" + ;; + esac + fi + else + eval flag=\"$hardcode_libdir_flag_spec\" + rpath="$rpath $flag" + fi + elif test -n "$runpath_var"; then + case "$perm_rpath " in + *" $libdir "*) ;; + *) perm_rpath="$perm_rpath $libdir" ;; + esac + fi + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*) + case :$dllsearchpath: in + *":$libdir:"*) ;; + *) dllsearchpath="$dllsearchpath:$libdir";; + esac + ;; + esac + done + # Substitute the hardcoded libdirs into the rpath. + if test -n "$hardcode_libdir_separator" && + test -n "$hardcode_libdirs"; then + libdir="$hardcode_libdirs" + eval rpath=\" $hardcode_libdir_flag_spec\" + fi + compile_rpath="$rpath" + + rpath= + hardcode_libdirs= + for libdir in $finalize_rpath; do + if test -n "$hardcode_libdir_flag_spec"; then + if test -n "$hardcode_libdir_separator"; then + if test -z "$hardcode_libdirs"; then + hardcode_libdirs="$libdir" + else + # Just accumulate the unique libdirs. + case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in + *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) + ;; + *) + hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir" + ;; + esac + fi + else + eval flag=\"$hardcode_libdir_flag_spec\" + rpath="$rpath $flag" + fi + elif test -n "$runpath_var"; then + case "$finalize_perm_rpath " in + *" $libdir "*) ;; + *) finalize_perm_rpath="$finalize_perm_rpath $libdir" ;; + esac + fi + done + # Substitute the hardcoded libdirs into the rpath. + if test -n "$hardcode_libdir_separator" && + test -n "$hardcode_libdirs"; then + libdir="$hardcode_libdirs" + eval rpath=\" $hardcode_libdir_flag_spec\" + fi + finalize_rpath="$rpath" + + if test -n "$libobjs" && test "$build_old_libs" = yes; then + # Transform all the library objects into standard objects. + compile_command=`$echo "X$compile_command" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP` + finalize_command=`$echo "X$finalize_command" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP` + fi + + dlsyms= + if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then + if test -n "$NM" && test -n "$global_symbol_pipe"; then + dlsyms="${outputname}S.c" + else + $echo "$modename: not configured to extract global symbols from dlpreopened files" 1>&2 + fi + fi + + if test -n "$dlsyms"; then + case $dlsyms in + "") ;; + *.c) + # Discover the nlist of each of the dlfiles. + nlist="$output_objdir/${outputname}.nm" + + $show "$rm $nlist ${nlist}S ${nlist}T" + $run $rm "$nlist" "${nlist}S" "${nlist}T" + + # Parse the name list into a source file. + $show "creating $output_objdir/$dlsyms" + + test -z "$run" && $echo > "$output_objdir/$dlsyms" "\ +/* $dlsyms - symbol resolution table for \`$outputname' dlsym emulation. */ +/* Generated by $PROGRAM - GNU $PACKAGE $VERSION$TIMESTAMP */ + +#ifdef __cplusplus +extern \"C\" { +#endif + +/* Prevent the only kind of declaration conflicts we can make. */ +#define lt_preloaded_symbols some_other_symbol + +/* External symbol declarations for the compiler. */\ +" + + if test "$dlself" = yes; then + $show "generating symbol list for \`$output'" + + test -z "$run" && $echo ': @PROGRAM@ ' > "$nlist" + + # Add our own program objects to the symbol list. + progfiles=`$echo "X$objs$old_deplibs" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP` + for arg in $progfiles; do + $show "extracting global C symbols from \`$arg'" + $run eval "$NM $arg | $global_symbol_pipe >> '$nlist'" + done + + if test -n "$exclude_expsyms"; then + $run eval '$EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T' + $run eval '$mv "$nlist"T "$nlist"' + fi + + if test -n "$export_symbols_regex"; then + $run eval '$EGREP -e "$export_symbols_regex" "$nlist" > "$nlist"T' + $run eval '$mv "$nlist"T "$nlist"' + fi + + # Prepare the list of exported symbols + if test -z "$export_symbols"; then + export_symbols="$output_objdir/$output.exp" + $run $rm $export_symbols + $run eval "${SED} -n -e '/^: @PROGRAM@$/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"' + else + $run eval "${SED} -e 's/\([][.*^$]\)/\\\1/g' -e 's/^/ /' -e 's/$/$/'"' < "$export_symbols" > "$output_objdir/$output.exp"' + $run eval 'grep -f "$output_objdir/$output.exp" < "$nlist" > "$nlist"T' + $run eval 'mv "$nlist"T "$nlist"' + fi + fi + + for arg in $dlprefiles; do + $show "extracting global C symbols from \`$arg'" + name=`$echo "$arg" | ${SED} -e 's%^.*/%%'` + $run eval '$echo ": $name " >> "$nlist"' + $run eval "$NM $arg | $global_symbol_pipe >> '$nlist'" + done + + if test -z "$run"; then + # Make sure we have at least an empty file. + test -f "$nlist" || : > "$nlist" + + if test -n "$exclude_expsyms"; then + $EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T + $mv "$nlist"T "$nlist" + fi + + # Try sorting and uniquifying the output. + if grep -v "^: " < "$nlist" | + if sort -k 3 /dev/null 2>&1; then + sort -k 3 + else + sort +2 + fi | + uniq > "$nlist"S; then + : + else + grep -v "^: " < "$nlist" > "$nlist"S + fi + + if test -f "$nlist"S; then + eval "$global_symbol_to_cdecl"' < "$nlist"S >> "$output_objdir/$dlsyms"' + else + $echo '/* NONE */' >> "$output_objdir/$dlsyms" + fi + + $echo >> "$output_objdir/$dlsyms" "\ + +#undef lt_preloaded_symbols + +#if defined (__STDC__) && __STDC__ +# define lt_ptr void * +#else +# define lt_ptr char * +# define const +#endif + +/* The mapping between symbol names and symbols. */ +const struct { + const char *name; + lt_ptr address; +} +lt_preloaded_symbols[] = +{\ +" + + eval "$global_symbol_to_c_name_address" < "$nlist" >> "$output_objdir/$dlsyms" + + $echo >> "$output_objdir/$dlsyms" "\ + {0, (lt_ptr) 0} +}; + +/* This works around a problem in FreeBSD linker */ +#ifdef FREEBSD_WORKAROUND +static const void *lt_preloaded_setup() { + return lt_preloaded_symbols; +} +#endif + +#ifdef __cplusplus +} +#endif\ +" + fi + + pic_flag_for_symtable= + case $host in + # compiling the symbol table file with pic_flag works around + # a FreeBSD bug that causes programs to crash when -lm is + # linked before any other PIC object. But we must not use + # pic_flag when linking with -static. The problem exists in + # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1. + *-*-freebsd2*|*-*-freebsd3.0*|*-*-freebsdelf3.0*) + case "$compile_command " in + *" -static "*) ;; + *) pic_flag_for_symtable=" $pic_flag -DFREEBSD_WORKAROUND";; + esac;; + *-*-hpux*) + case "$compile_command " in + *" -static "*) ;; + *) pic_flag_for_symtable=" $pic_flag";; + esac + esac + + # Now compile the dynamic symbol file. + $show "(cd $output_objdir && $LTCC -c$no_builtin_flag$pic_flag_for_symtable \"$dlsyms\")" + $run eval '(cd $output_objdir && $LTCC -c$no_builtin_flag$pic_flag_for_symtable "$dlsyms")' || exit $? + + # Clean up the generated files. + $show "$rm $output_objdir/$dlsyms $nlist ${nlist}S ${nlist}T" + $run $rm "$output_objdir/$dlsyms" "$nlist" "${nlist}S" "${nlist}T" + + # Transform the symbol file into the correct name. + compile_command=`$echo "X$compile_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%"` + finalize_command=`$echo "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%"` + ;; + *) + $echo "$modename: unknown suffix for \`$dlsyms'" 1>&2 + exit $EXIT_FAILURE + ;; + esac + else + # We keep going just in case the user didn't refer to + # lt_preloaded_symbols. The linker will fail if global_symbol_pipe + # really was required. + + # Nullify the symbol file. + compile_command=`$echo "X$compile_command" | $Xsed -e "s% @SYMFILE@%%"` + finalize_command=`$echo "X$finalize_command" | $Xsed -e "s% @SYMFILE@%%"` + fi + + if test "$need_relink" = no || test "$build_libtool_libs" != yes; then + # Replace the output file specification. + compile_command=`$echo "X$compile_command" | $Xsed -e 's%@OUTPUT@%'"$output"'%g'` + link_command="$compile_command$compile_rpath" + + # We have no uninstalled library dependencies, so finalize right now. + $show "$link_command" + $run eval "$link_command" + status=$? + + # Delete the generated files. + if test -n "$dlsyms"; then + $show "$rm $output_objdir/${outputname}S.${objext}" + $run $rm "$output_objdir/${outputname}S.${objext}" + fi + + exit $status + fi + + if test -n "$shlibpath_var"; then + # We should set the shlibpath_var + rpath= + for dir in $temp_rpath; do + case $dir in + [\\/]* | [A-Za-z]:[\\/]*) + # Absolute path. + rpath="$rpath$dir:" + ;; + *) + # Relative path: add a thisdir entry. + rpath="$rpath\$thisdir/$dir:" + ;; + esac + done + temp_rpath="$rpath" + fi + + if test -n "$compile_shlibpath$finalize_shlibpath"; then + compile_command="$shlibpath_var=\"$compile_shlibpath$finalize_shlibpath\$$shlibpath_var\" $compile_command" + fi + if test -n "$finalize_shlibpath"; then + finalize_command="$shlibpath_var=\"$finalize_shlibpath\$$shlibpath_var\" $finalize_command" + fi + + compile_var= + finalize_var= + if test -n "$runpath_var"; then + if test -n "$perm_rpath"; then + # We should set the runpath_var. + rpath= + for dir in $perm_rpath; do + rpath="$rpath$dir:" + done + compile_var="$runpath_var=\"$rpath\$$runpath_var\" " + fi + if test -n "$finalize_perm_rpath"; then + # We should set the runpath_var. + rpath= + for dir in $finalize_perm_rpath; do + rpath="$rpath$dir:" + done + finalize_var="$runpath_var=\"$rpath\$$runpath_var\" " + fi + fi + + if test "$no_install" = yes; then + # We don't need to create a wrapper script. + link_command="$compile_var$compile_command$compile_rpath" + # Replace the output file specification. + link_command=`$echo "X$link_command" | $Xsed -e 's%@OUTPUT@%'"$output"'%g'` + # Delete the old output file. + $run $rm $output + # Link the executable and exit + $show "$link_command" + $run eval "$link_command" || exit $? + exit $EXIT_SUCCESS + fi + + if test "$hardcode_action" = relink; then + # Fast installation is not supported + link_command="$compile_var$compile_command$compile_rpath" + relink_command="$finalize_var$finalize_command$finalize_rpath" + + $echo "$modename: warning: this platform does not like uninstalled shared libraries" 1>&2 + $echo "$modename: \`$output' will be relinked during installation" 1>&2 + else + if test "$fast_install" != no; then + link_command="$finalize_var$compile_command$finalize_rpath" + if test "$fast_install" = yes; then + relink_command=`$echo "X$compile_var$compile_command$compile_rpath" | $Xsed -e 's%@OUTPUT@%\$progdir/\$file%g'` + else + # fast_install is set to needless + relink_command= + fi + else + link_command="$compile_var$compile_command$compile_rpath" + relink_command="$finalize_var$finalize_command$finalize_rpath" + fi + fi + + # Replace the output file specification. + link_command=`$echo "X$link_command" | $Xsed -e 's%@OUTPUT@%'"$output_objdir/$outputname"'%g'` + + # Delete the old output files. + $run $rm $output $output_objdir/$outputname $output_objdir/lt-$outputname + + $show "$link_command" + $run eval "$link_command" || exit $? + + # Now create the wrapper script. + $show "creating $output" + + # Quote the relink command for shipping. + if test -n "$relink_command"; then + # Preserve any variables that may affect compiler behavior + for var in $variables_saved_for_relink; do + if eval test -z \"\${$var+set}\"; then + relink_command="{ test -z \"\${$var+set}\" || unset $var || { $var=; export $var; }; }; $relink_command" + elif eval var_value=\$$var; test -z "$var_value"; then + relink_command="$var=; export $var; $relink_command" + else + var_value=`$echo "X$var_value" | $Xsed -e "$sed_quote_subst"` + relink_command="$var=\"$var_value\"; export $var; $relink_command" + fi + done + relink_command="(cd `pwd`; $relink_command)" + relink_command=`$echo "X$relink_command" | $Xsed -e "$sed_quote_subst"` + fi + + # Quote $echo for shipping. + if test "X$echo" = "X$SHELL $progpath --fallback-echo"; then + case $progpath in + [\\/]* | [A-Za-z]:[\\/]*) qecho="$SHELL $progpath --fallback-echo";; + *) qecho="$SHELL `pwd`/$progpath --fallback-echo";; + esac + qecho=`$echo "X$qecho" | $Xsed -e "$sed_quote_subst"` + else + qecho=`$echo "X$echo" | $Xsed -e "$sed_quote_subst"` + fi + + # Only actually do things if our run command is non-null. + if test -z "$run"; then + # win32 will think the script is a binary if it has + # a .exe suffix, so we strip it off here. + case $output in + *.exe) output=`$echo $output|${SED} 's,.exe$,,'` ;; + esac + # test for cygwin because mv fails w/o .exe extensions + case $host in + *cygwin*) + exeext=.exe + outputname=`$echo $outputname|${SED} 's,.exe$,,'` ;; + *) exeext= ;; + esac + case $host in + *cygwin* | *mingw* ) + cwrappersource=`$echo ${objdir}/lt-${output}.c` + cwrapper=`$echo ${output}.exe` + $rm $cwrappersource $cwrapper + trap "$rm $cwrappersource $cwrapper; exit $EXIT_FAILURE" 1 2 15 + + cat > $cwrappersource <> $cwrappersource<<"EOF" +#include +#include +#include +#include +#include +#include + +#if defined(PATH_MAX) +# define LT_PATHMAX PATH_MAX +#elif defined(MAXPATHLEN) +# define LT_PATHMAX MAXPATHLEN +#else +# define LT_PATHMAX 1024 +#endif + +#ifndef DIR_SEPARATOR +#define DIR_SEPARATOR '/' +#endif + +#if defined (_WIN32) || defined (__MSDOS__) || defined (__DJGPP__) || \ + defined (__OS2__) +#define HAVE_DOS_BASED_FILE_SYSTEM +#ifndef DIR_SEPARATOR_2 +#define DIR_SEPARATOR_2 '\\' +#endif +#endif + +#ifndef DIR_SEPARATOR_2 +# define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR) +#else /* DIR_SEPARATOR_2 */ +# define IS_DIR_SEPARATOR(ch) \ + (((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2)) +#endif /* DIR_SEPARATOR_2 */ + +#define XMALLOC(type, num) ((type *) xmalloc ((num) * sizeof(type))) +#define XFREE(stale) do { \ + if (stale) { free ((void *) stale); stale = 0; } \ +} while (0) + +const char *program_name = NULL; + +void * xmalloc (size_t num); +char * xstrdup (const char *string); +char * basename (const char *name); +char * fnqualify(const char *path); +char * strendzap(char *str, const char *pat); +void lt_fatal (const char *message, ...); + +int +main (int argc, char *argv[]) +{ + char **newargz; + int i; + + program_name = (char *) xstrdup ((char *) basename (argv[0])); + newargz = XMALLOC(char *, argc+2); +EOF + + cat >> $cwrappersource <> $cwrappersource <<"EOF" + newargz[1] = fnqualify(argv[0]); + /* we know the script has the same name, without the .exe */ + /* so make sure newargz[1] doesn't end in .exe */ + strendzap(newargz[1],".exe"); + for (i = 1; i < argc; i++) + newargz[i+1] = xstrdup(argv[i]); + newargz[argc+1] = NULL; +EOF + + cat >> $cwrappersource <> $cwrappersource <<"EOF" +} + +void * +xmalloc (size_t num) +{ + void * p = (void *) malloc (num); + if (!p) + lt_fatal ("Memory exhausted"); + + return p; +} + +char * +xstrdup (const char *string) +{ + return string ? strcpy ((char *) xmalloc (strlen (string) + 1), string) : NULL +; +} + +char * +basename (const char *name) +{ + const char *base; + +#if defined (HAVE_DOS_BASED_FILE_SYSTEM) + /* Skip over the disk name in MSDOS pathnames. */ + if (isalpha (name[0]) && name[1] == ':') + name += 2; +#endif + + for (base = name; *name; name++) + if (IS_DIR_SEPARATOR (*name)) + base = name + 1; + return (char *) base; +} + +char * +fnqualify(const char *path) +{ + size_t size; + char *p; + char tmp[LT_PATHMAX + 1]; + + assert(path != NULL); + + /* Is it qualified already? */ +#if defined (HAVE_DOS_BASED_FILE_SYSTEM) + if (isalpha (path[0]) && path[1] == ':') + return xstrdup (path); +#endif + if (IS_DIR_SEPARATOR (path[0])) + return xstrdup (path); + + /* prepend the current directory */ + /* doesn't handle '~' */ + if (getcwd (tmp, LT_PATHMAX) == NULL) + lt_fatal ("getcwd failed"); + size = strlen(tmp) + 1 + strlen(path) + 1; /* +2 for '/' and '\0' */ + p = XMALLOC(char, size); + sprintf(p, "%s%c%s", tmp, DIR_SEPARATOR, path); + return p; +} + +char * +strendzap(char *str, const char *pat) +{ + size_t len, patlen; + + assert(str != NULL); + assert(pat != NULL); + + len = strlen(str); + patlen = strlen(pat); + + if (patlen <= len) + { + str += len - patlen; + if (strcmp(str, pat) == 0) + *str = '\0'; + } + return str; +} + +static void +lt_error_core (int exit_status, const char * mode, + const char * message, va_list ap) +{ + fprintf (stderr, "%s: %s: ", program_name, mode); + vfprintf (stderr, message, ap); + fprintf (stderr, ".\n"); + + if (exit_status >= 0) + exit (exit_status); +} + +void +lt_fatal (const char *message, ...) +{ + va_list ap; + va_start (ap, message); + lt_error_core (EXIT_FAILURE, "FATAL", message, ap); + va_end (ap); +} +EOF + # we should really use a build-platform specific compiler + # here, but OTOH, the wrappers (shell script and this C one) + # are only useful if you want to execute the "real" binary. + # Since the "real" binary is built for $host, then this + # wrapper might as well be built for $host, too. + $run $LTCC -s -o $cwrapper $cwrappersource + ;; + esac + $rm $output + trap "$rm $output; exit $EXIT_FAILURE" 1 2 15 + + $echo > $output "\ +#! $SHELL + +# $output - temporary wrapper script for $objdir/$outputname +# Generated by $PROGRAM - GNU $PACKAGE $VERSION$TIMESTAMP +# +# The $output program cannot be directly executed until all the libtool +# libraries that it depends on are installed. +# +# This wrapper script should never be moved out of the build directory. +# If it is, it will not operate correctly. + +# Sed substitution that helps us do robust quoting. It backslashifies +# metacharacters that are still active within double-quoted strings. +Xsed='${SED} -e 1s/^X//' +sed_quote_subst='$sed_quote_subst' + +# The HP-UX ksh and POSIX shell print the target directory to stdout +# if CDPATH is set. +if test \"\${CDPATH+set}\" = set; then CDPATH=:; export CDPATH; fi + +relink_command=\"$relink_command\" + +# This environment variable determines our operation mode. +if test \"\$libtool_install_magic\" = \"$magic\"; then + # install mode needs the following variable: + notinst_deplibs='$notinst_deplibs' +else + # When we are sourced in execute mode, \$file and \$echo are already set. + if test \"\$libtool_execute_magic\" != \"$magic\"; then + echo=\"$qecho\" + file=\"\$0\" + # Make sure echo works. + if test \"X\$1\" = X--no-reexec; then + # Discard the --no-reexec flag, and continue. + shift + elif test \"X\`(\$echo '\t') 2>/dev/null\`\" = 'X\t'; then + # Yippee, \$echo works! + : + else + # Restart under the correct shell, and then maybe \$echo will work. + exec $SHELL \"\$0\" --no-reexec \${1+\"\$@\"} + fi + fi\ +" + $echo >> $output "\ + + # Find the directory that this script lives in. + thisdir=\`\$echo \"X\$file\" | \$Xsed -e 's%/[^/]*$%%'\` + test \"x\$thisdir\" = \"x\$file\" && thisdir=. + + # Follow symbolic links until we get to the real thisdir. + file=\`ls -ld \"\$file\" | ${SED} -n 's/.*-> //p'\` + while test -n \"\$file\"; do + destdir=\`\$echo \"X\$file\" | \$Xsed -e 's%/[^/]*\$%%'\` + + # If there was a directory component, then change thisdir. + if test \"x\$destdir\" != \"x\$file\"; then + case \"\$destdir\" in + [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"\$destdir\" ;; + *) thisdir=\"\$thisdir/\$destdir\" ;; + esac + fi + + file=\`\$echo \"X\$file\" | \$Xsed -e 's%^.*/%%'\` + file=\`ls -ld \"\$thisdir/\$file\" | ${SED} -n 's/.*-> //p'\` + done + + # Try to get the absolute directory name. + absdir=\`cd \"\$thisdir\" && pwd\` + test -n \"\$absdir\" && thisdir=\"\$absdir\" +" + + if test "$fast_install" = yes; then + $echo >> $output "\ + program=lt-'$outputname'$exeext + progdir=\"\$thisdir/$objdir\" + + if test ! -f \"\$progdir/\$program\" || \\ + { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | ${SED} 1q\`; \\ + test \"X\$file\" != \"X\$progdir/\$program\"; }; then + + file=\"\$\$-\$program\" + + if test ! -d \"\$progdir\"; then + $mkdir \"\$progdir\" + else + $rm \"\$progdir/\$file\" + fi" + + $echo >> $output "\ + + # relink executable if necessary + if test -n \"\$relink_command\"; then + if relink_command_output=\`eval \$relink_command 2>&1\`; then : + else + $echo \"\$relink_command_output\" >&2 + $rm \"\$progdir/\$file\" + exit $EXIT_FAILURE + fi + fi + + $mv \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null || + { $rm \"\$progdir/\$program\"; + $mv \"\$progdir/\$file\" \"\$progdir/\$program\"; } + $rm \"\$progdir/\$file\" + fi" + else + $echo >> $output "\ + program='$outputname' + progdir=\"\$thisdir/$objdir\" +" + fi + + $echo >> $output "\ + + if test -f \"\$progdir/\$program\"; then" + + # Export our shlibpath_var if we have one. + if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then + $echo >> $output "\ + # Add our own library path to $shlibpath_var + $shlibpath_var=\"$temp_rpath\$$shlibpath_var\" + + # Some systems cannot cope with colon-terminated $shlibpath_var + # The second colon is a workaround for a bug in BeOS R4 sed + $shlibpath_var=\`\$echo \"X\$$shlibpath_var\" | \$Xsed -e 's/::*\$//'\` + + export $shlibpath_var +" + fi + + # fixup the dll searchpath if we need to. + if test -n "$dllsearchpath"; then + $echo >> $output "\ + # Add the dll search path components to the executable PATH + PATH=$dllsearchpath:\$PATH +" + fi + + $echo >> $output "\ + if test \"\$libtool_execute_magic\" != \"$magic\"; then + # Run the actual program with our arguments. +" + case $host in + # Backslashes separate directories on plain windows + *-*-mingw | *-*-os2*) + $echo >> $output "\ + exec \$progdir\\\\\$program \${1+\"\$@\"} +" + ;; + + *) + $echo >> $output "\ + exec \$progdir/\$program \${1+\"\$@\"} +" + ;; + esac + $echo >> $output "\ + \$echo \"\$0: cannot exec \$program \${1+\"\$@\"}\" + exit $EXIT_FAILURE + fi + else + # The program doesn't exist. + \$echo \"\$0: error: \$progdir/\$program does not exist\" 1>&2 + \$echo \"This script is just a wrapper for \$program.\" 1>&2 + $echo \"See the $PACKAGE documentation for more information.\" 1>&2 + exit $EXIT_FAILURE + fi +fi\ +" + chmod +x $output + fi + exit $EXIT_SUCCESS + ;; + esac + + # See if we need to build an old-fashioned archive. + for oldlib in $oldlibs; do + + if test "$build_libtool_libs" = convenience; then + oldobjs="$libobjs_save" + addlibs="$convenience" + build_libtool_libs=no + else + if test "$build_libtool_libs" = module; then + oldobjs="$libobjs_save" + build_libtool_libs=no + else + oldobjs="$old_deplibs $non_pic_objects" + fi + addlibs="$old_convenience" + fi + + if test -n "$addlibs"; then + gentop="$output_objdir/${outputname}x" + $show "${rm}r $gentop" + $run ${rm}r "$gentop" + $show "$mkdir $gentop" + $run $mkdir "$gentop" + status=$? + if test "$status" -ne 0 && test ! -d "$gentop"; then + exit $status + fi + generated="$generated $gentop" + + # Add in members from convenience archives. + for xlib in $addlibs; do + # Extract the objects. + case $xlib in + [\\/]* | [A-Za-z]:[\\/]*) xabs="$xlib" ;; + *) xabs=`pwd`"/$xlib" ;; + esac + xlib=`$echo "X$xlib" | $Xsed -e 's%^.*/%%'` + xdir="$gentop/$xlib" + + $show "${rm}r $xdir" + $run ${rm}r "$xdir" + $show "$mkdir $xdir" + $run $mkdir "$xdir" + status=$? + if test "$status" -ne 0 && test ! -d "$xdir"; then + exit $status + fi + # We will extract separately just the conflicting names and we will no + # longer touch any unique names. It is faster to leave these extract + # automatically by $AR in one run. + $show "(cd $xdir && $AR x $xabs)" + $run eval "(cd \$xdir && $AR x \$xabs)" || exit $? + if ($AR t "$xabs" | sort | sort -uc >/dev/null 2>&1); then + : + else + $echo "$modename: warning: object name conflicts; renaming object files" 1>&2 + $echo "$modename: warning: to ensure that they will not overwrite" 1>&2 + $AR t "$xabs" | sort | uniq -cd | while read -r count name + do + i=1 + while test "$i" -le "$count" + do + # Put our $i before any first dot (extension) + # Never overwrite any file + name_to="$name" + while test "X$name_to" = "X$name" || test -f "$xdir/$name_to" + do + name_to=`$echo "X$name_to" | $Xsed -e "s/\([^.]*\)/\1-$i/"` + done + $show "(cd $xdir && $AR xN $i $xabs '$name' && $mv '$name' '$name_to')" + $run eval "(cd \$xdir && $AR xN $i \$xabs '$name' && $mv '$name' '$name_to')" || exit $? + i=`expr $i + 1` + done + done + fi + + oldobjs="$oldobjs "`find $xdir -name \*.${objext} -print -o -name \*.lo -print | $NL2SP` + done + fi + + # Do each command in the archive commands. + if test -n "$old_archive_from_new_cmds" && test "$build_libtool_libs" = yes; then + cmds=$old_archive_from_new_cmds + else + eval cmds=\"$old_archive_cmds\" + + if len=`expr "X$cmds" : ".*"` && + test "$len" -le "$max_cmd_len" || test "$max_cmd_len" -le -1; then + cmds=$old_archive_cmds + else + # the command line is too long to link in one step, link in parts + $echo "using piecewise archive linking..." + save_RANLIB=$RANLIB + RANLIB=: + objlist= + concat_cmds= + save_oldobjs=$oldobjs + # GNU ar 2.10+ was changed to match POSIX; thus no paths are + # encoded into archives. This makes 'ar r' malfunction in + # this piecewise linking case whenever conflicting object + # names appear in distinct ar calls; check, warn and compensate. + if (for obj in $save_oldobjs + do + $echo "X$obj" | $Xsed -e 's%^.*/%%' + done | sort | sort -uc >/dev/null 2>&1); then + : + else + $echo "$modename: warning: object name conflicts; overriding AR_FLAGS to 'cq'" 1>&2 + $echo "$modename: warning: to ensure that POSIX-compatible ar will work" 1>&2 + AR_FLAGS=cq + fi + # Is there a better way of finding the last object in the list? + for obj in $save_oldobjs + do + last_oldobj=$obj + done + for obj in $save_oldobjs + do + oldobjs="$objlist $obj" + objlist="$objlist $obj" + eval test_cmds=\"$old_archive_cmds\" + if len=`expr "X$test_cmds" : ".*"` && + test "$len" -le "$max_cmd_len"; then + : + else + # the above command should be used before it gets too long + oldobjs=$objlist + if test "$obj" = "$last_oldobj" ; then + RANLIB=$save_RANLIB + fi + test -z "$concat_cmds" || concat_cmds=$concat_cmds~ + eval concat_cmds=\"\${concat_cmds}$old_archive_cmds\" + objlist= + fi + done + RANLIB=$save_RANLIB + oldobjs=$objlist + if test "X$oldobjs" = "X" ; then + eval cmds=\"\$concat_cmds\" + else + eval cmds=\"\$concat_cmds~\$old_archive_cmds\" + fi + fi + fi + save_ifs="$IFS"; IFS='~' + for cmd in $cmds; do + eval cmd=\"$cmd\" + IFS="$save_ifs" + $show "$cmd" + $run eval "$cmd" || exit $? + done + IFS="$save_ifs" + done + + if test -n "$generated"; then + $show "${rm}r$generated" + $run ${rm}r$generated + fi + + # Now create the libtool archive. + case $output in + *.la) + old_library= + test "$build_old_libs" = yes && old_library="$libname.$libext" + $show "creating $output" + + # Preserve any variables that may affect compiler behavior + for var in $variables_saved_for_relink; do + if eval test -z \"\${$var+set}\"; then + relink_command="{ test -z \"\${$var+set}\" || unset $var || { $var=; export $var; }; }; $relink_command" + elif eval var_value=\$$var; test -z "$var_value"; then + relink_command="$var=; export $var; $relink_command" + else + var_value=`$echo "X$var_value" | $Xsed -e "$sed_quote_subst"` + relink_command="$var=\"$var_value\"; export $var; $relink_command" + fi + done + # Quote the link command for shipping. + relink_command="(cd `pwd`; $SHELL $progpath $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)" + relink_command=`$echo "X$relink_command" | $Xsed -e "$sed_quote_subst"` + if test "$hardcode_automatic" = yes ; then + relink_command= + fi + + + # Only create the output if not a dry run. + if test -z "$run"; then + for installed in no yes; do + if test "$installed" = yes; then + if test -z "$install_libdir"; then + break + fi + output="$output_objdir/$outputname"i + # Replace all uninstalled libtool libraries with the installed ones + newdependency_libs= + for deplib in $dependency_libs; do + case $deplib in + *.la) + name=`$echo "X$deplib" | $Xsed -e 's%^.*/%%'` + eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib` + if test -z "$libdir"; then + $echo "$modename: \`$deplib' is not a valid libtool archive" 1>&2 + exit $EXIT_FAILURE + fi + newdependency_libs="$newdependency_libs $libdir/$name" + ;; + *) newdependency_libs="$newdependency_libs $deplib" ;; + esac + done + dependency_libs="$newdependency_libs" + newdlfiles= + for lib in $dlfiles; do + name=`$echo "X$lib" | $Xsed -e 's%^.*/%%'` + eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib` + if test -z "$libdir"; then + $echo "$modename: \`$lib' is not a valid libtool archive" 1>&2 + exit $EXIT_FAILURE + fi + newdlfiles="$newdlfiles $libdir/$name" + done + dlfiles="$newdlfiles" + newdlprefiles= + for lib in $dlprefiles; do + name=`$echo "X$lib" | $Xsed -e 's%^.*/%%'` + eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib` + if test -z "$libdir"; then + $echo "$modename: \`$lib' is not a valid libtool archive" 1>&2 + exit $EXIT_FAILURE + fi + newdlprefiles="$newdlprefiles $libdir/$name" + done + dlprefiles="$newdlprefiles" + else + newdlfiles= + for lib in $dlfiles; do + case $lib in + [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;; + *) abs=`pwd`"/$lib" ;; + esac + newdlfiles="$newdlfiles $abs" + done + dlfiles="$newdlfiles" + newdlprefiles= + for lib in $dlprefiles; do + case $lib in + [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;; + *) abs=`pwd`"/$lib" ;; + esac + newdlprefiles="$newdlprefiles $abs" + done + dlprefiles="$newdlprefiles" + fi + $rm $output + # place dlname in correct position for cygwin + tdlname=$dlname + case $host,$output,$installed,$module,$dlname in + *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll) tdlname=../bin/$dlname ;; + esac + $echo > $output "\ +# $outputname - a libtool library file +# Generated by $PROGRAM - GNU $PACKAGE $VERSION$TIMESTAMP +# +# Please DO NOT delete this file! +# It is necessary for linking the library. + +# The name that we can dlopen(3). +dlname='$tdlname' + +# Names of this library. +library_names='$library_names' + +# The name of the static archive. +old_library='$old_library' + +# Libraries that this one depends upon. +dependency_libs='$dependency_libs' + +# Version information for $libname. +current=$current +age=$age +revision=$revision + +# Is this an already installed library? +installed=$installed + +# Should we warn about portability when linking against -modules? +shouldnotlink=$module + +# Files to dlopen/dlpreopen +dlopen='$dlfiles' +dlpreopen='$dlprefiles' + +# Directory that this library needs to be installed in: +libdir='$install_libdir'" + if test "$installed" = no && test "$need_relink" = yes; then + $echo >> $output "\ +relink_command=\"$relink_command\"" + fi + done + fi + + # Do a symbolic link so that the libtool archive can be found in + # LD_LIBRARY_PATH before the program is installed. + $show "(cd $output_objdir && $rm $outputname && $LN_S ../$outputname $outputname)" + $run eval '(cd $output_objdir && $rm $outputname && $LN_S ../$outputname $outputname)' || exit $? + ;; + esac + exit $EXIT_SUCCESS + ;; + + # libtool install mode + install) + modename="$modename: install" + + # There may be an optional sh(1) argument at the beginning of + # install_prog (especially on Windows NT). + if test "$nonopt" = "$SHELL" || test "$nonopt" = /bin/sh || + # Allow the use of GNU shtool's install command. + $echo "X$nonopt" | $Xsed | grep shtool > /dev/null; then + # Aesthetically quote it. + arg=`$echo "X$nonopt" | $Xsed -e "$sed_quote_subst"` + case $arg in + *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*) + arg="\"$arg\"" + ;; + esac + install_prog="$arg " + arg="$1" + shift + else + install_prog= + arg="$nonopt" + fi + + # The real first argument should be the name of the installation program. + # Aesthetically quote it. + arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"` + case $arg in + *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*) + arg="\"$arg\"" + ;; + esac + install_prog="$install_prog$arg" + + # We need to accept at least all the BSD install flags. + dest= + files= + opts= + prev= + install_type= + isdir=no + stripme= + for arg + do + if test -n "$dest"; then + files="$files $dest" + dest="$arg" + continue + fi + + case $arg in + -d) isdir=yes ;; + -f) prev="-f" ;; + -g) prev="-g" ;; + -m) prev="-m" ;; + -o) prev="-o" ;; + -s) + stripme=" -s" + continue + ;; + -*) ;; + + *) + # If the previous option needed an argument, then skip it. + if test -n "$prev"; then + prev= + else + dest="$arg" + continue + fi + ;; + esac + + # Aesthetically quote the argument. + arg=`$echo "X$arg" | $Xsed -e "$sed_quote_subst"` + case $arg in + *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*) + arg="\"$arg\"" + ;; + esac + install_prog="$install_prog $arg" + done + + if test -z "$install_prog"; then + $echo "$modename: you must specify an install program" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE + fi + + if test -n "$prev"; then + $echo "$modename: the \`$prev' option requires an argument" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE + fi + + if test -z "$files"; then + if test -z "$dest"; then + $echo "$modename: no file or destination specified" 1>&2 + else + $echo "$modename: you must specify a destination" 1>&2 + fi + $echo "$help" 1>&2 + exit $EXIT_FAILURE + fi + + # Strip any trailing slash from the destination. + dest=`$echo "X$dest" | $Xsed -e 's%/$%%'` + + # Check to see that the destination is a directory. + test -d "$dest" && isdir=yes + if test "$isdir" = yes; then + destdir="$dest" + destname= + else + destdir=`$echo "X$dest" | $Xsed -e 's%/[^/]*$%%'` + test "X$destdir" = "X$dest" && destdir=. + destname=`$echo "X$dest" | $Xsed -e 's%^.*/%%'` + + # Not a directory, so check to see that there is only one file specified. + set dummy $files + if test "$#" -gt 2; then + $echo "$modename: \`$dest' is not a directory" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE + fi + fi + case $destdir in + [\\/]* | [A-Za-z]:[\\/]*) ;; + *) + for file in $files; do + case $file in + *.lo) ;; + *) + $echo "$modename: \`$destdir' must be an absolute directory name" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE + ;; + esac + done + ;; + esac + + # This variable tells wrapper scripts just to set variables rather + # than running their programs. + libtool_install_magic="$magic" + + staticlibs= + future_libdirs= + current_libdirs= + for file in $files; do + + # Do each installation. + case $file in + *.$libext) + # Do the static libraries later. + staticlibs="$staticlibs $file" + ;; + + *.la) + # Check to see that this really is a libtool archive. + if (${SED} -e '2q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then : + else + $echo "$modename: \`$file' is not a valid libtool archive" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE + fi + + library_names= + old_library= + relink_command= + # If there is no directory component, then add one. + case $file in + */* | *\\*) . $file ;; + *) . ./$file ;; + esac + + # Add the libdir to current_libdirs if it is the destination. + if test "X$destdir" = "X$libdir"; then + case "$current_libdirs " in + *" $libdir "*) ;; + *) current_libdirs="$current_libdirs $libdir" ;; + esac + else + # Note the libdir as a future libdir. + case "$future_libdirs " in + *" $libdir "*) ;; + *) future_libdirs="$future_libdirs $libdir" ;; + esac + fi + + dir=`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'`/ + test "X$dir" = "X$file/" && dir= + dir="$dir$objdir" + + if test -n "$relink_command"; then + # Determine the prefix the user has applied to our future dir. + inst_prefix_dir=`$echo "$destdir" | $SED "s%$libdir\$%%"` + + # Don't allow the user to place us outside of our expected + # location b/c this prevents finding dependent libraries that + # are installed to the same prefix. + # At present, this check doesn't affect windows .dll's that + # are installed into $libdir/../bin (currently, that works fine) + # but it's something to keep an eye on. + if test "$inst_prefix_dir" = "$destdir"; then + $echo "$modename: error: cannot install \`$file' to a directory not ending in $libdir" 1>&2 + exit $EXIT_FAILURE + fi + + if test -n "$inst_prefix_dir"; then + # Stick the inst_prefix_dir data into the link command. + relink_command=`$echo "$relink_command" | $SED "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%"` + else + relink_command=`$echo "$relink_command" | $SED "s%@inst_prefix_dir@%%"` + fi + + $echo "$modename: warning: relinking \`$file'" 1>&2 + $show "$relink_command" + if $run eval "$relink_command"; then : + else + $echo "$modename: error: relink \`$file' with the above command before installing it" 1>&2 + exit $EXIT_FAILURE + fi + fi + + # See the names of the shared library. + set dummy $library_names + if test -n "$2"; then + realname="$2" + shift + shift + + srcname="$realname" + test -n "$relink_command" && srcname="$realname"T + + # Install the shared library and build the symlinks. + $show "$install_prog $dir/$srcname $destdir/$realname" + $run eval "$install_prog $dir/$srcname $destdir/$realname" || exit $? + if test -n "$stripme" && test -n "$striplib"; then + $show "$striplib $destdir/$realname" + $run eval "$striplib $destdir/$realname" || exit $? + fi + + if test "$#" -gt 0; then + # Delete the old symlinks, and create new ones. + for linkname + do + if test "$linkname" != "$realname"; then + $show "(cd $destdir && $rm $linkname && $LN_S $realname $linkname)" + $run eval "(cd $destdir && $rm $linkname && $LN_S $realname $linkname)" + fi + done + fi + + # Do each command in the postinstall commands. + lib="$destdir/$realname" + cmds=$postinstall_cmds + save_ifs="$IFS"; IFS='~' + for cmd in $cmds; do + IFS="$save_ifs" + eval cmd=\"$cmd\" + $show "$cmd" + $run eval "$cmd" || exit $? + done + IFS="$save_ifs" + fi + + # Install the pseudo-library for information purposes. + name=`$echo "X$file" | $Xsed -e 's%^.*/%%'` + instname="$dir/$name"i + $show "$install_prog $instname $destdir/$name" + $run eval "$install_prog $instname $destdir/$name" || exit $? + + # Maybe install the static library, too. + test -n "$old_library" && staticlibs="$staticlibs $dir/$old_library" + ;; + + *.lo) + # Install (i.e. copy) a libtool object. + + # Figure out destination file name, if it wasn't already specified. + if test -n "$destname"; then + destfile="$destdir/$destname" + else + destfile=`$echo "X$file" | $Xsed -e 's%^.*/%%'` + destfile="$destdir/$destfile" + fi + + # Deduce the name of the destination old-style object file. + case $destfile in + *.lo) + staticdest=`$echo "X$destfile" | $Xsed -e "$lo2o"` + ;; + *.$objext) + staticdest="$destfile" + destfile= + ;; + *) + $echo "$modename: cannot copy a libtool object to \`$destfile'" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE + ;; + esac + + # Install the libtool object if requested. + if test -n "$destfile"; then + $show "$install_prog $file $destfile" + $run eval "$install_prog $file $destfile" || exit $? + fi + + # Install the old object if enabled. + if test "$build_old_libs" = yes; then + # Deduce the name of the old-style object file. + staticobj=`$echo "X$file" | $Xsed -e "$lo2o"` + + $show "$install_prog $staticobj $staticdest" + $run eval "$install_prog \$staticobj \$staticdest" || exit $? + fi + exit $EXIT_SUCCESS + ;; + + *) + # Figure out destination file name, if it wasn't already specified. + if test -n "$destname"; then + destfile="$destdir/$destname" + else + destfile=`$echo "X$file" | $Xsed -e 's%^.*/%%'` + destfile="$destdir/$destfile" + fi + + # If the file is missing, and there is a .exe on the end, strip it + # because it is most likely a libtool script we actually want to + # install + stripped_ext="" + case $file in + *.exe) + if test ! -f "$file"; then + file=`$echo $file|${SED} 's,.exe$,,'` + stripped_ext=".exe" + fi + ;; + esac + + # Do a test to see if this is really a libtool program. + case $host in + *cygwin*|*mingw*) + wrapper=`$echo $file | ${SED} -e 's,.exe$,,'` + ;; + *) + wrapper=$file + ;; + esac + if (${SED} -e '4q' $wrapper | grep "^# Generated by .*$PACKAGE")>/dev/null 2>&1; then + notinst_deplibs= + relink_command= + + # To insure that "foo" is sourced, and not "foo.exe", + # finese the cygwin/MSYS system by explicitly sourcing "foo." + # which disallows the automatic-append-.exe behavior. + case $build in + *cygwin* | *mingw*) wrapperdot=${wrapper}. ;; + *) wrapperdot=${wrapper} ;; + esac + # If there is no directory component, then add one. + case $file in + */* | *\\*) . ${wrapperdot} ;; + *) . ./${wrapperdot} ;; + esac + + # Check the variables that should have been set. + if test -z "$notinst_deplibs"; then + $echo "$modename: invalid libtool wrapper script \`$wrapper'" 1>&2 + exit $EXIT_FAILURE + fi + + finalize=yes + for lib in $notinst_deplibs; do + # Check to see that each library is installed. + libdir= + if test -f "$lib"; then + # If there is no directory component, then add one. + case $lib in + */* | *\\*) . $lib ;; + *) . ./$lib ;; + esac + fi + libfile="$libdir/"`$echo "X$lib" | $Xsed -e 's%^.*/%%g'` ### testsuite: skip nested quoting test + if test -n "$libdir" && test ! -f "$libfile"; then + $echo "$modename: warning: \`$lib' has not been installed in \`$libdir'" 1>&2 + finalize=no + fi + done + + relink_command= + # To insure that "foo" is sourced, and not "foo.exe", + # finese the cygwin/MSYS system by explicitly sourcing "foo." + # which disallows the automatic-append-.exe behavior. + case $build in + *cygwin* | *mingw*) wrapperdot=${wrapper}. ;; + *) wrapperdot=${wrapper} ;; + esac + # If there is no directory component, then add one. + case $file in + */* | *\\*) . ${wrapperdot} ;; + *) . ./${wrapperdot} ;; + esac + + outputname= + if test "$fast_install" = no && test -n "$relink_command"; then + if test "$finalize" = yes && test -z "$run"; then + tmpdir="/tmp" + test -n "$TMPDIR" && tmpdir="$TMPDIR" + tmpdir="$tmpdir/libtool-$$" + save_umask=`umask` + umask 0077 + if $mkdir "$tmpdir"; then + umask $save_umask + else + umask $save_umask + $echo "$modename: error: cannot create temporary directory \`$tmpdir'" 1>&2 + continue + fi + file=`$echo "X$file$stripped_ext" | $Xsed -e 's%^.*/%%'` + outputname="$tmpdir/$file" + # Replace the output file specification. + relink_command=`$echo "X$relink_command" | $Xsed -e 's%@OUTPUT@%'"$outputname"'%g'` + + $show "$relink_command" + if $run eval "$relink_command"; then : + else + $echo "$modename: error: relink \`$file' with the above command before installing it" 1>&2 + ${rm}r "$tmpdir" + continue + fi + file="$outputname" + else + $echo "$modename: warning: cannot relink \`$file'" 1>&2 + fi + else + # Install the binary that we compiled earlier. + file=`$echo "X$file$stripped_ext" | $Xsed -e "s%\([^/]*\)$%$objdir/\1%"` + fi + fi + + # remove .exe since cygwin /usr/bin/install will append another + # one anyways + case $install_prog,$host in + */usr/bin/install*,*cygwin*) + case $file:$destfile in + *.exe:*.exe) + # this is ok + ;; + *.exe:*) + destfile=$destfile.exe + ;; + *:*.exe) + destfile=`$echo $destfile | ${SED} -e 's,.exe$,,'` + ;; + esac + ;; + esac + $show "$install_prog$stripme $file $destfile" + $run eval "$install_prog\$stripme \$file \$destfile" || exit $? + test -n "$outputname" && ${rm}r "$tmpdir" + ;; + esac + done + + for file in $staticlibs; do + name=`$echo "X$file" | $Xsed -e 's%^.*/%%'` + + # Set up the ranlib parameters. + oldlib="$destdir/$name" + + $show "$install_prog $file $oldlib" + $run eval "$install_prog \$file \$oldlib" || exit $? + + if test -n "$stripme" && test -n "$old_striplib"; then + $show "$old_striplib $oldlib" + $run eval "$old_striplib $oldlib" || exit $? + fi + + # Do each command in the postinstall commands. + cmds=$old_postinstall_cmds + save_ifs="$IFS"; IFS='~' + for cmd in $cmds; do + IFS="$save_ifs" + eval cmd=\"$cmd\" + $show "$cmd" + $run eval "$cmd" || exit $? + done + IFS="$save_ifs" + done + + if test -n "$future_libdirs"; then + $echo "$modename: warning: remember to run \`$progname --finish$future_libdirs'" 1>&2 + fi + + if test -n "$current_libdirs"; then + # Maybe just do a dry run. + test -n "$run" && current_libdirs=" -n$current_libdirs" + exec_cmd='$SHELL $progpath $preserve_args --finish$current_libdirs' + else + exit $EXIT_SUCCESS + fi + ;; + + # libtool finish mode + finish) + modename="$modename: finish" + libdirs="$nonopt" + admincmds= + + if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then + for dir + do + libdirs="$libdirs $dir" + done + + for libdir in $libdirs; do + if test -n "$finish_cmds"; then + # Do each command in the finish commands. + cmds=$finish_cmds + save_ifs="$IFS"; IFS='~' + for cmd in $cmds; do + IFS="$save_ifs" + eval cmd=\"$cmd\" + $show "$cmd" + $run eval "$cmd" || admincmds="$admincmds + $cmd" + done + IFS="$save_ifs" + fi + if test -n "$finish_eval"; then + # Do the single finish_eval. + eval cmds=\"$finish_eval\" + $run eval "$cmds" || admincmds="$admincmds + $cmds" + fi + done + fi + + # Exit here if they wanted silent mode. + test "$show" = : && exit $EXIT_SUCCESS + + $echo "----------------------------------------------------------------------" + $echo "Libraries have been installed in:" + for libdir in $libdirs; do + $echo " $libdir" + done + $echo + $echo "If you ever happen to want to link against installed libraries" + $echo "in a given directory, LIBDIR, you must either use libtool, and" + $echo "specify the full pathname of the library, or use the \`-LLIBDIR'" + $echo "flag during linking and do at least one of the following:" + if test -n "$shlibpath_var"; then + $echo " - add LIBDIR to the \`$shlibpath_var' environment variable" + $echo " during execution" + fi + if test -n "$runpath_var"; then + $echo " - add LIBDIR to the \`$runpath_var' environment variable" + $echo " during linking" + fi + if test -n "$hardcode_libdir_flag_spec"; then + libdir=LIBDIR + eval flag=\"$hardcode_libdir_flag_spec\" + + $echo " - use the \`$flag' linker flag" + fi + if test -n "$admincmds"; then + $echo " - have your system administrator run these commands:$admincmds" + fi + if test -f /etc/ld.so.conf; then + $echo " - have your system administrator add LIBDIR to \`/etc/ld.so.conf'" + fi + $echo + $echo "See any operating system documentation about shared libraries for" + $echo "more information, such as the ld(1) and ld.so(8) manual pages." + $echo "----------------------------------------------------------------------" + exit $EXIT_SUCCESS + ;; + + # libtool execute mode + execute) + modename="$modename: execute" + + # The first argument is the command name. + cmd="$nonopt" + if test -z "$cmd"; then + $echo "$modename: you must specify a COMMAND" 1>&2 + $echo "$help" + exit $EXIT_FAILURE + fi + + # Handle -dlopen flags immediately. + for file in $execute_dlfiles; do + if test ! -f "$file"; then + $echo "$modename: \`$file' is not a file" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE + fi + + dir= + case $file in + *.la) + # Check to see that this really is a libtool archive. + if (${SED} -e '2q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then : + else + $echo "$modename: \`$lib' is not a valid libtool archive" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE + fi + + # Read the libtool library. + dlname= + library_names= + + # If there is no directory component, then add one. + case $file in + */* | *\\*) . $file ;; + *) . ./$file ;; + esac + + # Skip this library if it cannot be dlopened. + if test -z "$dlname"; then + # Warn if it was a shared library. + test -n "$library_names" && $echo "$modename: warning: \`$file' was not linked with \`-export-dynamic'" + continue + fi + + dir=`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'` + test "X$dir" = "X$file" && dir=. + + if test -f "$dir/$objdir/$dlname"; then + dir="$dir/$objdir" + else + $echo "$modename: cannot find \`$dlname' in \`$dir' or \`$dir/$objdir'" 1>&2 + exit $EXIT_FAILURE + fi + ;; + + *.lo) + # Just add the directory containing the .lo file. + dir=`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'` + test "X$dir" = "X$file" && dir=. + ;; + + *) + $echo "$modename: warning \`-dlopen' is ignored for non-libtool libraries and objects" 1>&2 + continue + ;; + esac + + # Get the absolute pathname. + absdir=`cd "$dir" && pwd` + test -n "$absdir" && dir="$absdir" + + # Now add the directory to shlibpath_var. + if eval "test -z \"\$$shlibpath_var\""; then + eval "$shlibpath_var=\"\$dir\"" + else + eval "$shlibpath_var=\"\$dir:\$$shlibpath_var\"" + fi + done + + # This variable tells wrapper scripts just to set shlibpath_var + # rather than running their programs. + libtool_execute_magic="$magic" + + # Check if any of the arguments is a wrapper script. + args= + for file + do + case $file in + -*) ;; + *) + # Do a test to see if this is really a libtool program. + if (${SED} -e '4q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then + # If there is no directory component, then add one. + case $file in + */* | *\\*) . $file ;; + *) . ./$file ;; + esac + + # Transform arg to wrapped name. + file="$progdir/$program" + fi + ;; + esac + # Quote arguments (to preserve shell metacharacters). + file=`$echo "X$file" | $Xsed -e "$sed_quote_subst"` + args="$args \"$file\"" + done + + if test -z "$run"; then + if test -n "$shlibpath_var"; then + # Export the shlibpath_var. + eval "export $shlibpath_var" + fi + + # Restore saved environment variables + if test "${save_LC_ALL+set}" = set; then + LC_ALL="$save_LC_ALL"; export LC_ALL + fi + if test "${save_LANG+set}" = set; then + LANG="$save_LANG"; export LANG + fi + + # Now prepare to actually exec the command. + exec_cmd="\$cmd$args" + else + # Display what would be done. + if test -n "$shlibpath_var"; then + eval "\$echo \"\$shlibpath_var=\$$shlibpath_var\"" + $echo "export $shlibpath_var" + fi + $echo "$cmd$args" + exit $EXIT_SUCCESS + fi + ;; + + # libtool clean and uninstall mode + clean | uninstall) + modename="$modename: $mode" + rm="$nonopt" + files= + rmforce= + exit_status=0 + + # This variable tells wrapper scripts just to set variables rather + # than running their programs. + libtool_install_magic="$magic" + + for arg + do + case $arg in + -f) rm="$rm $arg"; rmforce=yes ;; + -*) rm="$rm $arg" ;; + *) files="$files $arg" ;; + esac + done + + if test -z "$rm"; then + $echo "$modename: you must specify an RM program" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE + fi + + rmdirs= + + origobjdir="$objdir" + for file in $files; do + dir=`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'` + if test "X$dir" = "X$file"; then + dir=. + objdir="$origobjdir" + else + objdir="$dir/$origobjdir" + fi + name=`$echo "X$file" | $Xsed -e 's%^.*/%%'` + test "$mode" = uninstall && objdir="$dir" + + # Remember objdir for removal later, being careful to avoid duplicates + if test "$mode" = clean; then + case " $rmdirs " in + *" $objdir "*) ;; + *) rmdirs="$rmdirs $objdir" ;; + esac + fi + + # Don't error if the file doesn't exist and rm -f was used. + if (test -L "$file") >/dev/null 2>&1 \ + || (test -h "$file") >/dev/null 2>&1 \ + || test -f "$file"; then + : + elif test -d "$file"; then + exit_status=1 + continue + elif test "$rmforce" = yes; then + continue + fi + + rmfiles="$file" + + case $name in + *.la) + # Possibly a libtool archive, so verify it. + if (${SED} -e '2q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then + . $dir/$name + + # Delete the libtool libraries and symlinks. + for n in $library_names; do + rmfiles="$rmfiles $objdir/$n" + done + test -n "$old_library" && rmfiles="$rmfiles $objdir/$old_library" + test "$mode" = clean && rmfiles="$rmfiles $objdir/$name $objdir/${name}i" + + if test "$mode" = uninstall; then + if test -n "$library_names"; then + # Do each command in the postuninstall commands. + cmds=$postuninstall_cmds + save_ifs="$IFS"; IFS='~' + for cmd in $cmds; do + IFS="$save_ifs" + eval cmd=\"$cmd\" + $show "$cmd" + $run eval "$cmd" + if test "$?" -ne 0 && test "$rmforce" != yes; then + exit_status=1 + fi + done + IFS="$save_ifs" + fi + + if test -n "$old_library"; then + # Do each command in the old_postuninstall commands. + cmds=$old_postuninstall_cmds + save_ifs="$IFS"; IFS='~' + for cmd in $cmds; do + IFS="$save_ifs" + eval cmd=\"$cmd\" + $show "$cmd" + $run eval "$cmd" + if test "$?" -ne 0 && test "$rmforce" != yes; then + exit_status=1 + fi + done + IFS="$save_ifs" + fi + # FIXME: should reinstall the best remaining shared library. + fi + fi + ;; + + *.lo) + # Possibly a libtool object, so verify it. + if (${SED} -e '2q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then + + # Read the .lo file + . $dir/$name + + # Add PIC object to the list of files to remove. + if test -n "$pic_object" \ + && test "$pic_object" != none; then + rmfiles="$rmfiles $dir/$pic_object" + fi + + # Add non-PIC object to the list of files to remove. + if test -n "$non_pic_object" \ + && test "$non_pic_object" != none; then + rmfiles="$rmfiles $dir/$non_pic_object" + fi + fi + ;; + + *) + if test "$mode" = clean ; then + noexename=$name + case $file in + *.exe) + file=`$echo $file|${SED} 's,.exe$,,'` + noexename=`$echo $name|${SED} 's,.exe$,,'` + # $file with .exe has already been added to rmfiles, + # add $file without .exe + rmfiles="$rmfiles $file" + ;; + esac + # Do a test to see if this is a libtool program. + if (${SED} -e '4q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; then + relink_command= + . $dir/$noexename + + # note $name still contains .exe if it was in $file originally + # as does the version of $file that was added into $rmfiles + rmfiles="$rmfiles $objdir/$name $objdir/${name}S.${objext}" + if test "$fast_install" = yes && test -n "$relink_command"; then + rmfiles="$rmfiles $objdir/lt-$name" + fi + if test "X$noexename" != "X$name" ; then + rmfiles="$rmfiles $objdir/lt-${noexename}.c" + fi + fi + fi + ;; + esac + $show "$rm $rmfiles" + $run $rm $rmfiles || exit_status=1 + done + objdir="$origobjdir" + + # Try to remove the ${objdir}s in the directories where we deleted files + for dir in $rmdirs; do + if test -d "$dir"; then + $show "rmdir $dir" + $run rmdir $dir >/dev/null 2>&1 + fi + done + + exit $exit_status + ;; + + "") + $echo "$modename: you must specify a MODE" 1>&2 + $echo "$generic_help" 1>&2 + exit $EXIT_FAILURE + ;; + esac + + if test -z "$exec_cmd"; then + $echo "$modename: invalid operation mode \`$mode'" 1>&2 + $echo "$generic_help" 1>&2 + exit $EXIT_FAILURE + fi +fi # test -z "$show_help" + +if test -n "$exec_cmd"; then + eval exec $exec_cmd + exit $EXIT_FAILURE +fi + +# We need to display help for each of the modes. +case $mode in +"") $echo \ +"Usage: $modename [OPTION]... [MODE-ARG]... + +Provide generalized library-building support services. + + --config show all configuration variables + --debug enable verbose shell tracing +-n, --dry-run display commands without modifying any files + --features display basic configuration information and exit + --finish same as \`--mode=finish' + --help display this help message and exit + --mode=MODE use operation mode MODE [default=inferred from MODE-ARGS] + --quiet same as \`--silent' + --silent don't print informational messages + --tag=TAG use configuration variables from tag TAG + --version print version information + +MODE must be one of the following: + + clean remove files from the build directory + compile compile a source file into a libtool object + execute automatically set library path, then run a program + finish complete the installation of libtool libraries + install install libraries or executables + link create a library or an executable + uninstall remove libraries from an installed directory + +MODE-ARGS vary depending on the MODE. Try \`$modename --help --mode=MODE' for +a more detailed description of MODE. + +Report bugs to ." + exit $EXIT_SUCCESS + ;; + +clean) + $echo \ +"Usage: $modename [OPTION]... --mode=clean RM [RM-OPTION]... FILE... + +Remove files from the build directory. + +RM is the name of the program to use to delete files associated with each FILE +(typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed +to RM. + +If FILE is a libtool library, object or program, all the files associated +with it are deleted. Otherwise, only FILE itself is deleted using RM." + ;; + +compile) + $echo \ +"Usage: $modename [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE + +Compile a source file into a libtool library object. + +This mode accepts the following additional options: + + -o OUTPUT-FILE set the output file name to OUTPUT-FILE + -prefer-pic try to building PIC objects only + -prefer-non-pic try to building non-PIC objects only + -static always build a \`.o' file suitable for static linking + +COMPILE-COMMAND is a command to be used in creating a \`standard' object file +from the given SOURCEFILE. + +The output file name is determined by removing the directory component from +SOURCEFILE, then substituting the C source code suffix \`.c' with the +library object suffix, \`.lo'." + ;; + +execute) + $echo \ +"Usage: $modename [OPTION]... --mode=execute COMMAND [ARGS]... + +Automatically set library path, then run a program. + +This mode accepts the following additional options: + + -dlopen FILE add the directory containing FILE to the library path + +This mode sets the library path environment variable according to \`-dlopen' +flags. + +If any of the ARGS are libtool executable wrappers, then they are translated +into their corresponding uninstalled binary, and any of their required library +directories are added to the library path. + +Then, COMMAND is executed, with ARGS as arguments." + ;; + +finish) + $echo \ +"Usage: $modename [OPTION]... --mode=finish [LIBDIR]... + +Complete the installation of libtool libraries. + +Each LIBDIR is a directory that contains libtool libraries. + +The commands that this mode executes may require superuser privileges. Use +the \`--dry-run' option if you just want to see what would be executed." + ;; + +install) + $echo \ +"Usage: $modename [OPTION]... --mode=install INSTALL-COMMAND... + +Install executables or libraries. + +INSTALL-COMMAND is the installation command. The first component should be +either the \`install' or \`cp' program. + +The rest of the components are interpreted as arguments to that command (only +BSD-compatible install options are recognized)." + ;; + +link) + $echo \ +"Usage: $modename [OPTION]... --mode=link LINK-COMMAND... + +Link object files or libraries together to form another library, or to +create an executable program. + +LINK-COMMAND is a command using the C compiler that you would use to create +a program from several object files. + +The following components of LINK-COMMAND are treated specially: + + -all-static do not do any dynamic linking at all + -avoid-version do not add a version suffix if possible + -dlopen FILE \`-dlpreopen' FILE if it cannot be dlopened at runtime + -dlpreopen FILE link in FILE and add its symbols to lt_preloaded_symbols + -export-dynamic allow symbols from OUTPUT-FILE to be resolved with dlsym(3) + -export-symbols SYMFILE + try to export only the symbols listed in SYMFILE + -export-symbols-regex REGEX + try to export only the symbols matching REGEX + -LLIBDIR search LIBDIR for required installed libraries + -lNAME OUTPUT-FILE requires the installed library libNAME + -module build a library that can dlopened + -no-fast-install disable the fast-install mode + -no-install link a not-installable executable + -no-undefined declare that a library does not refer to external symbols + -o OUTPUT-FILE create OUTPUT-FILE from the specified objects + -objectlist FILE Use a list of object files found in FILE to specify objects + -precious-files-regex REGEX + don't remove output files matching REGEX + -release RELEASE specify package release information + -rpath LIBDIR the created library will eventually be installed in LIBDIR + -R[ ]LIBDIR add LIBDIR to the runtime path of programs and libraries + -static do not do any dynamic linking of libtool libraries + -version-info CURRENT[:REVISION[:AGE]] + specify library version info [each variable defaults to 0] + +All other options (arguments beginning with \`-') are ignored. + +Every other argument is treated as a filename. Files ending in \`.la' are +treated as uninstalled libtool libraries, other files are standard or library +object files. + +If the OUTPUT-FILE ends in \`.la', then a libtool library is created, +only library objects (\`.lo' files) may be specified, and \`-rpath' is +required, except when creating a convenience library. + +If OUTPUT-FILE ends in \`.a' or \`.lib', then a standard library is created +using \`ar' and \`ranlib', or on Windows using \`lib'. + +If OUTPUT-FILE ends in \`.lo' or \`.${objext}', then a reloadable object file +is created, otherwise an executable program is created." + ;; + +uninstall) + $echo \ +"Usage: $modename [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE... + +Remove libraries from an installation directory. + +RM is the name of the program to use to delete files associated with each FILE +(typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed +to RM. + +If FILE is a libtool library, all the files associated with it are deleted. +Otherwise, only FILE itself is deleted using RM." + ;; + +*) + $echo "$modename: invalid operation mode \`$mode'" 1>&2 + $echo "$help" 1>&2 + exit $EXIT_FAILURE + ;; +esac + +$echo +$echo "Try \`$modename --help' for more information about other modes." + +exit $EXIT_SUCCESS + +# The TAGs below are defined such that we never get into a situation +# in which we disable both kinds of libraries. Given conflicting +# choices, we go for a static library, that is the most portable, +# since we can't tell whether shared libraries were disabled because +# the user asked for that or because the platform doesn't support +# them. This is particularly important on AIX, because we don't +# support having both static and shared libraries enabled at the same +# time on that platform, so we default to a shared-only configuration. +# If a disable-shared tag is given, we'll fallback to a static-only +# configuration. But we'll never go from static-only to shared-only. + +# ### BEGIN LIBTOOL TAG CONFIG: disable-shared +build_libtool_libs=no +build_old_libs=yes +# ### END LIBTOOL TAG CONFIG: disable-shared + +# ### BEGIN LIBTOOL TAG CONFIG: disable-static +build_old_libs=`case $build_libtool_libs in yes) $echo no;; *) $echo yes;; esac` +# ### END LIBTOOL TAG CONFIG: disable-static + +# Local Variables: +# mode:shell-script +# sh-indentation:2 +# End: diff --git a/mozilla/zap/zmk/speex-1.1.10/missing b/mozilla/zap/zmk/speex-1.1.10/missing new file mode 100755 index 00000000000..4432a8aab73 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/missing @@ -0,0 +1,336 @@ +#! /bin/sh +# Common stub for a few missing GNU programs while installing. +# Copyright (C) 1996, 1997, 1999, 2000, 2002 Free Software Foundation, Inc. +# Originally by Fran,cois Pinard , 1996. + +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2, or (at your option) +# any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA +# 02111-1307, USA. + +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + +if test $# -eq 0; then + echo 1>&2 "Try \`$0 --help' for more information" + exit 1 +fi + +run=: + +# In the cases where this matters, `missing' is being run in the +# srcdir already. +if test -f configure.ac; then + configure_ac=configure.ac +else + configure_ac=configure.in +fi + +case "$1" in +--run) + # Try to run requested program, and just exit if it succeeds. + run= + shift + "$@" && exit 0 + ;; +esac + +# If it does not exist, or fails to run (possibly an outdated version), +# try to emulate it. +case "$1" in + + -h|--h|--he|--hel|--help) + echo "\ +$0 [OPTION]... PROGRAM [ARGUMENT]... + +Handle \`PROGRAM [ARGUMENT]...' for when PROGRAM is missing, or return an +error status if there is no known handling for PROGRAM. + +Options: + -h, --help display this help and exit + -v, --version output version information and exit + --run try to run the given command, and emulate it if it fails + +Supported PROGRAM values: + aclocal touch file \`aclocal.m4' + autoconf touch file \`configure' + autoheader touch file \`config.h.in' + automake touch all \`Makefile.in' files + bison create \`y.tab.[ch]', if possible, from existing .[ch] + flex create \`lex.yy.c', if possible, from existing .c + help2man touch the output file + lex create \`lex.yy.c', if possible, from existing .c + makeinfo touch the output file + tar try tar, gnutar, gtar, then tar without non-portable flags + yacc create \`y.tab.[ch]', if possible, from existing .[ch]" + ;; + + -v|--v|--ve|--ver|--vers|--versi|--versio|--version) + echo "missing 0.4 - GNU automake" + ;; + + -*) + echo 1>&2 "$0: Unknown \`$1' option" + echo 1>&2 "Try \`$0 --help' for more information" + exit 1 + ;; + + aclocal*) + if test -z "$run" && ($1 --version) > /dev/null 2>&1; then + # We have it, but it failed. + exit 1 + fi + + echo 1>&2 "\ +WARNING: \`$1' is missing on your system. You should only need it if + you modified \`acinclude.m4' or \`${configure_ac}'. You might want + to install the \`Automake' and \`Perl' packages. Grab them from + any GNU archive site." + touch aclocal.m4 + ;; + + autoconf) + if test -z "$run" && ($1 --version) > /dev/null 2>&1; then + # We have it, but it failed. + exit 1 + fi + + echo 1>&2 "\ +WARNING: \`$1' is missing on your system. You should only need it if + you modified \`${configure_ac}'. You might want to install the + \`Autoconf' and \`GNU m4' packages. Grab them from any GNU + archive site." + touch configure + ;; + + autoheader) + if test -z "$run" && ($1 --version) > /dev/null 2>&1; then + # We have it, but it failed. + exit 1 + fi + + echo 1>&2 "\ +WARNING: \`$1' is missing on your system. You should only need it if + you modified \`acconfig.h' or \`${configure_ac}'. You might want + to install the \`Autoconf' and \`GNU m4' packages. Grab them + from any GNU archive site." + files=`sed -n 's/^[ ]*A[CM]_CONFIG_HEADER(\([^)]*\)).*/\1/p' ${configure_ac}` + test -z "$files" && files="config.h" + touch_files= + for f in $files; do + case "$f" in + *:*) touch_files="$touch_files "`echo "$f" | + sed -e 's/^[^:]*://' -e 's/:.*//'`;; + *) touch_files="$touch_files $f.in";; + esac + done + touch $touch_files + ;; + + automake*) + if test -z "$run" && ($1 --version) > /dev/null 2>&1; then + # We have it, but it failed. + exit 1 + fi + + echo 1>&2 "\ +WARNING: \`$1' is missing on your system. You should only need it if + you modified \`Makefile.am', \`acinclude.m4' or \`${configure_ac}'. + You might want to install the \`Automake' and \`Perl' packages. + Grab them from any GNU archive site." + find . -type f -name Makefile.am -print | + sed 's/\.am$/.in/' | + while read f; do touch "$f"; done + ;; + + autom4te) + if test -z "$run" && ($1 --version) > /dev/null 2>&1; then + # We have it, but it failed. + exit 1 + fi + + echo 1>&2 "\ +WARNING: \`$1' is needed, and you do not seem to have it handy on your + system. You might have modified some files without having the + proper tools for further handling them. + You can get \`$1Help2man' as part of \`Autoconf' from any GNU + archive site." + + file=`echo "$*" | sed -n 's/.*--output[ =]*\([^ ]*\).*/\1/p'` + test -z "$file" && file=`echo "$*" | sed -n 's/.*-o[ ]*\([^ ]*\).*/\1/p'` + if test -f "$file"; then + touch $file + else + test -z "$file" || exec >$file + echo "#! /bin/sh" + echo "# Created by GNU Automake missing as a replacement of" + echo "# $ $@" + echo "exit 0" + chmod +x $file + exit 1 + fi + ;; + + bison|yacc) + echo 1>&2 "\ +WARNING: \`$1' is missing on your system. You should only need it if + you modified a \`.y' file. You may need the \`Bison' package + in order for those modifications to take effect. You can get + \`Bison' from any GNU archive site." + rm -f y.tab.c y.tab.h + if [ $# -ne 1 ]; then + eval LASTARG="\${$#}" + case "$LASTARG" in + *.y) + SRCFILE=`echo "$LASTARG" | sed 's/y$/c/'` + if [ -f "$SRCFILE" ]; then + cp "$SRCFILE" y.tab.c + fi + SRCFILE=`echo "$LASTARG" | sed 's/y$/h/'` + if [ -f "$SRCFILE" ]; then + cp "$SRCFILE" y.tab.h + fi + ;; + esac + fi + if [ ! -f y.tab.h ]; then + echo >y.tab.h + fi + if [ ! -f y.tab.c ]; then + echo 'main() { return 0; }' >y.tab.c + fi + ;; + + lex|flex) + echo 1>&2 "\ +WARNING: \`$1' is missing on your system. You should only need it if + you modified a \`.l' file. You may need the \`Flex' package + in order for those modifications to take effect. You can get + \`Flex' from any GNU archive site." + rm -f lex.yy.c + if [ $# -ne 1 ]; then + eval LASTARG="\${$#}" + case "$LASTARG" in + *.l) + SRCFILE=`echo "$LASTARG" | sed 's/l$/c/'` + if [ -f "$SRCFILE" ]; then + cp "$SRCFILE" lex.yy.c + fi + ;; + esac + fi + if [ ! -f lex.yy.c ]; then + echo 'main() { return 0; }' >lex.yy.c + fi + ;; + + help2man) + if test -z "$run" && ($1 --version) > /dev/null 2>&1; then + # We have it, but it failed. + exit 1 + fi + + echo 1>&2 "\ +WARNING: \`$1' is missing on your system. You should only need it if + you modified a dependency of a manual page. You may need the + \`Help2man' package in order for those modifications to take + effect. You can get \`Help2man' from any GNU archive site." + + file=`echo "$*" | sed -n 's/.*-o \([^ ]*\).*/\1/p'` + if test -z "$file"; then + file=`echo "$*" | sed -n 's/.*--output=\([^ ]*\).*/\1/p'` + fi + if [ -f "$file" ]; then + touch $file + else + test -z "$file" || exec >$file + echo ".ab help2man is required to generate this page" + exit 1 + fi + ;; + + makeinfo) + if test -z "$run" && (makeinfo --version) > /dev/null 2>&1; then + # We have makeinfo, but it failed. + exit 1 + fi + + echo 1>&2 "\ +WARNING: \`$1' is missing on your system. You should only need it if + you modified a \`.texi' or \`.texinfo' file, or any other file + indirectly affecting the aspect of the manual. The spurious + call might also be the consequence of using a buggy \`make' (AIX, + DU, IRIX). You might want to install the \`Texinfo' package or + the \`GNU make' package. Grab either from any GNU archive site." + file=`echo "$*" | sed -n 's/.*-o \([^ ]*\).*/\1/p'` + if test -z "$file"; then + file=`echo "$*" | sed 's/.* \([^ ]*\) *$/\1/'` + file=`sed -n '/^@setfilename/ { s/.* \([^ ]*\) *$/\1/; p; q; }' $file` + fi + touch $file + ;; + + tar) + shift + if test -n "$run"; then + echo 1>&2 "ERROR: \`tar' requires --run" + exit 1 + fi + + # We have already tried tar in the generic part. + # Look for gnutar/gtar before invocation to avoid ugly error + # messages. + if (gnutar --version > /dev/null 2>&1); then + gnutar "$@" && exit 0 + fi + if (gtar --version > /dev/null 2>&1); then + gtar "$@" && exit 0 + fi + firstarg="$1" + if shift; then + case "$firstarg" in + *o*) + firstarg=`echo "$firstarg" | sed s/o//` + tar "$firstarg" "$@" && exit 0 + ;; + esac + case "$firstarg" in + *h*) + firstarg=`echo "$firstarg" | sed s/h//` + tar "$firstarg" "$@" && exit 0 + ;; + esac + fi + + echo 1>&2 "\ +WARNING: I can't seem to be able to run \`tar' with the given arguments. + You may want to install GNU tar or Free paxutils, or check the + command line arguments." + exit 1 + ;; + + *) + echo 1>&2 "\ +WARNING: \`$1' is needed, and you do not seem to have it handy on your + system. You might have modified some files without having the + proper tools for further handling them. Check the \`README' file, + it often tells you about the needed prerequirements for installing + this package. You may also peek at any GNU archive site, in case + some other package would contain this missing \`$1' program." + exit 1 + ;; +esac + +exit 0 diff --git a/mozilla/zap/zmk/speex-1.1.10/mkinstalldirs b/mozilla/zap/zmk/speex-1.1.10/mkinstalldirs new file mode 100755 index 00000000000..ba0325b9a2b --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/mkinstalldirs @@ -0,0 +1,111 @@ +#! /bin/sh +# mkinstalldirs --- make directory hierarchy +# Author: Noah Friedman +# Created: 1993-05-16 +# Public domain + +errstatus=0 +dirmode="" + +usage="\ +Usage: mkinstalldirs [-h] [--help] [-m mode] dir ..." + +# process command line arguments +while test $# -gt 0 ; do + case $1 in + -h | --help | --h*) # -h for help + echo "$usage" 1>&2 + exit 0 + ;; + -m) # -m PERM arg + shift + test $# -eq 0 && { echo "$usage" 1>&2; exit 1; } + dirmode=$1 + shift + ;; + --) # stop option processing + shift + break + ;; + -*) # unknown option + echo "$usage" 1>&2 + exit 1 + ;; + *) # first non-opt arg + break + ;; + esac +done + +for file +do + if test -d "$file"; then + shift + else + break + fi +done + +case $# in + 0) exit 0 ;; +esac + +case $dirmode in + '') + if mkdir -p -- . 2>/dev/null; then + echo "mkdir -p -- $*" + exec mkdir -p -- "$@" + fi + ;; + *) + if mkdir -m "$dirmode" -p -- . 2>/dev/null; then + echo "mkdir -m $dirmode -p -- $*" + exec mkdir -m "$dirmode" -p -- "$@" + fi + ;; +esac + +for file +do + set fnord `echo ":$file" | sed -ne 's/^:\//#/;s/^://;s/\// /g;s/^#/\//;p'` + shift + + pathcomp= + for d + do + pathcomp="$pathcomp$d" + case $pathcomp in + -*) pathcomp=./$pathcomp ;; + esac + + if test ! -d "$pathcomp"; then + echo "mkdir $pathcomp" + + mkdir "$pathcomp" || lasterr=$? + + if test ! -d "$pathcomp"; then + errstatus=$lasterr + else + if test ! -z "$dirmode"; then + echo "chmod $dirmode $pathcomp" + lasterr="" + chmod "$dirmode" "$pathcomp" || lasterr=$? + + if test ! -z "$lasterr"; then + errstatus=$lasterr + fi + fi + fi + fi + + pathcomp="$pathcomp/" + done +done + +exit $errstatus + +# Local Variables: +# mode: shell-script +# sh-indentation: 2 +# End: +# mkinstalldirs ends here diff --git a/mozilla/zap/zmk/speex-1.1.10/speex.m4 b/mozilla/zap/zmk/speex-1.1.10/speex.m4 new file mode 100755 index 00000000000..96623142fc3 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/speex.m4 @@ -0,0 +1,104 @@ +# Configure paths for libspeex +# Jean-Marc Valin +# Shamelessly stolen from: +# Jack Moffitt 10-21-2000 +# Shamelessly stolen from Owen Taylor and Manish Singh + +dnl XIPH_PATH_SPEEX([ACTION-IF-FOUND [, ACTION-IF-NOT-FOUND]]) +dnl Test for libspeex, and define SPEEX_CFLAGS and SPEEX_LIBS +dnl +AC_DEFUN([XIPH_PATH_SPEEX], +[dnl +dnl Get the cflags and libraries +dnl +AC_ARG_WITH(speex,[ --with-speex=PFX Prefix where libspeex is installed (optional)], speex_prefix="$withval", speex_prefix="") +AC_ARG_WITH(speex-libraries,[ --with-speex-libraries=DIR Directory where libspeex library is installed (optional)], speex_libraries="$withval", speex_libraries="") +AC_ARG_WITH(speex-includes,[ --with-speex-includes=DIR Directory where libspeex header files are installed (optional)], speex_includes="$withval", speex_includes="") +AC_ARG_ENABLE(speextest, [ --disable-speextest Do not try to compile and run a test Speex program],, enable_speextest=yes) + + if test "x$speex_libraries" != "x" ; then + SPEEX_LIBS="-L$speex_libraries" + elif test "x$speex_prefix" != "x" ; then + SPEEX_LIBS="-L$speex_prefix/lib" + elif test "x$prefix" != "xNONE" ; then + SPEEX_LIBS="-L$prefix/lib" + fi + + SPEEX_LIBS="$SPEEX_LIBS -lspeex" + + if test "x$speex_includes" != "x" ; then + SPEEX_CFLAGS="-I$speex_includes" + elif test "x$speex_prefix" != "x" ; then + SPEEX_CFLAGS="-I$speex_prefix/include" + elif test "x$prefix" != "xNONE"; then + SPEEX_CFLAGS="-I$prefix/include" + fi + + AC_MSG_CHECKING(for Speex) + no_speex="" + + + if test "x$enable_speextest" = "xyes" ; then + ac_save_CFLAGS="$CFLAGS" + ac_save_LIBS="$LIBS" + CFLAGS="$CFLAGS $SPEEX_CFLAGS" + LIBS="$LIBS $SPEEX_LIBS" +dnl +dnl Now check if the installed Speex is sufficiently new. +dnl + rm -f conf.speextest + AC_TRY_RUN([ +#include +#include +#include +#include + +int main () +{ + system("touch conf.speextest"); + return 0; +} + +],, no_speex=yes,[echo $ac_n "cross compiling; assumed OK... $ac_c"]) + CFLAGS="$ac_save_CFLAGS" + LIBS="$ac_save_LIBS" + fi + + if test "x$no_speex" = "x" ; then + AC_MSG_RESULT(yes) + ifelse([$1], , :, [$1]) + else + AC_MSG_RESULT(no) + if test -f conf.speextest ; then + : + else + echo "*** Could not run Speex test program, checking why..." + CFLAGS="$CFLAGS $SPEEX_CFLAGS" + LIBS="$LIBS $SPEEX_LIBS" + AC_TRY_LINK([ +#include +#include +], [ return 0; ], + [ echo "*** The test program compiled, but did not run. This usually means" + echo "*** that the run-time linker is not finding Speex or finding the wrong" + echo "*** version of Speex. If it is not finding Speex, you'll need to set your" + echo "*** LD_LIBRARY_PATH environment variable, or edit /etc/ld.so.conf to point" + echo "*** to the installed location Also, make sure you have run ldconfig if that" + echo "*** is required on your system" + echo "***" + echo "*** If you have an old version installed, it is best to remove it, although" + echo "*** you may also be able to get things to work by modifying LD_LIBRARY_PATH"], + [ echo "*** The test program failed to compile or link. See the file config.log for the" + echo "*** exact error that occured. This usually means Speex was incorrectly installed" + echo "*** or that you have moved Speex since it was installed." ]) + CFLAGS="$ac_save_CFLAGS" + LIBS="$ac_save_LIBS" + fi + SPEEX_CFLAGS="" + SPEEX_LIBS="" + ifelse([$2], , :, [$2]) + fi + AC_SUBST(SPEEX_CFLAGS) + AC_SUBST(SPEEX_LIBS) + rm -f conf.speextest +]) diff --git a/mozilla/zap/zmk/speex-1.1.10/speex.pc.in b/mozilla/zap/zmk/speex-1.1.10/speex.pc.in new file mode 100755 index 00000000000..c58d7b3b39b --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/speex.pc.in @@ -0,0 +1,14 @@ +# libspeex pkg-config source file + +prefix=@prefix@ +exec_prefix=@exec_prefix@ +libdir=@libdir@ +includedir=@includedir@ + +Name: speex +Description: Speex is an audio codec tuned for speech +Version: @SPEEX_VERSION@ +Requires: +Conflicts: +Libs: -L${libdir} -lspeex +Cflags: -I${includedir} diff --git a/mozilla/zap/zmk/speex-1.1.10/src/Makefile.am b/mozilla/zap/zmk/speex-1.1.10/src/Makefile.am new file mode 100755 index 00000000000..0f261738070 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/src/Makefile.am @@ -0,0 +1,26 @@ +## Process this file with automake to produce Makefile.in. -*-Makefile-*- + +# $Id: Makefile.am,v 1.1.2.1 2005-08-16 20:04:30 alex%croczilla.com Exp $ + +# Disable automatic dependency tracking if using other tools than gcc and gmake +#AUTOMAKE_OPTIONS = no-dependencies + +INCLUDES = -I$(top_srcdir)/include -I$(top_builddir)/include -I$(top_builddir) @OGG_CFLAGS@ + +mandir = $(prefix)/share/man +man_MANS = speexenc.1 speexdec.1 + +EXTRA_DIST = $(man_MANS) getopt_win.h getopt.c getopt1.c wave_out.c wave_out.h + +include_HEADERS = +noinst_HEADERS = wav_io.h + +bin_PROGRAMS = speexenc speexdec + +speexenc_SOURCES = speexenc.c wav_io.c +speexenc_LDADD = $(top_builddir)/libspeex/libspeex.la \ + $(OGG_LIBS) + +speexdec_SOURCES = speexdec.c wav_io.c +speexdec_LDADD = $(top_builddir)/libspeex/libspeex.la \ + $(OGG_LIBS) diff --git a/mozilla/zap/zmk/speex-1.1.10/src/Makefile.in b/mozilla/zap/zmk/speex-1.1.10/src/Makefile.in new file mode 100755 index 00000000000..b1342e23295 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/src/Makefile.in @@ -0,0 +1,561 @@ +# Makefile.in generated by automake 1.8.5 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004 Free Software Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +# $Id: Makefile.in,v 1.1.2.1 2005-08-16 20:04:30 alex%croczilla.com Exp $ + +# Disable automatic dependency tracking if using other tools than gcc and gmake +#AUTOMAKE_OPTIONS = no-dependencies + + +SOURCES = $(speexdec_SOURCES) $(speexenc_SOURCES) + +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +top_builddir = .. +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +INSTALL = @INSTALL@ +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +host_triplet = @host@ +bin_PROGRAMS = speexenc$(EXEEXT) speexdec$(EXEEXT) +subdir = src +DIST_COMMON = $(include_HEADERS) $(noinst_HEADERS) \ + $(srcdir)/Makefile.am $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ + $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = +am__installdirs = "$(DESTDIR)$(bindir)" "$(DESTDIR)$(man1dir)" "$(DESTDIR)$(includedir)" +binPROGRAMS_INSTALL = $(INSTALL_PROGRAM) +PROGRAMS = $(bin_PROGRAMS) +am_speexdec_OBJECTS = speexdec.$(OBJEXT) wav_io.$(OBJEXT) +speexdec_OBJECTS = $(am_speexdec_OBJECTS) +am__DEPENDENCIES_1 = +speexdec_DEPENDENCIES = $(top_builddir)/libspeex/libspeex.la \ + $(am__DEPENDENCIES_1) +am_speexenc_OBJECTS = speexenc.$(OBJEXT) wav_io.$(OBJEXT) +speexenc_OBJECTS = $(am_speexenc_OBJECTS) +speexenc_DEPENDENCIES = $(top_builddir)/libspeex/libspeex.la \ + $(am__DEPENDENCIES_1) +DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir) +depcomp = $(SHELL) $(top_srcdir)/depcomp +am__depfiles_maybe = depfiles +@AMDEP_TRUE@DEP_FILES = ./$(DEPDIR)/speexdec.Po \ +@AMDEP_TRUE@ ./$(DEPDIR)/speexenc.Po ./$(DEPDIR)/wav_io.Po +COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ + $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) +LTCOMPILE = $(LIBTOOL) --mode=compile $(CC) $(DEFS) \ + $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ + $(AM_CFLAGS) $(CFLAGS) +CCLD = $(CC) +LINK = $(LIBTOOL) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ + $(AM_LDFLAGS) $(LDFLAGS) -o $@ +SOURCES = $(speexdec_SOURCES) $(speexenc_SOURCES) +DIST_SOURCES = $(speexdec_SOURCES) $(speexenc_SOURCES) +man1dir = $(mandir)/man1 +NROFF = nroff +MANS = $(man_MANS) +includeHEADERS_INSTALL = $(INSTALL_HEADER) +HEADERS = $(include_HEADERS) $(noinst_HEADERS) +ETAGS = etags +CTAGS = ctags +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +AMDEP_FALSE = @AMDEP_FALSE@ +AMDEP_TRUE = @AMDEP_TRUE@ +AMTAR = @AMTAR@ +AR = @AR@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CXX = @CXX@ +CXXCPP = @CXXCPP@ +CXXDEPMODE = @CXXDEPMODE@ +CXXFLAGS = @CXXFLAGS@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +ECHO = @ECHO@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +F77 = @F77@ +FFLAGS = @FFLAGS@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +LDFLAGS = @LDFLAGS@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +MAINT = @MAINT@ +MAINTAINER_MODE_FALSE = @MAINTAINER_MODE_FALSE@ +MAINTAINER_MODE_TRUE = @MAINTAINER_MODE_TRUE@ +MAKEINFO = @MAKEINFO@ +OBJEXT = @OBJEXT@ +OGG_CFLAGS = @OGG_CFLAGS@ +OGG_LIBS = @OGG_LIBS@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +RANLIB = @RANLIB@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +SIZE16 = @SIZE16@ +SIZE32 = @SIZE32@ +SPEEX_LT_AGE = @SPEEX_LT_AGE@ +SPEEX_LT_CURRENT = @SPEEX_LT_CURRENT@ +SPEEX_LT_REVISION = @SPEEX_LT_REVISION@ +SPEEX_VERSION = @SPEEX_VERSION@ +STRIP = @STRIP@ +VERSION = @VERSION@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_CXX = @ac_ct_CXX@ +ac_ct_F77 = @ac_ct_F77@ +ac_ct_RANLIB = @ac_ct_RANLIB@ +ac_ct_STRIP = @ac_ct_STRIP@ +am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ +am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ +am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ +am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +datadir = @datadir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localstatedir = @localstatedir@ +mandir = $(prefix)/share/man +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +src = @src@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +INCLUDES = -I$(top_srcdir)/include -I$(top_builddir)/include -I$(top_builddir) @OGG_CFLAGS@ +man_MANS = speexenc.1 speexdec.1 +EXTRA_DIST = $(man_MANS) getopt_win.h getopt.c getopt1.c wave_out.c wave_out.h +include_HEADERS = +noinst_HEADERS = wav_io.h +speexenc_SOURCES = speexenc.c wav_io.c +speexenc_LDADD = $(top_builddir)/libspeex/libspeex.la \ + $(OGG_LIBS) + +speexdec_SOURCES = speexdec.c wav_io.c +speexdec_LDADD = $(top_builddir)/libspeex/libspeex.la \ + $(OGG_LIBS) + +all: all-am + +.SUFFIXES: +.SUFFIXES: .c .lo .o .obj +$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ + && exit 0; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/Makefile'; \ + cd $(top_srcdir) && \ + $(AUTOMAKE) --gnu src/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +install-binPROGRAMS: $(bin_PROGRAMS) + @$(NORMAL_INSTALL) + test -z "$(bindir)" || $(mkdir_p) "$(DESTDIR)$(bindir)" + @list='$(bin_PROGRAMS)'; for p in $$list; do \ + p1=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ + if test -f $$p \ + || test -f $$p1 \ + ; then \ + f=`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \ + echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=install $(binPROGRAMS_INSTALL) '$$p' '$(DESTDIR)$(bindir)/$$f'"; \ + $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=install $(binPROGRAMS_INSTALL) "$$p" "$(DESTDIR)$(bindir)/$$f" || exit 1; \ + else :; fi; \ + done + +uninstall-binPROGRAMS: + @$(NORMAL_UNINSTALL) + @list='$(bin_PROGRAMS)'; for p in $$list; do \ + f=`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/'`; \ + echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \ + rm -f "$(DESTDIR)$(bindir)/$$f"; \ + done + +clean-binPROGRAMS: + @list='$(bin_PROGRAMS)'; for p in $$list; do \ + f=`echo $$p|sed 's/$(EXEEXT)$$//'`; \ + echo " rm -f $$p $$f"; \ + rm -f $$p $$f ; \ + done +speexdec$(EXEEXT): $(speexdec_OBJECTS) $(speexdec_DEPENDENCIES) + @rm -f speexdec$(EXEEXT) + $(LINK) $(speexdec_LDFLAGS) $(speexdec_OBJECTS) $(speexdec_LDADD) $(LIBS) +speexenc$(EXEEXT): $(speexenc_OBJECTS) $(speexenc_DEPENDENCIES) + @rm -f speexenc$(EXEEXT) + $(LINK) $(speexenc_LDFLAGS) $(speexenc_OBJECTS) $(speexenc_LDADD) $(LIBS) + +mostlyclean-compile: + -rm -f *.$(OBJEXT) + +distclean-compile: + -rm -f *.tab.c + +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/speexdec.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/speexenc.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/wav_io.Po@am__quote@ + +.c.o: +@am__fastdepCC_TRUE@ if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ +@am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi +@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ depfile='$(DEPDIR)/$*.Po' tmpdepfile='$(DEPDIR)/$*.TPo' @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(COMPILE) -c $< + +.c.obj: +@am__fastdepCC_TRUE@ if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ `$(CYGPATH_W) '$<'`; \ +@am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi +@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ depfile='$(DEPDIR)/$*.Po' tmpdepfile='$(DEPDIR)/$*.TPo' @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(COMPILE) -c `$(CYGPATH_W) '$<'` + +.c.lo: +@am__fastdepCC_TRUE@ if $(LTCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \ +@am__fastdepCC_TRUE@ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Plo"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi +@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ depfile='$(DEPDIR)/$*.Plo' tmpdepfile='$(DEPDIR)/$*.TPlo' @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(LTCOMPILE) -c -o $@ $< + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +distclean-libtool: + -rm -f libtool +uninstall-info-am: +install-man1: $(man1_MANS) $(man_MANS) + @$(NORMAL_INSTALL) + test -z "$(man1dir)" || $(mkdir_p) "$(DESTDIR)$(man1dir)" + @list='$(man1_MANS) $(dist_man1_MANS) $(nodist_man1_MANS)'; \ + l2='$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \ + for i in $$l2; do \ + case "$$i" in \ + *.1*) list="$$list $$i" ;; \ + esac; \ + done; \ + for i in $$list; do \ + if test -f $(srcdir)/$$i; then file=$(srcdir)/$$i; \ + else file=$$i; fi; \ + ext=`echo $$i | sed -e 's/^.*\\.//'`; \ + case "$$ext" in \ + 1*) ;; \ + *) ext='1' ;; \ + esac; \ + inst=`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \ + inst=`echo $$inst | sed -e 's/^.*\///'`; \ + inst=`echo $$inst | sed '$(transform)'`.$$ext; \ + echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \ + $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst"; \ + done +uninstall-man1: + @$(NORMAL_UNINSTALL) + @list='$(man1_MANS) $(dist_man1_MANS) $(nodist_man1_MANS)'; \ + l2='$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \ + for i in $$l2; do \ + case "$$i" in \ + *.1*) list="$$list $$i" ;; \ + esac; \ + done; \ + for i in $$list; do \ + ext=`echo $$i | sed -e 's/^.*\\.//'`; \ + case "$$ext" in \ + 1*) ;; \ + *) ext='1' ;; \ + esac; \ + inst=`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \ + inst=`echo $$inst | sed -e 's/^.*\///'`; \ + inst=`echo $$inst | sed '$(transform)'`.$$ext; \ + echo " rm -f '$(DESTDIR)$(man1dir)/$$inst'"; \ + rm -f "$(DESTDIR)$(man1dir)/$$inst"; \ + done +install-includeHEADERS: $(include_HEADERS) + @$(NORMAL_INSTALL) + test -z "$(includedir)" || $(mkdir_p) "$(DESTDIR)$(includedir)" + @list='$(include_HEADERS)'; for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + f="`echo $$p | sed -e 's|^.*/||'`"; \ + echo " $(includeHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(includedir)/$$f'"; \ + $(includeHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(includedir)/$$f"; \ + done + +uninstall-includeHEADERS: + @$(NORMAL_UNINSTALL) + @list='$(include_HEADERS)'; for p in $$list; do \ + f="`echo $$p | sed -e 's|^.*/||'`"; \ + echo " rm -f '$(DESTDIR)$(includedir)/$$f'"; \ + rm -f "$(DESTDIR)$(includedir)/$$f"; \ + done + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + tags=; \ + here=`pwd`; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$tags $$unique; \ + fi +ctags: CTAGS +CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + tags=; \ + here=`pwd`; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + test -z "$(CTAGS_ARGS)$$tags$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$tags $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && cd $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) $$here + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ + list='$(DISTFILES)'; for file in $$list; do \ + case $$file in \ + $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ + $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ + esac; \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test "$$dir" != "$$file" && test "$$dir" != "."; then \ + dir="/$$dir"; \ + $(mkdir_p) "$(distdir)$$dir"; \ + else \ + dir=''; \ + fi; \ + if test -d $$d/$$file; then \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + fi; \ + cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + else \ + test -f $(distdir)/$$file \ + || cp -p $$d/$$file $(distdir)/$$file \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile $(PROGRAMS) $(MANS) $(HEADERS) +installdirs: + for dir in "$(DESTDIR)$(bindir)" "$(DESTDIR)$(man1dir)" "$(DESTDIR)$(includedir)"; do \ + test -z "$$dir" || $(mkdir_p) "$$dir"; \ + done +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + `test -z '$(STRIP)' || \ + echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -rm -f $(CONFIG_CLEAN_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am + +distclean: distclean-am + -rm -rf ./$(DEPDIR) + -rm -f Makefile +distclean-am: clean-am distclean-compile distclean-generic \ + distclean-libtool distclean-tags + +dvi: dvi-am + +dvi-am: + +html: html-am + +info: info-am + +info-am: + +install-data-am: install-includeHEADERS install-man + +install-exec-am: install-binPROGRAMS + +install-info: install-info-am + +install-man: install-man1 + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -rf ./$(DEPDIR) + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-compile mostlyclean-generic \ + mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-binPROGRAMS uninstall-includeHEADERS \ + uninstall-info-am uninstall-man + +uninstall-man: uninstall-man1 + +.PHONY: CTAGS GTAGS all all-am check check-am clean clean-binPROGRAMS \ + clean-generic clean-libtool ctags distclean distclean-compile \ + distclean-generic distclean-libtool distclean-tags distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-binPROGRAMS install-data install-data-am install-exec \ + install-exec-am install-includeHEADERS install-info \ + install-info-am install-man install-man1 install-strip \ + installcheck installcheck-am installdirs maintainer-clean \ + maintainer-clean-generic mostlyclean mostlyclean-compile \ + mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ + tags uninstall uninstall-am uninstall-binPROGRAMS \ + uninstall-includeHEADERS uninstall-info-am uninstall-man \ + uninstall-man1 + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/mozilla/zap/zmk/speex-1.1.10/src/getopt.c b/mozilla/zap/zmk/speex-1.1.10/src/getopt.c new file mode 100755 index 00000000000..33d299bd46a --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/src/getopt.c @@ -0,0 +1,1047 @@ +/* Getopt for GNU. + NOTE: getopt is now part of the C library, so if you don't know what + "Keep this file name-space clean" means, talk to drepper@gnu.org + before changing it! + + Copyright (C) 1987, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 + Free Software Foundation, Inc. + + The GNU C Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public License as + published by the Free Software Foundation; either version 2 of the + License, or (at your option) any later version. + + The GNU C Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public + License along with the GNU C Library; see the file COPYING.LIB. If not, + write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, + Boston, MA 02111-1307, USA. */ + +/* This tells Alpha OSF/1 not to define a getopt prototype in . + Ditto for AIX 3.2 and . */ +#ifndef _NO_PROTO +# define _NO_PROTO +#endif + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#if !defined __STDC__ || !__STDC__ +/* This is a separate conditional since some stdc systems + reject `defined (const)'. */ +# ifndef const +# define const +# endif +#endif + +#include + +/* Comment out all this code if we are using the GNU C Library, and are not + actually compiling the library itself. This code is part of the GNU C + Library, but also included in many other GNU distributions. Compiling + and linking in this code is a waste when using the GNU C library + (especially if it is a shared library). Rather than having every GNU + program understand `configure --with-gnu-libc' and omit the object files, + it is simpler to just do this in the source for each such file. */ + +#define GETOPT_INTERFACE_VERSION 2 +#if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2 +# include +# if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION +# define ELIDE_CODE +# endif +#endif + +#ifndef ELIDE_CODE + + +/* This needs to come after some library #include + to get __GNU_LIBRARY__ defined. */ +#ifdef __GNU_LIBRARY__ +/* Don't include stdlib.h for non-GNU C libraries because some of them + contain conflicting prototypes for getopt. */ +# include +# include +#endif /* GNU C library. */ + +#ifdef VMS +# include +# if HAVE_STRING_H - 0 +# include +# endif +#endif + +#ifndef _ +/* This is for other GNU distributions with internationalized messages. + When compiling libc, the _ macro is predefined. */ +# ifdef HAVE_LIBINTL_H +# include +# define _(msgid) gettext (msgid) +# else +# define _(msgid) (msgid) +# endif +#endif + +/* This version of `getopt' appears to the caller like standard Unix `getopt' + but it behaves differently for the user, since it allows the user + to intersperse the options with the other arguments. + + As `getopt' works, it permutes the elements of ARGV so that, + when it is done, all the options precede everything else. Thus + all application programs are extended to handle flexible argument order. + + Setting the environment variable POSIXLY_CORRECT disables permutation. + Then the behavior is completely standard. + + GNU application programs can use a third alternative mode in which + they can distinguish the relative order of options and other arguments. */ + +#include "getopt_win.h" + +/* For communication from `getopt' to the caller. + When `getopt' finds an option that takes an argument, + the argument value is returned here. + Also, when `ordering' is RETURN_IN_ORDER, + each non-option ARGV-element is returned here. */ + +char *optarg; + +/* Index in ARGV of the next element to be scanned. + This is used for communication to and from the caller + and for communication between successive calls to `getopt'. + + On entry to `getopt', zero means this is the first call; initialize. + + When `getopt' returns -1, this is the index of the first of the + non-option elements that the caller should itself scan. + + Otherwise, `optind' communicates from one call to the next + how much of ARGV has been scanned so far. */ + +/* 1003.2 says this must be 1 before any call. */ +int optind = 1; + +/* Formerly, initialization of getopt depended on optind==0, which + causes problems with re-calling getopt as programs generally don't + know that. */ + +int __getopt_initialized; + +/* The next char to be scanned in the option-element + in which the last option character we returned was found. + This allows us to pick up the scan where we left off. + + If this is zero, or a null string, it means resume the scan + by advancing to the next ARGV-element. */ + +static char *nextchar; + +/* Callers store zero here to inhibit the error message + for unrecognized options. */ + +int opterr = 1; + +/* Set to an option character which was unrecognized. + This must be initialized on some systems to avoid linking in the + system's own getopt implementation. */ + +int optopt = '?'; + +/* Describe how to deal with options that follow non-option ARGV-elements. + + If the caller did not specify anything, + the default is REQUIRE_ORDER if the environment variable + POSIXLY_CORRECT is defined, PERMUTE otherwise. + + REQUIRE_ORDER means don't recognize them as options; + stop option processing when the first non-option is seen. + This is what Unix does. + This mode of operation is selected by either setting the environment + variable POSIXLY_CORRECT, or using `+' as the first character + of the list of option characters. + + PERMUTE is the default. We permute the contents of ARGV as we scan, + so that eventually all the non-options are at the end. This allows options + to be given in any order, even with programs that were not written to + expect this. + + RETURN_IN_ORDER is an option available to programs that were written + to expect options and other ARGV-elements in any order and that care about + the ordering of the two. We describe each non-option ARGV-element + as if it were the argument of an option with character code 1. + Using `-' as the first character of the list of option characters + selects this mode of operation. + + The special argument `--' forces an end of option-scanning regardless + of the value of `ordering'. In the case of RETURN_IN_ORDER, only + `--' can cause `getopt' to return -1 with `optind' != ARGC. */ + +static enum +{ + REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER +} ordering; + +/* Value of POSIXLY_CORRECT environment variable. */ +static char *posixly_correct; + +#ifdef __GNU_LIBRARY__ +/* We want to avoid inclusion of string.h with non-GNU libraries + because there are many ways it can cause trouble. + On some systems, it contains special magic macros that don't work + in GCC. */ +# include +# define my_index strchr +#else + +#include + +/* Avoid depending on library functions or files + whose names are inconsistent. */ + +#ifndef getenv +extern char *getenv (); +#endif + +static char * +my_index (str, chr) + const char *str; + int chr; +{ + while (*str) + { + if (*str == chr) + return (char *) str; + str++; + } + return 0; +} + +/* If using GCC, we can safely declare strlen this way. + If not using GCC, it is ok not to declare it. */ +#ifdef __GNUC__ +/* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h. + That was relevant to code that was here before. */ +# if (!defined __STDC__ || !__STDC__) && !defined strlen +/* gcc with -traditional declares the built-in strlen to return int, + and has done so at least since version 2.4.5. -- rms. */ +extern int strlen (const char *); +# endif /* not __STDC__ */ +#endif /* __GNUC__ */ + +#endif /* not __GNU_LIBRARY__ */ + +/* Handle permutation of arguments. */ + +/* Describe the part of ARGV that contains non-options that have + been skipped. `first_nonopt' is the index in ARGV of the first of them; + `last_nonopt' is the index after the last of them. */ + +static int first_nonopt; +static int last_nonopt; + +#ifdef _LIBC +/* Bash 2.0 gives us an environment variable containing flags + indicating ARGV elements that should not be considered arguments. */ + +/* Defined in getopt_init.c */ +extern char *__getopt_nonoption_flags; + +static int nonoption_flags_max_len; +static int nonoption_flags_len; + +static int original_argc; +static char *const *original_argv; + +/* Make sure the environment variable bash 2.0 puts in the environment + is valid for the getopt call we must make sure that the ARGV passed + to getopt is that one passed to the process. */ +static void +__attribute__ ((unused)) +store_args_and_env (int argc, char *const *argv) +{ + /* XXX This is no good solution. We should rather copy the args so + that we can compare them later. But we must not use malloc(3). */ + original_argc = argc; + original_argv = argv; +} +# ifdef text_set_element +text_set_element (__libc_subinit, store_args_and_env); +# endif /* text_set_element */ + +# define SWAP_FLAGS(ch1, ch2) \ + if (nonoption_flags_len > 0) \ + { \ + char __tmp = __getopt_nonoption_flags[ch1]; \ + __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \ + __getopt_nonoption_flags[ch2] = __tmp; \ + } +#else /* !_LIBC */ +# define SWAP_FLAGS(ch1, ch2) +#endif /* _LIBC */ + +/* Exchange two adjacent subsequences of ARGV. + One subsequence is elements [first_nonopt,last_nonopt) + which contains all the non-options that have been skipped so far. + The other is elements [last_nonopt,optind), which contains all + the options processed since those non-options were skipped. + + `first_nonopt' and `last_nonopt' are relocated so that they describe + the new indices of the non-options in ARGV after they are moved. */ + +#if defined __STDC__ && __STDC__ +static void exchange (char **); +#endif + +static void +exchange (argv) + char **argv; +{ + int bottom = first_nonopt; + int middle = last_nonopt; + int top = optind; + char *tem; + + /* Exchange the shorter segment with the far end of the longer segment. + That puts the shorter segment into the right place. + It leaves the longer segment in the right place overall, + but it consists of two parts that need to be swapped next. */ + +#ifdef _LIBC + /* First make sure the handling of the `__getopt_nonoption_flags' + string can work normally. Our top argument must be in the range + of the string. */ + if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len) + { + /* We must extend the array. The user plays games with us and + presents new arguments. */ + char *new_str = malloc (top + 1); + if (new_str == NULL) + nonoption_flags_len = nonoption_flags_max_len = 0; + else + { + memset (__mempcpy (new_str, __getopt_nonoption_flags, + nonoption_flags_max_len), + '\0', top + 1 - nonoption_flags_max_len); + nonoption_flags_max_len = top + 1; + __getopt_nonoption_flags = new_str; + } + } +#endif + + while (top > middle && middle > bottom) + { + if (top - middle > middle - bottom) + { + /* Bottom segment is the short one. */ + int len = middle - bottom; + register int i; + + /* Swap it with the top part of the top segment. */ + for (i = 0; i < len; i++) + { + tem = argv[bottom + i]; + argv[bottom + i] = argv[top - (middle - bottom) + i]; + argv[top - (middle - bottom) + i] = tem; + SWAP_FLAGS (bottom + i, top - (middle - bottom) + i); + } + /* Exclude the moved bottom segment from further swapping. */ + top -= len; + } + else + { + /* Top segment is the short one. */ + int len = top - middle; + register int i; + + /* Swap it with the bottom part of the bottom segment. */ + for (i = 0; i < len; i++) + { + tem = argv[bottom + i]; + argv[bottom + i] = argv[middle + i]; + argv[middle + i] = tem; + SWAP_FLAGS (bottom + i, middle + i); + } + /* Exclude the moved top segment from further swapping. */ + bottom += len; + } + } + + /* Update records for the slots the non-options now occupy. */ + + first_nonopt += (optind - last_nonopt); + last_nonopt = optind; +} + +/* Initialize the internal data when the first call is made. */ + +#if defined __STDC__ && __STDC__ +static const char *_getopt_initialize (int, char *const *, const char *); +#endif +static const char * +_getopt_initialize (argc, argv, optstring) + int argc; + char *const *argv; + const char *optstring; +{ + /* Start processing options with ARGV-element 1 (since ARGV-element 0 + is the program name); the sequence of previously skipped + non-option ARGV-elements is empty. */ + + first_nonopt = last_nonopt = optind; + + nextchar = NULL; + + posixly_correct = getenv ("POSIXLY_CORRECT"); + + /* Determine how to handle the ordering of options and nonoptions. */ + + if (optstring[0] == '-') + { + ordering = RETURN_IN_ORDER; + ++optstring; + } + else if (optstring[0] == '+') + { + ordering = REQUIRE_ORDER; + ++optstring; + } + else if (posixly_correct != NULL) + ordering = REQUIRE_ORDER; + else + ordering = PERMUTE; + +#ifdef _LIBC + if (posixly_correct == NULL + && argc == original_argc && argv == original_argv) + { + if (nonoption_flags_max_len == 0) + { + if (__getopt_nonoption_flags == NULL + || __getopt_nonoption_flags[0] == '\0') + nonoption_flags_max_len = -1; + else + { + const char *orig_str = __getopt_nonoption_flags; + int len = nonoption_flags_max_len = strlen (orig_str); + if (nonoption_flags_max_len < argc) + nonoption_flags_max_len = argc; + __getopt_nonoption_flags = + (char *) malloc (nonoption_flags_max_len); + if (__getopt_nonoption_flags == NULL) + nonoption_flags_max_len = -1; + else + memset (__mempcpy (__getopt_nonoption_flags, orig_str, len), + '\0', nonoption_flags_max_len - len); + } + } + nonoption_flags_len = nonoption_flags_max_len; + } + else + nonoption_flags_len = 0; +#endif + + return optstring; +} + +/* Scan elements of ARGV (whose length is ARGC) for option characters + given in OPTSTRING. + + If an element of ARGV starts with '-', and is not exactly "-" or "--", + then it is an option element. The characters of this element + (aside from the initial '-') are option characters. If `getopt' + is called repeatedly, it returns successively each of the option characters + from each of the option elements. + + If `getopt' finds another option character, it returns that character, + updating `optind' and `nextchar' so that the next call to `getopt' can + resume the scan with the following option character or ARGV-element. + + If there are no more option characters, `getopt' returns -1. + Then `optind' is the index in ARGV of the first ARGV-element + that is not an option. (The ARGV-elements have been permuted + so that those that are not options now come last.) + + OPTSTRING is a string containing the legitimate option characters. + If an option character is seen that is not listed in OPTSTRING, + return '?' after printing an error message. If you set `opterr' to + zero, the error message is suppressed but we still return '?'. + + If a char in OPTSTRING is followed by a colon, that means it wants an arg, + so the following text in the same ARGV-element, or the text of the following + ARGV-element, is returned in `optarg'. Two colons mean an option that + wants an optional arg; if there is text in the current ARGV-element, + it is returned in `optarg', otherwise `optarg' is set to zero. + + If OPTSTRING starts with `-' or `+', it requests different methods of + handling the non-option ARGV-elements. + See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above. + + Long-named options begin with `--' instead of `-'. + Their names may be abbreviated as long as the abbreviation is unique + or is an exact match for some defined option. If they have an + argument, it follows the option name in the same ARGV-element, separated + from the option name by a `=', or else the in next ARGV-element. + When `getopt' finds a long-named option, it returns 0 if that option's + `flag' field is nonzero, the value of the option's `val' field + if the `flag' field is zero. + + The elements of ARGV aren't really const, because we permute them. + But we pretend they're const in the prototype to be compatible + with other systems. + + LONGOPTS is a vector of `struct option' terminated by an + element containing a name which is zero. + + LONGIND returns the index in LONGOPT of the long-named option found. + It is only valid when a long-named option has been found by the most + recent call. + + If LONG_ONLY is nonzero, '-' as well as '--' can introduce + long-named options. */ + +int +_getopt_internal (argc, argv, optstring, longopts, longind, long_only) + int argc; + char *const *argv; + const char *optstring; + const struct option *longopts; + int *longind; + int long_only; +{ + optarg = NULL; + + if (optind == 0 || !__getopt_initialized) + { + if (optind == 0) + optind = 1; /* Don't scan ARGV[0], the program name. */ + optstring = _getopt_initialize (argc, argv, optstring); + __getopt_initialized = 1; + } + + /* Test whether ARGV[optind] points to a non-option argument. + Either it does not have option syntax, or there is an environment flag + from the shell indicating it is not an option. The later information + is only used when the used in the GNU libc. */ +#ifdef _LIBC +# define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0' \ + || (optind < nonoption_flags_len \ + && __getopt_nonoption_flags[optind] == '1')) +#else +# define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0') +#endif + + if (nextchar == NULL || *nextchar == '\0') + { + /* Advance to the next ARGV-element. */ + + /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been + moved back by the user (who may also have changed the arguments). */ + if (last_nonopt > optind) + last_nonopt = optind; + if (first_nonopt > optind) + first_nonopt = optind; + + if (ordering == PERMUTE) + { + /* If we have just processed some options following some non-options, + exchange them so that the options come first. */ + + if (first_nonopt != last_nonopt && last_nonopt != optind) + exchange ((char **) argv); + else if (last_nonopt != optind) + first_nonopt = optind; + + /* Skip any additional non-options + and extend the range of non-options previously skipped. */ + + while (optind < argc && NONOPTION_P) + optind++; + last_nonopt = optind; + } + + /* The special ARGV-element `--' means premature end of options. + Skip it like a null option, + then exchange with previous non-options as if it were an option, + then skip everything else like a non-option. */ + + if (optind != argc && !strcmp (argv[optind], "--")) + { + optind++; + + if (first_nonopt != last_nonopt && last_nonopt != optind) + exchange ((char **) argv); + else if (first_nonopt == last_nonopt) + first_nonopt = optind; + last_nonopt = argc; + + optind = argc; + } + + /* If we have done all the ARGV-elements, stop the scan + and back over any non-options that we skipped and permuted. */ + + if (optind == argc) + { + /* Set the next-arg-index to point at the non-options + that we previously skipped, so the caller will digest them. */ + if (first_nonopt != last_nonopt) + optind = first_nonopt; + return -1; + } + + /* If we have come to a non-option and did not permute it, + either stop the scan or describe it to the caller and pass it by. */ + + if (NONOPTION_P) + { + if (ordering == REQUIRE_ORDER) + return -1; + optarg = argv[optind++]; + return 1; + } + + /* We have found another option-ARGV-element. + Skip the initial punctuation. */ + + nextchar = (argv[optind] + 1 + + (longopts != NULL && argv[optind][1] == '-')); + } + + /* Decode the current option-ARGV-element. */ + + /* Check whether the ARGV-element is a long option. + + If long_only and the ARGV-element has the form "-f", where f is + a valid short option, don't consider it an abbreviated form of + a long option that starts with f. Otherwise there would be no + way to give the -f short option. + + On the other hand, if there's a long option "fubar" and + the ARGV-element is "-fu", do consider that an abbreviation of + the long option, just like "--fu", and not "-f" with arg "u". + + This distinction seems to be the most useful approach. */ + + if (longopts != NULL + && (argv[optind][1] == '-' + || (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1]))))) + { + char *nameend; + const struct option *p; + const struct option *pfound = NULL; + int exact = 0; + int ambig = 0; + int indfound = -1; + int option_index; + + for (nameend = nextchar; *nameend && *nameend != '='; nameend++) + /* Do nothing. */ ; + + /* Test all long options for either exact match + or abbreviated matches. */ + for (p = longopts, option_index = 0; p->name; p++, option_index++) + if (!strncmp (p->name, nextchar, nameend - nextchar)) + { + if ((unsigned int) (nameend - nextchar) + == (unsigned int) strlen (p->name)) + { + /* Exact match found. */ + pfound = p; + indfound = option_index; + exact = 1; + break; + } + else if (pfound == NULL) + { + /* First nonexact match found. */ + pfound = p; + indfound = option_index; + } + else + /* Second or later nonexact match found. */ + ambig = 1; + } + + if (ambig && !exact) + { + if (opterr) + fprintf (stderr, _("%s: option `%s' is ambiguous\n"), + argv[0], argv[optind]); + nextchar += strlen (nextchar); + optind++; + optopt = 0; + return '?'; + } + + if (pfound != NULL) + { + option_index = indfound; + optind++; + if (*nameend) + { + /* Don't test has_arg with >, because some C compilers don't + allow it to be used on enums. */ + if (pfound->has_arg) + optarg = nameend + 1; + else + { + if (opterr) + { + if (argv[optind - 1][1] == '-') + /* --option */ + fprintf (stderr, + _("%s: option `--%s' doesn't allow an argument\n"), + argv[0], pfound->name); + else + /* +option or -option */ + fprintf (stderr, + _("%s: option `%c%s' doesn't allow an argument\n"), + argv[0], argv[optind - 1][0], pfound->name); + } + + nextchar += strlen (nextchar); + + optopt = pfound->val; + return '?'; + } + } + else if (pfound->has_arg == 1) + { + if (optind < argc) + optarg = argv[optind++]; + else + { + if (opterr) + fprintf (stderr, + _("%s: option `%s' requires an argument\n"), + argv[0], argv[optind - 1]); + nextchar += strlen (nextchar); + optopt = pfound->val; + return optstring[0] == ':' ? ':' : '?'; + } + } + nextchar += strlen (nextchar); + if (longind != NULL) + *longind = option_index; + if (pfound->flag) + { + *(pfound->flag) = pfound->val; + return 0; + } + return pfound->val; + } + + /* Can't find it as a long option. If this is not getopt_long_only, + or the option starts with '--' or is not a valid short + option, then it's an error. + Otherwise interpret it as a short option. */ + if (!long_only || argv[optind][1] == '-' + || my_index (optstring, *nextchar) == NULL) + { + if (opterr) + { + if (argv[optind][1] == '-') + /* --option */ + fprintf (stderr, _("%s: unrecognized option `--%s'\n"), + argv[0], nextchar); + else + /* +option or -option */ + fprintf (stderr, _("%s: unrecognized option `%c%s'\n"), + argv[0], argv[optind][0], nextchar); + } + nextchar = (char *) ""; + optind++; + optopt = 0; + return '?'; + } + } + + /* Look at and handle the next short option-character. */ + + { + char c = *nextchar++; + char *temp = my_index (optstring, c); + + /* Increment `optind' when we start to process its last character. */ + if (*nextchar == '\0') + ++optind; + + if (temp == NULL || c == ':') + { + if (opterr) + { + if (posixly_correct) + /* 1003.2 specifies the format of this message. */ + fprintf (stderr, _("%s: illegal option -- %c\n"), + argv[0], c); + else + fprintf (stderr, _("%s: invalid option -- %c\n"), + argv[0], c); + } + optopt = c; + return '?'; + } + /* Convenience. Treat POSIX -W foo same as long option --foo */ + if (temp[0] == 'W' && temp[1] == ';') + { + char *nameend; + const struct option *p; + const struct option *pfound = NULL; + int exact = 0; + int ambig = 0; + int indfound = 0; + int option_index; + + /* This is an option that requires an argument. */ + if (*nextchar != '\0') + { + optarg = nextchar; + /* If we end this ARGV-element by taking the rest as an arg, + we must advance to the next element now. */ + optind++; + } + else if (optind == argc) + { + if (opterr) + { + /* 1003.2 specifies the format of this message. */ + fprintf (stderr, _("%s: option requires an argument -- %c\n"), + argv[0], c); + } + optopt = c; + if (optstring[0] == ':') + c = ':'; + else + c = '?'; + return c; + } + else + /* We already incremented `optind' once; + increment it again when taking next ARGV-elt as argument. */ + optarg = argv[optind++]; + + /* optarg is now the argument, see if it's in the + table of longopts. */ + + for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++) + /* Do nothing. */ ; + + /* Test all long options for either exact match + or abbreviated matches. */ + for (p = longopts, option_index = 0; p->name; p++, option_index++) + if (!strncmp (p->name, nextchar, nameend - nextchar)) + { + if ((unsigned int) (nameend - nextchar) == strlen (p->name)) + { + /* Exact match found. */ + pfound = p; + indfound = option_index; + exact = 1; + break; + } + else if (pfound == NULL) + { + /* First nonexact match found. */ + pfound = p; + indfound = option_index; + } + else + /* Second or later nonexact match found. */ + ambig = 1; + } + if (ambig && !exact) + { + if (opterr) + fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"), + argv[0], argv[optind]); + nextchar += strlen (nextchar); + optind++; + return '?'; + } + if (pfound != NULL) + { + option_index = indfound; + if (*nameend) + { + /* Don't test has_arg with >, because some C compilers don't + allow it to be used on enums. */ + if (pfound->has_arg) + optarg = nameend + 1; + else + { + if (opterr) + fprintf (stderr, _("\ +%s: option `-W %s' doesn't allow an argument\n"), + argv[0], pfound->name); + + nextchar += strlen (nextchar); + return '?'; + } + } + else if (pfound->has_arg == 1) + { + if (optind < argc) + optarg = argv[optind++]; + else + { + if (opterr) + fprintf (stderr, + _("%s: option `%s' requires an argument\n"), + argv[0], argv[optind - 1]); + nextchar += strlen (nextchar); + return optstring[0] == ':' ? ':' : '?'; + } + } + nextchar += strlen (nextchar); + if (longind != NULL) + *longind = option_index; + if (pfound->flag) + { + *(pfound->flag) = pfound->val; + return 0; + } + return pfound->val; + } + nextchar = NULL; + return 'W'; /* Let the application handle it. */ + } + if (temp[1] == ':') + { + if (temp[2] == ':') + { + /* This is an option that accepts an argument optionally. */ + if (*nextchar != '\0') + { + optarg = nextchar; + optind++; + } + else + optarg = NULL; + nextchar = NULL; + } + else + { + /* This is an option that requires an argument. */ + if (*nextchar != '\0') + { + optarg = nextchar; + /* If we end this ARGV-element by taking the rest as an arg, + we must advance to the next element now. */ + optind++; + } + else if (optind == argc) + { + if (opterr) + { + /* 1003.2 specifies the format of this message. */ + fprintf (stderr, + _("%s: option requires an argument -- %c\n"), + argv[0], c); + } + optopt = c; + if (optstring[0] == ':') + c = ':'; + else + c = '?'; + } + else + /* We already incremented `optind' once; + increment it again when taking next ARGV-elt as argument. */ + optarg = argv[optind++]; + nextchar = NULL; + } + } + return c; + } +} + +int +getopt (argc, argv, optstring) + int argc; + char *const *argv; + const char *optstring; +{ + return _getopt_internal (argc, argv, optstring, + (const struct option *) 0, + (int *) 0, + 0); +} + +#endif /* Not ELIDE_CODE. */ + +#ifdef TEST + +/* Compile with -DTEST to make an executable for use in testing + the above definition of `getopt'. */ + +int +main (argc, argv) + int argc; + char **argv; +{ + int c; + int digit_optind = 0; + + while (1) + { + int this_option_optind = optind ? optind : 1; + + c = getopt (argc, argv, "abc:d:0123456789"); + if (c == -1) + break; + + switch (c) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + if (digit_optind != 0 && digit_optind != this_option_optind) + printf ("digits occur in two different argv-elements.\n"); + digit_optind = this_option_optind; + printf ("option %c\n", c); + break; + + case 'a': + printf ("option a\n"); + break; + + case 'b': + printf ("option b\n"); + break; + + case 'c': + printf ("option c with value `%s'\n", optarg); + break; + + case '?': + break; + + default: + printf ("?? getopt returned character code 0%o ??\n", c); + } + } + + if (optind < argc) + { + printf ("non-option ARGV-elements: "); + while (optind < argc) + printf ("%s ", argv[optind++]); + printf ("\n"); + } + + exit (0); +} + +#endif /* TEST */ diff --git a/mozilla/zap/zmk/speex-1.1.10/src/getopt1.c b/mozilla/zap/zmk/speex-1.1.10/src/getopt1.c new file mode 100755 index 00000000000..39f8383e94c --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/src/getopt1.c @@ -0,0 +1,188 @@ +/* getopt_long and getopt_long_only entry points for GNU getopt. + Copyright (C) 1987,88,89,90,91,92,93,94,96,97,98 + Free Software Foundation, Inc. + This file is part of the GNU C Library. + + The GNU C Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public License as + published by the Free Software Foundation; either version 2 of the + License, or (at your option) any later version. + + The GNU C Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public + License along with the GNU C Library; see the file COPYING.LIB. If not, + write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, + Boston, MA 02111-1307, USA. */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "getopt_win.h" + +#if !defined __STDC__ || !__STDC__ +/* This is a separate conditional since some stdc systems + reject `defined (const)'. */ +#ifndef const +#define const +#endif +#endif + +#include + +/* Comment out all this code if we are using the GNU C Library, and are not + actually compiling the library itself. This code is part of the GNU C + Library, but also included in many other GNU distributions. Compiling + and linking in this code is a waste when using the GNU C library + (especially if it is a shared library). Rather than having every GNU + program understand `configure --with-gnu-libc' and omit the object files, + it is simpler to just do this in the source for each such file. */ + +#define GETOPT_INTERFACE_VERSION 2 +#if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2 +#include +#if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION +#define ELIDE_CODE +#endif +#endif + +#ifndef ELIDE_CODE + + +/* This needs to come after some library #include + to get __GNU_LIBRARY__ defined. */ +#ifdef __GNU_LIBRARY__ +#include +#endif + +#ifndef NULL +#define NULL 0 +#endif + +int +getopt_long (argc, argv, options, long_options, opt_index) + int argc; + char *const *argv; + const char *options; + const struct option *long_options; + int *opt_index; +{ + return _getopt_internal (argc, argv, options, long_options, opt_index, 0); +} + +/* Like getopt_long, but '-' as well as '--' can indicate a long option. + If an option that starts with '-' (not '--') doesn't match a long option, + but does match a short option, it is parsed as a short option + instead. */ + +int +getopt_long_only (argc, argv, options, long_options, opt_index) + int argc; + char *const *argv; + const char *options; + const struct option *long_options; + int *opt_index; +{ + return _getopt_internal (argc, argv, options, long_options, opt_index, 1); +} + + +#endif /* Not ELIDE_CODE. */ + +#ifdef TEST + +#include + +int +main (argc, argv) + int argc; + char **argv; +{ + int c; + int digit_optind = 0; + + while (1) + { + int this_option_optind = optind ? optind : 1; + int option_index = 0; + static struct option long_options[] = + { + {"add", 1, 0, 0}, + {"append", 0, 0, 0}, + {"delete", 1, 0, 0}, + {"verbose", 0, 0, 0}, + {"create", 0, 0, 0}, + {"file", 1, 0, 0}, + {0, 0, 0, 0} + }; + + c = getopt_long (argc, argv, "abc:d:0123456789", + long_options, &option_index); + if (c == -1) + break; + + switch (c) + { + case 0: + printf ("option %s", long_options[option_index].name); + if (optarg) + printf (" with arg %s", optarg); + printf ("\n"); + break; + + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + if (digit_optind != 0 && digit_optind != this_option_optind) + printf ("digits occur in two different argv-elements.\n"); + digit_optind = this_option_optind; + printf ("option %c\n", c); + break; + + case 'a': + printf ("option a\n"); + break; + + case 'b': + printf ("option b\n"); + break; + + case 'c': + printf ("option c with value `%s'\n", optarg); + break; + + case 'd': + printf ("option d with value `%s'\n", optarg); + break; + + case '?': + break; + + default: + printf ("?? getopt returned character code 0%o ??\n", c); + } + } + + if (optind < argc) + { + printf ("non-option ARGV-elements: "); + while (optind < argc) + printf ("%s ", argv[optind++]); + printf ("\n"); + } + + exit (0); +} + +#endif /* TEST */ diff --git a/mozilla/zap/zmk/speex-1.1.10/src/getopt_win.h b/mozilla/zap/zmk/speex-1.1.10/src/getopt_win.h new file mode 100755 index 00000000000..91eb54e5570 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/src/getopt_win.h @@ -0,0 +1,169 @@ +/* Declarations for getopt. + Copyright (C) 1989,90,91,92,93,94,96,97,98 Free Software Foundation, Inc. + This file is part of the GNU C Library. + + The GNU C Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public License as + published by the Free Software Foundation; either version 2 of the + License, or (at your option) any later version. + + The GNU C Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public + License along with the GNU C Library; see the file COPYING.LIB. If not, + write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, + Boston, MA 02111-1307, USA. */ + +#ifndef _GETOPT_H + +#ifndef __need_getopt +# define _GETOPT_H 1 +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* For communication from `getopt' to the caller. + When `getopt' finds an option that takes an argument, + the argument value is returned here. + Also, when `ordering' is RETURN_IN_ORDER, + each non-option ARGV-element is returned here. */ + +extern char *optarg; + +/* Index in ARGV of the next element to be scanned. + This is used for communication to and from the caller + and for communication between successive calls to `getopt'. + + On entry to `getopt', zero means this is the first call; initialize. + + When `getopt' returns -1, this is the index of the first of the + non-option elements that the caller should itself scan. + + Otherwise, `optind' communicates from one call to the next + how much of ARGV has been scanned so far. */ + +extern int optind; + +/* Callers store zero here to inhibit the error message `getopt' prints + for unrecognized options. */ + +extern int opterr; + +/* Set to an option character which was unrecognized. */ + +extern int optopt; + +#ifndef __need_getopt +/* Describe the long-named options requested by the application. + The LONG_OPTIONS argument to getopt_long or getopt_long_only is a vector + of `struct option' terminated by an element containing a name which is + zero. + + The field `has_arg' is: + no_argument (or 0) if the option does not take an argument, + required_argument (or 1) if the option requires an argument, + optional_argument (or 2) if the option takes an optional argument. + + If the field `flag' is not NULL, it points to a variable that is set + to the value given in the field `val' when the option is found, but + left unchanged if the option is not found. + + To have a long-named option do something other than set an `int' to + a compiled-in constant, such as set a value from `optarg', set the + option's `flag' field to zero and its `val' field to a nonzero + value (the equivalent single-letter option character, if there is + one). For long options that have a zero `flag' field, `getopt' + returns the contents of the `val' field. */ + +struct option +{ +# if defined __STDC__ && __STDC__ + const char *name; +# else + char *name; +# endif + /* has_arg can't be an enum because some compilers complain about + type mismatches in all the code that assumes it is an int. */ + int has_arg; + int *flag; + int val; +}; + +/* Names for the values of the `has_arg' field of `struct option'. */ + +# define no_argument 0 +# define required_argument 1 +# define optional_argument 2 +#endif /* need getopt */ + + +/* Get definitions and prototypes for functions to process the + arguments in ARGV (ARGC of them, minus the program name) for + options given in OPTS. + + Return the option character from OPTS just read. Return -1 when + there are no more options. For unrecognized options, or options + missing arguments, `optopt' is set to the option letter, and '?' is + returned. + + The OPTS string is a list of characters which are recognized option + letters, optionally followed by colons, specifying that that letter + takes an argument, to be placed in `optarg'. + + If a letter in OPTS is followed by two colons, its argument is + optional. This behavior is specific to the GNU `getopt'. + + The argument `--' causes premature termination of argument + scanning, explicitly telling `getopt' that there are no more + options. + + If OPTS begins with `--', then non-option arguments are treated as + arguments to the option '\0'. This behavior is specific to the GNU + `getopt'. */ + +#if defined __STDC__ && __STDC__ +# ifdef __GNU_LIBRARY__ +/* Many other libraries have conflicting prototypes for getopt, with + differences in the consts, in stdlib.h. To avoid compilation + errors, only prototype getopt for the GNU C library. */ +extern int getopt (int __argc, char *const *__argv, const char *__shortopts); +# else /* not __GNU_LIBRARY__ */ +extern int getopt (); +# endif /* __GNU_LIBRARY__ */ + +# ifndef __need_getopt +extern int getopt_long (int __argc, char *const *__argv, const char *__shortopts, + const struct option *__longopts, int *__longind); +extern int getopt_long_only (int __argc, char *const *__argv, + const char *__shortopts, + const struct option *__longopts, int *__longind); + +/* Internal only. Users should not call this directly. */ +extern int _getopt_internal (int __argc, char *const *__argv, + const char *__shortopts, + const struct option *__longopts, int *__longind, + int __long_only); +# endif +#else /* not __STDC__ */ +extern int getopt (); +# ifndef __need_getopt +extern int getopt_long (); +extern int getopt_long_only (); + +extern int _getopt_internal (); +# endif +#endif /* __STDC__ */ + +#ifdef __cplusplus +} +#endif + +/* Make sure we later can get all the definitions and declarations. */ +#undef __need_getopt + +#endif /* getopt.h */ diff --git a/mozilla/zap/zmk/speex-1.1.10/src/speexdec.1 b/mozilla/zap/zmk/speex-1.1.10/src/speexdec.1 new file mode 100755 index 00000000000..b3f85b05f8f --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/src/speexdec.1 @@ -0,0 +1,78 @@ +.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.29. +.TH SPEEXDEC "1" "September 2003" "speexdec version 1.1" "User Commands" +.SH NAME +speexdec \- manual page for speexdec version 1.1 +.SH SYNOPSIS +.B speexdec +[\fIoptions\fR] \fIinput_file.spx \fR[\fIoutput_file\fR] +.SH DESCRIPTION +Decodes a Speex file and produce a WAV file or raw file +.SS "input_file can be:" +.TP +filename.spx +regular Speex file +.TP +- +stdin +.SS "output_file can be:" +.TP +filename.wav +Wav file +.TP +filename.* +Raw PCM file (any extension other that .wav) +.TP +- +stdout +.TP +(nothing) +Will be played to soundcard +.SH OPTIONS +.TP +\fB\-\-enh\fR +Enable perceptual enhancement (default) +.TP +\fB\-\-no\-enh\fR +Disable perceptual enhancement +.TP +\fB\-\-force\-nb\fR +Force decoding in narrowband +.TP +\fB\-\-force\-wb\fR +Force decoding in wideband +.TP +\fB\-\-force\-uwb\fR +Force decoding in ultra-wideband +.TP +\fB\-\-mono\fR +Force decoding in mono +.TP +\fB\-\-stereo\fR +Force decoding in stereo +.TP +\fB\-\-rate\fR n +Force decoding at sampling rate n Hz +.TP +\fB\-\-packet\-loss\fR n +Simulate n % random packet loss +.TP +\fB\-V\fR +Verbose mode (show bit-rate) +.TP +\fB\-h\fR, \fB\-\-help\fR +This help +.TP +\fB\-v\fR, \fB\-\-version\fR +Version information +.TP +\fB\-\-pf\fR +Deprecated, use \fB\-\-enh\fR instead +.TP +\fB\-\-no\-pf\fR +Deprecated, use \fB\-\-no\-enh\fR instead +.PP +More information is available from the Speex site: http://www.speex.org +.PP +Please report bugs to the mailing list `speex-dev@xiph.org'. +.SH COPYRIGHT +Copyright \(co 2002 Jean-Marc Valin diff --git a/mozilla/zap/zmk/speex-1.1.10/src/speexdec.c b/mozilla/zap/zmk/speex-1.1.10/src/speexdec.c new file mode 100755 index 00000000000..a20c39e2981 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/src/speexdec.c @@ -0,0 +1,773 @@ +/* Copyright (C) 2002-2003 Jean-Marc Valin + File: speexdec.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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 +#if !defined WIN32 && !defined _WIN32 +#include +#include +#endif +#ifndef HAVE_GETOPT_LONG +#include "getopt_win.h" +#endif +#include +#include + +#include +#include + +#if defined WIN32 || defined _WIN32 +#include +#include "getopt_win.h" +#include "wave_out.h" +/* We need the following two to set stdout to binary */ +#include +#include +#endif +#include + +#ifdef __MINGW32__ +#include "wave_out.c" +#endif + +#ifdef HAVE_SYS_SOUNDCARD_H +#include +#include +#include +#include +#include + +#elif defined HAVE_SYS_AUDIOIO_H +#include +#include +#include +#include +#ifndef AUDIO_ENCODING_SLINEAR +#define AUDIO_ENCODING_SLINEAR AUDIO_ENCODING_LINEAR /* Solaris */ +#endif + +#endif + +#include +#include "wav_io.h" +#include +#include +#include +#include "wav_io.h" + +#define MAX_FRAME_SIZE 2000 + +#define readint(buf, base) (((buf[base+3]<<24)&0xff000000)| \ + ((buf[base+2]<<16)&0xff0000)| \ + ((buf[base+1]<<8)&0xff00)| \ + (buf[base]&0xff)) + +static void print_comments(char *comments, int length) +{ + char *c=comments; + int len, i, nb_fields; + char *end; + + if (length<8) + { + fprintf (stderr, "Invalid/corrupted comments\n"); + return; + } + end = c+length; + len=readint(c, 0); + c+=4; + if (c+len>end) + { + fprintf (stderr, "Invalid/corrupted comments\n"); + return; + } + fwrite(c, 1, len, stderr); + c+=len; + fprintf (stderr, "\n"); + if (c+4>end) + { + fprintf (stderr, "Invalid/corrupted comments\n"); + return; + } + nb_fields=readint(c, 0); + c+=4; + for (i=0;iend) + { + fprintf (stderr, "Invalid/corrupted comments\n"); + return; + } + len=readint(c, 0); + c+=4; + if (c+len>end) + { + fprintf (stderr, "Invalid/corrupted comments\n"); + return; + } + fwrite(c, 1, len, stderr); + c+=len; + fprintf (stderr, "\n"); + } +} + +FILE *out_file_open(char *outFile, int rate, int *channels) +{ + FILE *fout=NULL; + /*Open output file*/ + if (strlen(outFile)==0) + { +#if defined HAVE_SYS_SOUNDCARD_H + int audio_fd, format, stereo; + audio_fd=open("/dev/dsp", O_WRONLY); + if (audio_fd<0) + { + perror("Cannot open /dev/dsp"); + exit(1); + } + + format=AFMT_S16_NE; + if (ioctl(audio_fd, SNDCTL_DSP_SETFMT, &format)==-1) + { + perror("SNDCTL_DSP_SETFMT"); + close(audio_fd); + exit(1); + } + + stereo=0; + if (*channels==2) + stereo=1; + if (ioctl(audio_fd, SNDCTL_DSP_STEREO, &stereo)==-1) + { + perror("SNDCTL_DSP_STEREO"); + close(audio_fd); + exit(1); + } + if (stereo!=0) + { + if (*channels==1) + fprintf (stderr, "Cannot set mono mode, will decode in stereo\n"); + *channels=2; + } + + if (ioctl(audio_fd, SNDCTL_DSP_SPEED, &rate)==-1) + { + perror("SNDCTL_DSP_SPEED"); + close(audio_fd); + exit(1); + } + fout = fdopen(audio_fd, "w"); +#elif defined HAVE_SYS_AUDIOIO_H + audio_info_t info; + int audio_fd; + + audio_fd = open("/dev/audio", O_WRONLY); + if (audio_fd<0) + { + perror("Cannot open /dev/audio"); + exit(1); + } + + AUDIO_INITINFO(&info); +#ifdef AUMODE_PLAY /* NetBSD/OpenBSD */ + info.mode = AUMODE_PLAY; +#endif + info.play.encoding = AUDIO_ENCODING_SLINEAR; + info.play.precision = 16; + info.play.sample_rate = rate; + info.play.channels = *channels; + + if (ioctl(audio_fd, AUDIO_SETINFO, &info) < 0) + { + perror ("AUDIO_SETINFO"); + exit(1); + } + fout = fdopen(audio_fd, "w"); +#elif defined WIN32 || defined _WIN32 + { + unsigned int speex_channels = *channels; + if (Set_WIN_Params (INVALID_FILEDESC, rate, SAMPLE_SIZE, speex_channels)) + { + fprintf (stderr, "Can't access %s\n", "WAVE OUT"); + exit(1); + } + } +#else + fprintf (stderr, "No soundcard support\n"); + exit(1); +#endif + } else { + if (strcmp(outFile,"-")==0) + { +#if defined WIN32 || defined _WIN32 + _setmode(_fileno(stdout), _O_BINARY); +#endif + fout=stdout; + } + else + { + fout = fopen(outFile, "wb"); + if (!fout) + { + perror(outFile); + exit(1); + } + if (strcmp(outFile+strlen(outFile)-4,".wav")==0 || strcmp(outFile+strlen(outFile)-4,".WAV")==0) + write_wav_header(fout, rate, *channels, 0, 0); + } + } + return fout; +} + +void usage() +{ + printf ("Usage: speexdec [options] input_file.spx [output_file]\n"); + printf ("\n"); + printf ("Decodes a Speex file and produce a WAV file or raw file\n"); + printf ("\n"); + printf ("input_file can be:\n"); + printf (" filename.spx regular Speex file\n"); + printf (" - stdin\n"); + printf ("\n"); + printf ("output_file can be:\n"); + printf (" filename.wav Wav file\n"); + printf (" filename.* Raw PCM file (any extension other that .wav)\n"); + printf (" - stdout\n"); + printf (" (nothing) Will be played to soundcard\n"); + printf ("\n"); + printf ("Options:\n"); + printf (" --enh Enable perceptual enhancement (default)\n"); + printf (" --no-enh Disable perceptual enhancement\n"); + printf (" --force-nb Force decoding in narrowband\n"); + printf (" --force-wb Force decoding in wideband\n"); + printf (" --force-uwb Force decoding in ultra-wideband\n"); + printf (" --mono Force decoding in mono\n"); + printf (" --stereo Force decoding in stereo\n"); + printf (" --rate n Force decoding at sampling rate n Hz\n"); + printf (" --packet-loss n Simulate n %% random packet loss\n"); + printf (" -V Verbose mode (show bit-rate)\n"); + printf (" -h, --help This help\n"); + printf (" -v, --version Version information\n"); + printf (" --pf Deprecated, use --enh instead\n"); + printf (" --no-pf Deprecated, use --no-enh instead\n"); + printf ("\n"); + printf ("More information is available from the Speex site: http://www.speex.org\n"); + printf ("\n"); + printf ("Please report bugs to the mailing list `speex-dev@xiph.org'.\n"); +} + +void version() +{ + printf ("speexdec (Speex decoder) version " SPEEX_VERSION " (compiled " __DATE__ ")\n"); + printf ("Copyright (C) 2002-2003 Jean-Marc Valin\n"); +} + +void version_short() +{ + printf ("speexdec version " SPEEX_VERSION "\n"); + printf ("Copyright (C) 2002-2003 Jean-Marc Valin\n"); +} + +static void *process_header(ogg_packet *op, int enh_enabled, int *frame_size, int *rate, int *nframes, int forceMode, int *channels, SpeexStereoState *stereo, int *extra_headers, int quiet) +{ + void *st; + const SpeexMode *mode; + SpeexHeader *header; + int modeID; + SpeexCallback callback; + + header = speex_packet_to_header((char*)op->packet, op->bytes); + if (!header) + { + fprintf (stderr, "Cannot read header\n"); + return NULL; + } + if (header->mode >= SPEEX_NB_MODES) + { + fprintf (stderr, "Mode number %d does not (yet/any longer) exist in this version\n", + header->mode); + return NULL; + } + + modeID = header->mode; + if (forceMode!=-1) + modeID = forceMode; + + mode = speex_lib_get_mode (modeID); + + if (header->speex_version_id > 1) + { + fprintf (stderr, "This file was encoded with Speex bit-stream version %d, which I don't know how to decode\n", header->speex_version_id); + return NULL; + } + + if (mode->bitstream_version < header->mode_bitstream_version) + { + fprintf (stderr, "The file was encoded with a newer version of Speex. You need to upgrade in order to play it.\n"); + return NULL; + } + if (mode->bitstream_version > header->mode_bitstream_version) + { + fprintf (stderr, "The file was encoded with an older version of Speex. You would need to downgrade the version in order to play it.\n"); + return NULL; + } + + st = speex_decoder_init(mode); + if (!st) + { + fprintf (stderr, "Decoder initialization failed.\n"); + return NULL; + } + speex_decoder_ctl(st, SPEEX_SET_ENH, &enh_enabled); + speex_decoder_ctl(st, SPEEX_GET_FRAME_SIZE, frame_size); + + if (!(*channels==1)) + { + callback.callback_id = SPEEX_INBAND_STEREO; + callback.func = speex_std_stereo_request_handler; + callback.data = stereo; + speex_decoder_ctl(st, SPEEX_SET_HANDLER, &callback); + } + if (!*rate) + *rate = header->rate; + /* Adjust rate if --force-* options are used */ + if (forceMode!=-1) + { + if (header->mode < forceMode) + *rate <<= (forceMode - header->mode); + if (header->mode > forceMode) + *rate >>= (header->mode - forceMode); + } + + speex_decoder_ctl(st, SPEEX_SET_SAMPLING_RATE, rate); + + *nframes = header->frames_per_packet; + + if (*channels==-1) + *channels = header->nb_channels; + + if (!quiet) + { + fprintf (stderr, "Decoding %d Hz audio using %s mode", + *rate, mode->modeName); + + if (*channels==1) + fprintf (stderr, " (mono"); + else + fprintf (stderr, " (stereo"); + + if (header->vbr) + fprintf (stderr, ", VBR)\n"); + else + fprintf(stderr, ")\n"); + /*fprintf (stderr, "Decoding %d Hz audio at %d bps using %s mode\n", + *rate, mode->bitrate, mode->modeName);*/ + } + + *extra_headers = header->extra_headers; + + free(header); + return st; +} + +int main(int argc, char **argv) +{ + int c; + int option_index = 0; + char *inFile, *outFile; + FILE *fin, *fout=NULL; + short out[MAX_FRAME_SIZE]; + short output[MAX_FRAME_SIZE]; + int frame_size=0; + void *st=NULL; + SpeexBits bits; + int packet_count=0; + int stream_init = 0; + int quiet = 0; + ogg_int64_t page_granule=0, last_granule=0; + int skip_samples=0, page_nb_packets; + struct option long_options[] = + { + {"help", no_argument, NULL, 0}, + {"quiet", no_argument, NULL, 0}, + {"version", no_argument, NULL, 0}, + {"version-short", no_argument, NULL, 0}, + {"enh", no_argument, NULL, 0}, + {"no-enh", no_argument, NULL, 0}, + {"pf", no_argument, NULL, 0}, + {"no-pf", no_argument, NULL, 0}, + {"force-nb", no_argument, NULL, 0}, + {"force-wb", no_argument, NULL, 0}, + {"force-uwb", no_argument, NULL, 0}, + {"rate", required_argument, NULL, 0}, + {"mono", no_argument, NULL, 0}, + {"stereo", no_argument, NULL, 0}, + {"packet-loss", required_argument, NULL, 0}, + {0, 0, 0, 0} + }; + ogg_sync_state oy; + ogg_page og; + ogg_packet op; + ogg_stream_state os; + int enh_enabled; + int nframes=2; + int print_bitrate=0; + int close_in=0; + int eos=0; + int forceMode=-1; + int audio_size=0; + float loss_percent=-1; + SpeexStereoState stereo = SPEEX_STEREO_STATE_INIT; + int channels=-1; + int rate=0; + int extra_headers; + int wav_format=0; + + enh_enabled = 1; + + /*Process options*/ + while(1) + { + c = getopt_long (argc, argv, "hvV", + long_options, &option_index); + if (c==-1) + break; + + switch(c) + { + case 0: + if (strcmp(long_options[option_index].name,"help")==0) + { + usage(); + exit(0); + } else if (strcmp(long_options[option_index].name,"quiet")==0) + { + quiet = 1; + } else if (strcmp(long_options[option_index].name,"version")==0) + { + version(); + exit(0); + } else if (strcmp(long_options[option_index].name,"version-short")==0) + { + version_short(); + exit(0); + } else if (strcmp(long_options[option_index].name,"enh")==0) + { + enh_enabled=1; + } else if (strcmp(long_options[option_index].name,"no-enh")==0) + { + enh_enabled=0; + } else if (strcmp(long_options[option_index].name,"pf")==0) + { + fprintf (stderr, "--pf is deprecated, use --enh instead\n"); + enh_enabled=1; + } else if (strcmp(long_options[option_index].name,"no-pf")==0) + { + fprintf (stderr, "--no-pf is deprecated, use --no-enh instead\n"); + enh_enabled=0; + } else if (strcmp(long_options[option_index].name,"force-nb")==0) + { + forceMode=0; + } else if (strcmp(long_options[option_index].name,"force-wb")==0) + { + forceMode=1; + } else if (strcmp(long_options[option_index].name,"force-uwb")==0) + { + forceMode=2; + } else if (strcmp(long_options[option_index].name,"mono")==0) + { + channels=1; + } else if (strcmp(long_options[option_index].name,"stereo")==0) + { + channels=2; + } else if (strcmp(long_options[option_index].name,"rate")==0) + { + rate=atoi (optarg); + } else if (strcmp(long_options[option_index].name,"packet-loss")==0) + { + loss_percent = atof(optarg); + } + break; + case 'h': + usage(); + exit(0); + break; + case 'v': + version(); + exit(0); + break; + case 'V': + print_bitrate=1; + break; + case '?': + usage(); + exit(1); + break; + } + } + if (argc-optind!=2 && argc-optind!=1) + { + usage(); + exit(1); + } + inFile=argv[optind]; + + if (argc-optind==2) + outFile=argv[optind+1]; + else + outFile = ""; + wav_format = strlen(outFile)>=4 && ( + strcmp(outFile+strlen(outFile)-4,".wav")==0 + || strcmp(outFile+strlen(outFile)-4,".WAV")==0); + /*Open input file*/ + if (strcmp(inFile, "-")==0) + { +#if defined WIN32 || defined _WIN32 + _setmode(_fileno(stdin), _O_BINARY); +#endif + fin=stdin; + } + else + { + fin = fopen(inFile, "rb"); + if (!fin) + { + perror(inFile); + exit(1); + } + close_in=1; + } + + + /*Init Ogg data struct*/ + ogg_sync_init(&oy); + + speex_bits_init(&bits); + /*Main decoding loop*/ + while (1) + { + char *data; + int i, j, nb_read; + /*Get the ogg buffer for writing*/ + data = ogg_sync_buffer(&oy, 200); + /*Read bitstream from input file*/ + nb_read = fread(data, sizeof(char), 200, fin); + ogg_sync_wrote(&oy, nb_read); + + /*Loop for all complete pages we got (most likely only one)*/ + while (ogg_sync_pageout(&oy, &og)==1) + { + int packet_no; + if (stream_init == 0) { + ogg_stream_init(&os, ogg_page_serialno(&og)); + stream_init = 1; + } + /*Add page to the bitstream*/ + ogg_stream_pagein(&os, &og); + page_granule = ogg_page_granulepos(&og); + page_nb_packets = ogg_page_packets(&og); + if (page_granule>0 && frame_size) + { + skip_samples = page_nb_packets*frame_size*nframes - (page_granule-last_granule); + if (ogg_page_eos(&og)) + skip_samples = -skip_samples; + /*else if (!ogg_page_bos(&og)) + skip_samples = 0;*/ + } else + { + skip_samples = 0; + } + /*printf ("page granulepos: %d %d %d\n", skip_samples, page_nb_packets, (int)page_granule);*/ + last_granule = page_granule; + /*Extract all available packets*/ + packet_no=0; + while (!eos && ogg_stream_packetout(&os, &op)==1) + { + /*If first packet, process as Speex header*/ + if (packet_count==0) + { + st = process_header(&op, enh_enabled, &frame_size, &rate, &nframes, forceMode, &channels, &stereo, &extra_headers, quiet); + if (!nframes) + nframes=1; + if (!st) + exit(1); + fout = out_file_open(outFile, rate, &channels); + + } else if (packet_count==1) + { + if (!quiet) + print_comments((char*)op.packet, op.bytes); + } else if (packet_count<=1+extra_headers) + { + /* Ignore extra headers */ + } else { + int lost=0; + packet_no++; + if (loss_percent>0 && 100*((float)rand())/RAND_MAX 0) + { + /*printf ("chopping first packet\n");*/ + new_frame_size -= skip_samples; + frame_offset = skip_samples; + } + if (packet_no == page_nb_packets && skip_samples < 0) + { + int packet_length = nframes*frame_size+skip_samples; + new_frame_size = packet_length - j*frame_size; + if (new_frame_size<0) + new_frame_size = 0; + if (new_frame_size>frame_size) + new_frame_size = frame_size; + /*printf ("chopping end: %d %d %d\n", new_frame_size, packet_length, packet_no);*/ + } + if (new_frame_size) + { +#if defined WIN32 || defined _WIN32 + if (strlen(outFile)==0) + WIN_Play_Samples (out+frame_offset*channels, sizeof(short) * new_frame_size*channels); + else +#endif + fwrite(out+frame_offset*channels, sizeof(short), new_frame_size*channels, fout); + + audio_size+=sizeof(short)*new_frame_size*channels; + } + } + } + } + packet_count++; + } + } + if (feof(fin)) + break; + + } + + if (wav_format) + { + if (fseek(fout,4,SEEK_SET)==0) + { + int tmp; + tmp = le_int(audio_size+36); + fwrite(&tmp,4,1,fout); + if (fseek(fout,32,SEEK_CUR)==0) + { + tmp = le_int(audio_size); + fwrite(&tmp,4,1,fout); + } else + { + fprintf (stderr, "First seek worked, second didn't\n"); + } + } else { + fprintf (stderr, "Cannot seek on wave file, size will be incorrect\n"); + } + } + + if (st) + speex_decoder_destroy(st); + else + { + fprintf (stderr, "This doesn't look like a Speex file\n"); + } + speex_bits_destroy(&bits); + if (stream_init) + ogg_stream_clear(&os); + ogg_sync_clear(&oy); + +#if defined WIN32 || defined _WIN32 + if (strlen(outFile)==0) + WIN_Audio_close (); +#endif + + if (close_in) + fclose(fin); + if (fout != NULL) + fclose(fout); + + return 0; +} diff --git a/mozilla/zap/zmk/speex-1.1.10/src/speexenc.1 b/mozilla/zap/zmk/speex-1.1.10/src/speexenc.1 new file mode 100755 index 00000000000..779cdc72dd8 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/src/speexenc.1 @@ -0,0 +1,105 @@ +.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.29. +.TH SPEEXENC "1" "September 2003" "speexenc version 1.1" "User Commands" +.SH NAME +speexenc \- manual page for speexenc version 1.1 +.SH SYNOPSIS +.B speexenc +[\fIoptions\fR] \fIinput_file output_file\fR +.SH DESCRIPTION +Encodes input_file using Speex. It can read the WAV or raw files. +.SS "input_file can be:" +.TP +filename.wav +wav file +.TP +filename.* +Raw PCM file (any extension other than .wav) +.TP +- +stdin +.SS "output_file can be:" +.TP +filename.spx +Speex file +.TP +- +stdout +.SH OPTIONS +.TP +\fB\-n\fR, \fB\-\-narrowband\fR +Narrowband (8 kHz) input file +.TP +\fB\-w\fR, \fB\-\-wideband\fR +Wideband (16 kHz) input file +.HP +\fB\-u\fR, \fB\-\-ultra\-wideband\fR "Ultra-wideband" (32 kHz) input file +.TP +\fB\-\-quality\fR n +Encoding quality (0-10), default 3 +.TP +\fB\-\-bitrate\fR n +Encoding bit-rate (use bit-rate n or lower) +.TP +\fB\-\-vbr\fR +Enable variable bit-rate (VBR) +.TP +\fB\-\-abr\fR rate +Enable average bit-rate (ABR) at rate bps +.TP +\fB\-\-vad\fR +Enable voice activity detection (VAD) +.TP +\fB\-\-dtx\fR +Enable file-based discontinuous transmission (DTX) +.TP +\fB\-\-comp\fR n +Set encoding complexity (0-10), default 3 +.TP +\fB\-\-nframes\fR n +Number of frames per Ogg packet (1-10), default 1 +.TP +\fB\-\-comment\fR +Add the given string as an extra comment. This may be +used multiple times +.TP +\fB\-\-author\fR +Author of this track +.TP +\fB\-\-title\fR +Title for this track +.TP +\fB\-h\fR, \fB\-\-help\fR +This help +.TP +\fB\-v\fR, \fB\-\-version\fR +Version information +.TP +\fB\-V\fR +Verbose mode (show bit-rate) +.SS "Raw input options:" +.TP +\fB\-\-rate\fR n +Sampling rate for raw input +.TP +\fB\-\-stereo\fR +Consider raw input as stereo +.TP +\fB\-\-le\fR +Raw input is little-endian +.TP +\fB\-\-be\fR +Raw input is big-endian +.TP +\fB\-\-8bit\fR +Raw input is 8-bit unsigned +.TP +\fB\-\-16bit\fR +Raw input is 16-bit signed +.PP +Default raw PCM input is 16-bit, little-endian, mono +.PP +More information is available from the Speex site: http://www.speex.org +.PP +Please report bugs to the mailing list `speex-dev@xiph.org'. +.SH COPYRIGHT +Copyright \(co 2002 Jean-Marc Valin diff --git a/mozilla/zap/zmk/speex-1.1.10/src/speexenc.c b/mozilla/zap/zmk/speex-1.1.10/src/speexenc.c new file mode 100755 index 00000000000..8a962b617dc --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/src/speexenc.c @@ -0,0 +1,865 @@ +/* Copyright (C) 2002-2003 Jean-Marc Valin + File: speexenc.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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 +#if !defined WIN32 && !defined _WIN32 +#include +#include +#endif +#ifndef HAVE_GETOPT_LONG +#include "getopt_win.h" +#endif +#include +#include +#include + +#include +#include +#include "wav_io.h" +#include +#include +#include + +#if defined WIN32 || defined _WIN32 +#include "getopt_win.h" +/* We need the following two to set stdout to binary */ +#include +#include +#endif + + +void comment_init(char **comments, int* length, char *vendor_string); +void comment_add(char **comments, int* length, char *tag, char *val); + + +/*Write an Ogg page to a file pointer*/ +int oe_write_page(ogg_page *page, FILE *fp) +{ + int written; + written = fwrite(page->header,1,page->header_len, fp); + written += fwrite(page->body,1,page->body_len, fp); + + return written; +} + +#define MAX_FRAME_SIZE 2000 +#define MAX_FRAME_BYTES 2000 + +/* Convert input audio bits, endians and channels */ +static int read_samples(FILE *fin,int frame_size, int bits, int channels, int lsb, short * input, char *buff, int *size) +{ + unsigned char in[MAX_FRAME_BYTES*2]; + int i; + short *s; + int nb_read; + + if (size && *size<=0) + { + return 0; + } + /*Read input audio*/ + if (size) + *size -= bits/8*channels*frame_size; + if (buff) + { + for (i=0;i<12;i++) + in[i]=buff[i]; + nb_read = fread(in+12,1,bits/8*channels*frame_size-12, fin) + 12; + if (size) + *size += 12; + } else { + nb_read = fread(in,1,bits/8*channels* frame_size, fin); + } + nb_read /= bits/8*channels; + + /*fprintf (stderr, "%d\n", nb_read);*/ + if (nb_read==0) + return 0; + + s=(short*)in; + if(bits==8) + { + /* Convert 8->16 bits */ + for(i=frame_size*channels-1;i>=0;i--) + { + s[i]=(in[i]<<8)^0x8000; + } + } else + { + /* convert to our endian format */ + for(i=0;i10) + nframes=10; + } else if (strcmp(long_options[option_index].name,"comp")==0) + { + complexity = atoi (optarg); + } else if (strcmp(long_options[option_index].name,"denoise")==0) + { + denoise_enabled=1; + } else if (strcmp(long_options[option_index].name,"agc")==0) + { + agc_enabled=1; + } else if (strcmp(long_options[option_index].name,"help")==0) + { + usage(); + exit(0); + } else if (strcmp(long_options[option_index].name,"quiet")==0) + { + quiet = 1; + } else if (strcmp(long_options[option_index].name,"version")==0) + { + version(); + exit(0); + } else if (strcmp(long_options[option_index].name,"version-short")==0) + { + version_short(); + exit(0); + } else if (strcmp(long_options[option_index].name,"le")==0) + { + lsb=1; + } else if (strcmp(long_options[option_index].name,"be")==0) + { + lsb=0; + } else if (strcmp(long_options[option_index].name,"8bit")==0) + { + fmt=8; + } else if (strcmp(long_options[option_index].name,"16bit")==0) + { + fmt=16; + } else if (strcmp(long_options[option_index].name,"stereo")==0) + { + chan=2; + } else if (strcmp(long_options[option_index].name,"rate")==0) + { + rate=atoi (optarg); + } else if (strcmp(long_options[option_index].name,"comment")==0) + { + if (!strchr(optarg, '=')) + { + fprintf (stderr, "Invalid comment: %s\n", optarg); + fprintf (stderr, "Comments must be of the form name=value\n"); + exit(1); + } + comment_add(&comments, &comments_length, NULL, optarg); + } else if (strcmp(long_options[option_index].name,"author")==0) + { + comment_add(&comments, &comments_length, "author=", optarg); + } else if (strcmp(long_options[option_index].name,"title")==0) + { + comment_add(&comments, &comments_length, "title=", optarg); + } + + break; + case 'n': + modeID = SPEEX_MODEID_NB; + break; + case 'h': + usage(); + exit(0); + break; + case 'v': + version(); + exit(0); + break; + case 'V': + print_bitrate=1; + break; + case 'w': + modeID = SPEEX_MODEID_WB; + break; + case 'u': + modeID = SPEEX_MODEID_UWB; + break; + case '?': + usage(); + exit(1); + break; + } + } + if (argc-optind!=2) + { + usage(); + exit(1); + } + inFile=argv[optind]; + outFile=argv[optind+1]; + + /*Initialize Ogg stream struct*/ + srand(time(NULL)); + if (ogg_stream_init(&os, rand())==-1) + { + fprintf(stderr,"Error: stream init failed\n"); + exit(1); + } + + if (strcmp(inFile, "-")==0) + { +#if defined WIN32 || defined _WIN32 + _setmode(_fileno(stdin), _O_BINARY); +#endif + fin=stdin; + } + else + { + fin = fopen(inFile, "rb"); + if (!fin) + { + perror(inFile); + exit(1); + } + close_in=1; + } + + { + fread(first_bytes, 1, 12, fin); + if (strncmp(first_bytes,"RIFF",4)==0 && strncmp(first_bytes,"RIFF",4)==0) + { + if (read_wav_header(fin, &rate, &chan, &fmt, &size)==-1) + exit(1); + wave_input=1; + lsb=1; /* CHECK: exists big-endian .wav ?? */ + } + } + + if (modeID==-1 && !rate) + { + /* By default, use narrowband/8 kHz */ + modeID = SPEEX_MODEID_NB; + rate=8000; + } else if (modeID!=-1 && rate) + { + if (rate>48000) + { + fprintf (stderr, "Error: sampling rate too high: %d Hz, try down-sampling\n", rate); + exit(1); + } else if (rate>25000) + { + if (modeID != SPEEX_MODEID_UWB) + { + fprintf (stderr, "Warning: Trying to encode in %s at %d Hz. I'll do it but I suggest you try ultra-wideband instead\n", mode->modeName , rate); + } + } else if (rate>12500) + { + if (modeID != SPEEX_MODEID_WB) + { + fprintf (stderr, "Warning: Trying to encode in %s at %d Hz. I'll do it but I suggest you try wideband instead\n", mode->modeName , rate); + } + } else if (rate>=6000) + { + if (modeID != SPEEX_MODEID_NB) + { + fprintf (stderr, "Warning: Trying to encode in %s at %d Hz. I'll do it but I suggest you try narrowband instead\n", mode->modeName , rate); + } + } else { + fprintf (stderr, "Error: sampling rate too low: %d Hz\n", rate); + exit(1); + } + } else if (modeID==-1) + { + if (rate>48000) + { + fprintf (stderr, "Error: sampling rate too high: %d Hz, try down-sampling\n", rate); + exit(1); + } else if (rate>25000) + { + modeID = SPEEX_MODEID_UWB; + } else if (rate>12500) + { + modeID = SPEEX_MODEID_WB; + } else if (rate>=6000) + { + modeID = SPEEX_MODEID_NB; + } else { + fprintf (stderr, "Error: Sampling rate too low: %d Hz\n", rate); + exit(1); + } + } else if (!rate) + { + if (modeID == SPEEX_MODEID_NB) + rate=8000; + else if (modeID == SPEEX_MODEID_WB) + rate=16000; + else if (modeID == SPEEX_MODEID_UWB) + rate=32000; + } + + if (!quiet) + if (rate!=8000 && rate!=16000 && rate!=32000) + fprintf (stderr, "Warning: Speex is only optimized for 8, 16 and 32 kHz. It will still work at %d Hz but your mileage may vary\n", rate); + + mode = speex_lib_get_mode (modeID); + + speex_init_header(&header, rate, 1, mode); + header.frames_per_packet=nframes; + header.vbr=vbr_enabled; + header.nb_channels = chan; + + { + char *st_string="mono"; + if (chan==2) + st_string="stereo"; + if (!quiet) + fprintf (stderr, "Encoding %d Hz audio using %s mode (%s)\n", + header.rate, mode->modeName, st_string); + } + /*fprintf (stderr, "Encoding %d Hz audio at %d bps using %s mode\n", + header.rate, mode->bitrate, mode->modeName);*/ + + /*Initialize Speex encoder*/ + st = speex_encoder_init(mode); + + if (strcmp(outFile,"-")==0) + { +#if defined WIN32 || defined _WIN32 + _setmode(_fileno(stdout), _O_BINARY); +#endif + fout=stdout; + } + else + { + fout = fopen(outFile, "wb"); + if (!fout) + { + perror(outFile); + exit(1); + } + close_out=1; + } + + speex_encoder_ctl(st, SPEEX_GET_FRAME_SIZE, &frame_size); + speex_encoder_ctl(st, SPEEX_SET_COMPLEXITY, &complexity); + speex_encoder_ctl(st, SPEEX_SET_SAMPLING_RATE, &rate); + + if (quality >= 0) + { + if (vbr_enabled) + speex_encoder_ctl(st, SPEEX_SET_VBR_QUALITY, &vbr_quality); + else + speex_encoder_ctl(st, SPEEX_SET_QUALITY, &quality); + } + if (bitrate) + { + if (quality >= 0 && vbr_enabled) + fprintf (stderr, "Warning: --bitrate option is overriding --quality\n"); + speex_encoder_ctl(st, SPEEX_SET_BITRATE, &bitrate); + } + if (vbr_enabled) + { + tmp=1; + speex_encoder_ctl(st, SPEEX_SET_VBR, &tmp); + } else if (vad_enabled) + { + tmp=1; + speex_encoder_ctl(st, SPEEX_SET_VAD, &tmp); + } + if (dtx_enabled) + speex_encoder_ctl(st, SPEEX_SET_DTX, &tmp); + if (dtx_enabled && !(vbr_enabled || abr_enabled || vad_enabled)) + { + fprintf (stderr, "Warning: --dtx is useless without --vad, --vbr or --abr\n"); + } else if ((vbr_enabled || abr_enabled) && (vad_enabled)) + { + fprintf (stderr, "Warning: --vad is already implied by --vbr or --abr\n"); + } + + if (abr_enabled) + { + speex_encoder_ctl(st, SPEEX_SET_ABR, &abr_enabled); + } + + speex_encoder_ctl(st, SPEEX_GET_LOOKAHEAD, &lookahead); + + if (denoise_enabled || agc_enabled) + { + preprocess = speex_preprocess_state_init(frame_size, rate); + speex_preprocess_ctl(preprocess, SPEEX_PREPROCESS_SET_DENOISE, &denoise_enabled); + speex_preprocess_ctl(preprocess, SPEEX_PREPROCESS_SET_AGC, &agc_enabled); + lookahead += frame_size; + } + + /*Write header*/ + { + + op.packet = (unsigned char *)speex_header_to_packet(&header, (int*)&(op.bytes)); + op.b_o_s = 1; + op.e_o_s = 0; + op.granulepos = 0; + op.packetno = 0; + ogg_stream_packetin(&os, &op); + free(op.packet); + + op.packet = (unsigned char *)comments; + op.bytes = comments_length; + op.b_o_s = 0; + op.e_o_s = 0; + op.granulepos = 0; + op.packetno = 1; + ogg_stream_packetin(&os, &op); + + while((result = ogg_stream_flush(&os, &og))) + { + if(!result) break; + ret = oe_write_page(&og, fout); + if(ret != og.header_len + og.body_len) + { + fprintf (stderr,"Error: failed writing header to output stream\n"); + exit(1); + } + else + bytes_written += ret; + } + } + + free(comments); + + speex_bits_init(&bits); + + if (!wave_input) + { + nb_samples = read_samples(fin,frame_size,fmt,chan,lsb,input, first_bytes, NULL); + } else { + nb_samples = read_samples(fin,frame_size,fmt,chan,lsb,input, NULL, &size); + } + if (nb_samples==0) + eos=1; + total_samples += nb_samples; + nb_encoded = -lookahead; + /*Main encoding loop (one frame per iteration)*/ + while (!eos || total_samples>nb_encoded) + { + id++; + /*Encode current frame*/ + if (chan==2) + speex_encode_stereo_int(input, frame_size, &bits); + + if (preprocess) + speex_preprocess(preprocess, input, NULL); + + speex_encode_int(st, input, &bits); + + nb_encoded += frame_size; + if (print_bitrate) { + int tmp; + char ch=13; + speex_encoder_ctl(st, SPEEX_GET_BITRATE, &tmp); + fputc (ch, stderr); + cumul_bits += tmp; + enc_frames += 1; + if (!quiet) + { + if (vad_enabled || vbr_enabled || abr_enabled) + fprintf (stderr, "Bitrate is use: %d bps (average %d bps) ", tmp, (int)(cumul_bits/enc_frames)); + else + fprintf (stderr, "Bitrate is use: %d bps ", tmp); + } + + } + + if (wave_input) + { + nb_samples = read_samples(fin,frame_size,fmt,chan,lsb,input, NULL, &size); + } else { + nb_samples = read_samples(fin,frame_size,fmt,chan,lsb,input, NULL, NULL); + } + if (nb_samples==0) + { + eos=1; + } + if (eos && total_samples<=nb_encoded) + op.e_o_s = 1; + else + op.e_o_s = 0; + total_samples += nb_samples; + + if ((id+1)%nframes!=0) + continue; + speex_bits_insert_terminator(&bits); + nbBytes = speex_bits_write(&bits, cbits, MAX_FRAME_BYTES); + speex_bits_reset(&bits); + op.packet = (unsigned char *)cbits; + op.bytes = nbBytes; + op.b_o_s = 0; + /*Is this redundent?*/ + if (eos && total_samples<=nb_encoded) + op.e_o_s = 1; + else + op.e_o_s = 0; + op.granulepos = (id+1)*frame_size-lookahead; + if (op.granulepos>total_samples) + op.granulepos = total_samples; + /*printf ("granulepos: %d %d %d %d %d %d\n", (int)op.granulepos, id, nframes, lookahead, 5, 6);*/ + op.packetno = 2+id/nframes; + ogg_stream_packetin(&os, &op); + + /*Write all new pages (most likely 0 or 1)*/ + while (ogg_stream_pageout(&os,&og)) + { + ret = oe_write_page(&og, fout); + if(ret != og.header_len + og.body_len) + { + fprintf (stderr,"Error: failed writing header to output stream\n"); + exit(1); + } + else + bytes_written += ret; + } + } + if ((id+1)%nframes!=0) + { + while ((id+1)%nframes!=0) + { + id++; + speex_bits_pack(&bits, 15, 5); + } + nbBytes = speex_bits_write(&bits, cbits, MAX_FRAME_BYTES); + op.packet = (unsigned char *)cbits; + op.bytes = nbBytes; + op.b_o_s = 0; + op.e_o_s = 1; + op.granulepos = (id+1)*frame_size-lookahead; + if (op.granulepos>total_samples) + op.granulepos = total_samples; + + op.packetno = 2+id/nframes; + ogg_stream_packetin(&os, &op); + } + /*Flush all pages left to be written*/ + while (ogg_stream_flush(&os, &og)) + { + ret = oe_write_page(&og, fout); + if(ret != og.header_len + og.body_len) + { + fprintf (stderr,"Error: failed writing header to output stream\n"); + exit(1); + } + else + bytes_written += ret; + } + + speex_encoder_destroy(st); + speex_bits_destroy(&bits); + ogg_stream_clear(&os); + + if (close_in) + fclose(fin); + if (close_out) + fclose(fout); + return 0; +} + +/* + 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 + +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) [framing_bit] = read a single bit as boolean + 8) if ( [framing_bit] unset or end of packet ) then ERROR + 9) done. + + If you have troubles, please write to ymnk@jcraft.com. + */ + +#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) + +void comment_init(char **comments, int* length, char *vendor_string) +{ + int vendor_length=strlen(vendor_string); + int user_comment_list_length=0; + int len=4+vendor_length+4; + char *p=(char*)malloc(len); + if(p==NULL){ + } + writeint(p, 0, vendor_length); + memcpy(p+4, vendor_string, vendor_length); + writeint(p, 4+vendor_length, user_comment_list_length); + *length=len; + *comments=p; +} +void comment_add(char **comments, int* length, char *tag, char *val) +{ + char* p=*comments; + int vendor_length=readint(p, 0); + int user_comment_list_length=readint(p, 4+vendor_length); + int tag_len=(tag?strlen(tag):0); + int val_len=strlen(val); + int len=(*length)+4+tag_len+val_len; + + p=(char*)realloc(p, len); + if(p==NULL){ + } + + writeint(p, *length, tag_len+val_len); /* length of comment */ + if(tag) memcpy(p+*length+4, tag, tag_len); /* comment */ + memcpy(p+*length+4+tag_len, val, val_len); /* comment */ + writeint(p, 4+vendor_length, user_comment_list_length+1); + + *comments=p; + *length=len; +} +#undef readint +#undef writeint diff --git a/mozilla/zap/zmk/speex-1.1.10/src/wav_io.c b/mozilla/zap/zmk/speex-1.1.10/src/wav_io.c new file mode 100755 index 00000000000..27d73ade76a --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/src/wav_io.c @@ -0,0 +1,263 @@ +/* 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 +#include +#include "speex/speex_types.h" + +static spx_uint32_t le_int(spx_uint32_t i) +{ + spx_uint32_t ret=i; +#ifdef WORDS_BIGENDIAN + ret = i>>24; + ret += (i>>8)&0x0000ff00; + ret += (i<<8)&0x00ff0000; + ret += (i<<24); +#endif + return ret; +} + +unsigned short be_short(unsigned short s) +{ + unsigned short ret=s; +#ifndef WORDS_BIGENDIAN + ret = s>>8; + ret += s<<8; +#endif + return ret; +} + +unsigned short le_short(unsigned short s) +{ + unsigned short ret=s; +#ifdef WORDS_BIGENDIAN + ret = s>>8; + ret += s<<8; +#endif + return ret; +} + + +int read_wav_header(FILE *file, int *rate, int *channels, int *format, int *size) +{ + char ch[5]; + int itmp; + short stmp; + int bpersec; + short balign; + int skip_bytes; + int i; + + ch[4]=0; +#if 0 + fread(ch, 1, 4, file); + if (strcmp(ch, "RIFF")!=0) + { + fseek(file, 0, SEEK_SET); + return 0; + } + + fread(&itmp, 4, 1, file); + *size = le_int(itmp-36); + + fread(ch, 1, 4, file); + if (strcmp(ch, "WAVE")!=0) + { + fprintf (stderr, "RIFF file is not a WAVE file\n"); + return -1; + } +#endif + fread(ch, 1, 4, file); + while (strcmp(ch, "fmt ")!=0) + { + fread(&itmp, 4, 1, file); + itmp = le_int(itmp); + /*fprintf (stderr, "skip=%d\n", itmp);*/ + /*strange way of seeking, but it works even for pipes*/ + for (i=0;i2) + { + fprintf (stderr, "Only mono and (intensity) stereo supported\n"); + return -1; + } + + fread(&itmp, 4, 1, file); + itmp = le_int(itmp); + *rate = itmp; + if (*rate != 8000 && *rate != 16000 && *rate != 11025 && *rate != 22050 && *rate != 32000 && *rate != 44100 && *rate != 48000) + { + fprintf (stderr, "Only 8 kHz (narrowband) and 16 kHz (wideband) supported (plus 11.025 kHz and 22.05 kHz, but your mileage may vary)\n"); + return -1; + } + + fread(&itmp, 4, 1, file); + bpersec = le_int(itmp); + + fread(&stmp, 2, 1, file); + balign = le_short(stmp); + + fread(&stmp, 2, 1, file); + stmp = le_short(stmp); + if (stmp!=16 && stmp!=8) + { + fprintf (stderr, "Only 8/16-bit linear supported\n"); + return -1; + } + *format=stmp; + + if (bpersec!=*rate**channels*stmp/8) + { + fprintf (stderr, "Corrupted header: ByteRate mismatch\n"); + return -1; + } + + if (balign!=*channels*stmp/8) + { + fprintf (stderr, "Corrupted header: BlockAlign mismatch\n"); + return -1; + } + + + /*strange way of seeking, but it works even for pipes*/ + if (skip_bytes>0) + for (i=0;i + +unsigned short be_short(unsigned short s); +unsigned short le_short(unsigned short s); +unsigned short le_int(unsigned int s); + +int read_wav_header(FILE *file, int *rate, int *channels, int *format, int *size); + +void write_wav_header(FILE *file, int rate, int channels, int format, int size); + +#endif diff --git a/mozilla/zap/zmk/speex-1.1.10/src/wave_out.c b/mozilla/zap/zmk/speex-1.1.10/src/wave_out.c new file mode 100755 index 00000000000..64eeb6e963d --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/src/wave_out.c @@ -0,0 +1,220 @@ +/* Copyright (c) 2002, John Edwards + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 + +/* Set TABS = 4 */ +/******************************************************************** + + function: To provide playback of 16 bit PCM wave data in Win32 + environments from decoded compressed files. + + ********************************************************************/ + +#if defined WIN32 || defined _WIN32 + +#include +#include +#include "wave_out.h" + +#define MAXWAVESIZE 4294967040LU +#define MAX_WAVEBLOCKS 32 + +// This is modified for USE_WIN_AUDIO - ONLY 2002-02-27 + + +static CRITICAL_SECTION cs; +static HWAVEOUT dev = NULL; +static int ScheduledBlocks = 0; +static int PlayedWaveHeadersCount = 0; // free index +static WAVEHDR* PlayedWaveHeaders [MAX_WAVEBLOCKS]; + +static int +Box ( const char* msg ) +{ + MessageBox ( NULL, msg, " "VERSION_STRING": Error Message . . .", MB_OK | MB_ICONEXCLAMATION ); + return -1; +} + + +/* + * This function registers already played WAVE chunks. Freeing is done by free_memory(), + */ + +static void CALLBACK +wave_callback ( HWAVE hWave, UINT uMsg, DWORD dwInstance, DWORD dwParam1, DWORD dwParam2 ) +{ + if ( uMsg == WOM_DONE ) { + EnterCriticalSection ( &cs ); + PlayedWaveHeaders [PlayedWaveHeadersCount++] = (WAVEHDR*) dwParam1; + LeaveCriticalSection ( &cs ); + } +} + + +static void +free_memory ( void ) +{ + WAVEHDR* wh; + HGLOBAL hg; + + EnterCriticalSection ( &cs ); + wh = PlayedWaveHeaders [--PlayedWaveHeadersCount]; + ScheduledBlocks--; // decrease the number of USED blocks + LeaveCriticalSection ( &cs ); + + waveOutUnprepareHeader ( dev, wh, sizeof (WAVEHDR) ); + + hg = GlobalHandle ( wh -> lpData ); // Deallocate the buffer memory + GlobalUnlock (hg); + GlobalFree (hg); + + hg = GlobalHandle ( wh ); // Deallocate the header memory + GlobalUnlock (hg); + GlobalFree (hg); +} + + +Int +Set_WIN_Params ( FILE_T dummyFile , + Ldouble SampleFreq, + Uint BitsPerSample, + Uint Channels ) +{ + WAVEFORMATEX outFormat; + UINT deviceID = WAVE_MAPPER; + + (void) dummyFile; + + if ( waveOutGetNumDevs () == 0 ) + return Box ( "No audio device present." ); + + outFormat.wFormatTag = WAVE_FORMAT_PCM; + outFormat.wBitsPerSample = BitsPerSample; + outFormat.nChannels = Channels; + outFormat.nSamplesPerSec = (unsigned long)(SampleFreq + 0.5); + outFormat.nBlockAlign = (outFormat.wBitsPerSample + 7) / 8 * outFormat.nChannels; + outFormat.nAvgBytesPerSec = outFormat.nSamplesPerSec * outFormat.nBlockAlign; + + switch ( waveOutOpen ( &dev, deviceID, &outFormat, (DWORD)wave_callback, 0, CALLBACK_FUNCTION ) ) + { + case MMSYSERR_ALLOCATED: return Box ( "Device is already open." ); + case MMSYSERR_BADDEVICEID: return Box ( "The specified device is out of range." ); + case MMSYSERR_NODRIVER: return Box ( "There is no audio driver in this system." ); + case MMSYSERR_NOMEM: return Box ( "Unable to allocate sound memory." ); + case WAVERR_BADFORMAT: return Box ( "This audio format is not supported." ); + case WAVERR_SYNC: return Box ( "The device is synchronous." ); + default: return Box ( "Unknown media error." ); + case MMSYSERR_NOERROR: break; + } + + waveOutReset ( dev ); + InitializeCriticalSection ( &cs ); + SetPriorityClass ( GetCurrentProcess (), HIGH_PRIORITY_CLASS ); + return 0; +} + + +int +WIN_Play_Samples ( const void* data, size_t len ) +{ + HGLOBAL hg; + HGLOBAL hg2; + LPWAVEHDR wh; + void* allocptr; + + do { + while ( PlayedWaveHeadersCount > 0 ) // free used blocks ... + free_memory (); + + if ( ScheduledBlocks < sizeof(PlayedWaveHeaders)/sizeof(*PlayedWaveHeaders) ) // wait for a free block ... + break; + Sleep (26); + } while (1); + + if ( (hg2 = GlobalAlloc ( GMEM_MOVEABLE, len )) == NULL ) // allocate some memory for a copy of the buffer + return Box ( "GlobalAlloc failed." ); + + allocptr = GlobalLock (hg2); + CopyMemory ( allocptr, data, len ); // Here we can call any modification output functions we want.... + + if ( (hg = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, sizeof (WAVEHDR))) == NULL ) // now make a header and WRITE IT! + return -1; + + wh = GlobalLock (hg); + wh -> dwBufferLength = len; + wh -> lpData = allocptr; + + if ( waveOutPrepareHeader ( dev, wh, sizeof (WAVEHDR)) != MMSYSERR_NOERROR ) { + GlobalUnlock (hg); + GlobalFree (hg); + return -1; + } + + if ( waveOutWrite ( dev, wh, sizeof (WAVEHDR)) != MMSYSERR_NOERROR ) { + GlobalUnlock (hg); + GlobalFree (hg); + return -1; + } + + EnterCriticalSection ( &cs ); + ScheduledBlocks++; + LeaveCriticalSection ( &cs ); + + return len; +} + + +int +WIN_Audio_close ( void ) +{ + if ( dev != NULL ) { + + while ( ScheduledBlocks > 0 ) { + Sleep (ScheduledBlocks); + while ( PlayedWaveHeadersCount > 0 ) // free used blocks ... + free_memory (); + } + + waveOutReset (dev); // reset the device + waveOutClose (dev); // close the device + dev = NULL; + } + + DeleteCriticalSection ( &cs ); + ScheduledBlocks = 0; + return 0; +} + +#endif + +/* end of wave_out.c */ diff --git a/mozilla/zap/zmk/speex-1.1.10/src/wave_out.h b/mozilla/zap/zmk/speex-1.1.10/src/wave_out.h new file mode 100755 index 00000000000..0c467b1945d --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/src/wave_out.h @@ -0,0 +1,71 @@ +/* Copyright (c) 2002, John Edwards + + 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. + + - Neither the name of the Xiph.org Foundation nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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. +*/ + +// WAVE_OUT.H - Necessary stuff for WIN_AUDIO + +#ifndef WAVE_OUT_H +#define WAVE_OUT_H + +#include +#include +#ifdef __MINGW32__ +#include +#endif + +#define VERSION_STRING "\n 0.7.0\n" + +#define Cdecl __cdecl +#define __attribute__(x) +#define sleep(__sec) Sleep ((__sec) * 1000) +#define inline __inline +#define restrict + +//// constants ///////////////////////////////////////////////////// + +#define CD_SAMPLE_FREQ 44.1e3 +#define SAMPLE_SIZE 16 +#define SAMPLE_SIZE_STRING "" +#define WINAUDIO_FD ((FILE_T)-128) +#define FILE_T FILE* +#define INVALID_FILEDESC NULL + +//// Simple types ////////////////////////////////////////////////// + +typedef signed int Int; // at least -32767...+32767, fast type +typedef unsigned int Uint; // at least 0...65535, fast type +typedef long double Ldouble; // most exact floating point format + +//// procedures/functions ////////////////////////////////////////// +// wave_out.c +Int Set_WIN_Params ( FILE_T dummyFile , Ldouble SampleFreq, Uint BitsPerSample, Uint Channels); +int WIN_Play_Samples ( const void* buff, size_t len ); +int WIN_Audio_close ( void ); + +#endif /* WAVE_OUT_H */ diff --git a/mozilla/zap/zmk/speex-1.1.10/symbian/Makefile.am b/mozilla/zap/zmk/speex-1.1.10/symbian/Makefile.am new file mode 100755 index 00000000000..b8e3f47b683 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/symbian/Makefile.am @@ -0,0 +1,6 @@ +## Process this file with automake to produce Makefile.in. -*-Makefile-*- + +# Disable automatic dependency tracking if using other tools than gcc and gmake +#AUTOMAKE_OPTIONS = no-dependencies + +EXTRA_DIST = bld.inf config.h speex.mmp diff --git a/mozilla/zap/zmk/speex-1.1.10/symbian/Makefile.in b/mozilla/zap/zmk/speex-1.1.10/symbian/Makefile.in new file mode 100755 index 00000000000..159781d463f --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/symbian/Makefile.in @@ -0,0 +1,322 @@ +# Makefile.in generated by automake 1.8.5 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004 Free Software Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +# Disable automatic dependency tracking if using other tools than gcc and gmake +#AUTOMAKE_OPTIONS = no-dependencies +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +top_builddir = .. +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +INSTALL = @INSTALL@ +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +host_triplet = @host@ +subdir = symbian +DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ + $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = +SOURCES = +DIST_SOURCES = +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +AMDEP_FALSE = @AMDEP_FALSE@ +AMDEP_TRUE = @AMDEP_TRUE@ +AMTAR = @AMTAR@ +AR = @AR@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CXX = @CXX@ +CXXCPP = @CXXCPP@ +CXXDEPMODE = @CXXDEPMODE@ +CXXFLAGS = @CXXFLAGS@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +ECHO = @ECHO@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +F77 = @F77@ +FFLAGS = @FFLAGS@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +LDFLAGS = @LDFLAGS@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +MAINT = @MAINT@ +MAINTAINER_MODE_FALSE = @MAINTAINER_MODE_FALSE@ +MAINTAINER_MODE_TRUE = @MAINTAINER_MODE_TRUE@ +MAKEINFO = @MAKEINFO@ +OBJEXT = @OBJEXT@ +OGG_CFLAGS = @OGG_CFLAGS@ +OGG_LIBS = @OGG_LIBS@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +RANLIB = @RANLIB@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +SIZE16 = @SIZE16@ +SIZE32 = @SIZE32@ +SPEEX_LT_AGE = @SPEEX_LT_AGE@ +SPEEX_LT_CURRENT = @SPEEX_LT_CURRENT@ +SPEEX_LT_REVISION = @SPEEX_LT_REVISION@ +SPEEX_VERSION = @SPEEX_VERSION@ +STRIP = @STRIP@ +VERSION = @VERSION@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_CXX = @ac_ct_CXX@ +ac_ct_F77 = @ac_ct_F77@ +ac_ct_RANLIB = @ac_ct_RANLIB@ +ac_ct_STRIP = @ac_ct_STRIP@ +am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ +am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ +am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ +am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +datadir = @datadir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +src = @src@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +EXTRA_DIST = bld.inf config.h speex.mmp +all: all-am + +.SUFFIXES: +$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ + && exit 0; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu symbian/Makefile'; \ + cd $(top_srcdir) && \ + $(AUTOMAKE) --gnu symbian/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +distclean-libtool: + -rm -f libtool +uninstall-info-am: +tags: TAGS +TAGS: + +ctags: CTAGS +CTAGS: + + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ + list='$(DISTFILES)'; for file in $$list; do \ + case $$file in \ + $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ + $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ + esac; \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test "$$dir" != "$$file" && test "$$dir" != "."; then \ + dir="/$$dir"; \ + $(mkdir_p) "$(distdir)$$dir"; \ + else \ + dir=''; \ + fi; \ + if test -d $$d/$$file; then \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + fi; \ + cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + else \ + test -f $(distdir)/$$file \ + || cp -p $$d/$$file $(distdir)/$$file \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile +installdirs: +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + `test -z '$(STRIP)' || \ + echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -rm -f $(CONFIG_CLEAN_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-am + -rm -f Makefile +distclean-am: clean-am distclean-generic distclean-libtool + +dvi: dvi-am + +dvi-am: + +html: html-am + +info: info-am + +info-am: + +install-data-am: + +install-exec-am: + +install-info: install-info-am + +install-man: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-info-am + +.PHONY: all all-am check check-am clean clean-generic clean-libtool \ + distclean distclean-generic distclean-libtool distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-exec install-exec-am \ + install-info install-info-am install-man install-strip \ + installcheck installcheck-am installdirs maintainer-clean \ + maintainer-clean-generic mostlyclean mostlyclean-generic \ + mostlyclean-libtool pdf pdf-am ps ps-am uninstall uninstall-am \ + uninstall-info-am + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/mozilla/zap/zmk/speex-1.1.10/symbian/bld.inf b/mozilla/zap/zmk/speex-1.1.10/symbian/bld.inf new file mode 100755 index 00000000000..71fa4d91421 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/symbian/bld.inf @@ -0,0 +1,35 @@ +/* + Copyright (C) 2003 Commonwealth Scientific and Industrial Research + Organisation (CSIRO) Australia + + 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. + + - Neither the name of CSIRO Australia nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 ORGANISATION 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. +*/ + +PRJ_MMPFILES + +speex.mmp diff --git a/mozilla/zap/zmk/speex-1.1.10/symbian/config.h b/mozilla/zap/zmk/speex-1.1.10/symbian/config.h new file mode 100755 index 00000000000..4ead5768530 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/symbian/config.h @@ -0,0 +1,57 @@ +/* + Copyright (C) 2003 Commonwealth Scientific and Industrial Research + Organisation (CSIRO) Australia + + 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. + + - Neither the name of CSIRO Australia nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 ORGANISATION 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 CONFIG_H +#define CONFIG_H + +/* An inline macro is required for use of the inline keyword as not all C compilers support */ +/* inline. It is officially C99 and C++ only */ + +#ifdef __WINS__ + +#define inline __inline + +/* Disable some pointless/stupid warnings */ + +#pragma warning(disable: 4100) /* unreferenced formal parameter */ +#pragma warning(disable: 4127) /* conditional expression is constant */ +#pragma warning(disable: 4305) /* truncation from '...' to '...' */ +#pragma warning(disable: 4244) /* conversion from '...' to '...', possible loss of data */ +#pragma warning(disable: 4701) /* local variable may be be used without having been initialized */ + +#endif /* ! __WINS__ */ + +/* Use only fixed point arithmetic */ + +#define FIXED_POINT 1 + +#endif /* ! CONFIG_H */ diff --git a/mozilla/zap/zmk/speex-1.1.10/symbian/speex.mmp b/mozilla/zap/zmk/speex-1.1.10/symbian/speex.mmp new file mode 100755 index 00000000000..5d071ff9f12 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/symbian/speex.mmp @@ -0,0 +1,45 @@ +/* + Copyright (C) 2003 Commonwealth Scientific and Industrial Research + Organisation (CSIRO) Australia + + 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. + + - Neither the name of CSIRO Australia nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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 ORGANISATION 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. +*/ + +TARGET speex.lib +TARGETTYPE lib +UID 0 +MACRO HAVE_CONFIG_H +SOURCEPATH ..\libspeex +SOURCE bits.c cb_search.c exc_5_64_table.c exc_5_256_table.c exc_8_128_table.c +SOURCE exc_10_16_table.c exc_10_32_table.c exc_20_32_table.c filters.c gain_table.c +SOURCE gain_table_lbr.c hexc_10_32_table.c hexc_table.c high_lsp_tables.c jitter.c +SOURCE lbr_48k_tables.c lpc.c lsp.c lsp_tables_nb.c ltp.c math_approx.c mdf.c misc.c +SOURCE modes.c nb_celp.c preprocess.c quant_lsp.c sb_celp.c smallft.c +SOURCE speex.c speex_callbacks.c speex_header.c stereo.c vbr.c vq.c +USERINCLUDE . ..\include\speex +SYSTEMINCLUDE \epoc32\include \epoc32\include\libc ..\include diff --git a/mozilla/zap/zmk/speex-1.1.10/win32/Makefile.am b/mozilla/zap/zmk/speex-1.1.10/win32/Makefile.am new file mode 100755 index 00000000000..f0829e26321 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/win32/Makefile.am @@ -0,0 +1,8 @@ +## Process this file with automake to produce Makefile.in. -*-Makefile-*- + +# Disable automatic dependency tracking if using other tools than gcc and gmake +#AUTOMAKE_OPTIONS = no-dependencies + +SUBDIRS = libspeex speexenc speexdec + +EXTRA_DIST = speex.iss config.h diff --git a/mozilla/zap/zmk/speex-1.1.10/win32/Makefile.in b/mozilla/zap/zmk/speex-1.1.10/win32/Makefile.in new file mode 100755 index 00000000000..61e08764974 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/win32/Makefile.in @@ -0,0 +1,466 @@ +# Makefile.in generated by automake 1.8.5 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004 Free Software Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +# Disable automatic dependency tracking if using other tools than gcc and gmake +#AUTOMAKE_OPTIONS = no-dependencies +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +top_builddir = .. +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +INSTALL = @INSTALL@ +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +host_triplet = @host@ +subdir = win32 +DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ + $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = +SOURCES = +DIST_SOURCES = +RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \ + html-recursive info-recursive install-data-recursive \ + install-exec-recursive install-info-recursive \ + install-recursive installcheck-recursive installdirs-recursive \ + pdf-recursive ps-recursive uninstall-info-recursive \ + uninstall-recursive +ETAGS = etags +CTAGS = ctags +DIST_SUBDIRS = $(SUBDIRS) +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +AMDEP_FALSE = @AMDEP_FALSE@ +AMDEP_TRUE = @AMDEP_TRUE@ +AMTAR = @AMTAR@ +AR = @AR@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CXX = @CXX@ +CXXCPP = @CXXCPP@ +CXXDEPMODE = @CXXDEPMODE@ +CXXFLAGS = @CXXFLAGS@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +ECHO = @ECHO@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +F77 = @F77@ +FFLAGS = @FFLAGS@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +LDFLAGS = @LDFLAGS@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +MAINT = @MAINT@ +MAINTAINER_MODE_FALSE = @MAINTAINER_MODE_FALSE@ +MAINTAINER_MODE_TRUE = @MAINTAINER_MODE_TRUE@ +MAKEINFO = @MAKEINFO@ +OBJEXT = @OBJEXT@ +OGG_CFLAGS = @OGG_CFLAGS@ +OGG_LIBS = @OGG_LIBS@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +RANLIB = @RANLIB@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +SIZE16 = @SIZE16@ +SIZE32 = @SIZE32@ +SPEEX_LT_AGE = @SPEEX_LT_AGE@ +SPEEX_LT_CURRENT = @SPEEX_LT_CURRENT@ +SPEEX_LT_REVISION = @SPEEX_LT_REVISION@ +SPEEX_VERSION = @SPEEX_VERSION@ +STRIP = @STRIP@ +VERSION = @VERSION@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_CXX = @ac_ct_CXX@ +ac_ct_F77 = @ac_ct_F77@ +ac_ct_RANLIB = @ac_ct_RANLIB@ +ac_ct_STRIP = @ac_ct_STRIP@ +am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ +am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ +am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ +am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +datadir = @datadir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +src = @src@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +SUBDIRS = libspeex speexenc speexdec +EXTRA_DIST = speex.iss config.h +all: all-recursive + +.SUFFIXES: +$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ + && exit 0; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu win32/Makefile'; \ + cd $(top_srcdir) && \ + $(AUTOMAKE) --gnu win32/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +distclean-libtool: + -rm -f libtool +uninstall-info-am: + +# This directory's subdirectories are mostly independent; you can cd +# into them and run `make' without going through this Makefile. +# To change the values of `make' variables: instead of editing Makefiles, +# (1) if the variable is set in `config.status', edit `config.status' +# (which will cause the Makefiles to be regenerated when you run `make'); +# (2) otherwise, pass the desired values on the `make' command line. +$(RECURSIVE_TARGETS): + @set fnord $$MAKEFLAGS; amf=$$2; \ + dot_seen=no; \ + target=`echo $@ | sed s/-recursive//`; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + dot_seen=yes; \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || case "$$amf" in *=*) exit 1;; *k*) fail=yes;; *) exit 1;; esac; \ + done; \ + if test "$$dot_seen" = "no"; then \ + $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ + fi; test -z "$$fail" + +mostlyclean-recursive clean-recursive distclean-recursive \ +maintainer-clean-recursive: + @set fnord $$MAKEFLAGS; amf=$$2; \ + dot_seen=no; \ + case "$@" in \ + distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ + *) list='$(SUBDIRS)' ;; \ + esac; \ + rev=''; for subdir in $$list; do \ + if test "$$subdir" = "."; then :; else \ + rev="$$subdir $$rev"; \ + fi; \ + done; \ + rev="$$rev ."; \ + target=`echo $@ | sed s/-recursive//`; \ + for subdir in $$rev; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || case "$$amf" in *=*) exit 1;; *k*) fail=yes;; *) exit 1;; esac; \ + done && test -z "$$fail" +tags-recursive: + list='$(SUBDIRS)'; for subdir in $$list; do \ + test "$$subdir" = . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \ + done +ctags-recursive: + list='$(SUBDIRS)'; for subdir in $$list; do \ + test "$$subdir" = . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \ + done + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: tags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + tags=; \ + here=`pwd`; \ + if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ + include_option=--etags-include; \ + empty_fix=.; \ + else \ + include_option=--include; \ + empty_fix=; \ + fi; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test ! -f $$subdir/TAGS || \ + tags="$$tags $$include_option=$$here/$$subdir/TAGS"; \ + fi; \ + done; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$tags $$unique; \ + fi +ctags: CTAGS +CTAGS: ctags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + tags=; \ + here=`pwd`; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) ' { files[$$0] = 1; } \ + END { for (i in files) print i; }'`; \ + test -z "$(CTAGS_ARGS)$$tags$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$tags $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && cd $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) $$here + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ + list='$(DISTFILES)'; for file in $$list; do \ + case $$file in \ + $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ + $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ + esac; \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test "$$dir" != "$$file" && test "$$dir" != "."; then \ + dir="/$$dir"; \ + $(mkdir_p) "$(distdir)$$dir"; \ + else \ + dir=''; \ + fi; \ + if test -d $$d/$$file; then \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + fi; \ + cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + else \ + test -f $(distdir)/$$file \ + || cp -p $$d/$$file $(distdir)/$$file \ + || exit 1; \ + fi; \ + done + list='$(SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test -d "$(distdir)/$$subdir" \ + || mkdir "$(distdir)/$$subdir" \ + || exit 1; \ + (cd $$subdir && \ + $(MAKE) $(AM_MAKEFLAGS) \ + top_distdir="../$(top_distdir)" \ + distdir="../$(distdir)/$$subdir" \ + distdir) \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-recursive +all-am: Makefile +installdirs: installdirs-recursive +installdirs-am: +install: install-recursive +install-exec: install-exec-recursive +install-data: install-data-recursive +uninstall: uninstall-recursive + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-recursive +install-strip: + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + `test -z '$(STRIP)' || \ + echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -rm -f $(CONFIG_CLEAN_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-recursive + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-recursive + -rm -f Makefile +distclean-am: clean-am distclean-generic distclean-libtool \ + distclean-tags + +dvi: dvi-recursive + +dvi-am: + +html: html-recursive + +info: info-recursive + +info-am: + +install-data-am: + +install-exec-am: + +install-info: install-info-recursive + +install-man: + +installcheck-am: + +maintainer-clean: maintainer-clean-recursive + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-recursive + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-recursive + +pdf-am: + +ps: ps-recursive + +ps-am: + +uninstall-am: uninstall-info-am + +uninstall-info: uninstall-info-recursive + +.PHONY: $(RECURSIVE_TARGETS) CTAGS GTAGS all all-am check check-am \ + clean clean-generic clean-libtool clean-recursive ctags \ + ctags-recursive distclean distclean-generic distclean-libtool \ + distclean-recursive distclean-tags distdir dvi dvi-am html \ + html-am info info-am install install-am install-data \ + install-data-am install-exec install-exec-am install-info \ + install-info-am install-man install-strip installcheck \ + installcheck-am installdirs installdirs-am maintainer-clean \ + maintainer-clean-generic maintainer-clean-recursive \ + mostlyclean mostlyclean-generic mostlyclean-libtool \ + mostlyclean-recursive pdf pdf-am ps ps-am tags tags-recursive \ + uninstall uninstall-am uninstall-info-am + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/mozilla/zap/zmk/speex-1.1.10/win32/config.h b/mozilla/zap/zmk/speex-1.1.10/win32/config.h new file mode 100755 index 00000000000..0c3be5100a2 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/win32/config.h @@ -0,0 +1,2 @@ +#define inline __inline +#define restrict diff --git a/mozilla/zap/zmk/speex-1.1.10/win32/libspeex/Makefile.am b/mozilla/zap/zmk/speex-1.1.10/win32/libspeex/Makefile.am new file mode 100755 index 00000000000..4f63aed87d9 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/win32/libspeex/Makefile.am @@ -0,0 +1,6 @@ +## Process this file with automake to produce Makefile.in. -*-Makefile-*- + +# Disable automatic dependency tracking if using other tools than gcc and gmake +#AUTOMAKE_OPTIONS = no-dependencies + +EXTRA_DIST = libspeex.dsp libspeex.dsw libspeex_dynamic.dsp speex.def diff --git a/mozilla/zap/zmk/speex-1.1.10/win32/libspeex/Makefile.in b/mozilla/zap/zmk/speex-1.1.10/win32/libspeex/Makefile.in new file mode 100755 index 00000000000..8b9195ba0fd --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/win32/libspeex/Makefile.in @@ -0,0 +1,322 @@ +# Makefile.in generated by automake 1.8.5 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004 Free Software Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +# Disable automatic dependency tracking if using other tools than gcc and gmake +#AUTOMAKE_OPTIONS = no-dependencies +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +top_builddir = ../.. +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +INSTALL = @INSTALL@ +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +host_triplet = @host@ +subdir = win32/libspeex +DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ + $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = +SOURCES = +DIST_SOURCES = +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +AMDEP_FALSE = @AMDEP_FALSE@ +AMDEP_TRUE = @AMDEP_TRUE@ +AMTAR = @AMTAR@ +AR = @AR@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CXX = @CXX@ +CXXCPP = @CXXCPP@ +CXXDEPMODE = @CXXDEPMODE@ +CXXFLAGS = @CXXFLAGS@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +ECHO = @ECHO@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +F77 = @F77@ +FFLAGS = @FFLAGS@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +LDFLAGS = @LDFLAGS@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +MAINT = @MAINT@ +MAINTAINER_MODE_FALSE = @MAINTAINER_MODE_FALSE@ +MAINTAINER_MODE_TRUE = @MAINTAINER_MODE_TRUE@ +MAKEINFO = @MAKEINFO@ +OBJEXT = @OBJEXT@ +OGG_CFLAGS = @OGG_CFLAGS@ +OGG_LIBS = @OGG_LIBS@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +RANLIB = @RANLIB@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +SIZE16 = @SIZE16@ +SIZE32 = @SIZE32@ +SPEEX_LT_AGE = @SPEEX_LT_AGE@ +SPEEX_LT_CURRENT = @SPEEX_LT_CURRENT@ +SPEEX_LT_REVISION = @SPEEX_LT_REVISION@ +SPEEX_VERSION = @SPEEX_VERSION@ +STRIP = @STRIP@ +VERSION = @VERSION@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_CXX = @ac_ct_CXX@ +ac_ct_F77 = @ac_ct_F77@ +ac_ct_RANLIB = @ac_ct_RANLIB@ +ac_ct_STRIP = @ac_ct_STRIP@ +am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ +am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ +am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ +am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +datadir = @datadir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +src = @src@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +EXTRA_DIST = libspeex.dsp libspeex.dsw libspeex_dynamic.dsp speex.def +all: all-am + +.SUFFIXES: +$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ + && exit 0; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu win32/libspeex/Makefile'; \ + cd $(top_srcdir) && \ + $(AUTOMAKE) --gnu win32/libspeex/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +distclean-libtool: + -rm -f libtool +uninstall-info-am: +tags: TAGS +TAGS: + +ctags: CTAGS +CTAGS: + + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ + list='$(DISTFILES)'; for file in $$list; do \ + case $$file in \ + $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ + $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ + esac; \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test "$$dir" != "$$file" && test "$$dir" != "."; then \ + dir="/$$dir"; \ + $(mkdir_p) "$(distdir)$$dir"; \ + else \ + dir=''; \ + fi; \ + if test -d $$d/$$file; then \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + fi; \ + cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + else \ + test -f $(distdir)/$$file \ + || cp -p $$d/$$file $(distdir)/$$file \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile +installdirs: +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + `test -z '$(STRIP)' || \ + echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -rm -f $(CONFIG_CLEAN_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-am + -rm -f Makefile +distclean-am: clean-am distclean-generic distclean-libtool + +dvi: dvi-am + +dvi-am: + +html: html-am + +info: info-am + +info-am: + +install-data-am: + +install-exec-am: + +install-info: install-info-am + +install-man: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-info-am + +.PHONY: all all-am check check-am clean clean-generic clean-libtool \ + distclean distclean-generic distclean-libtool distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-exec install-exec-am \ + install-info install-info-am install-man install-strip \ + installcheck installcheck-am installdirs maintainer-clean \ + maintainer-clean-generic mostlyclean mostlyclean-generic \ + mostlyclean-libtool pdf pdf-am ps ps-am uninstall uninstall-am \ + uninstall-info-am + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/mozilla/zap/zmk/speex-1.1.10/win32/libspeex/libspeex.dsp b/mozilla/zap/zmk/speex-1.1.10/win32/libspeex/libspeex.dsp new file mode 100755 index 00000000000..47a8b5c5b98 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/win32/libspeex/libspeex.dsp @@ -0,0 +1,302 @@ +# Microsoft Developer Studio Project File - Name="libspeex" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Static Library" 0x0104 + +CFG=libspeex - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "libspeex.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "libspeex.mak" CFG="libspeex - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "libspeex - Win32 Release" (based on "Win32 (x86) Static Library") +!MESSAGE "libspeex - Win32 Debug" (based on "Win32 (x86) Static Library") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "Perforce Project" +# PROP Scc_LocalPath "..\.." +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "libspeex - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +F90=df.exe +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /FD /c +# ADD CPP /nologo /GX /Ox /Ot /Og /Oi /Ob2 /I "../../include" /I "../" /D inline=__inline /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "HAVE_CONFIG_H" /YX /FD /c +# ADD BASE RSC /l 0x809 /d "NDEBUG" +# ADD RSC /l 0x809 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo + +!ELSEIF "$(CFG)" == "libspeex - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Target_Dir "" +F90=df.exe +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /FD /GZ /c +# ADD CPP /nologo /W3 /GX /Ox /Ot /Og /Oi /Ob2 /I "../../include" /I "../" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "HAVE_CONFIG_H" /YX /FD /c +# ADD BASE RSC /l 0x809 /d "_DEBUG" +# ADD RSC /l 0x809 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo + +!ENDIF + +# Begin Target + +# Name "libspeex - Win32 Release" +# Name "libspeex - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=..\..\libspeex\bits.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\cb_search.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\exc_10_16_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\exc_10_32_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\exc_20_32_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\exc_5_256_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\exc_5_64_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\exc_8_128_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\filters.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\gain_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\gain_table_lbr.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\hexc_10_32_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\hexc_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\high_lsp_tables.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\lpc.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\lsp.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\lsp_tables_nb.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\ltp.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\math_approx.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\misc.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\modes.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\nb_celp.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\preprocess.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\quant_lsp.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\sb_celp.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\smallft.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\speex.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\speex_callbacks.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\speex_header.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\stereo.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\vbr.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\vq.c +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Source File + +SOURCE=..\..\libspeex\cb_search.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\filters.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\lpc.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\lsp.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\ltp.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\misc.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\modes.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\nb_celp.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\quant_lsp.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\sb_celp.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\smallft.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\speex.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\speex_bits.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\speex_callbacks.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\speex_denoise.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\speex_header.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\speex_stereo.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\stack_alloc.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\vbr.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\vq.h +# End Source File +# End Group +# End Target +# End Project diff --git a/mozilla/zap/zmk/speex-1.1.10/win32/libspeex/libspeex.dsw b/mozilla/zap/zmk/speex-1.1.10/win32/libspeex/libspeex.dsw new file mode 100755 index 00000000000..9fb56fefec2 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/win32/libspeex/libspeex.dsw @@ -0,0 +1,41 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "libspeex"=.\libspeex.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "libspeex_dynamic"=.\libspeex_dynamic.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git a/mozilla/zap/zmk/speex-1.1.10/win32/libspeex/libspeex_dynamic.dsp b/mozilla/zap/zmk/speex-1.1.10/win32/libspeex/libspeex_dynamic.dsp new file mode 100755 index 00000000000..5e009728830 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/win32/libspeex/libspeex_dynamic.dsp @@ -0,0 +1,311 @@ +# Microsoft Developer Studio Project File - Name="libspeex_dynamic" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102 + +CFG=libspeex_dynamic - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "libspeex_dynamic.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "libspeex_dynamic.mak" CFG="libspeex_dynamic - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "libspeex_dynamic - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library") +!MESSAGE "libspeex_dynamic - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +MTL=midl.exe +RSC=rc.exe + +!IF "$(CFG)" == "libspeex_dynamic - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "libspeex_dynamic___Win32_Release" +# PROP BASE Intermediate_Dir "libspeex_dynamic___Win32_Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Dynamic_Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "LIBSPEEX_DYNAMIC_EXPORTS" /YX /FD /c +# ADD CPP /nologo /MT /W3 /GX /O2 /I "../../include" /I "../" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "LIBSPEEX_DYNAMIC_EXPORTS" /D "HAVE_CONFIG_H" /YX /FD /c +# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 +# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386 /out:"Release/libspeex.dll" + +!ELSEIF "$(CFG)" == "libspeex_dynamic - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "libspeex_dynamic___Win32_Debug" +# PROP BASE Intermediate_Dir "libspeex_dynamic___Win32_Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Dynamic_Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "LIBSPEEX_DYNAMIC_EXPORTS" /YX /FD /GZ /c +# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "../../include" /I "../" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "LIBSPEEX_DYNAMIC_EXPORTS" /D "HAVE_CONFIG_H" /YX /FD /GZ /c +# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 +# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /pdbtype:sept +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /out:"Debug/libspeex.dll" /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "libspeex_dynamic - Win32 Release" +# Name "libspeex_dynamic - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "" +# Begin Source File + +SOURCE=..\..\libspeex\bits.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\cb_search.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\exc_10_16_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\exc_10_32_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\exc_20_32_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\exc_5_256_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\exc_5_64_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\exc_8_128_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\filters.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\gain_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\gain_table_lbr.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\hexc_10_32_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\hexc_table.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\high_lsp_tables.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\lpc.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\lsp.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\lsp_tables_nb.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\ltp.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\math_approx.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\misc.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\modes.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\nb_celp.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\preprocess.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\quant_lsp.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\sb_celp.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\smallft.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\speex.c +# End Source File +# Begin Source File + +SOURCE=.\speex.def +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\speex_callbacks.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\speex_header.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\stereo.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\vbr.c +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\vq.c +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Source File + +SOURCE=..\..\libspeex\cb_search.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\filters.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\lpc.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\lsp.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\ltp.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\misc.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\modes.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\nb_celp.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\quant_lsp.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\sb_celp.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\smallft.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\speex.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\speex_bits.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\speex_callbacks.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\speex_denoise.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\speex_header.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\speex_stereo.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\stack_alloc.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\vbr.h +# End Source File +# Begin Source File + +SOURCE=..\..\libspeex\vq.h +# End Source File +# End Group +# End Target +# End Project diff --git a/mozilla/zap/zmk/speex-1.1.10/win32/libspeex/speex.def b/mozilla/zap/zmk/speex-1.1.10/win32/libspeex/speex.def new file mode 100755 index 00000000000..cb89364f5f9 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/win32/libspeex/speex.def @@ -0,0 +1,49 @@ +; +; speex.def +; +LIBRARY +EXPORTS +; +speex_encoder_init +speex_encoder_destroy +speex_encode +speex_encoder_ctl +speex_decoder_init +speex_decoder_destroy +speex_decode +speex_decoder_ctl +speex_mode_query +speex_lib_ctl +speex_bits_init +speex_bits_init_buffer +speex_bits_destroy +speex_bits_reset +speex_bits_rewind +speex_bits_read_from +speex_bits_read_whole_bytes +speex_bits_write +speex_bits_write_whole_bytes +speex_bits_pack +speex_bits_unpack_signed +speex_bits_unpack_unsigned +speex_bits_nbytes +speex_bits_peek_unsigned +speex_bits_peek +speex_bits_advance +speex_bits_remaining +speex_bits_insert_terminator +speex_inband_handler +speex_std_mode_request_handler +speex_std_high_mode_request_handler +speex_std_char_handler +speex_default_user_handler +speex_std_low_mode_request_handler +speex_std_vbr_request_handler +speex_std_enh_request_handler +speex_std_vbr_quality_request_handler +speex_init_header +speex_header_to_packet +speex_packet_to_header +speex_encode_stereo +speex_decode_stereo +speex_std_stereo_request_handler diff --git a/mozilla/zap/zmk/speex-1.1.10/win32/speex.iss b/mozilla/zap/zmk/speex-1.1.10/win32/speex.iss new file mode 100755 index 00000000000..8f2a398eff2 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/win32/speex.iss @@ -0,0 +1,47 @@ +; Script generated by the Inno Setup Script Wizard. +; SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES! + +[Setup] +AppName=Speex +AppVerName=Speex V1.1.6 +AppPublisherURL=http://www.speex.org +AppSupportURL=http://www.speex.org +AppUpdatesURL=http://www.speex.org +DefaultDirName={pf}\Speex +DefaultGroupName=Speex +AllowNoIcons=yes +LicenseFile=..\COPYING +InfoAfterFile=..\README +OutputDir=. +OutputBaseFilename=speex_win32_1.1.6_setup +; uncomment the following line if you want your installation to run on NT 3.51 too. +; MinVersion=4,3.51 + +[Tasks] +;Name: "desktopicon"; Description: "Create a &desktop icon"; GroupDescription: "Additional icons:"; MinVersion: 4,4 + +[Dirs] +Name: "{app}" +Name: "{app}\doc" +Name: "{app}\html" +Name: "{app}\libspeex" +Name: "{app}\libspeex\include" + +[Files] +Source: "speexdec\Release\speexdec.exe"; DestDir: "{app}"; Flags: ignoreversion +Source: "speexenc\Release\speexenc.exe"; DestDir: "{app}"; Flags: ignoreversion +Source: "libspeex\Release\libspeex.lib"; DestDir: "{app}\libspeex"; Flags: ignoreversion +Source: "libspeex\Release\libspeex.exp"; DestDir: "{app}\libspeex"; Flags: ignoreversion +Source: "libspeex\Release\libspeex.dll"; DestDir: "{app}\libspeex"; Flags: ignoreversion +Source: "..\include\speex\speex.h"; DestDir: "{app}\libspeex\include"; Flags: ignoreversion +Source: "..\include\speex\speex_bits.h"; DestDir: "{app}\libspeex\include"; Flags: ignoreversion +Source: "..\include\speex\speex_callbacks.h"; DestDir: "{app}\libspeex\include"; Flags: ignoreversion +Source: "..\include\speex\speex_echo.h"; DestDir: "{app}\libspeex\include"; Flags: ignoreversion +Source: "..\include\speex\speex_header.h"; DestDir: "{app}\libspeex\include"; Flags: ignoreversion +Source: "..\include\speex\speex_jitter.h"; DestDir: "{app}\libspeex\include"; Flags: ignoreversion +Source: "..\include\speex\speex_preprocess.h"; DestDir: "{app}\libspeex\include"; Flags: ignoreversion +Source: "..\include\speex\speex_stereo.h"; DestDir: "{app}\libspeex\include"; Flags: ignoreversion +Source: "..\doc\manual.pdf"; DestDir: "{app}\doc"; Flags: ignoreversion + +[Run] + diff --git a/mozilla/zap/zmk/speex-1.1.10/win32/speexdec/Makefile.am b/mozilla/zap/zmk/speex-1.1.10/win32/speexdec/Makefile.am new file mode 100755 index 00000000000..72a5dd874bc --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/win32/speexdec/Makefile.am @@ -0,0 +1,6 @@ +## Process this file with automake to produce Makefile.in. -*-Makefile-*- + +# Disable automatic dependency tracking if using other tools than gcc and gmake +#AUTOMAKE_OPTIONS = no-dependencies + +EXTRA_DIST = speexdec.dsp speexdec.dsw diff --git a/mozilla/zap/zmk/speex-1.1.10/win32/speexdec/Makefile.in b/mozilla/zap/zmk/speex-1.1.10/win32/speexdec/Makefile.in new file mode 100755 index 00000000000..f6771a3480d --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/win32/speexdec/Makefile.in @@ -0,0 +1,322 @@ +# Makefile.in generated by automake 1.8.5 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004 Free Software Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +# Disable automatic dependency tracking if using other tools than gcc and gmake +#AUTOMAKE_OPTIONS = no-dependencies +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +top_builddir = ../.. +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +INSTALL = @INSTALL@ +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +host_triplet = @host@ +subdir = win32/speexdec +DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ + $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = +SOURCES = +DIST_SOURCES = +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +AMDEP_FALSE = @AMDEP_FALSE@ +AMDEP_TRUE = @AMDEP_TRUE@ +AMTAR = @AMTAR@ +AR = @AR@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CXX = @CXX@ +CXXCPP = @CXXCPP@ +CXXDEPMODE = @CXXDEPMODE@ +CXXFLAGS = @CXXFLAGS@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +ECHO = @ECHO@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +F77 = @F77@ +FFLAGS = @FFLAGS@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +LDFLAGS = @LDFLAGS@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +MAINT = @MAINT@ +MAINTAINER_MODE_FALSE = @MAINTAINER_MODE_FALSE@ +MAINTAINER_MODE_TRUE = @MAINTAINER_MODE_TRUE@ +MAKEINFO = @MAKEINFO@ +OBJEXT = @OBJEXT@ +OGG_CFLAGS = @OGG_CFLAGS@ +OGG_LIBS = @OGG_LIBS@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +RANLIB = @RANLIB@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +SIZE16 = @SIZE16@ +SIZE32 = @SIZE32@ +SPEEX_LT_AGE = @SPEEX_LT_AGE@ +SPEEX_LT_CURRENT = @SPEEX_LT_CURRENT@ +SPEEX_LT_REVISION = @SPEEX_LT_REVISION@ +SPEEX_VERSION = @SPEEX_VERSION@ +STRIP = @STRIP@ +VERSION = @VERSION@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_CXX = @ac_ct_CXX@ +ac_ct_F77 = @ac_ct_F77@ +ac_ct_RANLIB = @ac_ct_RANLIB@ +ac_ct_STRIP = @ac_ct_STRIP@ +am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ +am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ +am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ +am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +datadir = @datadir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +src = @src@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +EXTRA_DIST = speexdec.dsp speexdec.dsw +all: all-am + +.SUFFIXES: +$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ + && exit 0; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu win32/speexdec/Makefile'; \ + cd $(top_srcdir) && \ + $(AUTOMAKE) --gnu win32/speexdec/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +distclean-libtool: + -rm -f libtool +uninstall-info-am: +tags: TAGS +TAGS: + +ctags: CTAGS +CTAGS: + + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ + list='$(DISTFILES)'; for file in $$list; do \ + case $$file in \ + $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ + $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ + esac; \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test "$$dir" != "$$file" && test "$$dir" != "."; then \ + dir="/$$dir"; \ + $(mkdir_p) "$(distdir)$$dir"; \ + else \ + dir=''; \ + fi; \ + if test -d $$d/$$file; then \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + fi; \ + cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + else \ + test -f $(distdir)/$$file \ + || cp -p $$d/$$file $(distdir)/$$file \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile +installdirs: +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + `test -z '$(STRIP)' || \ + echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -rm -f $(CONFIG_CLEAN_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-am + -rm -f Makefile +distclean-am: clean-am distclean-generic distclean-libtool + +dvi: dvi-am + +dvi-am: + +html: html-am + +info: info-am + +info-am: + +install-data-am: + +install-exec-am: + +install-info: install-info-am + +install-man: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-info-am + +.PHONY: all all-am check check-am clean clean-generic clean-libtool \ + distclean distclean-generic distclean-libtool distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-exec install-exec-am \ + install-info install-info-am install-man install-strip \ + installcheck installcheck-am installdirs maintainer-clean \ + maintainer-clean-generic mostlyclean mostlyclean-generic \ + mostlyclean-libtool pdf pdf-am ps ps-am uninstall uninstall-am \ + uninstall-info-am + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/mozilla/zap/zmk/speex-1.1.10/win32/speexdec/speexdec.dsp b/mozilla/zap/zmk/speex-1.1.10/win32/speexdec/speexdec.dsp new file mode 100755 index 00000000000..64fcd462e84 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/win32/speexdec/speexdec.dsp @@ -0,0 +1,130 @@ +# Microsoft Developer Studio Project File - Name="speexdec" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=speexdec - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "speexdec.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "speexdec.mak" CFG="speexdec - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "speexdec - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "speexdec - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "speexdec - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD CPP /nologo /GX /O2 /I "../../libspeex" /I "../../../ogg/include" /I "../../include" /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD BASE RSC /l 0x809 /d "NDEBUG" +# ADD RSC /l 0x809 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib winmm.lib /nologo /subsystem:console /machine:I386 /nodefaultlib:"LIBCMT.lib" + +!ELSEIF "$(CFG)" == "speexdec - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /I "../../libspeex" /I "../../../ogg/include" /I "../../include" /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD BASE RSC /l 0x809 /d "_DEBUG" +# ADD RSC /l 0x809 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib winmm.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "speexdec - Win32 Release" +# Name "speexdec - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=..\..\src\getopt.c +# End Source File +# Begin Source File + +SOURCE=..\..\src\getopt1.c +# End Source File +# Begin Source File + +SOURCE=..\..\src\speexdec.c +# End Source File +# Begin Source File + +SOURCE=..\..\src\wav_io.c +# End Source File +# Begin Source File + +SOURCE=..\..\src\wave_out.c +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Source File + +SOURCE=..\..\src\getopt_win.h +# End Source File +# Begin Source File + +SOURCE=..\..\src\wav_io.h +# End Source File +# Begin Source File + +SOURCE=..\..\src\wave_out.h +# End Source File +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# End Group +# End Target +# End Project diff --git a/mozilla/zap/zmk/speex-1.1.10/win32/speexdec/speexdec.dsw b/mozilla/zap/zmk/speex-1.1.10/win32/speexdec/speexdec.dsw new file mode 100755 index 00000000000..37f2d1f2139 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/win32/speexdec/speexdec.dsw @@ -0,0 +1,59 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "libspeex"=..\libspeex\libspeex.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "ogg_static"="..\..\..\MYOV-1.0\ogg\win32\ogg_static.dsp" - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "speexdec"=.\speexdec.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name libspeex + End Project Dependency + Begin Project Dependency + Project_Dep_Name ogg_static + End Project Dependency +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git a/mozilla/zap/zmk/speex-1.1.10/win32/speexenc/Makefile.am b/mozilla/zap/zmk/speex-1.1.10/win32/speexenc/Makefile.am new file mode 100755 index 00000000000..e55214c3f62 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/win32/speexenc/Makefile.am @@ -0,0 +1,6 @@ +## Process this file with automake to produce Makefile.in. -*-Makefile-*- + +# Disable automatic dependency tracking if using other tools than gcc and gmake +#AUTOMAKE_OPTIONS = no-dependencies + +EXTRA_DIST = speexenc.dsp speexenc.dsw diff --git a/mozilla/zap/zmk/speex-1.1.10/win32/speexenc/Makefile.in b/mozilla/zap/zmk/speex-1.1.10/win32/speexenc/Makefile.in new file mode 100755 index 00000000000..cb128ad83ea --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/win32/speexenc/Makefile.in @@ -0,0 +1,322 @@ +# Makefile.in generated by automake 1.8.5 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004 Free Software Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +# Disable automatic dependency tracking if using other tools than gcc and gmake +#AUTOMAKE_OPTIONS = no-dependencies +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +top_builddir = ../.. +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +INSTALL = @INSTALL@ +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +host_triplet = @host@ +subdir = win32/speexenc +DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ + $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = +SOURCES = +DIST_SOURCES = +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +AMDEP_FALSE = @AMDEP_FALSE@ +AMDEP_TRUE = @AMDEP_TRUE@ +AMTAR = @AMTAR@ +AR = @AR@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CXX = @CXX@ +CXXCPP = @CXXCPP@ +CXXDEPMODE = @CXXDEPMODE@ +CXXFLAGS = @CXXFLAGS@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +ECHO = @ECHO@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +F77 = @F77@ +FFLAGS = @FFLAGS@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +LDFLAGS = @LDFLAGS@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +MAINT = @MAINT@ +MAINTAINER_MODE_FALSE = @MAINTAINER_MODE_FALSE@ +MAINTAINER_MODE_TRUE = @MAINTAINER_MODE_TRUE@ +MAKEINFO = @MAKEINFO@ +OBJEXT = @OBJEXT@ +OGG_CFLAGS = @OGG_CFLAGS@ +OGG_LIBS = @OGG_LIBS@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +RANLIB = @RANLIB@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +SIZE16 = @SIZE16@ +SIZE32 = @SIZE32@ +SPEEX_LT_AGE = @SPEEX_LT_AGE@ +SPEEX_LT_CURRENT = @SPEEX_LT_CURRENT@ +SPEEX_LT_REVISION = @SPEEX_LT_REVISION@ +SPEEX_VERSION = @SPEEX_VERSION@ +STRIP = @STRIP@ +VERSION = @VERSION@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_CXX = @ac_ct_CXX@ +ac_ct_F77 = @ac_ct_F77@ +ac_ct_RANLIB = @ac_ct_RANLIB@ +ac_ct_STRIP = @ac_ct_STRIP@ +am__fastdepCC_FALSE = @am__fastdepCC_FALSE@ +am__fastdepCC_TRUE = @am__fastdepCC_TRUE@ +am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@ +am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +datadir = @datadir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +src = @src@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +EXTRA_DIST = speexenc.dsp speexenc.dsw +all: all-am + +.SUFFIXES: +$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ + && exit 0; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu win32/speexenc/Makefile'; \ + cd $(top_srcdir) && \ + $(AUTOMAKE) --gnu win32/speexenc/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +distclean-libtool: + -rm -f libtool +uninstall-info-am: +tags: TAGS +TAGS: + +ctags: CTAGS +CTAGS: + + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \ + list='$(DISTFILES)'; for file in $$list; do \ + case $$file in \ + $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \ + $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \ + esac; \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test "$$dir" != "$$file" && test "$$dir" != "."; then \ + dir="/$$dir"; \ + $(mkdir_p) "$(distdir)$$dir"; \ + else \ + dir=''; \ + fi; \ + if test -d $$d/$$file; then \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ + fi; \ + cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ + else \ + test -f $(distdir)/$$file \ + || cp -p $$d/$$file $(distdir)/$$file \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile +installdirs: +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + `test -z '$(STRIP)' || \ + echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -rm -f $(CONFIG_CLEAN_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-am + -rm -f Makefile +distclean-am: clean-am distclean-generic distclean-libtool + +dvi: dvi-am + +dvi-am: + +html: html-am + +info: info-am + +info-am: + +install-data-am: + +install-exec-am: + +install-info: install-info-am + +install-man: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-info-am + +.PHONY: all all-am check check-am clean clean-generic clean-libtool \ + distclean distclean-generic distclean-libtool distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-exec install-exec-am \ + install-info install-info-am install-man install-strip \ + installcheck installcheck-am installdirs maintainer-clean \ + maintainer-clean-generic mostlyclean mostlyclean-generic \ + mostlyclean-libtool pdf pdf-am ps ps-am uninstall uninstall-am \ + uninstall-info-am + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/mozilla/zap/zmk/speex-1.1.10/win32/speexenc/speexenc.dsp b/mozilla/zap/zmk/speex-1.1.10/win32/speexenc/speexenc.dsp new file mode 100755 index 00000000000..4b9dd89681c --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/win32/speexenc/speexenc.dsp @@ -0,0 +1,122 @@ +# Microsoft Developer Studio Project File - Name="speexenc" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=speexenc - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "speexenc.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "speexenc.mak" CFG="speexenc - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "speexenc - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "speexenc - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "speexenc - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD CPP /nologo /GX /Ox /Ot /Og /Oi /Ob2 /I "../../libspeex" /I "../../../ogg/include" /I "../../include" /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD BASE RSC /l 0x809 /d "NDEBUG" +# ADD RSC /l 0x809 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 /nodefaultlib:"LIBCMT.lib" + +!ELSEIF "$(CFG)" == "speexenc - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /I "../../libspeex" /I "../../../ogg/include" /I "../../include" /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD BASE RSC /l 0x809 /d "_DEBUG" +# ADD RSC /l 0x809 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "speexenc - Win32 Release" +# Name "speexenc - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=..\..\src\getopt.c +# End Source File +# Begin Source File + +SOURCE=..\..\src\getopt1.c +# End Source File +# Begin Source File + +SOURCE=..\..\src\speexenc.c +# End Source File +# Begin Source File + +SOURCE=..\..\src\wav_io.c +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Source File + +SOURCE=..\..\src\getopt_win.h +# End Source File +# Begin Source File + +SOURCE=..\..\src\wav_io.h +# End Source File +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# End Group +# End Target +# End Project diff --git a/mozilla/zap/zmk/speex-1.1.10/win32/speexenc/speexenc.dsw b/mozilla/zap/zmk/speex-1.1.10/win32/speexenc/speexenc.dsw new file mode 100755 index 00000000000..55aa72dbd83 --- /dev/null +++ b/mozilla/zap/zmk/speex-1.1.10/win32/speexenc/speexenc.dsw @@ -0,0 +1,59 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "libspeex"=..\libspeex\libspeex.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "ogg_static"="..\..\..\MYOV-1.0\ogg\win32\ogg_static.dsp" - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "speexenc"=.\speexenc.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name libspeex + End Project Dependency + Begin Project Dependency + Project_Dep_Name ogg_static + End Project Dependency +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git a/mozilla/zap/zmk/src/Makefile.in b/mozilla/zap/zmk/src/Makefile.in new file mode 100644 index 00000000000..c299d781eac --- /dev/null +++ b/mozilla/zap/zmk/src/Makefile.in @@ -0,0 +1,79 @@ +DEPTH = ../../.. +topsrcdir = @top_srcdir@ +srcdir = @srcdir@ +VPATH = @srcdir@ + +include $(DEPTH)/config/autoconf.mk + +MODULE = zmk +XPIDL_MODULE = zmk +LIBRARY_NAME = zmk +EXPORT_LIBRARY = 1 +IS_COMPONENT = 1 +MODULE_NAME = zapMediaKitModule +MOZILLA_INTERNAL_API = 1 + +REQUIRES = \ + xpcom \ + string \ + necko \ + zap_base \ + portaudio_v18_1 \ + $(NULL) + +CPPSRCS = \ + zapMediaGraph.cpp \ + zapMediaFrame.cpp \ + zapAudioDeviceManager.cpp \ + zapAudioDevice.cpp \ + zapAudioStreamUtils.cpp \ + zapAudioOut.cpp \ + zapAudioIn.cpp \ + zapMediaModule.cpp \ + zapPacketBuffer.cpp \ + zapFilterNode.cpp \ + zapSpeexEncoder.cpp \ + zapSpeexDecoder.cpp \ + zapUDPSocket.cpp \ + zapUDPSocketPair.cpp \ + zapDatagramFrame.cpp \ + zapRTPFrame.cpp \ + zapSpeexRTPPacketizer.cpp \ + zapSpeexRTPDepacketizer.cpp \ + zapRTPTransmitter.cpp \ + zapRTPReceiver.cpp \ + zapRTPSession.cpp \ + $(NULL) + +XPIDLSRCS = zapIMediaGraph.idl \ + zapIMediaNode.idl \ + zapIMediaSource.idl \ + zapIMediaSink.idl \ + zapIMediaFrame.idl \ + zapIAudioDeviceManager.idl \ + zapIAudioIn.idl \ + zapIAudioOut.idl \ + zapIAudioDevice.idl \ + zapIPortaudioDevice.idl \ + zapISpeexEncoder.idl \ + zapIRTPFrame.idl \ + zapIUDPSocket.idl \ + zapIUDPSocketPair.idl \ + $(NULL) + +SHARED_LIBRARY_LIBS += \ + $(DIST)/lib/$(LIB_PREFIX)moz_portaudio_v18_1.$(LIB_SUFFIX) \ + $(DIST)/lib/$(LIB_PREFIX)moz_speex_v1_1_10.$(LIB_SUFFIX) \ + $(NULL) + +ifeq ($(OS_ARCH),WINNT) +OS_LIBS += dsound.lib winmm.lib +endif + +include $(topsrcdir)/config/rules.mk + +EXTRA_DSO_LDOPTS += $(MOZ_COMPONENT_LIBS) + +INCLUDES += \ + -I$(srcdir)/../speex-1.1.10/include \ + $(NULL) diff --git a/mozilla/zap/zmk/src/test.js b/mozilla/zap/zmk/src/test.js new file mode 100644 index 00000000000..162dea189d2 --- /dev/null +++ b/mozilla/zap/zmk/src/test.js @@ -0,0 +1,52 @@ +Components.utils.importModule("resource:/jscodelib/zap/ClassUtils.js"); + +var adev = Components.classes["@mozilla.org/zap/audiodevicemanager;1"].getService(Components.interfaces.zapIAudioDeviceManager); + +var dev0 = adev.getDeviceAt(0).QueryInterface(Components.interfaces.zapIPortaudioDevice); +var dev1 = adev.getDeviceAt(1); +var dev2 = adev.getDeviceAt(2); +var dev3 = adev.getDeviceAt(3); + +var g = Components.classes["@mozilla.org/zap/mediagraph;1"].createInstance(Components.interfaces.zapIMediaGraph); + +var PB = makePropertyBag; + +//var a = g.addNode("testsource", null); +var ain= g.addNode("audioin", PB({$device:dev0})); +var aout = g.addNode("audioout", PB({$device:dev2})); +var inp = g.getNode(ain, Components.interfaces.zapIAudioIn, true); +var enc = g.addNode("speex-encoder", PB({$sample_rate:8000})); +var enc_ctl = g.getNode(enc, Components.interfaces.zapISpeexEncoder, true); +var dec = g.addNode("speex-decoder", PB({$sample_rate:32000})); +var buf = g.addNode("buffer", PB({$prefill_size:2, $max_size:10})); +var speex2rtp = g.addNode("speex2rtp-converter", null); +var rtp2speex = g.addNode("rtp2speex-converter", null); +//var udp6060 = g.addNode("udp-socket", PB({$port:6060})); +//var udp6061 = g.addNode("udp-socket", PB({$port:6061})); + +/* + + +----+ +----+ +----+ +----+ +----+ + |ain |----->|enc |----->|dec |----->|buf |----->|aout| + +----+ A +----+ B +----+ C +----+ D +----+ +*/ + +var A = g.connect(ain, PB({$frame_duration:0.02, $sample_rate:8000, $sample_format:"float32_32768"}), enc, null); +var B = g.connect(enc, null, speex2rtp, null); +var C = g.connect(speex2rtp, null, buf, null); +var D = g.connect(buf, null, rtp2speex, null); +var E = g.connect(rtp2speex, null, dec, null); +var F = g.connect(dec, null, aout, null); + + +//var A = g.connect(udp6060, null, buf, null); +//var B = g.connect(buf, null, udp6061, null); + +// var ain2= g.addNode("audioin", null); +// var aout2 = g.addNode("audioout", null); +// var inp2 = g.getNode(ain2, Components.interfaces.zapIAudioIn, true); +// var buf2 = g.addNode("buffer", makePropertyBag({$prefill_size:70})); +// var C = g.connect(ain2, null, buf2, null); +// var D = g.connect(buf2, null, aout2, null); + + diff --git a/mozilla/zap/zmk/src/test2.js b/mozilla/zap/zmk/src/test2.js new file mode 100644 index 00000000000..69fa1287fb0 --- /dev/null +++ b/mozilla/zap/zmk/src/test2.js @@ -0,0 +1,39 @@ +Components.utils.importModule("resource:/jscodelib/zap/ClassUtils.js"); + +var adev = Components.classes["@mozilla.org/zap/audiodevicemanager;1"].getService(Components.interfaces.zapIAudioDeviceManager); + +var dev0 = adev.getDeviceAt(0).QueryInterface(Components.interfaces.zapIPortaudioDevice); +var dev1 = adev.getDeviceAt(1); +var dev2 = adev.getDeviceAt(2); +var dev3 = adev.getDeviceAt(3); + +var g = Components.classes["@mozilla.org/zap/mediagraph;1"].createInstance(Components.interfaces.zapIMediaGraph); + +var PB = makePropertyBag; + +var ain= g.addNode("audioin", PB({$device:dev0})); +var aout = g.addNode("audioout", PB({$device:dev2})); +var inp = g.getNode(ain, Components.interfaces.zapIAudioIn, true); +var enc = g.addNode("speex-encoder", PB({$sample_rate:32000})); +var enc_ctl = g.getNode(enc, Components.interfaces.zapISpeexEncoder, true); +var dec = g.addNode("speex-decoder", PB({$sample_rate:32000})); +var buf1 = g.addNode("buffer", PB({$prefill_size:2, $max_size:10})); +var buf2 = g.addNode("buffer", PB({$prefill_size:2, $max_size:10})); +var speex2rtp = g.addNode("speex2rtp-converter", null); +var rtp2speex = g.addNode("rtp2speex-converter", null); +var udp1 = g.addNode("udp-socket-pair", PB({$portbase:6060})); +var udp2 = g.addNode("udp-socket-pair", PB({$portbase:6060})); +var udp2_ctl = g.getNode(udp2, Components.interfaces.zapIUDPSocketPair, true); +var rtpsession = g.addNode("rtp-session", PB({$address:"127.0.0.1", $port:udp2_ctl.portA})); + +var A = g.connect(ain, PB({$sample_rate:32000}), enc, null); +var B = g.connect(enc, null, speex2rtp, null); +var C = g.connect(speex2rtp, null, rtpsession, PB({$name:"local-rtp"})); +var D = g.connect(rtpsession, PB({$name:"remote-rtp"}), buf1, null); +var E = g.connect(buf1, null, udp1, PB({$name:"socket-a"})); + +var F = g.connect(udp2, PB({$name:"socket-a"}), buf2, null); +var G = g.connect(buf2, null, rtpsession, PB({$name:"remote-rtp"})); +var H = g.connect(rtpsession, PB({$name:"local-rtp"}), rtp2speex, null); +var I = g.connect(rtp2speex, null, dec, null); +var J = g.connect(dec, null, aout, null); diff --git a/mozilla/zap/zmk/src/zapAudioDevice.cpp b/mozilla/zap/zmk/src/zapAudioDevice.cpp new file mode 100644 index 00000000000..b26847e50a5 --- /dev/null +++ b/mozilla/zap/zmk/src/zapAudioDevice.cpp @@ -0,0 +1,118 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "zapAudioDevice.h" +#include "stdio.h" +#include "nsString.h" + +//////////////////////////////////////////////////////////////////////// +// zapAudioDevice + +zapAudioDevice::zapAudioDevice(PRInt32 index) + : mDeviceInfo(nsnull), + mDeviceID(index) +{ + // keep a hold on portaudio until we die: + Pa_Initialize(); +} + +zapAudioDevice::~zapAudioDevice() +{ + Pa_Terminate(); +} + +//---------------------------------------------------------------------- +// nsISupports methods: + +NS_IMPL_ADDREF(zapAudioDevice) +NS_IMPL_RELEASE(zapAudioDevice) + +NS_INTERFACE_MAP_BEGIN(zapAudioDevice) + NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, zapIAudioDevice) + NS_INTERFACE_MAP_ENTRY(zapIAudioDevice) + NS_INTERFACE_MAP_ENTRY(zapIPortaudioDevice) +NS_INTERFACE_MAP_END + +//---------------------------------------------------------------------- +// zapIAudioDevice methods: + +/* readonly attribute ACString name; */ +NS_IMETHODIMP +zapAudioDevice::GetName(nsACString & aName) +{ + aName = nsDependentCString(GetDeviceInfo()->name); + return NS_OK; +} + +/* readonly attribute unsigned long maxInputChannels; */ +NS_IMETHODIMP +zapAudioDevice::GetMaxInputChannels(PRUint32 *aMaxInputChannels) +{ + *aMaxInputChannels = GetDeviceInfo()->maxInputChannels; + return NS_OK; +} + +/* readonly attribute unsigned long maxOutputChannels; */ +NS_IMETHODIMP +zapAudioDevice::GetMaxOutputChannels(PRUint32 *aMaxOutputChannels) +{ + *aMaxOutputChannels = GetDeviceInfo()->maxOutputChannels; + return NS_OK; +} + +//---------------------------------------------------------------------- +// zapIPortaudioDevice methods: + +/* readonly attribute PRInt32 deviceID; */ +NS_IMETHODIMP +zapAudioDevice::GetDeviceID(PRInt32 *aDeviceID) +{ + *aDeviceID = mDeviceID; + return NS_OK; +} + + +//---------------------------------------------------------------------- +// implementation helpers: + +const PaDeviceInfo* +zapAudioDevice::GetDeviceInfo() { + if (!mDeviceInfo) { + mDeviceInfo = Pa_GetDeviceInfo(mDeviceID); + NS_ASSERTION(mDeviceInfo, "uh-oh. no device info"); + } + return mDeviceInfo; +} diff --git a/mozilla/zap/zmk/src/zapAudioDevice.h b/mozilla/zap/zmk/src/zapAudioDevice.h new file mode 100644 index 00000000000..02f99df94cf --- /dev/null +++ b/mozilla/zap/zmk/src/zapAudioDevice.h @@ -0,0 +1,71 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#ifndef __ZAP_AUDIODEVICE_H__ +#define __ZAP_AUDIODEVICE_H__ + +#include "zapIAudioDevice.h" +#include "zapIPortaudioDevice.h" +#include "nsAutoPtr.h" +#include "portaudio.h" + +class zapAudioDevice : public zapIAudioDevice, + public zapIPortaudioDevice +{ +public: + zapAudioDevice(PRInt32 index); + ~zapAudioDevice(); + + NS_DECL_ISUPPORTS + NS_DECL_ZAPIAUDIODEVICE + NS_DECL_ZAPIPORTAUDIODEVICE + +private: + const PaDeviceInfo* GetDeviceInfo(); + const PaDeviceInfo* mDeviceInfo; + PaDeviceID mDeviceID; +}; + +//---------------------------------------------------------------------- +// helper to create an add-refed audio device object: +inline zapIAudioDevice * +CreateAudioDevice(PRInt32 index) { + zapIAudioDevice* device = new zapAudioDevice(index); + NS_IF_ADDREF(device); + return device; +} + +#endif // __ZAP_AUDIODEVICE_H__ diff --git a/mozilla/zap/zmk/src/zapAudioDeviceManager.cpp b/mozilla/zap/zmk/src/zapAudioDeviceManager.cpp new file mode 100644 index 00000000000..86af7cf36b0 --- /dev/null +++ b/mozilla/zap/zmk/src/zapAudioDeviceManager.cpp @@ -0,0 +1,121 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "zapAudioDeviceManager.h" +#include "zapAudioDevice.h" +#include "portaudio.h" +#include "stdio.h" + +//////////////////////////////////////////////////////////////////////// +// zapAudioDeviceManager + +zapAudioDeviceManager::zapAudioDeviceManager() +{ + PaError err; + if ((err = Pa_Initialize()) != paNoError) { +#ifdef DEBUG + printf("Failed to initialize portaudio: %s\n", Pa_GetErrorText(err)); +#endif + } +} + +zapAudioDeviceManager::~zapAudioDeviceManager() +{ + Pa_Terminate(); +} + +//---------------------------------------------------------------------- +// nsISupports methods: + +NS_IMPL_ADDREF(zapAudioDeviceManager) +NS_IMPL_RELEASE(zapAudioDeviceManager) + +NS_INTERFACE_MAP_BEGIN(zapAudioDeviceManager) + NS_INTERFACE_MAP_ENTRY(nsISupports) + NS_INTERFACE_MAP_ENTRY(zapIAudioDeviceManager) +NS_INTERFACE_MAP_END + +//---------------------------------------------------------------------- +// zapIAudioDeviceManager methods: + +/* readonly attribute zapIAudioDevice defaultInputDevice; */ +NS_IMETHODIMP +zapAudioDeviceManager::GetDefaultInputDevice(zapIAudioDevice * *aDefaultInputDevice) +{ + PaDeviceID id = Pa_GetDefaultInputDeviceID(); + if (id == paNoDevice) { + *aDefaultInputDevice = nsnull; + return NS_ERROR_FAILURE; + } + + *aDefaultInputDevice = CreateAudioDevice(id); + return NS_OK; +} + +/* readonly attribute zapIAudioDevice defaultOutputDevice; */ +NS_IMETHODIMP +zapAudioDeviceManager::GetDefaultOutputDevice(zapIAudioDevice * *aDefaultOutputDevice) +{ + PaDeviceID id = Pa_GetDefaultOutputDeviceID(); + if (id == paNoDevice) { + *aDefaultOutputDevice = nsnull; + return NS_ERROR_FAILURE; + } + + *aDefaultOutputDevice = CreateAudioDevice(id); + return NS_OK; +} + +/* readonly attribute unsigned long deviceCount; */ +NS_IMETHODIMP +zapAudioDeviceManager::GetDeviceCount(PRUint32 *aDeviceCount) +{ + *aDeviceCount = Pa_CountDevices(); + return NS_OK; +} + +/* zapIAudioDevice getDeviceAt (in unsigned long pos); */ +NS_IMETHODIMP +zapAudioDeviceManager::GetDeviceAt(PRUint32 pos, zapIAudioDevice **_retval) +{ + if (pos < 0 || pos >= Pa_CountDevices()) { + *_retval = nsnull; + return NS_ERROR_FAILURE; + } + + *_retval = CreateAudioDevice(pos); + return NS_OK; +} diff --git a/mozilla/zap/zmk/src/zapAudioDeviceManager.h b/mozilla/zap/zmk/src/zapAudioDeviceManager.h new file mode 100644 index 00000000000..77e2f8dcdc3 --- /dev/null +++ b/mozilla/zap/zmk/src/zapAudioDeviceManager.h @@ -0,0 +1,55 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#ifndef __ZAP_AUDIODEVICEMANAGER_H__ +#define __ZAP_AUDIODEVICEMANAGER_H__ + +#include "zapIAudioDeviceManager.h" + +//////////////////////////////////////////////////////////////////////// +// zapAudioDeviceManager + +class zapAudioDeviceManager : public zapIAudioDeviceManager +{ +public: + zapAudioDeviceManager(); + ~zapAudioDeviceManager(); + + NS_DECL_ISUPPORTS + NS_DECL_ZAPIAUDIODEVICEMANAGER +}; + +#endif // __ZAP_AUDIODEVICEMANAGER_H__ diff --git a/mozilla/zap/zmk/src/zapAudioIn.cpp b/mozilla/zap/zmk/src/zapAudioIn.cpp new file mode 100644 index 00000000000..e6f72fa25bc --- /dev/null +++ b/mozilla/zap/zmk/src/zapAudioIn.cpp @@ -0,0 +1,789 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "zapAudioIn.h" +#include "stdio.h" +#include "nsString.h" +#include "zapMediaFrame.h" +#include "zapAudioDevice.h" +#include "nsIProxyObjectManager.h" +#include "nsAutoLock.h" +#include "nsHashPropertyBag.h" + +//////////////////////////////////////////////////////////////////////// +// zapAudioIn + +zapAudioIn::zapAudioIn() + : mStream(nsnull), + mState(zapAudioIn_PLAY_IDLE_CLOSED::Instance()), + mKeepRunning(PR_FALSE) +{ + mCallbackLock = PR_NewLock(); + + PaError err; + if ((err = Pa_Initialize()) != paNoError) { +#ifdef DEBUG + printf("Failed to initialize portaudio: %s\n", Pa_GetErrorText(err)); +#endif + } + +#ifdef DEBUG + printf("zapAudioIn::zapAudioIn()\n"); +#endif +} + +zapAudioIn::~zapAudioIn() +{ + PR_DestroyLock(mCallbackLock); + + NS_ASSERTION(!mStream, "stream still running"); + + Pa_Terminate(); +#ifdef DEBUG + printf("zapAudioIn::~zapAudioIn()\n"); +#endif +} + +//---------------------------------------------------------------------- +// nsISupports methods: + +NS_IMPL_ADDREF(zapAudioIn) +NS_IMPL_RELEASE(zapAudioIn) + +NS_INTERFACE_MAP_BEGIN(zapAudioIn) + NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, zapIMediaNode) + NS_INTERFACE_MAP_ENTRY(zapIMediaNode) + NS_INTERFACE_MAP_ENTRY(zapIMediaSource) + NS_INTERFACE_MAP_ENTRY(zapIAudioIn) +NS_INTERFACE_MAP_END + +//---------------------------------------------------------------------- +// zapIMediaNode methods: + +/* void addedToGraph (in zapIMediaGraph graph, in ACString id, in nsIPropertyBag2 node_pars); */ +NS_IMETHODIMP +zapAudioIn::AddedToGraph(zapIMediaGraph *graph, + const nsACString & id, + nsIPropertyBag2* node_pars) +{ + graph->GetEventQueue(getter_AddRefs(mEventQ)); + + // node parameter defaults: + mInputDevice = Pa_GetDefaultInputDeviceID(); + // unpack node parameters: + if (node_pars) { + nsCOMPtr device; + node_pars->GetPropertyAsInterface(NS_LITERAL_STRING("device"), + NS_GET_IID(zapIPortaudioDevice), + getter_AddRefs(device)); + if (device) { + device->GetDeviceID(&mInputDevice); + } + } +#ifdef DEBUG + printf("(audioin using device %d)", mInputDevice); +#endif + return NS_OK; +} + +/* void removedFromGraph (in zapIMediaGraph graph); */ +NS_IMETHODIMP +zapAudioIn::RemovedFromGraph(zapIMediaGraph *graph) +{ + return NS_OK; +} + +/* zapIMediaSource getSource (in nsIPropertyBag2 source_pars); */ +NS_IMETHODIMP +zapAudioIn::GetSource(nsIPropertyBag2 *source_pars, zapIMediaSource **_retval) +{ + if (mSink) { + NS_ERROR("already connected"); + return NS_ERROR_FAILURE; + } + + // source parameter defaults: + mSampleRate = 8000; // 8000Hz + mFrameDuration = 0.02; // 20ms + mNumChannels = 1; // mono + mSampleFormat = sf_float32_32768; + + // unpack source parameters: + if (source_pars) { + source_pars->GetPropertyAsDouble(NS_LITERAL_STRING("sample_rate"), + &mSampleRate); + source_pars->GetPropertyAsDouble(NS_LITERAL_STRING("frame_duration"), + &mFrameDuration); + source_pars->GetPropertyAsUint32(NS_LITERAL_STRING("channels"), + &mNumChannels); + nsCString sampleformat_string; + if (NS_SUCCEEDED(source_pars->GetPropertyAsACString(NS_LITERAL_STRING("sample_format"), + sampleformat_string))) { + mSampleFormat = StrToZapAudioSampleFormat(sampleformat_string); + if (mSampleFormat == sf_unknown) { + NS_ERROR("unknown sample format"); + return NS_ERROR_FAILURE; + } + } + } + + mSamplesPerFrame = (PRUint32)(mSampleRate*mFrameDuration*mNumChannels); + + *_retval = this; + NS_ADDREF(*_retval); + return NS_OK; +} + +/* zapIMediaSink getSink (in nsIPropertyBag2 sink_pars); */ +NS_IMETHODIMP +zapAudioIn::GetSink(nsIPropertyBag2 *sink_pars, zapIMediaSink **_retval) +{ + NS_ERROR("audioin is a source-only node"); + return NS_ERROR_FAILURE; +} + +//---------------------------------------------------------------------- +// zapIMediaSource methods: + +/* void connectSink (in zapIMediaSink sink, in ACString connection_id); */ +NS_IMETHODIMP +zapAudioIn::ConnectSink(zapIMediaSink *sink, + const nsACString & connection_id) +{ + return mState->ConnectSink(this, sink, connection_id); +} + +/* void disconnectSink (in zapIMediaSink sink, in ACString connection_id); */ +NS_IMETHODIMP +zapAudioIn::DisconnectSink(zapIMediaSink *sink, + const nsACString & connection_id) +{ + return mState->DisconnectSink(this, sink, connection_id); +} + +/* void requestFrame (); */ +NS_IMETHODIMP +zapAudioIn::RequestFrame() +{ + return mState->RequestFrame(this); +} + +//---------------------------------------------------------------------- +// zapIAudioIn methods: + +/* void play (); */ +NS_IMETHODIMP +zapAudioIn::Play() +{ + return mState->Play(this); +} + +/* void stop (); */ +NS_IMETHODIMP +zapAudioIn::Stop() +{ + return mState->Stop(this); +} + +/* readonly attribute zapIAudioDevice defaultInputDevice; */ +NS_IMETHODIMP +zapAudioIn::GetDefaultInputDevice(zapIAudioDevice * *aDefaultInputDevice) +{ + PaDeviceID id = Pa_GetDefaultInputDeviceID(); + if (id == paNoDevice) { + *aDefaultInputDevice = nsnull; + return NS_ERROR_FAILURE; + } + + *aDefaultInputDevice = CreateAudioDevice(id); + return NS_OK; +} + +//---------------------------------------------------------------------- +// portaudio audio source callback: + +class zapAudioInSendEvent : public PLEvent +{ +public: + zapAudioInSendEvent(zapAudioIn* audioin) + { + PL_InitEvent(this, audioin, EventHandler, EventCleanup); + } + + PR_STATIC_CALLBACK(void *) EventHandler(PLEvent* ev) + { + zapAudioInSendEvent* rev = (zapAudioInSendEvent*) ev; + zapAudioIn* audioin = (zapAudioIn*) ev->owner; + + audioin->SendFrame(rev->data, rev->timestamp); + + return (void*)PR_TRUE; + } + + PR_STATIC_CALLBACK(void) EventCleanup(PLEvent* ev) + { + delete (zapAudioInSendEvent*) ev; + } + + nsCString data; + double timestamp; +}; + + +int AudioInCallback(void* inputBuffer, void* outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void* userData) +{ +#ifdef DEBUG +// printf("{"); +#endif + + zapAudioIn* audioin = (zapAudioIn*)userData; + + nsAutoLock lock(audioin->mCallbackLock); + + if (!audioin->mKeepRunning) { +#ifdef DEBUG + printf("(audioin cb stopped)}"); +#endif + return 1; // stop stream + } + + // Post the frame. We need to do this synchronously to pace the callback. + audioin->mEventQ->EnterMonitor(); + // Unlock the callback lock, so that the stream can be closed while + // we're waiting for the event. It is important to do this AFTER + // entering the eventQ monitor but BEFORE posting, to coordinate the + // request revocation in CloseStream() + lock.unlock(); + zapAudioInSendEvent* ev = new zapAudioInSendEvent(audioin); + PRUint32 bufferLength = audioin->mSamplesPerFrame * GetPortAudioSampleSize(audioin->mSampleFormat); + ev->data.SetLength(bufferLength); + memcpy(ev->data.BeginWriting(), inputBuffer, bufferLength); + ev->timestamp = outTime; + + void* result; + audioin->mEventQ->PostSynchronousEvent(ev, &result); + audioin->mEventQ->ExitMonitor(); + +#ifdef DEBUG +// printf("}"); +#endif + return 0; +} + +//---------------------------------------------------------------------- +// Implementation helpers: + +void zapAudioIn::ChangeState(zapAudioInState* state) +{ + mState = state; +} + +nsresult zapAudioIn::StartStream() +{ + NS_ASSERTION(!mStream, "stream still running"); + + // Create a new streaminfo. We can't just implement nsIPropertyBag2 + // on zapAudioIn, because packets and their associated streaminfo + // might be buffered elsewhere in the graph while we are already + // busy on the next stream. + nsCOMPtr bag; + NS_NewHashPropertyBag(getter_AddRefs(bag)); + mStreamInfo = do_QueryInterface(bag); + + mStreamInfo->SetPropertyAsACString(NS_LITERAL_STRING("type"), + NS_LITERAL_CSTRING("audio")); + mStreamInfo->SetPropertyAsDouble(NS_LITERAL_STRING("sample_rate"), + mSampleRate); + mStreamInfo->SetPropertyAsDouble(NS_LITERAL_STRING("frame_duration"), + mFrameDuration); + mStreamInfo->SetPropertyAsUint32(NS_LITERAL_STRING("channels"), + mNumChannels); + + nsCString format_string; + ZapAudioSampleFormatToStr(mSampleFormat, format_string); + mStreamInfo->SetPropertyAsACString(NS_LITERAL_STRING("sample_format"), + format_string); + // No need to lock mCallbackLock; callback isn't running + mKeepRunning = PR_TRUE; + + PaError err = Pa_OpenStream(&mStream, + mInputDevice, mNumChannels, + ZapAudioSampleFormatToPaFormat(mSampleFormat), nsnull, + paNoDevice, 0, 0, nsnull, + mSampleRate, mSamplesPerFrame/mNumChannels, 1, + paNoFlag, + AudioInCallback, this); + + if (err != paNoError) { +#ifdef DEBUG + printf("Failed to open portaudio input stream: %s\n", Pa_GetErrorText(err)); +#endif + mKeepRunning = PR_FALSE; + return NS_ERROR_FAILURE; + } + + Pa_StartStream(mStream); + return NS_OK; +} + +void zapAudioIn::CloseStream() +{ + NS_ASSERTION(mStream, "stream not running"); + + // make sure that callback will stop the stream if it starts running + // from now on: + nsAutoLock lock(mCallbackLock); + mKeepRunning = PR_FALSE; + lock.unlock(); + // cancel any outstanding SendFrame() notifications: + mEventQ->EnterMonitor(); + mEventQ->RevokeEvents(this); + mEventQ->ExitMonitor(); + + Pa_CloseStream(mStream); + mStream = nsnull; +#ifdef DEBUG + printf("(audioin stream closed)"); +#endif +} + +void zapAudioIn::SendFrame(const nsACString& data, double timestamp) +{ + // Create frame: + zapMediaFrame* frame = new zapMediaFrame(); + frame->AddRef(); + + if (mSampleFormat == sf_float32_32768) { + // convert from int16 to float: + nsCString fdata; + fdata.SetLength(mSamplesPerFrame * GetZapAudioSampleSize(mSampleFormat)); + float* d = (float*)fdata.BeginWriting(); + nsACString::const_iterator p; + data.BeginReading(p); + PRInt16* s = (PRInt16*)p.get(); + for (int i=0; imData = fdata; + } + else { + // portaudio format maps directly onto zmk audio stream format + frame->mData = data; + } + frame->mStreamInfo = mStreamInfo; + frame->mTimestamp = (PRUint32)timestamp; + + mState->SendFrame(this, frame); + frame->Release(); +} + +//////////////////////////////////////////////////////////////////////// +// zapAudioInState implementation + +nsresult zapAudioInState::ConnectSink(zapAudioIn* audioin, zapIMediaSink* sink, + const nsACString& connection_id) +{ +#ifdef DEBUG + printf("zapAudioInState::ConnectSink: protocol error in state %s\n", GetName()); +#endif + return NS_ERROR_FAILURE; +} + +nsresult zapAudioInState::RequestFrame(zapAudioIn* audioin) +{ +#ifdef DEBUG + printf("zapAudioInState::RequestFrame: protocol error in state %s\n", GetName()); +#endif + return NS_ERROR_FAILURE; +} + +void zapAudioInState::SendFrame(zapAudioIn* audioin, zapIMediaFrame* frame) +{ +#ifdef DEBUG + printf("zapAudioInState::SendFrame: protocol error in state %s\n", GetName()); +#endif +} + +void zapAudioInState::ChangeState(zapAudioIn* audioin, zapAudioInState* state) +{ +#ifdef DEBUG + if (!((this == zapAudioIn_PLAY_IDLE_OPEN::Instance() && + state == zapAudioIn_PLAY_WAITING_OPEN::Instance()) || + (this == zapAudioIn_PLAY_WAITING_OPEN::Instance() && + state == zapAudioIn_PLAY_IDLE_OPEN::Instance()))) + printf("(audioin %s->%s)", GetName(), state->GetName()); +#endif + audioin->ChangeState(state); +} + +//////////////////////////////////////////////////////////////////////// +// zapAudioIn_STOP_IDLE_CLOSED implementation + +zapAudioInState* zapAudioIn_STOP_IDLE_CLOSED::Instance() +{ + if (!mInstance) { + mInstance = new zapAudioIn_STOP_IDLE_CLOSED; + } + return mInstance; +} + +zapAudioInState* zapAudioIn_STOP_IDLE_CLOSED::mInstance = nsnull; + +nsresult zapAudioIn_STOP_IDLE_CLOSED::Play(zapAudioIn* audioin) +{ + ChangeState(audioin, zapAudioIn_PLAY_IDLE_CLOSED::Instance()); + return NS_OK; +} + +nsresult zapAudioIn_STOP_IDLE_CLOSED::Stop(zapAudioIn* audioin) +{ + // already stopped + return NS_OK; +} + +nsresult zapAudioIn_STOP_IDLE_CLOSED::ConnectSink(zapAudioIn* audioin, + zapIMediaSink* sink, + const nsACString& connection_id) +{ + NS_ASSERTION(!audioin->mSink, "already connected"); + audioin->mSink = sink; + // stay in state + return NS_OK; +} + +nsresult zapAudioIn_STOP_IDLE_CLOSED::DisconnectSink(zapAudioIn* audioin, + zapIMediaSink *sink, + const nsACString & connection_id) +{ + audioin->mSink = nsnull; + // stay in state + return NS_OK; +} + +nsresult zapAudioIn_STOP_IDLE_CLOSED::RequestFrame(zapAudioIn* audioin) +{ + ChangeState(audioin, zapAudioIn_STOP_WAITING_CLOSED::Instance()); + return NS_OK; +} + + +//////////////////////////////////////////////////////////////////////// +// zapAudioIn_PLAY_IDLE_CLOSED implementation + +zapAudioInState* zapAudioIn_PLAY_IDLE_CLOSED::Instance() +{ + if (!mInstance) { + mInstance = new zapAudioIn_PLAY_IDLE_CLOSED; + } + return mInstance; +} + +zapAudioInState* zapAudioIn_PLAY_IDLE_CLOSED::mInstance = nsnull; + +nsresult zapAudioIn_PLAY_IDLE_CLOSED::Play(zapAudioIn* audioin) +{ + // play already pending + return NS_OK; +} + +nsresult zapAudioIn_PLAY_IDLE_CLOSED::Stop(zapAudioIn* audioin) +{ + ChangeState(audioin, zapAudioIn_STOP_IDLE_CLOSED::Instance()); + return NS_OK; +} + +nsresult zapAudioIn_PLAY_IDLE_CLOSED::ConnectSink(zapAudioIn* audioin, + zapIMediaSink* sink, + const nsACString& connection_id) +{ + NS_ASSERTION(!audioin->mSink, "already connected"); + audioin->mSink = sink; + // stay in state + return NS_OK; +} + +nsresult zapAudioIn_PLAY_IDLE_CLOSED::DisconnectSink(zapAudioIn* audioin, + zapIMediaSink *sink, + const nsACString & connection_id) +{ + audioin->mSink = nsnull; + // stay in state + return NS_OK; +} + +nsresult zapAudioIn_PLAY_IDLE_CLOSED::RequestFrame(zapAudioIn* audioin) +{ + if (NS_FAILED(audioin->StartStream())) { + ChangeState(audioin, zapAudioIn_STOP_WAITING_CLOSED::Instance()); + } + else { + // success. portaudio callback is running. + // sink is waiting for frame. + ChangeState(audioin, zapAudioIn_PLAY_WAITING_OPEN::Instance()); + } + return NS_OK; +} + + +//////////////////////////////////////////////////////////////////////// +// zapAudioIn_PLAY_IDLE_OPEN implementation + +zapAudioInState* zapAudioIn_PLAY_IDLE_OPEN::Instance() +{ + if (!mInstance) { + mInstance = new zapAudioIn_PLAY_IDLE_OPEN; + } + return mInstance; +} + +zapAudioInState* zapAudioIn_PLAY_IDLE_OPEN::mInstance = nsnull; + +nsresult zapAudioIn_PLAY_IDLE_OPEN::Play(zapAudioIn* audioin) +{ + // already playing + return NS_OK; +} + +nsresult zapAudioIn_PLAY_IDLE_OPEN::Stop(zapAudioIn* audioin) +{ + audioin->CloseStream(); + // make sure sink gets eof frame: + ChangeState(audioin, zapAudioIn_STOP_IDLEEOF_CLOSED::Instance()); + return NS_OK; +} + +nsresult zapAudioIn_PLAY_IDLE_OPEN::DisconnectSink(zapAudioIn* audioin, + zapIMediaSink *sink, + const nsACString & connection_id) +{ + audioin->CloseStream(); + audioin->mSink = nsnull; + ChangeState(audioin, zapAudioIn_PLAY_IDLE_CLOSED::Instance()); + return NS_OK; +} + +nsresult zapAudioIn_PLAY_IDLE_OPEN::RequestFrame(zapAudioIn* audioin) +{ + ChangeState(audioin, zapAudioIn_PLAY_WAITING_OPEN::Instance()); + return NS_OK; +} + +void zapAudioIn_PLAY_IDLE_OPEN::SendFrame(zapAudioIn* audioin, + zapIMediaFrame* frame) +{ + // Sink is not waiting. We have buffer overflow. +#ifdef DEBUG + printf("O"); +#endif + // Silently discard frame +} + + +//////////////////////////////////////////////////////////////////////// +// zapAudioIn_STOP_WAITING_CLOSED implementation + +zapAudioInState* zapAudioIn_STOP_WAITING_CLOSED::Instance() +{ + if (!mInstance) { + mInstance = new zapAudioIn_STOP_WAITING_CLOSED; + } + return mInstance; +} + +zapAudioInState* zapAudioIn_STOP_WAITING_CLOSED::mInstance = nsnull; + +nsresult zapAudioIn_STOP_WAITING_CLOSED::Play(zapAudioIn* audioin) +{ + if (NS_FAILED(audioin->StartStream())) { + ChangeState(audioin, zapAudioIn_STOP_WAITING_CLOSED::Instance()); + } + else { + // success. portaudio callback is running. + // sink is waiting for frame. + ChangeState(audioin, zapAudioIn_PLAY_WAITING_OPEN::Instance()); + } + return NS_OK; +} + +nsresult zapAudioIn_STOP_WAITING_CLOSED::Stop(zapAudioIn* audioin) +{ + // already stopped + return NS_OK; +} + +nsresult zapAudioIn_STOP_WAITING_CLOSED::DisconnectSink(zapAudioIn* audioin, + zapIMediaSink *sink, + const nsACString & connection_id) +{ + audioin->mSink = nsnull; + ChangeState(audioin, zapAudioIn_STOP_IDLE_CLOSED::Instance()); + return NS_OK; +} + + +//////////////////////////////////////////////////////////////////////// +// zapAudioIn_STOP_IDLEEOF_CLOSED implementation + +zapAudioInState* zapAudioIn_STOP_IDLEEOF_CLOSED::Instance() +{ + if (!mInstance) { + mInstance = new zapAudioIn_STOP_IDLEEOF_CLOSED; + } + return mInstance; +} + +zapAudioInState* zapAudioIn_STOP_IDLEEOF_CLOSED::mInstance = nsnull; + +nsresult zapAudioIn_STOP_IDLEEOF_CLOSED::Play(zapAudioIn* audioin) +{ + ChangeState(audioin, zapAudioIn_PLAY_IDLEEOF_CLOSED::Instance()); + return NS_OK; +} + +nsresult zapAudioIn_STOP_IDLEEOF_CLOSED::Stop(zapAudioIn* audioin) +{ + // already stopped + return NS_OK; +} + +nsresult zapAudioIn_STOP_IDLEEOF_CLOSED::DisconnectSink(zapAudioIn* audioin, + zapIMediaSink *sink, + const nsACString & connection_id) +{ + audioin->mSink = nsnull; + ChangeState(audioin, zapAudioIn_STOP_IDLE_CLOSED::Instance()); + return NS_OK; +} + +nsresult zapAudioIn_STOP_IDLEEOF_CLOSED::RequestFrame(zapAudioIn* audioin) +{ + // send eof frame: + audioin->mSink->ProcessFrame(nsnull); + ChangeState(audioin, zapAudioIn_STOP_IDLE_CLOSED::Instance()); + return NS_OK; +} + + +//////////////////////////////////////////////////////////////////////// +// zapAudioIn_PLAY_IDLEEOF_CLOSED implementation + +zapAudioInState* zapAudioIn_PLAY_IDLEEOF_CLOSED::Instance() +{ + if (!mInstance) { + mInstance = new zapAudioIn_PLAY_IDLEEOF_CLOSED; + } + return mInstance; +} + +zapAudioInState* zapAudioIn_PLAY_IDLEEOF_CLOSED::mInstance = nsnull; + +nsresult zapAudioIn_PLAY_IDLEEOF_CLOSED::Play(zapAudioIn* audioin) +{ + // play already pending + return NS_OK; +} + +nsresult zapAudioIn_PLAY_IDLEEOF_CLOSED::Stop(zapAudioIn* audioin) +{ + ChangeState(audioin, zapAudioIn_STOP_IDLEEOF_CLOSED::Instance()); + return NS_OK; +} + +nsresult zapAudioIn_PLAY_IDLEEOF_CLOSED::DisconnectSink(zapAudioIn* audioin, + zapIMediaSink *sink, + const nsACString & connection_id) +{ + audioin->mSink = nsnull; + ChangeState(audioin, zapAudioIn_PLAY_IDLE_CLOSED::Instance()); + return NS_OK; +} + +nsresult zapAudioIn_PLAY_IDLEEOF_CLOSED::RequestFrame(zapAudioIn* audioin) +{ + // send eof frame: + audioin->mSink->ProcessFrame(nsnull); + ChangeState(audioin, zapAudioIn_PLAY_IDLE_CLOSED::Instance()); + return NS_OK; +} + + +//////////////////////////////////////////////////////////////////////// +// zapAudioIn_PLAY_WAITING_OPEN implementation + +zapAudioInState* zapAudioIn_PLAY_WAITING_OPEN::Instance() +{ + if (!mInstance) { + mInstance = new zapAudioIn_PLAY_WAITING_OPEN; + } + return mInstance; +} + +zapAudioInState* zapAudioIn_PLAY_WAITING_OPEN::mInstance = nsnull; + +nsresult zapAudioIn_PLAY_WAITING_OPEN::Play(zapAudioIn* audioin) +{ + // already playing + return NS_OK; +} + +nsresult zapAudioIn_PLAY_WAITING_OPEN::Stop(zapAudioIn* audioin) +{ + audioin->CloseStream(); + ChangeState(audioin, zapAudioIn_STOP_IDLE_CLOSED::Instance()); + // send eof frame: + audioin->mSink->ProcessFrame(nsnull); + return NS_OK; +} + +nsresult zapAudioIn_PLAY_WAITING_OPEN::DisconnectSink(zapAudioIn* audioin, + zapIMediaSink *sink, + const nsACString & connection_id) +{ + audioin->CloseStream(); + audioin->mSink = nsnull; + ChangeState(audioin, zapAudioIn_PLAY_IDLE_CLOSED::Instance()); + return NS_OK; +} + +void zapAudioIn_PLAY_WAITING_OPEN::SendFrame(zapAudioIn* audioin, + zapIMediaFrame* frame) +{ + ChangeState(audioin, zapAudioIn_PLAY_IDLE_OPEN::Instance()); + audioin->mSink->ProcessFrame(frame); +} + + diff --git a/mozilla/zap/zmk/src/zapAudioIn.h b/mozilla/zap/zmk/src/zapAudioIn.h new file mode 100644 index 00000000000..c99bf854831 --- /dev/null +++ b/mozilla/zap/zmk/src/zapAudioIn.h @@ -0,0 +1,331 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#ifndef __ZAP_AUDIOIN_H__ +#define __ZAP_AUDIOIN_H__ + +#include "zapIMediaNode.h" +#include "zapIMediaSource.h" +#include "zapIMediaSink.h" +#include "zapIMediaGraph.h" +#include "zapIMediaFrame.h" +#include "zapIAudioIn.h" +#include "nsCOMPtr.h" +#include "portaudio.h" +#include "nsIEventQueue.h" +#include "nsIWritablePropertyBag2.h" +#include "zapAudioStreamUtils.h" + +//////////////////////////////////////////////////////////////////////// +// zapAudioIn + +// {FF982BFD-61EB-4C5E-9C11-90584445399A} +#define ZAP_AUDIOIN_CID \ + { 0xff982bfd, 0x61eb, 0x4c5e, { 0x9c, 0x11, 0x90, 0x58, 0x44, 0x45, 0x39, 0x9a } } + +#define ZAP_AUDIOIN_CONTRACTID ZAP_MEDIANODE_CONTRACTID_PREFIX "audioin" + +class zapAudioIn : public zapIMediaNode, + public zapIMediaSource, + public zapIAudioIn +{ +public: + zapAudioIn(); + ~zapAudioIn(); + + NS_DECL_ISUPPORTS + NS_DECL_ZAPIMEDIANODE + NS_DECL_ZAPIMEDIASOURCE + NS_DECL_ZAPIAUDIOIN + +private: + friend class zapAudioInState; + friend class zapAudioIn_STOP_IDLE_CLOSED; + friend class zapAudioIn_PLAY_IDLE_CLOSED; + friend class zapAudioIn_PLAY_IDLE_OPEN; + friend class zapAudioIn_STOP_WAITING_CLOSED; + friend class zapAudioIn_STOP_IDLEEOF_CLOSED; + friend class zapAudioIn_PLAY_IDLEEOF_CLOSED; + friend class zapAudioIn_PLAY_WAITING_OPEN; + + void ChangeState(zapAudioInState* state); + + zapAudioInState* mState; + + nsresult StartStream(); + void CloseStream(); + void SendFrame(const nsACString& data, double timestamp); + + // node parameters (set from zapIMediaGraph::AddNode()): + PaDeviceID mInputDevice; + + // source parameters (set from zapIMediaGraph::Connect()): + double mSampleRate; + double mFrameDuration; + PRUint32 mNumChannels; + zapAudioStreamSampleFormat mSampleFormat; + PRUint32 mSamplesPerFrame; + + nsCOMPtr mSink; + + PortAudioStream* mStream; + nsCOMPtr mStreamInfo; + + nsCOMPtr mEventQ; // media graph event queue + + friend class zapAudioInSendEvent; + friend int AudioInCallback(void* inputBuffer, void* outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void* userData); + PRLock* mCallbackLock; // lock to synchronize portaudio and media threads + PRBool mKeepRunning; // signals the portaudio callback whether to + // shut down or not + +}; + +//////////////////////////////////////////////////////////////////////// +// zapAudioInState: baseclass for zapAudioIn states + +class zapAudioInState +{ +public: + // zapIAudioIn handlers: + virtual nsresult Play(zapAudioIn* audioin)=0; + virtual nsresult Stop(zapAudioIn* audioin)=0; + + // zapIMediaSource handlers: + virtual nsresult ConnectSink(zapAudioIn* audioin, zapIMediaSink* sink, + const nsACString& connection_id); + virtual nsresult DisconnectSink(zapAudioIn* audioin, zapIMediaSink *sink, + const nsACString & connection_id)=0; + virtual nsresult RequestFrame(zapAudioIn* audioin); + + // portaudio callback handlers: + virtual void SendFrame(zapAudioIn* audioin, zapIMediaFrame* frame); + +#ifdef DEBUG + virtual const char* GetName()=0; +#endif + +protected: + void ChangeState(zapAudioIn* audioin, zapAudioInState* state); +}; + +//////////////////////////////////////////////////////////////////////// +// zapAudioIn_STOP_IDLE_CLOSED + +class zapAudioIn_STOP_IDLE_CLOSED : public zapAudioInState +{ +public: + static zapAudioInState* Instance(); + + virtual nsresult Play(zapAudioIn* audioin); + virtual nsresult Stop(zapAudioIn* audioin); + + virtual nsresult ConnectSink(zapAudioIn* audioin, zapIMediaSink* sink, + const nsACString& connection_id); + virtual nsresult DisconnectSink(zapAudioIn* audioin, zapIMediaSink *sink, + const nsACString & connection_id); + virtual nsresult RequestFrame(zapAudioIn* audioin); + +#ifdef DEBUG + virtual const char* GetName() { + static const char* name = "STOP_IDLE_CLOSED"; + return name; + } +#endif +private: + static zapAudioInState* mInstance; +}; + +//////////////////////////////////////////////////////////////////////// +// zapAudioIn_PLAY_IDLE_CLOSED: waiting for sink to connect and/or +// request first frame + +class zapAudioIn_PLAY_IDLE_CLOSED : public zapAudioInState +{ +public: + static zapAudioInState* Instance(); + + virtual nsresult Play(zapAudioIn* audioin); + virtual nsresult Stop(zapAudioIn* audioin); + + virtual nsresult ConnectSink(zapAudioIn* audioin, zapIMediaSink* sink, + const nsACString& connection_id); + virtual nsresult DisconnectSink(zapAudioIn* audioin, zapIMediaSink *sink, + const nsACString & connection_id); + virtual nsresult RequestFrame(zapAudioIn* audioin); +#ifdef DEBUG + virtual const char* GetName() { + static const char* name = "PLAY_IDLE_CLOSED"; + return name; + } +#endif + +private: + static zapAudioInState* mInstance; +}; + +//////////////////////////////////////////////////////////////////////// +// zapAudioIn_PLAY_IDLE_OPEN + +class zapAudioIn_PLAY_IDLE_OPEN : public zapAudioInState +{ +public: + static zapAudioInState* Instance(); + + virtual nsresult Play(zapAudioIn* audioin); + virtual nsresult Stop(zapAudioIn* audioin); + + virtual nsresult DisconnectSink(zapAudioIn* audioin, zapIMediaSink *sink, + const nsACString & connection_id); + virtual nsresult RequestFrame(zapAudioIn* audioin); + + virtual void SendFrame(zapAudioIn* audioin, zapIMediaFrame* frame); +#ifdef DEBUG + virtual const char* GetName() { + static const char* name = "PLAY_IDLE_OPEN"; + return name; + } +#endif + +private: + static zapAudioInState* mInstance; +}; + +//////////////////////////////////////////////////////////////////////// +// zapAudioIn_STOP_WAITING_CLOSED + +class zapAudioIn_STOP_WAITING_CLOSED : public zapAudioInState +{ +public: + static zapAudioInState* Instance(); + + virtual nsresult Play(zapAudioIn* audioin); + virtual nsresult Stop(zapAudioIn* audioin); + + virtual nsresult DisconnectSink(zapAudioIn* audioin, zapIMediaSink *sink, + const nsACString & connection_id); +#ifdef DEBUG + virtual const char* GetName() { + static const char* name = "STOP_WAITING_CLOSED"; + return name; + } +#endif + +private: + static zapAudioInState* mInstance; +}; + +//////////////////////////////////////////////////////////////////////// +// zapAudioIn_STOP_IDLEEOF_CLOSED + +class zapAudioIn_STOP_IDLEEOF_CLOSED : public zapAudioInState +{ +public: + static zapAudioInState* Instance(); + + virtual nsresult Play(zapAudioIn* audioin); + virtual nsresult Stop(zapAudioIn* audioin); + + virtual nsresult DisconnectSink(zapAudioIn* audioin, zapIMediaSink *sink, + const nsACString & connection_id); + virtual nsresult RequestFrame(zapAudioIn* audioin); +#ifdef DEBUG + virtual const char* GetName() { + static const char* name = "STOP_IDLEEOF_CLOSED"; + return name; + } +#endif + +private: + static zapAudioInState* mInstance; +}; + +//////////////////////////////////////////////////////////////////////// +// zapAudioIn_STOP_IDLEEOF_CLOSED + +class zapAudioIn_PLAY_IDLEEOF_CLOSED : public zapAudioInState +{ +public: + static zapAudioInState* Instance(); + + virtual nsresult Play(zapAudioIn* audioin); + virtual nsresult Stop(zapAudioIn* audioin); + + virtual nsresult DisconnectSink(zapAudioIn* audioin, zapIMediaSink *sink, + const nsACString & connection_id); + virtual nsresult RequestFrame(zapAudioIn* audioin); +#ifdef DEBUG + virtual const char* GetName() { + static const char* name = "PLAY_IDLEEOF_CLOSED"; + return name; + } +#endif + +private: + static zapAudioInState* mInstance; +}; + + +//////////////////////////////////////////////////////////////////////// +// zapAudioIn_PLAY_WAITING_OPEN + +class zapAudioIn_PLAY_WAITING_OPEN : public zapAudioInState +{ +public: + static zapAudioInState* Instance(); + + virtual nsresult Play(zapAudioIn* audioin); + virtual nsresult Stop(zapAudioIn* audioin); + + virtual nsresult DisconnectSink(zapAudioIn* audioin, zapIMediaSink *sink, + const nsACString & connection_id); + + virtual void SendFrame(zapAudioIn* audioin, zapIMediaFrame* frame); +#ifdef DEBUG + virtual const char* GetName() { + static const char* name = "PLAY_WAITING_OPEN"; + return name; + } +#endif + +private: + static zapAudioInState* mInstance; +}; + + +#endif // __ZAP_AUDIOIN_H__ diff --git a/mozilla/zap/zmk/src/zapAudioOut.cpp b/mozilla/zap/zmk/src/zapAudioOut.cpp new file mode 100644 index 00000000000..73808b53d19 --- /dev/null +++ b/mozilla/zap/zmk/src/zapAudioOut.cpp @@ -0,0 +1,512 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "zapAudioOut.h" +#include "stdio.h" +#include "nsString.h" +#include "zapMediaFrame.h" +#include "zapAudioDevice.h" +#include "nsIProxyObjectManager.h" +#include "nsAutoLock.h" + +//////////////////////////////////////////////////////////////////////// +// zapAudioOut + +zapAudioOut::zapAudioOut() + : mStream(nsnull), + mWaiting(PR_FALSE) +{ + mLock = PR_NewLock(); + + PaError err; + if ((err = Pa_Initialize()) != paNoError) { +#ifdef DEBUG + printf("Failed to initialize portaudio: %s\n", Pa_GetErrorText(err)); +#endif + } + +#ifdef DEBUG + printf("zapAudioOut::zapAudioOut()\n"); +#endif +} + +zapAudioOut::~zapAudioOut() +{ + PR_DestroyLock(mLock); + + NS_ASSERTION(!mStream, "stream still running"); + + Pa_Terminate(); +#ifdef DEBUG + printf("zapAudioOut::~zapAudioOut()\n"); +#endif +} + +//---------------------------------------------------------------------- +// nsISupports methods: + +NS_IMPL_ADDREF(zapAudioOut) +NS_IMPL_RELEASE(zapAudioOut) + +NS_INTERFACE_MAP_BEGIN(zapAudioOut) + NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, zapIMediaNode) + NS_INTERFACE_MAP_ENTRY(zapIMediaNode) + NS_INTERFACE_MAP_ENTRY(zapIMediaSink) + NS_INTERFACE_MAP_ENTRY(zapIAudioOut) +NS_INTERFACE_MAP_END + +//---------------------------------------------------------------------- +// zapIMediaNode methods: + +/* void addedToGraph (in zapIMediaGraph graph, in ACString id, in nsIPropertyBag2 node_pars); */ +NS_IMETHODIMP +zapAudioOut::AddedToGraph(zapIMediaGraph *graph, + const nsACString & id, + nsIPropertyBag2* node_pars) +{ + graph->GetEventQueue(getter_AddRefs(mEventQ)); + + // node parameter defaults: + mOutputDevice = Pa_GetDefaultOutputDeviceID(); + // unpack node parameters: + if (node_pars) { + nsCOMPtr device; + node_pars->GetPropertyAsInterface(NS_LITERAL_STRING("device"), + NS_GET_IID(zapIPortaudioDevice), + getter_AddRefs(device)); + if (device) + device->GetDeviceID(&mOutputDevice); + } +#ifdef DEBUG + printf("(audioout using device %d)", mOutputDevice); +#endif + return NS_OK; +} + +/* void removedFromGraph (in zapIMediaGraph graph); */ +NS_IMETHODIMP +zapAudioOut::RemovedFromGraph(zapIMediaGraph *graph) +{ + return NS_OK; +} + +/* zapIMediaSource getSource (in nsIPropertyBag2 source_pars); */ +NS_IMETHODIMP +zapAudioOut::GetSource(nsIPropertyBag2 *source_pars, zapIMediaSource **_retval) +{ + NS_ERROR("audioout is a sink-only node"); + return NS_ERROR_FAILURE; +} + +/* zapIMediaSink getSink (in nsIPropertyBag2 sink_pars); */ +NS_IMETHODIMP +zapAudioOut::GetSink(nsIPropertyBag2 *sink_pars, zapIMediaSink **_retval) +{ + if (mSource) { + NS_ERROR("already connected"); + return NS_ERROR_FAILURE; + } + *_retval = this; + NS_ADDREF(*_retval); + return NS_OK; +} + +//---------------------------------------------------------------------- +// portaudio audio sink callback: + +class zapAudioOutRequestEvent : public PLEvent +{ +public: + zapAudioOutRequestEvent(zapAudioOut* audioout) + { + PL_InitEvent(this, audioout, EventHandler, EventCleanup); + } + + PR_STATIC_CALLBACK(void *) EventHandler(PLEvent* ev) + { + zapAudioOutRequestEvent* rev = (zapAudioOutRequestEvent*) ev; + zapAudioOut* audioout = (zapAudioOut*) ev->owner; + + nsAutoLock lock(audioout->mLock); + NS_ASSERTION(audioout->mSource, "source gone"); + NS_ASSERTION(!audioout->mWaiting, "protocol error"); + audioout->mWaiting = PR_TRUE; + audioout->mFrame = nsnull; + lock.unlock(); + audioout->mSource->RequestFrame(); + return (void*)PR_TRUE; + } + + PR_STATIC_CALLBACK(void) EventCleanup(PLEvent* ev) + { + delete (zapAudioOutRequestEvent*) ev; + } +}; + +int AudioOutCallback(void* inputBuffer, void* outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void* userData) +{ +#ifdef DEBUG +// printf("["); +#endif + + PRBool stopStream = PR_FALSE; + zapAudioOut* audioout = (zapAudioOut*)userData; + + nsAutoLock lock(audioout->mLock); + + if (audioout->mWaiting) { + // underflow: we are still waiting for the next frame. +#ifdef DEBUG + printf("U"); +#endif + // Generate a silence buffer + // XXX in the case of Float32 samples, this requires a sane + // floating point representation where zero is 0 0 0 0. + if (audioout->mSampleFormat == sf_float32_32768) { + // output buffer is int16: + memset(outputBuffer, 0, audioout->mSamplesPerFrame*2); + } + else { + memset(outputBuffer, 0, audioout->mSamplesPerFrame * GetZapAudioSampleSize(audioout->mSampleFormat)); + } + } + else { + if (audioout->mFrame) { + // We've got a frame. Consume it. +#ifdef DEBUG +// PRUint32 timestamp; +// audioout->mFrame->GetTimestamp(×tamp); +// printf("<%d>", timestamp); +#endif + nsCString data; + audioout->mFrame->GetData(data); + NS_ASSERTION(data.Length() == audioout->mSamplesPerFrame * GetZapAudioSampleSize(audioout->mSampleFormat), + "buffer length mismatch"); + PRUint32 l = PR_MIN(data.Length(), audioout->mSamplesPerFrame * GetZapAudioSampleSize(audioout->mSampleFormat)); + if (audioout->mSampleFormat == sf_float32_32768) { + // convert to int16 + float* s = (float*)data.BeginReading(); + PRInt16* d = (PRInt16*)outputBuffer; + for (int i=0; imEventQ->EnterMonitor(); + zapAudioOutRequestEvent* ev = new zapAudioOutRequestEvent(audioout); + void* result = nsnull; + + // Unlock mLock. This must be done after we've entered the + // eventQ monitor to synchronize ourselves with event revocation + // in the case of stream closure. + lock.unlock(); + audioout->mEventQ->PostSynchronousEvent(ev, &result); + audioout->mEventQ->ExitMonitor(); + if (!result) { + // the event was cancelled +#ifdef DEBUG + printf("(audioout stop1)"); +#endif + stopStream = PR_TRUE; + } + } + else { + // EOF +#ifdef DEBUG + printf("(audioout stop2)"); +#endif + stopStream = PR_TRUE; + } + } + +#ifdef DEBUG +// printf("]"); +#endif + + return stopStream; +} + +//---------------------------------------------------------------------- +// zapIMediaSink methods: + +/* void connectSource (in zapIMediaSource source, in ACString connection_id); */ +NS_IMETHODIMP +zapAudioOut::ConnectSource(zapIMediaSource *source, + const nsACString & connection_id) +{ + NS_ASSERTION(!mSource, "already connected"); + NS_ASSERTION(!mWaiting, "protocol error"); + NS_ASSERTION(!mStream, "protocol error"); + + mSource = source; + + // request first buffer frame: + mWaiting = PR_TRUE; + mSource->RequestFrame(); + + return NS_OK; +} + +/* void disconnectSource (in zapIMediaSource source, in ACString connection_id); */ +NS_IMETHODIMP +zapAudioOut::DisconnectSource(zapIMediaSource *source, + const nsACString & connection_id) +{ + mSource = nsnull; + if (mStream) { + CloseStream(); + } + mWaiting = PR_FALSE; + return NS_OK; +} + +class zapAudioOutCloseEvent : public PLEvent +{ +public: + zapAudioOutCloseEvent(zapAudioOut* _audioout) + : audioout(_audioout) + { + PL_InitEvent(this, audioout, EventHandler, EventCleanup); + } + + PR_STATIC_CALLBACK(void *) EventHandler(PLEvent* ev) + { + zapAudioOutCloseEvent* rev = (zapAudioOutCloseEvent*) ev; + + rev->audioout->CloseStream(); + return (void*)PR_TRUE; + } + + PR_STATIC_CALLBACK(void) EventCleanup(PLEvent* ev) + { + delete (zapAudioOutCloseEvent*) ev; + } + + // reference to keep alive the audioout object while the stream is + // being closed: + nsRefPtr audioout; +}; + + +/* void processFrame (in zapIMediaFrame frame); */ +NS_IMETHODIMP +zapAudioOut::ProcessFrame(zapIMediaFrame *frame) +{ + nsAutoLock lock(mLock); + NS_ASSERTION(mWaiting, "protocol error"); + mWaiting = PR_FALSE; + mFrame = frame; + + if (mStream && !frame) { + // Schedule stream closure. The call needs to be asynchronous + // since this ProcessFrame call might be nested in the callback's + // RequestFrame call: + mEventQ->EnterMonitor(); + zapAudioOutCloseEvent* ev = new zapAudioOutCloseEvent(this); + mEventQ->PostEvent(ev); + mEventQ->ExitMonitor(); + } + else if (!mStream) { + if (frame) { + nsCOMPtr streamInfo; + frame->GetStreamInfo(getter_AddRefs(streamInfo)); + if (NS_FAILED(StartStream(streamInfo))) { +#ifdef DEBUG + NS_ERROR("Error opening stream"); +#endif + } + } + else { + // an EOF frame. request next stream: + mWaiting = PR_TRUE; + lock.unlock(); + mSource->RequestFrame(); + } + } + + return NS_OK; +} + +//---------------------------------------------------------------------- +// zapIAudioOut methods: + +/* readonly attribute zapIAudioDevice defaultOutputDevice; */ +NS_IMETHODIMP +zapAudioOut::GetDefaultOutputDevice(zapIAudioDevice * *aDefaultOutputDevice) +{ + PaDeviceID id = Pa_GetDefaultOutputDeviceID(); + if (id == paNoDevice) { + *aDefaultOutputDevice = nsnull; + return NS_ERROR_FAILURE; + } + + *aDefaultOutputDevice = CreateAudioDevice(id); + return NS_OK; +} + +//---------------------------------------------------------------------- +// Implementation helpers: + +nsresult zapAudioOut::StartStream(nsIPropertyBag2* streamInfo) +{ + NS_ASSERTION(!mStream, "stream still running"); + + if (!streamInfo) { + NS_ERROR("missing stream info"); + return NS_ERROR_FAILURE; + } + + nsCString type; + if (NS_FAILED(streamInfo->GetPropertyAsACString(NS_LITERAL_STRING("type"), + type)) || + type != NS_LITERAL_CSTRING("audio")) { + NS_ERROR("unsupported stream type"); + return NS_ERROR_FAILURE; + } + + double sampleRate; + if (NS_FAILED(streamInfo->GetPropertyAsDouble(NS_LITERAL_STRING("sample_rate"), + &sampleRate))) { + NS_ERROR("unknown sample rate"); + return NS_ERROR_FAILURE; + } + + double frameDuration; + if (NS_FAILED(streamInfo->GetPropertyAsDouble(NS_LITERAL_STRING("frame_duration"), + &frameDuration))) { + NS_ERROR("unknown frame duration"); + return NS_ERROR_FAILURE; + } + + PRUint32 numOutputChannels; + if (NS_FAILED(streamInfo->GetPropertyAsUint32(NS_LITERAL_STRING("channels"), + &numOutputChannels))) { + NS_ERROR("unknown output channel count"); + return NS_ERROR_FAILURE; + } + + nsCString format_string; + if (NS_FAILED(streamInfo->GetPropertyAsACString(NS_LITERAL_STRING("sample_format"), + format_string))) { + NS_ERROR("unknown sample format"); + return NS_ERROR_FAILURE; + } + mSampleFormat = StrToZapAudioSampleFormat(format_string); + if (mSampleFormat == sf_unknown) { + NS_ERROR("unknown sample format"); + return NS_ERROR_FAILURE; + } + + mSamplesPerFrame = (PRUint32)(sampleRate*frameDuration*numOutputChannels); + + // try to open stream: + PaError err = Pa_OpenStream(&mStream, + paNoDevice, 0, 0, nsnull, + mOutputDevice, numOutputChannels, + ZapAudioSampleFormatToPaFormat(mSampleFormat), nsnull, + sampleRate, mSamplesPerFrame/numOutputChannels, 0, + paNoFlag, + AudioOutCallback, this); + + if (err != paNoError) { +#ifdef DEBUG + printf("Failed to open portaudio output stream: %s\n", Pa_GetErrorText(err)); +#endif + return NS_ERROR_FAILURE; + } + + // start playing stream: + Pa_StartStream(mStream); + + return NS_OK; +} + +void zapAudioOut::CloseStream() +{ + if (!mStream) return; // stream already stopped + + // XXX Note: If the stream is not stopped before closing, + // Pa_CloseStream() will block the media thread until the next + // callback. More gravely, if the stream is closed while in the + // callback, portaudio will crash. The first issue we can't prevent + // easily. To prevent the second issue we must revoke any pending + // events from the callback that prevent it from completing while + // the media thread is not pumping events: + + // Ensure that if the portaudio callback is called now, it will see + // an EOF frame and stop the stream rather than posting a new + // request: + nsAutoLock lock(mLock); + mFrame = nsnull; + mWaiting = PR_FALSE; + lock.unlock(); + + // Depending on when the callback ran we might still have an old + // callback waiting for a pending frame request. By cancelling all + // requests we ensure that it can run to completion (also stopping + // the stream): + mEventQ->EnterMonitor(); + mEventQ->RevokeEvents(this); + mEventQ->ExitMonitor(); + + // At this point we have made sure that the portaudio callback can + // run to completion and it is safe to close the + // stream. Pa_CloseStream() will wait for the callback to complete, + // blocking the media thread. + + Pa_CloseStream(mStream); + mStream = nsnull; +#ifdef DEBUG + printf("(audioout stream closed)"); +#endif + + if (mSource) { + // we still have a source. request first frame of next stream: + mWaiting = PR_TRUE; + mSource->RequestFrame(); + } + +} + diff --git a/mozilla/zap/zmk/src/zapAudioOut.h b/mozilla/zap/zmk/src/zapAudioOut.h new file mode 100644 index 00000000000..0ca7e0bc4d8 --- /dev/null +++ b/mozilla/zap/zmk/src/zapAudioOut.h @@ -0,0 +1,104 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#ifndef __ZAP_AUDIOOUT_H__ +#define __ZAP_AUDIOOUT_H__ + +#include "zapIMediaNode.h" +#include "zapIMediaSource.h" +#include "zapIMediaSink.h" +#include "zapIMediaGraph.h" +#include "zapIMediaFrame.h" +#include "zapIAudioOut.h" +#include "nsCOMPtr.h" +#include "portaudio.h" +#include "nsIEventQueue.h" +#include "nsIPropertyBag2.h" +#include "zapAudioStreamUtils.h" + +//////////////////////////////////////////////////////////////////////// +// zapAudioOut + +// {1FE87612-773C-4FBC-8EF2-C7509F6584D0} +#define ZAP_AUDIOOUT_CID \ + { 0x1fe87612, 0x773c, 0x4fbc, { 0x8e, 0xf2, 0xc7, 0x50, 0x9f, 0x65, 0x84, 0xd0 } } + +#define ZAP_AUDIOOUT_CONTRACTID ZAP_MEDIANODE_CONTRACTID_PREFIX "audioout" + +class zapAudioOut : public zapIMediaNode, + public zapIMediaSink, + public zapIAudioOut +{ +public: + zapAudioOut(); + ~zapAudioOut(); + + NS_DECL_ISUPPORTS + NS_DECL_ZAPIMEDIANODE + NS_DECL_ZAPIMEDIASINK + NS_DECL_ZAPIAUDIOOUT + +private: + friend class zapAudioOutRequestEvent; + friend class zapAudioOutCloseEvent; + friend int AudioOutCallback(void* inputBuffer, void* outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void* userData); + + nsresult StartStream(nsIPropertyBag2* streamInfo); + void CloseStream(); + + nsCOMPtr mEventQ; // media graph event queue + + // node parameters (set in zapIMediaGraph::AddNode()): + PaDeviceID mOutputDevice; + + // stream parameters (obtained from first stream frame): + zapAudioStreamSampleFormat mSampleFormat; + PRUint32 mSamplesPerFrame; + + // We need a buffer for 1 frame to mediate between the portaudio + // callback and the sync/async processing model of the graph: + nsCOMPtr mFrame; + + PRBool mWaiting; // true == waiting for data + PortAudioStream* mStream; + PRLock* mLock; // lock to synchronize portaudio and media threads + + nsCOMPtr mSource; +}; + +#endif // __ZAP_AUDIOOUT_H__ diff --git a/mozilla/zap/zmk/src/zapAudioStreamUtils.cpp b/mozilla/zap/zmk/src/zapAudioStreamUtils.cpp new file mode 100644 index 00000000000..b8f2dc0ce1b --- /dev/null +++ b/mozilla/zap/zmk/src/zapAudioStreamUtils.cpp @@ -0,0 +1,135 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "zapAudioStreamUtils.h" + +zapAudioStreamSampleFormat StrToZapAudioSampleFormat(const nsACString& str) +{ + zapAudioStreamSampleFormat rv = sf_unknown; + + if (str == NS_LITERAL_CSTRING("float32_1")) { + rv = sf_float32_1; + } + else if (str == NS_LITERAL_CSTRING("float32_32768")) { + rv = sf_float32_32768; + } + else if (str == NS_LITERAL_CSTRING("int16")) { + rv = sf_int16; + } + else if (str == NS_LITERAL_CSTRING("int32")) { + rv = sf_int32; + } + + return rv; +} + +void ZapAudioSampleFormatToStr(zapAudioStreamSampleFormat format, nsACString& str) +{ + switch (format) { + case sf_float32_1: + str = NS_LITERAL_CSTRING("float32_1"); + break; + case sf_float32_32768: + str = NS_LITERAL_CSTRING("float32_32768"); + break; + case sf_int16: + str = NS_LITERAL_CSTRING("int16"); + break; + case sf_int32: + str = NS_LITERAL_CSTRING("int32"); + break; + default: + str.Truncate(); + } +} + +PRUint32 GetZapAudioSampleSize(zapAudioStreamSampleFormat format) +{ + switch (format) { + case sf_float32_1: + case sf_float32_32768: + case sf_int32: + return 4; + break; + case sf_int16: + return 2; + break; + default: + return 0; + } +} + +PRUint32 GetPortAudioSampleSize(zapAudioStreamSampleFormat format) +{ + switch (format) { + case sf_float32_32768: + // special case. this format maps onto portaudio int16 and will + // be converted in audioin/audioout: + return 2; + break; + case sf_float32_1: + case sf_int32: + return 4; + break; + case sf_int16: + return 2; + break; + default: + return 0; + } +} + +PaSampleFormat ZapAudioSampleFormatToPaFormat(zapAudioStreamSampleFormat format) +{ + switch (format) { + case sf_float32_1: + return paFloat32; + break; + case sf_float32_32768: + // audioin & audioout will map this onto int16 + return paInt16; + break; + case sf_int32: + return paInt32; + break; + case sf_int16: + return paInt16; + break; + default: + NS_ERROR("unknown format"); + } + return 0; +} diff --git a/mozilla/zap/zmk/src/zapAudioStreamUtils.h b/mozilla/zap/zmk/src/zapAudioStreamUtils.h new file mode 100644 index 00000000000..dd4c150e424 --- /dev/null +++ b/mozilla/zap/zmk/src/zapAudioStreamUtils.h @@ -0,0 +1,59 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#ifndef __ZAP_AUDIOSTREAMUTILS_H__ +#define __ZAP_AUDIOSTREAMUTILS_H__ + +#include "nsString.h" +#include "portaudio.h" + +enum zapAudioStreamSampleFormat { + sf_float32_1, + sf_float32_32768, + sf_int16, + sf_int32, + sf_unknown +}; + +zapAudioStreamSampleFormat StrToZapAudioSampleFormat(const nsACString& str); +void ZapAudioSampleFormatToStr(zapAudioStreamSampleFormat format, nsACString& str); + +PRUint32 GetZapAudioSampleSize(zapAudioStreamSampleFormat format); +PRUint32 GetPortAudioSampleSize(zapAudioStreamSampleFormat format); + +PaSampleFormat ZapAudioSampleFormatToPaFormat(zapAudioStreamSampleFormat format); + +#endif // __ZAP_AUDIOSTREAMUTILS_H__ diff --git a/mozilla/zap/zmk/src/zapDatagramFrame.cpp b/mozilla/zap/zmk/src/zapDatagramFrame.cpp new file mode 100644 index 00000000000..5c9f1fd6389 --- /dev/null +++ b/mozilla/zap/zmk/src/zapDatagramFrame.cpp @@ -0,0 +1,159 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "zapDatagramFrame.h" +#include "stdio.h" + +//////////////////////////////////////////////////////////////////////// +// zapDatagramFrame + +//---------------------------------------------------------------------- +// nsISupports methods: + +NS_IMPL_ADDREF_INHERITED(zapDatagramFrame, zapMediaFrame) +NS_IMPL_RELEASE_INHERITED(zapDatagramFrame, zapMediaFrame) + +NS_INTERFACE_MAP_BEGIN(zapDatagramFrame) + NS_INTERFACE_MAP_ENTRY(nsIDatagram) +NS_INTERFACE_MAP_END_INHERITING(zapMediaFrame) + +//---------------------------------------------------------------------- +// nsIDatagram methods: + +/* readonly attribute ACString data; */ +NS_IMETHODIMP +zapDatagramFrame::GetData(nsACString & aData) +{ + return zapMediaFrame::GetData(aData); +} + + +/* readonly attribute ACString address; */ +NS_IMETHODIMP +zapDatagramFrame::GetAddress(nsACString & aAddress) +{ + aAddress = mAddress; + return NS_OK; +} + +/* readonly attribute long port; */ +NS_IMETHODIMP +zapDatagramFrame::GetPort(PRInt32 *aPort) +{ + *aPort = mPort; + return NS_OK; +} + + +//////////////////////////////////////////////////////////////////////// +// zapDatagramWrapperFrame + +zapDatagramWrapperFrame::zapDatagramWrapperFrame() +{ +#ifdef DEBUG +// printf("'"); +#endif +} + +zapDatagramWrapperFrame::~zapDatagramWrapperFrame() +{ +#ifdef DEBUG +// printf("`"); +#endif +} + +//---------------------------------------------------------------------- +// nsISupports methods: + +NS_IMPL_THREADSAFE_ADDREF(zapDatagramWrapperFrame) +NS_IMPL_THREADSAFE_RELEASE(zapDatagramWrapperFrame) + +NS_INTERFACE_MAP_BEGIN(zapDatagramWrapperFrame) + NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, zapIMediaFrame) + NS_INTERFACE_MAP_ENTRY(zapIMediaFrame) + NS_INTERFACE_MAP_ENTRY(nsIDatagram) +NS_INTERFACE_MAP_END + +//---------------------------------------------------------------------- +// zapIMediaFrame methods: + +/* readonly attribute nsIPropertyBag2 streamInfo; */ +NS_IMETHODIMP +zapDatagramWrapperFrame::GetStreamInfo(nsIPropertyBag2** aStreamInfo) +{ + *aStreamInfo = mStreamInfo.get(); + NS_IF_ADDREF(*aStreamInfo); + return NS_OK; +} + +/* readonly attribute unsigned long timestamp; */ +NS_IMETHODIMP +zapDatagramWrapperFrame::GetTimestamp(PRUint32 *aTimestamp) +{ + *aTimestamp = 0; + // shouldn't be called for datagram frames + return NS_ERROR_FAILURE; +} + +/* readonly attribute ACString data; */ +NS_IMETHODIMP +zapDatagramWrapperFrame::GetData(nsACString & aData) +{ + NS_ASSERTION(mDatagram, "uh-oh, no datagram"); + return mDatagram->GetData(aData); +} + +//---------------------------------------------------------------------- +// nsIDatagram methods: + +/* readonly attribute ACString data; */ +// see zapIMediaFrame + +/* readonly attribute ACString address; */ +NS_IMETHODIMP +zapDatagramWrapperFrame::GetAddress(nsACString & aAddress) +{ + NS_ASSERTION(mDatagram, "uh-oh, no datagram"); + return mDatagram->GetAddress(aAddress); +} + +/* readonly attribute long port; */ +NS_IMETHODIMP +zapDatagramWrapperFrame::GetPort(PRInt32 *aPort) +{ + NS_ASSERTION(mDatagram, "uh-oh, no datagram"); + return mDatagram->GetPort(aPort); +} diff --git a/mozilla/zap/zmk/src/zapDatagramFrame.h b/mozilla/zap/zmk/src/zapDatagramFrame.h new file mode 100644 index 00000000000..7becb8529ec --- /dev/null +++ b/mozilla/zap/zmk/src/zapDatagramFrame.h @@ -0,0 +1,80 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#ifndef __ZAP_DATAGRAMFRAME_H__ +#define __ZAP_DATAGRAMFRAME_H__ + +#include "zapMediaFrame.h" +#include "nsIUDPSocket.h" + +//////////////////////////////////////////////////////////////////////// +// + +class zapDatagramFrame : public zapMediaFrame, + public nsIDatagram +{ +public: + NS_DECL_ISUPPORTS_INHERITED + NS_DECL_NSIDATAGRAM + + nsCString mAddress; + PRUint32 mPort; +}; + + +//////////////////////////////////////////////////////////////////////// +// A wrapper around an nsIDatagram + +class zapDatagramWrapperFrame : public zapIMediaFrame, + public nsIDatagram +{ +public: + NS_DECL_ISUPPORTS + NS_DECL_ZAPIMEDIAFRAME + // nsIDatagram: + //NS_IMETHOD GetData(nsACString & aData); see zapIMediaFrame + NS_IMETHOD GetAddress(nsACString & aAddress); + NS_IMETHOD GetPort(PRInt32 *aPort); + + + zapDatagramWrapperFrame(); + ~zapDatagramWrapperFrame(); + + nsCOMPtr mStreamInfo; + nsCOMPtr mDatagram; +}; + +#endif // __ZAP_DATAGRAMFRAME_H__ diff --git a/mozilla/zap/zmk/src/zapFilterNode.cpp b/mozilla/zap/zmk/src/zapFilterNode.cpp new file mode 100644 index 00000000000..662b8a5bc03 --- /dev/null +++ b/mozilla/zap/zmk/src/zapFilterNode.cpp @@ -0,0 +1,208 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "zapFilterNode.h" +#include "zapIMediaFrame.h" +#include "zapIMediaGraph.h" +#include "nsIPropertyBag2.h" +#include "stdio.h" + +//////////////////////////////////////////////////////////////////////// +// zapFilterNode + +zapFilterNode::zapFilterNode() + : mStreamOpen(PR_FALSE), + mWaiting(PR_FALSE) +{ +} + +zapFilterNode::~zapFilterNode() +{ +} + +//---------------------------------------------------------------------- +// nsISupports methods: + +NS_IMPL_ADDREF(zapFilterNode) +NS_IMPL_RELEASE(zapFilterNode) + +NS_INTERFACE_MAP_BEGIN(zapFilterNode) + NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, zapIMediaNode) + NS_INTERFACE_MAP_ENTRY(zapIMediaNode) + NS_INTERFACE_MAP_ENTRY(zapIMediaSink) + NS_INTERFACE_MAP_ENTRY(zapIMediaSource) +NS_INTERFACE_MAP_END + + +//---------------------------------------------------------------------- +// zapIMediaNode methods: + +/* zapIMediaSource getSource (in nsIPropertyBag2 source_pars); */ +NS_IMETHODIMP +zapFilterNode::GetSource(nsIPropertyBag2 *source_pars, zapIMediaSource **_retval) +{ + if (mSink) { + NS_ERROR("source end already connected"); + *_retval = nsnull; + return NS_ERROR_FAILURE; + } + *_retval = this; + NS_ADDREF(*_retval); + return NS_OK; +} + +/* zapIMediaSink getSink (in nsIPropertyBag2 sink_pars); */ +NS_IMETHODIMP +zapFilterNode::GetSink(nsIPropertyBag2 *sink_pars, zapIMediaSink **_retval) +{ + if (mSource) { + NS_ERROR("sink end already connected"); + *_retval = nsnull; + return NS_ERROR_FAILURE; + } + *_retval = this; + NS_ADDREF(*_retval); + return NS_OK; +} + +//---------------------------------------------------------------------- +// zapIMediaSource methods: + + +/* void connectSink (in zapIMediaSink sink, in ACString connection_id); */ +NS_IMETHODIMP +zapFilterNode::ConnectSink(zapIMediaSink *sink, const nsACString & connection_id) +{ + NS_ASSERTION(!mSink, "sink already connected"); + mSink = sink; + return NS_OK; +} + +/* void disconnectSink (in zapIMediaSink sink, in ACString connection_id); */ +NS_IMETHODIMP +zapFilterNode::DisconnectSink(zapIMediaSink *sink, const nsACString & connection_id) +{ + mSink = nsnull; + if (mStreamOpen) { + mStreamOpen = PR_FALSE; + CloseStream(); + } + return NS_OK; +} + +/* void requestFrame (); */ +NS_IMETHODIMP +zapFilterNode::RequestFrame() +{ + if (mWaiting) return NS_OK; // already waiting + mWaiting = PR_TRUE; + if (mSource) + mSource->RequestFrame(); + return NS_OK; +} + +//---------------------------------------------------------------------- +// zapIMediaSink methods: + +/* void connectSource (in zapIMediaSource source, in ACString connection_id); */ +NS_IMETHODIMP +zapFilterNode::ConnectSource(zapIMediaSource *source, const nsACString & connection_id) +{ + NS_ASSERTION(!mSource, "source already connected"); + mSource = source; + + if (mWaiting) + mSource->RequestFrame(); + + return NS_OK; +} + +/* void disconnectSource (in zapIMediaSource source, in ACString connection_id); */ +NS_IMETHODIMP +zapFilterNode::DisconnectSource(zapIMediaSource *source, const nsACString & connection_id) +{ + mSource = nsnull; + if (mStreamOpen && mWaiting) { + mStreamOpen = PR_FALSE; + mWaiting = PR_FALSE; + CloseStream(); + // send EOF frame: + if (mSink) + mSink->ProcessFrame(nsnull); + } + return NS_OK; +} + +/* void processFrame (in zapIMediaFrame frame); */ +NS_IMETHODIMP +zapFilterNode::ProcessFrame(zapIMediaFrame *frame) +{ + NS_ASSERTION(mWaiting, "uh-oh, unexpectatly received a frame"); + if (!mSink) { + // silently drop frame + mWaiting = PR_FALSE; + if (mStreamOpen) { + CloseStream(); + mStreamOpen = PR_FALSE; + } + } + else if (!frame) { + // EOF + if (mStreamOpen) { + CloseStream(); + mStreamOpen = PR_FALSE; + } + mWaiting = PR_FALSE; + mSink->ProcessFrame(nsnull); + } + else { + if (!mStreamOpen) { + nsCOMPtr streamInfo; + frame->GetStreamInfo(getter_AddRefs(streamInfo)); + if (NS_FAILED(OpenStream(streamInfo))) + return NS_ERROR_FAILURE; + mStreamOpen = PR_TRUE; + } + mWaiting = PR_FALSE; + nsCOMPtr output_frame; + if (NS_FAILED(Filter(frame, getter_AddRefs(output_frame)))) + return NS_ERROR_FAILURE; + mSink->ProcessFrame(output_frame); + } + + return NS_OK; +} + diff --git a/mozilla/zap/zmk/src/zapFilterNode.h b/mozilla/zap/zmk/src/zapFilterNode.h new file mode 100644 index 00000000000..57246c03b17 --- /dev/null +++ b/mozilla/zap/zmk/src/zapFilterNode.h @@ -0,0 +1,78 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#ifndef __ZAP_FILTERNODE_H__ +#define __ZAP_FILTERNODE_H__ + +#include "zapIMediaNode.h" +#include "zapIMediaSource.h" +#include "zapIMediaSink.h" +#include "nsCOMPtr.h" + +//////////////////////////////////////////////////////////////////////// +// zapFilterNode: baseclass for filter-type nodes + +class zapFilterNode : public zapIMediaNode, + public zapIMediaSource, + public zapIMediaSink +{ + NS_DECL_ISUPPORTS + NS_DECL_ZAPIMEDIASOURCE + NS_DECL_ZAPIMEDIASINK + + // zapIMediaSource: + NS_IMETHOD GetSource(nsIPropertyBag2 *source_pars, zapIMediaSource **_retval); + NS_IMETHOD GetSink(nsIPropertyBag2 *sink_pars, zapIMediaSink **_retval); + + zapFilterNode(); + virtual ~zapFilterNode(); + + // methods to be implemented by subclass: + // NS_IMETHOD AddedToGraph(zapIMediaGraph *graph, const nsACString & id, nsIPropertyBag2 *node_pars) = 0; + // NS_IMETHOD RemovedFromGraph(zapIMediaGraph *graph) = 0; + virtual nsresult OpenStream(nsIPropertyBag2* streamInfo)=0; + virtual void CloseStream()=0; + virtual nsresult Filter(zapIMediaFrame* input, zapIMediaFrame** output)=0; + +private: + PRBool mStreamOpen; + PRBool mWaiting; + enum { IDLE_CLOSED, WAITING_CLOSED, IDLE_RUNNING, WAITING_RUNNING } mState; + nsCOMPtr mSink; + nsCOMPtr mSource; +}; + +#endif // __ZAP_FILTER_H__ diff --git a/mozilla/zap/zmk/src/zapIAudioDevice.idl b/mozilla/zap/zmk/src/zapIAudioDevice.idl new file mode 100644 index 00000000000..e19853a9df7 --- /dev/null +++ b/mozilla/zap/zmk/src/zapIAudioDevice.idl @@ -0,0 +1,46 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "nsISupports.idl" + +[scriptable, uuid(8696ffbc-f57e-4b4f-afe3-a7fd5ec2b534)] +interface zapIAudioDevice : nsISupports +{ + readonly attribute ACString name; + + readonly attribute unsigned long maxInputChannels; + readonly attribute unsigned long maxOutputChannels; +}; diff --git a/mozilla/zap/zmk/src/zapIAudioDeviceManager.idl b/mozilla/zap/zmk/src/zapIAudioDeviceManager.idl new file mode 100644 index 00000000000..04004f62cdc --- /dev/null +++ b/mozilla/zap/zmk/src/zapIAudioDeviceManager.idl @@ -0,0 +1,57 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "nsISupports.idl" + +interface zapIAudioDevice; + +%{ C++ +// {A0662AD8-3C64-483D-BA22-82AFC434CC2A} +#define ZAP_AUDIODEVICEMANAGER_CID \ +{ 0xa0662ad8, 0x3c64, 0x483d, { 0xba, 0x22, 0x82, 0xaf, 0xc4, 0x34, 0xcc, 0x2a } } + +#define ZAP_AUDIODEVICEMANAGER_CONTRACTID "@mozilla.org/zap/audiodevicemanager;1" +%} + +[scriptable, uuid(df3f2743-91a4-4a9e-b80a-1fdb6f5501c7)] +interface zapIAudioDeviceManager : nsISupports +{ + readonly attribute zapIAudioDevice defaultInputDevice; + readonly attribute zapIAudioDevice defaultOutputDevice; + + readonly attribute unsigned long deviceCount; + zapIAudioDevice getDeviceAt(in unsigned long pos); +}; diff --git a/mozilla/zap/zmk/src/zapIAudioIn.idl b/mozilla/zap/zmk/src/zapIAudioIn.idl new file mode 100644 index 00000000000..d60d76e37ba --- /dev/null +++ b/mozilla/zap/zmk/src/zapIAudioIn.idl @@ -0,0 +1,48 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "nsISupports.idl" + +interface zapIAudioDevice; + +[scriptable, uuid(cde103a9-19a9-410c-a457-7b38de07563f)] +interface zapIAudioIn : nsISupports +{ + void play(); + void stop(); + + readonly attribute zapIAudioDevice defaultInputDevice; +}; diff --git a/mozilla/zap/zmk/src/zapIAudioOut.idl b/mozilla/zap/zmk/src/zapIAudioOut.idl new file mode 100644 index 00000000000..1e4b7b3368c --- /dev/null +++ b/mozilla/zap/zmk/src/zapIAudioOut.idl @@ -0,0 +1,45 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "nsISupports.idl" + +interface zapIAudioDevice; + +[scriptable, uuid(ee5127c4-3e10-4efc-8ec5-6e66a65bf9fa)] +interface zapIAudioOut : nsISupports +{ + readonly attribute zapIAudioDevice defaultOutputDevice; +}; diff --git a/mozilla/zap/zmk/src/zapIDatagramFrame.idl b/mozilla/zap/zmk/src/zapIDatagramFrame.idl new file mode 100644 index 00000000000..a208f3c863d --- /dev/null +++ b/mozilla/zap/zmk/src/zapIDatagramFrame.idl @@ -0,0 +1,47 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "zapIMediaFrame.idl" + +[scriptable, uuid(7b851f67-6870-4bab-889d-00dc1c0fd7c3)] +interface zapIDatagramFrame : zapIMediaFrame +{ + /** + * remote address and port + */ + readonly attribute ACString address; + readonly attribute long port; +}; \ No newline at end of file diff --git a/mozilla/zap/zmk/src/zapIMediaFrame.idl b/mozilla/zap/zmk/src/zapIMediaFrame.idl new file mode 100644 index 00000000000..39976e515d7 --- /dev/null +++ b/mozilla/zap/zmk/src/zapIMediaFrame.idl @@ -0,0 +1,48 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "nsISupports.idl" + +interface nsIPropertyBag2; + +[scriptable, uuid(3330d074-7663-48bd-879b-6787267fbc20)] +interface zapIMediaFrame : nsISupports +{ + readonly attribute nsIPropertyBag2 streamInfo; + readonly attribute unsigned long timestamp; + readonly attribute ACString data; +}; + diff --git a/mozilla/zap/zmk/src/zapIMediaGraph.idl b/mozilla/zap/zmk/src/zapIMediaGraph.idl new file mode 100644 index 00000000000..cf7bd4148fe --- /dev/null +++ b/mozilla/zap/zmk/src/zapIMediaGraph.idl @@ -0,0 +1,84 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "nsISupports.idl" +interface nsIPropertyBag2; +interface nsIEventQueue; + +%{ C++ +// {CF53EEE9-5A2E-4533-92C4-0E37E50B2E01} +#define ZAP_MEDIAGRAPH_CID \ +{ 0xcf53eee9, 0x5a2e, 0x4533, { 0x92, 0xc4, 0x0e, 0x37, 0xe5, 0x0b, 0x2e, 0x01 } } + +#define ZAP_MEDIAGRAPH_CONTRACTID "@mozilla.org/zap/mediagraph;1" +%} + + +[scriptable, uuid(5fc78f9c-1cbb-4628-8863-d23e25beabe1)] +interface zapIMediaGraph : nsISupports +{ + /** Add node of 'type' and return its id in the graph + * The node will instantiated from the contractid + * "@mozilla.org/zap/medianode;type='type'". + */ + ACString addNode(in ACString type, in nsIPropertyBag2 node_pars); + + void removeNode(in ACString id_or_alias); + void getNode(in ACString id_or_alias, in nsIIDRef uuid, + in boolean synchronous, + [iid_is(uuid),retval] out nsQIResult result); + + /** Set or move alias to point to id_or_alias. + * Alias MUST NOT start with the special letter '#' which is + * reserved as a node id prefix. + */ + void setAlias(in ACString alias, in ACString id_or_alias); + + /** + * Connect source to sink and return id for the connection. + */ + ACString connect(in ACString source_node, in nsIPropertyBag2 source_pars, + in ACString sink_node, in nsIPropertyBag2 sink_pars); + + void disconnect(in ACString connection_id); + + void shutdown(); + + /** + * The event queue for this media graph + */ + readonly attribute nsIEventQueue eventQueue; +}; diff --git a/mozilla/zap/zmk/src/zapIMediaNode.idl b/mozilla/zap/zmk/src/zapIMediaNode.idl new file mode 100644 index 00000000000..f1a0d615825 --- /dev/null +++ b/mozilla/zap/zmk/src/zapIMediaNode.idl @@ -0,0 +1,82 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "nsISupports.idl" + +interface zapIMediaGraph; +interface zapIMediaSource; +interface zapIMediaSink; +interface nsIPropertyBag2; + +%{ C++ +#define ZAP_MEDIANODE_CONTRACTID_PREFIX "@mozilla.org/zap/medianode;type=" +%} + +[scriptable, uuid(8477a773-8b2e-4e8b-8ca7-d37886750074)] +interface zapIMediaNode : nsISupports +{ + /** + * Called when this node is first added to a media graph. + * 'id' is the identifier by which this node will be known + * in 'graph'. + */ + void addedToGraph(in zapIMediaGraph graph, in ACString id, + in nsIPropertyBag2 node_pars); + + /** + * Called when this node is removed from the graph. + * The framework will call this method only after all connections + * have been disconnected. + */ + void removedFromGraph(in zapIMediaGraph graph); + + /** + * Return a source with the given parameters. + * Throw error if the source as characterized by the parameter map + * is not supported, if this is a sink-only node, or if the node + * can't take any more connections. + */ + zapIMediaSource getSource(in nsIPropertyBag2 source_pars); + + /** + * Returns a sink with the given parameters. + * Throws error if the sink as characterized by the parameter map + * is not supported, if this is a source-only node, or if the node + * can't take any more connections. + */ + zapIMediaSink getSink(in nsIPropertyBag2 sink_pars); +}; + diff --git a/mozilla/zap/zmk/src/zapIMediaSink.idl b/mozilla/zap/zmk/src/zapIMediaSink.idl new file mode 100644 index 00000000000..e5450cf2c36 --- /dev/null +++ b/mozilla/zap/zmk/src/zapIMediaSink.idl @@ -0,0 +1,62 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "nsISupports.idl" + +interface zapIMediaSource; +interface zapIMediaFrame; + +[scriptable, uuid(76ab2487-e3bb-41de-872e-e587fc790ec5)] +interface zapIMediaSink : nsISupports +{ + /** + * Called by the graph to connect a source to this sink. + * Will be called after a successful source->connectSink(). + */ + void connectSource(in zapIMediaSource source, in ACString connection_id); + + /** + * Called by the graph to disconnect the previously connected source + * from this sink. Will be followed by a call source->disconnectSink(). + */ + void disconnectSource(in zapIMediaSource source, in ACString connection_id); + + /** + * Called by a source in response to a previous + * requestFrame() call. + */ + void processFrame(in zapIMediaFrame frame); +}; diff --git a/mozilla/zap/zmk/src/zapIMediaSource.idl b/mozilla/zap/zmk/src/zapIMediaSource.idl new file mode 100644 index 00000000000..fffd10195f1 --- /dev/null +++ b/mozilla/zap/zmk/src/zapIMediaSource.idl @@ -0,0 +1,63 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "nsISupports.idl" + +interface zapIMediaSink; + +[scriptable, uuid(4bee7ec8-baa5-49e5-9c73-2baf869fa8ba)] +interface zapIMediaSource : nsISupports +{ + /** + * Called by the graph to connect a sink to this source. + * On success, will be followed by a call sink->connectSource(). + */ + void connectSink(in zapIMediaSink sink, in ACString connection_id); + + /** + * Called by the graph to disconnect the previously connected sink + * from this source. Will be called after sink->disconnectSource(). + */ + void disconnectSink(in zapIMediaSink sink, in ACString connection_id); + + /** + * Called by a sink to request the first or next media frame. The + * source must call processFrame() on the sink as soon as a frame + * becomes available. The processFrame() call may be nested in the + * request or scheduled. + */ + void requestFrame(); +}; diff --git a/mozilla/zap/zmk/src/zapIPortaudioDevice.idl b/mozilla/zap/zmk/src/zapIPortaudioDevice.idl new file mode 100644 index 00000000000..c6f1d9fb1ff --- /dev/null +++ b/mozilla/zap/zmk/src/zapIPortaudioDevice.idl @@ -0,0 +1,43 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "nsISupports.idl" + +[scriptable, uuid(a799474b-ba7b-40ad-9a33-fe7db12d6408)] +interface zapIPortaudioDevice : nsISupports +{ + readonly attribute PRInt32 deviceID; +}; diff --git a/mozilla/zap/zmk/src/zapIRTPFrame.idl b/mozilla/zap/zmk/src/zapIRTPFrame.idl new file mode 100644 index 00000000000..55666954deb --- /dev/null +++ b/mozilla/zap/zmk/src/zapIRTPFrame.idl @@ -0,0 +1,104 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "zapIMediaFrame.idl" + +/** + * An RFC3550 RTP media frame. + */ +[scriptable, uuid(ffbf6655-d72d-41a9-b90a-6bebd2dde428)] +interface zapIRTPFrame : zapIMediaFrame +{ + /** + * V header field (2 bits) + */ + attribute unsigned short version; + + /** + * P header field (1 bit) + */ + attribute boolean padding; + + /** + * X header field (1 bit) + */ + attribute boolean extension; + + /** + * CC header field (4 bits) + */ + attribute unsigned short CSRCCount; + + /** + * M header field (1 bit) + */ + attribute unsigned short marker; + + /** + * PT header field (7 bits) + */ + attribute unsigned short payloadType; + + /** + * Sequence number header field (16 bits) + */ + attribute unsigned short sequenceNumber; + + /** + * Timestamp header field (32 bits) + */ + attribute unsigned long rtpTimestamp; + + /** + * SSRC header field (32 bits) + */ + attribute unsigned long SSRC; + + /** + * CSRC header list (0 to 15 items, 32 bits each) + * 'index' must be between 0 and CSRCCount-1 + */ + unsigned long getCSRC(in unsigned short index); + void setCSRC(in unsigned short index, in unsigned long CSRC); + + // XXX add accessor for extension header + + /** + * Packet payload + */ + attribute ACString payload; +}; + diff --git a/mozilla/zap/zmk/src/zapISpeexEncoder.idl b/mozilla/zap/zmk/src/zapISpeexEncoder.idl new file mode 100644 index 00000000000..be7f93ae002 --- /dev/null +++ b/mozilla/zap/zmk/src/zapISpeexEncoder.idl @@ -0,0 +1,89 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "nsISupports.idl" + +[scriptable, uuid(3e19e795-0305-4450-9c2a-b7b888700170)] +interface zapISpeexEncoder : nsISupports +{ + /** + * Set encoder speech quality. + * (integer between 0 and 10) + */ + void SetQuality(in unsigned long quality); + + /** + * Toggles variable bit-rate encoding + */ + attribute boolean vbr; + + /** + * Encoder vbr speech quality. + * (float between 0 and 10) + */ + attribute float vbrQuality; + + /** + * CPU resources allowed for encoder (integer between 0 and 10) + */ + attribute unsigned long complexity; + + /** + * Toggle voice activity detection + */ + attribute boolean vad; + + /** + * Toggle discontinuous transmission + */ + attribute boolean dtx; + + /** + * Average bitrate (bps). + */ + attribute unsigned long averageBitrate; + + /** + * Maximum bitrate (bps). + */ + attribute unsigned long maxBitrate; + + /** + * optimize encoding for a certain percentage of packet loss. + * (integer in percent) + */ + attribute unsigned long plcTuning; +}; diff --git a/mozilla/zap/zmk/src/zapIUDPSocket.idl b/mozilla/zap/zmk/src/zapIUDPSocket.idl new file mode 100644 index 00000000000..9c94353f649 --- /dev/null +++ b/mozilla/zap/zmk/src/zapIUDPSocket.idl @@ -0,0 +1,43 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "nsISupports.idl" + +[scriptable, uuid(cbe6328c-1ad6-437b-9576-6fb3524b0537)] +interface zapIUDPSocket : nsISupports +{ + readonly attribute unsigned short port; +}; diff --git a/mozilla/zap/zmk/src/zapIUDPSocketPair.idl b/mozilla/zap/zmk/src/zapIUDPSocketPair.idl new file mode 100644 index 00000000000..6ddaf66a47d --- /dev/null +++ b/mozilla/zap/zmk/src/zapIUDPSocketPair.idl @@ -0,0 +1,44 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "nsISupports.idl" + +[scriptable, uuid(0b7efe5e-e68f-42c0-8128-d2ebf833212a)] +interface zapIUDPSocketPair : nsISupports +{ + readonly attribute unsigned short portA; + readonly attribute unsigned short portB; +}; diff --git a/mozilla/zap/zmk/src/zapMediaFrame.cpp b/mozilla/zap/zmk/src/zapMediaFrame.cpp new file mode 100644 index 00000000000..55791658230 --- /dev/null +++ b/mozilla/zap/zmk/src/zapMediaFrame.cpp @@ -0,0 +1,95 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "zapMediaFrame.h" +#include "stdio.h" + +//////////////////////////////////////////////////////////////////////// +// zapMediaFrame + +zapMediaFrame::zapMediaFrame() +{ +#ifdef DEBUG +// printf("/"); +#endif +} + +zapMediaFrame::~zapMediaFrame() +{ +#ifdef DEBUG +// printf("\\"); +#endif +} + +//---------------------------------------------------------------------- +// nsISupports methods: + +NS_IMPL_THREADSAFE_ADDREF(zapMediaFrame) +NS_IMPL_THREADSAFE_RELEASE(zapMediaFrame) + +NS_INTERFACE_MAP_BEGIN(zapMediaFrame) + NS_INTERFACE_MAP_ENTRY(nsISupports) + NS_INTERFACE_MAP_ENTRY(zapIMediaFrame) +NS_INTERFACE_MAP_END + +//---------------------------------------------------------------------- +// zapIMediaFrame methods: + +/* readonly attribute nsIPropertyBag2 streamInfo; */ +NS_IMETHODIMP +zapMediaFrame::GetStreamInfo(nsIPropertyBag2** aStreamInfo) +{ + *aStreamInfo = mStreamInfo.get(); + NS_IF_ADDREF(*aStreamInfo); + return NS_OK; +} + +/* readonly attribute unsigned long timestamp; */ +NS_IMETHODIMP +zapMediaFrame::GetTimestamp(PRUint32 *aTimestamp) +{ + *aTimestamp = mTimestamp; + return NS_OK; +} + +/* readonly attribute ACString data; */ +NS_IMETHODIMP +zapMediaFrame::GetData(nsACString & aData) +{ + aData = mData; + return NS_OK; +} + diff --git a/mozilla/zap/zmk/src/zapMediaFrame.h b/mozilla/zap/zmk/src/zapMediaFrame.h new file mode 100644 index 00000000000..c96b3043722 --- /dev/null +++ b/mozilla/zap/zmk/src/zapMediaFrame.h @@ -0,0 +1,59 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#ifndef __ZAP_MEDIAFRAME_H__ +#define __ZAP_MEDIAFRAME_H__ + +#include "zapIMediaFrame.h" +#include "nsString.h" +#include "nsIPropertyBag2.h" +#include "nsCOMPtr.h" + +class zapMediaFrame : public zapIMediaFrame +{ +public: + NS_DECL_ISUPPORTS + NS_DECL_ZAPIMEDIAFRAME + + zapMediaFrame(); + ~zapMediaFrame(); + + nsCString mData; + PRUint32 mTimestamp; + nsCOMPtr mStreamInfo; +}; + +#endif // __ZAP_MEDIAFRAME_H__ diff --git a/mozilla/zap/zmk/src/zapMediaGraph.cpp b/mozilla/zap/zmk/src/zapMediaGraph.cpp new file mode 100644 index 00000000000..d59f6fc0b8d --- /dev/null +++ b/mozilla/zap/zmk/src/zapMediaGraph.cpp @@ -0,0 +1,576 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "zapMediaGraph.h" +#include "nsIProxyObjectManager.h" +#include "nsIServiceManager.h" +#include "prmem.h" +#include "stdio.h" +#include "zapIMediaSource.h" +#include "zapIMediaSink.h" +#include "nsIPropertyBag2.h" + +// ConstructMediaGraph will create a media graph on a new thread and +// return a (nearly) threadsafe proxy. +// If SAME_THREAD_MEDIA_GRAPH is set, the media graph will be created +// on the calling thread. This might be useful for debugging +//#define SAME_THREAD_MEDIA_GRAPH 1 + + +static NS_DEFINE_CID(kEventQueueServiceCID, NS_EVENTQUEUESERVICE_CID); + + +//////////////////////////////////////////////////////////////////////// +// zapMediaGraph + +zapMediaGraph::zapMediaGraph() + : mPumpingEvents(PR_FALSE), + mNodeIdCounter(0), + mConnectionIdCounter(0) +{ +#ifdef DEBUG + printf("zapMediaGraph::zapMediaGraph()\n"); +#endif + + mNodes = new Descriptor(); + mConnections = new Descriptor(); +} + +zapMediaGraph::~zapMediaGraph() +{ +#ifdef DEBUG + printf("zapMediaGraph::~zapMediaGraph()\n"); +#endif + Shutdown(); + + NS_ASSERTION(mNodes && mNodes->prev == mNodes && mNodes->next == mNodes, + "corrupt node list"); + delete mNodes; + + NS_ASSERTION(mConnections && mConnections->prev == mConnections && + mConnections->next == mConnections, + "corrupt connection list"); + delete mConnections; +} + +//---------------------------------------------------------------------- +// nsISupports methods: + +NS_IMPL_THREADSAFE_ADDREF(zapMediaGraph) + +void* ShutdownEventHandler(PLEvent *event) +{ + zapMediaGraph* owner = (zapMediaGraph*)PL_GetEventOwner(event); + owner->mPumpingEvents = PR_FALSE; + return nsnull; +} + +void ShutdownDestroyHandler(PLEvent *event) +{ + PR_FREEIF(event); +} + +NS_IMETHODIMP_(nsrefcnt) +zapMediaGraph::Release() +{ + nsrefcnt count; + NS_PRECONDITION(mRefCnt != 0, "dup release"); + count = PR_AtomicDecrement((PRInt32 *)&mRefCnt); + NS_LOG_RELEASE(this, count, "zapMediaGraph"); + + if (count == 0) { + mRefCnt = 1; // stabilize + NS_DELETEXPCOM(this); + return 0; + } +#ifndef SAME_THREAD_MEDIA_GRAPH + else if (count == 1) { + // By this time we should only have the nsIThread object holding onto us. + if (!mEventQ) { + // Hmm... we could have a race condition here if the + // proxification failed. + NS_ERROR("Uh-oh, we haven't got an event queue. Potential race condition. We might leave a thread running!"); + } + else { + // Spin down event loop. This will exit Run() and the nsIThread + // will release us. + PLEvent *event = PR_NEW(PLEvent); + + PL_InitEvent(event, this, ShutdownEventHandler, ShutdownDestroyHandler); + mEventQ->PostEvent(event); + } + } +#endif + return count; +} + +NS_INTERFACE_MAP_BEGIN(zapMediaGraph) + NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIRunnable) + NS_INTERFACE_MAP_ENTRY(zapIMediaGraph) + NS_INTERFACE_MAP_ENTRY(nsIRunnable) +NS_INTERFACE_MAP_END + +//---------------------------------------------------------------------- +// nsIRunnable methods: + +NS_IMETHODIMP +zapMediaGraph::Run() +{ + nsresult rv = NS_OK; + + nsIThread::GetCurrent(getter_AddRefs(mMediaThread)); + if (!mMediaThread) return NS_ERROR_FAILURE; + + nsCOMPtr eventQService = + do_GetService(kEventQueueServiceCID); + if (!eventQService) return NS_ERROR_FAILURE; + +#ifdef SAME_THREAD_MEDIA_GRAPH + eventQService->GetSpecialEventQueue(nsIEventQueueService::CURRENT_THREAD_EVENT_QUEUE, getter_AddRefs(mEventQ)); +#else + // create an event queue: + eventQService->CreateFromIThread(mMediaThread, PR_FALSE, + getter_AddRefs(mEventQ)); +#endif + + if (!mEventQ) return NS_ERROR_FAILURE; + +#ifndef SAME_THREAD_MEDIA_GRAPH + // run event loop: +#ifdef DEBUG + printf("running media thread\n"); +#endif + + PLEvent *event; + mPumpingEvents = PR_TRUE; + + while (mPumpingEvents) { +#ifdef DEBUG +// printf("."); +#endif + rv = mEventQ->WaitForEvent(&event); + NS_ASSERTION(NS_SUCCEEDED(rv), "WaitForEvent error"); + if (NS_SUCCEEDED(rv)) { + rv = mEventQ->HandleEvent(event); + NS_ASSERTION(NS_SUCCEEDED(rv), "HandleEvent error"); + } + } + + // clean up: + eventQService->DestroyThreadEventQueue(); + mEventQ = nsnull; +#endif // !SAME_THREAD_MEDIA_GRAPH + + return rv; +} + +//---------------------------------------------------------------------- +// Implementation helpers: + +zapMediaGraph::NodeDescriptor* +zapMediaGraph::ResolveNodeDescriptor(const nsACString& id_or_alias) +{ + Descriptor* t = mNodes->next; + + // find target (an alias or node): + while (1) { + if (t->type == Descriptor::SENTINEL) return nsnull; + if (t->name == id_or_alias) break; + t = t->next; + } + + // resolve aliases: + while (t->type == Descriptor::ALIAS) { + t = ((AliasDescriptor*)t)->target; + } + + NS_ASSERTION(t->type == Descriptor::NODE, "corrupt node list"); + + return NS_STATIC_CAST(NodeDescriptor*, t); +} + +void +zapMediaGraph::RemoveDescriptor(Descriptor* d) +{ + // remove descriptor d from list: + d->prev->next = d->next; + d->next->prev = d->prev; + + // recursively remove all descriptors pointing to d: + Descriptor* p = mNodes; + while ((p = p->next)->type != Descriptor::SENTINEL) { + if (p->type == Descriptor::ALIAS && + ((AliasDescriptor*)p)->target == d) { + RemoveDescriptor(p); + // restart from beginning, because the list will have changed. + // this could be made more efficient, but our list should always + // be relatively small and aliasing not deep. + p = mNodes; + } + } + + if (d->type == Descriptor::NODE) { + RemoveNodeDescriptorConnections(NS_STATIC_CAST(NodeDescriptor*, d)); + NS_STATIC_CAST(NodeDescriptor*, d)->node->RemovedFromGraph(this); + } + delete d; +} + +void +zapMediaGraph::RemoveConnection(ConnectionDescriptor* d) +{ + // remove descriptor from list: + d->prev->next = d->next; + d->next->prev = d->prev; + + d->sink->DisconnectSource(d->src, d->name); + d->src->DisconnectSink(d->sink, d->name); + delete d; +} + +void +zapMediaGraph::RemoveNodeDescriptorConnections(NodeDescriptor* d) +{ + // search for connections pointing to d and remove them: + Descriptor* p = mConnections; + while((p = p->next)->type != Descriptor::SENTINEL) { + if (NS_STATIC_CAST(ConnectionDescriptor*, p)->src_nd == d || + NS_STATIC_CAST(ConnectionDescriptor*, p)->sink_nd == d) { + RemoveConnection(NS_STATIC_CAST(ConnectionDescriptor*, p)); + // restart from beginning, because the list might have changed. + // this could be made more efficient, but our list should be + // relatively small. + p = mConnections; + } + } +} + +//---------------------------------------------------------------------- +// zapIMediaGraph methods: + +/* ACString addNode (in ACString type, in nsIPropertyBag2 node_pars); */ +NS_IMETHODIMP +zapMediaGraph::AddNode(const nsACString & type, nsIPropertyBag2* node_pars, + nsACString & _retval) +{ + // create a new instance of the given type: + nsCString clazz = NS_LITERAL_CSTRING(ZAP_MEDIANODE_CONTRACTID_PREFIX)+type; +#ifdef DEBUG + printf("Trying to instantiate component %s\n", clazz.get()); +#endif + nsCOMPtr node = do_CreateInstance(clazz.get()); + if (!node) return NS_ERROR_FAILURE; + + // make a new id: + nsCString id = NS_LITERAL_CSTRING("#"); + id.AppendInt(mNodeIdCounter++); + + // insert into node list: + NodeDescriptor *descriptor = new NodeDescriptor(id, node, mNodes, mNodes->next); + mNodes->next = descriptor; + descriptor->next->prev = descriptor; + + // finally inform the node that it has been added to the graph: + if (NS_FAILED(node->AddedToGraph(this, id, node_pars))) { + // remove descriptor and all nodes pointing to it from list: + RemoveDescriptor(descriptor); + return NS_ERROR_FAILURE; + } + + _retval = id; + + return NS_OK; +} + +/* void removeNode (in ACString id_or_alias); */ +NS_IMETHODIMP +zapMediaGraph::RemoveNode(const nsACString & id_or_alias) +{ + NodeDescriptor* d = ResolveNodeDescriptor(id_or_alias); + if (!d) { + NS_WARNING("Target node not found"); + return NS_ERROR_FAILURE; + } + RemoveDescriptor(d); + return NS_OK; +} + + + /* void getNode (in ACString id_or_alias, in nsIIDRef uuid, in boolean synchronous, [iid_is (uuid), retval] out nsQIResult result); */ +NS_IMETHODIMP +zapMediaGraph::GetNode(const nsACString & id_or_alias, + const nsIID & uuid, PRBool synchronous, + void * *result) +{ + NodeDescriptor* nd = ResolveNodeDescriptor(id_or_alias); + if (!nd) { + NS_ERROR("Target node not found"); + *result = nsnull; + return NS_ERROR_FAILURE; + } + if (synchronous) + return nd->node->QueryInterface(uuid, result); + else + return NS_GetProxyForObject(mEventQ, uuid, nd->node, + PROXY_ASYNC | PROXY_ALWAYS | + PROXY_AUTOPROXIFY | PROXY_ISUPPORTS, + result); +} + +/* void setAlias (in ACString alias, in ACString id_or_alias); */ +NS_IMETHODIMP +zapMediaGraph::SetAlias(const nsACString & alias, const nsACString & id_or_alias) +{ + // check if alias name is allowed: + if (!alias.IsEmpty()) { + nsACString::const_iterator p; + alias.BeginReading(p); + if (*p == '#') { + NS_ERROR("Disallowed alias name"); + return NS_ERROR_FAILURE; + } + } + + // look for target node: + Descriptor* t = mNodes->next; + while(1) { + if (t->type == Descriptor::SENTINEL) { + NS_ERROR("Target node not found"); + return NS_ERROR_FAILURE; + } + if (t->name == id_or_alias) break; + t= t->next; + } + + // look for node with the alias name: + Descriptor* a = mNodes; + while ((a = a->next)->type != Descriptor::SENTINEL) { + if (a->name == alias) { + if (a->type == Descriptor::NODE) { + NS_ERROR("Alias clashes with a node name"); + return NS_ERROR_FAILURE; + } + break; + } + } + + if (a->type == Descriptor::SENTINEL) { + // create a new alias descriptor: + a = new AliasDescriptor(alias, t, mNodes, mNodes->next); + mNodes->next = a; + a->next->prev = a; + } + else { + // move exisiting alias to new target: + NS_ASSERTION(a->type == Descriptor::ALIAS, "node not an alias ?!?"); + ((AliasDescriptor*)a)->target = t; + } + + return NS_OK; +} + +/* ACString connect (in ACString source_node, in zapIMap source_pars, in ACString sink_node, in nsIPropertyBag2 sink_pars); */ +NS_IMETHODIMP +zapMediaGraph::Connect(const nsACString & source_node_id, nsIPropertyBag2 *source_pars, + const nsACString & sink_node_id, nsIPropertyBag2 *sink_pars, + nsACString & _retval) +{ + NodeDescriptor* src_nd = ResolveNodeDescriptor(source_node_id); + if (!src_nd) { + NS_ERROR("Source node not found"); + return NS_ERROR_FAILURE; + } + nsCOMPtr sourcenode = src_nd->node; + + NodeDescriptor* sink_nd = ResolveNodeDescriptor(sink_node_id); + if (!sink_nd) { + NS_ERROR("Sink node not found"); + return NS_ERROR_FAILURE; + } + nsCOMPtr sinknode = sink_nd->node; + + // obtain source: + nsCOMPtr source; + nsresult rv = sourcenode->GetSource(source_pars, getter_AddRefs(source)); + if (NS_FAILED(rv)) return rv; + + // obtain sink: + nsCOMPtr sink; + rv = sinknode->GetSink(sink_pars, getter_AddRefs(sink)); + if (NS_FAILED(rv)) return rv; + + // generate new connection id: + nsCString id = NS_LITERAL_CSTRING("~"); + id.AppendInt(mConnectionIdCounter++); + + // try to form connection: + rv = source->ConnectSink(sink, id); + if (NS_FAILED(rv)) return rv; + rv = sink->ConnectSource(source, id); + if (NS_FAILED(rv)) { + source->DisconnectSink(sink, id); + return rv; + } + + // insert connection into list: + // XXX possibly we need to move this before the connect{sink,source} calls + // and clean up in error case + ConnectionDescriptor *descriptor = new ConnectionDescriptor(id, src_nd, sink_nd, source, sink, mConnections, mConnections->next); + mConnections->next = descriptor; + descriptor->next->prev = descriptor; + + _retval = id; + + return NS_OK; +} + +/* void disconnect (in ACString connection_id); */ +NS_IMETHODIMP +zapMediaGraph::Disconnect(const nsACString & connection_id) +{ + // find connection: + Descriptor* t = mConnections->next; + + while (1) { + if (t->type == Descriptor::SENTINEL) { + NS_ERROR("Connection not found"); + return NS_ERROR_FAILURE; + } + if (t->name == connection_id) break; + t = t->next; + } + + RemoveConnection(NS_STATIC_CAST(ConnectionDescriptor*, t)); + return NS_OK; +} + + +/* void shutdown (); */ +NS_IMETHODIMP +zapMediaGraph::Shutdown() +{ + // release all nodes in a robust way: + while (mNodes->next->type != Descriptor::SENTINEL) + RemoveDescriptor(mNodes->next); + + // Don't set mPumpingEvents to false here! If we still have a proxy + // holding onto us it would block. We have to keep pumping events + // until our ref count goes down to one. The event loop will be spun + // down from Release(). + return NS_OK; +} + +/* readonly attribute nsIEventQueue eventQueue; */ +NS_IMETHODIMP +zapMediaGraph::GetEventQueue(nsIEventQueue * *aEventQueue) +{ + *aEventQueue = mEventQ; + NS_IF_ADDREF(*aEventQueue); + return NS_OK; +} + + +//---------------------------------------------------------------------- +// Constructor function: + + +NS_IMETHODIMP ConstructMediaGraph(nsISupports *aOuter, REFNSIID aIID, + void **result) +{ + nsresult rv = NS_OK; + *result = nsnull; + + if (aOuter != nsnull) return NS_ERROR_NO_AGGREGATION; + + nsCOMPtr eventQService = + do_GetService(kEventQueueServiceCID); + if (!eventQService) { + NS_ERROR("Can't get event queue service"); + return NS_ERROR_FAILURE; + } + nsIRunnable* mediaGraph = (nsIRunnable*) new zapMediaGraph(); + if (!mediaGraph) return NS_ERROR_OUT_OF_MEMORY; + NS_ADDREF(mediaGraph); + + nsCOMPtr mediaThread; + nsCOMPtr eventQ; + +#ifdef SAME_THREAD_MEDIA_GRAPH + nsIThread::GetCurrent(getter_AddRefs(mediaThread)); + eventQService->GetSpecialEventQueue(nsIEventQueueService::CURRENT_THREAD_EVENT_QUEUE, + getter_AddRefs(eventQ)); + // For the 'SAME THREAD' case, Run() doesn't go into an event loop, + // but it still has to be called to initialize the media graph: + rv = mediaGraph->Run(); + if (NS_FAILED(rv)) { + NS_ERROR("media graph initialization error"); + NS_RELEASE(mediaGraph); + return NS_ERROR_FAILURE; + } +#else + // Create a new thread and run the media graph: + NS_NewThread(getter_AddRefs(mediaThread), mediaGraph, 0, PR_UNJOINABLE_THREAD, + PR_PRIORITY_HIGH); + if (!mediaThread) { + NS_RELEASE(mediaGraph); + return NS_ERROR_FAILURE; + } + + // Get the thread's event queue. We call CreateFromIThread() instead + // of GetThreadEventQueue() to make sure that the event queue + // exists. This avoids potential race conditions in case Run() + // hasn't had a chance to create the queue yet. + eventQService->CreateFromIThread(mediaThread, PR_FALSE, + getter_AddRefs(eventQ)); +#endif + + if (!eventQ) { + NS_ERROR("Strange. Couldn't get event queue"); + NS_RELEASE(mediaGraph); + return NS_ERROR_FAILURE; + } + + // Return a proxy for the media graph: + rv = NS_GetProxyForObject(eventQ, aIID, mediaGraph, + PROXY_SYNC | PROXY_ALWAYS | PROXY_AUTOPROXIFY | PROXY_ISUPPORTS, + result); + if (NS_FAILED(rv)) { + NS_ERROR("proxification failure. potential race condition."); + } + NS_RELEASE(mediaGraph); + + return rv; +} diff --git a/mozilla/zap/zmk/src/zapMediaGraph.h b/mozilla/zap/zmk/src/zapMediaGraph.h new file mode 100644 index 00000000000..3c171429868 --- /dev/null +++ b/mozilla/zap/zmk/src/zapMediaGraph.h @@ -0,0 +1,148 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#ifndef __ZAP_MEDIAGRAPH_H__ +#define __ZAP_MEDIAGRAPH_H__ + +#include "zapIMediaGraph.h" +#include "nsIEventQueue.h" +#include "nsIThread.h" +#include "nsIRunnable.h" +#include "nsCOMPtr.h" +#include "nsAutoPtr.h" +#include "zapIMediaNode.h" +#include "nsString.h" + +class zapMediaGraph : public zapIMediaGraph, + public nsIRunnable +{ +public: + NS_DECL_ISUPPORTS + NS_DECL_ZAPIMEDIAGRAPH + NS_DECL_NSIRUNNABLE + + zapMediaGraph(); + ~zapMediaGraph(); + +private: + // A media graph is unlikely to contain many nodes (<< 20), so we + // use a simple linked lists rather than a hashtable to keep track + // of nodes, aliases and connections: + + struct Descriptor { + Descriptor() : type(SENTINEL) { prev = this; next = this; }; + virtual ~Descriptor() {}; + + enum { NODE, ALIAS, CONNECTION, SENTINEL } type; + nsCString name; + Descriptor* prev; + Descriptor* next; + }; + + struct NodeDescriptor : public Descriptor { + NodeDescriptor(const nsACString& _name, zapIMediaNode* _node, + Descriptor* _prev, Descriptor* _next) + : node(_node) { + type = NODE; + name = _name; + prev = _prev; + next = _next; + }; + + nsCOMPtr node; + }; + + struct AliasDescriptor : public Descriptor { + AliasDescriptor(const nsACString& _name, Descriptor* _target, + Descriptor* _prev, Descriptor* _next) + : target(_target) { + type = ALIAS; + name = _name; + prev = _prev; + next = _next; + }; + + Descriptor* target; + }; + + struct ConnectionDescriptor : public Descriptor { + ConnectionDescriptor(const nsACString& _name, + NodeDescriptor* _src_nd, + NodeDescriptor* _sink_nd, + zapIMediaSource* _src, + zapIMediaSink* _sink, + Descriptor* _prev, Descriptor* _next) + : src_nd(_src_nd), sink_nd(_sink_nd), + src(_src), sink(_sink) + { + type = CONNECTION; + name = _name; + prev = _prev; + next = _next; + }; + + NodeDescriptor* src_nd; + NodeDescriptor* sink_nd; + nsCOMPtr src; + nsCOMPtr sink; + }; + + // List of nodes and Aliases. Only contains descriptors of type + // ALIAS, NODE and SENTINEL. + Descriptor* mNodes; + + // List of connections. Only contains descriptors of type CONNECTION + // and SENTINEL. + Descriptor* mConnections; + + NodeDescriptor* ResolveNodeDescriptor(const nsACString& id_or_alias); + void RemoveDescriptor(Descriptor* d); + void RemoveConnection(ConnectionDescriptor* d); + void RemoveNodeDescriptorConnections(NodeDescriptor* d); + + nsCOMPtr mMediaThread; + nsCOMPtr mEventQ; + PRBool mPumpingEvents; + PRUint32 mNodeIdCounter; + PRUint32 mConnectionIdCounter; + + friend void* ShutdownEventHandler(PLEvent *self); +}; + +// constructor to obtain a proxied zapMediaGraph object: +NS_IMETHODIMP ConstructMediaGraph(nsISupports *aOuter, REFNSIID aIID, void **result); + +#endif // __ZAP_MEDIAGRAPH_H__ diff --git a/mozilla/zap/zmk/src/zapMediaModule.cpp b/mozilla/zap/zmk/src/zapMediaModule.cpp new file mode 100644 index 00000000000..5aca85c3070 --- /dev/null +++ b/mozilla/zap/zmk/src/zapMediaModule.cpp @@ -0,0 +1,142 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "nsIGenericFactory.h" +#include "zapMediaGraph.h" +#include "zapAudioDeviceManager.h" +#include "zapAudioIn.h" +#include "zapAudioOut.h" +#include "zapPacketBuffer.h" +#include "zapSpeexEncoder.h" +#include "zapSpeexDecoder.h" +#include "zapSpeexRTPPacketizer.h" +#include "zapSpeexRTPDepacketizer.h" +#include "zapUDPSocket.h" +#include "zapUDPSocketPair.h" +#include "zapRTPTransmitter.h" +#include "zapRTPReceiver.h" +#include "zapRTPSession.h" + +NS_GENERIC_FACTORY_CONSTRUCTOR(zapAudioDeviceManager) +NS_GENERIC_FACTORY_CONSTRUCTOR(zapAudioIn) +NS_GENERIC_FACTORY_CONSTRUCTOR(zapAudioOut) +NS_GENERIC_FACTORY_CONSTRUCTOR(zapPacketBuffer) +NS_GENERIC_FACTORY_CONSTRUCTOR(zapSpeexEncoder) +NS_GENERIC_FACTORY_CONSTRUCTOR(zapSpeexDecoder) +NS_GENERIC_FACTORY_CONSTRUCTOR(zapSpeexRTPPacketizer) +NS_GENERIC_FACTORY_CONSTRUCTOR(zapSpeexRTPDepacketizer) +NS_GENERIC_FACTORY_CONSTRUCTOR(zapUDPSocket) +NS_GENERIC_FACTORY_CONSTRUCTOR(zapUDPSocketPair) +NS_GENERIC_FACTORY_CONSTRUCTOR(zapRTPTransmitter) +NS_GENERIC_FACTORY_CONSTRUCTOR(zapRTPReceiver) +NS_GENERIC_FACTORY_CONSTRUCTOR(zapRTPSession) + +static const nsModuleComponentInfo gComponents[] = +{ + { "Mozilla ZMK Media Graph", + ZAP_MEDIAGRAPH_CID, + ZAP_MEDIAGRAPH_CONTRACTID, + ConstructMediaGraph + }, + { "Mozilla ZMK Audio Device Manager", + ZAP_AUDIODEVICEMANAGER_CID, + ZAP_AUDIODEVICEMANAGER_CONTRACTID, + zapAudioDeviceManagerConstructor + }, + { "Mozilla ZMK Audio In", + ZAP_AUDIOIN_CID, + ZAP_AUDIOIN_CONTRACTID, + zapAudioInConstructor + }, + { "Mozilla ZMK Audio Out", + ZAP_AUDIOOUT_CID, + ZAP_AUDIOOUT_CONTRACTID, + zapAudioOutConstructor + }, + { "Mozilla ZMK Media Packet Buffer", + ZAP_PACKETBUFFER_CID, + ZAP_PACKETBUFFER_CONTRACTID, + zapPacketBufferConstructor + }, + { "Mozilla ZMK Speex Encoder", + ZAP_SPEEXENCODER_CID, + ZAP_SPEEXENCODER_CONTRACTID, + zapSpeexEncoderConstructor + }, + { "Mozilla ZMK Speex Decoder", + ZAP_SPEEXDECODER_CID, + ZAP_SPEEXDECODER_CONTRACTID, + zapSpeexDecoderConstructor + }, + { "Mozilla ZMK Speex RTP Packetizer", + ZAP_SPEEXRTPPACKETIZER_CID, + ZAP_SPEEXRTPPACKETIZER_CONTRACTID, + zapSpeexRTPPacketizerConstructor + }, + { "Mozilla ZMK Speex RTP Depacketizer", + ZAP_SPEEXRTPDEPACKETIZER_CID, + ZAP_SPEEXRTPDEPACKETIZER_CONTRACTID, + zapSpeexRTPDepacketizerConstructor + }, + { "Mozilla ZMK UDP Socket", + ZAP_UDPSOCKET_CID, + ZAP_UDPSOCKET_CONTRACTID, + zapUDPSocketConstructor + }, + { "Mozilla ZMK UDP Socket Pair", + ZAP_UDPSOCKETPAIR_CID, + ZAP_UDPSOCKETPAIR_CONTRACTID, + zapUDPSocketPairConstructor + }, + { "Mozilla ZMK RTP Transmitter", + ZAP_RTPTRANSMITTER_CID, + ZAP_RTPTRANSMITTER_CONTRACTID, + zapRTPTransmitterConstructor + }, + { "Mozilla ZMK RTP Receiver", + ZAP_RTPRECEIVER_CID, + ZAP_RTPRECEIVER_CONTRACTID, + zapRTPReceiverConstructor + }, + { "Mozilla ZMK RTP Session", + ZAP_RTPSESSION_CID, + ZAP_RTPSESSION_CONTRACTID, + zapRTPSessionConstructor + } +}; + +NS_IMPL_NSGETMODULE(zapMediaService, gComponents) + diff --git a/mozilla/zap/zmk/src/zapMediaUtils.h b/mozilla/zap/zmk/src/zapMediaUtils.h new file mode 100644 index 00000000000..e2e117e26f9 --- /dev/null +++ b/mozilla/zap/zmk/src/zapMediaUtils.h @@ -0,0 +1,59 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + + +#define ZMK_VERIFY_STREAM_TYPE(streamInfo, type) \ + if (!streamInfo) { \ + NS_ERROR("Missing streamInfo"); \ + return NS_ERROR_FAILURE; \ + } \ + { \ + nsCString stype; \ + if (NS_FAILED(streamInfo->GetPropertyAsACString( \ + NS_LITERAL_STRING("type"), \ + stype)) || \ + stype != NS_LITERAL_CSTRING(type)) { \ + NS_ERROR("Stream is not of type " type); \ + return NS_ERROR_FAILURE; \ + } \ + } + + +#define ZMK_CREATE_STREAM_INFO(streamInfo, type) \ + NS_NewHashPropertyBag2(getter_AddRefs(streamInfo)); \ + streamInfo->SetPropertyAsACString(NS_LITERAL_STRING("type"), \ + NS_LITERAL_CSTRING(type)); + diff --git a/mozilla/zap/zmk/src/zapPacketBuffer.cpp b/mozilla/zap/zmk/src/zapPacketBuffer.cpp new file mode 100644 index 00000000000..1cec2cf779f --- /dev/null +++ b/mozilla/zap/zmk/src/zapPacketBuffer.cpp @@ -0,0 +1,797 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "zapPacketBuffer.h" +#include "nsIPropertyBag2.h" +#include "stdio.h" +#include "zapIMediaFrame.h" +#include "zapIMediaGraph.h" +#include "prmem.h" +#include "nsAutoPtr.h" +#include "nsString.h" + +//////////////////////////////////////////////////////////////////////// +// PacketDeallocator: helper to clean up packet buffer + +class PacketDeallocator : public nsDequeFunctor +{ +public: + virtual void* operator()(void* obj) { + zapIMediaFrame* frame = (zapIMediaFrame*)obj; + NS_IF_RELEASE(frame); + return 0; + } +}; + + +//////////////////////////////////////////////////////////////////////// +// zapPacketBuffer + +zapPacketBuffer::zapPacketBuffer() + : mBuffer(0), + mSourceState(zapPacketBufferSource_STOP_IDLE::Instance()), + mSinkState(zapPacketBufferSink_IDLE_PREFILLING::Instance()) +{ +#ifdef DEBUG + printf("zapPacketBuffer::zapPacketBuffer()\n"); +#endif +} + +zapPacketBuffer::~zapPacketBuffer() +{ + ClearBuffer(); +#ifdef DEBUG + printf("zapPacketBuffer::~zapPacketBuffer()\n"); +#endif +} + +//---------------------------------------------------------------------- +// nsISupports methods: + +NS_IMPL_ADDREF(zapPacketBuffer) +NS_IMPL_RELEASE(zapPacketBuffer) + +NS_INTERFACE_MAP_BEGIN(zapPacketBuffer) + NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, zapIMediaNode) + NS_INTERFACE_MAP_ENTRY(zapIMediaNode) + NS_INTERFACE_MAP_ENTRY(zapIMediaSink) + NS_INTERFACE_MAP_ENTRY(zapIMediaSource) +NS_INTERFACE_MAP_END + +//---------------------------------------------------------------------- +// zapIMediaNode methods: + +/* void addedToGraph (in zapIMediaGraph graph, in ACString id, in nsIPropertyBag2 node_pars); */ +NS_IMETHODIMP +zapPacketBuffer::AddedToGraph(zapIMediaGraph *graph, + const nsACString & id, + nsIPropertyBag2* node_pars) +{ + graph->GetEventQueue(getter_AddRefs(mEventQueue)); + + // node parameter defaults: + mPrefillSize = 0; + mMaxSize = 10; + // unpack node parameters: + if (node_pars) { + node_pars->GetPropertyAsUint32(NS_LITERAL_STRING("prefill_size"), &mPrefillSize); + node_pars->GetPropertyAsUint32(NS_LITERAL_STRING("max_size"), &mMaxSize); + + if (mMaxSizeConnectSource(this, source, connection_id); +} + +/* void disconnectSource (in zapIMediaSource source, in ACString connection_id); */ +NS_IMETHODIMP +zapPacketBuffer::DisconnectSource(zapIMediaSource *source, + const nsACString & connection_id) +{ + return mSourceState->DisconnectSource(this, source, connection_id); +} + +/* void processFrame (in zapIMediaFrame frame); */ +NS_IMETHODIMP +zapPacketBuffer::ProcessFrame(zapIMediaFrame *frame) +{ + return mSourceState->ProcessFrame(this, frame); +} + +//---------------------------------------------------------------------- +// zapIMediaSource methods: + +/* void connectSink (in zapIMediaSink sink, in ACString connection_id); */ +NS_IMETHODIMP +zapPacketBuffer::ConnectSink(zapIMediaSink *sink, + const nsACString & connection_id) +{ + return mSinkState->ConnectSink(this, sink, connection_id); +} + +/* void disconnectSink (in zapIMediaSink sink, in ACString connection_id); */ +NS_IMETHODIMP +zapPacketBuffer::DisconnectSink(zapIMediaSink *sink, + const nsACString & connection_id) +{ + return mSinkState->DisconnectSink(this, sink, connection_id); +} + +/* void requestFrame (); */ +NS_IMETHODIMP +zapPacketBuffer::RequestFrame() +{ + return mSinkState->RequestFrame(this); +} + +//---------------------------------------------------------------------- +// Implementation helpers: + +void +zapPacketBuffer::ChangeSourceState(zapPacketBufferSourceState* state) +{ + mSourceState = state; +} + +void +zapPacketBuffer::ChangeSinkState(zapPacketBufferSinkState* state) +{ + mSinkState = state; +} + +void zapPacketBuffer::RunQueueing() +{ + mSourceState->RunQueueing(this); +} + +void zapPacketBuffer::StopQueueing() +{ + mSourceState->StopQueueing(this); +} + +void zapPacketBuffer::PacketQueued() +{ + mSinkState->PacketQueued(this); +} + +void zapPacketBuffer::PacketDequeued() +{ + mSourceState->PacketDequeued(this); +} + +void zapPacketBuffer::ClearBuffer() +{ + PacketDeallocator deallocator; + mBuffer.ForEach(deallocator); + mBuffer.Empty(); +} + +class zapPacketBufferRequestFrameEvent : public PLEvent +{ +public: + zapPacketBufferRequestFrameEvent(zapPacketBuffer* pb) + : packetbuffer(pb) + { + PL_InitEvent(this, packetbuffer, EventHandler, EventCleanup); + } + + PR_STATIC_CALLBACK(void *) EventHandler(PLEvent* ev) + { + zapPacketBuffer* pb = (zapPacketBuffer*) ev->owner; + + if (pb->mSource) + pb->mSource->RequestFrame(); + + return (void*)PR_TRUE; + } + + PR_STATIC_CALLBACK(void) EventCleanup(PLEvent* ev) + { + delete (zapPacketBufferRequestFrameEvent*) ev; + } + + nsRefPtr packetbuffer; +}; + +void zapPacketBuffer::PostFrameRequest() +{ + mEventQueue->EnterMonitor(); + zapPacketBufferRequestFrameEvent* ev = new zapPacketBufferRequestFrameEvent(this); + mEventQueue->PostEvent(ev); + mEventQueue->ExitMonitor(); +} + +//////////////////////////////////////////////////////////////////////// +// zapPacketBufferSourceState implementation + +nsresult +zapPacketBufferSourceState::ConnectSource(zapPacketBuffer* pb, + zapIMediaSource* source, + const nsACString & connection_id) +{ +#ifdef DEBUG + printf("zapPacketBufferSourceState::ConnectSource: protocol error in state %s\n", + GetName()); +#endif + return NS_ERROR_FAILURE; +} + +nsresult +zapPacketBufferSourceState::DisconnectSource(zapPacketBuffer* pb, + zapIMediaSource* source, + const nsACString& connection_id) +{ +#ifdef DEBUG + printf("zapPacketBufferSourceState::DisconnectSource: protocol error in state %s\n", + GetName()); +#endif + return NS_ERROR_FAILURE; +} + +nsresult +zapPacketBufferSourceState::ProcessFrame(zapPacketBuffer* pb, + zapIMediaFrame* frame) +{ +#ifdef DEBUG + printf("zapPacketBufferSourceState::ProcessFrame: protocol error in state %s\n", + GetName()); +#endif + return NS_ERROR_FAILURE; +} + +void zapPacketBufferSourceState::ChangeState(zapPacketBuffer* pb, + zapPacketBufferSourceState* state) +{ + pb->ChangeSourceState(state); +} + +//////////////////////////////////////////////////////////////////////// +// zapPacketBufferSource_STOP_IDLE implementation + +zapPacketBufferSourceState* zapPacketBufferSource_STOP_IDLE::Instance() +{ + if (!mInstance) { + mInstance = new zapPacketBufferSource_STOP_IDLE; + } + return mInstance; +} + +zapPacketBufferSourceState* zapPacketBufferSource_STOP_IDLE::mInstance = nsnull; + +void zapPacketBufferSource_STOP_IDLE::PacketDequeued(zapPacketBuffer* pb) +{ + NS_ERROR("not reached"); +} + +void zapPacketBufferSource_STOP_IDLE::RunQueueing(zapPacketBuffer* pb) +{ + if (pb->mSource) { + ChangeState(pb, zapPacketBufferSource_RUN_WAITING::Instance()); + pb->mSource->RequestFrame(); + } + else + ChangeState(pb, zapPacketBufferSource_RUN_IDLE::Instance()); +} + +void zapPacketBufferSource_STOP_IDLE::StopQueueing(zapPacketBuffer* pb) +{ + // we're already stopped; do nothing +} + +nsresult +zapPacketBufferSource_STOP_IDLE::ConnectSource(zapPacketBuffer* pb, + zapIMediaSource* source, + const nsACString & connection_id) +{ + if (pb->mSource) { + NS_ERROR("source already connected"); + return NS_ERROR_FAILURE; + } + + pb->mSource = source; + return NS_OK; +} + +nsresult +zapPacketBufferSource_STOP_IDLE::DisconnectSource(zapPacketBuffer* pb, + zapIMediaSource* source, + const nsACString& connection_id) +{ + pb->mSource = nsnull; + return NS_OK; +} + +//////////////////////////////////////////////////////////////////////// +// zapPacketBufferSource_STOP_WAITING implementation + +zapPacketBufferSourceState* zapPacketBufferSource_STOP_WAITING::Instance() +{ + if (!mInstance) { + mInstance = new zapPacketBufferSource_STOP_WAITING; + } + return mInstance; +} + +zapPacketBufferSourceState* zapPacketBufferSource_STOP_WAITING::mInstance = nsnull; + +void zapPacketBufferSource_STOP_WAITING::PacketDequeued(zapPacketBuffer* pb) +{ + NS_ERROR("not reached"); +} + +void zapPacketBufferSource_STOP_WAITING::RunQueueing(zapPacketBuffer* pb) +{ + ChangeState(pb, zapPacketBufferSource_RUN_WAITING::Instance()); +} + +void zapPacketBufferSource_STOP_WAITING::StopQueueing(zapPacketBuffer* pb) +{ + // queuing is already stopped +} + +nsresult +zapPacketBufferSource_STOP_WAITING::DisconnectSource(zapPacketBuffer* pb, + zapIMediaSource* source, + const nsACString& connection_id) +{ + pb->mSource = nsnull; + // we won't get a packet from the source anymore: + ChangeState(pb, zapPacketBufferSource_STOP_IDLE::Instance()); + return NS_OK; +} + +nsresult +zapPacketBufferSource_STOP_WAITING::ProcessFrame(zapPacketBuffer* pb, + zapIMediaFrame* frame) +{ + // silently discard frame; the sink doesn't want it: +#ifdef DEBUG + printf("(buffer discard)"); +#endif + ChangeState(pb, zapPacketBufferSource_STOP_IDLE::Instance()); + return NS_OK; +} + +//////////////////////////////////////////////////////////////////////// +// zapPacketBufferSource_RUN_WAITING implementation + +zapPacketBufferSourceState* zapPacketBufferSource_RUN_WAITING::Instance() +{ + if (!mInstance) { + mInstance = new zapPacketBufferSource_RUN_WAITING; + } + return mInstance; +} + +zapPacketBufferSourceState* zapPacketBufferSource_RUN_WAITING::mInstance = nsnull; + +void zapPacketBufferSource_RUN_WAITING::PacketDequeued(zapPacketBuffer* pb) +{ + // nothing to do; we're already waiting for a packet +} + +void zapPacketBufferSource_RUN_WAITING::RunQueueing(zapPacketBuffer* pb) +{ + // already running +} + +void zapPacketBufferSource_RUN_WAITING::StopQueueing(zapPacketBuffer* pb) +{ + ChangeState(pb, zapPacketBufferSource_STOP_WAITING::Instance()); +} + +nsresult +zapPacketBufferSource_RUN_WAITING::DisconnectSource(zapPacketBuffer* pb, + zapIMediaSource* source, + const nsACString& connection_id) +{ + pb->mSource = nsnull; + // enqueue an EOF frame: + pb->mBuffer.Push(nsnull); + // we won't get any more packet from this source: + ChangeState(pb, zapPacketBufferSource_RUN_IDLE::Instance()); + pb->PacketQueued(); + return NS_OK; +} + +nsresult +zapPacketBufferSource_RUN_WAITING::ProcessFrame(zapPacketBuffer* pb, + zapIMediaFrame* frame) +{ + // enqueue packet: + NS_IF_ADDREF(frame); + pb->mBuffer.Push(frame); + + if (pb->mBuffer.GetSize() < pb->mMaxSize) { + // our buffer is not full; schedule next packet + pb->PostFrameRequest(); + } + else { + ChangeState(pb, zapPacketBufferSource_RUN_IDLE::Instance()); + } + pb->PacketQueued(); + + return NS_OK; +} + +//////////////////////////////////////////////////////////////////////// +// zapPacketBufferSource_RUN_IDLE implementation + +zapPacketBufferSourceState* zapPacketBufferSource_RUN_IDLE::Instance() +{ + if (!mInstance) { + mInstance = new zapPacketBufferSource_RUN_IDLE; + } + return mInstance; +} + +zapPacketBufferSourceState* zapPacketBufferSource_RUN_IDLE::mInstance = nsnull; + +void zapPacketBufferSource_RUN_IDLE::PacketDequeued(zapPacketBuffer* pb) +{ + if (pb->mSource && pb->mBuffer.GetSize() < pb->mMaxSize) { + pb->PostFrameRequest(); + ChangeState(pb, zapPacketBufferSource_RUN_WAITING::Instance()); + } +} + +void zapPacketBufferSource_RUN_IDLE::RunQueueing(zapPacketBuffer* pb) +{ + // already running +} + +void zapPacketBufferSource_RUN_IDLE::StopQueueing(zapPacketBuffer* pb) +{ + ChangeState(pb, zapPacketBufferSource_STOP_IDLE::Instance()); +} + +nsresult +zapPacketBufferSource_RUN_IDLE::ConnectSource(zapPacketBuffer* pb, + zapIMediaSource* source, + const nsACString & connection_id) +{ + if (pb->mSource) { + NS_ERROR("source already connected"); + return NS_ERROR_FAILURE; + } + + pb->mSource = source; + + if (pb->mBuffer.GetSize() < pb->mMaxSize) { + pb->PostFrameRequest(); + ChangeState(pb, zapPacketBufferSource_RUN_WAITING::Instance()); + } + + return NS_OK; +} + +nsresult +zapPacketBufferSource_RUN_IDLE::DisconnectSource(zapPacketBuffer* pb, + zapIMediaSource* source, + const nsACString& connection_id) +{ + pb->mSource = nsnull; + // enqueue an EOF frame: + pb->mBuffer.Push(nsnull); + pb->PacketQueued(); + return NS_OK; +} + + + +//////////////////////////////////////////////////////////////////////// +// zapPacketBufferSinkState implementation + +nsresult +zapPacketBufferSinkState::ConnectSink(zapPacketBuffer* pb, zapIMediaSink* sink, + const nsACString& connection_id) +{ +#ifdef DEBUG + printf("zapPacketBufferSinkState::ConnectSink: protocol error in state %s\n", + GetName()); +#endif + return NS_ERROR_FAILURE; +} + +nsresult +zapPacketBufferSinkState::DisconnectSink(zapPacketBuffer* pb, zapIMediaSink *sink, + const nsACString & connection_id) +{ +#ifdef DEBUG + printf("zapPacketBufferSinkState::DisconnectSink: protocol error in state %s\n", + GetName()); +#endif + return NS_ERROR_FAILURE; +} + +nsresult +zapPacketBufferSinkState::RequestFrame(zapPacketBuffer* pb) +{ +#ifdef DEBUG + printf("zapPacketBufferSinkState::RequestFrame: protocol error in state %s\n", + GetName()); +#endif + return NS_ERROR_FAILURE; +} + +void zapPacketBufferSinkState::ChangeState(zapPacketBuffer* pb, + zapPacketBufferSinkState* state) +{ + pb->ChangeSinkState(state); +} + +//////////////////////////////////////////////////////////////////////// +// zapPacketBufferSink_WAITING_PREFILLING implementation + +zapPacketBufferSinkState* +zapPacketBufferSink_WAITING_PREFILLING::Instance() +{ + if (!mInstance) { + mInstance = new zapPacketBufferSink_WAITING_PREFILLING; + } + return mInstance; +} + +zapPacketBufferSinkState* +zapPacketBufferSink_WAITING_PREFILLING::mInstance = nsnull; + +void zapPacketBufferSink_WAITING_PREFILLING::PacketQueued(zapPacketBuffer* pb) +{ + if (pb->mBuffer.GetSize() >= pb->mPrefillSize || + (zapIMediaFrame*)pb->mBuffer.Peek() == nsnull) { + // we are finished prefilling or the stream has ended. + // start dequeuing: + ChangeState(pb, zapPacketBufferSink_IDLE::Instance()); + zapIMediaFrame* frame = (zapIMediaFrame*)pb->mBuffer.PopFront(); + pb->mSink->ProcessFrame(frame); + NS_IF_RELEASE(frame); + pb->PacketDequeued(); + } +} + +nsresult +zapPacketBufferSink_WAITING_PREFILLING::DisconnectSink(zapPacketBuffer* pb, + zapIMediaSink *sink, + const nsACString & connection_id) +{ + pb->mSink = nsnull; + pb->StopQueueing(); + pb->ClearBuffer(); + ChangeState(pb, zapPacketBufferSink_IDLE_PREFILLING::Instance()); + return NS_OK; +} + +//////////////////////////////////////////////////////////////////////// +// zapPacketBufferSink_WAITING implementation + +zapPacketBufferSinkState* +zapPacketBufferSink_WAITING::Instance() +{ + if (!mInstance) { + mInstance = new zapPacketBufferSink_WAITING; + } + return mInstance; +} + +zapPacketBufferSinkState* +zapPacketBufferSink_WAITING::mInstance = nsnull; + +void zapPacketBufferSink_WAITING::PacketQueued(zapPacketBuffer* pb) +{ + NS_ASSERTION(pb->mBuffer.GetSize(), "packet queued, but empty queue"); + zapIMediaFrame* frame = (zapIMediaFrame*)pb->mBuffer.PopFront(); + if (!frame) { + // An EOF frame. Make sure next stream gets prefilled again: + ChangeState(pb, zapPacketBufferSink_IDLE_PREFILLING::Instance()); + } + else + ChangeState(pb, zapPacketBufferSink_IDLE::Instance()); + pb->mSink->ProcessFrame(frame); + NS_IF_RELEASE(frame); + pb->PacketDequeued(); +} + +nsresult +zapPacketBufferSink_WAITING::DisconnectSink(zapPacketBuffer* pb, + zapIMediaSink *sink, + const nsACString & connection_id) +{ + pb->mSink = nsnull; + pb->StopQueueing(); + pb->ClearBuffer(); + ChangeState(pb, zapPacketBufferSink_IDLE_PREFILLING::Instance()); + return NS_OK; +} + +//////////////////////////////////////////////////////////////////////// +// zapPacketBufferSink_IDLE implementation + +zapPacketBufferSinkState* +zapPacketBufferSink_IDLE::Instance() +{ + if (!mInstance) { + mInstance = new zapPacketBufferSink_IDLE; + } + return mInstance; +} + +zapPacketBufferSinkState* +zapPacketBufferSink_IDLE::mInstance = nsnull; + +void zapPacketBufferSink_IDLE::PacketQueued(zapPacketBuffer* pb) +{ + // do nothing +} + + +nsresult +zapPacketBufferSink_IDLE::DisconnectSink(zapPacketBuffer* pb, + zapIMediaSink *sink, + const nsACString & connection_id) +{ + pb->mSink = nsnull; + pb->StopQueueing(); + pb->ClearBuffer(); + ChangeState(pb, zapPacketBufferSink_IDLE_PREFILLING::Instance()); + return NS_OK; +} + +nsresult +zapPacketBufferSink_IDLE::RequestFrame(zapPacketBuffer* pb) +{ + if (pb->mBuffer.GetSize()) { + zapIMediaFrame* frame = (zapIMediaFrame*)pb->mBuffer.PopFront(); + if (!frame) { + // An EOF frame. Make sure next stream gets prefilled again: + ChangeState(pb, zapPacketBufferSink_IDLE_PREFILLING::Instance()); + } + pb->mSink->ProcessFrame(frame); + NS_IF_RELEASE(frame); + pb->PacketDequeued(); + } + else { + // nothing in buffer + ChangeState(pb, zapPacketBufferSink_WAITING::Instance()); + } + return NS_OK; +} + +//////////////////////////////////////////////////////////////////////// +// zapPacketBufferSink_IDLE_PREFILLING implementation + +zapPacketBufferSinkState* +zapPacketBufferSink_IDLE_PREFILLING::Instance() +{ + if (!mInstance) { + mInstance = new zapPacketBufferSink_IDLE_PREFILLING; + } + return mInstance; +} + +zapPacketBufferSinkState* +zapPacketBufferSink_IDLE_PREFILLING::mInstance = nsnull; + +void zapPacketBufferSink_IDLE_PREFILLING::PacketQueued(zapPacketBuffer* pb) +{ + // do nothing +} + + +nsresult +zapPacketBufferSink_IDLE_PREFILLING::ConnectSink(zapPacketBuffer* pb, + zapIMediaSink* sink, + const nsACString& connection_id) +{ + if (pb->mSink) { + NS_ERROR("already connected"); + return NS_ERROR_FAILURE; + } + pb->mSink = sink; + + return NS_OK; +} + + +nsresult +zapPacketBufferSink_IDLE_PREFILLING::DisconnectSink(zapPacketBuffer* pb, + zapIMediaSink *sink, + const nsACString & connection_id) +{ + pb->mSink = nsnull; + pb->StopQueueing(); + pb->ClearBuffer(); + return NS_OK; +} + +nsresult +zapPacketBufferSink_IDLE_PREFILLING::RequestFrame(zapPacketBuffer* pb) +{ + pb->RunQueueing(); + + if (pb->mBuffer.GetSize() <= pb->mPrefillSize) { + ChangeState(pb, zapPacketBufferSink_WAITING_PREFILLING::Instance()); + } + else { + zapIMediaFrame* frame = (zapIMediaFrame*)pb->mBuffer.PopFront(); + if (frame) + ChangeState(pb, zapPacketBufferSink_IDLE::Instance()); + // else ... prefill next frame + pb->mSink->ProcessFrame(frame); + NS_IF_RELEASE(frame); + pb->PacketDequeued(); + } + return NS_OK; +} diff --git a/mozilla/zap/zmk/src/zapPacketBuffer.h b/mozilla/zap/zmk/src/zapPacketBuffer.h new file mode 100644 index 00000000000..7d68c64c08b --- /dev/null +++ b/mozilla/zap/zmk/src/zapPacketBuffer.h @@ -0,0 +1,361 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#ifndef __ZAP_PACKETBUFFER_H__ +#define __ZAP_PACKETBUFFER_H__ + +#include "zapIMediaNode.h" +#include "zapIMediaSource.h" +#include "zapIMediaSink.h" +#include "nsDeque.h" +#include "nsCOMPtr.h" +#include "nsIEventQueue.h" + +//////////////////////////////////////////////////////////////////////// +// zapPacketBuffer + +// {2FD0FE12-0727-4EED-96EE-94901F4FE201} +#define ZAP_PACKETBUFFER_CID \ + { 0x2fd0fe12, 0x0727, 0x4eed, { 0x96, 0xee, 0x94, 0x90, 0x1f, 0x4f, 0xe2, 0x01 } } + +#define ZAP_PACKETBUFFER_CONTRACTID ZAP_MEDIANODE_CONTRACTID_PREFIX "buffer" + +class zapPacketBuffer : public zapIMediaNode, + public zapIMediaSource, + public zapIMediaSink +{ + NS_DECL_ISUPPORTS + NS_DECL_ZAPIMEDIANODE + NS_DECL_ZAPIMEDIASOURCE + NS_DECL_ZAPIMEDIASINK + + zapPacketBuffer(); + ~zapPacketBuffer(); + +private: + friend class zapPacketBufferRequestFrameEvent; + friend class zapPacketBufferSourceState; + friend class zapPacketBufferSource_STOP_IDLE; + friend class zapPacketBufferSource_STOP_WAITING; + friend class zapPacketBufferSource_RUN_WAITING; + friend class zapPacketBufferSource_RUN_IDLE; + friend class zapPacketBufferSinkState; + friend class zapPacketBufferSink_WAITING_PREFILLING; + friend class zapPacketBufferSink_WAITING; + friend class zapPacketBufferSink_IDLE; + friend class zapPacketBufferSink_IDLE_PREFILLING; + + zapPacketBufferSourceState* mSourceState; + zapPacketBufferSinkState* mSinkState; + + void ChangeSourceState(zapPacketBufferSourceState* state); + void ChangeSinkState(zapPacketBufferSinkState* state); + void RunQueueing(); + void StopQueueing(); + void PacketQueued(); + void PacketDequeued(); + void ClearBuffer(); + void PostFrameRequest(); + + // node parameters (set in zapIMediaGraph::AddNode()): + PRUint32 mPrefillSize; // number of packets to prefill the buffer with + PRUint32 mMaxSize; // maximum number of packets buffered + + + nsDeque mBuffer; // the actual buffer + + nsCOMPtr mEventQueue; // media graph event queue + + nsCOMPtr mSink; + nsCOMPtr mSource; +}; + +//////////////////////////////////////////////////////////////////////// +// zapPacketBufferSourceState: baseclass for zapPacketBuffer source +// states + +class zapPacketBufferSourceState +{ +public: + virtual void PacketDequeued(zapPacketBuffer* pb)=0; + virtual void RunQueueing(zapPacketBuffer* pb)=0; + virtual void StopQueueing(zapPacketBuffer* pb)=0; + + // zapIMediaSink handlers: + virtual nsresult ConnectSource(zapPacketBuffer* pb, zapIMediaSource* source, + const nsACString & connection_id); + virtual nsresult DisconnectSource(zapPacketBuffer* pb, zapIMediaSource* source, + const nsACString& connection_id); + virtual nsresult ProcessFrame(zapPacketBuffer* pb, zapIMediaFrame* frame); +#ifdef DEBUG + virtual const char* GetName()=0; +#endif + +protected: + void ChangeState(zapPacketBuffer* pb, zapPacketBufferSourceState* state); +}; + +//////////////////////////////////////////////////////////////////////// +// zapPacketBufferSource_STOP_IDLE + +class zapPacketBufferSource_STOP_IDLE : public zapPacketBufferSourceState +{ +public: + static zapPacketBufferSourceState* Instance(); + + virtual void PacketDequeued(zapPacketBuffer* pb); + virtual void RunQueueing(zapPacketBuffer* pb); + virtual void StopQueueing(zapPacketBuffer* pb); + + virtual nsresult ConnectSource(zapPacketBuffer* pb, zapIMediaSource* source, + const nsACString & connection_id); + virtual nsresult DisconnectSource(zapPacketBuffer* pb, zapIMediaSource* source, + const nsACString& connection_id); +#ifdef DEBUG + virtual const char* GetName() { + static const char* name = "STOP_IDLE"; + return name; + } +#endif + +private: + static zapPacketBufferSourceState* mInstance; +}; + +//////////////////////////////////////////////////////////////////////// +// zapPacketBufferSource_STOP_WAITING + +class zapPacketBufferSource_STOP_WAITING : public zapPacketBufferSourceState +{ +public: + static zapPacketBufferSourceState* Instance(); + + virtual void PacketDequeued(zapPacketBuffer* pb); + virtual void RunQueueing(zapPacketBuffer* pb); + virtual void StopQueueing(zapPacketBuffer* pb); + + virtual nsresult DisconnectSource(zapPacketBuffer* pb, zapIMediaSource* source, + const nsACString& connection_id); + virtual nsresult ProcessFrame(zapPacketBuffer* pb, zapIMediaFrame* frame); +#ifdef DEBUG + virtual const char* GetName() { + static const char* name = "STOP_WAITING"; + return name; + } +#endif + +private: + static zapPacketBufferSourceState* mInstance; +}; + +//////////////////////////////////////////////////////////////////////// +// zapPacketBufferSource_RUN_WAITING + +class zapPacketBufferSource_RUN_WAITING : public zapPacketBufferSourceState +{ +public: + static zapPacketBufferSourceState* Instance(); + + virtual void PacketDequeued(zapPacketBuffer* pb); + virtual void RunQueueing(zapPacketBuffer* pb); + virtual void StopQueueing(zapPacketBuffer* pb); + + virtual nsresult DisconnectSource(zapPacketBuffer* pb, zapIMediaSource* source, + const nsACString& connection_id); + virtual nsresult ProcessFrame(zapPacketBuffer* pb, zapIMediaFrame* frame); +#ifdef DEBUG + virtual const char* GetName() { + static const char* name = "RUN_WAITING"; + return name; + } +#endif + +private: + static zapPacketBufferSourceState* mInstance; +}; + +//////////////////////////////////////////////////////////////////////// +// zapPacketBufferSource_RUN_IDLE + +class zapPacketBufferSource_RUN_IDLE : public zapPacketBufferSourceState +{ +public: + static zapPacketBufferSourceState* Instance(); + + virtual void PacketDequeued(zapPacketBuffer* pb); + virtual void RunQueueing(zapPacketBuffer* pb); + virtual void StopQueueing(zapPacketBuffer* pb); + + virtual nsresult ConnectSource(zapPacketBuffer* pb, zapIMediaSource* source, + const nsACString & connection_id); + virtual nsresult DisconnectSource(zapPacketBuffer* pb, zapIMediaSource* source, + const nsACString& connection_id); +#ifdef DEBUG + virtual const char* GetName() { + static const char* name = "RUN_IDLE"; + return name; + } +#endif + +private: + static zapPacketBufferSourceState* mInstance; +}; + + +//////////////////////////////////////////////////////////////////////// +// zapPacketBufferSinkState: baseclass for zapPacketBuffer sink states + +class zapPacketBufferSinkState +{ +public: + virtual void PacketQueued(zapPacketBuffer* pb)=0; + + // zapIMediaSource handlers: + virtual nsresult ConnectSink(zapPacketBuffer* pb, zapIMediaSink* sink, + const nsACString& connection_id); + virtual nsresult DisconnectSink(zapPacketBuffer* pb, zapIMediaSink *sink, + const nsACString & connection_id); + virtual nsresult RequestFrame(zapPacketBuffer* pb); +#ifdef DEBUG + virtual const char* GetName()=0; +#endif + +protected: + void ChangeState(zapPacketBuffer* pb, zapPacketBufferSinkState* state); +}; + +//////////////////////////////////////////////////////////////////////// +// zapPacketBufferSink_WAITING_PREFILLING + +class zapPacketBufferSink_WAITING_PREFILLING : public zapPacketBufferSinkState +{ +public: + static zapPacketBufferSinkState* Instance(); + + virtual void PacketQueued(zapPacketBuffer* pb); + + // zapIMediaSource handlers: + virtual nsresult DisconnectSink(zapPacketBuffer* pb, zapIMediaSink *sink, + const nsACString & connection_id); +#ifdef DEBUG + virtual const char* GetName() { + static const char* name = "WAITING_PREFILLING"; + return name; + } +#endif + +private: + static zapPacketBufferSinkState* mInstance; +}; + +//////////////////////////////////////////////////////////////////////// +// zapPacketBufferSink_WAITING + +class zapPacketBufferSink_WAITING : public zapPacketBufferSinkState +{ +public: + static zapPacketBufferSinkState* Instance(); + + virtual void PacketQueued(zapPacketBuffer* pb); + + // zapIMediaSource handlers: + virtual nsresult DisconnectSink(zapPacketBuffer* pb, zapIMediaSink *sink, + const nsACString & connection_id); +#ifdef DEBUG + virtual const char* GetName() { + static const char* name = "WAITING"; + return name; + } +#endif + +private: + static zapPacketBufferSinkState* mInstance; +}; + +//////////////////////////////////////////////////////////////////////// +// zapPacketBufferSink_IDLE + +class zapPacketBufferSink_IDLE : public zapPacketBufferSinkState +{ +public: + static zapPacketBufferSinkState* Instance(); + + virtual void PacketQueued(zapPacketBuffer* pb); + + // zapIMediaSource handlers: + virtual nsresult DisconnectSink(zapPacketBuffer* pb, zapIMediaSink *sink, + const nsACString & connection_id); + virtual nsresult RequestFrame(zapPacketBuffer* pb); +#ifdef DEBUG + virtual const char* GetName() { + static const char* name = "IDLE"; + return name; + } +#endif + +private: + static zapPacketBufferSinkState* mInstance; +}; + +//////////////////////////////////////////////////////////////////////// +// zapPacketBufferSink_IDLE_PREFILLING + +class zapPacketBufferSink_IDLE_PREFILLING : public zapPacketBufferSinkState +{ +public: + static zapPacketBufferSinkState* Instance(); + + virtual void PacketQueued(zapPacketBuffer* pb); + + // zapIMediaSource handlers: + virtual nsresult ConnectSink(zapPacketBuffer* pb, zapIMediaSink* sink, + const nsACString& connection_id); + virtual nsresult DisconnectSink(zapPacketBuffer* pb, zapIMediaSink *sink, + const nsACString & connection_id); + virtual nsresult RequestFrame(zapPacketBuffer* pb); +#ifdef DEBUG + virtual const char* GetName() { + static const char* name = "IDLE_PREFILLING"; + return name; + } +#endif + +private: + static zapPacketBufferSinkState* mInstance; +}; + + +#endif // __ZAP_PACKETBUFFER_H__ diff --git a/mozilla/zap/zmk/src/zapRTPFrame.cpp b/mozilla/zap/zmk/src/zapRTPFrame.cpp new file mode 100644 index 00000000000..ce4b5932e8c --- /dev/null +++ b/mozilla/zap/zmk/src/zapRTPFrame.cpp @@ -0,0 +1,311 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "zapRTPFrame.h" +#include "stdio.h" +#include "nsString.h" +#include "prnetdb.h" + +//////////////////////////////////////////////////////////////////////// +// zapRTPFrame implementation + +zapRTPFrame::zapRTPFrame() +{ +} + +zapRTPFrame::~zapRTPFrame() +{ +} + +PRBool +zapRTPFrame::Init(const nsACString& octets, nsIPropertyBag2* streamInfo) +{ + //XXX validate packet more + if (octets.Length() < 12) return PR_FALSE; + + mData = octets; + mStreamInfo = streamInfo; + + return PR_TRUE; +} + +PRBool +zapRTPFrame::Init() +{ + mData.SetLength(12); + memset(mData.BeginWriting(), '\0', 12); + SetVersion(2); + + return PR_TRUE; +} + +//---------------------------------------------------------------------- +// nsISupports methods: + +NS_IMPL_ADDREF(zapRTPFrame) +NS_IMPL_RELEASE(zapRTPFrame) + +NS_INTERFACE_MAP_BEGIN(zapRTPFrame) + NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, zapIRTPFrame) + NS_INTERFACE_MAP_ENTRY(zapIRTPFrame) + NS_INTERFACE_MAP_ENTRY(zapIMediaFrame) +NS_INTERFACE_MAP_END + +//---------------------------------------------------------------------- +// zapIRTPFrame methods: + + +/* attribute unsigned short version; */ +NS_IMETHODIMP +zapRTPFrame::GetVersion(PRUint16 *aVersion) +{ + *aVersion = (mData.BeginReading()[0] & 0xC0) >> 6; + return NS_OK; +} +NS_IMETHODIMP +zapRTPFrame::SetVersion(PRUint16 aVersion) +{ + mData.BeginWriting()[0] |= ((aVersion << 6) & 0xC0); + return NS_OK; +} + +/* attribute boolean padding; */ +NS_IMETHODIMP +zapRTPFrame::GetPadding(PRBool *aPadding) +{ + *aPadding = (mData.BeginReading()[0] & 0x20) >> 5; + return NS_OK; +} +NS_IMETHODIMP +zapRTPFrame::SetPadding(PRBool aPadding) +{ + mData.BeginWriting()[0] |= ((aPadding << 5) & 0x20); + return NS_OK; +} + +/* attribute boolean extension; */ +NS_IMETHODIMP +zapRTPFrame::GetExtension(PRBool *aExtension) +{ + *aExtension = (mData.BeginReading()[0] & 0x10) >> 4; + return NS_OK; +} +NS_IMETHODIMP +zapRTPFrame::SetExtension(PRBool aExtension) +{ + mData.BeginWriting()[0] |= ((aExtension << 4) & 0x10); + return NS_OK; +} + +/* attribute unsigned short CSRCCount; */ +NS_IMETHODIMP +zapRTPFrame::GetCSRCCount(PRUint16 *aCSRCCount) +{ + *aCSRCCount = mData.BeginReading()[0] & 0x0F; + return NS_OK; +} +NS_IMETHODIMP +zapRTPFrame::SetCSRCCount(PRUint16 aCSRCCount) +{ + mData.BeginWriting()[0] |= (aCSRCCount & 0x0F); + return NS_OK; +} + +/* attribute unsigned short marker; */ +NS_IMETHODIMP +zapRTPFrame::GetMarker(PRUint16 *aMarker) +{ + *aMarker = (mData.BeginReading()[1] & 0x80) >> 7; + return NS_OK; +} +NS_IMETHODIMP +zapRTPFrame::SetMarker(PRUint16 aMarker) +{ + mData.BeginWriting()[1] |= ((aMarker << 7) & 0x80); + return NS_OK; +} + +/* attribute unsigned short payloadType; */ +NS_IMETHODIMP +zapRTPFrame::GetPayloadType(PRUint16 *aPayloadType) +{ + *aPayloadType = mData.BeginReading()[1] & 0x7F; + return NS_OK; +} +NS_IMETHODIMP +zapRTPFrame::SetPayloadType(PRUint16 aPayloadType) +{ + mData.BeginWriting()[1] |= (aPayloadType & 0x7F); + return NS_OK; +} + +/* attribute unsigned short sequenceNumber; */ +NS_IMETHODIMP +zapRTPFrame::GetSequenceNumber(PRUint16 *aSequenceNumber) +{ + *aSequenceNumber = PR_ntohs(((PRUint16*)mData.BeginReading())[1]); + return NS_OK; +} +NS_IMETHODIMP +zapRTPFrame::SetSequenceNumber(PRUint16 aSequenceNumber) +{ + ((PRUint16*)mData.BeginWriting())[1] = PR_htons(aSequenceNumber); + return NS_OK; +} + +/* attribute unsigned long rtpTimestamp; */ +NS_IMETHODIMP +zapRTPFrame::GetRtpTimestamp(PRUint32 *aTimestamp) +{ + *aTimestamp = PR_ntohl(((PRUint32*)mData.BeginReading())[1]); + return NS_OK; +} +NS_IMETHODIMP +zapRTPFrame::SetRtpTimestamp(PRUint32 aTimestamp) +{ + ((PRUint32*)mData.BeginWriting())[1] = PR_htonl(aTimestamp); + return NS_OK; +} + +/* attribute unsigned long SSRC; */ +NS_IMETHODIMP +zapRTPFrame::GetSSRC(PRUint32 *aSSRC) +{ + *aSSRC = PR_ntohl(((PRUint32*)mData.BeginReading())[2]); + return NS_OK; +} +NS_IMETHODIMP +zapRTPFrame::SetSSRC(PRUint32 aSSRC) +{ + ((PRUint32*)mData.BeginWriting())[2] = PR_htonl(aSSRC); + return NS_OK; +} + +/* unsigned long getCSRC (in unsigned short index); */ +NS_IMETHODIMP +zapRTPFrame::GetCSRC(PRUint16 index, PRUint32 *_retval) +{ + return NS_ERROR_NOT_IMPLEMENTED; +} + +/* void setCSRC (in unsigned short index, in unsigned long CSRC); */ +NS_IMETHODIMP +zapRTPFrame::SetCSRC(PRUint16 index, PRUint32 CSRC) +{ + return NS_ERROR_NOT_IMPLEMENTED; +} + +/* attribute ACString payload; */ +NS_IMETHODIMP +zapRTPFrame::GetPayload(nsACString & aPayload) +{ + // RTP header is 12 bytes + 4*CSRC: + PRUint16 csrcCount; + GetCSRCCount(&csrcCount); + PRUint16 offset = 12 + csrcCount*4; + aPayload = Substring(mData, offset); + return NS_OK; +} +NS_IMETHODIMP +zapRTPFrame::SetPayload(const nsACString & aPayload) +{ + PRUint16 csrcCount; + GetCSRCCount(&csrcCount); + PRUint16 length = 12 + csrcCount*4; + mData = Substring(mData, 0, length); + NS_ASSERTION(mData.Length()==length, "Unexpected!"); + mData.Append(aPayload); + return NS_OK; +} + +//---------------------------------------------------------------------- +// zapIMediaFrame methods: + +/* readonly attribute nsIPropertyBag2 streamInfo; */ +NS_IMETHODIMP +zapRTPFrame::GetStreamInfo(nsIPropertyBag2** aStreamInfo) +{ + *aStreamInfo = mStreamInfo.get(); + NS_IF_ADDREF(*aStreamInfo); + return NS_OK; +} + +/* readonly attribute unsigned long timestamp; */ +NS_IMETHODIMP +zapRTPFrame::GetTimestamp(PRUint32 *aTimestamp) +{ + return GetRtpTimestamp(aTimestamp); +} + +/* readonly attribute ACString data; */ +NS_IMETHODIMP +zapRTPFrame::GetData(nsACString & aData) +{ + aData = mData; + return NS_OK; +} + + +//---------------------------------------------------------------------- + +zapIRTPFrame * +CreateRTPFrame(const nsACString & octets, nsIPropertyBag2* streamInfo) +{ + zapRTPFrame* frame = new zapRTPFrame(); + if (!frame) return nsnull; + NS_ADDREF(frame); + + if (!frame->Init(octets, streamInfo)) { + NS_RELEASE(frame); + return nsnull; + } + return frame; +} + +// Create a blank rtp frame: +zapRTPFrame* +CreateRTPFrame() +{ + zapRTPFrame* frame = new zapRTPFrame(); + if (!frame) return nsnull; + NS_ADDREF(frame); + + if (!frame->Init()) { + NS_RELEASE(frame); + return nsnull; + } + return frame; +} diff --git a/mozilla/zap/zmk/src/zapRTPFrame.h b/mozilla/zap/zmk/src/zapRTPFrame.h new file mode 100644 index 00000000000..f6d6fc38b54 --- /dev/null +++ b/mozilla/zap/zmk/src/zapRTPFrame.h @@ -0,0 +1,69 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#ifndef __ZAP_RTPFRAME_H__ +#define __ZAP_RTPFRAME_H__ + +#include "zapIRTPFrame.h" +#include "nsString.h" +#include "nsCOMPtr.h" +#include "nsIPropertyBag2.h" + +class zapRTPFrame : public zapIRTPFrame +{ +public: + NS_DECL_ISUPPORTS + NS_DECL_ZAPIRTPFRAME + NS_DECL_ZAPIMEDIAFRAME + + zapRTPFrame(); + ~zapRTPFrame(); + PRBool Init(const nsACString& octets, nsIPropertyBag2* streamInfo); + PRBool Init(); + + nsCString mData; + nsCOMPtr mStreamInfo; +}; + +//---------------------------------------------------------------------- +// helpers to create add-refed rtp frame objects: +zapIRTPFrame * +CreateRTPFrame(const nsACString & octets, nsIPropertyBag2* streamInfo); + +zapRTPFrame * +CreateRTPFrame(); + +#endif // __ZAP_RTPPACKET_H__ diff --git a/mozilla/zap/zmk/src/zapRTPReceiver.cpp b/mozilla/zap/zmk/src/zapRTPReceiver.cpp new file mode 100644 index 00000000000..70b6b104340 --- /dev/null +++ b/mozilla/zap/zmk/src/zapRTPReceiver.cpp @@ -0,0 +1,99 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "zapRTPReceiver.h" +#include "zapRTPFrame.h" +#include "zapIMediaGraph.h" +#include "nsString.h" +#include "nsIPropertyBag2.h" +#include "zapDatagramFrame.h" +#include "stdio.h" +#include "nsHashPropertyBag.h" +#include "zapMediaUtils.h" + +//////////////////////////////////////////////////////////////////////// +// zapRTPReceiver + +zapRTPReceiver::zapRTPReceiver() +{ +#ifdef DEBUG + printf("zapRTPReceiver::zapRTPReceiver()\n"); +#endif +} + +zapRTPReceiver::~zapRTPReceiver() +{ +#ifdef DEBUG + printf("zapRTPReceiver::~zapRTPReceiver()\n"); +#endif +} + +NS_IMETHODIMP +zapRTPReceiver::AddedToGraph(zapIMediaGraph *graph, const nsACString & id, + nsIPropertyBag2 *node_pars) +{ + return NS_OK; +} + +NS_IMETHODIMP +zapRTPReceiver::RemovedFromGraph(zapIMediaGraph *graph) +{ + return NS_OK; +} + +nsresult +zapRTPReceiver::OpenStream(nsIPropertyBag2* streamInfo) +{ + ZMK_VERIFY_STREAM_TYPE(streamInfo, "datagram"); + ZMK_CREATE_STREAM_INFO(mStreamInfo, "rtp"); + + return NS_OK; +} + +void +zapRTPReceiver::CloseStream() +{ +} + +nsresult +zapRTPReceiver::Filter(zapIMediaFrame* input, zapIMediaFrame** output) +{ + nsCString octets; + input->GetData(octets); + // create RTP frame from packet octets: + *output = CreateRTPFrame(octets, mStreamInfo); + return NS_OK; +} diff --git a/mozilla/zap/zmk/src/zapRTPReceiver.h b/mozilla/zap/zmk/src/zapRTPReceiver.h new file mode 100644 index 00000000000..3fc556e4b3b --- /dev/null +++ b/mozilla/zap/zmk/src/zapRTPReceiver.h @@ -0,0 +1,74 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#ifndef __ZAP_RTPRECEIVER_H__ +#define __ZAP_RTPRECEIVER_H__ + +#include "zapFilterNode.h" +#include "nsIWritablePropertyBag2.h" +#include "nsString.h" + +//////////////////////////////////////////////////////////////////////// +// zapRTPReceiver + +// {C6D6733C-3B23-4D1D-BE7B-6E7E19B300A9} +#define ZAP_RTPRECEIVER_CID \ + { 0xc6d6733c, 0x3b23, 0x4d1d, { 0xbe, 0x7b, 0x6e, 0x7e, 0x19, 0xb3, 0x00, 0xa9 } } + +#define ZAP_RTPRECEIVER_CONTRACTID ZAP_MEDIANODE_CONTRACTID_PREFIX "rtp-receiver" + +class zapRTPReceiver : public zapFilterNode +{ +public: + zapRTPReceiver(); + ~zapRTPReceiver(); + + NS_IMETHOD AddedToGraph(zapIMediaGraph *graph, + const nsACString & id, + nsIPropertyBag2 *node_pars); + NS_IMETHOD RemovedFromGraph(zapIMediaGraph *graph); + virtual nsresult OpenStream(nsIPropertyBag2* streamInfo); + virtual void CloseStream(); + virtual nsresult Filter(zapIMediaFrame* input, zapIMediaFrame** output); + +private: + nsCOMPtr mStreamInfo; + PRUint32 mSSRC; + nsCString mAddress; + PRUint32 mPort; +}; + +#endif // __ZAP_RTPRECEIVER_H__ diff --git a/mozilla/zap/zmk/src/zapRTPSession.cpp b/mozilla/zap/zmk/src/zapRTPSession.cpp new file mode 100644 index 00000000000..c88e55b7202 --- /dev/null +++ b/mozilla/zap/zmk/src/zapRTPSession.cpp @@ -0,0 +1,206 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "zapRTPSession.h" +#include // for rand +#include "zapIMediaGraph.h" +#include "nsHashPropertyBag.h" + +//////////////////////////////////////////////////////////////////////// +// zapRTPSession + +zapRTPSession::zapRTPSession() +{ +#ifdef DEBUG + printf("zapRTPSession::zapRTPSession()\n"); +#endif +} + +zapRTPSession::~zapRTPSession() +{ + NS_ASSERTION(!mTransmitter && !mReceiver, "unclean shutdown"); +#ifdef DEBUG + printf("zapRTPSession::~zapRTPSession()\n"); +#endif +} + +//---------------------------------------------------------------------- +// nsISupports methods: + +NS_IMPL_ADDREF(zapRTPSession) +NS_IMPL_RELEASE(zapRTPSession) + +NS_INTERFACE_MAP_BEGIN(zapRTPSession) + NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, zapIMediaNode) + NS_INTERFACE_MAP_ENTRY(zapIMediaNode) +NS_INTERFACE_MAP_END + +//---------------------------------------------------------------------- +// zapIMediaNode methods: + +/* void addedToGraph (in zapIMediaGraph graph, in ACString id, in nsIPropertyBag2 node_pars); */ +NS_IMETHODIMP +zapRTPSession::AddedToGraph(zapIMediaGraph *graph, + const nsACString & id, + nsIPropertyBag2* node_pars) +{ + // unpack node parameters: + if (!node_pars) { + NS_ERROR("no node parameters"); + return NS_ERROR_FAILURE; + } + + nsCString address; + NS_ENSURE_SUCCESS(node_pars->GetPropertyAsACString(NS_LITERAL_STRING("address"), + address), + NS_ERROR_FAILURE); + + PRUint16 rtpPort, rtcpPort; + NS_ENSURE_SUCCESS(node_pars->GetPropertyAsUint16(NS_LITERAL_STRING("rtp_port"), + &rtpPort), + NS_ERROR_FAILURE); + NS_ENSURE_SUCCESS(node_pars->GetPropertyAsUint16(NS_LITERAL_STRING("rtcp_port"), + &rtcpPort), + NS_ERROR_FAILURE); + + // hook up transmitter: + nsCOMPtr transmitter_pars; + NS_NewHashPropertyBag2(getter_AddRefs(transmitter_pars)); + transmitter_pars->SetPropertyAsACString(NS_LITERAL_STRING("address"), + address); + transmitter_pars->SetPropertyAsUint16(NS_LITERAL_STRING("port"), rtpPort); + + NS_ENSURE_SUCCESS(graph->AddNode(NS_LITERAL_CSTRING("rtp-transmitter"), + transmitter_pars, mTransmitterID), + NS_ERROR_FAILURE); + graph->GetNode(mTransmitterID, NS_GET_IID(zapIMediaNode), true, + getter_AddRefs(mTransmitter)); + if (!mTransmitter) { + NS_ERROR("transmitter doesn't implement required interface"); + graph->RemoveNode(mTransmitterID); + return NS_ERROR_FAILURE; + } + + // hook up receiver: + if (NS_FAILED(graph->AddNode(NS_LITERAL_CSTRING("rtp-receiver"), + nsnull, mReceiverID))) { + graph->RemoveNode(mTransmitterID); + return NS_ERROR_FAILURE; + } + graph->GetNode(mReceiverID, NS_GET_IID(zapIMediaNode), true, + getter_AddRefs(mReceiver)); + if (!mReceiver) { + NS_ERROR("receiver doesn't implement required interface"); + graph->RemoveNode(mReceiverID); + graph->RemoveNode(mTransmitterID); + return NS_ERROR_FAILURE; + } + + return NS_OK; +} + +/* void removedFromGraph (in zapIMediaGraph graph); */ +NS_IMETHODIMP +zapRTPSession::RemovedFromGraph(zapIMediaGraph *graph) +{ + if (mTransmitter) { + graph->RemoveNode(mTransmitterID); + mTransmitter = nsnull; + } + if (mReceiver) { + graph->RemoveNode(mReceiverID); + mReceiver = nsnull; + } + return NS_OK; +} + +/* zapIMediaSource getSource (in nsIPropertyBag2 source_pars); */ +NS_IMETHODIMP +zapRTPSession::GetSource(nsIPropertyBag2 *source_pars, zapIMediaSource **_retval) +{ + NS_ASSERTION(mTransmitter, "uh-oh, no transmitter"); + NS_ASSERTION(mReceiver, "uh-oh, no receiver"); + + // dispatch depending on source name given in source parameters + if (!source_pars) { + NS_ERROR("no source pars"); + return NS_ERROR_FAILURE; + } + + nsCString source_name; + NS_ENSURE_SUCCESS(source_pars->GetPropertyAsACString(NS_LITERAL_STRING("name"), source_name), + NS_ERROR_FAILURE); + + if (source_name == NS_LITERAL_CSTRING("remote-rtp")) { + return mTransmitter->GetSource(source_pars, _retval); + } + else if (source_name == NS_LITERAL_CSTRING("local-rtp")) { + return mReceiver->GetSource(source_pars, _retval); + } + + NS_ERROR("unknown source"); + return NS_ERROR_FAILURE; +} + +/* zapIMediaSink getSink (in nsIPropertyBag2 sink_pars); */ +NS_IMETHODIMP +zapRTPSession::GetSink(nsIPropertyBag2 *sink_pars, zapIMediaSink **_retval) +{ + NS_ASSERTION(mTransmitter, "uh-oh, no transmitter"); + NS_ASSERTION(mReceiver, "uh-oh, no receiver"); + + // dispatch depending on source name given in sink parameters + if (!sink_pars) { + NS_ERROR("no sink pars"); + return NS_ERROR_FAILURE; + } + + nsCString sink_name; + NS_ENSURE_SUCCESS(sink_pars->GetPropertyAsACString(NS_LITERAL_STRING("name"), sink_name), + NS_ERROR_FAILURE); + + if (sink_name == NS_LITERAL_CSTRING("local-rtp")) { + return mTransmitter->GetSink(sink_pars, _retval); + } + else if (sink_name == NS_LITERAL_CSTRING("remote-rtp")) { + return mReceiver->GetSink(sink_pars, _retval); + } + + NS_ERROR("unknown sink"); + return NS_ERROR_FAILURE; +} + + diff --git a/mozilla/zap/zmk/src/zapRTPSession.h b/mozilla/zap/zmk/src/zapRTPSession.h new file mode 100644 index 00000000000..774b69b7603 --- /dev/null +++ b/mozilla/zap/zmk/src/zapRTPSession.h @@ -0,0 +1,69 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#ifndef __ZAP_RTPSESSION_H__ +#define __ZAP_RTPSESSION_H__ + +#include "zapIMediaNode.h" +#include "nsCOMPtr.h" +#include "nsString.h" + +//////////////////////////////////////////////////////////////////////// +// zapRTPSession + +// {BFB34654-4314-4D82-8867-4DB6F0E732A0} +#define ZAP_RTPSESSION_CID \ + { 0xbfb34654, 0x4314, 0x4d82, { 0x88, 0x67, 0x4d, 0xb6, 0xf0, 0xe7, 0x32, 0xa0 } } + +#define ZAP_RTPSESSION_CONTRACTID ZAP_MEDIANODE_CONTRACTID_PREFIX "rtp-session" + +class zapRTPSession : public zapIMediaNode +{ +public: + zapRTPSession(); + ~zapRTPSession(); + + NS_DECL_ISUPPORTS + NS_DECL_ZAPIMEDIANODE +private: + PRUint32 mSSRC; + nsCString mTransmitterID; + nsCString mReceiverID; + nsCOMPtr mTransmitter; + nsCOMPtr mReceiver; +}; + +#endif // __ZAP_RTPSESSION_H__ diff --git a/mozilla/zap/zmk/src/zapRTPTransmitter.cpp b/mozilla/zap/zmk/src/zapRTPTransmitter.cpp new file mode 100644 index 00000000000..a4a61196666 --- /dev/null +++ b/mozilla/zap/zmk/src/zapRTPTransmitter.cpp @@ -0,0 +1,141 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "zapRTPTransmitter.h" +#include "zapRTPFrame.h" +#include "zapIMediaGraph.h" +#include "nsString.h" +#include "nsIPropertyBag2.h" +#include "zapDatagramFrame.h" +#include "stdio.h" +#include "nsHashPropertyBag.h" +#include "zapMediaUtils.h" + +//////////////////////////////////////////////////////////////////////// +// zapRTPTransmitter + +zapRTPTransmitter::zapRTPTransmitter() +{ +#ifdef DEBUG + printf("zapRTPTransmitter::zapRTPTransmitter()\n"); +#endif +} + +zapRTPTransmitter::~zapRTPTransmitter() +{ +#ifdef DEBUG + printf("zapRTPTransmitter::~zapRTPTransmitter()\n"); +#endif +} + +NS_IMETHODIMP +zapRTPTransmitter::AddedToGraph(zapIMediaGraph *graph, const nsACString & id, + nsIPropertyBag2 *node_pars) +{ + // unpack node parameters: + if (!node_pars) { + NS_ERROR("no node parameters"); + return NS_ERROR_FAILURE; + } +// NS_ENSURE_SUCCESS(node_pars->GetPropertyAsUint32( +// NS_LITERAL_STRING("SSRC"), &mSSRC), +// NS_ERROR_FAILURE); + // XXX implement collision resolution (RFC3550) + mSSRC = rand(); + + + NS_ENSURE_SUCCESS(node_pars->GetPropertyAsACString( + NS_LITERAL_STRING("address"), mAddress), + NS_ERROR_FAILURE); + NS_ENSURE_SUCCESS(node_pars->GetPropertyAsUint16( + NS_LITERAL_STRING("port"), &mPort), + NS_ERROR_FAILURE); + + // RFC3550 5.1: + // The initial value of the sequence number SHOULD be random + // (unpredictable) to make known-plaintext attacks on encryption + // more difficult, even if the source itself does not encrypt + // according to the method in Section 9.1, because the packets may + // flow through a translator that does. + mSequenceNumber = rand(); + + return NS_OK; +} + +NS_IMETHODIMP +zapRTPTransmitter::RemovedFromGraph(zapIMediaGraph *graph) +{ + return NS_OK; +} + +nsresult +zapRTPTransmitter::OpenStream(nsIPropertyBag2* streamInfo) +{ + ZMK_VERIFY_STREAM_TYPE(streamInfo, "rtp"); + ZMK_CREATE_STREAM_INFO(mStreamInfo, "datagram"); + + return NS_OK; +} + +void +zapRTPTransmitter::CloseStream() +{ +} + +nsresult +zapRTPTransmitter::Filter(zapIMediaFrame* input, zapIMediaFrame** output) +{ + // input frame must be an rtp frame: + nsCOMPtr rtpFrame = do_QueryInterface(input); + if (!rtpFrame) { + NS_ERROR("unexpected frame"); + return NS_ERROR_FAILURE; + } + + // set SSRC and sequence number: + rtpFrame->SetSSRC(mSSRC); + rtpFrame->SetSequenceNumber(mSequenceNumber++); + + // create datagram frame: + zapDatagramFrame* frame = new zapDatagramFrame(); + frame->AddRef(); + frame->mStreamInfo = mStreamInfo; + input->GetData(frame->mData); + frame->mAddress = mAddress; + frame->mPort = mPort; + *output = frame; + return NS_OK; +} diff --git a/mozilla/zap/zmk/src/zapRTPTransmitter.h b/mozilla/zap/zmk/src/zapRTPTransmitter.h new file mode 100644 index 00000000000..565987c5479 --- /dev/null +++ b/mozilla/zap/zmk/src/zapRTPTransmitter.h @@ -0,0 +1,75 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#ifndef __ZAP_RTPTRANSMITTER_H__ +#define __ZAP_RTPTRANSMITTER_H__ + +#include "zapFilterNode.h" +#include "nsIWritablePropertyBag2.h" +#include "nsString.h" + +//////////////////////////////////////////////////////////////////////// +// zapRTPTransmitter + +// {C9A54262-F676-420A-90B4-3C92D7E2C456} +#define ZAP_RTPTRANSMITTER_CID \ + { 0xc9a54262, 0xf676, 0x420a, { 0x90, 0xb4, 0x3c, 0x92, 0xd7, 0xe2, 0xc4, 0x56 } } + +#define ZAP_RTPTRANSMITTER_CONTRACTID ZAP_MEDIANODE_CONTRACTID_PREFIX "rtp-transmitter" + +class zapRTPTransmitter : public zapFilterNode +{ +public: + zapRTPTransmitter(); + ~zapRTPTransmitter(); + + NS_IMETHOD AddedToGraph(zapIMediaGraph *graph, + const nsACString & id, + nsIPropertyBag2 *node_pars); + NS_IMETHOD RemovedFromGraph(zapIMediaGraph *graph); + virtual nsresult OpenStream(nsIPropertyBag2* streamInfo); + virtual void CloseStream(); + virtual nsresult Filter(zapIMediaFrame* input, zapIMediaFrame** output); + +private: + nsCOMPtr mStreamInfo; + PRUint32 mSSRC; + nsCString mAddress; + PRUint16 mPort; + PRUint16 mSequenceNumber; +}; + +#endif // __ZAP_RTPTRANSMITTER_H__ diff --git a/mozilla/zap/zmk/src/zapSpeexDecoder.cpp b/mozilla/zap/zmk/src/zapSpeexDecoder.cpp new file mode 100644 index 00000000000..c9e6d117e3b --- /dev/null +++ b/mozilla/zap/zmk/src/zapSpeexDecoder.cpp @@ -0,0 +1,177 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "zapSpeexDecoder.h" +#include "zapIMediaFrame.h" +#include "zapIMediaGraph.h" +#include "nsString.h" +#include "nsIPropertyBag2.h" +#include "zapIAudioIn.h" +#include "zapMediaFrame.h" +#include "stdio.h" +#include "nsHashPropertyBag.h" + +//////////////////////////////////////////////////////////////////////// +// zapSpeexDecoder + +zapSpeexDecoder::zapSpeexDecoder() + : mDecoderState(nsnull) +{ +#ifdef DEBUG + printf("zapSpeexDecoder::zapSpeexDecoder()"); +#endif +} + +zapSpeexDecoder::~zapSpeexDecoder() +{ + NS_ASSERTION(!mDecoderState, "unclean shutdown"); +#ifdef DEBUG + printf("zapSpeexDecoder::~zapSpeexDecoder()"); +#endif +} + +NS_IMETHODIMP +zapSpeexDecoder::AddedToGraph(zapIMediaGraph *graph, const nsACString & id, nsIPropertyBag2 *node_pars) +{ + // default: nb mode + const SpeexMode* speexmode = &speex_nb_mode; + mSampleRate = 8000.0f; + + // extract node parameters: + + if (node_pars) { + if (NS_SUCCEEDED(node_pars->GetPropertyAsDouble(NS_LITERAL_STRING("sample_rate"), + &mSampleRate))) { + if (mSampleRate == 8000.0f) { + speexmode = &speex_nb_mode; + } + else if (mSampleRate == 16000.0f) { + speexmode = &speex_wb_mode; + } + else if (mSampleRate == 32000.0f) { + speexmode = &speex_uwb_mode; + } + else { + NS_ERROR("unsupported sample rate"); + return NS_ERROR_FAILURE; + } + } + } + + speex_bits_init(&mDecoderBits); + mDecoderState = speex_decoder_init(speexmode); + + return NS_OK; +} + +NS_IMETHODIMP +zapSpeexDecoder::RemovedFromGraph(zapIMediaGraph *graph) +{ + speex_bits_destroy(&mDecoderBits); + speex_decoder_destroy(mDecoderState); + mDecoderState = nsnull; + return NS_OK; +} + +nsresult +zapSpeexDecoder::OpenStream(nsIPropertyBag2* streamInfo) +{ + if (!streamInfo) { + NS_ERROR("can't open stream without info"); + return NS_ERROR_FAILURE; + } + + nsCString type; + if (NS_FAILED(streamInfo->GetPropertyAsACString(NS_LITERAL_STRING("type"), + type)) || + type != NS_LITERAL_CSTRING("audio/speex")) { + NS_ERROR("can only decode audio/speex streams"); + return NS_ERROR_FAILURE; + } + + // Stream parameters are ok. + + // determine output buffer size: + int frameSize; + speex_decoder_ctl(mDecoderState, SPEEX_GET_FRAME_SIZE, &frameSize); + mOutputBufferLength = 4 * frameSize; // float32 samples + + // Create a new streaminfo: + nsCOMPtr bag; + NS_NewHashPropertyBag(getter_AddRefs(bag)); + mStreamInfo = do_QueryInterface(bag); + mStreamInfo->SetPropertyAsACString(NS_LITERAL_STRING("type"), + NS_LITERAL_CSTRING("audio")); + mStreamInfo->SetPropertyAsDouble(NS_LITERAL_STRING("sample_rate"), + mSampleRate); + mStreamInfo->SetPropertyAsDouble(NS_LITERAL_STRING("frame_duration"), + 0.02); + mStreamInfo->SetPropertyAsUint32(NS_LITERAL_STRING("channels"), + 1); + mStreamInfo->SetPropertyAsACString(NS_LITERAL_STRING("sample_format"), + NS_LITERAL_CSTRING("float32_32768")); + + + return NS_OK; +} + +void +zapSpeexDecoder::CloseStream() +{ +} + +nsresult +zapSpeexDecoder::Filter(zapIMediaFrame* input, zapIMediaFrame** output) +{ + // flush old bits: + speex_bits_reset(&mDecoderBits); + + // create frame: + zapMediaFrame* frame = new zapMediaFrame(); + frame->AddRef(); + frame->mStreamInfo = mStreamInfo; + input->GetTimestamp(&frame->mTimestamp); + + // decode frame: + nsCString data; + input->GetData(data); + speex_bits_read_from(&mDecoderBits, (char*)data.BeginReading(), data.Length()); + frame->mData.SetLength(mOutputBufferLength); + speex_decode(mDecoderState, &mDecoderBits, (float*)frame->mData.BeginWriting()); + + *output = frame; + return NS_OK; +} diff --git a/mozilla/zap/zmk/src/zapSpeexDecoder.h b/mozilla/zap/zmk/src/zapSpeexDecoder.h new file mode 100644 index 00000000000..6e123d9979b --- /dev/null +++ b/mozilla/zap/zmk/src/zapSpeexDecoder.h @@ -0,0 +1,75 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#ifndef __ZAP_SPEEXDECODER_H__ +#define __ZAP_SPEEXDECODER_H__ + +#include "zapFilterNode.h" +#include "speex/speex.h" +#include "nsIWritablePropertyBag2.h" + +//////////////////////////////////////////////////////////////////////// +// zapSpeexDecoder + +// {9B930D99-3608-449B-8BA0-D77EBB879AE1} +#define ZAP_SPEEXDECODER_CID \ + { 0x9b930d99, 0x3608, 0x449b, { 0x8b, 0xa0, 0xd7, 0x7e, 0xbb, 0x87, 0x9a, 0xe1 } } + +#define ZAP_SPEEXDECODER_CONTRACTID ZAP_MEDIANODE_CONTRACTID_PREFIX "speex-decoder" + +class zapSpeexDecoder : public zapFilterNode +{ +public: + zapSpeexDecoder(); + ~zapSpeexDecoder(); + + NS_IMETHOD AddedToGraph(zapIMediaGraph *graph, + const nsACString & id, + nsIPropertyBag2 *node_pars); + NS_IMETHOD RemovedFromGraph(zapIMediaGraph *graph); + virtual nsresult OpenStream(nsIPropertyBag2* streamInfo); + virtual void CloseStream(); + virtual nsresult Filter(zapIMediaFrame* input, zapIMediaFrame** output); + +private: + double mSampleRate; + SpeexBits mDecoderBits; + void* mDecoderState; + PRUint32 mOutputBufferLength; // length of output buffers (bytes) + nsCOMPtr mStreamInfo; +}; + +#endif // __ZAP_SPEEXDECODER_H__ diff --git a/mozilla/zap/zmk/src/zapSpeexEncoder.cpp b/mozilla/zap/zmk/src/zapSpeexEncoder.cpp new file mode 100644 index 00000000000..387a53ffbca --- /dev/null +++ b/mozilla/zap/zmk/src/zapSpeexEncoder.cpp @@ -0,0 +1,364 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "zapSpeexEncoder.h" +#include "zapIMediaFrame.h" +#include "zapIMediaGraph.h" +#include "nsIPropertyBag2.h" +#include "zapIAudioIn.h" +#include "zapMediaFrame.h" +#include "stdio.h" +#include "nsHashPropertyBag.h" + +//////////////////////////////////////////////////////////////////////// +// zapSpeexEncoder + +zapSpeexEncoder::zapSpeexEncoder() + : mEncoderState(nsnull) +{ +#ifdef DEBUG + printf("zapSpeexEncoder::zapSpeexEncoder()"); +#endif +} + +zapSpeexEncoder::~zapSpeexEncoder() +{ + NS_ASSERTION(!mEncoderState, "unclean shutdown"); +#ifdef DEBUG + printf("zapSpeexEncoder::~zapSpeexEncoder()"); +#endif +} + +//---------------------------------------------------------------------- +// nsISupports methods: + +NS_IMPL_ADDREF_INHERITED(zapSpeexEncoder, zapFilterNode) +NS_IMPL_RELEASE_INHERITED(zapSpeexEncoder, zapFilterNode) + +NS_INTERFACE_MAP_BEGIN(zapSpeexEncoder) + NS_INTERFACE_MAP_ENTRY(zapISpeexEncoder) +NS_INTERFACE_MAP_END_INHERITING(zapFilterNode) + +//---------------------------------------------------------------------- +// zapISpeexEncoder methods: + +/* void SetQuality (in unsigned long quality); */ +NS_IMETHODIMP +zapSpeexEncoder::SetQuality(PRUint32 aQuality) +{ + int val = aQuality; + speex_encoder_ctl(mEncoderState, SPEEX_SET_QUALITY, &val); + return NS_OK; +} + +/* attribute boolean vbr; */ +NS_IMETHODIMP +zapSpeexEncoder::GetVbr(PRBool *aVbr) +{ + int bVBR; + speex_encoder_ctl(mEncoderState, SPEEX_GET_VBR, &bVBR); + *aVbr = (bVBR==1); + return NS_OK; +} +NS_IMETHODIMP +zapSpeexEncoder::SetVbr(PRBool aVbr) +{ + int bVBR = aVbr; + speex_encoder_ctl(mEncoderState, SPEEX_SET_VBR, &bVBR); + return NS_OK; +} + +/* attribute float vbrQuality; */ +NS_IMETHODIMP +zapSpeexEncoder::GetVbrQuality(float *aVbrQuality) +{ + speex_encoder_ctl(mEncoderState, SPEEX_GET_VBR_QUALITY, aVbrQuality); + return NS_OK; +} +NS_IMETHODIMP +zapSpeexEncoder::SetVbrQuality(float aVbrQuality) +{ + speex_encoder_ctl(mEncoderState, SPEEX_SET_VBR_QUALITY, &aVbrQuality); + return NS_OK; +} + +/* attribute unsigned long complexity; */ +NS_IMETHODIMP +zapSpeexEncoder::GetComplexity(PRUint32 *aComplexity) +{ + int complexity; + speex_encoder_ctl(mEncoderState, SPEEX_GET_COMPLEXITY, &complexity); + *aComplexity = complexity; + return NS_OK; +} +NS_IMETHODIMP +zapSpeexEncoder::SetComplexity(PRUint32 aComplexity) +{ + int complexity = aComplexity; + speex_encoder_ctl(mEncoderState, SPEEX_SET_COMPLEXITY, &complexity); + return NS_OK; +} + +/* attribute boolean vad; */ +NS_IMETHODIMP +zapSpeexEncoder::GetVad(PRBool *aVad) +{ + int bVAD; + speex_encoder_ctl(mEncoderState, SPEEX_GET_VAD, &bVAD); + *aVad = (bVAD==1); + return NS_OK; +} +NS_IMETHODIMP +zapSpeexEncoder::SetVad(PRBool aVad) +{ + int bVAD = aVad; + speex_encoder_ctl(mEncoderState, SPEEX_SET_VAD, &bVAD); + return NS_OK; +} + +/* attribute boolean dtx; */ +NS_IMETHODIMP +zapSpeexEncoder::GetDtx(PRBool *aDtx) +{ + int bDTX; + speex_encoder_ctl(mEncoderState, SPEEX_GET_DTX, &bDTX); + *aDtx = (bDTX==1); + return NS_OK; +} +NS_IMETHODIMP +zapSpeexEncoder::SetDtx(PRBool aDtx) +{ + int bDTX = aDtx; + speex_encoder_ctl(mEncoderState, SPEEX_SET_DTX, &bDTX); + return NS_OK; +} + +/* attribute unsigned long averageBitrate; */ +NS_IMETHODIMP +zapSpeexEncoder::GetAverageBitrate(PRUint32 *aAverageBitrate) +{ + int abr; + speex_encoder_ctl(mEncoderState, SPEEX_GET_ABR, &abr); + *aAverageBitrate = (PRUint32)abr; + return NS_OK; +} +NS_IMETHODIMP +zapSpeexEncoder::SetAverageBitrate(PRUint32 aAverageBitrate) +{ + int abr = aAverageBitrate; + speex_encoder_ctl(mEncoderState, SPEEX_SET_ABR, &abr); + return NS_OK; +} + +/* attribute unsigned long maxBitrate; */ +NS_IMETHODIMP +zapSpeexEncoder::GetMaxBitrate(PRUint32 *aMaxBitrate) +{ + int br; + speex_encoder_ctl(mEncoderState, SPEEX_GET_BITRATE, &br); + *aMaxBitrate = (PRUint32)br; + return NS_OK; +} +NS_IMETHODIMP +zapSpeexEncoder::SetMaxBitrate(PRUint32 aMaxBitrate) +{ + int br = aMaxBitrate; + speex_encoder_ctl(mEncoderState, SPEEX_SET_BITRATE, &br); + return NS_OK; +} + +/* attribute unsigned long plcTuning; */ +NS_IMETHODIMP +zapSpeexEncoder::GetPlcTuning(PRUint32 *aPlcTuning) +{ + int plct; + speex_encoder_ctl(mEncoderState, SPEEX_GET_PLC_TUNING, &plct); + *aPlcTuning = (PRUint32)plct; + return NS_OK; +} +NS_IMETHODIMP +zapSpeexEncoder::SetPlcTuning(PRUint32 aPlcTuning) +{ + int plct = aPlcTuning; + speex_encoder_ctl(mEncoderState, SPEEX_SET_PLC_TUNING, &plct); + return NS_OK; +} + + +//---------------------------------------------------------------------- +// Implementation helpers: + +NS_IMETHODIMP +zapSpeexEncoder::AddedToGraph(zapIMediaGraph *graph, const nsACString & id, nsIPropertyBag2 *node_pars) +{ + // default: nb mode + const SpeexMode* speexmode = &speex_nb_mode; + mSampleRate = 8000.0f; + + // extract node parameters: + + if (node_pars) { + if (NS_SUCCEEDED(node_pars->GetPropertyAsDouble(NS_LITERAL_STRING("sample_rate"), + &mSampleRate))) { + if (mSampleRate == 8000.0f) { + speexmode = &speex_nb_mode; + } + else if (mSampleRate == 16000.0f) { + speexmode = &speex_wb_mode; + } + else if (mSampleRate == 32000.0f) { + speexmode = &speex_uwb_mode; + } + else { + NS_ERROR("unsupported sample rate"); + return NS_ERROR_FAILURE; + } + } + } + + speex_bits_init(&mEncoderBits); + mEncoderState = speex_encoder_init(speexmode); + return NS_OK; +} + +NS_IMETHODIMP +zapSpeexEncoder::RemovedFromGraph(zapIMediaGraph *graph) +{ + speex_bits_destroy(&mEncoderBits); + speex_encoder_destroy(mEncoderState); + mEncoderState = nsnull; + return NS_OK; +} + +nsresult +zapSpeexEncoder::OpenStream(nsIPropertyBag2* streamInfo) +{ + if (!streamInfo) { + NS_ERROR("can't open stream without info"); + return NS_ERROR_FAILURE; + } + + nsCString type; + if (NS_FAILED(streamInfo->GetPropertyAsACString(NS_LITERAL_STRING("type"), + type)) || + type != NS_LITERAL_CSTRING("audio")) { + NS_ERROR("can only encode audio streams"); + return NS_ERROR_FAILURE; + } + + double sampleRate; + if (NS_FAILED(streamInfo->GetPropertyAsDouble(NS_LITERAL_STRING("sample_rate"), + &sampleRate)) || + sampleRate != mSampleRate) { + NS_ERROR("unsupported sample rate"); +#ifdef DEBUG + printf("%f != %f\n", sampleRate, mSampleRate); +#endif + return NS_ERROR_FAILURE; + } + + double frameDuration; + if (NS_FAILED(streamInfo->GetPropertyAsDouble(NS_LITERAL_STRING("frame_duration"), + &frameDuration)) || + frameDuration != 0.02) { + NS_ERROR("unsupported frame duration"); + return NS_ERROR_FAILURE; + } + + PRUint32 numOutputChannels; + if (NS_FAILED(streamInfo->GetPropertyAsUint32(NS_LITERAL_STRING("channels"), + &numOutputChannels)) || + numOutputChannels != 1) { + NS_ERROR("unsupported channel count"); + return NS_ERROR_FAILURE; + } + + + nsCString sampleFormat; + if (NS_FAILED(streamInfo->GetPropertyAsACString(NS_LITERAL_STRING("sample_format"), + sampleFormat)) || + sampleFormat != NS_LITERAL_CSTRING("float32_32768")) { + NS_ERROR("unsupported sample format"); + return NS_ERROR_FAILURE; + } + + // Stream parameters are ok. + + // determine expected buffer size: + int frameSize; + speex_encoder_ctl(mEncoderState, SPEEX_GET_FRAME_SIZE, &frameSize); + mInputBufferLength = 4 * frameSize; // float32 samples + + // Create a new streaminfo: + nsCOMPtr bag; + NS_NewHashPropertyBag(getter_AddRefs(bag)); + mStreamInfo = do_QueryInterface(bag); + mStreamInfo->SetPropertyAsACString(NS_LITERAL_STRING("type"), + NS_LITERAL_CSTRING("audio/speex")); + + return NS_OK; +} + +void +zapSpeexEncoder::CloseStream() +{ +} + +nsresult +zapSpeexEncoder::Filter(zapIMediaFrame* input, zapIMediaFrame** output) +{ + // flush old bits: + speex_bits_reset(&mEncoderBits); + + // encode frame: + nsCString data; + input->GetData(data); + NS_ASSERTION(mInputBufferLength == data.Length(), "unexpected frame length"); + speex_encode(mEncoderState, (float*)data.BeginReading(), &mEncoderBits); + + // Create frame: + zapMediaFrame* frame = new zapMediaFrame(); + frame->AddRef(); + frame->mStreamInfo = mStreamInfo; + input->GetTimestamp(&frame->mTimestamp); + + // copy data: + int length = speex_bits_nbytes(&mEncoderBits); + frame->mData.SetLength(length); + speex_bits_write(&mEncoderBits, (char*)frame->mData.BeginWriting(), length); + *output = frame; + return NS_OK; +} diff --git a/mozilla/zap/zmk/src/zapSpeexEncoder.h b/mozilla/zap/zmk/src/zapSpeexEncoder.h new file mode 100644 index 00000000000..769e4ceb74c --- /dev/null +++ b/mozilla/zap/zmk/src/zapSpeexEncoder.h @@ -0,0 +1,81 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#ifndef __ZAP_SPEEXENCODER_H__ +#define __ZAP_SPEEXENCODER_H__ + +#include "zapFilterNode.h" +#include "speex/speex.h" +#include "nsIWritablePropertyBag2.h" +#include "zapISpeexEncoder.h" +#include "nsString.h" + +//////////////////////////////////////////////////////////////////////// +// zapSpeexEncoder + +// {68A90E36-5D20-4F90-8CA1-7ECC41953F48} +#define ZAP_SPEEXENCODER_CID \ + { 0x68a90e36, 0x5d20, 0x4f90, { 0x8c, 0xa1, 0x7e, 0xcc, 0x41, 0x95, 0x3f, 0x48 } } + +#define ZAP_SPEEXENCODER_CONTRACTID ZAP_MEDIANODE_CONTRACTID_PREFIX "speex-encoder" + +class zapSpeexEncoder : public zapFilterNode, + public zapISpeexEncoder +{ +public: + zapSpeexEncoder(); + ~zapSpeexEncoder(); + + NS_DECL_ISUPPORTS_INHERITED + NS_DECL_ZAPISPEEXENCODER + + NS_IMETHOD AddedToGraph(zapIMediaGraph *graph, + const nsACString & id, + nsIPropertyBag2 *node_pars); + NS_IMETHOD RemovedFromGraph(zapIMediaGraph *graph); + virtual nsresult OpenStream(nsIPropertyBag2* streamInfo); + virtual void CloseStream(); + virtual nsresult Filter(zapIMediaFrame* input, zapIMediaFrame** output); + +private: + double mSampleRate; // encoder sample rate + SpeexBits mEncoderBits; + void* mEncoderState; + PRUint32 mInputBufferLength; // expected length of input buffers (bytes) + nsCOMPtr mStreamInfo; +}; + +#endif // __ZAP_SPEEXENCODER_H__ diff --git a/mozilla/zap/zmk/src/zapSpeexRTPDepacketizer.cpp b/mozilla/zap/zmk/src/zapSpeexRTPDepacketizer.cpp new file mode 100644 index 00000000000..f04e9f5b985 --- /dev/null +++ b/mozilla/zap/zmk/src/zapSpeexRTPDepacketizer.cpp @@ -0,0 +1,122 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "zapSpeexRTPDepacketizer.h" +#include "zapRTPFrame.h" +#include "zapIMediaGraph.h" +#include "nsString.h" +#include "nsIPropertyBag2.h" +#include "zapMediaFrame.h" +#include "stdio.h" +#include "nsHashPropertyBag.h" + +//////////////////////////////////////////////////////////////////////// +// zapSpeexRTPDepacketizer + +zapSpeexRTPDepacketizer::zapSpeexRTPDepacketizer() +{ +} + +zapSpeexRTPDepacketizer::~zapSpeexRTPDepacketizer() +{ +} + +NS_IMETHODIMP +zapSpeexRTPDepacketizer::AddedToGraph(zapIMediaGraph *graph, + const nsACString & id, + nsIPropertyBag2 *node_pars) +{ + return NS_OK; +} + +NS_IMETHODIMP +zapSpeexRTPDepacketizer::RemovedFromGraph(zapIMediaGraph *graph) +{ + return NS_OK; +} + +nsresult +zapSpeexRTPDepacketizer::OpenStream(nsIPropertyBag2* streamInfo) +{ + if (!streamInfo) { + NS_ERROR("can't open stream without info"); + return NS_ERROR_FAILURE; + } + + nsCString type; + if (NS_FAILED(streamInfo->GetPropertyAsACString(NS_LITERAL_STRING("type"), + type)) || + type != NS_LITERAL_CSTRING("rtp")) { + NS_ERROR("can only convert rtp streams"); + return NS_ERROR_FAILURE; + } + + // Stream parameters are ok. + + // Create a new streaminfo: + nsCOMPtr bag; + NS_NewHashPropertyBag(getter_AddRefs(bag)); + mStreamInfo = do_QueryInterface(bag); + mStreamInfo->SetPropertyAsACString(NS_LITERAL_STRING("type"), + NS_LITERAL_CSTRING("audio/speex")); + return NS_OK; +} + +void +zapSpeexRTPDepacketizer::CloseStream() +{ +} + +nsresult +zapSpeexRTPDepacketizer::Filter(zapIMediaFrame* input, zapIMediaFrame** output) +{ + nsCOMPtr rtpFrame = do_QueryInterface(input); + if (!rtpFrame) { + NS_ERROR("stream format error"); + *output = nsnull; + return NS_ERROR_FAILURE; + } + + // create frame: + zapMediaFrame* frame = new zapMediaFrame(); + frame->AddRef(); + frame->mStreamInfo = mStreamInfo; + rtpFrame->GetPayload(frame->mData); + rtpFrame->GetTimestamp(&frame->mTimestamp); + + *output = frame; + return NS_OK; +} diff --git a/mozilla/zap/zmk/src/zapSpeexRTPDepacketizer.h b/mozilla/zap/zmk/src/zapSpeexRTPDepacketizer.h new file mode 100644 index 00000000000..c4bc90b436d --- /dev/null +++ b/mozilla/zap/zmk/src/zapSpeexRTPDepacketizer.h @@ -0,0 +1,71 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#ifndef __ZAP_SPEEXRTPDEPACKETIZER_H__ +#define __ZAP_SPEEXRTPDEPACKETIZER_H__ + +#include "zapFilterNode.h" +#include "speex/speex.h" +#include "nsIWritablePropertyBag2.h" + +//////////////////////////////////////////////////////////////////////// +// zapSpeexRTPDepacketizer + +// {109CA60D-EF11-41EB-91BB-6DC1437AB694} +#define ZAP_SPEEXRTPDEPACKETIZER_CID \ + { 0x109ca60d, 0xef11, 0x41eb, { 0x91, 0xbb, 0x6d, 0xc1, 0x43, 0x7a, 0xb6, 0x94 } } + +#define ZAP_SPEEXRTPDEPACKETIZER_CONTRACTID ZAP_MEDIANODE_CONTRACTID_PREFIX "speex-rtp-depacketizer" + +class zapSpeexRTPDepacketizer : public zapFilterNode +{ +public: + zapSpeexRTPDepacketizer(); + ~zapSpeexRTPDepacketizer(); + + NS_IMETHOD AddedToGraph(zapIMediaGraph *graph, + const nsACString & id, + nsIPropertyBag2 *node_pars); + NS_IMETHOD RemovedFromGraph(zapIMediaGraph *graph); + virtual nsresult OpenStream(nsIPropertyBag2* streamInfo); + virtual void CloseStream(); + virtual nsresult Filter(zapIMediaFrame* input, zapIMediaFrame** output); + +private: + nsCOMPtr mStreamInfo; +}; + +#endif // __ZAP_SPEEXRTPDEPACKETIZER_H__ diff --git a/mozilla/zap/zmk/src/zapSpeexRTPPacketizer.cpp b/mozilla/zap/zmk/src/zapSpeexRTPPacketizer.cpp new file mode 100644 index 00000000000..380aae2b2d7 --- /dev/null +++ b/mozilla/zap/zmk/src/zapSpeexRTPPacketizer.cpp @@ -0,0 +1,129 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "zapSpeexRTPPacketizer.h" +#include "zapRTPFrame.h" +#include "zapIMediaGraph.h" +#include "nsString.h" +#include "nsIPropertyBag2.h" +#include "zapMediaFrame.h" +#include "stdio.h" +#include "nsHashPropertyBag.h" + +//////////////////////////////////////////////////////////////////////// +// zapSpeexRTPPacketizer + +zapSpeexRTPPacketizer::zapSpeexRTPPacketizer() +{ +} + +zapSpeexRTPPacketizer::~zapSpeexRTPPacketizer() +{ +} + +NS_IMETHODIMP +zapSpeexRTPPacketizer::AddedToGraph(zapIMediaGraph *graph, const nsACString & id, nsIPropertyBag2 *node_pars) +{ + // set defaults: + mPayloadType = 96; + + // extract node parameters: + if (node_pars) { + node_pars->GetPropertyAsUint16(NS_LITERAL_STRING("payload_type"), + &mPayloadType); + } + + return NS_OK; +} + +NS_IMETHODIMP +zapSpeexRTPPacketizer::RemovedFromGraph(zapIMediaGraph *graph) +{ + return NS_OK; +} + +nsresult +zapSpeexRTPPacketizer::OpenStream(nsIPropertyBag2* streamInfo) +{ + if (!streamInfo) { + NS_ERROR("can't open stream without info"); + return NS_ERROR_FAILURE; + } + + nsCString type; + if (NS_FAILED(streamInfo->GetPropertyAsACString(NS_LITERAL_STRING("type"), + type)) || + type != NS_LITERAL_CSTRING("audio/speex")) { + NS_ERROR("can only convert audio/speex streams"); + return NS_ERROR_FAILURE; + } + + // Stream parameters are ok. + + // Create a new streaminfo: + nsCOMPtr bag; + NS_NewHashPropertyBag(getter_AddRefs(bag)); + mStreamInfo = do_QueryInterface(bag); + mStreamInfo->SetPropertyAsACString(NS_LITERAL_STRING("type"), + NS_LITERAL_CSTRING("rtp")); + return NS_OK; +} + +void +zapSpeexRTPPacketizer::CloseStream() +{ +} + +nsresult +zapSpeexRTPPacketizer::Filter(zapIMediaFrame* input, zapIMediaFrame** output) +{ + // create RTP frame: + zapRTPFrame* frame = CreateRTPFrame(); + frame->mStreamInfo = mStreamInfo; + + nsCString data; + input->GetData(data); + + frame->SetPayload(data); + frame->SetPayloadType(mPayloadType); + + PRUint32 timestamp; + input->GetTimestamp(×tamp); + frame->SetRtpTimestamp(timestamp); + + *output = frame; + return NS_OK; +} diff --git a/mozilla/zap/zmk/src/zapSpeexRTPPacketizer.h b/mozilla/zap/zmk/src/zapSpeexRTPPacketizer.h new file mode 100644 index 00000000000..bb2e6f10a51 --- /dev/null +++ b/mozilla/zap/zmk/src/zapSpeexRTPPacketizer.h @@ -0,0 +1,72 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#ifndef __ZAP_SPEEXRTPPACKETIZER_H__ +#define __ZAP_SPEEXRTPPACKETIZER_H__ + +#include "zapFilterNode.h" +#include "speex/speex.h" +#include "nsIWritablePropertyBag2.h" + +//////////////////////////////////////////////////////////////////////// +// zapSpeexRTPPacketizer + +// {BFB82FAE-DF32-4BBF-A0A8-417F04A846F7} +#define ZAP_SPEEXRTPPACKETIZER_CID \ + { 0xbfb82fae, 0xdf32, 0x4bbf, { 0xa0, 0xa8, 0x41, 0x7f, 0x04, 0xa8, 0x46, 0xf7 } } + +#define ZAP_SPEEXRTPPACKETIZER_CONTRACTID ZAP_MEDIANODE_CONTRACTID_PREFIX "speex-rtp-packetizer" + +class zapSpeexRTPPacketizer : public zapFilterNode +{ +public: + zapSpeexRTPPacketizer(); + ~zapSpeexRTPPacketizer(); + + NS_IMETHOD AddedToGraph(zapIMediaGraph *graph, + const nsACString & id, + nsIPropertyBag2 *node_pars); + NS_IMETHOD RemovedFromGraph(zapIMediaGraph *graph); + virtual nsresult OpenStream(nsIPropertyBag2* streamInfo); + virtual void CloseStream(); + virtual nsresult Filter(zapIMediaFrame* input, zapIMediaFrame** output); + +private: + nsCOMPtr mStreamInfo; + PRUint16 mPayloadType; +}; + +#endif // __ZAP_SPEEXRTPPACKETIZER_H__ diff --git a/mozilla/zap/zmk/src/zapUDPSocket.cpp b/mozilla/zap/zmk/src/zapUDPSocket.cpp new file mode 100644 index 00000000000..1431cc1fb9d --- /dev/null +++ b/mozilla/zap/zmk/src/zapUDPSocket.cpp @@ -0,0 +1,306 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "zapUDPSocket.h" +#include "nsIComponentManager.h" +#include "nsHashPropertyBag.h" +#include "nsString.h" +#include "zapDatagramFrame.h" +#include "nsNetCID.h" + +//////////////////////////////////////////////////////////////////////// +// zapUDPSocket + +zapUDPSocket::zapUDPSocket() + : mSinkWaiting(PR_FALSE), + mWaitingOnSource(PR_FALSE) +{ +#ifdef DEBUG + printf("zapUDPSocket::zapUDPSocket()\n"); +#endif +} + +zapUDPSocket::~zapUDPSocket() +{ + NS_ASSERTION(!mSocket, "unclean shutdown"); +#ifdef DEBUG + printf("zapUDPSocket::~zapUDPSocket()\n"); +#endif +} + +//---------------------------------------------------------------------- +// nsISupports methods: + +// these need to be threadsafe, as the socket thread will access them: +NS_IMPL_THREADSAFE_ADDREF(zapUDPSocket) +NS_IMPL_THREADSAFE_RELEASE(zapUDPSocket) + +NS_INTERFACE_MAP_BEGIN(zapUDPSocket) + NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, zapIMediaNode) + NS_INTERFACE_MAP_ENTRY(zapIMediaNode) + NS_INTERFACE_MAP_ENTRY(zapIMediaSource) + NS_INTERFACE_MAP_ENTRY(zapIMediaSink) + NS_INTERFACE_MAP_ENTRY(nsIUDPReceiver) + NS_INTERFACE_MAP_ENTRY(zapIUDPSocket) +NS_INTERFACE_MAP_END + +//---------------------------------------------------------------------- +// zapIMediaNode methods: + +/* void addedToGraph (in zapIMediaGraph graph, in ACString id, in nsIPropertyBag2 node_pars); */ +NS_IMETHODIMP +zapUDPSocket::AddedToGraph(zapIMediaGraph *graph, + const nsACString & id, + nsIPropertyBag2* node_pars) +{ + // unpack node parameters: + if (!node_pars) { + NS_ERROR("no node parameters"); + return NS_ERROR_FAILURE; + } + + if (NS_FAILED(node_pars->GetPropertyAsInterface(NS_LITERAL_STRING("socket"), + NS_GET_IID(nsIUDPSocket), + getter_AddRefs(mSocket))) + || !mSocket) { + PRUint16 port = 0; + node_pars->GetPropertyAsUint16(NS_LITERAL_STRING("port"), &port); + mSocket = do_CreateInstance(NS_UDPSOCKET_CONTRACTID); + if (!mSocket) { + NS_ERROR("failure creating socket"); + return NS_ERROR_FAILURE; + } + + if (NS_FAILED(mSocket->Init(port))) { + NS_ERROR("port initialization failed"); + mSocket = nsnull; + return NS_ERROR_FAILURE; + } + } + + mSocket->SetReceiver(this); + + // create a new streaminfo: + nsCOMPtr bag; + NS_NewHashPropertyBag(getter_AddRefs(bag)); + mStreamInfo = do_QueryInterface(bag); + + mStreamInfo->SetPropertyAsACString(NS_LITERAL_STRING("type"), + NS_LITERAL_CSTRING("datagram")); + + return NS_OK; +} + +/* void removedFromGraph (in zapIMediaGraph graph); */ +NS_IMETHODIMP +zapUDPSocket::RemovedFromGraph(zapIMediaGraph *graph) +{ + if (mSocket) { + mSocket->Close(); + mSocket = nsnull; + } + return NS_OK; +} + +/* zapIMediaSource getSource (in nsIPropertyBag2 source_pars); */ +NS_IMETHODIMP +zapUDPSocket::GetSource(nsIPropertyBag2 *source_pars, zapIMediaSource **_retval) +{ + if (mSink) { + NS_ERROR("already connected"); + return NS_ERROR_FAILURE; + } + + *_retval = this; + NS_ADDREF(*_retval); + return NS_OK; +} + +/* zapIMediaSink getSink (in nsIPropertyBag2 sink_pars); */ +NS_IMETHODIMP +zapUDPSocket::GetSink(nsIPropertyBag2 *sink_pars, zapIMediaSink **_retval) +{ + if (mSource) { + NS_ERROR("already connected"); + return NS_ERROR_FAILURE; + } + + *_retval = this; + NS_ADDREF(*_retval); + return NS_OK; +} + + +//---------------------------------------------------------------------- +// zapIMediaSource methods: + +/* void connectSink (in zapIMediaSink sink, in ACString connection_id); */ +NS_IMETHODIMP +zapUDPSocket::ConnectSink(zapIMediaSink *sink, + const nsACString & connection_id) +{ + NS_ASSERTION(!mSink, "already connected"); + mSink = sink; + return NS_OK; +} + +/* void disconnectSink (in zapIMediaSink sink, in ACString connection_id); */ +NS_IMETHODIMP +zapUDPSocket::DisconnectSink(zapIMediaSink *sink, + const nsACString & connection_id) +{ + mSink = nsnull; + mSinkWaiting = PR_FALSE; + return NS_OK; +} + +/* void requestFrame (); */ +NS_IMETHODIMP +zapUDPSocket::RequestFrame() +{ + NS_ASSERTION(!mSinkWaiting, "protocol error"); + mSinkWaiting = PR_TRUE; + return NS_OK; +} + + +//---------------------------------------------------------------------- +// zapIMediaSink methods: + +/* void connectSource (in zapIMediaSource source, in ACString connection_id); */ +NS_IMETHODIMP +zapUDPSocket::ConnectSource(zapIMediaSource *source, + const nsACString & connection_id) +{ + NS_ASSERTION(!mSource, "already connected"); + mSource = source; + + // request first buffer frame: + mWaitingOnSource = PR_TRUE; + mSource->RequestFrame(); + + return NS_OK; +} + +/* void disconnectSource (in zapIMediaSource source, in ACString connection_id); */ +NS_IMETHODIMP +zapUDPSocket::DisconnectSource(zapIMediaSource *source, + const nsACString & connection_id) +{ + mSource = nsnull; + mWaitingOnSource = PR_FALSE; + return NS_OK; +} + +/* void processFrame (in zapIMediaFrame frame); */ +NS_IMETHODIMP +zapUDPSocket::ProcessFrame(zapIMediaFrame *frame) +{ + nsCOMPtr dg = do_QueryInterface(frame); + if (!dg) { +#ifdef DEBUG + printf("n"); +#endif + // silently drop EOF or incompatible frame + } + else { + nsCString data, address; + PRInt32 port; + dg->GetData(data); + dg->GetAddress(address); + dg->GetPort(&port); + mSocket->Send(data, address, port); + } + + // request next frame + // XXX we need some pacing callback here + mWaitingOnSource = PR_FALSE; + mSource->RequestFrame(); + + return NS_OK; +} + +//---------------------------------------------------------------------- +// nsIUDPReceiver methods: + +/* void handleDatagram (in nsIUDPSocket socket, in nsIDatagram data); */ +NS_IMETHODIMP +zapUDPSocket::HandleDatagram(nsIUDPSocket *socket, nsIDatagram *data) +{ + if (!mSinkWaiting) { + // silently discard datagram: +#ifdef DEBUG + printf("d"); +#endif + } + else { + NS_ASSERTION(mSink, "uh-oh, no sink!"); + NS_ASSERTION(data, "no datagram"); + // build frame + zapDatagramWrapperFrame* frame = new zapDatagramWrapperFrame(); + frame->AddRef(); + frame->mStreamInfo = mStreamInfo; + frame->mDatagram = data; + mSinkWaiting = PR_FALSE; + mSink->ProcessFrame(frame); + frame->Release(); + } + + return NS_OK; +} + +//---------------------------------------------------------------------- +// zapIUDPSocket methods: + +/* readonly attribute unsigned short port; */ +NS_IMETHODIMP +zapUDPSocket::GetPort(PRUint16 *aPort) +{ + if (!mSocket) { + *aPort = 0; + return NS_ERROR_FAILURE; + } + + PRInt32 port; + mSocket->GetPort(&port); + if (port == -1) { + *aPort = 0; + return NS_ERROR_FAILURE; + } + *aPort = (PRUint16)port; + + return NS_OK; +} diff --git a/mozilla/zap/zmk/src/zapUDPSocket.h b/mozilla/zap/zmk/src/zapUDPSocket.h new file mode 100644 index 00000000000..0f32935fb42 --- /dev/null +++ b/mozilla/zap/zmk/src/zapUDPSocket.h @@ -0,0 +1,88 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#ifndef __ZAP_UDPSOCKET_H__ +#define __ZAP_UDPSOCKET_H__ + +#include "zapIMediaNode.h" +#include "zapIMediaSource.h" +#include "zapIMediaSink.h" +#include "zapIMediaGraph.h" +#include "zapIMediaFrame.h" +#include "nsCOMPtr.h" +#include "nsIWritablePropertyBag2.h" +#include "nsIUDPSocket.h" +#include "zapIUDPSocket.h" + +//////////////////////////////////////////////////////////////////////// +// zapUDPSocket + +// {F6469415-EF80-499F-89AE-39297DE09F24} +#define ZAP_UDPSOCKET_CID \ + { 0xf6469415, 0xef80, 0x499f, { 0x89, 0xae, 0x39, 0x29, 0x7d, 0xe0, 0x9f, 0x24 } } + +#define ZAP_UDPSOCKET_CONTRACTID ZAP_MEDIANODE_CONTRACTID_PREFIX "udp-socket" + +class zapUDPSocket : public zapIMediaNode, + public zapIMediaSink, + public zapIMediaSource, + public nsIUDPReceiver, + public zapIUDPSocket +{ +public: + zapUDPSocket(); + ~zapUDPSocket(); + + NS_DECL_ISUPPORTS + NS_DECL_ZAPIMEDIANODE + NS_DECL_ZAPIMEDIASINK + NS_DECL_ZAPIMEDIASOURCE + NS_DECL_NSIUDPRECEIVER + NS_DECL_ZAPIUDPSOCKET + +private: + nsCOMPtr mSocket; + + PRBool mSinkWaiting; + PRBool mWaitingOnSource; + + nsCOMPtr mStreamInfo; + + nsCOMPtr mSource; + nsCOMPtr mSink; +}; + +#endif // __ZAP_UDPSOCKET_H__ diff --git a/mozilla/zap/zmk/src/zapUDPSocketPair.cpp b/mozilla/zap/zmk/src/zapUDPSocketPair.cpp new file mode 100644 index 00000000000..3e0c75ef7f5 --- /dev/null +++ b/mozilla/zap/zmk/src/zapUDPSocketPair.cpp @@ -0,0 +1,253 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "zapUDPSocketPair.h" +#include "zapIMediaGraph.h" +#include "nsHashPropertyBag.h" +#include "zapIUDPSocket.h" +#include "nsIUDPSocket.h" +#include "nsNetCID.h" +#include "nsComponentManagerUtils.h" +#include "nsString.h" + +//////////////////////////////////////////////////////////////////////// +// zapUDPSocketPair + +zapUDPSocketPair::zapUDPSocketPair() +{ +#ifdef DEBUG + printf("zapUDPSocketPair::zapUDPSocketPair()\n"); +#endif +} + +zapUDPSocketPair::~zapUDPSocketPair() +{ +#ifdef DEBUG + printf("zapUDPSocketPair::~zapUDPSocketPair()\n"); +#endif +} + +//---------------------------------------------------------------------- +// nsISupports methods: + +NS_IMPL_ADDREF(zapUDPSocketPair) +NS_IMPL_RELEASE(zapUDPSocketPair) + +NS_INTERFACE_MAP_BEGIN(zapUDPSocketPair) + NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, zapIMediaNode) + NS_INTERFACE_MAP_ENTRY(zapIMediaNode) + NS_INTERFACE_MAP_ENTRY(zapIUDPSocketPair) +NS_INTERFACE_MAP_END + +//---------------------------------------------------------------------- +// zapIMediaNode methods: + +/* void addedToGraph (in zapIMediaGraph graph, in ACString id, in nsIPropertyBag2 node_pars); */ +NS_IMETHODIMP +zapUDPSocketPair::AddedToGraph(zapIMediaGraph *graph, + const nsACString & id, + nsIPropertyBag2* node_pars) +{ + PRUint16 portbase = 49152; + // unpack node parameters: + if (node_pars) { + node_pars->GetPropertyAsUint16(NS_LITERAL_STRING("portbase"), &portbase); + } + + if (portbase == 0 || portbase == 65535) { + NS_ERROR("portbase must be between 1 and 65534"); + return NS_ERROR_FAILURE; + } + + // create sockets: + nsCOMPtr socketA = do_CreateInstance(NS_UDPSOCKET_CONTRACTID); + nsCOMPtr socketB = do_CreateInstance(NS_UDPSOCKET_CONTRACTID); + + if (!socketA || !socketB) { + NS_ERROR("failure creating sockets"); + return NS_ERROR_FAILURE; + } + + // search for free ports port_a, port_b + // with portbase <= port_a, port_a = 2*n, and port_b = 2*n+1: + + // make sure portbase is next even number: + portbase = ((portbase+1)>>1)<<1; + for (PRUint32 port = portbase; port<65535; port+=2) { + if (NS_SUCCEEDED(socketA->Init(port))) { + if (NS_SUCCEEDED(socketB->Init(port+1))) { + break; + } + else { + socketA->Close(); + } + } + } + if (port == 65536) { + NS_ERROR("no free ports found"); + return NS_ERROR_FAILURE; + } + + // create a propertybag for initializing our socket nodes: + nsCOMPtr props; + NS_NewHashPropertyBag2(getter_AddRefs(props)); + + // create socket nodes: + props->SetPropertyAsInterface(NS_LITERAL_STRING("socket"), socketA); + NS_ENSURE_SUCCESS(graph->AddNode(NS_LITERAL_CSTRING("udp-socket"), + props, mSocketAID), + NS_ERROR_FAILURE); + graph->GetNode(mSocketAID, NS_GET_IID(zapIMediaNode), true, + getter_AddRefs(mSocketA)); + if (!mSocketA) { + graph->RemoveNode(mSocketAID); + return NS_ERROR_FAILURE; + } + + props->SetPropertyAsInterface(NS_LITERAL_STRING("socket"), socketB); + if (NS_FAILED(graph->AddNode(NS_LITERAL_CSTRING("udp-socket"), + props, mSocketBID))) { + graph->RemoveNode(mSocketAID); + return NS_ERROR_FAILURE; + } + graph->GetNode(mSocketBID, NS_GET_IID(zapIMediaNode), true, + getter_AddRefs(mSocketB)); + if (!mSocketB) { + graph->RemoveNode(mSocketAID); + graph->RemoveNode(mSocketBID); + return NS_ERROR_FAILURE; + } + + return NS_OK; +} + +/* void removedFromGraph (in zapIMediaGraph graph); */ +NS_IMETHODIMP +zapUDPSocketPair::RemovedFromGraph(zapIMediaGraph *graph) +{ + if (mSocketA) { + graph->RemoveNode(mSocketAID); + mSocketA = nsnull; + } + if (mSocketB) { + graph->RemoveNode(mSocketBID); + mSocketB = nsnull; + } + return NS_OK; +} + +/* zapIMediaSource getSource (in nsIPropertyBag2 source_pars); */ +NS_IMETHODIMP +zapUDPSocketPair::GetSource(nsIPropertyBag2 *source_pars, zapIMediaSource **_retval) +{ + NS_ASSERTION(mSocketA, "uh-oh, no socket A"); + NS_ASSERTION(mSocketB, "uh-oh, no socket B"); + + // dispatch depending on source name given in source parameters + if (!source_pars) { + NS_ERROR("no source pars"); + return NS_ERROR_FAILURE; + } + + nsCString source_name; + NS_ENSURE_SUCCESS(source_pars->GetPropertyAsACString(NS_LITERAL_STRING("name"), source_name), + NS_ERROR_FAILURE); + + if (source_name == NS_LITERAL_CSTRING("socket-a")) { + return mSocketA->GetSource(source_pars, _retval); + } + else if (source_name == NS_LITERAL_CSTRING("socket-b")) { + return mSocketB->GetSource(source_pars, _retval); + } + + NS_ERROR("unknown source"); + return NS_ERROR_FAILURE; +} + +/* zapIMediaSink getSink (in nsIPropertyBag2 sink_pars); */ +NS_IMETHODIMP +zapUDPSocketPair::GetSink(nsIPropertyBag2 *sink_pars, zapIMediaSink **_retval) +{ + NS_ASSERTION(mSocketA, "uh-oh, no socket A"); + NS_ASSERTION(mSocketB, "uh-oh, no socket B"); + + // dispatch depending on source name given in sink parameters + if (!sink_pars) { + NS_ERROR("no sink pars"); + return NS_ERROR_FAILURE; + } + + nsCString sink_name; + NS_ENSURE_SUCCESS(sink_pars->GetPropertyAsACString(NS_LITERAL_STRING("name"), sink_name), + NS_ERROR_FAILURE); + + if (sink_name == NS_LITERAL_CSTRING("socket-a")) { + return mSocketA->GetSink(sink_pars, _retval); + } + else if (sink_name == NS_LITERAL_CSTRING("socket-b")) { + return mSocketB->GetSink(sink_pars, _retval); + } + + NS_ERROR("unknown sink"); + return NS_ERROR_FAILURE; +} + +//---------------------------------------------------------------------- +// zapIUDPSocketPair methods: + +/* readonly attribute unsigned short portA; */ +NS_IMETHODIMP +zapUDPSocketPair::GetPortA(PRUint16 *aPortA) +{ + nsCOMPtr udpSocket = do_QueryInterface(mSocketA); + if (!udpSocket) { + *aPortA = 0; + return NS_ERROR_FAILURE; + } + return udpSocket->GetPort(aPortA); +} + +/* readonly attribute unsigned short portB; */ +NS_IMETHODIMP +zapUDPSocketPair::GetPortB(PRUint16 *aPortB) +{ + nsCOMPtr udpSocket = do_QueryInterface(mSocketB); + if (!udpSocket) { + *aPortB = 0; + return NS_ERROR_FAILURE; + } + return udpSocket->GetPort(aPortB); +} diff --git a/mozilla/zap/zmk/src/zapUDPSocketPair.h b/mozilla/zap/zmk/src/zapUDPSocketPair.h new file mode 100644 index 00000000000..9a751e1e8ee --- /dev/null +++ b/mozilla/zap/zmk/src/zapUDPSocketPair.h @@ -0,0 +1,72 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Mozilla SIP client project. + * + * The Initial Developer of the Original Code is 8x8 Inc. + * Portions created by the Initial Developer are Copyright (C) 2005 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Alex Fritze (original author) + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#ifndef __ZAP_UDPSOCKETPAIR_H__ +#define __ZAP_UDPSOCKETPAIR_H__ + +#include "zapIMediaNode.h" +#include "zapIUDPSocketPair.h" +#include "nsCOMPtr.h" +#include "nsString.h" + +//////////////////////////////////////////////////////////////////////// +// zapUDPSocketPair + +// {773E5FB9-588A-42CD-A1ED-AA5294E1E0B1} +#define ZAP_UDPSOCKETPAIR_CID \ + { 0x773e5fb9, 0x588a, 0x42cd, { 0xa1, 0xed, 0xaa, 0x52, 0x94, 0xe1, 0xe0, 0xb1 } } + +#define ZAP_UDPSOCKETPAIR_CONTRACTID ZAP_MEDIANODE_CONTRACTID_PREFIX "udp-socket-pair" + +class zapUDPSocketPair : public zapIMediaNode, + public zapIUDPSocketPair +{ +public: + zapUDPSocketPair(); + ~zapUDPSocketPair(); + + NS_DECL_ISUPPORTS + NS_DECL_ZAPIMEDIANODE + NS_DECL_ZAPIUDPSOCKETPAIR + +private: + nsCString mSocketAID; + nsCString mSocketBID; + nsCOMPtr mSocketA; + nsCOMPtr mSocketB; +}; + +#endif // __ZAP_UDPSOCKETPAIR_H__