diff --git a/sflphone-client-gnome/src/config/accountconfigdialog.c b/sflphone-client-gnome/src/config/accountconfigdialog.c index b103db80ba035f6eeb0722de5d6cc28de5871316..b8a21586d211af67e2f5d45addd033d96426ee6a 100644 --- a/sflphone-client-gnome/src/config/accountconfigdialog.c +++ b/sflphone-client-gnome/src/config/accountconfigdialog.c @@ -667,7 +667,6 @@ GtkWidget * create_advanced_tab(account_t **a) local_address = g_hash_table_lookup(currentAccount->properties, LOCAL_ADDRESS); published_address = g_hash_table_lookup(currentAccount->properties, PUBLISHED_ADDRESS); published_port = g_hash_table_lookup(currentAccount->properties, PUBLISHED_PORT); - published_port = g_hash_table_lookup(currentAccount->properties, PUBLISHED_PORT); stun_enable = g_hash_table_lookup(currentAccount->properties, ACCOUNT_SIP_STUN_ENABLED); stun_server = g_hash_table_lookup(currentAccount->properties, ACCOUNT_SIP_STUN_SERVER); } @@ -946,36 +945,13 @@ show_account_window (account_t * a) g_strdup((gchar *)gtk_entry_get_text(GTK_ENTRY(expireSpinBox)))); if (strcmp(proto, "SIP") == 0) { - guint i, size; - account_t * account; - gchar * stun_srv; - gchar * stun_enable; - gboolean flag = FALSE; - - size = account_list_get_size(); - // If a SIP account already exists, fetch its information about STUN - for(i=0; i<size; i++){ - account = account_list_get_nth(i); - if( strcmp(g_hash_table_lookup(account->properties, ACCOUNT_TYPE), "SIP" ) == 0 ) - { - stun_srv = g_hash_table_lookup(account->properties, ACCOUNT_SIP_STUN_SERVER); - stun_enable = g_hash_table_lookup(account->properties, ACCOUNT_SIP_STUN_ENABLED); - g_hash_table_replace(currentAccount->properties, g_strdup(ACCOUNT_SIP_STUN_SERVER), - g_strdup(stun_srv)); - g_hash_table_replace(currentAccount->properties, g_strdup(ACCOUNT_SIP_STUN_ENABLED), - g_strdup(stun_enable)); - flag = TRUE; - break; - } - } - - // Otherwise set a default value - if(!flag) - { - g_hash_table_replace(currentAccount->properties, g_strdup(ACCOUNT_SIP_STUN_SERVER), (gchar*)""); - g_hash_table_replace(currentAccount->properties, g_strdup(ACCOUNT_SIP_STUN_ENABLED), "false"); - } + g_hash_table_replace(currentAccount->properties, g_strdup(ACCOUNT_SIP_STUN_ENABLED), + g_strdup(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(useStunRadioButton)) ? "true":"false")); + + g_hash_table_replace(currentAccount->properties, g_strdup(ACCOUNT_SIP_STUN_SERVER), + g_strdup(gtk_entry_get_text(GTK_ENTRY(stunServerEntry)))); + gchar* keyExchange = (gchar *)gtk_combo_box_get_active_text(GTK_COMBO_BOX(keyExchangeCombo)); if (g_strcasecmp(keyExchange, "ZRTP") == 0) { g_hash_table_replace(currentAccount->properties, g_strdup(ACCOUNT_SRTP_ENABLED), g_strdup("true")); diff --git a/sflphone-client-gnome/src/sflphone_const.h b/sflphone-client-gnome/src/sflphone_const.h index 4997eea888d8dcb5791524ae9e33f5023947b818..09088573eaa5fa0adb0f0e4fe9e6ad0aa6dbd136 100644 --- a/sflphone-client-gnome/src/sflphone_const.h +++ b/sflphone-client-gnome/src/sflphone_const.h @@ -40,6 +40,7 @@ #define c_(COMMENT,STRING) gettext(STRING) #define n_(SING,PLUR,COUNT) ngettext(SING,PLUR,COUNT) + /** Warnings unused variables **/ #define UNUSED_VAR(var) (void*)var diff --git a/sflphone-client-kde/doc/introduction/introduction.html b/sflphone-client-kde/doc/introduction/introduction.html new file mode 100644 index 0000000000000000000000000000000000000000..f923dc5433bc534eb62400867b1a6c95ded7c29f --- /dev/null +++ b/sflphone-client-kde/doc/introduction/introduction.html @@ -0,0 +1,31 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"> +<HTML +><HEAD +><TITLE +>Introduction</TITLE +><META +NAME="GENERATOR" +CONTENT="Modular DocBook HTML Stylesheet Version 1.79"></HEAD +><BODY +CLASS="CHAPTER" +><DIV +CLASS="CHAPTER" +><H1 +><A +NAME="introduction" +></A +>Chapter 1. Introduction</H1 +> + +<P +>This user manual is intended to describe the contents and use of the softphone. + is a KDE client for .It communicates with the core side through DBus. + is meant to be a robust enterprise-class desktop phone. +It provides functions like call transfer, call hold, multiple lines, multiple accounts support. +It is SIP and IAX2 compatible. + audio layer is build upon a native ALSA interface and and a native PulseAudio interface.</P +> + </DIV +></BODY +></HTML +> \ No newline at end of file diff --git a/sflphone-common/libs/pjproject/pjlib-util/include/pjlib-util/config.h b/sflphone-common/libs/pjproject/pjlib-util/include/pjlib-util/config.h index f1e5b1e9937d7317795ef6342d8fed0efea112aa..84259301c0dac413dc4510a52d7398234373866f 100644 --- a/sflphone-common/libs/pjproject/pjlib-util/include/pjlib-util/config.h +++ b/sflphone-common/libs/pjproject/pjlib-util/include/pjlib-util/config.h @@ -1,5 +1,5 @@ /* $Id: config.h 2394 2008-12-23 17:27:53Z bennylp $ */ -/* +/* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org> * @@ -15,7 +15,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __PJLIB_UTIL_CONFIG_H__ #define __PJLIB_UTIL_CONFIG_H__ @@ -59,7 +59,7 @@ * (the #pj_dns_packet_dup() function). * * Generally name compression is desired, since it saves some memory (see - * PJ_DNS_RESOLVER_RES_BUF_SIZE setting). However it comes at the expense of + * PJ_DNS_RESOLVER_RES_BUF_SIZE setting). However it comes at the expense of * a little processing overhead to perform name scanning and also a little * bit more stack usage (8 bytes per entry on 32bit platform). * @@ -84,7 +84,7 @@ /** - * Default retransmission delay, in miliseconds. The combination of + * Default retransmission delay, in miliseconds. The combination of * retransmission delay and count determines the query timeout. * * Default: 2000 (2 seconds, according to RFC 1035) @@ -106,8 +106,8 @@ /** - * Maximum life-time of DNS response in the resolver response cache, - * in seconds. If the value is zero, then DNS response caching will be + * Maximum life-time of DNS response in the resolver response cache, + * in seconds. If the value is zero, then DNS response caching will be * disabled. * * Default is 300 seconds (5 minutes). @@ -120,8 +120,8 @@ /** * The life-time of invalid DNS response in the resolver response cache. - * An invalid DNS response is a response which RCODE is non-zero and - * response without any answer section. These responses can be put in + * An invalid DNS response is a response which RCODE is non-zero and + * response without any answer section. These responses can be put in * the cache too to minimize message round-trip. * * Default: 60 (one minute). @@ -133,7 +133,7 @@ #endif /** - * The interval on which nameservers which are known to be good to be + * The interval on which nameservers which are known to be good to be * probed again to determine whether they are still good. Note that * this applies to both active nameserver (the one currently being used) * and idle nameservers (good nameservers that are not currently selected). diff --git a/sflphone-common/libs/pjproject/pjlib-util/src/pjlib-util/resolver_wrap.cpp b/sflphone-common/libs/pjproject/pjlib-util/src/pjlib-util/resolver_wrap.cpp index aece5356d7ae6cd2f685ba31f776372bfacfead5..19d306e1d0f872325d28a522f86970cce0c7e750 100644 --- a/sflphone-common/libs/pjproject/pjlib-util/src/pjlib-util/resolver_wrap.cpp +++ b/sflphone-common/libs/pjproject/pjlib-util/src/pjlib-util/resolver_wrap.cpp @@ -1,5 +1,5 @@ /* $Id: resolver_wrap.cpp 2873 2009-08-13 11:54:35Z nanang $ */ -/* +/* * Copyright (C) 2009 Teluu Inc. (http://www.teluu.com) * * This program is free software; you can redistribute it and/or modify @@ -14,7 +14,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* diff --git a/sflphone-common/libs/pjproject/pjlib-util/src/pjlib-util/xml_wrap.cpp b/sflphone-common/libs/pjproject/pjlib-util/src/pjlib-util/xml_wrap.cpp index b33e4d3cf145876a10313ff81af241f8e08a08cd..66c9273931b692113d6cc3d48d0283cae24fdd29 100644 --- a/sflphone-common/libs/pjproject/pjlib-util/src/pjlib-util/xml_wrap.cpp +++ b/sflphone-common/libs/pjproject/pjlib-util/src/pjlib-util/xml_wrap.cpp @@ -1,5 +1,5 @@ /* $Id: xml_wrap.cpp 2873 2009-08-13 11:54:35Z nanang $ */ -/* +/* * Copyright (C) 2009 Teluu Inc. (http://www.teluu.com) * * This program is free software; you can redistribute it and/or modify @@ -14,7 +14,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* diff --git a/sflphone-common/libs/pjproject/pjlib/include/pj/config.h b/sflphone-common/libs/pjproject/pjlib/include/pj/config.h index fb951d378cf2d86fd2db1c4a4e6998c891d221a3..aba3fa7070bfbd35d07634196d76276fdfa76ff8 100644 --- a/sflphone-common/libs/pjproject/pjlib/include/pj/config.h +++ b/sflphone-common/libs/pjproject/pjlib/include/pj/config.h @@ -1,5 +1,5 @@ /* $Id: config.h 2843 2009-07-22 11:12:35Z bennylp $ */ -/* +/* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org> * @@ -15,7 +15,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __PJ_CONFIG_H__ #define __PJ_CONFIG_H__ @@ -49,78 +49,78 @@ * Include target OS specific configuration. */ #if defined(PJ_AUTOCONF) - /* - * Autoconf - */ +/* + * Autoconf + */ # include <pj/compat/os_auto.h> #elif defined(PJ_SYMBIAN) && PJ_SYMBIAN!=0 - /* - * SymbianOS - */ +/* + * SymbianOS + */ # include <pj/compat/os_symbian.h> #elif defined(PJ_WIN32_WINCE) || defined(_WIN32_WCE) || defined(UNDER_CE) - /* - * Windows CE - */ +/* + * Windows CE + */ # undef PJ_WIN32_WINCE # define PJ_WIN32_WINCE 1 # include <pj/compat/os_win32_wince.h> - /* Also define Win32 */ +/* Also define Win32 */ # define PJ_WIN32 1 #elif defined(PJ_WIN32) || defined(_WIN32) || defined(__WIN32__) || \ defined(_WIN64) || defined(WIN32) || defined(__TOS_WIN__) - /* - * Win32 - */ +/* + * Win32 + */ # undef PJ_WIN32 # define PJ_WIN32 1 # include <pj/compat/os_win32.h> #elif defined(PJ_LINUX_KERNEL) && PJ_LINUX_KERNEL!=0 - /* - * Linux kernel - */ +/* + * Linux kernel + */ # include <pj/compat/os_linux_kernel.h> #elif defined(PJ_LINUX) || defined(linux) || defined(__linux) - /* - * Linux - */ +/* + * Linux + */ # undef PJ_LINUX # define PJ_LINUX 1 # include <pj/compat/os_linux.h> #elif defined(PJ_PALMOS) && PJ_PALMOS!=0 - /* - * Palm - */ +/* + * Palm + */ # include <pj/compat/os_palmos.h> #elif defined(PJ_SUNOS) || defined(sun) || defined(__sun) - /* - * SunOS - */ +/* + * SunOS + */ # undef PJ_SUNOS # define PJ_SUNOS 1 # include <pj/compat/os_sunos.h> #elif defined(PJ_DARWINOS) || defined(__MACOSX__) || \ defined (__APPLE__) || defined (__MACH__) - /* - * MacOS X - */ +/* + * MacOS X + */ # undef PJ_DARWINOS # define PJ_DARWINOS 1 # include <pj/compat/os_darwinos.h> #elif defined(PJ_RTEMS) && PJ_RTEMS!=0 - /* - * RTEMS - */ +/* + * RTEMS + */ # include <pj/compat/os_rtems.h> #else # error "Please specify target os." @@ -131,17 +131,17 @@ * Target machine specific configuration. */ #if defined(PJ_AUTOCONF) - /* - * Autoconf configured - */ +/* + * Autoconf configured + */ #include <pj/compat/m_auto.h> #elif defined (PJ_M_I386) || defined(_i386_) || defined(i_386_) || \ defined(_X86_) || defined(x86) || defined(__i386__) || \ defined(__i386) || defined(_M_IX86) || defined(__I86__) - /* - * Generic i386 processor family, little-endian - */ +/* + * Generic i386 processor family, little-endian + */ # undef PJ_M_I386 # define PJ_M_I386 1 # define PJ_M_NAME "i386" @@ -152,9 +152,9 @@ #elif defined (PJ_M_X86_64) || defined(__amd64__) || defined(__amd64) || \ defined(__x86_64__) || defined(__x86_64) - /* - * AMD 64bit processor, little endian - */ +/* + * AMD 64bit processor, little endian + */ # undef PJ_M_X86_64 # define PJ_M_X86_64 1 # define PJ_M_NAME "x86_64" @@ -164,9 +164,9 @@ #elif defined(PJ_M_IA64) || defined(__ia64__) || defined(_IA64) || \ defined(__IA64__) || defined( _M_IA64) - /* - * Intel IA64 processor, little endian - */ +/* + * Intel IA64 processor, little endian + */ # undef PJ_M_IA64 # define PJ_M_IA64 1 # define PJ_M_NAME "ia64" @@ -176,9 +176,9 @@ #elif defined (PJ_M_M68K) && PJ_M_M68K != 0 - /* - * Motorola m64k processor, little endian - */ +/* + * Motorola m64k processor, little endian + */ # undef PJ_M_M68K # define PJ_M_M68K 1 # define PJ_M_NAME "m68k" @@ -189,9 +189,9 @@ #elif defined (PJ_M_ALPHA) || defined (__alpha__) || defined (__alpha) || \ defined (_M_ALPHA) - /* - * DEC Alpha processor, little endian - */ +/* + * DEC Alpha processor, little endian + */ # undef PJ_M_ALPHA # define PJ_M_ALPHA 1 # define PJ_M_NAME "alpha" @@ -202,9 +202,9 @@ #elif defined(PJ_M_MIPS) || defined(__mips__) || defined(__mips) || \ defined(__MIPS__) || defined(MIPS) || defined(_MIPS_) - /* - * MIPS, default to little endian - */ +/* + * MIPS, default to little endian + */ # undef PJ_M_MIPS # define PJ_M_MIPS 1 # define PJ_M_NAME "mips" @@ -216,9 +216,9 @@ #elif defined (PJ_M_SPARC) || defined( __sparc__) || defined(__sparc) - /* - * Sun Sparc, big endian - */ +/* + * Sun Sparc, big endian + */ # undef PJ_M_SPARC # define PJ_M_SPARC 1 # define PJ_M_NAME "sparc" @@ -228,9 +228,9 @@ #elif defined (PJ_M_ARMV4) || defined(ARM) || defined(_ARM_) || \ defined(ARMV4) || defined(__arm__) - /* - * ARM, default to little endian - */ +/* + * ARM, default to little endian + */ # undef PJ_M_ARMV4 # define PJ_M_ARMV4 1 # define PJ_M_NAME "armv4" @@ -243,9 +243,9 @@ #elif defined (PJ_M_POWERPC) || defined(__powerpc) || defined(__powerpc__) || \ defined(__POWERPC__) || defined(__ppc__) || defined(_M_PPC) || \ defined(_ARCH_PPC) - /* - * PowerPC, big endian - */ +/* + * PowerPC, big endian + */ # undef PJ_M_POWERPC # define PJ_M_POWERPC 1 # define PJ_M_NAME "powerpc" @@ -255,16 +255,16 @@ #elif defined (PJ_M_NIOS2) || defined(__nios2) || defined(__nios2__) || \ defined(__NIOS2__) || defined(__M_NIOS2) || defined(_ARCH_NIOS2) - /* - * Nios2, little endian - */ +/* + * Nios2, little endian + */ # undef PJ_M_NIOS2 # define PJ_M_NIOS2 1 # define PJ_M_NAME "nios2" # define PJ_HAS_PENTIUM 0 # define PJ_IS_LITTLE_ENDIAN 1 # define PJ_IS_BIG_ENDIAN 0 - + #else # error "Please specify target machine." #endif @@ -420,7 +420,7 @@ * in the application. * * This will slow down pool creation and destruction and will add - * few bytes of overhead, so application would normally want to + * few bytes of overhead, so application would normally want to * disable this feature on release build. * * Default: 0 @@ -449,14 +449,14 @@ * * Default: 8192 */ -#ifndef PJ_THREAD_DEFAULT_STACK_SIZE +#ifndef PJ_THREAD_DEFAULT_STACK_SIZE # define PJ_THREAD_DEFAULT_STACK_SIZE 8192 #endif /** - * Specify if PJ_CHECK_STACK() macro is enabled to check the sanity of - * the stack. The OS implementation may check that no stack overflow + * Specify if PJ_CHECK_STACK() macro is enabled to check the sanity of + * the stack. The OS implementation may check that no stack overflow * occurs, and it also may collect statistic about stack usage. Note * that this will increase the footprint of the libraries since it * tracks the filename and line number of each functions. @@ -486,7 +486,7 @@ #endif /** - * Support IPv6 in the library. If this support is disabled, some IPv6 + * Support IPv6 in the library. If this support is disabled, some IPv6 * related functions will return PJ_EIPV6NOTSUP. * * Default: 0 (disabled, for now) @@ -495,21 +495,21 @@ # define PJ_HAS_IPV6 0 #endif - /** - * Maximum hostname length. - * Libraries sometimes needs to make copy of an address to stack buffer; - * the value here affects the stack usage. - * - * Default: 128 - */ +/** +* Maximum hostname length. +* Libraries sometimes needs to make copy of an address to stack buffer; +* the value here affects the stack usage. +* +* Default: 128 +*/ #ifndef PJ_MAX_HOSTNAME # define PJ_MAX_HOSTNAME (128) #endif /** * Constants for declaring the maximum handles that can be supported by - * a single IOQ framework. This constant might not be relevant to the - * underlying I/O queue impelementation, but still, developers should be + * a single IOQ framework. This constant might not be relevant to the + * underlying I/O queue impelementation, but still, developers should be * aware of this constant, to make sure that the program will not break when * the underlying implementation changes. */ @@ -523,8 +523,8 @@ * things to ensure thread safety of handle unregistration operation by * employing reference counter to each handle. * - * In addition, the ioqueue will preallocate memory for the handles, - * according to the maximum number of handles that is specified during + * In addition, the ioqueue will preallocate memory for the handles, + * according to the maximum number of handles that is specified during * ioqueue creation. * * All applications would normally want this enabled, but you may disable @@ -545,7 +545,7 @@ * concurrently/in parallel. The default is yes, which means that if there * are more than one pending operations complete simultaneously, more * than one threads may call the key's callback at the same time. This - * generally would promote good scalability for application, at the + * generally would promote good scalability for application, at the * expense of more complexity to manage the concurrent accesses. * * Please see the ioqueue documentation for more info. @@ -600,14 +600,14 @@ * set to value lower than FD_SETSIZE. */ #if PJ_FD_SETSIZE_SETABLE - /* Only override FD_SETSIZE if the value has not been set */ +/* Only override FD_SETSIZE if the value has not been set */ # ifndef FD_SETSIZE # define FD_SETSIZE PJ_IOQUEUE_MAX_HANDLES # endif #else - /* When FD_SETSIZE is not changeable, check if PJ_IOQUEUE_MAX_HANDLES - * is lower than FD_SETSIZE value. - */ +/* When FD_SETSIZE is not changeable, check if PJ_IOQUEUE_MAX_HANDLES + * is lower than FD_SETSIZE value. + */ # ifdef FD_SETSIZE # if PJ_IOQUEUE_MAX_HANDLES > FD_SETSIZE # error "PJ_IOQUEUE_MAX_HANDLES is greater than FD_SETSIZE" @@ -724,7 +724,7 @@ #ifndef PJ_NATIVE_ERR_POSITIVE # define PJ_NATIVE_ERR_POSITIVE 1 #endif - + /** * Include error message string in the library (pj_strerror()). * This is very much desirable! @@ -741,7 +741,7 @@ * functions to compare alnum strings. On some systems, they're faster * then stricmp/strcasecmp, but they can be slower on other systems. * When disabled, pjlib will fallback to stricmp/strnicmp. - * + * * Default: 0 */ #ifndef PJ_HAS_STRICMP_ALNUM @@ -761,7 +761,7 @@ * * The libraries support generation of dynamic link libraries for * Symbian ABIv2 target (.dso/Dynamic Shared Object files, in Symbian - * terms). Similar procedures may be applied for Win32 DLL with some + * terms). Similar procedures may be applied for Win32 DLL with some * modification. * * Depending on the platforms, these steps may be necessary in order to @@ -769,7 +769,7 @@ * - Create the (Visual Studio) projects to produce DLL output. PJLIB * does not provide ready to use project files to produce DLL, so * you need to create these projects yourself. For Symbian, the MMP - * files have been setup to produce DSO files for targets that + * files have been setup to produce DSO files for targets that * require them. * - In the (Visual Studio) projects, some macros need to be declared * so that appropriate modifiers are added to symbol declarations @@ -778,49 +778,49 @@ * MMP files. * - Some build systems require .DEF file to be specified when creating * the DLL. For Symbian, .DEF files are included in pjlib distribution, - * in <tt>pjlib/build.symbian</tt> directory. These DEF files are + * in <tt>pjlib/build.symbian</tt> directory. These DEF files are * created by running <tt>./makedef.sh all</tt> from this directory, * inside Mingw. * * Macros related for building DLL/DSO files: * - For platforms that supports dynamic link libraries generation, * it must declare <tt>PJ_EXPORT_SPECIFIER</tt> macro which value contains - * the prefix to be added to symbol definition, to export this + * the prefix to be added to symbol definition, to export this * symbol in the DLL/DSO. For example, on Win32/Visual Studio, the - * value of this macro is \a __declspec(dllexport), and for ARM - * ABIv2/Symbian, the value is \a EXPORT_C. + * value of this macro is \a __declspec(dllexport), and for ARM + * ABIv2/Symbian, the value is \a EXPORT_C. * - For platforms that supports linking with dynamic link libraries, * it must declare <tt>PJ_IMPORT_SPECIFIER</tt> macro which value contains - * the prefix to be added to symbol declaration, to import this + * the prefix to be added to symbol declaration, to import this * symbol from a DLL/DSO. For example, on Win32/Visual Studio, the - * value of this macro is \a __declspec(dllimport), and for ARM - * ABIv2/Symbian, the value is \a IMPORT_C. - * - Both <tt>PJ_EXPORT_SPECIFIER</tt> and <tt>PJ_IMPORT_SPECIFIER</tt> + * value of this macro is \a __declspec(dllimport), and for ARM + * ABIv2/Symbian, the value is \a IMPORT_C. + * - Both <tt>PJ_EXPORT_SPECIFIER</tt> and <tt>PJ_IMPORT_SPECIFIER</tt> * macros above can be declared in your \a config_site.h if they are not * declared by pjlib. - * - When PJLIB is built as DLL/DSO, both <tt>PJ_DLL</tt> and - * <tt>PJ_EXPORTING</tt> macros must be declared, so that + * - When PJLIB is built as DLL/DSO, both <tt>PJ_DLL</tt> and + * <tt>PJ_EXPORTING</tt> macros must be declared, so that * <tt>PJ_EXPORT_SPECIFIER</tt> modifier will be added into function * definition. * - When application wants to link dynamically with PJLIB, then it * must declare <tt>PJ_DLL</tt> macro when using/including PJLIB header, - * so that <tt>PJ_IMPORT_SPECIFIER</tt> modifier is properly added into + * so that <tt>PJ_IMPORT_SPECIFIER</tt> modifier is properly added into * symbol declarations. * * When <b>PJ_DLL</b> macro is not declared, static linking is assumed. * * For example, here are some settings to produce DLLs with Visual Studio * on Windows/Win32: - * - Create Visual Studio projects to produce DLL. Add the appropriate + * - Create Visual Studio projects to produce DLL. Add the appropriate * project dependencies to avoid link errors. - * - In the projects, declare <tt>PJ_DLL</tt> and <tt>PJ_EXPORTING</tt> + * - In the projects, declare <tt>PJ_DLL</tt> and <tt>PJ_EXPORTING</tt> * macros. * - Declare these macros in your <tt>config_site.h</tt>: \verbatim #define PJ_EXPORT_SPECIFIER __declspec(dllexport) #define PJ_IMPORT_SPECIFIER __declspec(dllimport) \endverbatim - * - And in the application (that links with the DLL) project, add + * - And in the application (that links with the DLL) project, add * <tt>PJ_DLL</tt> in the macro declarations. */ @@ -844,7 +844,7 @@ * is built as dynamic library. * * This macro should have been added by platform specific headers, - * if the platform supports building dynamic library target. + * if the platform supports building dynamic library target. */ #ifndef PJ_EXPORT_DECL_SPECIFIER # define PJ_EXPORT_DECL_SPECIFIER @@ -857,7 +857,7 @@ * is built as dynamic library. * * This macro should have been added by platform specific headers, - * if the platform supports building dynamic library target. + * if the platform supports building dynamic library target. */ #ifndef PJ_EXPORT_DEF_SPECIFIER # define PJ_EXPORT_DEF_SPECIFIER @@ -952,7 +952,7 @@ * @def PJ_DECL_DATA(type) * @param type The data type. * Declare a global data. - */ + */ #if defined(PJ_DLL) # if defined(PJ_EXPORTING) # define PJ_DECL_DATA(type) PJ_EXPORT_DECL_SPECIFIER extern type @@ -968,7 +968,7 @@ * @def PJ_DEF_DATA(type) * @param type The data type. * Define a global data. - */ + */ #if defined(PJ_DLL) && defined(PJ_EXPORTING) # define PJ_DEF_DATA(type) PJ_EXPORT_DEF_SPECIFIER type #elif !defined(PJ_DEF_DATA) @@ -1058,19 +1058,19 @@ PJ_BEGIN_DECL /** * PJLIB version string constant. @see pj_get_version() */ -PJ_DECL_DATA(const char*) PJ_VERSION; +PJ_DECL_DATA (const char*) PJ_VERSION; /** * Get PJLIB version string. * * @return #PJ_VERSION constant. */ -PJ_DECL(const char*) pj_get_version(void); +PJ_DECL (const char*) pj_get_version (void); /** * Dump configuration to log with verbosity equal to info(3). */ -PJ_DECL(void) pj_dump_config(void); +PJ_DECL (void) pj_dump_config (void); PJ_END_DECL diff --git a/sflphone-common/libs/pjproject/pjlib/src/pj/addr_resolv_symbian.cpp b/sflphone-common/libs/pjproject/pjlib/src/pj/addr_resolv_symbian.cpp index a0f4453dcef2545167dacd407b60f9560aadf640..98833dbedbc5ce0ae58fed8d41bba59eca827a0a 100644 --- a/sflphone-common/libs/pjproject/pjlib/src/pj/addr_resolv_symbian.cpp +++ b/sflphone-common/libs/pjproject/pjlib/src/pj/addr_resolv_symbian.cpp @@ -1,5 +1,5 @@ /* $Id: addr_resolv_symbian.cpp 2888 2009-08-17 11:29:39Z nanang $ */ -/* +/* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org> * @@ -15,7 +15,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <pj/addr_resolv.h> #include <pj/assert.h> @@ -27,175 +27,199 @@ #include <pj/unicode.h> #include "os_symbian.h" - + #define THIS_FILE "addr_resolv_symbian.cpp" #define TRACE_ME 0 // PJLIB API: resolve hostname -PJ_DEF(pj_status_t) pj_gethostbyname(const pj_str_t *name, pj_hostent *he) +PJ_DEF (pj_status_t) pj_gethostbyname (const pj_str_t *name, pj_hostent *he) { static pj_addrinfo ai; static char *aliases[2]; static char *addrlist[2]; unsigned count = 1; pj_status_t status; - - status = pj_getaddrinfo(PJ_AF_INET, name, &count, &ai); + + status = pj_getaddrinfo (PJ_AF_INET, name, &count, &ai); + if (status != PJ_SUCCESS) - return status; - + return status; + aliases[0] = ai.ai_canonname; + aliases[1] = NULL; - + addrlist[0] = (char*) &ai.ai_addr.ipv4.sin_addr; + addrlist[1] = NULL; - - pj_bzero(he, sizeof(*he)); + + pj_bzero (he, sizeof (*he)); + he->h_name = aliases[0]; + he->h_aliases = aliases; + he->h_addrtype = PJ_AF_INET; + he->h_length = 4; + he->h_addr_list = addrlist; - + return PJ_SUCCESS; } // Resolve for specific address family -static pj_status_t getaddrinfo_by_af(int af, const pj_str_t *name, - unsigned *count, pj_addrinfo ai[]) +static pj_status_t getaddrinfo_by_af (int af, const pj_str_t *name, + unsigned *count, pj_addrinfo ai[]) { unsigned i; pj_status_t status; - - PJ_ASSERT_RETURN(name && count && ai, PJ_EINVAL); + + PJ_ASSERT_RETURN (name && count && ai, PJ_EINVAL); #if !defined(PJ_HAS_IPV6) || !PJ_HAS_IPV6 + if (af == PJ_AF_INET6) - return PJ_EIPV6NOTSUP; + return PJ_EIPV6NOTSUP; + #endif - + // Return failure if access point is marked as down by app. PJ_SYMBIAN_CHECK_CONNECTION(); // Get resolver for the specified address family - RHostResolver &resv = PjSymbianOS::Instance()->GetResolver(af); + RHostResolver &resv = PjSymbianOS::Instance()->GetResolver (af); // Convert name to Unicode wchar_t name16[PJ_MAX_HOSTNAME]; - pj_ansi_to_unicode(name->ptr, name->slen, name16, PJ_ARRAY_SIZE(name16)); - TPtrC16 data((const TUint16*)name16); + + pj_ansi_to_unicode (name->ptr, name->slen, name16, PJ_ARRAY_SIZE (name16)); + + TPtrC16 data ( (const TUint16*) name16); // Resolve! TNameEntry nameEntry; + TRequestStatus reqStatus; - - resv.GetByName(data, nameEntry, reqStatus); - User::WaitForRequest(reqStatus); - + + resv.GetByName (data, nameEntry, reqStatus); + + User::WaitForRequest (reqStatus); + // Iterate each result i = 0; + while (reqStatus == KErrNone && i < *count) { - - // Get the resolved TInetAddr - TInetAddr inetAddr(nameEntry().iAddr); - int addrlen; + + // Get the resolved TInetAddr + TInetAddr inetAddr (nameEntry().iAddr); + int addrlen; #if TRACE_ME - if (1) { - pj_sockaddr a; - char ipaddr[PJ_INET6_ADDRSTRLEN+2]; - int namelen; - - namelen = sizeof(pj_sockaddr); - if (PjSymbianOS::Addr2pj(inetAddr, a, &namelen, - PJ_FALSE) == PJ_SUCCESS) - { - PJ_LOG(5,(THIS_FILE, "resolve %.*s: %s", - (int)name->slen, name->ptr, - pj_sockaddr_print(&a, ipaddr, sizeof(ipaddr), 2))); - } - } + + if (1) { + pj_sockaddr a; + char ipaddr[PJ_INET6_ADDRSTRLEN+2]; + int namelen; + + namelen = sizeof (pj_sockaddr); + + if (PjSymbianOS::Addr2pj (inetAddr, a, &namelen, + PJ_FALSE) == PJ_SUCCESS) { + PJ_LOG (5, (THIS_FILE, "resolve %.*s: %s", + (int) name->slen, name->ptr, + pj_sockaddr_print (&a, ipaddr, sizeof (ipaddr), 2))); + } + } + #endif - - // Ignore if this is not the same address family - // Not a good idea, as Symbian mapps IPv4 to IPv6. - //fam = inetAddr.Family(); - //if (fam != af) { - // resv.Next(nameEntry, reqStatus); - // User::WaitForRequest(reqStatus); - // continue; - //} - - // Convert IP address first to get IPv4 mapped address - addrlen = sizeof(ai[i].ai_addr); - status = PjSymbianOS::Addr2pj(inetAddr, ai[i].ai_addr, - &addrlen, PJ_TRUE); - if (status != PJ_SUCCESS) - return status; - - // Ignore if address family doesn't match - if (ai[i].ai_addr.addr.sa_family != af) { - resv.Next(nameEntry, reqStatus); - User::WaitForRequest(reqStatus); - continue; - } - - // Convert the official address to ANSI. - pj_unicode_to_ansi((const wchar_t*)nameEntry().iName.Ptr(), - nameEntry().iName.Length(), - ai[i].ai_canonname, sizeof(ai[i].ai_canonname)); - - // Next - ++i; - resv.Next(nameEntry, reqStatus); - User::WaitForRequest(reqStatus); + + // Ignore if this is not the same address family + // Not a good idea, as Symbian mapps IPv4 to IPv6. + //fam = inetAddr.Family(); + //if (fam != af) { + // resv.Next(nameEntry, reqStatus); + // User::WaitForRequest(reqStatus); + // continue; + //} + + // Convert IP address first to get IPv4 mapped address + addrlen = sizeof (ai[i].ai_addr); + + status = PjSymbianOS::Addr2pj (inetAddr, ai[i].ai_addr, + &addrlen, PJ_TRUE); + + if (status != PJ_SUCCESS) + return status; + + // Ignore if address family doesn't match + if (ai[i].ai_addr.addr.sa_family != af) { + resv.Next (nameEntry, reqStatus); + User::WaitForRequest (reqStatus); + continue; + } + + // Convert the official address to ANSI. + pj_unicode_to_ansi ( (const wchar_t*) nameEntry().iName.Ptr(), + nameEntry().iName.Length(), + ai[i].ai_canonname, sizeof (ai[i].ai_canonname)); + + // Next + ++i; + + resv.Next (nameEntry, reqStatus); + + User::WaitForRequest (reqStatus); } *count = i; + return PJ_SUCCESS; } /* Resolve IPv4/IPv6 address */ -PJ_DEF(pj_status_t) pj_getaddrinfo(int af, const pj_str_t *nodename, - unsigned *count, pj_addrinfo ai[]) +PJ_DEF (pj_status_t) pj_getaddrinfo (int af, const pj_str_t *nodename, + unsigned *count, pj_addrinfo ai[]) { unsigned start; pj_status_t status = PJ_EAFNOTSUP; - - PJ_ASSERT_RETURN(af==PJ_AF_INET || af==PJ_AF_INET6 || af==PJ_AF_UNSPEC, - PJ_EAFNOTSUP); - PJ_ASSERT_RETURN(nodename && count && *count && ai, PJ_EINVAL); - + + PJ_ASSERT_RETURN (af==PJ_AF_INET || af==PJ_AF_INET6 || af==PJ_AF_UNSPEC, + PJ_EAFNOTSUP); + PJ_ASSERT_RETURN (nodename && count && *count && ai, PJ_EINVAL); + start = 0; - + if (af==PJ_AF_INET6 || af==PJ_AF_UNSPEC) { unsigned max = *count; - status = getaddrinfo_by_af(PJ_AF_INET6, nodename, - &max, &ai[start]); - if (status == PJ_SUCCESS) { - (*count) -= max; - start += max; - } + status = getaddrinfo_by_af (PJ_AF_INET6, nodename, + &max, &ai[start]); + + if (status == PJ_SUCCESS) { + (*count) -= max; + start += max; + } } - + if (af==PJ_AF_INET || af==PJ_AF_UNSPEC) { unsigned max = *count; - status = getaddrinfo_by_af(PJ_AF_INET, nodename, - &max, &ai[start]); - if (status == PJ_SUCCESS) { - (*count) -= max; - start += max; - } + status = getaddrinfo_by_af (PJ_AF_INET, nodename, + &max, &ai[start]); + + if (status == PJ_SUCCESS) { + (*count) -= max; + start += max; + } } - + *count = start; - + if (*count) { - return PJ_SUCCESS; + return PJ_SUCCESS; } else { - return status!=PJ_SUCCESS ? status : PJ_ENOTFOUND; + return status!=PJ_SUCCESS ? status : PJ_ENOTFOUND; } } diff --git a/sflphone-common/libs/pjproject/pjlib/src/pj/exception_symbian.cpp b/sflphone-common/libs/pjproject/pjlib/src/pj/exception_symbian.cpp index e54cebddf940cd73896ee81e1f59afad48d16d74..14ded02ed9c7f93154068aef65904015728dc4b1 100644 --- a/sflphone-common/libs/pjproject/pjlib/src/pj/exception_symbian.cpp +++ b/sflphone-common/libs/pjproject/pjlib/src/pj/exception_symbian.cpp @@ -1,5 +1,5 @@ /* $Id: exception_symbian.cpp 2394 2008-12-23 17:27:53Z bennylp $ */ -/* +/* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org> * @@ -15,7 +15,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <pj/except.h> #include <pj/os.h> @@ -25,19 +25,19 @@ #if defined(PJ_HAS_EXCEPTION_NAMES) && PJ_HAS_EXCEPTION_NAMES != 0 - static const char *exception_id_names[PJ_MAX_EXCEPTION_ID]; +static const char *exception_id_names[PJ_MAX_EXCEPTION_ID]; #else - /* - * Start from 1 (not 0)!!! - * Exception 0 is reserved for normal path of setjmp()!!! - */ - static int last_exception_id = 1; +/* + * Start from 1 (not 0)!!! + * Exception 0 is reserved for normal path of setjmp()!!! + */ +static int last_exception_id = 1; #endif /* PJ_HAS_EXCEPTION_NAMES */ #if defined(PJ_HAS_EXCEPTION_NAMES) && PJ_HAS_EXCEPTION_NAMES != 0 -PJ_DEF(pj_status_t) pj_exception_id_alloc( const char *name, - pj_exception_id_t *id) +PJ_DEF (pj_status_t) pj_exception_id_alloc (const char *name, + pj_exception_id_t *id) { unsigned i; @@ -47,6 +47,7 @@ PJ_DEF(pj_status_t) pj_exception_id_alloc( const char *name, * Start from 1 (not 0)!!! * Exception 0 is reserved for normal path of setjmp()!!! */ + for (i=1; i<PJ_MAX_EXCEPTION_ID; ++i) { if (exception_id_names[i] == NULL) { exception_id_names[i] = name; @@ -57,17 +58,18 @@ PJ_DEF(pj_status_t) pj_exception_id_alloc( const char *name, } pj_leave_critical_section(); + return PJ_ETOOMANY; } -PJ_DEF(pj_status_t) pj_exception_id_free( pj_exception_id_t id ) +PJ_DEF (pj_status_t) pj_exception_id_free (pj_exception_id_t id) { /* * Start from 1 (not 0)!!! * Exception 0 is reserved for normal path of setjmp()!!! */ - PJ_ASSERT_RETURN(id>0 && id<PJ_MAX_EXCEPTION_ID, PJ_EINVAL); - + PJ_ASSERT_RETURN (id>0 && id<PJ_MAX_EXCEPTION_ID, PJ_EINVAL); + pj_enter_critical_section(); exception_id_names[id] = NULL; pj_leave_critical_section(); @@ -76,13 +78,13 @@ PJ_DEF(pj_status_t) pj_exception_id_free( pj_exception_id_t id ) } -PJ_DEF(const char*) pj_exception_id_name(pj_exception_id_t id) +PJ_DEF (const char*) pj_exception_id_name (pj_exception_id_t id) { /* * Start from 1 (not 0)!!! * Exception 0 is reserved for normal path of setjmp()!!! */ - PJ_ASSERT_RETURN(id>0 && id<PJ_MAX_EXCEPTION_ID, "<Invalid ID>"); + PJ_ASSERT_RETURN (id>0 && id<PJ_MAX_EXCEPTION_ID, "<Invalid ID>"); if (exception_id_names[id] == NULL) return "<Unallocated ID>"; @@ -91,21 +93,21 @@ PJ_DEF(const char*) pj_exception_id_name(pj_exception_id_t id) } #else /* PJ_HAS_EXCEPTION_NAMES */ -PJ_DEF(pj_status_t) pj_exception_id_alloc( const char *name, - pj_exception_id_t *id) +PJ_DEF (pj_status_t) pj_exception_id_alloc (const char *name, + pj_exception_id_t *id) { - PJ_ASSERT_RETURN(last_exception_id < PJ_MAX_EXCEPTION_ID-1, PJ_ETOOMANY); + PJ_ASSERT_RETURN (last_exception_id < PJ_MAX_EXCEPTION_ID-1, PJ_ETOOMANY); *id = last_exception_id++; return PJ_SUCCESS; } -PJ_DEF(pj_status_t) pj_exception_id_free( pj_exception_id_t id ) +PJ_DEF (pj_status_t) pj_exception_id_free (pj_exception_id_t id) { return PJ_SUCCESS; } -PJ_DEF(const char*) pj_exception_id_name(pj_exception_id_t id) +PJ_DEF (const char*) pj_exception_id_name (pj_exception_id_t id) { return ""; } diff --git a/sflphone-common/libs/pjproject/pjlib/src/pj/ioqueue_symbian.cpp b/sflphone-common/libs/pjproject/pjlib/src/pj/ioqueue_symbian.cpp index c436d4c45836f7c21e5b7bd6930eba005942d01d..4acbd9619b6c0e66565af39076dfe987b65090a3 100644 --- a/sflphone-common/libs/pjproject/pjlib/src/pj/ioqueue_symbian.cpp +++ b/sflphone-common/libs/pjproject/pjlib/src/pj/ioqueue_symbian.cpp @@ -1,5 +1,5 @@ /* $Id: ioqueue_symbian.cpp 2771 2009-06-17 13:31:13Z bennylp $ */ -/* +/* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org> * @@ -15,7 +15,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <pj/ioqueue.h> #include <pj/assert.h> @@ -32,8 +32,8 @@ class CIoqueueCallback; /* * IO Queue structure. */ -struct pj_ioqueue_t -{ + +struct pj_ioqueue_t { int eventCount; }; @@ -41,148 +41,144 @@ struct pj_ioqueue_t ///////////////////////////////////////////////////////////////////////////// // Class to encapsulate asynchronous socket operation. // + class CIoqueueCallback : public CActive { -public: - static CIoqueueCallback* NewL(pj_ioqueue_t *ioqueue, - pj_ioqueue_key_t *key, - pj_sock_t sock, - const pj_ioqueue_callback *cb, - void *user_data); - - // - // Start asynchronous recv() operation - // - pj_status_t StartRead(pj_ioqueue_op_key_t *op_key, - void *buf, pj_ssize_t *size, unsigned flags, - pj_sockaddr_t *addr, int *addrlen); - - // - // Start asynchronous accept() operation. - // - pj_status_t StartAccept(pj_ioqueue_op_key_t *op_key, - pj_sock_t *new_sock, - pj_sockaddr_t *local, - pj_sockaddr_t *remote, - int *addrlen ); - - // - // Completion callback. - // - void RunL(); - - // - // CActive's DoCancel() - // - void DoCancel(); - - // - // Cancel operation and call callback. - // - void CancelOperation(pj_ioqueue_op_key_t *op_key, - pj_ssize_t bytes_status); - - // - // Accessors - // - void* get_user_data() const - { - return user_data_; - } - void set_user_data(void *user_data) - { - user_data_ = user_data; - } - pj_ioqueue_op_key_t *get_op_key() const - { - return pending_data_.common_.op_key_; - } - CPjSocket* get_pj_socket() - { - return sock_; - } - -private: - // Type of pending operation. - enum Type { - TYPE_NONE, - TYPE_READ, - TYPE_ACCEPT, - }; - - // Static data. - pj_ioqueue_t *ioqueue_; - pj_ioqueue_key_t *key_; - CPjSocket *sock_; - pj_ioqueue_callback cb_; - void *user_data_; - - // Symbian data. - TPtr8 aBufferPtr_; - TInetAddr aAddress_; - - // Application data. - Type type_; - - union Pending_Data - { - struct Common - { - pj_ioqueue_op_key_t *op_key_; - } common_; - - struct Pending_Read - { - pj_ioqueue_op_key_t *op_key_; - pj_sockaddr_t *addr_; - int *addrlen_; - } read_; - - struct Pending_Accept - { - pj_ioqueue_op_key_t *op_key_; - pj_sock_t *new_sock_; - pj_sockaddr_t *local_; - pj_sockaddr_t *remote_; - int *addrlen_; - } accept_; - }; - - union Pending_Data pending_data_; - RSocket blank_sock_; - - CIoqueueCallback(pj_ioqueue_t *ioqueue, - pj_ioqueue_key_t *key, pj_sock_t sock, - const pj_ioqueue_callback *cb, void *user_data) - : CActive(CActive::EPriorityStandard), - ioqueue_(ioqueue), key_(key), sock_((CPjSocket*)sock), - user_data_(user_data), aBufferPtr_(NULL, 0), type_(TYPE_NONE) - { - pj_memcpy(&cb_, cb, sizeof(*cb)); - } - - void ConstructL() - { - CActiveScheduler::Add(this); - } - - void HandleReadCompletion(); - CPjSocket *HandleAcceptCompletion(); + public: + static CIoqueueCallback* NewL (pj_ioqueue_t *ioqueue, + pj_ioqueue_key_t *key, + pj_sock_t sock, + const pj_ioqueue_callback *cb, + void *user_data); + + // + // Start asynchronous recv() operation + // + pj_status_t StartRead (pj_ioqueue_op_key_t *op_key, + void *buf, pj_ssize_t *size, unsigned flags, + pj_sockaddr_t *addr, int *addrlen); + + // + // Start asynchronous accept() operation. + // + pj_status_t StartAccept (pj_ioqueue_op_key_t *op_key, + pj_sock_t *new_sock, + pj_sockaddr_t *local, + pj_sockaddr_t *remote, + int *addrlen); + + // + // Completion callback. + // + void RunL(); + + // + // CActive's DoCancel() + // + void DoCancel(); + + // + // Cancel operation and call callback. + // + void CancelOperation (pj_ioqueue_op_key_t *op_key, + pj_ssize_t bytes_status); + + // + // Accessors + // + void* get_user_data() const { + return user_data_; + } + + void set_user_data (void *user_data) { + user_data_ = user_data; + } + + pj_ioqueue_op_key_t *get_op_key() const { + return pending_data_.common_.op_key_; + } + + CPjSocket* get_pj_socket() { + return sock_; + } + + private: + // Type of pending operation. + enum Type { + TYPE_NONE, + TYPE_READ, + TYPE_ACCEPT, + }; + + // Static data. + pj_ioqueue_t *ioqueue_; + pj_ioqueue_key_t *key_; + CPjSocket *sock_; + pj_ioqueue_callback cb_; + void *user_data_; + + // Symbian data. + TPtr8 aBufferPtr_; + TInetAddr aAddress_; + + // Application data. + Type type_; + + union Pending_Data { + + struct Common { + pj_ioqueue_op_key_t *op_key_; + } common_; + + struct Pending_Read { + pj_ioqueue_op_key_t *op_key_; + pj_sockaddr_t *addr_; + int *addrlen_; + } read_; + + struct Pending_Accept { + pj_ioqueue_op_key_t *op_key_; + pj_sock_t *new_sock_; + pj_sockaddr_t *local_; + pj_sockaddr_t *remote_; + int *addrlen_; + } accept_; + }; + + union Pending_Data pending_data_; + RSocket blank_sock_; + + CIoqueueCallback (pj_ioqueue_t *ioqueue, + pj_ioqueue_key_t *key, pj_sock_t sock, + const pj_ioqueue_callback *cb, void *user_data) + : CActive (CActive::EPriorityStandard), + ioqueue_ (ioqueue), key_ (key), sock_ ( (CPjSocket*) sock), + user_data_ (user_data), aBufferPtr_ (NULL, 0), type_ (TYPE_NONE) { + pj_memcpy (&cb_, cb, sizeof (*cb)); + } + + + void ConstructL() { + CActiveScheduler::Add (this); + } + + void HandleReadCompletion(); + CPjSocket *HandleAcceptCompletion(); }; -CIoqueueCallback* CIoqueueCallback::NewL(pj_ioqueue_t *ioqueue, - pj_ioqueue_key_t *key, - pj_sock_t sock, - const pj_ioqueue_callback *cb, - void *user_data) +CIoqueueCallback* CIoqueueCallback::NewL (pj_ioqueue_t *ioqueue, + pj_ioqueue_key_t *key, + pj_sock_t sock, + const pj_ioqueue_callback *cb, + void *user_data) { - CIoqueueCallback *self = new CIoqueueCallback(ioqueue, key, sock, - cb, user_data); - CleanupStack::PushL(self); + CIoqueueCallback *self = new CIoqueueCallback (ioqueue, key, sock, + cb, user_data); + CleanupStack::PushL (self); self->ConstructL(); - CleanupStack::Pop(self); + CleanupStack::Pop (self); return self; } @@ -191,13 +187,13 @@ CIoqueueCallback* CIoqueueCallback::NewL(pj_ioqueue_t *ioqueue, // // Start asynchronous recv() operation // -pj_status_t CIoqueueCallback::StartRead(pj_ioqueue_op_key_t *op_key, - void *buf, pj_ssize_t *size, - unsigned flags, - pj_sockaddr_t *addr, int *addrlen) +pj_status_t CIoqueueCallback::StartRead (pj_ioqueue_op_key_t *op_key, + void *buf, pj_ssize_t *size, + unsigned flags, + pj_sockaddr_t *addr, int *addrlen) { - PJ_ASSERT_RETURN(IsActive()==false, PJ_EBUSY); - PJ_ASSERT_RETURN(pending_data_.common_.op_key_==NULL, PJ_EBUSY); + PJ_ASSERT_RETURN (IsActive() ==false, PJ_EBUSY); + PJ_ASSERT_RETURN (pending_data_.common_.op_key_==NULL, PJ_EBUSY); flags &= ~PJ_IOQUEUE_ALWAYS_ASYNC; @@ -205,27 +201,29 @@ pj_status_t CIoqueueCallback::StartRead(pj_ioqueue_op_key_t *op_key, pending_data_.read_.addr_ = addr; pending_data_.read_.addrlen_ = addrlen; - aBufferPtr_.Set((TUint8*)buf, 0, (TInt)*size); + aBufferPtr_.Set ( (TUint8*) buf, 0, (TInt) *size); type_ = TYPE_READ; + if (addr && addrlen) { - sock_->Socket().RecvFrom(aBufferPtr_, aAddress_, flags, iStatus); + sock_->Socket().RecvFrom (aBufferPtr_, aAddress_, flags, iStatus); } else { - aAddress_.SetAddress(0); - aAddress_.SetPort(0); - - if (sock_->IsDatagram()) { - sock_->Socket().Recv(aBufferPtr_, flags, iStatus); - } else { - // Using static like this is not pretty, but we don't need to use - // the value anyway, hence doing it like this is probably most - // optimal. - static TSockXfrLength len; - sock_->Socket().RecvOneOrMore(aBufferPtr_, flags, iStatus, len); - } + aAddress_.SetAddress (0); + aAddress_.SetPort (0); + + if (sock_->IsDatagram()) { + sock_->Socket().Recv (aBufferPtr_, flags, iStatus); + } else { + // Using static like this is not pretty, but we don't need to use + // the value anyway, hence doing it like this is probably most + // optimal. + static TSockXfrLength len; + sock_->Socket().RecvOneOrMore (aBufferPtr_, flags, iStatus, len); + } } SetActive(); + return PJ_EPENDING; } @@ -233,19 +231,19 @@ pj_status_t CIoqueueCallback::StartRead(pj_ioqueue_op_key_t *op_key, // // Start asynchronous accept() operation. // -pj_status_t CIoqueueCallback::StartAccept(pj_ioqueue_op_key_t *op_key, - pj_sock_t *new_sock, - pj_sockaddr_t *local, - pj_sockaddr_t *remote, - int *addrlen ) +pj_status_t CIoqueueCallback::StartAccept (pj_ioqueue_op_key_t *op_key, + pj_sock_t *new_sock, + pj_sockaddr_t *local, + pj_sockaddr_t *remote, + int *addrlen) { - PJ_ASSERT_RETURN(IsActive()==false, PJ_EBUSY); - PJ_ASSERT_RETURN(pending_data_.common_.op_key_==NULL, PJ_EBUSY); + PJ_ASSERT_RETURN (IsActive() ==false, PJ_EBUSY); + PJ_ASSERT_RETURN (pending_data_.common_.op_key_==NULL, PJ_EBUSY); // addrlen must be specified if local or remote is specified - PJ_ASSERT_RETURN((!local && !remote) || - (addrlen && *addrlen), PJ_EINVAL); - + PJ_ASSERT_RETURN ( (!local && !remote) || + (addrlen && *addrlen), PJ_EINVAL); + pending_data_.accept_.op_key_ = op_key; pending_data_.accept_.new_sock_ = new_sock; pending_data_.accept_.local_ = local; @@ -253,10 +251,10 @@ pj_status_t CIoqueueCallback::StartAccept(pj_ioqueue_op_key_t *op_key, pending_data_.accept_.addrlen_ = addrlen; // Create blank socket - blank_sock_.Open(PjSymbianOS::Instance()->SocketServ()); + blank_sock_.Open (PjSymbianOS::Instance()->SocketServ()); type_ = TYPE_ACCEPT; - sock_->Socket().Accept(blank_sock_, iStatus); + sock_->Socket().Accept (blank_sock_, iStatus); SetActive(); return PJ_EPENDING; @@ -266,16 +264,16 @@ pj_status_t CIoqueueCallback::StartAccept(pj_ioqueue_op_key_t *op_key, // // Handle asynchronous RecvFrom() completion // -void CIoqueueCallback::HandleReadCompletion() +void CIoqueueCallback::HandleReadCompletion() { if (pending_data_.read_.addr_ && pending_data_.read_.addrlen_) { - PjSymbianOS::Addr2pj(aAddress_, - *(pj_sockaddr*)pending_data_.read_.addr_, - pending_data_.read_.addrlen_); - pending_data_.read_.addr_ = NULL; - pending_data_.read_.addrlen_ = NULL; + PjSymbianOS::Addr2pj (aAddress_, + * (pj_sockaddr*) pending_data_.read_.addr_, + pending_data_.read_.addrlen_); + pending_data_.read_.addr_ = NULL; + pending_data_.read_.addrlen_ = NULL; } - + pending_data_.read_.op_key_ = NULL; } @@ -283,55 +281,57 @@ void CIoqueueCallback::HandleReadCompletion() // // Handle asynchronous Accept() completion. // -CPjSocket *CIoqueueCallback::HandleAcceptCompletion() +CPjSocket *CIoqueueCallback::HandleAcceptCompletion() { - CPjSocket *pjNewSock = new CPjSocket(get_pj_socket()->GetAf(), - get_pj_socket()->GetSockType(), - blank_sock_); - int addrlen = 0; - - if (pending_data_.accept_.new_sock_) { - *pending_data_.accept_.new_sock_ = (pj_sock_t)pjNewSock; - pending_data_.accept_.new_sock_ = NULL; - } - - if (pending_data_.accept_.local_) { - TInetAddr aAddr; - pj_sockaddr *ptr_sockaddr; - - blank_sock_.LocalName(aAddr); - ptr_sockaddr = (pj_sockaddr*)pending_data_.accept_.local_; - addrlen = *pending_data_.accept_.addrlen_; - PjSymbianOS::Addr2pj(aAddr, *ptr_sockaddr, &addrlen); - pending_data_.accept_.local_ = NULL; - } - - if (pending_data_.accept_.remote_) { - TInetAddr aAddr; - pj_sockaddr *ptr_sockaddr; - - blank_sock_.RemoteName(aAddr); - ptr_sockaddr = (pj_sockaddr*)pending_data_.accept_.remote_; - addrlen = *pending_data_.accept_.addrlen_; - PjSymbianOS::Addr2pj(aAddr, *ptr_sockaddr, &addrlen); - pending_data_.accept_.remote_ = NULL; - } - - if (pending_data_.accept_.addrlen_) { - if (addrlen == 0) { - if (pjNewSock->GetAf() == PJ_AF_INET) - addrlen = sizeof(pj_sockaddr_in); - else if (pjNewSock->GetAf() == PJ_AF_INET6) - addrlen = sizeof(pj_sockaddr_in6); - else { - pj_assert(!"Unsupported address family"); - } - } - *pending_data_.accept_.addrlen_ = addrlen; - pending_data_.accept_.addrlen_ = NULL; - } - - return pjNewSock; + CPjSocket *pjNewSock = new CPjSocket (get_pj_socket()->GetAf(), + get_pj_socket()->GetSockType(), + blank_sock_); + int addrlen = 0; + + if (pending_data_.accept_.new_sock_) { + *pending_data_.accept_.new_sock_ = (pj_sock_t) pjNewSock; + pending_data_.accept_.new_sock_ = NULL; + } + + if (pending_data_.accept_.local_) { + TInetAddr aAddr; + pj_sockaddr *ptr_sockaddr; + + blank_sock_.LocalName (aAddr); + ptr_sockaddr = (pj_sockaddr*) pending_data_.accept_.local_; + addrlen = *pending_data_.accept_.addrlen_; + PjSymbianOS::Addr2pj (aAddr, *ptr_sockaddr, &addrlen); + pending_data_.accept_.local_ = NULL; + } + + if (pending_data_.accept_.remote_) { + TInetAddr aAddr; + pj_sockaddr *ptr_sockaddr; + + blank_sock_.RemoteName (aAddr); + ptr_sockaddr = (pj_sockaddr*) pending_data_.accept_.remote_; + addrlen = *pending_data_.accept_.addrlen_; + PjSymbianOS::Addr2pj (aAddr, *ptr_sockaddr, &addrlen); + pending_data_.accept_.remote_ = NULL; + } + + if (pending_data_.accept_.addrlen_) { + if (addrlen == 0) { + if (pjNewSock->GetAf() == PJ_AF_INET) + addrlen = sizeof (pj_sockaddr_in); + else if (pjNewSock->GetAf() == PJ_AF_INET6) + addrlen = sizeof (pj_sockaddr_in6); + else { + pj_assert (!"Unsupported address family"); + } + } + + *pending_data_.accept_.addrlen_ = addrlen; + + pending_data_.accept_.addrlen_ = NULL; + } + + return pjNewSock; } @@ -345,58 +345,64 @@ void CIoqueueCallback::RunL() type_ = TYPE_NONE; if (cur_type == TYPE_READ) { - // - // Completion of asynchronous RecvFrom() - // - - /* Clear op_key (save it to temp variable first!) */ - pj_ioqueue_op_key_t *op_key = pending_data_.read_.op_key_; - pending_data_.read_.op_key_ = NULL; - - // Handle failure condition - if (iStatus != KErrNone) { - if (cb_.on_read_complete) { - cb_.on_read_complete( key_, op_key, - -PJ_RETURN_OS_ERROR(iStatus.Int())); - } - return; - } - - HandleReadCompletion(); - - /* Call callback */ - if (cb_.on_read_complete) { - cb_.on_read_complete(key_, op_key, aBufferPtr_.Length()); - } + // + // Completion of asynchronous RecvFrom() + // + + /* Clear op_key (save it to temp variable first!) */ + pj_ioqueue_op_key_t *op_key = pending_data_.read_.op_key_; + pending_data_.read_.op_key_ = NULL; + + // Handle failure condition + + if (iStatus != KErrNone) { + if (cb_.on_read_complete) { + cb_.on_read_complete (key_, op_key, + -PJ_RETURN_OS_ERROR (iStatus.Int())); + } + + return; + } + + HandleReadCompletion(); + + /* Call callback */ + + if (cb_.on_read_complete) { + cb_.on_read_complete (key_, op_key, aBufferPtr_.Length()); + } } else if (cur_type == TYPE_ACCEPT) { - // - // Completion of asynchronous Accept() - // - - /* Clear op_key (save it to temp variable first!) */ - pj_ioqueue_op_key_t *op_key = pending_data_.read_.op_key_; - pending_data_.read_.op_key_ = NULL; - - // Handle failure condition - if (iStatus != KErrNone) { - if (pending_data_.accept_.new_sock_) - *pending_data_.accept_.new_sock_ = PJ_INVALID_SOCKET; - - if (cb_.on_accept_complete) { - cb_.on_accept_complete( key_, op_key, PJ_INVALID_SOCKET, - -PJ_RETURN_OS_ERROR(iStatus.Int())); - } - return; - } - - CPjSocket *pjNewSock = HandleAcceptCompletion(); - - // Call callback. - if (cb_.on_accept_complete) { - cb_.on_accept_complete( key_, op_key, (pj_sock_t)pjNewSock, - PJ_SUCCESS); - } + // + // Completion of asynchronous Accept() + // + + /* Clear op_key (save it to temp variable first!) */ + pj_ioqueue_op_key_t *op_key = pending_data_.read_.op_key_; + pending_data_.read_.op_key_ = NULL; + + // Handle failure condition + + if (iStatus != KErrNone) { + if (pending_data_.accept_.new_sock_) + *pending_data_.accept_.new_sock_ = PJ_INVALID_SOCKET; + + if (cb_.on_accept_complete) { + cb_.on_accept_complete (key_, op_key, PJ_INVALID_SOCKET, + -PJ_RETURN_OS_ERROR (iStatus.Int())); + } + + return; + } + + CPjSocket *pjNewSock = HandleAcceptCompletion(); + + // Call callback. + + if (cb_.on_accept_complete) { + cb_.on_accept_complete (key_, op_key, (pj_sock_t) pjNewSock, + PJ_SUCCESS); + } } ioqueue_->eventCount++; @@ -408,31 +414,32 @@ void CIoqueueCallback::RunL() void CIoqueueCallback::DoCancel() { if (type_ == TYPE_READ) - sock_->Socket().CancelRecv(); + sock_->Socket().CancelRecv(); else if (type_ == TYPE_ACCEPT) - sock_->Socket().CancelAccept(); + sock_->Socket().CancelAccept(); type_ = TYPE_NONE; + pending_data_.common_.op_key_ = NULL; } // // Cancel operation and call callback. // -void CIoqueueCallback::CancelOperation(pj_ioqueue_op_key_t *op_key, - pj_ssize_t bytes_status) +void CIoqueueCallback::CancelOperation (pj_ioqueue_op_key_t *op_key, + pj_ssize_t bytes_status) { Type cur_type = type_; - pj_assert(op_key == pending_data_.common_.op_key_); + pj_assert (op_key == pending_data_.common_.op_key_); Cancel(); if (cur_type == TYPE_READ) { - if (cb_.on_read_complete) - cb_.on_read_complete(key_, op_key, bytes_status); + if (cb_.on_read_complete) + cb_.on_read_complete (key_, op_key, bytes_status); } else if (cur_type == TYPE_ACCEPT) - ; + ; } @@ -440,8 +447,8 @@ void CIoqueueCallback::CancelOperation(pj_ioqueue_op_key_t *op_key, /* * IO Queue key structure. */ -struct pj_ioqueue_key_t -{ + +struct pj_ioqueue_key_t { CIoqueueCallback *cbObj; }; @@ -449,7 +456,7 @@ struct pj_ioqueue_key_t /* * Return the name of the ioqueue implementation. */ -PJ_DEF(const char*) pj_ioqueue_name(void) +PJ_DEF (const char*) pj_ioqueue_name (void) { return "ioqueue-symbian"; } @@ -458,15 +465,15 @@ PJ_DEF(const char*) pj_ioqueue_name(void) /* * Create a new I/O Queue framework. */ -PJ_DEF(pj_status_t) pj_ioqueue_create( pj_pool_t *pool, - pj_size_t max_fd, - pj_ioqueue_t **p_ioqueue) +PJ_DEF (pj_status_t) pj_ioqueue_create (pj_pool_t *pool, + pj_size_t max_fd, + pj_ioqueue_t **p_ioqueue) { pj_ioqueue_t *ioq; - PJ_UNUSED_ARG(max_fd); + PJ_UNUSED_ARG (max_fd); - ioq = PJ_POOL_ZALLOC_T(pool, pj_ioqueue_t); + ioq = PJ_POOL_ZALLOC_T (pool, pj_ioqueue_t); *p_ioqueue = ioq; return PJ_SUCCESS; } @@ -475,79 +482,80 @@ PJ_DEF(pj_status_t) pj_ioqueue_create( pj_pool_t *pool, /* * Destroy the I/O queue. */ -PJ_DEF(pj_status_t) pj_ioqueue_destroy( pj_ioqueue_t *ioq ) +PJ_DEF (pj_status_t) pj_ioqueue_destroy (pj_ioqueue_t *ioq) { - PJ_UNUSED_ARG(ioq); + PJ_UNUSED_ARG (ioq); return PJ_SUCCESS; } /* - * Set the lock object to be used by the I/O Queue. + * Set the lock object to be used by the I/O Queue. */ -PJ_DEF(pj_status_t) pj_ioqueue_set_lock( pj_ioqueue_t *ioq, - pj_lock_t *lock, - pj_bool_t auto_delete ) +PJ_DEF (pj_status_t) pj_ioqueue_set_lock (pj_ioqueue_t *ioq, + pj_lock_t *lock, + pj_bool_t auto_delete) { /* Don't really need lock for now */ - PJ_UNUSED_ARG(ioq); - + PJ_UNUSED_ARG (ioq); + if (auto_delete) { - pj_lock_destroy(lock); + pj_lock_destroy (lock); } return PJ_SUCCESS; } -PJ_DEF(pj_status_t) pj_ioqueue_set_default_concurrency(pj_ioqueue_t *ioqueue, - pj_bool_t allow) +PJ_DEF (pj_status_t) pj_ioqueue_set_default_concurrency (pj_ioqueue_t *ioqueue, + pj_bool_t allow) { - /* Not supported, just return PJ_SUCCESS silently */ - PJ_UNUSED_ARG(ioqueue); - PJ_UNUSED_ARG(allow); - return PJ_SUCCESS; + /* Not supported, just return PJ_SUCCESS silently */ + PJ_UNUSED_ARG (ioqueue); + PJ_UNUSED_ARG (allow); + return PJ_SUCCESS; } /* - * Register a socket to the I/O queue framework. + * Register a socket to the I/O queue framework. */ -PJ_DEF(pj_status_t) pj_ioqueue_register_sock( pj_pool_t *pool, - pj_ioqueue_t *ioq, - pj_sock_t sock, - void *user_data, - const pj_ioqueue_callback *cb, - pj_ioqueue_key_t **p_key ) +PJ_DEF (pj_status_t) pj_ioqueue_register_sock (pj_pool_t *pool, + pj_ioqueue_t *ioq, + pj_sock_t sock, + void *user_data, + const pj_ioqueue_callback *cb, + pj_ioqueue_key_t **p_key) { pj_ioqueue_key_t *key; - key = PJ_POOL_ZALLOC_T(pool, pj_ioqueue_key_t); - key->cbObj = CIoqueueCallback::NewL(ioq, key, sock, cb, user_data); + key = PJ_POOL_ZALLOC_T (pool, pj_ioqueue_key_t); + key->cbObj = CIoqueueCallback::NewL (ioq, key, sock, cb, user_data); *p_key = key; return PJ_SUCCESS; } /* - * Unregister from the I/O Queue framework. + * Unregister from the I/O Queue framework. */ -PJ_DEF(pj_status_t) pj_ioqueue_unregister( pj_ioqueue_key_t *key ) +PJ_DEF (pj_status_t) pj_ioqueue_unregister (pj_ioqueue_key_t *key) { if (key == NULL || key->cbObj == NULL) - return PJ_SUCCESS; + return PJ_SUCCESS; // Cancel pending async object if (key->cbObj) { - key->cbObj->Cancel(); + key->cbObj->Cancel(); } // Close socket. key->cbObj->get_pj_socket()->Socket().Close(); + delete key->cbObj->get_pj_socket(); // Delete async object. if (key->cbObj) { - delete key->cbObj; - key->cbObj = NULL; + delete key->cbObj; + key->cbObj = NULL; } return PJ_SUCCESS; @@ -557,7 +565,7 @@ PJ_DEF(pj_status_t) pj_ioqueue_unregister( pj_ioqueue_key_t *key ) /* * Get user data associated with an ioqueue key. */ -PJ_DEF(void*) pj_ioqueue_get_user_data( pj_ioqueue_key_t *key ) +PJ_DEF (void*) pj_ioqueue_get_user_data (pj_ioqueue_key_t *key) { return key->cbObj->get_user_data(); } @@ -567,13 +575,14 @@ PJ_DEF(void*) pj_ioqueue_get_user_data( pj_ioqueue_key_t *key ) * Set or change the user data to be associated with the file descriptor or * handle or socket descriptor. */ -PJ_DEF(pj_status_t) pj_ioqueue_set_user_data( pj_ioqueue_key_t *key, - void *user_data, - void **old_data) +PJ_DEF (pj_status_t) pj_ioqueue_set_user_data (pj_ioqueue_key_t *key, + void *user_data, + void **old_data) { if (old_data) - *old_data = key->cbObj->get_user_data(); - key->cbObj->set_user_data(user_data); + *old_data = key->cbObj->get_user_data(); + + key->cbObj->set_user_data (user_data); return PJ_SUCCESS; } @@ -582,88 +591,91 @@ PJ_DEF(pj_status_t) pj_ioqueue_set_user_data( pj_ioqueue_key_t *key, /* * Initialize operation key. */ -PJ_DEF(void) pj_ioqueue_op_key_init( pj_ioqueue_op_key_t *op_key, - pj_size_t size ) +PJ_DEF (void) pj_ioqueue_op_key_init (pj_ioqueue_op_key_t *op_key, + pj_size_t size) { - pj_bzero(op_key, size); + pj_bzero (op_key, size); } /* * Check if operation is pending on the specified operation key. */ -PJ_DEF(pj_bool_t) pj_ioqueue_is_pending( pj_ioqueue_key_t *key, - pj_ioqueue_op_key_t *op_key ) +PJ_DEF (pj_bool_t) pj_ioqueue_is_pending (pj_ioqueue_key_t *key, + pj_ioqueue_op_key_t *op_key) { - return key->cbObj->get_op_key()==op_key && - key->cbObj->IsActive(); + return key->cbObj->get_op_key() ==op_key && + key->cbObj->IsActive(); } /* * Post completion status to the specified operation key and call the - * appropriate callback. + * appropriate callback. */ -PJ_DEF(pj_status_t) pj_ioqueue_post_completion( pj_ioqueue_key_t *key, - pj_ioqueue_op_key_t *op_key, - pj_ssize_t bytes_status ) +PJ_DEF (pj_status_t) pj_ioqueue_post_completion (pj_ioqueue_key_t *key, + pj_ioqueue_op_key_t *op_key, + pj_ssize_t bytes_status) { - if (pj_ioqueue_is_pending(key, op_key)) { - key->cbObj->CancelOperation(op_key, bytes_status); + if (pj_ioqueue_is_pending (key, op_key)) { + key->cbObj->CancelOperation (op_key, bytes_status); } + return PJ_SUCCESS; } #if defined(PJ_HAS_TCP) && PJ_HAS_TCP != 0 /** - * Instruct I/O Queue to accept incoming connection on the specified + * Instruct I/O Queue to accept incoming connection on the specified * listening socket. */ -PJ_DEF(pj_status_t) pj_ioqueue_accept( pj_ioqueue_key_t *key, - pj_ioqueue_op_key_t *op_key, - pj_sock_t *new_sock, - pj_sockaddr_t *local, - pj_sockaddr_t *remote, - int *addrlen ) +PJ_DEF (pj_status_t) pj_ioqueue_accept (pj_ioqueue_key_t *key, + pj_ioqueue_op_key_t *op_key, + pj_sock_t *new_sock, + pj_sockaddr_t *local, + pj_sockaddr_t *remote, + int *addrlen) { - - return key->cbObj->StartAccept(op_key, new_sock, local, remote, addrlen); + + return key->cbObj->StartAccept (op_key, new_sock, local, remote, addrlen); } /* * Initiate non-blocking socket connect. */ -PJ_DEF(pj_status_t) pj_ioqueue_connect( pj_ioqueue_key_t *key, - const pj_sockaddr_t *addr, - int addrlen ) +PJ_DEF (pj_status_t) pj_ioqueue_connect (pj_ioqueue_key_t *key, + const pj_sockaddr_t *addr, + int addrlen) { pj_status_t status; - + RSocket &rSock = key->cbObj->get_pj_socket()->Socket(); TInetAddr inetAddr; TRequestStatus reqStatus; // Return failure if access point is marked as down by app. PJ_SYMBIAN_CHECK_CONNECTION(); - + // Convert address - status = PjSymbianOS::pj2Addr(*(const pj_sockaddr*)addr, addrlen, - inetAddr); + status = PjSymbianOS::pj2Addr (* (const pj_sockaddr*) addr, addrlen, + inetAddr); + if (status != PJ_SUCCESS) - return status; - + return status; + // We don't support async connect for now. - PJ_TODO(IOQUEUE_SUPPORT_ASYNC_CONNECT); + PJ_TODO (IOQUEUE_SUPPORT_ASYNC_CONNECT); - rSock.Connect(inetAddr, reqStatus); - User::WaitForRequest(reqStatus); + rSock.Connect (inetAddr, reqStatus); + + User::WaitForRequest (reqStatus); if (reqStatus == KErrNone) - return PJ_SUCCESS; + return PJ_SUCCESS; - return PJ_RETURN_OS_ERROR(reqStatus.Int()); + return PJ_RETURN_OS_ERROR (reqStatus.Int()); } @@ -672,14 +684,14 @@ PJ_DEF(pj_status_t) pj_ioqueue_connect( pj_ioqueue_key_t *key, /* * Poll the I/O Queue for completed events. */ -PJ_DEF(int) pj_ioqueue_poll( pj_ioqueue_t *ioq, - const pj_time_val *timeout) +PJ_DEF (int) pj_ioqueue_poll (pj_ioqueue_t *ioq, + const pj_time_val *timeout) { /* Polling is not necessary on Symbian, since all async activities * are registered to active scheduler. */ - PJ_UNUSED_ARG(ioq); - PJ_UNUSED_ARG(timeout); + PJ_UNUSED_ARG (ioq); + PJ_UNUSED_ARG (timeout); return 0; } @@ -687,19 +699,20 @@ PJ_DEF(int) pj_ioqueue_poll( pj_ioqueue_t *ioq, /* * Instruct the I/O Queue to read from the specified handle. */ -PJ_DEF(pj_status_t) pj_ioqueue_recv( pj_ioqueue_key_t *key, - pj_ioqueue_op_key_t *op_key, - void *buffer, - pj_ssize_t *length, - pj_uint32_t flags ) +PJ_DEF (pj_status_t) pj_ioqueue_recv (pj_ioqueue_key_t *key, + pj_ioqueue_op_key_t *op_key, + void *buffer, + pj_ssize_t *length, + pj_uint32_t flags) { // If socket has reader, delete it. if (key->cbObj->get_pj_socket()->Reader()) - key->cbObj->get_pj_socket()->DestroyReader(); - + key->cbObj->get_pj_socket()->DestroyReader(); + // Clear flag flags &= ~PJ_IOQUEUE_ALWAYS_ASYNC; - return key->cbObj->StartRead(op_key, buffer, length, flags, NULL, NULL); + + return key->cbObj->StartRead (op_key, buffer, length, flags, NULL, NULL); } @@ -708,57 +721,60 @@ PJ_DEF(pj_status_t) pj_ioqueue_recv( pj_ioqueue_key_t *key, * normally called for socket, and the remote address will also be returned * along with the data. */ -PJ_DEF(pj_status_t) pj_ioqueue_recvfrom( pj_ioqueue_key_t *key, - pj_ioqueue_op_key_t *op_key, - void *buffer, - pj_ssize_t *length, - pj_uint32_t flags, - pj_sockaddr_t *addr, - int *addrlen) +PJ_DEF (pj_status_t) pj_ioqueue_recvfrom (pj_ioqueue_key_t *key, + pj_ioqueue_op_key_t *op_key, + void *buffer, + pj_ssize_t *length, + pj_uint32_t flags, + pj_sockaddr_t *addr, + int *addrlen) { CPjSocket *sock = key->cbObj->get_pj_socket(); - + // If address is specified, check that the length match the // address family + if (addr || addrlen) { - PJ_ASSERT_RETURN(addr && addrlen && *addrlen, PJ_EINVAL); - if (sock->GetAf() == PJ_AF_INET) { - PJ_ASSERT_RETURN(*addrlen>=(int)sizeof(pj_sockaddr_in), PJ_EINVAL); - } else if (sock->GetAf() == PJ_AF_INET6) { - PJ_ASSERT_RETURN(*addrlen>=(int)sizeof(pj_sockaddr_in6), PJ_EINVAL); - } + PJ_ASSERT_RETURN (addr && addrlen && *addrlen, PJ_EINVAL); + + if (sock->GetAf() == PJ_AF_INET) { + PJ_ASSERT_RETURN (*addrlen>= (int) sizeof (pj_sockaddr_in), PJ_EINVAL); + } else if (sock->GetAf() == PJ_AF_INET6) { + PJ_ASSERT_RETURN (*addrlen>= (int) sizeof (pj_sockaddr_in6), PJ_EINVAL); + } } - + // If socket has reader, delete it. if (sock->Reader()) - sock->DestroyReader(); - + sock->DestroyReader(); + if (key->cbObj->IsActive()) - return PJ_EBUSY; + return PJ_EBUSY; // Clear flag flags &= ~PJ_IOQUEUE_ALWAYS_ASYNC; - return key->cbObj->StartRead(op_key, buffer, length, flags, addr, addrlen); + + return key->cbObj->StartRead (op_key, buffer, length, flags, addr, addrlen); } /* * Instruct the I/O Queue to write to the handle. */ -PJ_DEF(pj_status_t) pj_ioqueue_send( pj_ioqueue_key_t *key, - pj_ioqueue_op_key_t *op_key, - const void *data, - pj_ssize_t *length, - pj_uint32_t flags ) +PJ_DEF (pj_status_t) pj_ioqueue_send (pj_ioqueue_key_t *key, + pj_ioqueue_op_key_t *op_key, + const void *data, + pj_ssize_t *length, + pj_uint32_t flags) { TRequestStatus reqStatus; - TPtrC8 aBuffer((const TUint8*)data, (TInt)*length); + TPtrC8 aBuffer ( (const TUint8*) data, (TInt) *length); TSockXfrLength aLen; - - PJ_UNUSED_ARG(op_key); + + PJ_UNUSED_ARG (op_key); // Forcing pending operation is not supported. - PJ_ASSERT_RETURN((flags & PJ_IOQUEUE_ALWAYS_ASYNC)==0, PJ_EINVAL); + PJ_ASSERT_RETURN ( (flags & PJ_IOQUEUE_ALWAYS_ASYNC) ==0, PJ_EINVAL); // Return failure if access point is marked as down by app. PJ_SYMBIAN_CHECK_CONNECTION(); @@ -766,11 +782,11 @@ PJ_DEF(pj_status_t) pj_ioqueue_send( pj_ioqueue_key_t *key, // Clear flag flags &= ~PJ_IOQUEUE_ALWAYS_ASYNC; - key->cbObj->get_pj_socket()->Socket().Send(aBuffer, flags, reqStatus, aLen); - User::WaitForRequest(reqStatus); + key->cbObj->get_pj_socket()->Socket().Send (aBuffer, flags, reqStatus, aLen); + User::WaitForRequest (reqStatus); if (reqStatus.Int() != KErrNone) - return PJ_RETURN_OS_ERROR(reqStatus.Int()); + return PJ_RETURN_OS_ERROR (reqStatus.Int()); //At least in UIQ Emulator, aLen.Length() reports incorrect length //for UDP (some newlc.com users seem to have reported this too). @@ -782,45 +798,48 @@ PJ_DEF(pj_status_t) pj_ioqueue_send( pj_ioqueue_key_t *key, /* * Instruct the I/O Queue to write to the handle. */ -PJ_DEF(pj_status_t) pj_ioqueue_sendto( pj_ioqueue_key_t *key, - pj_ioqueue_op_key_t *op_key, - const void *data, - pj_ssize_t *length, - pj_uint32_t flags, - const pj_sockaddr_t *addr, - int addrlen) +PJ_DEF (pj_status_t) pj_ioqueue_sendto (pj_ioqueue_key_t *key, + pj_ioqueue_op_key_t *op_key, + const void *data, + pj_ssize_t *length, + pj_uint32_t flags, + const pj_sockaddr_t *addr, + int addrlen) { TRequestStatus reqStatus; TPtrC8 aBuffer; TInetAddr inetAddr; TSockXfrLength aLen; pj_status_t status; - - PJ_UNUSED_ARG(op_key); + + PJ_UNUSED_ARG (op_key); // Forcing pending operation is not supported. - PJ_ASSERT_RETURN((flags & PJ_IOQUEUE_ALWAYS_ASYNC)==0, PJ_EINVAL); + PJ_ASSERT_RETURN ( (flags & PJ_IOQUEUE_ALWAYS_ASYNC) ==0, PJ_EINVAL); // Return failure if access point is marked as down by app. PJ_SYMBIAN_CHECK_CONNECTION(); // Convert address - status = PjSymbianOS::pj2Addr(*(const pj_sockaddr*)addr, addrlen, - inetAddr); + status = PjSymbianOS::pj2Addr (* (const pj_sockaddr*) addr, addrlen, + inetAddr); + if (status != PJ_SUCCESS) - return status; - + return status; + // Clear flag flags &= ~PJ_IOQUEUE_ALWAYS_ASYNC; - aBuffer.Set((const TUint8*)data, (TInt)*length); + aBuffer.Set ( (const TUint8*) data, (TInt) *length); + CPjSocket *pjSock = key->cbObj->get_pj_socket(); - pjSock->Socket().SendTo(aBuffer, inetAddr, flags, reqStatus, aLen); - User::WaitForRequest(reqStatus); + pjSock->Socket().SendTo (aBuffer, inetAddr, flags, reqStatus, aLen); + + User::WaitForRequest (reqStatus); if (reqStatus.Int() != KErrNone) - return PJ_RETURN_OS_ERROR(reqStatus.Int()); + return PJ_RETURN_OS_ERROR (reqStatus.Int()); //At least in UIQ Emulator, aLen.Length() reports incorrect length //for UDP (some newlc.com users seem to have reported this too). @@ -828,25 +847,25 @@ PJ_DEF(pj_status_t) pj_ioqueue_sendto( pj_ioqueue_key_t *key, return PJ_SUCCESS; } -PJ_DEF(pj_status_t) pj_ioqueue_set_concurrency(pj_ioqueue_key_t *key, - pj_bool_t allow) +PJ_DEF (pj_status_t) pj_ioqueue_set_concurrency (pj_ioqueue_key_t *key, + pj_bool_t allow) { - /* Not supported, just return PJ_SUCCESS silently */ - PJ_UNUSED_ARG(key); - PJ_UNUSED_ARG(allow); - return PJ_SUCCESS; + /* Not supported, just return PJ_SUCCESS silently */ + PJ_UNUSED_ARG (key); + PJ_UNUSED_ARG (allow); + return PJ_SUCCESS; } -PJ_DEF(pj_status_t) pj_ioqueue_lock_key(pj_ioqueue_key_t *key) +PJ_DEF (pj_status_t) pj_ioqueue_lock_key (pj_ioqueue_key_t *key) { - /* Not supported, just return PJ_SUCCESS silently */ - PJ_UNUSED_ARG(key); - return PJ_SUCCESS; + /* Not supported, just return PJ_SUCCESS silently */ + PJ_UNUSED_ARG (key); + return PJ_SUCCESS; } -PJ_DEF(pj_status_t) pj_ioqueue_unlock_key(pj_ioqueue_key_t *key) +PJ_DEF (pj_status_t) pj_ioqueue_unlock_key (pj_ioqueue_key_t *key) { - /* Not supported, just return PJ_SUCCESS silently */ - PJ_UNUSED_ARG(key); - return PJ_SUCCESS; + /* Not supported, just return PJ_SUCCESS silently */ + PJ_UNUSED_ARG (key); + return PJ_SUCCESS; } diff --git a/sflphone-common/libs/pjproject/pjlib/src/pj/ip_helper_symbian.cpp b/sflphone-common/libs/pjproject/pjlib/src/pj/ip_helper_symbian.cpp index 9f634a0b8b152df42b2736a63ca1a612d8028edb..3cf3845870b18cd5c36fc34521f947dad2721b60 100644 --- a/sflphone-common/libs/pjproject/pjlib/src/pj/ip_helper_symbian.cpp +++ b/sflphone-common/libs/pjproject/pjlib/src/pj/ip_helper_symbian.cpp @@ -1,5 +1,5 @@ /* $Id: ip_helper_symbian.cpp 2394 2008-12-23 17:27:53Z bennylp $ */ -/* +/* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org> * @@ -15,7 +15,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <pj/ip_helper.h> #include <pj/addr_resolv.h> @@ -31,119 +31,123 @@ #define THIS_FILE "ip_helper_symbian.cpp" #define TRACE_ME 0 -static pj_status_t rsock_enum_interface(int af, - unsigned *p_cnt, - pj_sockaddr ifs[]) +static pj_status_t rsock_enum_interface (int af, + unsigned *p_cnt, + pj_sockaddr ifs[]) { TInt rc; RSocket rSock; TPckgBuf<TSoInetInterfaceInfo> info; unsigned i; - + if (PjSymbianOS::Instance()->Connection()) { - - rc = rSock.Open(PjSymbianOS::Instance()->SocketServ(), - af, PJ_SOCK_DGRAM, KProtocolInetUdp, - *PjSymbianOS::Instance()->Connection()); + + rc = rSock.Open (PjSymbianOS::Instance()->SocketServ(), + af, PJ_SOCK_DGRAM, KProtocolInetUdp, + *PjSymbianOS::Instance()->Connection()); } else { - - rc = rSock.Open(PjSymbianOS::Instance()->SocketServ(), - af, PJ_SOCK_DGRAM, KProtocolInetUdp); - + + rc = rSock.Open (PjSymbianOS::Instance()->SocketServ(), + af, PJ_SOCK_DGRAM, KProtocolInetUdp); + } - + if (rc != KErrNone) - return PJ_RETURN_OS_ERROR(rc); - - rSock.SetOpt(KSoInetEnumInterfaces, KSolInetIfCtrl); - + return PJ_RETURN_OS_ERROR (rc); + + rSock.SetOpt (KSoInetEnumInterfaces, KSolInetIfCtrl); + for (i=0; i<*p_cnt && - rSock.GetOpt(KSoInetNextInterface, KSolInetIfCtrl, - info) == KErrNone; ) - { - TInetAddr &iAddress = info().iAddress; - int namelen; + rSock.GetOpt (KSoInetNextInterface, KSolInetIfCtrl, + info) == KErrNone;) { + TInetAddr &iAddress = info().iAddress; + int namelen; #if TRACE_ME - if (1) { - pj_sockaddr a; - char ipaddr[PJ_INET6_ADDRSTRLEN+2]; - - namelen = sizeof(pj_sockaddr); - if (PjSymbianOS::Addr2pj(iAddress, a, &namelen, - PJ_FALSE) == PJ_SUCCESS) - { - PJ_LOG(5,(THIS_FILE, "Enum: found address %s", - pj_sockaddr_print(&a, ipaddr, sizeof(ipaddr), 2))); - } - } + + if (1) { + pj_sockaddr a; + char ipaddr[PJ_INET6_ADDRSTRLEN+2]; + + namelen = sizeof (pj_sockaddr); + + if (PjSymbianOS::Addr2pj (iAddress, a, &namelen, + PJ_FALSE) == PJ_SUCCESS) { + PJ_LOG (5, (THIS_FILE, "Enum: found address %s", + pj_sockaddr_print (&a, ipaddr, sizeof (ipaddr), 2))); + } + } + #endif - - namelen = sizeof(ifs[i]); - if (PjSymbianOS::Addr2pj(iAddress, ifs[i], &namelen, - PJ_TRUE) != PJ_SUCCESS) - { - continue; - } - - if (ifs[i].addr.sa_family != af) - continue; - - ++i; + + namelen = sizeof (ifs[i]); + + if (PjSymbianOS::Addr2pj (iAddress, ifs[i], &namelen, + PJ_TRUE) != PJ_SUCCESS) { + continue; + } + + if (ifs[i].addr.sa_family != af) + continue; + + ++i; } - + rSock.Close(); - + // Done *p_cnt = i; - + return PJ_SUCCESS; } - + /* * Enumerate the local IP interface currently active in the host. */ -PJ_DEF(pj_status_t) pj_enum_ip_interface(int af, - unsigned *p_cnt, - pj_sockaddr ifs[]) +PJ_DEF (pj_status_t) pj_enum_ip_interface (int af, + unsigned *p_cnt, + pj_sockaddr ifs[]) { unsigned start; pj_status_t status = PJ_SUCCESS; start = 0; - + /* Get IPv6 interface first. */ + if (af==PJ_AF_INET6 || af==PJ_AF_UNSPEC) { - unsigned max = *p_cnt; - status = rsock_enum_interface(PJ_AF_INET6, &max, &ifs[start]); - if (status == PJ_SUCCESS) { - (*p_cnt) -= max; - start += max; - } + unsigned max = *p_cnt; + status = rsock_enum_interface (PJ_AF_INET6, &max, &ifs[start]); + + if (status == PJ_SUCCESS) { + (*p_cnt) -= max; + start += max; + } } - + /* Get IPv4 interface. */ if (af==PJ_AF_INET || af==PJ_AF_UNSPEC) { - unsigned max = *p_cnt; - status = rsock_enum_interface(PJ_AF_INET, &max, &ifs[start]); - if (status == PJ_SUCCESS) { - (*p_cnt) -= max; - start += max; - } + unsigned max = *p_cnt; + status = rsock_enum_interface (PJ_AF_INET, &max, &ifs[start]); + + if (status == PJ_SUCCESS) { + (*p_cnt) -= max; + start += max; + } } - + *p_cnt = start; - + return start ? PJ_SUCCESS : PJ_ENOTFOUND; } /* * Enumerate the IP routing table for this host. */ -PJ_DEF(pj_status_t) pj_enum_ip_route(unsigned *p_cnt, - pj_ip_route_entry routes[]) +PJ_DEF (pj_status_t) pj_enum_ip_route (unsigned *p_cnt, + pj_ip_route_entry routes[]) { - PJ_ASSERT_RETURN(p_cnt && *p_cnt > 0 && routes, PJ_EINVAL); + PJ_ASSERT_RETURN (p_cnt && *p_cnt > 0 && routes, PJ_EINVAL); *p_cnt = 0; return PJ_ENOTSUP; } diff --git a/sflphone-common/libs/pjproject/pjlib/src/pj/log_writer_symbian_console.cpp b/sflphone-common/libs/pjproject/pjlib/src/pj/log_writer_symbian_console.cpp index 8f627cf149067127f7bf0402c0268f77f748361d..34d4a40254363c3c1b25142accf7622a4040f1da 100644 --- a/sflphone-common/libs/pjproject/pjlib/src/pj/log_writer_symbian_console.cpp +++ b/sflphone-common/libs/pjproject/pjlib/src/pj/log_writer_symbian_console.cpp @@ -1,5 +1,5 @@ /* $Id: log_writer_symbian_console.cpp 2394 2008-12-23 17:27:53Z bennylp $ */ -/* +/* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org> * @@ -15,7 +15,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <pj/log.h> #include <pj/os.h> @@ -24,21 +24,21 @@ #include "os_symbian.h" #include <e32cons.h> -PJ_DEF(void) pj_log_write(int level, const char *buffer, int len) +PJ_DEF (void) pj_log_write (int level, const char *buffer, int len) { #if 0 wchar_t wbuffer[PJ_LOG_MAX_SIZE]; CConsoleBase *cons = PjSymbianOS::Instance->Console(); - pj_ansi_to_unicode(buffer, len, wbuffer, PJ_ARRAY_SIZE(wbuffer)); + pj_ansi_to_unicode (buffer, len, wbuffer, PJ_ARRAY_SIZE (wbuffer)); - - TPtrC16 aPtr((TUint16*)wbuffer, len); - console->Write(aPtr); + + TPtrC16 aPtr ( (TUint16*) wbuffer, len); + console->Write (aPtr); #else - PJ_UNUSED_ARG(level); - PJ_UNUSED_ARG(buffer); - PJ_UNUSED_ARG(len); + PJ_UNUSED_ARG (level); + PJ_UNUSED_ARG (buffer); + PJ_UNUSED_ARG (len); #endif } diff --git a/sflphone-common/libs/pjproject/pjlib/src/pj/os_core_symbian.cpp b/sflphone-common/libs/pjproject/pjlib/src/pj/os_core_symbian.cpp index 8b036152180cccc77692b806e202ce82b63dcf80..96478ec4edfc5c87ecdd0a9e6ddf73bc9024c133 100644 --- a/sflphone-common/libs/pjproject/pjlib/src/pj/os_core_symbian.cpp +++ b/sflphone-common/libs/pjproject/pjlib/src/pj/os_core_symbian.cpp @@ -1,5 +1,5 @@ /* $Id: os_core_symbian.cpp 2853 2009-08-05 10:58:02Z bennylp $ */ -/* +/* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org> * @@ -15,7 +15,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <pj/os.h> @@ -35,15 +35,14 @@ #define DUMMY_MUTEX ((pj_mutex_t*)101) #define DUMMY_SEMAPHORE ((pj_sem_t*)102) #define THIS_FILE "os_core_symbian.c" - + /* * Note: * * The Symbian implementation does not support threading! - */ + */ -struct pj_thread_t -{ +struct pj_thread_t { char obj_name[PJ_MAX_OBJ_NAME]; void *tls_values[PJ_MAX_TLS]; @@ -57,13 +56,11 @@ struct pj_thread_t } main_thread; -struct pj_atomic_t -{ +struct pj_atomic_t { pj_atomic_value_t value; }; -struct pj_sem_t -{ +struct pj_sem_t { int value; int max; }; @@ -73,7 +70,7 @@ static int tls_vars[PJ_MAX_TLS]; /* atexit handlers */ static unsigned atexit_count; -static void (*atexit_func[32])(void); +static void (*atexit_func[32]) (void); @@ -84,7 +81,7 @@ static void (*atexit_func[32])(void); // CPjTimeoutTimer::CPjTimeoutTimer() -: CActive(PJ_SYMBIAN_TIMER_PRIORITY), hasTimedOut_(PJ_FALSE) + : CActive (PJ_SYMBIAN_TIMER_PRIORITY), hasTimedOut_ (PJ_FALSE) { } @@ -98,27 +95,27 @@ void CPjTimeoutTimer::ConstructL() { hasTimedOut_ = PJ_FALSE; timer_.CreateLocal(); - CActiveScheduler::Add(this); + CActiveScheduler::Add (this); } CPjTimeoutTimer *CPjTimeoutTimer::NewL() { CPjTimeoutTimer *self = new CPjTimeoutTimer; - CleanupStack::PushL(self); + CleanupStack::PushL (self); self->ConstructL(); - CleanupStack::Pop(self); + CleanupStack::Pop (self); return self; } -void CPjTimeoutTimer::StartTimer(TUint miliSeconds) +void CPjTimeoutTimer::StartTimer (TUint miliSeconds) { Cancel(); hasTimedOut_ = PJ_FALSE; - timer_.After(iStatus, miliSeconds * 1000); + timer_.After (iStatus, miliSeconds * 1000); SetActive(); } @@ -137,9 +134,9 @@ void CPjTimeoutTimer::DoCancel() timer_.Cancel(); } -TInt CPjTimeoutTimer::RunError(TInt aError) +TInt CPjTimeoutTimer::RunError (TInt aError) { - PJ_UNUSED_ARG(aError); + PJ_UNUSED_ARG (aError); return KErrNone; } @@ -151,16 +148,16 @@ TInt CPjTimeoutTimer::RunError(TInt aError) // PjSymbianOS::PjSymbianOS() -: isConnectionUp_(false), - isSocketServInitialized_(false), isResolverInitialized_(false), - console_(NULL), selectTimeoutTimer_(NULL), - appSocketServ_(NULL), appConnection_(NULL), appHostResolver_(NULL), - appHostResolver6_(NULL) + : isConnectionUp_ (false), + isSocketServInitialized_ (false), isResolverInitialized_ (false), + console_ (NULL), selectTimeoutTimer_ (NULL), + appSocketServ_ (NULL), appConnection_ (NULL), appHostResolver_ (NULL), + appHostResolver6_ (NULL) { } // Set parameters -void PjSymbianOS::SetParameters(pj_symbianos_params *params) +void PjSymbianOS::SetParameters (pj_symbianos_params *params) { appSocketServ_ = (RSocketServ*) params->rsocketserv; appConnection_ = (RConnection*) params->rconnection; @@ -184,54 +181,57 @@ TInt PjSymbianOS::Initialize() selectTimeoutTimer_ = CPjTimeoutTimer::NewL(); #if 0 - pj_assert(console_ == NULL); - TRAPD(err, console_ = Console::NewL(_L("PJLIB"), - TSize(KConsFullScreen,KConsFullScreen))); + pj_assert (console_ == NULL); + TRAPD (err, console_ = Console::NewL (_L ("PJLIB"), + TSize (KConsFullScreen,KConsFullScreen))); return err; #endif /* Only create RSocketServ if application doesn't specify it * in the parameters */ + if (!isSocketServInitialized_ && appSocketServ_ == NULL) { - err = socketServ_.Connect(); - if (err != KErrNone) - goto on_error; + err = socketServ_.Connect(); + + if (err != KErrNone) + goto on_error; - isSocketServInitialized_ = true; + isSocketServInitialized_ = true; } if (!isResolverInitialized_) { - if (appHostResolver_ == NULL) { - if (Connection()) - err = hostResolver_.Open(SocketServ(), KAfInet, KSockStream, - *Connection()); - else - err = hostResolver_.Open(SocketServ(), KAfInet, KSockStream); - - if (err != KErrNone) - goto on_error; - } - + if (appHostResolver_ == NULL) { + if (Connection()) + err = hostResolver_.Open (SocketServ(), KAfInet, KSockStream, + *Connection()); + else + err = hostResolver_.Open (SocketServ(), KAfInet, KSockStream); + + if (err != KErrNone) + goto on_error; + } + #if defined(PJ_HAS_IPV6) && PJ_HAS_IPV6!=0 - if (appHostResolver6_ == NULL) { - if (Connection()) - err = hostResolver6_.Open(SocketServ(), KAfInet6, KSockStream, - *Connection()); - else - err = hostResolver6_.Open(SocketServ(), KAfInet6, KSockStream); - - if (err != KErrNone) - goto on_error; - } + if (appHostResolver6_ == NULL) { + if (Connection()) + err = hostResolver6_.Open (SocketServ(), KAfInet6, KSockStream, + *Connection()); + else + err = hostResolver6_.Open (SocketServ(), KAfInet6, KSockStream); + + if (err != KErrNone) + goto on_error; + } + #endif - - - isResolverInitialized_ = true; + + + isResolverInitialized_ = true; } isConnectionUp_ = true; - + return KErrNone; on_error: @@ -243,26 +243,27 @@ on_error: void PjSymbianOS::Shutdown() { isConnectionUp_ = false; - + if (isResolverInitialized_) { - hostResolver_.Close(); + hostResolver_.Close(); #if defined(PJ_HAS_IPV6) && PJ_HAS_IPV6!=0 - hostResolver6_.Close(); + hostResolver6_.Close(); #endif - isResolverInitialized_ = false; + isResolverInitialized_ = false; } if (isSocketServInitialized_) { - socketServ_.Close(); - isSocketServInitialized_ = false; + socketServ_.Close(); + isSocketServInitialized_ = false; } delete console_; + console_ = NULL; delete selectTimeoutTimer_; selectTimeoutTimer_ = NULL; - + appSocketServ_ = NULL; appConnection_ = NULL; appHostResolver_ = NULL; @@ -270,24 +271,24 @@ void PjSymbianOS::Shutdown() } // Convert to Unicode -TInt PjSymbianOS::ConvertToUnicode(TDes16 &aUnicode, const TDesC8 &aForeign) +TInt PjSymbianOS::ConvertToUnicode (TDes16 &aUnicode, const TDesC8 &aForeign) { #if 0 - pj_assert(conv_ != NULL); - return conv_->ConvertToUnicode(aUnicode, aForeign, convToUnicodeState_); + pj_assert (conv_ != NULL); + return conv_->ConvertToUnicode (aUnicode, aForeign, convToUnicodeState_); #else - return CnvUtfConverter::ConvertToUnicodeFromUtf8(aUnicode, aForeign); + return CnvUtfConverter::ConvertToUnicodeFromUtf8 (aUnicode, aForeign); #endif } // Convert from Unicode -TInt PjSymbianOS::ConvertFromUnicode(TDes8 &aForeign, const TDesC16 &aUnicode) +TInt PjSymbianOS::ConvertFromUnicode (TDes8 &aForeign, const TDesC16 &aUnicode) { #if 0 - pj_assert(conv_ != NULL); - return conv_->ConvertFromUnicode(aForeign, aUnicode, convToAnsiState_); + pj_assert (conv_ != NULL); + return conv_->ConvertFromUnicode (aForeign, aUnicode, convToAnsiState_); #else - return CnvUtfConverter::ConvertFromUnicodeToUtf8(aForeign, aUnicode); + return CnvUtfConverter::ConvertFromUnicodeToUtf8 (aForeign, aUnicode); #endif } @@ -297,25 +298,25 @@ TInt PjSymbianOS::ConvertFromUnicode(TDes8 &aForeign, const TDesC16 &aUnicode) // PJLIB os.h implementation // -PJ_DEF(pj_uint32_t) pj_getpid(void) +PJ_DEF (pj_uint32_t) pj_getpid (void) { return 0; } /* Set Symbian specific parameters */ -PJ_DEF(pj_status_t) pj_symbianos_set_params(pj_symbianos_params *prm) +PJ_DEF (pj_status_t) pj_symbianos_set_params (pj_symbianos_params *prm) { - PJ_ASSERT_RETURN(prm != NULL, PJ_EINVAL); - PjSymbianOS::Instance()->SetParameters(prm); + PJ_ASSERT_RETURN (prm != NULL, PJ_EINVAL); + PjSymbianOS::Instance()->SetParameters (prm); return PJ_SUCCESS; } /* Set connection status */ -PJ_DEF(void) pj_symbianos_set_connection_status(pj_bool_t up) +PJ_DEF (void) pj_symbianos_set_connection_status (pj_bool_t up) { - PjSymbianOS::Instance()->SetConnectionStatus(up != 0); + PjSymbianOS::Instance()->SetConnectionStatus (up != 0); } @@ -323,169 +324,180 @@ PJ_DEF(void) pj_symbianos_set_connection_status(pj_bool_t up) * pj_init(void). * Init PJLIB! */ -PJ_DEF(pj_status_t) pj_init(void) +PJ_DEF (pj_status_t) pj_init (void) { - char stack_ptr; + char stack_ptr; pj_status_t status; - - pj_ansi_strcpy(main_thread.obj_name, "pjthread"); + + pj_ansi_strcpy (main_thread.obj_name, "pjthread"); // Init main thread - pj_memset(&main_thread, 0, sizeof(main_thread)); + pj_memset (&main_thread, 0, sizeof (main_thread)); // Initialize PjSymbianOS instance PjSymbianOS *os = PjSymbianOS::Instance(); - PJ_LOG(4,(THIS_FILE, "Initializing PJLIB for Symbian OS..")); + PJ_LOG (4, (THIS_FILE, "Initializing PJLIB for Symbian OS..")); - TInt err; + TInt err; err = os->Initialize(); + if (err != KErrNone) - return PJ_RETURN_OS_ERROR(err); + return PJ_RETURN_OS_ERROR (err); /* Init logging */ pj_log_init(); - /* Initialize exception ID for the pool. + /* Initialize exception ID for the pool. * Must do so after critical section is configured. - */ - status = pj_exception_id_alloc("PJLIB/No memory", &PJ_NO_MEMORY_EXCEPTION); + */ + status = pj_exception_id_alloc ("PJLIB/No memory", &PJ_NO_MEMORY_EXCEPTION); + if (status != PJ_SUCCESS) goto on_error; #if defined(PJ_OS_HAS_CHECK_STACK) && PJ_OS_HAS_CHECK_STACK!=0 main_thread.stk_start = &stack_ptr; + main_thread.stk_size = 0xFFFFFFFFUL; + main_thread.stk_max_usage = 0; + #else stack_ptr = '\0'; + #endif - PJ_LOG(5,(THIS_FILE, "PJLIB initialized.")); + PJ_LOG (5, (THIS_FILE, "PJLIB initialized.")); + return PJ_SUCCESS; on_error: pj_shutdown(); - return PJ_RETURN_OS_ERROR(err); + + return PJ_RETURN_OS_ERROR (err); } -PJ_DEF(pj_status_t) pj_atexit(pj_exit_callback func) +PJ_DEF (pj_status_t) pj_atexit (pj_exit_callback func) { - if (atexit_count >= PJ_ARRAY_SIZE(atexit_func)) - return PJ_ETOOMANY; + if (atexit_count >= PJ_ARRAY_SIZE (atexit_func)) + return PJ_ETOOMANY; atexit_func[atexit_count++] = func; + return PJ_SUCCESS; } -PJ_DEF(void) pj_shutdown(void) +PJ_DEF (void) pj_shutdown (void) { /* Call atexit() functions */ while (atexit_count > 0) { - (*atexit_func[atexit_count-1])(); - --atexit_count; + (*atexit_func[atexit_count-1]) (); + --atexit_count; } /* Free exception ID */ if (PJ_NO_MEMORY_EXCEPTION != -1) { - pj_exception_id_free(PJ_NO_MEMORY_EXCEPTION); - PJ_NO_MEMORY_EXCEPTION = -1; + pj_exception_id_free (PJ_NO_MEMORY_EXCEPTION); + PJ_NO_MEMORY_EXCEPTION = -1; } /* Clear static variables */ pj_errno_clear_handlers(); PjSymbianOS *os = PjSymbianOS::Instance(); + os->Shutdown(); } ///////////////////////////////////////////////////////////////////////////// -class CPollTimeoutTimer : public CActive +class CPollTimeoutTimer : public CActive { -public: - static CPollTimeoutTimer* NewL(int msec, TInt prio); - ~CPollTimeoutTimer(); - - virtual void RunL(); - virtual void DoCancel(); -private: - RTimer rtimer_; - - explicit CPollTimeoutTimer(TInt prio); - void ConstructL(int msec); + public: + static CPollTimeoutTimer* NewL (int msec, TInt prio); + ~CPollTimeoutTimer(); + + virtual void RunL(); + virtual void DoCancel(); + + private: + RTimer rtimer_; + + explicit CPollTimeoutTimer (TInt prio); + void ConstructL (int msec); }; -CPollTimeoutTimer::CPollTimeoutTimer(TInt prio) -: CActive(prio) +CPollTimeoutTimer::CPollTimeoutTimer (TInt prio) + : CActive (prio) { } -CPollTimeoutTimer::~CPollTimeoutTimer() +CPollTimeoutTimer::~CPollTimeoutTimer() { rtimer_.Close(); } -void CPollTimeoutTimer::ConstructL(int msec) +void CPollTimeoutTimer::ConstructL (int msec) { rtimer_.CreateLocal(); - CActiveScheduler::Add(this); - rtimer_.After(iStatus, msec*1000); + CActiveScheduler::Add (this); + rtimer_.After (iStatus, msec*1000); SetActive(); } -CPollTimeoutTimer* CPollTimeoutTimer::NewL(int msec, TInt prio) +CPollTimeoutTimer* CPollTimeoutTimer::NewL (int msec, TInt prio) { - CPollTimeoutTimer *self = new CPollTimeoutTimer(prio); - CleanupStack::PushL(self); - self->ConstructL(msec); - CleanupStack::Pop(self); + CPollTimeoutTimer *self = new CPollTimeoutTimer (prio); + CleanupStack::PushL (self); + self->ConstructL (msec); + CleanupStack::Pop (self); return self; } -void CPollTimeoutTimer::RunL() +void CPollTimeoutTimer::RunL() { } -void CPollTimeoutTimer::DoCancel() +void CPollTimeoutTimer::DoCancel() { - rtimer_.Cancel(); + rtimer_.Cancel(); } /* - * Wait the completion of any Symbian active objects. + * Wait the completion of any Symbian active objects. */ -PJ_DEF(pj_bool_t) pj_symbianos_poll(int priority, int ms_timeout) +PJ_DEF (pj_bool_t) pj_symbianos_poll (int priority, int ms_timeout) { CPollTimeoutTimer *timer = NULL; - + if (priority==-1) - priority = EPriorityNull; - + priority = EPriorityNull; + if (ms_timeout >= 0) { - timer = CPollTimeoutTimer::NewL(ms_timeout, priority); + timer = CPollTimeoutTimer::NewL (ms_timeout, priority); } - - PjSymbianOS::Instance()->WaitForActiveObjects(priority); - + + PjSymbianOS::Instance()->WaitForActiveObjects (priority); + if (timer) { bool timer_is_active = timer->IsActive(); - - timer->Cancel(); - + + timer->Cancel(); + delete timer; - - return timer_is_active ? PJ_TRUE : PJ_FALSE; - + + return timer_is_active ? PJ_TRUE : PJ_FALSE; + } else { - return PJ_TRUE; + return PJ_TRUE; } } @@ -493,7 +505,7 @@ PJ_DEF(pj_bool_t) pj_symbianos_poll(int priority, int ms_timeout) /* * pj_thread_is_registered() */ -PJ_DEF(pj_bool_t) pj_thread_is_registered(void) +PJ_DEF (pj_bool_t) pj_thread_is_registered (void) { return PJ_FALSE; } @@ -502,9 +514,9 @@ PJ_DEF(pj_bool_t) pj_thread_is_registered(void) /* * Get thread priority value for the thread. */ -PJ_DEF(int) pj_thread_get_prio(pj_thread_t *thread) +PJ_DEF (int) pj_thread_get_prio (pj_thread_t *thread) { - PJ_UNUSED_ARG(thread); + PJ_UNUSED_ARG (thread); return 1; } @@ -512,10 +524,10 @@ PJ_DEF(int) pj_thread_get_prio(pj_thread_t *thread) /* * Set the thread priority. */ -PJ_DEF(pj_status_t) pj_thread_set_prio(pj_thread_t *thread, int prio) +PJ_DEF (pj_status_t) pj_thread_set_prio (pj_thread_t *thread, int prio) { - PJ_UNUSED_ARG(thread); - PJ_UNUSED_ARG(prio); + PJ_UNUSED_ARG (thread); + PJ_UNUSED_ARG (prio); return PJ_SUCCESS; } @@ -523,9 +535,9 @@ PJ_DEF(pj_status_t) pj_thread_set_prio(pj_thread_t *thread, int prio) /* * Get the lowest priority value available on this system. */ -PJ_DEF(int) pj_thread_get_prio_min(pj_thread_t *thread) +PJ_DEF (int) pj_thread_get_prio_min (pj_thread_t *thread) { - PJ_UNUSED_ARG(thread); + PJ_UNUSED_ARG (thread); return 1; } @@ -533,9 +545,9 @@ PJ_DEF(int) pj_thread_get_prio_min(pj_thread_t *thread) /* * Get the highest priority value available on this system. */ -PJ_DEF(int) pj_thread_get_prio_max(pj_thread_t *thread) +PJ_DEF (int) pj_thread_get_prio_max (pj_thread_t *thread) { - PJ_UNUSED_ARG(thread); + PJ_UNUSED_ARG (thread); return 1; } @@ -543,22 +555,22 @@ PJ_DEF(int) pj_thread_get_prio_max(pj_thread_t *thread) /* * pj_thread_get_os_handle() */ -PJ_DEF(void*) pj_thread_get_os_handle(pj_thread_t *thread) +PJ_DEF (void*) pj_thread_get_os_handle (pj_thread_t *thread) { - PJ_UNUSED_ARG(thread); + PJ_UNUSED_ARG (thread); return NULL; } /* * pj_thread_register(..) */ -PJ_DEF(pj_status_t) pj_thread_register ( const char *cstr_thread_name, - pj_thread_desc desc, - pj_thread_t **thread_ptr) +PJ_DEF (pj_status_t) pj_thread_register (const char *cstr_thread_name, + pj_thread_desc desc, + pj_thread_t **thread_ptr) { - PJ_UNUSED_ARG(cstr_thread_name); - PJ_UNUSED_ARG(desc); - PJ_UNUSED_ARG(thread_ptr); + PJ_UNUSED_ARG (cstr_thread_name); + PJ_UNUSED_ARG (desc); + PJ_UNUSED_ARG (thread_ptr); return PJ_EINVALIDOP; } @@ -566,21 +578,21 @@ PJ_DEF(pj_status_t) pj_thread_register ( const char *cstr_thread_name, /* * pj_thread_create(...) */ -PJ_DEF(pj_status_t) pj_thread_create( pj_pool_t *pool, - const char *thread_name, - pj_thread_proc *proc, - void *arg, - pj_size_t stack_size, - unsigned flags, - pj_thread_t **ptr_thread) -{ - PJ_UNUSED_ARG(pool); - PJ_UNUSED_ARG(thread_name); - PJ_UNUSED_ARG(proc); - PJ_UNUSED_ARG(arg); - PJ_UNUSED_ARG(stack_size); - PJ_UNUSED_ARG(flags); - PJ_UNUSED_ARG(ptr_thread); +PJ_DEF (pj_status_t) pj_thread_create (pj_pool_t *pool, + const char *thread_name, + pj_thread_proc *proc, + void *arg, + pj_size_t stack_size, + unsigned flags, + pj_thread_t **ptr_thread) +{ + PJ_UNUSED_ARG (pool); + PJ_UNUSED_ARG (thread_name); + PJ_UNUSED_ARG (proc); + PJ_UNUSED_ARG (arg); + PJ_UNUSED_ARG (stack_size); + PJ_UNUSED_ARG (flags); + PJ_UNUSED_ARG (ptr_thread); /* Sorry mate, we don't support threading */ return PJ_ENOTSUP; @@ -589,25 +601,25 @@ PJ_DEF(pj_status_t) pj_thread_create( pj_pool_t *pool, /* * pj_thread-get_name() */ -PJ_DEF(const char*) pj_thread_get_name(pj_thread_t *p) +PJ_DEF (const char*) pj_thread_get_name (pj_thread_t *p) { - pj_assert(p == &main_thread); + pj_assert (p == &main_thread); return p->obj_name; } /* * pj_thread_resume() */ -PJ_DEF(pj_status_t) pj_thread_resume(pj_thread_t *p) +PJ_DEF (pj_status_t) pj_thread_resume (pj_thread_t *p) { - PJ_UNUSED_ARG(p); + PJ_UNUSED_ARG (p); return PJ_EINVALIDOP; } /* * pj_thread_this() */ -PJ_DEF(pj_thread_t*) pj_thread_this(void) +PJ_DEF (pj_thread_t*) pj_thread_this (void) { return &main_thread; } @@ -615,27 +627,27 @@ PJ_DEF(pj_thread_t*) pj_thread_this(void) /* * pj_thread_join() */ -PJ_DEF(pj_status_t) pj_thread_join(pj_thread_t *rec) +PJ_DEF (pj_status_t) pj_thread_join (pj_thread_t *rec) { - PJ_UNUSED_ARG(rec); + PJ_UNUSED_ARG (rec); return PJ_EINVALIDOP; } /* * pj_thread_destroy() */ -PJ_DEF(pj_status_t) pj_thread_destroy(pj_thread_t *rec) +PJ_DEF (pj_status_t) pj_thread_destroy (pj_thread_t *rec) { - PJ_UNUSED_ARG(rec); + PJ_UNUSED_ARG (rec); return PJ_EINVALIDOP; } /* * pj_thread_sleep() */ -PJ_DEF(pj_status_t) pj_thread_sleep(unsigned msec) +PJ_DEF (pj_status_t) pj_thread_sleep (unsigned msec) { - User::After(msec*1000); + User::After (msec*1000); return PJ_SUCCESS; } @@ -646,20 +658,22 @@ PJ_DEF(pj_status_t) pj_thread_sleep(unsigned msec) * pj_thread_local_alloc() */ -PJ_DEF(pj_status_t) pj_thread_local_alloc(long *index) +PJ_DEF (pj_status_t) pj_thread_local_alloc (long *index) { unsigned i; /* Find unused TLS variable */ - for (i=0; i<PJ_ARRAY_SIZE(tls_vars); ++i) { - if (tls_vars[i] == 0) - break; + + for (i=0; i<PJ_ARRAY_SIZE (tls_vars); ++i) { + if (tls_vars[i] == 0) + break; } - if (i == PJ_ARRAY_SIZE(tls_vars)) - return PJ_ETOOMANY; + if (i == PJ_ARRAY_SIZE (tls_vars)) + return PJ_ETOOMANY; tls_vars[i] = 1; + *index = i; return PJ_SUCCESS; @@ -668,10 +682,10 @@ PJ_DEF(pj_status_t) pj_thread_local_alloc(long *index) /* * pj_thread_local_free() */ -PJ_DEF(void) pj_thread_local_free(long index) +PJ_DEF (void) pj_thread_local_free (long index) { - PJ_ASSERT_ON_FAIL(index >= 0 && index < (int)PJ_ARRAY_SIZE(tls_vars) && - tls_vars[index] != 0, return); + PJ_ASSERT_ON_FAIL (index >= 0 && index < (int) PJ_ARRAY_SIZE (tls_vars) && + tls_vars[index] != 0, return); tls_vars[index] = 0; } @@ -680,12 +694,12 @@ PJ_DEF(void) pj_thread_local_free(long index) /* * pj_thread_local_set() */ -PJ_DEF(pj_status_t) pj_thread_local_set(long index, void *value) +PJ_DEF (pj_status_t) pj_thread_local_set (long index, void *value) { pj_thread_t *rec = pj_thread_this(); - PJ_ASSERT_RETURN(index >= 0 && index < (int)PJ_ARRAY_SIZE(tls_vars) && - tls_vars[index] != 0, PJ_EINVAL); + PJ_ASSERT_RETURN (index >= 0 && index < (int) PJ_ARRAY_SIZE (tls_vars) && + tls_vars[index] != 0, PJ_EINVAL); rec->tls_values[index] = value; return PJ_SUCCESS; @@ -694,12 +708,12 @@ PJ_DEF(pj_status_t) pj_thread_local_set(long index, void *value) /* * pj_thread_local_get() */ -PJ_DEF(void*) pj_thread_local_get(long index) +PJ_DEF (void*) pj_thread_local_get (long index) { pj_thread_t *rec = pj_thread_this(); - PJ_ASSERT_RETURN(index >= 0 && index < (int)PJ_ARRAY_SIZE(tls_vars) && - tls_vars[index] != 0, NULL); + PJ_ASSERT_RETURN (index >= 0 && index < (int) PJ_ARRAY_SIZE (tls_vars) && + tls_vars[index] != 0, NULL); return rec->tls_values[index]; } @@ -709,11 +723,11 @@ PJ_DEF(void*) pj_thread_local_get(long index) /* * Create atomic variable. */ -PJ_DEF(pj_status_t) pj_atomic_create( pj_pool_t *pool, - pj_atomic_value_t initial, - pj_atomic_t **atomic ) +PJ_DEF (pj_status_t) pj_atomic_create (pj_pool_t *pool, + pj_atomic_value_t initial, + pj_atomic_t **atomic) { - *atomic = (pj_atomic_t*)pj_pool_alloc(pool, sizeof(struct pj_atomic_t)); + *atomic = (pj_atomic_t*) pj_pool_alloc (pool, sizeof (struct pj_atomic_t)); (*atomic)->value = initial; return PJ_SUCCESS; } @@ -722,9 +736,9 @@ PJ_DEF(pj_status_t) pj_atomic_create( pj_pool_t *pool, /* * Destroy atomic variable. */ -PJ_DEF(pj_status_t) pj_atomic_destroy( pj_atomic_t *atomic_var ) +PJ_DEF (pj_status_t) pj_atomic_destroy (pj_atomic_t *atomic_var) { - PJ_UNUSED_ARG(atomic_var); + PJ_UNUSED_ARG (atomic_var); return PJ_SUCCESS; } @@ -732,8 +746,8 @@ PJ_DEF(pj_status_t) pj_atomic_destroy( pj_atomic_t *atomic_var ) /* * Set the value of an atomic type, and return the previous value. */ -PJ_DEF(void) pj_atomic_set( pj_atomic_t *atomic_var, - pj_atomic_value_t value) +PJ_DEF (void) pj_atomic_set (pj_atomic_t *atomic_var, + pj_atomic_value_t value) { atomic_var->value = value; } @@ -742,7 +756,7 @@ PJ_DEF(void) pj_atomic_set( pj_atomic_t *atomic_var, /* * Get the value of an atomic type. */ -PJ_DEF(pj_atomic_value_t) pj_atomic_get(pj_atomic_t *atomic_var) +PJ_DEF (pj_atomic_value_t) pj_atomic_get (pj_atomic_t *atomic_var) { return atomic_var->value; } @@ -751,7 +765,7 @@ PJ_DEF(pj_atomic_value_t) pj_atomic_get(pj_atomic_t *atomic_var) /* * Increment the value of an atomic type. */ -PJ_DEF(void) pj_atomic_inc(pj_atomic_t *atomic_var) +PJ_DEF (void) pj_atomic_inc (pj_atomic_t *atomic_var) { ++atomic_var->value; } @@ -760,7 +774,7 @@ PJ_DEF(void) pj_atomic_inc(pj_atomic_t *atomic_var) /* * Increment the value of an atomic type and get the result. */ -PJ_DEF(pj_atomic_value_t) pj_atomic_inc_and_get(pj_atomic_t *atomic_var) +PJ_DEF (pj_atomic_value_t) pj_atomic_inc_and_get (pj_atomic_t *atomic_var) { return ++atomic_var->value; } @@ -769,16 +783,16 @@ PJ_DEF(pj_atomic_value_t) pj_atomic_inc_and_get(pj_atomic_t *atomic_var) /* * Decrement the value of an atomic type. */ -PJ_DEF(void) pj_atomic_dec(pj_atomic_t *atomic_var) +PJ_DEF (void) pj_atomic_dec (pj_atomic_t *atomic_var) { --atomic_var->value; -} +} /* * Decrement the value of an atomic type and get the result. */ -PJ_DEF(pj_atomic_value_t) pj_atomic_dec_and_get(pj_atomic_t *atomic_var) +PJ_DEF (pj_atomic_value_t) pj_atomic_dec_and_get (pj_atomic_t *atomic_var) { return --atomic_var->value; } @@ -787,8 +801,8 @@ PJ_DEF(pj_atomic_value_t) pj_atomic_dec_and_get(pj_atomic_t *atomic_var) /* * Add a value to an atomic type. */ -PJ_DEF(void) pj_atomic_add( pj_atomic_t *atomic_var, - pj_atomic_value_t value) +PJ_DEF (void) pj_atomic_add (pj_atomic_t *atomic_var, + pj_atomic_value_t value) { atomic_var->value += value; } @@ -797,8 +811,8 @@ PJ_DEF(void) pj_atomic_add( pj_atomic_t *atomic_var, /* * Add a value to an atomic type and get the result. */ -PJ_DEF(pj_atomic_value_t) pj_atomic_add_and_get( pj_atomic_t *atomic_var, - pj_atomic_value_t value) +PJ_DEF (pj_atomic_value_t) pj_atomic_add_and_get (pj_atomic_t *atomic_var, + pj_atomic_value_t value) { atomic_var->value += value; return atomic_var->value; @@ -808,14 +822,14 @@ PJ_DEF(pj_atomic_value_t) pj_atomic_add_and_get( pj_atomic_t *atomic_var, ///////////////////////////////////////////////////////////////////////////// -PJ_DEF(pj_status_t) pj_mutex_create( pj_pool_t *pool, - const char *name, - int type, - pj_mutex_t **mutex) +PJ_DEF (pj_status_t) pj_mutex_create (pj_pool_t *pool, + const char *name, + int type, + pj_mutex_t **mutex) { - PJ_UNUSED_ARG(pool); - PJ_UNUSED_ARG(name); - PJ_UNUSED_ARG(type); + PJ_UNUSED_ARG (pool); + PJ_UNUSED_ARG (name); + PJ_UNUSED_ARG (type); *mutex = DUMMY_MUTEX; return PJ_SUCCESS; @@ -824,55 +838,55 @@ PJ_DEF(pj_status_t) pj_mutex_create( pj_pool_t *pool, /* * pj_mutex_create_simple() */ -PJ_DEF(pj_status_t) pj_mutex_create_simple( pj_pool_t *pool, - const char *name, - pj_mutex_t **mutex ) +PJ_DEF (pj_status_t) pj_mutex_create_simple (pj_pool_t *pool, + const char *name, + pj_mutex_t **mutex) { - return pj_mutex_create(pool, name, PJ_MUTEX_SIMPLE, mutex); + return pj_mutex_create (pool, name, PJ_MUTEX_SIMPLE, mutex); } -PJ_DEF(pj_status_t) pj_mutex_create_recursive( pj_pool_t *pool, - const char *name, - pj_mutex_t **mutex ) +PJ_DEF (pj_status_t) pj_mutex_create_recursive (pj_pool_t *pool, + const char *name, + pj_mutex_t **mutex) { - return pj_mutex_create(pool, name, PJ_MUTEX_RECURSE, mutex); + return pj_mutex_create (pool, name, PJ_MUTEX_RECURSE, mutex); } /* * pj_mutex_lock() */ -PJ_DEF(pj_status_t) pj_mutex_lock(pj_mutex_t *mutex) +PJ_DEF (pj_status_t) pj_mutex_lock (pj_mutex_t *mutex) { - pj_assert(mutex == DUMMY_MUTEX); + pj_assert (mutex == DUMMY_MUTEX); return PJ_SUCCESS; } /* * pj_mutex_trylock() */ -PJ_DEF(pj_status_t) pj_mutex_trylock(pj_mutex_t *mutex) +PJ_DEF (pj_status_t) pj_mutex_trylock (pj_mutex_t *mutex) { - pj_assert(mutex == DUMMY_MUTEX); + pj_assert (mutex == DUMMY_MUTEX); return PJ_SUCCESS; } /* * pj_mutex_unlock() */ -PJ_DEF(pj_status_t) pj_mutex_unlock(pj_mutex_t *mutex) +PJ_DEF (pj_status_t) pj_mutex_unlock (pj_mutex_t *mutex) { - pj_assert(mutex == DUMMY_MUTEX); + pj_assert (mutex == DUMMY_MUTEX); return PJ_SUCCESS; } /* * pj_mutex_destroy() */ -PJ_DEF(pj_status_t) pj_mutex_destroy(pj_mutex_t *mutex) +PJ_DEF (pj_status_t) pj_mutex_destroy (pj_mutex_t *mutex) { - pj_assert(mutex == DUMMY_MUTEX); + pj_assert (mutex == DUMMY_MUTEX); return PJ_SUCCESS; } @@ -889,7 +903,7 @@ PJ_DEF(pj_status_t) pj_mutex_destroy(pj_mutex_t *mutex) /* * Enter critical section. */ -PJ_DEF(void) pj_enter_critical_section(void) +PJ_DEF (void) pj_enter_critical_section (void) { /* Nothing to do */ } @@ -898,7 +912,7 @@ PJ_DEF(void) pj_enter_critical_section(void) /* * Leave critical section. */ -PJ_DEF(void) pj_leave_critical_section(void) +PJ_DEF (void) pj_leave_critical_section (void) { /* Nothing to do */ } @@ -909,17 +923,17 @@ PJ_DEF(void) pj_leave_critical_section(void) /* * Create semaphore. */ -PJ_DEF(pj_status_t) pj_sem_create( pj_pool_t *pool, - const char *name, - unsigned initial, - unsigned max, - pj_sem_t **p_sem) +PJ_DEF (pj_status_t) pj_sem_create (pj_pool_t *pool, + const char *name, + unsigned initial, + unsigned max, + pj_sem_t **p_sem) { pj_sem_t *sem; - - PJ_UNUSED_ARG(name); - sem = (pj_sem_t*) pj_pool_zalloc(pool, sizeof(pj_sem_t)); + PJ_UNUSED_ARG (name); + + sem = (pj_sem_t*) pj_pool_zalloc (pool, sizeof (pj_sem_t)); sem->value = initial; sem->max = max; @@ -932,14 +946,14 @@ PJ_DEF(pj_status_t) pj_sem_create( pj_pool_t *pool, /* * Wait for semaphore. */ -PJ_DEF(pj_status_t) pj_sem_wait(pj_sem_t *sem) +PJ_DEF (pj_status_t) pj_sem_wait (pj_sem_t *sem) { if (sem->value > 0) { - sem->value--; - return PJ_SUCCESS; + sem->value--; + return PJ_SUCCESS; } else { - pj_assert(!"Unexpected!"); - return PJ_EINVALIDOP; + pj_assert (!"Unexpected!"); + return PJ_EINVALIDOP; } } @@ -947,14 +961,14 @@ PJ_DEF(pj_status_t) pj_sem_wait(pj_sem_t *sem) /* * Try wait for semaphore. */ -PJ_DEF(pj_status_t) pj_sem_trywait(pj_sem_t *sem) +PJ_DEF (pj_status_t) pj_sem_trywait (pj_sem_t *sem) { if (sem->value > 0) { - sem->value--; - return PJ_SUCCESS; + sem->value--; + return PJ_SUCCESS; } else { - pj_assert(!"Unexpected!"); - return PJ_EINVALIDOP; + pj_assert (!"Unexpected!"); + return PJ_EINVALIDOP; } } @@ -962,7 +976,7 @@ PJ_DEF(pj_status_t) pj_sem_trywait(pj_sem_t *sem) /* * Release semaphore. */ -PJ_DEF(pj_status_t) pj_sem_post(pj_sem_t *sem) +PJ_DEF (pj_status_t) pj_sem_post (pj_sem_t *sem) { sem->value++; return PJ_SUCCESS; @@ -972,56 +986,57 @@ PJ_DEF(pj_status_t) pj_sem_post(pj_sem_t *sem) /* * Destroy semaphore. */ -PJ_DEF(pj_status_t) pj_sem_destroy(pj_sem_t *sem) +PJ_DEF (pj_status_t) pj_sem_destroy (pj_sem_t *sem) { - PJ_UNUSED_ARG(sem); + PJ_UNUSED_ARG (sem); return PJ_SUCCESS; } #if defined(PJ_OS_HAS_CHECK_STACK) && PJ_OS_HAS_CHECK_STACK != 0 /* - * The implementation of stack checking. + * The implementation of stack checking. */ -PJ_DEF(void) pj_thread_check_stack(const char *file, int line) +PJ_DEF (void) pj_thread_check_stack (const char *file, int line) { char stk_ptr; pj_uint32_t usage; pj_thread_t *thread = pj_thread_this(); - pj_assert(thread); + pj_assert (thread); /* Calculate current usage. */ usage = (&stk_ptr > thread->stk_start) ? &stk_ptr - thread->stk_start : - thread->stk_start - &stk_ptr; + thread->stk_start - &stk_ptr; /* Assert if stack usage is dangerously high. */ - pj_assert("STACK OVERFLOW!! " && (usage <= thread->stk_size - 128)); + pj_assert ("STACK OVERFLOW!! " && (usage <= thread->stk_size - 128)); /* Keep statistic. */ + if (usage > thread->stk_max_usage) { - thread->stk_max_usage = usage; - thread->caller_file = file; - thread->caller_line = line; + thread->stk_max_usage = usage; + thread->caller_file = file; + thread->caller_line = line; } } /* - * Get maximum stack usage statistic. + * Get maximum stack usage statistic. */ -PJ_DEF(pj_uint32_t) pj_thread_get_stack_max_usage(pj_thread_t *thread) +PJ_DEF (pj_uint32_t) pj_thread_get_stack_max_usage (pj_thread_t *thread) { return thread->stk_max_usage; } /* - * Dump thread stack status. + * Dump thread stack status. */ -PJ_DEF(pj_status_t) pj_thread_get_stack_info(pj_thread_t *thread, - const char **file, - int *line) +PJ_DEF (pj_status_t) pj_thread_get_stack_info (pj_thread_t *thread, + const char **file, + int *line) { - pj_assert(thread); + pj_assert (thread); *file = thread->caller_file; *line = thread->caller_line; diff --git a/sflphone-common/libs/pjproject/pjlib/src/pj/os_error_symbian.cpp b/sflphone-common/libs/pjproject/pjlib/src/pj/os_error_symbian.cpp index 31707b97c377903df1c5561cdbcda4101e5b935c..bb57cd9663c507be0d5feb5c3368a99843db3bae 100644 --- a/sflphone-common/libs/pjproject/pjlib/src/pj/os_error_symbian.cpp +++ b/sflphone-common/libs/pjproject/pjlib/src/pj/os_error_symbian.cpp @@ -1,5 +1,5 @@ /* $Id: os_error_symbian.cpp 2394 2008-12-23 17:27:53Z bennylp $ */ -/* +/* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org> * @@ -15,7 +15,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <pj/errno.h> #include <pj/assert.h> @@ -28,68 +28,70 @@ #if defined(PJ_HAS_ERROR_STRING) && (PJ_HAS_ERROR_STRING!=0) + static const struct { pj_os_err_type code; const char *msg; } gaErrorList[] = { + /* * Generic error -1 to -46 */ - PJ_BUILD_ERR( KErrNotFound, "Unable to find the specified object"), - PJ_BUILD_ERR( KErrGeneral, "General (unspecified) error"), - PJ_BUILD_ERR( KErrCancel, "The operation was cancelled"), - PJ_BUILD_ERR( KErrNoMemory, "Not enough memory"), - PJ_BUILD_ERR( KErrNotSupported, "The operation requested is not supported"), - PJ_BUILD_ERR( KErrArgument, "Bad request"), - PJ_BUILD_ERR( KErrTotalLossOfPrecision, "Total loss of precision"), - PJ_BUILD_ERR( KErrBadHandle, "Bad object"), - PJ_BUILD_ERR( KErrOverflow, "Overflow"), - PJ_BUILD_ERR( KErrUnderflow, "Underflow"), - PJ_BUILD_ERR( KErrAlreadyExists,"Already exists"), - PJ_BUILD_ERR( KErrPathNotFound, "Unable to find the specified folder"), - PJ_BUILD_ERR( KErrDied, "Closed"), - PJ_BUILD_ERR( KErrInUse, "The specified object is currently in use by another program"), - PJ_BUILD_ERR( KErrServerTerminated, "Server has closed"), - PJ_BUILD_ERR( KErrServerBusy, "Server busy"), - PJ_BUILD_ERR( KErrCompletion, "Completion error"), - PJ_BUILD_ERR( KErrNotReady, "Not ready"), - PJ_BUILD_ERR( KErrUnknown, "Unknown error"), - PJ_BUILD_ERR( KErrCorrupt, "Corrupt"), - PJ_BUILD_ERR( KErrAccessDenied, "Access denied"), - PJ_BUILD_ERR( KErrLocked, "Locked"), - PJ_BUILD_ERR( KErrWrite, "Failed to write"), - PJ_BUILD_ERR( KErrDisMounted, "Wrong disk present"), - PJ_BUILD_ERR( KErrEof, "Unexpected end of file"), - PJ_BUILD_ERR( KErrDiskFull, "Disk full"), - PJ_BUILD_ERR( KErrBadDriver, "Bad device driver"), - PJ_BUILD_ERR( KErrBadName, "Bad name"), - PJ_BUILD_ERR( KErrCommsLineFail,"Comms line failed"), - PJ_BUILD_ERR( KErrCommsFrame, "Comms frame error"), - PJ_BUILD_ERR( KErrCommsOverrun, "Comms overrun error"), - PJ_BUILD_ERR( KErrCommsParity, "Comms parity error"), - PJ_BUILD_ERR( KErrTimedOut, "Timed out"), - PJ_BUILD_ERR( KErrCouldNotConnect, "Failed to connect"), - PJ_BUILD_ERR( KErrCouldNotDisconnect, "Failed to disconnect"), - PJ_BUILD_ERR( KErrDisconnected, "Disconnected"), - PJ_BUILD_ERR( KErrBadLibraryEntryPoint, "Bad library entry point"), - PJ_BUILD_ERR( KErrBadDescriptor,"Bad descriptor"), - PJ_BUILD_ERR( KErrAbort, "Interrupted"), - PJ_BUILD_ERR( KErrTooBig, "Too big"), - PJ_BUILD_ERR( KErrDivideByZero, "Divide by zero"), - PJ_BUILD_ERR( KErrBadPower, "Batteries too low"), - PJ_BUILD_ERR( KErrDirFull, "Folder full"), - PJ_BUILD_ERR( KErrHardwareNotAvailable, ""), - PJ_BUILD_ERR( KErrSessionClosed, ""), - PJ_BUILD_ERR( KErrPermissionDenied, ""), + PJ_BUILD_ERR (KErrNotFound, "Unable to find the specified object"), + PJ_BUILD_ERR (KErrGeneral, "General (unspecified) error"), + PJ_BUILD_ERR (KErrCancel, "The operation was cancelled"), + PJ_BUILD_ERR (KErrNoMemory, "Not enough memory"), + PJ_BUILD_ERR (KErrNotSupported, "The operation requested is not supported"), + PJ_BUILD_ERR (KErrArgument, "Bad request"), + PJ_BUILD_ERR (KErrTotalLossOfPrecision, "Total loss of precision"), + PJ_BUILD_ERR (KErrBadHandle, "Bad object"), + PJ_BUILD_ERR (KErrOverflow, "Overflow"), + PJ_BUILD_ERR (KErrUnderflow, "Underflow"), + PJ_BUILD_ERR (KErrAlreadyExists,"Already exists"), + PJ_BUILD_ERR (KErrPathNotFound, "Unable to find the specified folder"), + PJ_BUILD_ERR (KErrDied, "Closed"), + PJ_BUILD_ERR (KErrInUse, "The specified object is currently in use by another program"), + PJ_BUILD_ERR (KErrServerTerminated, "Server has closed"), + PJ_BUILD_ERR (KErrServerBusy, "Server busy"), + PJ_BUILD_ERR (KErrCompletion, "Completion error"), + PJ_BUILD_ERR (KErrNotReady, "Not ready"), + PJ_BUILD_ERR (KErrUnknown, "Unknown error"), + PJ_BUILD_ERR (KErrCorrupt, "Corrupt"), + PJ_BUILD_ERR (KErrAccessDenied, "Access denied"), + PJ_BUILD_ERR (KErrLocked, "Locked"), + PJ_BUILD_ERR (KErrWrite, "Failed to write"), + PJ_BUILD_ERR (KErrDisMounted, "Wrong disk present"), + PJ_BUILD_ERR (KErrEof, "Unexpected end of file"), + PJ_BUILD_ERR (KErrDiskFull, "Disk full"), + PJ_BUILD_ERR (KErrBadDriver, "Bad device driver"), + PJ_BUILD_ERR (KErrBadName, "Bad name"), + PJ_BUILD_ERR (KErrCommsLineFail,"Comms line failed"), + PJ_BUILD_ERR (KErrCommsFrame, "Comms frame error"), + PJ_BUILD_ERR (KErrCommsOverrun, "Comms overrun error"), + PJ_BUILD_ERR (KErrCommsParity, "Comms parity error"), + PJ_BUILD_ERR (KErrTimedOut, "Timed out"), + PJ_BUILD_ERR (KErrCouldNotConnect, "Failed to connect"), + PJ_BUILD_ERR (KErrCouldNotDisconnect, "Failed to disconnect"), + PJ_BUILD_ERR (KErrDisconnected, "Disconnected"), + PJ_BUILD_ERR (KErrBadLibraryEntryPoint, "Bad library entry point"), + PJ_BUILD_ERR (KErrBadDescriptor,"Bad descriptor"), + PJ_BUILD_ERR (KErrAbort, "Interrupted"), + PJ_BUILD_ERR (KErrTooBig, "Too big"), + PJ_BUILD_ERR (KErrDivideByZero, "Divide by zero"), + PJ_BUILD_ERR (KErrBadPower, "Batteries too low"), + PJ_BUILD_ERR (KErrDirFull, "Folder full"), + PJ_BUILD_ERR (KErrHardwareNotAvailable, ""), + PJ_BUILD_ERR (KErrSessionClosed, ""), + PJ_BUILD_ERR (KErrPermissionDenied, ""), /* * Socket errors (-190 - -1000) */ - PJ_BUILD_ERR( KErrNetUnreach, "Could not connect to the network. Currently unreachable"), - PJ_BUILD_ERR( KErrHostUnreach, "Could not connect to the specified server"), - PJ_BUILD_ERR( KErrNoProtocolOpt,"The specified server refuses the selected protocol"), - PJ_BUILD_ERR( KErrUrgentData, ""), - PJ_BUILD_ERR( KErrWouldBlock, "Conflicts with KErrExtended, but cannot occur in practice"), + PJ_BUILD_ERR (KErrNetUnreach, "Could not connect to the network. Currently unreachable"), + PJ_BUILD_ERR (KErrHostUnreach, "Could not connect to the specified server"), + PJ_BUILD_ERR (KErrNoProtocolOpt,"The specified server refuses the selected protocol"), + PJ_BUILD_ERR (KErrUrgentData, ""), + PJ_BUILD_ERR (KErrWouldBlock, "Conflicts with KErrExtended, but cannot occur in practice"), {0, NULL} }; @@ -97,45 +99,45 @@ static const struct { #endif /* PJ_HAS_ERROR_STRING */ -PJ_DEF(pj_status_t) pj_get_os_error(void) +PJ_DEF (pj_status_t) pj_get_os_error (void) { return -1; } -PJ_DEF(void) pj_set_os_error(pj_status_t code) +PJ_DEF (void) pj_set_os_error (pj_status_t code) { - PJ_UNUSED_ARG(code); + PJ_UNUSED_ARG (code); } -PJ_DEF(pj_status_t) pj_get_netos_error(void) +PJ_DEF (pj_status_t) pj_get_netos_error (void) { return -1; } -PJ_DEF(void) pj_set_netos_error(pj_status_t code) +PJ_DEF (void) pj_set_netos_error (pj_status_t code) { - PJ_UNUSED_ARG(code); + PJ_UNUSED_ARG (code); } PJ_BEGIN_DECL - PJ_DECL(int) platform_strerror( pj_os_err_type os_errcode, - char *buf, pj_size_t bufsize); +PJ_DECL (int) platform_strerror (pj_os_err_type os_errcode, + char *buf, pj_size_t bufsize); PJ_END_DECL -/* +/* * platform_strerror() * - * Platform specific error message. This file is called by pj_strerror() - * in errno.c + * Platform specific error message. This file is called by pj_strerror() + * in errno.c */ -PJ_DEF(int) platform_strerror( pj_os_err_type os_errcode, - char *buf, pj_size_t bufsize) +PJ_DEF (int) platform_strerror (pj_os_err_type os_errcode, + char *buf, pj_size_t bufsize) { int len = 0; - pj_assert(buf != NULL); - pj_assert(bufsize >= 0); + pj_assert (buf != NULL); + pj_assert (bufsize >= 0); /* * MUST NOT check stack here. @@ -145,26 +147,31 @@ PJ_DEF(int) platform_strerror( pj_os_err_type os_errcode, if (!len) { #if defined(PJ_HAS_ERROR_STRING) && (PJ_HAS_ERROR_STRING!=0) - int i; + int i; + for (i = 0; gaErrorList[i].msg; ++i) { if (gaErrorList[i].code == os_errcode) { - len = strlen(gaErrorList[i].msg); - if ((pj_size_t)len >= bufsize) { - len = bufsize-1; - } - pj_memcpy(buf, gaErrorList[i].msg, len); - buf[len] = '\0'; + len = strlen (gaErrorList[i].msg); + + if ( (pj_size_t) len >= bufsize) { + len = bufsize-1; + } + + pj_memcpy (buf, gaErrorList[i].msg, len); + + buf[len] = '\0'; break; } } + #endif /* PJ_HAS_ERROR_STRING */ } if (!len) { - len = pj_ansi_snprintf( buf, bufsize, "Symbian native error %d", - os_errcode); - buf[len] = '\0'; + len = pj_ansi_snprintf (buf, bufsize, "Symbian native error %d", + os_errcode); + buf[len] = '\0'; } return len; diff --git a/sflphone-common/libs/pjproject/pjlib/src/pj/pool_policy_new.cpp b/sflphone-common/libs/pjproject/pjlib/src/pj/pool_policy_new.cpp index e22040a2f42be5a2f401f2a8a9b3dffd6c305919..6f99c068c3beede2da7c6348c89476cf1e20851b 100644 --- a/sflphone-common/libs/pjproject/pjlib/src/pj/pool_policy_new.cpp +++ b/sflphone-common/libs/pjproject/pjlib/src/pj/pool_policy_new.cpp @@ -1,5 +1,5 @@ /* $Id: pool_policy_new.cpp 2394 2008-12-23 17:27:53Z bennylp $ */ -/* +/* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org> * @@ -15,7 +15,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <pj/pool.h> #include <pj/except.h> @@ -27,76 +27,78 @@ * This file contains pool default policy definition and implementation. */ #include "pool_signature.h" - -static void *operator_new(pj_pool_factory *factory, pj_size_t size) + +static void *operator_new (pj_pool_factory *factory, pj_size_t size) { void *mem; PJ_CHECK_STACK(); if (factory->on_block_alloc) { - int rc; - rc = factory->on_block_alloc(factory, size); - if (!rc) - return NULL; + int rc; + rc = factory->on_block_alloc (factory, size); + + if (!rc) + return NULL; } - - mem = (void*) new char[size+(SIG_SIZE << 1)]; - + + mem = (void*) new char[size+ (SIG_SIZE << 1) ]; + /* Exception for new operator may be disabled, so.. */ + if (mem) { - /* Apply signature when PJ_SAFE_POOL is set. It will move - * "mem" pointer forward. - */ - APPLY_SIG(mem, size); + /* Apply signature when PJ_SAFE_POOL is set. It will move + * "mem" pointer forward. + */ + APPLY_SIG (mem, size); } return mem; } -static void operator_delete(pj_pool_factory *factory, void *mem, pj_size_t size) +static void operator_delete (pj_pool_factory *factory, void *mem, pj_size_t size) { PJ_CHECK_STACK(); - if (factory->on_block_free) - factory->on_block_free(factory, size); - + if (factory->on_block_free) + factory->on_block_free (factory, size); + /* Check and remove signature when PJ_SAFE_POOL is set. It will * move "mem" pointer backward. */ - REMOVE_SIG(mem, size); + REMOVE_SIG (mem, size); /* Note that when PJ_SAFE_POOL is set, the actual size of the block * is size + SIG_SIZE*2. */ - char *p = (char*)mem; + char *p = (char*) mem; + delete [] p; } -static void default_pool_callback(pj_pool_t *pool, pj_size_t size) +static void default_pool_callback (pj_pool_t *pool, pj_size_t size) { PJ_CHECK_STACK(); - PJ_UNUSED_ARG(pool); - PJ_UNUSED_ARG(size); + PJ_UNUSED_ARG (pool); + PJ_UNUSED_ARG (size); - PJ_THROW(PJ_NO_MEMORY_EXCEPTION); + PJ_THROW (PJ_NO_MEMORY_EXCEPTION); } -PJ_DEF_DATA(pj_pool_factory_policy) pj_pool_factory_default_policy = -{ +PJ_DEF_DATA (pj_pool_factory_policy) pj_pool_factory_default_policy = { &operator_new, &operator_delete, &default_pool_callback, 0 }; -PJ_DEF(const pj_pool_factory_policy*) pj_pool_factory_get_default_policy(void) +PJ_DEF (const pj_pool_factory_policy*) pj_pool_factory_get_default_policy (void) { return &pj_pool_factory_default_policy; } - + #endif /* PJ_HAS_POOL_ALT_API */ diff --git a/sflphone-common/libs/pjproject/pjlib/src/pj/sock_select_symbian.cpp b/sflphone-common/libs/pjproject/pjlib/src/pj/sock_select_symbian.cpp index 727bcfdf8b3783a3e984f2804c642d3ab86a37cb..48170ff6d014141c1914aa352a001d1e17eaf021 100644 --- a/sflphone-common/libs/pjproject/pjlib/src/pj/sock_select_symbian.cpp +++ b/sflphone-common/libs/pjproject/pjlib/src/pj/sock_select_symbian.cpp @@ -1,5 +1,5 @@ /* $Id: sock_select_symbian.cpp 2394 2008-12-23 17:27:53Z bennylp $ */ -/* +/* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org> * @@ -15,7 +15,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <pj/sock_select.h> #include <pj/array.h> @@ -23,140 +23,143 @@ #include <pj/os.h> #include "os_symbian.h" - -struct symbian_fd_set -{ + +struct symbian_fd_set { unsigned count; CPjSocket *sock[PJ_IOQUEUE_MAX_HANDLES]; }; -PJ_DEF(void) PJ_FD_ZERO(pj_fd_set_t *fdsetp) +PJ_DEF (void) PJ_FD_ZERO (pj_fd_set_t *fdsetp) { - symbian_fd_set *fds = (symbian_fd_set *)fdsetp; + symbian_fd_set *fds = (symbian_fd_set *) fdsetp; fds->count = 0; } -PJ_DEF(void) PJ_FD_SET(pj_sock_t fd, pj_fd_set_t *fdsetp) +PJ_DEF (void) PJ_FD_SET (pj_sock_t fd, pj_fd_set_t *fdsetp) { - symbian_fd_set *fds = (symbian_fd_set *)fdsetp; + symbian_fd_set *fds = (symbian_fd_set *) fdsetp; - PJ_ASSERT_ON_FAIL(fds->count < PJ_IOQUEUE_MAX_HANDLES, return); - fds->sock[fds->count++] = (CPjSocket*)fd; + PJ_ASSERT_ON_FAIL (fds->count < PJ_IOQUEUE_MAX_HANDLES, return); + fds->sock[fds->count++] = (CPjSocket*) fd; } -PJ_DEF(void) PJ_FD_CLR(pj_sock_t fd, pj_fd_set_t *fdsetp) +PJ_DEF (void) PJ_FD_CLR (pj_sock_t fd, pj_fd_set_t *fdsetp) { - symbian_fd_set *fds = (symbian_fd_set *)fdsetp; + symbian_fd_set *fds = (symbian_fd_set *) fdsetp; unsigned i; - + for (i=0; i<fds->count; ++i) { - if (fds->sock[i] == (CPjSocket*)fd) { - pj_array_erase(fds->sock, sizeof(fds->sock[0]), fds->count, i); - --fds->count; - return; - } + if (fds->sock[i] == (CPjSocket*) fd) { + pj_array_erase (fds->sock, sizeof (fds->sock[0]), fds->count, i); + --fds->count; + return; + } } } -PJ_DEF(pj_bool_t) PJ_FD_ISSET(pj_sock_t fd, const pj_fd_set_t *fdsetp) +PJ_DEF (pj_bool_t) PJ_FD_ISSET (pj_sock_t fd, const pj_fd_set_t *fdsetp) { - symbian_fd_set *fds = (symbian_fd_set *)fdsetp; + symbian_fd_set *fds = (symbian_fd_set *) fdsetp; unsigned i; - + for (i=0; i<fds->count; ++i) { - if (fds->sock[i] == (CPjSocket*)fd) { - return PJ_TRUE; - } + if (fds->sock[i] == (CPjSocket*) fd) { + return PJ_TRUE; + } } return PJ_FALSE; } -PJ_DEF(pj_size_t) PJ_FD_COUNT(const pj_fd_set_t *fdsetp) +PJ_DEF (pj_size_t) PJ_FD_COUNT (const pj_fd_set_t *fdsetp) { - symbian_fd_set *fds = (symbian_fd_set *)fdsetp; + symbian_fd_set *fds = (symbian_fd_set *) fdsetp; return fds->count; } -PJ_DEF(int) pj_sock_select( int n, - pj_fd_set_t *readfds, - pj_fd_set_t *writefds, - pj_fd_set_t *exceptfds, - const pj_time_val *timeout) +PJ_DEF (int) pj_sock_select (int n, + pj_fd_set_t *readfds, + pj_fd_set_t *writefds, + pj_fd_set_t *exceptfds, + const pj_time_val *timeout) { CPjTimeoutTimer *pjTimer; unsigned i; - PJ_UNUSED_ARG(n); - PJ_UNUSED_ARG(writefds); - PJ_UNUSED_ARG(exceptfds); + PJ_UNUSED_ARG (n); + PJ_UNUSED_ARG (writefds); + PJ_UNUSED_ARG (exceptfds); if (timeout) { - pjTimer = PjSymbianOS::Instance()->SelectTimeoutTimer(); - pjTimer->StartTimer(timeout->sec*1000 + timeout->msec); + pjTimer = PjSymbianOS::Instance()->SelectTimeoutTimer(); + pjTimer->StartTimer (timeout->sec*1000 + timeout->msec); } else { - pjTimer = NULL; + pjTimer = NULL; } /* Scan for readable sockets */ if (readfds) { - symbian_fd_set *fds = (symbian_fd_set *)readfds; + symbian_fd_set *fds = (symbian_fd_set *) readfds; - do { - /* Scan sockets for readily available data */ - for (i=0; i<fds->count; ++i) { - CPjSocket *pjsock = fds->sock[i]; + do { + /* Scan sockets for readily available data */ + for (i=0; i<fds->count; ++i) { + CPjSocket *pjsock = fds->sock[i]; - if (pjsock->Reader()) { - if (pjsock->Reader()->HasData() && !pjsock->Reader()->IsActive()) { + if (pjsock->Reader()) { + if (pjsock->Reader()->HasData() && !pjsock->Reader()->IsActive()) { - /* Found socket with data ready */ - PJ_FD_ZERO(readfds); - PJ_FD_SET((pj_sock_t)pjsock, readfds); + /* Found socket with data ready */ + PJ_FD_ZERO (readfds); + PJ_FD_SET ( (pj_sock_t) pjsock, readfds); - /* Cancel timer, if any */ - if (pjTimer) { - pjTimer->Cancel(); - } + /* Cancel timer, if any */ - /* Clear writable and exception fd_set */ - if (writefds) - PJ_FD_ZERO(writefds); - if (exceptfds) - PJ_FD_ZERO(exceptfds); + if (pjTimer) { + pjTimer->Cancel(); + } - return 1; + /* Clear writable and exception fd_set */ + if (writefds) + PJ_FD_ZERO (writefds); - } else if (!pjsock->Reader()->IsActive()) - pjsock->Reader()->StartRecvFrom(); + if (exceptfds) + PJ_FD_ZERO (exceptfds); - } else { - pjsock->CreateReader(); - pjsock->Reader()->StartRecvFrom(); - } - } + return 1; - PjSymbianOS::Instance()->WaitForActiveObjects(); + } else if (!pjsock->Reader()->IsActive()) + pjsock->Reader()->StartRecvFrom(); - } while (pjTimer==NULL || !pjTimer->HasTimedOut()); + } else { + pjsock->CreateReader(); + pjsock->Reader()->StartRecvFrom(); + } + } + + PjSymbianOS::Instance()->WaitForActiveObjects(); + + } while (pjTimer==NULL || !pjTimer->HasTimedOut()); } /* Timeout */ if (readfds) - PJ_FD_ZERO(readfds); + PJ_FD_ZERO (readfds); + if (writefds) - PJ_FD_ZERO(writefds); + PJ_FD_ZERO (writefds); + if (exceptfds) - PJ_FD_ZERO(exceptfds); + PJ_FD_ZERO (exceptfds); return 0; } diff --git a/sflphone-common/libs/pjproject/pjlib/src/pj/sock_symbian.cpp b/sflphone-common/libs/pjproject/pjlib/src/pj/sock_symbian.cpp index 9bffb6e760044eb81c48949ff3841db3ff3fd45c..af174cc85551b6b23beba92981108042ef90a6eb 100644 --- a/sflphone-common/libs/pjproject/pjlib/src/pj/sock_symbian.cpp +++ b/sflphone-common/libs/pjproject/pjlib/src/pj/sock_symbian.cpp @@ -1,5 +1,5 @@ /* $Id: sock_symbian.cpp 2771 2009-06-17 13:31:13Z bennylp $ */ -/* +/* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org> * @@ -15,7 +15,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <pj/sock.h> #include <pj/addr_resolv.h> @@ -92,19 +92,19 @@ CPjSocket::~CPjSocket() // Create socket reader. -CPjSocketReader *CPjSocket::CreateReader(unsigned max_len) +CPjSocketReader *CPjSocket::CreateReader (unsigned max_len) { - pj_assert(sockReader_ == NULL); - return sockReader_ = CPjSocketReader::NewL(*this, max_len); + pj_assert (sockReader_ == NULL); + return sockReader_ = CPjSocketReader::NewL (*this, max_len); } // Delete socket reader when it's not wanted. -void CPjSocket::DestroyReader() +void CPjSocket::DestroyReader() { if (sockReader_) { - sockReader_->Cancel(); - delete sockReader_; - sockReader_ = NULL; + sockReader_->Cancel(); + delete sockReader_; + sockReader_ = NULL; } } @@ -116,28 +116,28 @@ void CPjSocket::DestroyReader() // -CPjSocketReader::CPjSocketReader(CPjSocket &sock) -: CActive(EPriorityStandard), - sock_(sock), buffer_(NULL, 0), readCb_(NULL), key_(NULL) +CPjSocketReader::CPjSocketReader (CPjSocket &sock) + : CActive (EPriorityStandard), + sock_ (sock), buffer_ (NULL, 0), readCb_ (NULL), key_ (NULL) { } -void CPjSocketReader::ConstructL(unsigned max_len) +void CPjSocketReader::ConstructL (unsigned max_len) { isDatagram_ = sock_.IsDatagram(); TUint8 *ptr = new TUint8[max_len]; - buffer_.Set(ptr, 0, (TInt)max_len); - CActiveScheduler::Add(this); + buffer_.Set (ptr, 0, (TInt) max_len); + CActiveScheduler::Add (this); } -CPjSocketReader *CPjSocketReader::NewL(CPjSocket &sock, unsigned max_len) +CPjSocketReader *CPjSocketReader::NewL (CPjSocket &sock, unsigned max_len) { - CPjSocketReader *self = new (ELeave) CPjSocketReader(sock); - CleanupStack::PushL(self); - self->ConstructL(max_len); - CleanupStack::Pop(self); + CPjSocketReader *self = new (ELeave) CPjSocketReader (sock); + CleanupStack::PushL (self); + self->ConstructL (max_len); + CleanupStack::Pop (self); return self; } @@ -149,27 +149,29 @@ CPjSocketReader::~CPjSocketReader() delete [] data; } -void CPjSocketReader::StartRecv(void (*cb)(void *key), - void *key, - TDes8 *aDesc, - TUint flags) +void CPjSocketReader::StartRecv (void (*cb) (void *key), + void *key, + TDes8 *aDesc, + TUint flags) { - StartRecvFrom(cb, key, aDesc, flags, NULL); + StartRecvFrom (cb, key, aDesc, flags, NULL); } -void CPjSocketReader::StartRecvFrom(void (*cb)(void *key), - void *key, - TDes8 *aDesc, - TUint flags, - TSockAddr *fromAddr) +void CPjSocketReader::StartRecvFrom (void (*cb) (void *key), + void *key, + TDes8 *aDesc, + TUint flags, + TSockAddr *fromAddr) { readCb_ = cb; key_ = key; if (aDesc == NULL) aDesc = &buffer_; + if (fromAddr == NULL) fromAddr = &recvAddr_; - sock_.Socket().RecvFrom(*aDesc, *fromAddr, flags, iStatus); + sock_.Socket().RecvFrom (*aDesc, *fromAddr, flags, iStatus); + SetActive(); } @@ -180,40 +182,41 @@ void CPjSocketReader::DoCancel() void CPjSocketReader::RunL() { - void (*old_cb)(void *key) = readCb_; + void (*old_cb) (void *key) = readCb_; void *old_key = key_; readCb_ = NULL; key_ = NULL; if (old_cb) { - (*old_cb)(old_key); + (*old_cb) (old_key); } } // Append data to aDesc, up to aDesc's maximum size. // If socket is datagram based, buffer_ will be clared. -void CPjSocketReader::ReadData(TDes8 &aDesc, TInetAddr *addr) +void CPjSocketReader::ReadData (TDes8 &aDesc, TInetAddr *addr) { if (isDatagram_) - aDesc.Zero(); + aDesc.Zero(); if (buffer_.Length() == 0) - return; + return; TInt size_to_copy = aDesc.MaxLength() - aDesc.Length(); + if (size_to_copy > buffer_.Length()) - size_to_copy = buffer_.Length(); + size_to_copy = buffer_.Length(); - aDesc.Append(buffer_.Ptr(), size_to_copy); + aDesc.Append (buffer_.Ptr(), size_to_copy); if (isDatagram_) - buffer_.Zero(); + buffer_.Zero(); else - buffer_.Delete(0, size_to_copy); + buffer_.Delete (0, size_to_copy); if (addr) - *addr = recvAddr_; + *addr = recvAddr_; } @@ -226,10 +229,10 @@ void CPjSocketReader::ReadData(TDes8 &aDesc, TInetAddr *addr) /* * Convert 16-bit value from network byte order to host byte order. */ -PJ_DEF(pj_uint16_t) pj_ntohs(pj_uint16_t netshort) +PJ_DEF (pj_uint16_t) pj_ntohs (pj_uint16_t netshort) { #if PJ_IS_LITTLE_ENDIAN - return pj_swap16(netshort); + return pj_swap16 (netshort); #else return netshort; #endif @@ -238,10 +241,10 @@ PJ_DEF(pj_uint16_t) pj_ntohs(pj_uint16_t netshort) /* * Convert 16-bit value from host byte order to network byte order. */ -PJ_DEF(pj_uint16_t) pj_htons(pj_uint16_t hostshort) +PJ_DEF (pj_uint16_t) pj_htons (pj_uint16_t hostshort) { #if PJ_IS_LITTLE_ENDIAN - return pj_swap16(hostshort); + return pj_swap16 (hostshort); #else return hostshort; #endif @@ -250,10 +253,10 @@ PJ_DEF(pj_uint16_t) pj_htons(pj_uint16_t hostshort) /* * Convert 32-bit value from network byte order to host byte order. */ -PJ_DEF(pj_uint32_t) pj_ntohl(pj_uint32_t netlong) +PJ_DEF (pj_uint32_t) pj_ntohl (pj_uint32_t netlong) { #if PJ_IS_LITTLE_ENDIAN - return pj_swap32(netlong); + return pj_swap32 (netlong); #else return netlong; #endif @@ -262,10 +265,10 @@ PJ_DEF(pj_uint32_t) pj_ntohl(pj_uint32_t netlong) /* * Convert 32-bit value from host byte order to network byte order. */ -PJ_DEF(pj_uint32_t) pj_htonl(pj_uint32_t hostlong) +PJ_DEF (pj_uint32_t) pj_htonl (pj_uint32_t hostlong) { #if PJ_IS_LITTLE_ENDIAN - return pj_swap32(hostlong); + return pj_swap32 (hostlong); #else return netlong; #endif @@ -275,25 +278,25 @@ PJ_DEF(pj_uint32_t) pj_htonl(pj_uint32_t hostlong) * Convert an Internet host address given in network byte order * to string in standard numbers and dots notation. */ -PJ_DEF(char*) pj_inet_ntoa(pj_in_addr inaddr) +PJ_DEF (char*) pj_inet_ntoa (pj_in_addr inaddr) { - static char str8[PJ_INET_ADDRSTRLEN]; - TBuf<PJ_INET_ADDRSTRLEN> str16(0); + static char str8[PJ_INET_ADDRSTRLEN]; + TBuf<PJ_INET_ADDRSTRLEN> str16 (0); /* (Symbian IP address is in host byte order) */ - TInetAddr temp_addr((TUint32)pj_ntohl(inaddr.s_addr), (TUint)0); - temp_addr.Output(str16); - - return pj_unicode_to_ansi((const wchar_t*)str16.PtrZ(), str16.Length(), - str8, sizeof(str8)); + TInetAddr temp_addr ( (TUint32) pj_ntohl (inaddr.s_addr), (TUint) 0); + temp_addr.Output (str16); + + return pj_unicode_to_ansi ( (const wchar_t*) str16.PtrZ(), str16.Length(), + str8, sizeof (str8)); } /* * This function converts the Internet host address cp from the standard * numbers-and-dots notation into binary data and stores it in the structure - * that inp points to. + * that inp points to. */ -PJ_DEF(int) pj_inet_aton(const pj_str_t *cp, struct pj_in_addr *inp) +PJ_DEF (int) pj_inet_aton (const pj_str_t *cp, struct pj_in_addr *inp) { enum { MAXIPLEN = PJ_INET_ADDRSTRLEN }; @@ -307,48 +310,52 @@ PJ_DEF(int) pj_inet_aton(const pj_str_t *cp, struct pj_in_addr *inp) * this function might be called with cp->slen >= 16 * (i.e. when called with hostname to check if it's an IP addr). */ - PJ_ASSERT_RETURN(cp && cp->slen && inp, 0); + PJ_ASSERT_RETURN (cp && cp->slen && inp, 0); + if (cp->slen >= 16) { - return 0; + return 0; } char tempaddr8[MAXIPLEN]; - pj_memcpy(tempaddr8, cp->ptr, cp->slen); + + pj_memcpy (tempaddr8, cp->ptr, cp->slen); tempaddr8[cp->slen] = '\0'; wchar_t tempaddr16[MAXIPLEN]; - pj_ansi_to_unicode(tempaddr8, pj_ansi_strlen(tempaddr8), - tempaddr16, sizeof(tempaddr16)); + pj_ansi_to_unicode (tempaddr8, pj_ansi_strlen (tempaddr8), + tempaddr16, sizeof (tempaddr16)); - TBuf<MAXIPLEN> ip_addr((const TText*)tempaddr16); + TBuf<MAXIPLEN> ip_addr ( (const TText*) tempaddr16); TInetAddr addr; - addr.Init(KAfInet); - if (addr.Input(ip_addr) == KErrNone) { - /* Success (Symbian IP address is in host byte order) */ - inp->s_addr = pj_htonl(addr.Address()); - return 1; + addr.Init (KAfInet); + + if (addr.Input (ip_addr) == KErrNone) { + /* Success (Symbian IP address is in host byte order) */ + inp->s_addr = pj_htonl (addr.Address()); + return 1; } else { - /* Error */ - return 0; + /* Error */ + return 0; } } /* * Convert text to IPv4/IPv6 address. */ -PJ_DEF(pj_status_t) pj_inet_pton(int af, const pj_str_t *src, void *dst) +PJ_DEF (pj_status_t) pj_inet_pton (int af, const pj_str_t *src, void *dst) { char tempaddr[PJ_INET6_ADDRSTRLEN]; - PJ_ASSERT_RETURN(af==PJ_AF_INET || af==PJ_AF_INET6, PJ_EINVAL); - PJ_ASSERT_RETURN(src && src->slen && dst, PJ_EINVAL); + PJ_ASSERT_RETURN (af==PJ_AF_INET || af==PJ_AF_INET6, PJ_EINVAL); + PJ_ASSERT_RETURN (src && src->slen && dst, PJ_EINVAL); - /* Initialize output with PJ_IN_ADDR_NONE for IPv4 (to be + /* Initialize output with PJ_IN_ADDR_NONE for IPv4 (to be * compatible with pj_inet_aton() */ + if (af==PJ_AF_INET) { - ((pj_in_addr*)dst)->s_addr = PJ_INADDR_NONE; + ( (pj_in_addr*) dst)->s_addr = PJ_INADDR_NONE; } /* Caution: @@ -356,88 +363,96 @@ PJ_DEF(pj_status_t) pj_inet_pton(int af, const pj_str_t *src, void *dst) * (i.e. when called with hostname to check if it's an IP addr). */ if (src->slen >= PJ_INET6_ADDRSTRLEN) { - return PJ_ENAMETOOLONG; + return PJ_ENAMETOOLONG; } - pj_memcpy(tempaddr, src->ptr, src->slen); + pj_memcpy (tempaddr, src->ptr, src->slen); + tempaddr[src->slen] = '\0'; wchar_t tempaddr16[PJ_INET6_ADDRSTRLEN]; - pj_ansi_to_unicode(tempaddr, pj_ansi_strlen(tempaddr), - tempaddr16, sizeof(tempaddr16)); + pj_ansi_to_unicode (tempaddr, pj_ansi_strlen (tempaddr), + tempaddr16, sizeof (tempaddr16)); - TBuf<PJ_INET6_ADDRSTRLEN> ip_addr((const TText*)tempaddr16); + TBuf<PJ_INET6_ADDRSTRLEN> ip_addr ( (const TText*) tempaddr16); TInetAddr addr; - addr.Init(KAfInet6); - if (addr.Input(ip_addr) == KErrNone) { - if (af==PJ_AF_INET) { - /* Success (Symbian IP address is in host byte order) */ - pj_uint32_t ip = pj_htonl(addr.Address()); - pj_memcpy(dst, &ip, 4); - } else if (af==PJ_AF_INET6) { - const TIp6Addr & ip6 = addr.Ip6Address(); - pj_memcpy(dst, ip6.u.iAddr8, 16); - } else { - pj_assert(!"Unexpected!"); - return PJ_EBUG; - } - return PJ_SUCCESS; + addr.Init (KAfInet6); + + if (addr.Input (ip_addr) == KErrNone) { + if (af==PJ_AF_INET) { + /* Success (Symbian IP address is in host byte order) */ + pj_uint32_t ip = pj_htonl (addr.Address()); + pj_memcpy (dst, &ip, 4); + } else if (af==PJ_AF_INET6) { + const TIp6Addr & ip6 = addr.Ip6Address(); + pj_memcpy (dst, ip6.u.iAddr8, 16); + } else { + pj_assert (!"Unexpected!"); + return PJ_EBUG; + } + + return PJ_SUCCESS; } else { - /* Error */ - return PJ_EINVAL; + /* Error */ + return PJ_EINVAL; } } /* * Convert IPv4/IPv6 address to text. */ -PJ_DEF(pj_status_t) pj_inet_ntop(int af, const void *src, - char *dst, int size) +PJ_DEF (pj_status_t) pj_inet_ntop (int af, const void *src, + char *dst, int size) { - PJ_ASSERT_RETURN(src && dst && size, PJ_EINVAL); + PJ_ASSERT_RETURN (src && dst && size, PJ_EINVAL); *dst = '\0'; if (af==PJ_AF_INET) { - TBuf<PJ_INET_ADDRSTRLEN> str16; - pj_in_addr inaddr; + TBuf<PJ_INET_ADDRSTRLEN> str16; + pj_in_addr inaddr; + + if (size < PJ_INET_ADDRSTRLEN) + return PJ_ETOOSMALL; + + pj_memcpy (&inaddr, src, 4); - if (size < PJ_INET_ADDRSTRLEN) - return PJ_ETOOSMALL; + /* Symbian IP address is in host byte order */ + TInetAddr temp_addr ( (TUint32) pj_ntohl (inaddr.s_addr), (TUint) 0); - pj_memcpy(&inaddr, src, 4); + temp_addr.Output (str16); - /* Symbian IP address is in host byte order */ - TInetAddr temp_addr((TUint32)pj_ntohl(inaddr.s_addr), (TUint)0); - temp_addr.Output(str16); - - pj_unicode_to_ansi((const wchar_t*)str16.PtrZ(), str16.Length(), - dst, size); - return PJ_SUCCESS; + pj_unicode_to_ansi ( (const wchar_t*) str16.PtrZ(), str16.Length(), + dst, size); + + return PJ_SUCCESS; } else if (af==PJ_AF_INET6) { - TBuf<PJ_INET6_ADDRSTRLEN> str16; + TBuf<PJ_INET6_ADDRSTRLEN> str16; + + if (size < PJ_INET6_ADDRSTRLEN) + return PJ_ETOOSMALL; + + TIp6Addr ip6; - if (size < PJ_INET6_ADDRSTRLEN) - return PJ_ETOOSMALL; + pj_memcpy (ip6.u.iAddr8, src, 16); - TIp6Addr ip6; - pj_memcpy(ip6.u.iAddr8, src, 16); + TInetAddr temp_addr (ip6, (TUint) 0); - TInetAddr temp_addr(ip6, (TUint)0); - temp_addr.Output(str16); - - pj_unicode_to_ansi((const wchar_t*)str16.PtrZ(), str16.Length(), - dst, size); - return PJ_SUCCESS; + temp_addr.Output (str16); + + pj_unicode_to_ansi ( (const wchar_t*) str16.PtrZ(), str16.Length(), + dst, size); + + return PJ_SUCCESS; } else { - pj_assert(!"Unsupport address family"); - return PJ_EINVAL; + pj_assert (!"Unsupport address family"); + return PJ_EINVAL; } } @@ -445,7 +460,7 @@ PJ_DEF(pj_status_t) pj_inet_ntop(int af, const void *src, /* * Get hostname. */ -PJ_DEF(const pj_str_t*) pj_gethostname(void) +PJ_DEF (const pj_str_t*) pj_gethostname (void) { static char buf[PJ_MAX_HOSTNAME]; static pj_str_t hostname; @@ -453,66 +468,70 @@ PJ_DEF(const pj_str_t*) pj_gethostname(void) PJ_CHECK_STACK(); if (hostname.ptr == NULL) { - RHostResolver &resv = PjSymbianOS::Instance()->GetResolver(PJ_AF_INET); - TRequestStatus reqStatus; - THostName tmpName; + RHostResolver &resv = PjSymbianOS::Instance()->GetResolver (PJ_AF_INET); + TRequestStatus reqStatus; + THostName tmpName; - // Return empty hostname if access point is marked as down by app. - PJ_SYMBIAN_CHECK_CONNECTION2(&hostname); + // Return empty hostname if access point is marked as down by app. + PJ_SYMBIAN_CHECK_CONNECTION2 (&hostname); - resv.GetHostName(tmpName, reqStatus); - User::WaitForRequest(reqStatus); + resv.GetHostName (tmpName, reqStatus); + User::WaitForRequest (reqStatus); - hostname.ptr = pj_unicode_to_ansi((const wchar_t*)tmpName.Ptr(), tmpName.Length(), - buf, sizeof(buf)); - hostname.slen = tmpName.Length(); + hostname.ptr = pj_unicode_to_ansi ( (const wchar_t*) tmpName.Ptr(), tmpName.Length(), + buf, sizeof (buf)); + hostname.slen = tmpName.Length(); } + return &hostname; } /* * Create new socket/endpoint for communication and returns a descriptor. */ -PJ_DEF(pj_status_t) pj_sock_socket(int af, - int type, - int proto, - pj_sock_t *p_sock) +PJ_DEF (pj_status_t) pj_sock_socket (int af, + int type, + int proto, + pj_sock_t *p_sock) { TInt rc; PJ_CHECK_STACK(); /* Sanity checks. */ - PJ_ASSERT_RETURN(p_sock!=NULL, PJ_EINVAL); + PJ_ASSERT_RETURN (p_sock!=NULL, PJ_EINVAL); // Return failure if access point is marked as down by app. PJ_SYMBIAN_CHECK_CONNECTION(); - + /* Set proto if none is specified. */ + if (proto == 0) { - if (type == pj_SOCK_STREAM()) - proto = KProtocolInetTcp; - else if (type == pj_SOCK_DGRAM()) - proto = KProtocolInetUdp; + if (type == pj_SOCK_STREAM()) + proto = KProtocolInetTcp; + else if (type == pj_SOCK_DGRAM()) + proto = KProtocolInetUdp; } /* Create Symbian RSocket */ RSocket rSock; + if (PjSymbianOS::Instance()->Connection()) - rc = rSock.Open(PjSymbianOS::Instance()->SocketServ(), - af, type, proto, - *PjSymbianOS::Instance()->Connection()); + rc = rSock.Open (PjSymbianOS::Instance()->SocketServ(), + af, type, proto, + *PjSymbianOS::Instance()->Connection()); else - rc = rSock.Open(PjSymbianOS::Instance()->SocketServ(), - af, type, proto); - + rc = rSock.Open (PjSymbianOS::Instance()->SocketServ(), + af, type, proto); + if (rc != KErrNone) - return PJ_RETURN_OS_ERROR(rc); + return PJ_RETURN_OS_ERROR (rc); /* Wrap Symbian RSocket into PJLIB's CPjSocket, and return to caller */ - CPjSocket *pjSock = new CPjSocket(af, type, rSock); - *p_sock = (pj_sock_t)pjSock; + CPjSocket *pjSock = new CPjSocket (af, type, rSock); + + *p_sock = (pj_sock_t) pjSock; return PJ_SUCCESS; } @@ -521,64 +540,65 @@ PJ_DEF(pj_status_t) pj_sock_socket(int af, /* * Bind socket. */ -PJ_DEF(pj_status_t) pj_sock_bind( pj_sock_t sock, - const pj_sockaddr_t *addr, - int len) +PJ_DEF (pj_status_t) pj_sock_bind (pj_sock_t sock, + const pj_sockaddr_t *addr, + int len) { pj_status_t status; TInt rc; PJ_CHECK_STACK(); - PJ_ASSERT_RETURN(sock != 0, PJ_EINVAL); - PJ_ASSERT_RETURN(addr && len>=(int)sizeof(pj_sockaddr_in), PJ_EINVAL); + PJ_ASSERT_RETURN (sock != 0, PJ_EINVAL); + PJ_ASSERT_RETURN (addr && len>= (int) sizeof (pj_sockaddr_in), PJ_EINVAL); // Convert PJLIB's pj_sockaddr into Symbian's TInetAddr TInetAddr inetAddr; - status = PjSymbianOS::pj2Addr(*(pj_sockaddr*)addr, len, inetAddr); + status = PjSymbianOS::pj2Addr (* (pj_sockaddr*) addr, len, inetAddr); + if (status != PJ_SUCCESS) - return status; + return status; // Get the RSocket instance - RSocket &rSock = ((CPjSocket*)sock)->Socket(); + RSocket &rSock = ( (CPjSocket*) sock)->Socket(); // Bind - rc = rSock.Bind(inetAddr); + rc = rSock.Bind (inetAddr); - return (rc==KErrNone) ? PJ_SUCCESS : PJ_RETURN_OS_ERROR(rc); + return (rc==KErrNone) ? PJ_SUCCESS : PJ_RETURN_OS_ERROR (rc); } /* * Bind socket. */ -PJ_DEF(pj_status_t) pj_sock_bind_in( pj_sock_t sock, - pj_uint32_t addr32, - pj_uint16_t port) +PJ_DEF (pj_status_t) pj_sock_bind_in (pj_sock_t sock, + pj_uint32_t addr32, + pj_uint16_t port) { pj_sockaddr_in addr; PJ_CHECK_STACK(); - pj_bzero(&addr, sizeof(addr)); + pj_bzero (&addr, sizeof (addr)); addr.sin_family = PJ_AF_INET; - addr.sin_addr.s_addr = pj_htonl(addr32); - addr.sin_port = pj_htons(port); + addr.sin_addr.s_addr = pj_htonl (addr32); + addr.sin_port = pj_htons (port); - return pj_sock_bind(sock, &addr, sizeof(pj_sockaddr_in)); + return pj_sock_bind (sock, &addr, sizeof (pj_sockaddr_in)); } /* * Close socket. */ -PJ_DEF(pj_status_t) pj_sock_close(pj_sock_t sock) +PJ_DEF (pj_status_t) pj_sock_close (pj_sock_t sock) { PJ_CHECK_STACK(); - PJ_ASSERT_RETURN(sock != 0, PJ_EINVAL); + PJ_ASSERT_RETURN (sock != 0, PJ_EINVAL); - CPjSocket *pjSock = (CPjSocket*)sock; + CPjSocket *pjSock = (CPjSocket*) sock; // This will close the socket. delete pjSock; @@ -589,325 +609,334 @@ PJ_DEF(pj_status_t) pj_sock_close(pj_sock_t sock) /* * Get remote's name. */ -PJ_DEF(pj_status_t) pj_sock_getpeername( pj_sock_t sock, - pj_sockaddr_t *addr, - int *namelen) +PJ_DEF (pj_status_t) pj_sock_getpeername (pj_sock_t sock, + pj_sockaddr_t *addr, + int *namelen) { PJ_CHECK_STACK(); - - PJ_ASSERT_RETURN(sock && addr && namelen && - *namelen>=(int)sizeof(pj_sockaddr_in), PJ_EINVAL); - CPjSocket *pjSock = (CPjSocket*)sock; + PJ_ASSERT_RETURN (sock && addr && namelen && + *namelen>= (int) sizeof (pj_sockaddr_in), PJ_EINVAL); + + CPjSocket *pjSock = (CPjSocket*) sock; RSocket &rSock = pjSock->Socket(); // Socket must be connected. - PJ_ASSERT_RETURN(pjSock->IsConnected(), PJ_EINVALIDOP); + PJ_ASSERT_RETURN (pjSock->IsConnected(), PJ_EINVALIDOP); TInetAddr inetAddr; - rSock.RemoteName(inetAddr); + rSock.RemoteName (inetAddr); - return PjSymbianOS::Addr2pj(inetAddr, *(pj_sockaddr*)addr, namelen); + return PjSymbianOS::Addr2pj (inetAddr, * (pj_sockaddr*) addr, namelen); } /* * Get socket name. */ -PJ_DEF(pj_status_t) pj_sock_getsockname( pj_sock_t sock, - pj_sockaddr_t *addr, - int *namelen) +PJ_DEF (pj_status_t) pj_sock_getsockname (pj_sock_t sock, + pj_sockaddr_t *addr, + int *namelen) { PJ_CHECK_STACK(); - - PJ_ASSERT_RETURN(sock && addr && namelen && - *namelen>=(int)sizeof(pj_sockaddr_in), PJ_EINVAL); - CPjSocket *pjSock = (CPjSocket*)sock; + PJ_ASSERT_RETURN (sock && addr && namelen && + *namelen>= (int) sizeof (pj_sockaddr_in), PJ_EINVAL); + + CPjSocket *pjSock = (CPjSocket*) sock; RSocket &rSock = pjSock->Socket(); TInetAddr inetAddr; - rSock.LocalName(inetAddr); + rSock.LocalName (inetAddr); - return PjSymbianOS::Addr2pj(inetAddr, *(pj_sockaddr*)addr, namelen); + return PjSymbianOS::Addr2pj (inetAddr, * (pj_sockaddr*) addr, namelen); } /* * Send data */ -PJ_DEF(pj_status_t) pj_sock_send(pj_sock_t sock, - const void *buf, - pj_ssize_t *len, - unsigned flags) +PJ_DEF (pj_status_t) pj_sock_send (pj_sock_t sock, + const void *buf, + pj_ssize_t *len, + unsigned flags) { PJ_CHECK_STACK(); - PJ_ASSERT_RETURN(sock && buf && len, PJ_EINVAL); + PJ_ASSERT_RETURN (sock && buf && len, PJ_EINVAL); // Return failure if access point is marked as down by app. PJ_SYMBIAN_CHECK_CONNECTION(); - - CPjSocket *pjSock = (CPjSocket*)sock; + + CPjSocket *pjSock = (CPjSocket*) sock; RSocket &rSock = pjSock->Socket(); // send() should only be called to connected socket - PJ_ASSERT_RETURN(pjSock->IsConnected(), PJ_EINVALIDOP); + PJ_ASSERT_RETURN (pjSock->IsConnected(), PJ_EINVALIDOP); - TPtrC8 data((const TUint8*)buf, (TInt)*len); + TPtrC8 data ( (const TUint8*) buf, (TInt) *len); TRequestStatus reqStatus; TSockXfrLength sentLen; - rSock.Send(data, flags, reqStatus, sentLen); - User::WaitForRequest(reqStatus); + rSock.Send (data, flags, reqStatus, sentLen); + User::WaitForRequest (reqStatus); - if (reqStatus.Int()==KErrNone) { - //*len = (TInt) sentLen.Length(); - return PJ_SUCCESS; + if (reqStatus.Int() ==KErrNone) { + //*len = (TInt) sentLen.Length(); + return PJ_SUCCESS; } else - return PJ_RETURN_OS_ERROR(reqStatus.Int()); + return PJ_RETURN_OS_ERROR (reqStatus.Int()); } /* * Send data. */ -PJ_DEF(pj_status_t) pj_sock_sendto(pj_sock_t sock, - const void *buf, - pj_ssize_t *len, - unsigned flags, - const pj_sockaddr_t *to, - int tolen) +PJ_DEF (pj_status_t) pj_sock_sendto (pj_sock_t sock, + const void *buf, + pj_ssize_t *len, + unsigned flags, + const pj_sockaddr_t *to, + int tolen) { pj_status_t status; - + PJ_CHECK_STACK(); - PJ_ASSERT_RETURN(sock && buf && len, PJ_EINVAL); + PJ_ASSERT_RETURN (sock && buf && len, PJ_EINVAL); // Return failure if access point is marked as down by app. PJ_SYMBIAN_CHECK_CONNECTION(); - - CPjSocket *pjSock = (CPjSocket*)sock; + + CPjSocket *pjSock = (CPjSocket*) sock; RSocket &rSock = pjSock->Socket(); // Only supports AF_INET for now - PJ_ASSERT_RETURN(tolen>=(int)sizeof(pj_sockaddr_in), PJ_EINVAL); + PJ_ASSERT_RETURN (tolen>= (int) sizeof (pj_sockaddr_in), PJ_EINVAL); TInetAddr inetAddr; - status = PjSymbianOS::pj2Addr(*(pj_sockaddr*)to, tolen, inetAddr); + status = PjSymbianOS::pj2Addr (* (pj_sockaddr*) to, tolen, inetAddr); + if (status != PJ_SUCCESS) - return status; + return status; + + TPtrC8 data ( (const TUint8*) buf, (TInt) *len); - TPtrC8 data((const TUint8*)buf, (TInt)*len); TRequestStatus reqStatus; + TSockXfrLength sentLen; - rSock.SendTo(data, inetAddr, flags, reqStatus, sentLen); - User::WaitForRequest(reqStatus); + rSock.SendTo (data, inetAddr, flags, reqStatus, sentLen); - if (reqStatus.Int()==KErrNone) { - //For some reason TSockXfrLength is not returning correctly! - //*len = (TInt) sentLen.Length(); - return PJ_SUCCESS; - } else - return PJ_RETURN_OS_ERROR(reqStatus.Int()); + User::WaitForRequest (reqStatus); + + if (reqStatus.Int() ==KErrNone) { + //For some reason TSockXfrLength is not returning correctly! + //*len = (TInt) sentLen.Length(); + return PJ_SUCCESS; + } else + return PJ_RETURN_OS_ERROR (reqStatus.Int()); } /* * Receive data. */ -PJ_DEF(pj_status_t) pj_sock_recv(pj_sock_t sock, - void *buf, - pj_ssize_t *len, - unsigned flags) +PJ_DEF (pj_status_t) pj_sock_recv (pj_sock_t sock, + void *buf, + pj_ssize_t *len, + unsigned flags) { PJ_CHECK_STACK(); - PJ_ASSERT_RETURN(sock && buf && len, PJ_EINVAL); - PJ_ASSERT_RETURN(*len > 0, PJ_EINVAL); + PJ_ASSERT_RETURN (sock && buf && len, PJ_EINVAL); + PJ_ASSERT_RETURN (*len > 0, PJ_EINVAL); // Return failure if access point is marked as down by app. PJ_SYMBIAN_CHECK_CONNECTION(); - CPjSocket *pjSock = (CPjSocket*)sock; + CPjSocket *pjSock = (CPjSocket*) sock; if (pjSock->Reader()) { - CPjSocketReader *reader = pjSock->Reader(); + CPjSocketReader *reader = pjSock->Reader(); - while (reader->IsActive() && !reader->HasData()) { - User::WaitForAnyRequest(); - } + while (reader->IsActive() && !reader->HasData()) { + User::WaitForAnyRequest(); + } - if (reader->HasData()) { - TPtr8 data((TUint8*)buf, (TInt)*len); - TInetAddr inetAddr; + if (reader->HasData()) { + TPtr8 data ( (TUint8*) buf, (TInt) *len); + TInetAddr inetAddr; - reader->ReadData(data, &inetAddr); + reader->ReadData (data, &inetAddr); - *len = data.Length(); - return PJ_SUCCESS; - } + *len = data.Length(); + return PJ_SUCCESS; + } } TRequestStatus reqStatus; + TSockXfrLength recvLen; - TPtr8 data((TUint8*)buf, (TInt)*len, (TInt)*len); + TPtr8 data ( (TUint8*) buf, (TInt) *len, (TInt) *len); if (pjSock->IsDatagram()) { - pjSock->Socket().Recv(data, flags, reqStatus); + pjSock->Socket().Recv (data, flags, reqStatus); } else { - // Using static like this is not pretty, but we don't need to use - // the value anyway, hence doing it like this is probably most - // optimal. - static TSockXfrLength len; - pjSock->Socket().RecvOneOrMore(data, flags, reqStatus, len); + // Using static like this is not pretty, but we don't need to use + // the value anyway, hence doing it like this is probably most + // optimal. + static TSockXfrLength len; + pjSock->Socket().RecvOneOrMore (data, flags, reqStatus, len); } - User::WaitForRequest(reqStatus); + + User::WaitForRequest (reqStatus); if (reqStatus == KErrNone) { - //*len = (TInt)recvLen.Length(); - *len = data.Length(); - return PJ_SUCCESS; + //*len = (TInt)recvLen.Length(); + *len = data.Length(); + return PJ_SUCCESS; } else { - *len = -1; - return PJ_RETURN_OS_ERROR(reqStatus.Int()); + *len = -1; + return PJ_RETURN_OS_ERROR (reqStatus.Int()); } } /* * Receive data. */ -PJ_DEF(pj_status_t) pj_sock_recvfrom(pj_sock_t sock, - void *buf, - pj_ssize_t *len, - unsigned flags, - pj_sockaddr_t *from, - int *fromlen) +PJ_DEF (pj_status_t) pj_sock_recvfrom (pj_sock_t sock, + void *buf, + pj_ssize_t *len, + unsigned flags, + pj_sockaddr_t *from, + int *fromlen) { PJ_CHECK_STACK(); - PJ_ASSERT_RETURN(sock && buf && len && from && fromlen, PJ_EINVAL); - PJ_ASSERT_RETURN(*len > 0, PJ_EINVAL); - PJ_ASSERT_RETURN(*fromlen >= (int)sizeof(pj_sockaddr_in), PJ_EINVAL); + PJ_ASSERT_RETURN (sock && buf && len && from && fromlen, PJ_EINVAL); + PJ_ASSERT_RETURN (*len > 0, PJ_EINVAL); + PJ_ASSERT_RETURN (*fromlen >= (int) sizeof (pj_sockaddr_in), PJ_EINVAL); // Return failure if access point is marked as down by app. PJ_SYMBIAN_CHECK_CONNECTION(); - CPjSocket *pjSock = (CPjSocket*)sock; + CPjSocket *pjSock = (CPjSocket*) sock; RSocket &rSock = pjSock->Socket(); if (pjSock->Reader()) { - CPjSocketReader *reader = pjSock->Reader(); + CPjSocketReader *reader = pjSock->Reader(); - while (reader->IsActive() && !reader->HasData()) { - User::WaitForAnyRequest(); - } + while (reader->IsActive() && !reader->HasData()) { + User::WaitForAnyRequest(); + } - if (reader->HasData()) { - TPtr8 data((TUint8*)buf, (TInt)*len); - TInetAddr inetAddr; + if (reader->HasData()) { + TPtr8 data ( (TUint8*) buf, (TInt) *len); + TInetAddr inetAddr; - reader->ReadData(data, &inetAddr); + reader->ReadData (data, &inetAddr); - *len = data.Length(); + *len = data.Length(); - if (from && fromlen) { - return PjSymbianOS::Addr2pj(inetAddr, *(pj_sockaddr*)from, - fromlen); - } else { - return PJ_SUCCESS; - } - } + if (from && fromlen) { + return PjSymbianOS::Addr2pj (inetAddr, * (pj_sockaddr*) from, + fromlen); + } else { + return PJ_SUCCESS; + } + } } TInetAddr inetAddr; + TRequestStatus reqStatus; TSockXfrLength recvLen; - TPtr8 data((TUint8*)buf, (TInt)*len, (TInt)*len); + TPtr8 data ( (TUint8*) buf, (TInt) *len, (TInt) *len); - rSock.RecvFrom(data, inetAddr, flags, reqStatus, recvLen); - User::WaitForRequest(reqStatus); + rSock.RecvFrom (data, inetAddr, flags, reqStatus, recvLen); + User::WaitForRequest (reqStatus); if (reqStatus == KErrNone) { - //*len = (TInt)recvLen.Length(); - *len = data.Length(); - return PjSymbianOS::Addr2pj(inetAddr, *(pj_sockaddr*)from, fromlen); + //*len = (TInt)recvLen.Length(); + *len = data.Length(); + return PjSymbianOS::Addr2pj (inetAddr, * (pj_sockaddr*) from, fromlen); } else { - *len = -1; - *fromlen = -1; - return PJ_RETURN_OS_ERROR(reqStatus.Int()); + *len = -1; + *fromlen = -1; + return PJ_RETURN_OS_ERROR (reqStatus.Int()); } } /* * Get socket option. */ -PJ_DEF(pj_status_t) pj_sock_getsockopt( pj_sock_t sock, - pj_uint16_t level, - pj_uint16_t optname, - void *optval, - int *optlen) +PJ_DEF (pj_status_t) pj_sock_getsockopt (pj_sock_t sock, + pj_uint16_t level, + pj_uint16_t optname, + void *optval, + int *optlen) { // Not supported for now. - PJ_UNUSED_ARG(sock); - PJ_UNUSED_ARG(level); - PJ_UNUSED_ARG(optname); - PJ_UNUSED_ARG(optval); - PJ_UNUSED_ARG(optlen); + PJ_UNUSED_ARG (sock); + PJ_UNUSED_ARG (level); + PJ_UNUSED_ARG (optname); + PJ_UNUSED_ARG (optval); + PJ_UNUSED_ARG (optlen); return PJ_EINVALIDOP; } /* * Set socket option. */ -PJ_DEF(pj_status_t) pj_sock_setsockopt( pj_sock_t sock, - pj_uint16_t level, - pj_uint16_t optname, - const void *optval, - int optlen) +PJ_DEF (pj_status_t) pj_sock_setsockopt (pj_sock_t sock, + pj_uint16_t level, + pj_uint16_t optname, + const void *optval, + int optlen) { // Not supported for now. - PJ_UNUSED_ARG(sock); - PJ_UNUSED_ARG(level); - PJ_UNUSED_ARG(optname); - PJ_UNUSED_ARG(optval); - PJ_UNUSED_ARG(optlen); + PJ_UNUSED_ARG (sock); + PJ_UNUSED_ARG (level); + PJ_UNUSED_ARG (optname); + PJ_UNUSED_ARG (optval); + PJ_UNUSED_ARG (optlen); return PJ_EINVALIDOP; } /* * Connect socket. */ -PJ_DEF(pj_status_t) pj_sock_connect( pj_sock_t sock, - const pj_sockaddr_t *addr, - int namelen) +PJ_DEF (pj_status_t) pj_sock_connect (pj_sock_t sock, + const pj_sockaddr_t *addr, + int namelen) { pj_status_t status; - + PJ_CHECK_STACK(); - PJ_ASSERT_RETURN(sock && addr && namelen, PJ_EINVAL); - PJ_ASSERT_RETURN(((pj_sockaddr*)addr)->addr.sa_family == PJ_AF_INET, - PJ_EINVAL); + PJ_ASSERT_RETURN (sock && addr && namelen, PJ_EINVAL); + PJ_ASSERT_RETURN ( ( (pj_sockaddr*) addr)->addr.sa_family == PJ_AF_INET, + PJ_EINVAL); // Return failure if access point is marked as down by app. PJ_SYMBIAN_CHECK_CONNECTION(); - - CPjSocket *pjSock = (CPjSocket*)sock; + + CPjSocket *pjSock = (CPjSocket*) sock; RSocket &rSock = pjSock->Socket(); TInetAddr inetAddr; TRequestStatus reqStatus; - status = PjSymbianOS::pj2Addr(*(pj_sockaddr*)addr, namelen, inetAddr); + status = PjSymbianOS::pj2Addr (* (pj_sockaddr*) addr, namelen, inetAddr); + if (status != PJ_SUCCESS) - return status; + return status; - rSock.Connect(inetAddr, reqStatus); - User::WaitForRequest(reqStatus); + rSock.Connect (inetAddr, reqStatus); + + User::WaitForRequest (reqStatus); if (reqStatus == KErrNone) { - pjSock->SetConnected(true); - return PJ_SUCCESS; + pjSock->SetConnected (true); + return PJ_SUCCESS; } else { - return PJ_RETURN_OS_ERROR(reqStatus.Int()); + return PJ_RETURN_OS_ERROR (reqStatus.Int()); } } @@ -916,100 +945,104 @@ PJ_DEF(pj_status_t) pj_sock_connect( pj_sock_t sock, * Shutdown socket. */ #if PJ_HAS_TCP -PJ_DEF(pj_status_t) pj_sock_shutdown( pj_sock_t sock, - int how) +PJ_DEF (pj_status_t) pj_sock_shutdown (pj_sock_t sock, + int how) { PJ_CHECK_STACK(); - PJ_ASSERT_RETURN(sock, PJ_EINVAL); + PJ_ASSERT_RETURN (sock, PJ_EINVAL); - CPjSocket *pjSock = (CPjSocket*)sock; + CPjSocket *pjSock = (CPjSocket*) sock; RSocket &rSock = pjSock->Socket(); RSocket::TShutdown aHow; + if (how == PJ_SD_RECEIVE) - aHow = RSocket::EStopInput; + aHow = RSocket::EStopInput; else if (how == PJ_SHUT_WR) - aHow = RSocket::EStopOutput; + aHow = RSocket::EStopOutput; else - aHow = RSocket::ENormal; + aHow = RSocket::ENormal; TRequestStatus reqStatus; - rSock.Shutdown(aHow, reqStatus); - User::WaitForRequest(reqStatus); + rSock.Shutdown (aHow, reqStatus); + + User::WaitForRequest (reqStatus); if (reqStatus == KErrNone) { - return PJ_SUCCESS; + return PJ_SUCCESS; } else { - return PJ_RETURN_OS_ERROR(reqStatus.Int()); + return PJ_RETURN_OS_ERROR (reqStatus.Int()); } } /* * Start listening to incoming connections. */ -PJ_DEF(pj_status_t) pj_sock_listen( pj_sock_t sock, - int backlog) +PJ_DEF (pj_status_t) pj_sock_listen (pj_sock_t sock, + int backlog) { PJ_CHECK_STACK(); - PJ_ASSERT_RETURN(sock && backlog, PJ_EINVAL); + PJ_ASSERT_RETURN (sock && backlog, PJ_EINVAL); - CPjSocket *pjSock = (CPjSocket*)sock; + CPjSocket *pjSock = (CPjSocket*) sock; RSocket &rSock = pjSock->Socket(); - TInt rc = rSock.Listen((TUint)backlog); + TInt rc = rSock.Listen ( (TUint) backlog); if (rc == KErrNone) { - return PJ_SUCCESS; + return PJ_SUCCESS; } else { - return PJ_RETURN_OS_ERROR(rc); + return PJ_RETURN_OS_ERROR (rc); } } /* * Accept incoming connections */ -PJ_DEF(pj_status_t) pj_sock_accept( pj_sock_t serverfd, - pj_sock_t *newsock, - pj_sockaddr_t *addr, - int *addrlen) +PJ_DEF (pj_status_t) pj_sock_accept (pj_sock_t serverfd, + pj_sock_t *newsock, + pj_sockaddr_t *addr, + int *addrlen) { PJ_CHECK_STACK(); - PJ_ASSERT_RETURN(serverfd && newsock, PJ_EINVAL); + PJ_ASSERT_RETURN (serverfd && newsock, PJ_EINVAL); - CPjSocket *pjSock = (CPjSocket*)serverfd; + CPjSocket *pjSock = (CPjSocket*) serverfd; RSocket &rSock = pjSock->Socket(); // Create a 'blank' socket RSocket newSock; - newSock.Open(PjSymbianOS::Instance()->SocketServ()); + newSock.Open (PjSymbianOS::Instance()->SocketServ()); // Call Accept() TRequestStatus reqStatus; - rSock.Accept(newSock, reqStatus); - User::WaitForRequest(reqStatus); + rSock.Accept (newSock, reqStatus); + User::WaitForRequest (reqStatus); if (reqStatus != KErrNone) { - return PJ_RETURN_OS_ERROR(reqStatus.Int()); + return PJ_RETURN_OS_ERROR (reqStatus.Int()); } // Create PJ socket - CPjSocket *newPjSock = new CPjSocket(pjSock->GetAf(), pjSock->GetSockType(), - newSock); - newPjSock->SetConnected(true); + CPjSocket *newPjSock = new CPjSocket (pjSock->GetAf(), pjSock->GetSockType(), + newSock); + + newPjSock->SetConnected (true); *newsock = (pj_sock_t) newPjSock; if (addr && addrlen) { - return pj_sock_getpeername(*newsock, addr, addrlen); + return pj_sock_getpeername (*newsock, addr, addrlen); } return PJ_SUCCESS; } + #endif /* PJ_HAS_TCP */ diff --git a/sflphone-common/libs/pjproject/pjlib/src/pj/timer_symbian.cpp b/sflphone-common/libs/pjproject/pjlib/src/pj/timer_symbian.cpp index 0a9dd8a9377941880e097e731889eacf6b2f416f..4aff5f9564eed554d9d068ea04594cd4c5a7526d 100644 --- a/sflphone-common/libs/pjproject/pjlib/src/pj/timer_symbian.cpp +++ b/sflphone-common/libs/pjproject/pjlib/src/pj/timer_symbian.cpp @@ -1,5 +1,5 @@ /* $Id: timer_symbian.cpp 2394 2008-12-23 17:27:53Z bennylp $ */ -/* +/* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org> * @@ -15,7 +15,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <pj/timer.h> #include <pj/pool.h> @@ -32,8 +32,8 @@ /** * The implementation of timer heap. */ -struct pj_timer_heap_t -{ + +struct pj_timer_heap_t { /** Maximum size of the heap. */ pj_size_t max_size; @@ -49,78 +49,83 @@ struct pj_timer_heap_t /** * Active object for each timer entry. */ -class CPjTimerEntry : public CActive + +class CPjTimerEntry : public CActive { -public: - static CPjTimerEntry* NewL( pj_timer_heap_t *timer_heap, - pj_timer_entry *entry, - const pj_time_val *delay); - - ~CPjTimerEntry(); - - virtual void RunL(); - virtual void DoCancel(); - -private: - pj_timer_heap_t *timer_heap_; - pj_timer_entry *entry_; - RTimer rtimer_; - - CPjTimerEntry(pj_timer_heap_t *timer_heap, pj_timer_entry *entry); - void ConstructL(const pj_time_val *delay); + + public: + static CPjTimerEntry* NewL (pj_timer_heap_t *timer_heap, + pj_timer_entry *entry, + const pj_time_val *delay); + + ~CPjTimerEntry(); + + virtual void RunL(); + virtual void DoCancel(); + + private: + pj_timer_heap_t *timer_heap_; + pj_timer_entry *entry_; + RTimer rtimer_; + + CPjTimerEntry (pj_timer_heap_t *timer_heap, pj_timer_entry *entry); + void ConstructL (const pj_time_val *delay); }; -CPjTimerEntry::CPjTimerEntry(pj_timer_heap_t *timer_heap, - pj_timer_entry *entry) -: CActive(PJ_SYMBIAN_TIMER_PRIORITY), timer_heap_(timer_heap), entry_(entry) +CPjTimerEntry::CPjTimerEntry (pj_timer_heap_t *timer_heap, + pj_timer_entry *entry) + : CActive (PJ_SYMBIAN_TIMER_PRIORITY), timer_heap_ (timer_heap), entry_ (entry) { } -CPjTimerEntry::~CPjTimerEntry() +CPjTimerEntry::~CPjTimerEntry() { Cancel(); rtimer_.Close(); } -void CPjTimerEntry::ConstructL(const pj_time_val *delay) +void CPjTimerEntry::ConstructL (const pj_time_val *delay) { rtimer_.CreateLocal(); - CActiveScheduler::Add(this); - - pj_int32_t interval = PJ_TIME_VAL_MSEC(*delay) * 1000; + CActiveScheduler::Add (this); + + pj_int32_t interval = PJ_TIME_VAL_MSEC (*delay) * 1000; + if (interval < 0) { - interval = 0; + interval = 0; } - rtimer_.After(iStatus, interval); + + rtimer_.After (iStatus, interval); + SetActive(); } -CPjTimerEntry* CPjTimerEntry::NewL(pj_timer_heap_t *timer_heap, - pj_timer_entry *entry, - const pj_time_val *delay) +CPjTimerEntry* CPjTimerEntry::NewL (pj_timer_heap_t *timer_heap, + pj_timer_entry *entry, + const pj_time_val *delay) { - CPjTimerEntry *self = new CPjTimerEntry(timer_heap, entry); - CleanupStack::PushL(self); - self->ConstructL(delay); - CleanupStack::Pop(self); + CPjTimerEntry *self = new CPjTimerEntry (timer_heap, entry); + CleanupStack::PushL (self); + self->ConstructL (delay); + CleanupStack::Pop (self); return self; } -void CPjTimerEntry::RunL() +void CPjTimerEntry::RunL() { --timer_heap_->cur_size; entry_->_timer_id = NULL; - entry_->cb(timer_heap_, entry_); - + entry_->cb (timer_heap_, entry_); + // Finger's crossed! delete this; } -void CPjTimerEntry::DoCancel() +void CPjTimerEntry::DoCancel() { - rtimer_.Cancel(); + rtimer_.Cancel(); } @@ -130,72 +135,77 @@ void CPjTimerEntry::DoCancel() /* * Calculate memory size required to create a timer heap. */ -PJ_DEF(pj_size_t) pj_timer_heap_mem_size(pj_size_t count) +PJ_DEF (pj_size_t) pj_timer_heap_mem_size (pj_size_t count) { return /* size of the timer heap itself: */ - sizeof(pj_timer_heap_t) + - /* size of each entry: */ - (count+2) * (sizeof(pj_timer_entry*)+sizeof(pj_timer_id_t)) + - /* lock, pool etc: */ - 132; + sizeof (pj_timer_heap_t) + + /* size of each entry: */ + (count+2) * (sizeof (pj_timer_entry*) +sizeof (pj_timer_id_t)) + + /* lock, pool etc: */ + 132; } /* * Create a new timer heap. */ -PJ_DEF(pj_status_t) pj_timer_heap_create( pj_pool_t *pool, - pj_size_t size, - pj_timer_heap_t **p_heap) +PJ_DEF (pj_status_t) pj_timer_heap_create (pj_pool_t *pool, + pj_size_t size, + pj_timer_heap_t **p_heap) { pj_timer_heap_t *ht; - PJ_ASSERT_RETURN(pool && p_heap, PJ_EINVAL); + PJ_ASSERT_RETURN (pool && p_heap, PJ_EINVAL); *p_heap = NULL; /* Allocate timer heap data structure from the pool */ - ht = PJ_POOL_ALLOC_T(pool, pj_timer_heap_t); + ht = PJ_POOL_ALLOC_T (pool, pj_timer_heap_t); + if (!ht) return PJ_ENOMEM; /* Initialize timer heap sizes */ ht->max_size = size; + ht->cur_size = 0; + ht->max_entries_per_poll = DEFAULT_MAX_TIMED_OUT_PER_POLL; *p_heap = ht; + return PJ_SUCCESS; } -PJ_DEF(void) pj_timer_heap_destroy( pj_timer_heap_t *ht ) +PJ_DEF (void) pj_timer_heap_destroy (pj_timer_heap_t *ht) { - PJ_UNUSED_ARG(ht); + PJ_UNUSED_ARG (ht); } -PJ_DEF(void) pj_timer_heap_set_lock( pj_timer_heap_t *ht, +PJ_DEF (void) pj_timer_heap_set_lock (pj_timer_heap_t *ht, pj_lock_t *lock, - pj_bool_t auto_del ) + pj_bool_t auto_del) { - PJ_UNUSED_ARG(ht); + PJ_UNUSED_ARG (ht); + if (auto_del) - pj_lock_destroy(lock); + pj_lock_destroy (lock); } -PJ_DEF(unsigned) pj_timer_heap_set_max_timed_out_per_poll(pj_timer_heap_t *ht, - unsigned count ) +PJ_DEF (unsigned) pj_timer_heap_set_max_timed_out_per_poll (pj_timer_heap_t *ht, + unsigned count) { unsigned old_count = ht->max_entries_per_poll; ht->max_entries_per_poll = count; return old_count; } -PJ_DEF(pj_timer_entry*) pj_timer_entry_init( pj_timer_entry *entry, - int id, - void *user_data, - pj_timer_heap_callback *cb ) +PJ_DEF (pj_timer_entry*) pj_timer_entry_init (pj_timer_entry *entry, + int id, + void *user_data, + pj_timer_heap_callback *cb) { - pj_assert(entry && cb); + pj_assert (entry && cb); entry->_timer_id = NULL; entry->id = id; @@ -205,72 +215,74 @@ PJ_DEF(pj_timer_entry*) pj_timer_entry_init( pj_timer_entry *entry, return entry; } -PJ_DEF(pj_status_t) pj_timer_heap_schedule( pj_timer_heap_t *ht, - pj_timer_entry *entry, - const pj_time_val *delay) +PJ_DEF (pj_status_t) pj_timer_heap_schedule (pj_timer_heap_t *ht, + pj_timer_entry *entry, + const pj_time_val *delay) { CPjTimerEntry *timerObj; - - PJ_ASSERT_RETURN(ht && entry && delay, PJ_EINVAL); - PJ_ASSERT_RETURN(entry->cb != NULL, PJ_EINVAL); + + PJ_ASSERT_RETURN (ht && entry && delay, PJ_EINVAL); + PJ_ASSERT_RETURN (entry->cb != NULL, PJ_EINVAL); /* Prevent same entry from being scheduled more than once */ - PJ_ASSERT_RETURN(entry->_timer_id == NULL, PJ_EINVALIDOP); + PJ_ASSERT_RETURN (entry->_timer_id == NULL, PJ_EINVALIDOP); - timerObj = CPjTimerEntry::NewL(ht, entry, delay); + timerObj = CPjTimerEntry::NewL (ht, entry, delay); entry->_timer_id = (void*) timerObj; - + ++ht->cur_size; return PJ_SUCCESS; } -PJ_DEF(int) pj_timer_heap_cancel( pj_timer_heap_t *ht, - pj_timer_entry *entry) +PJ_DEF (int) pj_timer_heap_cancel (pj_timer_heap_t *ht, + pj_timer_entry *entry) { - PJ_ASSERT_RETURN(ht && entry, PJ_EINVAL); - + PJ_ASSERT_RETURN (ht && entry, PJ_EINVAL); + if (entry->_timer_id != NULL) { - CPjTimerEntry *timerObj = (CPjTimerEntry*) entry->_timer_id; - timerObj->Cancel(); - delete timerObj; - entry->_timer_id = NULL; - --ht->cur_size; - return 1; + CPjTimerEntry *timerObj = (CPjTimerEntry*) entry->_timer_id; + timerObj->Cancel(); + delete timerObj; + entry->_timer_id = NULL; + --ht->cur_size; + return 1; } else { - return 0; + return 0; } } -PJ_DEF(unsigned) pj_timer_heap_poll( pj_timer_heap_t *ht, - pj_time_val *next_delay ) +PJ_DEF (unsigned) pj_timer_heap_poll (pj_timer_heap_t *ht, + pj_time_val *next_delay) { /* Polling is not necessary on Symbian, since all async activities * are registered to active scheduler. */ - PJ_UNUSED_ARG(ht); + PJ_UNUSED_ARG (ht); + if (next_delay) { - next_delay->sec = 1; - next_delay->msec = 0; + next_delay->sec = 1; + next_delay->msec = 0; } + return 0; } -PJ_DEF(pj_size_t) pj_timer_heap_count( pj_timer_heap_t *ht ) +PJ_DEF (pj_size_t) pj_timer_heap_count (pj_timer_heap_t *ht) { - PJ_ASSERT_RETURN(ht, 0); + PJ_ASSERT_RETURN (ht, 0); return ht->cur_size; } -PJ_DEF(pj_status_t) pj_timer_heap_earliest_time( pj_timer_heap_t * ht, - pj_time_val *timeval) +PJ_DEF (pj_status_t) pj_timer_heap_earliest_time (pj_timer_heap_t * ht, + pj_time_val *timeval) { /* We don't support this! */ - PJ_UNUSED_ARG(ht); - + PJ_UNUSED_ARG (ht); + timeval->sec = 1; timeval->msec = 0; - + return PJ_SUCCESS; } diff --git a/sflphone-common/libs/pjproject/pjlib/src/pj/unicode_symbian.cpp b/sflphone-common/libs/pjproject/pjlib/src/pj/unicode_symbian.cpp index e9eb957f957693b1c4dd8b6e54de19feb87495fd..c1ce1e52e5a0f93886aa1ba60f22116695b8ce9b 100644 --- a/sflphone-common/libs/pjproject/pjlib/src/pj/unicode_symbian.cpp +++ b/sflphone-common/libs/pjproject/pjlib/src/pj/unicode_symbian.cpp @@ -1,5 +1,5 @@ /* $Id: unicode_symbian.cpp 2394 2008-12-23 17:27:53Z bennylp $ */ -/* +/* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org> * @@ -15,7 +15,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <pj/unicode.h> @@ -25,20 +25,20 @@ /* * Convert ANSI strings to Unicode strings. */ -PJ_DEF(wchar_t*) pj_ansi_to_unicode( const char *str, pj_size_t len, - wchar_t *wbuf, pj_size_t wbuf_count) +PJ_DEF (wchar_t*) pj_ansi_to_unicode (const char *str, pj_size_t len, + wchar_t *wbuf, pj_size_t wbuf_count) { - TPtrC8 aForeign((const TUint8*)str, (TInt)len); - TPtr16 aUnicode((TUint16*)wbuf, (TInt)(wbuf_count-1)); + TPtrC8 aForeign ( (const TUint8*) str, (TInt) len); + TPtr16 aUnicode ( (TUint16*) wbuf, (TInt) (wbuf_count-1)); TInt left; - left = PjSymbianOS::Instance()->ConvertToUnicode(aUnicode, aForeign); + left = PjSymbianOS::Instance()->ConvertToUnicode (aUnicode, aForeign); if (left != 0) { - // Error, or there are unconvertable characters - *wbuf = 0; + // Error, or there are unconvertable characters + *wbuf = 0; } else { - wbuf[len] = 0; + wbuf[len] = 0; } return wbuf; @@ -48,20 +48,20 @@ PJ_DEF(wchar_t*) pj_ansi_to_unicode( const char *str, pj_size_t len, /* * Convert Unicode string to ANSI string. */ -PJ_DEF(char*) pj_unicode_to_ansi( const wchar_t *wstr, pj_size_t len, - char *buf, pj_size_t buf_size) +PJ_DEF (char*) pj_unicode_to_ansi (const wchar_t *wstr, pj_size_t len, + char *buf, pj_size_t buf_size) { - TPtrC16 aUnicode((const TUint16*)wstr, (TInt)len); - TPtr8 aForeign((TUint8*)buf, (TInt)(buf_size-1)); + TPtrC16 aUnicode ( (const TUint16*) wstr, (TInt) len); + TPtr8 aForeign ( (TUint8*) buf, (TInt) (buf_size-1)); TInt left; - left = PjSymbianOS::Instance()->ConvertFromUnicode(aForeign, aUnicode); + left = PjSymbianOS::Instance()->ConvertFromUnicode (aForeign, aUnicode); if (left != 0) { - // Error, or there are unconvertable characters - buf[0] = '\0'; + // Error, or there are unconvertable characters + buf[0] = '\0'; } else { - buf[len] = '\0'; + buf[len] = '\0'; } return buf; diff --git a/sflphone-common/libs/pjproject/pjlib/src/pjlib++-test/main.cpp b/sflphone-common/libs/pjproject/pjlib/src/pjlib++-test/main.cpp index 6b749ad62dfba137f30cd89cc30c0d60113ab5e4..f69f4cc75a4bf3bcc3c7d2b753200a1e0d199257 100644 --- a/sflphone-common/libs/pjproject/pjlib/src/pjlib++-test/main.cpp +++ b/sflphone-common/libs/pjproject/pjlib/src/pjlib++-test/main.cpp @@ -1,5 +1,5 @@ /* $Id */ -/* +/* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org> * @@ -15,7 +15,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <pj++/file.hpp> #include <pj++/list.hpp> @@ -42,20 +42,20 @@ int main() Pj_Caching_Pool mem; Pj_Pool the_pool; Pj_Pool *pool = &the_pool; - - the_pool.attach(mem.create_pool(4000,4000)); - Pj_Semaphore_Lock lsem(pool); + the_pool.attach (mem.create_pool (4000,4000)); + + Pj_Semaphore_Lock lsem (pool); Pj_Semaphore_Lock *plsem; - plsem = new(pool) Pj_Semaphore_Lock(pool); + plsem = new (pool) Pj_Semaphore_Lock (pool); delete plsem; - Pj_Proactor proactor(pool, 100, 100); + Pj_Proactor proactor (pool, 100, 100); - My_Event_Handler *event_handler = new(the_pool) My_Event_Handler; - proactor.register_socket_handler(pool, event_handler); - proactor.unregister_handler(event_handler); + My_Event_Handler *event_handler = new (the_pool) My_Event_Handler; + proactor.register_socket_handler (pool, event_handler); + proactor.unregister_handler (event_handler); return 0; } diff --git a/sflphone-common/libs/pjproject/pjlib/src/pjlib-test/exception_wrap.cpp b/sflphone-common/libs/pjproject/pjlib/src/pjlib-test/exception_wrap.cpp index ecc542e79b7a882260bead57d95e5aba1fa0802e..d9e4b682e4a6b8441f08cf32af704dff42c401b4 100644 --- a/sflphone-common/libs/pjproject/pjlib/src/pjlib-test/exception_wrap.cpp +++ b/sflphone-common/libs/pjproject/pjlib/src/pjlib-test/exception_wrap.cpp @@ -1,5 +1,5 @@ /* $Id: exception_wrap.cpp 2873 2009-08-13 11:54:35Z nanang $ */ -/* +/* * Copyright (C) 2009 Teluu Inc. (http://www.teluu.com) * * This program is free software; you can redistribute it and/or modify @@ -14,7 +14,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* diff --git a/sflphone-common/libs/pjproject/pjlib/src/pjlib-test/main_symbian.cpp b/sflphone-common/libs/pjproject/pjlib/src/pjlib-test/main_symbian.cpp index a91b671f2cb11adf3d02369bb100a42dfa5e79fe..a0b2ec7d1986c83b8ba8b90335b15a2123c4a8fd 100644 --- a/sflphone-common/libs/pjproject/pjlib/src/pjlib-test/main_symbian.cpp +++ b/sflphone-common/libs/pjproject/pjlib/src/pjlib-test/main_symbian.cpp @@ -25,8 +25,10 @@ int main() //err = test_main(); if (err) - return err; + return err; + return exp; + //return 0; } @@ -46,31 +48,31 @@ LOCAL_D CConsoleBase* console; // write all messages to this class MyScheduler : public CActiveScheduler { -public: - MyScheduler() - {} - void Error(TInt aError) const; + public: + MyScheduler() {} + + void Error (TInt aError) const; }; -void MyScheduler::Error(TInt aError) const +void MyScheduler::Error (TInt aError) const { - PJ_UNUSED_ARG(aError); + PJ_UNUSED_ARG (aError); } LOCAL_C void DoStartL() - { +{ // Create active scheduler (to run active objects) CActiveScheduler* scheduler = new (ELeave) MyScheduler; - CleanupStack::PushL(scheduler); - CActiveScheduler::Install(scheduler); + CleanupStack::PushL (scheduler); + CActiveScheduler::Install (scheduler); test_main(); - CActiveScheduler::Install(NULL); - CleanupStack::Pop(scheduler); + CActiveScheduler::Install (NULL); + CleanupStack::Pop (scheduler); delete scheduler; - } +} #define WRITE_TO_DEBUG_CONSOLE @@ -79,55 +81,59 @@ LOCAL_C void DoStartL() #endif // Global Functions -static void log_writer(int level, const char *buf, int len) +static void log_writer (int level, const char *buf, int len) { static wchar_t buf16[PJ_LOG_MAX_SIZE]; - PJ_UNUSED_ARG(level); - - pj_ansi_to_unicode(buf, len, buf16, PJ_ARRAY_SIZE(buf16)); + PJ_UNUSED_ARG (level); + + pj_ansi_to_unicode (buf, len, buf16, PJ_ARRAY_SIZE (buf16)); buf16[len] = 0; buf16[len+1] = 0; - - TPtrC16 aBuf((const TUint16*)buf16, (TInt)len); - console->Write(aBuf); - + + TPtrC16 aBuf ( (const TUint16*) buf16, (TInt) len); + console->Write (aBuf); + #ifdef WRITE_TO_DEBUG_CONSOLE - RDebug::Print(aBuf); + RDebug::Print (aBuf); #endif } GLDEF_C TInt E32Main() - { +{ // Create cleanup stack __UHEAP_MARK; CTrapCleanup* cleanup = CTrapCleanup::New(); // Create output console - TRAPD(createError, console = Console::NewL(_L("Console"), TSize(KConsFullScreen,KConsFullScreen))); + TRAPD (createError, console = Console::NewL (_L ("Console"), TSize (KConsFullScreen,KConsFullScreen))); + if (createError) return createError; - pj_log_set_log_func(&log_writer); + pj_log_set_log_func (&log_writer); // Run application code inside TRAP harness, wait keypress when terminated - TRAPD(mainError, DoStartL()); + TRAPD (mainError, DoStartL()); + if (mainError) - console->Printf(_L(" failed, leave code = %d"), mainError); - - console->Printf(_L(" [press any key]\n")); + console->Printf (_L (" failed, leave code = %d"), mainError); + + console->Printf (_L (" [press any key]\n")); + console->Getch(); - + delete console; + delete cleanup; - - CloseSTDLIB(); - + + CloseSTDLIB(); + __UHEAP_MARKEND; - + return KErrNone; - } +} #endif /* if 0 */ diff --git a/sflphone-common/libs/pjproject/pjlib/src/pjlib-test/pool_wrap.cpp b/sflphone-common/libs/pjproject/pjlib/src/pjlib-test/pool_wrap.cpp index 381e42aee345d4da3a9025e6f150e30df638c6dc..93d64af92e08988cb64ad15063b1ea38c40caf60 100644 --- a/sflphone-common/libs/pjproject/pjlib/src/pjlib-test/pool_wrap.cpp +++ b/sflphone-common/libs/pjproject/pjlib/src/pjlib-test/pool_wrap.cpp @@ -1,5 +1,5 @@ /* $Id: pool_wrap.cpp 2873 2009-08-13 11:54:35Z nanang $ */ -/* +/* * Copyright (C) 2009 Teluu Inc. (http://www.teluu.com) * * This program is free software; you can redistribute it and/or modify @@ -14,7 +14,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* diff --git a/sflphone-common/libs/pjproject/pjlib/src/pjlib-test/test_wrap.cpp b/sflphone-common/libs/pjproject/pjlib/src/pjlib-test/test_wrap.cpp index 788bd153b4ed6e8bcaee0e7bc5dd2c456319a3c5..1f0cbc8316beaa7badb32983cda2516ea5e88f0b 100644 --- a/sflphone-common/libs/pjproject/pjlib/src/pjlib-test/test_wrap.cpp +++ b/sflphone-common/libs/pjproject/pjlib/src/pjlib-test/test_wrap.cpp @@ -1,5 +1,5 @@ /* $Id: test_wrap.cpp 2873 2009-08-13 11:54:35Z nanang $ */ -/* +/* * Copyright (C) 2009 Teluu Inc. (http://www.teluu.com) * * This program is free software; you can redistribute it and/or modify @@ -14,7 +14,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* diff --git a/sflphone-common/libs/pjproject/pjmedia/bin/pjmedia-test-x86_64-unknown-linux-gnu b/sflphone-common/libs/pjproject/pjmedia/bin/pjmedia-test-x86_64-unknown-linux-gnu index 05967a469d0b401244ce9a0ceee6f82810617d12..867e855ceb5cda2a382d9f8351d117f87f0a0fac 100755 Binary files a/sflphone-common/libs/pjproject/pjmedia/bin/pjmedia-test-x86_64-unknown-linux-gnu and b/sflphone-common/libs/pjproject/pjmedia/bin/pjmedia-test-x86_64-unknown-linux-gnu differ diff --git a/sflphone-common/libs/pjproject/pjmedia/include/pjmedia-audiodev/config.h b/sflphone-common/libs/pjproject/pjmedia/include/pjmedia-audiodev/config.h index 8de42e41f8541dfccd021ad156a9fc050c074a8e..713f252af9d469dc09db1e95669a631840586664 100644 --- a/sflphone-common/libs/pjproject/pjmedia/include/pjmedia-audiodev/config.h +++ b/sflphone-common/libs/pjproject/pjmedia/include/pjmedia-audiodev/config.h @@ -1,5 +1,5 @@ /* $Id: config.h 2833 2009-07-14 14:33:39Z nanang $ */ -/* +/* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org> * @@ -15,7 +15,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __PJMEDIA_AUDIODEV_CONFIG_H__ #define __PJMEDIA_AUDIODEV_CONFIG_H__ @@ -85,7 +85,7 @@ PJ_BEGIN_DECL /** - * This setting controls whether Symbian audio (using built-in multimedia + * This setting controls whether Symbian audio (using built-in multimedia * framework) support should be included. */ #ifndef PJMEDIA_AUDIO_DEV_HAS_SYMB_MDA @@ -96,7 +96,7 @@ PJ_BEGIN_DECL /** * This setting controls whether the Audio Device API should support * device implementation that is based on the old sound device API - * (sound.h). + * (sound.h). * * Enable this API if: * - you have implemented your own sound device using the old sound @@ -130,7 +130,7 @@ PJ_END_DECL * @{ PJMEDIA Audio Device API is a cross-platform audio API appropriate for use with -VoIP applications and many other types of audio streaming applications. +VoIP applications and many other types of audio streaming applications. The API abstracts many different audio API's on various platforms, such as: - PortAudio back-end for Win32, Windows Mobile, Linux, Unix, dan MacOS X. @@ -140,45 +140,45 @@ The API abstracts many different audio API's on various platforms, such as: - null-audio implementation - and more to be implemented in the future -The Audio Device API/library is an evolution from PJMEDIA @ref PJMED_SND and +The Audio Device API/library is an evolution from PJMEDIA @ref PJMED_SND and contains many enhancements: - Forward compatibility: \n - The new API has been designed to be extensible, it will support new API's as - well as new features that may be introduced in the future without breaking - compatibility with applications that use this API as well as compatibility - with existing device implementations. + The new API has been designed to be extensible, it will support new API's as + well as new features that may be introduced in the future without breaking + compatibility with applications that use this API as well as compatibility + with existing device implementations. - Device capabilities: \n At the heart of the API is device capabilities management, where all possible audio capabilities of audio devices should be able to be handled in a generic - manner. With this framework, new capabilities that may be discovered in the - future can be handled in manner without breaking existing applications. + manner. With this framework, new capabilities that may be discovered in the + future can be handled in manner without breaking existing applications. - Built-in features: \n - The device capabilities framework enables applications to use and control + The device capabilities framework enables applications to use and control audio features built-in in the device, such as: - - echo cancellation, - - built-in codecs, + - echo cancellation, + - built-in codecs, - audio routing (e.g. to earpiece or loudspeaker), - volume control, - etc. - Codec support: \n - Some audio devices such as Nokia/Symbian Audio Proxy Server (APS) and Nokia + Some audio devices such as Nokia/Symbian Audio Proxy Server (APS) and Nokia VoIP Audio Services (VAS) support built-in hardware audio codecs (e.g. G.729, iLBC, and AMR), and application can use the sound device in encoded mode to - make use of these hardware codecs. + make use of these hardware codecs. - Multiple backends: \n - The new API supports multiple audio backends (called factories or drivers in - the code) to be active simultaneously, and audio backends may be added or - removed during run-time. + The new API supports multiple audio backends (called factories or drivers in + the code) to be active simultaneously, and audio backends may be added or + removed during run-time. @section using Overview on using the API @@ -186,11 +186,11 @@ contains many enhancements: @subsection getting_started Getting started -# <b>Configure the application's project settings</b>.\n - Add the following + Add the following include: \code #include <pjmedia_audiodev.h>\endcode\n - And add <b>pjmedia-audiodev</b> library to your application link + And add <b>pjmedia-audiodev</b> library to your application link specifications.\n -# <b>Compile time settings</b>.\n Use the compile time settings to enable or @@ -221,7 +221,7 @@ contains many enhancements: status = pjmedia_aud_dev_get_info(dev_idx, &info); printf("%d. %s (in=%d, out=%d)\n", - dev_idx, info.name, + dev_idx, info.name, info.input_count, info.output_count); } \endcode\n @@ -266,7 +266,7 @@ Capabilities are encoded as #pjmedia_aud_dev_cap enumeration. Please see -# Info: You can set the device settings when opening audio stream by setting the flags and the appropriate setting in #pjmedia_aud_param when calling #pjmedia_aud_stream_create()\n - -# Info: Once the audio stream is running, you can retrieve or change the stream + -# Info: Once the audio stream is running, you can retrieve or change the stream setting by specifying the capability in #pjmedia_aud_stream_get_cap() and #pjmedia_aud_stream_set_cap() respectively. @@ -321,12 +321,12 @@ or both. param.ext_fmt.vad = PJ_FALSE; \endcode\n -# Note that if non-PCM format is configured on the audio stream, the - capture and/or playback functions (#pjmedia_aud_rec_cb and + capture and/or playback functions (#pjmedia_aud_rec_cb and #pjmedia_aud_play_cb respectively) will report the audio frame as #pjmedia_frame_ext structure instead of the #pjmedia_frame. -# Optionally configure other device's capabilities. The following snippet shows how to enable echo cancellation on the device (note that this - snippet may not be necessary since the setting may have been enabled + snippet may not be necessary since the setting may have been enabled when calling #pjmedia_aud_dev_default_param() above): \code if (info.caps & PJMEDIA_AUD_DEV_CAP_EC) { @@ -339,7 +339,7 @@ or both. \code pjmedia_aud_stream *stream; - status = pjmedia_aud_stream_create(¶m, &rec_cb, &play_cb, + status = pjmedia_aud_stream_create(¶m, &rec_cb, &play_cb, user_data, &stream); \endcode @@ -362,7 +362,7 @@ or both. \code // Volume setting is an unsigned integer showing the level in percent. unsigned vol; - status = pjmedia_aud_stream_get_cap(stream, + status = pjmedia_aud_stream_get_cap(stream, PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, &vol); \endcode @@ -371,7 +371,7 @@ or both. \code // Volume setting is an unsigned integer showing the level in percent. unsigned vol = 50; - status = pjmedia_aud_stream_set_cap(stream, + status = pjmedia_aud_stream_set_cap(stream, PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, &vol); \endcode diff --git a/sflphone-common/libs/pjproject/pjmedia/include/pjmedia-codec/config.h b/sflphone-common/libs/pjproject/pjmedia/include/pjmedia-codec/config.h index 627f58882322304fdccdb033f8a75f89b83d17aa..fa47a23e79a6efdbc1ee863e5dd5d116563b7288 100644 --- a/sflphone-common/libs/pjproject/pjmedia/include/pjmedia-codec/config.h +++ b/sflphone-common/libs/pjproject/pjmedia/include/pjmedia-codec/config.h @@ -1,5 +1,5 @@ /* $Id: config.h 2875 2009-08-13 15:57:26Z bennylp $ */ -/* +/* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org> * @@ -15,7 +15,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __PJMEDIA_CODEC_CONFIG_H__ #define __PJMEDIA_CODEC_CONFIG_H__ @@ -131,7 +131,7 @@ /** * Enable Intel IPP AMR codec. This also needs to be enabled when AMR WB - * codec is enabled. This option is only used when PJMEDIA_HAS_INTEL_IPP + * codec is enabled. This option is only used when PJMEDIA_HAS_INTEL_IPP * is enabled. * * Default: 1 @@ -143,7 +143,7 @@ /** * Enable Intel IPP AMR wideband codec. The PJMEDIA_HAS_INTEL_IPP_CODEC_AMR - * option must also be enabled to use this codec. This option is only used + * option must also be enabled to use this codec. This option is only used * when PJMEDIA_HAS_INTEL_IPP is enabled. * * Default: 1 @@ -279,8 +279,8 @@ #endif /** - * Default G.722.1 codec encoder and decoder level adjustment. - * If the value is non-zero, then PCM input samples to the encoder will + * Default G.722.1 codec encoder and decoder level adjustment. + * If the value is non-zero, then PCM input samples to the encoder will * be shifted right by this value, and similarly PCM output samples from * the decoder will be shifted left by this value. * @@ -294,7 +294,7 @@ /** * Enabling both G.722.1 codec implementations, internal PJMEDIA and IPP, - * may cause problem in SDP, i.e: payload types duplications. So, let's + * may cause problem in SDP, i.e: payload types duplications. So, let's * just trap such case here at compile time. * * Application can control which implementation to be used by manipulating diff --git a/sflphone-common/libs/pjproject/pjmedia/include/pjmedia/config.h b/sflphone-common/libs/pjproject/pjmedia/include/pjmedia/config.h index 6ff1cad24e43edd2019118fec1e587cbc39e230d..0ddaa6d294038aa870c00155f328194c68cc81cd 100644 --- a/sflphone-common/libs/pjproject/pjmedia/include/pjmedia/config.h +++ b/sflphone-common/libs/pjproject/pjmedia/include/pjmedia/config.h @@ -1,5 +1,5 @@ /* $Id: config.h 2850 2009-08-01 09:20:59Z bennylp $ */ -/* +/* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org> * @@ -15,7 +15,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __PJMEDIA_CONFIG_H__ #define __PJMEDIA_CONFIG_H__ @@ -45,11 +45,11 @@ #endif /** - * Specify whether we prefer to use audio switch board rather than + * Specify whether we prefer to use audio switch board rather than * conference bridge. * - * Audio switch board is a kind of simplified version of conference - * bridge, but not really the subset of conference bridge. It has + * Audio switch board is a kind of simplified version of conference + * bridge, but not really the subset of conference bridge. It has * stricter rules on audio routing among the pjmedia ports and has * no audio mixing capability. The power of it is it could work with * encoded audio frames where conference brigde couldn't. @@ -127,21 +127,21 @@ /** * This denotes implementation of WSOLA using fixed or floating point WSOLA * algorithm. This implementation provides the best quality of the result, - * at the expense of one frame delay and intensive processing power + * at the expense of one frame delay and intensive processing power * requirement. */ #define PJMEDIA_WSOLA_IMP_WSOLA 1 /** - * This denotes implementation of WSOLA algorithm with faster waveform - * similarity calculation. This implementation provides fair quality of + * This denotes implementation of WSOLA algorithm with faster waveform + * similarity calculation. This implementation provides fair quality of * the result with the main advantage of low processing power requirement. */ #define PJMEDIA_WSOLA_IMP_WSOLA_LITE 2 /** * Specify type of Waveform based Similarity Overlap and Add (WSOLA) backend - * implementation to be used. WSOLA is an algorithm to expand and/or compress + * implementation to be used. WSOLA is an algorithm to expand and/or compress * audio frames without changing the pitch, and used by the delaybuf and as PLC * backend algorithm. * @@ -154,8 +154,8 @@ /** * Specify the default maximum duration of synthetic audio that is generated - * by WSOLA. This value should be long enough to cover burst of packet losses. - * but not too long, because as the duration increases the quality would + * by WSOLA. This value should be long enough to cover burst of packet losses. + * but not too long, because as the duration increases the quality would * degrade considerably. * * Note that this limit is only applied when fading is enabled in the WSOLA @@ -184,7 +184,7 @@ /** * Specify WSOLA algorithm delay, in milliseconds. The algorithm delay is * used to merge synthetic samples with real samples in the transition - * between real to synthetic and vice versa. The longer the delay, the + * between real to synthetic and vice versa. The longer the delay, the * smoother signal to be generated, at the expense of longer latency and * a slighty more computation. * @@ -213,7 +213,7 @@ /** * Specify number of sound buffers. Larger number is better for sound * stability and to accommodate sound devices that are unable to send frames - * in timely manner, however it would probably cause more audio delay (and + * in timely manner, however it would probably cause more audio delay (and * definitely will take more memory). One individual buffer is normally 10ms * or 20 ms long, depending on ptime settings (samples_per_frame value). * @@ -296,13 +296,13 @@ */ #define PJMEDIA_RESAMPLE_NONE 1 /**< No resampling. */ #define PJMEDIA_RESAMPLE_LIBRESAMPLE 2 /**< Sample rate conversion - using libresample. */ +using libresample. */ #define PJMEDIA_RESAMPLE_SPEEX 3 /**< Sample rate conversion - using Speex. */ +using Speex. */ #define PJMEDIA_RESAMPLE_LIBSAMPLERATE 4 /**< Sample rate conversion - using libsamplerate - (a.k.a Secret Rabbit Code) - */ +using libsamplerate +(a.k.a Secret Rabbit Code) +*/ /** * Select which resample implementation to use. Currently pjmedia supports: @@ -342,7 +342,7 @@ * This (among other thing) will affect the size of buffers to be allocated * for outgoing packets. */ -#ifndef PJMEDIA_MAX_FRAME_DURATION_MS +#ifndef PJMEDIA_MAX_FRAME_DURATION_MS # define PJMEDIA_MAX_FRAME_DURATION_MS 200 #endif @@ -350,7 +350,7 @@ /** * Max packet size to support. */ -#ifndef PJMEDIA_MAX_MTU +#ifndef PJMEDIA_MAX_MTU # define PJMEDIA_MAX_MTU 1500 #endif @@ -358,7 +358,7 @@ /** * DTMF/telephone-event duration, in timestamp. */ -#ifndef PJMEDIA_DTMF_DURATION +#ifndef PJMEDIA_DTMF_DURATION # define PJMEDIA_DTMF_DURATION 1600 /* in timestamp */ #endif @@ -368,7 +368,7 @@ * remote address required to make the stream switch transmission * to the source address. */ -#ifndef PJMEDIA_RTP_NAT_PROBATION_CNT +#ifndef PJMEDIA_RTP_NAT_PROBATION_CNT # define PJMEDIA_RTP_NAT_PROBATION_CNT 10 #endif @@ -409,9 +409,9 @@ /** * Specify whether RTCP XR support should be built into PJMEDIA. Disabling - * this feature will reduce footprint slightly. Note that even when this - * setting is enabled, RTCP XR processing will only be performed in stream - * if it is enabled on run-time on per stream basis. See + * this feature will reduce footprint slightly. Note that even when this + * setting is enabled, RTCP XR processing will only be performed in stream + * if it is enabled on run-time on per stream basis. See * PJMEDIA_STREAM_ENABLE_XR setting for more info. * * Default: 1 (yes). @@ -423,7 +423,7 @@ /** * The RTCP XR feature is activated and used by stream if \a enable_rtcp_xr - * field of \a pjmedia_stream_info structure is non-zero. This setting + * field of \a pjmedia_stream_info structure is non-zero. This setting * controls the default value of this field. * * Default: 0 (disabled) @@ -442,7 +442,7 @@ * * Specify zero to disable this feature. * - * Default: 600 msec (which gives good probability that some RTP + * Default: 600 msec (which gives good probability that some RTP * packets will reach the destination, but without * filling up the jitter buffer on the remote end). */ @@ -452,13 +452,13 @@ /** - * Specify the maximum duration of silence period in the codec, in msec. + * Specify the maximum duration of silence period in the codec, in msec. * This is useful for example to keep NAT binding open in the firewall - * and to prevent server from disconnecting the call because no + * and to prevent server from disconnecting the call because no * RTP packet is received. * * This only applies to codecs that use PJMEDIA's VAD (pretty much - * everything including iLBC, except Speex, which has its own DTX + * everything including iLBC, except Speex, which has its own DTX * mechanism). * * Use (-1) to disable this feature. @@ -510,7 +510,7 @@ * remote, or should it rather use the codec preference as specified by * local endpoint. * - * For example, suppose incoming call has codec order "8 0 3", while + * For example, suppose incoming call has codec order "8 0 3", while * local codec order is "3 0 8". If remote codec order is preferable, * the selected codec will be 8, while if local codec order is preferable, * the selected codec will be 3. @@ -538,7 +538,7 @@ /** - * This macro controls whether pjmedia should include SDP rtpmap + * This macro controls whether pjmedia should include SDP rtpmap * attribute for static payload types. SDP rtpmap for static * payload types are optional, although they are normally included * for interoperability reason. @@ -592,12 +592,12 @@ #endif -/* +/* * Below specifies the various tone generator backend algorithm. */ -/** - * The math's sine(), floating point. This has very good precision +/** + * The math's sine(), floating point. This has very good precision * but it's the slowest and requires floating point support and * linking with the math library. */ @@ -613,7 +613,7 @@ /** * Fixed point using sine signal generated by Cordic algorithm. This * algorithm can be tuned to provide balance between precision and - * performance by tuning the PJMEDIA_TONEGEN_FIXED_POINT_CORDIC_LOOP + * performance by tuning the PJMEDIA_TONEGEN_FIXED_POINT_CORDIC_LOOP * setting, and may be suitable for platforms that lack floating-point * support. */ @@ -628,7 +628,7 @@ /** - * Specify the tone generator algorithm to be used. Please see + * Specify the tone generator algorithm to be used. Please see * http://trac.pjsip.org/repos/wiki/Tone_Generator for the performance * analysis results of the various tone generator algorithms. * @@ -648,7 +648,7 @@ /** * Specify the number of calculation loops to generate the tone, when * PJMEDIA_TONEGEN_FIXED_POINT_CORDIC algorithm is used. With more calculation - * loops, the tone signal gets more precise, but this will add more + * loops, the tone signal gets more precise, but this will add more * processing. * * Valid values are 1 to 28. @@ -736,8 +736,8 @@ /** * Transport info (pjmedia_transport_info) contains a socket info and list - * of transport specific info, since transports can be chained together - * (for example, SRTP transport uses UDP transport as the underlying + * of transport specific info, since transports can be chained together + * (for example, SRTP transport uses UDP transport as the underlying * transport). This constant specifies maximum number of transport specific * infos that can be held in a transport info. */ @@ -780,22 +780,22 @@ #endif /** - * Specify another type of keep-alive and NAT hole punching + * Specify another type of keep-alive and NAT hole punching * mechanism (the other type is PJMEDIA_STREAM_VAD_SUSPEND_MSEC - * and PJMEDIA_CODEC_MAX_SILENCE_PERIOD) to be used by stream. - * When this feature is enabled, the stream will initially + * and PJMEDIA_CODEC_MAX_SILENCE_PERIOD) to be used by stream. + * When this feature is enabled, the stream will initially * transmit one packet to punch a hole in NAT, and periodically * transmit keep-alive packets. * * When this alternative keep-alive mechanism is used, application - * may disable the other keep-alive mechanisms, i.e: by setting - * PJMEDIA_STREAM_VAD_SUSPEND_MSEC to zero and + * may disable the other keep-alive mechanisms, i.e: by setting + * PJMEDIA_STREAM_VAD_SUSPEND_MSEC to zero and * PJMEDIA_CODEC_MAX_SILENCE_PERIOD to -1. * * The value of this macro specifies the type of packet used * for the keep-alive mechanism. Valid values are * PJMEDIA_STREAM_KA_EMPTY_RTP and PJMEDIA_STREAM_KA_USER. - * + * * The duration of the keep-alive interval further can be set * with PJMEDIA_STREAM_KA_INTERVAL setting. * diff --git a/sflphone-common/libs/pjproject/pjmedia/src/pjmedia-audiodev/symb_aps_dev.cpp b/sflphone-common/libs/pjproject/pjmedia/src/pjmedia-audiodev/symb_aps_dev.cpp index 50236536a0c56e17ac33266512494bff2cfc64c7..5b237e4c4d23f9f214f818ab34ddd360688501f1 100644 --- a/sflphone-common/libs/pjproject/pjmedia/src/pjmedia-audiodev/symb_aps_dev.cpp +++ b/sflphone-common/libs/pjproject/pjmedia/src/pjmedia-audiodev/symb_aps_dev.cpp @@ -1,5 +1,5 @@ /* $Id: symb_aps_dev.cpp 2677 2009-05-06 15:44:12Z nanang $ */ -/* +/* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org> * @@ -15,7 +15,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <pjmedia-audiodev/audiodev_imp.h> #include <pjmedia-audiodev/errno.h> @@ -35,7 +35,7 @@ #include <APSClientSession.h> #include <pjmedia-codec/amr_helper.h> -/* Pack/unpack G.729 frame of S60 DSP codec, taken from: +/* Pack/unpack G.729 frame of S60 DSP codec, taken from: * http://wiki.forum.nokia.com/index.php/TSS000776_-_Payload_conversion_for_G.729_audio_format */ #include "s60_g729_bitstream.h" @@ -59,8 +59,8 @@ static pj_uint8_t aps_g711_frame_len; /* APS factory */ -struct aps_factory -{ + +struct aps_factory { pjmedia_aud_dev_factory base; pj_pool_t *pool; pj_pool_factory *pf; @@ -69,15 +69,16 @@ struct aps_factory /* Forward declaration of CPjAudioEngine */ + class CPjAudioEngine; /* APS stream. */ -struct aps_stream -{ + +struct aps_stream { // Base pjmedia_aud_stream base; /**< Base class. */ - + // Pool pj_pool_t *pool; /**< Memory pool. */ @@ -100,7 +101,7 @@ struct aps_stream pj_uint16_t rec_buf_len; /**< Record buffer length. */ void *strm_data; /**< Stream data. */ - /* Resampling is needed, in case audio device is opened with clock rate + /* Resampling is needed, in case audio device is opened with clock rate * other than 8kHz (only for PCM format). */ pjmedia_resample *play_resample; /**< Resampler for playback. */ @@ -117,38 +118,37 @@ struct aps_stream /* Prototypes */ -static pj_status_t factory_init(pjmedia_aud_dev_factory *f); -static pj_status_t factory_destroy(pjmedia_aud_dev_factory *f); -static unsigned factory_get_dev_count(pjmedia_aud_dev_factory *f); -static pj_status_t factory_get_dev_info(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_dev_info *info); -static pj_status_t factory_default_param(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_param *param); -static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, - const pjmedia_aud_param *param, - pjmedia_aud_rec_cb rec_cb, - pjmedia_aud_play_cb play_cb, - void *user_data, - pjmedia_aud_stream **p_aud_strm); - -static pj_status_t stream_get_param(pjmedia_aud_stream *strm, - pjmedia_aud_param *param); -static pj_status_t stream_get_cap(pjmedia_aud_stream *strm, - pjmedia_aud_dev_cap cap, - void *value); -static pj_status_t stream_set_cap(pjmedia_aud_stream *strm, - pjmedia_aud_dev_cap cap, - const void *value); -static pj_status_t stream_start(pjmedia_aud_stream *strm); -static pj_status_t stream_stop(pjmedia_aud_stream *strm); -static pj_status_t stream_destroy(pjmedia_aud_stream *strm); +static pj_status_t factory_init (pjmedia_aud_dev_factory *f); +static pj_status_t factory_destroy (pjmedia_aud_dev_factory *f); +static unsigned factory_get_dev_count (pjmedia_aud_dev_factory *f); +static pj_status_t factory_get_dev_info (pjmedia_aud_dev_factory *f, + unsigned index, + pjmedia_aud_dev_info *info); +static pj_status_t factory_default_param (pjmedia_aud_dev_factory *f, + unsigned index, + pjmedia_aud_param *param); +static pj_status_t factory_create_stream (pjmedia_aud_dev_factory *f, + const pjmedia_aud_param *param, + pjmedia_aud_rec_cb rec_cb, + pjmedia_aud_play_cb play_cb, + void *user_data, + pjmedia_aud_stream **p_aud_strm); + +static pj_status_t stream_get_param (pjmedia_aud_stream *strm, + pjmedia_aud_param *param); +static pj_status_t stream_get_cap (pjmedia_aud_stream *strm, + pjmedia_aud_dev_cap cap, + void *value); +static pj_status_t stream_set_cap (pjmedia_aud_stream *strm, + pjmedia_aud_dev_cap cap, + const void *value); +static pj_status_t stream_start (pjmedia_aud_stream *strm); +static pj_status_t stream_stop (pjmedia_aud_stream *strm); +static pj_status_t stream_destroy (pjmedia_aud_stream *strm); /* Operations */ -static pjmedia_aud_dev_factory_op factory_op = -{ +static pjmedia_aud_dev_factory_op factory_op = { &factory_init, &factory_destroy, &factory_get_dev_count, @@ -157,8 +157,7 @@ static pjmedia_aud_dev_factory_op factory_op = &factory_create_stream }; -static pjmedia_aud_stream_op stream_op = -{ +static pjmedia_aud_stream_op stream_op = { &stream_get_param, &stream_get_cap, &stream_set_cap, @@ -175,297 +174,344 @@ static pjmedia_aud_stream_op stream_op = /* * Utility: print sound device error */ -static void snd_perror(const char *title, TInt rc) +static void snd_perror (const char *title, TInt rc) { - PJ_LOG(1,(THIS_FILE, "%s (error code=%d)", title, rc)); + PJ_LOG (1, (THIS_FILE, "%s (error code=%d)", title, rc)); } -typedef void(*PjAudioCallback)(TAPSCommBuffer &buf, void *user_data); +typedef void (*PjAudioCallback) (TAPSCommBuffer &buf, void *user_data); /** * Abstract class for handler of callbacks from APS client. */ + class MQueueHandlerObserver { -public: - MQueueHandlerObserver(PjAudioCallback RecCb_, PjAudioCallback PlayCb_, - void *UserData_) - : RecCb(RecCb_), PlayCb(PlayCb_), UserData(UserData_) - {} - - virtual void InputStreamInitialized(const TInt aStatus) = 0; - virtual void OutputStreamInitialized(const TInt aStatus) = 0; - virtual void NotifyError(const TInt aError) = 0; - -public: - PjAudioCallback RecCb; - PjAudioCallback PlayCb; - void *UserData; + + public: + MQueueHandlerObserver (PjAudioCallback RecCb_, PjAudioCallback PlayCb_, + void *UserData_) + : RecCb (RecCb_), PlayCb (PlayCb_), UserData (UserData_) {} + + virtual void InputStreamInitialized (const TInt aStatus) = 0; + virtual void OutputStreamInitialized (const TInt aStatus) = 0; + virtual void NotifyError (const TInt aError) = 0; + + public: + PjAudioCallback RecCb; + PjAudioCallback PlayCb; + void *UserData; }; /** * Handler for communication and data queue. */ + class CQueueHandler : public CActive { -public: - // Types of queue handler - enum TQueueHandlerType { - ERecordCommQueue, - EPlayCommQueue, - ERecordQueue, - EPlayQueue - }; - - // The order corresponds to the APS Server state, do not change! - enum TState { - EAPSPlayerInitialize = 1, - EAPSRecorderInitialize = 2, - EAPSPlayData = 3, - EAPSRecordData = 4, - EAPSPlayerInitComplete = 5, - EAPSRecorderInitComplete = 6 - }; - - static CQueueHandler* NewL(MQueueHandlerObserver* aObserver, - RMsgQueue<TAPSCommBuffer>* aQ, - RMsgQueue<TAPSCommBuffer>* aWriteQ, - TQueueHandlerType aType) - { - CQueueHandler* self = new (ELeave) CQueueHandler(aObserver, aQ, aWriteQ, - aType); - CleanupStack::PushL(self); - self->ConstructL(); - CleanupStack::Pop(self); - return self; - } - // Destructor - ~CQueueHandler() { Cancel(); } + public: + // Types of queue handler + enum TQueueHandlerType { + ERecordCommQueue, + EPlayCommQueue, + ERecordQueue, + EPlayQueue + }; + + // The order corresponds to the APS Server state, do not change! + enum TState { + EAPSPlayerInitialize = 1, + EAPSRecorderInitialize = 2, + EAPSPlayData = 3, + EAPSRecordData = 4, + EAPSPlayerInitComplete = 5, + EAPSRecorderInitComplete = 6 + }; + + static CQueueHandler* NewL (MQueueHandlerObserver* aObserver, + RMsgQueue<TAPSCommBuffer>* aQ, + RMsgQueue<TAPSCommBuffer>* aWriteQ, + TQueueHandlerType aType) { + CQueueHandler* self = new (ELeave) CQueueHandler (aObserver, aQ, aWriteQ, + aType); + CleanupStack::PushL (self); + self->ConstructL(); + CleanupStack::Pop (self); + return self; + } - // Start listening queue event - void Start() { - iQ->NotifyDataAvailable(iStatus); - SetActive(); - } + // Destructor + ~CQueueHandler() { + Cancel(); + } -private: - // Constructor - CQueueHandler(MQueueHandlerObserver* aObserver, - RMsgQueue<TAPSCommBuffer>* aQ, - RMsgQueue<TAPSCommBuffer>* aWriteQ, - TQueueHandlerType aType) - : CActive(CActive::EPriorityHigh), - iQ(aQ), iWriteQ(aWriteQ), iObserver(aObserver), iType(aType) - { - CActiveScheduler::Add(this); - - // use lower priority for comm queues - if ((iType == ERecordCommQueue) || (iType == EPlayCommQueue)) - SetPriority(CActive::EPriorityStandard); - } + // Start listening queue event + void Start() { + iQ->NotifyDataAvailable (iStatus); + SetActive(); + } - // Second phase constructor - void ConstructL() {} + private: + // Constructor + CQueueHandler (MQueueHandlerObserver* aObserver, + RMsgQueue<TAPSCommBuffer>* aQ, + RMsgQueue<TAPSCommBuffer>* aWriteQ, + TQueueHandlerType aType) + : CActive (CActive::EPriorityHigh), + iQ (aQ), iWriteQ (aWriteQ), iObserver (aObserver), iType (aType) { + CActiveScheduler::Add (this); - // Inherited from CActive - void DoCancel() { iQ->CancelDataAvailable(); } + // use lower priority for comm queues - void RunL() { - if (iStatus != KErrNone) { - iObserver->NotifyError(iStatus.Int()); - return; + if ( (iType == ERecordCommQueue) || (iType == EPlayCommQueue)) + SetPriority (CActive::EPriorityStandard); } - TAPSCommBuffer buffer; - TInt ret = iQ->Receive(buffer); - - if (ret != KErrNone) { - iObserver->NotifyError(ret); - return; - } - - switch (iType) { - case ERecordQueue: - if (buffer.iCommand == EAPSRecordData) { - iObserver->RecCb(buffer, iObserver->UserData); - } else { - iObserver->NotifyError(buffer.iStatus); - } - break; - - // Callbacks from the APS main thread - case EPlayCommQueue: - switch (buffer.iCommand) { - case EAPSPlayData: - if (buffer.iStatus == KErrUnderflow) { - iObserver->PlayCb(buffer, iObserver->UserData); - iWriteQ->Send(buffer); - } - break; - case EAPSPlayerInitialize: - iObserver->NotifyError(buffer.iStatus); - break; - case EAPSPlayerInitComplete: - iObserver->OutputStreamInitialized(buffer.iStatus); - break; - case EAPSRecorderInitComplete: - iObserver->InputStreamInitialized(buffer.iStatus); - break; - default: - iObserver->NotifyError(buffer.iStatus); - break; - } - break; - - // Callbacks from the APS recorder thread - case ERecordCommQueue: - switch (buffer.iCommand) { - // The APS recorder thread will only report errors - // through this handler. All other callbacks will be - // sent from the APS main thread through EPlayCommQueue - case EAPSRecorderInitialize: - case EAPSRecordData: - default: - iObserver->NotifyError(buffer.iStatus); - break; - } - break; - - default: - break; + // Second phase constructor + void ConstructL() {} + + // Inherited from CActive + void DoCancel() { + iQ->CancelDataAvailable(); } - // issue next request - iQ->NotifyDataAvailable(iStatus); - SetActive(); - } + void RunL() { + if (iStatus != KErrNone) { + iObserver->NotifyError (iStatus.Int()); + return; + } - TInt RunError(TInt) { - return 0; - } + TAPSCommBuffer buffer; + + TInt ret = iQ->Receive (buffer); + + if (ret != KErrNone) { + iObserver->NotifyError (ret); + return; + } + + switch (iType) { + + case ERecordQueue: + + if (buffer.iCommand == EAPSRecordData) { + iObserver->RecCb (buffer, iObserver->UserData); + } else { + iObserver->NotifyError (buffer.iStatus); + } + + break; + + // Callbacks from the APS main thread + + case EPlayCommQueue: + + switch (buffer.iCommand) { + + case EAPSPlayData: + + if (buffer.iStatus == KErrUnderflow) { + iObserver->PlayCb (buffer, iObserver->UserData); + iWriteQ->Send (buffer); + } - // Data - RMsgQueue<TAPSCommBuffer> *iQ; // (not owned) - RMsgQueue<TAPSCommBuffer> *iWriteQ; // (not owned) - MQueueHandlerObserver *iObserver; // (not owned) - TQueueHandlerType iType; + break; + + case EAPSPlayerInitialize: + iObserver->NotifyError (buffer.iStatus); + break; + + case EAPSPlayerInitComplete: + iObserver->OutputStreamInitialized (buffer.iStatus); + break; + + case EAPSRecorderInitComplete: + iObserver->InputStreamInitialized (buffer.iStatus); + break; + + default: + iObserver->NotifyError (buffer.iStatus); + break; + } + + break; + + // Callbacks from the APS recorder thread + + case ERecordCommQueue: + + switch (buffer.iCommand) { + // The APS recorder thread will only report errors + // through this handler. All other callbacks will be + // sent from the APS main thread through EPlayCommQueue + + case EAPSRecorderInitialize: + + case EAPSRecordData: + + default: + iObserver->NotifyError (buffer.iStatus); + break; + } + + break; + + default: + break; + } + + // issue next request + iQ->NotifyDataAvailable (iStatus); + + SetActive(); + } + + TInt RunError (TInt) { + return 0; + } + + // Data + RMsgQueue<TAPSCommBuffer> *iQ; // (not owned) + RMsgQueue<TAPSCommBuffer> *iWriteQ; // (not owned) + MQueueHandlerObserver *iObserver; // (not owned) + TQueueHandlerType iType; }; /* * Audio setting for CPjAudioEngine. */ + class CPjAudioSetting { -public: - TFourCC fourcc; - TAPSCodecMode mode; - TBool plc; - TBool vad; - TBool cng; - TBool loudspk; + + public: + TFourCC fourcc; + TAPSCodecMode mode; + TBool plc; + TBool vad; + TBool cng; + TBool loudspk; }; /* * Implementation: Symbian Input & Output Stream. */ + class CPjAudioEngine : public CBase, MQueueHandlerObserver { -public: - enum State - { - STATE_NULL, - STATE_INITIALIZING, - STATE_READY, - STATE_STREAMING, - STATE_PENDING_STOP - }; - - ~CPjAudioEngine(); - - static CPjAudioEngine *NewL(struct aps_stream *parent_strm, - PjAudioCallback rec_cb, - PjAudioCallback play_cb, - void *user_data, - const CPjAudioSetting &setting); - - TInt StartL(); - void Stop(); - - TInt ActivateSpeaker(TBool active); - - TInt SetVolume(TInt vol) { return iSession.SetVolume(vol); } - TInt GetVolume() { return iSession.Volume(); } - TInt GetMaxVolume() { return iSession.MaxVolume(); } - - TInt SetGain(TInt gain) { return iSession.SetGain(gain); } - TInt GetGain() { return iSession.Gain(); } - TInt GetMaxGain() { return iSession.MaxGain(); } - -private: - CPjAudioEngine(struct aps_stream *parent_strm, - PjAudioCallback rec_cb, - PjAudioCallback play_cb, - void *user_data, - const CPjAudioSetting &setting); - void ConstructL(); - - TInt InitPlayL(); - TInt InitRecL(); - TInt StartStreamL(); - - // Inherited from MQueueHandlerObserver - virtual void InputStreamInitialized(const TInt aStatus); - virtual void OutputStreamInitialized(const TInt aStatus); - virtual void NotifyError(const TInt aError); - - State state_; - struct aps_stream *parentStrm_; - CPjAudioSetting setting_; - - RAPSSession iSession; - TAPSInitSettings iPlaySettings; - TAPSInitSettings iRecSettings; - - RMsgQueue<TAPSCommBuffer> iReadQ; - RMsgQueue<TAPSCommBuffer> iReadCommQ; - RMsgQueue<TAPSCommBuffer> iWriteQ; - RMsgQueue<TAPSCommBuffer> iWriteCommQ; - - CQueueHandler *iPlayCommHandler; - CQueueHandler *iRecCommHandler; - CQueueHandler *iRecHandler; + + public: + enum State { + STATE_NULL, + STATE_INITIALIZING, + STATE_READY, + STATE_STREAMING, + STATE_PENDING_STOP + }; + + ~CPjAudioEngine(); + + static CPjAudioEngine *NewL (struct aps_stream *parent_strm, + PjAudioCallback rec_cb, + PjAudioCallback play_cb, + void *user_data, + const CPjAudioSetting &setting); + + TInt StartL(); + void Stop(); + + TInt ActivateSpeaker (TBool active); + + TInt SetVolume (TInt vol) { + return iSession.SetVolume (vol); + } + + TInt GetVolume() { + return iSession.Volume(); + } + + TInt GetMaxVolume() { + return iSession.MaxVolume(); + } + + TInt SetGain (TInt gain) { + return iSession.SetGain (gain); + } + + TInt GetGain() { + return iSession.Gain(); + } + + TInt GetMaxGain() { + return iSession.MaxGain(); + } + + private: + CPjAudioEngine (struct aps_stream *parent_strm, + PjAudioCallback rec_cb, + PjAudioCallback play_cb, + void *user_data, + const CPjAudioSetting &setting); + void ConstructL(); + + TInt InitPlayL(); + TInt InitRecL(); + TInt StartStreamL(); + + // Inherited from MQueueHandlerObserver + virtual void InputStreamInitialized (const TInt aStatus); + virtual void OutputStreamInitialized (const TInt aStatus); + virtual void NotifyError (const TInt aError); + + State state_; + + struct aps_stream *parentStrm_; + CPjAudioSetting setting_; + + RAPSSession iSession; + TAPSInitSettings iPlaySettings; + TAPSInitSettings iRecSettings; + + RMsgQueue<TAPSCommBuffer> iReadQ; + RMsgQueue<TAPSCommBuffer> iReadCommQ; + RMsgQueue<TAPSCommBuffer> iWriteQ; + RMsgQueue<TAPSCommBuffer> iWriteCommQ; + + CQueueHandler *iPlayCommHandler; + CQueueHandler *iRecCommHandler; + CQueueHandler *iRecHandler; }; -CPjAudioEngine* CPjAudioEngine::NewL(struct aps_stream *parent_strm, - PjAudioCallback rec_cb, - PjAudioCallback play_cb, - void *user_data, - const CPjAudioSetting &setting) +CPjAudioEngine* CPjAudioEngine::NewL (struct aps_stream *parent_strm, + PjAudioCallback rec_cb, + PjAudioCallback play_cb, + void *user_data, + const CPjAudioSetting &setting) { - CPjAudioEngine* self = new (ELeave) CPjAudioEngine(parent_strm, - rec_cb, play_cb, - user_data, - setting); - CleanupStack::PushL(self); + CPjAudioEngine* self = new (ELeave) CPjAudioEngine (parent_strm, + rec_cb, play_cb, + user_data, + setting); + CleanupStack::PushL (self); self->ConstructL(); - CleanupStack::Pop(self); + CleanupStack::Pop (self); return self; } -CPjAudioEngine::CPjAudioEngine(struct aps_stream *parent_strm, - PjAudioCallback rec_cb, - PjAudioCallback play_cb, - void *user_data, - const CPjAudioSetting &setting) - : MQueueHandlerObserver(rec_cb, play_cb, user_data), - state_(STATE_NULL), - parentStrm_(parent_strm), - setting_(setting), - iPlayCommHandler(0), - iRecCommHandler(0), - iRecHandler(0) +CPjAudioEngine::CPjAudioEngine (struct aps_stream *parent_strm, + PjAudioCallback rec_cb, + PjAudioCallback play_cb, + void *user_data, + const CPjAudioSetting &setting) + : MQueueHandlerObserver (rec_cb, play_cb, user_data), + state_ (STATE_NULL), + parentStrm_ (parent_strm), + setting_ (setting), + iPlayCommHandler (0), + iRecCommHandler (0), + iRecHandler (0) { } @@ -482,49 +528,57 @@ CPjAudioEngine::~CPjAudioEngine() // the client session. TTime start, now; enum { APS_CLOSE_WAIT_TIME = 200 }; /* in msecs */ - + start.UniversalTime(); + do { - pj_symbianos_poll(-1, APS_CLOSE_WAIT_TIME); - now.UniversalTime(); - } while (now.MicroSecondsFrom(start) < APS_CLOSE_WAIT_TIME * 1000); + pj_symbianos_poll (-1, APS_CLOSE_WAIT_TIME); + now.UniversalTime(); + } while (now.MicroSecondsFrom (start) < APS_CLOSE_WAIT_TIME * 1000); iSession.Close(); if (state_ == STATE_READY) { - if (parentStrm_->param.dir != PJMEDIA_DIR_PLAYBACK) { - iReadQ.Close(); - iReadCommQ.Close(); - } - iWriteQ.Close(); - iWriteCommQ.Close(); + if (parentStrm_->param.dir != PJMEDIA_DIR_PLAYBACK) { + iReadQ.Close(); + iReadCommQ.Close(); + } + + iWriteQ.Close(); + + iWriteCommQ.Close(); } - - TRACE_((THIS_FILE, "Sound device destroyed")); + + TRACE_ ( (THIS_FILE, "Sound device destroyed")); } TInt CPjAudioEngine::InitPlayL() { - TInt err = iSession.InitializePlayer(iPlaySettings); + TInt err = iSession.InitializePlayer (iPlaySettings); + if (err != KErrNone) { - snd_perror("Failed to initialize player", err); - return err; + snd_perror ("Failed to initialize player", err); + return err; } // Open message queues for the output stream TBuf<128> buf2 = iPlaySettings.iGlobal; - buf2.Append(_L("PlayQueue")); + + buf2.Append (_L ("PlayQueue")); + TBuf<128> buf3 = iPlaySettings.iGlobal; - buf3.Append(_L("PlayCommQueue")); - while (iWriteQ.OpenGlobal(buf2)) - User::After(10); - while (iWriteCommQ.OpenGlobal(buf3)) - User::After(10); + buf3.Append (_L ("PlayCommQueue")); + + while (iWriteQ.OpenGlobal (buf2)) + User::After (10); + + while (iWriteCommQ.OpenGlobal (buf3)) + User::After (10); // Construct message queue handler - iPlayCommHandler = CQueueHandler::NewL(this, &iWriteCommQ, &iWriteQ, - CQueueHandler::EPlayCommQueue); + iPlayCommHandler = CQueueHandler::NewL (this, &iWriteCommQ, &iWriteQ, + CQueueHandler::EPlayCommQueue); // Start observing APS callbacks on output stream message queue iPlayCommHandler->Start(); @@ -535,32 +589,38 @@ TInt CPjAudioEngine::InitPlayL() TInt CPjAudioEngine::InitRecL() { // Initialize input stream device - TInt err = iSession.InitializeRecorder(iRecSettings); + TInt err = iSession.InitializeRecorder (iRecSettings); + if (err != KErrNone && err != KErrAlreadyExists) { - snd_perror("Failed to initialize recorder", err); - return err; + snd_perror ("Failed to initialize recorder", err); + return err; } TBuf<128> buf1 = iRecSettings.iGlobal; - buf1.Append(_L("RecordQueue")); + + buf1.Append (_L ("RecordQueue")); TBuf<128> buf4 = iRecSettings.iGlobal; - buf4.Append(_L("RecordCommQueue")); + buf4.Append (_L ("RecordCommQueue")); // Must wait for APS thread to finish creating message queues // before we can open and use them. - while (iReadQ.OpenGlobal(buf1)) - User::After(10); - while (iReadCommQ.OpenGlobal(buf4)) - User::After(10); + + while (iReadQ.OpenGlobal (buf1)) + User::After (10); + + while (iReadCommQ.OpenGlobal (buf4)) + User::After (10); // Construct message queue handlers - iRecHandler = CQueueHandler::NewL(this, &iReadQ, NULL, - CQueueHandler::ERecordQueue); - iRecCommHandler = CQueueHandler::NewL(this, &iReadCommQ, NULL, - CQueueHandler::ERecordCommQueue); + iRecHandler = CQueueHandler::NewL (this, &iReadQ, NULL, + CQueueHandler::ERecordQueue); + + iRecCommHandler = CQueueHandler::NewL (this, &iReadCommQ, NULL, + CQueueHandler::ERecordCommQueue); // Start observing APS callbacks from on input stream message queue iRecHandler->Start(); + iRecCommHandler->Start(); return 0; @@ -569,10 +629,10 @@ TInt CPjAudioEngine::InitRecL() TInt CPjAudioEngine::StartL() { if (state_ == STATE_READY) - return StartStreamL(); + return StartStreamL(); + + PJ_ASSERT_RETURN (state_ == STATE_NULL, PJMEDIA_EAUD_INVOP); - PJ_ASSERT_RETURN(state_ == STATE_NULL, PJMEDIA_EAUD_INVOP); - // Even if only capturer are opened, playback thread of APS Server need // to be run(?). Since some messages will be delivered via play comm queue. state_ = STATE_INITIALIZING; @@ -583,17 +643,18 @@ TInt CPjAudioEngine::StartL() void CPjAudioEngine::Stop() { if (state_ == STATE_STREAMING) { - iSession.Stop(); - state_ = STATE_READY; - TRACE_((THIS_FILE, "Sound device stopped")); + iSession.Stop(); + state_ = STATE_READY; + TRACE_ ( (THIS_FILE, "Sound device stopped")); } else if (state_ == STATE_INITIALIZING) { - // Initialization is on progress, so let's set the state to - // STATE_PENDING_STOP to prevent it starting the stream. - state_ = STATE_PENDING_STOP; - - // Then wait until initialization done. - while (state_ != STATE_READY) - pj_symbianos_poll(-1, 100); + // Initialization is on progress, so let's set the state to + // STATE_PENDING_STOP to prevent it starting the stream. + state_ = STATE_PENDING_STOP; + + // Then wait until initialization done. + + while (state_ != STATE_READY) + pj_symbianos_poll (-1, 100); } } @@ -602,94 +663,96 @@ void CPjAudioEngine::ConstructL() // Recorder settings iRecSettings.iFourCC = setting_.fourcc; iRecSettings.iGlobal = APP_UID; - iRecSettings.iPriority = TMdaPriority(100); - iRecSettings.iPreference = TMdaPriorityPreference(0x05210001); + iRecSettings.iPriority = TMdaPriority (100); + iRecSettings.iPreference = TMdaPriorityPreference (0x05210001); iRecSettings.iSettings.iChannels = EMMFMono; iRecSettings.iSettings.iSampleRate = EMMFSampleRate8000Hz; // Player settings iPlaySettings.iFourCC = setting_.fourcc; iPlaySettings.iGlobal = APP_UID; - iPlaySettings.iPriority = TMdaPriority(100); - iPlaySettings.iPreference = TMdaPriorityPreference(0x05220001); + iPlaySettings.iPriority = TMdaPriority (100); + iPlaySettings.iPreference = TMdaPriorityPreference (0x05220001); iPlaySettings.iSettings.iChannels = EMMFMono; iPlaySettings.iSettings.iSampleRate = EMMFSampleRate8000Hz; iPlaySettings.iSettings.iVolume = 0; - User::LeaveIfError(iSession.Connect()); + User::LeaveIfError (iSession.Connect()); } TInt CPjAudioEngine::StartStreamL() { - pj_assert(state_==STATE_READY || state_==STATE_INITIALIZING); - - iSession.SetCng(setting_.cng); - iSession.SetVadMode(setting_.vad); - iSession.SetPlc(setting_.plc); - iSession.SetEncoderMode(setting_.mode); - iSession.SetDecoderMode(setting_.mode); - iSession.ActivateLoudspeaker(setting_.loudspk); + pj_assert (state_==STATE_READY || state_==STATE_INITIALIZING); + + iSession.SetCng (setting_.cng); + iSession.SetVadMode (setting_.vad); + iSession.SetPlc (setting_.plc); + iSession.SetEncoderMode (setting_.mode); + iSession.SetDecoderMode (setting_.mode); + iSession.ActivateLoudspeaker (setting_.loudspk); // Not only capture + if (parentStrm_->param.dir != PJMEDIA_DIR_CAPTURE) { - iSession.Write(); - TRACE_((THIS_FILE, "Player started")); + iSession.Write(); + TRACE_ ( (THIS_FILE, "Player started")); } // Not only playback if (parentStrm_->param.dir != PJMEDIA_DIR_PLAYBACK) { - iSession.Read(); - TRACE_((THIS_FILE, "Recorder started")); + iSession.Read(); + TRACE_ ( (THIS_FILE, "Recorder started")); } state_ = STATE_STREAMING; - + return 0; } -void CPjAudioEngine::InputStreamInitialized(const TInt aStatus) +void CPjAudioEngine::InputStreamInitialized (const TInt aStatus) { - TRACE_((THIS_FILE, "Recorder initialized, err=%d", aStatus)); + TRACE_ ( (THIS_FILE, "Recorder initialized, err=%d", aStatus)); if (aStatus == KErrNone) { - // Don't start the stream since Stop() has been requested. - if (state_ != STATE_PENDING_STOP) { - StartStreamL(); - } else { - state_ = STATE_READY; - } + // Don't start the stream since Stop() has been requested. + if (state_ != STATE_PENDING_STOP) { + StartStreamL(); + } else { + state_ = STATE_READY; + } } } -void CPjAudioEngine::OutputStreamInitialized(const TInt aStatus) +void CPjAudioEngine::OutputStreamInitialized (const TInt aStatus) { - TRACE_((THIS_FILE, "Player initialized, err=%d", aStatus)); + TRACE_ ( (THIS_FILE, "Player initialized, err=%d", aStatus)); if (aStatus == KErrNone) { - if (parentStrm_->param.dir == PJMEDIA_DIR_PLAYBACK) { - // Don't start the stream since Stop() has been requested. - if (state_ != STATE_PENDING_STOP) { - StartStreamL(); - } else { - state_ = STATE_READY; - } - } else - InitRecL(); + if (parentStrm_->param.dir == PJMEDIA_DIR_PLAYBACK) { + // Don't start the stream since Stop() has been requested. + if (state_ != STATE_PENDING_STOP) { + StartStreamL(); + } else { + state_ = STATE_READY; + } + } else + InitRecL(); } } -void CPjAudioEngine::NotifyError(const TInt aError) +void CPjAudioEngine::NotifyError (const TInt aError) { - snd_perror("Error from CQueueHandler", aError); + snd_perror ("Error from CQueueHandler", aError); } -TInt CPjAudioEngine::ActivateSpeaker(TBool active) +TInt CPjAudioEngine::ActivateSpeaker (TBool active) { if (state_ == STATE_READY || state_ == STATE_STREAMING) { - iSession.ActivateLoudspeaker(active); - TRACE_((THIS_FILE, "Loudspeaker turned %s", (active? "on":"off"))); - return KErrNone; + iSession.ActivateLoudspeaker (active); + TRACE_ ( (THIS_FILE, "Loudspeaker turned %s", (active? "on":"off"))); + return KErrNone; } + return KErrNotReady; } @@ -697,20 +760,22 @@ TInt CPjAudioEngine::ActivateSpeaker(TBool active) * Internal APS callbacks for PCM format */ -static void RecCbPcm(TAPSCommBuffer &buf, void *user_data) +static void RecCbPcm (TAPSCommBuffer &buf, void *user_data) { + struct aps_stream *strm = (struct aps_stream*) user_data; /* Buffer has to contain normal speech. */ - pj_assert(buf.iBuffer[0] == 1 && buf.iBuffer[1] == 0); + pj_assert (buf.iBuffer[0] == 1 && buf.iBuffer[1] == 0); /* Detect the recorder G.711 frame size, player frame size will follow * this recorder frame size. */ + if (aps_g711_frame_len == 0) { - aps_g711_frame_len = buf.iBuffer.Length() < 160? 80 : 160; - TRACE_((THIS_FILE, "Detected APS G.711 frame size = %u samples", - aps_g711_frame_len)); + aps_g711_frame_len = buf.iBuffer.Length() < 160? 80 : 160; + TRACE_ ( (THIS_FILE, "Detected APS G.711 frame size = %u samples", + aps_g711_frame_len)); } /* Decode APS buffer (coded in G.711) and put the PCM result into rec_buf. @@ -719,68 +784,75 @@ static void RecCbPcm(TAPSCommBuffer &buf, void *user_data) unsigned samples_processed = 0; while (samples_processed < aps_g711_frame_len) { - unsigned samples_to_process; - unsigned samples_req; - - samples_to_process = aps_g711_frame_len - samples_processed; - samples_req = (strm->param.samples_per_frame / - strm->param.channel_count / - strm->resample_factor) - - strm->rec_buf_len; - if (samples_to_process > samples_req) - samples_to_process = samples_req; - - pjmedia_ulaw_decode(&strm->rec_buf[strm->rec_buf_len], - buf.iBuffer.Ptr() + 2 + samples_processed, - samples_to_process); - - strm->rec_buf_len += samples_to_process; - samples_processed += samples_to_process; - - /* Buffer is full, time to call parent callback */ - if (strm->rec_buf_len == strm->param.samples_per_frame / - strm->param.channel_count / - strm->resample_factor) - { - pjmedia_frame f; - - /* Need to resample clock rate? */ - if (strm->rec_resample) { - unsigned resampled = 0; - - while (resampled < strm->rec_buf_len) { - pjmedia_resample_run(strm->rec_resample, - &strm->rec_buf[resampled], - strm->pcm_buf + - resampled * strm->resample_factor); - resampled += 80; - } - f.buf = strm->pcm_buf; - } else { - f.buf = strm->rec_buf; - } - - /* Need to convert channel count? */ - if (strm->param.channel_count != 1) { - pjmedia_convert_channel_1ton((pj_int16_t*)f.buf, - (pj_int16_t*)f.buf, - strm->param.channel_count, - strm->param.samples_per_frame / - strm->param.channel_count, - 0); - } - - /* Call parent callback */ - f.type = PJMEDIA_FRAME_TYPE_AUDIO; - f.size = strm->param.samples_per_frame << 1; - strm->rec_cb(strm->user_data, &f); - strm->rec_buf_len = 0; - } + unsigned samples_to_process; + unsigned samples_req; + + samples_to_process = aps_g711_frame_len - samples_processed; + samples_req = (strm->param.samples_per_frame / + strm->param.channel_count / + strm->resample_factor) - + strm->rec_buf_len; + + if (samples_to_process > samples_req) + samples_to_process = samples_req; + + pjmedia_ulaw_decode (&strm->rec_buf[strm->rec_buf_len], + buf.iBuffer.Ptr() + 2 + samples_processed, + samples_to_process); + + strm->rec_buf_len += samples_to_process; + + samples_processed += samples_to_process; + + /* Buffer is full, time to call parent callback */ + if (strm->rec_buf_len == strm->param.samples_per_frame / + strm->param.channel_count / + strm->resample_factor) { + pjmedia_frame f; + + /* Need to resample clock rate? */ + + if (strm->rec_resample) { + unsigned resampled = 0; + + while (resampled < strm->rec_buf_len) { + pjmedia_resample_run (strm->rec_resample, + &strm->rec_buf[resampled], + strm->pcm_buf + + resampled * strm->resample_factor); + resampled += 80; + } + + f.buf = strm->pcm_buf; + } else { + f.buf = strm->rec_buf; + } + + /* Need to convert channel count? */ + if (strm->param.channel_count != 1) { + pjmedia_convert_channel_1ton ( (pj_int16_t*) f.buf, + (pj_int16_t*) f.buf, + strm->param.channel_count, + strm->param.samples_per_frame / + strm->param.channel_count, + 0); + } + + /* Call parent callback */ + f.type = PJMEDIA_FRAME_TYPE_AUDIO; + + f.size = strm->param.samples_per_frame << 1; + + strm->rec_cb (strm->user_data, &f); + + strm->rec_buf_len = 0; + } } } -static void PlayCbPcm(TAPSCommBuffer &buf, void *user_data) +static void PlayCbPcm (TAPSCommBuffer &buf, void *user_data) { + struct aps_stream *strm = (struct aps_stream*) user_data; unsigned g711_frame_len = aps_g711_frame_len; @@ -788,79 +860,84 @@ static void PlayCbPcm(TAPSCommBuffer &buf, void *user_data) buf.iCommand = CQueueHandler::EAPSPlayData; buf.iStatus = 0; buf.iBuffer.Zero(); - buf.iBuffer.Append(1); - buf.iBuffer.Append(0); + buf.iBuffer.Append (1); + buf.iBuffer.Append (0); /* Assume frame size is 10ms if frame size hasn't been known. */ + if (g711_frame_len == 0) - g711_frame_len = 80; + g711_frame_len = 80; /* Call parent stream callback to get PCM samples to play, * encode the PCM samples into G.711 and put it into APS buffer. */ unsigned samples_processed = 0; - + while (samples_processed < g711_frame_len) { - /* Need more samples to play, time to call parent callback */ - if (strm->play_buf_len == 0) { - pjmedia_frame f; - unsigned samples_got; - - f.size = strm->param.samples_per_frame << 1; - if (strm->play_resample || strm->param.channel_count != 1) - f.buf = strm->pcm_buf; - else - f.buf = strm->play_buf; - - /* Call parent callback */ - strm->play_cb(strm->user_data, &f); - if (f.type != PJMEDIA_FRAME_TYPE_AUDIO) { - pjmedia_zero_samples((pj_int16_t*)f.buf, - strm->param.samples_per_frame); - } - - samples_got = strm->param.samples_per_frame / - strm->param.channel_count / - strm->resample_factor; - - /* Need to convert channel count? */ - if (strm->param.channel_count != 1) { - pjmedia_convert_channel_nto1((pj_int16_t*)f.buf, - (pj_int16_t*)f.buf, - strm->param.channel_count, - strm->param.samples_per_frame, - PJ_FALSE, - 0); - } - - /* Need to resample clock rate? */ - if (strm->play_resample) { - unsigned resampled = 0; - - while (resampled < samples_got) - { - pjmedia_resample_run(strm->play_resample, - strm->pcm_buf + - resampled * strm->resample_factor, - &strm->play_buf[resampled]); - resampled += 80; - } - } - - strm->play_buf_len = samples_got; - strm->play_buf_start = 0; - } - - unsigned tmp; - - tmp = PJ_MIN(strm->play_buf_len, g711_frame_len - samples_processed); - pjmedia_ulaw_encode((pj_uint8_t*)&strm->play_buf[strm->play_buf_start], - &strm->play_buf[strm->play_buf_start], - tmp); - buf.iBuffer.Append((TUint8*)&strm->play_buf[strm->play_buf_start], tmp); - samples_processed += tmp; - strm->play_buf_len -= tmp; - strm->play_buf_start += tmp; + /* Need more samples to play, time to call parent callback */ + if (strm->play_buf_len == 0) { + pjmedia_frame f; + unsigned samples_got; + + f.size = strm->param.samples_per_frame << 1; + + if (strm->play_resample || strm->param.channel_count != 1) + f.buf = strm->pcm_buf; + else + f.buf = strm->play_buf; + + /* Call parent callback */ + strm->play_cb (strm->user_data, &f); + + if (f.type != PJMEDIA_FRAME_TYPE_AUDIO) { + pjmedia_zero_samples ( (pj_int16_t*) f.buf, + strm->param.samples_per_frame); + } + + samples_got = strm->param.samples_per_frame / + + strm->param.channel_count / + strm->resample_factor; + + /* Need to convert channel count? */ + + if (strm->param.channel_count != 1) { + pjmedia_convert_channel_nto1 ( (pj_int16_t*) f.buf, + (pj_int16_t*) f.buf, + strm->param.channel_count, + strm->param.samples_per_frame, + PJ_FALSE, + 0); + } + + /* Need to resample clock rate? */ + if (strm->play_resample) { + unsigned resampled = 0; + + while (resampled < samples_got) { + pjmedia_resample_run (strm->play_resample, + strm->pcm_buf + + resampled * strm->resample_factor, + &strm->play_buf[resampled]); + resampled += 80; + } + } + + strm->play_buf_len = samples_got; + + strm->play_buf_start = 0; + } + + unsigned tmp; + + tmp = PJ_MIN (strm->play_buf_len, g711_frame_len - samples_processed); + pjmedia_ulaw_encode ( (pj_uint8_t*) &strm->play_buf[strm->play_buf_start], + &strm->play_buf[strm->play_buf_start], + tmp); + buf.iBuffer.Append ( (TUint8*) &strm->play_buf[strm->play_buf_start], tmp); + samples_processed += tmp; + strm->play_buf_len -= tmp; + strm->play_buf_start += tmp; } } @@ -868,131 +945,138 @@ static void PlayCbPcm(TAPSCommBuffer &buf, void *user_data) * Internal APS callbacks for non-PCM format */ -static void RecCb(TAPSCommBuffer &buf, void *user_data) +static void RecCb (TAPSCommBuffer &buf, void *user_data) { + struct aps_stream *strm = (struct aps_stream*) user_data; pjmedia_frame_ext *frame = (pjmedia_frame_ext*) strm->rec_buf; - - switch(strm->param.ext_fmt.id) { - case PJMEDIA_FORMAT_AMR: - { - const pj_uint8_t *p = (const pj_uint8_t*)buf.iBuffer.Ptr() + 1; - unsigned len = buf.iBuffer.Length() - 1; - - pjmedia_frame_ext_append_subframe(frame, p, len << 3, 160); - if (frame->samples_cnt == strm->param.samples_per_frame) { - frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; - strm->rec_cb(strm->user_data, (pjmedia_frame*)frame); - frame->samples_cnt = 0; - frame->subframe_cnt = 0; - } - } - break; - - case PJMEDIA_FORMAT_G729: - { - /* Check if we got a normal or SID frame. */ - if (buf.iBuffer[0] != 0 || buf.iBuffer[1] != 0) { - enum { NORMAL_LEN = 22, SID_LEN = 8 }; - TBitStream *bitstream = (TBitStream*)strm->strm_data; - unsigned src_len = buf.iBuffer.Length()- 2; - - pj_assert(src_len == NORMAL_LEN || src_len == SID_LEN); - - const TDesC8& p = bitstream->CompressG729Frame( - buf.iBuffer.Right(src_len), - src_len == SID_LEN); - - pjmedia_frame_ext_append_subframe(frame, p.Ptr(), - p.Length() << 3, 80); - } else { /* We got null frame. */ - pjmedia_frame_ext_append_subframe(frame, NULL, 0, 80); - } - - if (frame->samples_cnt == strm->param.samples_per_frame) { - frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; - strm->rec_cb(strm->user_data, (pjmedia_frame*)frame); - frame->samples_cnt = 0; - frame->subframe_cnt = 0; - } - } - break; - - case PJMEDIA_FORMAT_ILBC: - { - unsigned samples_got; - - samples_got = strm->param.ext_fmt.bitrate == 15200? 160 : 240; - - /* Check if we got a normal frame. */ - if (buf.iBuffer[0] == 1 && buf.iBuffer[1] == 0) { - const pj_uint8_t *p = (const pj_uint8_t*)buf.iBuffer.Ptr() + 2; - unsigned len = buf.iBuffer.Length() - 2; - - pjmedia_frame_ext_append_subframe(frame, p, len << 3, - samples_got); - } else { /* We got null frame. */ - pjmedia_frame_ext_append_subframe(frame, NULL, 0, samples_got); - } - - if (frame->samples_cnt == strm->param.samples_per_frame) { - frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; - strm->rec_cb(strm->user_data, (pjmedia_frame*)frame); - frame->samples_cnt = 0; - frame->subframe_cnt = 0; - } - } - break; - - case PJMEDIA_FORMAT_PCMU: - case PJMEDIA_FORMAT_PCMA: - { - unsigned samples_processed = 0; - - /* Make sure it is normal frame. */ - pj_assert(buf.iBuffer[0] == 1 && buf.iBuffer[1] == 0); - - /* Detect the recorder G.711 frame size, player frame size will - * follow this recorder frame size. - */ - if (aps_g711_frame_len == 0) { - aps_g711_frame_len = buf.iBuffer.Length() < 160? 80 : 160; - TRACE_((THIS_FILE, "Detected APS G.711 frame size = %u samples", - aps_g711_frame_len)); - } - - /* Convert APS buffer format into pjmedia_frame_ext. Whenever - * samples count in the frame is equal to stream's samples per - * frame, call parent stream callback. - */ - while (samples_processed < aps_g711_frame_len) { - unsigned tmp; - const pj_uint8_t *pb = (const pj_uint8_t*)buf.iBuffer.Ptr() + - 2 + samples_processed; - - tmp = PJ_MIN(strm->param.samples_per_frame - frame->samples_cnt, - aps_g711_frame_len - samples_processed); - - pjmedia_frame_ext_append_subframe(frame, pb, tmp << 3, tmp); - samples_processed += tmp; - - if (frame->samples_cnt == strm->param.samples_per_frame) { - frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; - strm->rec_cb(strm->user_data, (pjmedia_frame*)frame); - frame->samples_cnt = 0; - frame->subframe_cnt = 0; - } - } - } - break; - - default: - break; + + switch (strm->param.ext_fmt.id) { + + case PJMEDIA_FORMAT_AMR: { + const pj_uint8_t *p = (const pj_uint8_t*) buf.iBuffer.Ptr() + 1; + unsigned len = buf.iBuffer.Length() - 1; + + pjmedia_frame_ext_append_subframe (frame, p, len << 3, 160); + + if (frame->samples_cnt == strm->param.samples_per_frame) { + frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; + strm->rec_cb (strm->user_data, (pjmedia_frame*) frame); + frame->samples_cnt = 0; + frame->subframe_cnt = 0; + } + } + + break; + + case PJMEDIA_FORMAT_G729: { + /* Check if we got a normal or SID frame. */ + if (buf.iBuffer[0] != 0 || buf.iBuffer[1] != 0) { + enum { NORMAL_LEN = 22, SID_LEN = 8 }; + TBitStream *bitstream = (TBitStream*) strm->strm_data; + unsigned src_len = buf.iBuffer.Length()- 2; + + pj_assert (src_len == NORMAL_LEN || src_len == SID_LEN); + + const TDesC8& p = bitstream->CompressG729Frame ( + buf.iBuffer.Right (src_len), + src_len == SID_LEN); + + pjmedia_frame_ext_append_subframe (frame, p.Ptr(), + p.Length() << 3, 80); + } else { /* We got null frame. */ + pjmedia_frame_ext_append_subframe (frame, NULL, 0, 80); + } + + if (frame->samples_cnt == strm->param.samples_per_frame) { + frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; + strm->rec_cb (strm->user_data, (pjmedia_frame*) frame); + frame->samples_cnt = 0; + frame->subframe_cnt = 0; + } + } + + break; + + case PJMEDIA_FORMAT_ILBC: { + unsigned samples_got; + + samples_got = strm->param.ext_fmt.bitrate == 15200? 160 : 240; + + /* Check if we got a normal frame. */ + + if (buf.iBuffer[0] == 1 && buf.iBuffer[1] == 0) { + const pj_uint8_t *p = (const pj_uint8_t*) buf.iBuffer.Ptr() + 2; + unsigned len = buf.iBuffer.Length() - 2; + + pjmedia_frame_ext_append_subframe (frame, p, len << 3, + samples_got); + } else { /* We got null frame. */ + pjmedia_frame_ext_append_subframe (frame, NULL, 0, samples_got); + } + + if (frame->samples_cnt == strm->param.samples_per_frame) { + frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; + strm->rec_cb (strm->user_data, (pjmedia_frame*) frame); + frame->samples_cnt = 0; + frame->subframe_cnt = 0; + } + } + + break; + + case PJMEDIA_FORMAT_PCMU: + + case PJMEDIA_FORMAT_PCMA: { + unsigned samples_processed = 0; + + /* Make sure it is normal frame. */ + pj_assert (buf.iBuffer[0] == 1 && buf.iBuffer[1] == 0); + + /* Detect the recorder G.711 frame size, player frame size will + * follow this recorder frame size. + */ + + if (aps_g711_frame_len == 0) { + aps_g711_frame_len = buf.iBuffer.Length() < 160? 80 : 160; + TRACE_ ( (THIS_FILE, "Detected APS G.711 frame size = %u samples", + aps_g711_frame_len)); + } + + /* Convert APS buffer format into pjmedia_frame_ext. Whenever + * samples count in the frame is equal to stream's samples per + * frame, call parent stream callback. + */ + while (samples_processed < aps_g711_frame_len) { + unsigned tmp; + const pj_uint8_t *pb = (const pj_uint8_t*) buf.iBuffer.Ptr() + + 2 + samples_processed; + + tmp = PJ_MIN (strm->param.samples_per_frame - frame->samples_cnt, + aps_g711_frame_len - samples_processed); + + pjmedia_frame_ext_append_subframe (frame, pb, tmp << 3, tmp); + samples_processed += tmp; + + if (frame->samples_cnt == strm->param.samples_per_frame) { + frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; + strm->rec_cb (strm->user_data, (pjmedia_frame*) frame); + frame->samples_cnt = 0; + frame->subframe_cnt = 0; + } + } + } + + break; + + default: + break; } } -static void PlayCb(TAPSCommBuffer &buf, void *user_data) +static void PlayCb (TAPSCommBuffer &buf, void *user_data) { + struct aps_stream *strm = (struct aps_stream*) user_data; pjmedia_frame_ext *frame = (pjmedia_frame_ext*) strm->play_buf; @@ -1001,200 +1085,209 @@ static void PlayCb(TAPSCommBuffer &buf, void *user_data) buf.iStatus = 0; buf.iBuffer.Zero(); - switch(strm->param.ext_fmt.id) { - case PJMEDIA_FORMAT_AMR: - { - if (frame->samples_cnt == 0) { - frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; - strm->play_cb(strm->user_data, (pjmedia_frame*)frame); - pj_assert(frame->base.type==PJMEDIA_FRAME_TYPE_EXTENDED || - frame->base.type==PJMEDIA_FRAME_TYPE_NONE); - } - - if (frame->base.type == PJMEDIA_FRAME_TYPE_EXTENDED) { - pjmedia_frame_ext_subframe *sf; - unsigned samples_cnt; - - sf = pjmedia_frame_ext_get_subframe(frame, 0); - samples_cnt = frame->samples_cnt / frame->subframe_cnt; - - if (sf->data && sf->bitlen) { - /* AMR header for APS is one byte, the format (may be!): - * 0xxxxy00, where xxxx:frame type, y:not sure. - */ - unsigned len = (sf->bitlen+7)>>3; - enum {SID_FT = 8 }; - pj_uint8_t amr_header = 4, ft = SID_FT; - - if (len >= pjmedia_codec_amrnb_framelen[0]) - ft = pjmedia_codec_amr_get_mode2(PJ_TRUE, len); - - amr_header |= ft << 3; - buf.iBuffer.Append(amr_header); - - buf.iBuffer.Append((TUint8*)sf->data, len); - } else { - buf.iBuffer.Append(0); - } - - pjmedia_frame_ext_pop_subframes(frame, 1); - - } else { /* PJMEDIA_FRAME_TYPE_NONE */ - buf.iBuffer.Append(0); - - frame->samples_cnt = 0; - frame->subframe_cnt = 0; - } - } - break; - - case PJMEDIA_FORMAT_G729: - { - if (frame->samples_cnt == 0) { - frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; - strm->play_cb(strm->user_data, (pjmedia_frame*)frame); - pj_assert(frame->base.type==PJMEDIA_FRAME_TYPE_EXTENDED || - frame->base.type==PJMEDIA_FRAME_TYPE_NONE); - } - - if (frame->base.type == PJMEDIA_FRAME_TYPE_EXTENDED) { - pjmedia_frame_ext_subframe *sf; - unsigned samples_cnt; - - sf = pjmedia_frame_ext_get_subframe(frame, 0); - samples_cnt = frame->samples_cnt / frame->subframe_cnt; - - if (sf->data && sf->bitlen) { - enum { NORMAL_LEN = 10, SID_LEN = 2 }; - pj_bool_t sid_frame = ((sf->bitlen >> 3) == SID_LEN); - TBitStream *bitstream = (TBitStream*)strm->strm_data; - const TPtrC8 src(sf->data, sf->bitlen>>3); - const TDesC8 &dst = bitstream->ExpandG729Frame(src, - sid_frame); - if (sid_frame) { - buf.iBuffer.Append(0); - buf.iBuffer.Append(1); - } else { - buf.iBuffer.Append(1); - buf.iBuffer.Append(0); - } - buf.iBuffer.Append(dst); - } else { - buf.iBuffer.Append(0); - buf.iBuffer.Append(0); - } - - pjmedia_frame_ext_pop_subframes(frame, 1); - - } else { /* PJMEDIA_FRAME_TYPE_NONE */ - buf.iBuffer.Append(0); - buf.iBuffer.Append(0); - - frame->samples_cnt = 0; - frame->subframe_cnt = 0; - } - } - break; - - case PJMEDIA_FORMAT_ILBC: - { - if (frame->samples_cnt == 0) { - frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; - strm->play_cb(strm->user_data, (pjmedia_frame*)frame); - pj_assert(frame->base.type==PJMEDIA_FRAME_TYPE_EXTENDED || - frame->base.type==PJMEDIA_FRAME_TYPE_NONE); - } - - if (frame->base.type == PJMEDIA_FRAME_TYPE_EXTENDED) { - pjmedia_frame_ext_subframe *sf; - unsigned samples_cnt; - - sf = pjmedia_frame_ext_get_subframe(frame, 0); - samples_cnt = frame->samples_cnt / frame->subframe_cnt; - - pj_assert((strm->param.ext_fmt.bitrate == 15200 && - samples_cnt == 160) || - (strm->param.ext_fmt.bitrate != 15200 && - samples_cnt == 240)); - - if (sf->data && sf->bitlen) { - buf.iBuffer.Append(1); - buf.iBuffer.Append(0); - buf.iBuffer.Append((TUint8*)sf->data, sf->bitlen>>3); - } else { - buf.iBuffer.Append(0); - buf.iBuffer.Append(0); - } - - pjmedia_frame_ext_pop_subframes(frame, 1); - - } else { /* PJMEDIA_FRAME_TYPE_NONE */ - buf.iBuffer.Append(0); - buf.iBuffer.Append(0); - - frame->samples_cnt = 0; - frame->subframe_cnt = 0; - } - } - break; - - case PJMEDIA_FORMAT_PCMU: - case PJMEDIA_FORMAT_PCMA: - { - unsigned samples_ready = 0; - unsigned samples_req = aps_g711_frame_len; - - /* Assume frame size is 10ms if frame size hasn't been known. */ - if (samples_req == 0) - samples_req = 80; - - buf.iBuffer.Append(1); - buf.iBuffer.Append(0); - - /* Call parent stream callback to get samples to play. */ - while (samples_ready < samples_req) { - if (frame->samples_cnt == 0) { - frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; - strm->play_cb(strm->user_data, (pjmedia_frame*)frame); - pj_assert(frame->base.type==PJMEDIA_FRAME_TYPE_EXTENDED || - frame->base.type==PJMEDIA_FRAME_TYPE_NONE); - } - - if (frame->base.type == PJMEDIA_FRAME_TYPE_EXTENDED) { - pjmedia_frame_ext_subframe *sf; - unsigned samples_cnt; - - sf = pjmedia_frame_ext_get_subframe(frame, 0); - samples_cnt = frame->samples_cnt / frame->subframe_cnt; - if (sf->data && sf->bitlen) { - buf.iBuffer.Append((TUint8*)sf->data, sf->bitlen>>3); - } else { - pj_uint8_t silc; - silc = (strm->param.ext_fmt.id==PJMEDIA_FORMAT_PCMU)? - pjmedia_linear2ulaw(0) : pjmedia_linear2alaw(0); - buf.iBuffer.AppendFill(silc, samples_cnt); - } - samples_ready += samples_cnt; - - pjmedia_frame_ext_pop_subframes(frame, 1); - - } else { /* PJMEDIA_FRAME_TYPE_NONE */ - pj_uint8_t silc; - - silc = (strm->param.ext_fmt.id==PJMEDIA_FORMAT_PCMU)? - pjmedia_linear2ulaw(0) : pjmedia_linear2alaw(0); - buf.iBuffer.AppendFill(silc, samples_req - samples_ready); - - samples_ready = samples_req; - frame->samples_cnt = 0; - frame->subframe_cnt = 0; - } - } - } - break; - - default: - break; + switch (strm->param.ext_fmt.id) { + + case PJMEDIA_FORMAT_AMR: { + if (frame->samples_cnt == 0) { + frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; + strm->play_cb (strm->user_data, (pjmedia_frame*) frame); + pj_assert (frame->base.type==PJMEDIA_FRAME_TYPE_EXTENDED || + frame->base.type==PJMEDIA_FRAME_TYPE_NONE); + } + + if (frame->base.type == PJMEDIA_FRAME_TYPE_EXTENDED) { + pjmedia_frame_ext_subframe *sf; + unsigned samples_cnt; + + sf = pjmedia_frame_ext_get_subframe (frame, 0); + samples_cnt = frame->samples_cnt / frame->subframe_cnt; + + if (sf->data && sf->bitlen) { + /* AMR header for APS is one byte, the format (may be!): + * 0xxxxy00, where xxxx:frame type, y:not sure. + */ + unsigned len = (sf->bitlen+7) >>3; + enum {SID_FT = 8 }; + pj_uint8_t amr_header = 4, ft = SID_FT; + + if (len >= pjmedia_codec_amrnb_framelen[0]) + ft = pjmedia_codec_amr_get_mode2 (PJ_TRUE, len); + + amr_header |= ft << 3; + + buf.iBuffer.Append (amr_header); + + buf.iBuffer.Append ( (TUint8*) sf->data, len); + } else { + buf.iBuffer.Append (0); + } + + pjmedia_frame_ext_pop_subframes (frame, 1); + + } else { /* PJMEDIA_FRAME_TYPE_NONE */ + buf.iBuffer.Append (0); + + frame->samples_cnt = 0; + frame->subframe_cnt = 0; + } + } + + break; + + case PJMEDIA_FORMAT_G729: { + if (frame->samples_cnt == 0) { + frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; + strm->play_cb (strm->user_data, (pjmedia_frame*) frame); + pj_assert (frame->base.type==PJMEDIA_FRAME_TYPE_EXTENDED || + frame->base.type==PJMEDIA_FRAME_TYPE_NONE); + } + + if (frame->base.type == PJMEDIA_FRAME_TYPE_EXTENDED) { + pjmedia_frame_ext_subframe *sf; + unsigned samples_cnt; + + sf = pjmedia_frame_ext_get_subframe (frame, 0); + samples_cnt = frame->samples_cnt / frame->subframe_cnt; + + if (sf->data && sf->bitlen) { + enum { NORMAL_LEN = 10, SID_LEN = 2 }; + pj_bool_t sid_frame = ( (sf->bitlen >> 3) == SID_LEN); + TBitStream *bitstream = (TBitStream*) strm->strm_data; + const TPtrC8 src (sf->data, sf->bitlen>>3); + const TDesC8 &dst = bitstream->ExpandG729Frame (src, + sid_frame); + + if (sid_frame) { + buf.iBuffer.Append (0); + buf.iBuffer.Append (1); + } else { + buf.iBuffer.Append (1); + buf.iBuffer.Append (0); + } + + buf.iBuffer.Append (dst); + } else { + buf.iBuffer.Append (0); + buf.iBuffer.Append (0); + } + + pjmedia_frame_ext_pop_subframes (frame, 1); + + } else { /* PJMEDIA_FRAME_TYPE_NONE */ + buf.iBuffer.Append (0); + buf.iBuffer.Append (0); + + frame->samples_cnt = 0; + frame->subframe_cnt = 0; + } + } + + break; + + case PJMEDIA_FORMAT_ILBC: { + if (frame->samples_cnt == 0) { + frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; + strm->play_cb (strm->user_data, (pjmedia_frame*) frame); + pj_assert (frame->base.type==PJMEDIA_FRAME_TYPE_EXTENDED || + frame->base.type==PJMEDIA_FRAME_TYPE_NONE); + } + + if (frame->base.type == PJMEDIA_FRAME_TYPE_EXTENDED) { + pjmedia_frame_ext_subframe *sf; + unsigned samples_cnt; + + sf = pjmedia_frame_ext_get_subframe (frame, 0); + samples_cnt = frame->samples_cnt / frame->subframe_cnt; + + pj_assert ( (strm->param.ext_fmt.bitrate == 15200 && + samples_cnt == 160) || + (strm->param.ext_fmt.bitrate != 15200 && + samples_cnt == 240)); + + if (sf->data && sf->bitlen) { + buf.iBuffer.Append (1); + buf.iBuffer.Append (0); + buf.iBuffer.Append ( (TUint8*) sf->data, sf->bitlen>>3); + } else { + buf.iBuffer.Append (0); + buf.iBuffer.Append (0); + } + + pjmedia_frame_ext_pop_subframes (frame, 1); + + } else { /* PJMEDIA_FRAME_TYPE_NONE */ + buf.iBuffer.Append (0); + buf.iBuffer.Append (0); + + frame->samples_cnt = 0; + frame->subframe_cnt = 0; + } + } + + break; + + case PJMEDIA_FORMAT_PCMU: + + case PJMEDIA_FORMAT_PCMA: { + unsigned samples_ready = 0; + unsigned samples_req = aps_g711_frame_len; + + /* Assume frame size is 10ms if frame size hasn't been known. */ + + if (samples_req == 0) + samples_req = 80; + + buf.iBuffer.Append (1); + + buf.iBuffer.Append (0); + + /* Call parent stream callback to get samples to play. */ + while (samples_ready < samples_req) { + if (frame->samples_cnt == 0) { + frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; + strm->play_cb (strm->user_data, (pjmedia_frame*) frame); + pj_assert (frame->base.type==PJMEDIA_FRAME_TYPE_EXTENDED || + frame->base.type==PJMEDIA_FRAME_TYPE_NONE); + } + + if (frame->base.type == PJMEDIA_FRAME_TYPE_EXTENDED) { + pjmedia_frame_ext_subframe *sf; + unsigned samples_cnt; + + sf = pjmedia_frame_ext_get_subframe (frame, 0); + samples_cnt = frame->samples_cnt / frame->subframe_cnt; + + if (sf->data && sf->bitlen) { + buf.iBuffer.Append ( (TUint8*) sf->data, sf->bitlen>>3); + } else { + pj_uint8_t silc; + silc = (strm->param.ext_fmt.id==PJMEDIA_FORMAT_PCMU) ? + pjmedia_linear2ulaw (0) : pjmedia_linear2alaw (0); + buf.iBuffer.AppendFill (silc, samples_cnt); + } + + samples_ready += samples_cnt; + + pjmedia_frame_ext_pop_subframes (frame, 1); + + } else { /* PJMEDIA_FRAME_TYPE_NONE */ + pj_uint8_t silc; + + silc = (strm->param.ext_fmt.id==PJMEDIA_FORMAT_PCMU) ? + pjmedia_linear2ulaw (0) : pjmedia_linear2alaw (0); + buf.iBuffer.AppendFill (silc, samples_req - samples_ready); + + samples_ready = samples_req; + frame->samples_cnt = 0; + frame->subframe_cnt = 0; + } + } + } + + break; + + default: + break; } } @@ -1207,19 +1300,20 @@ static void PlayCb(TAPSCommBuffer &buf, void *user_data) * C compatible declaration of APS factory. */ PJ_BEGIN_DECL -PJ_DECL(pjmedia_aud_dev_factory*) pjmedia_aps_factory(pj_pool_factory *pf); +PJ_DECL (pjmedia_aud_dev_factory*) pjmedia_aps_factory (pj_pool_factory *pf); PJ_END_DECL /* * Init APS audio driver. */ -PJ_DEF(pjmedia_aud_dev_factory*) pjmedia_aps_factory(pj_pool_factory *pf) +PJ_DEF (pjmedia_aud_dev_factory*) pjmedia_aps_factory (pj_pool_factory *pf) { + struct aps_factory *f; pj_pool_t *pool; - pool = pj_pool_create(pf, "APS", 1000, 1000, NULL); - f = PJ_POOL_ZALLOC_T(pool, struct aps_factory); + pool = pj_pool_create (pf, "APS", 1000, 1000, NULL); + f = PJ_POOL_ZALLOC_T (pool, struct aps_factory); f->pf = pf; f->pool = pool; f->base.op = &factory_op; @@ -1228,20 +1322,21 @@ PJ_DEF(pjmedia_aud_dev_factory*) pjmedia_aps_factory(pj_pool_factory *pf) } /* API: init factory */ -static pj_status_t factory_init(pjmedia_aud_dev_factory *f) +static pj_status_t factory_init (pjmedia_aud_dev_factory *f) { - struct aps_factory *af = (struct aps_factory*)f; - pj_ansi_strcpy(af->dev_info.name, "S60 APS"); + struct aps_factory *af = (struct aps_factory*) f; + + pj_ansi_strcpy (af->dev_info.name, "S60 APS"); af->dev_info.default_samples_per_sec = 8000; af->dev_info.caps = PJMEDIA_AUD_DEV_CAP_EXT_FORMAT | - //PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING | - PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING | - PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE | - PJMEDIA_AUD_DEV_CAP_VAD | - PJMEDIA_AUD_DEV_CAP_CNG; - af->dev_info.routes = PJMEDIA_AUD_DEV_ROUTE_EARPIECE | - PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER; + //PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING | + PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING | + PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE | + PJMEDIA_AUD_DEV_CAP_VAD | + PJMEDIA_AUD_DEV_CAP_CNG; + af->dev_info.routes = PJMEDIA_AUD_DEV_ROUTE_EARPIECE | + PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER; af->dev_info.input_count = 1; af->dev_info.output_count = 1; @@ -1266,57 +1361,60 @@ static pj_status_t factory_init(pjmedia_aud_dev_factory *f) af->dev_info.ext_fmt[4].id = PJMEDIA_FORMAT_PCMA; af->dev_info.ext_fmt[4].bitrate = 64000; af->dev_info.ext_fmt[4].vad = PJ_FALSE; - - PJ_LOG(4, (THIS_FILE, "APS initialized")); + + PJ_LOG (4, (THIS_FILE, "APS initialized")); return PJ_SUCCESS; } /* API: destroy factory */ -static pj_status_t factory_destroy(pjmedia_aud_dev_factory *f) +static pj_status_t factory_destroy (pjmedia_aud_dev_factory *f) { - struct aps_factory *af = (struct aps_factory*)f; + + struct aps_factory *af = (struct aps_factory*) f; pj_pool_t *pool = af->pool; af->pool = NULL; - pj_pool_release(pool); + pj_pool_release (pool); + + PJ_LOG (4, (THIS_FILE, "APS destroyed")); - PJ_LOG(4, (THIS_FILE, "APS destroyed")); - return PJ_SUCCESS; } /* API: get number of devices */ -static unsigned factory_get_dev_count(pjmedia_aud_dev_factory *f) +static unsigned factory_get_dev_count (pjmedia_aud_dev_factory *f) { - PJ_UNUSED_ARG(f); + PJ_UNUSED_ARG (f); return 1; } /* API: get device info */ -static pj_status_t factory_get_dev_info(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_dev_info *info) +static pj_status_t factory_get_dev_info (pjmedia_aud_dev_factory *f, + unsigned index, + pjmedia_aud_dev_info *info) { - struct aps_factory *af = (struct aps_factory*)f; - PJ_ASSERT_RETURN(index == 0, PJMEDIA_EAUD_INVDEV); + struct aps_factory *af = (struct aps_factory*) f; - pj_memcpy(info, &af->dev_info, sizeof(*info)); + PJ_ASSERT_RETURN (index == 0, PJMEDIA_EAUD_INVDEV); + + pj_memcpy (info, &af->dev_info, sizeof (*info)); return PJ_SUCCESS; } /* API: create default device parameter */ -static pj_status_t factory_default_param(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_param *param) +static pj_status_t factory_default_param (pjmedia_aud_dev_factory *f, + unsigned index, + pjmedia_aud_param *param) { - struct aps_factory *af = (struct aps_factory*)f; - PJ_ASSERT_RETURN(index == 0, PJMEDIA_EAUD_INVDEV); + struct aps_factory *af = (struct aps_factory*) f; + + PJ_ASSERT_RETURN (index == 0, PJMEDIA_EAUD_INVDEV); - pj_bzero(param, sizeof(*param)); + pj_bzero (param, sizeof (*param)); param->dir = PJMEDIA_DIR_CAPTURE_PLAYBACK; param->rec_id = index; param->play_id = index; @@ -1332,15 +1430,17 @@ static pj_status_t factory_default_param(pjmedia_aud_dev_factory *f, /* API: create stream */ -static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, - const pjmedia_aud_param *param, - pjmedia_aud_rec_cb rec_cb, - pjmedia_aud_play_cb play_cb, - void *user_data, - pjmedia_aud_stream **p_aud_strm) +static pj_status_t factory_create_stream (pjmedia_aud_dev_factory *f, + const pjmedia_aud_param *param, + pjmedia_aud_rec_cb rec_cb, + pjmedia_aud_play_cb play_cb, + void *user_data, + pjmedia_aud_stream **p_aud_strm) { - struct aps_factory *af = (struct aps_factory*)f; + + struct aps_factory *af = (struct aps_factory*) f; pj_pool_t *pool; + struct aps_stream *strm; CPjAudioSetting aps_setting; @@ -1348,382 +1448,413 @@ static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, PjAudioCallback aps_play_cb; /* Can only support 16bits per sample */ - PJ_ASSERT_RETURN(param->bits_per_sample == BITS_PER_SAMPLE, PJ_EINVAL); + PJ_ASSERT_RETURN (param->bits_per_sample == BITS_PER_SAMPLE, PJ_EINVAL); /* Supported clock rates: - * - for non-PCM format: 8kHz - * - for PCM format: 8kHz and 16kHz + * - for non-PCM format: 8kHz + * - for PCM format: 8kHz and 16kHz */ - PJ_ASSERT_RETURN(param->clock_rate == 8000 || - (param->clock_rate == 16000 && - param->ext_fmt.id == PJMEDIA_FORMAT_L16), - PJ_EINVAL); + PJ_ASSERT_RETURN (param->clock_rate == 8000 || + (param->clock_rate == 16000 && + param->ext_fmt.id == PJMEDIA_FORMAT_L16), + PJ_EINVAL); /* Supported channels number: * - for non-PCM format: mono - * - for PCM format: mono and stereo + * - for PCM format: mono and stereo */ - PJ_ASSERT_RETURN(param->channel_count == 1 || - (param->channel_count == 2 && - param->ext_fmt.id == PJMEDIA_FORMAT_L16), - PJ_EINVAL); + PJ_ASSERT_RETURN (param->channel_count == 1 || + (param->channel_count == 2 && + param->ext_fmt.id == PJMEDIA_FORMAT_L16), + PJ_EINVAL); /* Create and Initialize stream descriptor */ - pool = pj_pool_create(af->pf, "aps-dev", 1000, 1000, NULL); - PJ_ASSERT_RETURN(pool, PJ_ENOMEM); + pool = pj_pool_create (af->pf, "aps-dev", 1000, 1000, NULL); + PJ_ASSERT_RETURN (pool, PJ_ENOMEM); - strm = PJ_POOL_ZALLOC_T(pool, struct aps_stream); + strm = PJ_POOL_ZALLOC_T (pool, struct aps_stream); strm->pool = pool; strm->param = *param; if (strm->param.flags & PJMEDIA_AUD_DEV_CAP_EXT_FORMAT == 0) - strm->param.ext_fmt.id = PJMEDIA_FORMAT_L16; - + strm->param.ext_fmt.id = PJMEDIA_FORMAT_L16; + /* Set audio engine fourcc. */ - switch(strm->param.ext_fmt.id) { - case PJMEDIA_FORMAT_L16: - case PJMEDIA_FORMAT_PCMU: - case PJMEDIA_FORMAT_PCMA: - aps_setting.fourcc = TFourCC(KMCPFourCCIdG711); - break; - case PJMEDIA_FORMAT_AMR: - aps_setting.fourcc = TFourCC(KMCPFourCCIdAMRNB); - break; - case PJMEDIA_FORMAT_G729: - aps_setting.fourcc = TFourCC(KMCPFourCCIdG729); - break; - case PJMEDIA_FORMAT_ILBC: - aps_setting.fourcc = TFourCC(KMCPFourCCIdILBC); - break; - default: - aps_setting.fourcc = 0; - break; + switch (strm->param.ext_fmt.id) { + + case PJMEDIA_FORMAT_L16: + + case PJMEDIA_FORMAT_PCMU: + + case PJMEDIA_FORMAT_PCMA: + aps_setting.fourcc = TFourCC (KMCPFourCCIdG711); + break; + + case PJMEDIA_FORMAT_AMR: + aps_setting.fourcc = TFourCC (KMCPFourCCIdAMRNB); + break; + + case PJMEDIA_FORMAT_G729: + aps_setting.fourcc = TFourCC (KMCPFourCCIdG729); + break; + + case PJMEDIA_FORMAT_ILBC: + aps_setting.fourcc = TFourCC (KMCPFourCCIdILBC); + break; + + default: + aps_setting.fourcc = 0; + break; } /* Set audio engine mode. */ - if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_AMR) - { - aps_setting.mode = (TAPSCodecMode)strm->param.ext_fmt.bitrate; - } - else if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_PCMU || - strm->param.ext_fmt.id == PJMEDIA_FORMAT_L16 || - (strm->param.ext_fmt.id == PJMEDIA_FORMAT_ILBC && - strm->param.ext_fmt.bitrate != 15200)) - { - aps_setting.mode = EULawOr30ms; - } - else if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_PCMA || - (strm->param.ext_fmt.id == PJMEDIA_FORMAT_ILBC && - strm->param.ext_fmt.bitrate == 15200)) - { - aps_setting.mode = EALawOr20ms; + if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_AMR) { + aps_setting.mode = (TAPSCodecMode) strm->param.ext_fmt.bitrate; + } else if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_PCMU || + strm->param.ext_fmt.id == PJMEDIA_FORMAT_L16 || + (strm->param.ext_fmt.id == PJMEDIA_FORMAT_ILBC && + strm->param.ext_fmt.bitrate != 15200)) { + aps_setting.mode = EULawOr30ms; + } else if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_PCMA || + (strm->param.ext_fmt.id == PJMEDIA_FORMAT_ILBC && + strm->param.ext_fmt.bitrate == 15200)) { + aps_setting.mode = EALawOr20ms; } - /* Disable VAD on L16, G711, and also G729 (G729's VAD potentially + /* Disable VAD on L16, G711, and also G729 (G729's VAD potentially * causes noise?). */ if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_PCMU || - strm->param.ext_fmt.id == PJMEDIA_FORMAT_PCMA || - strm->param.ext_fmt.id == PJMEDIA_FORMAT_L16 || - strm->param.ext_fmt.id == PJMEDIA_FORMAT_G729) - { - aps_setting.vad = EFalse; + strm->param.ext_fmt.id == PJMEDIA_FORMAT_PCMA || + strm->param.ext_fmt.id == PJMEDIA_FORMAT_L16 || + strm->param.ext_fmt.id == PJMEDIA_FORMAT_G729) { + aps_setting.vad = EFalse; } else { - aps_setting.vad = strm->param.ext_fmt.vad; + aps_setting.vad = strm->param.ext_fmt.vad; } - + /* Set other audio engine attributes. */ aps_setting.plc = strm->param.plc_enabled; + aps_setting.cng = aps_setting.vad; - aps_setting.loudspk = - strm->param.output_route==PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER; + + aps_setting.loudspk = + strm->param.output_route==PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER; /* Set audio engine callbacks. */ if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_L16) { - aps_play_cb = &PlayCbPcm; - aps_rec_cb = &RecCbPcm; + aps_play_cb = &PlayCbPcm; + aps_rec_cb = &RecCbPcm; } else { - aps_play_cb = &PlayCb; - aps_rec_cb = &RecCb; + aps_play_cb = &PlayCb; + aps_rec_cb = &RecCb; } strm->rec_cb = rec_cb; + strm->play_cb = play_cb; strm->user_data = user_data; strm->resample_factor = strm->param.clock_rate / 8000; /* play_buf size is samples per frame scaled in to 8kHz mono. */ - strm->play_buf = (pj_int16_t*)pj_pool_zalloc( - pool, - (strm->param.samples_per_frame / - strm->resample_factor / - strm->param.channel_count) << 1); + strm->play_buf = (pj_int16_t*) pj_pool_zalloc ( + pool, + (strm->param.samples_per_frame / + strm->resample_factor / + strm->param.channel_count) << 1); strm->play_buf_len = 0; strm->play_buf_start = 0; /* rec_buf size is samples per frame scaled in to 8kHz mono. */ - strm->rec_buf = (pj_int16_t*)pj_pool_zalloc( - pool, - (strm->param.samples_per_frame / - strm->resample_factor / - strm->param.channel_count) << 1); + strm->rec_buf = (pj_int16_t*) pj_pool_zalloc ( + pool, + (strm->param.samples_per_frame / + strm->resample_factor / + strm->param.channel_count) << 1); strm->rec_buf_len = 0; if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_G729) { - TBitStream *g729_bitstream = new TBitStream; - - PJ_ASSERT_RETURN(g729_bitstream, PJ_ENOMEM); - strm->strm_data = (void*)g729_bitstream; + TBitStream *g729_bitstream = new TBitStream; + + PJ_ASSERT_RETURN (g729_bitstream, PJ_ENOMEM); + strm->strm_data = (void*) g729_bitstream; } - + /* Init resampler when format is PCM and clock rate is not 8kHz */ - if (strm->param.clock_rate != 8000 && - strm->param.ext_fmt.id == PJMEDIA_FORMAT_L16) - { - pj_status_t status; - - if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { - /* Create resample for recorder */ - status = pjmedia_resample_create( pool, PJ_TRUE, PJ_FALSE, 1, - 8000, - strm->param.clock_rate, - 80, - &strm->rec_resample); - if (status != PJ_SUCCESS) - return status; - } - - if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { - /* Create resample for player */ - status = pjmedia_resample_create( pool, PJ_TRUE, PJ_FALSE, 1, - strm->param.clock_rate, - 8000, - 80 * strm->resample_factor, - &strm->play_resample); - if (status != PJ_SUCCESS) - return status; - } + if (strm->param.clock_rate != 8000 && + strm->param.ext_fmt.id == PJMEDIA_FORMAT_L16) { + pj_status_t status; + + if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { + /* Create resample for recorder */ + status = pjmedia_resample_create (pool, PJ_TRUE, PJ_FALSE, 1, + 8000, + strm->param.clock_rate, + 80, + &strm->rec_resample); + + if (status != PJ_SUCCESS) + return status; + } + + if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { + /* Create resample for player */ + status = pjmedia_resample_create (pool, PJ_TRUE, PJ_FALSE, 1, + strm->param.clock_rate, + 8000, + 80 * strm->resample_factor, + &strm->play_resample); + + if (status != PJ_SUCCESS) + return status; + } } /* Create PCM buffer, when the clock rate is not 8kHz or not mono */ if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_L16 && - (strm->resample_factor > 1 || strm->param.channel_count != 1)) - { - strm->pcm_buf = (pj_int16_t*)pj_pool_zalloc(pool, - strm->param.samples_per_frame << 1); + (strm->resample_factor > 1 || strm->param.channel_count != 1)) { + strm->pcm_buf = (pj_int16_t*) pj_pool_zalloc (pool, + strm->param.samples_per_frame << 1); } - + /* Create the audio engine. */ - TRAPD(err, strm->engine = CPjAudioEngine::NewL(strm, - aps_rec_cb, aps_play_cb, - strm, aps_setting)); + TRAPD (err, strm->engine = CPjAudioEngine::NewL (strm, + aps_rec_cb, aps_play_cb, + strm, aps_setting)); + if (err != KErrNone) { - pj_pool_release(pool); - return PJ_RETURN_OS_ERROR(err); + pj_pool_release (pool); + return PJ_RETURN_OS_ERROR (err); } /* Apply output volume setting if specified */ if (param->flags & PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING) { - stream_set_cap(&strm->base, PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, - ¶m->output_vol); + stream_set_cap (&strm->base, PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, + ¶m->output_vol); } /* Done */ strm->base.op = &stream_op; + *p_aud_strm = &strm->base; return PJ_SUCCESS; } /* API: Get stream info. */ -static pj_status_t stream_get_param(pjmedia_aud_stream *s, - pjmedia_aud_param *pi) +static pj_status_t stream_get_param (pjmedia_aud_stream *s, + pjmedia_aud_param *pi) { - struct aps_stream *strm = (struct aps_stream*)s; - PJ_ASSERT_RETURN(strm && pi, PJ_EINVAL); + struct aps_stream *strm = (struct aps_stream*) s; + + PJ_ASSERT_RETURN (strm && pi, PJ_EINVAL); - pj_memcpy(pi, &strm->param, sizeof(*pi)); + pj_memcpy (pi, &strm->param, sizeof (*pi)); /* Update the output volume setting */ - if (stream_get_cap(s, PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, - &pi->output_vol) == PJ_SUCCESS) - { - pi->flags |= PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING; + + if (stream_get_cap (s, PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, + &pi->output_vol) == PJ_SUCCESS) { + pi->flags |= PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING; } - + return PJ_SUCCESS; } /* API: get capability */ -static pj_status_t stream_get_cap(pjmedia_aud_stream *s, - pjmedia_aud_dev_cap cap, - void *pval) +static pj_status_t stream_get_cap (pjmedia_aud_stream *s, + pjmedia_aud_dev_cap cap, + void *pval) { - struct aps_stream *strm = (struct aps_stream*)s; + + struct aps_stream *strm = (struct aps_stream*) s; pj_status_t status = PJ_ENOTSUP; - PJ_ASSERT_RETURN(s && pval, PJ_EINVAL); + PJ_ASSERT_RETURN (s && pval, PJ_EINVAL); switch (cap) { - case PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE: - if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { - *(pjmedia_aud_dev_route*)pval = strm->param.output_route; - status = PJ_SUCCESS; - } - break; - - /* There is a case that GetMaxGain() stucks, e.g: in N95. */ - /* - case PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING: - if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { - PJ_ASSERT_RETURN(strm->engine, PJ_EINVAL); - - TInt max_gain = strm->engine->GetMaxGain(); - TInt gain = strm->engine->GetGain(); - - if (max_gain > 0 && gain >= 0) { - *(unsigned*)pval = gain * 100 / max_gain; - status = PJ_SUCCESS; - } else { - status = PJMEDIA_EAUD_NOTREADY; - } - } - break; - */ - - case PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING: - if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { - PJ_ASSERT_RETURN(strm->engine, PJ_EINVAL); - - TInt max_vol = strm->engine->GetMaxVolume(); - TInt vol = strm->engine->GetVolume(); - - if (max_vol > 0 && vol >= 0) { - *(unsigned*)pval = vol * 100 / max_vol; - status = PJ_SUCCESS; - } else { - status = PJMEDIA_EAUD_NOTREADY; - } - } - break; - default: - break; + + case PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE: + + if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { + * (pjmedia_aud_dev_route*) pval = strm->param.output_route; + status = PJ_SUCCESS; + } + + break; + + /* There is a case that GetMaxGain() stucks, e.g: in N95. */ + /* + case PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING: + if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { + PJ_ASSERT_RETURN(strm->engine, PJ_EINVAL); + + TInt max_gain = strm->engine->GetMaxGain(); + TInt gain = strm->engine->GetGain(); + + if (max_gain > 0 && gain >= 0) { + *(unsigned*)pval = gain * 100 / max_gain; + status = PJ_SUCCESS; + } else { + status = PJMEDIA_EAUD_NOTREADY; + } + } + break; + */ + + case PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING: + + if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { + PJ_ASSERT_RETURN (strm->engine, PJ_EINVAL); + + TInt max_vol = strm->engine->GetMaxVolume(); + TInt vol = strm->engine->GetVolume(); + + if (max_vol > 0 && vol >= 0) { + * (unsigned*) pval = vol * 100 / max_vol; + status = PJ_SUCCESS; + } else { + status = PJMEDIA_EAUD_NOTREADY; + } + } + + break; + + default: + break; } - + return status; } /* API: set capability */ -static pj_status_t stream_set_cap(pjmedia_aud_stream *s, - pjmedia_aud_dev_cap cap, - const void *pval) +static pj_status_t stream_set_cap (pjmedia_aud_stream *s, + pjmedia_aud_dev_cap cap, + const void *pval) { - struct aps_stream *strm = (struct aps_stream*)s; + + struct aps_stream *strm = (struct aps_stream*) s; pj_status_t status = PJ_ENOTSUP; - PJ_ASSERT_RETURN(s && pval, PJ_EINVAL); + PJ_ASSERT_RETURN (s && pval, PJ_EINVAL); switch (cap) { - case PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE: - if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { - pjmedia_aud_dev_route r = *(const pjmedia_aud_dev_route*)pval; - TInt err; - - PJ_ASSERT_RETURN(strm->engine, PJ_EINVAL); - - switch (r) { - case PJMEDIA_AUD_DEV_ROUTE_DEFAULT: - case PJMEDIA_AUD_DEV_ROUTE_EARPIECE: - err = strm->engine->ActivateSpeaker(EFalse); - status = (err==KErrNone)? PJ_SUCCESS:PJ_RETURN_OS_ERROR(err); - break; - case PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER: - err = strm->engine->ActivateSpeaker(ETrue); - status = (err==KErrNone)? PJ_SUCCESS:PJ_RETURN_OS_ERROR(err); - break; - default: - status = PJ_EINVAL; - break; - } - if (status == PJ_SUCCESS) - strm->param.output_route = r; - } - break; - - /* There is a case that GetMaxGain() stucks, e.g: in N95. */ - /* - case PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING: - if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { - PJ_ASSERT_RETURN(strm->engine, PJ_EINVAL); - - TInt max_gain = strm->engine->GetMaxGain(); - if (max_gain > 0) { - TInt gain, err; - - gain = *(unsigned*)pval * max_gain / 100; - err = strm->engine->SetGain(gain); - status = (err==KErrNone)? PJ_SUCCESS:PJ_RETURN_OS_ERROR(err); - } else { - status = PJMEDIA_EAUD_NOTREADY; - } - if (status == PJ_SUCCESS) - strm->param.input_vol = *(unsigned*)pval; - } - break; - */ - - case PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING: - if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { - PJ_ASSERT_RETURN(strm->engine, PJ_EINVAL); - - TInt max_vol = strm->engine->GetMaxVolume(); - if (max_vol > 0) { - TInt vol, err; - - vol = *(unsigned*)pval * max_vol / 100; - err = strm->engine->SetVolume(vol); - status = (err==KErrNone)? PJ_SUCCESS:PJ_RETURN_OS_ERROR(err); - } else { - status = PJMEDIA_EAUD_NOTREADY; - } - if (status == PJ_SUCCESS) - strm->param.output_vol = *(unsigned*)pval; - } - break; - default: - break; + + case PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE: + + if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { + pjmedia_aud_dev_route r = * (const pjmedia_aud_dev_route*) pval; + TInt err; + + PJ_ASSERT_RETURN (strm->engine, PJ_EINVAL); + + switch (r) { + + case PJMEDIA_AUD_DEV_ROUTE_DEFAULT: + + case PJMEDIA_AUD_DEV_ROUTE_EARPIECE: + err = strm->engine->ActivateSpeaker (EFalse); + status = (err==KErrNone) ? PJ_SUCCESS:PJ_RETURN_OS_ERROR (err); + break; + + case PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER: + err = strm->engine->ActivateSpeaker (ETrue); + status = (err==KErrNone) ? PJ_SUCCESS:PJ_RETURN_OS_ERROR (err); + break; + + default: + status = PJ_EINVAL; + break; + } + + if (status == PJ_SUCCESS) + strm->param.output_route = r; + } + + break; + + /* There is a case that GetMaxGain() stucks, e.g: in N95. */ + /* + case PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING: + if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { + PJ_ASSERT_RETURN(strm->engine, PJ_EINVAL); + + TInt max_gain = strm->engine->GetMaxGain(); + if (max_gain > 0) { + TInt gain, err; + + gain = *(unsigned*)pval * max_gain / 100; + err = strm->engine->SetGain(gain); + status = (err==KErrNone)? PJ_SUCCESS:PJ_RETURN_OS_ERROR(err); + } else { + status = PJMEDIA_EAUD_NOTREADY; + } + if (status == PJ_SUCCESS) + strm->param.input_vol = *(unsigned*)pval; + } + break; + */ + + case PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING: + + if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { + PJ_ASSERT_RETURN (strm->engine, PJ_EINVAL); + + TInt max_vol = strm->engine->GetMaxVolume(); + + if (max_vol > 0) { + TInt vol, err; + + vol = * (unsigned*) pval * max_vol / 100; + err = strm->engine->SetVolume (vol); + status = (err==KErrNone) ? PJ_SUCCESS:PJ_RETURN_OS_ERROR (err); + } else { + status = PJMEDIA_EAUD_NOTREADY; + } + + if (status == PJ_SUCCESS) + strm->param.output_vol = * (unsigned*) pval; + } + + break; + + default: + break; } - + return status; } /* API: Start stream. */ -static pj_status_t stream_start(pjmedia_aud_stream *strm) +static pj_status_t stream_start (pjmedia_aud_stream *strm) { - struct aps_stream *stream = (struct aps_stream*)strm; - PJ_ASSERT_RETURN(stream, PJ_EINVAL); + struct aps_stream *stream = (struct aps_stream*) strm; + + PJ_ASSERT_RETURN (stream, PJ_EINVAL); if (stream->engine) { - TInt err = stream->engine->StartL(); - if (err != KErrNone) - return PJ_RETURN_OS_ERROR(err); + TInt err = stream->engine->StartL(); + + if (err != KErrNone) + return PJ_RETURN_OS_ERROR (err); } return PJ_SUCCESS; } /* API: Stop stream. */ -static pj_status_t stream_stop(pjmedia_aud_stream *strm) +static pj_status_t stream_stop (pjmedia_aud_stream *strm) { - struct aps_stream *stream = (struct aps_stream*)strm; - PJ_ASSERT_RETURN(stream, PJ_EINVAL); + struct aps_stream *stream = (struct aps_stream*) strm; + + PJ_ASSERT_RETURN (stream, PJ_EINVAL); if (stream->engine) { - stream->engine->Stop(); + stream->engine->Stop(); } return PJ_SUCCESS; @@ -1731,28 +1862,31 @@ static pj_status_t stream_stop(pjmedia_aud_stream *strm) /* API: Destroy stream. */ -static pj_status_t stream_destroy(pjmedia_aud_stream *strm) +static pj_status_t stream_destroy (pjmedia_aud_stream *strm) { - struct aps_stream *stream = (struct aps_stream*)strm; - PJ_ASSERT_RETURN(stream, PJ_EINVAL); + struct aps_stream *stream = (struct aps_stream*) strm; + + PJ_ASSERT_RETURN (stream, PJ_EINVAL); - stream_stop(strm); + stream_stop (strm); delete stream->engine; stream->engine = NULL; if (stream->param.ext_fmt.id == PJMEDIA_FORMAT_G729) { - TBitStream *g729_bitstream = (TBitStream*)stream->strm_data; - stream->strm_data = NULL; - delete g729_bitstream; + TBitStream *g729_bitstream = (TBitStream*) stream->strm_data; + stream->strm_data = NULL; + delete g729_bitstream; } pj_pool_t *pool; + pool = stream->pool; + if (pool) { - stream->pool = NULL; - pj_pool_release(pool); + stream->pool = NULL; + pj_pool_release (pool); } return PJ_SUCCESS; diff --git a/sflphone-common/libs/pjproject/pjmedia/src/pjmedia-audiodev/symb_mda_dev.cpp b/sflphone-common/libs/pjproject/pjmedia/src/pjmedia-audiodev/symb_mda_dev.cpp index d943f2bd25aa7c289c34e664a9aa6ff072e39a21..44ba2f893edea6f7e70b438d4798e531b8eb6e05 100644 --- a/sflphone-common/libs/pjproject/pjmedia/src/pjmedia-audiodev/symb_mda_dev.cpp +++ b/sflphone-common/libs/pjproject/pjmedia/src/pjmedia-audiodev/symb_mda_dev.cpp @@ -1,5 +1,5 @@ /* $Id: symb_mda_dev.cpp 2777 2009-06-19 09:15:59Z bennylp $ */ -/* +/* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org> * @@ -15,7 +15,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <pjmedia-audiodev/audiodev_imp.h> #include <pjmedia-audiodev/errno.h> @@ -32,7 +32,7 @@ * This file provides sound implementation for Symbian Audio Streaming * device. Application using this sound abstraction must link with: * - mediaclientaudiostream.lib, and - * - mediaclientaudioinputstream.lib + * - mediaclientaudioinputstream.lib */ #include <mda/common/audio.h> #include <mdaaudiooutputstream.h> @@ -52,8 +52,8 @@ /* MDA factory */ -struct mda_factory -{ + +struct mda_factory { pjmedia_aud_dev_factory base; pj_pool_t *pool; pj_pool_factory *pf; @@ -61,15 +61,17 @@ struct mda_factory }; /* Forward declaration of internal engine. */ + class CPjAudioInputEngine; + class CPjAudioOutputEngine; /* MDA stream. */ -struct mda_stream -{ + +struct mda_stream { // Base pjmedia_aud_stream base; /**< Base class. */ - + // Pool pj_pool_t *pool; /**< Memory pool. */ @@ -83,38 +85,37 @@ struct mda_stream /* Prototypes */ -static pj_status_t factory_init(pjmedia_aud_dev_factory *f); -static pj_status_t factory_destroy(pjmedia_aud_dev_factory *f); -static unsigned factory_get_dev_count(pjmedia_aud_dev_factory *f); -static pj_status_t factory_get_dev_info(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_dev_info *info); -static pj_status_t factory_default_param(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_param *param); -static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, - const pjmedia_aud_param *param, - pjmedia_aud_rec_cb rec_cb, - pjmedia_aud_play_cb play_cb, - void *user_data, - pjmedia_aud_stream **p_aud_strm); - -static pj_status_t stream_get_param(pjmedia_aud_stream *strm, - pjmedia_aud_param *param); -static pj_status_t stream_get_cap(pjmedia_aud_stream *strm, - pjmedia_aud_dev_cap cap, - void *value); -static pj_status_t stream_set_cap(pjmedia_aud_stream *strm, - pjmedia_aud_dev_cap cap, - const void *value); -static pj_status_t stream_start(pjmedia_aud_stream *strm); -static pj_status_t stream_stop(pjmedia_aud_stream *strm); -static pj_status_t stream_destroy(pjmedia_aud_stream *strm); +static pj_status_t factory_init (pjmedia_aud_dev_factory *f); +static pj_status_t factory_destroy (pjmedia_aud_dev_factory *f); +static unsigned factory_get_dev_count (pjmedia_aud_dev_factory *f); +static pj_status_t factory_get_dev_info (pjmedia_aud_dev_factory *f, + unsigned index, + pjmedia_aud_dev_info *info); +static pj_status_t factory_default_param (pjmedia_aud_dev_factory *f, + unsigned index, + pjmedia_aud_param *param); +static pj_status_t factory_create_stream (pjmedia_aud_dev_factory *f, + const pjmedia_aud_param *param, + pjmedia_aud_rec_cb rec_cb, + pjmedia_aud_play_cb play_cb, + void *user_data, + pjmedia_aud_stream **p_aud_strm); + +static pj_status_t stream_get_param (pjmedia_aud_stream *strm, + pjmedia_aud_param *param); +static pj_status_t stream_get_cap (pjmedia_aud_stream *strm, + pjmedia_aud_dev_cap cap, + void *value); +static pj_status_t stream_set_cap (pjmedia_aud_stream *strm, + pjmedia_aud_dev_cap cap, + const void *value); +static pj_status_t stream_start (pjmedia_aud_stream *strm); +static pj_status_t stream_stop (pjmedia_aud_stream *strm); +static pj_status_t stream_destroy (pjmedia_aud_stream *strm); /* Operations */ -static pjmedia_aud_dev_factory_op factory_op = -{ +static pjmedia_aud_dev_factory_op factory_op = { &factory_init, &factory_destroy, &factory_get_dev_count, @@ -123,8 +124,7 @@ static pjmedia_aud_dev_factory_op factory_op = &factory_create_stream }; -static pjmedia_aud_stream_op stream_op = -{ +static pjmedia_aud_stream_op stream_op = { &stream_get_param, &stream_get_cap, &stream_set_cap, @@ -137,141 +137,171 @@ static pjmedia_aud_stream_op stream_op = /* * Convert clock rate to Symbian's TMdaAudioDataSettings capability. */ -static TInt get_clock_rate_cap(unsigned clock_rate) +static TInt get_clock_rate_cap (unsigned clock_rate) { switch (clock_rate) { - case 8000: return TMdaAudioDataSettings::ESampleRate8000Hz; - case 11025: return TMdaAudioDataSettings::ESampleRate11025Hz; - case 12000: return TMdaAudioDataSettings::ESampleRate12000Hz; - case 16000: return TMdaAudioDataSettings::ESampleRate16000Hz; - case 22050: return TMdaAudioDataSettings::ESampleRate22050Hz; - case 24000: return TMdaAudioDataSettings::ESampleRate24000Hz; - case 32000: return TMdaAudioDataSettings::ESampleRate32000Hz; - case 44100: return TMdaAudioDataSettings::ESampleRate44100Hz; - case 48000: return TMdaAudioDataSettings::ESampleRate48000Hz; - case 64000: return TMdaAudioDataSettings::ESampleRate64000Hz; - case 96000: return TMdaAudioDataSettings::ESampleRate96000Hz; - default: - return 0; + + case 8000: + return TMdaAudioDataSettings::ESampleRate8000Hz; + + case 11025: + return TMdaAudioDataSettings::ESampleRate11025Hz; + + case 12000: + return TMdaAudioDataSettings::ESampleRate12000Hz; + + case 16000: + return TMdaAudioDataSettings::ESampleRate16000Hz; + + case 22050: + return TMdaAudioDataSettings::ESampleRate22050Hz; + + case 24000: + return TMdaAudioDataSettings::ESampleRate24000Hz; + + case 32000: + return TMdaAudioDataSettings::ESampleRate32000Hz; + + case 44100: + return TMdaAudioDataSettings::ESampleRate44100Hz; + + case 48000: + return TMdaAudioDataSettings::ESampleRate48000Hz; + + case 64000: + return TMdaAudioDataSettings::ESampleRate64000Hz; + + case 96000: + return TMdaAudioDataSettings::ESampleRate96000Hz; + + default: + return 0; } } /* * Convert number of channels into Symbian's TMdaAudioDataSettings capability. */ -static TInt get_channel_cap(unsigned channel_count) +static TInt get_channel_cap (unsigned channel_count) { switch (channel_count) { - case 1: return TMdaAudioDataSettings::EChannelsMono; - case 2: return TMdaAudioDataSettings::EChannelsStereo; - default: - return 0; + + case 1: + return TMdaAudioDataSettings::EChannelsMono; + + case 2: + return TMdaAudioDataSettings::EChannelsStereo; + + default: + return 0; } } /* * Utility: print sound device error */ -static void snd_perror(const char *title, TInt rc) +static void snd_perror (const char *title, TInt rc) { - PJ_LOG(1,(THIS_FILE, "%s: error code %d", title, rc)); + PJ_LOG (1, (THIS_FILE, "%s: error code %d", title, rc)); } - + ////////////////////////////////////////////////////////////////////////////// // /* * Implementation: Symbian Input Stream. */ + class CPjAudioInputEngine : public CBase, MMdaAudioInputStreamCallback { -public: - enum State - { - STATE_INACTIVE, - STATE_ACTIVE, - }; - - ~CPjAudioInputEngine(); - - static CPjAudioInputEngine *NewL(struct mda_stream *parent_strm, - pjmedia_aud_rec_cb rec_cb, - void *user_data); - - static CPjAudioInputEngine *NewLC(struct mda_stream *parent_strm, - pjmedia_aud_rec_cb rec_cb, - void *user_data); - - pj_status_t StartRecord(); - void Stop(); - - pj_status_t SetGain(TInt gain) { - if (iInputStream_) { - iInputStream_->SetGain(gain); - return PJ_SUCCESS; - } else - return PJ_EINVALIDOP; - } - - TInt GetGain() { - if (iInputStream_) { - return iInputStream_->Gain(); - } else - return PJ_EINVALIDOP; - } - TInt GetMaxGain() { - if (iInputStream_) { - return iInputStream_->MaxGain(); - } else - return PJ_EINVALIDOP; - } - -private: - State state_; - struct mda_stream *parentStrm_; - pjmedia_aud_rec_cb recCb_; - void *userData_; - CMdaAudioInputStream *iInputStream_; - HBufC8 *iStreamBuffer_; - TPtr8 iFramePtr_; - TInt lastError_; - pj_uint32_t timeStamp_; - - // cache variable - // to avoid calculating frame length repeatedly - TInt frameLen_; - - // sometimes recorded size != requested framesize, so let's - // provide a buffer to make sure the rec callback returning - // framesize as requested. - TUint8 *frameRecBuf_; - TInt frameRecBufLen_; - - CPjAudioInputEngine(struct mda_stream *parent_strm, - pjmedia_aud_rec_cb rec_cb, - void *user_data); - void ConstructL(); - TPtr8 & GetFrame(); - -public: - virtual void MaiscOpenComplete(TInt aError); - virtual void MaiscBufferCopied(TInt aError, const TDesC8 &aBuffer); - virtual void MaiscRecordComplete(TInt aError); + public: + enum State { + STATE_INACTIVE, + STATE_ACTIVE, + }; + + ~CPjAudioInputEngine(); + + static CPjAudioInputEngine *NewL (struct mda_stream *parent_strm, + pjmedia_aud_rec_cb rec_cb, + void *user_data); + + static CPjAudioInputEngine *NewLC (struct mda_stream *parent_strm, + pjmedia_aud_rec_cb rec_cb, + void *user_data); + + pj_status_t StartRecord(); + void Stop(); + + pj_status_t SetGain (TInt gain) { + if (iInputStream_) { + iInputStream_->SetGain (gain); + return PJ_SUCCESS; + } else + return PJ_EINVALIDOP; + } + + TInt GetGain() { + if (iInputStream_) { + return iInputStream_->Gain(); + } else + return PJ_EINVALIDOP; + } + + TInt GetMaxGain() { + if (iInputStream_) { + return iInputStream_->MaxGain(); + } else + return PJ_EINVALIDOP; + } + + private: + State state_; + + struct mda_stream *parentStrm_; + pjmedia_aud_rec_cb recCb_; + void *userData_; + CMdaAudioInputStream *iInputStream_; + HBufC8 *iStreamBuffer_; + TPtr8 iFramePtr_; + TInt lastError_; + pj_uint32_t timeStamp_; + + // cache variable + // to avoid calculating frame length repeatedly + TInt frameLen_; + + // sometimes recorded size != requested framesize, so let's + // provide a buffer to make sure the rec callback returning + // framesize as requested. + TUint8 *frameRecBuf_; + TInt frameRecBufLen_; + + CPjAudioInputEngine (struct mda_stream *parent_strm, + pjmedia_aud_rec_cb rec_cb, + void *user_data); + void ConstructL(); + TPtr8 & GetFrame(); + + public: + virtual void MaiscOpenComplete (TInt aError); + virtual void MaiscBufferCopied (TInt aError, const TDesC8 &aBuffer); + virtual void MaiscRecordComplete (TInt aError); }; -CPjAudioInputEngine::CPjAudioInputEngine(struct mda_stream *parent_strm, - pjmedia_aud_rec_cb rec_cb, - void *user_data) - : state_(STATE_INACTIVE), parentStrm_(parent_strm), - recCb_(rec_cb), userData_(user_data), - iInputStream_(NULL), iStreamBuffer_(NULL), iFramePtr_(0, 0), - lastError_(KErrNone), timeStamp_(0), - frameLen_(parent_strm->param.samples_per_frame * - BYTES_PER_SAMPLE), - frameRecBuf_(NULL), frameRecBufLen_(0) +CPjAudioInputEngine::CPjAudioInputEngine (struct mda_stream *parent_strm, + pjmedia_aud_rec_cb rec_cb, + void *user_data) + : state_ (STATE_INACTIVE), parentStrm_ (parent_strm), + recCb_ (rec_cb), userData_ (user_data), + iInputStream_ (NULL), iStreamBuffer_ (NULL), iFramePtr_ (0, 0), + lastError_ (KErrNone), timeStamp_ (0), + frameLen_ (parent_strm->param.samples_per_frame * + BYTES_PER_SAMPLE), + frameRecBuf_ (NULL), frameRecBufLen_ (0) { } @@ -281,7 +311,7 @@ CPjAudioInputEngine::~CPjAudioInputEngine() delete iStreamBuffer_; iStreamBuffer_ = NULL; - + delete [] frameRecBuf_; frameRecBuf_ = NULL; frameRecBufLen_ = 0; @@ -289,33 +319,33 @@ CPjAudioInputEngine::~CPjAudioInputEngine() void CPjAudioInputEngine::ConstructL() { - iStreamBuffer_ = HBufC8::NewL(frameLen_); - CleanupStack::PushL(iStreamBuffer_); + iStreamBuffer_ = HBufC8::NewL (frameLen_); + CleanupStack::PushL (iStreamBuffer_); frameRecBuf_ = new TUint8[frameLen_*2]; - CleanupStack::PushL(frameRecBuf_); + CleanupStack::PushL (frameRecBuf_); } -CPjAudioInputEngine *CPjAudioInputEngine::NewLC(struct mda_stream *parent, - pjmedia_aud_rec_cb rec_cb, - void *user_data) +CPjAudioInputEngine *CPjAudioInputEngine::NewLC (struct mda_stream *parent, + pjmedia_aud_rec_cb rec_cb, + void *user_data) { - CPjAudioInputEngine* self = new (ELeave) CPjAudioInputEngine(parent, - rec_cb, - user_data); - CleanupStack::PushL(self); + CPjAudioInputEngine* self = new (ELeave) CPjAudioInputEngine (parent, + rec_cb, + user_data); + CleanupStack::PushL (self); self->ConstructL(); return self; } -CPjAudioInputEngine *CPjAudioInputEngine::NewL(struct mda_stream *parent, - pjmedia_aud_rec_cb rec_cb, - void *user_data) +CPjAudioInputEngine *CPjAudioInputEngine::NewL (struct mda_stream *parent, + pjmedia_aud_rec_cb rec_cb, + void *user_data) { - CPjAudioInputEngine *self = NewLC(parent, rec_cb, user_data); - CleanupStack::Pop(self->frameRecBuf_); - CleanupStack::Pop(self->iStreamBuffer_); - CleanupStack::Pop(self); + CPjAudioInputEngine *self = NewLC (parent, rec_cb, user_data); + CleanupStack::Pop (self->frameRecBuf_); + CleanupStack::Pop (self->iStreamBuffer_); + CleanupStack::Pop (self); return self; } @@ -325,44 +355,50 @@ pj_status_t CPjAudioInputEngine::StartRecord() // Ignore command if recording is in progress. if (state_ == STATE_ACTIVE) - return PJ_SUCCESS; + return PJ_SUCCESS; // According to Nokia's AudioStream example, some 2nd Edition, FP2 devices - // (such as Nokia 6630) require the stream to be reconstructed each time + // (such as Nokia 6630) require the stream to be reconstructed each time // before calling Open() - otherwise the callback never gets called. // For uniform behavior, lets just delete/re-create the stream for all // devices. // Destroy existing stream. if (iInputStream_) delete iInputStream_; + iInputStream_ = NULL; // Create the stream. - TRAPD(err, iInputStream_ = CMdaAudioInputStream::NewL(*this)); + TRAPD (err, iInputStream_ = CMdaAudioInputStream::NewL (*this)); + if (err != KErrNone) - return PJ_RETURN_OS_ERROR(err); + return PJ_RETURN_OS_ERROR (err); // Initialize settings. TMdaAudioDataSettings iStreamSettings; - iStreamSettings.iChannels = - get_channel_cap(parentStrm_->param.channel_count); - iStreamSettings.iSampleRate = - get_clock_rate_cap(parentStrm_->param.clock_rate); - - pj_assert(iStreamSettings.iChannels != 0 && - iStreamSettings.iSampleRate != 0); - - PJ_LOG(4,(THIS_FILE, "Opening sound device for capture, " - "clock rate=%d, channel count=%d..", - parentStrm_->param.clock_rate, - parentStrm_->param.channel_count)); - + + iStreamSettings.iChannels = + get_channel_cap (parentStrm_->param.channel_count); + + iStreamSettings.iSampleRate = + get_clock_rate_cap (parentStrm_->param.clock_rate); + + pj_assert (iStreamSettings.iChannels != 0 && + iStreamSettings.iSampleRate != 0); + + PJ_LOG (4, (THIS_FILE, "Opening sound device for capture, " + "clock rate=%d, channel count=%d..", + parentStrm_->param.clock_rate, + parentStrm_->param.channel_count)); + // Open stream. lastError_ = KRequestPending; - iInputStream_->Open(&iStreamSettings); - + + iInputStream_->Open (&iStreamSettings); + // Success - PJ_LOG(4,(THIS_FILE, "Sound capture started.")); + PJ_LOG (4, (THIS_FILE, "Sound capture started.")); + return PJ_SUCCESS; } @@ -371,113 +407,121 @@ void CPjAudioInputEngine::Stop() { // If capture is in progress, stop it. if (iInputStream_ && state_ == STATE_ACTIVE) { - lastError_ = KRequestPending; - iInputStream_->Stop(); + lastError_ = KRequestPending; + iInputStream_->Stop(); - // Wait until it's actually stopped - while (lastError_ == KRequestPending) - pj_symbianos_poll(-1, 100); + // Wait until it's actually stopped + + while (lastError_ == KRequestPending) + pj_symbianos_poll (-1, 100); } if (iInputStream_) { - delete iInputStream_; - iInputStream_ = NULL; + delete iInputStream_; + iInputStream_ = NULL; } - + state_ = STATE_INACTIVE; } -TPtr8 & CPjAudioInputEngine::GetFrame() +TPtr8 & CPjAudioInputEngine::GetFrame() { //iStreamBuffer_->Des().FillZ(frameLen_); - iFramePtr_.Set((TUint8*)(iStreamBuffer_->Ptr()), frameLen_, frameLen_); + iFramePtr_.Set ( (TUint8*) (iStreamBuffer_->Ptr()), frameLen_, frameLen_); return iFramePtr_; } -void CPjAudioInputEngine::MaiscOpenComplete(TInt aError) +void CPjAudioInputEngine::MaiscOpenComplete (TInt aError) { lastError_ = aError; + if (aError != KErrNone) { - snd_perror("Error in MaiscOpenComplete()", aError); - return; + snd_perror ("Error in MaiscOpenComplete()", aError); + return; } // set stream priority to normal and time sensitive - iInputStream_->SetPriority(EPriorityNormal, - EMdaPriorityPreferenceTime); + iInputStream_->SetPriority (EPriorityNormal, + EMdaPriorityPreferenceTime); // Read the first frame. TPtr8 & frm = GetFrame(); - TRAPD(err2, iInputStream_->ReadL(frm)); + + TRAPD (err2, iInputStream_->ReadL (frm)); + if (err2) { - PJ_LOG(4,(THIS_FILE, "Exception in iInputStream_->ReadL()")); + PJ_LOG (4, (THIS_FILE, "Exception in iInputStream_->ReadL()")); } } -void CPjAudioInputEngine::MaiscBufferCopied(TInt aError, - const TDesC8 &aBuffer) +void CPjAudioInputEngine::MaiscBufferCopied (TInt aError, + const TDesC8 &aBuffer) { lastError_ = aError; + if (aError != KErrNone) { - snd_perror("Error in MaiscBufferCopied()", aError); - return; + snd_perror ("Error in MaiscBufferCopied()", aError); + return; } if (frameRecBufLen_ || aBuffer.Length() < frameLen_) { - pj_memcpy(frameRecBuf_ + frameRecBufLen_, (void*) aBuffer.Ptr(), aBuffer.Length()); - frameRecBufLen_ += aBuffer.Length(); + pj_memcpy (frameRecBuf_ + frameRecBufLen_, (void*) aBuffer.Ptr(), aBuffer.Length()); + frameRecBufLen_ += aBuffer.Length(); } if (frameRecBufLen_) { - while (frameRecBufLen_ >= frameLen_) { - pjmedia_frame f; - - f.type = PJMEDIA_FRAME_TYPE_AUDIO; - f.buf = frameRecBuf_; - f.size = frameLen_; - f.timestamp.u32.lo = timeStamp_; - f.bit_info = 0; - - // Call the callback. - recCb_(userData_, &f); - // Increment timestamp. - timeStamp_ += parentStrm_->param.samples_per_frame; - - frameRecBufLen_ -= frameLen_; - pj_memmove(frameRecBuf_, frameRecBuf_+frameLen_, frameRecBufLen_); - } + while (frameRecBufLen_ >= frameLen_) { + pjmedia_frame f; + + f.type = PJMEDIA_FRAME_TYPE_AUDIO; + f.buf = frameRecBuf_; + f.size = frameLen_; + f.timestamp.u32.lo = timeStamp_; + f.bit_info = 0; + + // Call the callback. + recCb_ (userData_, &f); + // Increment timestamp. + timeStamp_ += parentStrm_->param.samples_per_frame; + + frameRecBufLen_ -= frameLen_; + pj_memmove (frameRecBuf_, frameRecBuf_+frameLen_, frameRecBufLen_); + } } else { - pjmedia_frame f; - - f.type = PJMEDIA_FRAME_TYPE_AUDIO; - f.buf = (void*)aBuffer.Ptr(); - f.size = aBuffer.Length(); - f.timestamp.u32.lo = timeStamp_; - f.bit_info = 0; - - // Call the callback. - recCb_(userData_, &f); - - // Increment timestamp. - timeStamp_ += parentStrm_->param.samples_per_frame; + pjmedia_frame f; + + f.type = PJMEDIA_FRAME_TYPE_AUDIO; + f.buf = (void*) aBuffer.Ptr(); + f.size = aBuffer.Length(); + f.timestamp.u32.lo = timeStamp_; + f.bit_info = 0; + + // Call the callback. + recCb_ (userData_, &f); + + // Increment timestamp. + timeStamp_ += parentStrm_->param.samples_per_frame; } // Record next frame TPtr8 & frm = GetFrame(); - TRAPD(err2, iInputStream_->ReadL(frm)); + + TRAPD (err2, iInputStream_->ReadL (frm)); + if (err2) { - PJ_LOG(4,(THIS_FILE, "Exception in iInputStream_->ReadL()")); + PJ_LOG (4, (THIS_FILE, "Exception in iInputStream_->ReadL()")); } } -void CPjAudioInputEngine::MaiscRecordComplete(TInt aError) +void CPjAudioInputEngine::MaiscRecordComplete (TInt aError) { lastError_ = aError; state_ = STATE_INACTIVE; + if (aError != KErrNone && aError != KErrCancel) { - snd_perror("Error in MaiscRecordComplete()", aError); + snd_perror ("Error in MaiscRecordComplete()", aError); } } @@ -492,77 +536,78 @@ void CPjAudioInputEngine::MaiscRecordComplete(TInt aError) class CPjAudioOutputEngine : public CBase, MMdaAudioOutputStreamCallback { -public: - enum State - { - STATE_INACTIVE, - STATE_ACTIVE, - }; - - ~CPjAudioOutputEngine(); - - static CPjAudioOutputEngine *NewL(struct mda_stream *parent_strm, - pjmedia_aud_play_cb play_cb, - void *user_data); - - static CPjAudioOutputEngine *NewLC(struct mda_stream *parent_strm, - pjmedia_aud_play_cb rec_cb, - void *user_data); - - pj_status_t StartPlay(); - void Stop(); - - pj_status_t SetVolume(TInt vol) { - if (iOutputStream_) { - iOutputStream_->SetVolume(vol); - return PJ_SUCCESS; - } else - return PJ_EINVALIDOP; - } - - TInt GetVolume() { - if (iOutputStream_) { - return iOutputStream_->Volume(); - } else - return PJ_EINVALIDOP; - } - - TInt GetMaxVolume() { - if (iOutputStream_) { - return iOutputStream_->MaxVolume(); - } else - return PJ_EINVALIDOP; - } -private: - State state_; - struct mda_stream *parentStrm_; - pjmedia_aud_play_cb playCb_; - void *userData_; - CMdaAudioOutputStream *iOutputStream_; - TUint8 *frameBuf_; - unsigned frameBufSize_; - TPtrC8 frame_; - TInt lastError_; - unsigned timestamp_; - - CPjAudioOutputEngine(struct mda_stream *parent_strm, - pjmedia_aud_play_cb play_cb, - void *user_data); - void ConstructL(); - - virtual void MaoscOpenComplete(TInt aError); - virtual void MaoscBufferCopied(TInt aError, const TDesC8& aBuffer); - virtual void MaoscPlayComplete(TInt aError); + public: + enum State { + STATE_INACTIVE, + STATE_ACTIVE, + }; + + ~CPjAudioOutputEngine(); + + static CPjAudioOutputEngine *NewL (struct mda_stream *parent_strm, + pjmedia_aud_play_cb play_cb, + void *user_data); + + static CPjAudioOutputEngine *NewLC (struct mda_stream *parent_strm, + pjmedia_aud_play_cb rec_cb, + void *user_data); + + pj_status_t StartPlay(); + void Stop(); + + pj_status_t SetVolume (TInt vol) { + if (iOutputStream_) { + iOutputStream_->SetVolume (vol); + return PJ_SUCCESS; + } else + return PJ_EINVALIDOP; + } + + TInt GetVolume() { + if (iOutputStream_) { + return iOutputStream_->Volume(); + } else + return PJ_EINVALIDOP; + } + + TInt GetMaxVolume() { + if (iOutputStream_) { + return iOutputStream_->MaxVolume(); + } else + return PJ_EINVALIDOP; + } + + private: + State state_; + + struct mda_stream *parentStrm_; + pjmedia_aud_play_cb playCb_; + void *userData_; + CMdaAudioOutputStream *iOutputStream_; + TUint8 *frameBuf_; + unsigned frameBufSize_; + TPtrC8 frame_; + TInt lastError_; + unsigned timestamp_; + + CPjAudioOutputEngine (struct mda_stream *parent_strm, + pjmedia_aud_play_cb play_cb, + void *user_data); + void ConstructL(); + + virtual void MaoscOpenComplete (TInt aError); + virtual void MaoscBufferCopied (TInt aError, const TDesC8& aBuffer); + virtual void MaoscPlayComplete (TInt aError); }; -CPjAudioOutputEngine::CPjAudioOutputEngine(struct mda_stream *parent_strm, - pjmedia_aud_play_cb play_cb, - void *user_data) -: state_(STATE_INACTIVE), parentStrm_(parent_strm), playCb_(play_cb), - userData_(user_data), iOutputStream_(NULL), frameBuf_(NULL), - lastError_(KErrNone), timestamp_(0) +CPjAudioOutputEngine::CPjAudioOutputEngine (struct mda_stream *parent_strm, + pjmedia_aud_play_cb play_cb, + void *user_data) + : state_ (STATE_INACTIVE), parentStrm_ (parent_strm), playCb_ (play_cb), + userData_ (user_data), iOutputStream_ (NULL), frameBuf_ (NULL), + lastError_ (KErrNone), timestamp_ (0) { } @@ -570,36 +615,36 @@ CPjAudioOutputEngine::CPjAudioOutputEngine(struct mda_stream *parent_strm, void CPjAudioOutputEngine::ConstructL() { frameBufSize_ = parentStrm_->param.samples_per_frame * - BYTES_PER_SAMPLE; + BYTES_PER_SAMPLE; frameBuf_ = new TUint8[frameBufSize_]; } CPjAudioOutputEngine::~CPjAudioOutputEngine() { Stop(); - delete [] frameBuf_; + delete [] frameBuf_; } CPjAudioOutputEngine * -CPjAudioOutputEngine::NewLC(struct mda_stream *parent_strm, - pjmedia_aud_play_cb play_cb, - void *user_data) +CPjAudioOutputEngine::NewLC (struct mda_stream *parent_strm, + pjmedia_aud_play_cb play_cb, + void *user_data) { - CPjAudioOutputEngine* self = new (ELeave) CPjAudioOutputEngine(parent_strm, - play_cb, - user_data); - CleanupStack::PushL(self); + CPjAudioOutputEngine* self = new (ELeave) CPjAudioOutputEngine (parent_strm, + play_cb, + user_data); + CleanupStack::PushL (self); self->ConstructL(); return self; } CPjAudioOutputEngine * -CPjAudioOutputEngine::NewL(struct mda_stream *parent_strm, - pjmedia_aud_play_cb play_cb, - void *user_data) +CPjAudioOutputEngine::NewL (struct mda_stream *parent_strm, + pjmedia_aud_play_cb play_cb, + void *user_data) { - CPjAudioOutputEngine *self = NewLC(parent_strm, play_cb, user_data); - CleanupStack::Pop(self); + CPjAudioOutputEngine *self = NewLC (parent_strm, play_cb, user_data); + CleanupStack::Pop (self); return self; } @@ -607,38 +652,44 @@ pj_status_t CPjAudioOutputEngine::StartPlay() { // Ignore command if playing is in progress. if (state_ == STATE_ACTIVE) - return PJ_SUCCESS; - + return PJ_SUCCESS; + // Destroy existing stream. if (iOutputStream_) delete iOutputStream_; + iOutputStream_ = NULL; - + // Create the stream - TRAPD(err, iOutputStream_ = CMdaAudioOutputStream::NewL(*this)); + TRAPD (err, iOutputStream_ = CMdaAudioOutputStream::NewL (*this)); + if (err != KErrNone) - return PJ_RETURN_OS_ERROR(err); - + return PJ_RETURN_OS_ERROR (err); + // Initialize settings. TMdaAudioDataSettings iStreamSettings; - iStreamSettings.iChannels = - get_channel_cap(parentStrm_->param.channel_count); - iStreamSettings.iSampleRate = - get_clock_rate_cap(parentStrm_->param.clock_rate); - - pj_assert(iStreamSettings.iChannels != 0 && - iStreamSettings.iSampleRate != 0); - - PJ_LOG(4,(THIS_FILE, "Opening sound device for playback, " - "clock rate=%d, channel count=%d..", - parentStrm_->param.clock_rate, - parentStrm_->param.channel_count)); + + iStreamSettings.iChannels = + get_channel_cap (parentStrm_->param.channel_count); + + iStreamSettings.iSampleRate = + get_clock_rate_cap (parentStrm_->param.clock_rate); + + pj_assert (iStreamSettings.iChannels != 0 && + iStreamSettings.iSampleRate != 0); + + PJ_LOG (4, (THIS_FILE, "Opening sound device for playback, " + "clock rate=%d, channel count=%d..", + parentStrm_->param.clock_rate, + parentStrm_->param.channel_count)); // Open stream. lastError_ = KRequestPending; - iOutputStream_->Open(&iStreamSettings); + + iOutputStream_->Open (&iStreamSettings); // Success - PJ_LOG(4,(THIS_FILE, "Sound playback started")); + PJ_LOG (4, (THIS_FILE, "Sound playback started")); + return PJ_SUCCESS; } @@ -647,131 +698,137 @@ void CPjAudioOutputEngine::Stop() { // Stop stream if it's playing if (iOutputStream_ && state_ != STATE_INACTIVE) { - lastError_ = KRequestPending; - iOutputStream_->Stop(); + lastError_ = KRequestPending; + iOutputStream_->Stop(); - // Wait until it's actually stopped - while (lastError_ == KRequestPending) - pj_symbianos_poll(-1, 100); + // Wait until it's actually stopped + + while (lastError_ == KRequestPending) + pj_symbianos_poll (-1, 100); } - - if (iOutputStream_) { - delete iOutputStream_; - iOutputStream_ = NULL; + + if (iOutputStream_) { + delete iOutputStream_; + iOutputStream_ = NULL; } - + state_ = STATE_INACTIVE; } -void CPjAudioOutputEngine::MaoscOpenComplete(TInt aError) +void CPjAudioOutputEngine::MaoscOpenComplete (TInt aError) { lastError_ = aError; - + if (aError==KErrNone) { - // output stream opened succesfully, set status to Active - state_ = STATE_ACTIVE; - - // set stream properties, 16bit 8KHz mono - TMdaAudioDataSettings iSettings; - iSettings.iChannels = - get_channel_cap(parentStrm_->param.channel_count); - iSettings.iSampleRate = - get_clock_rate_cap(parentStrm_->param.clock_rate); - - iOutputStream_->SetAudioPropertiesL(iSettings.iSampleRate, - iSettings.iChannels); - - // set volume to 1/2th of stream max volume - iOutputStream_->SetVolume(iOutputStream_->MaxVolume()/2); - - // set stream priority to normal and time sensitive - iOutputStream_->SetPriority(EPriorityNormal, - EMdaPriorityPreferenceTime); - - // Call callback to retrieve frame from upstream. - pjmedia_frame f; - pj_status_t status; - - f.type = PJMEDIA_FRAME_TYPE_AUDIO; - f.buf = frameBuf_; - f.size = frameBufSize_; - f.timestamp.u32.lo = timestamp_; - f.bit_info = 0; - - status = playCb_(this->userData_, &f); - if (status != PJ_SUCCESS) { - this->Stop(); - return; - } - - if (f.type != PJMEDIA_FRAME_TYPE_AUDIO) - pj_bzero(frameBuf_, frameBufSize_); - - // Increment timestamp. - timestamp_ += (frameBufSize_ / BYTES_PER_SAMPLE); - - // issue WriteL() to write the first audio data block, - // subsequent calls to WriteL() will be issued in - // MMdaAudioOutputStreamCallback::MaoscBufferCopied() - // until whole data buffer is written. - frame_.Set(frameBuf_, frameBufSize_); - iOutputStream_->WriteL(frame_); + // output stream opened succesfully, set status to Active + state_ = STATE_ACTIVE; + + // set stream properties, 16bit 8KHz mono + TMdaAudioDataSettings iSettings; + iSettings.iChannels = + get_channel_cap (parentStrm_->param.channel_count); + iSettings.iSampleRate = + get_clock_rate_cap (parentStrm_->param.clock_rate); + + iOutputStream_->SetAudioPropertiesL (iSettings.iSampleRate, + iSettings.iChannels); + + // set volume to 1/2th of stream max volume + iOutputStream_->SetVolume (iOutputStream_->MaxVolume() /2); + + // set stream priority to normal and time sensitive + iOutputStream_->SetPriority (EPriorityNormal, + EMdaPriorityPreferenceTime); + + // Call callback to retrieve frame from upstream. + pjmedia_frame f; + pj_status_t status; + + f.type = PJMEDIA_FRAME_TYPE_AUDIO; + f.buf = frameBuf_; + f.size = frameBufSize_; + f.timestamp.u32.lo = timestamp_; + f.bit_info = 0; + + status = playCb_ (this->userData_, &f); + + if (status != PJ_SUCCESS) { + this->Stop(); + return; + } + + if (f.type != PJMEDIA_FRAME_TYPE_AUDIO) + pj_bzero (frameBuf_, frameBufSize_); + + // Increment timestamp. + timestamp_ += (frameBufSize_ / BYTES_PER_SAMPLE); + + // issue WriteL() to write the first audio data block, + // subsequent calls to WriteL() will be issued in + // MMdaAudioOutputStreamCallback::MaoscBufferCopied() + // until whole data buffer is written. + frame_.Set (frameBuf_, frameBufSize_); + + iOutputStream_->WriteL (frame_); } else { - snd_perror("Error in MaoscOpenComplete()", aError); + snd_perror ("Error in MaoscOpenComplete()", aError); } } -void CPjAudioOutputEngine::MaoscBufferCopied(TInt aError, - const TDesC8& aBuffer) +void CPjAudioOutputEngine::MaoscBufferCopied (TInt aError, + const TDesC8& aBuffer) { - PJ_UNUSED_ARG(aBuffer); + PJ_UNUSED_ARG (aBuffer); if (aError==KErrNone) { - // Buffer successfully written, feed another one. - - // Call callback to retrieve frame from upstream. - pjmedia_frame f; - pj_status_t status; - - f.type = PJMEDIA_FRAME_TYPE_AUDIO; - f.buf = frameBuf_; - f.size = frameBufSize_; - f.timestamp.u32.lo = timestamp_; - f.bit_info = 0; - - status = playCb_(this->userData_, &f); - if (status != PJ_SUCCESS) { - this->Stop(); - return; - } - - if (f.type != PJMEDIA_FRAME_TYPE_AUDIO) - pj_bzero(frameBuf_, frameBufSize_); - - // Increment timestamp. - timestamp_ += (frameBufSize_ / BYTES_PER_SAMPLE); - - // Write to playback stream. - frame_.Set(frameBuf_, frameBufSize_); - iOutputStream_->WriteL(frame_); + // Buffer successfully written, feed another one. + + // Call callback to retrieve frame from upstream. + pjmedia_frame f; + pj_status_t status; + + f.type = PJMEDIA_FRAME_TYPE_AUDIO; + f.buf = frameBuf_; + f.size = frameBufSize_; + f.timestamp.u32.lo = timestamp_; + f.bit_info = 0; + + status = playCb_ (this->userData_, &f); + + if (status != PJ_SUCCESS) { + this->Stop(); + return; + } + + if (f.type != PJMEDIA_FRAME_TYPE_AUDIO) + pj_bzero (frameBuf_, frameBufSize_); + + // Increment timestamp. + timestamp_ += (frameBufSize_ / BYTES_PER_SAMPLE); + + // Write to playback stream. + frame_.Set (frameBuf_, frameBufSize_); + + iOutputStream_->WriteL (frame_); } else if (aError==KErrAbort) { - // playing was aborted, due to call to CMdaAudioOutputStream::Stop() - state_ = STATE_INACTIVE; + // playing was aborted, due to call to CMdaAudioOutputStream::Stop() + state_ = STATE_INACTIVE; } else { - // error writing data to output - lastError_ = aError; - state_ = STATE_INACTIVE; - snd_perror("Error in MaoscBufferCopied()", aError); + // error writing data to output + lastError_ = aError; + state_ = STATE_INACTIVE; + snd_perror ("Error in MaoscBufferCopied()", aError); } } -void CPjAudioOutputEngine::MaoscPlayComplete(TInt aError) +void CPjAudioOutputEngine::MaoscPlayComplete (TInt aError) { lastError_ = aError; state_ = STATE_INACTIVE; + if (aError != KErrNone && aError != KErrCancel) { - snd_perror("Error in MaoscPlayComplete()", aError); + snd_perror ("Error in MaoscPlayComplete()", aError); } } @@ -783,19 +840,20 @@ void CPjAudioOutputEngine::MaoscPlayComplete(TInt aError) * C compatible declaration of MDA factory. */ PJ_BEGIN_DECL -PJ_DECL(pjmedia_aud_dev_factory*) pjmedia_symb_mda_factory(pj_pool_factory *pf); +PJ_DECL (pjmedia_aud_dev_factory*) pjmedia_symb_mda_factory (pj_pool_factory *pf); PJ_END_DECL /* * Init Symbian audio driver. */ -pjmedia_aud_dev_factory* pjmedia_symb_mda_factory(pj_pool_factory *pf) +pjmedia_aud_dev_factory* pjmedia_symb_mda_factory (pj_pool_factory *pf) { + struct mda_factory *f; pj_pool_t *pool; - pool = pj_pool_create(pf, "symb_aud", 1000, 1000, NULL); - f = PJ_POOL_ZALLOC_T(pool, struct mda_factory); + pool = pj_pool_create (pf, "symb_aud", 1000, 1000, NULL); + f = PJ_POOL_ZALLOC_T (pool, struct mda_factory); f->pf = pf; f->pool = pool; f->base.op = &factory_op; @@ -804,67 +862,71 @@ pjmedia_aud_dev_factory* pjmedia_symb_mda_factory(pj_pool_factory *pf) } /* API: init factory */ -static pj_status_t factory_init(pjmedia_aud_dev_factory *f) +static pj_status_t factory_init (pjmedia_aud_dev_factory *f) { - struct mda_factory *af = (struct mda_factory*)f; - pj_ansi_strcpy(af->dev_info.name, "Symbian Audio"); + struct mda_factory *af = (struct mda_factory*) f; + + pj_ansi_strcpy (af->dev_info.name, "Symbian Audio"); af->dev_info.default_samples_per_sec = 8000; af->dev_info.caps = PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING | - PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING; + PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING; af->dev_info.input_count = 1; af->dev_info.output_count = 1; - PJ_LOG(4, (THIS_FILE, "Symb Mda initialized")); + PJ_LOG (4, (THIS_FILE, "Symb Mda initialized")); return PJ_SUCCESS; } /* API: destroy factory */ -static pj_status_t factory_destroy(pjmedia_aud_dev_factory *f) +static pj_status_t factory_destroy (pjmedia_aud_dev_factory *f) { - struct mda_factory *af = (struct mda_factory*)f; + + struct mda_factory *af = (struct mda_factory*) f; pj_pool_t *pool = af->pool; af->pool = NULL; - pj_pool_release(pool); + pj_pool_release (pool); + + PJ_LOG (4, (THIS_FILE, "Symbian Mda destroyed")); - PJ_LOG(4, (THIS_FILE, "Symbian Mda destroyed")); - return PJ_SUCCESS; } /* API: get number of devices */ -static unsigned factory_get_dev_count(pjmedia_aud_dev_factory *f) +static unsigned factory_get_dev_count (pjmedia_aud_dev_factory *f) { - PJ_UNUSED_ARG(f); + PJ_UNUSED_ARG (f); return 1; } /* API: get device info */ -static pj_status_t factory_get_dev_info(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_dev_info *info) +static pj_status_t factory_get_dev_info (pjmedia_aud_dev_factory *f, + unsigned index, + pjmedia_aud_dev_info *info) { - struct mda_factory *af = (struct mda_factory*)f; - PJ_ASSERT_RETURN(index == 0, PJMEDIA_EAUD_INVDEV); + struct mda_factory *af = (struct mda_factory*) f; - pj_memcpy(info, &af->dev_info, sizeof(*info)); + PJ_ASSERT_RETURN (index == 0, PJMEDIA_EAUD_INVDEV); + + pj_memcpy (info, &af->dev_info, sizeof (*info)); return PJ_SUCCESS; } /* API: create default device parameter */ -static pj_status_t factory_default_param(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_param *param) +static pj_status_t factory_default_param (pjmedia_aud_dev_factory *f, + unsigned index, + pjmedia_aud_param *param) { - struct mda_factory *af = (struct mda_factory*)f; - PJ_ASSERT_RETURN(index == 0, PJMEDIA_EAUD_INVDEV); + struct mda_factory *af = (struct mda_factory*) f; + + PJ_ASSERT_RETURN (index == 0, PJMEDIA_EAUD_INVDEV); - pj_bzero(param, sizeof(*param)); + pj_bzero (param, sizeof (*param)); param->dir = PJMEDIA_DIR_CAPTURE_PLAYBACK; param->rec_id = index; param->play_id = index; @@ -879,210 +941,239 @@ static pj_status_t factory_default_param(pjmedia_aud_dev_factory *f, /* API: create stream */ -static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, - const pjmedia_aud_param *param, - pjmedia_aud_rec_cb rec_cb, - pjmedia_aud_play_cb play_cb, - void *user_data, - pjmedia_aud_stream **p_aud_strm) +static pj_status_t factory_create_stream (pjmedia_aud_dev_factory *f, + const pjmedia_aud_param *param, + pjmedia_aud_rec_cb rec_cb, + pjmedia_aud_play_cb play_cb, + void *user_data, + pjmedia_aud_stream **p_aud_strm) { - struct mda_factory *mf = (struct mda_factory*)f; + + struct mda_factory *mf = (struct mda_factory*) f; pj_pool_t *pool; + struct mda_stream *strm; /* Can only support 16bits per sample raw PCM format. */ - PJ_ASSERT_RETURN(param->bits_per_sample == BITS_PER_SAMPLE, PJ_EINVAL); - PJ_ASSERT_RETURN((param->flags & PJMEDIA_AUD_DEV_CAP_EXT_FORMAT)==0 || - param->ext_fmt.id == PJMEDIA_FORMAT_L16, - PJ_ENOTSUP); - + PJ_ASSERT_RETURN (param->bits_per_sample == BITS_PER_SAMPLE, PJ_EINVAL); + PJ_ASSERT_RETURN ( (param->flags & PJMEDIA_AUD_DEV_CAP_EXT_FORMAT) ==0 || + param->ext_fmt.id == PJMEDIA_FORMAT_L16, + PJ_ENOTSUP); + /* It seems that MDA recorder only supports for mono channel. */ - PJ_ASSERT_RETURN(param->channel_count == 1, PJ_EINVAL); + PJ_ASSERT_RETURN (param->channel_count == 1, PJ_EINVAL); /* Create and Initialize stream descriptor */ - pool = pj_pool_create(mf->pf, "symb_aud_dev", 1000, 1000, NULL); - PJ_ASSERT_RETURN(pool, PJ_ENOMEM); + pool = pj_pool_create (mf->pf, "symb_aud_dev", 1000, 1000, NULL); + PJ_ASSERT_RETURN (pool, PJ_ENOMEM); - strm = PJ_POOL_ZALLOC_T(pool, struct mda_stream); + strm = PJ_POOL_ZALLOC_T (pool, struct mda_stream); strm->pool = pool; strm->param = *param; // Create the output stream. + if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { - TRAPD(err, strm->out_engine = CPjAudioOutputEngine::NewL(strm, play_cb, - user_data)); - if (err != KErrNone) { - pj_pool_release(pool); - return PJ_RETURN_OS_ERROR(err); - } + TRAPD (err, strm->out_engine = CPjAudioOutputEngine::NewL (strm, play_cb, + user_data)); + + if (err != KErrNone) { + pj_pool_release (pool); + return PJ_RETURN_OS_ERROR (err); + } } // Create the input stream. if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { - TRAPD(err, strm->in_engine = CPjAudioInputEngine::NewL(strm, rec_cb, - user_data)); - if (err != KErrNone) { - strm->in_engine = NULL; - delete strm->out_engine; - strm->out_engine = NULL; - pj_pool_release(pool); - return PJ_RETURN_OS_ERROR(err); - } + TRAPD (err, strm->in_engine = CPjAudioInputEngine::NewL (strm, rec_cb, + user_data)); + + if (err != KErrNone) { + strm->in_engine = NULL; + delete strm->out_engine; + strm->out_engine = NULL; + pj_pool_release (pool); + return PJ_RETURN_OS_ERROR (err); + } } - + /* Done */ strm->base.op = &stream_op; + *p_aud_strm = &strm->base; return PJ_SUCCESS; } /* API: Get stream info. */ -static pj_status_t stream_get_param(pjmedia_aud_stream *s, - pjmedia_aud_param *pi) +static pj_status_t stream_get_param (pjmedia_aud_stream *s, + pjmedia_aud_param *pi) { - struct mda_stream *strm = (struct mda_stream*)s; - PJ_ASSERT_RETURN(strm && pi, PJ_EINVAL); + struct mda_stream *strm = (struct mda_stream*) s; + + PJ_ASSERT_RETURN (strm && pi, PJ_EINVAL); + + pj_memcpy (pi, &strm->param, sizeof (*pi)); - pj_memcpy(pi, &strm->param, sizeof(*pi)); - return PJ_SUCCESS; } /* API: get capability */ -static pj_status_t stream_get_cap(pjmedia_aud_stream *s, - pjmedia_aud_dev_cap cap, - void *pval) +static pj_status_t stream_get_cap (pjmedia_aud_stream *s, + pjmedia_aud_dev_cap cap, + void *pval) { - struct mda_stream *strm = (struct mda_stream*)s; + + struct mda_stream *strm = (struct mda_stream*) s; pj_status_t status = PJ_ENOTSUP; - PJ_ASSERT_RETURN(s && pval, PJ_EINVAL); + PJ_ASSERT_RETURN (s && pval, PJ_EINVAL); switch (cap) { - case PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING: - if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { - PJ_ASSERT_RETURN(strm->in_engine, PJ_EINVAL); - - TInt max_gain = strm->in_engine->GetMaxGain(); - TInt gain = strm->in_engine->GetGain(); - - if (max_gain > 0 && gain >= 0) { - *(unsigned*)pval = gain * 100 / max_gain; - status = PJ_SUCCESS; - } else { - status = PJMEDIA_EAUD_NOTREADY; - } - } - break; - case PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING: - if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { - PJ_ASSERT_RETURN(strm->out_engine, PJ_EINVAL); - - TInt max_vol = strm->out_engine->GetMaxVolume(); - TInt vol = strm->out_engine->GetVolume(); - - if (max_vol > 0 && vol >= 0) { - *(unsigned*)pval = vol * 100 / max_vol; - status = PJ_SUCCESS; - } else { - status = PJMEDIA_EAUD_NOTREADY; - } - } - break; - default: - break; + + case PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING: + + if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { + PJ_ASSERT_RETURN (strm->in_engine, PJ_EINVAL); + + TInt max_gain = strm->in_engine->GetMaxGain(); + TInt gain = strm->in_engine->GetGain(); + + if (max_gain > 0 && gain >= 0) { + * (unsigned*) pval = gain * 100 / max_gain; + status = PJ_SUCCESS; + } else { + status = PJMEDIA_EAUD_NOTREADY; + } + } + + break; + + case PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING: + + if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { + PJ_ASSERT_RETURN (strm->out_engine, PJ_EINVAL); + + TInt max_vol = strm->out_engine->GetMaxVolume(); + TInt vol = strm->out_engine->GetVolume(); + + if (max_vol > 0 && vol >= 0) { + * (unsigned*) pval = vol * 100 / max_vol; + status = PJ_SUCCESS; + } else { + status = PJMEDIA_EAUD_NOTREADY; + } + } + + break; + + default: + break; } - + return status; } /* API: set capability */ -static pj_status_t stream_set_cap(pjmedia_aud_stream *s, - pjmedia_aud_dev_cap cap, - const void *pval) +static pj_status_t stream_set_cap (pjmedia_aud_stream *s, + pjmedia_aud_dev_cap cap, + const void *pval) { - struct mda_stream *strm = (struct mda_stream*)s; + + struct mda_stream *strm = (struct mda_stream*) s; pj_status_t status = PJ_ENOTSUP; - PJ_ASSERT_RETURN(s && pval, PJ_EINVAL); + PJ_ASSERT_RETURN (s && pval, PJ_EINVAL); switch (cap) { - case PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING: - if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { - PJ_ASSERT_RETURN(strm->in_engine, PJ_EINVAL); - - TInt max_gain = strm->in_engine->GetMaxGain(); - if (max_gain > 0) { - TInt gain; - - gain = *(unsigned*)pval * max_gain / 100; - status = strm->in_engine->SetGain(gain); - } else { - status = PJMEDIA_EAUD_NOTREADY; - } - } - break; - case PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING: - if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { - PJ_ASSERT_RETURN(strm->out_engine, PJ_EINVAL); - - TInt max_vol = strm->out_engine->GetMaxVolume(); - if (max_vol > 0) { - TInt vol; - - vol = *(unsigned*)pval * max_vol / 100; - status = strm->out_engine->SetVolume(vol); - } else { - status = PJMEDIA_EAUD_NOTREADY; - } - } - break; - default: - break; + + case PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING: + + if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { + PJ_ASSERT_RETURN (strm->in_engine, PJ_EINVAL); + + TInt max_gain = strm->in_engine->GetMaxGain(); + + if (max_gain > 0) { + TInt gain; + + gain = * (unsigned*) pval * max_gain / 100; + status = strm->in_engine->SetGain (gain); + } else { + status = PJMEDIA_EAUD_NOTREADY; + } + } + + break; + + case PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING: + + if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { + PJ_ASSERT_RETURN (strm->out_engine, PJ_EINVAL); + + TInt max_vol = strm->out_engine->GetMaxVolume(); + + if (max_vol > 0) { + TInt vol; + + vol = * (unsigned*) pval * max_vol / 100; + status = strm->out_engine->SetVolume (vol); + } else { + status = PJMEDIA_EAUD_NOTREADY; + } + } + + break; + + default: + break; } - + return status; } /* API: Start stream. */ -static pj_status_t stream_start(pjmedia_aud_stream *strm) +static pj_status_t stream_start (pjmedia_aud_stream *strm) { - struct mda_stream *stream = (struct mda_stream*)strm; - PJ_ASSERT_RETURN(stream, PJ_EINVAL); + struct mda_stream *stream = (struct mda_stream*) strm; + + PJ_ASSERT_RETURN (stream, PJ_EINVAL); if (stream->out_engine) { - pj_status_t status; - status = stream->out_engine->StartPlay(); - if (status != PJ_SUCCESS) - return status; + pj_status_t status; + status = stream->out_engine->StartPlay(); + + if (status != PJ_SUCCESS) + return status; } - + if (stream->in_engine) { - pj_status_t status; - status = stream->in_engine->StartRecord(); - if (status != PJ_SUCCESS) - return status; + pj_status_t status; + status = stream->in_engine->StartRecord(); + + if (status != PJ_SUCCESS) + return status; } return PJ_SUCCESS; } /* API: Stop stream. */ -static pj_status_t stream_stop(pjmedia_aud_stream *strm) +static pj_status_t stream_stop (pjmedia_aud_stream *strm) { - struct mda_stream *stream = (struct mda_stream*)strm; - PJ_ASSERT_RETURN(stream, PJ_EINVAL); + struct mda_stream *stream = (struct mda_stream*) strm; + + PJ_ASSERT_RETURN (stream, PJ_EINVAL); if (stream->in_engine) { - stream->in_engine->Stop(); + stream->in_engine->Stop(); } - + if (stream->out_engine) { - stream->out_engine->Stop(); + stream->out_engine->Stop(); } return PJ_SUCCESS; @@ -1090,13 +1181,14 @@ static pj_status_t stream_stop(pjmedia_aud_stream *strm) /* API: Destroy stream. */ -static pj_status_t stream_destroy(pjmedia_aud_stream *strm) +static pj_status_t stream_destroy (pjmedia_aud_stream *strm) { - struct mda_stream *stream = (struct mda_stream*)strm; - PJ_ASSERT_RETURN(stream, PJ_EINVAL); + struct mda_stream *stream = (struct mda_stream*) strm; - stream_stop(strm); + PJ_ASSERT_RETURN (stream, PJ_EINVAL); + + stream_stop (strm); delete stream->in_engine; stream->in_engine = NULL; @@ -1106,9 +1198,10 @@ static pj_status_t stream_destroy(pjmedia_aud_stream *strm) pj_pool_t *pool; pool = stream->pool; + if (pool) { - stream->pool = NULL; - pj_pool_release(pool); + stream->pool = NULL; + pj_pool_release (pool); } return PJ_SUCCESS; diff --git a/sflphone-common/libs/pjproject/pjmedia/src/pjmedia-audiodev/symb_vas_dev.cpp b/sflphone-common/libs/pjproject/pjmedia/src/pjmedia-audiodev/symb_vas_dev.cpp index 504a15dd25b20de4b74dbd789901025b6cc6adb4..a4c156bebb9f73e00f598a8ac271df2a65ac39de 100644 --- a/sflphone-common/libs/pjproject/pjmedia/src/pjmedia-audiodev/symb_vas_dev.cpp +++ b/sflphone-common/libs/pjproject/pjmedia/src/pjmedia-audiodev/symb_vas_dev.cpp @@ -1,5 +1,5 @@ /* $Id: symb_vas_dev.cpp 2833 2009-07-14 14:33:39Z nanang $ */ -/* +/* * Copyright (C) 2009 Teluu Inc. (http://www.teluu.com) * * This program is free software; you can redistribute it and/or modify @@ -14,7 +14,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <pjmedia-audiodev/audiodev_imp.h> #include <pjmedia-audiodev/errno.h> @@ -40,10 +40,10 @@ #include <VoIPILBCDecoderIntfc.h> #include <VoIPILBCEncoderIntfc.h> -/* AMR helper */ +/* AMR helper */ #include <pjmedia-codec/amr_helper.h> -/* Pack/unpack G.729 frame of S60 DSP codec, taken from: +/* Pack/unpack G.729 frame of S60 DSP codec, taken from: * http://wiki.forum.nokia.com/index.php/TSS000776_-_Payload_conversion_for_G.729_audio_format */ #include "s60_g729_bitstream.h" @@ -70,8 +70,8 @@ static pj_uint8_t vas_g711_frame_len; /* VAS factory */ -struct vas_factory -{ + +struct vas_factory { pjmedia_aud_dev_factory base; pj_pool_t *pool; pj_pool_factory *pf; @@ -80,15 +80,16 @@ struct vas_factory /* Forward declaration of CPjAudioEngine */ + class CPjAudioEngine; /* VAS stream. */ -struct vas_stream -{ + +struct vas_stream { // Base pjmedia_aud_stream base; /**< Base class. */ - + // Pool pj_pool_t *pool; /**< Memory pool. */ @@ -111,7 +112,7 @@ struct vas_stream pj_uint16_t rec_buf_len; /**< Record buffer length. */ void *strm_data; /**< Stream data. */ - /* Resampling is needed, in case audio device is opened with clock rate + /* Resampling is needed, in case audio device is opened with clock rate * other than 8kHz (only for PCM format). */ pjmedia_resample *play_resample; /**< Resampler for playback. */ @@ -128,38 +129,37 @@ struct vas_stream /* Prototypes */ -static pj_status_t factory_init(pjmedia_aud_dev_factory *f); -static pj_status_t factory_destroy(pjmedia_aud_dev_factory *f); -static unsigned factory_get_dev_count(pjmedia_aud_dev_factory *f); -static pj_status_t factory_get_dev_info(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_dev_info *info); -static pj_status_t factory_default_param(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_param *param); -static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, - const pjmedia_aud_param *param, - pjmedia_aud_rec_cb rec_cb, - pjmedia_aud_play_cb play_cb, - void *user_data, - pjmedia_aud_stream **p_aud_strm); - -static pj_status_t stream_get_param(pjmedia_aud_stream *strm, - pjmedia_aud_param *param); -static pj_status_t stream_get_cap(pjmedia_aud_stream *strm, - pjmedia_aud_dev_cap cap, - void *value); -static pj_status_t stream_set_cap(pjmedia_aud_stream *strm, - pjmedia_aud_dev_cap cap, - const void *value); -static pj_status_t stream_start(pjmedia_aud_stream *strm); -static pj_status_t stream_stop(pjmedia_aud_stream *strm); -static pj_status_t stream_destroy(pjmedia_aud_stream *strm); +static pj_status_t factory_init (pjmedia_aud_dev_factory *f); +static pj_status_t factory_destroy (pjmedia_aud_dev_factory *f); +static unsigned factory_get_dev_count (pjmedia_aud_dev_factory *f); +static pj_status_t factory_get_dev_info (pjmedia_aud_dev_factory *f, + unsigned index, + pjmedia_aud_dev_info *info); +static pj_status_t factory_default_param (pjmedia_aud_dev_factory *f, + unsigned index, + pjmedia_aud_param *param); +static pj_status_t factory_create_stream (pjmedia_aud_dev_factory *f, + const pjmedia_aud_param *param, + pjmedia_aud_rec_cb rec_cb, + pjmedia_aud_play_cb play_cb, + void *user_data, + pjmedia_aud_stream **p_aud_strm); + +static pj_status_t stream_get_param (pjmedia_aud_stream *strm, + pjmedia_aud_param *param); +static pj_status_t stream_get_cap (pjmedia_aud_stream *strm, + pjmedia_aud_dev_cap cap, + void *value); +static pj_status_t stream_set_cap (pjmedia_aud_stream *strm, + pjmedia_aud_dev_cap cap, + const void *value); +static pj_status_t stream_start (pjmedia_aud_stream *strm); +static pj_status_t stream_stop (pjmedia_aud_stream *strm); +static pj_status_t stream_destroy (pjmedia_aud_stream *strm); /* Operations */ -static pjmedia_aud_dev_factory_op factory_op = -{ +static pjmedia_aud_dev_factory_op factory_op = { &factory_init, &factory_destroy, &factory_get_dev_count, @@ -168,8 +168,7 @@ static pjmedia_aud_dev_factory_op factory_op = &factory_create_stream }; -static pjmedia_aud_stream_op stream_op = -{ +static pjmedia_aud_stream_op stream_op = { &stream_get_param, &stream_get_cap, &stream_set_cap, @@ -186,267 +185,303 @@ static pjmedia_aud_stream_op stream_op = /* * Utility: print sound device error */ -static void snd_perror(const char *title, TInt rc) +static void snd_perror (const char *title, TInt rc) { - PJ_LOG(1,(THIS_FILE, "%s (error code=%d)", title, rc)); + PJ_LOG (1, (THIS_FILE, "%s (error code=%d)", title, rc)); } -typedef void(*PjAudioCallback)(CVoIPDataBuffer *buf, void *user_data); +typedef void (*PjAudioCallback) (CVoIPDataBuffer *buf, void *user_data); /* * Audio setting for CPjAudioEngine. */ + class CPjAudioSetting { -public: - TVoIPCodecFormat format; - TInt mode; - TBool plc; - TBool vad; - TBool cng; - TBool loudspk; + + public: + TVoIPCodecFormat format; + TInt mode; + TBool plc; + TBool vad; + TBool cng; + TBool loudspk; }; /* * Implementation: Symbian Input & Output Stream. */ + class CPjAudioEngine : public CBase, - public MVoIPDownlinkObserver, - public MVoIPUplinkObserver, - public MVoIPFormatObserver + public MVoIPDownlinkObserver, + public MVoIPUplinkObserver, + public MVoIPFormatObserver { -public: - enum State - { - STATE_NULL, - STATE_STARTING, - STATE_READY, - STATE_STREAMING - }; - - ~CPjAudioEngine(); - - static CPjAudioEngine *NewL(struct vas_stream *parent_strm, - PjAudioCallback rec_cb, - PjAudioCallback play_cb, - void *user_data, - const CPjAudioSetting &setting); - - TInt Start(); - void Stop(); - - TInt ActivateSpeaker(TBool active); - - TInt SetVolume(TInt vol) { return iVoIPDnlink->SetVolume(vol); } - TInt GetVolume() { TInt vol;iVoIPDnlink->GetVolume(vol);return vol; } - TInt GetMaxVolume() { TInt vol;iVoIPDnlink->GetMaxVolume(vol);return vol; } - - TInt SetGain(TInt gain) { return iVoIPUplink->SetGain(gain); } - TInt GetGain() { TInt gain;iVoIPUplink->GetGain(gain);return gain; } - TInt GetMaxGain() { TInt gain;iVoIPUplink->GetMaxGain(gain);return gain; } - -private: - CPjAudioEngine(struct vas_stream *parent_strm, - PjAudioCallback rec_cb, - PjAudioCallback play_cb, - void *user_data, - const CPjAudioSetting &setting); - void ConstructL(); - - TInt InitPlay(); - TInt InitRec(); - - TInt StartPlay(); - TInt StartRec(); - - // From MVoIPDownlinkObserver - virtual void FillBuffer(const CVoIPAudioDownlinkStream& aSrc, - CVoIPDataBuffer* aBuffer); - virtual void Event(const CVoIPAudioDownlinkStream& aSrc, - TInt aEventType, - TInt aError); - - // From MVoIPUplinkObserver - virtual void EmptyBuffer(const CVoIPAudioUplinkStream& aSrc, - CVoIPDataBuffer* aBuffer); - virtual void Event(const CVoIPAudioUplinkStream& aSrc, - TInt aEventType, - TInt aError); - - // From MVoIPFormatObserver - virtual void Event(const CVoIPFormatIntfc& aSrc, TInt aEventType); - - State dn_state_; - State up_state_; - struct vas_stream *parentStrm_; - CPjAudioSetting setting_; - PjAudioCallback rec_cb_; - PjAudioCallback play_cb_; - void *user_data_; - - // VAS objects - CVoIPUtilityFactory *iFactory; - CVoIPAudioDownlinkStream *iVoIPDnlink; - CVoIPAudioUplinkStream *iVoIPUplink; - CVoIPFormatIntfc *enc_fmt_if; - CVoIPFormatIntfc *dec_fmt_if; + + public: + enum State { + STATE_NULL, + STATE_STARTING, + STATE_READY, + STATE_STREAMING + }; + + ~CPjAudioEngine(); + + static CPjAudioEngine *NewL (struct vas_stream *parent_strm, + PjAudioCallback rec_cb, + PjAudioCallback play_cb, + void *user_data, + const CPjAudioSetting &setting); + + TInt Start(); + void Stop(); + + TInt ActivateSpeaker (TBool active); + + TInt SetVolume (TInt vol) { + return iVoIPDnlink->SetVolume (vol); + } + + TInt GetVolume() { + TInt vol; + iVoIPDnlink->GetVolume (vol); + return vol; + } + + TInt GetMaxVolume() { + TInt vol; + iVoIPDnlink->GetMaxVolume (vol); + return vol; + } + + TInt SetGain (TInt gain) { + return iVoIPUplink->SetGain (gain); + } + + TInt GetGain() { + TInt gain; + iVoIPUplink->GetGain (gain); + return gain; + } + + TInt GetMaxGain() { + TInt gain; + iVoIPUplink->GetMaxGain (gain); + return gain; + } + + private: + CPjAudioEngine (struct vas_stream *parent_strm, + PjAudioCallback rec_cb, + PjAudioCallback play_cb, + void *user_data, + const CPjAudioSetting &setting); + void ConstructL(); + + TInt InitPlay(); + TInt InitRec(); + + TInt StartPlay(); + TInt StartRec(); + + // From MVoIPDownlinkObserver + virtual void FillBuffer (const CVoIPAudioDownlinkStream& aSrc, + CVoIPDataBuffer* aBuffer); + virtual void Event (const CVoIPAudioDownlinkStream& aSrc, + TInt aEventType, + TInt aError); + + // From MVoIPUplinkObserver + virtual void EmptyBuffer (const CVoIPAudioUplinkStream& aSrc, + CVoIPDataBuffer* aBuffer); + virtual void Event (const CVoIPAudioUplinkStream& aSrc, + TInt aEventType, + TInt aError); + + // From MVoIPFormatObserver + virtual void Event (const CVoIPFormatIntfc& aSrc, TInt aEventType); + + State dn_state_; + State up_state_; + + struct vas_stream *parentStrm_; + CPjAudioSetting setting_; + PjAudioCallback rec_cb_; + PjAudioCallback play_cb_; + void *user_data_; + + // VAS objects + CVoIPUtilityFactory *iFactory; + CVoIPAudioDownlinkStream *iVoIPDnlink; + CVoIPAudioUplinkStream *iVoIPUplink; + CVoIPFormatIntfc *enc_fmt_if; + CVoIPFormatIntfc *dec_fmt_if; }; -CPjAudioEngine* CPjAudioEngine::NewL(struct vas_stream *parent_strm, - PjAudioCallback rec_cb, - PjAudioCallback play_cb, - void *user_data, - const CPjAudioSetting &setting) +CPjAudioEngine* CPjAudioEngine::NewL (struct vas_stream *parent_strm, + PjAudioCallback rec_cb, + PjAudioCallback play_cb, + void *user_data, + const CPjAudioSetting &setting) { - CPjAudioEngine* self = new (ELeave) CPjAudioEngine(parent_strm, - rec_cb, play_cb, - user_data, - setting); - CleanupStack::PushL(self); + CPjAudioEngine* self = new (ELeave) CPjAudioEngine (parent_strm, + rec_cb, play_cb, + user_data, + setting); + CleanupStack::PushL (self); self->ConstructL(); - CleanupStack::Pop(self); + CleanupStack::Pop (self); return self; } void CPjAudioEngine::ConstructL() { TInt err; - const TVersion ver(1, 0, 0); /* Not really used at this time */ + const TVersion ver (1, 0, 0); /* Not really used at this time */ - err = CVoIPUtilityFactory::CreateFactory(iFactory); - User::LeaveIfError(err); + err = CVoIPUtilityFactory::CreateFactory (iFactory); + User::LeaveIfError (err); if (parentStrm_->param.dir != PJMEDIA_DIR_CAPTURE) { - err = iFactory->CreateDownlinkStream(ver, - CVoIPUtilityFactory::EVoIPCall, - iVoIPDnlink); - User::LeaveIfError(err); + err = iFactory->CreateDownlinkStream (ver, + CVoIPUtilityFactory::EVoIPCall, + iVoIPDnlink); + User::LeaveIfError (err); } if (parentStrm_->param.dir != PJMEDIA_DIR_PLAYBACK) { - err = iFactory->CreateUplinkStream(ver, - CVoIPUtilityFactory::EVoIPCall, - iVoIPUplink); - User::LeaveIfError(err); + err = iFactory->CreateUplinkStream (ver, + CVoIPUtilityFactory::EVoIPCall, + iVoIPUplink); + User::LeaveIfError (err); } } -CPjAudioEngine::CPjAudioEngine(struct vas_stream *parent_strm, - PjAudioCallback rec_cb, - PjAudioCallback play_cb, - void *user_data, - const CPjAudioSetting &setting) - : dn_state_(STATE_NULL), - up_state_(STATE_NULL), - parentStrm_(parent_strm), - setting_(setting), - rec_cb_(rec_cb), - play_cb_(play_cb), - user_data_(user_data), - iFactory(NULL), - iVoIPDnlink(NULL), - iVoIPUplink(NULL), - enc_fmt_if(NULL), - dec_fmt_if(NULL) +CPjAudioEngine::CPjAudioEngine (struct vas_stream *parent_strm, + PjAudioCallback rec_cb, + PjAudioCallback play_cb, + void *user_data, + const CPjAudioSetting &setting) + : dn_state_ (STATE_NULL), + up_state_ (STATE_NULL), + parentStrm_ (parent_strm), + setting_ (setting), + rec_cb_ (rec_cb), + play_cb_ (play_cb), + user_data_ (user_data), + iFactory (NULL), + iVoIPDnlink (NULL), + iVoIPUplink (NULL), + enc_fmt_if (NULL), + dec_fmt_if (NULL) { } CPjAudioEngine::~CPjAudioEngine() { Stop(); - + if (iVoIPUplink) - iVoIPUplink->Close(); - + iVoIPUplink->Close(); + if (iVoIPDnlink) - iVoIPDnlink->Close(); + iVoIPDnlink->Close(); delete iVoIPDnlink; + delete iVoIPUplink; + delete iFactory; - - TRACE_((THIS_FILE, "Sound device destroyed")); + + TRACE_ ( (THIS_FILE, "Sound device destroyed")); } TInt CPjAudioEngine::InitPlay() { TInt err; - pj_assert(iVoIPDnlink); + pj_assert (iVoIPDnlink); + + err = iVoIPDnlink->SetFormat (setting_.format, dec_fmt_if); - err = iVoIPDnlink->SetFormat(setting_.format, dec_fmt_if); if (err != KErrNone) - return err; - - err = dec_fmt_if->SetObserver(*this); + return err; + + err = dec_fmt_if->SetObserver (*this); + if (err != KErrNone) - return err; + return err; - return iVoIPDnlink->Open(*this); + return iVoIPDnlink->Open (*this); } TInt CPjAudioEngine::InitRec() { TInt err; - - pj_assert(iVoIPUplink); - err = iVoIPUplink->SetFormat(setting_.format, enc_fmt_if); + pj_assert (iVoIPUplink); + + err = iVoIPUplink->SetFormat (setting_.format, enc_fmt_if); + if (err != KErrNone) - return err; - - err = enc_fmt_if->SetObserver(*this); + return err; + + err = enc_fmt_if->SetObserver (*this); + if (err != KErrNone) - return err; - - return iVoIPUplink->Open(*this); + return err; + + return iVoIPUplink->Open (*this); } TInt CPjAudioEngine::StartPlay() { TInt err; - - pj_assert(iVoIPDnlink); - pj_assert(dn_state_ == STATE_READY); + + pj_assert (iVoIPDnlink); + pj_assert (dn_state_ == STATE_READY); /* Configure specific codec setting */ + switch (setting_.format) { - case EG711: - { - CVoIPG711DecoderIntfc *g711dec_if = (CVoIPG711DecoderIntfc*) - dec_fmt_if; - err = g711dec_if->SetMode((CVoIPFormatIntfc::TG711CodecMode) - setting_.mode); - pj_assert(err == KErrNone); - } - break; - - case EILBC: - { - CVoIPILBCDecoderIntfc *ilbcdec_if = (CVoIPILBCDecoderIntfc*) - dec_fmt_if; - err = ilbcdec_if->SetMode((CVoIPFormatIntfc::TILBCCodecMode) - setting_.mode); - pj_assert(err == KErrNone); - } - break; - - default: - break; + + case EG711: { + CVoIPG711DecoderIntfc *g711dec_if = (CVoIPG711DecoderIntfc*) + dec_fmt_if; + err = g711dec_if->SetMode ( (CVoIPFormatIntfc::TG711CodecMode) + setting_.mode); + pj_assert (err == KErrNone); + } + + break; + + case EILBC: { + CVoIPILBCDecoderIntfc *ilbcdec_if = (CVoIPILBCDecoderIntfc*) + dec_fmt_if; + err = ilbcdec_if->SetMode ( (CVoIPFormatIntfc::TILBCCodecMode) + setting_.mode); + pj_assert (err == KErrNone); + } + + break; + + default: + break; } - + /* Configure audio routing */ - ActivateSpeaker(setting_.loudspk); + ActivateSpeaker (setting_.loudspk); /* Start player */ err = iVoIPDnlink->Start(); - + if (err == KErrNone) { - dn_state_ = STATE_STREAMING; - TRACE_((THIS_FILE, "Downlink started")); + dn_state_ = STATE_STREAMING; + TRACE_ ( (THIS_FILE, "Downlink started")); } else { - snd_perror("Failed starting downlink", err); + snd_perror ("Failed starting downlink", err); } return err; @@ -455,47 +490,49 @@ TInt CPjAudioEngine::StartPlay() TInt CPjAudioEngine::StartRec() { TInt err; - - pj_assert(iVoIPUplink); - pj_assert(up_state_ == STATE_READY); + + pj_assert (iVoIPUplink); + pj_assert (up_state_ == STATE_READY); /* Configure specific codec setting */ + switch (setting_.format) { - case EG711: - { - CVoIPG711EncoderIntfc *g711enc_if = (CVoIPG711EncoderIntfc*) - enc_fmt_if; - err = g711enc_if->SetMode((CVoIPFormatIntfc::TG711CodecMode) - setting_.mode); - pj_assert(err == KErrNone); - } - break; - - case EILBC: - { - CVoIPILBCEncoderIntfc *ilbcenc_if = (CVoIPILBCEncoderIntfc*) - enc_fmt_if; - err = ilbcenc_if->SetMode((CVoIPFormatIntfc::TILBCCodecMode) - setting_.mode); - pj_assert(err == KErrNone); - } - break; - - default: - break; + + case EG711: { + CVoIPG711EncoderIntfc *g711enc_if = (CVoIPG711EncoderIntfc*) + enc_fmt_if; + err = g711enc_if->SetMode ( (CVoIPFormatIntfc::TG711CodecMode) + setting_.mode); + pj_assert (err == KErrNone); + } + + break; + + case EILBC: { + CVoIPILBCEncoderIntfc *ilbcenc_if = (CVoIPILBCEncoderIntfc*) + enc_fmt_if; + err = ilbcenc_if->SetMode ( (CVoIPFormatIntfc::TILBCCodecMode) + setting_.mode); + pj_assert (err == KErrNone); + } + + break; + + default: + break; } - + /* Configure general codec setting */ - enc_fmt_if->SetVAD(setting_.vad); - + enc_fmt_if->SetVAD (setting_.vad); + /* Start recorder */ err = iVoIPUplink->Start(); - + if (err == KErrNone) { - up_state_ = STATE_STREAMING; - TRACE_((THIS_FILE, "Uplink started")); + up_state_ = STATE_STREAMING; + TRACE_ ( (THIS_FILE, "Uplink started")); } else { - snd_perror("Failed starting uplink", err); + snd_perror ("Failed starting uplink", err); } return err; @@ -504,37 +541,49 @@ TInt CPjAudioEngine::StartRec() TInt CPjAudioEngine::Start() { TInt err = KErrNone; - + if (iVoIPDnlink) { - switch(dn_state_) { - case STATE_READY: - err = StartPlay(); - break; - case STATE_NULL: - err = InitPlay(); - if (err != KErrNone) - return err; - dn_state_ = STATE_STARTING; - break; - default: - break; - } + switch (dn_state_) { + + case STATE_READY: + err = StartPlay(); + break; + + case STATE_NULL: + err = InitPlay(); + + if (err != KErrNone) + return err; + + dn_state_ = STATE_STARTING; + + break; + + default: + break; + } } - + if (iVoIPUplink) { - switch(up_state_) { - case STATE_READY: - err = StartRec(); - break; - case STATE_NULL: - err = InitRec(); - if (err != KErrNone) - return err; - up_state_ = STATE_STARTING; - break; - default: - break; - } + switch (up_state_) { + + case STATE_READY: + err = StartRec(); + break; + + case STATE_NULL: + err = InitRec(); + + if (err != KErrNone) + return err; + + up_state_ = STATE_STARTING; + + break; + + default: + break; + } } return err; @@ -543,132 +592,146 @@ TInt CPjAudioEngine::Start() void CPjAudioEngine::Stop() { if (iVoIPDnlink) { - switch(dn_state_) { - case STATE_STREAMING: - iVoIPDnlink->Stop(); - dn_state_ = STATE_READY; - break; - case STATE_STARTING: - dn_state_ = STATE_NULL; - break; - default: - break; - } + switch (dn_state_) { + + case STATE_STREAMING: + iVoIPDnlink->Stop(); + dn_state_ = STATE_READY; + break; + + case STATE_STARTING: + dn_state_ = STATE_NULL; + break; + + default: + break; + } } if (iVoIPUplink) { - switch(up_state_) { - case STATE_STREAMING: - iVoIPUplink->Stop(); - up_state_ = STATE_READY; - break; - case STATE_STARTING: - up_state_ = STATE_NULL; - break; - default: - break; - } + switch (up_state_) { + + case STATE_STREAMING: + iVoIPUplink->Stop(); + up_state_ = STATE_READY; + break; + + case STATE_STARTING: + up_state_ = STATE_NULL; + break; + + default: + break; + } } } -TInt CPjAudioEngine::ActivateSpeaker(TBool active) +TInt CPjAudioEngine::ActivateSpeaker (TBool active) { TInt err = KErrNotSupported; - + if (iVoIPDnlink) { - err = iVoIPDnlink->SetAudioDevice(active? - CVoIPAudioDownlinkStream::ELoudSpeaker : - CVoIPAudioDownlinkStream::EHandset); - TRACE_((THIS_FILE, "Loudspeaker turned %s", (active? "on":"off"))); + err = iVoIPDnlink->SetAudioDevice (active? + CVoIPAudioDownlinkStream::ELoudSpeaker : + CVoIPAudioDownlinkStream::EHandset); + TRACE_ ( (THIS_FILE, "Loudspeaker turned %s", (active? "on":"off"))); } - + return err; } // Callback from MVoIPDownlinkObserver -void CPjAudioEngine::FillBuffer(const CVoIPAudioDownlinkStream& aSrc, - CVoIPDataBuffer* aBuffer) +void CPjAudioEngine::FillBuffer (const CVoIPAudioDownlinkStream& aSrc, + CVoIPDataBuffer* aBuffer) { - play_cb_(aBuffer, user_data_); - iVoIPDnlink->BufferFilled(aBuffer); + play_cb_ (aBuffer, user_data_); + iVoIPDnlink->BufferFilled (aBuffer); } // Callback from MVoIPUplinkObserver -void CPjAudioEngine::EmptyBuffer(const CVoIPAudioUplinkStream& aSrc, - CVoIPDataBuffer* aBuffer) +void CPjAudioEngine::EmptyBuffer (const CVoIPAudioUplinkStream& aSrc, + CVoIPDataBuffer* aBuffer) { - rec_cb_(aBuffer, user_data_); - iVoIPUplink->BufferEmptied(aBuffer); + rec_cb_ (aBuffer, user_data_); + iVoIPUplink->BufferEmptied (aBuffer); } // Callback from MVoIPDownlinkObserver -void CPjAudioEngine::Event(const CVoIPAudioDownlinkStream& /*aSrc*/, - TInt aEventType, - TInt aError) +void CPjAudioEngine::Event (const CVoIPAudioDownlinkStream& /*aSrc*/, + TInt aEventType, + TInt aError) { switch (aEventType) { - case MVoIPDownlinkObserver::KOpenComplete: - if (aError == KErrNone) { - State last_state = dn_state_; - - dn_state_ = STATE_READY; - TRACE_((THIS_FILE, "Downlink opened")); - - if (last_state == STATE_STARTING) - StartPlay(); - } - break; - - case MVoIPDownlinkObserver::KDownlinkClosed: - dn_state_ = STATE_NULL; - TRACE_((THIS_FILE, "Downlink closed")); - break; - - case MVoIPDownlinkObserver::KDownlinkError: - dn_state_ = STATE_READY; - snd_perror("Downlink problem", aError); - break; - default: - break; + + case MVoIPDownlinkObserver::KOpenComplete: + + if (aError == KErrNone) { + State last_state = dn_state_; + + dn_state_ = STATE_READY; + TRACE_ ( (THIS_FILE, "Downlink opened")); + + if (last_state == STATE_STARTING) + StartPlay(); + } + + break; + + case MVoIPDownlinkObserver::KDownlinkClosed: + dn_state_ = STATE_NULL; + TRACE_ ( (THIS_FILE, "Downlink closed")); + break; + + case MVoIPDownlinkObserver::KDownlinkError: + dn_state_ = STATE_READY; + snd_perror ("Downlink problem", aError); + break; + + default: + break; } } // Callback from MVoIPUplinkObserver -void CPjAudioEngine::Event(const CVoIPAudioUplinkStream& /*aSrc*/, - TInt aEventType, - TInt aError) +void CPjAudioEngine::Event (const CVoIPAudioUplinkStream& /*aSrc*/, + TInt aEventType, + TInt aError) { switch (aEventType) { - case MVoIPUplinkObserver::KOpenComplete: - if (aError == KErrNone) { - State last_state = up_state_; - - up_state_ = STATE_READY; - TRACE_((THIS_FILE, "Uplink opened")); - - if (last_state == STATE_STARTING) - StartRec(); - } - break; - - case MVoIPUplinkObserver::KUplinkClosed: - up_state_ = STATE_NULL; - TRACE_((THIS_FILE, "Uplink closed")); - break; - - case MVoIPUplinkObserver::KUplinkError: - up_state_ = STATE_READY; - snd_perror("Uplink problem", aError); - break; - default: - break; + + case MVoIPUplinkObserver::KOpenComplete: + + if (aError == KErrNone) { + State last_state = up_state_; + + up_state_ = STATE_READY; + TRACE_ ( (THIS_FILE, "Uplink opened")); + + if (last_state == STATE_STARTING) + StartRec(); + } + + break; + + case MVoIPUplinkObserver::KUplinkClosed: + up_state_ = STATE_NULL; + TRACE_ ( (THIS_FILE, "Uplink closed")); + break; + + case MVoIPUplinkObserver::KUplinkError: + up_state_ = STATE_READY; + snd_perror ("Uplink problem", aError); + break; + + default: + break; } } // Callback from MVoIPFormatObserver -void CPjAudioEngine::Event(const CVoIPFormatIntfc& /*aSrc*/, - TInt /*aEventType*/) +void CPjAudioEngine::Event (const CVoIPFormatIntfc& /*aSrc*/, + TInt /*aEventType*/) { } @@ -678,89 +741,101 @@ void CPjAudioEngine::Event(const CVoIPFormatIntfc& /*aSrc*/, #ifdef USE_NATIVE_PCM -static void RecCbPcm2(CVoIPDataBuffer *buf, void *user_data) +static void RecCbPcm2 (CVoIPDataBuffer *buf, void *user_data) { + struct vas_stream *strm = (struct vas_stream*) user_data; - TPtr8 buffer(0, 0, 0); + TPtr8 buffer (0, 0, 0); pj_int16_t *p_buf; unsigned buf_len; /* Get the buffer */ - buf->GetPayloadPtr(buffer); - + buf->GetPayloadPtr (buffer); + /* Call parent callback */ p_buf = (pj_int16_t*) buffer.Ptr(); buf_len = buffer.Length() >> 1; + while (buf_len) { - unsigned req; - - req = strm->param.samples_per_frame - strm->rec_buf_len; - if (req > buf_len) - req = buf_len; - pjmedia_copy_samples(strm->rec_buf + strm->rec_buf_len, p_buf, req); - p_buf += req; - buf_len -= req; - strm->rec_buf_len += req; - - if (strm->rec_buf_len >= strm->param.samples_per_frame) { - pjmedia_frame f; - - f.buf = strm->rec_buf; - f.type = PJMEDIA_FRAME_TYPE_AUDIO; - f.size = strm->param.samples_per_frame << 1; - strm->rec_cb(strm->user_data, &f); - strm->rec_buf_len = 0; - } + unsigned req; + + req = strm->param.samples_per_frame - strm->rec_buf_len; + + if (req > buf_len) + req = buf_len; + + pjmedia_copy_samples (strm->rec_buf + strm->rec_buf_len, p_buf, req); + + p_buf += req; + + buf_len -= req; + + strm->rec_buf_len += req; + + if (strm->rec_buf_len >= strm->param.samples_per_frame) { + pjmedia_frame f; + + f.buf = strm->rec_buf; + f.type = PJMEDIA_FRAME_TYPE_AUDIO; + f.size = strm->param.samples_per_frame << 1; + strm->rec_cb (strm->user_data, &f); + strm->rec_buf_len = 0; + } } } -static void PlayCbPcm2(CVoIPDataBuffer *buf, void *user_data) +static void PlayCbPcm2 (CVoIPDataBuffer *buf, void *user_data) { + struct vas_stream *strm = (struct vas_stream*) user_data; - TPtr8 buffer(0, 0, 0); + TPtr8 buffer (0, 0, 0); pjmedia_frame f; /* Get the buffer */ - buf->GetPayloadPtr(buffer); + buf->GetPayloadPtr (buffer); /* Call parent callback */ f.buf = strm->play_buf; f.size = strm->param.samples_per_frame << 1; - strm->play_cb(strm->user_data, &f); + strm->play_cb (strm->user_data, &f); + if (f.type != PJMEDIA_FRAME_TYPE_AUDIO) { - pjmedia_zero_samples((pj_int16_t*)f.buf, - strm->param.samples_per_frame); + pjmedia_zero_samples ( (pj_int16_t*) f.buf, + strm->param.samples_per_frame); } + f.size = strm->param.samples_per_frame << 1; /* Init buffer attributes and header. */ buffer.Zero(); - buffer.Append((TUint8*)f.buf, f.size); + buffer.Append ( (TUint8*) f.buf, f.size); /* Set the buffer */ - buf->SetPayloadPtr(buffer); + buf->SetPayloadPtr (buffer); } #else // not USE_NATIVE_PCM -static void RecCbPcm(CVoIPDataBuffer *buf, void *user_data) +static void RecCbPcm (CVoIPDataBuffer *buf, void *user_data) { + struct vas_stream *strm = (struct vas_stream*) user_data; - TPtr8 buffer(0, 0, 0); + TPtr8 buffer (0, 0, 0); /* Get the buffer */ - buf->GetPayloadPtr(buffer); - + buf->GetPayloadPtr (buffer); + /* Buffer has to contain normal speech. */ - pj_assert(buffer[0] == 1 && buffer[1] == 0); + pj_assert (buffer[0] == 1 && buffer[1] == 0); /* Detect the recorder G.711 frame size, player frame size will follow * this recorder frame size. */ + if (vas_g711_frame_len == 0) { - vas_g711_frame_len = buffer.Length() < 160? 80 : 160; - TRACE_((THIS_FILE, "Detected VAS G.711 frame size = %u samples", - vas_g711_frame_len)); + vas_g711_frame_len = buffer.Length() < 160? 80 : 160; + TRACE_ ( (THIS_FILE, "Detected VAS G.711 frame size = %u samples", + vas_g711_frame_len)); } /* Decode VAS buffer (coded in G.711) and put the PCM result into rec_buf. @@ -769,511 +844,539 @@ static void RecCbPcm(CVoIPDataBuffer *buf, void *user_data) unsigned samples_processed = 0; while (samples_processed < vas_g711_frame_len) { - unsigned samples_to_process; - unsigned samples_req; - - samples_to_process = vas_g711_frame_len - samples_processed; - samples_req = (strm->param.samples_per_frame / - strm->param.channel_count / - strm->resample_factor) - - strm->rec_buf_len; - if (samples_to_process > samples_req) - samples_to_process = samples_req; - - pjmedia_ulaw_decode(&strm->rec_buf[strm->rec_buf_len], - buffer.Ptr() + 2 + samples_processed, - samples_to_process); - - strm->rec_buf_len += samples_to_process; - samples_processed += samples_to_process; - - /* Buffer is full, time to call parent callback */ - if (strm->rec_buf_len == strm->param.samples_per_frame / - strm->param.channel_count / - strm->resample_factor) - { - pjmedia_frame f; - - /* Need to resample clock rate? */ - if (strm->rec_resample) { - unsigned resampled = 0; - - while (resampled < strm->rec_buf_len) { - pjmedia_resample_run(strm->rec_resample, - &strm->rec_buf[resampled], - strm->pcm_buf + - resampled * strm->resample_factor); - resampled += 80; - } - f.buf = strm->pcm_buf; - } else { - f.buf = strm->rec_buf; - } - - /* Need to convert channel count? */ - if (strm->param.channel_count != 1) { - pjmedia_convert_channel_1ton((pj_int16_t*)f.buf, - (pj_int16_t*)f.buf, - strm->param.channel_count, - strm->param.samples_per_frame / - strm->param.channel_count, - 0); - } - - /* Call parent callback */ - f.type = PJMEDIA_FRAME_TYPE_AUDIO; - f.size = strm->param.samples_per_frame << 1; - strm->rec_cb(strm->user_data, &f); - strm->rec_buf_len = 0; - } + unsigned samples_to_process; + unsigned samples_req; + + samples_to_process = vas_g711_frame_len - samples_processed; + samples_req = (strm->param.samples_per_frame / + strm->param.channel_count / + strm->resample_factor) - + strm->rec_buf_len; + + if (samples_to_process > samples_req) + samples_to_process = samples_req; + + pjmedia_ulaw_decode (&strm->rec_buf[strm->rec_buf_len], + buffer.Ptr() + 2 + samples_processed, + samples_to_process); + + strm->rec_buf_len += samples_to_process; + + samples_processed += samples_to_process; + + /* Buffer is full, time to call parent callback */ + if (strm->rec_buf_len == strm->param.samples_per_frame / + strm->param.channel_count / + strm->resample_factor) { + pjmedia_frame f; + + /* Need to resample clock rate? */ + + if (strm->rec_resample) { + unsigned resampled = 0; + + while (resampled < strm->rec_buf_len) { + pjmedia_resample_run (strm->rec_resample, + &strm->rec_buf[resampled], + strm->pcm_buf + + resampled * strm->resample_factor); + resampled += 80; + } + + f.buf = strm->pcm_buf; + } else { + f.buf = strm->rec_buf; + } + + /* Need to convert channel count? */ + if (strm->param.channel_count != 1) { + pjmedia_convert_channel_1ton ( (pj_int16_t*) f.buf, + (pj_int16_t*) f.buf, + strm->param.channel_count, + strm->param.samples_per_frame / + strm->param.channel_count, + 0); + } + + /* Call parent callback */ + f.type = PJMEDIA_FRAME_TYPE_AUDIO; + + f.size = strm->param.samples_per_frame << 1; + + strm->rec_cb (strm->user_data, &f); + + strm->rec_buf_len = 0; + } } } #endif // USE_NATIVE_PCM -static void PlayCbPcm(CVoIPDataBuffer *buf, void *user_data) +static void PlayCbPcm (CVoIPDataBuffer *buf, void *user_data) { + struct vas_stream *strm = (struct vas_stream*) user_data; unsigned g711_frame_len = vas_g711_frame_len; - TPtr8 buffer(0, 0, 0); + TPtr8 buffer (0, 0, 0); /* Get the buffer */ - buf->GetPayloadPtr(buffer); + buf->GetPayloadPtr (buffer); /* Init buffer attributes and header. */ buffer.Zero(); - buffer.Append(1); - buffer.Append(0); + buffer.Append (1); + buffer.Append (0); /* Assume frame size is 10ms if frame size hasn't been known. */ + if (g711_frame_len == 0) - g711_frame_len = 80; + g711_frame_len = 80; /* Call parent stream callback to get PCM samples to play, * encode the PCM samples into G.711 and put it into VAS buffer. */ unsigned samples_processed = 0; - + while (samples_processed < g711_frame_len) { - /* Need more samples to play, time to call parent callback */ - if (strm->play_buf_len == 0) { - pjmedia_frame f; - unsigned samples_got; - - f.size = strm->param.samples_per_frame << 1; - if (strm->play_resample || strm->param.channel_count != 1) - f.buf = strm->pcm_buf; - else - f.buf = strm->play_buf; - - /* Call parent callback */ - strm->play_cb(strm->user_data, &f); - if (f.type != PJMEDIA_FRAME_TYPE_AUDIO) { - pjmedia_zero_samples((pj_int16_t*)f.buf, - strm->param.samples_per_frame); - } - - samples_got = strm->param.samples_per_frame / - strm->param.channel_count / - strm->resample_factor; - - /* Need to convert channel count? */ - if (strm->param.channel_count != 1) { - pjmedia_convert_channel_nto1((pj_int16_t*)f.buf, - (pj_int16_t*)f.buf, - strm->param.channel_count, - strm->param.samples_per_frame, - PJ_FALSE, - 0); - } - - /* Need to resample clock rate? */ - if (strm->play_resample) { - unsigned resampled = 0; - - while (resampled < samples_got) - { - pjmedia_resample_run(strm->play_resample, - strm->pcm_buf + - resampled * strm->resample_factor, - &strm->play_buf[resampled]); - resampled += 80; - } - } - - strm->play_buf_len = samples_got; - strm->play_buf_start = 0; - } - - unsigned tmp; - - tmp = PJ_MIN(strm->play_buf_len, g711_frame_len - samples_processed); - pjmedia_ulaw_encode((pj_uint8_t*)&strm->play_buf[strm->play_buf_start], - &strm->play_buf[strm->play_buf_start], - tmp); - buffer.Append((TUint8*)&strm->play_buf[strm->play_buf_start], tmp); - samples_processed += tmp; - strm->play_buf_len -= tmp; - strm->play_buf_start += tmp; + /* Need more samples to play, time to call parent callback */ + if (strm->play_buf_len == 0) { + pjmedia_frame f; + unsigned samples_got; + + f.size = strm->param.samples_per_frame << 1; + + if (strm->play_resample || strm->param.channel_count != 1) + f.buf = strm->pcm_buf; + else + f.buf = strm->play_buf; + + /* Call parent callback */ + strm->play_cb (strm->user_data, &f); + + if (f.type != PJMEDIA_FRAME_TYPE_AUDIO) { + pjmedia_zero_samples ( (pj_int16_t*) f.buf, + strm->param.samples_per_frame); + } + + samples_got = strm->param.samples_per_frame / + + strm->param.channel_count / + strm->resample_factor; + + /* Need to convert channel count? */ + + if (strm->param.channel_count != 1) { + pjmedia_convert_channel_nto1 ( (pj_int16_t*) f.buf, + (pj_int16_t*) f.buf, + strm->param.channel_count, + strm->param.samples_per_frame, + PJ_FALSE, + 0); + } + + /* Need to resample clock rate? */ + if (strm->play_resample) { + unsigned resampled = 0; + + while (resampled < samples_got) { + pjmedia_resample_run (strm->play_resample, + strm->pcm_buf + + resampled * strm->resample_factor, + &strm->play_buf[resampled]); + resampled += 80; + } + } + + strm->play_buf_len = samples_got; + + strm->play_buf_start = 0; + } + + unsigned tmp; + + tmp = PJ_MIN (strm->play_buf_len, g711_frame_len - samples_processed); + pjmedia_ulaw_encode ( (pj_uint8_t*) &strm->play_buf[strm->play_buf_start], + &strm->play_buf[strm->play_buf_start], + tmp); + buffer.Append ( (TUint8*) &strm->play_buf[strm->play_buf_start], tmp); + samples_processed += tmp; + strm->play_buf_len -= tmp; + strm->play_buf_start += tmp; } /* Set the buffer */ - buf->SetPayloadPtr(buffer); + buf->SetPayloadPtr (buffer); } /**************************************************************************** * Internal VAS callbacks for non-PCM format */ -static void RecCb(CVoIPDataBuffer *buf, void *user_data) +static void RecCb (CVoIPDataBuffer *buf, void *user_data) { + struct vas_stream *strm = (struct vas_stream*) user_data; pjmedia_frame_ext *frame = (pjmedia_frame_ext*) strm->rec_buf; - TPtr8 buffer(0, 0, 0); + TPtr8 buffer (0, 0, 0); /* Get the buffer */ - buf->GetPayloadPtr(buffer); - - switch(strm->param.ext_fmt.id) { - case PJMEDIA_FORMAT_AMR: - { - const pj_uint8_t *p = (const pj_uint8_t*)buffer.Ptr() + 1; - unsigned len = buffer.Length() - 1; - - pjmedia_frame_ext_append_subframe(frame, p, len << 3, 160); - if (frame->samples_cnt == strm->param.samples_per_frame) { - frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; - strm->rec_cb(strm->user_data, (pjmedia_frame*)frame); - frame->samples_cnt = 0; - frame->subframe_cnt = 0; - } - } - break; - - case PJMEDIA_FORMAT_G729: - { - /* Check if we got a normal or SID frame. */ - if (buffer[0] != 0) { - enum { NORMAL_LEN = 22, SID_LEN = 8 }; - TBitStream *bitstream = (TBitStream*)strm->strm_data; - unsigned src_len = buffer.Length()- 2; - - pj_assert(src_len == NORMAL_LEN || src_len == SID_LEN); - - const TDesC8& p = bitstream->CompressG729Frame( - buffer.Right(src_len), - src_len == SID_LEN); - - pjmedia_frame_ext_append_subframe(frame, p.Ptr(), - p.Length() << 3, 80); - } else { /* We got null frame. */ - pjmedia_frame_ext_append_subframe(frame, NULL, 0, 80); - } - - if (frame->samples_cnt == strm->param.samples_per_frame) { - frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; - strm->rec_cb(strm->user_data, (pjmedia_frame*)frame); - frame->samples_cnt = 0; - frame->subframe_cnt = 0; - } - } - break; - - case PJMEDIA_FORMAT_ILBC: - { - unsigned samples_got; - - samples_got = strm->param.ext_fmt.bitrate == 15200? 160 : 240; - - /* Check if we got a normal or SID frame. */ - if (buffer[0] != 0) { - const pj_uint8_t *p = (const pj_uint8_t*)buffer.Ptr() + 2; - unsigned len = buffer.Length() - 2; - - pjmedia_frame_ext_append_subframe(frame, p, len << 3, - samples_got); - } else { /* We got null frame. */ - pjmedia_frame_ext_append_subframe(frame, NULL, 0, samples_got); - } - - if (frame->samples_cnt == strm->param.samples_per_frame) { - frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; - strm->rec_cb(strm->user_data, (pjmedia_frame*)frame); - frame->samples_cnt = 0; - frame->subframe_cnt = 0; - } - } - break; - - case PJMEDIA_FORMAT_PCMU: - case PJMEDIA_FORMAT_PCMA: - { - unsigned samples_processed = 0; - - /* Make sure it is normal frame. */ - pj_assert(buffer[0] == 1 && buffer[1] == 0); - - /* Detect the recorder G.711 frame size, player frame size will - * follow this recorder frame size. - */ - if (vas_g711_frame_len == 0) { - vas_g711_frame_len = buffer.Length() < 160? 80 : 160; - TRACE_((THIS_FILE, "Detected VAS G.711 frame size = %u samples", - vas_g711_frame_len)); - } - - /* Convert VAS buffer format into pjmedia_frame_ext. Whenever - * samples count in the frame is equal to stream's samples per - * frame, call parent stream callback. - */ - while (samples_processed < vas_g711_frame_len) { - unsigned tmp; - const pj_uint8_t *pb = (const pj_uint8_t*)buffer.Ptr() + - 2 + samples_processed; - - tmp = PJ_MIN(strm->param.samples_per_frame - frame->samples_cnt, - vas_g711_frame_len - samples_processed); - - pjmedia_frame_ext_append_subframe(frame, pb, tmp << 3, tmp); - samples_processed += tmp; - - if (frame->samples_cnt == strm->param.samples_per_frame) { - frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; - strm->rec_cb(strm->user_data, (pjmedia_frame*)frame); - frame->samples_cnt = 0; - frame->subframe_cnt = 0; - } - } - } - break; - - default: - break; + buf->GetPayloadPtr (buffer); + + switch (strm->param.ext_fmt.id) { + + case PJMEDIA_FORMAT_AMR: { + const pj_uint8_t *p = (const pj_uint8_t*) buffer.Ptr() + 1; + unsigned len = buffer.Length() - 1; + + pjmedia_frame_ext_append_subframe (frame, p, len << 3, 160); + + if (frame->samples_cnt == strm->param.samples_per_frame) { + frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; + strm->rec_cb (strm->user_data, (pjmedia_frame*) frame); + frame->samples_cnt = 0; + frame->subframe_cnt = 0; + } + } + + break; + + case PJMEDIA_FORMAT_G729: { + /* Check if we got a normal or SID frame. */ + if (buffer[0] != 0) { + enum { NORMAL_LEN = 22, SID_LEN = 8 }; + TBitStream *bitstream = (TBitStream*) strm->strm_data; + unsigned src_len = buffer.Length()- 2; + + pj_assert (src_len == NORMAL_LEN || src_len == SID_LEN); + + const TDesC8& p = bitstream->CompressG729Frame ( + buffer.Right (src_len), + src_len == SID_LEN); + + pjmedia_frame_ext_append_subframe (frame, p.Ptr(), + p.Length() << 3, 80); + } else { /* We got null frame. */ + pjmedia_frame_ext_append_subframe (frame, NULL, 0, 80); + } + + if (frame->samples_cnt == strm->param.samples_per_frame) { + frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; + strm->rec_cb (strm->user_data, (pjmedia_frame*) frame); + frame->samples_cnt = 0; + frame->subframe_cnt = 0; + } + } + + break; + + case PJMEDIA_FORMAT_ILBC: { + unsigned samples_got; + + samples_got = strm->param.ext_fmt.bitrate == 15200? 160 : 240; + + /* Check if we got a normal or SID frame. */ + + if (buffer[0] != 0) { + const pj_uint8_t *p = (const pj_uint8_t*) buffer.Ptr() + 2; + unsigned len = buffer.Length() - 2; + + pjmedia_frame_ext_append_subframe (frame, p, len << 3, + samples_got); + } else { /* We got null frame. */ + pjmedia_frame_ext_append_subframe (frame, NULL, 0, samples_got); + } + + if (frame->samples_cnt == strm->param.samples_per_frame) { + frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; + strm->rec_cb (strm->user_data, (pjmedia_frame*) frame); + frame->samples_cnt = 0; + frame->subframe_cnt = 0; + } + } + + break; + + case PJMEDIA_FORMAT_PCMU: + + case PJMEDIA_FORMAT_PCMA: { + unsigned samples_processed = 0; + + /* Make sure it is normal frame. */ + pj_assert (buffer[0] == 1 && buffer[1] == 0); + + /* Detect the recorder G.711 frame size, player frame size will + * follow this recorder frame size. + */ + + if (vas_g711_frame_len == 0) { + vas_g711_frame_len = buffer.Length() < 160? 80 : 160; + TRACE_ ( (THIS_FILE, "Detected VAS G.711 frame size = %u samples", + vas_g711_frame_len)); + } + + /* Convert VAS buffer format into pjmedia_frame_ext. Whenever + * samples count in the frame is equal to stream's samples per + * frame, call parent stream callback. + */ + while (samples_processed < vas_g711_frame_len) { + unsigned tmp; + const pj_uint8_t *pb = (const pj_uint8_t*) buffer.Ptr() + + 2 + samples_processed; + + tmp = PJ_MIN (strm->param.samples_per_frame - frame->samples_cnt, + vas_g711_frame_len - samples_processed); + + pjmedia_frame_ext_append_subframe (frame, pb, tmp << 3, tmp); + samples_processed += tmp; + + if (frame->samples_cnt == strm->param.samples_per_frame) { + frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; + strm->rec_cb (strm->user_data, (pjmedia_frame*) frame); + frame->samples_cnt = 0; + frame->subframe_cnt = 0; + } + } + } + + break; + + default: + break; } } -static void PlayCb(CVoIPDataBuffer *buf, void *user_data) +static void PlayCb (CVoIPDataBuffer *buf, void *user_data) { + struct vas_stream *strm = (struct vas_stream*) user_data; pjmedia_frame_ext *frame = (pjmedia_frame_ext*) strm->play_buf; - TPtr8 buffer(0, 0, 0); + TPtr8 buffer (0, 0, 0); /* Get the buffer */ - buf->GetPayloadPtr(buffer); + buf->GetPayloadPtr (buffer); /* Init buffer attributes and header. */ buffer.Zero(); - switch(strm->param.ext_fmt.id) { - case PJMEDIA_FORMAT_AMR: - { - if (frame->samples_cnt == 0) { - frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; - strm->play_cb(strm->user_data, (pjmedia_frame*)frame); - pj_assert(frame->base.type==PJMEDIA_FRAME_TYPE_EXTENDED || - frame->base.type==PJMEDIA_FRAME_TYPE_NONE); - } - - if (frame->base.type == PJMEDIA_FRAME_TYPE_EXTENDED) { - pjmedia_frame_ext_subframe *sf; - unsigned samples_cnt; - - sf = pjmedia_frame_ext_get_subframe(frame, 0); - samples_cnt = frame->samples_cnt / frame->subframe_cnt; - - if (sf->data && sf->bitlen) { - /* AMR header for VAS is one byte, the format (may be!): - * 0xxxxy00, where xxxx:frame type, y:not sure. - */ - unsigned len = (sf->bitlen+7)>>3; - enum {SID_FT = 8 }; - pj_uint8_t amr_header = 4, ft = SID_FT; - - if (len >= pjmedia_codec_amrnb_framelen[0]) - ft = pjmedia_codec_amr_get_mode2(PJ_TRUE, len); - - amr_header |= ft << 3; - buffer.Append(amr_header); - - buffer.Append((TUint8*)sf->data, len); - } else { - buffer.Append(0); - } - - pjmedia_frame_ext_pop_subframes(frame, 1); - - } else { /* PJMEDIA_FRAME_TYPE_NONE */ - buffer.Append(0); - - frame->samples_cnt = 0; - frame->subframe_cnt = 0; - } - } - break; - - case PJMEDIA_FORMAT_G729: - { - if (frame->samples_cnt == 0) { - frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; - strm->play_cb(strm->user_data, (pjmedia_frame*)frame); - pj_assert(frame->base.type==PJMEDIA_FRAME_TYPE_EXTENDED || - frame->base.type==PJMEDIA_FRAME_TYPE_NONE); - } - - if (frame->base.type == PJMEDIA_FRAME_TYPE_EXTENDED) { - pjmedia_frame_ext_subframe *sf; - unsigned samples_cnt; - - sf = pjmedia_frame_ext_get_subframe(frame, 0); - samples_cnt = frame->samples_cnt / frame->subframe_cnt; - - if (sf->data && sf->bitlen) { - enum { NORMAL_LEN = 10, SID_LEN = 2 }; - pj_bool_t sid_frame = ((sf->bitlen >> 3) == SID_LEN); - TBitStream *bitstream = (TBitStream*)strm->strm_data; - const TPtrC8 src(sf->data, sf->bitlen>>3); - const TDesC8 &dst = bitstream->ExpandG729Frame(src, - sid_frame); - if (sid_frame) { - buffer.Append(2); - buffer.Append(0); - } else { - buffer.Append(1); - buffer.Append(0); - } - buffer.Append(dst); - } else { - buffer.Append(2); - buffer.Append(0); - - buffer.AppendFill(0, 22); - } - - pjmedia_frame_ext_pop_subframes(frame, 1); - - } else { /* PJMEDIA_FRAME_TYPE_NONE */ - buffer.Append(2); - buffer.Append(0); - - buffer.AppendFill(0, 22); - } - } - break; - - case PJMEDIA_FORMAT_ILBC: - { - if (frame->samples_cnt == 0) { - frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; - strm->play_cb(strm->user_data, (pjmedia_frame*)frame); - pj_assert(frame->base.type==PJMEDIA_FRAME_TYPE_EXTENDED || - frame->base.type==PJMEDIA_FRAME_TYPE_NONE); - } - - if (frame->base.type == PJMEDIA_FRAME_TYPE_EXTENDED) { - pjmedia_frame_ext_subframe *sf; - unsigned samples_cnt; - - sf = pjmedia_frame_ext_get_subframe(frame, 0); - samples_cnt = frame->samples_cnt / frame->subframe_cnt; - - pj_assert((strm->param.ext_fmt.bitrate == 15200 && - samples_cnt == 160) || - (strm->param.ext_fmt.bitrate != 15200 && - samples_cnt == 240)); - - if (sf->data && sf->bitlen) { - buffer.Append(1); - buffer.Append(0); - buffer.Append((TUint8*)sf->data, sf->bitlen>>3); - } else { - unsigned frame_len; - - buffer.Append(1); - buffer.Append(0); - - /* VAS iLBC frame is 20ms or 30ms */ - frame_len = strm->param.ext_fmt.bitrate == 15200? 38 : 50; - buffer.AppendFill(0, frame_len); - } - - pjmedia_frame_ext_pop_subframes(frame, 1); - - } else { /* PJMEDIA_FRAME_TYPE_NONE */ - - unsigned frame_len; - - buffer.Append(1); - buffer.Append(0); - - /* VAS iLBC frame is 20ms or 30ms */ - frame_len = strm->param.ext_fmt.bitrate == 15200? 38 : 50; - buffer.AppendFill(0, frame_len); - - } - } - break; - - case PJMEDIA_FORMAT_PCMU: - case PJMEDIA_FORMAT_PCMA: - { - unsigned samples_ready = 0; - unsigned samples_req = vas_g711_frame_len; - - /* Assume frame size is 10ms if frame size hasn't been known. */ - if (samples_req == 0) - samples_req = 80; - - buffer.Append(1); - buffer.Append(0); - - /* Call parent stream callback to get samples to play. */ - while (samples_ready < samples_req) { - if (frame->samples_cnt == 0) { - frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; - strm->play_cb(strm->user_data, (pjmedia_frame*)frame); - pj_assert(frame->base.type==PJMEDIA_FRAME_TYPE_EXTENDED || - frame->base.type==PJMEDIA_FRAME_TYPE_NONE); - } - - if (frame->base.type == PJMEDIA_FRAME_TYPE_EXTENDED) { - pjmedia_frame_ext_subframe *sf; - unsigned samples_cnt; - - sf = pjmedia_frame_ext_get_subframe(frame, 0); - samples_cnt = frame->samples_cnt / frame->subframe_cnt; - if (sf->data && sf->bitlen) { - buffer.Append((TUint8*)sf->data, sf->bitlen>>3); - } else { - pj_uint8_t silc; - silc = (strm->param.ext_fmt.id==PJMEDIA_FORMAT_PCMU)? - pjmedia_linear2ulaw(0) : pjmedia_linear2alaw(0); - buffer.AppendFill(silc, samples_cnt); - } - samples_ready += samples_cnt; - - pjmedia_frame_ext_pop_subframes(frame, 1); - - } else { /* PJMEDIA_FRAME_TYPE_NONE */ - pj_uint8_t silc; - - silc = (strm->param.ext_fmt.id==PJMEDIA_FORMAT_PCMU)? - pjmedia_linear2ulaw(0) : pjmedia_linear2alaw(0); - buffer.AppendFill(silc, samples_req - samples_ready); - - samples_ready = samples_req; - frame->samples_cnt = 0; - frame->subframe_cnt = 0; - } - } - } - break; - - default: - break; + switch (strm->param.ext_fmt.id) { + + case PJMEDIA_FORMAT_AMR: { + if (frame->samples_cnt == 0) { + frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; + strm->play_cb (strm->user_data, (pjmedia_frame*) frame); + pj_assert (frame->base.type==PJMEDIA_FRAME_TYPE_EXTENDED || + frame->base.type==PJMEDIA_FRAME_TYPE_NONE); + } + + if (frame->base.type == PJMEDIA_FRAME_TYPE_EXTENDED) { + pjmedia_frame_ext_subframe *sf; + unsigned samples_cnt; + + sf = pjmedia_frame_ext_get_subframe (frame, 0); + samples_cnt = frame->samples_cnt / frame->subframe_cnt; + + if (sf->data && sf->bitlen) { + /* AMR header for VAS is one byte, the format (may be!): + * 0xxxxy00, where xxxx:frame type, y:not sure. + */ + unsigned len = (sf->bitlen+7) >>3; + enum {SID_FT = 8 }; + pj_uint8_t amr_header = 4, ft = SID_FT; + + if (len >= pjmedia_codec_amrnb_framelen[0]) + ft = pjmedia_codec_amr_get_mode2 (PJ_TRUE, len); + + amr_header |= ft << 3; + + buffer.Append (amr_header); + + buffer.Append ( (TUint8*) sf->data, len); + } else { + buffer.Append (0); + } + + pjmedia_frame_ext_pop_subframes (frame, 1); + + } else { /* PJMEDIA_FRAME_TYPE_NONE */ + buffer.Append (0); + + frame->samples_cnt = 0; + frame->subframe_cnt = 0; + } + } + + break; + + case PJMEDIA_FORMAT_G729: { + if (frame->samples_cnt == 0) { + frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; + strm->play_cb (strm->user_data, (pjmedia_frame*) frame); + pj_assert (frame->base.type==PJMEDIA_FRAME_TYPE_EXTENDED || + frame->base.type==PJMEDIA_FRAME_TYPE_NONE); + } + + if (frame->base.type == PJMEDIA_FRAME_TYPE_EXTENDED) { + pjmedia_frame_ext_subframe *sf; + unsigned samples_cnt; + + sf = pjmedia_frame_ext_get_subframe (frame, 0); + samples_cnt = frame->samples_cnt / frame->subframe_cnt; + + if (sf->data && sf->bitlen) { + enum { NORMAL_LEN = 10, SID_LEN = 2 }; + pj_bool_t sid_frame = ( (sf->bitlen >> 3) == SID_LEN); + TBitStream *bitstream = (TBitStream*) strm->strm_data; + const TPtrC8 src (sf->data, sf->bitlen>>3); + const TDesC8 &dst = bitstream->ExpandG729Frame (src, + sid_frame); + + if (sid_frame) { + buffer.Append (2); + buffer.Append (0); + } else { + buffer.Append (1); + buffer.Append (0); + } + + buffer.Append (dst); + } else { + buffer.Append (2); + buffer.Append (0); + + buffer.AppendFill (0, 22); + } + + pjmedia_frame_ext_pop_subframes (frame, 1); + + } else { /* PJMEDIA_FRAME_TYPE_NONE */ + buffer.Append (2); + buffer.Append (0); + + buffer.AppendFill (0, 22); + } + } + + break; + + case PJMEDIA_FORMAT_ILBC: { + if (frame->samples_cnt == 0) { + frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; + strm->play_cb (strm->user_data, (pjmedia_frame*) frame); + pj_assert (frame->base.type==PJMEDIA_FRAME_TYPE_EXTENDED || + frame->base.type==PJMEDIA_FRAME_TYPE_NONE); + } + + if (frame->base.type == PJMEDIA_FRAME_TYPE_EXTENDED) { + pjmedia_frame_ext_subframe *sf; + unsigned samples_cnt; + + sf = pjmedia_frame_ext_get_subframe (frame, 0); + samples_cnt = frame->samples_cnt / frame->subframe_cnt; + + pj_assert ( (strm->param.ext_fmt.bitrate == 15200 && + samples_cnt == 160) || + (strm->param.ext_fmt.bitrate != 15200 && + samples_cnt == 240)); + + if (sf->data && sf->bitlen) { + buffer.Append (1); + buffer.Append (0); + buffer.Append ( (TUint8*) sf->data, sf->bitlen>>3); + } else { + unsigned frame_len; + + buffer.Append (1); + buffer.Append (0); + + /* VAS iLBC frame is 20ms or 30ms */ + frame_len = strm->param.ext_fmt.bitrate == 15200? 38 : 50; + buffer.AppendFill (0, frame_len); + } + + pjmedia_frame_ext_pop_subframes (frame, 1); + + } else { /* PJMEDIA_FRAME_TYPE_NONE */ + + unsigned frame_len; + + buffer.Append (1); + buffer.Append (0); + + /* VAS iLBC frame is 20ms or 30ms */ + frame_len = strm->param.ext_fmt.bitrate == 15200? 38 : 50; + buffer.AppendFill (0, frame_len); + + } + } + + break; + + case PJMEDIA_FORMAT_PCMU: + + case PJMEDIA_FORMAT_PCMA: { + unsigned samples_ready = 0; + unsigned samples_req = vas_g711_frame_len; + + /* Assume frame size is 10ms if frame size hasn't been known. */ + + if (samples_req == 0) + samples_req = 80; + + buffer.Append (1); + + buffer.Append (0); + + /* Call parent stream callback to get samples to play. */ + while (samples_ready < samples_req) { + if (frame->samples_cnt == 0) { + frame->base.type = PJMEDIA_FRAME_TYPE_EXTENDED; + strm->play_cb (strm->user_data, (pjmedia_frame*) frame); + pj_assert (frame->base.type==PJMEDIA_FRAME_TYPE_EXTENDED || + frame->base.type==PJMEDIA_FRAME_TYPE_NONE); + } + + if (frame->base.type == PJMEDIA_FRAME_TYPE_EXTENDED) { + pjmedia_frame_ext_subframe *sf; + unsigned samples_cnt; + + sf = pjmedia_frame_ext_get_subframe (frame, 0); + samples_cnt = frame->samples_cnt / frame->subframe_cnt; + + if (sf->data && sf->bitlen) { + buffer.Append ( (TUint8*) sf->data, sf->bitlen>>3); + } else { + pj_uint8_t silc; + silc = (strm->param.ext_fmt.id==PJMEDIA_FORMAT_PCMU) ? + pjmedia_linear2ulaw (0) : pjmedia_linear2alaw (0); + buffer.AppendFill (silc, samples_cnt); + } + + samples_ready += samples_cnt; + + pjmedia_frame_ext_pop_subframes (frame, 1); + + } else { /* PJMEDIA_FRAME_TYPE_NONE */ + pj_uint8_t silc; + + silc = (strm->param.ext_fmt.id==PJMEDIA_FORMAT_PCMU) ? + pjmedia_linear2ulaw (0) : pjmedia_linear2alaw (0); + buffer.AppendFill (silc, samples_req - samples_ready); + + samples_ready = samples_req; + frame->samples_cnt = 0; + frame->subframe_cnt = 0; + } + } + } + + break; + + default: + break; } /* Set the buffer */ - buf->SetPayloadPtr(buffer); + buf->SetPayloadPtr (buffer); } @@ -1285,19 +1388,20 @@ static void PlayCb(CVoIPDataBuffer *buf, void *user_data) * C compatible declaration of VAS factory. */ PJ_BEGIN_DECL -PJ_DECL(pjmedia_aud_dev_factory*)pjmedia_symb_vas_factory(pj_pool_factory *pf); +PJ_DECL (pjmedia_aud_dev_factory*) pjmedia_symb_vas_factory (pj_pool_factory *pf); PJ_END_DECL /* * Init VAS audio driver. */ -PJ_DEF(pjmedia_aud_dev_factory*) pjmedia_symb_vas_factory(pj_pool_factory *pf) +PJ_DEF (pjmedia_aud_dev_factory*) pjmedia_symb_vas_factory (pj_pool_factory *pf) { + struct vas_factory *f; pj_pool_t *pool; - pool = pj_pool_create(pf, "VAS", 1000, 1000, NULL); - f = PJ_POOL_ZALLOC_T(pool, struct vas_factory); + pool = pj_pool_create (pf, "VAS", 1000, 1000, NULL); + f = PJ_POOL_ZALLOC_T (pool, struct vas_factory); f->pf = pf; f->pool = pool; f->base.op = &factory_op; @@ -1306,169 +1410,185 @@ PJ_DEF(pjmedia_aud_dev_factory*) pjmedia_symb_vas_factory(pj_pool_factory *pf) } /* API: init factory */ -static pj_status_t factory_init(pjmedia_aud_dev_factory *f) +static pj_status_t factory_init (pjmedia_aud_dev_factory *f) { - struct vas_factory *af = (struct vas_factory*)f; + + struct vas_factory *af = (struct vas_factory*) f; CVoIPUtilityFactory *vas_factory; CVoIPAudioUplinkStream *vas_uplink; CVoIPAudioDownlinkStream *vas_dnlink; RArray<TVoIPCodecFormat> uplink_formats, dnlink_formats; unsigned ext_fmt_cnt = 0; - TVersion vas_version(1, 0, 0); /* Not really used at this time */ + TVersion vas_version (1, 0, 0); /* Not really used at this time */ TInt err; - pj_ansi_strcpy(af->dev_info.name, "S60 VAS"); + pj_ansi_strcpy (af->dev_info.name, "S60 VAS"); af->dev_info.default_samples_per_sec = 8000; af->dev_info.caps = PJMEDIA_AUD_DEV_CAP_EXT_FORMAT | - //PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING | - PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING | - PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE | - PJMEDIA_AUD_DEV_CAP_VAD | - PJMEDIA_AUD_DEV_CAP_CNG; - af->dev_info.routes = PJMEDIA_AUD_DEV_ROUTE_EARPIECE | - PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER; + //PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING | + PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING | + PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE | + PJMEDIA_AUD_DEV_CAP_VAD | + PJMEDIA_AUD_DEV_CAP_CNG; + af->dev_info.routes = PJMEDIA_AUD_DEV_ROUTE_EARPIECE | + PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER; af->dev_info.input_count = 1; af->dev_info.output_count = 1; af->dev_info.ext_fmt_cnt = 0; /* Enumerate supported formats */ - err = CVoIPUtilityFactory::CreateFactory(vas_factory); + err = CVoIPUtilityFactory::CreateFactory (vas_factory); + if (err != KErrNone) - goto on_error; + goto on_error; - /* On VAS 2.0, uplink & downlink stream should be instantiated before + /* On VAS 2.0, uplink & downlink stream should be instantiated before * querying formats. */ - err = vas_factory->CreateUplinkStream(vas_version, - CVoIPUtilityFactory::EVoIPCall, - vas_uplink); + err = vas_factory->CreateUplinkStream (vas_version, + CVoIPUtilityFactory::EVoIPCall, + vas_uplink); + if (err != KErrNone) - goto on_error; - - err = vas_factory->CreateDownlinkStream(vas_version, - CVoIPUtilityFactory::EVoIPCall, - vas_dnlink); + goto on_error; + + err = vas_factory->CreateDownlinkStream (vas_version, + CVoIPUtilityFactory::EVoIPCall, + vas_dnlink); + if (err != KErrNone) - goto on_error; - + goto on_error; + uplink_formats.Reset(); - err = vas_factory->GetSupportedUplinkFormats(uplink_formats); + + err = vas_factory->GetSupportedUplinkFormats (uplink_formats); + if (err != KErrNone) - goto on_error; + goto on_error; dnlink_formats.Reset(); - err = vas_factory->GetSupportedDownlinkFormats(dnlink_formats); + + err = vas_factory->GetSupportedDownlinkFormats (dnlink_formats); + if (err != KErrNone) - goto on_error; + goto on_error; /* Free the streams, they are just used for querying formats */ delete vas_uplink; + vas_uplink = NULL; + delete vas_dnlink; + vas_dnlink = NULL; - + for (TInt i = 0; i < dnlink_formats.Count(); i++) { - /* Format must be supported by both downlink & uplink. */ - if (uplink_formats.Find(dnlink_formats[i]) == KErrNotFound) - continue; - - switch (dnlink_formats[i]) { - case EAMR_NB: - af->dev_info.ext_fmt[ext_fmt_cnt].id = PJMEDIA_FORMAT_AMR; - af->dev_info.ext_fmt[ext_fmt_cnt].bitrate = 7400; - af->dev_info.ext_fmt[ext_fmt_cnt].vad = PJ_TRUE; - break; - - case EG729: - af->dev_info.ext_fmt[ext_fmt_cnt].id = PJMEDIA_FORMAT_G729; - af->dev_info.ext_fmt[ext_fmt_cnt].bitrate = 8000; - af->dev_info.ext_fmt[ext_fmt_cnt].vad = PJ_FALSE; - break; - - case EILBC: - af->dev_info.ext_fmt[ext_fmt_cnt].id = PJMEDIA_FORMAT_ILBC; - af->dev_info.ext_fmt[ext_fmt_cnt].bitrate = 13333; - af->dev_info.ext_fmt[ext_fmt_cnt].vad = PJ_TRUE; - break; - - case EG711: + /* Format must be supported by both downlink & uplink. */ + if (uplink_formats.Find (dnlink_formats[i]) == KErrNotFound) + continue; + + switch (dnlink_formats[i]) { + + case EAMR_NB: + af->dev_info.ext_fmt[ext_fmt_cnt].id = PJMEDIA_FORMAT_AMR; + af->dev_info.ext_fmt[ext_fmt_cnt].bitrate = 7400; + af->dev_info.ext_fmt[ext_fmt_cnt].vad = PJ_TRUE; + break; + + case EG729: + af->dev_info.ext_fmt[ext_fmt_cnt].id = PJMEDIA_FORMAT_G729; + af->dev_info.ext_fmt[ext_fmt_cnt].bitrate = 8000; + af->dev_info.ext_fmt[ext_fmt_cnt].vad = PJ_FALSE; + break; + + case EILBC: + af->dev_info.ext_fmt[ext_fmt_cnt].id = PJMEDIA_FORMAT_ILBC; + af->dev_info.ext_fmt[ext_fmt_cnt].bitrate = 13333; + af->dev_info.ext_fmt[ext_fmt_cnt].vad = PJ_TRUE; + break; + + case EG711: #if PJMEDIA_AUDIO_DEV_SYMB_VAS_VERSION==2 - case EG711_10MS: + + case EG711_10MS: #endif - af->dev_info.ext_fmt[ext_fmt_cnt].id = PJMEDIA_FORMAT_PCMU; - af->dev_info.ext_fmt[ext_fmt_cnt].bitrate = 64000; - af->dev_info.ext_fmt[ext_fmt_cnt].vad = PJ_FALSE; - ++ext_fmt_cnt; - af->dev_info.ext_fmt[ext_fmt_cnt].id = PJMEDIA_FORMAT_PCMA; - af->dev_info.ext_fmt[ext_fmt_cnt].bitrate = 64000; - af->dev_info.ext_fmt[ext_fmt_cnt].vad = PJ_FALSE; - break; - - default: - continue; - } - - ++ext_fmt_cnt; + af->dev_info.ext_fmt[ext_fmt_cnt].id = PJMEDIA_FORMAT_PCMU; + af->dev_info.ext_fmt[ext_fmt_cnt].bitrate = 64000; + af->dev_info.ext_fmt[ext_fmt_cnt].vad = PJ_FALSE; + ++ext_fmt_cnt; + af->dev_info.ext_fmt[ext_fmt_cnt].id = PJMEDIA_FORMAT_PCMA; + af->dev_info.ext_fmt[ext_fmt_cnt].bitrate = 64000; + af->dev_info.ext_fmt[ext_fmt_cnt].vad = PJ_FALSE; + break; + + default: + continue; + } + + ++ext_fmt_cnt; } - + af->dev_info.ext_fmt_cnt = ext_fmt_cnt; uplink_formats.Close(); dnlink_formats.Close(); - - PJ_LOG(3, (THIS_FILE, "VAS initialized")); + + PJ_LOG (3, (THIS_FILE, "VAS initialized")); return PJ_SUCCESS; - + on_error: - return PJ_RETURN_OS_ERROR(err); + return PJ_RETURN_OS_ERROR (err); } /* API: destroy factory */ -static pj_status_t factory_destroy(pjmedia_aud_dev_factory *f) +static pj_status_t factory_destroy (pjmedia_aud_dev_factory *f) { - struct vas_factory *af = (struct vas_factory*)f; + + struct vas_factory *af = (struct vas_factory*) f; pj_pool_t *pool = af->pool; af->pool = NULL; - pj_pool_release(pool); + pj_pool_release (pool); + + PJ_LOG (3, (THIS_FILE, "VAS destroyed")); - PJ_LOG(3, (THIS_FILE, "VAS destroyed")); - return PJ_SUCCESS; } /* API: get number of devices */ -static unsigned factory_get_dev_count(pjmedia_aud_dev_factory *f) +static unsigned factory_get_dev_count (pjmedia_aud_dev_factory *f) { - PJ_UNUSED_ARG(f); + PJ_UNUSED_ARG (f); return 1; } /* API: get device info */ -static pj_status_t factory_get_dev_info(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_dev_info *info) +static pj_status_t factory_get_dev_info (pjmedia_aud_dev_factory *f, + unsigned index, + pjmedia_aud_dev_info *info) { - struct vas_factory *af = (struct vas_factory*)f; - PJ_ASSERT_RETURN(index == 0, PJMEDIA_EAUD_INVDEV); + struct vas_factory *af = (struct vas_factory*) f; + + PJ_ASSERT_RETURN (index == 0, PJMEDIA_EAUD_INVDEV); - pj_memcpy(info, &af->dev_info, sizeof(*info)); + pj_memcpy (info, &af->dev_info, sizeof (*info)); return PJ_SUCCESS; } /* API: create default device parameter */ -static pj_status_t factory_default_param(pjmedia_aud_dev_factory *f, - unsigned index, - pjmedia_aud_param *param) +static pj_status_t factory_default_param (pjmedia_aud_dev_factory *f, + unsigned index, + pjmedia_aud_param *param) { - struct vas_factory *af = (struct vas_factory*)f; - PJ_ASSERT_RETURN(index == 0, PJMEDIA_EAUD_INVDEV); + struct vas_factory *af = (struct vas_factory*) f; - pj_bzero(param, sizeof(*param)); + PJ_ASSERT_RETURN (index == 0, PJMEDIA_EAUD_INVDEV); + + pj_bzero (param, sizeof (*param)); param->dir = PJMEDIA_DIR_CAPTURE_PLAYBACK; param->rec_id = index; param->play_id = index; @@ -1484,15 +1604,17 @@ static pj_status_t factory_default_param(pjmedia_aud_dev_factory *f, /* API: create stream */ -static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, - const pjmedia_aud_param *param, - pjmedia_aud_rec_cb rec_cb, - pjmedia_aud_play_cb play_cb, - void *user_data, - pjmedia_aud_stream **p_aud_strm) +static pj_status_t factory_create_stream (pjmedia_aud_dev_factory *f, + const pjmedia_aud_param *param, + pjmedia_aud_rec_cb rec_cb, + pjmedia_aud_play_cb play_cb, + void *user_data, + pjmedia_aud_stream **p_aud_strm) { - struct vas_factory *af = (struct vas_factory*)f; + + struct vas_factory *af = (struct vas_factory*) f; pj_pool_t *pool; + struct vas_stream *strm; CPjAudioSetting vas_setting; @@ -1500,406 +1622,433 @@ static pj_status_t factory_create_stream(pjmedia_aud_dev_factory *f, PjAudioCallback vas_play_cb; /* Can only support 16bits per sample */ - PJ_ASSERT_RETURN(param->bits_per_sample == BITS_PER_SAMPLE, PJ_EINVAL); + PJ_ASSERT_RETURN (param->bits_per_sample == BITS_PER_SAMPLE, PJ_EINVAL); /* Supported clock rates: - * - for non-PCM format: 8kHz - * - for PCM format: 8kHz and 16kHz + * - for non-PCM format: 8kHz + * - for PCM format: 8kHz and 16kHz */ - PJ_ASSERT_RETURN(param->clock_rate == 8000 || - (param->clock_rate == 16000 && - param->ext_fmt.id == PJMEDIA_FORMAT_L16), - PJ_EINVAL); + PJ_ASSERT_RETURN (param->clock_rate == 8000 || + (param->clock_rate == 16000 && + param->ext_fmt.id == PJMEDIA_FORMAT_L16), + PJ_EINVAL); /* Supported channels number: * - for non-PCM format: mono - * - for PCM format: mono and stereo + * - for PCM format: mono and stereo */ - PJ_ASSERT_RETURN(param->channel_count == 1 || - (param->channel_count == 2 && - param->ext_fmt.id == PJMEDIA_FORMAT_L16), - PJ_EINVAL); + PJ_ASSERT_RETURN (param->channel_count == 1 || + (param->channel_count == 2 && + param->ext_fmt.id == PJMEDIA_FORMAT_L16), + PJ_EINVAL); /* Create and Initialize stream descriptor */ - pool = pj_pool_create(af->pf, "vas-dev", 1000, 1000, NULL); - PJ_ASSERT_RETURN(pool, PJ_ENOMEM); + pool = pj_pool_create (af->pf, "vas-dev", 1000, 1000, NULL); + PJ_ASSERT_RETURN (pool, PJ_ENOMEM); - strm = PJ_POOL_ZALLOC_T(pool, struct vas_stream); + strm = PJ_POOL_ZALLOC_T (pool, struct vas_stream); strm->pool = pool; strm->param = *param; if (strm->param.flags & PJMEDIA_AUD_DEV_CAP_EXT_FORMAT == 0) - strm->param.ext_fmt.id = PJMEDIA_FORMAT_L16; - + strm->param.ext_fmt.id = PJMEDIA_FORMAT_L16; + /* Set audio engine fourcc. */ - switch(strm->param.ext_fmt.id) { - case PJMEDIA_FORMAT_L16: -#ifdef USE_NATIVE_PCM - vas_setting.format = EPCM16; + switch (strm->param.ext_fmt.id) { + + case PJMEDIA_FORMAT_L16: +#ifdef USE_NATIVE_PCM + vas_setting.format = EPCM16; #else - vas_setting.format = EG711; + vas_setting.format = EG711; #endif - break; - case PJMEDIA_FORMAT_PCMU: - case PJMEDIA_FORMAT_PCMA: - vas_setting.format = EG711; - break; - case PJMEDIA_FORMAT_AMR: - vas_setting.format = EAMR_NB; - break; - case PJMEDIA_FORMAT_G729: - vas_setting.format = EG729; - break; - case PJMEDIA_FORMAT_ILBC: - vas_setting.format = EILBC; - break; - default: - vas_setting.format = ENULL; - break; + break; + + case PJMEDIA_FORMAT_PCMU: + + case PJMEDIA_FORMAT_PCMA: + vas_setting.format = EG711; + break; + + case PJMEDIA_FORMAT_AMR: + vas_setting.format = EAMR_NB; + break; + + case PJMEDIA_FORMAT_G729: + vas_setting.format = EG729; + break; + + case PJMEDIA_FORMAT_ILBC: + vas_setting.format = EILBC; + break; + + default: + vas_setting.format = ENULL; + break; } /* Set audio engine mode. */ - if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_L16) - { -#ifdef USE_NATIVE_PCM - vas_setting.mode = 0; + if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_L16) { +#ifdef USE_NATIVE_PCM + vas_setting.mode = 0; #else - vas_setting.mode = CVoIPFormatIntfc::EG711uLaw; + vas_setting.mode = CVoIPFormatIntfc::EG711uLaw; #endif - } - else if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_AMR) - { - vas_setting.mode = strm->param.ext_fmt.bitrate; - } - else if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_PCMU) - { - vas_setting.mode = CVoIPFormatIntfc::EG711uLaw; - } - else if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_PCMA) - { - vas_setting.mode = CVoIPFormatIntfc::EG711ALaw; - } - else if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_ILBC) - { - if (strm->param.ext_fmt.bitrate == 15200) - vas_setting.mode = CVoIPFormatIntfc::EiLBC20mSecFrame; - else - vas_setting.mode = CVoIPFormatIntfc::EiLBC30mSecFrame; + } else if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_AMR) { + vas_setting.mode = strm->param.ext_fmt.bitrate; + } else if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_PCMU) { + vas_setting.mode = CVoIPFormatIntfc::EG711uLaw; + } else if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_PCMA) { + vas_setting.mode = CVoIPFormatIntfc::EG711ALaw; + } else if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_ILBC) { + if (strm->param.ext_fmt.bitrate == 15200) + vas_setting.mode = CVoIPFormatIntfc::EiLBC20mSecFrame; + else + vas_setting.mode = CVoIPFormatIntfc::EiLBC30mSecFrame; } else { - vas_setting.mode = 0; + vas_setting.mode = 0; } - /* Disable VAD on L16, G711, iLBC, and also G729 (G729's SID + /* Disable VAD on L16, G711, iLBC, and also G729 (G729's SID * potentially cause noise?). */ if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_PCMU || - strm->param.ext_fmt.id == PJMEDIA_FORMAT_PCMA || - strm->param.ext_fmt.id == PJMEDIA_FORMAT_L16 || - strm->param.ext_fmt.id == PJMEDIA_FORMAT_ILBC || - strm->param.ext_fmt.id == PJMEDIA_FORMAT_G729) - { - vas_setting.vad = EFalse; + strm->param.ext_fmt.id == PJMEDIA_FORMAT_PCMA || + strm->param.ext_fmt.id == PJMEDIA_FORMAT_L16 || + strm->param.ext_fmt.id == PJMEDIA_FORMAT_ILBC || + strm->param.ext_fmt.id == PJMEDIA_FORMAT_G729) { + vas_setting.vad = EFalse; } else { - vas_setting.vad = strm->param.ext_fmt.vad; + vas_setting.vad = strm->param.ext_fmt.vad; } - + /* Set other audio engine attributes. */ vas_setting.plc = strm->param.plc_enabled; + vas_setting.cng = vas_setting.vad; - vas_setting.loudspk = - strm->param.output_route==PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER; + + vas_setting.loudspk = + strm->param.output_route==PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER; /* Set audio engine callbacks. */ if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_L16) { #ifdef USE_NATIVE_PCM - vas_play_cb = &PlayCbPcm2; - vas_rec_cb = &RecCbPcm2; + vas_play_cb = &PlayCbPcm2; + vas_rec_cb = &RecCbPcm2; #else - vas_play_cb = &PlayCbPcm; - vas_rec_cb = &RecCbPcm; + vas_play_cb = &PlayCbPcm; + vas_rec_cb = &RecCbPcm; #endif } else { - vas_play_cb = &PlayCb; - vas_rec_cb = &RecCb; + vas_play_cb = &PlayCb; + vas_rec_cb = &RecCb; } strm->rec_cb = rec_cb; + strm->play_cb = play_cb; strm->user_data = user_data; strm->resample_factor = strm->param.clock_rate / 8000; /* play_buf size is samples per frame scaled in to 8kHz mono. */ - strm->play_buf = (pj_int16_t*)pj_pool_zalloc( - pool, - (strm->param.samples_per_frame / - strm->resample_factor / - strm->param.channel_count) << 1); + strm->play_buf = (pj_int16_t*) pj_pool_zalloc ( + pool, + (strm->param.samples_per_frame / + strm->resample_factor / + strm->param.channel_count) << 1); strm->play_buf_len = 0; strm->play_buf_start = 0; /* rec_buf size is samples per frame scaled in to 8kHz mono. */ - strm->rec_buf = (pj_int16_t*)pj_pool_zalloc( - pool, - (strm->param.samples_per_frame / - strm->resample_factor / - strm->param.channel_count) << 1); + strm->rec_buf = (pj_int16_t*) pj_pool_zalloc ( + pool, + (strm->param.samples_per_frame / + strm->resample_factor / + strm->param.channel_count) << 1); strm->rec_buf_len = 0; if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_G729) { - TBitStream *g729_bitstream = new TBitStream; - - PJ_ASSERT_RETURN(g729_bitstream, PJ_ENOMEM); - strm->strm_data = (void*)g729_bitstream; + TBitStream *g729_bitstream = new TBitStream; + + PJ_ASSERT_RETURN (g729_bitstream, PJ_ENOMEM); + strm->strm_data = (void*) g729_bitstream; } - + /* Init resampler when format is PCM and clock rate is not 8kHz */ - if (strm->param.clock_rate != 8000 && - strm->param.ext_fmt.id == PJMEDIA_FORMAT_L16) - { - pj_status_t status; - - if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { - /* Create resample for recorder */ - status = pjmedia_resample_create( pool, PJ_TRUE, PJ_FALSE, 1, - 8000, - strm->param.clock_rate, - 80, - &strm->rec_resample); - if (status != PJ_SUCCESS) - return status; - } - - if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { - /* Create resample for player */ - status = pjmedia_resample_create( pool, PJ_TRUE, PJ_FALSE, 1, - strm->param.clock_rate, - 8000, - 80 * strm->resample_factor, - &strm->play_resample); - if (status != PJ_SUCCESS) - return status; - } + if (strm->param.clock_rate != 8000 && + strm->param.ext_fmt.id == PJMEDIA_FORMAT_L16) { + pj_status_t status; + + if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { + /* Create resample for recorder */ + status = pjmedia_resample_create (pool, PJ_TRUE, PJ_FALSE, 1, + 8000, + strm->param.clock_rate, + 80, + &strm->rec_resample); + + if (status != PJ_SUCCESS) + return status; + } + + if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { + /* Create resample for player */ + status = pjmedia_resample_create (pool, PJ_TRUE, PJ_FALSE, 1, + strm->param.clock_rate, + 8000, + 80 * strm->resample_factor, + &strm->play_resample); + + if (status != PJ_SUCCESS) + return status; + } } /* Create PCM buffer, when the clock rate is not 8kHz or not mono */ if (strm->param.ext_fmt.id == PJMEDIA_FORMAT_L16 && - (strm->resample_factor > 1 || strm->param.channel_count != 1)) - { - strm->pcm_buf = (pj_int16_t*)pj_pool_zalloc(pool, - strm->param.samples_per_frame << 1); + (strm->resample_factor > 1 || strm->param.channel_count != 1)) { + strm->pcm_buf = (pj_int16_t*) pj_pool_zalloc (pool, + strm->param.samples_per_frame << 1); } - + /* Create the audio engine. */ - TRAPD(err, strm->engine = CPjAudioEngine::NewL(strm, - vas_rec_cb, vas_play_cb, - strm, vas_setting)); + TRAPD (err, strm->engine = CPjAudioEngine::NewL (strm, + vas_rec_cb, vas_play_cb, + strm, vas_setting)); + if (err != KErrNone) { - pj_pool_release(pool); - return PJ_RETURN_OS_ERROR(err); + pj_pool_release (pool); + return PJ_RETURN_OS_ERROR (err); } /* Apply output volume setting if specified */ if (param->flags & PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING) { - stream_set_cap(&strm->base, PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, - ¶m->output_vol); + stream_set_cap (&strm->base, PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, + ¶m->output_vol); } /* Done */ strm->base.op = &stream_op; + *p_aud_strm = &strm->base; return PJ_SUCCESS; } /* API: Get stream info. */ -static pj_status_t stream_get_param(pjmedia_aud_stream *s, - pjmedia_aud_param *pi) +static pj_status_t stream_get_param (pjmedia_aud_stream *s, + pjmedia_aud_param *pi) { - struct vas_stream *strm = (struct vas_stream*)s; - PJ_ASSERT_RETURN(strm && pi, PJ_EINVAL); + struct vas_stream *strm = (struct vas_stream*) s; - pj_memcpy(pi, &strm->param, sizeof(*pi)); + PJ_ASSERT_RETURN (strm && pi, PJ_EINVAL); + + pj_memcpy (pi, &strm->param, sizeof (*pi)); /* Update the output volume setting */ - if (stream_get_cap(s, PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, - &pi->output_vol) == PJ_SUCCESS) - { - pi->flags |= PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING; + + if (stream_get_cap (s, PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, + &pi->output_vol) == PJ_SUCCESS) { + pi->flags |= PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING; } - + return PJ_SUCCESS; } /* API: get capability */ -static pj_status_t stream_get_cap(pjmedia_aud_stream *s, - pjmedia_aud_dev_cap cap, - void *pval) +static pj_status_t stream_get_cap (pjmedia_aud_stream *s, + pjmedia_aud_dev_cap cap, + void *pval) { - struct vas_stream *strm = (struct vas_stream*)s; + + struct vas_stream *strm = (struct vas_stream*) s; pj_status_t status = PJ_ENOTSUP; - PJ_ASSERT_RETURN(s && pval, PJ_EINVAL); + PJ_ASSERT_RETURN (s && pval, PJ_EINVAL); switch (cap) { - case PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE: - if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { - *(pjmedia_aud_dev_route*)pval = strm->param.output_route; - status = PJ_SUCCESS; - } - break; - - /* There is a case that GetMaxGain() stucks, e.g: in N95. */ - /* - case PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING: - if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { - PJ_ASSERT_RETURN(strm->engine, PJ_EINVAL); - - TInt max_gain = strm->engine->GetMaxGain(); - TInt gain = strm->engine->GetGain(); - - if (max_gain > 0 && gain >= 0) { - *(unsigned*)pval = gain * 100 / max_gain; - status = PJ_SUCCESS; - } else { - status = PJMEDIA_EAUD_NOTREADY; - } - } - break; - */ - - case PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING: - if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { - PJ_ASSERT_RETURN(strm->engine, PJ_EINVAL); - - TInt max_vol = strm->engine->GetMaxVolume(); - TInt vol = strm->engine->GetVolume(); - - if (max_vol > 0 && vol >= 0) { - *(unsigned*)pval = vol * 100 / max_vol; - status = PJ_SUCCESS; - } else { - status = PJMEDIA_EAUD_NOTREADY; - } - } - break; - default: - break; + + case PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE: + + if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { + * (pjmedia_aud_dev_route*) pval = strm->param.output_route; + status = PJ_SUCCESS; + } + + break; + + /* There is a case that GetMaxGain() stucks, e.g: in N95. */ + /* + case PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING: + if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { + PJ_ASSERT_RETURN(strm->engine, PJ_EINVAL); + + TInt max_gain = strm->engine->GetMaxGain(); + TInt gain = strm->engine->GetGain(); + + if (max_gain > 0 && gain >= 0) { + *(unsigned*)pval = gain * 100 / max_gain; + status = PJ_SUCCESS; + } else { + status = PJMEDIA_EAUD_NOTREADY; + } + } + break; + */ + + case PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING: + + if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { + PJ_ASSERT_RETURN (strm->engine, PJ_EINVAL); + + TInt max_vol = strm->engine->GetMaxVolume(); + TInt vol = strm->engine->GetVolume(); + + if (max_vol > 0 && vol >= 0) { + * (unsigned*) pval = vol * 100 / max_vol; + status = PJ_SUCCESS; + } else { + status = PJMEDIA_EAUD_NOTREADY; + } + } + + break; + + default: + break; } - + return status; } /* API: set capability */ -static pj_status_t stream_set_cap(pjmedia_aud_stream *s, - pjmedia_aud_dev_cap cap, - const void *pval) +static pj_status_t stream_set_cap (pjmedia_aud_stream *s, + pjmedia_aud_dev_cap cap, + const void *pval) { - struct vas_stream *strm = (struct vas_stream*)s; + + struct vas_stream *strm = (struct vas_stream*) s; pj_status_t status = PJ_ENOTSUP; - PJ_ASSERT_RETURN(s && pval, PJ_EINVAL); + PJ_ASSERT_RETURN (s && pval, PJ_EINVAL); switch (cap) { - case PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE: - if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { - pjmedia_aud_dev_route r = *(const pjmedia_aud_dev_route*)pval; - TInt err; - - PJ_ASSERT_RETURN(strm->engine, PJ_EINVAL); - - switch (r) { - case PJMEDIA_AUD_DEV_ROUTE_DEFAULT: - case PJMEDIA_AUD_DEV_ROUTE_EARPIECE: - err = strm->engine->ActivateSpeaker(EFalse); - status = (err==KErrNone)? PJ_SUCCESS:PJ_RETURN_OS_ERROR(err); - break; - case PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER: - err = strm->engine->ActivateSpeaker(ETrue); - status = (err==KErrNone)? PJ_SUCCESS:PJ_RETURN_OS_ERROR(err); - break; - default: - status = PJ_EINVAL; - break; - } - if (status == PJ_SUCCESS) - strm->param.output_route = r; - } - break; - - /* There is a case that GetMaxGain() stucks, e.g: in N95. */ - /* - case PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING: - if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { - PJ_ASSERT_RETURN(strm->engine, PJ_EINVAL); - - TInt max_gain = strm->engine->GetMaxGain(); - if (max_gain > 0) { - TInt gain, err; - - gain = *(unsigned*)pval * max_gain / 100; - err = strm->engine->SetGain(gain); - status = (err==KErrNone)? PJ_SUCCESS:PJ_RETURN_OS_ERROR(err); - } else { - status = PJMEDIA_EAUD_NOTREADY; - } - if (status == PJ_SUCCESS) - strm->param.input_vol = *(unsigned*)pval; - } - break; - */ - - case PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING: - if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { - PJ_ASSERT_RETURN(strm->engine, PJ_EINVAL); - - TInt max_vol = strm->engine->GetMaxVolume(); - if (max_vol > 0) { - TInt vol, err; - - vol = *(unsigned*)pval * max_vol / 100; - err = strm->engine->SetVolume(vol); - status = (err==KErrNone)? PJ_SUCCESS:PJ_RETURN_OS_ERROR(err); - } else { - status = PJMEDIA_EAUD_NOTREADY; - } - if (status == PJ_SUCCESS) - strm->param.output_vol = *(unsigned*)pval; - } - break; - default: - break; + + case PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE: + + if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { + pjmedia_aud_dev_route r = * (const pjmedia_aud_dev_route*) pval; + TInt err; + + PJ_ASSERT_RETURN (strm->engine, PJ_EINVAL); + + switch (r) { + + case PJMEDIA_AUD_DEV_ROUTE_DEFAULT: + + case PJMEDIA_AUD_DEV_ROUTE_EARPIECE: + err = strm->engine->ActivateSpeaker (EFalse); + status = (err==KErrNone) ? PJ_SUCCESS:PJ_RETURN_OS_ERROR (err); + break; + + case PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER: + err = strm->engine->ActivateSpeaker (ETrue); + status = (err==KErrNone) ? PJ_SUCCESS:PJ_RETURN_OS_ERROR (err); + break; + + default: + status = PJ_EINVAL; + break; + } + + if (status == PJ_SUCCESS) + strm->param.output_route = r; + } + + break; + + /* There is a case that GetMaxGain() stucks, e.g: in N95. */ + /* + case PJMEDIA_AUD_DEV_CAP_INPUT_VOLUME_SETTING: + if (strm->param.dir & PJMEDIA_DIR_CAPTURE) { + PJ_ASSERT_RETURN(strm->engine, PJ_EINVAL); + + TInt max_gain = strm->engine->GetMaxGain(); + if (max_gain > 0) { + TInt gain, err; + + gain = *(unsigned*)pval * max_gain / 100; + err = strm->engine->SetGain(gain); + status = (err==KErrNone)? PJ_SUCCESS:PJ_RETURN_OS_ERROR(err); + } else { + status = PJMEDIA_EAUD_NOTREADY; + } + if (status == PJ_SUCCESS) + strm->param.input_vol = *(unsigned*)pval; + } + break; + */ + + case PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING: + + if (strm->param.dir & PJMEDIA_DIR_PLAYBACK) { + PJ_ASSERT_RETURN (strm->engine, PJ_EINVAL); + + TInt max_vol = strm->engine->GetMaxVolume(); + + if (max_vol > 0) { + TInt vol, err; + + vol = * (unsigned*) pval * max_vol / 100; + err = strm->engine->SetVolume (vol); + status = (err==KErrNone) ? PJ_SUCCESS:PJ_RETURN_OS_ERROR (err); + } else { + status = PJMEDIA_EAUD_NOTREADY; + } + + if (status == PJ_SUCCESS) + strm->param.output_vol = * (unsigned*) pval; + } + + break; + + default: + break; } - + return status; } /* API: Start stream. */ -static pj_status_t stream_start(pjmedia_aud_stream *strm) +static pj_status_t stream_start (pjmedia_aud_stream *strm) { - struct vas_stream *stream = (struct vas_stream*)strm; - PJ_ASSERT_RETURN(stream, PJ_EINVAL); + struct vas_stream *stream = (struct vas_stream*) strm; + + PJ_ASSERT_RETURN (stream, PJ_EINVAL); if (stream->engine) { - TInt err = stream->engine->Start(); - if (err != KErrNone) - return PJ_RETURN_OS_ERROR(err); + TInt err = stream->engine->Start(); + + if (err != KErrNone) + return PJ_RETURN_OS_ERROR (err); } return PJ_SUCCESS; } /* API: Stop stream. */ -static pj_status_t stream_stop(pjmedia_aud_stream *strm) +static pj_status_t stream_stop (pjmedia_aud_stream *strm) { - struct vas_stream *stream = (struct vas_stream*)strm; - PJ_ASSERT_RETURN(stream, PJ_EINVAL); + struct vas_stream *stream = (struct vas_stream*) strm; + + PJ_ASSERT_RETURN (stream, PJ_EINVAL); if (stream->engine) { - stream->engine->Stop(); + stream->engine->Stop(); } return PJ_SUCCESS; @@ -1907,28 +2056,31 @@ static pj_status_t stream_stop(pjmedia_aud_stream *strm) /* API: Destroy stream. */ -static pj_status_t stream_destroy(pjmedia_aud_stream *strm) +static pj_status_t stream_destroy (pjmedia_aud_stream *strm) { - struct vas_stream *stream = (struct vas_stream*)strm; - PJ_ASSERT_RETURN(stream, PJ_EINVAL); + struct vas_stream *stream = (struct vas_stream*) strm; + + PJ_ASSERT_RETURN (stream, PJ_EINVAL); - stream_stop(strm); + stream_stop (strm); delete stream->engine; stream->engine = NULL; if (stream->param.ext_fmt.id == PJMEDIA_FORMAT_G729) { - TBitStream *g729_bitstream = (TBitStream*)stream->strm_data; - stream->strm_data = NULL; - delete g729_bitstream; + TBitStream *g729_bitstream = (TBitStream*) stream->strm_data; + stream->strm_data = NULL; + delete g729_bitstream; } pj_pool_t *pool; + pool = stream->pool; + if (pool) { - stream->pool = NULL; - pj_pool_release(pool); + stream->pool = NULL; + pj_pool_release (pool); } return PJ_SUCCESS; diff --git a/sflphone-common/libs/pjproject/pjmedia/src/pjmedia/sdp_wrap.cpp b/sflphone-common/libs/pjproject/pjmedia/src/pjmedia/sdp_wrap.cpp index dd5b8fd09cb13bf51740f6a9a199bcfa927ee63f..cfca6d28ccc016aa5bb9112daaf12b3c2e61f14e 100644 --- a/sflphone-common/libs/pjproject/pjmedia/src/pjmedia/sdp_wrap.cpp +++ b/sflphone-common/libs/pjproject/pjmedia/src/pjmedia/sdp_wrap.cpp @@ -1,5 +1,5 @@ /* $Id: sdp_wrap.cpp 2873 2009-08-13 11:54:35Z nanang $ */ -/* +/* * Copyright (C) 2009 Teluu Inc. (http://www.teluu.com) * * This program is free software; you can redistribute it and/or modify @@ -14,7 +14,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* diff --git a/sflphone-common/libs/pjproject/pjnath/include/pjnath/config.h b/sflphone-common/libs/pjproject/pjnath/include/pjnath/config.h index f6e5cf81886cb5769557733894cacbd9c23a3f97..91ab258825971a4528788888a14b62d63396ed4a 100644 --- a/sflphone-common/libs/pjproject/pjnath/include/pjnath/config.h +++ b/sflphone-common/libs/pjproject/pjnath/include/pjnath/config.h @@ -1,5 +1,5 @@ /* $Id: config.h 2724 2009-05-29 13:04:03Z bennylp $ */ -/* +/* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org> * @@ -15,7 +15,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __PJNATH_CONFIG_H__ #define __PJNATH_CONFIG_H__ @@ -66,9 +66,9 @@ /** * The default initial STUN round-trip time estimation (the RTO value - * in RFC 3489-bis), in miliseconds. - * This value is used to control the STUN request - * retransmit time. The initial value of retransmission interval + * in RFC 3489-bis), in miliseconds. + * This value is used to control the STUN request + * retransmit time. The initial value of retransmission interval * would be set to this value, and will be doubled after each * retransmission. */ @@ -79,7 +79,7 @@ /** * The STUN transaction timeout value, in miliseconds. - * After the last retransmission is sent and if no response is received + * After the last retransmission is sent and if no response is received * after this time, the STUN transaction will be considered to have failed. * * The default value is 16x RTO (as per RFC 3489-bis). @@ -202,8 +202,8 @@ /** - * Number of seconds to refresh the permission/channel binding before the - * permission/channel binding expires. This value should be greater than + * Number of seconds to refresh the permission/channel binding before the + * permission/channel binding expires. This value should be greater than * PJ_TURN_PERM_TIMEOUT setting. */ #ifndef PJ_TURN_REFRESH_SEC_BEFORE @@ -212,7 +212,7 @@ /** - * The TURN session timer heart beat interval. When this timer occurs, the + * The TURN session timer heart beat interval. When this timer occurs, the * TURN session will scan all the permissions/channel bindings to see which * need to be refreshed. */ @@ -282,10 +282,10 @@ /** * The number of bits to represent ICE candidate's local preference. The * local preference is used to specify preference among candidates with - * the same type, and ICE draft suggests 65535 as the default local - * preference, which means we need 16 bits to represent the value. But + * the same type, and ICE draft suggests 65535 as the default local + * preference, which means we need 16 bits to represent the value. But * since we don't have the facility to specify local preference, we'll - * just disable this feature and let the preference sorted by the + * just disable this feature and let the preference sorted by the * type only. * * Default: 0 @@ -316,15 +316,15 @@ /** - * According to ICE Section 8.2. Updating States, if an In-Progress pair in - * the check list is for the same component as a nominated pair, the agent + * According to ICE Section 8.2. Updating States, if an In-Progress pair in + * the check list is for the same component as a nominated pair, the agent * SHOULD cease retransmissions for its check if its pair priority is lower * than the lowest priority nominated pair for that component. * * If a higher priority check is In Progress, this rule would cause that * check to be performed even when it most likely will fail. * - * The macro here controls if ICE session should cancel all In Progress + * The macro here controls if ICE session should cancel all In Progress * checks for the same component regardless of its priority. * * Default: 1 (yes, cancel all) diff --git a/sflphone-common/libs/pjproject/pjsip-apps/bin/pjsua-x86_64-unknown-linux-gnu b/sflphone-common/libs/pjproject/pjsip-apps/bin/pjsua-x86_64-unknown-linux-gnu index bb31dcbaa405d15a1a346008a66468e56eb3efeb..87e725cfc4299d138697617d25cf97d53d29b0f1 100755 Binary files a/sflphone-common/libs/pjproject/pjsip-apps/bin/pjsua-x86_64-unknown-linux-gnu and b/sflphone-common/libs/pjproject/pjsip-apps/bin/pjsua-x86_64-unknown-linux-gnu differ diff --git a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/auddemo b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/auddemo index 50810e25a2f1e8fdc258e12b0307fef4ada073e1..df0c0716b7c0b96d81ae7b2d4b8890b0a63499e4 100755 Binary files a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/auddemo and b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/auddemo differ diff --git a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/confsample b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/confsample index a0481c8188c53d3da9c6d76674ac93dea9ebbc53..241d17b6014e78017fbc5356ca3f363b56a2e405 100755 Binary files a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/confsample and b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/confsample differ diff --git a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/encdec b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/encdec index 62cc311341097b30baad0307928d4f7dd09bbed2..a459eb53c06e9dddf4bfe8f3a1b40549a86dc1cc 100755 Binary files a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/encdec and b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/encdec differ diff --git a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/jbsim b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/jbsim index 5804afc0eb743fe10c5980202541b8e30bc5c352..c59a41e77b02720e76982452da56d8e14f85abe8 100755 Binary files a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/jbsim and b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/jbsim differ diff --git a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/latency b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/latency index 5835c613ea70284efa213ddde61f469f39bd7b70..98878a757b8aa3f6ac8898c83bdcf18acfa00c66 100755 Binary files a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/latency and b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/latency differ diff --git a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/level b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/level index 81ea58da71356ad464cba6c581b6c8c4d9091d3f..f1696e6bd838e219a56549906856a735b0cc62e5 100755 Binary files a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/level and b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/level differ diff --git a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/mix b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/mix index b763cb277ace6942b26fa5b04568f756cb050c0d..b97cd6347675b7ac3a4abbafe984ed8d656a6648 100755 Binary files a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/mix and b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/mix differ diff --git a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/pcaputil b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/pcaputil index 69c265864ff8215e6aa4cadb55a8b728cf882470..2c3b95d38fdb4c18a303d826c127b2604c44cb54 100755 Binary files a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/pcaputil and b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/pcaputil differ diff --git a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/pjsip-perf b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/pjsip-perf index 114433776234ae4a08ef832067aaae36299ddc73..a1fe6016414b63439d4f7a0d24056e07f3de2a2e 100755 Binary files a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/pjsip-perf and b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/pjsip-perf differ diff --git a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/playfile b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/playfile index 2693f63a2d463907915dab619dd28082cef7af70..0cac592e896c4a2d0608d461f659099176f55d43 100755 Binary files a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/playfile and b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/playfile differ diff --git a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/playsine b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/playsine index 236ea55a6ff6c0c476b72460a32fe5864d2ea704..84712fa583892b6219dfe8d25f5fc89a923c7d33 100755 Binary files a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/playsine and b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/playsine differ diff --git a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/recfile b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/recfile index f39c8a177c7975e9eb82cbdf6e72f860662f25ae..859b70f259ad7e113ad1bf95aac54a0fd298233c 100755 Binary files a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/recfile and b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/recfile differ diff --git a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/resampleplay b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/resampleplay index 3929997b6924d704d98cefaffbc01d7ed642c839..3ad17da993028b9c6443c4cb416a8fca8c0b46cb 100755 Binary files a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/resampleplay and b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/resampleplay differ diff --git a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/simple_pjsua b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/simple_pjsua index 7af4bda76090acd0bff6862775d2b7765a44f9da..cbc5efd4a074b1ffb69d4bdd45480e70385ddf2c 100755 Binary files a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/simple_pjsua and b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/simple_pjsua differ diff --git a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/simpleua b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/simpleua index 36c7ecb36e92f2f30c644053a52b3203c0d52f79..e91d5c98603a833402ffa013cbad6528400b507d 100755 Binary files a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/simpleua and b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/simpleua differ diff --git a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/siprtp b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/siprtp index c5eecef2910b603cfb59c8b6488714ad72af0c39..706f3da0a1abde5ed81d46a8de3aec09e768c360 100755 Binary files a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/siprtp and b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/siprtp differ diff --git a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/stereotest b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/stereotest index 1197eaec6937ec3d895acdc36aac697385dc81a6..48d2cb9d29d85e3fe06d3160478351c1de5cc2ce 100755 Binary files a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/stereotest and b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/stereotest differ diff --git a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/streamutil b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/streamutil index 2b8341776294a37e41fa9a212dffbefbd3dd85b1..d75839500e29e409ece938dd2cf92c5801168fa2 100755 Binary files a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/streamutil and b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/streamutil differ diff --git a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/strerror b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/strerror index a2023069ffe97e26bd1def9920667515845b3d3f..9ae95e6a81673b759e1243210bb48319e1d55515 100755 Binary files a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/strerror and b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/strerror differ diff --git a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/tonegen b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/tonegen index d91ba2bee467ae85bc0e8a728d122db545e6529b..8b1b0b29ad70d1d356102fb46ec8a8055f77200b 100755 Binary files a/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/tonegen and b/sflphone-common/libs/pjproject/pjsip-apps/bin/samples/x86_64-unknown-linux-gnu/tonegen differ diff --git a/sflphone-common/libs/pjproject/pjsip-apps/src/pjsua_wince/pjsua_wince.cpp b/sflphone-common/libs/pjproject/pjsip-apps/src/pjsua_wince/pjsua_wince.cpp index a10c67f887e3396f998e694ce5b4f3322de127f2..8609fc5f0ed414089f4666ff9c1bebe9c0b85d7c 100644 --- a/sflphone-common/libs/pjproject/pjsip-apps/src/pjsua_wince/pjsua_wince.cpp +++ b/sflphone-common/libs/pjproject/pjsip-apps/src/pjsua_wince/pjsua_wince.cpp @@ -54,15 +54,15 @@ static HWND hwndActionButton, hwndExitButton; // // STUN server #if 0 - // Use this to have the STUN server resolved normally +// Use this to have the STUN server resolved normally # define STUN_DOMAIN NULL # define STUN_SERVER "stun.fwdnet.net" #elif 0 - // Use this to have the STUN server resolved with DNS SRV +// Use this to have the STUN server resolved with DNS SRV # define STUN_DOMAIN "iptel.org" # define STUN_SERVER NULL #else - // Use this to disable STUN +// Use this to disable STUN # define STUN_DOMAIN NULL # define STUN_SERVER NULL #endif @@ -82,16 +82,14 @@ static int g_current_acc; static int g_current_call = PJSUA_INVALID_ID; static int g_current_action; -enum -{ +enum { ID_GLOBAL_STATUS = 21, ID_URI, ID_CALL_STATUS, ID_POLL_TIMER, }; -enum -{ +enum { ID_MENU_NONE = 64, ID_MENU_CALL, ID_MENU_ANSWER, @@ -104,85 +102,101 @@ enum static ATOM MyRegisterClass (HINSTANCE, LPTSTR); BOOL InitInstance (HINSTANCE, int); static void OnCreate (HWND hWnd); -static LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM); +static LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM); ///////////////////////////////////////////////////////////////////////////// -static void OnError(const wchar_t *title, pj_status_t status) +static void OnError (const wchar_t *title, pj_status_t status) { char errmsg[PJ_ERR_MSG_SIZE]; - PJ_DECL_UNICODE_TEMP_BUF(werrmsg, PJ_ERR_MSG_SIZE); + PJ_DECL_UNICODE_TEMP_BUF (werrmsg, PJ_ERR_MSG_SIZE); + + pj_strerror (status, errmsg, sizeof (errmsg)); - pj_strerror(status, errmsg, sizeof(errmsg)); - - MessageBox(NULL, PJ_STRING_TO_NATIVE(errmsg, werrmsg, PJ_ERR_MSG_SIZE), - title, MB_OK); + MessageBox (NULL, PJ_STRING_TO_NATIVE (errmsg, werrmsg, PJ_ERR_MSG_SIZE), + title, MB_OK); } -static void SetLocalURI(const char *uri, int len, bool enabled=true) +static void SetLocalURI (const char *uri, int len, bool enabled=true) { wchar_t tmp[128]; - if (len==-1) len=pj_ansi_strlen(uri); - pj_ansi_to_unicode(uri, len, tmp, PJ_ARRAY_SIZE(tmp)); - SetDlgItemText(hMainWnd, ID_GLOBAL_STATUS, tmp); - EnableWindow(hwndGlobalStatus, enabled?TRUE:FALSE); + + if (len==-1) len=pj_ansi_strlen (uri); + + pj_ansi_to_unicode (uri, len, tmp, PJ_ARRAY_SIZE (tmp)); + + SetDlgItemText (hMainWnd, ID_GLOBAL_STATUS, tmp); + + EnableWindow (hwndGlobalStatus, enabled?TRUE:FALSE); } -static void SetURI(const char *uri, int len, bool enabled=true) +static void SetURI (const char *uri, int len, bool enabled=true) { wchar_t tmp[128]; - if (len==-1) len=pj_ansi_strlen(uri); - pj_ansi_to_unicode(uri, len, tmp, PJ_ARRAY_SIZE(tmp)); - SetDlgItemText(hMainWnd, ID_URI, tmp); - EnableWindow(hwndURI, enabled?TRUE:FALSE); + + if (len==-1) len=pj_ansi_strlen (uri); + + pj_ansi_to_unicode (uri, len, tmp, PJ_ARRAY_SIZE (tmp)); + + SetDlgItemText (hMainWnd, ID_URI, tmp); + + EnableWindow (hwndURI, enabled?TRUE:FALSE); } -static void SetCallStatus(const char *state, int len) +static void SetCallStatus (const char *state, int len) { wchar_t tmp[128]; - if (len==-1) len=pj_ansi_strlen(state); - pj_ansi_to_unicode(state, len, tmp, PJ_ARRAY_SIZE(tmp)); - SetDlgItemText(hMainWnd, ID_CALL_STATUS, tmp); + + if (len==-1) len=pj_ansi_strlen (state); + + pj_ansi_to_unicode (state, len, tmp, PJ_ARRAY_SIZE (tmp)); + + SetDlgItemText (hMainWnd, ID_CALL_STATUS, tmp); } -static void SetAction(int action, bool enable=true) +static void SetAction (int action, bool enable=true) { HMENU hMenu; - hMenu = CommandBar_GetMenu(hwndCB, 0); + hMenu = CommandBar_GetMenu (hwndCB, 0); - RemoveMenu(hMenu, ID_MENU_NONE, MF_BYCOMMAND); - RemoveMenu(hMenu, ID_MENU_CALL, MF_BYCOMMAND); - RemoveMenu(hMenu, ID_MENU_ANSWER, MF_BYCOMMAND); - RemoveMenu(hMenu, ID_MENU_DISCONNECT, MF_BYCOMMAND); + RemoveMenu (hMenu, ID_MENU_NONE, MF_BYCOMMAND); + RemoveMenu (hMenu, ID_MENU_CALL, MF_BYCOMMAND); + RemoveMenu (hMenu, ID_MENU_ANSWER, MF_BYCOMMAND); + RemoveMenu (hMenu, ID_MENU_DISCONNECT, MF_BYCOMMAND); switch (action) { - case ID_MENU_NONE: - InsertMenu(hMenu, ID_EXIT, MF_BYCOMMAND, action, TEXT("None")); - SetWindowText(hwndActionButton, TEXT("-")); - break; - case ID_MENU_CALL: - InsertMenu(hMenu, ID_EXIT, MF_BYCOMMAND, action, TEXT("Call")); - SetWindowText(hwndActionButton, TEXT("&Call")); - break; - case ID_MENU_ANSWER: - InsertMenu(hMenu, ID_EXIT, MF_BYCOMMAND, action, TEXT("Answer")); - SetWindowText(hwndActionButton, TEXT("&Answer")); - break; - case ID_MENU_DISCONNECT: - InsertMenu(hMenu, ID_EXIT, MF_BYCOMMAND, action, TEXT("Hangup")); - SetWindowText(hwndActionButton, TEXT("&Hangup")); - break; + + case ID_MENU_NONE: + InsertMenu (hMenu, ID_EXIT, MF_BYCOMMAND, action, TEXT ("None")); + SetWindowText (hwndActionButton, TEXT ("-")); + break; + + case ID_MENU_CALL: + InsertMenu (hMenu, ID_EXIT, MF_BYCOMMAND, action, TEXT ("Call")); + SetWindowText (hwndActionButton, TEXT ("&Call")); + break; + + case ID_MENU_ANSWER: + InsertMenu (hMenu, ID_EXIT, MF_BYCOMMAND, action, TEXT ("Answer")); + SetWindowText (hwndActionButton, TEXT ("&Answer")); + break; + + case ID_MENU_DISCONNECT: + InsertMenu (hMenu, ID_EXIT, MF_BYCOMMAND, action, TEXT ("Hangup")); + SetWindowText (hwndActionButton, TEXT ("&Hangup")); + break; } - EnableMenuItem(hMenu, action, MF_BYCOMMAND | (enable?MF_ENABLED:MF_GRAYED)); - DrawMenuBar(hMainWnd); + EnableMenuItem (hMenu, action, MF_BYCOMMAND | (enable?MF_ENABLED:MF_GRAYED)); + + DrawMenuBar (hMainWnd); g_current_action = action; } @@ -191,35 +205,35 @@ static void SetAction(int action, bool enable=true) /* * Handler when invite state has changed. */ -static void on_call_state(pjsua_call_id call_id, pjsip_event *e) +static void on_call_state (pjsua_call_id call_id, pjsip_event *e) { pjsua_call_info call_info; - PJ_UNUSED_ARG(e); + PJ_UNUSED_ARG (e); - pjsua_call_get_info(call_id, &call_info); + pjsua_call_get_info (call_id, &call_info); if (call_info.state == PJSIP_INV_STATE_DISCONNECTED) { - g_current_call = PJSUA_INVALID_ID; - SetURI(SIP_DST_URI, -1); - SetAction(ID_MENU_CALL); - //SetCallStatus(call_info.state_text.ptr, call_info.state_text.slen); - SetCallStatus(call_info.last_status_text.ptr, call_info.last_status_text.slen); + g_current_call = PJSUA_INVALID_ID; + SetURI (SIP_DST_URI, -1); + SetAction (ID_MENU_CALL); + //SetCallStatus(call_info.state_text.ptr, call_info.state_text.slen); + SetCallStatus (call_info.last_status_text.ptr, call_info.last_status_text.slen); } else { - //if (g_current_call == PJSUA_INVALID_ID) - // g_current_call = call_id; + //if (g_current_call == PJSUA_INVALID_ID) + // g_current_call = call_id; - if (call_info.remote_contact.slen) - SetURI(call_info.remote_contact.ptr, call_info.remote_contact.slen, false); - else - SetURI(call_info.remote_info.ptr, call_info.remote_info.slen, false); + if (call_info.remote_contact.slen) + SetURI (call_info.remote_contact.ptr, call_info.remote_contact.slen, false); + else + SetURI (call_info.remote_info.ptr, call_info.remote_info.slen, false); - if (call_info.state == PJSIP_INV_STATE_CONFIRMED) - SetAction(ID_MENU_DISCONNECT); + if (call_info.state == PJSIP_INV_STATE_CONFIRMED) + SetAction (ID_MENU_DISCONNECT); - SetCallStatus(call_info.state_text.ptr, call_info.state_text.slen); + SetCallStatus (call_info.state_text.ptr, call_info.state_text.slen); } } @@ -229,15 +243,15 @@ static void on_call_state(pjsua_call_id call_id, pjsip_event *e) * The action may connect the call to sound device, to file, or * to loop the call. */ -static void on_call_media_state(pjsua_call_id call_id) +static void on_call_media_state (pjsua_call_id call_id) { pjsua_call_info call_info; - pjsua_call_get_info(call_id, &call_info); + pjsua_call_get_info (call_id, &call_info); if (call_info.media_status == PJSUA_CALL_MEDIA_ACTIVE) { - pjsua_conf_connect(call_info.conf_slot, 0); - pjsua_conf_connect(0, call_info.conf_slot); + pjsua_conf_connect (call_info.conf_slot, 0); + pjsua_conf_connect (0, call_info.conf_slot); } } @@ -245,37 +259,37 @@ static void on_call_media_state(pjsua_call_id call_id) /** * Handler when there is incoming call. */ -static void on_incoming_call(pjsua_acc_id acc_id, pjsua_call_id call_id, - pjsip_rx_data *rdata) +static void on_incoming_call (pjsua_acc_id acc_id, pjsua_call_id call_id, + pjsip_rx_data *rdata) { pjsua_call_info call_info; - PJ_UNUSED_ARG(acc_id); - PJ_UNUSED_ARG(rdata); + PJ_UNUSED_ARG (acc_id); + PJ_UNUSED_ARG (rdata); if (g_current_call != PJSUA_INVALID_ID) { - pj_str_t reason; - reason = pj_str("Another call is in progress"); - pjsua_call_answer(call_id, PJSIP_SC_BUSY_HERE, &reason, NULL); - return; + pj_str_t reason; + reason = pj_str ("Another call is in progress"); + pjsua_call_answer (call_id, PJSIP_SC_BUSY_HERE, &reason, NULL); + return; } g_current_call = call_id; - pjsua_call_get_info(call_id, &call_info); + pjsua_call_get_info (call_id, &call_info); - SetAction(ID_MENU_ANSWER); - SetURI(call_info.remote_info.ptr, call_info.remote_info.slen, false); - pjsua_call_answer(call_id, 200, NULL, NULL); + SetAction (ID_MENU_ANSWER); + SetURI (call_info.remote_info.ptr, call_info.remote_info.slen, false); + pjsua_call_answer (call_id, 200, NULL, NULL); } /* * Handler registration status has changed. */ -static void on_reg_state(pjsua_acc_id acc_id) +static void on_reg_state (pjsua_acc_id acc_id) { - PJ_UNUSED_ARG(acc_id); + PJ_UNUSED_ARG (acc_id); // Log already written. } @@ -284,65 +298,65 @@ static void on_reg_state(pjsua_acc_id acc_id) /* * Handler on buddy state changed. */ -static void on_buddy_state(pjsua_buddy_id buddy_id) +static void on_buddy_state (pjsua_buddy_id buddy_id) { /* Currently this is not processed */ - PJ_UNUSED_ARG(buddy_id); + PJ_UNUSED_ARG (buddy_id); } /** * Incoming IM message (i.e. MESSAGE request)! */ -static void on_pager(pjsua_call_id call_id, const pj_str_t *from, - const pj_str_t *to, const pj_str_t *contact, - const pj_str_t *mime_type, const pj_str_t *text) +static void on_pager (pjsua_call_id call_id, const pj_str_t *from, + const pj_str_t *to, const pj_str_t *contact, + const pj_str_t *mime_type, const pj_str_t *text) { /* Currently this is not processed */ - PJ_UNUSED_ARG(call_id); - PJ_UNUSED_ARG(from); - PJ_UNUSED_ARG(to); - PJ_UNUSED_ARG(contact); - PJ_UNUSED_ARG(mime_type); - PJ_UNUSED_ARG(text); + PJ_UNUSED_ARG (call_id); + PJ_UNUSED_ARG (from); + PJ_UNUSED_ARG (to); + PJ_UNUSED_ARG (contact); + PJ_UNUSED_ARG (mime_type); + PJ_UNUSED_ARG (text); } /** * Received typing indication */ -static void on_typing(pjsua_call_id call_id, const pj_str_t *from, - const pj_str_t *to, const pj_str_t *contact, - pj_bool_t is_typing) +static void on_typing (pjsua_call_id call_id, const pj_str_t *from, + const pj_str_t *to, const pj_str_t *contact, + pj_bool_t is_typing) { /* Currently this is not processed */ - PJ_UNUSED_ARG(call_id); - PJ_UNUSED_ARG(from); - PJ_UNUSED_ARG(to); - PJ_UNUSED_ARG(contact); - PJ_UNUSED_ARG(is_typing); + PJ_UNUSED_ARG (call_id); + PJ_UNUSED_ARG (from); + PJ_UNUSED_ARG (to); + PJ_UNUSED_ARG (contact); + PJ_UNUSED_ARG (is_typing); } -/** - * Callback upon NAT detection completion +/** + * Callback upon NAT detection completion */ -static void nat_detect_cb(const pj_stun_nat_detect_result *res) +static void nat_detect_cb (const pj_stun_nat_detect_result *res) { if (res->status != PJ_SUCCESS) { - char msg[250]; - pj_ansi_snprintf(msg, sizeof(msg), "NAT detection failed: %s", - res->status_text); - SetCallStatus(msg, pj_ansi_strlen(msg)); + char msg[250]; + pj_ansi_snprintf (msg, sizeof (msg), "NAT detection failed: %s", + res->status_text); + SetCallStatus (msg, pj_ansi_strlen (msg)); } else { - char msg[250]; - pj_ansi_snprintf(msg, sizeof(msg), "NAT type is %s", - res->nat_type_name); - SetCallStatus(msg, pj_ansi_strlen(msg)); + char msg[250]; + pj_ansi_snprintf (msg, sizeof (msg), "NAT type is %s", + res->nat_type_name); + SetCallStatus (msg, pj_ansi_strlen (msg)); } } -static BOOL OnInitStack(void) +static BOOL OnInitStack (void) { pjsua_config cfg; pjsua_logging_config log_cfg; @@ -356,141 +370,172 @@ static BOOL OnInitStack(void) /* Create pjsua */ status = pjsua_create(); + if (status != PJ_SUCCESS) { - OnError(TEXT("Error creating pjsua"), status); - return FALSE; + OnError (TEXT ("Error creating pjsua"), status); + return FALSE; } /* Create global pool for application */ - g_pool = pjsua_pool_create("pjsua", 4000, 4000); + g_pool = pjsua_pool_create ("pjsua", 4000, 4000); /* Init configs */ - pjsua_config_default(&cfg); - pjsua_media_config_default(&media_cfg); - pjsua_transport_config_default(&udp_cfg); + pjsua_config_default (&cfg); + + pjsua_media_config_default (&media_cfg); + + pjsua_transport_config_default (&udp_cfg); + udp_cfg.port = SIP_PORT; - pjsua_transport_config_default(&rtp_cfg); + pjsua_transport_config_default (&rtp_cfg); + rtp_cfg.port = 40000; - pjsua_logging_config_default(&log_cfg); + pjsua_logging_config_default (&log_cfg); + log_cfg.level = 5; - log_cfg.log_filename = pj_str("\\pjsua.txt"); + + log_cfg.log_filename = pj_str ("\\pjsua.txt"); + log_cfg.msg_logging = 1; + log_cfg.decor = pj_log_get_decor() | PJ_LOG_HAS_CR; /* Setup media */ media_cfg.clock_rate = 8000; + media_cfg.ec_options = PJMEDIA_ECHO_SIMPLE; + media_cfg.ec_tail_len = 256; + // use default quality setting //media_cfg.quality = 1; media_cfg.ptime = 20; + media_cfg.enable_ice = USE_ICE; /* Initialize application callbacks */ cfg.cb.on_call_state = &on_call_state; + cfg.cb.on_call_media_state = &on_call_media_state; + cfg.cb.on_incoming_call = &on_incoming_call; + cfg.cb.on_reg_state = &on_reg_state; + cfg.cb.on_buddy_state = &on_buddy_state; + cfg.cb.on_pager = &on_pager; + cfg.cb.on_typing = &on_typing; + cfg.cb.on_nat_detect = &nat_detect_cb; if (SIP_PROXY) { - cfg.outbound_proxy_cnt = 1; - cfg.outbound_proxy[0] = pj_str(SIP_PROXY); + cfg.outbound_proxy_cnt = 1; + cfg.outbound_proxy[0] = pj_str (SIP_PROXY); } - + if (NAMESERVER) { - cfg.nameserver_count = 1; - cfg.nameserver[0] = pj_str(NAMESERVER); + cfg.nameserver_count = 1; + cfg.nameserver[0] = pj_str (NAMESERVER); } - + if (NAMESERVER && STUN_DOMAIN) { - cfg.stun_domain = pj_str(STUN_DOMAIN); + cfg.stun_domain = pj_str (STUN_DOMAIN); } else if (STUN_SERVER) { - cfg.stun_host = pj_str(STUN_SERVER); + cfg.stun_host = pj_str (STUN_SERVER); } - - + + /* Initialize pjsua */ - status = pjsua_init(&cfg, &log_cfg, &media_cfg); + status = pjsua_init (&cfg, &log_cfg, &media_cfg); + if (status != PJ_SUCCESS) { - OnError(TEXT("Initialization error"), status); - return FALSE; + OnError (TEXT ("Initialization error"), status); + return FALSE; } /* Set codec priority */ - pjsua_codec_set_priority(pj_cstr(&tmp, "pcmu"), 240); - pjsua_codec_set_priority(pj_cstr(&tmp, "pcma"), 230); - pjsua_codec_set_priority(pj_cstr(&tmp, "speex/8000"), 190); - pjsua_codec_set_priority(pj_cstr(&tmp, "ilbc"), 189); - pjsua_codec_set_priority(pj_cstr(&tmp, "speex/16000"), 180); - pjsua_codec_set_priority(pj_cstr(&tmp, "speex/32000"), 0); - pjsua_codec_set_priority(pj_cstr(&tmp, "gsm"), 100); + pjsua_codec_set_priority (pj_cstr (&tmp, "pcmu"), 240); + + pjsua_codec_set_priority (pj_cstr (&tmp, "pcma"), 230); + + pjsua_codec_set_priority (pj_cstr (&tmp, "speex/8000"), 190); + + pjsua_codec_set_priority (pj_cstr (&tmp, "ilbc"), 189); + + pjsua_codec_set_priority (pj_cstr (&tmp, "speex/16000"), 180); + + pjsua_codec_set_priority (pj_cstr (&tmp, "speex/32000"), 0); + + pjsua_codec_set_priority (pj_cstr (&tmp, "gsm"), 100); /* Add UDP transport and the corresponding PJSUA account */ - status = pjsua_transport_create(PJSIP_TRANSPORT_UDP, - &udp_cfg, &transport_id); + status = pjsua_transport_create (PJSIP_TRANSPORT_UDP, + &udp_cfg, &transport_id); + if (status != PJ_SUCCESS) { - OnError(TEXT("Error starting SIP transport"), status); - return FALSE; + OnError (TEXT ("Error starting SIP transport"), status); + return FALSE; } - pjsua_transport_get_info(transport_id, &transport_info); + pjsua_transport_get_info (transport_id, &transport_info); - g_local_uri.ptr = (char*)pj_pool_alloc(g_pool, 128); - g_local_uri.slen = pj_ansi_sprintf(g_local_uri.ptr, - "<sip:%.*s:%d>", - (int)transport_info.local_name.host.slen, - transport_info.local_name.host.ptr, - transport_info.local_name.port); + g_local_uri.ptr = (char*) pj_pool_alloc (g_pool, 128); + g_local_uri.slen = pj_ansi_sprintf (g_local_uri.ptr, + "<sip:%.*s:%d>", + (int) transport_info.local_name.host.slen, + transport_info.local_name.host.ptr, + transport_info.local_name.port); /* Add local account */ - pjsua_acc_add_local(transport_id, PJ_TRUE, &g_current_acc); - pjsua_acc_set_online_status(g_current_acc, PJ_TRUE); + pjsua_acc_add_local (transport_id, PJ_TRUE, &g_current_acc); + pjsua_acc_set_online_status (g_current_acc, PJ_TRUE); /* Add account */ + if (HAS_SIP_ACCOUNT) { - pjsua_acc_config cfg; - - pjsua_acc_config_default(&cfg); - cfg.id = pj_str("sip:" SIP_USER "@" SIP_DOMAIN); - cfg.reg_uri = pj_str("sip:" SIP_DOMAIN); - cfg.cred_count = 1; - cfg.cred_info[0].realm = pj_str(SIP_REALM); - cfg.cred_info[0].scheme = pj_str("digest"); - cfg.cred_info[0].username = pj_str(SIP_USER); - cfg.cred_info[0].data_type = PJSIP_CRED_DATA_PLAIN_PASSWD; - cfg.cred_info[0].data = pj_str(SIP_PASSWD); - - status = pjsua_acc_add(&cfg, PJ_TRUE, &g_current_acc); - if (status != PJ_SUCCESS) { - pjsua_destroy(); - return PJ_FALSE; - } + pjsua_acc_config cfg; + + pjsua_acc_config_default (&cfg); + cfg.id = pj_str ("sip:" SIP_USER "@" SIP_DOMAIN); + cfg.reg_uri = pj_str ("sip:" SIP_DOMAIN); + cfg.cred_count = 1; + cfg.cred_info[0].realm = pj_str (SIP_REALM); + cfg.cred_info[0].scheme = pj_str ("digest"); + cfg.cred_info[0].username = pj_str (SIP_USER); + cfg.cred_info[0].data_type = PJSIP_CRED_DATA_PLAIN_PASSWD; + cfg.cred_info[0].data = pj_str (SIP_PASSWD); + + status = pjsua_acc_add (&cfg, PJ_TRUE, &g_current_acc); + + if (status != PJ_SUCCESS) { + pjsua_destroy(); + return PJ_FALSE; + } } /* Add buddy */ if (SIP_DST_URI) { - pjsua_buddy_config bcfg; - - pjsua_buddy_config_default(&bcfg); - bcfg.uri = pj_str(SIP_DST_URI); - bcfg.subscribe = PJ_FALSE; - - pjsua_buddy_add(&bcfg, NULL); + pjsua_buddy_config bcfg; + + pjsua_buddy_config_default (&bcfg); + bcfg.uri = pj_str (SIP_DST_URI); + bcfg.subscribe = PJ_FALSE; + + pjsua_buddy_add (&bcfg, NULL); } /* Start pjsua */ status = pjsua_start(); + if (status != PJ_SUCCESS) { - OnError(TEXT("Error starting pjsua"), status); - return FALSE; + OnError (TEXT ("Error starting pjsua"), status); + return FALSE; } return TRUE; @@ -499,40 +544,39 @@ static BOOL OnInitStack(void) ////////////////////////////////////////////////////////////////////////////// -int WINAPI WinMain(HINSTANCE hInstance, - HINSTANCE hPrevInstance, - LPTSTR lpCmdLine, - int nCmdShow) +int WINAPI WinMain (HINSTANCE hInstance, + HINSTANCE hPrevInstance, + LPTSTR lpCmdLine, + int nCmdShow) { MSG msg; HACCEL hAccelTable; - PJ_UNUSED_ARG(lpCmdLine); - PJ_UNUSED_ARG(hPrevInstance); + PJ_UNUSED_ARG (lpCmdLine); + PJ_UNUSED_ARG (hPrevInstance); // Perform application initialization: - if (!InitInstance (hInstance, nCmdShow)) - { - return FALSE; + + if (!InitInstance (hInstance, nCmdShow)) { + return FALSE; } - - hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_PJSUA_WINCE); - - + + hAccelTable = LoadAccelerators (hInstance, (LPCTSTR) IDC_PJSUA_WINCE); + + // Main message loop: - while (GetMessage(&msg, NULL, 0, 0)) - { - if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) - { - TranslateMessage(&msg); - DispatchMessage(&msg); - } + + while (GetMessage (&msg, NULL, 0, 0)) { + if (!TranslateAccelerator (msg.hwnd, hAccelTable, &msg)) { + TranslateMessage (&msg); + DispatchMessage (&msg); + } } - + return msg.wParam; } -static ATOM MyRegisterClass(HINSTANCE hInstance, LPTSTR szWindowClass) +static ATOM MyRegisterClass (HINSTANCE hInstance, LPTSTR szWindowClass) { WNDCLASS wc; @@ -541,17 +585,17 @@ static ATOM MyRegisterClass(HINSTANCE hInstance, LPTSTR szWindowClass) wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; - wc.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_PJSUA_WINCE)); + wc.hIcon = LoadIcon (hInstance, MAKEINTRESOURCE (IDI_PJSUA_WINCE)); wc.hCursor = 0; - wc.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH); + wc.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH); wc.lpszMenuName = 0; wc.lpszClassName = szWindowClass; - return RegisterClass(&wc); + return RegisterClass (&wc); } -BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) +BOOL InitInstance (HINSTANCE hInstance, int nCmdShow) { HWND hWnd; TCHAR szTitle[MAX_LOADSTRING]; @@ -560,221 +604,244 @@ BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) hInst = hInstance; /* Init stack */ + if (OnInitStack() == FALSE) - return FALSE; + return FALSE; + + LoadString (hInstance, IDC_PJSUA_WINCE, szWindowClass, MAX_LOADSTRING); - LoadString(hInstance, IDC_PJSUA_WINCE, szWindowClass, MAX_LOADSTRING); - MyRegisterClass(hInstance, szWindowClass); + MyRegisterClass (hInstance, szWindowClass); - LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); - hWnd = CreateWindow(szWindowClass, szTitle, WS_VISIBLE, - CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, 200, - NULL, NULL, hInstance, NULL); + LoadString (hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); - if (!hWnd) - { - return FALSE; + hWnd = CreateWindow (szWindowClass, szTitle, WS_VISIBLE, + CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, 200, + NULL, NULL, hInstance, NULL); + + if (!hWnd) { + return FALSE; } hMainWnd = hWnd; - ShowWindow(hWnd, nCmdShow); - UpdateWindow(hWnd); + + ShowWindow (hWnd, nCmdShow); + UpdateWindow (hWnd); + if (hwndCB) - CommandBar_Show(hwndCB, TRUE); + CommandBar_Show (hwndCB, TRUE); - SetTimer(hMainWnd, ID_POLL_TIMER, 50, NULL); + SetTimer (hMainWnd, ID_POLL_TIMER, 50, NULL); pjsua_detect_nat_type(); + return TRUE; } -static void OnCreate(HWND hWnd) +static void OnCreate (HWND hWnd) { - enum - { - X = 10, - Y = 40, - W = 220, - H = 30, + enum { + X = 10, + Y = 40, + W = 220, + H = 30, }; DWORD dwStyle; hMainWnd = hWnd; - hwndCB = CommandBar_Create(hInst, hWnd, 1); - CommandBar_InsertMenubar(hwndCB, hInst, IDM_MENU, 0); - CommandBar_AddAdornments(hwndCB, 0, 0); + hwndCB = CommandBar_Create (hInst, hWnd, 1); + CommandBar_InsertMenubar (hwndCB, hInst, IDM_MENU, 0); + CommandBar_AddAdornments (hwndCB, 0, 0); // Create global status text - dwStyle = WS_CHILD | WS_VISIBLE | WS_DISABLED | ES_LEFT; - hwndGlobalStatus = CreateWindow( - TEXT("EDIT"), // Class name - NULL, // Window text - dwStyle, // Window style - X, // x-coordinate of the upper-left corner - Y+0, // y-coordinate of the upper-left corner - W, // Width of the window for the edit - // control - H-5, // Height of the window for the edit - // control - hWnd, // Window handle to the parent window - (HMENU) ID_GLOBAL_STATUS, // Control identifier - hInst, // Instance handle - NULL); // Specify NULL for this parameter when - // you create a control - SetLocalURI(g_local_uri.ptr, g_local_uri.slen, false); + dwStyle = WS_CHILD | WS_VISIBLE | WS_DISABLED | ES_LEFT; + hwndGlobalStatus = CreateWindow ( + TEXT ("EDIT"), // Class name + NULL, // Window text + dwStyle, // Window style + X, // x-coordinate of the upper-left corner + Y+0, // y-coordinate of the upper-left corner + W, // Width of the window for the edit + // control + H-5, // Height of the window for the edit + // control + hWnd, // Window handle to the parent window + (HMENU) ID_GLOBAL_STATUS, // Control identifier + hInst, // Instance handle + NULL); // Specify NULL for this parameter when + // you create a control + SetLocalURI (g_local_uri.ptr, g_local_uri.slen, false); // Create URI edit - dwStyle = WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_BORDER; + dwStyle = WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_BORDER; hwndURI = CreateWindow ( - TEXT("EDIT"), // Class name - NULL, // Window text - dwStyle, // Window style - X, // x-coordinate of the upper-left corner - Y+H, // y-coordinate of the upper-left corner - W, // Width of the window for the edit - // control - H-5, // Height of the window for the edit - // control - hWnd, // Window handle to the parent window - (HMENU) ID_URI, // Control identifier - hInst, // Instance handle - NULL); // Specify NULL for this parameter when - // you create a control + TEXT ("EDIT"), // Class name + NULL, // Window text + dwStyle, // Window style + X, // x-coordinate of the upper-left corner + Y+H, // y-coordinate of the upper-left corner + W, // Width of the window for the edit + // control + H-5, // Height of the window for the edit + // control + hWnd, // Window handle to the parent window + (HMENU) ID_URI, // Control identifier + hInst, // Instance handle + NULL); // Specify NULL for this parameter when + // you create a control // Create action Button - hwndActionButton = CreateWindow( L"button", L"Action", - WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, - X, Y+2*H, - 60, H-5, hWnd, - (HMENU) ID_BTN_ACTION, - hInst, NULL ); + hwndActionButton = CreateWindow (L"button", L"Action", + WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, + X, Y+2*H, + 60, H-5, hWnd, + (HMENU) ID_BTN_ACTION, + hInst, NULL); // Create exit button - hwndExitButton = CreateWindow( L"button", L"E&xit", - WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, - X+70, Y+2*H, - 60, H-5, hWnd, - (HMENU) ID_EXIT, - hInst, NULL ); + hwndExitButton = CreateWindow (L"button", L"E&xit", + WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, + X+70, Y+2*H, + 60, H-5, hWnd, + (HMENU) ID_EXIT, + hInst, NULL); // Create call status edit - dwStyle = WS_CHILD | WS_VISIBLE | WS_DISABLED; + dwStyle = WS_CHILD | WS_VISIBLE | WS_DISABLED; hwndCallStatus = CreateWindow ( - TEXT("EDIT"), // Class name - NULL, // Window text - dwStyle, // Window style - X, // x-coordinate of the upper-left corner - Y+3*H, // y-coordinate of the upper-left corner - W, // Width of the window for the edit - // control - H-5, // Height of the window for the edit - // control - hWnd, // Window handle to the parent window - (HMENU) ID_CALL_STATUS, // Control identifier - hInst, // Instance handle - NULL); // Specify NULL for this parameter when - // you create a control - SetCallStatus("Ready", 5); - SetAction(ID_MENU_CALL); - SetURI(SIP_DST_URI, -1); - SetFocus(hWnd); + TEXT ("EDIT"), // Class name + NULL, // Window text + dwStyle, // Window style + X, // x-coordinate of the upper-left corner + Y+3*H, // y-coordinate of the upper-left corner + W, // Width of the window for the edit + // control + H-5, // Height of the window for the edit + // control + hWnd, // Window handle to the parent window + (HMENU) ID_CALL_STATUS, // Control identifier + hInst, // Instance handle + NULL); // Specify NULL for this parameter when + // you create a control + SetCallStatus ("Ready", 5); + SetAction (ID_MENU_CALL); + SetURI (SIP_DST_URI, -1); + SetFocus (hWnd); } -static void OnDestroy(void) +static void OnDestroy (void) { pjsua_destroy(); } -static LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) +static LRESULT CALLBACK WndProc (HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; - + switch (message) { - case WM_KEYUP: - if (wParam==114) { - wParam = ID_MENU_CALL; - } else if (wParam==115) { - if (g_current_call == PJSUA_INVALID_ID) - wParam = ID_EXIT; - else - wParam = ID_MENU_DISCONNECT; - } else - break; - - case WM_COMMAND: - wmId = LOWORD(wParam); - wmEvent = HIWORD(wParam); - if (wmId == ID_BTN_ACTION) - wmId = g_current_action; - switch (wmId) - { - case ID_MENU_CALL: - if (g_current_call != PJSUA_INVALID_ID) { - MessageBox(NULL, TEXT("Can not make call"), - TEXT("You already have one call active"), MB_OK); - } - pj_str_t dst_uri; - wchar_t text[256]; - char tmp[256]; - pj_status_t status; - - GetWindowText(hwndURI, text, PJ_ARRAY_SIZE(text)); - pj_unicode_to_ansi(text, pj_unicode_strlen(text), - tmp, sizeof(tmp)); - dst_uri.ptr = tmp; - dst_uri.slen = pj_ansi_strlen(tmp); - status = pjsua_call_make_call(g_current_acc, - &dst_uri, 0, NULL, - NULL, &g_current_call); - if (status != PJ_SUCCESS) - OnError(TEXT("Unable to make call"), status); - break; - case ID_MENU_ANSWER: - if (g_current_call == PJSUA_INVALID_ID) - MessageBox(NULL, TEXT("Can not answer"), - TEXT("There is no call!"), MB_OK); - else - pjsua_call_answer(g_current_call, 200, NULL, NULL); - break; - case ID_MENU_DISCONNECT: - if (g_current_call == PJSUA_INVALID_ID) - MessageBox(NULL, TEXT("Can not disconnect"), - TEXT("There is no call!"), MB_OK); - else - pjsua_call_hangup(g_current_call, PJSIP_SC_DECLINE, NULL, NULL); - break; - case ID_EXIT: - DestroyWindow(hWnd); - break; - default: - return DefWindowProc(hWnd, message, wParam, lParam); - } - break; - - case WM_CREATE: - OnCreate(hWnd); - break; - - case WM_DESTROY: - OnDestroy(); - CommandBar_Destroy(hwndCB); - PostQuitMessage(0); - break; - - case WM_TIMER: - pjsua_handle_events(1); - break; - - default: - return DefWindowProc(hWnd, message, wParam, lParam); + + case WM_KEYUP: + + if (wParam==114) { + wParam = ID_MENU_CALL; + } else if (wParam==115) { + if (g_current_call == PJSUA_INVALID_ID) + wParam = ID_EXIT; + else + wParam = ID_MENU_DISCONNECT; + } else + break; + + case WM_COMMAND: + wmId = LOWORD (wParam); + + wmEvent = HIWORD (wParam); + + if (wmId == ID_BTN_ACTION) + wmId = g_current_action; + + switch (wmId) { + + case ID_MENU_CALL: + + if (g_current_call != PJSUA_INVALID_ID) { + MessageBox (NULL, TEXT ("Can not make call"), + TEXT ("You already have one call active"), MB_OK); + } + + pj_str_t dst_uri; + + wchar_t text[256]; + char tmp[256]; + pj_status_t status; + + GetWindowText (hwndURI, text, PJ_ARRAY_SIZE (text)); + pj_unicode_to_ansi (text, pj_unicode_strlen (text), + tmp, sizeof (tmp)); + dst_uri.ptr = tmp; + dst_uri.slen = pj_ansi_strlen (tmp); + status = pjsua_call_make_call (g_current_acc, + &dst_uri, 0, NULL, + NULL, &g_current_call); + + if (status != PJ_SUCCESS) + OnError (TEXT ("Unable to make call"), status); + + break; + + case ID_MENU_ANSWER: + if (g_current_call == PJSUA_INVALID_ID) + MessageBox (NULL, TEXT ("Can not answer"), + TEXT ("There is no call!"), MB_OK); + else + pjsua_call_answer (g_current_call, 200, NULL, NULL); + + break; + + case ID_MENU_DISCONNECT: + if (g_current_call == PJSUA_INVALID_ID) + MessageBox (NULL, TEXT ("Can not disconnect"), + TEXT ("There is no call!"), MB_OK); + else + pjsua_call_hangup (g_current_call, PJSIP_SC_DECLINE, NULL, NULL); + + break; + + case ID_EXIT: + DestroyWindow (hWnd); + + break; + + default: + return DefWindowProc (hWnd, message, wParam, lParam); + } + + break; + + case WM_CREATE: + OnCreate (hWnd); + break; + + case WM_DESTROY: + OnDestroy(); + CommandBar_Destroy (hwndCB); + PostQuitMessage (0); + break; + + case WM_TIMER: + pjsua_handle_events (1); + break; + + default: + return DefWindowProc (hWnd, message, wParam, lParam); } - return 0; + + return 0; } diff --git a/sflphone-common/libs/pjproject/pjsip-apps/src/pocketpj/PocketPJ.cpp b/sflphone-common/libs/pjproject/pjsip-apps/src/pocketpj/PocketPJ.cpp index 2d42d96e2ea3f8e259bbfb5dc4ab2966ea01d874..cc75d884ba8ed66ab5e30a943b74a3ec7d4f896e 100644 --- a/sflphone-common/libs/pjproject/pjsip-apps/src/pocketpj/PocketPJ.cpp +++ b/sflphone-common/libs/pjproject/pjsip-apps/src/pocketpj/PocketPJ.cpp @@ -14,21 +14,21 @@ static char THIS_FILE[] = __FILE__; ///////////////////////////////////////////////////////////////////////////// // CPocketPJApp -BEGIN_MESSAGE_MAP(CPocketPJApp, CWinApp) - //{{AFX_MSG_MAP(CPocketPJApp) - // NOTE - the ClassWizard will add and remove mapping macros here. - // DO NOT EDIT what you see in these blocks of generated code! - //}}AFX_MSG_MAP +BEGIN_MESSAGE_MAP (CPocketPJApp, CWinApp) + //{{AFX_MSG_MAP(CPocketPJApp) + // NOTE - the ClassWizard will add and remove mapping macros here. + // DO NOT EDIT what you see in these blocks of generated code! + //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CPocketPJApp construction CPocketPJApp::CPocketPJApp() - : CWinApp() + : CWinApp() { - // TODO: add construction code here, - // Place all significant initialization in InitInstance + // TODO: add construction code here, + // Place all significant initialization in InitInstance } ///////////////////////////////////////////////////////////////////////////// @@ -41,26 +41,24 @@ CPocketPJApp theApp; BOOL CPocketPJApp::InitInstance() { - // Standard initialization - // If you are not using these features and wish to reduce the size - // of your final executable, you should remove from the following - // the specific initialization routines you do not need. + // Standard initialization + // If you are not using these features and wish to reduce the size + // of your final executable, you should remove from the following + // the specific initialization routines you do not need. - CPocketPJDlg dlg; - m_pMainWnd = &dlg; - int nResponse = dlg.DoModal(); - if (nResponse == IDOK) - { - // TODO: Place code here to handle when the dialog is - // dismissed with OK - } - else if (nResponse == IDCANCEL) - { - // TODO: Place code here to handle when the dialog is - // dismissed with Cancel - } + CPocketPJDlg dlg; + m_pMainWnd = &dlg; + int nResponse = dlg.DoModal(); - // Since the dialog has been closed, return FALSE so that we exit the - // application, rather than start the application's message pump. - return FALSE; + if (nResponse == IDOK) { + // TODO: Place code here to handle when the dialog is + // dismissed with OK + } else if (nResponse == IDCANCEL) { + // TODO: Place code here to handle when the dialog is + // dismissed with Cancel + } + + // Since the dialog has been closed, return FALSE so that we exit the + // application, rather than start the application's message pump. + return FALSE; } diff --git a/sflphone-common/libs/pjproject/pjsip-apps/src/pocketpj/PocketPJDlg.cpp b/sflphone-common/libs/pjproject/pjsip-apps/src/pocketpj/PocketPJDlg.cpp index 2a5eee51f5df9fc16ac283ad0c602417502b278e..ecec2641ab1e47d227c98d472cb441bc3e739422 100644 --- a/sflphone-common/libs/pjproject/pjsip-apps/src/pocketpj/PocketPJDlg.cpp +++ b/sflphone-common/libs/pjproject/pjsip-apps/src/pocketpj/PocketPJDlg.cpp @@ -18,64 +18,65 @@ static CPocketPJDlg *theDlg; ///////////////////////////////////////////////////////////////////////////// // CPocketPJDlg dialog -CPocketPJDlg::CPocketPJDlg(CWnd* pParent /*=NULL*/) - : CDialog(CPocketPJDlg::IDD, pParent), m_PopUp(NULL) +CPocketPJDlg::CPocketPJDlg (CWnd* pParent /*=NULL*/) + : CDialog (CPocketPJDlg::IDD, pParent), m_PopUp (NULL) { - //{{AFX_DATA_INIT(CPocketPJDlg) - // NOTE: the ClassWizard will add member initialization here - //}}AFX_DATA_INIT - // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 - m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); - - theDlg = this; - - m_PopUp = new CPopUpWnd(this); - m_PopUp->Hide(); - - unsigned i; - m_PopUpCount = 0; - for (i=0; i<POPUP_MAX_TYPE; ++i) { - m_PopUpState[i] = FALSE; - } + //{{AFX_DATA_INIT(CPocketPJDlg) + // NOTE: the ClassWizard will add member initialization here + //}}AFX_DATA_INIT + // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 + m_hIcon = AfxGetApp()->LoadIcon (IDR_MAINFRAME); + + theDlg = this; + + m_PopUp = new CPopUpWnd (this); + m_PopUp->Hide(); + + unsigned i; + m_PopUpCount = 0; + + for (i=0; i<POPUP_MAX_TYPE; ++i) { + m_PopUpState[i] = FALSE; + } } -void CPocketPJDlg::DoDataExchange(CDataExchange* pDX) +void CPocketPJDlg::DoDataExchange (CDataExchange* pDX) { - CDialog::DoDataExchange(pDX); - //{{AFX_DATA_MAP(CPocketPJDlg) - DDX_Control(pDX, IDC_URL, m_Url); - DDX_Control(pDX, IDC_BUDDY_LIST, m_BuddyList); - DDX_Control(pDX, IDC_BTN_ACTION, m_BtnUrlAction); - DDX_Control(pDX, IDC_BTN_ACC, m_BtnAcc); - DDX_Control(pDX, IDC_ACC_ID, m_AccId); - //}}AFX_DATA_MAP + CDialog::DoDataExchange (pDX); + //{{AFX_DATA_MAP(CPocketPJDlg) + DDX_Control (pDX, IDC_URL, m_Url); + DDX_Control (pDX, IDC_BUDDY_LIST, m_BuddyList); + DDX_Control (pDX, IDC_BTN_ACTION, m_BtnUrlAction); + DDX_Control (pDX, IDC_BTN_ACC, m_BtnAcc); + DDX_Control (pDX, IDC_ACC_ID, m_AccId); + //}}AFX_DATA_MAP } -BEGIN_MESSAGE_MAP(CPocketPJDlg, CDialog) - //{{AFX_MSG_MAP(CPocketPJDlg) - ON_BN_CLICKED(IDC_BTN_ACC, OnBtnAcc) - ON_BN_CLICKED(IDC_BTN_ACTION, OnBtnAction) - ON_COMMAND(IDC_ACC_SETTINGS, OnSettings) - ON_COMMAND(IDC_URI_CALL, OnUriCall) - ON_WM_TIMER() - ON_COMMAND(IDC_URI_ADD_BUDDY, OnUriAddBuddy) - ON_COMMAND(IDC_URI_DEL_BUDDY, OnUriDelBuddy) - ON_COMMAND(IDC_ACC_ONLINE, OnAccOnline) - ON_COMMAND(IDC_ACC_INVISIBLE, OnAccInvisible) - ON_NOTIFY(NM_CLICK, IDC_BUDDY_LIST, OnClickBuddyList) - //}}AFX_MSG_MAP +BEGIN_MESSAGE_MAP (CPocketPJDlg, CDialog) + //{{AFX_MSG_MAP(CPocketPJDlg) + ON_BN_CLICKED (IDC_BTN_ACC, OnBtnAcc) + ON_BN_CLICKED (IDC_BTN_ACTION, OnBtnAction) + ON_COMMAND (IDC_ACC_SETTINGS, OnSettings) + ON_COMMAND (IDC_URI_CALL, OnUriCall) + ON_WM_TIMER() + ON_COMMAND (IDC_URI_ADD_BUDDY, OnUriAddBuddy) + ON_COMMAND (IDC_URI_DEL_BUDDY, OnUriDelBuddy) + ON_COMMAND (IDC_ACC_ONLINE, OnAccOnline) + ON_COMMAND (IDC_ACC_INVISIBLE, OnAccInvisible) + ON_NOTIFY (NM_CLICK, IDC_BUDDY_LIST, OnClickBuddyList) + //}}AFX_MSG_MAP END_MESSAGE_MAP() -void CPocketPJDlg::Error(const CString &title, pj_status_t rc) +void CPocketPJDlg::Error (const CString &title, pj_status_t rc) { char errmsg[PJ_ERR_MSG_SIZE]; wchar_t werrmsg[PJ_ERR_MSG_SIZE]; - pj_strerror(rc, errmsg, sizeof(errmsg)); - pj_ansi_to_unicode(errmsg, strlen(errmsg), werrmsg, PJ_ARRAY_SIZE(werrmsg)); + pj_strerror (rc, errmsg, sizeof (errmsg)); + pj_ansi_to_unicode (errmsg, strlen (errmsg), werrmsg, PJ_ARRAY_SIZE (werrmsg)); - AfxMessageBox(title + _T(": ") + werrmsg); + AfxMessageBox (title + _T (": ") + werrmsg); } BOOL CPocketPJDlg::Restart() @@ -84,41 +85,43 @@ BOOL CPocketPJDlg::Restart() pj_status_t status; char ver[80]; - sprintf(ver, "PocketPJ/%s", pj_get_version()); + sprintf (ver, "PocketPJ/%s", pj_get_version()); - ShowWindow(SW_SHOW); - PopUp_Show(POPUP_REGISTRATION, ver, - "Starting up....", "", "", "", 0); + ShowWindow (SW_SHOW); + PopUp_Show (POPUP_REGISTRATION, ver, + "Starting up....", "", "", "", 0); - KillTimer(TIMER_ID); + KillTimer (TIMER_ID); // Destroy first. - PopUp_Modify(POPUP_REGISTRATION, POPUP_EL_TITLE3, "Cleaning up.."); + PopUp_Modify (POPUP_REGISTRATION, POPUP_EL_TITLE3, "Cleaning up.."); pjsua_destroy(); - m_BtnAcc.SetBitmap(::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_OFFLINE)) ); + m_BtnAcc.SetBitmap (::LoadBitmap (AfxGetInstanceHandle(), MAKEINTRESOURCE (IDB_OFFLINE))); UpdateWindow(); // Create - PopUp_Show(POPUP_REGISTRATION, ver, - "Starting up....", "Creating stack..", "", "", 0); + PopUp_Show (POPUP_REGISTRATION, ver, + "Starting up....", "Creating stack..", "", "", 0); status = pjsua_create(); + if (status != PJ_SUCCESS) { - Error(_T("Error in creating library"), status); - PopUp_Hide(POPUP_REGISTRATION); - return FALSE; + Error (_T ("Error in creating library"), status); + PopUp_Hide (POPUP_REGISTRATION); + return FALSE; } pjsua_config cfg; + pjsua_logging_config log_cfg; pjsua_media_config media_cfg; - pjsua_config_default(&cfg); + pjsua_config_default (&cfg); cfg.max_calls = 1; cfg.thread_cnt = 0; - cfg.user_agent = pj_str(ver); + cfg.user_agent = pj_str (ver); cfg.cb.on_call_state = &on_call_state; cfg.cb.on_call_media_state = &on_call_media_state; @@ -130,47 +133,50 @@ BOOL CPocketPJDlg::Restart() /* Configure nameserver */ char nameserver[60]; { - FIXED_INFO fi; - ULONG len = sizeof(fi); - CString err; - - PopUp_Modify(POPUP_REGISTRATION, POPUP_EL_TITLE3, "Retrieving network parameters.."); - if (GetNetworkParams(&fi, &len) != ERROR_SUCCESS) { - err = _T("Info: Error querying network parameters. You must configure DNS server."); - } else if (fi.CurrentDnsServer == NULL) { - err = _T("Info: DNS server not configured. You must configure DNS server."); - } - - if (err.GetLength()) { - if (m_Cfg.m_DNS.GetLength()) { - pj_unicode_to_ansi((LPCTSTR)m_Cfg.m_DNS, m_Cfg.m_DNS.GetLength(), - nameserver, sizeof(nameserver)); - cfg.nameserver_count = 1; - cfg.nameserver[0] = pj_str(nameserver); - } else { - AfxMessageBox(err); - pjsua_destroy(); - PopUp_Hide(POPUP_REGISTRATION); - return FALSE; - } - } else { - strcpy(nameserver, fi.CurrentDnsServer->IpAddress.String); - cfg.nameserver_count = 1; - cfg.nameserver[0] = pj_str(nameserver); - } + FIXED_INFO fi; + ULONG len = sizeof (fi); + CString err; + + PopUp_Modify (POPUP_REGISTRATION, POPUP_EL_TITLE3, "Retrieving network parameters.."); + + if (GetNetworkParams (&fi, &len) != ERROR_SUCCESS) { + err = _T ("Info: Error querying network parameters. You must configure DNS server."); + } else if (fi.CurrentDnsServer == NULL) { + err = _T ("Info: DNS server not configured. You must configure DNS server."); + } + + if (err.GetLength()) { + if (m_Cfg.m_DNS.GetLength()) { + pj_unicode_to_ansi ( (LPCTSTR) m_Cfg.m_DNS, m_Cfg.m_DNS.GetLength(), + nameserver, sizeof (nameserver)); + cfg.nameserver_count = 1; + cfg.nameserver[0] = pj_str (nameserver); + } else { + AfxMessageBox (err); + pjsua_destroy(); + PopUp_Hide (POPUP_REGISTRATION); + return FALSE; + } + } else { + strcpy (nameserver, fi.CurrentDnsServer->IpAddress.String); + cfg.nameserver_count = 1; + cfg.nameserver[0] = pj_str (nameserver); + } } char tmp_stun[80]; + if (m_Cfg.m_UseStun) { - pj_unicode_to_ansi((LPCTSTR)m_Cfg.m_StunSrv, m_Cfg.m_StunSrv.GetLength(), - tmp_stun, sizeof(tmp_stun)); - cfg.stun_host = pj_str(tmp_stun); + pj_unicode_to_ansi ( (LPCTSTR) m_Cfg.m_StunSrv, m_Cfg.m_StunSrv.GetLength(), + tmp_stun, sizeof (tmp_stun)); + cfg.stun_host = pj_str (tmp_stun); } - pjsua_logging_config_default(&log_cfg); - log_cfg.log_filename = pj_str("\\PocketPJ.TXT"); + pjsua_logging_config_default (&log_cfg); + + log_cfg.log_filename = pj_str ("\\PocketPJ.TXT"); - pjsua_media_config_default(&media_cfg); + pjsua_media_config_default (&media_cfg); media_cfg.clock_rate = 8000; media_cfg.audio_frame_ptime = 40; media_cfg.ec_tail_len = 0; @@ -183,205 +189,246 @@ BOOL CPocketPJDlg::Restart() media_cfg.no_vad = !m_Cfg.m_VAD; if (m_Cfg.m_EchoSuppress) { - media_cfg.ec_options = PJMEDIA_ECHO_SIMPLE; - media_cfg.ec_tail_len = m_Cfg.m_EcTail; + media_cfg.ec_options = PJMEDIA_ECHO_SIMPLE; + media_cfg.ec_tail_len = m_Cfg.m_EcTail; } // Init - PopUp_Modify(POPUP_REGISTRATION, POPUP_EL_TITLE3, "Initializing.."); - status = pjsua_init(&cfg, &log_cfg, &media_cfg); + PopUp_Modify (POPUP_REGISTRATION, POPUP_EL_TITLE3, "Initializing.."); + + status = pjsua_init (&cfg, &log_cfg, &media_cfg); + if (status != PJ_SUCCESS) { - Error(_T("Error initializing library"), status); - pjsua_destroy(); - PopUp_Hide(POPUP_REGISTRATION); - return FALSE; + Error (_T ("Error initializing library"), status); + pjsua_destroy(); + PopUp_Hide (POPUP_REGISTRATION); + return FALSE; } // Create one UDP transport - PopUp_Modify(POPUP_REGISTRATION, POPUP_EL_TITLE3, "Adding UDP transport.."); + PopUp_Modify (POPUP_REGISTRATION, POPUP_EL_TITLE3, "Adding UDP transport.."); + pjsua_transport_id transport_id; + pjsua_transport_config udp_cfg; - pjsua_transport_config_default(&udp_cfg); + pjsua_transport_config_default (&udp_cfg); + udp_cfg.port = 0; - status = pjsua_transport_create(PJSIP_TRANSPORT_UDP, - &udp_cfg, &transport_id); + + status = pjsua_transport_create (PJSIP_TRANSPORT_UDP, + &udp_cfg, &transport_id); + if (status != PJ_SUCCESS) { - Error(_T("Error creating UDP transport"), status); - pjsua_destroy(); - PopUp_Hide(POPUP_REGISTRATION); - return FALSE; + Error (_T ("Error creating UDP transport"), status); + pjsua_destroy(); + PopUp_Hide (POPUP_REGISTRATION); + return FALSE; } if (m_Cfg.m_TCP) { - // Create one TCP transport - PopUp_Modify(POPUP_REGISTRATION, POPUP_EL_TITLE3, "Adding TCP transport.."); - pjsua_transport_id transport_id; - pjsua_transport_config tcp_cfg; - - pjsua_transport_config_default(&tcp_cfg); - tcp_cfg.port = 0; - status = pjsua_transport_create(PJSIP_TRANSPORT_TCP, - &tcp_cfg, &transport_id); - if (status != PJ_SUCCESS) { - Error(_T("Error creating TCP transport"), status); - pjsua_destroy(); - PopUp_Hide(POPUP_REGISTRATION); - return FALSE; - } + // Create one TCP transport + PopUp_Modify (POPUP_REGISTRATION, POPUP_EL_TITLE3, "Adding TCP transport.."); + pjsua_transport_id transport_id; + pjsua_transport_config tcp_cfg; + + pjsua_transport_config_default (&tcp_cfg); + tcp_cfg.port = 0; + status = pjsua_transport_create (PJSIP_TRANSPORT_TCP, + &tcp_cfg, &transport_id); + + if (status != PJ_SUCCESS) { + Error (_T ("Error creating TCP transport"), status); + pjsua_destroy(); + PopUp_Hide (POPUP_REGISTRATION); + return FALSE; + } } // Adjust codecs priority pj_str_t tmp; - pjsua_codec_set_priority(pj_cstr(&tmp, "*"), 0); - for (i=0; i<(unsigned)m_Cfg.m_Codecs.GetSize(); ++i) { - CString codec = m_Cfg.m_Codecs.GetAt(i); - char tmp_nam[80]; - - pj_unicode_to_ansi((LPCTSTR)codec, codec.GetLength(), - tmp_nam, sizeof(tmp_nam)); - pjsua_codec_set_priority(pj_cstr(&tmp, tmp_nam), (pj_uint8_t)(200-i)); + + pjsua_codec_set_priority (pj_cstr (&tmp, "*"), 0); + + for (i=0; i< (unsigned) m_Cfg.m_Codecs.GetSize(); ++i) { + CString codec = m_Cfg.m_Codecs.GetAt (i); + char tmp_nam[80]; + + pj_unicode_to_ansi ( (LPCTSTR) codec, codec.GetLength(), + tmp_nam, sizeof (tmp_nam)); + pjsua_codec_set_priority (pj_cstr (&tmp, tmp_nam), (pj_uint8_t) (200-i)); } // Start! - PopUp_Modify(POPUP_REGISTRATION, POPUP_EL_TITLE3, "Starting.."); + PopUp_Modify (POPUP_REGISTRATION, POPUP_EL_TITLE3, "Starting.."); + status = pjsua_start(); + if (status != PJ_SUCCESS) { - Error(_T("Error starting library"), status); - pjsua_destroy(); - PopUp_Hide(POPUP_REGISTRATION); - return FALSE; + Error (_T ("Error starting library"), status); + pjsua_destroy(); + PopUp_Hide (POPUP_REGISTRATION); + return FALSE; } // Add account - PopUp_Modify(POPUP_REGISTRATION, POPUP_EL_TITLE3, "Adding account.."); + PopUp_Modify (POPUP_REGISTRATION, POPUP_EL_TITLE3, "Adding account.."); + char domain[80], username[80], passwd[80]; + char id[80], reg_uri[80]; + pjsua_acc_config acc_cfg; - pj_unicode_to_ansi((LPCTSTR)m_Cfg.m_Domain, m_Cfg.m_Domain.GetLength(), - domain, sizeof(domain)); - pj_unicode_to_ansi((LPCTSTR)m_Cfg.m_User, m_Cfg.m_User.GetLength(), - username, sizeof(username)); - pj_unicode_to_ansi((LPCTSTR)m_Cfg.m_Password, m_Cfg.m_Password.GetLength(), - passwd, sizeof(passwd)); + pj_unicode_to_ansi ( (LPCTSTR) m_Cfg.m_Domain, m_Cfg.m_Domain.GetLength(), + domain, sizeof (domain)); - snprintf(id, sizeof(id), "<sip:%s@%s>", username, domain); - snprintf(reg_uri, sizeof(reg_uri), "sip:%s", domain); + pj_unicode_to_ansi ( (LPCTSTR) m_Cfg.m_User, m_Cfg.m_User.GetLength(), + username, sizeof (username)); + + pj_unicode_to_ansi ( (LPCTSTR) m_Cfg.m_Password, m_Cfg.m_Password.GetLength(), + passwd, sizeof (passwd)); + + snprintf (id, sizeof (id), "<sip:%s@%s>", username, domain); + + snprintf (reg_uri, sizeof (reg_uri), "sip:%s", domain); + + pjsua_acc_config_default (&acc_cfg); + + acc_cfg.id = pj_str (id); + + acc_cfg.reg_uri = pj_str (reg_uri); - pjsua_acc_config_default(&acc_cfg); - acc_cfg.id = pj_str(id); - acc_cfg.reg_uri = pj_str(reg_uri); acc_cfg.cred_count = 1; - acc_cfg.cred_info[0].scheme = pj_str("Digest"); - acc_cfg.cred_info[0].realm = pj_str("*"); - acc_cfg.cred_info[0].username = pj_str(username); + + acc_cfg.cred_info[0].scheme = pj_str ("Digest"); + + acc_cfg.cred_info[0].realm = pj_str ("*"); + + acc_cfg.cred_info[0].username = pj_str (username); + acc_cfg.cred_info[0].data_type = 0; - acc_cfg.cred_info[0].data = pj_str(passwd); + + acc_cfg.cred_info[0].data = pj_str (passwd); #if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0) acc_cfg.use_srtp = (m_Cfg.m_UseSrtp ? PJMEDIA_SRTP_OPTIONAL : PJMEDIA_SRTP_DISABLED); + acc_cfg.srtp_secure_signaling = 0; + #endif acc_cfg.publish_enabled = m_Cfg.m_UsePublish; - + char route[80]; + if (m_Cfg.m_TCP) { - snprintf(route, sizeof(route), "<sip:%s;lr;transport=tcp>", domain); - acc_cfg.proxy[acc_cfg.proxy_cnt++] = pj_str(route); + snprintf (route, sizeof (route), "<sip:%s;lr;transport=tcp>", domain); + acc_cfg.proxy[acc_cfg.proxy_cnt++] = pj_str (route); } else { - snprintf(route, sizeof(route), "<sip:%s;lr>", domain); - acc_cfg.proxy[acc_cfg.proxy_cnt++] = pj_str(route); + snprintf (route, sizeof (route), "<sip:%s;lr>", domain); + acc_cfg.proxy[acc_cfg.proxy_cnt++] = pj_str (route); } - status = pjsua_acc_add(&acc_cfg, PJ_TRUE, &m_PjsuaAccId); + status = pjsua_acc_add (&acc_cfg, PJ_TRUE, &m_PjsuaAccId); + if (status != PJ_SUCCESS) { - Error(_T("Invalid account settings"), status); - pjsua_destroy(); - PopUp_Hide(POPUP_REGISTRATION); - return FALSE; + Error (_T ("Invalid account settings"), status); + pjsua_destroy(); + PopUp_Hide (POPUP_REGISTRATION); + return FALSE; } - CString acc_text = m_Cfg.m_User + _T("@") + m_Cfg.m_Domain; - m_AccId.SetWindowText(acc_text); + CString acc_text = m_Cfg.m_User + _T ("@") + m_Cfg.m_Domain; + + m_AccId.SetWindowText (acc_text); - PopUp_Modify(POPUP_REGISTRATION, POPUP_EL_TITLE1, acc_text); - PopUp_Modify(POPUP_REGISTRATION, POPUP_EL_TITLE2, "Registering.."); - PopUp_Modify(POPUP_REGISTRATION, POPUP_EL_TITLE3, ""); + PopUp_Modify (POPUP_REGISTRATION, POPUP_EL_TITLE1, acc_text); + PopUp_Modify (POPUP_REGISTRATION, POPUP_EL_TITLE2, "Registering.."); + PopUp_Modify (POPUP_REGISTRATION, POPUP_EL_TITLE3, ""); - SetTimer(TIMER_ID, 100, NULL); + SetTimer (TIMER_ID, 100, NULL); return TRUE; } -void CPocketPJDlg::PopUp_Show( PopUpType type, - const CString& title1, - const CString& title2, - const CString& title3, - const CString& btn1, - const CString& btn2, - unsigned userData) +void CPocketPJDlg::PopUp_Show (PopUpType type, + const CString& title1, + const CString& title2, + const CString& title3, + const CString& btn1, + const CString& btn2, + unsigned userData) { - PJ_UNUSED_ARG(userData); + PJ_UNUSED_ARG (userData); if (!m_PopUpState[type]) - ++m_PopUpCount; + ++m_PopUpCount; m_PopUpState[type] = TRUE; m_PopUpContent[type].m_Title1 = title1; + m_PopUpContent[type].m_Title2 = title2; + m_PopUpContent[type].m_Title3 = title3; + m_PopUpContent[type].m_Btn1 = btn1; + m_PopUpContent[type].m_Btn2 = btn2; - m_PopUp->SetContent(m_PopUpContent[type]); + m_PopUp->SetContent (m_PopUpContent[type]); + m_PopUp->Show(); } -void CPocketPJDlg::PopUp_Modify(PopUpType type, - PopUpElement el, - const CString& text) +void CPocketPJDlg::PopUp_Modify (PopUpType type, + PopUpElement el, + const CString& text) { switch (el) { - case POPUP_EL_TITLE1: - m_PopUpContent[type].m_Title1 = text; - break; - case POPUP_EL_TITLE2: - m_PopUpContent[type].m_Title2 = text; - break; - case POPUP_EL_TITLE3: - m_PopUpContent[type].m_Title3 = text; - break; - case POPUP_EL_BUTTON1: - m_PopUpContent[type].m_Btn1 = text; - break; - case POPUP_EL_BUTTON2: - m_PopUpContent[type].m_Btn1 = text; - break; + + case POPUP_EL_TITLE1: + m_PopUpContent[type].m_Title1 = text; + break; + + case POPUP_EL_TITLE2: + m_PopUpContent[type].m_Title2 = text; + break; + + case POPUP_EL_TITLE3: + m_PopUpContent[type].m_Title3 = text; + break; + + case POPUP_EL_BUTTON1: + m_PopUpContent[type].m_Btn1 = text; + break; + + case POPUP_EL_BUTTON2: + m_PopUpContent[type].m_Btn1 = text; + break; } - m_PopUp->SetContent(m_PopUpContent[type]); + m_PopUp->SetContent (m_PopUpContent[type]); } -void CPocketPJDlg::PopUp_Hide(PopUpType type) +void CPocketPJDlg::PopUp_Hide (PopUpType type) { if (m_PopUpState[type]) - --m_PopUpCount; + --m_PopUpCount; m_PopUpState[type] = FALSE; if (m_PopUpCount == 0) { - m_PopUp->Hide(); - UpdateWindow(); + m_PopUp->Hide(); + UpdateWindow(); } else { - for (int i=POPUP_MAX_TYPE-1; i>=0; --i) { - if (m_PopUpState[i]) { - m_PopUp->SetContent(m_PopUpContent[i]); - break; - } - } + for (int i=POPUP_MAX_TYPE-1; i>=0; --i) { + if (m_PopUpState[i]) { + m_PopUp->SetContent (m_PopUpContent[i]); + break; + } + } } } @@ -389,109 +436,120 @@ void CPocketPJDlg::OnCallState() { pjsua_call_info ci; - pjsua_call_get_info(0, &ci); - + pjsua_call_get_info (0, &ci); + switch (ci.state) { - case PJSIP_INV_STATE_NULL: /**< Before INVITE is sent or received */ - break; - case PJSIP_INV_STATE_CALLING: /**< After INVITE is sent */ - PopUp_Show(POPUP_CALL, "Calling..", ci.remote_info.ptr, "", - "", "Hangup", 0); - break; - case PJSIP_INV_STATE_INCOMING: /**< After INVITE is received. */ - PopUp_Show(POPUP_CALL, "Incoming call..", ci.remote_info.ptr, "", - "Answer", "Hangup", 0); - pjsua_call_answer(0, 180, NULL, NULL); - if (m_Cfg.m_AutoAnswer) - OnPopUpButton(1); - break; - case PJSIP_INV_STATE_EARLY: /**< After response with To tag. */ - case PJSIP_INV_STATE_CONNECTING:/**< After 2xx is sent/received. */ - case PJSIP_INV_STATE_CONFIRMED: /**< After ACK is sent/received. */ - { - CString stateText = ci.state_text.ptr; - PopUp_Modify(POPUP_CALL, POPUP_EL_TITLE3, stateText); - } - break; - case PJSIP_INV_STATE_DISCONNECTED:/**< Session is terminated. */ - PopUp_Modify(POPUP_CALL, POPUP_EL_TITLE3, "Disconnected"); - PopUp_Hide(POPUP_CALL); - break; - } + + case PJSIP_INV_STATE_NULL: /**< Before INVITE is sent or received */ + break; + + case PJSIP_INV_STATE_CALLING: /**< After INVITE is sent */ + PopUp_Show (POPUP_CALL, "Calling..", ci.remote_info.ptr, "", + "", "Hangup", 0); + break; + + case PJSIP_INV_STATE_INCOMING: /**< After INVITE is received. */ + PopUp_Show (POPUP_CALL, "Incoming call..", ci.remote_info.ptr, "", + "Answer", "Hangup", 0); + pjsua_call_answer (0, 180, NULL, NULL); + + if (m_Cfg.m_AutoAnswer) + OnPopUpButton (1); + + break; + + case PJSIP_INV_STATE_EARLY: /**< After response with To tag. */ + + case PJSIP_INV_STATE_CONNECTING:/**< After 2xx is sent/received. */ + + case PJSIP_INV_STATE_CONFIRMED: { /**< After ACK is sent/received. */ + CString stateText = ci.state_text.ptr; + PopUp_Modify (POPUP_CALL, POPUP_EL_TITLE3, stateText); + } + + break; + + case PJSIP_INV_STATE_DISCONNECTED:/**< Session is terminated. */ + PopUp_Modify (POPUP_CALL, POPUP_EL_TITLE3, "Disconnected"); + PopUp_Hide (POPUP_CALL); + break; + } } -void CPocketPJDlg::on_call_state(pjsua_call_id call_id, pjsip_event *e) +void CPocketPJDlg::on_call_state (pjsua_call_id call_id, pjsip_event *e) { - PJ_UNUSED_ARG(e); - PJ_UNUSED_ARG(call_id); + PJ_UNUSED_ARG (e); + PJ_UNUSED_ARG (call_id); theDlg->OnCallState(); } -void CPocketPJDlg::on_call_media_state(pjsua_call_id call_id) +void CPocketPJDlg::on_call_media_state (pjsua_call_id call_id) { pjsua_call_info call_info; - pjsua_call_get_info(call_id, &call_info); + pjsua_call_get_info (call_id, &call_info); + if (call_info.media_status == PJSUA_CALL_MEDIA_ACTIVE) { - pjsua_conf_connect(call_info.conf_slot, 0); - pjsua_conf_connect(0, call_info.conf_slot); + pjsua_conf_connect (call_info.conf_slot, 0); + pjsua_conf_connect (0, call_info.conf_slot); } } -void CPocketPJDlg::on_incoming_call(pjsua_acc_id acc_id, pjsua_call_id call_id, - pjsip_rx_data *rdata) +void CPocketPJDlg::on_incoming_call (pjsua_acc_id acc_id, pjsua_call_id call_id, + pjsip_rx_data *rdata) { - PJ_UNUSED_ARG(acc_id); - PJ_UNUSED_ARG(call_id); - PJ_UNUSED_ARG(rdata); + PJ_UNUSED_ARG (acc_id); + PJ_UNUSED_ARG (call_id); + PJ_UNUSED_ARG (rdata); } void CPocketPJDlg::OnRegState() { pjsua_acc_info ai; - pjsua_acc_get_info(m_PjsuaAccId, &ai); + pjsua_acc_get_info (m_PjsuaAccId, &ai); - CString acc_text = m_Cfg.m_User + _T("@") + m_Cfg.m_Domain; + CString acc_text = m_Cfg.m_User + _T ("@") + m_Cfg.m_Domain; if (ai.expires>0 && ai.status/100==2) { - /* Registration success */ - HBITMAP old = m_BtnAcc.SetBitmap(::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_ONLINE)) ); - PJ_UNUSED_ARG(old); - acc_text += " (OK)"; - m_AccId.SetWindowText(acc_text); + /* Registration success */ + HBITMAP old = m_BtnAcc.SetBitmap (::LoadBitmap (AfxGetInstanceHandle(), MAKEINTRESOURCE (IDB_ONLINE))); + PJ_UNUSED_ARG (old); + acc_text += " (OK)"; + m_AccId.SetWindowText (acc_text); } else if (ai.status/100 != 2) { - acc_text += " (err)"; - Error(_T("SIP registration error"), PJSIP_ERRNO_FROM_SIP_STATUS(ai.status)); - m_AccId.SetWindowText(acc_text); + acc_text += " (err)"; + Error (_T ("SIP registration error"), PJSIP_ERRNO_FROM_SIP_STATUS (ai.status)); + m_AccId.SetWindowText (acc_text); } - PopUp_Hide(POPUP_REGISTRATION); + + PopUp_Hide (POPUP_REGISTRATION); } -void CPocketPJDlg::on_reg_state(pjsua_acc_id acc_id) +void CPocketPJDlg::on_reg_state (pjsua_acc_id acc_id) { - PJ_UNUSED_ARG(acc_id); + PJ_UNUSED_ARG (acc_id); theDlg->OnRegState(); } -void CPocketPJDlg::on_buddy_state(pjsua_buddy_id buddy_id) +void CPocketPJDlg::on_buddy_state (pjsua_buddy_id buddy_id) { - PJ_UNUSED_ARG(buddy_id); + PJ_UNUSED_ARG (buddy_id); theDlg->RedrawBuddyList(); } -void CPocketPJDlg::on_pager(pjsua_call_id call_id, const pj_str_t *from, - const pj_str_t *to, const pj_str_t *contact, - const pj_str_t *mime_type, const pj_str_t *text) +void CPocketPJDlg::on_pager (pjsua_call_id call_id, const pj_str_t *from, + const pj_str_t *to, const pj_str_t *contact, + const pj_str_t *mime_type, const pj_str_t *text) { - PJ_UNUSED_ARG(call_id); - PJ_UNUSED_ARG(from); - PJ_UNUSED_ARG(to); - PJ_UNUSED_ARG(contact); - PJ_UNUSED_ARG(mime_type); - PJ_UNUSED_ARG(text); + PJ_UNUSED_ARG (call_id); + PJ_UNUSED_ARG (from); + PJ_UNUSED_ARG (to); + PJ_UNUSED_ARG (contact); + PJ_UNUSED_ARG (mime_type); + PJ_UNUSED_ARG (text); } ///////////////////////////////////////////////////////////////////////////// @@ -499,143 +557,150 @@ void CPocketPJDlg::on_pager(pjsua_call_id call_id, const pj_str_t *from, BOOL CPocketPJDlg::OnInitDialog() { - CDialog::OnInitDialog(); - - // Set the icon for this dialog. The framework does this automatically - // when the application's main window is not a dialog - SetIcon(m_hIcon, TRUE); // Set big icon - SetIcon(m_hIcon, FALSE); // Set small icon - - CenterWindow(GetDesktopWindow()); // center to the hpc screen - - // TODO: Add extra initialization here - - m_Cfg.LoadRegistry(); - //ShowWindow(SW_SHOW); - m_AccId.SetWindowText(m_Cfg.m_User); - - CImageList *il = new CImageList; - VERIFY(il->Create(16, 16, ILC_COLOR|ILC_MASK, 2, 4)); - - CBitmap *bmp = new CBitmap; - bmp->LoadBitmap(MAKEINTRESOURCE(IDB_BLANK)); - il->Add(bmp, RGB(255,255,255)); - bmp = new CBitmap; - bmp->LoadBitmap(MAKEINTRESOURCE(IDB_ONLINE)); - il->Add(bmp, RGB(255,255,255)); - - m_BuddyList.SetImageList(il, LVSIL_SMALL); - - if (m_Cfg.m_Domain.GetLength()==0 || Restart() == FALSE) { - for (;;) { - CSettingsDlg dlg(m_Cfg); - if (dlg.DoModal() != IDOK) { - EndDialog(IDOK); - return TRUE; - } - - m_Cfg.SaveRegistry(); - - if (Restart()) - break; - } - } - - RedrawBuddyList(); - return TRUE; // return TRUE unless you set the focus to a control + CDialog::OnInitDialog(); + + // Set the icon for this dialog. The framework does this automatically + // when the application's main window is not a dialog + SetIcon (m_hIcon, TRUE); // Set big icon + SetIcon (m_hIcon, FALSE); // Set small icon + + CenterWindow (GetDesktopWindow()); // center to the hpc screen + + // TODO: Add extra initialization here + + m_Cfg.LoadRegistry(); + //ShowWindow(SW_SHOW); + m_AccId.SetWindowText (m_Cfg.m_User); + + CImageList *il = new CImageList; + VERIFY (il->Create (16, 16, ILC_COLOR|ILC_MASK, 2, 4)); + + CBitmap *bmp = new CBitmap; + bmp->LoadBitmap (MAKEINTRESOURCE (IDB_BLANK)); + il->Add (bmp, RGB (255,255,255)); + bmp = new CBitmap; + bmp->LoadBitmap (MAKEINTRESOURCE (IDB_ONLINE)); + il->Add (bmp, RGB (255,255,255)); + + m_BuddyList.SetImageList (il, LVSIL_SMALL); + + if (m_Cfg.m_Domain.GetLength() ==0 || Restart() == FALSE) { + for (;;) { + CSettingsDlg dlg (m_Cfg); + + if (dlg.DoModal() != IDOK) { + EndDialog (IDOK); + return TRUE; + } + + m_Cfg.SaveRegistry(); + + if (Restart()) + break; + } + } + + RedrawBuddyList(); + + return TRUE; // return TRUE unless you set the focus to a control } -void CPocketPJDlg::OnBtnAcc() +void CPocketPJDlg::OnBtnAcc() { CMenu menu; - VERIFY(menu.LoadMenu(IDR_ACC_MENU)); - CMenu* pPopup = menu.GetSubMenu(0); - ASSERT(pPopup != NULL); + VERIFY (menu.LoadMenu (IDR_ACC_MENU)); + CMenu* pPopup = menu.GetSubMenu (0); + ASSERT (pPopup != NULL); RECT r; - m_BtnAcc.GetWindowRect(&r); - pPopup->TrackPopupMenu(TPM_LEFTALIGN, r.left+4, r.top+4, this); + m_BtnAcc.GetWindowRect (&r); + pPopup->TrackPopupMenu (TPM_LEFTALIGN, r.left+4, r.top+4, this); } -void CPocketPJDlg::OnBtnAction() +void CPocketPJDlg::OnBtnAction() { CMenu menu; - VERIFY(menu.LoadMenu(IDR_URI_MENU)); - CMenu* pPopup = menu.GetSubMenu(0); - ASSERT(pPopup != NULL); + VERIFY (menu.LoadMenu (IDR_URI_MENU)); + CMenu* pPopup = menu.GetSubMenu (0); + ASSERT (pPopup != NULL); RECT r; - this->m_BtnUrlAction.GetWindowRect(&r); - pPopup->TrackPopupMenu(TPM_LEFTALIGN, r.left+4, r.top+4, this); + this->m_BtnUrlAction.GetWindowRect (&r); + pPopup->TrackPopupMenu (TPM_LEFTALIGN, r.left+4, r.top+4, this); } -void CPocketPJDlg::OnSettings() +void CPocketPJDlg::OnSettings() { for (;;) { - CSettingsDlg dlg(m_Cfg); - if (dlg.DoModal() != IDOK) { - return; - } + CSettingsDlg dlg (m_Cfg); + + if (dlg.DoModal() != IDOK) { + return; + } - m_Cfg.SaveRegistry(); + m_Cfg.SaveRegistry(); - if (Restart()) - break; + if (Restart()) + break; } } void CPocketPJDlg::OnOK() { - if (AfxMessageBox(_T("Quit PocketPJ?"), MB_YESNO)==IDYES) { - KillTimer(TIMER_ID); - PopUp_Show(POPUP_REGISTRATION, "", "Shutting down..", "", "", "", 0); - pjsua_destroy(); - CDialog::OnOK(); - PopUp_Hide(POPUP_REGISTRATION); - m_Cfg.SaveRegistry(); - return; + if (AfxMessageBox (_T ("Quit PocketPJ?"), MB_YESNO) ==IDYES) { + KillTimer (TIMER_ID); + PopUp_Show (POPUP_REGISTRATION, "", "Shutting down..", "", "", "", 0); + pjsua_destroy(); + CDialog::OnOK(); + PopUp_Hide (POPUP_REGISTRATION); + m_Cfg.SaveRegistry(); + return; } } -void CPocketPJDlg::OnTimer(UINT nIDEvent) +void CPocketPJDlg::OnTimer (UINT nIDEvent) { - pjsua_handle_events(10); - CDialog::OnTimer(nIDEvent); + pjsua_handle_events (10); + CDialog::OnTimer (nIDEvent); } -int CPocketPJDlg::FindBuddyInPjsua(const CString &Uri) +int CPocketPJDlg::FindBuddyInPjsua (const CString &Uri) { char uri[80]; pjsua_buddy_id id[128]; - unsigned i, count = PJ_ARRAY_SIZE(id); + unsigned i, count = PJ_ARRAY_SIZE (id); + + if (pjsua_enum_buddies (id, &count) != PJ_SUCCESS) + return PJSUA_INVALID_ID; - if (pjsua_enum_buddies(id, &count) != PJ_SUCCESS) - return PJSUA_INVALID_ID; if (count==0) - return PJSUA_INVALID_ID; + return PJSUA_INVALID_ID; - pj_unicode_to_ansi((LPCTSTR)Uri, Uri.GetLength(), uri, sizeof(uri)); + pj_unicode_to_ansi ( (LPCTSTR) Uri, Uri.GetLength(), uri, sizeof (uri)); for (i=0; i<count; ++i) { - pjsua_buddy_info bi; - pjsua_buddy_get_info(id[i], &bi); - if (pj_strcmp2(&bi.uri, uri)==0) - return i; + pjsua_buddy_info bi; + pjsua_buddy_get_info (id[i], &bi); + + if (pj_strcmp2 (&bi.uri, uri) ==0) + return i; } return PJSUA_INVALID_ID; } -int CPocketPJDlg::FindBuddyInCfg(const CString &uri) +int CPocketPJDlg::FindBuddyInCfg (const CString &uri) { int i; + for (i=0; i<m_Cfg.m_BuddyList.GetSize(); ++i) { - if (m_Cfg.m_BuddyList.GetAt(0) == uri) { - return i; - } + if (m_Cfg.m_BuddyList.GetAt (0) == uri) { + return i; + } } + return -1; } @@ -646,127 +711,136 @@ void CPocketPJDlg::RedrawBuddyList() m_BuddyList.DeleteAllItems(); for (i=0; i<m_Cfg.m_BuddyList.GetSize(); ++i) { - int isOnline; - int id; - - id = FindBuddyInPjsua(m_Cfg.m_BuddyList.GetAt(i)); - if (id != PJSUA_INVALID_ID) { - pjsua_buddy_info bi; - pjsua_buddy_get_info(id, &bi); - isOnline = (bi.status == PJSUA_BUDDY_STATUS_ONLINE); - } else { - isOnline = 0; - } - - LVITEM lvi; - memset(&lvi, 0, sizeof(lvi)); - lvi.mask = LVIF_TEXT | LVIF_IMAGE; - lvi.iItem = i; - lvi.iImage = isOnline; - lvi.pszText = (LPTSTR)(LPCTSTR)m_Cfg.m_BuddyList.GetAt(i); - - m_BuddyList.InsertItem(&lvi); + int isOnline; + int id; + + id = FindBuddyInPjsua (m_Cfg.m_BuddyList.GetAt (i)); + + if (id != PJSUA_INVALID_ID) { + pjsua_buddy_info bi; + pjsua_buddy_get_info (id, &bi); + isOnline = (bi.status == PJSUA_BUDDY_STATUS_ONLINE); + } else { + isOnline = 0; + } + + LVITEM lvi; + + memset (&lvi, 0, sizeof (lvi)); + lvi.mask = LVIF_TEXT | LVIF_IMAGE; + lvi.iItem = i; + lvi.iImage = isOnline; + lvi.pszText = (LPTSTR) (LPCTSTR) m_Cfg.m_BuddyList.GetAt (i); + + m_BuddyList.InsertItem (&lvi); } } -void CPocketPJDlg::OnUriCall() +void CPocketPJDlg::OnUriCall() { char tmp[120]; CString uri; pj_status_t status; - m_Url.GetWindowText(uri); - pj_unicode_to_ansi((LPCTSTR)uri, uri.GetLength(), tmp, sizeof(tmp)); - if ((status=pjsua_verify_sip_url(tmp)) != PJ_SUCCESS) { - Error("The URL is not valid SIP URL", status); - return; + m_Url.GetWindowText (uri); + pj_unicode_to_ansi ( (LPCTSTR) uri, uri.GetLength(), tmp, sizeof (tmp)); + + if ( (status=pjsua_verify_sip_url (tmp)) != PJ_SUCCESS) { + Error ("The URL is not valid SIP URL", status); + return; } - pj_str_t dest_uri = pj_str(tmp); + pj_str_t dest_uri = pj_str (tmp); + pjsua_call_id call_id; - status = pjsua_call_make_call(m_PjsuaAccId, &dest_uri, 0, NULL, NULL, &call_id); + status = pjsua_call_make_call (m_PjsuaAccId, &dest_uri, 0, NULL, NULL, &call_id); if (status != PJ_SUCCESS) - Error("Unable to make call", status); + Error ("Unable to make call", status); } -void CPocketPJDlg::OnUriAddBuddy() +void CPocketPJDlg::OnUriAddBuddy() { int i; char tmp[120]; CString uri; pj_status_t status; - m_Url.GetWindowText(uri); - pj_unicode_to_ansi((LPCTSTR)uri, uri.GetLength(), tmp, sizeof(tmp)); - if ((status=pjsua_verify_sip_url(tmp)) != PJ_SUCCESS) { - Error("The URL is not valid SIP URL", status); - return; + m_Url.GetWindowText (uri); + pj_unicode_to_ansi ( (LPCTSTR) uri, uri.GetLength(), tmp, sizeof (tmp)); + + if ( (status=pjsua_verify_sip_url (tmp)) != PJ_SUCCESS) { + Error ("The URL is not valid SIP URL", status); + return; } for (i=0; i<m_Cfg.m_BuddyList.GetSize(); ++i) { - if (m_Cfg.m_BuddyList.GetAt(0) == uri) { - AfxMessageBox(_T("The URI is already in the buddy list")); - return; - } + if (m_Cfg.m_BuddyList.GetAt (0) == uri) { + AfxMessageBox (_T ("The URI is already in the buddy list")); + return; + } } - m_Cfg.m_BuddyList.Add(uri); + m_Cfg.m_BuddyList.Add (uri); + RedrawBuddyList(); } -void CPocketPJDlg::OnUriDelBuddy() +void CPocketPJDlg::OnUriDelBuddy() { CString uri; - m_Url.GetWindowText(uri); - int i = FindBuddyInCfg(uri); + m_Url.GetWindowText (uri); + int i = FindBuddyInCfg (uri); + if (i<0) { - /* Buddy not found */ - return; + /* Buddy not found */ + return; } - m_Cfg.m_BuddyList.RemoveAt(i); + m_Cfg.m_BuddyList.RemoveAt (i); + RedrawBuddyList(); - AfxMessageBox(_T("Buddy " + uri + " deleted")); + AfxMessageBox (_T ("Buddy " + uri + " deleted")); } -void CPocketPJDlg::OnAccOnline() +void CPocketPJDlg::OnAccOnline() { - pjsua_acc_set_online_status(m_PjsuaAccId, PJ_TRUE); - m_BtnAcc.SetBitmap(::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_ONLINE)) ); + pjsua_acc_set_online_status (m_PjsuaAccId, PJ_TRUE); + m_BtnAcc.SetBitmap (::LoadBitmap (AfxGetInstanceHandle(), MAKEINTRESOURCE (IDB_ONLINE))); } -void CPocketPJDlg::OnAccInvisible() +void CPocketPJDlg::OnAccInvisible() { - pjsua_acc_set_online_status(m_PjsuaAccId, PJ_FALSE); - m_BtnAcc.SetBitmap(::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_INVISIBLE)) ); + pjsua_acc_set_online_status (m_PjsuaAccId, PJ_FALSE); + m_BtnAcc.SetBitmap (::LoadBitmap (AfxGetInstanceHandle(), MAKEINTRESOURCE (IDB_INVISIBLE))); } -void CPocketPJDlg::OnPopUpButton(int btnNo) +void CPocketPJDlg::OnPopUpButton (int btnNo) { if (btnNo == 1) { - pjsua_call_answer(0, 200, NULL, 0); - PopUp_Modify(POPUP_CALL, POPUP_EL_BUTTON1, ""); + pjsua_call_answer (0, 200, NULL, 0); + PopUp_Modify (POPUP_CALL, POPUP_EL_BUTTON1, ""); } else if (btnNo == 2) { - // Hangup button - PopUp_Modify(POPUP_CALL, POPUP_EL_TITLE2, "Hang up.."); - PopUp_Modify(POPUP_CALL, POPUP_EL_TITLE3, ""); - pjsua_call_hangup(0, PJSIP_SC_DECLINE, 0, 0); + // Hangup button + PopUp_Modify (POPUP_CALL, POPUP_EL_TITLE2, "Hang up.."); + PopUp_Modify (POPUP_CALL, POPUP_EL_TITLE3, ""); + pjsua_call_hangup (0, PJSIP_SC_DECLINE, 0, 0); } } -void CPocketPJDlg::OnClickBuddyList(NMHDR* pNMHDR, LRESULT* pResult) +void CPocketPJDlg::OnClickBuddyList (NMHDR* pNMHDR, LRESULT* pResult) { POSITION pos = m_BuddyList.GetFirstSelectedItemPosition(); - PJ_UNUSED_ARG(pNMHDR); + PJ_UNUSED_ARG (pNMHDR); if (pos != NULL) { - int iItem = m_BuddyList.GetNextSelectedItem(pos); - CString uri = m_BuddyList.GetItemText(iItem, 0); - m_Url.SetWindowText(uri); + int iItem = m_BuddyList.GetNextSelectedItem (pos); + CString uri = m_BuddyList.GetItemText (iItem, 0); + m_Url.SetWindowText (uri); } + *pResult = 0; } diff --git a/sflphone-common/libs/pjproject/pjsip-apps/src/pocketpj/PopUpWnd.cpp b/sflphone-common/libs/pjproject/pjsip-apps/src/pocketpj/PopUpWnd.cpp index 1f1654f0621eca2dd67e4686be3002f1a647eff5..a92d2454e21f48256aa624a55358b576c276ebc3 100644 --- a/sflphone-common/libs/pjproject/pjsip-apps/src/pocketpj/PopUpWnd.cpp +++ b/sflphone-common/libs/pjproject/pjsip-apps/src/pocketpj/PopUpWnd.cpp @@ -16,9 +16,9 @@ static char THIS_FILE[] = __FILE__; ///////////////////////////////////////////////////////////////////////////// // CPopUpWnd -CPopUpWnd::CPopUpWnd(CPocketPJDlg* pParent) +CPopUpWnd::CPopUpWnd (CPocketPJDlg* pParent) { - Create(pParent); + Create (pParent); } CPopUpWnd::~CPopUpWnd() @@ -26,81 +26,95 @@ CPopUpWnd::~CPopUpWnd() DestroyWindow(); } -BOOL CPopUpWnd::Create(CPocketPJDlg* pParent) +BOOL CPopUpWnd::Create (CPocketPJDlg* pParent) { BOOL bSuccess; m_ParentWnd = pParent; // Register window class - CString csClassName = AfxRegisterWndClass(CS_HREDRAW|CS_VREDRAW, - 0, - CBrush(::GetSysColor(COLOR_BTNFACE))); + CString csClassName = AfxRegisterWndClass (CS_HREDRAW|CS_VREDRAW, + 0, + CBrush (::GetSysColor (COLOR_BTNFACE))); // Create popup window - bSuccess = CreateEx(WS_EX_DLGMODALFRAME|WS_EX_TOPMOST, // Extended style - csClassName, // Classname - _T("PocketPJ"), // Title - WS_POPUP|WS_BORDER|WS_CAPTION, // style - 0,0, // position - updated soon. - 1,1, // Size - updated soon - pParent->GetSafeHwnd(), // handle to parent - 0, // No menu - NULL); - if (!bSuccess) - return FALSE; - - ShowWindow(SW_HIDE); + bSuccess = CreateEx (WS_EX_DLGMODALFRAME|WS_EX_TOPMOST, // Extended style + csClassName, // Classname + _T ("PocketPJ"), // Title + WS_POPUP|WS_BORDER|WS_CAPTION, // style + 0,0, // position - updated soon. + 1,1, // Size - updated soon + pParent->GetSafeHwnd(), // handle to parent + 0, // No menu + NULL); + + if (!bSuccess) + return FALSE; + + ShowWindow (SW_HIDE); // Now create the controls - CRect TempRect(0,0,10,10); + CRect TempRect (0,0,10,10); /* |SS_LEFTNOWORDWRAP */ - bSuccess = m_Title1.Create(_T("Title1"), WS_CHILD|WS_VISIBLE|SS_NOPREFIX, - TempRect, this, IDC_TITLE1); + bSuccess = m_Title1.Create (_T ("Title1"), WS_CHILD|WS_VISIBLE|SS_NOPREFIX, + TempRect, this, IDC_TITLE1); + if (!bSuccess) - return FALSE; + return FALSE; + + bSuccess = m_Title2.Create (_T ("Title2"), WS_CHILD|WS_VISIBLE|SS_NOPREFIX, + TempRect, this, IDC_TITLE2); - bSuccess = m_Title2.Create(_T("Title2"), WS_CHILD|WS_VISIBLE|SS_NOPREFIX, - TempRect, this, IDC_TITLE2); if (!bSuccess) - return FALSE; + return FALSE; + + bSuccess = m_Title3.Create (_T ("Title3"), WS_CHILD|WS_VISIBLE|SS_NOPREFIX, + TempRect, this, IDC_TITLE3); - bSuccess = m_Title3.Create(_T("Title3"), WS_CHILD|WS_VISIBLE|SS_NOPREFIX, - TempRect, this, IDC_TITLE3); if (!bSuccess) - return FALSE; + return FALSE; + + bSuccess = m_Btn1.Create (_T ("Button1"), + WS_CHILD|WS_VISIBLE|WS_TABSTOP| BS_PUSHBUTTON, + TempRect, this, IDC_BTN1); - bSuccess = m_Btn1.Create(_T("Button1"), - WS_CHILD|WS_VISIBLE|WS_TABSTOP| BS_PUSHBUTTON, - TempRect, this, IDC_BTN1); if (!bSuccess) - return FALSE; + return FALSE; + + bSuccess = m_Btn2.Create (_T ("Button2"), + WS_CHILD|WS_VISIBLE|WS_TABSTOP| BS_PUSHBUTTON, + TempRect, this, IDC_BTN2); - bSuccess = m_Btn2.Create(_T("Button2"), - WS_CHILD|WS_VISIBLE|WS_TABSTOP| BS_PUSHBUTTON, - TempRect, this, IDC_BTN2); if (!bSuccess) - return FALSE; + return FALSE; - CFont *ft1 = new CFont, - *ft2 = new CFont, - *ft3 = new CFont; + CFont *ft1 = new CFont, + *ft2 = new CFont, + *ft3 = new CFont; LOGFONT lf; - memset(&lf, 0, sizeof(LOGFONT)); + + memset (&lf, 0, sizeof (LOGFONT)); + lf.lfHeight = 12; - lstrcpy(lf.lfFaceName, _T("Arial")); - VERIFY(ft1->CreateFontIndirect(&lf)); - VERIFY(ft3->CreateFontIndirect(&lf)); + + lstrcpy (lf.lfFaceName, _T ("Arial")); + + VERIFY (ft1->CreateFontIndirect (&lf)); + + VERIFY (ft3->CreateFontIndirect (&lf)); lf.lfHeight = 20; - VERIFY(ft2->CreateFontIndirect(&lf)); - m_Title1.SetFont(ft1, TRUE); - m_Title2.SetFont(ft2, TRUE); - m_Title3.SetFont(ft3, TRUE); + VERIFY (ft2->CreateFontIndirect (&lf)); + + m_Title1.SetFont (ft1, TRUE); + + m_Title2.SetFont (ft2, TRUE); + + m_Title3.SetFont (ft3, TRUE); SetWindowSize(); @@ -113,109 +127,111 @@ BOOL CPopUpWnd::Create(CPocketPJDlg* pParent) return TRUE; } -void CPopUpWnd::SetContent(const CPopUpContent &content) +void CPopUpWnd::SetContent (const CPopUpContent &content) { - m_Title1.SetWindowText(content.m_Title1); - m_Title2.SetWindowText(content.m_Title2); - m_Title3.SetWindowText(content.m_Title3); + m_Title1.SetWindowText (content.m_Title1); + m_Title2.SetWindowText (content.m_Title2); + m_Title3.SetWindowText (content.m_Title3); if (content.m_Btn1 != "") { - m_Btn1.SetWindowText(content.m_Btn1); - m_Btn1.ShowWindow(SW_SHOW); + m_Btn1.SetWindowText (content.m_Btn1); + m_Btn1.ShowWindow (SW_SHOW); } else { - m_Btn1.ShowWindow(SW_HIDE); + m_Btn1.ShowWindow (SW_HIDE); } if (content.m_Btn2 != "") { - m_Btn2.SetWindowText(content.m_Btn2); - m_Btn2.ShowWindow(SW_SHOW); + m_Btn2.SetWindowText (content.m_Btn2); + m_Btn2.ShowWindow (SW_SHOW); } else { - m_Btn2.ShowWindow(SW_HIDE); + m_Btn2.ShowWindow (SW_HIDE); } UpdateWindow(); - ShowWindow(SW_SHOW); + + ShowWindow (SW_SHOW); } -void CPopUpWnd::SetWindowSize(int width, int height) +void CPopUpWnd::SetWindowSize (int width, int height) { enum { H1 = 16, H2 = 40, H3 = 16, S = 5, G = 10, BW=60, BH=20, BG=40}; - CRect rootRect(0, 0, 320, 240); + CRect rootRect (0, 0, 320, 240); int Y; - MoveWindow((rootRect.Width() - width)/2, (rootRect.Height() - height)/2, - width, height); + MoveWindow ( (rootRect.Width() - width) /2, (rootRect.Height() - height) /2, + width, height); - m_Title1.MoveWindow(10, Y=S, width-20, H1); - m_Title2.MoveWindow(10, Y+=H1+G, width-20, H2); - m_Title3.MoveWindow(10, Y+=H2+G, width-20, H3); + m_Title1.MoveWindow (10, Y=S, width-20, H1); + m_Title2.MoveWindow (10, Y+=H1+G, width-20, H2); + m_Title3.MoveWindow (10, Y+=H2+G, width-20, H3); - m_Btn1.MoveWindow((width-2*BW-BG)/2, Y+=H3+G, BW, BH); - m_Btn2.MoveWindow((width-2*BW-BG)/2+BW+BG, Y, BW, BH); + m_Btn1.MoveWindow ( (width-2*BW-BG) /2, Y+=H3+G, BW, BH); + m_Btn2.MoveWindow ( (width-2*BW-BG) /2+BW+BG, Y, BW, BH); } -void CPopUpWnd::Hide() -{ - if (!::IsWindow(GetSafeHwnd())) +void CPopUpWnd::Hide() +{ + if (!::IsWindow (GetSafeHwnd())) return; - if (IsWindowVisible()) - { - ShowWindow(SW_HIDE); - ModifyStyle(WS_VISIBLE, 0); + if (IsWindowVisible()) { + ShowWindow (SW_HIDE); + ModifyStyle (WS_VISIBLE, 0); } } -void CPopUpWnd::Show() -{ - if (!::IsWindow(GetSafeHwnd())) +void CPopUpWnd::Show() +{ + if (!::IsWindow (GetSafeHwnd())) return; - ModifyStyle(0, WS_VISIBLE); - ShowWindow(SW_SHOWNA); - RedrawWindow(NULL,NULL,RDW_ERASE|RDW_INVALIDATE|RDW_UPDATENOW); + ModifyStyle (0, WS_VISIBLE); + + ShowWindow (SW_SHOWNA); + + RedrawWindow (NULL,NULL,RDW_ERASE|RDW_INVALIDATE|RDW_UPDATENOW); } -BEGIN_MESSAGE_MAP(CPopUpWnd, CWnd) +BEGIN_MESSAGE_MAP (CPopUpWnd, CWnd) //{{AFX_MSG_MAP(CPopUpWnd) ON_WM_ERASEBKGND() - //}}AFX_MSG_MAP - ON_BN_CLICKED(IDC_BTN1, OnCancel1) - ON_BN_CLICKED(IDC_BTN2, OnCancel2) + //}}AFX_MSG_MAP + ON_BN_CLICKED (IDC_BTN1, OnCancel1) + ON_BN_CLICKED (IDC_BTN2, OnCancel2) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CPopUpWnd message handlers -BOOL CPopUpWnd::OnEraseBkgnd(CDC* pDC) +BOOL CPopUpWnd::OnEraseBkgnd (CDC* pDC) { CBrush backBrush; - backBrush.CreateSolidBrush(RGB(255,255,255)); - CBrush* pOldBrush = pDC->SelectObject(&backBrush); + backBrush.CreateSolidBrush (RGB (255,255,255)); + CBrush* pOldBrush = pDC->SelectObject (&backBrush); CRect rect; - pDC->GetClipBox(&rect); // Erase the area needed - pDC->PatBlt(rect.left, rect.top, rect.Width(), rect.Height(), PATCOPY); - pDC->SelectObject(pOldBrush); + pDC->GetClipBox (&rect); // Erase the area needed + pDC->PatBlt (rect.left, rect.top, rect.Width(), rect.Height(), PATCOPY); + pDC->SelectObject (pOldBrush); return TRUE; } -void CPopUpWnd::OnCancel1() +void CPopUpWnd::OnCancel1() { - m_ParentWnd->OnPopUpButton(1); + m_ParentWnd->OnPopUpButton (1); } -void CPopUpWnd::OnCancel2() +void CPopUpWnd::OnCancel2() { - m_ParentWnd->OnPopUpButton(2); + m_ParentWnd->OnPopUpButton (2); } -BOOL CPopUpWnd::DestroyWindow() +BOOL CPopUpWnd::DestroyWindow() { return CWnd::DestroyWindow(); } @@ -223,13 +239,12 @@ BOOL CPopUpWnd::DestroyWindow() void CPopUpWnd::PeekAndPump() { MSG msg; - while (::PeekMessage(&msg, NULL,0,0,PM_NOREMOVE)) - { - if (!AfxGetApp()->PumpMessage()) - { - ::PostQuitMessage(0); + + while (::PeekMessage (&msg, NULL,0,0,PM_NOREMOVE)) { + if (!AfxGetApp()->PumpMessage()) { + ::PostQuitMessage (0); return; - } + } } } diff --git a/sflphone-common/libs/pjproject/pjsip-apps/src/pocketpj/SettingsDlg.cpp b/sflphone-common/libs/pjproject/pjsip-apps/src/pocketpj/SettingsDlg.cpp index 1357044ae2c4675b973a6de003ba6a4a8476b784..6d963f81fa3ec9b2ec11faf8c56bd006f3464868 100644 --- a/sflphone-common/libs/pjproject/pjsip-apps/src/pocketpj/SettingsDlg.cpp +++ b/sflphone-common/libs/pjproject/pjsip-apps/src/pocketpj/SettingsDlg.cpp @@ -37,20 +37,20 @@ static char THIS_FILE[] = __FILE__; ///////////////////////////////////////////////////////////////////////////// // Settings CPocketPJSettings::CPocketPJSettings() -: m_UseStun(FALSE), m_UseIce(FALSE), m_UseSrtp(FALSE), m_UsePublish(FALSE), - m_EchoSuppress(TRUE), m_EcTail(200), m_TCP(FALSE), m_VAD(FALSE), - m_AutoAnswer(FALSE) + : m_UseStun (FALSE), m_UseIce (FALSE), m_UseSrtp (FALSE), m_UsePublish (FALSE), + m_EchoSuppress (TRUE), m_EcTail (200), m_TCP (FALSE), m_VAD (FALSE), + m_AutoAnswer (FALSE) { /* Init codec list */ #if defined(PJMEDIA_HAS_GSM_CODEC) && PJMEDIA_HAS_GSM_CODEC - m_Codecs.Add(_T("GSM")); + m_Codecs.Add (_T ("GSM")); #endif #if defined(PJMEDIA_HAS_G711_CODEC) && PJMEDIA_HAS_G711_CODEC - m_Codecs.Add(_T("PCMU")); - m_Codecs.Add(_T("PCMA")); + m_Codecs.Add (_T ("PCMU")); + m_Codecs.Add (_T ("PCMA")); #endif #if defined(PJMEDIA_HAS_SPEEX_CODEC) && PJMEDIA_HAS_SPEEX_CODEC - m_Codecs.Add(_T("Speex")); + m_Codecs.Add (_T ("Speex")); #endif } @@ -63,113 +63,131 @@ void CPocketPJSettings::LoadRegistry() DWORD cbData; - if (key.Open(HKEY_CURRENT_USER, REG_PATH) != ERROR_SUCCESS) - return; + if (key.Open (HKEY_CURRENT_USER, REG_PATH) != ERROR_SUCCESS) + return; - cbData = sizeof(textVal); - if (key.QueryValue(textVal, REG_DOMAIN, &cbData) == ERROR_SUCCESS) { - m_Domain = textVal; + cbData = sizeof (textVal); + + if (key.QueryValue (textVal, REG_DOMAIN, &cbData) == ERROR_SUCCESS) { + m_Domain = textVal; } - cbData = sizeof(textVal); - if (key.QueryValue(textVal, REG_USER, &cbData) == ERROR_SUCCESS) { - m_User = textVal; + cbData = sizeof (textVal); + + if (key.QueryValue (textVal, REG_USER, &cbData) == ERROR_SUCCESS) { + m_User = textVal; } - cbData = sizeof(textVal); - if (key.QueryValue(textVal, REG_PASSWD, &cbData) == ERROR_SUCCESS) { - m_Password = textVal; + cbData = sizeof (textVal); + + if (key.QueryValue (textVal, REG_PASSWD, &cbData) == ERROR_SUCCESS) { + m_Password = textVal; } - cbData = sizeof(textVal); - if (key.QueryValue(textVal, REG_STUN_SRV, &cbData) == ERROR_SUCCESS) { - m_StunSrv = textVal; + cbData = sizeof (textVal); + + if (key.QueryValue (textVal, REG_STUN_SRV, &cbData) == ERROR_SUCCESS) { + m_StunSrv = textVal; } - cbData = sizeof(textVal); - if (key.QueryValue(textVal, REG_DNS, &cbData) == ERROR_SUCCESS) { - m_DNS = textVal; + cbData = sizeof (textVal); + + if (key.QueryValue (textVal, REG_DNS, &cbData) == ERROR_SUCCESS) { + m_DNS = textVal; } dwordVal = 0; - if (key.QueryValue(dwordVal, REG_USE_STUN) == ERROR_SUCCESS) { - m_UseStun = dwordVal != 0; + + if (key.QueryValue (dwordVal, REG_USE_STUN) == ERROR_SUCCESS) { + m_UseStun = dwordVal != 0; } - if (key.QueryValue(dwordVal, REG_USE_ICE) == ERROR_SUCCESS) { - m_UseIce = dwordVal != 0; + if (key.QueryValue (dwordVal, REG_USE_ICE) == ERROR_SUCCESS) { + m_UseIce = dwordVal != 0; } - if (key.QueryValue(dwordVal, REG_USE_SRTP) == ERROR_SUCCESS) { - m_UseSrtp = dwordVal != 0; + if (key.QueryValue (dwordVal, REG_USE_SRTP) == ERROR_SUCCESS) { + m_UseSrtp = dwordVal != 0; } - cbData = sizeof(dwordVal); - if (key.QueryValue(dwordVal, REG_USE_PUBLISH) == ERROR_SUCCESS) { - m_UsePublish = dwordVal != 0; + cbData = sizeof (dwordVal); + + if (key.QueryValue (dwordVal, REG_USE_PUBLISH) == ERROR_SUCCESS) { + m_UsePublish = dwordVal != 0; } - cbData = sizeof(dwordVal); - if (key.QueryValue(dwordVal, REG_ENABLE_EC) == ERROR_SUCCESS) { - m_EchoSuppress = dwordVal != 0; + cbData = sizeof (dwordVal); + + if (key.QueryValue (dwordVal, REG_ENABLE_EC) == ERROR_SUCCESS) { + m_EchoSuppress = dwordVal != 0; } - cbData = sizeof(dwordVal); - if (key.QueryValue(dwordVal, REG_EC_TAIL) == ERROR_SUCCESS) { - m_EcTail = dwordVal; + cbData = sizeof (dwordVal); + + if (key.QueryValue (dwordVal, REG_EC_TAIL) == ERROR_SUCCESS) { + m_EcTail = dwordVal; } - cbData = sizeof(dwordVal); - if (key.QueryValue(dwordVal, REG_ENABLE_TCP) == ERROR_SUCCESS) { - m_TCP = dwordVal != 0; + cbData = sizeof (dwordVal); + + if (key.QueryValue (dwordVal, REG_ENABLE_TCP) == ERROR_SUCCESS) { + m_TCP = dwordVal != 0; } - cbData = sizeof(dwordVal); - if (key.QueryValue(dwordVal, REG_ENABLE_VAD) == ERROR_SUCCESS) { - m_VAD = dwordVal != 0; + cbData = sizeof (dwordVal); + + if (key.QueryValue (dwordVal, REG_ENABLE_VAD) == ERROR_SUCCESS) { + m_VAD = dwordVal != 0; } - cbData = sizeof(dwordVal); - if (key.QueryValue(dwordVal, REG_AUTO_ANSWER) == ERROR_SUCCESS) { - m_AutoAnswer = dwordVal != 0; + cbData = sizeof (dwordVal); + + if (key.QueryValue (dwordVal, REG_AUTO_ANSWER) == ERROR_SUCCESS) { + m_AutoAnswer = dwordVal != 0; } m_BuddyList.RemoveAll(); DWORD buddyCount = 0; - cbData = sizeof(dwordVal); - if (key.QueryValue(dwordVal, REG_BUDDY_CNT) == ERROR_SUCCESS) { - buddyCount = dwordVal; + cbData = sizeof (dwordVal); + + if (key.QueryValue (dwordVal, REG_BUDDY_CNT) == ERROR_SUCCESS) { + buddyCount = dwordVal; } unsigned i; + for (i=0; i<buddyCount; ++i) { - CString entry; - entry.Format(REG_BUDDY_X, i); + CString entry; + entry.Format (REG_BUDDY_X, i); - cbData = sizeof(textVal); - if (key.QueryValue(textVal, entry, &cbData) == ERROR_SUCCESS) { - m_BuddyList.Add(textVal); - } + cbData = sizeof (textVal); + + if (key.QueryValue (textVal, entry, &cbData) == ERROR_SUCCESS) { + m_BuddyList.Add (textVal); + } } DWORD codecCount = 0; - cbData = sizeof(dwordVal); - if (key.QueryValue(codecCount, REG_CODEC_CNT) == ERROR_SUCCESS) { - m_Codecs.RemoveAll(); + cbData = sizeof (dwordVal); + + if (key.QueryValue (codecCount, REG_CODEC_CNT) == ERROR_SUCCESS) { - for (i=0; i<codecCount; ++i) { - CString entry; - entry.Format(REG_CODEC_X, i); + m_Codecs.RemoveAll(); - cbData = sizeof(textVal); - if (key.QueryValue(textVal, entry, &cbData) == ERROR_SUCCESS) { - m_Codecs.Add(textVal); - } - } + for (i=0; i<codecCount; ++i) { + CString entry; + entry.Format (REG_CODEC_X, i); + + cbData = sizeof (textVal); + + if (key.QueryValue (textVal, entry, &cbData) == ERROR_SUCCESS) { + m_Codecs.Add (textVal); + } + } } key.Close(); @@ -180,42 +198,55 @@ void CPocketPJSettings::SaveRegistry() { CRegKey key; - if (key.Create(HKEY_CURRENT_USER, REG_PATH) != ERROR_SUCCESS) - return; + if (key.Create (HKEY_CURRENT_USER, REG_PATH) != ERROR_SUCCESS) + return; + + key.SetValue (m_Domain, REG_DOMAIN); + + key.SetValue (m_User, REG_USER); + + key.SetValue (m_Password, REG_PASSWD); - key.SetValue(m_Domain, REG_DOMAIN); - key.SetValue(m_User, REG_USER); - key.SetValue(m_Password, REG_PASSWD); - key.SetValue(m_StunSrv, REG_STUN_SRV); - key.SetValue(m_DNS, REG_DNS); - - key.SetValue(m_UseStun, REG_USE_STUN); - key.SetValue(m_UseIce, REG_USE_ICE); - key.SetValue(m_UseSrtp, REG_USE_SRTP); - key.SetValue(m_UsePublish, REG_USE_PUBLISH); + key.SetValue (m_StunSrv, REG_STUN_SRV); - key.SetValue(m_EchoSuppress, REG_ENABLE_EC); - key.SetValue(m_EcTail, REG_EC_TAIL); + key.SetValue (m_DNS, REG_DNS); - key.SetValue(m_TCP, REG_ENABLE_TCP); - key.SetValue(m_VAD, REG_ENABLE_VAD); - key.SetValue(m_AutoAnswer, REG_AUTO_ANSWER); + key.SetValue (m_UseStun, REG_USE_STUN); - key.SetValue(m_BuddyList.GetSize(), REG_BUDDY_CNT); + key.SetValue (m_UseIce, REG_USE_ICE); + + key.SetValue (m_UseSrtp, REG_USE_SRTP); + + key.SetValue (m_UsePublish, REG_USE_PUBLISH); + + key.SetValue (m_EchoSuppress, REG_ENABLE_EC); + + key.SetValue (m_EcTail, REG_EC_TAIL); + + key.SetValue (m_TCP, REG_ENABLE_TCP); + + key.SetValue (m_VAD, REG_ENABLE_VAD); + + key.SetValue (m_AutoAnswer, REG_AUTO_ANSWER); + + key.SetValue (m_BuddyList.GetSize(), REG_BUDDY_CNT); int i; + for (i=0; i<m_BuddyList.GetSize(); ++i) { - CString entry; - entry.Format(REG_BUDDY_X, i); - key.SetValue(m_BuddyList.GetAt(i), entry); + CString entry; + entry.Format (REG_BUDDY_X, i); + key.SetValue (m_BuddyList.GetAt (i), entry); } DWORD N = m_Codecs.GetSize(); - key.SetValue(N, REG_CODEC_CNT); + + key.SetValue (N, REG_CODEC_CNT); + for (i=0; i<m_Codecs.GetSize(); ++i) { - CString entry; - entry.Format(REG_CODEC_X, i); - key.SetValue(m_Codecs.GetAt(i), entry); + CString entry; + entry.Format (REG_CODEC_X, i); + key.SetValue (m_Codecs.GetAt (i), entry); } key.Close(); @@ -226,127 +257,137 @@ void CPocketPJSettings::SaveRegistry() // CSettingsDlg dialog -CSettingsDlg::CSettingsDlg(CPocketPJSettings &cfg, CWnd* pParent) - : CDialog(CSettingsDlg::IDD, pParent), m_Cfg(cfg) +CSettingsDlg::CSettingsDlg (CPocketPJSettings &cfg, CWnd* pParent) + : CDialog (CSettingsDlg::IDD, pParent), m_Cfg (cfg) { - //{{AFX_DATA_INIT(CSettingsDlg) - m_Domain = _T(""); - m_ICE = FALSE; - m_Passwd = _T(""); - m_PUBLISH = FALSE; - m_SRTP = FALSE; - m_STUN = FALSE; - m_StunSrv = _T(""); - m_User = _T(""); - m_Dns = _T(""); - m_EchoSuppress = FALSE; - m_EcTail = _T(""); - m_TCP = FALSE; - m_VAD = FALSE; - m_AutoAnswer = FALSE; - //}}AFX_DATA_INIT - - m_Domain = m_Cfg.m_Domain; - m_ICE = m_Cfg.m_UseIce; - m_Passwd = m_Cfg.m_Password; - m_PUBLISH = m_Cfg.m_UsePublish; - m_SRTP = m_Cfg.m_UseSrtp; - m_STUN = m_Cfg.m_UseStun; - m_StunSrv = m_Cfg.m_StunSrv; - m_User = m_Cfg.m_User; - m_Dns = m_Cfg.m_DNS; - m_EchoSuppress = m_Cfg.m_EchoSuppress; - m_TCP = m_Cfg.m_TCP; - m_VAD = m_Cfg.m_VAD; - m_AutoAnswer= m_Cfg.m_AutoAnswer; - - CString s; - s.Format(_T("%d"), m_Cfg.m_EcTail); - m_EcTail = s; + //{{AFX_DATA_INIT(CSettingsDlg) + m_Domain = _T (""); + m_ICE = FALSE; + m_Passwd = _T (""); + m_PUBLISH = FALSE; + m_SRTP = FALSE; + m_STUN = FALSE; + m_StunSrv = _T (""); + m_User = _T (""); + m_Dns = _T (""); + m_EchoSuppress = FALSE; + m_EcTail = _T (""); + m_TCP = FALSE; + m_VAD = FALSE; + m_AutoAnswer = FALSE; + //}}AFX_DATA_INIT + + m_Domain = m_Cfg.m_Domain; + m_ICE = m_Cfg.m_UseIce; + m_Passwd = m_Cfg.m_Password; + m_PUBLISH = m_Cfg.m_UsePublish; + m_SRTP = m_Cfg.m_UseSrtp; + m_STUN = m_Cfg.m_UseStun; + m_StunSrv = m_Cfg.m_StunSrv; + m_User = m_Cfg.m_User; + m_Dns = m_Cfg.m_DNS; + m_EchoSuppress = m_Cfg.m_EchoSuppress; + m_TCP = m_Cfg.m_TCP; + m_VAD = m_Cfg.m_VAD; + m_AutoAnswer= m_Cfg.m_AutoAnswer; + + CString s; + s.Format (_T ("%d"), m_Cfg.m_EcTail); + m_EcTail = s; } -void CSettingsDlg::DoDataExchange(CDataExchange* pDX) +void CSettingsDlg::DoDataExchange (CDataExchange* pDX) { - CDialog::DoDataExchange(pDX); - //{{AFX_DATA_MAP(CSettingsDlg) - DDX_Control(pDX, IDC_CODECS, m_Codecs); - DDX_Text(pDX, IDC_DOMAIN, m_Domain); - DDX_Check(pDX, IDC_ICE, m_ICE); - DDX_Text(pDX, IDC_PASSWD, m_Passwd); - DDX_Check(pDX, IDC_PUBLISH, m_PUBLISH); - DDX_Check(pDX, IDC_SRTP, m_SRTP); - DDX_Check(pDX, IDC_STUN, m_STUN); - DDX_Text(pDX, IDC_STUN_SRV, m_StunSrv); - DDX_Text(pDX, IDC_USER, m_User); - DDX_Text(pDX, IDC_DNS, m_Dns); - DDX_Check(pDX, IDC_ECHO_SUPPRESS, m_EchoSuppress); - DDX_Text(pDX, IDC_EC_TAIL, m_EcTail); - DDX_Check(pDX, IDC_TCP, m_TCP); - DDX_Check(pDX, IDC_VAD, m_VAD); - DDX_Check(pDX, IDC_AA, m_AutoAnswer); - //}}AFX_DATA_MAP - - - if (m_Codecs.GetCount() == 0) { - int i; - for (i=0; i<m_Cfg.m_Codecs.GetSize(); ++i) { - m_Codecs.AddString(m_Cfg.m_Codecs.GetAt(i)); - } - m_Codecs.SetCurSel(0); - } + CDialog::DoDataExchange (pDX); + //{{AFX_DATA_MAP(CSettingsDlg) + DDX_Control (pDX, IDC_CODECS, m_Codecs); + DDX_Text (pDX, IDC_DOMAIN, m_Domain); + DDX_Check (pDX, IDC_ICE, m_ICE); + DDX_Text (pDX, IDC_PASSWD, m_Passwd); + DDX_Check (pDX, IDC_PUBLISH, m_PUBLISH); + DDX_Check (pDX, IDC_SRTP, m_SRTP); + DDX_Check (pDX, IDC_STUN, m_STUN); + DDX_Text (pDX, IDC_STUN_SRV, m_StunSrv); + DDX_Text (pDX, IDC_USER, m_User); + DDX_Text (pDX, IDC_DNS, m_Dns); + DDX_Check (pDX, IDC_ECHO_SUPPRESS, m_EchoSuppress); + DDX_Text (pDX, IDC_EC_TAIL, m_EcTail); + DDX_Check (pDX, IDC_TCP, m_TCP); + DDX_Check (pDX, IDC_VAD, m_VAD); + DDX_Check (pDX, IDC_AA, m_AutoAnswer); + //}}AFX_DATA_MAP + + + if (m_Codecs.GetCount() == 0) { + int i; + + for (i=0; i<m_Cfg.m_Codecs.GetSize(); ++i) { + m_Codecs.AddString (m_Cfg.m_Codecs.GetAt (i)); + } + + m_Codecs.SetCurSel (0); + } } -BEGIN_MESSAGE_MAP(CSettingsDlg, CDialog) - //{{AFX_MSG_MAP(CSettingsDlg) - ON_BN_CLICKED(IDC_STUN, OnStun) - ON_BN_CLICKED(IDC_ECHO_SUPPRESS, OnEchoSuppress) - ON_CBN_SELCHANGE(IDC_CODECS, OnSelchangeCodecs) - //}}AFX_MSG_MAP +BEGIN_MESSAGE_MAP (CSettingsDlg, CDialog) + //{{AFX_MSG_MAP(CSettingsDlg) + ON_BN_CLICKED (IDC_STUN, OnStun) + ON_BN_CLICKED (IDC_ECHO_SUPPRESS, OnEchoSuppress) + ON_CBN_SELCHANGE (IDC_CODECS, OnSelchangeCodecs) + //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CSettingsDlg message handlers -int CSettingsDlg::DoModal() +int CSettingsDlg::DoModal() { - int rc = CDialog::DoModal(); + int rc = CDialog::DoModal(); return rc; } -void CSettingsDlg::OnStun() +void CSettingsDlg::OnStun() { } -void CSettingsDlg::OnEchoSuppress() +void CSettingsDlg::OnEchoSuppress() { } -void CSettingsDlg::OnSelchangeCodecs() +void CSettingsDlg::OnSelchangeCodecs() { int cur = m_Codecs.GetCurSel(); + if (cur < 1) - return; + return; CString codec; + DWORD N; - m_Codecs.GetLBText(cur, codec); + m_Codecs.GetLBText (cur, codec); + N = m_Codecs.GetCount(); - m_Codecs.DeleteString(cur); + + m_Codecs.DeleteString (cur); + N = m_Codecs.GetCount(); - m_Codecs.InsertString(0, codec); + + m_Codecs.InsertString (0, codec); + N = m_Codecs.GetCount(); - m_Codecs.SetCurSel(0); + + m_Codecs.SetCurSel (0); } -void CSettingsDlg::OnOK() +void CSettingsDlg::OnOK() { - UpdateData(TRUE); + UpdateData (TRUE); m_Cfg.m_Domain = m_Domain; m_Cfg.m_UseIce = m_ICE != 0; @@ -358,7 +399,7 @@ void CSettingsDlg::OnOK() m_Cfg.m_User = m_User; m_Cfg.m_DNS = m_Dns; m_Cfg.m_EchoSuppress= m_EchoSuppress != 0; - m_Cfg.m_EcTail = _ttoi(m_EcTail); + m_Cfg.m_EcTail = _ttoi (m_EcTail); m_Cfg.m_TCP = m_TCP != 0; m_Cfg.m_VAD = m_VAD != 0; m_Cfg.m_AutoAnswer = m_AutoAnswer != 0; @@ -366,10 +407,11 @@ void CSettingsDlg::OnOK() unsigned i; m_Cfg.m_Codecs.RemoveAll(); DWORD N = m_Codecs.GetCount(); + for (i=0; i<N; ++i) { - CString codec; - m_Codecs.GetLBText(i, codec); - m_Cfg.m_Codecs.Add(codec); + CString codec; + m_Codecs.GetLBText (i, codec); + m_Cfg.m_Codecs.Add (codec); } CDialog::OnOK(); diff --git a/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua/main_symbian.cpp b/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua/main_symbian.cpp index b1b884286cac3137827bd10a5cd42839b9d89007..75b85cab1c8c21cd04811f88fc44932da5c344f5 100644 --- a/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua/main_symbian.cpp +++ b/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua/main_symbian.cpp @@ -1,5 +1,5 @@ /* $Id: main_symbian.cpp 2673 2009-05-05 10:46:51Z nanang $ */ -/* +/* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org> * @@ -15,7 +15,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "ua.h" @@ -30,7 +30,7 @@ CConsoleBase* console; // Needed by APS //TPtrC APP_UID = _L("200235D3"); -TPtrC APP_UID = _L("A000000D"); +TPtrC APP_UID = _L ("A000000D"); //////////////////////////////////////////////////////////////////////////// @@ -38,13 +38,13 @@ TPtrC APP_UID = _L("A000000D"); LOCAL_C void DoStartL() { CActiveScheduler *scheduler = new (ELeave) CActiveScheduler; - CleanupStack::PushL(scheduler); - CActiveScheduler::Install(scheduler); + CleanupStack::PushL (scheduler); + CActiveScheduler::Install (scheduler); ua_main(); - - CActiveScheduler::Install(NULL); - CleanupStack::Pop(scheduler); + + CActiveScheduler::Install (NULL); + CleanupStack::Pop (scheduler); delete scheduler; } @@ -61,22 +61,26 @@ GLDEF_C TInt E32Main() CTrapCleanup* cleanup = CTrapCleanup::New(); // Create output console - TRAPD(createError, console = Console::NewL(_L("Console"), TSize(KConsFullScreen,KConsFullScreen))); + TRAPD (createError, console = Console::NewL (_L ("Console"), TSize (KConsFullScreen,KConsFullScreen))); + if (createError) return createError; - TRAPD(startError, DoStartL()); + TRAPD (startError, DoStartL()); + + console->Printf (_L ("[press any key to close]\n")); - console->Printf(_L("[press any key to close]\n")); console->Getch(); - + delete console; + delete cleanup; - CloseSTDLIB(); + CloseSTDLIB(); // Mark end of heap usage, detect memory leaks __UHEAP_MARKEND; + return KErrNone; } diff --git a/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua/ua.cpp b/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua/ua.cpp index a86bfa040364ffa1b7843402fd8b7c974924958f..3b2182bc11d686be8d2b9a7525ce1de0adef5a34 100644 --- a/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua/ua.cpp +++ b/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua/ua.cpp @@ -1,5 +1,5 @@ /* $Id: ua.cpp 2781 2009-06-22 14:06:40Z nanang $ */ -/* +/* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org> * @@ -15,7 +15,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <pjsua-lib/pjsua.h> #include <pjsua-lib/pjsua_internal.h> @@ -66,15 +66,15 @@ // // STUN server #if 0 - // Use this to have the STUN server resolved normally +// Use this to have the STUN server resolved normally # define STUN_DOMAIN NULL # define STUN_SERVER "stun.pjsip.org" #elif 0 - // Use this to have the STUN server resolved with DNS SRV +// Use this to have the STUN server resolved with DNS SRV # define STUN_DOMAIN "pjsip.org" # define STUN_SERVER NULL #else - // Use this to disable STUN +// Use this to disable STUN # define STUN_DOMAIN NULL # define STUN_SERVER NULL #endif @@ -98,179 +98,180 @@ static pjsua_buddy_id g_buddy_id = PJSUA_INVALID_ID; /* Callback called by the library upon receiving incoming call */ -static void on_incoming_call(pjsua_acc_id acc_id, pjsua_call_id call_id, - pjsip_rx_data *rdata) +static void on_incoming_call (pjsua_acc_id acc_id, pjsua_call_id call_id, + pjsip_rx_data *rdata) { pjsua_call_info ci; - PJ_UNUSED_ARG(acc_id); - PJ_UNUSED_ARG(rdata); + PJ_UNUSED_ARG (acc_id); + PJ_UNUSED_ARG (rdata); if (g_call_id != PJSUA_INVALID_ID) { - pjsua_call_answer(call_id, PJSIP_SC_BUSY_HERE, NULL, NULL); - return; + pjsua_call_answer (call_id, PJSIP_SC_BUSY_HERE, NULL, NULL); + return; } - - pjsua_call_get_info(call_id, &ci); - PJ_LOG(3,(THIS_FILE, "Incoming call from %.*s!!", - (int)ci.remote_info.slen, - ci.remote_info.ptr)); + pjsua_call_get_info (call_id, &ci); + + PJ_LOG (3, (THIS_FILE, "Incoming call from %.*s!!", + (int) ci.remote_info.slen, + ci.remote_info.ptr)); g_call_id = call_id; - + /* Automatically answer incoming calls with 180/Ringing */ - pjsua_call_answer(call_id, 180, NULL, NULL); + pjsua_call_answer (call_id, 180, NULL, NULL); } /* Callback called by the library when call's state has changed */ -static void on_call_state(pjsua_call_id call_id, pjsip_event *e) +static void on_call_state (pjsua_call_id call_id, pjsip_event *e) { pjsua_call_info ci; - PJ_UNUSED_ARG(e); + PJ_UNUSED_ARG (e); + + pjsua_call_get_info (call_id, &ci); - pjsua_call_get_info(call_id, &ci); - if (ci.state == PJSIP_INV_STATE_DISCONNECTED) { - if (call_id == g_call_id) - g_call_id = PJSUA_INVALID_ID; + if (call_id == g_call_id) + g_call_id = PJSUA_INVALID_ID; } else if (ci.state != PJSIP_INV_STATE_INCOMING) { - if (g_call_id == PJSUA_INVALID_ID) - g_call_id = call_id; + if (g_call_id == PJSUA_INVALID_ID) + g_call_id = call_id; } - - PJ_LOG(3,(THIS_FILE, "Call %d state=%.*s", call_id, - (int)ci.state_text.slen, - ci.state_text.ptr)); + + PJ_LOG (3, (THIS_FILE, "Call %d state=%.*s", call_id, + + (int) ci.state_text.slen, + ci.state_text.ptr)); } /* Callback called by the library when call's media state has changed */ -static void on_call_media_state(pjsua_call_id call_id) +static void on_call_media_state (pjsua_call_id call_id) { pjsua_call_info ci; - pjsua_call_get_info(call_id, &ci); + pjsua_call_get_info (call_id, &ci); if (ci.media_status == PJSUA_CALL_MEDIA_ACTIVE) { - // When media is active, connect call to sound device. - pjsua_conf_connect(ci.conf_slot, 0); - pjsua_conf_connect(0, ci.conf_slot); + // When media is active, connect call to sound device. + pjsua_conf_connect (ci.conf_slot, 0); + pjsua_conf_connect (0, ci.conf_slot); } } /* Handler on buddy state changed. */ -static void on_buddy_state(pjsua_buddy_id buddy_id) +static void on_buddy_state (pjsua_buddy_id buddy_id) { pjsua_buddy_info info; - pjsua_buddy_get_info(buddy_id, &info); + pjsua_buddy_get_info (buddy_id, &info); - PJ_LOG(3,(THIS_FILE, "%.*s status is %.*s", - (int)info.uri.slen, - info.uri.ptr, - (int)info.status_text.slen, - info.status_text.ptr)); + PJ_LOG (3, (THIS_FILE, "%.*s status is %.*s", + (int) info.uri.slen, + info.uri.ptr, + (int) info.status_text.slen, + info.status_text.ptr)); } /* Incoming IM message (i.e. MESSAGE request)! */ -static void on_pager(pjsua_call_id call_id, const pj_str_t *from, - const pj_str_t *to, const pj_str_t *contact, - const pj_str_t *mime_type, const pj_str_t *text) +static void on_pager (pjsua_call_id call_id, const pj_str_t *from, + const pj_str_t *to, const pj_str_t *contact, + const pj_str_t *mime_type, const pj_str_t *text) { /* Note: call index may be -1 */ - PJ_UNUSED_ARG(call_id); - PJ_UNUSED_ARG(to); - PJ_UNUSED_ARG(contact); - PJ_UNUSED_ARG(mime_type); - - PJ_LOG(3,(THIS_FILE,"MESSAGE from %.*s: %.*s", - (int)from->slen, from->ptr, - (int)text->slen, text->ptr)); + PJ_UNUSED_ARG (call_id); + PJ_UNUSED_ARG (to); + PJ_UNUSED_ARG (contact); + PJ_UNUSED_ARG (mime_type); + + PJ_LOG (3, (THIS_FILE,"MESSAGE from %.*s: %.*s", + (int) from->slen, from->ptr, + (int) text->slen, text->ptr)); } /* Received typing indication */ -static void on_typing(pjsua_call_id call_id, const pj_str_t *from, - const pj_str_t *to, const pj_str_t *contact, - pj_bool_t is_typing) +static void on_typing (pjsua_call_id call_id, const pj_str_t *from, + const pj_str_t *to, const pj_str_t *contact, + pj_bool_t is_typing) { - PJ_UNUSED_ARG(call_id); - PJ_UNUSED_ARG(to); - PJ_UNUSED_ARG(contact); + PJ_UNUSED_ARG (call_id); + PJ_UNUSED_ARG (to); + PJ_UNUSED_ARG (contact); - PJ_LOG(3,(THIS_FILE, "IM indication: %.*s %s", - (int)from->slen, from->ptr, - (is_typing?"is typing..":"has stopped typing"))); + PJ_LOG (3, (THIS_FILE, "IM indication: %.*s %s", + (int) from->slen, from->ptr, + (is_typing?"is typing..":"has stopped typing"))); } /* Call transfer request status. */ -static void on_call_transfer_status(pjsua_call_id call_id, - int status_code, - const pj_str_t *status_text, - pj_bool_t final, - pj_bool_t *p_cont) +static void on_call_transfer_status (pjsua_call_id call_id, + int status_code, + const pj_str_t *status_text, + pj_bool_t final, + pj_bool_t *p_cont) { - PJ_LOG(3,(THIS_FILE, "Call %d: transfer status=%d (%.*s) %s", - call_id, status_code, - (int)status_text->slen, status_text->ptr, - (final ? "[final]" : ""))); + PJ_LOG (3, (THIS_FILE, "Call %d: transfer status=%d (%.*s) %s", + call_id, status_code, + (int) status_text->slen, status_text->ptr, + (final ? "[final]" : ""))); if (status_code/100 == 2) { - PJ_LOG(3,(THIS_FILE, - "Call %d: call transfered successfully, disconnecting call", - call_id)); - pjsua_call_hangup(call_id, PJSIP_SC_GONE, NULL, NULL); - *p_cont = PJ_FALSE; + PJ_LOG (3, (THIS_FILE, + "Call %d: call transfered successfully, disconnecting call", + call_id)); + pjsua_call_hangup (call_id, PJSIP_SC_GONE, NULL, NULL); + *p_cont = PJ_FALSE; } } /* NAT detection result */ -static void on_nat_detect(const pj_stun_nat_detect_result *res) +static void on_nat_detect (const pj_stun_nat_detect_result *res) { if (res->status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "NAT detection failed", res->status); + pjsua_perror (THIS_FILE, "NAT detection failed", res->status); } else { - PJ_LOG(3, (THIS_FILE, "NAT detected as %s", res->nat_type_name)); - } + PJ_LOG (3, (THIS_FILE, "NAT detected as %s", res->nat_type_name)); + } } /* Notification that call is being replaced. */ -static void on_call_replaced(pjsua_call_id old_call_id, - pjsua_call_id new_call_id) +static void on_call_replaced (pjsua_call_id old_call_id, + pjsua_call_id new_call_id) { pjsua_call_info old_ci, new_ci; - pjsua_call_get_info(old_call_id, &old_ci); - pjsua_call_get_info(new_call_id, &new_ci); + pjsua_call_get_info (old_call_id, &old_ci); + pjsua_call_get_info (new_call_id, &new_ci); - PJ_LOG(3,(THIS_FILE, "Call %d with %.*s is being replaced by " - "call %d with %.*s", - old_call_id, - (int)old_ci.remote_info.slen, old_ci.remote_info.ptr, - new_call_id, - (int)new_ci.remote_info.slen, new_ci.remote_info.ptr)); + PJ_LOG (3, (THIS_FILE, "Call %d with %.*s is being replaced by " + "call %d with %.*s", + old_call_id, + (int) old_ci.remote_info.slen, old_ci.remote_info.ptr, + new_call_id, + (int) new_ci.remote_info.slen, new_ci.remote_info.ptr)); } //#include<e32debug.h> /* Logging callback */ -static void log_writer(int level, const char *buf, int len) +static void log_writer (int level, const char *buf, int len) { static wchar_t buf16[PJ_LOG_MAX_SIZE]; - PJ_UNUSED_ARG(level); - - pj_ansi_to_unicode(buf, len, buf16, PJ_ARRAY_SIZE(buf16)); + PJ_UNUSED_ARG (level); - TPtrC16 aBuf((const TUint16*)buf16, (TInt)len); + pj_ansi_to_unicode (buf, len, buf16, PJ_ARRAY_SIZE (buf16)); + + TPtrC16 aBuf ( (const TUint16*) buf16, (TInt) len); //RDebug::Print(aBuf); - console->Write(aBuf); - + console->Write (aBuf); + } /* @@ -283,63 +284,79 @@ static pj_status_t app_startup() pj_status_t status; /* Redirect log before pjsua_init() */ - pj_log_set_log_func(&log_writer); - + pj_log_set_log_func (&log_writer); + /* Set log level */ - pj_log_set_level(CON_LOG_LEVEL); + pj_log_set_level (CON_LOG_LEVEL); /* Create pjsua first! */ status = pjsua_create(); + if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "pjsua_create() error", status); - return status; + pjsua_perror (THIS_FILE, "pjsua_create() error", status); + return status; } /* Init pjsua */ pjsua_config cfg; + pjsua_logging_config log_cfg; + pjsua_media_config med_cfg; - pjsua_config_default(&cfg); + pjsua_config_default (&cfg); + cfg.max_calls = 2; + cfg.thread_cnt = 0; // Disable threading on Symbian + cfg.use_srtp = USE_SRTP; + cfg.srtp_secure_signaling = 0; - + cfg.cb.on_incoming_call = &on_incoming_call; + cfg.cb.on_call_media_state = &on_call_media_state; + cfg.cb.on_call_state = &on_call_state; + cfg.cb.on_buddy_state = &on_buddy_state; + cfg.cb.on_pager = &on_pager; + cfg.cb.on_typing = &on_typing; + cfg.cb.on_call_transfer_status = &on_call_transfer_status; + cfg.cb.on_call_replaced = &on_call_replaced; + cfg.cb.on_nat_detect = &on_nat_detect; - + if (SIP_PROXY) { - cfg.outbound_proxy_cnt = 1; - cfg.outbound_proxy[0] = pj_str(SIP_PROXY); + cfg.outbound_proxy_cnt = 1; + cfg.outbound_proxy[0] = pj_str (SIP_PROXY); } - + if (NAMESERVER) { - cfg.nameserver_count = 1; - cfg.nameserver[0] = pj_str(NAMESERVER); + cfg.nameserver_count = 1; + cfg.nameserver[0] = pj_str (NAMESERVER); } - + if (NAMESERVER && STUN_DOMAIN) { - cfg.stun_domain = pj_str(STUN_DOMAIN); + cfg.stun_domain = pj_str (STUN_DOMAIN); } else if (STUN_SERVER) { - cfg.stun_host = pj_str(STUN_SERVER); + cfg.stun_host = pj_str (STUN_SERVER); } - - - pjsua_logging_config_default(&log_cfg); + + + pjsua_logging_config_default (&log_cfg); + log_cfg.level = FILE_LOG_LEVEL; log_cfg.console_level = CON_LOG_LEVEL; log_cfg.cb = &log_writer; - log_cfg.log_filename = pj_str("C:\\data\\symbian_ua.log"); + log_cfg.log_filename = pj_str ("C:\\data\\symbian_ua.log"); - pjsua_media_config_default(&med_cfg); + pjsua_media_config_default (&med_cfg); med_cfg.thread_cnt = 0; // Disable threading on Symbian med_cfg.has_ioqueue = PJ_FALSE; med_cfg.clock_rate = 8000; @@ -348,100 +365,112 @@ static pj_status_t app_startup() med_cfg.enable_ice = USE_ICE; med_cfg.snd_auto_close_time = 0; // wait for 0 seconds idle before sound dev get auto-closed //med_cfg.no_vad = PJ_TRUE; - - status = pjsua_init(&cfg, &log_cfg, &med_cfg); + + status = pjsua_init (&cfg, &log_cfg, &med_cfg); + if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "pjsua_init() error", status); - pjsua_destroy(); - return status; + pjsua_perror (THIS_FILE, "pjsua_init() error", status); + pjsua_destroy(); + return status; } - + /* Adjust Speex priority and enable only the narrowband */ { - pj_str_t codec_id = pj_str("speex/8000"); - pjmedia_codec_mgr_set_codec_priority( - pjmedia_endpt_get_codec_mgr(pjsua_var.med_endpt), - &codec_id, PJMEDIA_CODEC_PRIO_NORMAL+1); - - codec_id = pj_str("speex/16000"); - pjmedia_codec_mgr_set_codec_priority( - pjmedia_endpt_get_codec_mgr(pjsua_var.med_endpt), - &codec_id, PJMEDIA_CODEC_PRIO_DISABLED); - - codec_id = pj_str("speex/32000"); - pjmedia_codec_mgr_set_codec_priority( - pjmedia_endpt_get_codec_mgr(pjsua_var.med_endpt), - &codec_id, PJMEDIA_CODEC_PRIO_DISABLED); + pj_str_t codec_id = pj_str ("speex/8000"); + pjmedia_codec_mgr_set_codec_priority ( + pjmedia_endpt_get_codec_mgr (pjsua_var.med_endpt), + &codec_id, PJMEDIA_CODEC_PRIO_NORMAL+1); + + codec_id = pj_str ("speex/16000"); + pjmedia_codec_mgr_set_codec_priority ( + pjmedia_endpt_get_codec_mgr (pjsua_var.med_endpt), + &codec_id, PJMEDIA_CODEC_PRIO_DISABLED); + + codec_id = pj_str ("speex/32000"); + pjmedia_codec_mgr_set_codec_priority ( + pjmedia_endpt_get_codec_mgr (pjsua_var.med_endpt), + &codec_id, PJMEDIA_CODEC_PRIO_DISABLED); } - + /* Add UDP transport. */ pjsua_transport_config tcfg; + pjsua_transport_id tid; - pjsua_transport_config_default(&tcfg); + pjsua_transport_config_default (&tcfg); + tcfg.port = SIP_PORT; - status = pjsua_transport_create(PJSIP_TRANSPORT_UDP, &tcfg, &tid); + + status = pjsua_transport_create (PJSIP_TRANSPORT_UDP, &tcfg, &tid); + if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error creating UDP transport", status); - pjsua_destroy(); - return status; + pjsua_perror (THIS_FILE, "Error creating UDP transport", status); + pjsua_destroy(); + return status; } /* Add TCP transport */ #if ENABLE_SIP_TCP - pjsua_transport_config_default(&tcfg); + pjsua_transport_config_default (&tcfg); + tcfg.port = SIP_PORT; - status = pjsua_transport_create(PJSIP_TRANSPORT_TCP, &tcfg, &tid); + + status = pjsua_transport_create (PJSIP_TRANSPORT_TCP, &tcfg, &tid); + if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error creating TCP transport", status); - pjsua_destroy(); - return status; + pjsua_perror (THIS_FILE, "Error creating TCP transport", status); + pjsua_destroy(); + return status; } + #endif - + /* Add account for the transport */ - pjsua_acc_add_local(tid, PJ_TRUE, &g_acc_id); + pjsua_acc_add_local (tid, PJ_TRUE, &g_acc_id); /* Initialization is done, now start pjsua */ status = pjsua_start(); + if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error starting pjsua", status); - pjsua_destroy(); - return status; + pjsua_perror (THIS_FILE, "Error starting pjsua", status); + pjsua_destroy(); + return status; } /* Register to SIP server by creating SIP account. */ if (HAS_SIP_ACCOUNT) { - pjsua_acc_config cfg; - - pjsua_acc_config_default(&cfg); - cfg.id = pj_str("sip:" SIP_USER "@" SIP_DOMAIN); - cfg.reg_uri = pj_str("sip:" SIP_DOMAIN); - cfg.cred_count = 1; - cfg.cred_info[0].realm = pj_str("*"); - cfg.cred_info[0].scheme = pj_str("digest"); - cfg.cred_info[0].username = pj_str(SIP_USER); - cfg.cred_info[0].data_type = PJSIP_CRED_DATA_PLAIN_PASSWD; - cfg.cred_info[0].data = pj_str(SIP_PASSWD); - - status = pjsua_acc_add(&cfg, PJ_TRUE, &g_acc_id); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error adding account", status); - pjsua_destroy(); - return status; - } + pjsua_acc_config cfg; + + pjsua_acc_config_default (&cfg); + cfg.id = pj_str ("sip:" SIP_USER "@" SIP_DOMAIN); + cfg.reg_uri = pj_str ("sip:" SIP_DOMAIN); + cfg.cred_count = 1; + cfg.cred_info[0].realm = pj_str ("*"); + cfg.cred_info[0].scheme = pj_str ("digest"); + cfg.cred_info[0].username = pj_str (SIP_USER); + cfg.cred_info[0].data_type = PJSIP_CRED_DATA_PLAIN_PASSWD; + cfg.cred_info[0].data = pj_str (SIP_PASSWD); + + status = pjsua_acc_add (&cfg, PJ_TRUE, &g_acc_id); + + if (status != PJ_SUCCESS) { + pjsua_perror (THIS_FILE, "Error adding account", status); + pjsua_destroy(); + return status; + } } if (SIP_DST_URI) { - pjsua_buddy_config bcfg; - - pjsua_buddy_config_default(&bcfg); - bcfg.uri = pj_str(SIP_DST_URI); - bcfg.subscribe = PJ_FALSE; - - pjsua_buddy_add(&bcfg, &g_buddy_id); + pjsua_buddy_config bcfg; + + pjsua_buddy_config_default (&bcfg); + bcfg.uri = pj_str (SIP_DST_URI); + bcfg.subscribe = PJ_FALSE; + + pjsua_buddy_add (&bcfg, &g_buddy_id); } + return PJ_SUCCESS; } @@ -452,445 +481,486 @@ static pj_status_t app_startup() */ #include <e32base.h> -class ConsoleUI : public CActive +class ConsoleUI : public CActive { -public: - ConsoleUI(CConsoleBase *con); - ~ConsoleUI(); - - // Run console UI - void Run(); - - // Stop - void Stop(); - -protected: - // Cancel asynchronous read. - void DoCancel(); - - // Implementation: called when read has completed. - void RunL(); - -private: - CConsoleBase *con_; + + public: + ConsoleUI (CConsoleBase *con); + ~ConsoleUI(); + + // Run console UI + void Run(); + + // Stop + void Stop(); + + protected: + // Cancel asynchronous read. + void DoCancel(); + + // Implementation: called when read has completed. + void RunL(); + + private: + CConsoleBase *con_; }; -ConsoleUI::ConsoleUI(CConsoleBase *con) -: CActive(EPriorityStandard), con_(con) +ConsoleUI::ConsoleUI (CConsoleBase *con) + : CActive (EPriorityStandard), con_ (con) { - CActiveScheduler::Add(this); + CActiveScheduler::Add (this); } -ConsoleUI::~ConsoleUI() +ConsoleUI::~ConsoleUI() { Stop(); } // Run console UI -void ConsoleUI::Run() +void ConsoleUI::Run() { - con_->Read(iStatus); + con_->Read (iStatus); SetActive(); } // Stop console UI -void ConsoleUI::Stop() +void ConsoleUI::Stop() { Cancel(); } // Cancel asynchronous read. -void ConsoleUI::DoCancel() +void ConsoleUI::DoCancel() { con_->ReadCancel(); } -static void PrintMainMenu() +static void PrintMainMenu() { const char *menu = - "\n\n" - "Main Menu:\n" - " d Enable/disable codecs\n" - " m Call " SIP_DST_URI "\n" - " a Answer call\n" - " g Hangup all calls\n" - " t Toggle audio route\n" + "\n\n" + "Main Menu:\n" + " d Enable/disable codecs\n" + " m Call " SIP_DST_URI "\n" + " a Answer call\n" + " g Hangup all calls\n" + " t Toggle audio route\n" #if !defined(PJMEDIA_CONF_USE_SWITCH_BOARD) || PJMEDIA_CONF_USE_SWITCH_BOARD==0 - " j Toggle loopback audio\n" + " j Toggle loopback audio\n" #endif - "up/dn Increase/decrease output volume\n" - " s Subscribe " SIP_DST_URI "\n" - " S Unsubscribe presence\n" - " o Set account online\n" - " O Set account offline\n" - " w Quit\n"; - - PJ_LOG(3, (THIS_FILE, menu)); + "up/dn Increase/decrease output volume\n" + " s Subscribe " SIP_DST_URI "\n" + " S Unsubscribe presence\n" + " o Set account online\n" + " O Set account offline\n" + " w Quit\n"; + + PJ_LOG (3, (THIS_FILE, menu)); } -static void PrintCodecMenu() +static void PrintCodecMenu() { - const char *menu = - "\n\n" - "Codec Menu:\n" - " a Enable all codecs\n" + const char *menu = + "\n\n" + "Codec Menu:\n" + " a Enable all codecs\n" #if PJMEDIA_HAS_PASSTHROUGH_CODEC_AMR - " d Enable only AMR\n" + " d Enable only AMR\n" #endif #if PJMEDIA_HAS_PASSTHROUGH_CODEC_G729 - " g Enable only G.729\n" + " g Enable only G.729\n" #endif #if PJMEDIA_HAS_PASSTHROUGH_CODEC_ILBC - " j Enable only iLBC\n" + " j Enable only iLBC\n" #endif - " m Enable only Speex\n" - " p Enable only GSM\n" - " t Enable only PCMU\n" - " w Enable only PCMA\n"; - - PJ_LOG(3, (THIS_FILE, menu)); + " m Enable only Speex\n" + " p Enable only GSM\n" + " t Enable only PCMU\n" + " w Enable only PCMA\n"; + + PJ_LOG (3, (THIS_FILE, menu)); } -static void HandleMainMenu(TKeyCode kc) { +static void HandleMainMenu (TKeyCode kc) +{ switch (kc) { - - case EKeyUpArrow: - case EKeyDownArrow: - { - unsigned vol; - pj_status_t status; - - status = pjsua_snd_get_setting( - PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, &vol); - if (status == PJ_SUCCESS) { - if (kc == EKeyUpArrow) - vol = PJ_MIN(100, vol+10); - else - vol = (vol>=10 ? vol-10 : 0); - status = pjsua_snd_set_setting( - PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, - &vol, PJ_TRUE); - } - - if (status == PJ_SUCCESS) { - PJ_LOG(3,(THIS_FILE, "Output volume set to %d", vol)); - } else { - pjsua_perror(THIS_FILE, "Error setting volume", status); - } - } - break; - - case 't': - { - pjmedia_aud_dev_route route; - pj_status_t status; - - status = pjsua_snd_get_setting(PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE, - &route); - - if (status == PJ_SUCCESS) { - if (route == PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER) - route = PJMEDIA_AUD_DEV_ROUTE_EARPIECE; - else - route = PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER; - - status = pjsua_snd_set_setting( - PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE, - &route, PJ_TRUE); - } - - if (status != PJ_SUCCESS) - pjsua_perror(THIS_FILE, "Error switch audio route", status); - } - break; - - case 'j': - { - static pj_bool_t loopback_active = PJ_FALSE; - if (!loopback_active) - pjsua_conf_connect(0, 0); - else - pjsua_conf_disconnect(0, 0); - loopback_active = !loopback_active; - } - break; - - case 'm': - if (g_call_id != PJSUA_INVALID_ID) { - PJ_LOG(3,(THIS_FILE, "Another call is active")); - break; - } - - if (pjsua_verify_sip_url(SIP_DST_URI) == PJ_SUCCESS) { - pj_str_t dst = pj_str(SIP_DST_URI); - pjsua_call_make_call(g_acc_id, &dst, 0, NULL, - NULL, &g_call_id); - } else { - PJ_LOG(3,(THIS_FILE, "Invalid SIP URI")); - } - break; - case 'a': - if (g_call_id != PJSUA_INVALID_ID) - pjsua_call_answer(g_call_id, 200, NULL, NULL); - break; - case 'g': - pjsua_call_hangup_all(); - break; - case 's': - case 'S': - if (g_buddy_id != PJSUA_INVALID_ID) - pjsua_buddy_subscribe_pres(g_buddy_id, kc=='s'); - break; - case 'o': - case 'O': - pjsua_acc_set_online_status(g_acc_id, kc=='o'); - break; - - default: - PJ_LOG(3,(THIS_FILE, "Keycode '%c' (%d) is pressed", kc, kc)); - break; + + case EKeyUpArrow: + + case EKeyDownArrow: { + unsigned vol; + pj_status_t status; + + status = pjsua_snd_get_setting ( + PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, &vol); + + if (status == PJ_SUCCESS) { + if (kc == EKeyUpArrow) + vol = PJ_MIN (100, vol+10); + else + vol = (vol>=10 ? vol-10 : 0); + + status = pjsua_snd_set_setting ( + PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING, + &vol, PJ_TRUE); + } + + if (status == PJ_SUCCESS) { + PJ_LOG (3, (THIS_FILE, "Output volume set to %d", vol)); + } else { + pjsua_perror (THIS_FILE, "Error setting volume", status); + } + } + + break; + + case 't': { + pjmedia_aud_dev_route route; + pj_status_t status; + + status = pjsua_snd_get_setting (PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE, + &route); + + if (status == PJ_SUCCESS) { + if (route == PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER) + route = PJMEDIA_AUD_DEV_ROUTE_EARPIECE; + else + route = PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER; + + status = pjsua_snd_set_setting ( + PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE, + &route, PJ_TRUE); + } + + if (status != PJ_SUCCESS) + pjsua_perror (THIS_FILE, "Error switch audio route", status); + } + + break; + + case 'j': { + static pj_bool_t loopback_active = PJ_FALSE; + + if (!loopback_active) + pjsua_conf_connect (0, 0); + else + pjsua_conf_disconnect (0, 0); + + loopback_active = !loopback_active; + } + + break; + + case 'm': + + if (g_call_id != PJSUA_INVALID_ID) { + PJ_LOG (3, (THIS_FILE, "Another call is active")); + break; + } + + if (pjsua_verify_sip_url (SIP_DST_URI) == PJ_SUCCESS) { + pj_str_t dst = pj_str (SIP_DST_URI); + pjsua_call_make_call (g_acc_id, &dst, 0, NULL, + NULL, &g_call_id); + } else { + PJ_LOG (3, (THIS_FILE, "Invalid SIP URI")); + } + + break; + + case 'a': + + if (g_call_id != PJSUA_INVALID_ID) + pjsua_call_answer (g_call_id, 200, NULL, NULL); + + break; + + case 'g': + pjsua_call_hangup_all(); + + break; + + case 's': + + case 'S': + if (g_buddy_id != PJSUA_INVALID_ID) + pjsua_buddy_subscribe_pres (g_buddy_id, kc=='s'); + + break; + + case 'o': + + case 'O': + pjsua_acc_set_online_status (g_acc_id, kc=='o'); + + break; + + default: + PJ_LOG (3, (THIS_FILE, "Keycode '%c' (%d) is pressed", kc, kc)); + + break; } PrintMainMenu(); } -static void HandleCodecMenu(TKeyCode kc) { +static void HandleCodecMenu (TKeyCode kc) +{ const pj_str_t ID_ALL = {"*", 1}; pj_str_t codec = {NULL, 0}; - + if (kc == 'a') { - pjsua_codec_set_priority(&ID_ALL, PJMEDIA_CODEC_PRIO_NORMAL); - PJ_LOG(3,(THIS_FILE, "All codecs activated")); + pjsua_codec_set_priority (&ID_ALL, PJMEDIA_CODEC_PRIO_NORMAL); + PJ_LOG (3, (THIS_FILE, "All codecs activated")); } else { - switch (kc) { - case 'd': - codec = pj_str("AMR"); - break; - case 'g': - codec = pj_str("G729"); - break; - case 'j': - codec = pj_str("ILBC"); - break; - case 'm': - codec = pj_str("SPEEX/8000"); - break; - case 'p': - codec = pj_str("GSM"); - break; - case 't': - codec = pj_str("PCMU"); - break; - case 'w': - codec = pj_str("PCMA"); - break; - default: - PJ_LOG(3,(THIS_FILE, "Keycode '%c' (%d) is pressed", kc, kc)); - break; - } - - if (codec.slen) { - pj_status_t status; - - pjsua_codec_set_priority(&ID_ALL, PJMEDIA_CODEC_PRIO_DISABLED); - - status = pjsua_codec_set_priority(&codec, - PJMEDIA_CODEC_PRIO_NORMAL); - if (status == PJ_SUCCESS) - PJ_LOG(3,(THIS_FILE, "%s activated", codec.ptr)); - else - PJ_LOG(3,(THIS_FILE, "Failed activating %s, err=%d", - codec.ptr, status)); - } + switch (kc) { + + case 'd': + codec = pj_str ("AMR"); + break; + + case 'g': + codec = pj_str ("G729"); + break; + + case 'j': + codec = pj_str ("ILBC"); + break; + + case 'm': + codec = pj_str ("SPEEX/8000"); + break; + + case 'p': + codec = pj_str ("GSM"); + break; + + case 't': + codec = pj_str ("PCMU"); + break; + + case 'w': + codec = pj_str ("PCMA"); + break; + + default: + PJ_LOG (3, (THIS_FILE, "Keycode '%c' (%d) is pressed", kc, kc)); + break; + } + + if (codec.slen) { + pj_status_t status; + + pjsua_codec_set_priority (&ID_ALL, PJMEDIA_CODEC_PRIO_DISABLED); + + status = pjsua_codec_set_priority (&codec, + PJMEDIA_CODEC_PRIO_NORMAL); + + if (status == PJ_SUCCESS) + PJ_LOG (3, (THIS_FILE, "%s activated", codec.ptr)); + else + PJ_LOG (3, (THIS_FILE, "Failed activating %s, err=%d", + codec.ptr, status)); + } } } // Implementation: called when read has completed. -void ConsoleUI::RunL() +void ConsoleUI::RunL() { enum { - MENU_TYPE_MAIN = 0, - MENU_TYPE_CODEC = 1 + MENU_TYPE_MAIN = 0, + MENU_TYPE_CODEC = 1 }; static int menu_type = MENU_TYPE_MAIN; TKeyCode kc = con_->KeyCode(); pj_bool_t reschedule = PJ_TRUE; - + if (menu_type == MENU_TYPE_MAIN) { - if (kc == 'w') { - CActiveScheduler::Stop(); - reschedule = PJ_FALSE; - } else if (kc == 'd') { - menu_type = MENU_TYPE_CODEC; - PrintCodecMenu(); - } else { - HandleMainMenu(kc); - } + if (kc == 'w') { + CActiveScheduler::Stop(); + reschedule = PJ_FALSE; + } else if (kc == 'd') { + menu_type = MENU_TYPE_CODEC; + PrintCodecMenu(); + } else { + HandleMainMenu (kc); + } } else { - HandleCodecMenu(kc); - - menu_type = MENU_TYPE_MAIN; - PrintMainMenu(); + HandleCodecMenu (kc); + + menu_type = MENU_TYPE_MAIN; + PrintMainMenu(); } - + if (reschedule) - Run(); + Run(); } #if 0 // IP networking related testing -static pj_status_t test_addr(void) +static pj_status_t test_addr (void) { - int af; - unsigned i, count; - pj_addrinfo ai[8]; - pj_sockaddr ifs[8]; - const pj_str_t *hostname; - pj_hostent he; - pj_status_t status; - - pj_log_set_log_func(&log_writer); - - status = pj_init(); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "pj_init() error", status); - return status; - } - - af = pj_AF_INET(); - + int af; + unsigned i, count; + pj_addrinfo ai[8]; + pj_sockaddr ifs[8]; + const pj_str_t *hostname; + pj_hostent he; + pj_status_t status; + + pj_log_set_log_func (&log_writer); + + status = pj_init(); + + if (status != PJ_SUCCESS) { + pjsua_perror (THIS_FILE, "pj_init() error", status); + return status; + } + + af = pj_AF_INET(); + #if 0 - pj_in_addr in_addr; - pj_str_t aa = pj_str("1.1.1.1"); - in_addr = pj_inet_addr(&aa); - char *the_addr = pj_inet_ntoa(in_addr); - PJ_LOG(3,(THIS_FILE, "IP addr=%s", the_addr)); - - aa = pj_str("192.168.0.15"); - in_addr = pj_inet_addr(&aa); - the_addr = pj_inet_ntoa(in_addr); - PJ_LOG(3,(THIS_FILE, "IP addr=%s", the_addr)); - - aa = pj_str("2.2.2.2"); - in_addr = pj_inet_addr(&aa); - the_addr = pj_inet_ntoa(in_addr); - PJ_LOG(3,(THIS_FILE, "IP addr=%s", the_addr)); - - return -1; + pj_in_addr in_addr; + pj_str_t aa = pj_str ("1.1.1.1"); + in_addr = pj_inet_addr (&aa); + char *the_addr = pj_inet_ntoa (in_addr); + PJ_LOG (3, (THIS_FILE, "IP addr=%s", the_addr)); + + aa = pj_str ("192.168.0.15"); + in_addr = pj_inet_addr (&aa); + the_addr = pj_inet_ntoa (in_addr); + PJ_LOG (3, (THIS_FILE, "IP addr=%s", the_addr)); + + aa = pj_str ("2.2.2.2"); + in_addr = pj_inet_addr (&aa); + the_addr = pj_inet_ntoa (in_addr); + PJ_LOG (3, (THIS_FILE, "IP addr=%s", the_addr)); + + return -1; #endif - - // Hostname - hostname = pj_gethostname(); - if (hostname == NULL) { - status = PJ_ERESOLVE; - pjsua_perror(THIS_FILE, "pj_gethostname() error", status); - goto on_return; - } - - PJ_LOG(3,(THIS_FILE, "Hostname: %.*s", hostname->slen, hostname->ptr)); - - // Gethostbyname - status = pj_gethostbyname(hostname, &he); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "pj_gethostbyname() error", status); - } else { - PJ_LOG(3,(THIS_FILE, "gethostbyname: %s", - pj_inet_ntoa(*(pj_in_addr*)he.h_addr))); - } - - // Getaddrinfo - count = PJ_ARRAY_SIZE(ai); - status = pj_getaddrinfo(af, hostname, &count, ai); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "pj_getaddrinfo() error", status); - } else { - for (i=0; i<count; ++i) { - char ipaddr[PJ_INET6_ADDRSTRLEN+2]; - PJ_LOG(3,(THIS_FILE, "Addrinfo: %s", - pj_sockaddr_print(&ai[i].ai_addr, ipaddr, sizeof(ipaddr), 2))); - } - } - - // Enum interface - count = PJ_ARRAY_SIZE(ifs); - status = pj_enum_ip_interface(af, &count, ifs); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "pj_enum_ip_interface() error", status); - } else { - for (i=0; i<count; ++i) { - char ipaddr[PJ_INET6_ADDRSTRLEN+2]; - PJ_LOG(3,(THIS_FILE, "Interface: %s", - pj_sockaddr_print(&ifs[i], ipaddr, sizeof(ipaddr), 2))); - } - } - - // Get default iinterface - status = pj_getdefaultipinterface(af, &ifs[0]); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "pj_getdefaultipinterface() error", status); - } else { - char ipaddr[PJ_INET6_ADDRSTRLEN+2]; - PJ_LOG(3,(THIS_FILE, "Default IP: %s", - pj_sockaddr_print(&ifs[0], ipaddr, sizeof(ipaddr), 2))); - } - - // Get default IP address - status = pj_gethostip(af, &ifs[0]); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "pj_gethostip() error", status); - } else { - char ipaddr[PJ_INET6_ADDRSTRLEN+2]; - PJ_LOG(3,(THIS_FILE, "Host IP: %s", - pj_sockaddr_print(&ifs[0], ipaddr, sizeof(ipaddr), 2))); - } - - status = -1; - + + // Hostname + hostname = pj_gethostname(); + + if (hostname == NULL) { + status = PJ_ERESOLVE; + pjsua_perror (THIS_FILE, "pj_gethostname() error", status); + goto on_return; + } + + PJ_LOG (3, (THIS_FILE, "Hostname: %.*s", hostname->slen, hostname->ptr)); + + // Gethostbyname + status = pj_gethostbyname (hostname, &he); + + if (status != PJ_SUCCESS) { + pjsua_perror (THIS_FILE, "pj_gethostbyname() error", status); + } else { + PJ_LOG (3, (THIS_FILE, "gethostbyname: %s", + pj_inet_ntoa (* (pj_in_addr*) he.h_addr))); + } + + // Getaddrinfo + count = PJ_ARRAY_SIZE (ai); + + status = pj_getaddrinfo (af, hostname, &count, ai); + + if (status != PJ_SUCCESS) { + pjsua_perror (THIS_FILE, "pj_getaddrinfo() error", status); + } else { + for (i=0; i<count; ++i) { + char ipaddr[PJ_INET6_ADDRSTRLEN+2]; + PJ_LOG (3, (THIS_FILE, "Addrinfo: %s", + pj_sockaddr_print (&ai[i].ai_addr, ipaddr, sizeof (ipaddr), 2))); + } + } + + // Enum interface + count = PJ_ARRAY_SIZE (ifs); + + status = pj_enum_ip_interface (af, &count, ifs); + + if (status != PJ_SUCCESS) { + pjsua_perror (THIS_FILE, "pj_enum_ip_interface() error", status); + } else { + for (i=0; i<count; ++i) { + char ipaddr[PJ_INET6_ADDRSTRLEN+2]; + PJ_LOG (3, (THIS_FILE, "Interface: %s", + pj_sockaddr_print (&ifs[i], ipaddr, sizeof (ipaddr), 2))); + } + } + + // Get default iinterface + status = pj_getdefaultipinterface (af, &ifs[0]); + + if (status != PJ_SUCCESS) { + pjsua_perror (THIS_FILE, "pj_getdefaultipinterface() error", status); + } else { + char ipaddr[PJ_INET6_ADDRSTRLEN+2]; + PJ_LOG (3, (THIS_FILE, "Default IP: %s", + pj_sockaddr_print (&ifs[0], ipaddr, sizeof (ipaddr), 2))); + } + + // Get default IP address + status = pj_gethostip (af, &ifs[0]); + + if (status != PJ_SUCCESS) { + pjsua_perror (THIS_FILE, "pj_gethostip() error", status); + } else { + char ipaddr[PJ_INET6_ADDRSTRLEN+2]; + PJ_LOG (3, (THIS_FILE, "Host IP: %s", + pj_sockaddr_print (&ifs[0], ipaddr, sizeof (ipaddr), 2))); + } + + status = -1; + on_return: - pj_shutdown(); - return status; + pj_shutdown(); + return status; } + #endif #include <es_sock.h> #if 0 -// Force network connection to use the first IAP, -// this is useful for debugging on emulator without GUI. +// Force network connection to use the first IAP, +// this is useful for debugging on emulator without GUI. // Include commdb.lib & apengine.lib in symbian_ua.mmp file // if this is enabled. #include <apdatahandler.h> -inline void ForceUseFirstIAP() +inline void ForceUseFirstIAP() { TUint32 rank = 1; TUint32 bearers; TUint32 prompt; TUint32 iap; - CCommsDatabase* commDb = CCommsDatabase::NewL(EDatabaseTypeIAP); - CleanupStack::PushL(commDb); + CCommsDatabase* commDb = CCommsDatabase::NewL (EDatabaseTypeIAP); + CleanupStack::PushL (commDb); + + CApDataHandler* apDataHandler = CApDataHandler::NewLC (*commDb); - CApDataHandler* apDataHandler = CApDataHandler::NewLC(*commDb); - TCommDbConnectionDirection direction = ECommDbConnectionDirectionOutgoing; - apDataHandler->GetPreferredIfDbIapTypeL(rank, direction, bearers, prompt, iap); + apDataHandler->GetPreferredIfDbIapTypeL (rank, direction, bearers, prompt, iap); prompt = ECommDbDialogPrefDoNotPrompt; - apDataHandler->SetPreferredIfDbIapTypeL(rank, direction, bearers, (TCommDbDialogPref)prompt, iap, ETrue); - CleanupStack::PopAndDestroy(2); // apDataHandler, commDb + apDataHandler->SetPreferredIfDbIapTypeL (rank, direction, bearers, (TCommDbDialogPref) prompt, iap, ETrue); + CleanupStack::PopAndDestroy (2); // apDataHandler, commDb } -static void SelectIAP() +static void SelectIAP() { ForceUseFirstIAP(); } #else -static void SelectIAP() +static void SelectIAP() { } @@ -899,96 +969,108 @@ static void SelectIAP() // Class CConnMon to monitor network connection (RConnection). Whenever // the connection is down, it will notify PJLIB and restart PJSUA-LIB. -class CConnMon : public CActive { -public: - static CConnMon* NewL(RConnection &conn, RSocketServ &sserver) { - CConnMon *self = new (ELeave) CConnMon(conn, sserver); - CleanupStack::PushL(self); - self->ConstructL(); - CleanupStack::Pop(self); - return self; - } - - void Start() { - conn_.ProgressNotification(nif_progress_, iStatus); - SetActive(); - } - - void Stop() { - Cancel(); - } - - ~CConnMon() { Stop(); } - -private: - CConnMon(RConnection &conn, RSocketServ &sserver) : - CActive(EPriorityHigh), - conn_(conn), - sserver_(sserver) - { - CActiveScheduler::Add(this); - } - - void ConstructL() {} - void DoCancel() { - conn_.CancelProgressNotification(); - } +class CConnMon : public CActive +{ - void RunL() { - int stage = nif_progress_().iStage; - - if (stage == KLinkLayerClosed) { - pj_status_t status; - TInt err; - - // Tell pjlib that connection is down. - pj_symbianos_set_connection_status(PJ_FALSE); - - PJ_LOG(3, (THIS_FILE, "RConnection closed, restarting PJSUA..")); - - // Destroy pjsua - pjsua_destroy(); - PJ_LOG(3, (THIS_FILE, "PJSUA destroyed.")); - - // Reopen the connection - err = conn_.Open(sserver_); - if (err == KErrNone) - err = conn_.Start(); - if (err != KErrNone) { - CActiveScheduler::Stop(); - return; - } - - // Reinit Symbian OS param before pj_init() - pj_symbianos_params sym_params; - pj_bzero(&sym_params, sizeof(sym_params)); - sym_params.rsocketserv = &sserver_; - sym_params.rconnection = &conn_; - pj_symbianos_set_params(&sym_params); - - // Reinit pjsua - status = app_startup(); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "app_startup() error", status); - CActiveScheduler::Stop(); - return; - } - - PJ_LOG(3, (THIS_FILE, "PJSUA restarted.")); - PrintMainMenu(); - } - - Start(); - } - - RConnection& conn_; - RSocketServ& sserver_; - TNifProgressBuf nif_progress_; + public: + static CConnMon* NewL (RConnection &conn, RSocketServ &sserver) { + CConnMon *self = new (ELeave) CConnMon (conn, sserver); + CleanupStack::PushL (self); + self->ConstructL(); + CleanupStack::Pop (self); + return self; + } + + void Start() { + conn_.ProgressNotification (nif_progress_, iStatus); + SetActive(); + } + + void Stop() { + Cancel(); + } + + ~CConnMon() { + Stop(); + } + + private: + CConnMon (RConnection &conn, RSocketServ &sserver) : + CActive (EPriorityHigh), + conn_ (conn), + sserver_ (sserver) { + CActiveScheduler::Add (this); + } + + void ConstructL() {} + + void DoCancel() { + conn_.CancelProgressNotification(); + } + + void RunL() { + int stage = nif_progress_().iStage; + + if (stage == KLinkLayerClosed) { + pj_status_t status; + TInt err; + + // Tell pjlib that connection is down. + pj_symbianos_set_connection_status (PJ_FALSE); + + PJ_LOG (3, (THIS_FILE, "RConnection closed, restarting PJSUA..")); + + // Destroy pjsua + pjsua_destroy(); + PJ_LOG (3, (THIS_FILE, "PJSUA destroyed.")); + + // Reopen the connection + err = conn_.Open (sserver_); + + if (err == KErrNone) + err = conn_.Start(); + + if (err != KErrNone) { + CActiveScheduler::Stop(); + return; + } + + // Reinit Symbian OS param before pj_init() + pj_symbianos_params sym_params; + + pj_bzero (&sym_params, sizeof (sym_params)); + + sym_params.rsocketserv = &sserver_; + + sym_params.rconnection = &conn_; + + pj_symbianos_set_params (&sym_params); + + // Reinit pjsua + status = app_startup(); + + if (status != PJ_SUCCESS) { + pjsua_perror (THIS_FILE, "app_startup() error", status); + CActiveScheduler::Stop(); + return; + } + + PJ_LOG (3, (THIS_FILE, "PJSUA restarted.")); + + PrintMainMenu(); + } + + Start(); + } + + RConnection& conn_; + RSocketServ& sserver_; + TNifProgressBuf nif_progress_; }; //////////////////////////////////////////////////////////////////////////// -int ua_main() +int ua_main() { RSocketServ aSocketServer; RConnection aConn; @@ -997,81 +1079,94 @@ int ua_main() pj_status_t status; SelectIAP(); - + // Initialize RSocketServ - if ((err=aSocketServer.Connect()) != KErrNone) - return PJ_STATUS_FROM_OS(err); - + + if ( (err=aSocketServer.Connect()) != KErrNone) + return PJ_STATUS_FROM_OS (err); + // Open up a connection - if ((err=aConn.Open(aSocketServer)) != KErrNone) { - aSocketServer.Close(); - return PJ_STATUS_FROM_OS(err); + if ( (err=aConn.Open (aSocketServer)) != KErrNone) { + aSocketServer.Close(); + return PJ_STATUS_FROM_OS (err); } - - if ((err=aConn.Start()) != KErrNone) { - aSocketServer.Close(); - return PJ_STATUS_FROM_OS(err); + + if ( (err=aConn.Start()) != KErrNone) { + aSocketServer.Close(); + return PJ_STATUS_FROM_OS (err); } - + // Set Symbian OS parameters in pjlib. // This must be done before pj_init() is called. - pj_bzero(&sym_params, sizeof(sym_params)); + pj_bzero (&sym_params, sizeof (sym_params)); + sym_params.rsocketserv = &aSocketServer; + sym_params.rconnection = &aConn; - pj_symbianos_set_params(&sym_params); - + + pj_symbianos_set_params (&sym_params); + // Initialize pjsua status = app_startup(); + //status = test_addr(); if (status != PJ_SUCCESS) { - aConn.Close(); - aSocketServer.Close(); - return status; + aConn.Close(); + aSocketServer.Close(); + return status; } - + // Run the UI - ConsoleUI *con = new ConsoleUI(console); - + ConsoleUI *con = new ConsoleUI (console); + con->Run(); + PrintMainMenu(); // Init & start connection monitor - CConnMon *connmon = CConnMon::NewL(aConn, aSocketServer); + CConnMon *connmon = CConnMon::NewL (aConn, aSocketServer); + connmon->Start(); CActiveScheduler::Start(); - + delete connmon; + delete con; // Dump memory statistics - PJ_LOG(3,(THIS_FILE, "Max heap usage: %u.%03uMB", - pjsua_var.cp.peak_used_size / 1000000, - (pjsua_var.cp.peak_used_size % 1000000)/1000)); - + PJ_LOG (3, (THIS_FILE, "Max heap usage: %u.%03uMB", + pjsua_var.cp.peak_used_size / 1000000, + (pjsua_var.cp.peak_used_size % 1000000) /1000)); + // check max stack usage #if defined(PJ_OS_HAS_CHECK_STACK) && PJ_OS_HAS_CHECK_STACK!=0 - pj_thread_t* this_thread = pj_thread_this(); - if (!this_thread) - return status; - - const char* max_stack_file; - int max_stack_line; - status = pj_thread_get_stack_info(this_thread, &max_stack_file, &max_stack_line); - - PJ_LOG(3,(THIS_FILE, "Max stack usage: %u at %s:%d", - pj_thread_get_stack_max_usage(this_thread), - max_stack_file, max_stack_line)); + pj_thread_t* this_thread = pj_thread_this(); + + if (!this_thread) + return status; + + const char* max_stack_file; + + int max_stack_line; + + status = pj_thread_get_stack_info (this_thread, &max_stack_file, &max_stack_line); + + PJ_LOG (3, (THIS_FILE, "Max stack usage: %u at %s:%d", + pj_thread_get_stack_max_usage (this_thread), + max_stack_file, max_stack_line)); + #endif - + // Shutdown pjsua pjsua_destroy(); - + // Close connection and socket server aConn.Close(); + aSocketServer.Close(); - + return status; } diff --git a/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/Symbian_ua_guiSettingItemListSets.cpp b/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/Symbian_ua_guiSettingItemListSets.cpp index 6d7522938b924bc781abb0d7ae49544c8af38811..69d842c37df7062f36df385435f9c5b97caf0431 100644 --- a/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/Symbian_ua_guiSettingItemListSets.cpp +++ b/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/Symbian_ua_guiSettingItemListSets.cpp @@ -3,16 +3,16 @@ Name : Symbian_ua_guiSettingItemListSettings.cpp Author : nanang Copyright : (c) 2008-2009 Teluu Inc. - Description : + Description : ======================================================================== */ /** - * Generated helper class which manages the settings contained + * Generated helper class which manages the settings contained * in 'symbian_ua_guiSettingItemList'. Each CAknSettingItem maintains * a reference to data in this class so that changes in the setting * item list can be synchronized with this storage. */ - + // [[[ begin generated region: do not modify [Generated Includes] #include <e32base.h> #include <stringloader.h> @@ -25,120 +25,123 @@ * C/C++ constructor for settings data, cannot throw */ TSymbian_ua_guiSettingItemListSettings::TSymbian_ua_guiSettingItemListSettings() - { - } +{ +} /** * Two-phase constructor for settings data */ TSymbian_ua_guiSettingItemListSettings* TSymbian_ua_guiSettingItemListSettings::NewL() - { - TSymbian_ua_guiSettingItemListSettings* data = new( ELeave ) TSymbian_ua_guiSettingItemListSettings; - CleanupStack::PushL( data ); - data->ConstructL(); - CleanupStack::Pop( data ); - return data; - } - +{ + TSymbian_ua_guiSettingItemListSettings* data = new (ELeave) TSymbian_ua_guiSettingItemListSettings; + CleanupStack::PushL (data); + data->ConstructL(); + CleanupStack::Pop (data); + return data; +} + /** * Second phase for initializing settings data */ void TSymbian_ua_guiSettingItemListSettings::ConstructL() - { - // [[[ begin generated region: do not modify [Generated Initializers] - { - HBufC* text = StringLoader::LoadLC( R_SYMBIAN_UA_GUI_SETTING_ITEM_LIST_ED_REGISTRAR ); - SetEd_registrar( text->Des() ); - CleanupStack::PopAndDestroy( text ); - } - { - HBufC* text = StringLoader::LoadLC( R_SYMBIAN_UA_GUI_SETTING_ITEM_LIST_ED_USER ); - SetEd_user( text->Des() ); - CleanupStack::PopAndDestroy( text ); - } - SetB_srtp( 0 ); - SetB_ice( 0 ); - { - HBufC* text = StringLoader::LoadLC( R_SYMBIAN_UA_GUI_SETTING_ITEM_LIST_ED_STUN_SERVER ); - SetEd_stun_server( text->Des() ); - CleanupStack::PopAndDestroy( text ); - } - // ]]] end generated region [Generated Initializers] - - } - +{ + // [[[ begin generated region: do not modify [Generated Initializers] + { + HBufC* text = StringLoader::LoadLC (R_SYMBIAN_UA_GUI_SETTING_ITEM_LIST_ED_REGISTRAR); + SetEd_registrar (text->Des()); + CleanupStack::PopAndDestroy (text); + } + + { + HBufC* text = StringLoader::LoadLC (R_SYMBIAN_UA_GUI_SETTING_ITEM_LIST_ED_USER); + SetEd_user (text->Des()); + CleanupStack::PopAndDestroy (text); + } + + SetB_srtp (0); + SetB_ice (0); + { + HBufC* text = StringLoader::LoadLC (R_SYMBIAN_UA_GUI_SETTING_ITEM_LIST_ED_STUN_SERVER); + SetEd_stun_server (text->Des()); + CleanupStack::PopAndDestroy (text); + } + + // ]]] end generated region [Generated Initializers] + +} + // [[[ begin generated region: do not modify [Generated Contents] TDes& TSymbian_ua_guiSettingItemListSettings::Ed_registrar() - { - return iEd_registrar; - } - -void TSymbian_ua_guiSettingItemListSettings::SetEd_registrar(const TDesC& aValue) - { - if ( aValue.Length() < KEd_registrarMaxLength) - iEd_registrar.Copy( aValue ); - else - iEd_registrar.Copy( aValue.Ptr(), KEd_registrarMaxLength); - } +{ + return iEd_registrar; +} + +void TSymbian_ua_guiSettingItemListSettings::SetEd_registrar (const TDesC& aValue) +{ + if (aValue.Length() < KEd_registrarMaxLength) + iEd_registrar.Copy (aValue); + else + iEd_registrar.Copy (aValue.Ptr(), KEd_registrarMaxLength); +} TDes& TSymbian_ua_guiSettingItemListSettings::Ed_user() - { - return iEd_user; - } - -void TSymbian_ua_guiSettingItemListSettings::SetEd_user(const TDesC& aValue) - { - if ( aValue.Length() < KEd_userMaxLength) - iEd_user.Copy( aValue ); - else - iEd_user.Copy( aValue.Ptr(), KEd_userMaxLength); - } +{ + return iEd_user; +} + +void TSymbian_ua_guiSettingItemListSettings::SetEd_user (const TDesC& aValue) +{ + if (aValue.Length() < KEd_userMaxLength) + iEd_user.Copy (aValue); + else + iEd_user.Copy (aValue.Ptr(), KEd_userMaxLength); +} TDes& TSymbian_ua_guiSettingItemListSettings::Ed_password() - { - return iEd_password; - } - -void TSymbian_ua_guiSettingItemListSettings::SetEd_password(const TDesC& aValue) - { - if ( aValue.Length() < KEd_passwordMaxLength) - iEd_password.Copy( aValue ); - else - iEd_password.Copy( aValue.Ptr(), KEd_passwordMaxLength); - } +{ + return iEd_password; +} + +void TSymbian_ua_guiSettingItemListSettings::SetEd_password (const TDesC& aValue) +{ + if (aValue.Length() < KEd_passwordMaxLength) + iEd_password.Copy (aValue); + else + iEd_password.Copy (aValue.Ptr(), KEd_passwordMaxLength); +} TBool& TSymbian_ua_guiSettingItemListSettings::B_srtp() - { - return iB_srtp; - } +{ + return iB_srtp; +} -void TSymbian_ua_guiSettingItemListSettings::SetB_srtp(const TBool& aValue) - { - iB_srtp = aValue; - } +void TSymbian_ua_guiSettingItemListSettings::SetB_srtp (const TBool& aValue) +{ + iB_srtp = aValue; +} TBool& TSymbian_ua_guiSettingItemListSettings::B_ice() - { - return iB_ice; - } +{ + return iB_ice; +} -void TSymbian_ua_guiSettingItemListSettings::SetB_ice(const TBool& aValue) - { - iB_ice = aValue; - } +void TSymbian_ua_guiSettingItemListSettings::SetB_ice (const TBool& aValue) +{ + iB_ice = aValue; +} TDes& TSymbian_ua_guiSettingItemListSettings::Ed_stun_server() - { - return iEd_stun_server; - } - -void TSymbian_ua_guiSettingItemListSettings::SetEd_stun_server(const TDesC& aValue) - { - if ( aValue.Length() < KEd_stun_serverMaxLength) - iEd_stun_server.Copy( aValue ); - else - iEd_stun_server.Copy( aValue.Ptr(), KEd_stun_serverMaxLength); - } +{ + return iEd_stun_server; +} + +void TSymbian_ua_guiSettingItemListSettings::SetEd_stun_server (const TDesC& aValue) +{ + if (aValue.Length() < KEd_stun_serverMaxLength) + iEd_stun_server.Copy (aValue); + else + iEd_stun_server.Copy (aValue.Ptr(), KEd_stun_serverMaxLength); +} // ]]] end generated region [Generated Contents] diff --git a/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/symbian_ua.cpp b/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/symbian_ua.cpp index f722336a1b900a640f9aecab638b82c5b60f10cc..1e56a4f9fe5f534dd8c26789f89c068b324c340b 100644 --- a/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/symbian_ua.cpp +++ b/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/symbian_ua.cpp @@ -1,5 +1,5 @@ /* $Id: ua.cpp 1793 2008-02-14 13:39:24Z bennylp $ */ -/* +/* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org> * @@ -15,7 +15,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <pjsua-lib/pjsua.h> #include <pjsua-lib/pjsua_internal.h> @@ -38,222 +38,230 @@ static pjsua_buddy_id g_buddy_id = PJSUA_INVALID_ID; static symbian_ua_info_cb_t g_cb = {NULL, NULL, NULL, NULL, NULL}; -static void log_writer(int level, const char *buf, int len) +static void log_writer (int level, const char *buf, int len) { static wchar_t buf16[PJ_LOG_MAX_SIZE]; - PJ_UNUSED_ARG(level); - + PJ_UNUSED_ARG (level); + if (!g_cb.on_info) - return; + return; + + pj_ansi_to_unicode (buf, len, buf16, PJ_ARRAY_SIZE (buf16)); - pj_ansi_to_unicode(buf, len, buf16, PJ_ARRAY_SIZE(buf16)); - g_cb.on_info(buf16); + g_cb.on_info (buf16); } -static void on_reg_state(pjsua_acc_id acc_id) +static void on_reg_state (pjsua_acc_id acc_id) { pjsua_acc_info acc_info; pj_status_t status; - status = pjsua_acc_get_info(acc_id, &acc_info); + status = pjsua_acc_get_info (acc_id, &acc_info); + if (status != PJ_SUCCESS) - return; + return; if (acc_info.status == 200) { - if (acc_info.expires) { - PJ_LOG(3,(THIS_FILE, "Registration success!")); - if (g_cb.on_reg_state) g_cb.on_reg_state(true); - } else { - PJ_LOG(3,(THIS_FILE, "Unregistration success!")); - if (g_cb.on_unreg_state) g_cb.on_unreg_state(true); - } + if (acc_info.expires) { + PJ_LOG (3, (THIS_FILE, "Registration success!")); + + if (g_cb.on_reg_state) g_cb.on_reg_state (true); + } else { + PJ_LOG (3, (THIS_FILE, "Unregistration success!")); + + if (g_cb.on_unreg_state) g_cb.on_unreg_state (true); + } } else { - if (acc_info.expires) { - PJ_LOG(3,(THIS_FILE, "Registration failed!")); - if (g_cb.on_reg_state) g_cb.on_reg_state(false); - } else { - PJ_LOG(3,(THIS_FILE, "Unregistration failed!")); - if (g_cb.on_unreg_state) g_cb.on_unreg_state(false); - } + if (acc_info.expires) { + PJ_LOG (3, (THIS_FILE, "Registration failed!")); + + if (g_cb.on_reg_state) g_cb.on_reg_state (false); + } else { + PJ_LOG (3, (THIS_FILE, "Unregistration failed!")); + + if (g_cb.on_unreg_state) g_cb.on_unreg_state (false); + } } } /* Callback called by the library upon receiving incoming call */ -static void on_incoming_call(pjsua_acc_id acc_id, pjsua_call_id call_id, - pjsip_rx_data *rdata) +static void on_incoming_call (pjsua_acc_id acc_id, pjsua_call_id call_id, + pjsip_rx_data *rdata) { pjsua_call_info ci; - PJ_UNUSED_ARG(acc_id); - PJ_UNUSED_ARG(rdata); + PJ_UNUSED_ARG (acc_id); + PJ_UNUSED_ARG (rdata); if (g_call_id != PJSUA_INVALID_ID) { - pjsua_call_answer(call_id, PJSIP_SC_BUSY_HERE, NULL, NULL); - return; + pjsua_call_answer (call_id, PJSIP_SC_BUSY_HERE, NULL, NULL); + return; } - - pjsua_call_get_info(call_id, &ci); - PJ_LOG(3,(THIS_FILE, "Incoming call from %.*s!!", - (int)ci.remote_info.slen, - ci.remote_info.ptr)); + pjsua_call_get_info (call_id, &ci); + + PJ_LOG (3, (THIS_FILE, "Incoming call from %.*s!!", + (int) ci.remote_info.slen, + ci.remote_info.ptr)); g_call_id = call_id; - + /* Automatically answer incoming calls with 180/Ringing */ - pjsua_call_answer(call_id, 180, NULL, NULL); + pjsua_call_answer (call_id, 180, NULL, NULL); if (g_cb.on_incoming_call) { - static wchar_t disp[256]; - static wchar_t uri[PJSIP_MAX_URL_SIZE]; + static wchar_t disp[256]; + static wchar_t uri[PJSIP_MAX_URL_SIZE]; - pj_ansi_to_unicode(ci.remote_info.ptr, ci.remote_info.slen, - disp, PJ_ARRAY_SIZE(disp)); - pj_ansi_to_unicode(ci.remote_contact.ptr, ci.remote_contact.slen, - uri, PJ_ARRAY_SIZE(uri)); + pj_ansi_to_unicode (ci.remote_info.ptr, ci.remote_info.slen, + disp, PJ_ARRAY_SIZE (disp)); + pj_ansi_to_unicode (ci.remote_contact.ptr, ci.remote_contact.slen, + uri, PJ_ARRAY_SIZE (uri)); - g_cb.on_incoming_call(disp, uri); + g_cb.on_incoming_call (disp, uri); } } /* Callback called by the library when call's state has changed */ -static void on_call_state(pjsua_call_id call_id, pjsip_event *e) +static void on_call_state (pjsua_call_id call_id, pjsip_event *e) { pjsua_call_info ci; - PJ_UNUSED_ARG(e); + PJ_UNUSED_ARG (e); + + pjsua_call_get_info (call_id, &ci); - pjsua_call_get_info(call_id, &ci); - if (ci.state == PJSIP_INV_STATE_DISCONNECTED) { - if (call_id == g_call_id) - g_call_id = PJSUA_INVALID_ID; - if (g_cb.on_call_end) { - static wchar_t reason[256]; - pj_ansi_to_unicode(ci.last_status_text.ptr, ci.last_status_text.slen, - reason, PJ_ARRAY_SIZE(reason)); - g_cb.on_call_end(reason); - } + if (call_id == g_call_id) + g_call_id = PJSUA_INVALID_ID; + + if (g_cb.on_call_end) { + static wchar_t reason[256]; + pj_ansi_to_unicode (ci.last_status_text.ptr, ci.last_status_text.slen, + reason, PJ_ARRAY_SIZE (reason)); + g_cb.on_call_end (reason); + } } else if (ci.state != PJSIP_INV_STATE_INCOMING) { - if (g_call_id == PJSUA_INVALID_ID) - g_call_id = call_id; + if (g_call_id == PJSUA_INVALID_ID) + g_call_id = call_id; } - - PJ_LOG(3,(THIS_FILE, "Call %d state=%.*s", call_id, - (int)ci.state_text.slen, - ci.state_text.ptr)); + + PJ_LOG (3, (THIS_FILE, "Call %d state=%.*s", call_id, + + (int) ci.state_text.slen, + ci.state_text.ptr)); } /* Callback called by the library when call's media state has changed */ -static void on_call_media_state(pjsua_call_id call_id) +static void on_call_media_state (pjsua_call_id call_id) { pjsua_call_info ci; - pjsua_call_get_info(call_id, &ci); + pjsua_call_get_info (call_id, &ci); if (ci.media_status == PJSUA_CALL_MEDIA_ACTIVE) { - // When media is active, connect call to sound device. - pjsua_conf_connect(ci.conf_slot, 0); - pjsua_conf_connect(0, ci.conf_slot); + // When media is active, connect call to sound device. + pjsua_conf_connect (ci.conf_slot, 0); + pjsua_conf_connect (0, ci.conf_slot); } } /* Handler on buddy state changed. */ -static void on_buddy_state(pjsua_buddy_id buddy_id) +static void on_buddy_state (pjsua_buddy_id buddy_id) { pjsua_buddy_info info; - pjsua_buddy_get_info(buddy_id, &info); + pjsua_buddy_get_info (buddy_id, &info); - PJ_LOG(3,(THIS_FILE, "%.*s status is %.*s", - (int)info.uri.slen, - info.uri.ptr, - (int)info.status_text.slen, - info.status_text.ptr)); + PJ_LOG (3, (THIS_FILE, "%.*s status is %.*s", + (int) info.uri.slen, + info.uri.ptr, + (int) info.status_text.slen, + info.status_text.ptr)); } /* Incoming IM message (i.e. MESSAGE request)! */ -static void on_pager(pjsua_call_id call_id, const pj_str_t *from, - const pj_str_t *to, const pj_str_t *contact, - const pj_str_t *mime_type, const pj_str_t *text) +static void on_pager (pjsua_call_id call_id, const pj_str_t *from, + const pj_str_t *to, const pj_str_t *contact, + const pj_str_t *mime_type, const pj_str_t *text) { /* Note: call index may be -1 */ - PJ_UNUSED_ARG(call_id); - PJ_UNUSED_ARG(to); - PJ_UNUSED_ARG(contact); - PJ_UNUSED_ARG(mime_type); - - PJ_LOG(3,(THIS_FILE,"MESSAGE from %.*s: %.*s", - (int)from->slen, from->ptr, - (int)text->slen, text->ptr)); + PJ_UNUSED_ARG (call_id); + PJ_UNUSED_ARG (to); + PJ_UNUSED_ARG (contact); + PJ_UNUSED_ARG (mime_type); + + PJ_LOG (3, (THIS_FILE,"MESSAGE from %.*s: %.*s", + (int) from->slen, from->ptr, + (int) text->slen, text->ptr)); } /* Received typing indication */ -static void on_typing(pjsua_call_id call_id, const pj_str_t *from, - const pj_str_t *to, const pj_str_t *contact, - pj_bool_t is_typing) +static void on_typing (pjsua_call_id call_id, const pj_str_t *from, + const pj_str_t *to, const pj_str_t *contact, + pj_bool_t is_typing) { - PJ_UNUSED_ARG(call_id); - PJ_UNUSED_ARG(to); - PJ_UNUSED_ARG(contact); + PJ_UNUSED_ARG (call_id); + PJ_UNUSED_ARG (to); + PJ_UNUSED_ARG (contact); - PJ_LOG(3,(THIS_FILE, "IM indication: %.*s %s", - (int)from->slen, from->ptr, - (is_typing?"is typing..":"has stopped typing"))); + PJ_LOG (3, (THIS_FILE, "IM indication: %.*s %s", + (int) from->slen, from->ptr, + (is_typing?"is typing..":"has stopped typing"))); } /* Call transfer request status. */ -static void on_call_transfer_status(pjsua_call_id call_id, - int status_code, - const pj_str_t *status_text, - pj_bool_t final, - pj_bool_t *p_cont) +static void on_call_transfer_status (pjsua_call_id call_id, + int status_code, + const pj_str_t *status_text, + pj_bool_t final, + pj_bool_t *p_cont) { - PJ_LOG(3,(THIS_FILE, "Call %d: transfer status=%d (%.*s) %s", - call_id, status_code, - (int)status_text->slen, status_text->ptr, - (final ? "[final]" : ""))); + PJ_LOG (3, (THIS_FILE, "Call %d: transfer status=%d (%.*s) %s", + call_id, status_code, + (int) status_text->slen, status_text->ptr, + (final ? "[final]" : ""))); if (status_code/100 == 2) { - PJ_LOG(3,(THIS_FILE, - "Call %d: call transfered successfully, disconnecting call", - call_id)); - pjsua_call_hangup(call_id, PJSIP_SC_GONE, NULL, NULL); - *p_cont = PJ_FALSE; + PJ_LOG (3, (THIS_FILE, + "Call %d: call transfered successfully, disconnecting call", + call_id)); + pjsua_call_hangup (call_id, PJSIP_SC_GONE, NULL, NULL); + *p_cont = PJ_FALSE; } } /* NAT detection result */ -static void on_nat_detect(const pj_stun_nat_detect_result *res) +static void on_nat_detect (const pj_stun_nat_detect_result *res) { if (res->status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "NAT detection failed", res->status); + pjsua_perror (THIS_FILE, "NAT detection failed", res->status); } else { - PJ_LOG(3, (THIS_FILE, "NAT detected as %s", res->nat_type_name)); - } + PJ_LOG (3, (THIS_FILE, "NAT detected as %s", res->nat_type_name)); + } } /* Notification that call is being replaced. */ -static void on_call_replaced(pjsua_call_id old_call_id, - pjsua_call_id new_call_id) +static void on_call_replaced (pjsua_call_id old_call_id, + pjsua_call_id new_call_id) { pjsua_call_info old_ci, new_ci; - pjsua_call_get_info(old_call_id, &old_ci); - pjsua_call_get_info(new_call_id, &new_ci); + pjsua_call_get_info (old_call_id, &old_ci); + pjsua_call_get_info (new_call_id, &new_ci); - PJ_LOG(3,(THIS_FILE, "Call %d with %.*s is being replaced by " - "call %d with %.*s", - old_call_id, - (int)old_ci.remote_info.slen, old_ci.remote_info.ptr, - new_call_id, - (int)new_ci.remote_info.slen, new_ci.remote_info.ptr)); + PJ_LOG (3, (THIS_FILE, "Call %d with %.*s is being replaced by " + "call %d with %.*s", + old_call_id, + (int) old_ci.remote_info.slen, old_ci.remote_info.ptr, + new_call_id, + (int) new_ci.remote_info.slen, new_ci.remote_info.ptr)); } int symbian_ua_init() @@ -261,132 +269,167 @@ int symbian_ua_init() TInt err; pj_symbianos_params sym_params; pj_status_t status; - + // Initialize RSocketServ - if ((err=aSocketServer.Connect()) != KErrNone) - return PJ_STATUS_FROM_OS(err); - + + if ( (err=aSocketServer.Connect()) != KErrNone) + return PJ_STATUS_FROM_OS (err); + // Open up a connection - if ((err=aConn.Open(aSocketServer)) != KErrNone) { - aSocketServer.Close(); - return PJ_STATUS_FROM_OS(err); + if ( (err=aConn.Open (aSocketServer)) != KErrNone) { + aSocketServer.Close(); + return PJ_STATUS_FROM_OS (err); } - - if ((err=aConn.Start()) != KErrNone) { - aConn.Close(); - aSocketServer.Close(); - return PJ_STATUS_FROM_OS(err); + + if ( (err=aConn.Start()) != KErrNone) { + aConn.Close(); + aSocketServer.Close(); + return PJ_STATUS_FROM_OS (err); } - + // Set Symbian OS parameters in pjlib. // This must be done before pj_init() is called. - pj_bzero(&sym_params, sizeof(sym_params)); + pj_bzero (&sym_params, sizeof (sym_params)); + sym_params.rsocketserv = &aSocketServer; + sym_params.rconnection = &aConn; - pj_symbianos_set_params(&sym_params); + + pj_symbianos_set_params (&sym_params); /* Redirect log before pjsua_init() */ - pj_log_set_log_func(&log_writer); - + pj_log_set_log_func (&log_writer); + /* Set log level */ - pj_log_set_level(LOG_LEVEL); + pj_log_set_level (LOG_LEVEL); /* Create pjsua first! */ status = pjsua_create(); + if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "pjsua_create() error", status); - return status; + pjsua_perror (THIS_FILE, "pjsua_create() error", status); + return status; } /* Init pjsua */ pjsua_config cfg; - pjsua_config_default(&cfg); + pjsua_config_default (&cfg); + cfg.max_calls = 2; + cfg.thread_cnt = 0; // Disable threading on Symbian + cfg.use_srtp = USE_SRTP; + cfg.srtp_secure_signaling = 0; cfg.cb.on_incoming_call = &on_incoming_call; + cfg.cb.on_call_media_state = &on_call_media_state; + cfg.cb.on_call_state = &on_call_state; + cfg.cb.on_buddy_state = &on_buddy_state; + cfg.cb.on_pager = &on_pager; + cfg.cb.on_typing = &on_typing; + cfg.cb.on_call_transfer_status = &on_call_transfer_status; + cfg.cb.on_call_replaced = &on_call_replaced; + cfg.cb.on_nat_detect = &on_nat_detect; + cfg.cb.on_reg_state = &on_reg_state; pjsua_media_config med_cfg; - pjsua_media_config_default(&med_cfg); + pjsua_media_config_default (&med_cfg); + med_cfg.thread_cnt = 0; // Disable threading on Symbian + med_cfg.has_ioqueue = PJ_FALSE; + med_cfg.clock_rate = 8000; + #if defined(PJMEDIA_SYM_SND_USE_APS) && (PJMEDIA_SYM_SND_USE_APS==1) med_cfg.audio_frame_ptime = 20; + #else med_cfg.audio_frame_ptime = 40; + #endif med_cfg.ec_tail_len = 0; + med_cfg.enable_ice = USE_ICE; + med_cfg.snd_auto_close_time = 5; // wait for 5 seconds idle before sound dev get auto-closed pjsua_logging_config log_cfg; - pjsua_logging_config_default(&log_cfg); + pjsua_logging_config_default (&log_cfg); + log_cfg.console_level = LOG_LEVEL; + log_cfg.cb = &log_writer; + log_cfg.decor = 0; - status = pjsua_init(&cfg, &log_cfg, &med_cfg); + status = pjsua_init (&cfg, &log_cfg, &med_cfg); + if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "pjsua_init() error", status); - pjsua_destroy(); - return status; + pjsua_perror (THIS_FILE, "pjsua_init() error", status); + pjsua_destroy(); + return status; } /* Add UDP transport. */ pjsua_transport_config tcfg; + pjsua_transport_id tid; - pjsua_transport_config_default(&tcfg); + pjsua_transport_config_default (&tcfg); + tcfg.port = SIP_PORT; - status = pjsua_transport_create(PJSIP_TRANSPORT_UDP, &tcfg, &tid); + + status = pjsua_transport_create (PJSIP_TRANSPORT_UDP, &tcfg, &tid); + if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error creating transport", status); - pjsua_destroy(); - return status; + pjsua_perror (THIS_FILE, "Error creating transport", status); + pjsua_destroy(); + return status; } /* Add account for the transport */ - pjsua_acc_add_local(tid, PJ_TRUE, &g_acc_id); + pjsua_acc_add_local (tid, PJ_TRUE, &g_acc_id); /* Initialization is done, now start pjsua */ status = pjsua_start(); + if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error starting pjsua", status); - pjsua_destroy(); - return status; + pjsua_perror (THIS_FILE, "Error starting pjsua", status); + pjsua_destroy(); + return status; } /* Adjust Speex priority and enable only the narrowband */ { - pj_str_t codec_id = pj_str("speex/8000"); - pjmedia_codec_mgr_set_codec_priority( - pjmedia_endpt_get_codec_mgr(pjsua_var.med_endpt), - &codec_id, PJMEDIA_CODEC_PRIO_NORMAL+1); - - codec_id = pj_str("speex/16000"); - pjmedia_codec_mgr_set_codec_priority( - pjmedia_endpt_get_codec_mgr(pjsua_var.med_endpt), - &codec_id, PJMEDIA_CODEC_PRIO_DISABLED); - - codec_id = pj_str("speex/32000"); - pjmedia_codec_mgr_set_codec_priority( - pjmedia_endpt_get_codec_mgr(pjsua_var.med_endpt), - &codec_id, PJMEDIA_CODEC_PRIO_DISABLED); + pj_str_t codec_id = pj_str ("speex/8000"); + pjmedia_codec_mgr_set_codec_priority ( + pjmedia_endpt_get_codec_mgr (pjsua_var.med_endpt), + &codec_id, PJMEDIA_CODEC_PRIO_NORMAL+1); + + codec_id = pj_str ("speex/16000"); + pjmedia_codec_mgr_set_codec_priority ( + pjmedia_endpt_get_codec_mgr (pjsua_var.med_endpt), + &codec_id, PJMEDIA_CODEC_PRIO_DISABLED); + + codec_id = pj_str ("speex/32000"); + pjmedia_codec_mgr_set_codec_priority ( + pjmedia_endpt_get_codec_mgr (pjsua_var.med_endpt), + &codec_id, PJMEDIA_CODEC_PRIO_DISABLED); } return PJ_SUCCESS; @@ -397,97 +440,104 @@ int symbian_ua_destroy() { // Shutdown pjsua pjsua_destroy(); - + // Close connection and socket server aConn.Close(); aSocketServer.Close(); - + CloseSTDLIB(); return PJ_SUCCESS; } -void symbian_ua_set_info_callback(const symbian_ua_info_cb_t *cb) +void symbian_ua_set_info_callback (const symbian_ua_info_cb_t *cb) { if (cb) - g_cb = *cb; + g_cb = *cb; else - pj_bzero(&g_cb, sizeof(g_cb)); + pj_bzero (&g_cb, sizeof (g_cb)); } -int symbian_ua_set_account(const char *domain, const char *username, - const char *password, - bool use_srtp, bool use_ice) +int symbian_ua_set_account (const char *domain, const char *username, + const char *password, + bool use_srtp, bool use_ice) { pj_status_t status; - PJ_ASSERT_RETURN(username && password && domain, PJ_EINVAL); - PJ_UNUSED_ARG(use_srtp); - PJ_UNUSED_ARG(use_ice); + PJ_ASSERT_RETURN (username && password && domain, PJ_EINVAL); + PJ_UNUSED_ARG (use_srtp); + PJ_UNUSED_ARG (use_ice); if (domain[0] == 0) { - pjsua_acc_info acc_info; - pj_status_t status; - - status = pjsua_acc_get_info(g_acc_id, &acc_info); - if (status != PJ_SUCCESS) - return status; - - if (acc_info.status == 200) { - PJ_LOG(3,(THIS_FILE, "Unregistering..")); - pjsua_acc_set_registration(g_acc_id, PJ_FALSE); - g_acc_id = 0; - } - return PJ_SUCCESS; + pjsua_acc_info acc_info; + pj_status_t status; + + status = pjsua_acc_get_info (g_acc_id, &acc_info); + + if (status != PJ_SUCCESS) + return status; + + if (acc_info.status == 200) { + PJ_LOG (3, (THIS_FILE, "Unregistering..")); + pjsua_acc_set_registration (g_acc_id, PJ_FALSE); + g_acc_id = 0; + } + + return PJ_SUCCESS; } if (pjsua_acc_get_count() > 1) { - status = pjsua_acc_del(g_acc_id); - if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error removing account", status); - return status; - } - g_acc_id = 0; + status = pjsua_acc_del (g_acc_id); + + if (status != PJ_SUCCESS) { + pjsua_perror (THIS_FILE, "Error removing account", status); + return status; + } + + g_acc_id = 0; } pjsua_acc_config cfg; + char tmp_id[PJSIP_MAX_URL_SIZE]; char tmp_reg_uri[PJSIP_MAX_URL_SIZE]; - if (!pj_ansi_strnicmp(domain, "sip:", 4)) { - domain += 4; + if (!pj_ansi_strnicmp (domain, "sip:", 4)) { + domain += 4; } - pjsua_acc_config_default(&cfg); - pj_ansi_sprintf(tmp_id, "sip:%s@%s", username, domain); - cfg.id = pj_str(tmp_id); - pj_ansi_sprintf(tmp_reg_uri, "sip:%s", domain); - cfg.reg_uri = pj_str(tmp_reg_uri); + pjsua_acc_config_default (&cfg); + + pj_ansi_sprintf (tmp_id, "sip:%s@%s", username, domain); + cfg.id = pj_str (tmp_id); + pj_ansi_sprintf (tmp_reg_uri, "sip:%s", domain); + cfg.reg_uri = pj_str (tmp_reg_uri); cfg.cred_count = 1; - cfg.cred_info[0].realm = pj_str("*"); - cfg.cred_info[0].scheme = pj_str("digest"); - cfg.cred_info[0].username = pj_str((char*)username); + cfg.cred_info[0].realm = pj_str ("*"); + cfg.cred_info[0].scheme = pj_str ("digest"); + cfg.cred_info[0].username = pj_str ( (char*) username); cfg.cred_info[0].data_type = PJSIP_CRED_DATA_PLAIN_PASSWD; - cfg.cred_info[0].data = pj_str((char*)password); + cfg.cred_info[0].data = pj_str ( (char*) password); + + status = pjsua_acc_add (&cfg, PJ_TRUE, &g_acc_id); - status = pjsua_acc_add(&cfg, PJ_TRUE, &g_acc_id); if (status != PJ_SUCCESS) { - pjsua_perror(THIS_FILE, "Error setting account", status); - pjsua_destroy(); - return status; + pjsua_perror (THIS_FILE, "Error setting account", status); + pjsua_destroy(); + return status; } return PJ_SUCCESS; } -int symbian_ua_makecall(const char* dest_url) +int symbian_ua_makecall (const char* dest_url) { - if (pjsua_verify_sip_url(dest_url) == PJ_SUCCESS) { - pj_str_t dst = pj_str((char*)dest_url); - pjsua_call_make_call(g_acc_id, &dst, 0, NULL, - NULL, &g_call_id); + if (pjsua_verify_sip_url (dest_url) == PJ_SUCCESS) { + pj_str_t dst = pj_str ( (char*) dest_url); + pjsua_call_make_call (g_acc_id, &dst, 0, NULL, + NULL, &g_call_id); - return PJ_SUCCESS; + return PJ_SUCCESS; } return PJ_EINVAL; @@ -502,13 +552,13 @@ int symbian_ua_endcall() bool symbian_ua_anycall() { - return (pjsua_call_get_count()>0); + return (pjsua_call_get_count() >0); } int symbian_ua_answercall() { PJ_ASSERT_RETURN (g_call_id != PJSUA_INVALID_ID, PJ_EINVAL); - return pjsua_call_answer(g_call_id, 200, NULL, NULL); + return pjsua_call_answer (g_call_id, 200, NULL, NULL); } diff --git a/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiAppUi.cpp b/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiAppUi.cpp index ac399510b2bb98b03fe0b34dbf21a021b4be41ec..ab66bb27805fcce63c3a2a661ffca137f37d260c 100644 --- a/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiAppUi.cpp +++ b/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiAppUi.cpp @@ -3,7 +3,7 @@ Name : symbian_ua_guiAppUi.cpp Author : nanang Copyright : (c) 2008-2009 Teluu Inc. - Description : + Description : ======================================================================== */ // [[[ begin generated region: do not modify [Generated System Includes] @@ -29,167 +29,168 @@ /** * Construct the Csymbian_ua_guiAppUi instance - */ -Csymbian_ua_guiAppUi::Csymbian_ua_guiAppUi() : CTimer(0) - { - // [[[ begin generated region: do not modify [Generated Contents] - // ]]] end generated region [Generated Contents] + */ +Csymbian_ua_guiAppUi::Csymbian_ua_guiAppUi() : CTimer (0) +{ + // [[[ begin generated region: do not modify [Generated Contents] + // ]]] end generated region [Generated Contents] - } +} -/** +/** * The appui's destructor removes the container from the control * stack and destroys it. */ Csymbian_ua_guiAppUi::~Csymbian_ua_guiAppUi() - { - // [[[ begin generated region: do not modify [Generated Contents] - TRAPD( err_Dlg_wait_init, RemoveDlg_wait_initL() ); - // ]]] end generated region [Generated Contents] - } +{ + // [[[ begin generated region: do not modify [Generated Contents] + TRAPD (err_Dlg_wait_init, RemoveDlg_wait_initL()); + // ]]] end generated region [Generated Contents] +} // [[[ begin generated function: do not modify void Csymbian_ua_guiAppUi::InitializeContainersL() - { - iSymbian_ua_guiContainerView = Csymbian_ua_guiContainerView::NewL(); - AddViewL( iSymbian_ua_guiContainerView ); - iSymbian_ua_guiSettingItemListView = Csymbian_ua_guiSettingItemListView::NewL(); - AddViewL( iSymbian_ua_guiSettingItemListView ); - SetDefaultViewL( *iSymbian_ua_guiSettingItemListView ); - } +{ + iSymbian_ua_guiContainerView = Csymbian_ua_guiContainerView::NewL(); + AddViewL (iSymbian_ua_guiContainerView); + iSymbian_ua_guiSettingItemListView = Csymbian_ua_guiSettingItemListView::NewL(); + AddViewL (iSymbian_ua_guiSettingItemListView); + SetDefaultViewL (*iSymbian_ua_guiSettingItemListView); +} + // ]]] end generated function /** * Handle a command for this appui (override) * @param aCommand command id to be handled */ -void Csymbian_ua_guiAppUi::HandleCommandL( TInt aCommand ) - { - // [[[ begin generated region: do not modify [Generated Code] - TBool commandHandled = EFalse; - switch ( aCommand ) - { // code to dispatch to the AppUi's menu and CBA commands is generated here - default: - break; - } - - - if ( !commandHandled ) - { - if ( aCommand == EAknSoftkeyExit || aCommand == EEikCmdExit ) - { - symbian_ua_destroy(); - Exit(); - } - } - // ]]] end generated region [Generated Code] - - } - -/** +void Csymbian_ua_guiAppUi::HandleCommandL (TInt aCommand) +{ + // [[[ begin generated region: do not modify [Generated Code] + TBool commandHandled = EFalse; + + switch (aCommand) { // code to dispatch to the AppUi's menu and CBA commands is generated here + + default: + break; + } + + + if (!commandHandled) { + if (aCommand == EAknSoftkeyExit || aCommand == EEikCmdExit) { + symbian_ua_destroy(); + Exit(); + } + } + + // ]]] end generated region [Generated Code] + +} + +/** * Override of the HandleResourceChangeL virtual function */ -void Csymbian_ua_guiAppUi::HandleResourceChangeL( TInt aType ) - { - CAknViewAppUi::HandleResourceChangeL( aType ); - // [[[ begin generated region: do not modify [Generated Code] - // ]]] end generated region [Generated Code] - - } - -/** +void Csymbian_ua_guiAppUi::HandleResourceChangeL (TInt aType) +{ + CAknViewAppUi::HandleResourceChangeL (aType); + // [[[ begin generated region: do not modify [Generated Code] + // ]]] end generated region [Generated Code] + +} + +/** * Override of the HandleKeyEventL virtual function * @return EKeyWasConsumed if event was handled, EKeyWasNotConsumed if not - * @param aKeyEvent - * @param aType + * @param aKeyEvent + * @param aType */ -TKeyResponse Csymbian_ua_guiAppUi::HandleKeyEventL( - const TKeyEvent& aKeyEvent, - TEventCode aType ) - { - // The inherited HandleKeyEventL is private and cannot be called - // [[[ begin generated region: do not modify [Generated Contents] - // ]]] end generated region [Generated Contents] - - return EKeyWasNotConsumed; - } - -/** +TKeyResponse Csymbian_ua_guiAppUi::HandleKeyEventL ( + const TKeyEvent& aKeyEvent, + TEventCode aType) +{ + // The inherited HandleKeyEventL is private and cannot be called + // [[[ begin generated region: do not modify [Generated Contents] + // ]]] end generated region [Generated Contents] + + return EKeyWasNotConsumed; +} + +/** * Override of the HandleViewDeactivation virtual function * - * @param aViewIdToBeDeactivated - * @param aNewlyActivatedViewId + * @param aViewIdToBeDeactivated + * @param aNewlyActivatedViewId */ -void Csymbian_ua_guiAppUi::HandleViewDeactivation( - const TVwsViewId& aViewIdToBeDeactivated, - const TVwsViewId& aNewlyActivatedViewId ) - { - CAknViewAppUi::HandleViewDeactivation( - aViewIdToBeDeactivated, - aNewlyActivatedViewId ); - // [[[ begin generated region: do not modify [Generated Contents] - // ]]] end generated region [Generated Contents] - - } +void Csymbian_ua_guiAppUi::HandleViewDeactivation ( + const TVwsViewId& aViewIdToBeDeactivated, + const TVwsViewId& aNewlyActivatedViewId) +{ + CAknViewAppUi::HandleViewDeactivation ( + aViewIdToBeDeactivated, + aNewlyActivatedViewId); + // [[[ begin generated region: do not modify [Generated Contents] + // ]]] end generated region [Generated Contents] + +} /** - * @brief Completes the second phase of Symbian object construction. - * Put initialization code that could leave here. - */ + * @brief Completes the second phase of Symbian object construction. + * Put initialization code that could leave here. + */ void Csymbian_ua_guiAppUi::ConstructL() - { - // [[[ begin generated region: do not modify [Generated Contents] - BaseConstructL( EAknEnableSkin ); - InitializeContainersL(); - // ]]] end generated region [Generated Contents] - - // Create private folder - RProcess process; - TFileName path; - - path.Copy( process.FileName().Left(2) ); - - if(path.Compare(_L("c")) || path.Compare(_L("C"))) - CEikonEnv::Static()->FsSession().CreatePrivatePath(EDriveC); - else if(path.Compare(_L("e")) || path.Compare(_L("E"))) - CEikonEnv::Static()->FsSession().CreatePrivatePath(EDriveE); - - // Init PJSUA - if (symbian_ua_init() != 0) { - symbian_ua_destroy(); - Exit(); - } - - ExecuteDlg_wait_initLD(); - - CTimer::ConstructL(); - CActiveScheduler::Add( this ); - After(4000000); - } - -/** +{ + // [[[ begin generated region: do not modify [Generated Contents] + BaseConstructL (EAknEnableSkin); + InitializeContainersL(); + // ]]] end generated region [Generated Contents] + + // Create private folder + RProcess process; + TFileName path; + + path.Copy (process.FileName().Left (2)); + + if (path.Compare (_L ("c")) || path.Compare (_L ("C"))) + CEikonEnv::Static()->FsSession().CreatePrivatePath (EDriveC); + else if (path.Compare (_L ("e")) || path.Compare (_L ("E"))) + CEikonEnv::Static()->FsSession().CreatePrivatePath (EDriveE); + + // Init PJSUA + if (symbian_ua_init() != 0) { + symbian_ua_destroy(); + Exit(); + } + + ExecuteDlg_wait_initLD(); + + CTimer::ConstructL(); + CActiveScheduler::Add (this); + After (4000000); +} + +/** * Override of the HandleApplicationSpecificEventL virtual function */ -void Csymbian_ua_guiAppUi::HandleApplicationSpecificEventL( - TInt aType, - const TWsEvent& anEvent ) - { - CAknViewAppUi::HandleApplicationSpecificEventL( aType, anEvent ); - // [[[ begin generated region: do not modify [Generated Code] - // ]]] end generated region [Generated Code] - - } - -/** +void Csymbian_ua_guiAppUi::HandleApplicationSpecificEventL ( + TInt aType, + const TWsEvent& anEvent) +{ + CAknViewAppUi::HandleApplicationSpecificEventL (aType, anEvent); + // [[[ begin generated region: do not modify [Generated Code] + // ]]] end generated region [Generated Code] + +} + +/** * Handle the applicationSpecificEvent event. */ -void Csymbian_ua_guiAppUi::HandleSymbian_ua_guiAppUiApplicationSpecificEventL( - TInt /* aType */, - const TWsEvent& /* anEvent */ ) - { - // TODO: implement applicationSpecificEvent event handler - } - +void Csymbian_ua_guiAppUi::HandleSymbian_ua_guiAppUiApplicationSpecificEventL ( + TInt /* aType */, + const TWsEvent& /* anEvent */) +{ + // TODO: implement applicationSpecificEvent event handler +} + // [[[ begin generated function: do not modify /** * Execute the wait dialog for dlg_wait_init. This routine returns @@ -198,19 +199,22 @@ void Csymbian_ua_guiAppUi::HandleSymbian_ua_guiAppUiApplicationSpecificEventL( * @param aOverrideText optional override text. When null the text configured * in the UI Designer is used. */ -void Csymbian_ua_guiAppUi::ExecuteDlg_wait_initLD( const TDesC* aOverrideText ) - { - iDlg_wait_init = new ( ELeave ) CAknWaitDialog( - reinterpret_cast< CEikDialog** >( &iDlg_wait_init ), EFalse ); - if ( aOverrideText != NULL ) - { - iDlg_wait_init->SetTextL( *aOverrideText ); - } - iDlg_wait_init->ExecuteLD( R_APPLICATION_DLG_WAIT_INIT ); - iDlg_wait_initCallback = new ( ELeave ) CProgressDialogCallback( - this, iDlg_wait_init, &Csymbian_ua_guiAppUi::HandleDlg_wait_initCanceledL ); - iDlg_wait_init->SetCallback( iDlg_wait_initCallback ); - } +void Csymbian_ua_guiAppUi::ExecuteDlg_wait_initLD (const TDesC* aOverrideText) +{ + iDlg_wait_init = new (ELeave) CAknWaitDialog ( + reinterpret_cast< CEikDialog** > (&iDlg_wait_init), EFalse); + + if (aOverrideText != NULL) { + iDlg_wait_init->SetTextL (*aOverrideText); + } + + iDlg_wait_init->ExecuteLD (R_APPLICATION_DLG_WAIT_INIT); + + iDlg_wait_initCallback = new (ELeave) CProgressDialogCallback ( + this, iDlg_wait_init, &Csymbian_ua_guiAppUi::HandleDlg_wait_initCanceledL); + iDlg_wait_init->SetCallback (iDlg_wait_initCallback); +} + // ]]] end generated function // [[[ begin generated function: do not modify @@ -218,30 +222,32 @@ void Csymbian_ua_guiAppUi::ExecuteDlg_wait_initLD( const TDesC* aOverrideText ) * Close and dispose of the wait dialog for dlg_wait_init */ void Csymbian_ua_guiAppUi::RemoveDlg_wait_initL() - { - if ( iDlg_wait_init != NULL ) - { - iDlg_wait_init->SetCallback( NULL ); - iDlg_wait_init->ProcessFinishedL(); // deletes the dialog - iDlg_wait_init = NULL; - } - delete iDlg_wait_initCallback; - iDlg_wait_initCallback = NULL; - - } +{ + if (iDlg_wait_init != NULL) { + iDlg_wait_init->SetCallback (NULL); + iDlg_wait_init->ProcessFinishedL(); // deletes the dialog + iDlg_wait_init = NULL; + } + + delete iDlg_wait_initCallback; + + iDlg_wait_initCallback = NULL; + +} + // ]]] end generated function -/** +/** * Handle the canceled event. */ -void Csymbian_ua_guiAppUi::HandleDlg_wait_initCanceledL( CAknProgressDialog* /* aDialog */ ) - { - // TODO: implement canceled event handler - - } - +void Csymbian_ua_guiAppUi::HandleDlg_wait_initCanceledL (CAknProgressDialog* /* aDialog */) +{ + // TODO: implement canceled event handler + +} + void Csymbian_ua_guiAppUi::RunL() - { - RemoveDlg_wait_initL(); - iSymbian_ua_guiSettingItemListView->HandleCommandL(EAknSoftkeySave); - } +{ + RemoveDlg_wait_initL(); + iSymbian_ua_guiSettingItemListView->HandleCommandL (EAknSoftkeySave); +} diff --git a/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiApplication.cpp b/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiApplication.cpp index dc60fecd64d1cab99afdbb61aa15b9f49921935b..d32c672d6c7e08becc4bab7c0a2fe005a0d5948a 100644 --- a/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiApplication.cpp +++ b/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiApplication.cpp @@ -3,7 +3,7 @@ Name : symbian_ua_guiApplication.cpp Author : nanang Copyright : (c) 2008-2009 Teluu Inc. - Description : + Description : ======================================================================== */ // [[[ begin generated region: do not modify [Generated System Includes] @@ -19,50 +19,50 @@ // Needed by APS -TPtrC APP_UID = _L("EBD12EE4"); +TPtrC APP_UID = _L ("EBD12EE4"); /** * @brief Returns the application's UID (override from CApaApplication::AppDllUid()) * @return UID for this application (KUidsymbian_ua_guiApplication) */ TUid Csymbian_ua_guiApplication::AppDllUid() const - { - return KUidsymbian_ua_guiApplication; - } +{ + return KUidsymbian_ua_guiApplication; +} /** * @brief Creates the application's document (override from CApaApplication::CreateDocumentL()) * @return Pointer to the created document object (Csymbian_ua_guiDocument) */ CApaDocument* Csymbian_ua_guiApplication::CreateDocumentL() - { - return Csymbian_ua_guiDocument::NewL( *this ); - } +{ + return Csymbian_ua_guiDocument::NewL (*this); +} #ifdef EKA2 /** * @brief Called by the application framework to construct the application object * @return The application (Csymbian_ua_guiApplication) - */ + */ LOCAL_C CApaApplication* NewApplication() - { - return new Csymbian_ua_guiApplication; - } +{ + return new Csymbian_ua_guiApplication; +} /** * @brief This standard export is the entry point for all Series 60 applications * @return error code - */ + */ GLDEF_C TInt E32Main() - { - TInt err; - - err = EikStart::RunApplication( NewApplication ); +{ + TInt err; + + err = EikStart::RunApplication (NewApplication); + + return err; +} - return err; - } - #else // Series 60 2.x main DLL program code /** @@ -70,17 +70,17 @@ GLDEF_C TInt E32Main() * @return The application (Csymbian_ua_guiApplication) */ EXPORT_C CApaApplication* NewApplication() - { - return new Csymbian_ua_guiApplication; - } +{ + return new Csymbian_ua_guiApplication; +} /** * @brief This standard export is the entry point for all Series 60 applications * @return error code */ -GLDEF_C TInt E32Dll(TDllReason /*reason*/) - { - return KErrNone; - } +GLDEF_C TInt E32Dll (TDllReason /*reason*/) +{ + return KErrNone; +} #endif // EKA2 diff --git a/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiContainer.cpp b/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiContainer.cpp index 777217c7de802bbeee708c77d062236f1961d719..1ff6ff8bd9484cc2ed32a7d5af13a3deb486a0dd 100644 --- a/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiContainer.cpp +++ b/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiContainer.cpp @@ -3,7 +3,7 @@ Name : symbian_ua_guiContainer.cpp Author : nanang Copyright : (c) 2008-2009 Teluu Inc. - Description : + Description : ======================================================================== */ // [[[ begin generated region: do not modify [Generated System Includes] @@ -30,34 +30,35 @@ // ]]] end generated region [Generated Constants] /** - * First phase of Symbian two-phase construction. Should not + * First phase of Symbian two-phase construction. Should not * contain any code that could leave. */ CSymbian_ua_guiContainer::CSymbian_ua_guiContainer() - { - // [[[ begin generated region: do not modify [Generated Contents] - iLabel1 = NULL; - iEd_url = NULL; - iEd_info = NULL; - // ]]] end generated region [Generated Contents] - - } -/** +{ + // [[[ begin generated region: do not modify [Generated Contents] + iLabel1 = NULL; + iEd_url = NULL; + iEd_info = NULL; + // ]]] end generated region [Generated Contents] + +} + +/** * Destroy child controls. */ CSymbian_ua_guiContainer::~CSymbian_ua_guiContainer() - { - // [[[ begin generated region: do not modify [Generated Contents] - delete iLabel1; - iLabel1 = NULL; - delete iEd_url; - iEd_url = NULL; - delete iEd_info; - iEd_info = NULL; - // ]]] end generated region [Generated Contents] - - } - +{ + // [[[ begin generated region: do not modify [Generated Contents] + delete iLabel1; + iLabel1 = NULL; + delete iEd_url; + iEd_url = NULL; + delete iEd_info; + iEd_info = NULL; + // ]]] end generated region [Generated Contents] + +} + /** * Construct the control (first phase). * Creates an instance and initializes it. @@ -67,18 +68,18 @@ CSymbian_ua_guiContainer::~CSymbian_ua_guiContainer() * @param aCommandObserver command observer * @return initialized instance of CSymbian_ua_guiContainer */ -CSymbian_ua_guiContainer* CSymbian_ua_guiContainer::NewL( - const TRect& aRect, - const CCoeControl* aParent, - MEikCommandObserver* aCommandObserver ) - { - CSymbian_ua_guiContainer* self = CSymbian_ua_guiContainer::NewLC( - aRect, - aParent, - aCommandObserver ); - CleanupStack::Pop( self ); - return self; - } +CSymbian_ua_guiContainer* CSymbian_ua_guiContainer::NewL ( + const TRect& aRect, + const CCoeControl* aParent, + MEikCommandObserver* aCommandObserver) +{ + CSymbian_ua_guiContainer* self = CSymbian_ua_guiContainer::NewLC ( + aRect, + aParent, + aCommandObserver); + CleanupStack::Pop (self); + return self; +} /** * Construct the control (first phase). @@ -89,197 +90,205 @@ CSymbian_ua_guiContainer* CSymbian_ua_guiContainer::NewL( * @param aCommandObserver command observer * @return new instance of CSymbian_ua_guiContainer */ -CSymbian_ua_guiContainer* CSymbian_ua_guiContainer::NewLC( - const TRect& aRect, - const CCoeControl* aParent, - MEikCommandObserver* aCommandObserver ) - { - CSymbian_ua_guiContainer* self = new ( ELeave ) CSymbian_ua_guiContainer(); - CleanupStack::PushL( self ); - self->ConstructL( aRect, aParent, aCommandObserver ); - return self; - } - +CSymbian_ua_guiContainer* CSymbian_ua_guiContainer::NewLC ( + const TRect& aRect, + const CCoeControl* aParent, + MEikCommandObserver* aCommandObserver) +{ + CSymbian_ua_guiContainer* self = new (ELeave) CSymbian_ua_guiContainer(); + CleanupStack::PushL (self); + self->ConstructL (aRect, aParent, aCommandObserver); + return self; +} + /** * Construct the control (second phase). * Creates a window to contain the controls and activates it. * @param aRect bounding rectangle * @param aCommandObserver command observer * @param aParent owning parent, or NULL - */ -void CSymbian_ua_guiContainer::ConstructL( - const TRect& aRect, - const CCoeControl* aParent, - MEikCommandObserver* aCommandObserver ) - { - if ( aParent == NULL ) - { - CreateWindowL(); - } - else - { - SetContainerWindowL( *aParent ); - } - iFocusControl = NULL; - iCommandObserver = aCommandObserver; - InitializeControlsL(); - SetRect( aRect ); - ActivateL(); - // [[[ begin generated region: do not modify [Post-ActivateL initializations] - // ]]] end generated region [Post-ActivateL initializations] - - } - + */ +void CSymbian_ua_guiContainer::ConstructL ( + const TRect& aRect, + const CCoeControl* aParent, + MEikCommandObserver* aCommandObserver) +{ + if (aParent == NULL) { + CreateWindowL(); + } else { + SetContainerWindowL (*aParent); + } + + iFocusControl = NULL; + + iCommandObserver = aCommandObserver; + InitializeControlsL(); + SetRect (aRect); + ActivateL(); + // [[[ begin generated region: do not modify [Post-ActivateL initializations] + // ]]] end generated region [Post-ActivateL initializations] + +} + /** * Return the number of controls in the container (override) * @return count */ TInt CSymbian_ua_guiContainer::CountComponentControls() const - { - return ( int ) ELastControl; - } - +{ + return (int) ELastControl; +} + /** * Get the control with the given index (override) * @param aIndex Control index [0...n) (limited by #CountComponentControls) * @return Pointer to control */ -CCoeControl* CSymbian_ua_guiContainer::ComponentControl( TInt aIndex ) const - { - // [[[ begin generated region: do not modify [Generated Contents] - switch ( aIndex ) - { - case ELabel1: - return iLabel1; - case EEd_url: - return iEd_url; - case EEd_info: - return iEd_info; - } - // ]]] end generated region [Generated Contents] - - // handle any user controls here... - - return NULL; - } - +CCoeControl* CSymbian_ua_guiContainer::ComponentControl (TInt aIndex) const +{ + // [[[ begin generated region: do not modify [Generated Contents] + switch (aIndex) { + + case ELabel1: + return iLabel1; + + case EEd_url: + return iEd_url; + + case EEd_info: + return iEd_info; + } + + // ]]] end generated region [Generated Contents] + + // handle any user controls here... + + return NULL; +} + /** * Handle resizing of the container. This implementation will lay out * full-sized controls like list boxes for any screen size, and will layout * labels, editors, etc. to the size they were given in the UI designer. * This code will need to be modified to adjust arbitrary controls to * any screen size. - */ + */ void CSymbian_ua_guiContainer::SizeChanged() - { - CCoeControl::SizeChanged(); - LayoutControls(); - // [[[ begin generated region: do not modify [Generated Contents] - - // ]]] end generated region [Generated Contents] - - } - +{ + CCoeControl::SizeChanged(); + LayoutControls(); + // [[[ begin generated region: do not modify [Generated Contents] + + // ]]] end generated region [Generated Contents] + +} + // [[[ begin generated function: do not modify /** * Layout components as specified in the UI Designer */ void CSymbian_ua_guiContainer::LayoutControls() - { - iLabel1->SetExtent( TPoint( 2, 23 ), TSize( 32, 28 ) ); - iEd_url->SetExtent( TPoint( 49, 25 ), TSize( 197, 28 ) ); - iEd_info->SetExtent( TPoint( 3, 78 ), TSize( 235, 143 ) ); - } +{ + iLabel1->SetExtent (TPoint (2, 23), TSize (32, 28)); + iEd_url->SetExtent (TPoint (49, 25), TSize (197, 28)); + iEd_info->SetExtent (TPoint (3, 78), TSize (235, 143)); +} + // ]]] end generated function /** * Handle key events. - */ -TKeyResponse CSymbian_ua_guiContainer::OfferKeyEventL( - const TKeyEvent& aKeyEvent, - TEventCode aType ) - { - // [[[ begin generated region: do not modify [Generated Contents] - - // ]]] end generated region [Generated Contents] - - if ( iFocusControl != NULL - && iFocusControl->OfferKeyEventL( aKeyEvent, aType ) == EKeyWasConsumed ) - { - return EKeyWasConsumed; - } - return CCoeControl::OfferKeyEventL( aKeyEvent, aType ); - } - + */ +TKeyResponse CSymbian_ua_guiContainer::OfferKeyEventL ( + const TKeyEvent& aKeyEvent, + TEventCode aType) +{ + // [[[ begin generated region: do not modify [Generated Contents] + + // ]]] end generated region [Generated Contents] + + if (iFocusControl != NULL + && iFocusControl->OfferKeyEventL (aKeyEvent, aType) == EKeyWasConsumed) { + return EKeyWasConsumed; + } + + return CCoeControl::OfferKeyEventL (aKeyEvent, aType); +} + // [[[ begin generated function: do not modify /** * Initialize each control upon creation. - */ + */ void CSymbian_ua_guiContainer::InitializeControlsL() - { - iLabel1 = new ( ELeave ) CEikLabel; - iLabel1->SetContainerWindowL( *this ); - { - TResourceReader reader; - iEikonEnv->CreateResourceReaderLC( reader, R_SYMBIAN_UA_GUI_CONTAINER_LABEL1 ); - iLabel1->ConstructFromResourceL( reader ); - CleanupStack::PopAndDestroy(); // reader internal state - } - iEd_url = new ( ELeave ) CEikEdwin; - iEd_url->SetContainerWindowL( *this ); - { - TResourceReader reader; - iEikonEnv->CreateResourceReaderLC( reader, R_SYMBIAN_UA_GUI_CONTAINER_ED_URL ); - iEd_url->ConstructFromResourceL( reader ); - CleanupStack::PopAndDestroy(); // reader internal state - } - { - HBufC* text = StringLoader::LoadLC( R_SYMBIAN_UA_GUI_CONTAINER_ED_URL_2 ); - iEd_url->SetTextL( text ); - CleanupStack::PopAndDestroy( text ); - } - iEd_info = new ( ELeave ) CEikEdwin; - iEd_info->SetContainerWindowL( *this ); - { - TResourceReader reader; - iEikonEnv->CreateResourceReaderLC( reader, R_SYMBIAN_UA_GUI_CONTAINER_ED_INFO ); - iEd_info->ConstructFromResourceL( reader ); - CleanupStack::PopAndDestroy(); // reader internal state - } - { - HBufC* text = StringLoader::LoadLC( R_SYMBIAN_UA_GUI_CONTAINER_ED_INFO_2 ); - iEd_info->SetTextL( text ); - CleanupStack::PopAndDestroy( text ); - } - - iEd_url->SetFocus( ETrue ); - iFocusControl = iEd_url; - - } +{ + iLabel1 = new (ELeave) CEikLabel; + iLabel1->SetContainerWindowL (*this); + { + TResourceReader reader; + iEikonEnv->CreateResourceReaderLC (reader, R_SYMBIAN_UA_GUI_CONTAINER_LABEL1); + iLabel1->ConstructFromResourceL (reader); + CleanupStack::PopAndDestroy(); // reader internal state + } + + iEd_url = new (ELeave) CEikEdwin; + iEd_url->SetContainerWindowL (*this); + { + TResourceReader reader; + iEikonEnv->CreateResourceReaderLC (reader, R_SYMBIAN_UA_GUI_CONTAINER_ED_URL); + iEd_url->ConstructFromResourceL (reader); + CleanupStack::PopAndDestroy(); // reader internal state + } + + { + HBufC* text = StringLoader::LoadLC (R_SYMBIAN_UA_GUI_CONTAINER_ED_URL_2); + iEd_url->SetTextL (text); + CleanupStack::PopAndDestroy (text); + } + + iEd_info = new (ELeave) CEikEdwin; + iEd_info->SetContainerWindowL (*this); + { + TResourceReader reader; + iEikonEnv->CreateResourceReaderLC (reader, R_SYMBIAN_UA_GUI_CONTAINER_ED_INFO); + iEd_info->ConstructFromResourceL (reader); + CleanupStack::PopAndDestroy(); // reader internal state + } + + { + HBufC* text = StringLoader::LoadLC (R_SYMBIAN_UA_GUI_CONTAINER_ED_INFO_2); + iEd_info->SetTextL (text); + CleanupStack::PopAndDestroy (text); + } + + iEd_url->SetFocus (ETrue); + iFocusControl = iEd_url; + +} + // ]]] end generated function -/** +/** * Handle global resource changes, such as scalable UI or skin events (override) */ -void CSymbian_ua_guiContainer::HandleResourceChange( TInt aType ) - { - CCoeControl::HandleResourceChange( aType ); - SetRect( iAvkonViewAppUi->View( TUid::Uid( ESymbian_ua_guiContainerViewId ) )->ClientRect() ); - // [[[ begin generated region: do not modify [Generated Contents] - // ]]] end generated region [Generated Contents] - - } - +void CSymbian_ua_guiContainer::HandleResourceChange (TInt aType) +{ + CCoeControl::HandleResourceChange (aType); + SetRect (iAvkonViewAppUi->View (TUid::Uid (ESymbian_ua_guiContainerViewId))->ClientRect()); + // [[[ begin generated region: do not modify [Generated Contents] + // ]]] end generated region [Generated Contents] + +} + /** * Draw container contents. - */ -void CSymbian_ua_guiContainer::Draw( const TRect& aRect ) const - { - // [[[ begin generated region: do not modify [Generated Contents] - CWindowGc& gc = SystemGc(); - gc.Clear( aRect ); - - // ]]] end generated region [Generated Contents] - - } - + */ +void CSymbian_ua_guiContainer::Draw (const TRect& aRect) const +{ + // [[[ begin generated region: do not modify [Generated Contents] + CWindowGc& gc = SystemGc(); + gc.Clear (aRect); + + // ]]] end generated region [Generated Contents] + +} + diff --git a/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiContainerView.cpp b/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiContainerView.cpp index 661c210eac8ada40713cc3b7bbe0defd198b57e5..a01d8f353c10d8e10622026ad2c9fcb7c0ee9973 100644 --- a/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiContainerView.cpp +++ b/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiContainerView.cpp @@ -3,7 +3,7 @@ Name : symbian_ua_guiContainerView.cpp Author : nanang Copyright : (c) 2008-2009 Teluu Inc. - Description : + Description : ======================================================================== */ // [[[ begin generated region: do not modify [Generated System Includes] @@ -39,106 +39,111 @@ // ]]] end generated region [Generated Constants] Csymbian_ua_guiContainerView *myinstance = NULL; -_LIT(KStCall, "Call"); -_LIT(KStHangUp, "Hang Up"); +_LIT (KStCall, "Call"); +_LIT (KStHangUp, "Hang Up"); -void on_info(const wchar_t* buf) +void on_info (const wchar_t* buf) { - TPtrC aBuf((const TUint16*)buf); - - if (myinstance) - myinstance->PutMessage(aBuf); + TPtrC aBuf ( (const TUint16*) buf); + + if (myinstance) + myinstance->PutMessage (aBuf); } -void on_incoming_call(const wchar_t* caller_disp, const wchar_t* caller_uri) +void on_incoming_call (const wchar_t* caller_disp, const wchar_t* caller_uri) { - TBuf<512> buf; - TPtrC aDisp((const TUint16*)caller_disp); - TPtrC aUri((const TUint16*)caller_uri); - _LIT(KFormat, "Incoming call from %S, accept?"); - - buf.Format(KFormat, &aDisp); - if (Csymbian_ua_guiContainerView::RunQry_accept_callL(&buf) == EAknSoftkeyYes) - { - CEikButtonGroupContainer* cba = CEikButtonGroupContainer::Current(); - if (cba != NULL) { - TRAPD(result, cba->SetCommandL(ESymbian_ua_guiContainerViewControlPaneRightId, KStHangUp)); - cba->DrawDeferred(); - } - symbian_ua_answercall(); - } else { - symbian_ua_endcall(); - } + TBuf<512> buf; + TPtrC aDisp ( (const TUint16*) caller_disp); + TPtrC aUri ( (const TUint16*) caller_uri); + _LIT (KFormat, "Incoming call from %S, accept?"); + + buf.Format (KFormat, &aDisp); + + if (Csymbian_ua_guiContainerView::RunQry_accept_callL (&buf) == EAknSoftkeyYes) { + CEikButtonGroupContainer* cba = CEikButtonGroupContainer::Current(); + + if (cba != NULL) { + TRAPD (result, cba->SetCommandL (ESymbian_ua_guiContainerViewControlPaneRightId, KStHangUp)); + cba->DrawDeferred(); + } + + symbian_ua_answercall(); + } else { + symbian_ua_endcall(); + } } -void on_call_end(const wchar_t* reason) +void on_call_end (const wchar_t* reason) { - TPtrC aReason((const TUint16*)reason); - - CEikButtonGroupContainer* cba = CEikButtonGroupContainer::Current(); - if (cba != NULL) { - TRAPD(result, cba->SetCommandL(ESymbian_ua_guiContainerViewControlPaneRightId, KStCall)); - cba->DrawDeferred(); - } - - Csymbian_ua_guiContainerView::RunNote_infoL(&aReason); + TPtrC aReason ( (const TUint16*) reason); + + CEikButtonGroupContainer* cba = CEikButtonGroupContainer::Current(); + + if (cba != NULL) { + TRAPD (result, cba->SetCommandL (ESymbian_ua_guiContainerViewControlPaneRightId, KStCall)); + cba->DrawDeferred(); + } + + Csymbian_ua_guiContainerView::RunNote_infoL (&aReason); } -void on_reg_state(bool success) +void on_reg_state (bool success) { - if (success) - Csymbian_ua_guiContainerView::RunNote_infoL(); - else - Csymbian_ua_guiContainerView::RunNote_warningL(); + if (success) + Csymbian_ua_guiContainerView::RunNote_infoL(); + else + Csymbian_ua_guiContainerView::RunNote_warningL(); } -void on_unreg_state(bool success) +void on_unreg_state (bool success) { - TPtrC st_success(_L("Unregistration Success!")); - TPtrC st_failed(_L("Unregistration Failed!")); - - if (success) - Csymbian_ua_guiContainerView::RunNote_infoL(&st_success); - else - Csymbian_ua_guiContainerView::RunNote_warningL(&st_failed); + TPtrC st_success (_L ("Unregistration Success!")); + TPtrC st_failed (_L ("Unregistration Failed!")); + + if (success) + Csymbian_ua_guiContainerView::RunNote_infoL (&st_success); + else + Csymbian_ua_guiContainerView::RunNote_warningL (&st_failed); } -void Csymbian_ua_guiContainerView::PutMessage(const TDesC &msg) - { - if (!iSymbian_ua_guiContainer) - return; - - CEikEdwin *obj_info = (CEikEdwin*) iSymbian_ua_guiContainer->ComponentControl(iSymbian_ua_guiContainer->EEd_info); +void Csymbian_ua_guiContainerView::PutMessage (const TDesC &msg) +{ + if (!iSymbian_ua_guiContainer) + return; + + CEikEdwin *obj_info = (CEikEdwin*) iSymbian_ua_guiContainer->ComponentControl (iSymbian_ua_guiContainer->EEd_info); - obj_info->SetTextL(&msg); - obj_info->DrawDeferred(); - } + obj_info->SetTextL (&msg); + + obj_info->DrawDeferred(); +} /** * First phase of Symbian two-phase construction. Should not contain any * code that could leave. */ Csymbian_ua_guiContainerView::Csymbian_ua_guiContainerView() - { - // [[[ begin generated region: do not modify [Generated Contents] - iSymbian_ua_guiContainer = NULL; - // ]]] end generated region [Generated Contents] - - } -/** +{ + // [[[ begin generated region: do not modify [Generated Contents] + iSymbian_ua_guiContainer = NULL; + // ]]] end generated region [Generated Contents] + +} + +/** * The view's destructor removes the container from the control * stack and destroys it. */ Csymbian_ua_guiContainerView::~Csymbian_ua_guiContainerView() - { - // [[[ begin generated region: do not modify [Generated Contents] - delete iSymbian_ua_guiContainer; - iSymbian_ua_guiContainer = NULL; - // ]]] end generated region [Generated Contents] - - symbian_ua_set_info_callback(NULL); - myinstance = NULL; - } +{ + // [[[ begin generated region: do not modify [Generated Contents] + delete iSymbian_ua_guiContainer; + iSymbian_ua_guiContainer = NULL; + // ]]] end generated region [Generated Contents] + + symbian_ua_set_info_callback (NULL); + myinstance = NULL; +} /** * Symbian two-phase constructor. @@ -147,11 +152,11 @@ Csymbian_ua_guiContainerView::~Csymbian_ua_guiContainerView() * @return new instance of Csymbian_ua_guiContainerView */ Csymbian_ua_guiContainerView* Csymbian_ua_guiContainerView::NewL() - { - Csymbian_ua_guiContainerView* self = Csymbian_ua_guiContainerView::NewLC(); - CleanupStack::Pop( self ); - return self; - } +{ + Csymbian_ua_guiContainerView* self = Csymbian_ua_guiContainerView::NewLC(); + CleanupStack::Pop (self); + return self; +} /** * Symbian two-phase constructor. @@ -160,259 +165,266 @@ Csymbian_ua_guiContainerView* Csymbian_ua_guiContainerView::NewL() * @return new instance of Csymbian_ua_guiContainerView */ Csymbian_ua_guiContainerView* Csymbian_ua_guiContainerView::NewLC() - { - Csymbian_ua_guiContainerView* self = new ( ELeave ) Csymbian_ua_guiContainerView(); - CleanupStack::PushL( self ); - self->ConstructL(); - return self; - } +{ + Csymbian_ua_guiContainerView* self = new (ELeave) Csymbian_ua_guiContainerView(); + CleanupStack::PushL (self); + self->ConstructL(); + return self; +} /** - * Second-phase constructor for view. + * Second-phase constructor for view. * Initialize contents from resource. - */ + */ void Csymbian_ua_guiContainerView::ConstructL() - { - // [[[ begin generated region: do not modify [Generated Code] - BaseConstructL( R_SYMBIAN_UA_GUI_CONTAINER_SYMBIAN_UA_GUI_CONTAINER_VIEW ); - // ]]] end generated region [Generated Code] - - // add your own initialization code here - symbian_ua_info_cb_t cb; - Mem::FillZ(&cb, sizeof(cb)); - - cb.on_info = &on_info; - cb.on_incoming_call = &on_incoming_call; - cb.on_reg_state = &on_reg_state; - cb.on_unreg_state = &on_unreg_state; - cb.on_call_end = &on_call_end; - - symbian_ua_set_info_callback(&cb); - myinstance = this; - } - +{ + // [[[ begin generated region: do not modify [Generated Code] + BaseConstructL (R_SYMBIAN_UA_GUI_CONTAINER_SYMBIAN_UA_GUI_CONTAINER_VIEW); + // ]]] end generated region [Generated Code] + + // add your own initialization code here + symbian_ua_info_cb_t cb; + Mem::FillZ (&cb, sizeof (cb)); + + cb.on_info = &on_info; + cb.on_incoming_call = &on_incoming_call; + cb.on_reg_state = &on_reg_state; + cb.on_unreg_state = &on_unreg_state; + cb.on_call_end = &on_call_end; + + symbian_ua_set_info_callback (&cb); + myinstance = this; +} + /** * @return The UID for this view */ TUid Csymbian_ua_guiContainerView::Id() const - { - return TUid::Uid( ESymbian_ua_guiContainerViewId ); - } +{ + return TUid::Uid (ESymbian_ua_guiContainerViewId); +} /** * Handle a command for this view (override) * @param aCommand command id to be handled */ -void Csymbian_ua_guiContainerView::HandleCommandL( TInt aCommand ) - { - // [[[ begin generated region: do not modify [Generated Code] - TBool commandHandled = EFalse; - switch ( aCommand ) - { // code to dispatch to the AknView's menu and CBA commands is generated here - - case ESymbian_ua_guiContainerViewControlPaneRightId: - commandHandled = CallSoftKeyPressedL( aCommand ); - break; - case ESymbian_ua_guiContainerViewSettingMenuItemCommand: - commandHandled = HandleSettingMenuItemSelectedL( aCommand ); - break; - default: - break; - } - - - if ( !commandHandled ) - { - - if ( aCommand == ESymbian_ua_guiContainerViewControlPaneRightId ) - { - AppUi()->HandleCommandL( EEikCmdExit ); - } - - } - // ]]] end generated region [Generated Code] - - } +void Csymbian_ua_guiContainerView::HandleCommandL (TInt aCommand) +{ + // [[[ begin generated region: do not modify [Generated Code] + TBool commandHandled = EFalse; + + switch (aCommand) { // code to dispatch to the AknView's menu and CBA commands is generated here + + case ESymbian_ua_guiContainerViewControlPaneRightId: + commandHandled = CallSoftKeyPressedL (aCommand); + break; + + case ESymbian_ua_guiContainerViewSettingMenuItemCommand: + commandHandled = HandleSettingMenuItemSelectedL (aCommand); + break; + + default: + break; + } + + + if (!commandHandled) { + + if (aCommand == ESymbian_ua_guiContainerViewControlPaneRightId) { + AppUi()->HandleCommandL (EEikCmdExit); + } + + } + + // ]]] end generated region [Generated Code] + +} /** - * Handles user actions during activation of the view, + * Handles user actions during activation of the view, * such as initializing the content. */ -void Csymbian_ua_guiContainerView::DoActivateL( - const TVwsViewId& /*aPrevViewId*/, - TUid /*aCustomMessageId*/, - const TDesC8& /*aCustomMessage*/ ) - { - // [[[ begin generated region: do not modify [Generated Contents] - SetupStatusPaneL(); - - CEikButtonGroupContainer* cba = AppUi()->Cba(); - if ( cba != NULL ) - { - cba->MakeVisible( EFalse ); - } - - if ( iSymbian_ua_guiContainer == NULL ) - { - iSymbian_ua_guiContainer = CSymbian_ua_guiContainer::NewL( ClientRect(), NULL, this ); - iSymbian_ua_guiContainer->SetMopParent( this ); - AppUi()->AddToStackL( *this, iSymbian_ua_guiContainer ); - } - // ]]] end generated region [Generated Contents] - - cba = CEikButtonGroupContainer::Current(); - if (cba != NULL) { - if (symbian_ua_anycall()) - cba->SetCommandL(ESymbian_ua_guiContainerViewControlPaneRightId, KStHangUp); - else - cba->SetCommandL(ESymbian_ua_guiContainerViewControlPaneRightId, KStCall); - } - - } +void Csymbian_ua_guiContainerView::DoActivateL ( + const TVwsViewId& /*aPrevViewId*/, + TUid /*aCustomMessageId*/, + const TDesC8& /*aCustomMessage*/) +{ + // [[[ begin generated region: do not modify [Generated Contents] + SetupStatusPaneL(); + + CEikButtonGroupContainer* cba = AppUi()->Cba(); + + if (cba != NULL) { + cba->MakeVisible (EFalse); + } + + if (iSymbian_ua_guiContainer == NULL) { + iSymbian_ua_guiContainer = CSymbian_ua_guiContainer::NewL (ClientRect(), NULL, this); + iSymbian_ua_guiContainer->SetMopParent (this); + AppUi()->AddToStackL (*this, iSymbian_ua_guiContainer); + } + + // ]]] end generated region [Generated Contents] + + cba = CEikButtonGroupContainer::Current(); + + if (cba != NULL) { + if (symbian_ua_anycall()) + cba->SetCommandL (ESymbian_ua_guiContainerViewControlPaneRightId, KStHangUp); + else + cba->SetCommandL (ESymbian_ua_guiContainerViewControlPaneRightId, KStCall); + } + +} /** */ void Csymbian_ua_guiContainerView::DoDeactivate() - { - // [[[ begin generated region: do not modify [Generated Contents] - CleanupStatusPane(); - - CEikButtonGroupContainer* cba = AppUi()->Cba(); - if ( cba != NULL ) - { - cba->MakeVisible( ETrue ); - cba->DrawDeferred(); - } - - if ( iSymbian_ua_guiContainer != NULL ) - { - AppUi()->RemoveFromViewStack( *this, iSymbian_ua_guiContainer ); - delete iSymbian_ua_guiContainer; - iSymbian_ua_guiContainer = NULL; - } - // ]]] end generated region [Generated Contents] - - } +{ + // [[[ begin generated region: do not modify [Generated Contents] + CleanupStatusPane(); + + CEikButtonGroupContainer* cba = AppUi()->Cba(); + + if (cba != NULL) { + cba->MakeVisible (ETrue); + cba->DrawDeferred(); + } + + if (iSymbian_ua_guiContainer != NULL) { + AppUi()->RemoveFromViewStack (*this, iSymbian_ua_guiContainer); + delete iSymbian_ua_guiContainer; + iSymbian_ua_guiContainer = NULL; + } + + // ]]] end generated region [Generated Contents] + +} // [[[ begin generated function: do not modify void Csymbian_ua_guiContainerView::SetupStatusPaneL() - { - // reset the context pane - TUid contextPaneUid = TUid::Uid( EEikStatusPaneUidContext ); - CEikStatusPaneBase::TPaneCapabilities subPaneContext = - StatusPane()->PaneCapabilities( contextPaneUid ); - if ( subPaneContext.IsPresent() && subPaneContext.IsAppOwned() ) - { - CAknContextPane* context = static_cast< CAknContextPane* > ( - StatusPane()->ControlL( contextPaneUid ) ); - context->SetPictureToDefaultL(); - } - - // setup the title pane - TUid titlePaneUid = TUid::Uid( EEikStatusPaneUidTitle ); - CEikStatusPaneBase::TPaneCapabilities subPaneTitle = - StatusPane()->PaneCapabilities( titlePaneUid ); - if ( subPaneTitle.IsPresent() && subPaneTitle.IsAppOwned() ) - { - CAknTitlePane* title = static_cast< CAknTitlePane* >( - StatusPane()->ControlL( titlePaneUid ) ); - TResourceReader reader; - iEikonEnv->CreateResourceReaderLC( reader, R_SYMBIAN_UA_GUI_CONTAINER_TITLE_RESOURCE ); - title->SetFromResourceL( reader ); - CleanupStack::PopAndDestroy(); // reader internal state - } - - } +{ + // reset the context pane + TUid contextPaneUid = TUid::Uid (EEikStatusPaneUidContext); + CEikStatusPaneBase::TPaneCapabilities subPaneContext = + StatusPane()->PaneCapabilities (contextPaneUid); + + if (subPaneContext.IsPresent() && subPaneContext.IsAppOwned()) { + CAknContextPane* context = static_cast< CAknContextPane* > ( + StatusPane()->ControlL (contextPaneUid)); + context->SetPictureToDefaultL(); + } + + // setup the title pane + TUid titlePaneUid = TUid::Uid (EEikStatusPaneUidTitle); + + CEikStatusPaneBase::TPaneCapabilities subPaneTitle = + StatusPane()->PaneCapabilities (titlePaneUid); + + if (subPaneTitle.IsPresent() && subPaneTitle.IsAppOwned()) { + CAknTitlePane* title = static_cast< CAknTitlePane* > ( + StatusPane()->ControlL (titlePaneUid)); + TResourceReader reader; + iEikonEnv->CreateResourceReaderLC (reader, R_SYMBIAN_UA_GUI_CONTAINER_TITLE_RESOURCE); + title->SetFromResourceL (reader); + CleanupStack::PopAndDestroy(); // reader internal state + } + +} + // ]]] end generated function // [[[ begin generated function: do not modify void Csymbian_ua_guiContainerView::CleanupStatusPane() - { - } +{ +} + // ]]] end generated function -/** +/** * Handle status pane size change for this view (override) */ void Csymbian_ua_guiContainerView::HandleStatusPaneSizeChange() - { - CAknView::HandleStatusPaneSizeChange(); - - // this may fail, but we're not able to propagate exceptions here - TInt result; - TRAP( result, SetupStatusPaneL() ); - } - -/** +{ + CAknView::HandleStatusPaneSizeChange(); + + // this may fail, but we're not able to propagate exceptions here + TInt result; + TRAP (result, SetupStatusPaneL()); +} + +/** * Handle the rightSoftKeyPressed event. * @return ETrue if the command was handled, EFalse if not */ -TBool Csymbian_ua_guiContainerView::CallSoftKeyPressedL( TInt aCommand ) - { - CEikEdwin *obj_url = (CEikEdwin*) iSymbian_ua_guiContainer->ComponentControl(iSymbian_ua_guiContainer->EEd_url); - CEikButtonGroupContainer* cba = CEikButtonGroupContainer::Current(); - - if (symbian_ua_anycall()) { - symbian_ua_endcall(); - return ETrue; - } - - PutMessage(_L("Making call...")); - if ( cba != NULL ) { - cba->SetCommandL(aCommand, KStHangUp); - cba->DrawDeferred(); - } - - - TUint8 url[256]; - TPtr8 aUrl(url, 256); - - HBufC *buf = obj_url->GetTextInHBufL(); - CnvUtfConverter::ConvertFromUnicodeToUtf8(aUrl, *buf); - delete buf; - - if (symbian_ua_makecall((char *)aUrl.PtrZ()) != 0) { - PutMessage(_L("Making call failed!")); - if ( cba != NULL ) { - cba->SetCommandL(aCommand, KStCall); - cba->DrawDeferred(); - } - } - - return ETrue; - } - -/** +TBool Csymbian_ua_guiContainerView::CallSoftKeyPressedL (TInt aCommand) +{ + CEikEdwin *obj_url = (CEikEdwin*) iSymbian_ua_guiContainer->ComponentControl (iSymbian_ua_guiContainer->EEd_url); + CEikButtonGroupContainer* cba = CEikButtonGroupContainer::Current(); + + if (symbian_ua_anycall()) { + symbian_ua_endcall(); + return ETrue; + } + + PutMessage (_L ("Making call...")); + + if (cba != NULL) { + cba->SetCommandL (aCommand, KStHangUp); + cba->DrawDeferred(); + } + + + TUint8 url[256]; + + TPtr8 aUrl (url, 256); + + HBufC *buf = obj_url->GetTextInHBufL(); + CnvUtfConverter::ConvertFromUnicodeToUtf8 (aUrl, *buf); + delete buf; + + if (symbian_ua_makecall ( (char *) aUrl.PtrZ()) != 0) { + PutMessage (_L ("Making call failed!")); + + if (cba != NULL) { + cba->SetCommandL (aCommand, KStCall); + cba->DrawDeferred(); + } + } + + return ETrue; +} + +/** * Handle the selected event. * @param aCommand the command id invoked * @return ETrue if the command was handled, EFalse if not */ -TBool Csymbian_ua_guiContainerView::HandleSettingMenuItemSelectedL( TInt aCommand ) - { - AppUi()->ActivateLocalViewL(TUid::Uid(ESymbian_ua_guiSettingItemListViewId)); - return ETrue; - } - +TBool Csymbian_ua_guiContainerView::HandleSettingMenuItemSelectedL (TInt aCommand) +{ + AppUi()->ActivateLocalViewL (TUid::Uid (ESymbian_ua_guiSettingItemListViewId)); + return ETrue; +} + // [[[ begin generated function: do not modify /** * Show the popup note for note_error * @param aOverrideText optional override text */ -void Csymbian_ua_guiContainerView::RunNote_errorL( const TDesC* aOverrideText ) - { - CAknErrorNote* note = new ( ELeave ) CAknErrorNote(); - if ( aOverrideText == NULL ) - { - HBufC* noteText = StringLoader::LoadLC( R_SYMBIAN_UA_GUI_CONTAINER_NOTE_ERROR ); - note->ExecuteLD( *noteText ); - CleanupStack::PopAndDestroy( noteText ); - } - else - { - note->ExecuteLD( *aOverrideText ); - } - } +void Csymbian_ua_guiContainerView::RunNote_errorL (const TDesC* aOverrideText) +{ + CAknErrorNote* note = new (ELeave) CAknErrorNote(); + + if (aOverrideText == NULL) { + HBufC* noteText = StringLoader::LoadLC (R_SYMBIAN_UA_GUI_CONTAINER_NOTE_ERROR); + note->ExecuteLD (*noteText); + CleanupStack::PopAndDestroy (noteText); + } else { + note->ExecuteLD (*aOverrideText); + } +} + // ]]] end generated function // [[[ begin generated function: do not modify @@ -420,20 +432,19 @@ void Csymbian_ua_guiContainerView::RunNote_errorL( const TDesC* aOverrideText ) * Show the popup note for note_info * @param aOverrideText optional override text */ -void Csymbian_ua_guiContainerView::RunNote_infoL( const TDesC* aOverrideText ) - { - CAknInformationNote* note = new ( ELeave ) CAknInformationNote(); - if ( aOverrideText == NULL ) - { - HBufC* noteText = StringLoader::LoadLC( R_SYMBIAN_UA_GUI_CONTAINER_NOTE_INFO ); - note->ExecuteLD( *noteText ); - CleanupStack::PopAndDestroy( noteText ); - } - else - { - note->ExecuteLD( *aOverrideText ); - } - } +void Csymbian_ua_guiContainerView::RunNote_infoL (const TDesC* aOverrideText) +{ + CAknInformationNote* note = new (ELeave) CAknInformationNote(); + + if (aOverrideText == NULL) { + HBufC* noteText = StringLoader::LoadLC (R_SYMBIAN_UA_GUI_CONTAINER_NOTE_INFO); + note->ExecuteLD (*noteText); + CleanupStack::PopAndDestroy (noteText); + } else { + note->ExecuteLD (*aOverrideText); + } +} + // ]]] end generated function // [[[ begin generated function: do not modify @@ -441,20 +452,19 @@ void Csymbian_ua_guiContainerView::RunNote_infoL( const TDesC* aOverrideText ) * Show the popup note for note_warning * @param aOverrideText optional override text */ -void Csymbian_ua_guiContainerView::RunNote_warningL( const TDesC* aOverrideText ) - { - CAknWarningNote* note = new ( ELeave ) CAknWarningNote(); - if ( aOverrideText == NULL ) - { - HBufC* noteText = StringLoader::LoadLC( R_SYMBIAN_UA_GUI_CONTAINER_NOTE_WARNING ); - note->ExecuteLD( *noteText ); - CleanupStack::PopAndDestroy( noteText ); - } - else - { - note->ExecuteLD( *aOverrideText ); - } - } +void Csymbian_ua_guiContainerView::RunNote_warningL (const TDesC* aOverrideText) +{ + CAknWarningNote* note = new (ELeave) CAknWarningNote(); + + if (aOverrideText == NULL) { + HBufC* noteText = StringLoader::LoadLC (R_SYMBIAN_UA_GUI_CONTAINER_NOTE_WARNING); + note->ExecuteLD (*noteText); + CleanupStack::PopAndDestroy (noteText); + } else { + note->ExecuteLD (*aOverrideText); + } +} + // ]]] end generated function // [[[ begin generated function: do not modify @@ -463,16 +473,17 @@ void Csymbian_ua_guiContainerView::RunNote_warningL( const TDesC* aOverrideText * @param aOverrideText optional override text * @return EAknSoftkeyYes (left soft key id) or 0 */ -TInt Csymbian_ua_guiContainerView::RunQry_accept_callL( const TDesC* aOverrideText ) - { - - CAknQueryDialog* queryDialog = CAknQueryDialog::NewL(); - - if ( aOverrideText != NULL ) - { - queryDialog->SetPromptL( *aOverrideText ); - } - return queryDialog->ExecuteLD( R_SYMBIAN_UA_GUI_CONTAINER_QRY_ACCEPT_CALL ); - } +TInt Csymbian_ua_guiContainerView::RunQry_accept_callL (const TDesC* aOverrideText) +{ + + CAknQueryDialog* queryDialog = CAknQueryDialog::NewL(); + + if (aOverrideText != NULL) { + queryDialog->SetPromptL (*aOverrideText); + } + + return queryDialog->ExecuteLD (R_SYMBIAN_UA_GUI_CONTAINER_QRY_ACCEPT_CALL); +} + // ]]] end generated function diff --git a/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiDocument.cpp b/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiDocument.cpp index 8eb54f8d74fed49b685ad511827c23256e1d61f4..209c9ebcec9f9a653241e1340be8fb8b382c2949 100644 --- a/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiDocument.cpp +++ b/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiDocument.cpp @@ -3,7 +3,7 @@ Name : symbian_ua_guiDocument.cpp Author : nanang Copyright : (c) 2008-2009 Teluu Inc. - Description : + Description : ======================================================================== */ // [[[ begin generated region: do not modify [Generated User Includes] @@ -15,19 +15,19 @@ * @brief Constructs the document class for the application. * @param anApplication the application instance */ -Csymbian_ua_guiDocument::Csymbian_ua_guiDocument( CEikApplication& anApplication ) - : CAknDocument( anApplication ) - { - } +Csymbian_ua_guiDocument::Csymbian_ua_guiDocument (CEikApplication& anApplication) + : CAknDocument (anApplication) +{ +} /** - * @brief Completes the second phase of Symbian object construction. - * Put initialization code that could leave here. - */ + * @brief Completes the second phase of Symbian object construction. + * Put initialization code that could leave here. + */ void Csymbian_ua_guiDocument::ConstructL() - { - } - +{ +} + /** * Symbian OS two-phase constructor. * @@ -37,21 +37,21 @@ void Csymbian_ua_guiDocument::ConstructL() * @param aApp the application instance * @return the new Csymbian_ua_guiDocument */ -Csymbian_ua_guiDocument* Csymbian_ua_guiDocument::NewL( CEikApplication& aApp ) - { - Csymbian_ua_guiDocument* self = new ( ELeave ) Csymbian_ua_guiDocument( aApp ); - CleanupStack::PushL( self ); - self->ConstructL(); - CleanupStack::Pop( self ); - return self; - } +Csymbian_ua_guiDocument* Csymbian_ua_guiDocument::NewL (CEikApplication& aApp) +{ + Csymbian_ua_guiDocument* self = new (ELeave) Csymbian_ua_guiDocument (aApp); + CleanupStack::PushL (self); + self->ConstructL(); + CleanupStack::Pop (self); + return self; +} /** * @brief Creates the application UI object for this document. * @return the new instance - */ + */ CEikAppUi* Csymbian_ua_guiDocument::CreateAppUiL() - { - return new ( ELeave ) Csymbian_ua_guiAppUi; - } - +{ + return new (ELeave) Csymbian_ua_guiAppUi; +} + diff --git a/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiSettingItemList.cpp b/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiSettingItemList.cpp index 27f3d6e5ce3c2793c376ae827d531342cea8e787..15fba37ca33e2d2bcddce2b6c92a7d8e0621c144 100644 --- a/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiSettingItemList.cpp +++ b/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiSettingItemList.cpp @@ -3,7 +3,7 @@ Name : symbian_ua_guiSettingItemList.cpp Author : nanang Copyright : (c) 2008-2009 Teluu Inc. - Description : + Description : ======================================================================== */ @@ -22,7 +22,7 @@ #include <aknpopupfieldtext.h> #include <eikappui.h> #include <aknviewappui.h> -#include <akntextsettingpage.h> +#include <akntextsettingpage.h> #include <symbian_ua_gui.rsg> // ]]] end generated region [Generated System Includes] @@ -43,8 +43,8 @@ // ]]] end generated region [Generated Constants] -_LIT(KtxDicFileName ,"settings.ini" ); - +_LIT (KtxDicFileName ,"settings.ini"); + const TInt KRegistrar = 2; const TInt KUsername = 3; const TInt KPassword = 4; @@ -55,36 +55,36 @@ const TInt KIce = 7; /** * Construct the CSymbian_ua_guiSettingItemList instance * @param aCommandObserver command observer - */ -CSymbian_ua_guiSettingItemList::CSymbian_ua_guiSettingItemList( - TSymbian_ua_guiSettingItemListSettings& aSettings, - MEikCommandObserver* aCommandObserver ) - : iSettings( aSettings ), iCommandObserver( aCommandObserver ) - { - // [[[ begin generated region: do not modify [Generated Contents] - // ]]] end generated region [Generated Contents] - - } -/** + */ +CSymbian_ua_guiSettingItemList::CSymbian_ua_guiSettingItemList ( + TSymbian_ua_guiSettingItemListSettings& aSettings, + MEikCommandObserver* aCommandObserver) + : iSettings (aSettings), iCommandObserver (aCommandObserver) +{ + // [[[ begin generated region: do not modify [Generated Contents] + // ]]] end generated region [Generated Contents] + +} + +/** * Destroy any instance variables */ CSymbian_ua_guiSettingItemList::~CSymbian_ua_guiSettingItemList() - { - // [[[ begin generated region: do not modify [Generated Contents] - // ]]] end generated region [Generated Contents] - - } +{ + // [[[ begin generated region: do not modify [Generated Contents] + // ]]] end generated region [Generated Contents] + +} /** * Handle system notification that the container's size has changed. */ void CSymbian_ua_guiSettingItemList::SizeChanged() - { - if ( ListBox() ) - { - ListBox()->SetRect( Rect() ); - } - } +{ + if (ListBox()) { + ListBox()->SetRect (Rect()); + } +} /** * Create one setting item at a time, identified by id. @@ -93,73 +93,73 @@ void CSymbian_ua_guiSettingItemList::SizeChanged() * a reference to the underlying data, which EditItemL() uses * to edit and store the value. */ -CAknSettingItem* CSymbian_ua_guiSettingItemList::CreateSettingItemL( TInt aId ) - { - switch ( aId ) - { - // [[[ begin generated region: do not modify [Initializers] - case ESymbian_ua_guiSettingItemListViewEd_registrar: - { - CAknTextSettingItem* item = new ( ELeave ) - CAknTextSettingItem( - aId, - iSettings.Ed_registrar() ); - item->SetSettingPageFlags(CAknTextSettingPage::EZeroLengthAllowed); - return item; - } - case ESymbian_ua_guiSettingItemListViewEd_user: - { - CAknTextSettingItem* item = new ( ELeave ) - CAknTextSettingItem( - aId, - iSettings.Ed_user() ); - item->SetSettingPageFlags(CAknTextSettingPage::EZeroLengthAllowed); - return item; - } - case ESymbian_ua_guiSettingItemListViewEd_password: - { - CAknPasswordSettingItem* item = new ( ELeave ) - CAknPasswordSettingItem( - aId, - CAknPasswordSettingItem::EAlpha, - iSettings.Ed_password() ); - item->SetSettingPageFlags(CAknTextSettingPage::EZeroLengthAllowed); - return item; - } - case ESymbian_ua_guiSettingItemListViewB_srtp: - { - CAknBinaryPopupSettingItem* item = new ( ELeave ) - CAknBinaryPopupSettingItem( - aId, - iSettings.B_srtp() ); - item->SetHidden( ETrue ); - return item; - } - case ESymbian_ua_guiSettingItemListViewB_ice: - { - CAknBinaryPopupSettingItem* item = new ( ELeave ) - CAknBinaryPopupSettingItem( - aId, - iSettings.B_ice() ); - item->SetHidden( ETrue ); - return item; - } - case ESymbian_ua_guiSettingItemListViewEd_stun_server: - { - CAknTextSettingItem* item = new ( ELeave ) - CAknTextSettingItem( - aId, - iSettings.Ed_stun_server() ); - item->SetHidden( ETrue ); - return item; - } - // ]]] end generated region [Initializers] - - } - - return NULL; - } - +CAknSettingItem* CSymbian_ua_guiSettingItemList::CreateSettingItemL (TInt aId) +{ + switch (aId) { + // [[[ begin generated region: do not modify [Initializers] + + case ESymbian_ua_guiSettingItemListViewEd_registrar: { + CAknTextSettingItem* item = new (ELeave) + CAknTextSettingItem ( + aId, + iSettings.Ed_registrar()); + item->SetSettingPageFlags (CAknTextSettingPage::EZeroLengthAllowed); + return item; + } + + case ESymbian_ua_guiSettingItemListViewEd_user: { + CAknTextSettingItem* item = new (ELeave) + CAknTextSettingItem ( + aId, + iSettings.Ed_user()); + item->SetSettingPageFlags (CAknTextSettingPage::EZeroLengthAllowed); + return item; + } + + case ESymbian_ua_guiSettingItemListViewEd_password: { + CAknPasswordSettingItem* item = new (ELeave) + CAknPasswordSettingItem ( + aId, + CAknPasswordSettingItem::EAlpha, + iSettings.Ed_password()); + item->SetSettingPageFlags (CAknTextSettingPage::EZeroLengthAllowed); + return item; + } + + case ESymbian_ua_guiSettingItemListViewB_srtp: { + CAknBinaryPopupSettingItem* item = new (ELeave) + CAknBinaryPopupSettingItem ( + aId, + iSettings.B_srtp()); + item->SetHidden (ETrue); + return item; + } + + case ESymbian_ua_guiSettingItemListViewB_ice: { + CAknBinaryPopupSettingItem* item = new (ELeave) + CAknBinaryPopupSettingItem ( + aId, + iSettings.B_ice()); + item->SetHidden (ETrue); + return item; + } + + case ESymbian_ua_guiSettingItemListViewEd_stun_server: { + CAknTextSettingItem* item = new (ELeave) + CAknTextSettingItem ( + aId, + iSettings.Ed_stun_server()); + item->SetHidden (ETrue); + return item; + } + + // ]]] end generated region [Initializers] + + } + + return NULL; +} + /** * Edit the setting item identified by the given id and store * the changes into the store. @@ -168,256 +168,256 @@ CAknSettingItem* CSymbian_ua_guiSettingItemList::CreateSettingItemL( TInt aId ) * always show the edit page and interactively edit the item; * false: change the item in place if possible, else show the edit page */ -void CSymbian_ua_guiSettingItemList::EditItemL ( TInt aIndex, TBool aCalledFromMenu ) - { - CAknSettingItem* item = ( *SettingItemArray() )[aIndex]; - switch ( item->Identifier() ) - { - // [[[ begin generated region: do not modify [Editing Started Invoker] - // ]]] end generated region [Editing Started Invoker] - - } - - CAknSettingItemList::EditItemL( aIndex, aCalledFromMenu ); - - TBool storeValue = ETrue; - switch ( item->Identifier() ) - { - // [[[ begin generated region: do not modify [Editing Stopped Invoker] - // ]]] end generated region [Editing Stopped Invoker] - - } - - if ( storeValue ) - { - item->StoreL(); - SaveSettingValuesL(); - } - } +void CSymbian_ua_guiSettingItemList::EditItemL (TInt aIndex, TBool aCalledFromMenu) +{ + CAknSettingItem* item = (*SettingItemArray()) [aIndex]; + + switch (item->Identifier()) { + // [[[ begin generated region: do not modify [Editing Started Invoker] + // ]]] end generated region [Editing Started Invoker] + + } + + CAknSettingItemList::EditItemL (aIndex, aCalledFromMenu); + + TBool storeValue = ETrue; + + switch (item->Identifier()) { + // [[[ begin generated region: do not modify [Editing Stopped Invoker] + // ]]] end generated region [Editing Stopped Invoker] + + } + + if (storeValue) { + item->StoreL(); + SaveSettingValuesL(); + } +} + /** * Handle the "Change" option on the Options menu. This is an * alternative to the Selection key that forces the settings page * to come up rather than changing the value in place (if possible). */ void CSymbian_ua_guiSettingItemList::ChangeSelectedItemL() - { - if ( ListBox()->CurrentItemIndex() >= 0 ) - { - EditItemL( ListBox()->CurrentItemIndex(), ETrue ); - } - } +{ + if (ListBox()->CurrentItemIndex() >= 0) { + EditItemL (ListBox()->CurrentItemIndex(), ETrue); + } +} /** * Load the initial contents of the setting items. By default, * the setting items are populated with the default values from * the design. You can override those values here. * <p> - * Note: this call alone does not update the UI. + * Note: this call alone does not update the UI. * LoadSettingsL() must be called afterwards. */ void CSymbian_ua_guiSettingItemList::LoadSettingValuesL() - { - // load values into iSettings +{ + // load values into iSettings - TFileName path; - TFileName pathWithoutDrive; - CEikonEnv::Static()->FsSession().PrivatePath( pathWithoutDrive ); + TFileName path; + TFileName pathWithoutDrive; + CEikonEnv::Static()->FsSession().PrivatePath (pathWithoutDrive); - // Extract drive letter into appDrive: + // Extract drive letter into appDrive: #ifdef __WINS__ - path.Copy( _L("c:") ); + path.Copy (_L ("c:")); #else - RProcess process; - path.Copy( process.FileName().Left(2) ); + RProcess process; + path.Copy (process.FileName().Left (2)); #endif - path.Append( pathWithoutDrive ); - path.Append( KtxDicFileName ); - - TFindFile AufFolder(CCoeEnv::Static()->FsSession()); - if(KErrNone == AufFolder.FindByDir(path, KNullDesC)) - { - CDictionaryFileStore* MyDStore = CDictionaryFileStore::OpenLC(CCoeEnv::Static()->FsSession(),AufFolder.File(), TUid::Uid(1)); - TUid FileUid; - - FileUid.iUid = KRegistrar; - if(MyDStore->IsPresentL(FileUid)) - { - RDictionaryReadStream in; - in.OpenLC(*MyDStore,FileUid); - in >> iSettings.Ed_registrar(); - CleanupStack::PopAndDestroy(1);// in - } - - FileUid.iUid = KUsername; - if(MyDStore->IsPresentL(FileUid)) - { - RDictionaryReadStream in; - in.OpenLC(*MyDStore,FileUid); - in >> iSettings.Ed_user(); - CleanupStack::PopAndDestroy(1);// in - } - - FileUid.iUid = KPassword; - if(MyDStore->IsPresentL(FileUid)) - { - RDictionaryReadStream in; - in.OpenLC(*MyDStore,FileUid); - in >> iSettings.Ed_password(); - CleanupStack::PopAndDestroy(1);// in - } - - FileUid.iUid = KStunServer; - if(MyDStore->IsPresentL(FileUid)) - { - RDictionaryReadStream in; - in.OpenLC(*MyDStore,FileUid); - in >> iSettings.Ed_stun_server(); - CleanupStack::PopAndDestroy(1);// in - } - - FileUid.iUid = KSrtp; - if(MyDStore->IsPresentL(FileUid)) - { - RDictionaryReadStream in; - in.OpenLC(*MyDStore,FileUid); - iSettings.SetB_srtp((TBool)in.ReadInt32L()); - CleanupStack::PopAndDestroy(1);// in - } - - FileUid.iUid = KIce; - if(MyDStore->IsPresentL(FileUid)) - { - RDictionaryReadStream in; - in.OpenLC(*MyDStore,FileUid); - iSettings.SetB_ice((TBool)in.ReadInt32L()); - CleanupStack::PopAndDestroy(1);// in - } - - CleanupStack::PopAndDestroy(1);// Store - } - - } - + path.Append (pathWithoutDrive); + path.Append (KtxDicFileName); + + TFindFile AufFolder (CCoeEnv::Static()->FsSession()); + + if (KErrNone == AufFolder.FindByDir (path, KNullDesC)) { + CDictionaryFileStore* MyDStore = CDictionaryFileStore::OpenLC (CCoeEnv::Static()->FsSession(),AufFolder.File(), TUid::Uid (1)); + TUid FileUid; + + FileUid.iUid = KRegistrar; + + if (MyDStore->IsPresentL (FileUid)) { + RDictionaryReadStream in; + in.OpenLC (*MyDStore,FileUid); + in >> iSettings.Ed_registrar(); + CleanupStack::PopAndDestroy (1);// in + } + + FileUid.iUid = KUsername; + + if (MyDStore->IsPresentL (FileUid)) { + RDictionaryReadStream in; + in.OpenLC (*MyDStore,FileUid); + in >> iSettings.Ed_user(); + CleanupStack::PopAndDestroy (1);// in + } + + FileUid.iUid = KPassword; + + if (MyDStore->IsPresentL (FileUid)) { + RDictionaryReadStream in; + in.OpenLC (*MyDStore,FileUid); + in >> iSettings.Ed_password(); + CleanupStack::PopAndDestroy (1);// in + } + + FileUid.iUid = KStunServer; + + if (MyDStore->IsPresentL (FileUid)) { + RDictionaryReadStream in; + in.OpenLC (*MyDStore,FileUid); + in >> iSettings.Ed_stun_server(); + CleanupStack::PopAndDestroy (1);// in + } + + FileUid.iUid = KSrtp; + + if (MyDStore->IsPresentL (FileUid)) { + RDictionaryReadStream in; + in.OpenLC (*MyDStore,FileUid); + iSettings.SetB_srtp ( (TBool) in.ReadInt32L()); + CleanupStack::PopAndDestroy (1);// in + } + + FileUid.iUid = KIce; + + if (MyDStore->IsPresentL (FileUid)) { + RDictionaryReadStream in; + in.OpenLC (*MyDStore,FileUid); + iSettings.SetB_ice ( (TBool) in.ReadInt32L()); + CleanupStack::PopAndDestroy (1);// in + } + + CleanupStack::PopAndDestroy (1);// Store + } + +} + /** * Save the contents of the setting items. Note, this is called * whenever an item is changed and stored to the model, so it * may be called multiple times or not at all. */ void CSymbian_ua_guiSettingItemList::SaveSettingValuesL() - { - // store values from iSettings +{ + // store values from iSettings - TFileName path; - TFileName pathWithoutDrive; - CEikonEnv::Static()->FsSession().PrivatePath( pathWithoutDrive ); + TFileName path; + TFileName pathWithoutDrive; + CEikonEnv::Static()->FsSession().PrivatePath (pathWithoutDrive); - // Extract drive letter into appDrive: + // Extract drive letter into appDrive: #ifdef __WINS__ - path.Copy( _L("c:") ); + path.Copy (_L ("c:")); #else - RProcess process; - path.Copy( process.FileName().Left(2) ); - - if(path.Compare(_L("c")) || path.Compare(_L("C"))) - CEikonEnv::Static()->FsSession().CreatePrivatePath(EDriveC); - else if(path.Compare(_L("e")) || path.Compare(_L("E"))) - CEikonEnv::Static()->FsSession().CreatePrivatePath(EDriveE); + RProcess process; + path.Copy (process.FileName().Left (2)); + + if (path.Compare (_L ("c")) || path.Compare (_L ("C"))) + CEikonEnv::Static()->FsSession().CreatePrivatePath (EDriveC); + else if (path.Compare (_L ("e")) || path.Compare (_L ("E"))) + CEikonEnv::Static()->FsSession().CreatePrivatePath (EDriveE); + #endif - path.Append( pathWithoutDrive ); - path.Append( KtxDicFileName ); - - TFindFile AufFolder(CCoeEnv::Static()->FsSession()); - if(KErrNone == AufFolder.FindByDir(path, KNullDesC)) - { - User::LeaveIfError(CCoeEnv::Static()->FsSession().Delete(AufFolder.File())); - } - - CDictionaryFileStore* MyDStore = CDictionaryFileStore::OpenLC(CCoeEnv::Static()->FsSession(),path, TUid::Uid(1)); - - TUid FileUid = {0x0}; - - FileUid.iUid = KRegistrar; - RDictionaryWriteStream out1; - out1.AssignLC(*MyDStore,FileUid); - out1 << iSettings.Ed_registrar(); - out1.CommitL(); - CleanupStack::PopAndDestroy(1);// out2 - - FileUid.iUid = KUsername; - RDictionaryWriteStream out2; - out2.AssignLC(*MyDStore,FileUid); - out2 << iSettings.Ed_user(); - out2.CommitL(); - CleanupStack::PopAndDestroy(1);// out2 - - FileUid.iUid = KPassword; - RDictionaryWriteStream out3; - out3.AssignLC(*MyDStore,FileUid); - out3 << iSettings.Ed_password(); - out3.CommitL(); - CleanupStack::PopAndDestroy(1);// out2 - - FileUid.iUid = KStunServer; - RDictionaryWriteStream out4; - out4.AssignLC(*MyDStore,FileUid); - out4 << iSettings.Ed_stun_server(); - out4.CommitL(); - CleanupStack::PopAndDestroy(1);// out2 - - FileUid.iUid = KSrtp; - RDictionaryWriteStream out5; - out5.AssignLC(*MyDStore,FileUid); - out5.WriteInt32L(iSettings.B_srtp()); - out5.CommitL(); - CleanupStack::PopAndDestroy(1);// out1 - - FileUid.iUid = KIce; - RDictionaryWriteStream out6; - out6.AssignLC(*MyDStore,FileUid); - out6.WriteInt32L(iSettings.B_ice()); - out6.CommitL(); - CleanupStack::PopAndDestroy(1);// out1 - - MyDStore->CommitL(); - CleanupStack::PopAndDestroy(1);// Store - - } - - -/** + path.Append (pathWithoutDrive); + + path.Append (KtxDicFileName); + + TFindFile AufFolder (CCoeEnv::Static()->FsSession()); + + if (KErrNone == AufFolder.FindByDir (path, KNullDesC)) { + User::LeaveIfError (CCoeEnv::Static()->FsSession().Delete (AufFolder.File())); + } + + CDictionaryFileStore* MyDStore = CDictionaryFileStore::OpenLC (CCoeEnv::Static()->FsSession(),path, TUid::Uid (1)); + + TUid FileUid = {0x0}; + + FileUid.iUid = KRegistrar; + RDictionaryWriteStream out1; + out1.AssignLC (*MyDStore,FileUid); + out1 << iSettings.Ed_registrar(); + out1.CommitL(); + CleanupStack::PopAndDestroy (1);// out2 + + FileUid.iUid = KUsername; + RDictionaryWriteStream out2; + out2.AssignLC (*MyDStore,FileUid); + out2 << iSettings.Ed_user(); + out2.CommitL(); + CleanupStack::PopAndDestroy (1);// out2 + + FileUid.iUid = KPassword; + RDictionaryWriteStream out3; + out3.AssignLC (*MyDStore,FileUid); + out3 << iSettings.Ed_password(); + out3.CommitL(); + CleanupStack::PopAndDestroy (1);// out2 + + FileUid.iUid = KStunServer; + RDictionaryWriteStream out4; + out4.AssignLC (*MyDStore,FileUid); + out4 << iSettings.Ed_stun_server(); + out4.CommitL(); + CleanupStack::PopAndDestroy (1);// out2 + + FileUid.iUid = KSrtp; + RDictionaryWriteStream out5; + out5.AssignLC (*MyDStore,FileUid); + out5.WriteInt32L (iSettings.B_srtp()); + out5.CommitL(); + CleanupStack::PopAndDestroy (1);// out1 + + FileUid.iUid = KIce; + RDictionaryWriteStream out6; + out6.AssignLC (*MyDStore,FileUid); + out6.WriteInt32L (iSettings.B_ice()); + out6.CommitL(); + CleanupStack::PopAndDestroy (1);// out1 + + MyDStore->CommitL(); + CleanupStack::PopAndDestroy (1);// Store + +} + + +/** * Handle global resource changes, such as scalable UI or skin events (override) */ -void CSymbian_ua_guiSettingItemList::HandleResourceChange( TInt aType ) - { - CAknSettingItemList::HandleResourceChange( aType ); - SetRect( iAvkonViewAppUi->View( TUid::Uid( ESymbian_ua_guiSettingItemListViewId ) )->ClientRect() ); - // [[[ begin generated region: do not modify [Generated Contents] - // ]]] end generated region [Generated Contents] - - } - -/** +void CSymbian_ua_guiSettingItemList::HandleResourceChange (TInt aType) +{ + CAknSettingItemList::HandleResourceChange (aType); + SetRect (iAvkonViewAppUi->View (TUid::Uid (ESymbian_ua_guiSettingItemListViewId))->ClientRect()); + // [[[ begin generated region: do not modify [Generated Contents] + // ]]] end generated region [Generated Contents] + +} + +/** * Handle key event (override) * @param aKeyEvent key event * @param aType event code * @return EKeyWasConsumed if the event was handled, else EKeyWasNotConsumed */ -TKeyResponse CSymbian_ua_guiSettingItemList::OfferKeyEventL( - const TKeyEvent& aKeyEvent, - TEventCode aType ) - { - // [[[ begin generated region: do not modify [Generated Contents] - // ]]] end generated region [Generated Contents] - - if ( aKeyEvent.iCode == EKeyLeftArrow - || aKeyEvent.iCode == EKeyRightArrow ) - { - // allow the tab control to get the arrow keys - return EKeyWasNotConsumed; - } - - return CAknSettingItemList::OfferKeyEventL( aKeyEvent, aType ); - } - +TKeyResponse CSymbian_ua_guiSettingItemList::OfferKeyEventL ( + const TKeyEvent& aKeyEvent, + TEventCode aType) +{ + // [[[ begin generated region: do not modify [Generated Contents] + // ]]] end generated region [Generated Contents] + + if (aKeyEvent.iCode == EKeyLeftArrow + || aKeyEvent.iCode == EKeyRightArrow) { + // allow the tab control to get the arrow keys + return EKeyWasNotConsumed; + } + + return CAknSettingItemList::OfferKeyEventL (aKeyEvent, aType); +} + diff --git a/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiSettingItemListView.cpp b/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiSettingItemListView.cpp index 243ff994c57092b657a7f86bcee643b8393be22e..2a158b4bb501e994f02206f14f4330c86a027094 100644 --- a/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiSettingItemListView.cpp +++ b/sflphone-common/libs/pjproject/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiSettingItemListView.cpp @@ -3,7 +3,7 @@ Name : symbian_ua_guiSettingItemListView.cpp Author : nanang Copyright : (c) 2008-2009 Teluu Inc. - Description : + Description : ======================================================================== */ // [[[ begin generated region: do not modify [Generated System Includes] @@ -36,21 +36,22 @@ * code that could leave. */ Csymbian_ua_guiSettingItemListView::Csymbian_ua_guiSettingItemListView() - { - // [[[ begin generated region: do not modify [Generated Contents] - // ]]] end generated region [Generated Contents] - - } -/** +{ + // [[[ begin generated region: do not modify [Generated Contents] + // ]]] end generated region [Generated Contents] + +} + +/** * The view's destructor removes the container from the control * stack and destroys it. */ Csymbian_ua_guiSettingItemListView::~Csymbian_ua_guiSettingItemListView() - { - // [[[ begin generated region: do not modify [Generated Contents] - // ]]] end generated region [Generated Contents] - - } +{ + // [[[ begin generated region: do not modify [Generated Contents] + // ]]] end generated region [Generated Contents] + +} /** * Symbian two-phase constructor. @@ -59,11 +60,11 @@ Csymbian_ua_guiSettingItemListView::~Csymbian_ua_guiSettingItemListView() * @return new instance of Csymbian_ua_guiSettingItemListView */ Csymbian_ua_guiSettingItemListView* Csymbian_ua_guiSettingItemListView::NewL() - { - Csymbian_ua_guiSettingItemListView* self = Csymbian_ua_guiSettingItemListView::NewLC(); - CleanupStack::Pop( self ); - return self; - } +{ + Csymbian_ua_guiSettingItemListView* self = Csymbian_ua_guiSettingItemListView::NewLC(); + CleanupStack::Pop (self); + return self; +} /** * Symbian two-phase constructor. @@ -72,214 +73,219 @@ Csymbian_ua_guiSettingItemListView* Csymbian_ua_guiSettingItemListView::NewL() * @return new instance of Csymbian_ua_guiSettingItemListView */ Csymbian_ua_guiSettingItemListView* Csymbian_ua_guiSettingItemListView::NewLC() - { - Csymbian_ua_guiSettingItemListView* self = new ( ELeave ) Csymbian_ua_guiSettingItemListView(); - CleanupStack::PushL( self ); - self->ConstructL(); - return self; - } +{ + Csymbian_ua_guiSettingItemListView* self = new (ELeave) Csymbian_ua_guiSettingItemListView(); + CleanupStack::PushL (self); + self->ConstructL(); + return self; +} /** - * Second-phase constructor for view. + * Second-phase constructor for view. * Initialize contents from resource. - */ + */ void Csymbian_ua_guiSettingItemListView::ConstructL() - { - // [[[ begin generated region: do not modify [Generated Code] - BaseConstructL( R_SYMBIAN_UA_GUI_SETTING_ITEM_LIST_SYMBIAN_UA_GUI_SETTING_ITEM_LIST_VIEW ); - // ]]] end generated region [Generated Code] - - // add your own initialization code here - } - +{ + // [[[ begin generated region: do not modify [Generated Code] + BaseConstructL (R_SYMBIAN_UA_GUI_SETTING_ITEM_LIST_SYMBIAN_UA_GUI_SETTING_ITEM_LIST_VIEW); + // ]]] end generated region [Generated Code] + + // add your own initialization code here +} + /** * @return The UID for this view */ TUid Csymbian_ua_guiSettingItemListView::Id() const - { - return TUid::Uid( ESymbian_ua_guiSettingItemListViewId ); - } +{ + return TUid::Uid (ESymbian_ua_guiSettingItemListViewId); +} /** * Handle a command for this view (override) * @param aCommand command id to be handled */ -void Csymbian_ua_guiSettingItemListView::HandleCommandL( TInt aCommand ) - { - // [[[ begin generated region: do not modify [Generated Code] - TBool commandHandled = EFalse; - switch ( aCommand ) - { // code to dispatch to the AknView's menu and CBA commands is generated here - - case EAknSoftkeySave: - commandHandled = HandleControlPaneRightSoftKeyPressedL( aCommand ); - break; - case ESymbian_ua_guiSettingItemListViewMenuItem1Command: - commandHandled = HandleChangeSelectedSettingItemL( aCommand ); - break; - default: - break; - } - - - if ( !commandHandled ) - { - - } - // ]]] end generated region [Generated Code] - - } +void Csymbian_ua_guiSettingItemListView::HandleCommandL (TInt aCommand) +{ + // [[[ begin generated region: do not modify [Generated Code] + TBool commandHandled = EFalse; + + switch (aCommand) { // code to dispatch to the AknView's menu and CBA commands is generated here + + case EAknSoftkeySave: + commandHandled = HandleControlPaneRightSoftKeyPressedL (aCommand); + break; + + case ESymbian_ua_guiSettingItemListViewMenuItem1Command: + commandHandled = HandleChangeSelectedSettingItemL (aCommand); + break; + + default: + break; + } + + + if (!commandHandled) { + + } + + // ]]] end generated region [Generated Code] + +} /** - * Handles user actions during activation of the view, + * Handles user actions during activation of the view, * such as initializing the content. */ -void Csymbian_ua_guiSettingItemListView::DoActivateL( - const TVwsViewId& /*aPrevViewId*/, - TUid /*aCustomMessageId*/, - const TDesC8& /*aCustomMessage*/ ) - { - // [[[ begin generated region: do not modify [Generated Contents] - SetupStatusPaneL(); - - CEikButtonGroupContainer* cba = AppUi()->Cba(); - if ( cba != NULL ) - { - cba->MakeVisible( EFalse ); - } - - if ( iSymbian_ua_guiSettingItemList == NULL ) - { - iSettings = TSymbian_ua_guiSettingItemListSettings::NewL(); - iSymbian_ua_guiSettingItemList = new ( ELeave ) CSymbian_ua_guiSettingItemList( *iSettings, this ); - iSymbian_ua_guiSettingItemList->SetMopParent( this ); - iSymbian_ua_guiSettingItemList->ConstructFromResourceL( R_SYMBIAN_UA_GUI_SETTING_ITEM_LIST_SYMBIAN_UA_GUI_SETTING_ITEM_LIST ); - iSymbian_ua_guiSettingItemList->ActivateL(); - iSymbian_ua_guiSettingItemList->LoadSettingValuesL(); - iSymbian_ua_guiSettingItemList->LoadSettingsL(); - AppUi()->AddToStackL( *this, iSymbian_ua_guiSettingItemList ); - } - // ]]] end generated region [Generated Contents] - - } +void Csymbian_ua_guiSettingItemListView::DoActivateL ( + const TVwsViewId& /*aPrevViewId*/, + TUid /*aCustomMessageId*/, + const TDesC8& /*aCustomMessage*/) +{ + // [[[ begin generated region: do not modify [Generated Contents] + SetupStatusPaneL(); + + CEikButtonGroupContainer* cba = AppUi()->Cba(); + + if (cba != NULL) { + cba->MakeVisible (EFalse); + } + + if (iSymbian_ua_guiSettingItemList == NULL) { + iSettings = TSymbian_ua_guiSettingItemListSettings::NewL(); + iSymbian_ua_guiSettingItemList = new (ELeave) CSymbian_ua_guiSettingItemList (*iSettings, this); + iSymbian_ua_guiSettingItemList->SetMopParent (this); + iSymbian_ua_guiSettingItemList->ConstructFromResourceL (R_SYMBIAN_UA_GUI_SETTING_ITEM_LIST_SYMBIAN_UA_GUI_SETTING_ITEM_LIST); + iSymbian_ua_guiSettingItemList->ActivateL(); + iSymbian_ua_guiSettingItemList->LoadSettingValuesL(); + iSymbian_ua_guiSettingItemList->LoadSettingsL(); + AppUi()->AddToStackL (*this, iSymbian_ua_guiSettingItemList); + } + + // ]]] end generated region [Generated Contents] + +} /** */ void Csymbian_ua_guiSettingItemListView::DoDeactivate() - { - // [[[ begin generated region: do not modify [Generated Contents] - CleanupStatusPane(); - - CEikButtonGroupContainer* cba = AppUi()->Cba(); - if ( cba != NULL ) - { - cba->MakeVisible( ETrue ); - cba->DrawDeferred(); - } - - if ( iSymbian_ua_guiSettingItemList != NULL ) - { - AppUi()->RemoveFromStack( iSymbian_ua_guiSettingItemList ); - delete iSymbian_ua_guiSettingItemList; - iSymbian_ua_guiSettingItemList = NULL; - delete iSettings; - iSettings = NULL; - } - // ]]] end generated region [Generated Contents] - - } +{ + // [[[ begin generated region: do not modify [Generated Contents] + CleanupStatusPane(); + + CEikButtonGroupContainer* cba = AppUi()->Cba(); + + if (cba != NULL) { + cba->MakeVisible (ETrue); + cba->DrawDeferred(); + } + + if (iSymbian_ua_guiSettingItemList != NULL) { + AppUi()->RemoveFromStack (iSymbian_ua_guiSettingItemList); + delete iSymbian_ua_guiSettingItemList; + iSymbian_ua_guiSettingItemList = NULL; + delete iSettings; + iSettings = NULL; + } + + // ]]] end generated region [Generated Contents] + +} // [[[ begin generated function: do not modify void Csymbian_ua_guiSettingItemListView::SetupStatusPaneL() - { - // reset the context pane - TUid contextPaneUid = TUid::Uid( EEikStatusPaneUidContext ); - CEikStatusPaneBase::TPaneCapabilities subPaneContext = - StatusPane()->PaneCapabilities( contextPaneUid ); - if ( subPaneContext.IsPresent() && subPaneContext.IsAppOwned() ) - { - CAknContextPane* context = static_cast< CAknContextPane* > ( - StatusPane()->ControlL( contextPaneUid ) ); - context->SetPictureToDefaultL(); - } - - // setup the title pane - TUid titlePaneUid = TUid::Uid( EEikStatusPaneUidTitle ); - CEikStatusPaneBase::TPaneCapabilities subPaneTitle = - StatusPane()->PaneCapabilities( titlePaneUid ); - if ( subPaneTitle.IsPresent() && subPaneTitle.IsAppOwned() ) - { - CAknTitlePane* title = static_cast< CAknTitlePane* >( - StatusPane()->ControlL( titlePaneUid ) ); - TResourceReader reader; - iEikonEnv->CreateResourceReaderLC( reader, R_SYMBIAN_UA_GUI_SETTING_ITEM_LIST_TITLE_RESOURCE ); - title->SetFromResourceL( reader ); - CleanupStack::PopAndDestroy(); // reader internal state - } - - } +{ + // reset the context pane + TUid contextPaneUid = TUid::Uid (EEikStatusPaneUidContext); + CEikStatusPaneBase::TPaneCapabilities subPaneContext = + StatusPane()->PaneCapabilities (contextPaneUid); + + if (subPaneContext.IsPresent() && subPaneContext.IsAppOwned()) { + CAknContextPane* context = static_cast< CAknContextPane* > ( + StatusPane()->ControlL (contextPaneUid)); + context->SetPictureToDefaultL(); + } + + // setup the title pane + TUid titlePaneUid = TUid::Uid (EEikStatusPaneUidTitle); + + CEikStatusPaneBase::TPaneCapabilities subPaneTitle = + StatusPane()->PaneCapabilities (titlePaneUid); + + if (subPaneTitle.IsPresent() && subPaneTitle.IsAppOwned()) { + CAknTitlePane* title = static_cast< CAknTitlePane* > ( + StatusPane()->ControlL (titlePaneUid)); + TResourceReader reader; + iEikonEnv->CreateResourceReaderLC (reader, R_SYMBIAN_UA_GUI_SETTING_ITEM_LIST_TITLE_RESOURCE); + title->SetFromResourceL (reader); + CleanupStack::PopAndDestroy(); // reader internal state + } + +} + // ]]] end generated function // [[[ begin generated function: do not modify void Csymbian_ua_guiSettingItemListView::CleanupStatusPane() - { - } +{ +} + // ]]] end generated function -/** +/** * Handle status pane size change for this view (override) */ void Csymbian_ua_guiSettingItemListView::HandleStatusPaneSizeChange() - { - CAknView::HandleStatusPaneSizeChange(); - - // this may fail, but we're not able to propagate exceptions here - TInt result; - TRAP( result, SetupStatusPaneL() ); - } - -/** +{ + CAknView::HandleStatusPaneSizeChange(); + + // this may fail, but we're not able to propagate exceptions here + TInt result; + TRAP (result, SetupStatusPaneL()); +} + +/** * Handle the selected event. * @param aCommand the command id invoked * @return ETrue if the command was handled, EFalse if not */ -TBool Csymbian_ua_guiSettingItemListView::HandleChangeSelectedSettingItemL( TInt aCommand ) - { - iSymbian_ua_guiSettingItemList->ChangeSelectedItemL(); - return ETrue; - } - -/** +TBool Csymbian_ua_guiSettingItemListView::HandleChangeSelectedSettingItemL (TInt aCommand) +{ + iSymbian_ua_guiSettingItemList->ChangeSelectedItemL(); + return ETrue; +} + +/** * Handle the rightSoftKeyPressed event. * @return ETrue if the command was handled, EFalse if not */ -TBool Csymbian_ua_guiSettingItemListView::HandleControlPaneRightSoftKeyPressedL( TInt aCommand ) - { - TUint8 domain[256] = {0}; - TPtr8 cDomain(domain, sizeof(domain)); - TUint8 user[64] = {0}; - TPtr8 cUser(user, sizeof(user)); - TUint8 pass[64] = {0}; - TPtr8 cPass(pass, sizeof(pass)); - - cDomain.Copy(iSettings->Ed_registrar()); - cUser.Copy(iSettings->Ed_user()); - cPass.Copy(iSettings->Ed_password()); - symbian_ua_set_account((char*)domain, (char*)user, (char*)pass, false, false); - - AppUi()->ActivateLocalViewL(TUid::Uid(ESymbian_ua_guiContainerViewId)); - return ETrue; - } - -/** +TBool Csymbian_ua_guiSettingItemListView::HandleControlPaneRightSoftKeyPressedL (TInt aCommand) +{ + TUint8 domain[256] = {0}; + TPtr8 cDomain (domain, sizeof (domain)); + TUint8 user[64] = {0}; + TPtr8 cUser (user, sizeof (user)); + TUint8 pass[64] = {0}; + TPtr8 cPass (pass, sizeof (pass)); + + cDomain.Copy (iSettings->Ed_registrar()); + cUser.Copy (iSettings->Ed_user()); + cPass.Copy (iSettings->Ed_password()); + symbian_ua_set_account ( (char*) domain, (char*) user, (char*) pass, false, false); + + AppUi()->ActivateLocalViewL (TUid::Uid (ESymbian_ua_guiContainerViewId)); + return ETrue; +} + +/** * Handle the selected event. * @param aCommand the command id invoked * @return ETrue if the command was handled, EFalse if not */ -TBool Csymbian_ua_guiSettingItemListView::HandleCancelMenuItemSelectedL( TInt aCommand ) - { - AppUi()->ActivateLocalViewL(TUid::Uid(ESymbian_ua_guiContainerViewId)); - return ETrue; - } - +TBool Csymbian_ua_guiSettingItemListView::HandleCancelMenuItemSelectedL (TInt aCommand) +{ + AppUi()->ActivateLocalViewL (TUid::Uid (ESymbian_ua_guiContainerViewId)); + return ETrue; +} + diff --git a/sflphone-common/libs/pjproject/pjsip-apps/src/symsndtest/app_main.cpp b/sflphone-common/libs/pjproject/pjsip-apps/src/symsndtest/app_main.cpp index b270fa71b2efca391ffd58cc25f9875f6252fd26..b4c95f7b078771a784a8736d538bfe58a9093931 100644 --- a/sflphone-common/libs/pjproject/pjsip-apps/src/symsndtest/app_main.cpp +++ b/sflphone-common/libs/pjproject/pjsip-apps/src/symsndtest/app_main.cpp @@ -1,5 +1,5 @@ /* $Id: app_main.cpp 2821 2009-06-30 13:37:26Z nanang $ */ -/* +/* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org> * @@ -15,7 +15,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <pjmedia-audiodev/audiodev.h> #include <pjmedia/delaybuf.h> @@ -45,24 +45,24 @@ pj_pool_t *pool; pjmedia_delay_buf *delaybuf; /* Logging callback */ -static void log_writer(int level, const char *buf, unsigned len) +static void log_writer (int level, const char *buf, unsigned len) { static wchar_t buf16[PJ_LOG_MAX_SIZE]; - PJ_UNUSED_ARG(level); + PJ_UNUSED_ARG (level); - pj_ansi_to_unicode(buf, len, buf16, PJ_ARRAY_SIZE(buf16)); + pj_ansi_to_unicode (buf, len, buf16, PJ_ARRAY_SIZE (buf16)); - TPtrC16 aBuf((const TUint16*)buf16, (TInt)len); - console->Write(aBuf); + TPtrC16 aBuf ( (const TUint16*) buf16, (TInt) len); + console->Write (aBuf); } /* perror util */ -static void app_perror(const char *title, pj_status_t status) +static void app_perror (const char *title, pj_status_t status) { char errmsg[PJ_ERR_MSG_SIZE]; - pj_strerror(status, errmsg, sizeof(errmsg)); - PJ_LOG(1,(THIS_FILE, "Error: %s: %s", title, errmsg)); + pj_strerror (status, errmsg, sizeof (errmsg)); + PJ_LOG (1, (THIS_FILE, "Error: %s: %s", title, errmsg)); } /* Application init */ @@ -72,59 +72,65 @@ static pj_status_t app_init() pj_status_t status; /* Redirect log */ - pj_log_set_log_func((void (*)(int,const char*,int)) &log_writer); - pj_log_set_decor(PJ_LOG_HAS_NEWLINE); - pj_log_set_level(3); + pj_log_set_log_func ( (void (*) (int,const char*,int)) &log_writer); + pj_log_set_decor (PJ_LOG_HAS_NEWLINE); + pj_log_set_level (3); /* Init pjlib */ status = pj_init(); + if (status != PJ_SUCCESS) { - app_perror("pj_init()", status); - return status; + app_perror ("pj_init()", status); + return status; } - pj_caching_pool_init(&cp, NULL, 0); + pj_caching_pool_init (&cp, NULL, 0); /* Init sound subsystem */ - status = pjmedia_aud_subsys_init(&cp.factory); + status = pjmedia_aud_subsys_init (&cp.factory); + if (status != PJ_SUCCESS) { - app_perror("pjmedia_snd_init()", status); - pj_caching_pool_destroy(&cp); - pj_shutdown(); - return status; + app_perror ("pjmedia_snd_init()", status); + pj_caching_pool_destroy (&cp); + pj_shutdown(); + return status; } count = pjmedia_aud_dev_count(); - PJ_LOG(3,(THIS_FILE, "Device count: %d", count)); + + PJ_LOG (3, (THIS_FILE, "Device count: %d", count)); + for (i=0; i<count; ++i) { - pjmedia_aud_dev_info info; - pj_status_t status; - - status = pjmedia_aud_dev_get_info(i, &info); - pj_assert(status == PJ_SUCCESS); - PJ_LOG(3, (THIS_FILE, "%d: %s %d/%d %dHz", - i, info.name, info.input_count, info.output_count, - info.default_samples_per_sec)); + pjmedia_aud_dev_info info; + pj_status_t status; + + status = pjmedia_aud_dev_get_info (i, &info); + pj_assert (status == PJ_SUCCESS); + PJ_LOG (3, (THIS_FILE, "%d: %s %d/%d %dHz", + i, info.name, info.input_count, info.output_count, + info.default_samples_per_sec)); } /* Create pool */ - pool = pj_pool_create(&cp.factory, THIS_FILE, 512, 512, NULL); + pool = pj_pool_create (&cp.factory, THIS_FILE, 512, 512, NULL); + if (pool == NULL) { - app_perror("pj_pool_create()", status); - pj_caching_pool_destroy(&cp); - pj_shutdown(); - return status; + app_perror ("pj_pool_create()", status); + pj_caching_pool_destroy (&cp); + pj_shutdown(); + return status; } /* Init delay buffer */ - status = pjmedia_delay_buf_create(pool, THIS_FILE, CLOCK_RATE, - SAMPLES_PER_FRAME, CHANNEL_COUNT, - 0, 0, &delaybuf); + status = pjmedia_delay_buf_create (pool, THIS_FILE, CLOCK_RATE, + SAMPLES_PER_FRAME, CHANNEL_COUNT, + 0, 0, &delaybuf); + if (status != PJ_SUCCESS) { - app_perror("pjmedia_delay_buf_create()", status); + app_perror ("pjmedia_delay_buf_create()", status); //pj_caching_pool_destroy(&cp); - //pj_shutdown(); - //return status; + //pj_shutdown(); + //return status; } return PJ_SUCCESS; @@ -132,29 +138,30 @@ static pj_status_t app_init() /* Sound capture callback */ -static pj_status_t rec_cb(void *user_data, - pjmedia_frame *frame) +static pj_status_t rec_cb (void *user_data, + pjmedia_frame *frame) { - PJ_UNUSED_ARG(user_data); + PJ_UNUSED_ARG (user_data); - pjmedia_delay_buf_put(delaybuf, (pj_int16_t*)frame->buf); + pjmedia_delay_buf_put (delaybuf, (pj_int16_t*) frame->buf); if (frame->size != SAMPLES_PER_FRAME*2) { - PJ_LOG(3, (THIS_FILE, "Size captured = %u", - frame->size)); + PJ_LOG (3, (THIS_FILE, "Size captured = %u", + frame->size)); } ++rec_cnt; + return PJ_SUCCESS; } /* Play cb */ -static pj_status_t play_cb(void *user_data, - pjmedia_frame *frame) +static pj_status_t play_cb (void *user_data, + pjmedia_frame *frame) { - PJ_UNUSED_ARG(user_data); + PJ_UNUSED_ARG (user_data); - pjmedia_delay_buf_get(delaybuf, (pj_int16_t*)frame->buf); + pjmedia_delay_buf_get (delaybuf, (pj_int16_t*) frame->buf); frame->size = SAMPLES_PER_FRAME*2; frame->type = PJMEDIA_FRAME_TYPE_AUDIO; @@ -163,39 +170,43 @@ static pj_status_t play_cb(void *user_data, } /* Start sound */ -static pj_status_t snd_start(unsigned flag) +static pj_status_t snd_start (unsigned flag) { pjmedia_aud_param param; pj_status_t status; if (strm != NULL) { - app_perror("snd already open", PJ_EINVALIDOP); - return PJ_EINVALIDOP; + app_perror ("snd already open", PJ_EINVALIDOP); + return PJ_EINVALIDOP; } - pjmedia_aud_dev_default_param(0, ¶m); + pjmedia_aud_dev_default_param (0, ¶m); + param.channel_count = CHANNEL_COUNT; param.clock_rate = CLOCK_RATE; param.samples_per_frame = SAMPLES_PER_FRAME; param.dir = (pjmedia_dir) flag; - status = pjmedia_aud_stream_create(¶m, &rec_cb, &play_cb, NULL, &strm); + status = pjmedia_aud_stream_create (¶m, &rec_cb, &play_cb, NULL, &strm); + if (status != PJ_SUCCESS) { - app_perror("snd open", status); - return status; + app_perror ("snd open", status); + return status; } rec_cnt = play_cnt = 0; - pj_gettimeofday(&t_start); - pjmedia_delay_buf_reset(delaybuf); + pj_gettimeofday (&t_start); + + pjmedia_delay_buf_reset (delaybuf); + + status = pjmedia_aud_stream_start (strm); - status = pjmedia_aud_stream_start(strm); if (status != PJ_SUCCESS) { - app_perror("snd start", status); - pjmedia_aud_stream_destroy(strm); - strm = NULL; - return status; + app_perror ("snd start", status); + pjmedia_aud_stream_destroy (strm); + strm = NULL; + return status; } return PJ_SUCCESS; @@ -208,23 +219,26 @@ static pj_status_t snd_stop() pj_status_t status; if (strm == NULL) { - app_perror("snd not open", PJ_EINVALIDOP); - return PJ_EINVALIDOP; + app_perror ("snd not open", PJ_EINVALIDOP); + return PJ_EINVALIDOP; } - status = pjmedia_aud_stream_stop(strm); + status = pjmedia_aud_stream_stop (strm); + if (status != PJ_SUCCESS) { - app_perror("snd failed to stop", status); + app_perror ("snd failed to stop", status); } - status = pjmedia_aud_stream_destroy(strm); + + status = pjmedia_aud_stream_destroy (strm); + strm = NULL; - pj_gettimeofday(&now); - PJ_TIME_VAL_SUB(now, t_start); + pj_gettimeofday (&now); + PJ_TIME_VAL_SUB (now, t_start); - PJ_LOG(3,(THIS_FILE, "Duration: %d.%03d", now.sec, now.msec)); - PJ_LOG(3,(THIS_FILE, "Captured: %d", rec_cnt)); - PJ_LOG(3,(THIS_FILE, "Played: %d", play_cnt)); + PJ_LOG (3, (THIS_FILE, "Duration: %d.%03d", now.sec, now.msec)); + PJ_LOG (3, (THIS_FILE, "Captured: %d", rec_cnt)); + PJ_LOG (3, (THIS_FILE, "Played: %d", play_cnt)); return status; } @@ -233,12 +247,16 @@ static pj_status_t snd_stop() static void app_fini() { if (strm) - snd_stop(); + snd_stop(); pjmedia_aud_subsys_shutdown(); - pjmedia_delay_buf_destroy(delaybuf); - pj_pool_release(pool); - pj_caching_pool_destroy(&cp); + + pjmedia_delay_buf_destroy (delaybuf); + + pj_pool_release (pool); + + pj_caching_pool_destroy (&cp); + pj_shutdown(); } @@ -251,37 +269,38 @@ static void app_fini() class ConsoleUI : public CActive { -public: - ConsoleUI(CConsoleBase *con); - // Run console UI - void Run(); + public: + ConsoleUI (CConsoleBase *con); + + // Run console UI + void Run(); - // Stop - void Stop(); + // Stop + void Stop(); -protected: - // Cancel asynchronous read. - void DoCancel(); + protected: + // Cancel asynchronous read. + void DoCancel(); - // Implementation: called when read has completed. - void RunL(); + // Implementation: called when read has completed. + void RunL(); -private: - CConsoleBase *con_; + private: + CConsoleBase *con_; }; -ConsoleUI::ConsoleUI(CConsoleBase *con) -: CActive(EPriorityUserInput), con_(con) +ConsoleUI::ConsoleUI (CConsoleBase *con) + : CActive (EPriorityUserInput), con_ (con) { - CActiveScheduler::Add(this); + CActiveScheduler::Add (this); } // Run console UI void ConsoleUI::Run() { - con_->Read(iStatus); + con_->Read (iStatus); SetActive(); } @@ -299,13 +318,13 @@ void ConsoleUI::DoCancel() static void PrintMenu() { - PJ_LOG(3, (THIS_FILE, "\n\n" - "Menu:\n" - " a Start bidir sound\n" - " t Start recorder\n" - " p Start player\n" - " d Stop & close sound\n" - " w Quit\n")); + PJ_LOG (3, (THIS_FILE, "\n\n" + "Menu:\n" + " a Start bidir sound\n" + " t Start recorder\n" + " p Start player\n" + " d Stop & close sound\n" + " w Quit\n")); } // Implementation: called when read has completed. @@ -315,33 +334,39 @@ void ConsoleUI::RunL() pj_bool_t reschedule = PJ_TRUE; switch (kc) { - case 'w': - snd_stop(); - CActiveScheduler::Stop(); - reschedule = PJ_FALSE; - break; - case 'a': - snd_start(PJMEDIA_DIR_CAPTURE_PLAYBACK); - break; - case 't': - snd_start(PJMEDIA_DIR_CAPTURE); - break; - case 'p': - snd_start(PJMEDIA_DIR_PLAYBACK); - break; - case 'd': - snd_stop(); - break; - default: - PJ_LOG(3,(THIS_FILE, "Keycode '%c' (%d) is pressed", - kc, kc)); - break; + + case 'w': + snd_stop(); + CActiveScheduler::Stop(); + reschedule = PJ_FALSE; + break; + + case 'a': + snd_start (PJMEDIA_DIR_CAPTURE_PLAYBACK); + break; + + case 't': + snd_start (PJMEDIA_DIR_CAPTURE); + break; + + case 'p': + snd_start (PJMEDIA_DIR_PLAYBACK); + break; + + case 'd': + snd_stop(); + break; + + default: + PJ_LOG (3, (THIS_FILE, "Keycode '%c' (%d) is pressed", + kc, kc)); + break; } PrintMenu(); if (reschedule) - Run(); + Run(); } @@ -352,16 +377,18 @@ int app_main() return -1; // Run the UI - ConsoleUI *con = new ConsoleUI(console); + ConsoleUI *con = new ConsoleUI (console); con->Run(); PrintMenu(); + CActiveScheduler::Start(); delete con; app_fini(); + return 0; } diff --git a/sflphone-common/libs/pjproject/pjsip-apps/src/symsndtest/main_symbian.cpp b/sflphone-common/libs/pjproject/pjsip-apps/src/symsndtest/main_symbian.cpp index 5ed4eb83ee1f7cd6a95611455129221fb5f881a9..6b1a92f6b3f19f6f3cfa135ebfcadf8331c2f61d 100644 --- a/sflphone-common/libs/pjproject/pjsip-apps/src/symsndtest/main_symbian.cpp +++ b/sflphone-common/libs/pjproject/pjsip-apps/src/symsndtest/main_symbian.cpp @@ -1,5 +1,5 @@ /* $Id: main_symbian.cpp 2506 2009-03-12 18:11:37Z bennylp $ */ -/* +/* * Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org> * @@ -15,7 +15,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <e32std.h> @@ -29,7 +29,7 @@ CConsoleBase* console; // Needed by APS -TPtrC APP_UID = _L("A000000E"); +TPtrC APP_UID = _L ("A000000E"); int app_main(); @@ -39,13 +39,13 @@ int app_main(); LOCAL_C void DoStartL() { CActiveScheduler *scheduler = new (ELeave) CActiveScheduler; - CleanupStack::PushL(scheduler); - CActiveScheduler::Install(scheduler); + CleanupStack::PushL (scheduler); + CActiveScheduler::Install (scheduler); app_main(); - CActiveScheduler::Install(NULL); - CleanupStack::Pop(scheduler); + CActiveScheduler::Install (NULL); + CleanupStack::Pop (scheduler); delete scheduler; } @@ -62,22 +62,25 @@ GLDEF_C TInt E32Main() CTrapCleanup* cleanup = CTrapCleanup::New(); // Create output console - TRAPD(createError, console = Console::NewL(_L("Console"), TSize(KConsFullScreen,KConsFullScreen))); + TRAPD (createError, console = Console::NewL (_L ("Console"), TSize (KConsFullScreen,KConsFullScreen))); + if (createError) return createError; - TRAPD(startError, DoStartL()); + TRAPD (startError, DoStartL()); //console->Printf(_L("[press any key to close]\n")); //console->Getch(); delete console; + delete cleanup; CloseSTDLIB(); // Mark end of heap usage, detect memory leaks __UHEAP_MARKEND; + return KErrNone; } diff --git a/sflphone-common/libs/pjproject/pjsip/src/pjsip/sip_auth_parser_wrap.cpp b/sflphone-common/libs/pjproject/pjsip/src/pjsip/sip_auth_parser_wrap.cpp index 0f58a977e0261ad97c7dd6a369e9d6bf0f20803a..c308a758b482c6e3032087ae2971a704fe227fa9 100644 --- a/sflphone-common/libs/pjproject/pjsip/src/pjsip/sip_auth_parser_wrap.cpp +++ b/sflphone-common/libs/pjproject/pjsip/src/pjsip/sip_auth_parser_wrap.cpp @@ -1,5 +1,5 @@ /* $Id: sip_auth_parser_wrap.cpp 2873 2009-08-13 11:54:35Z nanang $ */ -/* +/* * Copyright (C) 2009 Teluu Inc. (http://www.teluu.com) * * This program is free software; you can redistribute it and/or modify @@ -14,7 +14,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* diff --git a/sflphone-common/libs/pjproject/pjsip/src/pjsip/sip_dialog_wrap.cpp b/sflphone-common/libs/pjproject/pjsip/src/pjsip/sip_dialog_wrap.cpp index 1dee2f2cc88dc343cefd477751ec884e764b8a7e..9f2080f5ba268a07dbea12913cf15489ebcd3557 100644 --- a/sflphone-common/libs/pjproject/pjsip/src/pjsip/sip_dialog_wrap.cpp +++ b/sflphone-common/libs/pjproject/pjsip/src/pjsip/sip_dialog_wrap.cpp @@ -1,5 +1,5 @@ /* $Id: sip_dialog_wrap.cpp 2873 2009-08-13 11:54:35Z nanang $ */ -/* +/* * Copyright (C) 2009 Teluu Inc. (http://www.teluu.com) * * This program is free software; you can redistribute it and/or modify @@ -14,7 +14,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* diff --git a/sflphone-common/libs/pjproject/pjsip/src/pjsip/sip_endpoint_wrap.cpp b/sflphone-common/libs/pjproject/pjsip/src/pjsip/sip_endpoint_wrap.cpp index 55b157aee113a918c838e31cc782c38f3b84572f..1689f7961b6918c42bd91553930fe239b714c0a7 100644 --- a/sflphone-common/libs/pjproject/pjsip/src/pjsip/sip_endpoint_wrap.cpp +++ b/sflphone-common/libs/pjproject/pjsip/src/pjsip/sip_endpoint_wrap.cpp @@ -1,5 +1,5 @@ /* $Id: sip_endpoint_wrap.cpp 2873 2009-08-13 11:54:35Z nanang $ */ -/* +/* * Copyright (C) 2009 Teluu Inc. (http://www.teluu.com) * * This program is free software; you can redistribute it and/or modify @@ -14,7 +14,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* diff --git a/sflphone-common/libs/pjproject/pjsip/src/pjsip/sip_parser_wrap.cpp b/sflphone-common/libs/pjproject/pjsip/src/pjsip/sip_parser_wrap.cpp index e27cd0429802382394649228f3da524bfb0d0c98..95f2ca7a4fe860427acfa2ef36be84e13d369bd6 100644 --- a/sflphone-common/libs/pjproject/pjsip/src/pjsip/sip_parser_wrap.cpp +++ b/sflphone-common/libs/pjproject/pjsip/src/pjsip/sip_parser_wrap.cpp @@ -1,5 +1,5 @@ /* $Id: sip_parser_wrap.cpp 2873 2009-08-13 11:54:35Z nanang $ */ -/* +/* * Copyright (C) 2009 Teluu Inc. (http://www.teluu.com) * * This program is free software; you can redistribute it and/or modify @@ -14,7 +14,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* diff --git a/sflphone-common/libs/pjproject/pjsip/src/pjsip/sip_tel_uri_wrap.cpp b/sflphone-common/libs/pjproject/pjsip/src/pjsip/sip_tel_uri_wrap.cpp index f82281a3231d07b532bb308357b8e6bc7b69a325..fc1f818e8b33be3cc592295667691061378b722c 100644 --- a/sflphone-common/libs/pjproject/pjsip/src/pjsip/sip_tel_uri_wrap.cpp +++ b/sflphone-common/libs/pjproject/pjsip/src/pjsip/sip_tel_uri_wrap.cpp @@ -1,5 +1,5 @@ /* $Id: sip_tel_uri_wrap.cpp 2873 2009-08-13 11:54:35Z nanang $ */ -/* +/* * Copyright (C) 2009 Teluu Inc. (http://www.teluu.com) * * This program is free software; you can redistribute it and/or modify @@ -14,7 +14,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* diff --git a/sflphone-common/libs/pjproject/pjsip/src/pjsip/sip_transport_wrap.cpp b/sflphone-common/libs/pjproject/pjsip/src/pjsip/sip_transport_wrap.cpp index 7fc80e2b170b2f3e136fc11d5c2c9f13b2a78fdc..d8501b89ed21f8a397da67215b2a363614110a92 100644 --- a/sflphone-common/libs/pjproject/pjsip/src/pjsip/sip_transport_wrap.cpp +++ b/sflphone-common/libs/pjproject/pjsip/src/pjsip/sip_transport_wrap.cpp @@ -1,5 +1,5 @@ /* $Id: sip_transport_wrap.cpp 2873 2009-08-13 11:54:35Z nanang $ */ -/* +/* * Copyright (C) 2009 Teluu Inc. (http://www.teluu.com) * * This program is free software; you can redistribute it and/or modify @@ -14,7 +14,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* diff --git a/sflphone-common/libs/pjproject/pjsip/src/pjsip/sip_util_proxy_wrap.cpp b/sflphone-common/libs/pjproject/pjsip/src/pjsip/sip_util_proxy_wrap.cpp index 0e394ee4f6f80a717f879ddba901477970e572b4..caa9f9f73fceb8e9166919fccb709a4edf516222 100644 --- a/sflphone-common/libs/pjproject/pjsip/src/pjsip/sip_util_proxy_wrap.cpp +++ b/sflphone-common/libs/pjproject/pjsip/src/pjsip/sip_util_proxy_wrap.cpp @@ -1,5 +1,5 @@ /* $Id: sip_util_proxy_wrap.cpp 2873 2009-08-13 11:54:35Z nanang $ */ -/* +/* * Copyright (C) 2009 Teluu Inc. (http://www.teluu.com) * * This program is free software; you can redistribute it and/or modify @@ -14,7 +14,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* diff --git a/sflphone-common/libs/pjproject/pjsip/src/pjsip/sip_util_wrap.cpp b/sflphone-common/libs/pjproject/pjsip/src/pjsip/sip_util_wrap.cpp index 06a93441903cd22f55b1a4d6110ccd41e45c0728..b27a511a2c0e88c077f880c0da7117f9038ab99f 100644 --- a/sflphone-common/libs/pjproject/pjsip/src/pjsip/sip_util_wrap.cpp +++ b/sflphone-common/libs/pjproject/pjsip/src/pjsip/sip_util_wrap.cpp @@ -1,5 +1,5 @@ /* $Id: sip_util_wrap.cpp 2873 2009-08-13 11:54:35Z nanang $ */ -/* +/* * Copyright (C) 2009 Teluu Inc. (http://www.teluu.com) * * This program is free software; you can redistribute it and/or modify @@ -14,7 +14,7 @@ * * 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 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* diff --git a/sflphone-common/libs/pjproject/third_party/build/speex/config.h b/sflphone-common/libs/pjproject/third_party/build/speex/config.h index ba7be7a6e21d233da490e2274094580c6d416459..e04c40be4f7383fdda6c17ec53d4369e70989492 100644 --- a/sflphone-common/libs/pjproject/third_party/build/speex/config.h +++ b/sflphone-common/libs/pjproject/third_party/build/speex/config.h @@ -4,7 +4,7 @@ #if !defined(PJ_HAS_FLOATING_POINT) || PJ_HAS_FLOATING_POINT==0 # define FIXED_POINT # define USE_KISS_FFT -#else +#else # define FLOATING_POINT # define USE_SMALLFT #endif @@ -12,7 +12,7 @@ #define EXPORT #if (defined(PJ_WIN32) && PJ_WIN32!=0) || \ - (defined(PJ_WIN32_WINCE) && PJ_WIN32_WINCE != 0) + (defined(PJ_WIN32_WINCE) && PJ_WIN32_WINCE != 0) # include "../../speex/win32/config.h" #else #define inline __inline diff --git a/sflphone-common/libs/pjproject/third_party/portaudio/src/hostapi/asio/iasiothiscallresolver.cpp b/sflphone-common/libs/pjproject/third_party/portaudio/src/hostapi/asio/iasiothiscallresolver.cpp index 8dfefbd67b95ffc0d64194ab75ab7a05e1b1f72f..1b4b33781f155d3eb78dbbfe53dba83bee14ac08 100644 --- a/sflphone-common/libs/pjproject/third_party/portaudio/src/hostapi/asio/iasiothiscallresolver.cpp +++ b/sflphone-common/libs/pjproject/third_party/portaudio/src/hostapi/asio/iasiothiscallresolver.cpp @@ -71,7 +71,7 @@ (IUnknown functions) 0 virtual HRESULT STDMETHODCALLTYPE (*QueryInterface)(REFIID riid, void **ppv) = 0; 4 virtual ULONG STDMETHODCALLTYPE (*AddRef)() = 0; - 8 virtual ULONG STDMETHODCALLTYPE (*Release)() = 0; + 8 virtual ULONG STDMETHODCALLTYPE (*Release)() = 0; (IASIO functions) 12 virtual ASIOBool (*init)(void *sysHandle) = 0; @@ -128,7 +128,7 @@ with MSVC, and requires that you ship the OpenASIO DLL with your application. - + ACKNOWLEDGEMENTS Ross Bencina: worked out the thiscall details above, wrote the original @@ -186,7 +186,7 @@ extern IASIO* theAsioDriver; // The following macros define the inline assembler for BORLAND first then gcc -#if defined(__BCPLUSPLUS__) || defined(__BORLANDC__) +#if defined(__BCPLUSPLUS__) || defined(__BORLANDC__) #define CALL_THISCALL_0( resultName, thisPtr, funcOffset )\ @@ -277,7 +277,7 @@ extern IASIO* theAsioDriver; :"=a"(resultName) /* Output Operands */ \ :"c"(thisPtr) /* Input Operands */ \ ); \ - + #define CALL_VOID_THISCALL_1( thisPtr, funcOffset, param1 ) \ __asm__ __volatile__ ("pushl %0\n\t" \ @@ -287,7 +287,7 @@ extern IASIO* theAsioDriver; :"r"(param1), /* Input Operands */ \ "c"(thisPtr) \ ); \ - + #define CALL_THISCALL_1( resultName, thisPtr, funcOffset, param1 ) \ __asm__ __volatile__ ("pushl %1\n\t" \ @@ -297,7 +297,7 @@ extern IASIO* theAsioDriver; :"r"(param1), /* Input Operands */ \ "c"(thisPtr) \ ); \ - + #define CALL_THISCALL_1_DOUBLE( resultName, thisPtr, funcOffset, param1 ) \ __asm__ __volatile__ ("pushl 4(%1)\n\t" \ @@ -310,7 +310,7 @@ extern IASIO* theAsioDriver; /* when using GCC 3.3.3, and maybe later versions*/\ "c"(thisPtr) \ ); \ - + #define CALL_THISCALL_2( resultName, thisPtr, funcOffset, param1, param2 ) \ __asm__ __volatile__ ("pushl %1\n\t" \ @@ -322,7 +322,7 @@ extern IASIO* theAsioDriver; "r"(param1), \ "c"(thisPtr) \ ); \ - + #define CALL_THISCALL_4( resultName, thisPtr, funcOffset, param1, param2, param3, param4 )\ __asm__ __volatile__ ("pushl %1\n\t" \ @@ -338,7 +338,7 @@ extern IASIO* theAsioDriver; "r"(param1), \ "c"(thisPtr) \ ); \ - + #endif @@ -354,8 +354,8 @@ IASIOThiscallResolver::IASIOThiscallResolver() } // Constructor called from ASIOInit() below -IASIOThiscallResolver::IASIOThiscallResolver(IASIO* that) -: that_( that ) +IASIOThiscallResolver::IASIOThiscallResolver (IASIO* that) + : that_ (that) { } @@ -363,11 +363,11 @@ IASIOThiscallResolver::IASIOThiscallResolver(IASIO* that) // really a COM object, just a wrapper which will work with the ASIO SDK. // If you wanted to use ASIO without the SDK you might want to implement COM // aggregation in these methods. -HRESULT STDMETHODCALLTYPE IASIOThiscallResolver::QueryInterface(REFIID riid, void **ppv) +HRESULT STDMETHODCALLTYPE IASIOThiscallResolver::QueryInterface (REFIID riid, void **ppv) { - (void)riid; // suppress unused variable warning + (void) riid; // suppress unused variable warning - assert( false ); // this function should never be called by the ASIO SDK. + assert (false); // this function should never be called by the ASIO SDK. *ppv = NULL; return E_NOINTERFACE; @@ -375,176 +375,176 @@ HRESULT STDMETHODCALLTYPE IASIOThiscallResolver::QueryInterface(REFIID riid, voi ULONG STDMETHODCALLTYPE IASIOThiscallResolver::AddRef() { - assert( false ); // this function should never be called by the ASIO SDK. + assert (false); // this function should never be called by the ASIO SDK. return 1; } ULONG STDMETHODCALLTYPE IASIOThiscallResolver::Release() { - assert( false ); // this function should never be called by the ASIO SDK. - + assert (false); // this function should never be called by the ASIO SDK. + return 1; } // Implement the IASIO interface methods by performing the vptr manipulation // described above then delegating to the real implementation. -ASIOBool IASIOThiscallResolver::init(void *sysHandle) +ASIOBool IASIOThiscallResolver::init (void *sysHandle) { ASIOBool result; - CALL_THISCALL_1( result, that_, 12, sysHandle ); + CALL_THISCALL_1 (result, that_, 12, sysHandle); return result; } -void IASIOThiscallResolver::getDriverName(char *name) +void IASIOThiscallResolver::getDriverName (char *name) { - CALL_VOID_THISCALL_1( that_, 16, name ); + CALL_VOID_THISCALL_1 (that_, 16, name); } long IASIOThiscallResolver::getDriverVersion() { ASIOBool result; - CALL_THISCALL_0( result, that_, 20 ); + CALL_THISCALL_0 (result, that_, 20); return result; } -void IASIOThiscallResolver::getErrorMessage(char *string) +void IASIOThiscallResolver::getErrorMessage (char *string) { - CALL_VOID_THISCALL_1( that_, 24, string ); + CALL_VOID_THISCALL_1 (that_, 24, string); } ASIOError IASIOThiscallResolver::start() { ASIOBool result; - CALL_THISCALL_0( result, that_, 28 ); + CALL_THISCALL_0 (result, that_, 28); return result; } ASIOError IASIOThiscallResolver::stop() { ASIOBool result; - CALL_THISCALL_0( result, that_, 32 ); + CALL_THISCALL_0 (result, that_, 32); return result; } -ASIOError IASIOThiscallResolver::getChannels(long *numInputChannels, long *numOutputChannels) +ASIOError IASIOThiscallResolver::getChannels (long *numInputChannels, long *numOutputChannels) { ASIOBool result; - CALL_THISCALL_2( result, that_, 36, numInputChannels, numOutputChannels ); + CALL_THISCALL_2 (result, that_, 36, numInputChannels, numOutputChannels); return result; } -ASIOError IASIOThiscallResolver::getLatencies(long *inputLatency, long *outputLatency) +ASIOError IASIOThiscallResolver::getLatencies (long *inputLatency, long *outputLatency) { ASIOBool result; - CALL_THISCALL_2( result, that_, 40, inputLatency, outputLatency ); + CALL_THISCALL_2 (result, that_, 40, inputLatency, outputLatency); return result; } -ASIOError IASIOThiscallResolver::getBufferSize(long *minSize, long *maxSize, +ASIOError IASIOThiscallResolver::getBufferSize (long *minSize, long *maxSize, long *preferredSize, long *granularity) { ASIOBool result; - CALL_THISCALL_4( result, that_, 44, minSize, maxSize, preferredSize, granularity ); + CALL_THISCALL_4 (result, that_, 44, minSize, maxSize, preferredSize, granularity); return result; } -ASIOError IASIOThiscallResolver::canSampleRate(ASIOSampleRate sampleRate) +ASIOError IASIOThiscallResolver::canSampleRate (ASIOSampleRate sampleRate) { ASIOBool result; - CALL_THISCALL_1_DOUBLE( result, that_, 48, sampleRate ); + CALL_THISCALL_1_DOUBLE (result, that_, 48, sampleRate); return result; } -ASIOError IASIOThiscallResolver::getSampleRate(ASIOSampleRate *sampleRate) +ASIOError IASIOThiscallResolver::getSampleRate (ASIOSampleRate *sampleRate) { ASIOBool result; - CALL_THISCALL_1( result, that_, 52, sampleRate ); + CALL_THISCALL_1 (result, that_, 52, sampleRate); return result; } -ASIOError IASIOThiscallResolver::setSampleRate(ASIOSampleRate sampleRate) -{ +ASIOError IASIOThiscallResolver::setSampleRate (ASIOSampleRate sampleRate) +{ ASIOBool result; - CALL_THISCALL_1_DOUBLE( result, that_, 56, sampleRate ); + CALL_THISCALL_1_DOUBLE (result, that_, 56, sampleRate); return result; } -ASIOError IASIOThiscallResolver::getClockSources(ASIOClockSource *clocks, long *numSources) +ASIOError IASIOThiscallResolver::getClockSources (ASIOClockSource *clocks, long *numSources) { ASIOBool result; - CALL_THISCALL_2( result, that_, 60, clocks, numSources ); + CALL_THISCALL_2 (result, that_, 60, clocks, numSources); return result; } -ASIOError IASIOThiscallResolver::setClockSource(long reference) +ASIOError IASIOThiscallResolver::setClockSource (long reference) { ASIOBool result; - CALL_THISCALL_1( result, that_, 64, reference ); + CALL_THISCALL_1 (result, that_, 64, reference); return result; } -ASIOError IASIOThiscallResolver::getSamplePosition(ASIOSamples *sPos, ASIOTimeStamp *tStamp) +ASIOError IASIOThiscallResolver::getSamplePosition (ASIOSamples *sPos, ASIOTimeStamp *tStamp) { ASIOBool result; - CALL_THISCALL_2( result, that_, 68, sPos, tStamp ); + CALL_THISCALL_2 (result, that_, 68, sPos, tStamp); return result; } -ASIOError IASIOThiscallResolver::getChannelInfo(ASIOChannelInfo *info) +ASIOError IASIOThiscallResolver::getChannelInfo (ASIOChannelInfo *info) { ASIOBool result; - CALL_THISCALL_1( result, that_, 72, info ); + CALL_THISCALL_1 (result, that_, 72, info); return result; } -ASIOError IASIOThiscallResolver::createBuffers(ASIOBufferInfo *bufferInfos, +ASIOError IASIOThiscallResolver::createBuffers (ASIOBufferInfo *bufferInfos, long numChannels, long bufferSize, ASIOCallbacks *callbacks) { ASIOBool result; - CALL_THISCALL_4( result, that_, 76, bufferInfos, numChannels, bufferSize, callbacks ); + CALL_THISCALL_4 (result, that_, 76, bufferInfos, numChannels, bufferSize, callbacks); return result; } ASIOError IASIOThiscallResolver::disposeBuffers() { ASIOBool result; - CALL_THISCALL_0( result, that_, 80 ); + CALL_THISCALL_0 (result, that_, 80); return result; } ASIOError IASIOThiscallResolver::controlPanel() { ASIOBool result; - CALL_THISCALL_0( result, that_, 84 ); + CALL_THISCALL_0 (result, that_, 84); return result; } -ASIOError IASIOThiscallResolver::future(long selector,void *opt) +ASIOError IASIOThiscallResolver::future (long selector,void *opt) { ASIOBool result; - CALL_THISCALL_2( result, that_, 88, selector, opt ); + CALL_THISCALL_2 (result, that_, 88, selector, opt); return result; } ASIOError IASIOThiscallResolver::outputReady() { ASIOBool result; - CALL_THISCALL_0( result, that_, 92 ); + CALL_THISCALL_0 (result, that_, 92); return result; } // Implement our substitute ASIOInit() method -ASIOError IASIOThiscallResolver::ASIOInit(ASIODriverInfo *info) +ASIOError IASIOThiscallResolver::ASIOInit (ASIODriverInfo *info) { // To ensure that our instance's vptr is correctly constructed, even if // ASIOInit is called prior to main(), we explicitly call its constructor // (potentially over the top of an existing instance). Note that this is // pretty ugly, and is only safe because IASIOThiscallResolver has no // destructor and contains no objects with destructors. - new((void*)&instance) IASIOThiscallResolver( theAsioDriver ); + new ( (void*) &instance) IASIOThiscallResolver (theAsioDriver); // Interpose between ASIO client code and the real driver. theAsioDriver = &instance; @@ -553,7 +553,7 @@ ASIOError IASIOThiscallResolver::ASIOInit(ASIODriverInfo *info) // real driver because theAsioDriver is reset to zero in ASIOExit(). // Delegate to the real ASIOInit - return ::ASIOInit(info); + return ::ASIOInit (info); } diff --git a/sflphone-common/libs/pjproject/third_party/portaudio/src/hostapi/asio/pa_asio.cpp b/sflphone-common/libs/pjproject/third_party/portaudio/src/hostapi/asio/pa_asio.cpp index 1ba67e92ae9080876f6b83b5550b241819acfe0f..cf54465cfa65c74901ed79159748ab6f2232d66f 100644 --- a/sflphone-common/libs/pjproject/third_party/portaudio/src/hostapi/asio/pa_asio.cpp +++ b/sflphone-common/libs/pjproject/third_party/portaudio/src/hostapi/asio/pa_asio.cpp @@ -29,13 +29,13 @@ */ /* - * The text above constitutes the entire PortAudio license; however, + * The text above constitutes the entire PortAudio license; however, * the PortAudio community also makes the following non-binding requests: * * 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. It is also - * requested that these non-binding requests be included along with the + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the * license above. */ @@ -83,7 +83,7 @@ @todo review ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable - @todo review Blocking i/o latency computations in OpenStream(), changing ring + @todo review Blocking i/o latency computations in OpenStream(), changing ring buffer to a non-power-of-two structure could reduce blocking i/o latency. @todo implement IsFormatSupported @@ -171,8 +171,8 @@ /* external reference to ASIO SDK's asioDrivers. - This is a bit messy because we want to explicitly manage - allocation/deallocation of this structure, but some layers of the SDK + This is a bit messy because we want to explicitly manage + allocation/deallocation of this structure, but some layers of the SDK which we currently use (eg the implementation in asio.cpp) still use this global version. @@ -190,9 +190,9 @@ extern AsioDrivers* asioDrivers; /* prototypes for functions declared in this file */ -extern "C" PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex ); -static void Terminate( struct PaUtilHostApiRepresentation *hostApi ); -static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, +extern "C" PaError PaAsio_Initialize (PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex); +static void Terminate (struct PaUtilHostApiRepresentation *hostApi); +static PaError OpenStream (struct PaUtilHostApiRepresentation *hostApi, PaStream** s, const PaStreamParameters *inputParameters, const PaStreamParameters *outputParameters, @@ -200,82 +200,109 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, unsigned long framesPerBuffer, PaStreamFlags streamFlags, PaStreamCallback *streamCallback, - void *userData ); -static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, + void *userData); +static PaError IsFormatSupported (struct PaUtilHostApiRepresentation *hostApi, const PaStreamParameters *inputParameters, const PaStreamParameters *outputParameters, - double sampleRate ); -static PaError CloseStream( PaStream* stream ); -static PaError StartStream( PaStream *stream ); -static PaError StopStream( PaStream *stream ); -static PaError AbortStream( PaStream *stream ); -static PaError IsStreamStopped( PaStream *s ); -static PaError IsStreamActive( PaStream *stream ); -static PaTime GetStreamTime( PaStream *stream ); -static double GetStreamCpuLoad( PaStream* stream ); -static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames ); -static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames ); -static signed long GetStreamReadAvailable( PaStream* stream ); -static signed long GetStreamWriteAvailable( PaStream* stream ); + double sampleRate); +static PaError CloseStream (PaStream* stream); +static PaError StartStream (PaStream *stream); +static PaError StopStream (PaStream *stream); +static PaError AbortStream (PaStream *stream); +static PaError IsStreamStopped (PaStream *s); +static PaError IsStreamActive (PaStream *stream); +static PaTime GetStreamTime (PaStream *stream); +static double GetStreamCpuLoad (PaStream* stream); +static PaError ReadStream (PaStream* stream, void *buffer, unsigned long frames); +static PaError WriteStream (PaStream* stream, const void *buffer, unsigned long frames); +static signed long GetStreamReadAvailable (PaStream* stream); +static signed long GetStreamWriteAvailable (PaStream* stream); /* Blocking i/o callback function. */ -static int BlockingIoPaCallback(const void *inputBuffer , - void *outputBuffer , - unsigned long framesPerBuffer, - const PaStreamCallbackTimeInfo *timeInfo , - PaStreamCallbackFlags statusFlags , - void *userData ); +static int BlockingIoPaCallback (const void *inputBuffer , + void *outputBuffer , + unsigned long framesPerBuffer, + const PaStreamCallbackTimeInfo *timeInfo , + PaStreamCallbackFlags statusFlags , + void *userData); /* our ASIO callback functions */ -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 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 ASIOCallbacks asioCallbacks_ = - { bufferSwitch, sampleRateChanged, asioMessages, bufferSwitchTimeInfo }; +static ASIOCallbacks asioCallbacks_ = { bufferSwitch, sampleRateChanged, asioMessages, bufferSwitchTimeInfo }; #define PA_ASIO_SET_LAST_HOST_ERROR( errorCode, errorText ) \ PaUtil_SetLastHostErrorInfo( paASIO, errorCode, errorText ) -static void PaAsio_SetLastSystemError( DWORD errorCode ) +static void PaAsio_SetLastSystemError (DWORD errorCode) { LPVOID lpMsgBuf; - FormatMessage( + FormatMessage ( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, errorCode, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL ); - PaUtil_SetLastHostErrorInfo( paASIO, errorCode, (const char*)lpMsgBuf ); - LocalFree( lpMsgBuf ); + PaUtil_SetLastHostErrorInfo (paASIO, errorCode, (const char*) lpMsgBuf); + LocalFree (lpMsgBuf); } #define PA_ASIO_SET_LAST_SYSTEM_ERROR( errorCode ) \ PaAsio_SetLastSystemError( errorCode ) -static const char* PaAsio_GetAsioErrorText( ASIOError asioError ) +static const char* PaAsio_GetAsioErrorText (ASIOError asioError) { const char *result; - switch( asioError ){ + switch (asioError) { + case ASE_OK: - case ASE_SUCCESS: result = "Success"; break; - case ASE_NotPresent: result = "Hardware input or output is not present or available"; break; - case ASE_HWMalfunction: result = "Hardware is malfunctioning"; break; - case ASE_InvalidParameter: result = "Input parameter invalid"; break; - case ASE_InvalidMode: result = "Hardware is in a bad mode or used in a bad mode"; break; - case ASE_SPNotAdvancing: result = "Hardware is not running when sample position is inquired"; break; - case ASE_NoClock: result = "Sample clock or rate cannot be determined or is not present"; break; - case ASE_NoMemory: result = "Not enough memory for completing the request"; break; - default: result = "Unknown ASIO error"; break; + + case ASE_SUCCESS: + result = "Success"; + break; + + case ASE_NotPresent: + result = "Hardware input or output is not present or available"; + break; + + case ASE_HWMalfunction: + result = "Hardware is malfunctioning"; + break; + + case ASE_InvalidParameter: + result = "Input parameter invalid"; + break; + + case ASE_InvalidMode: + result = "Hardware is in a bad mode or used in a bad mode"; + break; + + case ASE_SPNotAdvancing: + result = "Hardware is not running when sample position is inquired"; + break; + + case ASE_NoClock: + result = "Sample clock or rate cannot be determined or is not present"; + break; + + case ASE_NoMemory: + result = "Not enough memory for completing the request"; + break; + + default: + result = "Unknown ASIO error"; + break; } return result; @@ -290,30 +317,45 @@ static const char* PaAsio_GetAsioErrorText( ASIOError asioError ) // Atomic increment and decrement operations #if MAC - /* need to be implemented on Mac */ - inline long PaAsio_AtomicIncrement(volatile long* v) {return ++(*const_cast<long*>(v));} - inline long PaAsio_AtomicDecrement(volatile long* v) {return --(*const_cast<long*>(v));} +/* need to be implemented on Mac */ +inline long PaAsio_AtomicIncrement (volatile long* v) +{ + return ++ (*const_cast<long*> (v)); +} + +inline long PaAsio_AtomicDecrement (volatile long* v) +{ + return -- (*const_cast<long*> (v)); +} + #elif WINDOWS - inline long PaAsio_AtomicIncrement(volatile long* v) {return InterlockedIncrement(const_cast<long*>(v));} - inline long PaAsio_AtomicDecrement(volatile long* v) {return InterlockedDecrement(const_cast<long*>(v));} +inline long PaAsio_AtomicIncrement (volatile long* v) +{ + return InterlockedIncrement (const_cast<long*> (v)); +} + +inline long PaAsio_AtomicDecrement (volatile long* v) +{ + return InterlockedDecrement (const_cast<long*> (v)); +} + #endif -typedef struct PaAsioDriverInfo -{ +typedef struct PaAsioDriverInfo { ASIODriverInfo asioDriverInfo; long inputChannelCount, outputChannelCount; long bufferMinSize, bufferMaxSize, bufferPreferredSize, bufferGranularity; bool postOutput; } + PaAsioDriverInfo; /* PaAsioHostApiRepresentation - host api datastructure specific to this implementation */ -typedef struct -{ +typedef struct { PaUtilHostApiRepresentation inheritedHostApiRep; PaUtilStreamInterface callbackStreamInterface; PaUtilStreamInterface blockingStreamInterface; @@ -322,7 +364,7 @@ typedef struct AsioDrivers *asioDrivers; void *systemSpecific; - + /* the ASIO C API only allows one ASIO driver to be open at a time, so we keep track of whether we have the driver open here, and use this information to return errors from OpenStream if the @@ -337,6 +379,7 @@ typedef struct PaDeviceIndex openAsioDeviceIndex; PaAsioDriverInfo openAsioDriverInfo; } + PaAsioHostApiRepresentation; @@ -344,117 +387,206 @@ PaAsioHostApiRepresentation; Retrieve <driverCount> driver names from ASIO, returned in a char** allocated in <group>. */ -static char **GetAsioDriverNames( PaAsioHostApiRepresentation *asioHostApi, PaUtilAllocationGroup *group, long driverCount ) +static char **GetAsioDriverNames (PaAsioHostApiRepresentation *asioHostApi, PaUtilAllocationGroup *group, long driverCount) { char **result = 0; int i; - result =(char**)PaUtil_GroupAllocateMemory( - group, sizeof(char*) * driverCount ); - if( !result ) + result = (char**) PaUtil_GroupAllocateMemory ( + group, sizeof (char*) * driverCount); + + if (!result) goto error; - result[0] = (char*)PaUtil_GroupAllocateMemory( - group, 32 * driverCount ); - if( !result[0] ) + result[0] = (char*) PaUtil_GroupAllocateMemory ( + group, 32 * driverCount); + + if (!result[0]) goto error; - for( i=0; i<driverCount; ++i ) + for (i=0; i<driverCount; ++i) result[i] = result[0] + (32 * i); - asioHostApi->asioDrivers->getDriverNames( result, driverCount ); + asioHostApi->asioDrivers->getDriverNames (result, driverCount); error: return result; } -static PaSampleFormat AsioSampleTypeToPaNativeSampleFormat(ASIOSampleType type) +static PaSampleFormat AsioSampleTypeToPaNativeSampleFormat (ASIOSampleType type) { switch (type) { + case ASIOSTInt16MSB: + case ASIOSTInt16LSB: - return paInt16; + return paInt16; case ASIOSTFloat32MSB: + case ASIOSTFloat32LSB: + case ASIOSTFloat64MSB: + case ASIOSTFloat64LSB: - return paFloat32; + return paFloat32; case ASIOSTInt32MSB: + case ASIOSTInt32LSB: + case ASIOSTInt32MSB16: + case ASIOSTInt32LSB16: + case ASIOSTInt32MSB18: + case ASIOSTInt32MSB20: + case ASIOSTInt32MSB24: + case ASIOSTInt32LSB18: + case ASIOSTInt32LSB20: + case ASIOSTInt32LSB24: - return paInt32; + return paInt32; case ASIOSTInt24MSB: + case ASIOSTInt24LSB: - return paInt24; + return paInt24; default: - return paCustomFormat; + return paCustomFormat; } } -void AsioSampleTypeLOG(ASIOSampleType type) +void AsioSampleTypeLOG (ASIOSampleType type) { switch (type) { - case ASIOSTInt16MSB: PA_DEBUG(("ASIOSTInt16MSB\n")); break; - case ASIOSTInt16LSB: PA_DEBUG(("ASIOSTInt16LSB\n")); break; - case ASIOSTFloat32MSB:PA_DEBUG(("ASIOSTFloat32MSB\n"));break; - case ASIOSTFloat32LSB:PA_DEBUG(("ASIOSTFloat32LSB\n"));break; - case ASIOSTFloat64MSB:PA_DEBUG(("ASIOSTFloat64MSB\n"));break; - case ASIOSTFloat64LSB:PA_DEBUG(("ASIOSTFloat64LSB\n"));break; - case ASIOSTInt32MSB: PA_DEBUG(("ASIOSTInt32MSB\n")); break; - case ASIOSTInt32LSB: PA_DEBUG(("ASIOSTInt32LSB\n")); break; - case ASIOSTInt32MSB16:PA_DEBUG(("ASIOSTInt32MSB16\n"));break; - case ASIOSTInt32LSB16:PA_DEBUG(("ASIOSTInt32LSB16\n"));break; - case ASIOSTInt32MSB18:PA_DEBUG(("ASIOSTInt32MSB18\n"));break; - case ASIOSTInt32MSB20:PA_DEBUG(("ASIOSTInt32MSB20\n"));break; - case ASIOSTInt32MSB24:PA_DEBUG(("ASIOSTInt32MSB24\n"));break; - case ASIOSTInt32LSB18:PA_DEBUG(("ASIOSTInt32LSB18\n"));break; - case ASIOSTInt32LSB20:PA_DEBUG(("ASIOSTInt32LSB20\n"));break; - case ASIOSTInt32LSB24:PA_DEBUG(("ASIOSTInt32LSB24\n"));break; - case ASIOSTInt24MSB: PA_DEBUG(("ASIOSTInt24MSB\n")); break; - case ASIOSTInt24LSB: PA_DEBUG(("ASIOSTInt24LSB\n")); break; - default: PA_DEBUG(("Custom Format%d\n",type));break; + + case ASIOSTInt16MSB: + PA_DEBUG ( ("ASIOSTInt16MSB\n")); + break; + + case ASIOSTInt16LSB: + PA_DEBUG ( ("ASIOSTInt16LSB\n")); + break; + + case ASIOSTFloat32MSB: + PA_DEBUG ( ("ASIOSTFloat32MSB\n")); + break; + + case ASIOSTFloat32LSB: + PA_DEBUG ( ("ASIOSTFloat32LSB\n")); + break; + + case ASIOSTFloat64MSB: + PA_DEBUG ( ("ASIOSTFloat64MSB\n")); + break; + + case ASIOSTFloat64LSB: + PA_DEBUG ( ("ASIOSTFloat64LSB\n")); + break; + + case ASIOSTInt32MSB: + PA_DEBUG ( ("ASIOSTInt32MSB\n")); + break; + + case ASIOSTInt32LSB: + PA_DEBUG ( ("ASIOSTInt32LSB\n")); + break; + + case ASIOSTInt32MSB16: + PA_DEBUG ( ("ASIOSTInt32MSB16\n")); + break; + + case ASIOSTInt32LSB16: + PA_DEBUG ( ("ASIOSTInt32LSB16\n")); + break; + + case ASIOSTInt32MSB18: + PA_DEBUG ( ("ASIOSTInt32MSB18\n")); + break; + + case ASIOSTInt32MSB20: + PA_DEBUG ( ("ASIOSTInt32MSB20\n")); + break; + + case ASIOSTInt32MSB24: + PA_DEBUG ( ("ASIOSTInt32MSB24\n")); + break; + + case ASIOSTInt32LSB18: + PA_DEBUG ( ("ASIOSTInt32LSB18\n")); + break; + + case ASIOSTInt32LSB20: + PA_DEBUG ( ("ASIOSTInt32LSB20\n")); + break; + + case ASIOSTInt32LSB24: + PA_DEBUG ( ("ASIOSTInt32LSB24\n")); + break; + + case ASIOSTInt24MSB: + PA_DEBUG ( ("ASIOSTInt24MSB\n")); + break; + + case ASIOSTInt24LSB: + PA_DEBUG ( ("ASIOSTInt24LSB\n")); + break; + + default: + PA_DEBUG ( ("Custom Format%d\n",type)); + break; } } -static int BytesPerAsioSample( ASIOSampleType sampleType ) +static int BytesPerAsioSample (ASIOSampleType sampleType) { switch (sampleType) { + case ASIOSTInt16MSB: + case ASIOSTInt16LSB: return 2; case ASIOSTFloat64MSB: + case ASIOSTFloat64LSB: return 8; case ASIOSTFloat32MSB: + case ASIOSTFloat32LSB: + case ASIOSTInt32MSB: + case ASIOSTInt32LSB: + case ASIOSTInt32MSB16: + case ASIOSTInt32LSB16: + case ASIOSTInt32MSB18: + case ASIOSTInt32MSB20: + case ASIOSTInt32MSB24: + case ASIOSTInt32LSB18: + case ASIOSTInt32LSB20: + case ASIOSTInt32LSB24: return 4; case ASIOSTInt24MSB: + case ASIOSTInt24LSB: return 3; @@ -464,93 +596,86 @@ static int BytesPerAsioSample( ASIOSampleType sampleType ) } -static void Swap16( void *buffer, long shift, long count ) +static void Swap16 (void *buffer, long shift, long count) { - unsigned short *p = (unsigned short*)buffer; + unsigned short *p = (unsigned short*) buffer; unsigned short temp; (void) shift; /* unused parameter */ - while( count-- ) - { + while (count--) { temp = *p; - *p++ = (unsigned short)((temp<<8) | (temp>>8)); + *p++ = (unsigned short) ( (temp<<8) | (temp>>8)); } } -static void Swap24( void *buffer, long shift, long count ) +static void Swap24 (void *buffer, long shift, long count) { - unsigned char *p = (unsigned char*)buffer; + unsigned char *p = (unsigned char*) buffer; unsigned char temp; (void) shift; /* unused parameter */ - while( count-- ) - { + while (count--) { temp = *p; - *p = *(p+2); - *(p+2) = temp; + *p = * (p+2); + * (p+2) = temp; p += 3; } } #define PA_SWAP32_( x ) ((x>>24) | ((x>>8)&0xFF00) | ((x<<8)&0xFF0000) | (x<<24)); -static void Swap32( void *buffer, long shift, long count ) +static void Swap32 (void *buffer, long shift, long count) { - unsigned long *p = (unsigned long*)buffer; + unsigned long *p = (unsigned long*) buffer; unsigned long temp; (void) shift; /* unused parameter */ - while( count-- ) - { + while (count--) { temp = *p; - *p++ = PA_SWAP32_( temp); + *p++ = PA_SWAP32_ (temp); } } -static void SwapShiftLeft32( void *buffer, long shift, long count ) +static void SwapShiftLeft32 (void *buffer, long shift, long count) { - unsigned long *p = (unsigned long*)buffer; + unsigned long *p = (unsigned long*) buffer; unsigned long temp; - while( count-- ) - { + while (count--) { temp = *p; - temp = PA_SWAP32_( temp); + temp = PA_SWAP32_ (temp); *p++ = temp << shift; } } -static void ShiftRightSwap32( void *buffer, long shift, long count ) +static void ShiftRightSwap32 (void *buffer, long shift, long count) { - unsigned long *p = (unsigned long*)buffer; + unsigned long *p = (unsigned long*) buffer; unsigned long temp; - while( count-- ) - { + while (count--) { temp = *p >> shift; - *p++ = PA_SWAP32_( temp); + *p++ = PA_SWAP32_ (temp); } } -static void ShiftLeft32( void *buffer, long shift, long count ) +static void ShiftLeft32 (void *buffer, long shift, long count) { - unsigned long *p = (unsigned long*)buffer; + unsigned long *p = (unsigned long*) buffer; unsigned long temp; - while( count-- ) - { + while (count--) { temp = *p; *p++ = temp << shift; } } -static void ShiftRight32( void *buffer, long shift, long count ) +static void ShiftRight32 (void *buffer, long shift, long count) { - unsigned long *p = (unsigned long*)buffer; + unsigned long *p = (unsigned long*) buffer; unsigned long temp; - while( count-- ) - { + while (count--) { temp = *p; *p++ = temp >> shift; } @@ -558,65 +683,63 @@ static void ShiftRight32( void *buffer, long shift, long count ) #define PA_SWAP_( x, y ) temp=x; x = y; y = temp; -static void Swap64ConvertFloat64ToFloat32( void *buffer, long shift, long count ) +static void Swap64ConvertFloat64ToFloat32 (void *buffer, long shift, long count) { - double *in = (double*)buffer; - float *out = (float*)buffer; + double *in = (double*) buffer; + float *out = (float*) buffer; unsigned char *p; unsigned char temp; (void) shift; /* unused parameter */ - while( count-- ) - { - p = (unsigned char*)in; - PA_SWAP_( p[0], p[7] ); - PA_SWAP_( p[1], p[6] ); - PA_SWAP_( p[2], p[5] ); - PA_SWAP_( p[3], p[4] ); + while (count--) { + p = (unsigned char*) in; + PA_SWAP_ (p[0], p[7]); + PA_SWAP_ (p[1], p[6]); + PA_SWAP_ (p[2], p[5]); + PA_SWAP_ (p[3], p[4]); *out++ = (float) (*in++); } } -static void ConvertFloat64ToFloat32( void *buffer, long shift, long count ) +static void ConvertFloat64ToFloat32 (void *buffer, long shift, long count) { - double *in = (double*)buffer; - float *out = (float*)buffer; + double *in = (double*) buffer; + float *out = (float*) buffer; (void) shift; /* unused parameter */ - while( count-- ) + while (count--) *out++ = (float) (*in++); } -static void ConvertFloat32ToFloat64Swap64( void *buffer, long shift, long count ) +static void ConvertFloat32ToFloat64Swap64 (void *buffer, long shift, long count) { - float *in = ((float*)buffer) + (count-1); - double *out = ((double*)buffer) + (count-1); + float *in = ( (float*) buffer) + (count-1); + double *out = ( (double*) buffer) + (count-1); unsigned char *p; unsigned char temp; (void) shift; /* unused parameter */ - while( count-- ) - { + while (count--) { *out = *in--; - p = (unsigned char*)out; - PA_SWAP_( p[0], p[7] ); - PA_SWAP_( p[1], p[6] ); - PA_SWAP_( p[2], p[5] ); - PA_SWAP_( p[3], p[4] ); + p = (unsigned char*) out; + PA_SWAP_ (p[0], p[7]); + PA_SWAP_ (p[1], p[6]); + PA_SWAP_ (p[2], p[5]); + PA_SWAP_ (p[3], p[4]); out--; } } -static void ConvertFloat32ToFloat64( void *buffer, long shift, long count ) +static void ConvertFloat32ToFloat64 (void *buffer, long shift, long count) { - float *in = ((float*)buffer) + (count-1); - double *out = ((double*)buffer) + (count-1); + float *in = ( (float*) buffer) + (count-1); + double *out = ( (double*) buffer) + (count-1); (void) shift; /* unused parameter */ - while( count-- ) + while (count--) *out-- = *in--; } @@ -630,302 +753,337 @@ static void ConvertFloat32ToFloat64( void *buffer, long shift, long count ) #define PA_LSB_IS_NATIVE_ #endif -typedef void PaAsioBufferConverter( void *, long, long ); +typedef void PaAsioBufferConverter (void *, long, long); -static void SelectAsioToPaConverter( ASIOSampleType type, PaAsioBufferConverter **converter, long *shift ) +static void SelectAsioToPaConverter (ASIOSampleType type, PaAsioBufferConverter **converter, long *shift) { *shift = 0; *converter = 0; switch (type) { + case ASIOSTInt16MSB: /* dest: paInt16, no conversion necessary, possible byte swap*/ - #ifdef PA_LSB_IS_NATIVE_ - *converter = Swap16; - #endif +#ifdef PA_LSB_IS_NATIVE_ + *converter = Swap16; +#endif break; + case ASIOSTInt16LSB: /* dest: paInt16, no conversion necessary, possible byte swap*/ - #ifdef PA_MSB_IS_NATIVE_ - *converter = Swap16; - #endif +#ifdef PA_MSB_IS_NATIVE_ + *converter = Swap16; +#endif break; + case ASIOSTFloat32MSB: /* dest: paFloat32, no conversion necessary, possible byte swap*/ - #ifdef PA_LSB_IS_NATIVE_ - *converter = Swap32; - #endif +#ifdef PA_LSB_IS_NATIVE_ + *converter = Swap32; +#endif break; + case ASIOSTFloat32LSB: /* dest: paFloat32, no conversion necessary, possible byte swap*/ - #ifdef PA_MSB_IS_NATIVE_ - *converter = Swap32; - #endif +#ifdef PA_MSB_IS_NATIVE_ + *converter = Swap32; +#endif break; + case ASIOSTFloat64MSB: /* dest: paFloat32, in-place conversion to/from float32, possible byte swap*/ - #ifdef PA_LSB_IS_NATIVE_ - *converter = Swap64ConvertFloat64ToFloat32; - #else - *converter = ConvertFloat64ToFloat32; - #endif +#ifdef PA_LSB_IS_NATIVE_ + *converter = Swap64ConvertFloat64ToFloat32; +#else + *converter = ConvertFloat64ToFloat32; +#endif break; + case ASIOSTFloat64LSB: /* dest: paFloat32, in-place conversion to/from float32, possible byte swap*/ - #ifdef PA_MSB_IS_NATIVE_ - *converter = Swap64ConvertFloat64ToFloat32; - #else - *converter = ConvertFloat64ToFloat32; - #endif +#ifdef PA_MSB_IS_NATIVE_ + *converter = Swap64ConvertFloat64ToFloat32; +#else + *converter = ConvertFloat64ToFloat32; +#endif break; + case ASIOSTInt32MSB: /* dest: paInt32, no conversion necessary, possible byte swap */ - #ifdef PA_LSB_IS_NATIVE_ - *converter = Swap32; - #endif +#ifdef PA_LSB_IS_NATIVE_ + *converter = Swap32; +#endif break; + case ASIOSTInt32LSB: /* dest: paInt32, no conversion necessary, possible byte swap */ - #ifdef PA_MSB_IS_NATIVE_ - *converter = Swap32; - #endif +#ifdef PA_MSB_IS_NATIVE_ + *converter = Swap32; +#endif break; + case ASIOSTInt32MSB16: /* dest: paInt32, 16 bit shift, possible byte swap */ - #ifdef PA_LSB_IS_NATIVE_ - *converter = SwapShiftLeft32; - #else - *converter = ShiftLeft32; - #endif +#ifdef PA_LSB_IS_NATIVE_ + *converter = SwapShiftLeft32; +#else + *converter = ShiftLeft32; +#endif *shift = 16; break; + case ASIOSTInt32MSB18: /* dest: paInt32, 14 bit shift, possible byte swap */ - #ifdef PA_LSB_IS_NATIVE_ - *converter = SwapShiftLeft32; - #else - *converter = ShiftLeft32; - #endif +#ifdef PA_LSB_IS_NATIVE_ + *converter = SwapShiftLeft32; +#else + *converter = ShiftLeft32; +#endif *shift = 14; break; + case ASIOSTInt32MSB20: /* dest: paInt32, 12 bit shift, possible byte swap */ - #ifdef PA_LSB_IS_NATIVE_ - *converter = SwapShiftLeft32; - #else - *converter = ShiftLeft32; - #endif +#ifdef PA_LSB_IS_NATIVE_ + *converter = SwapShiftLeft32; +#else + *converter = ShiftLeft32; +#endif *shift = 12; break; + case ASIOSTInt32MSB24: /* dest: paInt32, 8 bit shift, possible byte swap */ - #ifdef PA_LSB_IS_NATIVE_ - *converter = SwapShiftLeft32; - #else - *converter = ShiftLeft32; - #endif +#ifdef PA_LSB_IS_NATIVE_ + *converter = SwapShiftLeft32; +#else + *converter = ShiftLeft32; +#endif *shift = 8; break; + case ASIOSTInt32LSB16: /* dest: paInt32, 16 bit shift, possible byte swap */ - #ifdef PA_MSB_IS_NATIVE_ - *converter = SwapShiftLeft32; - #else - *converter = ShiftLeft32; - #endif +#ifdef PA_MSB_IS_NATIVE_ + *converter = SwapShiftLeft32; +#else + *converter = ShiftLeft32; +#endif *shift = 16; break; + case ASIOSTInt32LSB18: /* dest: paInt32, 14 bit shift, possible byte swap */ - #ifdef PA_MSB_IS_NATIVE_ - *converter = SwapShiftLeft32; - #else - *converter = ShiftLeft32; - #endif +#ifdef PA_MSB_IS_NATIVE_ + *converter = SwapShiftLeft32; +#else + *converter = ShiftLeft32; +#endif *shift = 14; break; + case ASIOSTInt32LSB20: /* dest: paInt32, 12 bit shift, possible byte swap */ - #ifdef PA_MSB_IS_NATIVE_ - *converter = SwapShiftLeft32; - #else - *converter = ShiftLeft32; - #endif +#ifdef PA_MSB_IS_NATIVE_ + *converter = SwapShiftLeft32; +#else + *converter = ShiftLeft32; +#endif *shift = 12; break; + case ASIOSTInt32LSB24: /* dest: paInt32, 8 bit shift, possible byte swap */ - #ifdef PA_MSB_IS_NATIVE_ - *converter = SwapShiftLeft32; - #else - *converter = ShiftLeft32; - #endif +#ifdef PA_MSB_IS_NATIVE_ + *converter = SwapShiftLeft32; +#else + *converter = ShiftLeft32; +#endif *shift = 8; break; + case ASIOSTInt24MSB: /* dest: paInt24, no conversion necessary, possible byte swap */ - #ifdef PA_LSB_IS_NATIVE_ - *converter = Swap24; - #endif +#ifdef PA_LSB_IS_NATIVE_ + *converter = Swap24; +#endif break; + case ASIOSTInt24LSB: /* dest: paInt24, no conversion necessary, possible byte swap */ - #ifdef PA_MSB_IS_NATIVE_ - *converter = Swap24; - #endif +#ifdef PA_MSB_IS_NATIVE_ + *converter = Swap24; +#endif break; } } -static void SelectPaToAsioConverter( ASIOSampleType type, PaAsioBufferConverter **converter, long *shift ) +static void SelectPaToAsioConverter (ASIOSampleType type, PaAsioBufferConverter **converter, long *shift) { *shift = 0; *converter = 0; switch (type) { + case ASIOSTInt16MSB: /* src: paInt16, no conversion necessary, possible byte swap*/ - #ifdef PA_LSB_IS_NATIVE_ - *converter = Swap16; - #endif +#ifdef PA_LSB_IS_NATIVE_ + *converter = Swap16; +#endif break; + case ASIOSTInt16LSB: /* src: paInt16, no conversion necessary, possible byte swap*/ - #ifdef PA_MSB_IS_NATIVE_ - *converter = Swap16; - #endif +#ifdef PA_MSB_IS_NATIVE_ + *converter = Swap16; +#endif break; + case ASIOSTFloat32MSB: /* src: paFloat32, no conversion necessary, possible byte swap*/ - #ifdef PA_LSB_IS_NATIVE_ - *converter = Swap32; - #endif +#ifdef PA_LSB_IS_NATIVE_ + *converter = Swap32; +#endif break; + case ASIOSTFloat32LSB: /* src: paFloat32, no conversion necessary, possible byte swap*/ - #ifdef PA_MSB_IS_NATIVE_ - *converter = Swap32; - #endif +#ifdef PA_MSB_IS_NATIVE_ + *converter = Swap32; +#endif break; + case ASIOSTFloat64MSB: /* src: paFloat32, in-place conversion to/from float32, possible byte swap*/ - #ifdef PA_LSB_IS_NATIVE_ - *converter = ConvertFloat32ToFloat64Swap64; - #else - *converter = ConvertFloat32ToFloat64; - #endif +#ifdef PA_LSB_IS_NATIVE_ + *converter = ConvertFloat32ToFloat64Swap64; +#else + *converter = ConvertFloat32ToFloat64; +#endif break; + case ASIOSTFloat64LSB: /* src: paFloat32, in-place conversion to/from float32, possible byte swap*/ - #ifdef PA_MSB_IS_NATIVE_ - *converter = ConvertFloat32ToFloat64Swap64; - #else - *converter = ConvertFloat32ToFloat64; - #endif +#ifdef PA_MSB_IS_NATIVE_ + *converter = ConvertFloat32ToFloat64Swap64; +#else + *converter = ConvertFloat32ToFloat64; +#endif break; + case ASIOSTInt32MSB: /* src: paInt32, no conversion necessary, possible byte swap */ - #ifdef PA_LSB_IS_NATIVE_ - *converter = Swap32; - #endif +#ifdef PA_LSB_IS_NATIVE_ + *converter = Swap32; +#endif break; + case ASIOSTInt32LSB: /* src: paInt32, no conversion necessary, possible byte swap */ - #ifdef PA_MSB_IS_NATIVE_ - *converter = Swap32; - #endif +#ifdef PA_MSB_IS_NATIVE_ + *converter = Swap32; +#endif break; + case ASIOSTInt32MSB16: /* src: paInt32, 16 bit shift, possible byte swap */ - #ifdef PA_LSB_IS_NATIVE_ - *converter = ShiftRightSwap32; - #else - *converter = ShiftRight32; - #endif +#ifdef PA_LSB_IS_NATIVE_ + *converter = ShiftRightSwap32; +#else + *converter = ShiftRight32; +#endif *shift = 16; break; + case ASIOSTInt32MSB18: /* src: paInt32, 14 bit shift, possible byte swap */ - #ifdef PA_LSB_IS_NATIVE_ - *converter = ShiftRightSwap32; - #else - *converter = ShiftRight32; - #endif +#ifdef PA_LSB_IS_NATIVE_ + *converter = ShiftRightSwap32; +#else + *converter = ShiftRight32; +#endif *shift = 14; break; + case ASIOSTInt32MSB20: /* src: paInt32, 12 bit shift, possible byte swap */ - #ifdef PA_LSB_IS_NATIVE_ - *converter = ShiftRightSwap32; - #else - *converter = ShiftRight32; - #endif +#ifdef PA_LSB_IS_NATIVE_ + *converter = ShiftRightSwap32; +#else + *converter = ShiftRight32; +#endif *shift = 12; break; + case ASIOSTInt32MSB24: /* src: paInt32, 8 bit shift, possible byte swap */ - #ifdef PA_LSB_IS_NATIVE_ - *converter = ShiftRightSwap32; - #else - *converter = ShiftRight32; - #endif +#ifdef PA_LSB_IS_NATIVE_ + *converter = ShiftRightSwap32; +#else + *converter = ShiftRight32; +#endif *shift = 8; break; + case ASIOSTInt32LSB16: /* src: paInt32, 16 bit shift, possible byte swap */ - #ifdef PA_MSB_IS_NATIVE_ - *converter = ShiftRightSwap32; - #else - *converter = ShiftRight32; - #endif +#ifdef PA_MSB_IS_NATIVE_ + *converter = ShiftRightSwap32; +#else + *converter = ShiftRight32; +#endif *shift = 16; break; + case ASIOSTInt32LSB18: /* src: paInt32, 14 bit shift, possible byte swap */ - #ifdef PA_MSB_IS_NATIVE_ - *converter = ShiftRightSwap32; - #else - *converter = ShiftRight32; - #endif +#ifdef PA_MSB_IS_NATIVE_ + *converter = ShiftRightSwap32; +#else + *converter = ShiftRight32; +#endif *shift = 14; break; + case ASIOSTInt32LSB20: /* src: paInt32, 12 bit shift, possible byte swap */ - #ifdef PA_MSB_IS_NATIVE_ - *converter = ShiftRightSwap32; - #else - *converter = ShiftRight32; - #endif +#ifdef PA_MSB_IS_NATIVE_ + *converter = ShiftRightSwap32; +#else + *converter = ShiftRight32; +#endif *shift = 12; break; + case ASIOSTInt32LSB24: /* src: paInt32, 8 bit shift, possible byte swap */ - #ifdef PA_MSB_IS_NATIVE_ - *converter = ShiftRightSwap32; - #else - *converter = ShiftRight32; - #endif +#ifdef PA_MSB_IS_NATIVE_ + *converter = ShiftRightSwap32; +#else + *converter = ShiftRight32; +#endif *shift = 8; break; + case ASIOSTInt24MSB: /* src: paInt24, no conversion necessary, possible byte swap */ - #ifdef PA_LSB_IS_NATIVE_ - *converter = Swap24; - #endif +#ifdef PA_LSB_IS_NATIVE_ + *converter = Swap24; +#endif break; + case ASIOSTInt24LSB: /* src: paInt24, no conversion necessary, possible byte swap */ - #ifdef PA_MSB_IS_NATIVE_ - *converter = Swap24; - #endif +#ifdef PA_MSB_IS_NATIVE_ + *converter = Swap24; +#endif break; } } -typedef struct PaAsioDeviceInfo -{ +typedef struct PaAsioDeviceInfo { PaDeviceInfo commonDeviceInfo; long minBufferSize; long maxBufferSize; @@ -934,26 +1092,25 @@ typedef struct PaAsioDeviceInfo ASIOChannelInfo *asioChannelInfos; } + PaAsioDeviceInfo; -PaError PaAsio_GetAvailableLatencyValues( PaDeviceIndex device, - long *minLatency, long *maxLatency, long *preferredLatency, long *granularity ) +PaError PaAsio_GetAvailableLatencyValues (PaDeviceIndex device, + long *minLatency, long *maxLatency, long *preferredLatency, long *granularity) { PaError result; PaUtilHostApiRepresentation *hostApi; PaDeviceIndex hostApiDevice; - result = PaUtil_GetHostApiRepresentation( &hostApi, paASIO ); + result = PaUtil_GetHostApiRepresentation (&hostApi, paASIO); - if( result == paNoError ) - { - result = PaUtil_DeviceIndexToHostApiDeviceIndex( &hostApiDevice, device, hostApi ); + if (result == paNoError) { + result = PaUtil_DeviceIndexToHostApiDeviceIndex (&hostApiDevice, device, hostApi); - if( result == paNoError ) - { + if (result == paNoError) { PaAsioDeviceInfo *asioDeviceInfo = - (PaAsioDeviceInfo*)hostApi->deviceInfos[hostApiDevice]; + (PaAsioDeviceInfo*) hostApi->deviceInfos[hostApiDevice]; *minLatency = asioDeviceInfo->minBufferSize; *maxLatency = asioDeviceInfo->maxBufferSize; @@ -968,10 +1125,10 @@ PaError PaAsio_GetAvailableLatencyValues( PaDeviceIndex device, /* Unload whatever we loaded in LoadAsioDriver(). Also balance the call to CoInitialize(0). */ -static void UnloadAsioDriver( void ) +static void UnloadAsioDriver (void) { - ASIOExit(); - CoUninitialize(); + ASIOExit(); + CoUninitialize(); } /* @@ -980,67 +1137,63 @@ static void UnloadAsioDriver( void ) and must be closed by the called by calling UnloadAsioDriver() - if an error is returned the driver will already be unloaded. */ -static PaError LoadAsioDriver( PaAsioHostApiRepresentation *asioHostApi, const char *driverName, - PaAsioDriverInfo *driverInfo, void *systemSpecific ) +static PaError LoadAsioDriver (PaAsioHostApiRepresentation *asioHostApi, const char *driverName, + PaAsioDriverInfo *driverInfo, void *systemSpecific) { PaError result = paNoError; ASIOError asioError; int asioIsInitialized = 0; - /* - ASIO uses CoCreateInstance() to load a driver. That requires that - CoInitialize(0) be called for every thread that loads a driver. - It is OK to call CoInitialize(0) multiple times form one thread as long - as it is balanced by a call to CoUninitialize(). See UnloadAsioDriver(). - - The V18 version called CoInitialize() starting on 2/19/02. - That was removed from PA V19 for unknown reasons. - Phil Burk added it back on 6/27/08 so that JSyn would work. + /* + ASIO uses CoCreateInstance() to load a driver. That requires that + CoInitialize(0) be called for every thread that loads a driver. + It is OK to call CoInitialize(0) multiple times form one thread as long + as it is balanced by a call to CoUninitialize(). See UnloadAsioDriver(). + + The V18 version called CoInitialize() starting on 2/19/02. + That was removed from PA V19 for unknown reasons. + Phil Burk added it back on 6/27/08 so that JSyn would work. */ - CoInitialize( 0 ); + CoInitialize (0); - if( !asioHostApi->asioDrivers->loadDriver( const_cast<char*>(driverName) ) ) - { - /* If this returns an error then it might be because CoInitialize(0) was removed. - It should be called right before this. - */ + if (!asioHostApi->asioDrivers->loadDriver (const_cast<char*> (driverName))) { + /* If this returns an error then it might be because CoInitialize(0) was removed. + It should be called right before this. + */ result = paUnanticipatedHostError; - PA_ASIO_SET_LAST_HOST_ERROR( 0, "Failed to load ASIO driver" ); + PA_ASIO_SET_LAST_HOST_ERROR (0, "Failed to load ASIO driver"); goto error; } - memset( &driverInfo->asioDriverInfo, 0, sizeof(ASIODriverInfo) ); + memset (&driverInfo->asioDriverInfo, 0, sizeof (ASIODriverInfo)); + driverInfo->asioDriverInfo.asioVersion = 2; driverInfo->asioDriverInfo.sysRef = systemSpecific; - if( (asioError = ASIOInit( &driverInfo->asioDriverInfo )) != ASE_OK ) - { + + if ( (asioError = ASIOInit (&driverInfo->asioDriverInfo)) != ASE_OK) { result = paUnanticipatedHostError; - PA_ASIO_SET_LAST_ASIO_ERROR( asioError ); + PA_ASIO_SET_LAST_ASIO_ERROR (asioError); goto error; - } - else - { + } else { asioIsInitialized = 1; } - if( (asioError = ASIOGetChannels(&driverInfo->inputChannelCount, - &driverInfo->outputChannelCount)) != ASE_OK ) - { + if ( (asioError = ASIOGetChannels (&driverInfo->inputChannelCount, + &driverInfo->outputChannelCount)) != ASE_OK) { result = paUnanticipatedHostError; - PA_ASIO_SET_LAST_ASIO_ERROR( asioError ); + PA_ASIO_SET_LAST_ASIO_ERROR (asioError); goto error; } - if( (asioError = ASIOGetBufferSize(&driverInfo->bufferMinSize, - &driverInfo->bufferMaxSize, &driverInfo->bufferPreferredSize, - &driverInfo->bufferGranularity)) != ASE_OK ) - { + if ( (asioError = ASIOGetBufferSize (&driverInfo->bufferMinSize, + &driverInfo->bufferMaxSize, &driverInfo->bufferPreferredSize, + &driverInfo->bufferGranularity)) != ASE_OK) { result = paUnanticipatedHostError; - PA_ASIO_SET_LAST_ASIO_ERROR( asioError ); + PA_ASIO_SET_LAST_ASIO_ERROR (asioError); goto error; } - if( ASIOOutputReady() == ASE_OK ) + if (ASIOOutputReady() == ASE_OK) driverInfo->postOutput = true; else driverInfo->postOutput = false; @@ -1048,27 +1201,29 @@ static PaError LoadAsioDriver( PaAsioHostApiRepresentation *asioHostApi, const c return result; error: - if( asioIsInitialized ) - { - ASIOExit(); - } - CoUninitialize(); + if (asioIsInitialized) { + ASIOExit(); + } + + CoUninitialize(); + return result; } #define PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_ 13 /* must be the same number of elements as in the array below */ static ASIOSampleRate defaultSampleRateSearchOrder_[] - = {44100.0, 48000.0, 32000.0, 24000.0, 22050.0, 88200.0, 96000.0, - 192000.0, 16000.0, 12000.0, 11025.0, 9600.0, 8000.0 }; += {44100.0, 48000.0, 32000.0, 24000.0, 22050.0, 88200.0, 96000.0, + 192000.0, 16000.0, 12000.0, 11025.0, 9600.0, 8000.0 + }; /* we look up IsDebuggerPresent at runtime incase it isn't present (on Win95 for example) */ -typedef BOOL (WINAPI *IsDebuggerPresentPtr)(VOID); +typedef BOOL (WINAPI *IsDebuggerPresentPtr) (VOID); IsDebuggerPresentPtr IsDebuggerPresent_ = 0; //FARPROC IsDebuggerPresent_ = 0; // this is the current way to do it apparently according to davidv -PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex ) +PaError PaAsio_Initialize (PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex) { PaError result = paNoError; int i, driverCount; @@ -1077,9 +1232,9 @@ PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex char **names; PaAsioDriverInfo paAsioDriverInfo; - asioHostApi = (PaAsioHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaAsioHostApiRepresentation) ); - if( !asioHostApi ) - { + asioHostApi = (PaAsioHostApiRepresentation*) PaUtil_AllocateMemory (sizeof (PaAsioHostApiRepresentation)); + + if (!asioHostApi) { result = paInsufficientMemory; goto error; } @@ -1087,25 +1242,22 @@ PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex asioHostApi->asioDrivers = 0; /* avoid surprises in our error handler below */ asioHostApi->allocations = PaUtil_CreateAllocationGroup(); - if( !asioHostApi->allocations ) - { + + if (!asioHostApi->allocations) { result = paInsufficientMemory; goto error; } /* Allocate the AsioDrivers() driver list (class from ASIO SDK) */ - try - { + try { asioHostApi->asioDrivers = new AsioDrivers(); /* calls CoInitialize(0) */ - } - catch (std::bad_alloc) - { + } catch (std::bad_alloc) { asioHostApi->asioDrivers = 0; } + /* some implementations of new (ie MSVC, see http://support.microsoft.com/?kbid=167733) don't throw std::bad_alloc, so we also explicitly test for a null return. */ - if( asioHostApi->asioDrivers == 0 ) - { + if (asioHostApi->asioDrivers == 0) { result = paInsufficientMemory; goto error; } @@ -1122,24 +1274,23 @@ PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex (*hostApi)->info.name = "ASIO"; (*hostApi)->info.deviceCount = 0; - #ifdef WINDOWS - /* use desktop window as system specific ptr */ - asioHostApi->systemSpecific = GetDesktopWindow(); - #endif +#ifdef WINDOWS + /* use desktop window as system specific ptr */ + asioHostApi->systemSpecific = GetDesktopWindow(); +#endif /* driverCount is the number of installed drivers - not necessarily the number of installed physical devices. */ - #if MAC - driverCount = asioHostApi->asioDrivers->getNumFragments(); - #elif WINDOWS - driverCount = asioHostApi->asioDrivers->asioGetNumDev(); - #endif +#if MAC + driverCount = asioHostApi->asioDrivers->getNumFragments(); +#elif WINDOWS + driverCount = asioHostApi->asioDrivers->asioGetNumDev(); +#endif - if( driverCount > 0 ) - { - names = GetAsioDriverNames( asioHostApi, asioHostApi->allocations, driverCount ); - if( !names ) - { + if (driverCount > 0) { + names = GetAsioDriverNames (asioHostApi, asioHostApi->allocations, driverCount); + + if (!names) { result = paInsufficientMemory; goto error; } @@ -1147,64 +1298,59 @@ PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex /* allocate enough space for all drivers, even if some aren't installed */ - (*hostApi)->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory( - asioHostApi->allocations, sizeof(PaDeviceInfo*) * driverCount ); - if( !(*hostApi)->deviceInfos ) - { + (*hostApi)->deviceInfos = (PaDeviceInfo**) PaUtil_GroupAllocateMemory ( + asioHostApi->allocations, sizeof (PaDeviceInfo*) * driverCount); + + if (! (*hostApi)->deviceInfos) { result = paInsufficientMemory; goto error; } /* allocate all device info structs in a contiguous block */ - deviceInfoArray = (PaAsioDeviceInfo*)PaUtil_GroupAllocateMemory( - asioHostApi->allocations, sizeof(PaAsioDeviceInfo) * driverCount ); - if( !deviceInfoArray ) - { + deviceInfoArray = (PaAsioDeviceInfo*) PaUtil_GroupAllocateMemory ( + asioHostApi->allocations, sizeof (PaAsioDeviceInfo) * driverCount); + + if (!deviceInfoArray) { result = paInsufficientMemory; goto error; } - IsDebuggerPresent_ = GetProcAddress( LoadLibrary( "Kernel32.dll" ), "IsDebuggerPresent" ); + IsDebuggerPresent_ = GetProcAddress (LoadLibrary ("Kernel32.dll"), "IsDebuggerPresent"); - for( i=0; i < driverCount; ++i ) - { + for (i=0; i < driverCount; ++i) { - PA_DEBUG(("ASIO names[%d]:%s\n",i,names[i])); + PA_DEBUG ( ("ASIO names[%d]:%s\n",i,names[i])); // Since portaudio opens ALL ASIO drivers, and no one else does that, // we face fact that some drivers were not meant for it, drivers which act // like shells on top of REAL drivers, for instance. // so we get duplicate handles, locks and other problems. - // so lets NOT try to load any such wrappers. + // so lets NOT try to load any such wrappers. // The ones i [davidv] know of so far are: - if ( strcmp (names[i],"ASIO DirectX Full Duplex Driver") == 0 - || strcmp (names[i],"ASIO Multimedia Driver") == 0 - || strncmp(names[i],"Premiere",8) == 0 //"Premiere Elements Windows Sound 1.0" - || strncmp(names[i],"Adobe",5) == 0 //"Adobe Default Windows Sound 1.5" - || strncmp(names[i],"ReaRoute ASIO",13) == 0 //Reaper www.reaper.fm <- fix your stuff man. - ) - { - PA_DEBUG(("BLACKLISTED!!!\n")); + if (strcmp (names[i],"ASIO DirectX Full Duplex Driver") == 0 + || strcmp (names[i],"ASIO Multimedia Driver") == 0 + || strncmp (names[i],"Premiere",8) == 0 //"Premiere Elements Windows Sound 1.0" + || strncmp (names[i],"Adobe",5) == 0 //"Adobe Default Windows Sound 1.5" + || strncmp (names[i],"ReaRoute ASIO",13) == 0 //Reaper www.reaper.fm <- fix your stuff man. + ) { + PA_DEBUG ( ("BLACKLISTED!!!\n")); continue; } - if( IsDebuggerPresent_ && IsDebuggerPresent_() ) - { + if (IsDebuggerPresent_ && IsDebuggerPresent_()) { /* ASIO Digidesign Driver uses PACE copy protection which quits out if a debugger is running. So we don't load it if a debugger is running. */ - if( strcmp(names[i], "ASIO Digidesign Driver") == 0 ) - { - PA_DEBUG(("BLACKLISTED!!! ASIO Digidesign Driver would quit the debugger\n")); - continue; - } - } + if (strcmp (names[i], "ASIO Digidesign Driver") == 0) { + PA_DEBUG ( ("BLACKLISTED!!! ASIO Digidesign Driver would quit the debugger\n")); + continue; + } + } /* Attempt to load the asio driver... */ - if( LoadAsioDriver( asioHostApi, names[i], &paAsioDriverInfo, asioHostApi->systemSpecific ) == paNoError ) - { + if (LoadAsioDriver (asioHostApi, names[i], &paAsioDriverInfo, asioHostApi->systemSpecific) == paNoError) { PaAsioDeviceInfo *asioDeviceInfo = &deviceInfoArray[ (*hostApi)->info.deviceCount ]; PaDeviceInfo *deviceInfo = &asioDeviceInfo->commonDeviceInfo; @@ -1212,33 +1358,33 @@ PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex deviceInfo->hostApi = hostApiIndex; deviceInfo->name = names[i]; - PA_DEBUG(("PaAsio_Initialize: drv:%d name = %s\n", i,deviceInfo->name)); - PA_DEBUG(("PaAsio_Initialize: drv:%d inputChannels = %d\n", i, paAsioDriverInfo.inputChannelCount)); - PA_DEBUG(("PaAsio_Initialize: drv:%d outputChannels = %d\n", i, paAsioDriverInfo.outputChannelCount)); - PA_DEBUG(("PaAsio_Initialize: drv:%d bufferMinSize = %d\n", i, paAsioDriverInfo.bufferMinSize)); - PA_DEBUG(("PaAsio_Initialize: drv:%d bufferMaxSize = %d\n", i, paAsioDriverInfo.bufferMaxSize)); - PA_DEBUG(("PaAsio_Initialize: drv:%d bufferPreferredSize = %d\n", i, paAsioDriverInfo.bufferPreferredSize)); - PA_DEBUG(("PaAsio_Initialize: drv:%d bufferGranularity = %d\n", i, paAsioDriverInfo.bufferGranularity)); + PA_DEBUG ( ("PaAsio_Initialize: drv:%d name = %s\n", i,deviceInfo->name)); + PA_DEBUG ( ("PaAsio_Initialize: drv:%d inputChannels = %d\n", i, paAsioDriverInfo.inputChannelCount)); + PA_DEBUG ( ("PaAsio_Initialize: drv:%d outputChannels = %d\n", i, paAsioDriverInfo.outputChannelCount)); + PA_DEBUG ( ("PaAsio_Initialize: drv:%d bufferMinSize = %d\n", i, paAsioDriverInfo.bufferMinSize)); + PA_DEBUG ( ("PaAsio_Initialize: drv:%d bufferMaxSize = %d\n", i, paAsioDriverInfo.bufferMaxSize)); + PA_DEBUG ( ("PaAsio_Initialize: drv:%d bufferPreferredSize = %d\n", i, paAsioDriverInfo.bufferPreferredSize)); + PA_DEBUG ( ("PaAsio_Initialize: drv:%d bufferGranularity = %d\n", i, paAsioDriverInfo.bufferGranularity)); deviceInfo->maxInputChannels = paAsioDriverInfo.inputChannelCount; deviceInfo->maxOutputChannels = paAsioDriverInfo.outputChannelCount; deviceInfo->defaultSampleRate = 0.; bool foundDefaultSampleRate = false; - for( int j=0; j < PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_; ++j ) - { - ASIOError asioError = ASIOCanSampleRate( defaultSampleRateSearchOrder_[j] ); - if( asioError != ASE_NoClock && asioError != ASE_NotPresent ) - { + + for (int j=0; j < PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_; ++j) { + ASIOError asioError = ASIOCanSampleRate (defaultSampleRateSearchOrder_[j]); + + if (asioError != ASE_NoClock && asioError != ASE_NotPresent) { deviceInfo->defaultSampleRate = defaultSampleRateSearchOrder_[j]; foundDefaultSampleRate = true; break; } } - PA_DEBUG(("PaAsio_Initialize: drv:%d defaultSampleRate = %f\n", i, deviceInfo->defaultSampleRate)); + PA_DEBUG ( ("PaAsio_Initialize: drv:%d defaultSampleRate = %f\n", i, deviceInfo->defaultSampleRate)); - if( foundDefaultSampleRate ){ + if (foundDefaultSampleRate) { /* calculate default latency values from bufferPreferredSize for default low latency, and bufferPreferredSize * 3 @@ -1249,27 +1395,28 @@ PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex */ double defaultLowLatency = - paAsioDriverInfo.bufferPreferredSize / deviceInfo->defaultSampleRate; + paAsioDriverInfo.bufferPreferredSize / deviceInfo->defaultSampleRate; deviceInfo->defaultLowInputLatency = defaultLowLatency; deviceInfo->defaultLowOutputLatency = defaultLowLatency; long defaultHighLatencyBufferSize = - paAsioDriverInfo.bufferPreferredSize * 3; + paAsioDriverInfo.bufferPreferredSize * 3; - if( defaultHighLatencyBufferSize > paAsioDriverInfo.bufferMaxSize ) + if (defaultHighLatencyBufferSize > paAsioDriverInfo.bufferMaxSize) defaultHighLatencyBufferSize = paAsioDriverInfo.bufferMaxSize; double defaultHighLatency = - defaultHighLatencyBufferSize / deviceInfo->defaultSampleRate; + defaultHighLatencyBufferSize / deviceInfo->defaultSampleRate; + + if (defaultHighLatency < defaultLowLatency) + defaultHighLatency = defaultLowLatency; /* just incase the driver returns something strange */ - if( defaultHighLatency < defaultLowLatency ) - defaultHighLatency = defaultLowLatency; /* just incase the driver returns something strange */ - deviceInfo->defaultHighInputLatency = defaultHighLatency; + deviceInfo->defaultHighOutputLatency = defaultHighLatency; - - }else{ + + } else { deviceInfo->defaultLowInputLatency = 0.; deviceInfo->defaultLowOutputLatency = 0.; @@ -1277,10 +1424,11 @@ PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex deviceInfo->defaultHighOutputLatency = 0.; } - PA_DEBUG(("PaAsio_Initialize: drv:%d defaultLowInputLatency = %f\n", i, deviceInfo->defaultLowInputLatency)); - PA_DEBUG(("PaAsio_Initialize: drv:%d defaultLowOutputLatency = %f\n", i, deviceInfo->defaultLowOutputLatency)); - PA_DEBUG(("PaAsio_Initialize: drv:%d defaultHighInputLatency = %f\n", i, deviceInfo->defaultHighInputLatency)); - PA_DEBUG(("PaAsio_Initialize: drv:%d defaultHighOutputLatency = %f\n", i, deviceInfo->defaultHighOutputLatency)); + PA_DEBUG ( ("PaAsio_Initialize: drv:%d defaultLowInputLatency = %f\n", i, deviceInfo->defaultLowInputLatency)); + + PA_DEBUG ( ("PaAsio_Initialize: drv:%d defaultLowOutputLatency = %f\n", i, deviceInfo->defaultLowOutputLatency)); + PA_DEBUG ( ("PaAsio_Initialize: drv:%d defaultHighInputLatency = %f\n", i, deviceInfo->defaultHighInputLatency)); + PA_DEBUG ( ("PaAsio_Initialize: drv:%d defaultHighOutputLatency = %f\n", i, deviceInfo->defaultHighOutputLatency)); asioDeviceInfo->minBufferSize = paAsioDriverInfo.bufferMinSize; asioDeviceInfo->maxBufferSize = paAsioDriverInfo.bufferMaxSize; @@ -1288,39 +1436,39 @@ PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex asioDeviceInfo->bufferGranularity = paAsioDriverInfo.bufferGranularity; - asioDeviceInfo->asioChannelInfos = (ASIOChannelInfo*)PaUtil_GroupAllocateMemory( - asioHostApi->allocations, - sizeof(ASIOChannelInfo) * (deviceInfo->maxInputChannels - + deviceInfo->maxOutputChannels) ); - if( !asioDeviceInfo->asioChannelInfos ) - { + asioDeviceInfo->asioChannelInfos = (ASIOChannelInfo*) PaUtil_GroupAllocateMemory ( + asioHostApi->allocations, + sizeof (ASIOChannelInfo) * (deviceInfo->maxInputChannels + + deviceInfo->maxOutputChannels)); + + if (!asioDeviceInfo->asioChannelInfos) { result = paInsufficientMemory; goto error_unload; } int a; - for( a=0; a < deviceInfo->maxInputChannels; ++a ){ + for (a=0; a < deviceInfo->maxInputChannels; ++a) { asioDeviceInfo->asioChannelInfos[a].channel = a; asioDeviceInfo->asioChannelInfos[a].isInput = ASIOTrue; - ASIOError asioError = ASIOGetChannelInfo( &asioDeviceInfo->asioChannelInfos[a] ); - if( asioError != ASE_OK ) - { + ASIOError asioError = ASIOGetChannelInfo (&asioDeviceInfo->asioChannelInfos[a]); + + if (asioError != ASE_OK) { result = paUnanticipatedHostError; - PA_ASIO_SET_LAST_ASIO_ERROR( asioError ); + PA_ASIO_SET_LAST_ASIO_ERROR (asioError); goto error_unload; } } - for( a=0; a < deviceInfo->maxOutputChannels; ++a ){ + for (a=0; a < deviceInfo->maxOutputChannels; ++a) { int b = deviceInfo->maxInputChannels + a; asioDeviceInfo->asioChannelInfos[b].channel = a; asioDeviceInfo->asioChannelInfos[b].isInput = ASIOFalse; - ASIOError asioError = ASIOGetChannelInfo( &asioDeviceInfo->asioChannelInfos[b] ); - if( asioError != ASE_OK ) - { + ASIOError asioError = ASIOGetChannelInfo (&asioDeviceInfo->asioChannelInfos[b]); + + if (asioError != ASE_OK) { result = paUnanticipatedHostError; - PA_ASIO_SET_LAST_ASIO_ERROR( asioError ); + PA_ASIO_SET_LAST_ASIO_ERROR (asioError); goto error_unload; } } @@ -1330,18 +1478,16 @@ PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex UnloadAsioDriver(); (*hostApi)->deviceInfos[ (*hostApi)->info.deviceCount ] = deviceInfo; - ++(*hostApi)->info.deviceCount; + + ++ (*hostApi)->info.deviceCount; } } } - if( (*hostApi)->info.deviceCount > 0 ) - { + if ( (*hostApi)->info.deviceCount > 0) { (*hostApi)->info.defaultInputDevice = 0; (*hostApi)->info.defaultOutputDevice = 0; - } - else - { + } else { (*hostApi)->info.defaultInputDevice = paNoDevice; (*hostApi)->info.defaultOutputDevice = paNoDevice; } @@ -1351,97 +1497,97 @@ PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex (*hostApi)->OpenStream = OpenStream; (*hostApi)->IsFormatSupported = IsFormatSupported; - PaUtil_InitializeStreamInterface( &asioHostApi->callbackStreamInterface, CloseStream, StartStream, + PaUtil_InitializeStreamInterface (&asioHostApi->callbackStreamInterface, CloseStream, StartStream, StopStream, AbortStream, IsStreamStopped, IsStreamActive, GetStreamTime, GetStreamCpuLoad, PaUtil_DummyRead, PaUtil_DummyWrite, - PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable ); + PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable); - PaUtil_InitializeStreamInterface( &asioHostApi->blockingStreamInterface, CloseStream, StartStream, + PaUtil_InitializeStreamInterface (&asioHostApi->blockingStreamInterface, CloseStream, StartStream, StopStream, AbortStream, IsStreamStopped, IsStreamActive, GetStreamTime, PaUtil_DummyGetCpuLoad, - ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable ); + ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable); return result; error_unload: - UnloadAsioDriver(); + UnloadAsioDriver(); error: - if( asioHostApi ) - { - if( asioHostApi->allocations ) - { - PaUtil_FreeAllAllocations( asioHostApi->allocations ); - PaUtil_DestroyAllocationGroup( asioHostApi->allocations ); + + if (asioHostApi) { + if (asioHostApi->allocations) { + PaUtil_FreeAllAllocations (asioHostApi->allocations); + PaUtil_DestroyAllocationGroup (asioHostApi->allocations); } delete asioHostApi->asioDrivers; + asioDrivers = 0; /* keep SDK global in sync until we stop depending on it */ - PaUtil_FreeMemory( asioHostApi ); + PaUtil_FreeMemory (asioHostApi); } + return result; } -static void Terminate( struct PaUtilHostApiRepresentation *hostApi ) +static void Terminate (struct PaUtilHostApiRepresentation *hostApi) { - PaAsioHostApiRepresentation *asioHostApi = (PaAsioHostApiRepresentation*)hostApi; + PaAsioHostApiRepresentation *asioHostApi = (PaAsioHostApiRepresentation*) hostApi; /* IMPLEMENT ME: - clean up any resources not handled by the allocation group (need to review if there are any) */ - if( asioHostApi->allocations ) - { - PaUtil_FreeAllAllocations( asioHostApi->allocations ); - PaUtil_DestroyAllocationGroup( asioHostApi->allocations ); + if (asioHostApi->allocations) { + PaUtil_FreeAllAllocations (asioHostApi->allocations); + PaUtil_DestroyAllocationGroup (asioHostApi->allocations); } delete asioHostApi->asioDrivers; /* calls CoUninitialize() */ + asioDrivers = 0; /* keep SDK global in sync until we stop depending on it */ - PaUtil_FreeMemory( asioHostApi ); + PaUtil_FreeMemory (asioHostApi); } -static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, +static PaError IsFormatSupported (struct PaUtilHostApiRepresentation *hostApi, const PaStreamParameters *inputParameters, const PaStreamParameters *outputParameters, - double sampleRate ) + double sampleRate) { PaError result = paNoError; - PaAsioHostApiRepresentation *asioHostApi = (PaAsioHostApiRepresentation*)hostApi; + PaAsioHostApiRepresentation *asioHostApi = (PaAsioHostApiRepresentation*) hostApi; PaAsioDriverInfo *driverInfo = &asioHostApi->openAsioDriverInfo; int inputChannelCount, outputChannelCount; PaSampleFormat inputSampleFormat, outputSampleFormat; - PaDeviceIndex asioDeviceIndex; + PaDeviceIndex asioDeviceIndex; ASIOError asioError; - - if( inputParameters && outputParameters ) - { + + if (inputParameters && outputParameters) { /* full duplex ASIO stream must use the same device for input and output */ - if( inputParameters->device != outputParameters->device ) + if (inputParameters->device != outputParameters->device) return paBadIODeviceCombination; } - - if( inputParameters ) - { + + if (inputParameters) { inputChannelCount = inputParameters->channelCount; inputSampleFormat = inputParameters->sampleFormat; /* all standard sample formats are supported by the buffer adapter, this implementation doesn't support any custom sample formats */ - if( inputSampleFormat & paCustomFormat ) + + if (inputSampleFormat & paCustomFormat) return paSampleFormatNotSupported; - + /* unless alternate device specification is supported, reject the use of paUseHostApiSpecificDeviceSpecification */ - if( inputParameters->device == paUseHostApiSpecificDeviceSpecification ) + if (inputParameters->device == paUseHostApiSpecificDeviceSpecification) return paInvalidDevice; asioDeviceIndex = inputParameters->device; @@ -1450,26 +1596,24 @@ static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, /** @todo do more validation here */ // if( inputParameters->hostApiSpecificStreamInfo ) // return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */ - } - else - { + } else { inputChannelCount = 0; } - if( outputParameters ) - { + if (outputParameters) { outputChannelCount = outputParameters->channelCount; outputSampleFormat = outputParameters->sampleFormat; /* all standard sample formats are supported by the buffer adapter, this implementation doesn't support any custom sample formats */ - if( outputSampleFormat & paCustomFormat ) + + if (outputSampleFormat & paCustomFormat) return paSampleFormatNotSupported; - + /* unless alternate device specification is supported, reject the use of paUseHostApiSpecificDeviceSpecification */ - if( outputParameters->device == paUseHostApiSpecificDeviceSpecification ) + if (outputParameters->device == paUseHostApiSpecificDeviceSpecification) return paInvalidDevice; asioDeviceIndex = outputParameters->device; @@ -1478,9 +1622,7 @@ static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, /** @todo do more validation here */ // if( outputParameters->hostApiSpecificStreamInfo ) // return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */ - } - else - { + } else { outputChannelCount = 0; } @@ -1488,9 +1630,8 @@ static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, /* if an ASIO device is open we can only get format information for the currently open device */ - if( asioHostApi->openAsioDeviceIndex != paNoDevice - && asioHostApi->openAsioDeviceIndex != asioDeviceIndex ) - { + if (asioHostApi->openAsioDeviceIndex != paNoDevice + && asioHostApi->openAsioDeviceIndex != asioDeviceIndex) { return paDeviceUnavailable; } @@ -1499,50 +1640,47 @@ static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, rather than the ones in our device info structure which may be stale */ /* open the device if it's not already open */ - if( asioHostApi->openAsioDeviceIndex == paNoDevice ) - { - result = LoadAsioDriver( asioHostApi, asioHostApi->inheritedHostApiRep.deviceInfos[ asioDeviceIndex ]->name, - driverInfo, asioHostApi->systemSpecific ); - if( result != paNoError ) + if (asioHostApi->openAsioDeviceIndex == paNoDevice) { + result = LoadAsioDriver (asioHostApi, asioHostApi->inheritedHostApiRep.deviceInfos[ asioDeviceIndex ]->name, + driverInfo, asioHostApi->systemSpecific); + + if (result != paNoError) return result; } /* check that input device can support inputChannelCount */ - if( inputChannelCount > 0 ) - { - if( inputChannelCount > driverInfo->inputChannelCount ) - { + if (inputChannelCount > 0) { + if (inputChannelCount > driverInfo->inputChannelCount) { result = paInvalidChannelCount; goto done; } } /* check that output device can support outputChannelCount */ - if( outputChannelCount ) - { - if( outputChannelCount > driverInfo->outputChannelCount ) - { + if (outputChannelCount) { + if (outputChannelCount > driverInfo->outputChannelCount) { result = paInvalidChannelCount; goto done; } } - + /* query for sample rate support */ - asioError = ASIOCanSampleRate( sampleRate ); - if( asioError == ASE_NoClock || asioError == ASE_NotPresent ) - { + asioError = ASIOCanSampleRate (sampleRate); + + if (asioError == ASE_NoClock || asioError == ASE_NotPresent) { result = paInvalidSampleRate; goto done; } done: + /* close the device if it wasn't already open */ - if( asioHostApi->openAsioDeviceIndex == paNoDevice ) - { + + if (asioHostApi->openAsioDeviceIndex == paNoDevice) { UnloadAsioDriver(); /* not sure if we should check for errors here */ } - if( result == paNoError ) + if (result == paNoError) return paFormatIsSupported; else return result; @@ -1551,8 +1689,8 @@ done: /** A data structure specifically for storing blocking i/o related data. */ -typedef struct PaAsioStreamBlockingState -{ + +typedef struct PaAsioStreamBlockingState { int stopFlag; /**< Flag indicating that block processing is to be stopped. */ unsigned long writeBuffersRequested; /**< The number of available output buffers, requested by the #WriteStream() function. */ @@ -1580,14 +1718,14 @@ typedef struct PaAsioStreamBlockingState int outputUnderflowFlag; /**< Flag to signal an output underflow from within the callback function. */ int inputOverflowFlag; /**< Flag to signal an input overflow from within the callback function. */ } + PaAsioStreamBlockingState; /* PaAsioStream - a stream data structure specifically for this implementation */ -typedef struct PaAsioStream -{ +typedef struct PaAsioStream { PaUtilStreamRepresentation streamRepresentation; PaUtilCpuLoadMeasurer cpuLoadMeasurer; PaUtilBufferProcessor bufferProcessor; @@ -1630,86 +1768,71 @@ typedef struct PaAsioStream PaAsioStreamBlockingState *blockingState; /**< Blocking i/o data struct, or NULL when using callback interface. */ } + PaAsioStream; static PaAsioStream *theAsioStream = 0; /* due to ASIO sdk limitations there can be only one stream */ -static void ZeroOutputBuffers( PaAsioStream *stream, long index ) +static void ZeroOutputBuffers (PaAsioStream *stream, long index) { int i; - for( i=0; i < stream->outputChannelCount; ++i ) - { + for (i=0; i < stream->outputChannelCount; ++i) { void *buffer = stream->asioBufferInfos[ i + stream->inputChannelCount ].buffers[index]; - int bytesPerSample = BytesPerAsioSample( stream->asioChannelInfos[ i + stream->inputChannelCount ].type ); + int bytesPerSample = BytesPerAsioSample (stream->asioChannelInfos[ i + stream->inputChannelCount ].type); - memset( buffer, 0, stream->framesPerHostCallback * bytesPerSample ); + memset (buffer, 0, stream->framesPerHostCallback * bytesPerSample); } } -static unsigned long SelectHostBufferSize( unsigned long suggestedLatencyFrames, - PaAsioDriverInfo *driverInfo ) +static unsigned long SelectHostBufferSize (unsigned long suggestedLatencyFrames, + PaAsioDriverInfo *driverInfo) { unsigned long result; - if( suggestedLatencyFrames == 0 ) - { + if (suggestedLatencyFrames == 0) { result = driverInfo->bufferPreferredSize; - } - else{ - if( suggestedLatencyFrames <= (unsigned long)driverInfo->bufferMinSize ) - { + } else { + if (suggestedLatencyFrames <= (unsigned long) driverInfo->bufferMinSize) { result = driverInfo->bufferMinSize; - } - else if( suggestedLatencyFrames >= (unsigned long)driverInfo->bufferMaxSize ) - { + } else if (suggestedLatencyFrames >= (unsigned long) driverInfo->bufferMaxSize) { result = driverInfo->bufferMaxSize; - } - else - { - if( driverInfo->bufferGranularity == -1 ) - { + } else { + if (driverInfo->bufferGranularity == -1) { /* power-of-two */ result = 2; - while( result < suggestedLatencyFrames ) + while (result < suggestedLatencyFrames) result *= 2; - if( result < (unsigned long)driverInfo->bufferMinSize ) + if (result < (unsigned long) driverInfo->bufferMinSize) result = driverInfo->bufferMinSize; - if( result > (unsigned long)driverInfo->bufferMaxSize ) + if (result > (unsigned long) driverInfo->bufferMaxSize) result = driverInfo->bufferMaxSize; - } - else if( driverInfo->bufferGranularity == 0 ) - { + } else if (driverInfo->bufferGranularity == 0) { /* the documentation states that bufferGranularity should be zero when bufferMinSize, bufferMaxSize and bufferPreferredSize are the same. We assume that is the case. */ result = driverInfo->bufferPreferredSize; - } - else - { + } else { /* modulo granularity */ unsigned long remainder = - suggestedLatencyFrames % driverInfo->bufferGranularity; + suggestedLatencyFrames % driverInfo->bufferGranularity; - if( remainder == 0 ) - { + if (remainder == 0) { result = suggestedLatencyFrames; - } - else - { + } else { result = suggestedLatencyFrames - + (driverInfo->bufferGranularity - remainder); + + (driverInfo->bufferGranularity - remainder); - if( result > (unsigned long)driverInfo->bufferMaxSize ) + if (result > (unsigned long) driverInfo->bufferMaxSize) result = driverInfo->bufferMaxSize; } } @@ -1722,31 +1845,29 @@ static unsigned long SelectHostBufferSize( unsigned long suggestedLatencyFrames, /* returns channelSelectors if present */ -static PaError ValidateAsioSpecificStreamInfo( - const PaStreamParameters *streamParameters, - const PaAsioStreamInfo *streamInfo, - int deviceChannelCount, - int **channelSelectors ) +static PaError ValidateAsioSpecificStreamInfo ( + const PaStreamParameters *streamParameters, + const PaAsioStreamInfo *streamInfo, + int deviceChannelCount, + int **channelSelectors) { - if( streamInfo ) - { - if( streamInfo->size != sizeof( PaAsioStreamInfo ) - || streamInfo->version != 1 ) - { + if (streamInfo) { + if (streamInfo->size != sizeof (PaAsioStreamInfo) + || streamInfo->version != 1) { return paIncompatibleHostApiSpecificStreamInfo; } - if( streamInfo->flags & paAsioUseChannelSelectors ) + if (streamInfo->flags & paAsioUseChannelSelectors) *channelSelectors = streamInfo->channelSelectors; - if( !(*channelSelectors) ) + if (! (*channelSelectors)) return paIncompatibleHostApiSpecificStreamInfo; - for( int i=0; i < streamParameters->channelCount; ++i ){ - if( (*channelSelectors)[i] < 0 - || (*channelSelectors)[i] >= deviceChannelCount ){ + for (int i=0; i < streamParameters->channelCount; ++i) { + if ( (*channelSelectors) [i] < 0 + || (*channelSelectors) [i] >= deviceChannelCount) { return paInvalidChannelCount; - } + } } } @@ -1756,7 +1877,7 @@ static PaError ValidateAsioSpecificStreamInfo( /* see pa_hostapi.h for a list of validity guarantees made about OpenStream parameters */ -static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, +static PaError OpenStream (struct PaUtilHostApiRepresentation *hostApi, PaStream** s, const PaStreamParameters *inputParameters, const PaStreamParameters *outputParameters, @@ -1764,10 +1885,10 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, unsigned long framesPerBuffer, PaStreamFlags streamFlags, PaStreamCallback *streamCallback, - void *userData ) + void *userData) { PaError result = paNoError; - PaAsioHostApiRepresentation *asioHostApi = (PaAsioHostApiRepresentation*)hostApi; + PaAsioHostApiRepresentation *asioHostApi = (PaAsioHostApiRepresentation*) hostApi; PaAsioStream *stream = 0; PaAsioStreamInfo *inputStreamInfo, *outputStreamInfo; unsigned long framesPerHostBuffer; @@ -1788,7 +1909,7 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, bool isExternal = false; /* Are we using blocking i/o interface? */ - int usingBlockingIo = ( !streamCallback ) ? TRUE : FALSE; + int usingBlockingIo = (!streamCallback) ? TRUE : FALSE; /* Blocking i/o stuff */ long lBlockingBufferSize = 0; /* Desired ring buffer size in samples. */ long lBlockingBufferSizePow2 = 0; /* Power-of-2 rounded ring buffer size. */ @@ -1801,78 +1922,76 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, /* unless we move to using lower level ASIO calls, we can only have one device open at a time */ - if( asioHostApi->openAsioDeviceIndex != paNoDevice ) - { - PA_DEBUG(("OpenStream paDeviceUnavailable\n")); + + if (asioHostApi->openAsioDeviceIndex != paNoDevice) { + PA_DEBUG ( ("OpenStream paDeviceUnavailable\n")); return paDeviceUnavailable; } - if( inputParameters && outputParameters ) - { + if (inputParameters && outputParameters) { /* full duplex ASIO stream must use the same device for input and output */ - if( inputParameters->device != outputParameters->device ) - { - PA_DEBUG(("OpenStream paBadIODeviceCombination\n")); + if (inputParameters->device != outputParameters->device) { + PA_DEBUG ( ("OpenStream paBadIODeviceCombination\n")); return paBadIODeviceCombination; } } - if( inputParameters ) - { + if (inputParameters) { inputChannelCount = inputParameters->channelCount; inputSampleFormat = inputParameters->sampleFormat; - suggestedInputLatencyFrames = (unsigned long)((inputParameters->suggestedLatency * sampleRate)+0.5f); + suggestedInputLatencyFrames = (unsigned long) ( (inputParameters->suggestedLatency * sampleRate) +0.5f); /* unless alternate device specification is supported, reject the use of paUseHostApiSpecificDeviceSpecification */ - if( inputParameters->device == paUseHostApiSpecificDeviceSpecification ) + + if (inputParameters->device == paUseHostApiSpecificDeviceSpecification) return paInvalidDevice; asioDeviceIndex = inputParameters->device; - PaAsioDeviceInfo *asioDeviceInfo = (PaAsioDeviceInfo*)hostApi->deviceInfos[asioDeviceIndex]; + PaAsioDeviceInfo *asioDeviceInfo = (PaAsioDeviceInfo*) hostApi->deviceInfos[asioDeviceIndex]; /* validate hostApiSpecificStreamInfo */ - inputStreamInfo = (PaAsioStreamInfo*)inputParameters->hostApiSpecificStreamInfo; - result = ValidateAsioSpecificStreamInfo( inputParameters, inputStreamInfo, - asioDeviceInfo->commonDeviceInfo.maxInputChannels, - &inputChannelSelectors - ); - if( result != paNoError ) return result; - } - else - { + inputStreamInfo = (PaAsioStreamInfo*) inputParameters->hostApiSpecificStreamInfo; + + result = ValidateAsioSpecificStreamInfo (inputParameters, inputStreamInfo, + asioDeviceInfo->commonDeviceInfo.maxInputChannels, + &inputChannelSelectors + ); + + if (result != paNoError) return result; + } else { inputChannelCount = 0; inputSampleFormat = 0; suggestedInputLatencyFrames = 0; } - if( outputParameters ) - { + if (outputParameters) { outputChannelCount = outputParameters->channelCount; outputSampleFormat = outputParameters->sampleFormat; - suggestedOutputLatencyFrames = (unsigned long)((outputParameters->suggestedLatency * sampleRate)+0.5f); + suggestedOutputLatencyFrames = (unsigned long) ( (outputParameters->suggestedLatency * sampleRate) +0.5f); /* unless alternate device specification is supported, reject the use of paUseHostApiSpecificDeviceSpecification */ - if( outputParameters->device == paUseHostApiSpecificDeviceSpecification ) + + if (outputParameters->device == paUseHostApiSpecificDeviceSpecification) return paInvalidDevice; asioDeviceIndex = outputParameters->device; - PaAsioDeviceInfo *asioDeviceInfo = (PaAsioDeviceInfo*)hostApi->deviceInfos[asioDeviceIndex]; + PaAsioDeviceInfo *asioDeviceInfo = (PaAsioDeviceInfo*) hostApi->deviceInfos[asioDeviceIndex]; /* validate hostApiSpecificStreamInfo */ - outputStreamInfo = (PaAsioStreamInfo*)outputParameters->hostApiSpecificStreamInfo; - result = ValidateAsioSpecificStreamInfo( outputParameters, outputStreamInfo, - asioDeviceInfo->commonDeviceInfo.maxOutputChannels, - &outputChannelSelectors - ); - if( result != paNoError ) return result; - } - else - { + outputStreamInfo = (PaAsioStreamInfo*) outputParameters->hostApiSpecificStreamInfo; + + result = ValidateAsioSpecificStreamInfo (outputParameters, outputStreamInfo, + asioDeviceInfo->commonDeviceInfo.maxOutputChannels, + &outputChannelSelectors + ); + + if (result != paNoError) return result; + } else { outputChannelCount = 0; outputSampleFormat = 0; suggestedOutputLatencyFrames = 0; @@ -1883,33 +2002,30 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, /* NOTE: we load the driver and use its current settings rather than the ones in our device info structure which may be stale */ - result = LoadAsioDriver( asioHostApi, asioHostApi->inheritedHostApiRep.deviceInfos[ asioDeviceIndex ]->name, - driverInfo, asioHostApi->systemSpecific ); - if( result == paNoError ) + result = LoadAsioDriver (asioHostApi, asioHostApi->inheritedHostApiRep.deviceInfos[ asioDeviceIndex ]->name, + driverInfo, asioHostApi->systemSpecific); + + if (result == paNoError) asioIsInitialized = 1; - else{ - PA_DEBUG(("OpenStream ERROR1 - LoadAsioDriver returned %d\n", result)); + else { + PA_DEBUG ( ("OpenStream ERROR1 - LoadAsioDriver returned %d\n", result)); goto error; } /* check that input device can support inputChannelCount */ - if( inputChannelCount > 0 ) - { - if( inputChannelCount > driverInfo->inputChannelCount ) - { + if (inputChannelCount > 0) { + if (inputChannelCount > driverInfo->inputChannelCount) { result = paInvalidChannelCount; - PA_DEBUG(("OpenStream ERROR2\n")); + PA_DEBUG ( ("OpenStream ERROR2\n")); goto error; } } /* check that output device can support outputChannelCount */ - if( outputChannelCount ) - { - if( outputChannelCount > driverInfo->outputChannelCount ) - { + if (outputChannelCount) { + if (outputChannelCount > driverInfo->outputChannelCount) { result = paInvalidChannelCount; - PA_DEBUG(("OpenStream ERROR3\n")); + PA_DEBUG ( ("OpenStream ERROR3\n")); goto error; } } @@ -1921,16 +2037,18 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, { ASIOClockSource clocks[32]; long numSources=32; - asioError = ASIOGetClockSources(clocks, &numSources); - if( asioError != ASE_OK ){ - PA_DEBUG(("ERROR: ASIOGetClockSources: %s\n", PaAsio_GetAsioErrorText(asioError) )); - }else{ - PA_DEBUG(("INFO ASIOGetClockSources listing %d clocks\n", numSources )); - for (int i=0;i<numSources;++i){ - PA_DEBUG(("ASIOClockSource%d %s current:%d\n", i,clocks[i].name, clocks[i].isCurrentSource )); - + asioError = ASIOGetClockSources (clocks, &numSources); + + if (asioError != ASE_OK) { + PA_DEBUG ( ("ERROR: ASIOGetClockSources: %s\n", PaAsio_GetAsioErrorText (asioError))); + } else { + PA_DEBUG ( ("INFO ASIOGetClockSources listing %d clocks\n", numSources)); + + for (int i=0;i<numSources;++i) { + PA_DEBUG ( ("ASIOClockSource%d %s current:%d\n", i,clocks[i].name, clocks[i].isCurrentSource)); + /* - If you have problems with some drivers when externally clocked, + If you have problems with some drivers when externally clocked, uncomment the next two lines */ //if (clocks[i].isCurrentSource) @@ -1939,15 +2057,15 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, } } - // check that the device supports the requested sample rate + // check that the device supports the requested sample rate - asioError = ASIOCanSampleRate( sampleRate ); - PA_DEBUG(("ASIOCanSampleRate(%f):%d\n",sampleRate, asioError )); + asioError = ASIOCanSampleRate (sampleRate); - if( asioError != ASE_OK ) - { + PA_DEBUG ( ("ASIOCanSampleRate(%f):%d\n",sampleRate, asioError)); + + if (asioError != ASE_OK) { result = paInvalidSampleRate; - PA_DEBUG(("ERROR: ASIOCanSampleRate: %s\n", PaAsio_GetAsioErrorText(asioError) )); + PA_DEBUG ( ("ERROR: ASIOCanSampleRate: %s\n", PaAsio_GetAsioErrorText (asioError))); goto error; } @@ -1956,32 +2074,33 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, // sample rate if the device is not already in that rate. ASIOSampleRate oldRate; - asioError = ASIOGetSampleRate(&oldRate); - if( asioError != ASE_OK ) - { + + asioError = ASIOGetSampleRate (&oldRate); + + if (asioError != ASE_OK) { result = paInvalidSampleRate; - PA_DEBUG(("ERROR: ASIOGetSampleRate: %s\n", PaAsio_GetAsioErrorText(asioError) )); + PA_DEBUG ( ("ERROR: ASIOGetSampleRate: %s\n", PaAsio_GetAsioErrorText (asioError))); goto error; } - PA_DEBUG(("ASIOGetSampleRate:%f\n",oldRate)); - if (oldRate != sampleRate){ + PA_DEBUG ( ("ASIOGetSampleRate:%f\n",oldRate)); - PA_DEBUG(("before ASIOSetSampleRate(%f)\n",sampleRate)); + if (oldRate != sampleRate) { - asioError = ASIOSetSampleRate( isExternal?0:sampleRate ); + PA_DEBUG ( ("before ASIOSetSampleRate(%f)\n",sampleRate)); + + asioError = ASIOSetSampleRate (isExternal?0:sampleRate); /* Set sample rate */ - if( asioError != ASE_OK ) - { + + if (asioError != ASE_OK) { result = paInvalidSampleRate; - PA_DEBUG(("ERROR: ASIOSetSampleRate: %s\n", PaAsio_GetAsioErrorText(asioError) )); + PA_DEBUG ( ("ERROR: ASIOSetSampleRate: %s\n", PaAsio_GetAsioErrorText (asioError))); goto error; } - PA_DEBUG(("after ASIOSetSampleRate(%f)\n",sampleRate)); - } - else - { - PA_DEBUG(("No Need to change SR\n")); + + PA_DEBUG ( ("after ASIOSetSampleRate(%f)\n",sampleRate)); + } else { + PA_DEBUG ( ("No Need to change SR\n")); } @@ -1992,30 +2111,32 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, */ /* validate platform specific flags */ - if( (streamFlags & paPlatformSpecificFlags) != 0 ){ - PA_DEBUG(("OpenStream invalid flags!!\n")); + if ( (streamFlags & paPlatformSpecificFlags) != 0) { + PA_DEBUG ( ("OpenStream invalid flags!!\n")); return paInvalidFlag; /* unexpected platform specific flag */ } - stream = (PaAsioStream*)PaUtil_AllocateMemory( sizeof(PaAsioStream) ); - if( !stream ) - { + stream = (PaAsioStream*) PaUtil_AllocateMemory (sizeof (PaAsioStream)); + + if (!stream) { result = paInsufficientMemory; - PA_DEBUG(("OpenStream ERROR5\n")); + PA_DEBUG ( ("OpenStream ERROR5\n")); goto error; } + stream->blockingState = NULL; /* Blocking i/o not initialized, yet. */ - stream->completedBuffersPlayedEvent = CreateEvent( NULL, TRUE, FALSE, NULL ); - if( stream->completedBuffersPlayedEvent == NULL ) - { + stream->completedBuffersPlayedEvent = CreateEvent (NULL, TRUE, FALSE, NULL); + + if (stream->completedBuffersPlayedEvent == NULL) { result = paUnanticipatedHostError; - PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() ); - PA_DEBUG(("OpenStream ERROR6\n")); + PA_ASIO_SET_LAST_SYSTEM_ERROR (GetLastError()); + PA_DEBUG ( ("OpenStream ERROR6\n")); goto error; } + completedBuffersPlayedEventInited = 1; @@ -2024,95 +2145,88 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, stream->bufferPtrs = 0; /* for deallocation in error */ /* Using blocking i/o interface... */ - if( usingBlockingIo ) - { + + if (usingBlockingIo) { /* Blocking i/o is implemented by running callback mode, using a special blocking i/o callback. */ streamCallback = BlockingIoPaCallback; /* Setup PA to use the ASIO blocking i/o callback. */ userData = &theAsioStream; /* The callback user data will be the PA ASIO stream. */ - PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation, - &asioHostApi->blockingStreamInterface, streamCallback, userData ); - } - else /* Using callback interface... */ - { - PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation, - &asioHostApi->callbackStreamInterface, streamCallback, userData ); + PaUtil_InitializeStreamRepresentation (&stream->streamRepresentation, + &asioHostApi->blockingStreamInterface, streamCallback, userData); + } else { /* Using callback interface... */ + PaUtil_InitializeStreamRepresentation (&stream->streamRepresentation, + &asioHostApi->callbackStreamInterface, streamCallback, userData); } - PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate ); + PaUtil_InitializeCpuLoadMeasurer (&stream->cpuLoadMeasurer, sampleRate); - stream->asioBufferInfos = (ASIOBufferInfo*)PaUtil_AllocateMemory( - sizeof(ASIOBufferInfo) * (inputChannelCount + outputChannelCount) ); - if( !stream->asioBufferInfos ) - { + stream->asioBufferInfos = (ASIOBufferInfo*) PaUtil_AllocateMemory ( + sizeof (ASIOBufferInfo) * (inputChannelCount + outputChannelCount)); + + if (!stream->asioBufferInfos) { result = paInsufficientMemory; - PA_DEBUG(("OpenStream ERROR7\n")); + PA_DEBUG ( ("OpenStream ERROR7\n")); goto error; } - for( i=0; i < inputChannelCount; ++i ) - { + for (i=0; i < inputChannelCount; ++i) { ASIOBufferInfo *info = &stream->asioBufferInfos[i]; info->isInput = ASIOTrue; - if( inputChannelSelectors ){ + if (inputChannelSelectors) { // inputChannelSelectors values have already been validated in // ValidateAsioSpecificStreamInfo() above info->channelNum = inputChannelSelectors[i]; - }else{ + } else { info->channelNum = i; } info->buffers[0] = info->buffers[1] = 0; } - for( i=0; i < outputChannelCount; ++i ){ + for (i=0; i < outputChannelCount; ++i) { ASIOBufferInfo *info = &stream->asioBufferInfos[inputChannelCount+i]; info->isInput = ASIOFalse; - if( outputChannelSelectors ){ + if (outputChannelSelectors) { // outputChannelSelectors values have already been validated in // ValidateAsioSpecificStreamInfo() above info->channelNum = outputChannelSelectors[i]; - }else{ + } else { info->channelNum = i; } - + info->buffers[0] = info->buffers[1] = 0; } /* Using blocking i/o interface... */ - if( usingBlockingIo ) - { -/** @todo REVIEW selection of host buffer size for blocking i/o */ + if (usingBlockingIo) { + /** @todo REVIEW selection of host buffer size for blocking i/o */ /* Use default host latency for blocking i/o. */ - framesPerHostBuffer = SelectHostBufferSize( 0, driverInfo ); + framesPerHostBuffer = SelectHostBufferSize (0, driverInfo); - } - else /* Using callback interface... */ - { - framesPerHostBuffer = SelectHostBufferSize( - (( suggestedInputLatencyFrames > suggestedOutputLatencyFrames ) - ? suggestedInputLatencyFrames : suggestedOutputLatencyFrames), - driverInfo ); + } else { /* Using callback interface... */ + framesPerHostBuffer = SelectHostBufferSize ( + ( (suggestedInputLatencyFrames > suggestedOutputLatencyFrames) + ? suggestedInputLatencyFrames : suggestedOutputLatencyFrames), + driverInfo); } - PA_DEBUG(("PaAsioOpenStream: framesPerHostBuffer :%d\n", framesPerHostBuffer)); + PA_DEBUG ( ("PaAsioOpenStream: framesPerHostBuffer :%d\n", framesPerHostBuffer)); - asioError = ASIOCreateBuffers( stream->asioBufferInfos, - inputChannelCount+outputChannelCount, - framesPerHostBuffer, &asioCallbacks_ ); + asioError = ASIOCreateBuffers (stream->asioBufferInfos, + inputChannelCount+outputChannelCount, + framesPerHostBuffer, &asioCallbacks_); - if( asioError != ASE_OK - && framesPerHostBuffer != (unsigned long)driverInfo->bufferPreferredSize ) - { - PA_DEBUG(("ERROR: ASIOCreateBuffers: %s\n", PaAsio_GetAsioErrorText(asioError) )); + if (asioError != ASE_OK + && framesPerHostBuffer != (unsigned long) driverInfo->bufferPreferredSize) { + PA_DEBUG ( ("ERROR: ASIOCreateBuffers: %s\n", PaAsio_GetAsioErrorText (asioError))); /* Some buggy drivers (like the Hoontech DSP24) give incorrect [min, preferred, max] values They should work with the preferred size @@ -2122,221 +2236,217 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, framesPerHostBuffer = driverInfo->bufferPreferredSize; - PA_DEBUG(("PaAsioOpenStream: CORRECTED framesPerHostBuffer :%d\n", framesPerHostBuffer)); + PA_DEBUG ( ("PaAsioOpenStream: CORRECTED framesPerHostBuffer :%d\n", framesPerHostBuffer)); - ASIOError asioError2 = ASIOCreateBuffers( stream->asioBufferInfos, - inputChannelCount+outputChannelCount, - framesPerHostBuffer, &asioCallbacks_ ); - if( asioError2 == ASE_OK ) + ASIOError asioError2 = ASIOCreateBuffers (stream->asioBufferInfos, + inputChannelCount+outputChannelCount, + framesPerHostBuffer, &asioCallbacks_); + + if (asioError2 == ASE_OK) asioError = ASE_OK; } - if( asioError != ASE_OK ) - { + if (asioError != ASE_OK) { result = paUnanticipatedHostError; - PA_ASIO_SET_LAST_ASIO_ERROR( asioError ); - PA_DEBUG(("OpenStream ERROR9\n")); + PA_ASIO_SET_LAST_ASIO_ERROR (asioError); + PA_DEBUG ( ("OpenStream ERROR9\n")); goto error; } asioBuffersCreated = 1; - stream->asioChannelInfos = (ASIOChannelInfo*)PaUtil_AllocateMemory( - sizeof(ASIOChannelInfo) * (inputChannelCount + outputChannelCount) ); - if( !stream->asioChannelInfos ) - { + stream->asioChannelInfos = (ASIOChannelInfo*) PaUtil_AllocateMemory ( + sizeof (ASIOChannelInfo) * (inputChannelCount + outputChannelCount)); + + if (!stream->asioChannelInfos) { result = paInsufficientMemory; - PA_DEBUG(("OpenStream ERROR10\n")); + PA_DEBUG ( ("OpenStream ERROR10\n")); goto error; } - for( i=0; i < inputChannelCount + outputChannelCount; ++i ) - { + for (i=0; i < inputChannelCount + outputChannelCount; ++i) { stream->asioChannelInfos[i].channel = stream->asioBufferInfos[i].channelNum; stream->asioChannelInfos[i].isInput = stream->asioBufferInfos[i].isInput; - asioError = ASIOGetChannelInfo( &stream->asioChannelInfos[i] ); - if( asioError != ASE_OK ) - { + asioError = ASIOGetChannelInfo (&stream->asioChannelInfos[i]); + + if (asioError != ASE_OK) { result = paUnanticipatedHostError; - PA_ASIO_SET_LAST_ASIO_ERROR( asioError ); - PA_DEBUG(("OpenStream ERROR11\n")); + PA_ASIO_SET_LAST_ASIO_ERROR (asioError); + PA_DEBUG ( ("OpenStream ERROR11\n")); goto error; } } - stream->bufferPtrs = (void**)PaUtil_AllocateMemory( - 2 * sizeof(void*) * (inputChannelCount + outputChannelCount) ); - if( !stream->bufferPtrs ) - { + stream->bufferPtrs = (void**) PaUtil_AllocateMemory ( + + 2 * sizeof (void*) * (inputChannelCount + outputChannelCount)); + + if (!stream->bufferPtrs) { result = paInsufficientMemory; - PA_DEBUG(("OpenStream ERROR12\n")); + PA_DEBUG ( ("OpenStream ERROR12\n")); goto error; } - if( inputChannelCount > 0 ) - { + if (inputChannelCount > 0) { stream->inputBufferPtrs[0] = stream-> bufferPtrs; stream->inputBufferPtrs[1] = &stream->bufferPtrs[inputChannelCount]; - for( i=0; i<inputChannelCount; ++i ) - { + for (i=0; i<inputChannelCount; ++i) { stream->inputBufferPtrs[0][i] = stream->asioBufferInfos[i].buffers[0]; stream->inputBufferPtrs[1][i] = stream->asioBufferInfos[i].buffers[1]; } - } - else - { + } else { stream->inputBufferPtrs[0] = 0; stream->inputBufferPtrs[1] = 0; } - if( outputChannelCount > 0 ) - { + if (outputChannelCount > 0) { stream->outputBufferPtrs[0] = &stream->bufferPtrs[inputChannelCount*2]; stream->outputBufferPtrs[1] = &stream->bufferPtrs[inputChannelCount*2 + outputChannelCount]; - for( i=0; i<outputChannelCount; ++i ) - { + for (i=0; i<outputChannelCount; ++i) { stream->outputBufferPtrs[0][i] = stream->asioBufferInfos[inputChannelCount+i].buffers[0]; stream->outputBufferPtrs[1][i] = stream->asioBufferInfos[inputChannelCount+i].buffers[1]; } - } - else - { + } else { stream->outputBufferPtrs[0] = 0; stream->outputBufferPtrs[1] = 0; } - if( inputChannelCount > 0 ) - { + if (inputChannelCount > 0) { /* FIXME: assume all channels use the same type for now */ ASIOSampleType inputType = stream->asioChannelInfos[0].type; - PA_DEBUG(("ASIO Input type:%d",inputType)); - AsioSampleTypeLOG(inputType); - hostInputSampleFormat = AsioSampleTypeToPaNativeSampleFormat( inputType ); + PA_DEBUG ( ("ASIO Input type:%d",inputType)); + AsioSampleTypeLOG (inputType); + hostInputSampleFormat = AsioSampleTypeToPaNativeSampleFormat (inputType); - SelectAsioToPaConverter( inputType, &stream->inputBufferConverter, &stream->inputShift ); - } - else - { + SelectAsioToPaConverter (inputType, &stream->inputBufferConverter, &stream->inputShift); + } else { hostInputSampleFormat = 0; stream->inputBufferConverter = 0; } - if( outputChannelCount > 0 ) - { + if (outputChannelCount > 0) { /* FIXME: assume all channels use the same type for now */ ASIOSampleType outputType = stream->asioChannelInfos[inputChannelCount].type; - PA_DEBUG(("ASIO Output type:%d",outputType)); - AsioSampleTypeLOG(outputType); - hostOutputSampleFormat = AsioSampleTypeToPaNativeSampleFormat( outputType ); + PA_DEBUG ( ("ASIO Output type:%d",outputType)); + AsioSampleTypeLOG (outputType); + hostOutputSampleFormat = AsioSampleTypeToPaNativeSampleFormat (outputType); - SelectPaToAsioConverter( outputType, &stream->outputBufferConverter, &stream->outputShift ); - } - else - { + SelectPaToAsioConverter (outputType, &stream->outputBufferConverter, &stream->outputShift); + } else { hostOutputSampleFormat = 0; stream->outputBufferConverter = 0; } - ASIOGetLatencies( &stream->inputLatency, &stream->outputLatency ); + ASIOGetLatencies (&stream->inputLatency, &stream->outputLatency); /* Using blocking i/o interface... */ - if( usingBlockingIo ) - { + + if (usingBlockingIo) { /* Allocate the blocking i/o input ring buffer memory. */ - stream->blockingState = (PaAsioStreamBlockingState*)PaUtil_AllocateMemory( sizeof(PaAsioStreamBlockingState) ); - if( !stream->blockingState ) - { + stream->blockingState = (PaAsioStreamBlockingState*) PaUtil_AllocateMemory (sizeof (PaAsioStreamBlockingState)); + + if (!stream->blockingState) { result = paInsufficientMemory; - PA_DEBUG(("ERROR! Blocking i/o interface struct allocation failed in OpenStream()\n")); + PA_DEBUG ( ("ERROR! Blocking i/o interface struct allocation failed in OpenStream()\n")); goto error; } /* Initialize blocking i/o interface struct. */ stream->blockingState->readFramesReadyEvent = NULL; /* Uninitialized, yet. */ + stream->blockingState->writeBuffersReadyEvent = NULL; /* Uninitialized, yet. */ + stream->blockingState->readRingBufferData = NULL; /* Uninitialized, yet. */ + stream->blockingState->writeRingBufferData = NULL; /* Uninitialized, yet. */ + stream->blockingState->readStreamBuffer = NULL; /* Uninitialized, yet. */ + stream->blockingState->writeStreamBuffer = NULL; /* Uninitialized, yet. */ + stream->blockingState->stopFlag = TRUE; /* Not started, yet. */ /* If the user buffer is unspecified */ - if( framesPerBuffer == paFramesPerBufferUnspecified ) - { + if (framesPerBuffer == paFramesPerBufferUnspecified) { /* Make the user buffer the same size as the host buffer. */ framesPerBuffer = framesPerHostBuffer; } /* Initialize callback buffer processor. */ - result = PaUtil_InitializeBufferProcessor( &stream->bufferProcessor , - inputChannelCount , - inputSampleFormat & ~paNonInterleaved , /* Ring buffer. */ - hostInputSampleFormat , /* Host format. */ - outputChannelCount , - outputSampleFormat & ~paNonInterleaved, /* Ring buffer. */ - hostOutputSampleFormat , /* Host format. */ - sampleRate , - streamFlags , - framesPerBuffer , /* Frames per ring buffer block. */ - framesPerHostBuffer , /* Frames per asio buffer. */ - paUtilFixedHostBufferSize , - streamCallback , - userData ); - if( result != paNoError ){ - PA_DEBUG(("OpenStream ERROR13\n")); + result = PaUtil_InitializeBufferProcessor (&stream->bufferProcessor , + inputChannelCount , + inputSampleFormat & ~paNonInterleaved , /* Ring buffer. */ + hostInputSampleFormat , /* Host format. */ + outputChannelCount , + outputSampleFormat & ~paNonInterleaved, /* Ring buffer. */ + hostOutputSampleFormat , /* Host format. */ + sampleRate , + streamFlags , + framesPerBuffer , /* Frames per ring buffer block. */ + framesPerHostBuffer , /* Frames per asio buffer. */ + paUtilFixedHostBufferSize , + streamCallback , + userData); + + if (result != paNoError) { + PA_DEBUG ( ("OpenStream ERROR13\n")); goto error; } + callbackBufferProcessorInited = TRUE; /* Initialize the blocking i/o buffer processor. */ - result = PaUtil_InitializeBufferProcessor(&stream->blockingState->bufferProcessor, - inputChannelCount , - inputSampleFormat , /* User format. */ - inputSampleFormat & ~paNonInterleaved , /* Ring buffer. */ - outputChannelCount , - outputSampleFormat , /* User format. */ - outputSampleFormat & ~paNonInterleaved, /* Ring buffer. */ - sampleRate , - paClipOff | paDitherOff , /* Don't use dither nor clipping. */ - framesPerBuffer , /* Frames per user buffer. */ - framesPerBuffer , /* Frames per ring buffer block. */ - paUtilBoundedHostBufferSize , - NULL, NULL );/* No callback! */ - if( result != paNoError ){ - PA_DEBUG(("ERROR! Blocking i/o buffer processor initialization failed in OpenStream()\n")); + result = PaUtil_InitializeBufferProcessor (&stream->blockingState->bufferProcessor, + inputChannelCount , + inputSampleFormat , /* User format. */ + inputSampleFormat & ~paNonInterleaved , /* Ring buffer. */ + outputChannelCount , + outputSampleFormat , /* User format. */ + outputSampleFormat & ~paNonInterleaved, /* Ring buffer. */ + sampleRate , + paClipOff | paDitherOff , /* Don't use dither nor clipping. */ + framesPerBuffer , /* Frames per user buffer. */ + framesPerBuffer , /* Frames per ring buffer block. */ + paUtilBoundedHostBufferSize , + NULL, NULL); /* No callback! */ + + if (result != paNoError) { + PA_DEBUG ( ("ERROR! Blocking i/o buffer processor initialization failed in OpenStream()\n")); goto error; } + blockingBufferProcessorInited = TRUE; /* If input is requested. */ - if( inputChannelCount ) - { + + if (inputChannelCount) { /* Create the callback sync-event. */ - stream->blockingState->readFramesReadyEvent = CreateEvent( NULL, FALSE, FALSE, NULL ); - if( stream->blockingState->readFramesReadyEvent == NULL ) - { + stream->blockingState->readFramesReadyEvent = CreateEvent (NULL, FALSE, FALSE, NULL); + + if (stream->blockingState->readFramesReadyEvent == NULL) { result = paUnanticipatedHostError; - PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() ); - PA_DEBUG(("ERROR! Blocking i/o \"read frames ready\" event creation failed in OpenStream()\n")); + PA_ASIO_SET_LAST_SYSTEM_ERROR (GetLastError()); + PA_DEBUG ( ("ERROR! Blocking i/o \"read frames ready\" event creation failed in OpenStream()\n")); goto error; } + blockingReadFramesReadyEventInitialized = 1; /* Create pointer buffer to access non-interleaved data in ReadStream() */ - stream->blockingState->readStreamBuffer = (void**)PaUtil_AllocateMemory( sizeof(void*) * inputChannelCount ); - if( !stream->blockingState->readStreamBuffer ) - { + stream->blockingState->readStreamBuffer = (void**) PaUtil_AllocateMemory (sizeof (void*) * inputChannelCount); + + if (!stream->blockingState->readStreamBuffer) { result = paInsufficientMemory; - PA_DEBUG(("ERROR! Blocking i/o read stream buffer allocation failed in OpenStream()\n")); + PA_DEBUG ( ("ERROR! Blocking i/o read stream buffer allocation failed in OpenStream()\n")); goto error; } @@ -2355,74 +2465,79 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, 5) Get the next larger (or equal) power-of-two buffer size. */ lBlockingBufferSize = suggestedInputLatencyFrames - stream->inputLatency; + lBlockingBufferSize = (lBlockingBufferSize > 0) ? lBlockingBufferSize : 1; + lBlockingBufferSize = (lBlockingBufferSize + framesPerBuffer - 1) / framesPerBuffer; + lBlockingBufferSize = (lBlockingBufferSize + 1) * framesPerBuffer; /* Get the next larger or equal power-of-two buffersize. */ lBlockingBufferSizePow2 = 1; - while( lBlockingBufferSize > (lBlockingBufferSizePow2<<=1) ); + + while (lBlockingBufferSize > (lBlockingBufferSizePow2<<=1)); + lBlockingBufferSize = lBlockingBufferSizePow2; /* Compute total intput latency in seconds */ stream->streamRepresentation.streamInfo.inputLatency = - (double)( PaUtil_GetBufferProcessorInputLatency(&stream->bufferProcessor ) - + PaUtil_GetBufferProcessorInputLatency(&stream->blockingState->bufferProcessor) - + (lBlockingBufferSize / framesPerBuffer - 1) * framesPerBuffer - + stream->inputLatency ) + (double) (PaUtil_GetBufferProcessorInputLatency (&stream->bufferProcessor) + + PaUtil_GetBufferProcessorInputLatency (&stream->blockingState->bufferProcessor) + + (lBlockingBufferSize / framesPerBuffer - 1) * framesPerBuffer + + stream->inputLatency) / sampleRate; /* The code below prints the ASIO latency which doesn't include the buffer processor latency nor the blocking i/o latency. It reports the added latency separately. */ - PA_DEBUG(("PaAsio : ASIO InputLatency = %ld (%ld ms),\n added buffProc:%ld (%ld ms),\n added blocking:%ld (%ld ms)\n", - stream->inputLatency, - (long)( stream->inputLatency * (1000.0 / sampleRate) ), - PaUtil_GetBufferProcessorInputLatency(&stream->bufferProcessor), - (long)( PaUtil_GetBufferProcessorInputLatency(&stream->bufferProcessor) * (1000.0 / sampleRate) ), - PaUtil_GetBufferProcessorInputLatency(&stream->blockingState->bufferProcessor) + (lBlockingBufferSize / framesPerBuffer - 1) * framesPerBuffer, - (long)( (PaUtil_GetBufferProcessorInputLatency(&stream->blockingState->bufferProcessor) + (lBlockingBufferSize / framesPerBuffer - 1) * framesPerBuffer) * (1000.0 / sampleRate) ) - )); + PA_DEBUG ( ("PaAsio : ASIO InputLatency = %ld (%ld ms),\n added buffProc:%ld (%ld ms),\n added blocking:%ld (%ld ms)\n", + stream->inputLatency, + (long) (stream->inputLatency * (1000.0 / sampleRate)), + PaUtil_GetBufferProcessorInputLatency (&stream->bufferProcessor), + (long) (PaUtil_GetBufferProcessorInputLatency (&stream->bufferProcessor) * (1000.0 / sampleRate)), + PaUtil_GetBufferProcessorInputLatency (&stream->blockingState->bufferProcessor) + (lBlockingBufferSize / framesPerBuffer - 1) * framesPerBuffer, + (long) ( (PaUtil_GetBufferProcessorInputLatency (&stream->blockingState->bufferProcessor) + (lBlockingBufferSize / framesPerBuffer - 1) * framesPerBuffer) * (1000.0 / sampleRate)) + )); /* Determine the size of ring buffer in bytes. */ - lBytesPerFrame = inputChannelCount * Pa_GetSampleSize(inputSampleFormat ); + lBytesPerFrame = inputChannelCount * Pa_GetSampleSize (inputSampleFormat); /* Allocate the blocking i/o input ring buffer memory. */ - stream->blockingState->readRingBufferData = (void*)PaUtil_AllocateMemory( lBlockingBufferSize * lBytesPerFrame ); - if( !stream->blockingState->readRingBufferData ) - { + stream->blockingState->readRingBufferData = (void*) PaUtil_AllocateMemory (lBlockingBufferSize * lBytesPerFrame); + + if (!stream->blockingState->readRingBufferData) { result = paInsufficientMemory; - PA_DEBUG(("ERROR! Blocking i/o input ring buffer allocation failed in OpenStream()\n")); + PA_DEBUG ( ("ERROR! Blocking i/o input ring buffer allocation failed in OpenStream()\n")); goto error; } /* Initialize the input ring buffer struct. */ - PaUtil_InitializeRingBuffer( &stream->blockingState->readRingBuffer , - lBytesPerFrame , - lBlockingBufferSize , - stream->blockingState->readRingBufferData ); + PaUtil_InitializeRingBuffer (&stream->blockingState->readRingBuffer , + lBytesPerFrame , + lBlockingBufferSize , + stream->blockingState->readRingBufferData); } /* If output is requested. */ - if( outputChannelCount ) - { - stream->blockingState->writeBuffersReadyEvent = CreateEvent( NULL, FALSE, FALSE, NULL ); - if( stream->blockingState->writeBuffersReadyEvent == NULL ) - { + if (outputChannelCount) { + stream->blockingState->writeBuffersReadyEvent = CreateEvent (NULL, FALSE, FALSE, NULL); + + if (stream->blockingState->writeBuffersReadyEvent == NULL) { result = paUnanticipatedHostError; - PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() ); - PA_DEBUG(("ERROR! Blocking i/o \"write buffers ready\" event creation failed in OpenStream()\n")); + PA_ASIO_SET_LAST_SYSTEM_ERROR (GetLastError()); + PA_DEBUG ( ("ERROR! Blocking i/o \"write buffers ready\" event creation failed in OpenStream()\n")); goto error; } + blockingWriteBuffersReadyEventInitialized = 1; /* Create pointer buffer to access non-interleaved data in WriteStream() */ - stream->blockingState->writeStreamBuffer = (const void**)PaUtil_AllocateMemory( sizeof(const void*) * outputChannelCount ); - if( !stream->blockingState->writeStreamBuffer ) - { + stream->blockingState->writeStreamBuffer = (const void**) PaUtil_AllocateMemory (sizeof (const void*) * outputChannelCount); + + if (!stream->blockingState->writeStreamBuffer) { result = paInsufficientMemory; - PA_DEBUG(("ERROR! Blocking i/o write stream buffer allocation failed in OpenStream()\n")); + PA_DEBUG ( ("ERROR! Blocking i/o write stream buffer allocation failed in OpenStream()\n")); goto error; } @@ -2441,8 +2556,11 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, 5) Get the next larger (or equal) power-of-two buffer size. */ lBlockingBufferSize = suggestedOutputLatencyFrames - stream->outputLatency; + lBlockingBufferSize = (lBlockingBufferSize > 0) ? lBlockingBufferSize : 1; + lBlockingBufferSize = (lBlockingBufferSize + framesPerBuffer - 1) / framesPerBuffer; + lBlockingBufferSize = (lBlockingBufferSize + 1) * framesPerBuffer; /* The buffer size (without the additional block) corresponds @@ -2452,93 +2570,96 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, /* Get the next larger or equal power-of-two buffersize. */ lBlockingBufferSizePow2 = 1; - while( lBlockingBufferSize > (lBlockingBufferSizePow2<<=1) ); + + while (lBlockingBufferSize > (lBlockingBufferSizePow2<<=1)); + lBlockingBufferSize = lBlockingBufferSizePow2; /* Compute total output latency in seconds */ stream->streamRepresentation.streamInfo.outputLatency = - (double)( PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor ) - + PaUtil_GetBufferProcessorOutputLatency(&stream->blockingState->bufferProcessor) - + (lBlockingBufferSize / framesPerBuffer - 1) * framesPerBuffer - + stream->outputLatency ) + (double) (PaUtil_GetBufferProcessorOutputLatency (&stream->bufferProcessor) + + PaUtil_GetBufferProcessorOutputLatency (&stream->blockingState->bufferProcessor) + + (lBlockingBufferSize / framesPerBuffer - 1) * framesPerBuffer + + stream->outputLatency) / sampleRate; /* The code below prints the ASIO latency which doesn't include the buffer processor latency nor the blocking i/o latency. It reports the added latency separately. */ - PA_DEBUG(("PaAsio : ASIO OutputLatency = %ld (%ld ms),\n added buffProc:%ld (%ld ms),\n added blocking:%ld (%ld ms)\n", - stream->outputLatency, - (long)( stream->inputLatency * (1000.0 / sampleRate) ), - PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor), - (long)( PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor) * (1000.0 / sampleRate) ), - PaUtil_GetBufferProcessorOutputLatency(&stream->blockingState->bufferProcessor) + (lBlockingBufferSize / framesPerBuffer - 1) * framesPerBuffer, - (long)( (PaUtil_GetBufferProcessorOutputLatency(&stream->blockingState->bufferProcessor) + (lBlockingBufferSize / framesPerBuffer - 1) * framesPerBuffer) * (1000.0 / sampleRate) ) - )); + PA_DEBUG ( ("PaAsio : ASIO OutputLatency = %ld (%ld ms),\n added buffProc:%ld (%ld ms),\n added blocking:%ld (%ld ms)\n", + stream->outputLatency, + (long) (stream->inputLatency * (1000.0 / sampleRate)), + PaUtil_GetBufferProcessorOutputLatency (&stream->bufferProcessor), + (long) (PaUtil_GetBufferProcessorOutputLatency (&stream->bufferProcessor) * (1000.0 / sampleRate)), + PaUtil_GetBufferProcessorOutputLatency (&stream->blockingState->bufferProcessor) + (lBlockingBufferSize / framesPerBuffer - 1) * framesPerBuffer, + (long) ( (PaUtil_GetBufferProcessorOutputLatency (&stream->blockingState->bufferProcessor) + (lBlockingBufferSize / framesPerBuffer - 1) * framesPerBuffer) * (1000.0 / sampleRate)) + )); /* Determine the size of ring buffer in bytes. */ - lBytesPerFrame = outputChannelCount * Pa_GetSampleSize(outputSampleFormat); + lBytesPerFrame = outputChannelCount * Pa_GetSampleSize (outputSampleFormat); /* Allocate the blocking i/o output ring buffer memory. */ - stream->blockingState->writeRingBufferData = (void*)PaUtil_AllocateMemory( lBlockingBufferSize * lBytesPerFrame ); - if( !stream->blockingState->writeRingBufferData ) - { + stream->blockingState->writeRingBufferData = (void*) PaUtil_AllocateMemory (lBlockingBufferSize * lBytesPerFrame); + + if (!stream->blockingState->writeRingBufferData) { result = paInsufficientMemory; - PA_DEBUG(("ERROR! Blocking i/o output ring buffer allocation failed in OpenStream()\n")); + PA_DEBUG ( ("ERROR! Blocking i/o output ring buffer allocation failed in OpenStream()\n")); goto error; } /* Initialize the output ring buffer struct. */ - PaUtil_InitializeRingBuffer( &stream->blockingState->writeRingBuffer , - lBytesPerFrame , - lBlockingBufferSize , - stream->blockingState->writeRingBufferData ); + PaUtil_InitializeRingBuffer (&stream->blockingState->writeRingBuffer , + lBytesPerFrame , + lBlockingBufferSize , + stream->blockingState->writeRingBufferData); } stream->streamRepresentation.streamInfo.sampleRate = sampleRate; - } - else /* Using callback interface... */ - { - result = PaUtil_InitializeBufferProcessor( &stream->bufferProcessor, - inputChannelCount, inputSampleFormat, hostInputSampleFormat, - outputChannelCount, outputSampleFormat, hostOutputSampleFormat, - sampleRate, streamFlags, framesPerBuffer, - framesPerHostBuffer, paUtilFixedHostBufferSize, - streamCallback, userData ); - if( result != paNoError ){ - PA_DEBUG(("OpenStream ERROR13\n")); + } else { /* Using callback interface... */ + result = PaUtil_InitializeBufferProcessor (&stream->bufferProcessor, + inputChannelCount, inputSampleFormat, hostInputSampleFormat, + outputChannelCount, outputSampleFormat, hostOutputSampleFormat, + sampleRate, streamFlags, framesPerBuffer, + framesPerHostBuffer, paUtilFixedHostBufferSize, + streamCallback, userData); + + if (result != paNoError) { + PA_DEBUG ( ("OpenStream ERROR13\n")); goto error; } + callbackBufferProcessorInited = TRUE; stream->streamRepresentation.streamInfo.inputLatency = - (double)( PaUtil_GetBufferProcessorInputLatency(&stream->bufferProcessor) - + stream->inputLatency) / sampleRate; // seconds + (double) (PaUtil_GetBufferProcessorInputLatency (&stream->bufferProcessor) + + stream->inputLatency) / sampleRate; // seconds stream->streamRepresentation.streamInfo.outputLatency = - (double)( PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor) - + stream->outputLatency) / sampleRate; // seconds + (double) (PaUtil_GetBufferProcessorOutputLatency (&stream->bufferProcessor) + + stream->outputLatency) / sampleRate; // seconds stream->streamRepresentation.streamInfo.sampleRate = sampleRate; // the code below prints the ASIO latency which doesn't include the // buffer processor latency. it reports the added latency separately - PA_DEBUG(("PaAsio : ASIO InputLatency = %ld (%ld ms), added buffProc:%ld (%ld ms)\n", - stream->inputLatency, - (long)((stream->inputLatency*1000)/ sampleRate), - PaUtil_GetBufferProcessorInputLatency(&stream->bufferProcessor), - (long)((PaUtil_GetBufferProcessorInputLatency(&stream->bufferProcessor)*1000)/ sampleRate) - )); - - PA_DEBUG(("PaAsio : ASIO OuputLatency = %ld (%ld ms), added buffProc:%ld (%ld ms)\n", - stream->outputLatency, - (long)((stream->outputLatency*1000)/ sampleRate), - PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor), - (long)((PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor)*1000)/ sampleRate) - )); + PA_DEBUG ( ("PaAsio : ASIO InputLatency = %ld (%ld ms), added buffProc:%ld (%ld ms)\n", + stream->inputLatency, + (long) ( (stream->inputLatency*1000) / sampleRate), + PaUtil_GetBufferProcessorInputLatency (&stream->bufferProcessor), + (long) ( (PaUtil_GetBufferProcessorInputLatency (&stream->bufferProcessor) *1000) / sampleRate) + )); + + PA_DEBUG ( ("PaAsio : ASIO OuputLatency = %ld (%ld ms), added buffProc:%ld (%ld ms)\n", + stream->outputLatency, + (long) ( (stream->outputLatency*1000) / sampleRate), + PaUtil_GetBufferProcessorOutputLatency (&stream->bufferProcessor), + (long) ( (PaUtil_GetBufferProcessorOutputLatency (&stream->bufferProcessor) *1000) / sampleRate) + )); } stream->asioHostApi = asioHostApi; + stream->framesPerHostCallback = framesPerHostBuffer; stream->inputChannelCount = inputChannelCount; @@ -2548,61 +2669,64 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, asioHostApi->openAsioDeviceIndex = asioDeviceIndex; - *s = (PaStream*)stream; + *s = (PaStream*) stream; return result; error: - PA_DEBUG(("goto errored\n")); - if( stream ) - { - if( stream->blockingState ) - { - if( blockingBufferProcessorInited ) - PaUtil_TerminateBufferProcessor( &stream->blockingState->bufferProcessor ); - - if( stream->blockingState->writeRingBufferData ) - PaUtil_FreeMemory( stream->blockingState->writeRingBufferData ); - if( stream->blockingState->writeStreamBuffer ) - PaUtil_FreeMemory( stream->blockingState->writeStreamBuffer ); - if( blockingWriteBuffersReadyEventInitialized ) - CloseHandle( stream->blockingState->writeBuffersReadyEvent ); - - if( stream->blockingState->readRingBufferData ) - PaUtil_FreeMemory( stream->blockingState->readRingBufferData ); - if( stream->blockingState->readStreamBuffer ) - PaUtil_FreeMemory( stream->blockingState->readStreamBuffer ); - if( blockingReadFramesReadyEventInitialized ) - CloseHandle( stream->blockingState->readFramesReadyEvent ); - - PaUtil_FreeMemory( stream->blockingState ); + PA_DEBUG ( ("goto errored\n")); + + if (stream) { + if (stream->blockingState) { + if (blockingBufferProcessorInited) + PaUtil_TerminateBufferProcessor (&stream->blockingState->bufferProcessor); + + if (stream->blockingState->writeRingBufferData) + PaUtil_FreeMemory (stream->blockingState->writeRingBufferData); + + if (stream->blockingState->writeStreamBuffer) + PaUtil_FreeMemory (stream->blockingState->writeStreamBuffer); + + if (blockingWriteBuffersReadyEventInitialized) + CloseHandle (stream->blockingState->writeBuffersReadyEvent); + + if (stream->blockingState->readRingBufferData) + PaUtil_FreeMemory (stream->blockingState->readRingBufferData); + + if (stream->blockingState->readStreamBuffer) + PaUtil_FreeMemory (stream->blockingState->readStreamBuffer); + + if (blockingReadFramesReadyEventInitialized) + CloseHandle (stream->blockingState->readFramesReadyEvent); + + PaUtil_FreeMemory (stream->blockingState); } - if( callbackBufferProcessorInited ) - PaUtil_TerminateBufferProcessor( &stream->bufferProcessor ); + if (callbackBufferProcessorInited) + PaUtil_TerminateBufferProcessor (&stream->bufferProcessor); - if( completedBuffersPlayedEventInited ) - CloseHandle( stream->completedBuffersPlayedEvent ); + if (completedBuffersPlayedEventInited) + CloseHandle (stream->completedBuffersPlayedEvent); - if( stream->asioBufferInfos ) - PaUtil_FreeMemory( stream->asioBufferInfos ); + if (stream->asioBufferInfos) + PaUtil_FreeMemory (stream->asioBufferInfos); - if( stream->asioChannelInfos ) - PaUtil_FreeMemory( stream->asioChannelInfos ); + if (stream->asioChannelInfos) + PaUtil_FreeMemory (stream->asioChannelInfos); - if( stream->bufferPtrs ) - PaUtil_FreeMemory( stream->bufferPtrs ); + if (stream->bufferPtrs) + PaUtil_FreeMemory (stream->bufferPtrs); - PaUtil_FreeMemory( stream ); + PaUtil_FreeMemory (stream); } - if( asioBuffersCreated ) + if (asioBuffersCreated) ASIODisposeBuffers(); - if( asioIsInitialized ) - { - UnloadAsioDriver(); - } + if (asioIsInitialized) { + UnloadAsioDriver(); + } + return result; } @@ -2611,46 +2735,48 @@ error: When CloseStream() is called, the multi-api layer ensures that the stream has already been stopped or aborted. */ -static PaError CloseStream( PaStream* s ) +static PaError CloseStream (PaStream* s) { PaError result = paNoError; - PaAsioStream *stream = (PaAsioStream*)s; + PaAsioStream *stream = (PaAsioStream*) s; /* IMPLEMENT ME: - additional stream closing + cleanup */ - PaUtil_TerminateBufferProcessor( &stream->bufferProcessor ); - PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation ); + PaUtil_TerminateBufferProcessor (&stream->bufferProcessor); + PaUtil_TerminateStreamRepresentation (&stream->streamRepresentation); stream->asioHostApi->openAsioDeviceIndex = paNoDevice; - CloseHandle( stream->completedBuffersPlayedEvent ); + CloseHandle (stream->completedBuffersPlayedEvent); /* Using blocking i/o interface... */ - if( stream->blockingState ) - { - PaUtil_TerminateBufferProcessor( &stream->blockingState->bufferProcessor ); - if( stream->inputChannelCount ) { - PaUtil_FreeMemory( stream->blockingState->readRingBufferData ); - PaUtil_FreeMemory( stream->blockingState->readStreamBuffer ); - CloseHandle( stream->blockingState->readFramesReadyEvent ); + if (stream->blockingState) { + PaUtil_TerminateBufferProcessor (&stream->blockingState->bufferProcessor); + + if (stream->inputChannelCount) { + PaUtil_FreeMemory (stream->blockingState->readRingBufferData); + PaUtil_FreeMemory (stream->blockingState->readStreamBuffer); + CloseHandle (stream->blockingState->readFramesReadyEvent); } - if( stream->outputChannelCount ) { - PaUtil_FreeMemory( stream->blockingState->writeRingBufferData ); - PaUtil_FreeMemory( stream->blockingState->writeStreamBuffer ); - CloseHandle( stream->blockingState->writeBuffersReadyEvent ); + + if (stream->outputChannelCount) { + PaUtil_FreeMemory (stream->blockingState->writeRingBufferData); + PaUtil_FreeMemory (stream->blockingState->writeStreamBuffer); + CloseHandle (stream->blockingState->writeBuffersReadyEvent); } - PaUtil_FreeMemory( stream->blockingState ); + PaUtil_FreeMemory (stream->blockingState); } - PaUtil_FreeMemory( stream->asioBufferInfos ); - PaUtil_FreeMemory( stream->asioChannelInfos ); - PaUtil_FreeMemory( stream->bufferPtrs ); - PaUtil_FreeMemory( stream ); + PaUtil_FreeMemory (stream->asioBufferInfos); + + PaUtil_FreeMemory (stream->asioChannelInfos); + PaUtil_FreeMemory (stream->bufferPtrs); + PaUtil_FreeMemory (stream); ASIODisposeBuffers(); UnloadAsioDriver(); @@ -2659,7 +2785,7 @@ static PaError CloseStream( PaStream* s ) } -static void bufferSwitch(long index, ASIOBool directProcess) +static void bufferSwitch (long index, ASIOBool directProcess) { //TAKEN FROM THE ASIO SDK @@ -2673,27 +2799,28 @@ static void bufferSwitch(long index, ASIOBool directProcess) // timeInfo.systemTime fields and the according flags ASIOTime timeInfo; - memset( &timeInfo, 0, sizeof (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; + + if (ASIOGetSamplePosition (&timeInfo.timeInfo.samplePosition, &timeInfo.timeInfo.systemTime) == ASE_OK) + timeInfo.timeInfo.flags = kSystemTimeValid | kSamplePositionValid; // Call the real callback - bufferSwitchTimeInfo( &timeInfo, index, directProcess ); + bufferSwitchTimeInfo (&timeInfo, index, directProcess); } // conversion from 64 bit ASIOSample/ASIOTimeStamp to double float #if NATIVE_INT64 - #define ASIO64toDouble(a) (a) +#define ASIO64toDouble(a) (a) #else - const double twoRaisedTo32 = 4294967296.; - #define ASIO64toDouble(a) ((a).lo + (a).hi * twoRaisedTo32) +const double twoRaisedTo32 = 4294967296.; +#define ASIO64toDouble(a) ((a).lo + (a).hi * twoRaisedTo32) #endif -static ASIOTime *bufferSwitchTimeInfo( ASIOTime *timeInfo, long index, ASIOBool directProcess ) +static ASIOTime *bufferSwitchTimeInfo (ASIOTime *timeInfo, long index, ASIOBool directProcess) { // the actual processing callback. // Beware that this is normally in a seperate thread, hence be sure that @@ -2722,22 +2849,23 @@ static ASIOTime *bufferSwitchTimeInfo( ASIOTime *timeInfo, long index, ASIOBool // synchronization to other media is required if (timeInfo->timeInfo.flags & kSystemTimeValid) - asioDriverInfo.nanoSeconds = ASIO64toDouble(timeInfo->timeInfo.systemTime); + asioDriverInfo.nanoSeconds = ASIO64toDouble (timeInfo->timeInfo.systemTime); else - asioDriverInfo.nanoSeconds = 0; + asioDriverInfo.nanoSeconds = 0; if (timeInfo->timeInfo.flags & kSamplePositionValid) - asioDriverInfo.samples = ASIO64toDouble(timeInfo->timeInfo.samplePosition); + asioDriverInfo.samples = ASIO64toDouble (timeInfo->timeInfo.samplePosition); else - asioDriverInfo.samples = 0; + asioDriverInfo.samples = 0; if (timeInfo->timeCode.flags & kTcValid) - asioDriverInfo.tcSamples = ASIO64toDouble(timeInfo->timeCode.timeCodeSamples); + asioDriverInfo.tcSamples = ASIO64toDouble (timeInfo->timeCode.timeCodeSamples); else - asioDriverInfo.tcSamples = 0; + asioDriverInfo.tcSamples = 0; // get the system reference time asioDriverInfo.sysRefTime = get_sys_reference_time(); + #endif #if 0 @@ -2745,14 +2873,19 @@ static ASIOTime *bufferSwitchTimeInfo( ASIOTime *timeInfo, long index, ASIOBool // 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)); + + 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 - if( !theAsioStream ) + if (!theAsioStream) return 0L; // Keep sample position @@ -2760,57 +2893,51 @@ static ASIOTime *bufferSwitchTimeInfo( ASIOTime *timeInfo, long index, ASIOBool // protect against reentrancy - if( PaAsio_AtomicIncrement(&theAsioStream->reenterCount) ) - { + if (PaAsio_AtomicIncrement (&theAsioStream->reenterCount)) { theAsioStream->reenterError++; //DBUG(("bufferSwitchTimeInfo : reentrancy detection = %d\n", asioDriverInfo.reenterError)); return 0L; } int buffersDone = 0; - - do - { - if( buffersDone > 0 ) - { + + do { + if (buffersDone > 0) { // this is a reentered buffer, we missed processing it on time // set the input overflow and output underflow flags as appropriate - - if( theAsioStream->inputChannelCount > 0 ) + + if (theAsioStream->inputChannelCount > 0) theAsioStream->callbackFlags |= paInputOverflow; - - if( theAsioStream->outputChannelCount > 0 ) + + if (theAsioStream->outputChannelCount > 0) theAsioStream->callbackFlags |= paOutputUnderflow; - } - else - { - if( theAsioStream->zeroOutput ) - { - ZeroOutputBuffers( theAsioStream, index ); + } else { + if (theAsioStream->zeroOutput) { + ZeroOutputBuffers (theAsioStream, index); // Finally if the driver supports the ASIOOutputReady() optimization, // do it here, all data are in place - if( theAsioStream->postOutput ) + + if (theAsioStream->postOutput) ASIOOutputReady(); - if( theAsioStream->stopProcessing ) - { - if( theAsioStream->stopPlayoutCount < 2 ) - { + if (theAsioStream->stopProcessing) { + if (theAsioStream->stopPlayoutCount < 2) { ++theAsioStream->stopPlayoutCount; - if( theAsioStream->stopPlayoutCount == 2 ) - { + + if (theAsioStream->stopPlayoutCount == 2) { theAsioStream->isActive = 0; - if( theAsioStream->streamRepresentation.streamFinishedCallback != 0 ) - theAsioStream->streamRepresentation.streamFinishedCallback( theAsioStream->streamRepresentation.userData ); + + if (theAsioStream->streamRepresentation.streamFinishedCallback != 0) + theAsioStream->streamRepresentation.streamFinishedCallback (theAsioStream->streamRepresentation.userData); + theAsioStream->streamFinishedCallbackCalled = true; - SetEvent( theAsioStream->completedBuffersPlayedEvent ); + + SetEvent (theAsioStream->completedBuffersPlayedEvent); } } } - } - else - { + } else { #if 0 // test code to try to detect slip conditions... these may work on some systems @@ -2818,165 +2945,168 @@ static ASIOTime *bufferSwitchTimeInfo( ASIOTime *timeInfo, long index, ASIOBool // check that sample delta matches buffer size (otherwise we must have skipped // a buffer. -static double last_samples = -512; -double samples; + static double last_samples = -512; + double samples; //if( timeInfo->timeCode.flags & kTcValid ) // samples = ASIO64toDouble(timeInfo->timeCode.timeCodeSamples); //else - samples = ASIO64toDouble(timeInfo->timeInfo.samplePosition); -int delta = samples - last_samples; + samples = ASIO64toDouble (timeInfo->timeInfo.samplePosition); + int delta = samples - last_samples; //printf( "%d\n", delta); -last_samples = samples; + last_samples = samples; -if( delta > theAsioStream->framesPerHostCallback ) -{ - if( theAsioStream->inputChannelCount > 0 ) - theAsioStream->callbackFlags |= paInputOverflow; + if (delta > theAsioStream->framesPerHostCallback) { + if (theAsioStream->inputChannelCount > 0) + theAsioStream->callbackFlags |= paInputOverflow; - if( theAsioStream->outputChannelCount > 0 ) - theAsioStream->callbackFlags |= paOutputUnderflow; -} + if (theAsioStream->outputChannelCount > 0) + theAsioStream->callbackFlags |= paOutputUnderflow; + } // check that the buffer index is not the previous index (which would indicate // that a buffer was skipped. -static int previousIndex = 1; -if( index == previousIndex ) -{ - if( theAsioStream->inputChannelCount > 0 ) - theAsioStream->callbackFlags |= paInputOverflow; + static int previousIndex = 1; + + if (index == previousIndex) { + if (theAsioStream->inputChannelCount > 0) + theAsioStream->callbackFlags |= paInputOverflow; + + if (theAsioStream->outputChannelCount > 0) + theAsioStream->callbackFlags |= paOutputUnderflow; + } + + previousIndex = index; - if( theAsioStream->outputChannelCount > 0 ) - theAsioStream->callbackFlags |= paOutputUnderflow; -} -previousIndex = index; #endif int i; - PaUtil_BeginCpuLoadMeasurement( &theAsioStream->cpuLoadMeasurer ); + PaUtil_BeginCpuLoadMeasurement (&theAsioStream->cpuLoadMeasurer); PaStreamCallbackTimeInfo paTimeInfo; // asio systemTime is supposed to be measured according to the same // clock as timeGetTime - paTimeInfo.currentTime = (ASIO64toDouble( timeInfo->timeInfo.systemTime ) * .000000001); + paTimeInfo.currentTime = (ASIO64toDouble (timeInfo->timeInfo.systemTime) * .000000001); /* patch from Paul Boege */ paTimeInfo.inputBufferAdcTime = paTimeInfo.currentTime - - ((double)theAsioStream->inputLatency/theAsioStream->streamRepresentation.streamInfo.sampleRate); + ( (double) theAsioStream->inputLatency/theAsioStream->streamRepresentation.streamInfo.sampleRate); paTimeInfo.outputBufferDacTime = paTimeInfo.currentTime + - ((double)theAsioStream->outputLatency/theAsioStream->streamRepresentation.streamInfo.sampleRate); + ( (double) theAsioStream->outputLatency/theAsioStream->streamRepresentation.streamInfo.sampleRate); /* old version is buggy because the buffer processor also adds in its latency to the time parameters paTimeInfo.inputBufferAdcTime = paTimeInfo.currentTime - theAsioStream->streamRepresentation.streamInfo.inputLatency; paTimeInfo.outputBufferDacTime = paTimeInfo.currentTime + theAsioStream->streamRepresentation.streamInfo.outputLatency; */ -/* Disabled! Stopping and re-starting the stream causes an input overflow / output undeflow. S.Fischer */ + /* Disabled! Stopping and re-starting the stream causes an input overflow / output undeflow. S.Fischer */ #if 0 // detect underflows by checking inter-callback time > 2 buffer period -static double previousTime = -1; -if( previousTime > 0 ){ + static double previousTime = -1; - double delta = paTimeInfo.currentTime - previousTime; + if (previousTime > 0) { - if( delta >= 2. * (theAsioStream->framesPerHostCallback / theAsioStream->streamRepresentation.streamInfo.sampleRate) ){ - if( theAsioStream->inputChannelCount > 0 ) - theAsioStream->callbackFlags |= paInputOverflow; + double delta = paTimeInfo.currentTime - previousTime; + + if (delta >= 2. * (theAsioStream->framesPerHostCallback / theAsioStream->streamRepresentation.streamInfo.sampleRate)) { + if (theAsioStream->inputChannelCount > 0) + theAsioStream->callbackFlags |= paInputOverflow; + + if (theAsioStream->outputChannelCount > 0) + theAsioStream->callbackFlags |= paOutputUnderflow; + } + } + + previousTime = paTimeInfo.currentTime; - if( theAsioStream->outputChannelCount > 0 ) - theAsioStream->callbackFlags |= paOutputUnderflow; - } -} -previousTime = paTimeInfo.currentTime; #endif // note that the above input and output times do not need to be // adjusted for the latency of the buffer processor -- the buffer // processor handles that. - if( theAsioStream->inputBufferConverter ) - { - for( i=0; i<theAsioStream->inputChannelCount; i++ ) - { - theAsioStream->inputBufferConverter( theAsioStream->inputBufferPtrs[index][i], - theAsioStream->inputShift, theAsioStream->framesPerHostCallback ); + if (theAsioStream->inputBufferConverter) { + for (i=0; i<theAsioStream->inputChannelCount; i++) { + theAsioStream->inputBufferConverter (theAsioStream->inputBufferPtrs[index][i], + theAsioStream->inputShift, theAsioStream->framesPerHostCallback); } } - PaUtil_BeginBufferProcessing( &theAsioStream->bufferProcessor, &paTimeInfo, theAsioStream->callbackFlags ); + PaUtil_BeginBufferProcessing (&theAsioStream->bufferProcessor, &paTimeInfo, theAsioStream->callbackFlags); /* reset status flags once they've been passed to the callback */ theAsioStream->callbackFlags = 0; - PaUtil_SetInputFrameCount( &theAsioStream->bufferProcessor, 0 /* default to host buffer size */ ); - for( i=0; i<theAsioStream->inputChannelCount; ++i ) - PaUtil_SetNonInterleavedInputChannel( &theAsioStream->bufferProcessor, i, theAsioStream->inputBufferPtrs[index][i] ); + PaUtil_SetInputFrameCount (&theAsioStream->bufferProcessor, 0 /* default to host buffer size */); + + for (i=0; i<theAsioStream->inputChannelCount; ++i) + PaUtil_SetNonInterleavedInputChannel (&theAsioStream->bufferProcessor, i, theAsioStream->inputBufferPtrs[index][i]); - PaUtil_SetOutputFrameCount( &theAsioStream->bufferProcessor, 0 /* default to host buffer size */ ); - for( i=0; i<theAsioStream->outputChannelCount; ++i ) - PaUtil_SetNonInterleavedOutputChannel( &theAsioStream->bufferProcessor, i, theAsioStream->outputBufferPtrs[index][i] ); + PaUtil_SetOutputFrameCount (&theAsioStream->bufferProcessor, 0 /* default to host buffer size */); + + for (i=0; i<theAsioStream->outputChannelCount; ++i) + PaUtil_SetNonInterleavedOutputChannel (&theAsioStream->bufferProcessor, i, theAsioStream->outputBufferPtrs[index][i]); int callbackResult; - if( theAsioStream->stopProcessing ) + + if (theAsioStream->stopProcessing) callbackResult = paComplete; else callbackResult = paContinue; - unsigned long framesProcessed = PaUtil_EndBufferProcessing( &theAsioStream->bufferProcessor, &callbackResult ); - - if( theAsioStream->outputBufferConverter ) - { - for( i=0; i<theAsioStream->outputChannelCount; i++ ) - { - theAsioStream->outputBufferConverter( theAsioStream->outputBufferPtrs[index][i], - theAsioStream->outputShift, theAsioStream->framesPerHostCallback ); + + unsigned long framesProcessed = PaUtil_EndBufferProcessing (&theAsioStream->bufferProcessor, &callbackResult); + + if (theAsioStream->outputBufferConverter) { + for (i=0; i<theAsioStream->outputChannelCount; i++) { + theAsioStream->outputBufferConverter (theAsioStream->outputBufferPtrs[index][i], + theAsioStream->outputShift, theAsioStream->framesPerHostCallback); } } - PaUtil_EndCpuLoadMeasurement( &theAsioStream->cpuLoadMeasurer, framesProcessed ); + PaUtil_EndCpuLoadMeasurement (&theAsioStream->cpuLoadMeasurer, framesProcessed); // Finally if the driver supports the ASIOOutputReady() optimization, // do it here, all data are in place - if( theAsioStream->postOutput ) + + if (theAsioStream->postOutput) ASIOOutputReady(); - if( callbackResult == paContinue ) - { + if (callbackResult == paContinue) { /* nothing special to do */ - } - else if( callbackResult == paAbort ) - { + } else if (callbackResult == paAbort) { /* finish playback immediately */ theAsioStream->isActive = 0; - if( theAsioStream->streamRepresentation.streamFinishedCallback != 0 ) - theAsioStream->streamRepresentation.streamFinishedCallback( theAsioStream->streamRepresentation.userData ); + + if (theAsioStream->streamRepresentation.streamFinishedCallback != 0) + theAsioStream->streamRepresentation.streamFinishedCallback (theAsioStream->streamRepresentation.userData); + theAsioStream->streamFinishedCallbackCalled = true; - SetEvent( theAsioStream->completedBuffersPlayedEvent ); + + SetEvent (theAsioStream->completedBuffersPlayedEvent); + theAsioStream->zeroOutput = true; - } - else /* paComplete or other non-zero value indicating complete */ - { + } else { /* paComplete or other non-zero value indicating complete */ /* Finish playback once currently queued audio has completed. */ theAsioStream->stopProcessing = true; - if( PaUtil_IsBufferProcessorOutputEmpty( &theAsioStream->bufferProcessor ) ) - { + if (PaUtil_IsBufferProcessorOutputEmpty (&theAsioStream->bufferProcessor)) { theAsioStream->zeroOutput = true; theAsioStream->stopPlayoutCount = 0; } } } } - + ++buffersDone; - }while( PaAsio_AtomicDecrement(&theAsioStream->reenterCount) >= 0 ); + } while (PaAsio_AtomicDecrement (&theAsioStream->reenterCount) >= 0); return 0L; } -static void sampleRateChanged(ASIOSampleRate sRate) +static void sampleRateChanged (ASIOSampleRate sRate) { // TAKEN FROM THE ASIO SDK // do whatever you need to do if the sample rate changed @@ -2987,10 +3117,10 @@ static void sampleRateChanged(ASIOSampleRate sRate) // You might have to update time/sample related conversion routines, etc. (void) sRate; /* unused parameter */ - PA_DEBUG( ("sampleRateChanged : %d \n", sRate)); + PA_DEBUG ( ("sampleRateChanged : %d \n", sRate)); } -static long asioMessages(long selector, long value, void* message, double* opt) +static long asioMessages (long selector, long value, void* message, double* opt) { // TAKEN FROM THE ASIO SDK // currently the parameters "value", "message" and "opt" are not used. @@ -2999,20 +3129,22 @@ static long asioMessages(long selector, long value, void* message, double* opt) (void) message; /* unused parameters */ (void) opt; - PA_DEBUG( ("asioMessages : %d , %d \n", selector, value)); + PA_DEBUG ( ("asioMessages : %d , %d \n", selector, value)); + + switch (selector) { - 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; + + 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: @@ -3028,6 +3160,7 @@ static long asioMessages(long selector, long value, void* message, double* opt) /*FIXME: commented the next line out */ //asioDriverInfo.stopped; // In this sample the processing will just stop ret = 1L; + break; case kAsioResyncRequest: @@ -3038,6 +3171,7 @@ static long asioMessages(long selector, long value, void* message, double* opt) // by another thread. // However a driver can issue it in other situations, too. ret = 1L; + break; case kAsioLatenciesChanged: @@ -3045,6 +3179,7 @@ static long asioMessages(long selector, long value, void* message, double* opt) // 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; @@ -3053,6 +3188,7 @@ static long asioMessages(long selector, long value, void* message, double* opt) // If a host applications does not implement this selector, ASIO 1.0 is assumed // by the driver ret = 2L; + break; case kAsioSupportsTimeInfo: @@ -3061,6 +3197,7 @@ static long asioMessages(long selector, long value, void* message, double* opt) // For compatibility with ASIO 1.0 drivers the host application should always support // the "old" bufferSwitch method, too. ret = 1; + break; case kAsioSupportsTimeCode: @@ -3068,26 +3205,28 @@ static long asioMessages(long selector, long value, void* message, double* opt) // If an application does not need to know about time code, the driver has less work // to do. ret = 0; + break; } + return ret; } -static PaError StartStream( PaStream *s ) +static PaError StartStream (PaStream *s) { PaError result = paNoError; - PaAsioStream *stream = (PaAsioStream*)s; + PaAsioStream *stream = (PaAsioStream*) s; PaAsioStreamBlockingState *blockingState = stream->blockingState; ASIOError asioError; - if( stream->outputChannelCount > 0 ) - { - ZeroOutputBuffers( stream, 0 ); - ZeroOutputBuffers( stream, 1 ); + if (stream->outputChannelCount > 0) { + ZeroOutputBuffers (stream, 0); + ZeroOutputBuffers (stream, 1); } - PaUtil_ResetBufferProcessor( &stream->bufferProcessor ); + PaUtil_ResetBufferProcessor (&stream->bufferProcessor); + stream->stopProcessing = false; stream->zeroOutput = false; @@ -3097,77 +3236,77 @@ static PaError StartStream( PaStream *s ) stream->callbackFlags = 0; - if( ResetEvent( stream->completedBuffersPlayedEvent ) == 0 ) - { + if (ResetEvent (stream->completedBuffersPlayedEvent) == 0) { result = paUnanticipatedHostError; - PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() ); + PA_ASIO_SET_LAST_SYSTEM_ERROR (GetLastError()); } /* Using blocking i/o interface... */ - if( blockingState ) - { + if (blockingState) { /* Reset blocking i/o buffer processor. */ - PaUtil_ResetBufferProcessor( &blockingState->bufferProcessor ); + PaUtil_ResetBufferProcessor (&blockingState->bufferProcessor); /* If we're about to process some input data. */ - if( stream->inputChannelCount ) - { + + if (stream->inputChannelCount) { /* Reset callback-ReadStream sync event. */ - if( ResetEvent( blockingState->readFramesReadyEvent ) == 0 ) - { + if (ResetEvent (blockingState->readFramesReadyEvent) == 0) { result = paUnanticipatedHostError; - PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() ); + PA_ASIO_SET_LAST_SYSTEM_ERROR (GetLastError()); } /* Flush blocking i/o ring buffer. */ - PaUtil_FlushRingBuffer( &blockingState->readRingBuffer ); - (*blockingState->bufferProcessor.inputZeroer)( blockingState->readRingBuffer.buffer, 1, blockingState->bufferProcessor.inputChannelCount * blockingState->readRingBuffer.bufferSize ); + PaUtil_FlushRingBuffer (&blockingState->readRingBuffer); + + (*blockingState->bufferProcessor.inputZeroer) (blockingState->readRingBuffer.buffer, 1, blockingState->bufferProcessor.inputChannelCount * blockingState->readRingBuffer.bufferSize); } /* If we're about to process some output data. */ - if( stream->outputChannelCount ) - { + if (stream->outputChannelCount) { /* Reset callback-WriteStream sync event. */ - if( ResetEvent( blockingState->writeBuffersReadyEvent ) == 0 ) - { + if (ResetEvent (blockingState->writeBuffersReadyEvent) == 0) { result = paUnanticipatedHostError; - PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() ); + PA_ASIO_SET_LAST_SYSTEM_ERROR (GetLastError()); } /* Flush blocking i/o ring buffer. */ - PaUtil_FlushRingBuffer( &blockingState->writeRingBuffer ); - (*blockingState->bufferProcessor.outputZeroer)( blockingState->writeRingBuffer.buffer, 1, blockingState->bufferProcessor.outputChannelCount * blockingState->writeRingBuffer.bufferSize ); + PaUtil_FlushRingBuffer (&blockingState->writeRingBuffer); + + (*blockingState->bufferProcessor.outputZeroer) (blockingState->writeRingBuffer.buffer, 1, blockingState->bufferProcessor.outputChannelCount * blockingState->writeRingBuffer.bufferSize); /* Initialize the output ring buffer to "silence". */ - PaUtil_AdvanceRingBufferWriteIndex( &blockingState->writeRingBuffer, blockingState->writeRingBufferInitialFrames ); + PaUtil_AdvanceRingBufferWriteIndex (&blockingState->writeRingBuffer, blockingState->writeRingBufferInitialFrames); } /* Clear requested frames / buffers count. */ blockingState->writeBuffersRequested = 0; + blockingState->readFramesRequested = 0; + blockingState->writeBuffersRequestedFlag = FALSE; + blockingState->readFramesRequestedFlag = FALSE; + blockingState->outputUnderflowFlag = FALSE; + blockingState->inputOverflowFlag = FALSE; + blockingState->stopFlag = FALSE; } - if( result == paNoError ) - { + if (result == paNoError) { theAsioStream = stream; asioError = ASIOStart(); - if( asioError == ASE_OK ) - { + + if (asioError == ASE_OK) { stream->isActive = 1; stream->streamFinishedCallbackCalled = false; - } - else - { + } else { theAsioStream = 0; result = paUnanticipatedHostError; - PA_ASIO_SET_LAST_ASIO_ERROR( asioError ); + PA_ASIO_SET_LAST_ASIO_ERROR (asioError); } } @@ -3175,18 +3314,16 @@ static PaError StartStream( PaStream *s ) } -static PaError StopStream( PaStream *s ) +static PaError StopStream (PaStream *s) { PaError result = paNoError; - PaAsioStream *stream = (PaAsioStream*)s; + PaAsioStream *stream = (PaAsioStream*) s; PaAsioStreamBlockingState *blockingState = stream->blockingState; ASIOError asioError; - if( stream->isActive ) - { + if (stream->isActive) { /* If blocking i/o output is in use */ - if( blockingState && stream->outputChannelCount ) - { + if (blockingState && stream->outputChannelCount) { /* Request the whole output buffer to be available. */ blockingState->writeBuffersRequested = blockingState->writeRingBuffer.bufferSize; /* Signalize that additional buffers are need. */ @@ -3197,20 +3334,18 @@ static PaError StopStream( PaStream *s ) /* Wait until requested number of buffers has been freed. Time out after twice the blocking i/o ouput buffer could have been consumed. */ - DWORD timeout = (DWORD)( 2 * blockingState->writeRingBuffer.bufferSize * 1000 - / stream->streamRepresentation.streamInfo.sampleRate ); - DWORD waitResult = WaitForSingleObject( blockingState->writeBuffersReadyEvent, timeout ); + DWORD timeout = (DWORD) (2 * blockingState->writeRingBuffer.bufferSize * 1000 + / stream->streamRepresentation.streamInfo.sampleRate); + DWORD waitResult = WaitForSingleObject (blockingState->writeBuffersReadyEvent, timeout); /* If something seriously went wrong... */ - if( waitResult == WAIT_FAILED ) - { - PA_DEBUG(("WaitForSingleObject() failed in StopStream()\n")); + + if (waitResult == WAIT_FAILED) { + PA_DEBUG ( ("WaitForSingleObject() failed in StopStream()\n")); result = paUnanticipatedHostError; - PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() ); - } - else if( waitResult == WAIT_TIMEOUT ) - { - PA_DEBUG(("WaitForSingleObject() timed out in StopStream()\n")); + PA_ASIO_SET_LAST_SYSTEM_ERROR (GetLastError()); + } else if (waitResult == WAIT_TIMEOUT) { + PA_DEBUG ( ("WaitForSingleObject() timed out in StopStream()\n")); result = paTimedOut; } } @@ -3224,57 +3359,55 @@ static PaError StopStream( PaStream *s ) length is longer than the asio buffer size then that should be taken into account. */ - if( WaitForSingleObject( theAsioStream->completedBuffersPlayedEvent, - (DWORD)(stream->streamRepresentation.streamInfo.outputLatency * 1000. * 4.) ) - == WAIT_TIMEOUT ) - { - PA_DEBUG(("WaitForSingleObject() timed out in StopStream()\n" )); + + if (WaitForSingleObject (theAsioStream->completedBuffersPlayedEvent, + (DWORD) (stream->streamRepresentation.streamInfo.outputLatency * 1000. * 4.)) + == WAIT_TIMEOUT) { + PA_DEBUG ( ("WaitForSingleObject() timed out in StopStream()\n")); } } asioError = ASIOStop(); - if( asioError != ASE_OK ) - { + + if (asioError != ASE_OK) { result = paUnanticipatedHostError; - PA_ASIO_SET_LAST_ASIO_ERROR( asioError ); + PA_ASIO_SET_LAST_ASIO_ERROR (asioError); } theAsioStream = 0; + stream->isActive = 0; - if( !stream->streamFinishedCallbackCalled ) - { - if( stream->streamRepresentation.streamFinishedCallback != 0 ) - stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData ); + if (!stream->streamFinishedCallbackCalled) { + if (stream->streamRepresentation.streamFinishedCallback != 0) + stream->streamRepresentation.streamFinishedCallback (stream->streamRepresentation.userData); } return result; } -static PaError AbortStream( PaStream *s ) +static PaError AbortStream (PaStream *s) { PaError result = paNoError; - PaAsioStream *stream = (PaAsioStream*)s; + PaAsioStream *stream = (PaAsioStream*) s; ASIOError asioError; stream->zeroOutput = true; asioError = ASIOStop(); - if( asioError != ASE_OK ) - { + + if (asioError != ASE_OK) { result = paUnanticipatedHostError; - PA_ASIO_SET_LAST_ASIO_ERROR( asioError ); - } - else - { + PA_ASIO_SET_LAST_ASIO_ERROR (asioError); + } else { // make sure that the callback is not still in-flight when ASIOStop() // returns. This has been observed to happen on the Hoontech DSP24 for // example. int count = 2000; // only wait for 2 seconds, rather than hanging. - while( theAsioStream->reenterCount != -1 && count > 0 ) - { - Sleep(1); + + while (theAsioStream->reenterCount != -1 && count > 0) { + Sleep (1); --count; } } @@ -3284,21 +3417,21 @@ static PaError AbortStream( PaStream *s ) not - this is based on the fact that ASIOStop is unlikely to fail if the callback is running - it's more likely to fail because the callback is not running. */ - + theAsioStream = 0; + stream->isActive = 0; - if( !stream->streamFinishedCallbackCalled ) - { - if( stream->streamRepresentation.streamFinishedCallback != 0 ) - stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData ); + if (!stream->streamFinishedCallbackCalled) { + if (stream->streamRepresentation.streamFinishedCallback != 0) + stream->streamRepresentation.streamFinishedCallback (stream->streamRepresentation.userData); } return result; } -static PaError IsStreamStopped( PaStream *s ) +static PaError IsStreamStopped (PaStream *s) { //PaAsioStream *stream = (PaAsioStream*)s; (void) s; /* unused parameter */ @@ -3306,26 +3439,26 @@ static PaError IsStreamStopped( PaStream *s ) } -static PaError IsStreamActive( PaStream *s ) +static PaError IsStreamActive (PaStream *s) { - PaAsioStream *stream = (PaAsioStream*)s; + PaAsioStream *stream = (PaAsioStream*) s; return stream->isActive; } -static PaTime GetStreamTime( PaStream *s ) +static PaTime GetStreamTime (PaStream *s) { (void) s; /* unused parameter */ - return (double)timeGetTime() * .001; + return (double) timeGetTime() * .001; } -static double GetStreamCpuLoad( PaStream* s ) +static double GetStreamCpuLoad (PaStream* s) { - PaAsioStream *stream = (PaAsioStream*)s; + PaAsioStream *stream = (PaAsioStream*) s; - return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer ); + return PaUtil_GetCpuLoad (&stream->cpuLoadMeasurer); } @@ -3335,12 +3468,12 @@ static double GetStreamCpuLoad( PaStream* s ) for blocking streams. */ -static PaError ReadStream( PaStream *s , +static PaError ReadStream (PaStream *s , void *buffer, - unsigned long frames ) + unsigned long frames) { PaError result = paNoError; /* Initial return value. */ - PaAsioStream *stream = (PaAsioStream*)s; /* The PA ASIO stream. */ + PaAsioStream *stream = (PaAsioStream*) s; /* The PA ASIO stream. */ /* Pointer to the blocking i/o data struct. */ PaAsioStreamBlockingState *blockingState = stream->blockingState; @@ -3369,45 +3502,44 @@ static PaError ReadStream( PaStream *s , unsigned int i; /* Just a counter. */ /* About the time, needed to process 8 data blocks. */ - DWORD timeout = (DWORD)( 8 * lFramesPerBlock * 1000 / stream->streamRepresentation.streamInfo.sampleRate ); + DWORD timeout = (DWORD) (8 * lFramesPerBlock * 1000 / stream->streamRepresentation.streamInfo.sampleRate); DWORD waitResult = 0; /* Check if the stream is still available ready to gather new data. */ - if( blockingState->stopFlag || !stream->isActive ) - { - PA_DEBUG(("Warning! Stream no longer available for reading in ReadStream()\n")); + + if (blockingState->stopFlag || !stream->isActive) { + PA_DEBUG ( ("Warning! Stream no longer available for reading in ReadStream()\n")); result = paStreamIsStopped; return result; } /* If the stream is a input stream. */ - if( stream->inputChannelCount ) - { + if (stream->inputChannelCount) { /* Prepare buffer access. */ - if( !pBp->userOutputIsInterleaved ) - { + if (!pBp->userOutputIsInterleaved) { userBuffer = blockingState->readStreamBuffer; - for( i = 0; i<pBp->inputChannelCount; ++i ) - { - ((void**)userBuffer)[i] = ((void**)buffer)[i]; + + for (i = 0; i<pBp->inputChannelCount; ++i) { + ( (void**) userBuffer) [i] = ( (void**) buffer) [i]; } } /* Use the unchanged buffer. */ - else { userBuffer = buffer; } + else { + userBuffer = buffer; + } - do /* Internal block processing for too large user data buffers. */ - { + do { /* Internal block processing for too large user data buffers. */ /* Get the size of the current data block to be processed. */ - lFramesPerBlock =(lFramesPerBlock < lFramesRemaining) - ? lFramesPerBlock : lFramesRemaining; + lFramesPerBlock = (lFramesPerBlock < lFramesRemaining) + ? lFramesPerBlock : lFramesRemaining; /* Use predefined block size for as long there are enough buffers available, thereafter reduce the processing block size to match the number of remaining buffers. So the final data block is processed although it may be incomplete. */ /* If the available amount of data frames is insufficient. */ - if( PaUtil_GetRingBufferReadAvailable(pRb) < (long) lFramesPerBlock ) - { + + if (PaUtil_GetRingBufferReadAvailable (pRb) < (long) lFramesPerBlock) { /* Make sure, the event isn't already set! */ /* ResetEvent( blockingState->readFramesReadyEvent ); */ @@ -3418,30 +3550,33 @@ static PaError ReadStream( PaStream *s , blockingState->readFramesRequestedFlag = TRUE; /* Wait until requested number of buffers has been freed. */ - waitResult = WaitForSingleObject( blockingState->readFramesReadyEvent, timeout ); + waitResult = WaitForSingleObject (blockingState->readFramesReadyEvent, timeout); /* If something seriously went wrong... */ - if( waitResult == WAIT_FAILED ) - { - PA_DEBUG(("WaitForSingleObject() failed in ReadStream()\n")); + + if (waitResult == WAIT_FAILED) { + PA_DEBUG ( ("WaitForSingleObject() failed in ReadStream()\n")); result = paUnanticipatedHostError; - PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() ); + PA_ASIO_SET_LAST_SYSTEM_ERROR (GetLastError()); return result; - } - else if( waitResult == WAIT_TIMEOUT ) - { - PA_DEBUG(("WaitForSingleObject() timed out in ReadStream()\n")); + } else if (waitResult == WAIT_TIMEOUT) { + PA_DEBUG ( ("WaitForSingleObject() timed out in ReadStream()\n")); /* If block processing has stopped, abort! */ - if( blockingState->stopFlag ) { return result = paStreamIsStopped; } + + if (blockingState->stopFlag) { + return result = paStreamIsStopped; + } /* if a timeout is encountered, continue, perhaps we should give up eventually */ continue; + /* To give up eventually, we may increase the time out period and return an error if it fails anyway. */ /* retrun result = paTimedOut; */ } } + /* Now, the ring buffer contains the required amount of data frames. (Therefor we don't need to check the return argument of @@ -3454,47 +3589,48 @@ static PaError ReadStream( PaStream *s , segment is returned. Otherwise, i.e. if the first segment is large enough, the second segment's pointer will be NULL. */ - PaUtil_GetRingBufferReadRegions(pRb , - lFramesPerBlock , - &pRingBufferData1st, - &lRingBufferSize1st, - &pRingBufferData2nd, - &lRingBufferSize2nd); + PaUtil_GetRingBufferReadRegions (pRb , + lFramesPerBlock , + &pRingBufferData1st, + &lRingBufferSize1st, + &pRingBufferData2nd, + &lRingBufferSize2nd); /* Set number of frames to be copied from the ring buffer. */ - PaUtil_SetInputFrameCount( pBp, lRingBufferSize1st ); + PaUtil_SetInputFrameCount (pBp, lRingBufferSize1st); + /* Setup ring buffer access. */ - PaUtil_SetInterleavedInputChannels(pBp , /* Buffer processor. */ - 0 , /* The first channel's index. */ - pRingBufferData1st, /* First ring buffer segment. */ - 0 ); /* Use all available channels. */ + PaUtil_SetInterleavedInputChannels (pBp , /* Buffer processor. */ + 0 , /* The first channel's index. */ + pRingBufferData1st, /* First ring buffer segment. */ + 0); /* Use all available channels. */ /* If a second ring buffer segment is required. */ - if( lRingBufferSize2nd ) { + if (lRingBufferSize2nd) { /* Set number of frames to be copied from the ring buffer. */ - PaUtil_Set2ndInputFrameCount( pBp, lRingBufferSize2nd ); + PaUtil_Set2ndInputFrameCount (pBp, lRingBufferSize2nd); /* Setup ring buffer access. */ - PaUtil_Set2ndInterleavedInputChannels(pBp , /* Buffer processor. */ - 0 , /* The first channel's index. */ - pRingBufferData2nd, /* Second ring buffer segment. */ - 0 ); /* Use all available channels. */ + PaUtil_Set2ndInterleavedInputChannels (pBp , /* Buffer processor. */ + 0 , /* The first channel's index. */ + pRingBufferData2nd, /* Second ring buffer segment. */ + 0); /* Use all available channels. */ } /* Let the buffer processor handle "copy and conversion" and update the ring buffer indices manually. */ - lFramesCopied = PaUtil_CopyInput( pBp, &buffer, lFramesPerBlock ); - PaUtil_AdvanceRingBufferReadIndex( pRb, lFramesCopied ); + lFramesCopied = PaUtil_CopyInput (pBp, &buffer, lFramesPerBlock); + + PaUtil_AdvanceRingBufferReadIndex (pRb, lFramesCopied); /* Decrease number of unprocessed frames. */ lFramesRemaining -= lFramesCopied; } /* Continue with the next data chunk. */ - while( lFramesRemaining ); + while (lFramesRemaining); /* If there has been an input overflow within the callback */ - if( blockingState->inputOverflowFlag ) - { + if (blockingState->inputOverflowFlag) { blockingState->inputOverflowFlag = FALSE; /* Return the corresponding error code. */ @@ -3509,12 +3645,12 @@ static PaError ReadStream( PaStream *s , return result; } -static PaError WriteStream( PaStream *s , +static PaError WriteStream (PaStream *s , const void *buffer, - unsigned long frames ) + unsigned long frames) { PaError result = paNoError; /* Initial return value. */ - PaAsioStream *stream = (PaAsioStream*)s; /* The PA ASIO stream. */ + PaAsioStream *stream = (PaAsioStream*) s; /* The PA ASIO stream. */ /* Pointer to the blocking i/o data struct. */ PaAsioStreamBlockingState *blockingState = stream->blockingState; @@ -3539,7 +3675,7 @@ static PaError WriteStream( PaStream *s , unsigned long lFramesRemaining = frames; /* About the time, needed to process 8 data blocks. */ - DWORD timeout = (DWORD)( 8 * lFramesPerBlock * 1000 / stream->streamRepresentation.streamInfo.sampleRate ); + DWORD timeout = (DWORD) (8 * lFramesPerBlock * 1000 / stream->streamRepresentation.streamInfo.sampleRate); DWORD waitResult = 0; /* Copy the input argument to avoid pointer increment! */ @@ -3548,41 +3684,40 @@ static PaError WriteStream( PaStream *s , /* Check if the stream ist still available ready to recieve new data. */ - if( blockingState->stopFlag || !stream->isActive ) - { - PA_DEBUG(("Warning! Stream no longer available for writing in WriteStream()\n")); + + if (blockingState->stopFlag || !stream->isActive) { + PA_DEBUG ( ("Warning! Stream no longer available for writing in WriteStream()\n")); result = paStreamIsStopped; return result; } /* If the stream is a output stream. */ - if( stream->outputChannelCount ) - { + if (stream->outputChannelCount) { /* Prepare buffer access. */ - if( !pBp->userOutputIsInterleaved ) - { + if (!pBp->userOutputIsInterleaved) { userBuffer = blockingState->writeStreamBuffer; - for( i = 0; i<pBp->outputChannelCount; ++i ) - { - ((const void**)userBuffer)[i] = ((const void**)buffer)[i]; + + for (i = 0; i<pBp->outputChannelCount; ++i) { + ( (const void**) userBuffer) [i] = ( (const void**) buffer) [i]; } } /* Use the unchanged buffer. */ - else { userBuffer = buffer; } + else { + userBuffer = buffer; + } - do /* Internal block processing for too large user data buffers. */ - { + do { /* Internal block processing for too large user data buffers. */ /* Get the size of the current data block to be processed. */ - lFramesPerBlock =(lFramesPerBlock < lFramesRemaining) - ? lFramesPerBlock : lFramesRemaining; + lFramesPerBlock = (lFramesPerBlock < lFramesRemaining) + ? lFramesPerBlock : lFramesRemaining; /* Use predefined block size for as long there are enough frames available, thereafter reduce the processing block size to match the number of remaining frames. So the final data block is processed although it may be incomplete. */ /* If the available amount of buffers is insufficient. */ - if( PaUtil_GetRingBufferWriteAvailable(pRb) < (long) lFramesPerBlock ) - { + + if (PaUtil_GetRingBufferWriteAvailable (pRb) < (long) lFramesPerBlock) { /* Make sure, the event isn't already set! */ /* ResetEvent( blockingState->writeBuffersReadyEvent ); */ @@ -3593,29 +3728,33 @@ static PaError WriteStream( PaStream *s , blockingState->writeBuffersRequestedFlag = TRUE; /* Wait until requested number of buffers has been freed. */ - waitResult = WaitForSingleObject( blockingState->writeBuffersReadyEvent, timeout ); + waitResult = WaitForSingleObject (blockingState->writeBuffersReadyEvent, timeout); /* If something seriously went wrong... */ - if( waitResult == WAIT_FAILED ) - { - PA_DEBUG(("WaitForSingleObject() failed in WriteStream()\n")); + + if (waitResult == WAIT_FAILED) { + PA_DEBUG ( ("WaitForSingleObject() failed in WriteStream()\n")); result = paUnanticipatedHostError; - PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() ); + PA_ASIO_SET_LAST_SYSTEM_ERROR (GetLastError()); return result; - } - else if( waitResult == WAIT_TIMEOUT ) - { - PA_DEBUG(("WaitForSingleObject() timed out in WriteStream()\n")); + } else if (waitResult == WAIT_TIMEOUT) { + PA_DEBUG ( ("WaitForSingleObject() timed out in WriteStream()\n")); /* If block processing has stopped, abort! */ - if( blockingState->stopFlag ) { return result = paStreamIsStopped; } + + if (blockingState->stopFlag) { + return result = paStreamIsStopped; + } + /* if a timeout is encountered, continue, perhaps we should give up eventually */ continue; + /* To give up eventually, we may increase the time out period and return an error if it fails anyway. */ /* retrun result = paTimedOut; */ } } + /* Now, the ring buffer contains the required amount of free space to store the provided number of data frames. (Therefor we don't need to check the return argument of @@ -3628,47 +3767,48 @@ static PaError WriteStream( PaStream *s , segment is returned. Otherwise, i.e. if the first segment is large enough, the second segment's pointer will be NULL. */ - PaUtil_GetRingBufferWriteRegions(pRb , - lFramesPerBlock , - &pRingBufferData1st, - &lRingBufferSize1st, - &pRingBufferData2nd, - &lRingBufferSize2nd); + PaUtil_GetRingBufferWriteRegions (pRb , + lFramesPerBlock , + &pRingBufferData1st, + &lRingBufferSize1st, + &pRingBufferData2nd, + &lRingBufferSize2nd); /* Set number of frames to be copied to the ring buffer. */ - PaUtil_SetOutputFrameCount( pBp, lRingBufferSize1st ); + PaUtil_SetOutputFrameCount (pBp, lRingBufferSize1st); + /* Setup ring buffer access. */ - PaUtil_SetInterleavedOutputChannels(pBp , /* Buffer processor. */ - 0 , /* The first channel's index. */ - pRingBufferData1st, /* First ring buffer segment. */ - 0 ); /* Use all available channels. */ + PaUtil_SetInterleavedOutputChannels (pBp , /* Buffer processor. */ + 0 , /* The first channel's index. */ + pRingBufferData1st, /* First ring buffer segment. */ + 0); /* Use all available channels. */ /* If a second ring buffer segment is required. */ - if( lRingBufferSize2nd ) { + if (lRingBufferSize2nd) { /* Set number of frames to be copied to the ring buffer. */ - PaUtil_Set2ndOutputFrameCount( pBp, lRingBufferSize2nd ); + PaUtil_Set2ndOutputFrameCount (pBp, lRingBufferSize2nd); /* Setup ring buffer access. */ - PaUtil_Set2ndInterleavedOutputChannels(pBp , /* Buffer processor. */ - 0 , /* The first channel's index. */ - pRingBufferData2nd, /* Second ring buffer segment. */ - 0 ); /* Use all available channels. */ + PaUtil_Set2ndInterleavedOutputChannels (pBp , /* Buffer processor. */ + 0 , /* The first channel's index. */ + pRingBufferData2nd, /* Second ring buffer segment. */ + 0); /* Use all available channels. */ } /* Let the buffer processor handle "copy and conversion" and update the ring buffer indices manually. */ - lFramesCopied = PaUtil_CopyOutput( pBp, &userBuffer, lFramesPerBlock ); - PaUtil_AdvanceRingBufferWriteIndex( pRb, lFramesCopied ); + lFramesCopied = PaUtil_CopyOutput (pBp, &userBuffer, lFramesPerBlock); + + PaUtil_AdvanceRingBufferWriteIndex (pRb, lFramesCopied); /* Decrease number of unprocessed frames. */ lFramesRemaining -= lFramesCopied; } /* Continue with the next data chunk. */ - while( lFramesRemaining ); + while (lFramesRemaining); /* If there has been an output underflow within the callback */ - if( blockingState->outputUnderflowFlag ) - { + if (blockingState->outputUnderflowFlag) { blockingState->outputUnderflowFlag = FALSE; /* Return the corresponding error code. */ @@ -3676,8 +3816,7 @@ static PaError WriteStream( PaStream *s , } } /* If this is not an output stream. */ - else - { + else { result = paCanNotWriteToAnInputOnlyStream; } @@ -3685,25 +3824,25 @@ static PaError WriteStream( PaStream *s , } -static signed long GetStreamReadAvailable( PaStream* s ) +static signed long GetStreamReadAvailable (PaStream* s) { - PaAsioStream *stream = (PaAsioStream*)s; + PaAsioStream *stream = (PaAsioStream*) s; /* Call buffer utility routine to get the number of available frames. */ - return PaUtil_GetRingBufferReadAvailable( &stream->blockingState->readRingBuffer ); + return PaUtil_GetRingBufferReadAvailable (&stream->blockingState->readRingBuffer); } -static signed long GetStreamWriteAvailable( PaStream* s ) +static signed long GetStreamWriteAvailable (PaStream* s) { - PaAsioStream *stream = (PaAsioStream*)s; + PaAsioStream *stream = (PaAsioStream*) s; /* Call buffer utility routine to get the number of empty buffers. */ - return PaUtil_GetRingBufferWriteAvailable( &stream->blockingState->writeRingBuffer ); + return PaUtil_GetRingBufferWriteAvailable (&stream->blockingState->writeRingBuffer); } -PaError PaAsio_ShowControlPanel( PaDeviceIndex device, void* systemSpecific ) +PaError PaAsio_ShowControlPanel (PaDeviceIndex device, void* systemSpecific) { PaError result = paNoError; PaUtilHostApiRepresentation *hostApi; @@ -3715,12 +3854,14 @@ PaError PaAsio_ShowControlPanel( PaDeviceIndex device, void* systemSpecific ) PaAsioDeviceInfo *asioDeviceInfo; - result = PaUtil_GetHostApiRepresentation( &hostApi, paASIO ); - if( result != paNoError ) + result = PaUtil_GetHostApiRepresentation (&hostApi, paASIO); + + if (result != paNoError) goto error; - result = PaUtil_DeviceIndexToHostApiDeviceIndex( &hostApiDevice, device, hostApi ); - if( result != paNoError ) + result = PaUtil_DeviceIndexToHostApiDeviceIndex (&hostApiDevice, device, hostApi); + + if (result != paNoError) goto error; /* @@ -3731,84 +3872,87 @@ PaError PaAsio_ShowControlPanel( PaDeviceIndex device, void* systemSpecific ) done safely while a stream is open. */ - asioHostApi = (PaAsioHostApiRepresentation*)hostApi; - if( asioHostApi->openAsioDeviceIndex != paNoDevice ) - { + asioHostApi = (PaAsioHostApiRepresentation*) hostApi; + + if (asioHostApi->openAsioDeviceIndex != paNoDevice) { result = paDeviceUnavailable; goto error; } - asioDeviceInfo = (PaAsioDeviceInfo*)hostApi->deviceInfos[hostApiDevice]; + asioDeviceInfo = (PaAsioDeviceInfo*) hostApi->deviceInfos[hostApiDevice]; /* See notes about CoInitialize(0) in LoadAsioDriver(). */ - CoInitialize(0); + CoInitialize (0); - if( !asioHostApi->asioDrivers->loadDriver( const_cast<char*>(asioDeviceInfo->commonDeviceInfo.name) ) ) - { + if (!asioHostApi->asioDrivers->loadDriver (const_cast<char*> (asioDeviceInfo->commonDeviceInfo.name))) { result = paUnanticipatedHostError; goto error; } /* CRUCIAL!!! */ - memset( &asioDriverInfo, 0, sizeof(ASIODriverInfo) ); + memset (&asioDriverInfo, 0, sizeof (ASIODriverInfo)); + asioDriverInfo.asioVersion = 2; + asioDriverInfo.sysRef = systemSpecific; - asioError = ASIOInit( &asioDriverInfo ); - if( asioError != ASE_OK ) - { + + asioError = ASIOInit (&asioDriverInfo); + + if (asioError != ASE_OK) { result = paUnanticipatedHostError; - PA_ASIO_SET_LAST_ASIO_ERROR( asioError ); + PA_ASIO_SET_LAST_ASIO_ERROR (asioError); goto error; - } - else - { + } else { asioIsInitialized = 1; } -PA_DEBUG(("PaAsio_ShowControlPanel: ASIOInit(): %s\n", PaAsio_GetAsioErrorText(asioError) )); -PA_DEBUG(("asioVersion: ASIOInit(): %ld\n", asioDriverInfo.asioVersion )); -PA_DEBUG(("driverVersion: ASIOInit(): %ld\n", asioDriverInfo.driverVersion )); -PA_DEBUG(("Name: ASIOInit(): %s\n", asioDriverInfo.name )); -PA_DEBUG(("ErrorMessage: ASIOInit(): %s\n", asioDriverInfo.errorMessage )); + PA_DEBUG ( ("PaAsio_ShowControlPanel: ASIOInit(): %s\n", PaAsio_GetAsioErrorText (asioError))); + + PA_DEBUG ( ("asioVersion: ASIOInit(): %ld\n", asioDriverInfo.asioVersion)); + PA_DEBUG ( ("driverVersion: ASIOInit(): %ld\n", asioDriverInfo.driverVersion)); + PA_DEBUG ( ("Name: ASIOInit(): %s\n", asioDriverInfo.name)); + PA_DEBUG ( ("ErrorMessage: ASIOInit(): %s\n", asioDriverInfo.errorMessage)); asioError = ASIOControlPanel(); - if( asioError != ASE_OK ) - { - PA_DEBUG(("PaAsio_ShowControlPanel: ASIOControlPanel(): %s\n", PaAsio_GetAsioErrorText(asioError) )); + + if (asioError != ASE_OK) { + PA_DEBUG ( ("PaAsio_ShowControlPanel: ASIOControlPanel(): %s\n", PaAsio_GetAsioErrorText (asioError))); result = paUnanticipatedHostError; - PA_ASIO_SET_LAST_ASIO_ERROR( asioError ); + PA_ASIO_SET_LAST_ASIO_ERROR (asioError); goto error; } -PA_DEBUG(("PaAsio_ShowControlPanel: ASIOControlPanel(): %s\n", PaAsio_GetAsioErrorText(asioError) )); + PA_DEBUG ( ("PaAsio_ShowControlPanel: ASIOControlPanel(): %s\n", PaAsio_GetAsioErrorText (asioError))); asioError = ASIOExit(); - if( asioError != ASE_OK ) - { + + if (asioError != ASE_OK) { result = paUnanticipatedHostError; - PA_ASIO_SET_LAST_ASIO_ERROR( asioError ); + PA_ASIO_SET_LAST_ASIO_ERROR (asioError); asioIsInitialized = 0; goto error; } - CoUninitialize(); -PA_DEBUG(("PaAsio_ShowControlPanel: ASIOExit(): %s\n", PaAsio_GetAsioErrorText(asioError) )); + CoUninitialize(); + + PA_DEBUG ( ("PaAsio_ShowControlPanel: ASIOExit(): %s\n", PaAsio_GetAsioErrorText (asioError))); return result; error: - if( asioIsInitialized ) - { - ASIOExit(); - } - CoUninitialize(); + + if (asioIsInitialized) { + ASIOExit(); + } + + CoUninitialize(); return result; } -PaError PaAsio_GetInputChannelName( PaDeviceIndex device, int channelIndex, - const char** channelName ) +PaError PaAsio_GetInputChannelName (PaDeviceIndex device, int channelIndex, + const char** channelName) { PaError result = paNoError; PaUtilHostApiRepresentation *hostApi; @@ -3816,17 +3960,19 @@ PaError PaAsio_GetInputChannelName( PaDeviceIndex device, int channelIndex, PaAsioDeviceInfo *asioDeviceInfo; - result = PaUtil_GetHostApiRepresentation( &hostApi, paASIO ); - if( result != paNoError ) + result = PaUtil_GetHostApiRepresentation (&hostApi, paASIO); + + if (result != paNoError) goto error; - result = PaUtil_DeviceIndexToHostApiDeviceIndex( &hostApiDevice, device, hostApi ); - if( result != paNoError ) + result = PaUtil_DeviceIndexToHostApiDeviceIndex (&hostApiDevice, device, hostApi); + + if (result != paNoError) goto error; - asioDeviceInfo = (PaAsioDeviceInfo*)hostApi->deviceInfos[hostApiDevice]; + asioDeviceInfo = (PaAsioDeviceInfo*) hostApi->deviceInfos[hostApiDevice]; - if( channelIndex < 0 || channelIndex >= asioDeviceInfo->commonDeviceInfo.maxInputChannels ){ + if (channelIndex < 0 || channelIndex >= asioDeviceInfo->commonDeviceInfo.maxInputChannels) { result = paInvalidChannelCount; goto error; } @@ -3834,14 +3980,14 @@ PaError PaAsio_GetInputChannelName( PaDeviceIndex device, int channelIndex, *channelName = asioDeviceInfo->asioChannelInfos[channelIndex].name; return paNoError; - + error: return result; } -PaError PaAsio_GetOutputChannelName( PaDeviceIndex device, int channelIndex, - const char** channelName ) +PaError PaAsio_GetOutputChannelName (PaDeviceIndex device, int channelIndex, + const char** channelName) { PaError result = paNoError; PaUtilHostApiRepresentation *hostApi; @@ -3849,26 +3995,29 @@ PaError PaAsio_GetOutputChannelName( PaDeviceIndex device, int channelIndex, PaAsioDeviceInfo *asioDeviceInfo; - result = PaUtil_GetHostApiRepresentation( &hostApi, paASIO ); - if( result != paNoError ) + result = PaUtil_GetHostApiRepresentation (&hostApi, paASIO); + + if (result != paNoError) goto error; - result = PaUtil_DeviceIndexToHostApiDeviceIndex( &hostApiDevice, device, hostApi ); - if( result != paNoError ) + result = PaUtil_DeviceIndexToHostApiDeviceIndex (&hostApiDevice, device, hostApi); + + if (result != paNoError) goto error; - asioDeviceInfo = (PaAsioDeviceInfo*)hostApi->deviceInfos[hostApiDevice]; + asioDeviceInfo = (PaAsioDeviceInfo*) hostApi->deviceInfos[hostApiDevice]; - if( channelIndex < 0 || channelIndex >= asioDeviceInfo->commonDeviceInfo.maxOutputChannels ){ + if (channelIndex < 0 || channelIndex >= asioDeviceInfo->commonDeviceInfo.maxOutputChannels) { result = paInvalidChannelCount; goto error; } *channelName = asioDeviceInfo->asioChannelInfos[ - asioDeviceInfo->commonDeviceInfo.maxInputChannels + channelIndex].name; + + asioDeviceInfo->commonDeviceInfo.maxInputChannels + channelIndex].name; return paNoError; - + error: return result; } @@ -3884,15 +4033,15 @@ error: ** 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 BlockingIoPaCallback(const void *inputBuffer , - void *outputBuffer , - unsigned long framesPerBuffer, - const PaStreamCallbackTimeInfo *timeInfo , - PaStreamCallbackFlags statusFlags , - void *userData ) +static int BlockingIoPaCallback (const void *inputBuffer , + void *outputBuffer , + unsigned long framesPerBuffer, + const PaStreamCallbackTimeInfo *timeInfo , + PaStreamCallbackFlags statusFlags , + void *userData) { PaError result = paNoError; /* Initial return value. */ - PaAsioStream *stream = *(PaAsioStream**)userData; /* The PA ASIO stream. */ /* This is a pointer to "theAsioStream", see OpenStream(). */ + PaAsioStream *stream = * (PaAsioStream**) userData; /* The PA ASIO stream. */ /* This is a pointer to "theAsioStream", see OpenStream(). */ PaAsioStreamBlockingState *blockingState = stream->blockingState; /* Persume blockingState is valid, otherwise the callback wouldn't be running. */ /* Get a pointer to the stream's blocking i/o buffer processor. */ @@ -3900,11 +4049,11 @@ static int BlockingIoPaCallback(const void *inputBuffer , PaUtilRingBuffer *pRb = NULL; /* If output data has been requested. */ - if( stream->outputChannelCount ) - { + + if (stream->outputChannelCount) { /* If the callback input argument signalizes a output underflow, make sure the WriteStream() function knows about it, too! */ - if( statusFlags & paOutputUnderflowed ) { + if (statusFlags & paOutputUnderflowed) { blockingState->outputUnderflowFlag = TRUE; } @@ -3912,36 +4061,32 @@ static int BlockingIoPaCallback(const void *inputBuffer , pRb = &blockingState->writeRingBuffer; /* If the blocking i/o buffer contains enough output data, */ - if( PaUtil_GetRingBufferReadAvailable(pRb) >= (long) framesPerBuffer ) - { + if (PaUtil_GetRingBufferReadAvailable (pRb) >= (long) framesPerBuffer) { /* Extract the requested data from the ring buffer. */ - PaUtil_ReadRingBuffer( pRb, outputBuffer, framesPerBuffer ); - } - else /* If no output data is available :-( */ - { + PaUtil_ReadRingBuffer (pRb, outputBuffer, framesPerBuffer); + } else { /* If no output data is available :-( */ /* Signalize a write-buffer underflow. */ blockingState->outputUnderflowFlag = TRUE; /* Fill the output buffer with silence. */ - (*pBp->outputZeroer)( outputBuffer, 1, pBp->outputChannelCount * framesPerBuffer ); + (*pBp->outputZeroer) (outputBuffer, 1, pBp->outputChannelCount * framesPerBuffer); /* If playback is to be stopped */ - if( blockingState->stopFlag && PaUtil_GetRingBufferReadAvailable(pRb) < (long) framesPerBuffer ) - { + + if (blockingState->stopFlag && PaUtil_GetRingBufferReadAvailable (pRb) < (long) framesPerBuffer) { /* Extract all the remaining data from the ring buffer, whether it is a complete data block or not. */ - PaUtil_ReadRingBuffer( pRb, outputBuffer, PaUtil_GetRingBufferReadAvailable(pRb) ); + PaUtil_ReadRingBuffer (pRb, outputBuffer, PaUtil_GetRingBufferReadAvailable (pRb)); } } /* Set blocking i/o event? */ - if( blockingState->writeBuffersRequestedFlag && PaUtil_GetRingBufferWriteAvailable(pRb) >= (long) blockingState->writeBuffersRequested ) - { + if (blockingState->writeBuffersRequestedFlag && PaUtil_GetRingBufferWriteAvailable (pRb) >= (long) blockingState->writeBuffersRequested) { /* Reset buffer request. */ blockingState->writeBuffersRequestedFlag = FALSE; blockingState->writeBuffersRequested = 0; /* Signalize that requested buffers are ready. */ - SetEvent( blockingState->writeBuffersReadyEvent ); + SetEvent (blockingState->writeBuffersReadyEvent); /* What do we do if SetEvent() returns zero, i.e. the event could not be set? How to return errors from within the callback? - S.Fischer */ @@ -3949,11 +4094,10 @@ static int BlockingIoPaCallback(const void *inputBuffer , } /* If input data has been supplied. */ - if( stream->inputChannelCount ) - { + if (stream->inputChannelCount) { /* If the callback input argument signalizes a input overflow, make sure the ReadStream() function knows about it, too! */ - if( statusFlags & paInputOverflowed ) { + if (statusFlags & paInputOverflowed) { blockingState->inputOverflowFlag = TRUE; } @@ -3961,26 +4105,24 @@ static int BlockingIoPaCallback(const void *inputBuffer , pRb = &blockingState->readRingBuffer; /* If the blocking i/o buffer contains not enough input buffers */ - if( PaUtil_GetRingBufferWriteAvailable(pRb) < (long) framesPerBuffer ) - { + if (PaUtil_GetRingBufferWriteAvailable (pRb) < (long) framesPerBuffer) { /* Signalize a read-buffer overflow. */ blockingState->inputOverflowFlag = TRUE; /* Remove some old data frames from the buffer. */ - PaUtil_AdvanceRingBufferReadIndex( pRb, framesPerBuffer ); + PaUtil_AdvanceRingBufferReadIndex (pRb, framesPerBuffer); } /* Insert the current input data into the ring buffer. */ - PaUtil_WriteRingBuffer( pRb, inputBuffer, framesPerBuffer ); + PaUtil_WriteRingBuffer (pRb, inputBuffer, framesPerBuffer); /* Set blocking i/o event? */ - if( blockingState->readFramesRequestedFlag && PaUtil_GetRingBufferReadAvailable(pRb) >= (long) blockingState->readFramesRequested ) - { + if (blockingState->readFramesRequestedFlag && PaUtil_GetRingBufferReadAvailable (pRb) >= (long) blockingState->readFramesRequested) { /* Reset buffer request. */ blockingState->readFramesRequestedFlag = FALSE; blockingState->readFramesRequested = 0; /* Signalize that requested buffers are ready. */ - SetEvent( blockingState->readFramesReadyEvent ); + SetEvent (blockingState->readFramesReadyEvent); /* What do we do if SetEvent() returns zero, i.e. the event could not be set? How to return errors from within the callback? - S.Fischer */ diff --git a/sflphone-common/libs/pjproject/third_party/portaudio/src/hostapi/wasapi/pa_win_wasapi.cpp b/sflphone-common/libs/pjproject/third_party/portaudio/src/hostapi/wasapi/pa_win_wasapi.cpp index f13a7f230296c87f606ec1f7505bde967afc1543..0653b138b06b8af86dcc82464d605d4e3eac2922 100644 --- a/sflphone-common/libs/pjproject/third_party/portaudio/src/hostapi/wasapi/pa_win_wasapi.cpp +++ b/sflphone-common/libs/pjproject/third_party/portaudio/src/hostapi/wasapi/pa_win_wasapi.cpp @@ -26,13 +26,13 @@ */ /* - * The text above constitutes the entire PortAudio license; however, + * The text above constitutes the entire PortAudio license; however, * the PortAudio community also makes the following non-binding requests: * * 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. It is also - * requested that these non-binding requests be included along with the + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the * license above. */ @@ -82,21 +82,22 @@ extern "C" { #endif /* __cplusplus */ -PaError PaWinWasapi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index ); + PaError PaWinWasapi_Initialize (PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index); #ifdef __cplusplus } + #endif /* __cplusplus */ -static void Terminate( struct PaUtilHostApiRepresentation *hostApi ); -static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, +static void Terminate (struct PaUtilHostApiRepresentation *hostApi); +static PaError IsFormatSupported (struct PaUtilHostApiRepresentation *hostApi, const PaStreamParameters *inputParameters, const PaStreamParameters *outputParameters, - double sampleRate ); -static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, + double sampleRate); +static PaError OpenStream (struct PaUtilHostApiRepresentation *hostApi, PaStream** s, const PaStreamParameters *inputParameters, const PaStreamParameters *outputParameters, @@ -104,19 +105,19 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, unsigned long framesPerBuffer, PaStreamFlags streamFlags, PaStreamCallback *streamCallback, - void *userData ); -static PaError CloseStream( PaStream* stream ); -static PaError StartStream( PaStream *stream ); -static PaError StopStream( PaStream *stream ); -static PaError AbortStream( PaStream *stream ); -static PaError IsStreamStopped( PaStream *s ); -static PaError IsStreamActive( PaStream *stream ); -static PaTime GetStreamTime( PaStream *stream ); -static double GetStreamCpuLoad( PaStream* stream ); -static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames ); -static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames ); -static signed long GetStreamReadAvailable( PaStream* stream ); -static signed long GetStreamWriteAvailable( PaStream* stream ); + void *userData); +static PaError CloseStream (PaStream* stream); +static PaError StartStream (PaStream *stream); +static PaError StopStream (PaStream *stream); +static PaError AbortStream (PaStream *stream); +static PaError IsStreamStopped (PaStream *s); +static PaError IsStreamActive (PaStream *stream); +static PaTime GetStreamTime (PaStream *stream); +static double GetStreamCpuLoad (PaStream* stream); +static PaError ReadStream (PaStream* stream, void *buffer, unsigned long frames); +static PaError WriteStream (PaStream* stream, const void *buffer, unsigned long frames); +static signed long GetStreamReadAvailable (PaStream* stream); +static signed long GetStreamWriteAvailable (PaStream* stream); /* IMPLEMENT ME: a macro like the following one should be used for reporting @@ -132,7 +133,8 @@ static signed long GetStreamWriteAvailable( PaStream* stream ); //currently built using RC1 SDK (5600) #if _MSC_VER < 1400 -PaError PaWinWasapi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex ){ +PaError PaWinWasapi_Initialize (PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex) +{ return paNoError; } @@ -149,8 +151,8 @@ PaError PaWinWasapi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApi i assume that neither of these will cause the Driver to "load", but again, who knows how they implement their stuff */ -typedef struct PaWinWasapiDeviceInfo -{ + +typedef struct PaWinWasapiDeviceInfo { //hmm is it wise to keep a reference until Terminate? //TODO Check if that interface requires the driver to be loaded! IMMDevice * device; @@ -174,8 +176,7 @@ typedef struct PaWinWasapiDeviceInfo } PaWinWasapiDeviceInfo; -typedef struct -{ +typedef struct { PaUtilHostApiRepresentation inheritedHostApiRep; PaUtilStreamInterface callbackStreamInterface; PaUtilStreamInterface blockingStreamInterface; @@ -199,7 +200,7 @@ typedef struct /* PaWinWasapiStream - a stream data structure specifically for this implementation */ -typedef struct PaWinWasapiSubStream{ +typedef struct PaWinWasapiSubStream { IAudioClient *client; WAVEFORMATEXTENSIBLE wavex; UINT32 bufferSize; @@ -208,8 +209,7 @@ typedef struct PaWinWasapiSubStream{ unsigned long framesPerHostCallback; /* just an example */ }PaWinWasapiSubStream; -typedef struct PaWinWasapiStream -{ /* IMPLEMENT ME: rename this */ +typedef struct PaWinWasapiStream { /* IMPLEMENT ME: rename this */ PaUtilStreamRepresentation streamRepresentation; PaUtilCpuLoadMeasurer cpuLoadMeasurer; PaUtilBufferProcessor bufferProcessor; @@ -220,20 +220,20 @@ typedef struct PaWinWasapiStream //input - PaWinWasapiSubStream in; + PaWinWasapiSubStream in; IAudioCaptureClient *cclient; IAudioEndpointVolume *inVol; - //output - PaWinWasapiSubStream out; + //output + PaWinWasapiSubStream out; IAudioRenderClient *rclient; - IAudioEndpointVolume *outVol; + IAudioEndpointVolume *outVol; bool running; bool closeRequest; DWORD dwThreadId; HANDLE hThread; - HANDLE hNotificationEvent; + HANDLE hNotificationEvent; GUID session; @@ -242,62 +242,145 @@ typedef struct PaWinWasapiStream #define PRINT(x) PA_DEBUG(x); void -logAUDCLNT_E(HRESULT res){ +logAUDCLNT_E (HRESULT res) +{ char *text = 0; - switch(res){ - case S_OK: return; break; - case E_POINTER :text ="E_POINTER"; break; - case E_INVALIDARG :text ="E_INVALIDARG"; break; - - case AUDCLNT_E_NOT_INITIALIZED :text ="AUDCLNT_E_NOT_INITIALIZED"; break; - case AUDCLNT_E_ALREADY_INITIALIZED :text ="AUDCLNT_E_ALREADY_INITIALIZED"; break; - case AUDCLNT_E_WRONG_ENDPOINT_TYPE :text ="AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break; - case AUDCLNT_E_DEVICE_INVALIDATED :text ="AUDCLNT_E_DEVICE_INVALIDATED"; break; - case AUDCLNT_E_NOT_STOPPED :text ="AUDCLNT_E_NOT_STOPPED"; break; - case AUDCLNT_E_BUFFER_TOO_LARGE :text ="AUDCLNT_E_BUFFER_TOO_LARGE"; break; - case AUDCLNT_E_OUT_OF_ORDER :text ="AUDCLNT_E_OUT_OF_ORDER"; break; - case AUDCLNT_E_UNSUPPORTED_FORMAT :text ="AUDCLNT_E_UNSUPPORTED_FORMAT"; break; - case AUDCLNT_E_INVALID_SIZE :text ="AUDCLNT_E_INVALID_SIZE"; break; - case AUDCLNT_E_DEVICE_IN_USE :text ="AUDCLNT_E_DEVICE_IN_USE"; break; - case AUDCLNT_E_BUFFER_OPERATION_PENDING :text ="AUDCLNT_E_BUFFER_OPERATION_PENDING"; break; - case AUDCLNT_E_THREAD_NOT_REGISTERED :text ="AUDCLNT_E_THREAD_NOT_REGISTERED"; break; - case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED :text ="AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break; - case AUDCLNT_E_ENDPOINT_CREATE_FAILED :text ="AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break; - case AUDCLNT_E_SERVICE_NOT_RUNNING :text ="AUDCLNT_E_SERVICE_NOT_RUNNING"; break; - // case AUDCLNT_E_CPUUSAGE_EXCEEDED :text ="AUDCLNT_E_CPUUSAGE_EXCEEDED"; break; - //Header error? - case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED :text ="AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break; - case AUDCLNT_E_EXCLUSIVE_MODE_ONLY :text ="AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break; - case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL :text ="AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break; - case AUDCLNT_E_EVENTHANDLE_NOT_SET :text ="AUDCLNT_E_EVENTHANDLE_NOT_SET"; break; - case AUDCLNT_E_INCORRECT_BUFFER_SIZE :text ="AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break; - case AUDCLNT_E_BUFFER_SIZE_ERROR :text ="AUDCLNT_E_BUFFER_SIZE_ERROR"; break; - case AUDCLNT_S_BUFFER_EMPTY :text ="AUDCLNT_S_BUFFER_EMPTY"; break; - case AUDCLNT_S_THREAD_ALREADY_REGISTERED :text ="AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break; + + switch (res) { + + case S_OK: + return; + break; + + case E_POINTER : + text ="E_POINTER"; + break; + + case E_INVALIDARG : + text ="E_INVALIDARG"; + break; + + case AUDCLNT_E_NOT_INITIALIZED : + text ="AUDCLNT_E_NOT_INITIALIZED"; + break; + + case AUDCLNT_E_ALREADY_INITIALIZED : + text ="AUDCLNT_E_ALREADY_INITIALIZED"; + break; + + case AUDCLNT_E_WRONG_ENDPOINT_TYPE : + text ="AUDCLNT_E_WRONG_ENDPOINT_TYPE"; + break; + + case AUDCLNT_E_DEVICE_INVALIDATED : + text ="AUDCLNT_E_DEVICE_INVALIDATED"; + break; + + case AUDCLNT_E_NOT_STOPPED : + text ="AUDCLNT_E_NOT_STOPPED"; + break; + + case AUDCLNT_E_BUFFER_TOO_LARGE : + text ="AUDCLNT_E_BUFFER_TOO_LARGE"; + break; + + case AUDCLNT_E_OUT_OF_ORDER : + text ="AUDCLNT_E_OUT_OF_ORDER"; + break; + + case AUDCLNT_E_UNSUPPORTED_FORMAT : + text ="AUDCLNT_E_UNSUPPORTED_FORMAT"; + break; + + case AUDCLNT_E_INVALID_SIZE : + text ="AUDCLNT_E_INVALID_SIZE"; + break; + + case AUDCLNT_E_DEVICE_IN_USE : + text ="AUDCLNT_E_DEVICE_IN_USE"; + break; + + case AUDCLNT_E_BUFFER_OPERATION_PENDING : + text ="AUDCLNT_E_BUFFER_OPERATION_PENDING"; + break; + + case AUDCLNT_E_THREAD_NOT_REGISTERED : + text ="AUDCLNT_E_THREAD_NOT_REGISTERED"; + break; + + case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED : + text ="AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; + break; + + case AUDCLNT_E_ENDPOINT_CREATE_FAILED : + text ="AUDCLNT_E_ENDPOINT_CREATE_FAILED"; + break; + + case AUDCLNT_E_SERVICE_NOT_RUNNING : + text ="AUDCLNT_E_SERVICE_NOT_RUNNING"; + break; + // case AUDCLNT_E_CPUUSAGE_EXCEEDED :text ="AUDCLNT_E_CPUUSAGE_EXCEEDED"; break; + //Header error? + + case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED : + text ="AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; + break; + + case AUDCLNT_E_EXCLUSIVE_MODE_ONLY : + text ="AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; + break; + + case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL : + text ="AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; + break; + + case AUDCLNT_E_EVENTHANDLE_NOT_SET : + text ="AUDCLNT_E_EVENTHANDLE_NOT_SET"; + break; + + case AUDCLNT_E_INCORRECT_BUFFER_SIZE : + text ="AUDCLNT_E_INCORRECT_BUFFER_SIZE"; + break; + + case AUDCLNT_E_BUFFER_SIZE_ERROR : + text ="AUDCLNT_E_BUFFER_SIZE_ERROR"; + break; + + case AUDCLNT_S_BUFFER_EMPTY : + text ="AUDCLNT_S_BUFFER_EMPTY"; + break; + + case AUDCLNT_S_THREAD_ALREADY_REGISTERED : + text ="AUDCLNT_S_THREAD_ALREADY_REGISTERED"; + break; + default: text =" dunno!"; return ; - break; + break; } - PRINT(("WASAPI ERROR HRESULT: 0x%X : %s\n",res,text)); + + PRINT ( ("WASAPI ERROR HRESULT: 0x%X : %s\n",res,text)); } inline double -nano100ToMillis(const REFERENCE_TIME &ref){ +nano100ToMillis (const REFERENCE_TIME &ref) +{ // 1 nano = 0.000000001 seconds //100 nano = 0.0000001 seconds //100 nano = 0.0001 milliseconds - return ((double)ref)*0.0001; + return ( (double) ref) *0.0001; } inline double -nano100ToSeconds(const REFERENCE_TIME &ref){ +nano100ToSeconds (const REFERENCE_TIME &ref) +{ // 1 nano = 0.000000001 seconds //100 nano = 0.0000001 seconds //100 nano = 0.0001 milliseconds - return ((double)ref)*0.0000001; + return ( (double) ref) *0.0000001; } #ifndef IF_FAILED_JUMP @@ -308,11 +391,11 @@ nano100ToSeconds(const REFERENCE_TIME &ref){ //AVRT is the new "multimedia schedulling stuff" -typedef BOOL (WINAPI *FAvRtCreateThreadOrderingGroup) (PHANDLE,PLARGE_INTEGER,GUID*,PLARGE_INTEGER); -typedef BOOL (WINAPI *FAvRtDeleteThreadOrderingGroup) (HANDLE); -typedef BOOL (WINAPI *FAvRtWaitOnThreadOrderingGroup) (HANDLE); -typedef HANDLE (WINAPI *FAvSetMmThreadCharacteristics) (LPCTSTR,LPDWORD); -typedef BOOL (WINAPI *FAvSetMmThreadPriority) (HANDLE,AVRT_PRIORITY); +typedef BOOL (WINAPI *FAvRtCreateThreadOrderingGroup) (PHANDLE,PLARGE_INTEGER,GUID*,PLARGE_INTEGER); +typedef BOOL (WINAPI *FAvRtDeleteThreadOrderingGroup) (HANDLE); +typedef BOOL (WINAPI *FAvRtWaitOnThreadOrderingGroup) (HANDLE); +typedef HANDLE (WINAPI *FAvSetMmThreadCharacteristics) (LPCTSTR,LPDWORD); +typedef BOOL (WINAPI *FAvSetMmThreadPriority) (HANDLE,AVRT_PRIORITY); HMODULE hDInputDLL = 0; FAvRtCreateThreadOrderingGroup pAvRtCreateThreadOrderingGroup=0; @@ -330,51 +413,60 @@ FAvSetMmThreadPriority pAvSetMmThreadPriority=0; return false; \ } \ } \ - + bool -setupAVRT(){ +setupAVRT() +{ - hDInputDLL = LoadLibraryA("avrt.dll"); - if(hDInputDLL == NULL) + hDInputDLL = LoadLibraryA ("avrt.dll"); + + if (hDInputDLL == NULL) return false; - setupPTR(pAvRtCreateThreadOrderingGroup, FAvRtCreateThreadOrderingGroup, "AvRtCreateThreadOrderingGroup"); - setupPTR(pAvRtDeleteThreadOrderingGroup, FAvRtDeleteThreadOrderingGroup, "AvRtDeleteThreadOrderingGroup"); - setupPTR(pAvRtWaitOnThreadOrderingGroup, FAvRtWaitOnThreadOrderingGroup, "AvRtWaitOnThreadOrderingGroup"); - setupPTR(pAvSetMmThreadCharacteristics, FAvSetMmThreadCharacteristics, "AvSetMmThreadCharacteristicsA"); - setupPTR(pAvSetMmThreadPriority, FAvSetMmThreadPriority, "AvSetMmThreadPriority"); + setupPTR (pAvRtCreateThreadOrderingGroup, FAvRtCreateThreadOrderingGroup, "AvRtCreateThreadOrderingGroup"); + + setupPTR (pAvRtDeleteThreadOrderingGroup, FAvRtDeleteThreadOrderingGroup, "AvRtDeleteThreadOrderingGroup"); + + setupPTR (pAvRtWaitOnThreadOrderingGroup, FAvRtWaitOnThreadOrderingGroup, "AvRtWaitOnThreadOrderingGroup"); + + setupPTR (pAvSetMmThreadCharacteristics, FAvSetMmThreadCharacteristics, "AvSetMmThreadCharacteristicsA"); + + setupPTR (pAvSetMmThreadPriority, FAvSetMmThreadPriority, "AvSetMmThreadPriority"); return true; } -PaError PaWinWasapi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex ) +PaError PaWinWasapi_Initialize (PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex) { - if (!setupAVRT()){ - PRINT(("Windows WASAPI : No AVRT! (not VISTA?)")); + if (!setupAVRT()) { + PRINT ( ("Windows WASAPI : No AVRT! (not VISTA?)")); return paNoError; } - CoInitialize(NULL); + CoInitialize (NULL); PaError result = paNoError; PaWinWasapiHostApiRepresentation *paWasapi; PaDeviceInfo *deviceInfoArray; - paWasapi = (PaWinWasapiHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaWinWasapiHostApiRepresentation) ); - if( !paWasapi ){ + paWasapi = (PaWinWasapiHostApiRepresentation*) PaUtil_AllocateMemory (sizeof (PaWinWasapiHostApiRepresentation)); + + if (!paWasapi) { result = paInsufficientMemory; goto error; } paWasapi->allocations = PaUtil_CreateAllocationGroup(); - if( !paWasapi->allocations ){ + + if (!paWasapi->allocations) { result = paInsufficientMemory; goto error; } *hostApi = &paWasapi->inheritedHostApiRep; + (*hostApi)->info.structVersion = 1; (*hostApi)->info.type = paWASAPI; (*hostApi)->info.name = "Windows WASAPI"; @@ -387,170 +479,181 @@ PaError PaWinWasapi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApi IMMDeviceCollection* spEndpoints=0; paWasapi->enumerator = 0; - hResult = CoCreateInstance( - __uuidof(MMDeviceEnumerator), NULL,CLSCTX_INPROC_SERVER, - __uuidof(IMMDeviceEnumerator), - (void**)&paWasapi->enumerator); + hResult = CoCreateInstance ( + __uuidof (MMDeviceEnumerator), NULL,CLSCTX_INPROC_SERVER, + __uuidof (IMMDeviceEnumerator), + (void**) &paWasapi->enumerator); - IF_FAILED_JUMP(hResult, error); + IF_FAILED_JUMP (hResult, error); //getting default device ids in the eMultimedia "role" { { IMMDevice* defaultRenderer=0; - hResult = paWasapi->enumerator->GetDefaultAudioEndpoint(eRender, eMultimedia, &defaultRenderer); - IF_FAILED_JUMP(hResult, error); + hResult = paWasapi->enumerator->GetDefaultAudioEndpoint (eRender, eMultimedia, &defaultRenderer); + IF_FAILED_JUMP (hResult, error); WCHAR* pszDeviceId = NULL; - hResult = defaultRenderer->GetId(&pszDeviceId); - IF_FAILED_JUMP(hResult, error); - StringCchCopyW(paWasapi->defaultRenderer, MAX_STR_LEN-1, pszDeviceId); - CoTaskMemFree(pszDeviceId); + hResult = defaultRenderer->GetId (&pszDeviceId); + IF_FAILED_JUMP (hResult, error); + StringCchCopyW (paWasapi->defaultRenderer, MAX_STR_LEN-1, pszDeviceId); + CoTaskMemFree (pszDeviceId); defaultRenderer->Release(); } { IMMDevice* defaultCapturer=0; - hResult = paWasapi->enumerator->GetDefaultAudioEndpoint(eCapture, eMultimedia, &defaultCapturer); - IF_FAILED_JUMP(hResult, error); + hResult = paWasapi->enumerator->GetDefaultAudioEndpoint (eCapture, eMultimedia, &defaultCapturer); + IF_FAILED_JUMP (hResult, error); WCHAR* pszDeviceId = NULL; - hResult = defaultCapturer->GetId(&pszDeviceId); - IF_FAILED_JUMP(hResult, error); - StringCchCopyW(paWasapi->defaultCapturer, MAX_STR_LEN-1, pszDeviceId); - CoTaskMemFree(pszDeviceId); + hResult = defaultCapturer->GetId (&pszDeviceId); + IF_FAILED_JUMP (hResult, error); + StringCchCopyW (paWasapi->defaultCapturer, MAX_STR_LEN-1, pszDeviceId); + CoTaskMemFree (pszDeviceId); defaultCapturer->Release(); } } - hResult = paWasapi->enumerator->EnumAudioEndpoints(eAll, DEVICE_STATE_ACTIVE, &spEndpoints); - IF_FAILED_JUMP(hResult, error); + hResult = paWasapi->enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &spEndpoints); + IF_FAILED_JUMP (hResult, error); - hResult = spEndpoints->GetCount(&paWasapi->deviceCount); - IF_FAILED_JUMP(hResult, error); + hResult = spEndpoints->GetCount (&paWasapi->deviceCount); + IF_FAILED_JUMP (hResult, error); paWasapi->devInfo = new PaWinWasapiDeviceInfo[paWasapi->deviceCount]; { for (size_t step=0;step<paWasapi->deviceCount;++step) - memset(&paWasapi->devInfo[step],0,sizeof(PaWinWasapiDeviceInfo)); + memset (&paWasapi->devInfo[step],0,sizeof (PaWinWasapiDeviceInfo)); } - if( paWasapi->deviceCount > 0 ) - { - (*hostApi)->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory( - paWasapi->allocations, sizeof(PaDeviceInfo*) * paWasapi->deviceCount ); - if( !(*hostApi)->deviceInfos ){ + if (paWasapi->deviceCount > 0) { + (*hostApi)->deviceInfos = (PaDeviceInfo**) PaUtil_GroupAllocateMemory ( + paWasapi->allocations, sizeof (PaDeviceInfo*) * paWasapi->deviceCount); + + if (! (*hostApi)->deviceInfos) { result = paInsufficientMemory; goto error; } /* allocate all device info structs in a contiguous block */ - deviceInfoArray = (PaDeviceInfo*)PaUtil_GroupAllocateMemory( - paWasapi->allocations, sizeof(PaDeviceInfo) * paWasapi->deviceCount ); - if( !deviceInfoArray ){ + deviceInfoArray = (PaDeviceInfo*) PaUtil_GroupAllocateMemory ( + paWasapi->allocations, sizeof (PaDeviceInfo) * paWasapi->deviceCount); + + if (!deviceInfoArray) { result = paInsufficientMemory; goto error; } - for( UINT i=0; i < paWasapi->deviceCount; ++i ){ + for (UINT i=0; i < paWasapi->deviceCount; ++i) { - PA_DEBUG(("i:%d\n",i)); + PA_DEBUG ( ("i:%d\n",i)); PaDeviceInfo *deviceInfo = &deviceInfoArray[i]; deviceInfo->structVersion = 2; deviceInfo->hostApi = hostApiIndex; - hResult = spEndpoints->Item(i, &paWasapi->devInfo[i].device); - IF_FAILED_JUMP(hResult, error); + hResult = spEndpoints->Item (i, &paWasapi->devInfo[i].device); + IF_FAILED_JUMP (hResult, error); //getting ID { WCHAR* pszDeviceId = NULL; - hResult = paWasapi->devInfo[i].device->GetId(&pszDeviceId); - IF_FAILED_JUMP(hResult, error); - StringCchCopyW(paWasapi->devInfo[i].szDeviceID, MAX_STR_LEN-1, pszDeviceId); - CoTaskMemFree(pszDeviceId); + hResult = paWasapi->devInfo[i].device->GetId (&pszDeviceId); + IF_FAILED_JUMP (hResult, error); + StringCchCopyW (paWasapi->devInfo[i].szDeviceID, MAX_STR_LEN-1, pszDeviceId); + CoTaskMemFree (pszDeviceId); - if (lstrcmpW(paWasapi->devInfo[i].szDeviceID, paWasapi->defaultCapturer)==0){ + if (lstrcmpW (paWasapi->devInfo[i].szDeviceID, paWasapi->defaultCapturer) ==0) { //we found the default input! (*hostApi)->info.defaultInputDevice = (*hostApi)->info.deviceCount; } - if (lstrcmpW(paWasapi->devInfo[i].szDeviceID, paWasapi->defaultRenderer)==0){ + + if (lstrcmpW (paWasapi->devInfo[i].szDeviceID, paWasapi->defaultRenderer) ==0) { //we found the default output! (*hostApi)->info.defaultOutputDevice = (*hostApi)->info.deviceCount; } } DWORD state=0; - hResult = paWasapi->devInfo[i].device->GetState(&paWasapi->devInfo[i].state); - IF_FAILED_JUMP(hResult, error); + hResult = paWasapi->devInfo[i].device->GetState (&paWasapi->devInfo[i].state); + IF_FAILED_JUMP (hResult, error); - if (paWasapi->devInfo[i].state != DEVICE_STATE_ACTIVE){ - PRINT(("WASAPI device:%d is not currently available (state:%d)\n",i,state)); + if (paWasapi->devInfo[i].state != DEVICE_STATE_ACTIVE) { + PRINT ( ("WASAPI device:%d is not currently available (state:%d)\n",i,state)); //spDevice->Release(); //continue; } { IPropertyStore* spProperties; - hResult = paWasapi->devInfo[i].device->OpenPropertyStore(STGM_READ, &spProperties); - IF_FAILED_JUMP(hResult, error); + hResult = paWasapi->devInfo[i].device->OpenPropertyStore (STGM_READ, &spProperties); + IF_FAILED_JUMP (hResult, error); //getting "Friendly" Name { PROPVARIANT value; - PropVariantInit(&value); - hResult = spProperties->GetValue(PKEY_Device_FriendlyName, &value); - IF_FAILED_JUMP(hResult, error); + PropVariantInit (&value); + hResult = spProperties->GetValue (PKEY_Device_FriendlyName, &value); + IF_FAILED_JUMP (hResult, error); deviceInfo->name = 0; - char* deviceName = (char*)PaUtil_GroupAllocateMemory( paWasapi->allocations, MAX_STR_LEN + 1 ); - if( !deviceName ){ + char* deviceName = (char*) PaUtil_GroupAllocateMemory (paWasapi->allocations, MAX_STR_LEN + 1); + + if (!deviceName) { result = paInsufficientMemory; goto error; } - if (value.pwszVal) - wcstombs(deviceName, value.pwszVal,MAX_STR_LEN-1); //todo proper size - else{ - sprintf(deviceName,"baddev%d",i); - } + + if (value.pwszVal) + wcstombs (deviceName, value.pwszVal,MAX_STR_LEN-1); //todo proper size + else { + sprintf (deviceName,"baddev%d",i); + } deviceInfo->name = deviceName; - PropVariantClear(&value); + + PropVariantClear (&value); } #if 0 DWORD numProps = 0; - hResult = spProperties->GetCount(&numProps); - IF_FAILED_JUMP(hResult, error); + hResult = spProperties->GetCount (&numProps); + IF_FAILED_JUMP (hResult, error); { - for (DWORD i=0;i<numProps;++i){ + for (DWORD i=0;i<numProps;++i) { PROPERTYKEY pkey; - hResult = spProperties->GetAt(i,&pkey); + hResult = spProperties->GetAt (i,&pkey); PROPVARIANT value; - PropVariantInit(&value); - hResult = spProperties->GetValue(pkey, &value); + PropVariantInit (&value); + hResult = spProperties->GetValue (pkey, &value); + + switch (value.vt) { - switch(value.vt){ case 11: - PRINT(("property*%u*\n",value.ulVal)); - break; + PRINT ( ("property*%u*\n",value.ulVal)); + break; + case 19: - PRINT(("property*%d*\n",value.boolVal)); - break; - case 31: - { + PRINT ( ("property*%d*\n",value.boolVal)); + break; + + case 31: { char temp[512]; - wcstombs(temp, value.pwszVal,MAX_STR_LEN-1); - PRINT(("property*%s*\n",temp)); + wcstombs (temp, value.pwszVal,MAX_STR_LEN-1); + PRINT ( ("property*%s*\n",temp)); } + break; - default:break; + + default: + break; } - PropVariantClear(&value); + PropVariantClear (&value); } } + #endif /* These look interresting... but they are undocumented @@ -567,9 +670,10 @@ PaError PaWinWasapi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApi //getting the Endpoint data { IMMEndpoint *endpoint=0; - hResult = paWasapi->devInfo[i].device->QueryInterface(__uuidof(IMMEndpoint),(void **)&endpoint); - if (SUCCEEDED(hResult)){ - hResult = endpoint->GetDataFlow(&paWasapi->devInfo[i].flow); + hResult = paWasapi->devInfo[i].device->QueryInterface (__uuidof (IMMEndpoint), (void **) &endpoint); + + if (SUCCEEDED (hResult)) { + hResult = endpoint->GetDataFlow (&paWasapi->devInfo[i].flow); endpoint->Release(); } } @@ -579,56 +683,60 @@ PaError PaWinWasapi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApi { IAudioClient *myClient=0; - hResult = paWasapi->devInfo[i].device->Activate(__uuidof(IAudioClient), CLSCTX_INPROC_SERVER, NULL, (void**)&myClient); - IF_FAILED_JUMP(hResult, error); + hResult = paWasapi->devInfo[i].device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, NULL, (void**) &myClient); + IF_FAILED_JUMP (hResult, error); - hResult = myClient->GetDevicePeriod( - &paWasapi->devInfo[i].DefaultDevicePeriod, - &paWasapi->devInfo[i].MinimumDevicePeriod); - IF_FAILED_JUMP(hResult, error); + hResult = myClient->GetDevicePeriod ( + &paWasapi->devInfo[i].DefaultDevicePeriod, + &paWasapi->devInfo[i].MinimumDevicePeriod); + IF_FAILED_JUMP (hResult, error); - hResult = myClient->GetMixFormat(&paWasapi->devInfo[i].MixFormat); + hResult = myClient->GetMixFormat (&paWasapi->devInfo[i].MixFormat); - if (hResult != S_OK){ - /*davidv: this happened with my hardware, previously for that same device in DirectSound: - Digital Output (Realtek AC'97 Audio)'s GUID: {0x38f2cf50,0x7b4c,0x4740,0x86,0xeb,0xd4,0x38,0x66,0xd8,0xc8, 0x9f} - so something must be _really_ wrong with this device, TODO handle this better. We kind of need GetMixFormat*/ - logAUDCLNT_E(hResult); - goto error; - } + if (hResult != S_OK) { + /*davidv: this happened with my hardware, previously for that same device in DirectSound: + Digital Output (Realtek AC'97 Audio)'s GUID: {0x38f2cf50,0x7b4c,0x4740,0x86,0xeb,0xd4,0x38,0x66,0xd8,0xc8, 0x9f} + so something must be _really_ wrong with this device, TODO handle this better. We kind of need GetMixFormat*/ + logAUDCLNT_E (hResult); + goto error; + } myClient->Release(); } //we can now fill in portaudio device data deviceInfo->maxInputChannels = 0; //for now + deviceInfo->maxOutputChannels = 0; //for now - switch(paWasapi->devInfo[i].flow){ + switch (paWasapi->devInfo[i].flow) { + case eRender: //hum not exaclty maximum, more like "default" deviceInfo->maxOutputChannels = paWasapi->devInfo[i].MixFormat->nChannels; - deviceInfo->defaultHighOutputLatency = nano100ToSeconds(paWasapi->devInfo[i].DefaultDevicePeriod); - deviceInfo->defaultLowOutputLatency = nano100ToSeconds(paWasapi->devInfo[i].MinimumDevicePeriod); - break; + deviceInfo->defaultHighOutputLatency = nano100ToSeconds (paWasapi->devInfo[i].DefaultDevicePeriod); + deviceInfo->defaultLowOutputLatency = nano100ToSeconds (paWasapi->devInfo[i].MinimumDevicePeriod); + break; + case eCapture: //hum not exaclty maximum, more like "default" deviceInfo->maxInputChannels = paWasapi->devInfo[i].MixFormat->nChannels; - deviceInfo->defaultHighInputLatency = nano100ToSeconds(paWasapi->devInfo[i].DefaultDevicePeriod); - deviceInfo->defaultLowInputLatency = nano100ToSeconds(paWasapi->devInfo[i].MinimumDevicePeriod); - break; + deviceInfo->defaultHighInputLatency = nano100ToSeconds (paWasapi->devInfo[i].DefaultDevicePeriod); + deviceInfo->defaultLowInputLatency = nano100ToSeconds (paWasapi->devInfo[i].MinimumDevicePeriod); + break; + default: - PRINT(("WASAPI device:%d bad Data FLow! \n",i)); + PRINT ( ("WASAPI device:%d bad Data FLow! \n",i)); goto error; - break; + break; } - deviceInfo->defaultSampleRate = (double)paWasapi->devInfo[i].MixFormat->nSamplesPerSec; + deviceInfo->defaultSampleRate = (double) paWasapi->devInfo[i].MixFormat->nSamplesPerSec; (*hostApi)->deviceInfos[i] = deviceInfo; - ++(*hostApi)->info.deviceCount; + ++ (*hostApi)->info.deviceCount; } } @@ -638,16 +746,16 @@ PaError PaWinWasapi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApi (*hostApi)->OpenStream = OpenStream; (*hostApi)->IsFormatSupported = IsFormatSupported; - PaUtil_InitializeStreamInterface( &paWasapi->callbackStreamInterface, CloseStream, StartStream, + PaUtil_InitializeStreamInterface (&paWasapi->callbackStreamInterface, CloseStream, StartStream, StopStream, AbortStream, IsStreamStopped, IsStreamActive, GetStreamTime, GetStreamCpuLoad, PaUtil_DummyRead, PaUtil_DummyWrite, - PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable ); + PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable); - PaUtil_InitializeStreamInterface( &paWasapi->blockingStreamInterface, CloseStream, StartStream, + PaUtil_InitializeStreamInterface (&paWasapi->blockingStreamInterface, CloseStream, StartStream, StopStream, AbortStream, IsStreamStopped, IsStreamActive, GetStreamTime, PaUtil_DummyGetCpuLoad, - ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable ); + ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable); return result; @@ -659,92 +767,105 @@ error: if (paWasapi->enumerator) paWasapi->enumerator->Release(); - if( paWasapi ) - { - if( paWasapi->allocations ) - { - PaUtil_FreeAllAllocations( paWasapi->allocations ); - PaUtil_DestroyAllocationGroup( paWasapi->allocations ); + if (paWasapi) { + if (paWasapi->allocations) { + PaUtil_FreeAllAllocations (paWasapi->allocations); + PaUtil_DestroyAllocationGroup (paWasapi->allocations); } - PaUtil_FreeMemory( paWasapi ); + PaUtil_FreeMemory (paWasapi); } + return result; } -static void Terminate( struct PaUtilHostApiRepresentation *hostApi ) +static void Terminate (struct PaUtilHostApiRepresentation *hostApi) { - PaWinWasapiHostApiRepresentation *paWasapi = (PaWinWasapiHostApiRepresentation*)hostApi; + PaWinWasapiHostApiRepresentation *paWasapi = (PaWinWasapiHostApiRepresentation*) hostApi; paWasapi->enumerator->Release(); - for (UINT i=0;i<paWasapi->deviceCount;++i){ + for (UINT i=0;i<paWasapi->deviceCount;++i) { PaWinWasapiDeviceInfo *info = &paWasapi->devInfo[i]; if (info->device) info->device->Release(); if (info->MixFormat) - CoTaskMemFree(info->MixFormat); + CoTaskMemFree (info->MixFormat); } + delete [] paWasapi->devInfo; CoUninitialize(); - if( paWasapi->allocations ){ - PaUtil_FreeAllAllocations( paWasapi->allocations ); - PaUtil_DestroyAllocationGroup( paWasapi->allocations ); + if (paWasapi->allocations) { + PaUtil_FreeAllAllocations (paWasapi->allocations); + PaUtil_DestroyAllocationGroup (paWasapi->allocations); } - PaUtil_FreeMemory( paWasapi ); + PaUtil_FreeMemory (paWasapi); } static void -LogWAVEFORMATEXTENSIBLE(const WAVEFORMATEXTENSIBLE *in){ - - const WAVEFORMATEX *old = (WAVEFORMATEX *)in; - - switch (old->wFormatTag){ - case WAVE_FORMAT_EXTENSIBLE:{ - - PRINT(("wFormatTag=WAVE_FORMAT_EXTENSIBLE\n")); - - if (in->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT){ - PRINT(("SubFormat=KSDATAFORMAT_SUBTYPE_IEEE_FLOAT\n")); - } - else if (in->SubFormat == KSDATAFORMAT_SUBTYPE_PCM){ - PRINT(("SubFormat=KSDATAFORMAT_SUBTYPE_PCM\n")); - } - else{ - PRINT(("SubFormat=CUSTOM GUID{%d:%d:%d:%d%d%d%d%d%d%d%d}\n", - in->SubFormat.Data1, - in->SubFormat.Data2, - in->SubFormat.Data3, - (int)in->SubFormat.Data4[0], - (int)in->SubFormat.Data4[1], - (int)in->SubFormat.Data4[2], - (int)in->SubFormat.Data4[3], - (int)in->SubFormat.Data4[4], - (int)in->SubFormat.Data4[5], - (int)in->SubFormat.Data4[6], - (int)in->SubFormat.Data4[7])); - } - PRINT(("Samples.wValidBitsPerSample=%d\n", in->Samples.wValidBitsPerSample)); - PRINT(("dwChannelMask=0x%X\n",in->dwChannelMask)); - }break; - - case WAVE_FORMAT_PCM: PRINT(("wFormatTag=WAVE_FORMAT_PCM\n")); break; - case WAVE_FORMAT_IEEE_FLOAT: PRINT(("wFormatTag=WAVE_FORMAT_IEEE_FLOAT\n")); break; - default : PRINT(("wFormatTag=UNKNOWN(%d)\n",old->wFormatTag)); break; - } - - PRINT(("nChannels =%d\n",old->nChannels)); - PRINT(("nSamplesPerSec =%d\n",old->nSamplesPerSec)); - PRINT(("nAvgBytesPerSec=%d\n",old->nAvgBytesPerSec)); - PRINT(("nBlockAlign =%d\n",old->nBlockAlign)); - PRINT(("wBitsPerSample =%d\n",old->wBitsPerSample)); - PRINT(("cbSize =%d\n",old->cbSize)); +LogWAVEFORMATEXTENSIBLE (const WAVEFORMATEXTENSIBLE *in) +{ + + const WAVEFORMATEX *old = (WAVEFORMATEX *) in; + + switch (old->wFormatTag) { + + case WAVE_FORMAT_EXTENSIBLE: { + + PRINT ( ("wFormatTag=WAVE_FORMAT_EXTENSIBLE\n")); + + if (in->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT) { + PRINT ( ("SubFormat=KSDATAFORMAT_SUBTYPE_IEEE_FLOAT\n")); + } else if (in->SubFormat == KSDATAFORMAT_SUBTYPE_PCM) { + PRINT ( ("SubFormat=KSDATAFORMAT_SUBTYPE_PCM\n")); + } else { + PRINT ( ("SubFormat=CUSTOM GUID{%d:%d:%d:%d%d%d%d%d%d%d%d}\n", + in->SubFormat.Data1, + in->SubFormat.Data2, + in->SubFormat.Data3, + (int) in->SubFormat.Data4[0], + (int) in->SubFormat.Data4[1], + (int) in->SubFormat.Data4[2], + (int) in->SubFormat.Data4[3], + (int) in->SubFormat.Data4[4], + (int) in->SubFormat.Data4[5], + (int) in->SubFormat.Data4[6], + (int) in->SubFormat.Data4[7])); + } + + PRINT ( ("Samples.wValidBitsPerSample=%d\n", in->Samples.wValidBitsPerSample)); + + PRINT ( ("dwChannelMask=0x%X\n",in->dwChannelMask)); + } + + break; + + case WAVE_FORMAT_PCM: + PRINT ( ("wFormatTag=WAVE_FORMAT_PCM\n")); + break; + + case WAVE_FORMAT_IEEE_FLOAT: + PRINT ( ("wFormatTag=WAVE_FORMAT_IEEE_FLOAT\n")); + break; + + default : + PRINT ( ("wFormatTag=UNKNOWN(%d)\n",old->wFormatTag)); + break; + } + + PRINT ( ("nChannels =%d\n",old->nChannels)); + + PRINT ( ("nSamplesPerSec =%d\n",old->nSamplesPerSec)); + PRINT ( ("nAvgBytesPerSec=%d\n",old->nAvgBytesPerSec)); + PRINT ( ("nBlockAlign =%d\n",old->nBlockAlign)); + PRINT ( ("wBitsPerSample =%d\n",old->wBitsPerSample)); + PRINT ( ("cbSize =%d\n",old->cbSize)); } @@ -753,53 +874,82 @@ LogWAVEFORMATEXTENSIBLE(const WAVEFORMATEXTENSIBLE *in){ WAVEFORMATXXX is always interleaved */ static PaSampleFormat -waveformatToPaFormat(const WAVEFORMATEXTENSIBLE *in){ +waveformatToPaFormat (const WAVEFORMATEXTENSIBLE *in) +{ - const WAVEFORMATEX *old = (WAVEFORMATEX*)in; + const WAVEFORMATEX *old = (WAVEFORMATEX*) in; - switch (old->wFormatTag){ + switch (old->wFormatTag) { - case WAVE_FORMAT_EXTENSIBLE: - { - if (in->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT){ + case WAVE_FORMAT_EXTENSIBLE: { + if (in->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT) { if (in->Samples.wValidBitsPerSample == 32) return paFloat32; else return paCustomFormat; - } - else if (in->SubFormat == KSDATAFORMAT_SUBTYPE_PCM){ - switch (old->wBitsPerSample){ - case 32: return paInt32; break; - case 24: return paInt24;break; - case 8: return paUInt8;break; - case 16: return paInt16;break; - default: return paCustomFormat;break; + } else if (in->SubFormat == KSDATAFORMAT_SUBTYPE_PCM) { + switch (old->wBitsPerSample) { + + case 32: + return paInt32; + break; + + case 24: + return paInt24; + break; + + case 8: + return paUInt8; + break; + + case 16: + return paInt16; + break; + + default: + return paCustomFormat; + break; } - } - else + } else return paCustomFormat; } + break; case WAVE_FORMAT_IEEE_FLOAT: return paFloat32; - break; + break; - case WAVE_FORMAT_PCM: - { - switch (old->wBitsPerSample){ - case 32: return paInt32; break; - case 24: return paInt24;break; - case 8: return paUInt8;break; - case 16: return paInt16;break; - default: return paCustomFormat;break; + case WAVE_FORMAT_PCM: { + switch (old->wBitsPerSample) { + + case 32: + return paInt32; + break; + + case 24: + return paInt24; + break; + + case 8: + return paUInt8; + break; + + case 16: + return paInt16; + break; + + default: + return paCustomFormat; + break; } } + break; default: return paCustomFormat; - break; + break; } return paCustomFormat; @@ -808,56 +958,96 @@ waveformatToPaFormat(const WAVEFORMATEXTENSIBLE *in){ static PaError -waveformatFromParams(WAVEFORMATEXTENSIBLE*wavex, - const PaStreamParameters * params, - double sampleRate){ +waveformatFromParams (WAVEFORMATEXTENSIBLE*wavex, + const PaStreamParameters * params, + double sampleRate) +{ size_t bytesPerSample = 0; - switch( params->sampleFormat & ~paNonInterleaved ){ + + switch (params->sampleFormat & ~paNonInterleaved) { + case paFloat32: - case paInt32: bytesPerSample=4;break; - case paInt16: bytesPerSample=2;break; - case paInt24: bytesPerSample=3;break; + + case paInt32: + bytesPerSample=4; + break; + + case paInt16: + bytesPerSample=2; + break; + + case paInt24: + bytesPerSample=3; + break; + case paInt8: - case paUInt8: bytesPerSample=1;break; + + case paUInt8: + bytesPerSample=1; + break; + case paCustomFormat: - default: return paSampleFormatNotSupported;break; + + default: + return paSampleFormatNotSupported; + break; } - memset(wavex,0,sizeof(WAVEFORMATEXTENSIBLE)); + memset (wavex,0,sizeof (WAVEFORMATEXTENSIBLE)); - WAVEFORMATEX *old = (WAVEFORMATEX *)wavex; - old->nChannels = (WORD)params->channelCount; - old->nSamplesPerSec = (DWORD)sampleRate; - old->wBitsPerSample = (WORD)(bytesPerSample*8); - old->nAvgBytesPerSec = (DWORD)(old->nSamplesPerSec * old->nChannels * bytesPerSample); - old->nBlockAlign = (WORD)(old->nChannels * bytesPerSample); + WAVEFORMATEX *old = (WAVEFORMATEX *) wavex; + old->nChannels = (WORD) params->channelCount; + old->nSamplesPerSec = (DWORD) sampleRate; + old->wBitsPerSample = (WORD) (bytesPerSample*8); + old->nAvgBytesPerSec = (DWORD) (old->nSamplesPerSec * old->nChannels * bytesPerSample); + old->nBlockAlign = (WORD) (old->nChannels * bytesPerSample); //WAVEFORMATEX - if (params->channelCount <=2 && (bytesPerSample == 2 || bytesPerSample == 1)){ + + if (params->channelCount <=2 && (bytesPerSample == 2 || bytesPerSample == 1)) { old->cbSize = 0; old->wFormatTag = WAVE_FORMAT_PCM; } + //WAVEFORMATEXTENSIBLE - else{ + else { old->wFormatTag = WAVE_FORMAT_EXTENSIBLE; old->cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX); - if ((params->sampleFormat & ~paNonInterleaved) == paFloat32) + if ( (params->sampleFormat & ~paNonInterleaved) == paFloat32) wavex->SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT; else wavex->SubFormat = KSDATAFORMAT_SUBTYPE_PCM; wavex->Samples.wValidBitsPerSample = old->wBitsPerSample; //no extra padding! - switch(params->channelCount){ - case 1: wavex->dwChannelMask = SPEAKER_FRONT_CENTER; break; - case 2: wavex->dwChannelMask = 0x1 | 0x2; break; - case 4: wavex->dwChannelMask = 0x1 | 0x2 | 0x10 | 0x20; break; - case 6: wavex->dwChannelMask = 0x1 | 0x2 | 0x4 | 0x8 | 0x10 | 0x20; break; - case 8: wavex->dwChannelMask = 0x1 | 0x2 | 0x4 | 0x8 | 0x10 | 0x20 | 0x40 | 0x80; break; - default: wavex->dwChannelMask = 0; break; + switch (params->channelCount) { + + case 1: + wavex->dwChannelMask = SPEAKER_FRONT_CENTER; + break; + + case 2: + wavex->dwChannelMask = 0x1 | 0x2; + break; + + case 4: + wavex->dwChannelMask = 0x1 | 0x2 | 0x10 | 0x20; + break; + + case 6: + wavex->dwChannelMask = 0x1 | 0x2 | 0x4 | 0x8 | 0x10 | 0x20; + break; + + case 8: + wavex->dwChannelMask = 0x1 | 0x2 | 0x4 | 0x8 | 0x10 | 0x20 | 0x40 | 0x80; + break; + + default: + wavex->dwChannelMask = 0; + break; } } @@ -876,51 +1066,47 @@ waveformatFromParams(WAVEFORMATEXTENSIBLE*wavex, #define paInt16 ((PaSampleFormat) 0x00000008) */ //lifted from pa_wdmks -static void wasapiFillWFEXT( WAVEFORMATEXTENSIBLE* pwfext, PaSampleFormat sampleFormat, double sampleRate, int channelCount) +static void wasapiFillWFEXT (WAVEFORMATEXTENSIBLE* pwfext, PaSampleFormat sampleFormat, double sampleRate, int channelCount) { - PA_DEBUG(( "sampleFormat = %lx\n" , sampleFormat )); - PA_DEBUG(( "sampleRate = %f\n" , sampleRate )); - PA_DEBUG(( "chanelCount = %d\n", channelCount )); + PA_DEBUG ( ("sampleFormat = %lx\n" , sampleFormat)); + PA_DEBUG ( ("sampleRate = %f\n" , sampleRate)); + PA_DEBUG ( ("chanelCount = %d\n", channelCount)); pwfext->Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE; pwfext->Format.nChannels = channelCount; - pwfext->Format.nSamplesPerSec = (int)sampleRate; - if(channelCount == 1) + pwfext->Format.nSamplesPerSec = (int) sampleRate; + + if (channelCount == 1) pwfext->dwChannelMask = KSAUDIO_SPEAKER_DIRECTOUT; else pwfext->dwChannelMask = KSAUDIO_SPEAKER_STEREO; - if(sampleFormat == paFloat32) - { + + if (sampleFormat == paFloat32) { pwfext->Format.nBlockAlign = channelCount * 4; pwfext->Format.wBitsPerSample = 32; - pwfext->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX); + pwfext->Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE)-sizeof (WAVEFORMATEX); pwfext->Samples.wValidBitsPerSample = 32; pwfext->SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT; - } - else if(sampleFormat == paInt32) - { + } else if (sampleFormat == paInt32) { pwfext->Format.nBlockAlign = channelCount * 4; pwfext->Format.wBitsPerSample = 32; - pwfext->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX); + pwfext->Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE)-sizeof (WAVEFORMATEX); pwfext->Samples.wValidBitsPerSample = 32; pwfext->SubFormat = KSDATAFORMAT_SUBTYPE_PCM; - } - else if(sampleFormat == paInt24) - { + } else if (sampleFormat == paInt24) { pwfext->Format.nBlockAlign = channelCount * 3; pwfext->Format.wBitsPerSample = 24; - pwfext->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX); + pwfext->Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE)-sizeof (WAVEFORMATEX); pwfext->Samples.wValidBitsPerSample = 24; pwfext->SubFormat = KSDATAFORMAT_SUBTYPE_PCM; - } - else if(sampleFormat == paInt16) - { + } else if (sampleFormat == paInt16) { pwfext->Format.nBlockAlign = channelCount * 2; pwfext->Format.wBitsPerSample = 16; - pwfext->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX); + pwfext->Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE)-sizeof (WAVEFORMATEX); pwfext->Samples.wValidBitsPerSample = 16; pwfext->SubFormat = KSDATAFORMAT_SUBTYPE_PCM; } + pwfext->Format.nAvgBytesPerSec = pwfext->Format.nSamplesPerSec * pwfext->Format.nBlockAlign; } @@ -936,198 +1122,201 @@ const int BestToWorst[FORMATTESTS]={paFloat32,paInt24,paInt16}; static PaError -GetClosestFormat(IAudioClient * myClient, double sampleRate,const PaStreamParameters * params, - AUDCLNT_SHAREMODE *shareMode, WAVEFORMATEXTENSIBLE *outWavex) +GetClosestFormat (IAudioClient * myClient, double sampleRate,const PaStreamParameters * params, + AUDCLNT_SHAREMODE *shareMode, WAVEFORMATEXTENSIBLE *outWavex) { - //TODO we should try exclusive first and shared after - *shareMode = PORTAUDIO_SHAREMODE; - - PaError answer = paInvalidSampleRate; - - waveformatFromParams(outWavex,params,sampleRate); - WAVEFORMATEX *sharedClosestMatch=0; - HRESULT hResult=!S_OK; - - if (*shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE) - hResult = myClient->IsFormatSupported(AUDCLNT_SHAREMODE_EXCLUSIVE,(WAVEFORMATEX*)outWavex,NULL); - else - hResult = myClient->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, (WAVEFORMATEX*)&outWavex,&sharedClosestMatch); - - if (hResult == S_OK) - answer = paFormatIsSupported; - else if (sharedClosestMatch){ - WAVEFORMATEXTENSIBLE* ext = (WAVEFORMATEXTENSIBLE*)sharedClosestMatch; - - int closestMatchSR = (int)sharedClosestMatch->nSamplesPerSec; - - if (sharedClosestMatch->wFormatTag == WAVE_FORMAT_EXTENSIBLE) - memcpy(outWavex,sharedClosestMatch,sizeof(WAVEFORMATEXTENSIBLE)); - else - memcpy(outWavex,sharedClosestMatch,sizeof(WAVEFORMATEX)); - - CoTaskMemFree(sharedClosestMatch); - - if ((int)sampleRate == closestMatchSR) - answer = paFormatIsSupported; - else - answer = paInvalidSampleRate; - - }else { - - //it doesnt suggest anything?? ok lets show it the MENU! - - //ok fun time as with pa_win_mme, we know only a refusal of the user-requested - //sampleRate+num Channel is disastrous, as the portaudio buffer processor converts between anything - //so lets only use the number - for (int i=0;i<FORMATTESTS;++i){ - WAVEFORMATEXTENSIBLE ext; - wasapiFillWFEXT(&ext,BestToWorst[i],sampleRate,params->channelCount); - if (*shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE) - hResult = myClient->IsFormatSupported(AUDCLNT_SHAREMODE_EXCLUSIVE,(WAVEFORMATEX*)&ext,NULL); - else - hResult = myClient->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, (WAVEFORMATEX*)&ext,&sharedClosestMatch); - - if (hResult == S_OK){ - memcpy(outWavex,&ext,sizeof(WAVEFORMATEXTENSIBLE)); - answer = paFormatIsSupported; - break; - } - } - - if (answer!=paFormatIsSupported) { - //try MIX format? - //why did it HAVE to come to this .... - WAVEFORMATEX pcm16WaveFormat; - memset(&pcm16WaveFormat,0,sizeof(WAVEFORMATEX)); - pcm16WaveFormat.wFormatTag = WAVE_FORMAT_PCM; - pcm16WaveFormat.nChannels = 2; - pcm16WaveFormat.nSamplesPerSec = (DWORD)sampleRate; - pcm16WaveFormat.nBlockAlign = 4; - pcm16WaveFormat.nAvgBytesPerSec = pcm16WaveFormat.nSamplesPerSec*pcm16WaveFormat.nBlockAlign; - pcm16WaveFormat.wBitsPerSample = 16; - pcm16WaveFormat.cbSize = 0; - - if (*shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE) - hResult = myClient->IsFormatSupported(AUDCLNT_SHAREMODE_EXCLUSIVE,(WAVEFORMATEX*)&pcm16WaveFormat,NULL); - else - hResult = myClient->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, (WAVEFORMATEX*)&pcm16WaveFormat,&sharedClosestMatch); - - if (hResult == S_OK){ - memcpy(outWavex,&pcm16WaveFormat,sizeof(WAVEFORMATEX)); - answer = paFormatIsSupported; - } - } - - logAUDCLNT_E(hResult); - } - - return answer; + //TODO we should try exclusive first and shared after + *shareMode = PORTAUDIO_SHAREMODE; + + PaError answer = paInvalidSampleRate; + + waveformatFromParams (outWavex,params,sampleRate); + WAVEFORMATEX *sharedClosestMatch=0; + HRESULT hResult=!S_OK; + + if (*shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE) + hResult = myClient->IsFormatSupported (AUDCLNT_SHAREMODE_EXCLUSIVE, (WAVEFORMATEX*) outWavex,NULL); + else + hResult = myClient->IsFormatSupported (AUDCLNT_SHAREMODE_SHARED, (WAVEFORMATEX*) &outWavex,&sharedClosestMatch); + + if (hResult == S_OK) + answer = paFormatIsSupported; + else if (sharedClosestMatch) { + WAVEFORMATEXTENSIBLE* ext = (WAVEFORMATEXTENSIBLE*) sharedClosestMatch; + + int closestMatchSR = (int) sharedClosestMatch->nSamplesPerSec; + + if (sharedClosestMatch->wFormatTag == WAVE_FORMAT_EXTENSIBLE) + memcpy (outWavex,sharedClosestMatch,sizeof (WAVEFORMATEXTENSIBLE)); + else + memcpy (outWavex,sharedClosestMatch,sizeof (WAVEFORMATEX)); + + CoTaskMemFree (sharedClosestMatch); + + if ( (int) sampleRate == closestMatchSR) + answer = paFormatIsSupported; + else + answer = paInvalidSampleRate; + + } else { + + //it doesnt suggest anything?? ok lets show it the MENU! + + //ok fun time as with pa_win_mme, we know only a refusal of the user-requested + //sampleRate+num Channel is disastrous, as the portaudio buffer processor converts between anything + //so lets only use the number + for (int i=0;i<FORMATTESTS;++i) { + WAVEFORMATEXTENSIBLE ext; + wasapiFillWFEXT (&ext,BestToWorst[i],sampleRate,params->channelCount); + + if (*shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE) + hResult = myClient->IsFormatSupported (AUDCLNT_SHAREMODE_EXCLUSIVE, (WAVEFORMATEX*) &ext,NULL); + else + hResult = myClient->IsFormatSupported (AUDCLNT_SHAREMODE_SHARED, (WAVEFORMATEX*) &ext,&sharedClosestMatch); + + if (hResult == S_OK) { + memcpy (outWavex,&ext,sizeof (WAVEFORMATEXTENSIBLE)); + answer = paFormatIsSupported; + break; + } + } + + if (answer!=paFormatIsSupported) { + //try MIX format? + //why did it HAVE to come to this .... + WAVEFORMATEX pcm16WaveFormat; + memset (&pcm16WaveFormat,0,sizeof (WAVEFORMATEX)); + pcm16WaveFormat.wFormatTag = WAVE_FORMAT_PCM; + pcm16WaveFormat.nChannels = 2; + pcm16WaveFormat.nSamplesPerSec = (DWORD) sampleRate; + pcm16WaveFormat.nBlockAlign = 4; + pcm16WaveFormat.nAvgBytesPerSec = pcm16WaveFormat.nSamplesPerSec*pcm16WaveFormat.nBlockAlign; + pcm16WaveFormat.wBitsPerSample = 16; + pcm16WaveFormat.cbSize = 0; + + if (*shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE) + hResult = myClient->IsFormatSupported (AUDCLNT_SHAREMODE_EXCLUSIVE, (WAVEFORMATEX*) &pcm16WaveFormat,NULL); + else + hResult = myClient->IsFormatSupported (AUDCLNT_SHAREMODE_SHARED, (WAVEFORMATEX*) &pcm16WaveFormat,&sharedClosestMatch); + + if (hResult == S_OK) { + memcpy (outWavex,&pcm16WaveFormat,sizeof (WAVEFORMATEX)); + answer = paFormatIsSupported; + } + } + + logAUDCLNT_E (hResult); + } + + return answer; } -static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, +static PaError IsFormatSupported (struct PaUtilHostApiRepresentation *hostApi, const PaStreamParameters *inputParameters, const PaStreamParameters *outputParameters, - double sampleRate ) + double sampleRate) { int inputChannelCount, outputChannelCount; PaSampleFormat inputSampleFormat, outputSampleFormat; - if( inputParameters ) - { + if (inputParameters) { inputChannelCount = inputParameters->channelCount; inputSampleFormat = inputParameters->sampleFormat; /* all standard sample formats are supported by the buffer adapter, this implementation doesn't support any custom sample formats */ - if( inputSampleFormat & paCustomFormat ) + + if (inputSampleFormat & paCustomFormat) return paSampleFormatNotSupported; /* unless alternate device specification is supported, reject the use of paUseHostApiSpecificDeviceSpecification */ - if( inputParameters->device == paUseHostApiSpecificDeviceSpecification ) + if (inputParameters->device == paUseHostApiSpecificDeviceSpecification) return paInvalidDevice; /* check that input device can support inputChannelCount */ - if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels ) + if (inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels) return paInvalidChannelCount; /* validate inputStreamInfo */ - if( inputParameters->hostApiSpecificStreamInfo ) + if (inputParameters->hostApiSpecificStreamInfo) return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */ - PaWinWasapiHostApiRepresentation *paWasapi = (PaWinWasapiHostApiRepresentation*)hostApi; + PaWinWasapiHostApiRepresentation *paWasapi = (PaWinWasapiHostApiRepresentation*) hostApi; + + + IAudioClient *myClient=0; + HRESULT hResult = paWasapi->devInfo[inputParameters->device].device->Activate ( + __uuidof (IAudioClient), CLSCTX_INPROC_SERVER, NULL, (void**) &myClient); - IAudioClient *myClient=0; - HRESULT hResult = paWasapi->devInfo[inputParameters->device].device->Activate( - __uuidof(IAudioClient), CLSCTX_INPROC_SERVER, NULL, (void**)&myClient); - if (hResult != S_OK){ - logAUDCLNT_E(hResult); - return paInvalidDevice; - } + if (hResult != S_OK) { + logAUDCLNT_E (hResult); + return paInvalidDevice; + } WAVEFORMATEXTENSIBLE wavex; - AUDCLNT_SHAREMODE shareMode; - PaError answer = GetClosestFormat(myClient,sampleRate,inputParameters,&shareMode,&wavex); - myClient->Release(); - if (answer !=paFormatIsSupported) - return answer; - } - else - { + AUDCLNT_SHAREMODE shareMode; + PaError answer = GetClosestFormat (myClient,sampleRate,inputParameters,&shareMode,&wavex); + myClient->Release(); + + if (answer !=paFormatIsSupported) + return answer; + } else { inputChannelCount = 0; } - if( outputParameters ) - { + if (outputParameters) { outputChannelCount = outputParameters->channelCount; outputSampleFormat = outputParameters->sampleFormat; /* all standard sample formats are supported by the buffer adapter, this implementation doesn't support any custom sample formats */ - if( outputSampleFormat & paCustomFormat ) + + if (outputSampleFormat & paCustomFormat) return paSampleFormatNotSupported; /* unless alternate device specification is supported, reject the use of paUseHostApiSpecificDeviceSpecification */ - if( outputParameters->device == paUseHostApiSpecificDeviceSpecification ) + if (outputParameters->device == paUseHostApiSpecificDeviceSpecification) return paInvalidDevice; /* check that output device can support outputChannelCount */ - if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels ) + if (outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels) return paInvalidChannelCount; /* validate outputStreamInfo */ - if( outputParameters->hostApiSpecificStreamInfo ) + if (outputParameters->hostApiSpecificStreamInfo) return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */ - PaWinWasapiHostApiRepresentation *paWasapi = (PaWinWasapiHostApiRepresentation*)hostApi; + PaWinWasapiHostApiRepresentation *paWasapi = (PaWinWasapiHostApiRepresentation*) hostApi; + + IAudioClient *myClient=0; - IAudioClient *myClient=0; - HRESULT hResult = paWasapi->devInfo[outputParameters->device].device->Activate( - __uuidof(IAudioClient), CLSCTX_INPROC_SERVER, NULL, (void**)&myClient); - if (hResult != S_OK){ - logAUDCLNT_E(hResult); - return paInvalidDevice; - } + HRESULT hResult = paWasapi->devInfo[outputParameters->device].device->Activate ( + __uuidof (IAudioClient), CLSCTX_INPROC_SERVER, NULL, (void**) &myClient); + + if (hResult != S_OK) { + logAUDCLNT_E (hResult); + return paInvalidDevice; + } WAVEFORMATEXTENSIBLE wavex; - AUDCLNT_SHAREMODE shareMode; - PaError answer = GetClosestFormat(myClient,sampleRate,outputParameters,&shareMode,&wavex); - myClient->Release(); - if (answer !=paFormatIsSupported) - return answer; - } - else - { + AUDCLNT_SHAREMODE shareMode; + PaError answer = GetClosestFormat (myClient,sampleRate,outputParameters,&shareMode,&wavex); + myClient->Release(); + + if (answer !=paFormatIsSupported) + return answer; + } else { outputChannelCount = 0; } @@ -1139,7 +1328,7 @@ static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, /* see pa_hostapi.h for a list of validity guarantees made about OpenStream parameters */ -static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, +static PaError OpenStream (struct PaUtilHostApiRepresentation *hostApi, PaStream** s, const PaStreamParameters *inputParameters, const PaStreamParameters *outputParameters, @@ -1147,200 +1336,204 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, unsigned long framesPerBuffer, PaStreamFlags streamFlags, PaStreamCallback *streamCallback, - void *userData ) + void *userData) { PaError result = paNoError; - PaWinWasapiHostApiRepresentation *paWasapi = (PaWinWasapiHostApiRepresentation*)hostApi; + PaWinWasapiHostApiRepresentation *paWasapi = (PaWinWasapiHostApiRepresentation*) hostApi; PaWinWasapiStream *stream = 0; int inputChannelCount, outputChannelCount; PaSampleFormat inputSampleFormat, outputSampleFormat; PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat; - stream = (PaWinWasapiStream*)PaUtil_AllocateMemory( sizeof(PaWinWasapiStream) ); - if( !stream ){ + stream = (PaWinWasapiStream*) PaUtil_AllocateMemory (sizeof (PaWinWasapiStream)); + + if (!stream) { result = paInsufficientMemory; goto error; } - if( inputParameters ) - { + if (inputParameters) { inputChannelCount = inputParameters->channelCount; inputSampleFormat = inputParameters->sampleFormat; /* unless alternate device specification is supported, reject the use of paUseHostApiSpecificDeviceSpecification */ - if( inputParameters->device == paUseHostApiSpecificDeviceSpecification ) + if (inputParameters->device == paUseHostApiSpecificDeviceSpecification) return paInvalidDevice; /* check that input device can support inputChannelCount */ - if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels ) + if (inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels) return paInvalidChannelCount; /* validate inputStreamInfo */ - if( inputParameters->hostApiSpecificStreamInfo ) + if (inputParameters->hostApiSpecificStreamInfo) return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */ PaWinWasapiDeviceInfo &info = paWasapi->devInfo[inputParameters->device]; - HRESULT hResult = info.device->Activate( - __uuidof(IAudioClient), CLSCTX_INPROC_SERVER, NULL, - (void**)&stream->in.client); + HRESULT hResult = info.device->Activate ( + __uuidof (IAudioClient), CLSCTX_INPROC_SERVER, NULL, + (void**) &stream->in.client); if (hResult != S_OK) return paInvalidDevice; - hResult = info.device->Activate( - __uuidof(IAudioEndpointVolume), CLSCTX_INPROC_SERVER, NULL, - (void**)&stream->inVol); + hResult = info.device->Activate ( + __uuidof (IAudioEndpointVolume), CLSCTX_INPROC_SERVER, NULL, + (void**) &stream->inVol); if (hResult != S_OK) return paInvalidDevice; - - AUDCLNT_SHAREMODE shareMode; - PaError answer = GetClosestFormat(stream->in.client,sampleRate,inputParameters,&shareMode,&stream->in.wavex); - - if (answer !=paFormatIsSupported) - return answer; + + AUDCLNT_SHAREMODE shareMode; + + PaError answer = GetClosestFormat (stream->in.client,sampleRate,inputParameters,&shareMode,&stream->in.wavex); + + if (answer !=paFormatIsSupported) + return answer; //stream->out.period = info.DefaultDevicePeriod; stream->in.period = info.MinimumDevicePeriod; - hResult = stream->in.client->Initialize( - shareMode, - 0, //no flags - stream->in.period, - 0,//stream->out.period, - (WAVEFORMATEX*)&stream->in.wavex, - &stream->session - ); - - if (hResult != S_OK){ - logAUDCLNT_E(hResult); + hResult = stream->in.client->Initialize ( + shareMode, + 0, //no flags + stream->in.period, + 0,//stream->out.period, + (WAVEFORMATEX*) &stream->in.wavex, + &stream->session + ); + + if (hResult != S_OK) { + logAUDCLNT_E (hResult); return paInvalidDevice; } - hResult = stream->in.client->GetBufferSize(&stream->in.bufferSize); + hResult = stream->in.client->GetBufferSize (&stream->in.bufferSize); + if (hResult != S_OK) return paInvalidDevice; - hResult = stream->in.client->GetStreamLatency(&stream->in.latency); + hResult = stream->in.client->GetStreamLatency (&stream->in.latency); + if (hResult != S_OK) return paInvalidDevice; - double periodsPerSecond = 1.0/nano100ToSeconds(stream->in.period); - double samplesPerPeriod = (double)(stream->in.wavex.Format.nSamplesPerSec)/periodsPerSecond; + double periodsPerSecond = 1.0/nano100ToSeconds (stream->in.period); + + double samplesPerPeriod = (double) (stream->in.wavex.Format.nSamplesPerSec) /periodsPerSecond; //this is the number of samples that are required at each period - stream->in.framesPerHostCallback = (unsigned long)samplesPerPeriod;//unrelated to channels + stream->in.framesPerHostCallback = (unsigned long) samplesPerPeriod;//unrelated to channels /* IMPLEMENT ME - establish which host formats are available */ hostInputSampleFormat = - PaUtil_SelectClosestAvailableFormat( waveformatToPaFormat(&stream->in.wavex), inputSampleFormat ); - } - else - { + PaUtil_SelectClosestAvailableFormat (waveformatToPaFormat (&stream->in.wavex), inputSampleFormat); + } else { inputChannelCount = 0; inputSampleFormat = hostInputSampleFormat = paInt16; /* Surpress 'uninitialised var' warnings. */ } - if( outputParameters ) - { + if (outputParameters) { outputChannelCount = outputParameters->channelCount; outputSampleFormat = outputParameters->sampleFormat; /* unless alternate device specification is supported, reject the use of paUseHostApiSpecificDeviceSpecification */ - if( outputParameters->device == paUseHostApiSpecificDeviceSpecification ) + if (outputParameters->device == paUseHostApiSpecificDeviceSpecification) return paInvalidDevice; /* check that output device can support inputChannelCount */ - if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels ) + if (outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels) return paInvalidChannelCount; /* validate outputStreamInfo */ - if( outputParameters->hostApiSpecificStreamInfo ) + if (outputParameters->hostApiSpecificStreamInfo) return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */ PaWinWasapiDeviceInfo &info = paWasapi->devInfo[outputParameters->device]; - HRESULT hResult = info.device->Activate( - __uuidof(IAudioClient), CLSCTX_INPROC_SERVER, NULL, - (void**)&stream->out.client); + HRESULT hResult = info.device->Activate ( + __uuidof (IAudioClient), CLSCTX_INPROC_SERVER, NULL, + (void**) &stream->out.client); if (hResult != S_OK) return paInvalidDevice; - AUDCLNT_SHAREMODE shareMode; - PaError answer = GetClosestFormat(stream->out.client,sampleRate,outputParameters,&shareMode,&stream->out.wavex); - - if (answer !=paFormatIsSupported) - return answer; - LogWAVEFORMATEXTENSIBLE(&stream->out.wavex); + AUDCLNT_SHAREMODE shareMode; + + PaError answer = GetClosestFormat (stream->out.client,sampleRate,outputParameters,&shareMode,&stream->out.wavex); + + if (answer !=paFormatIsSupported) + return answer; - // stream->out.period = info.DefaultDevicePeriod; + LogWAVEFORMATEXTENSIBLE (&stream->out.wavex); + + // stream->out.period = info.DefaultDevicePeriod; stream->out.period = info.MinimumDevicePeriod; - /*For an exclusive-mode stream that uses event-driven buffering, - the caller must specify nonzero values for hnsPeriodicity and hnsBufferDuration, - and the values of these two parameters must be equal */ - if (shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE){ - hResult = stream->out.client->Initialize( - shareMode, - AUDCLNT_STREAMFLAGS_EVENTCALLBACK, - stream->out.period, - stream->out.period, - (WAVEFORMATEX*)&stream->out.wavex, - &stream->session - ); - } - else{ - hResult = stream->out.client->Initialize( - shareMode, - AUDCLNT_STREAMFLAGS_EVENTCALLBACK, - 0, - 0, - (WAVEFORMATEX*)&stream->out.wavex, - &stream->session - ); - } - - - if (hResult != S_OK){ - logAUDCLNT_E(hResult); + /*For an exclusive-mode stream that uses event-driven buffering, + the caller must specify nonzero values for hnsPeriodicity and hnsBufferDuration, + and the values of these two parameters must be equal */ + if (shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE) { + hResult = stream->out.client->Initialize ( + shareMode, + AUDCLNT_STREAMFLAGS_EVENTCALLBACK, + stream->out.period, + stream->out.period, + (WAVEFORMATEX*) &stream->out.wavex, + &stream->session + ); + } else { + hResult = stream->out.client->Initialize ( + shareMode, + AUDCLNT_STREAMFLAGS_EVENTCALLBACK, + 0, + 0, + (WAVEFORMATEX*) &stream->out.wavex, + &stream->session + ); + } + + + if (hResult != S_OK) { + logAUDCLNT_E (hResult); return paInvalidDevice; } - hResult = info.device->Activate( - __uuidof(IAudioEndpointVolume), CLSCTX_INPROC_SERVER, NULL, - (void**)&stream->outVol); + hResult = info.device->Activate ( + + __uuidof (IAudioEndpointVolume), CLSCTX_INPROC_SERVER, NULL, + (void**) &stream->outVol); if (hResult != S_OK) return paInvalidDevice; - hResult = stream->out.client->GetBufferSize(&stream->out.bufferSize); + hResult = stream->out.client->GetBufferSize (&stream->out.bufferSize); + if (hResult != S_OK) return paInvalidDevice; - hResult = stream->out.client->GetStreamLatency(&stream->out.latency); + hResult = stream->out.client->GetStreamLatency (&stream->out.latency); + if (hResult != S_OK) return paInvalidDevice; - - double periodsPerSecond = 1.0/nano100ToSeconds(stream->out.period); - double samplesPerPeriod = (double)(stream->out.wavex.Format.nSamplesPerSec)/periodsPerSecond; + + double periodsPerSecond = 1.0/nano100ToSeconds (stream->out.period); + + double samplesPerPeriod = (double) (stream->out.wavex.Format.nSamplesPerSec) /periodsPerSecond; //this is the number of samples that are required at each period stream->out.framesPerHostCallback = stream->out.bufferSize; //(unsigned long)samplesPerPeriod;//unrelated to channels /* IMPLEMENT ME - establish which host formats are available */ - hostOutputSampleFormat = PaUtil_SelectClosestAvailableFormat( waveformatToPaFormat(&stream->out.wavex), outputSampleFormat ); - } - else - { + hostOutputSampleFormat = PaUtil_SelectClosestAvailableFormat (waveformatToPaFormat (&stream->out.wavex), outputSampleFormat); + } else { outputChannelCount = 0; outputSampleFormat = hostOutputSampleFormat = paInt16; /* Surpress 'uninitialized var' warnings. */ } @@ -1374,56 +1567,55 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, /* validate platform specific flags */ - if( (streamFlags & paPlatformSpecificFlags) != 0 ) + if ( (streamFlags & paPlatformSpecificFlags) != 0) return paInvalidFlag; /* unexpected platform specific flag */ - if( streamCallback ) - { - PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation, - &paWasapi->callbackStreamInterface, streamCallback, userData ); - } - else - { - PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation, - &paWasapi->blockingStreamInterface, streamCallback, userData ); + if (streamCallback) { + PaUtil_InitializeStreamRepresentation (&stream->streamRepresentation, + &paWasapi->callbackStreamInterface, streamCallback, userData); + } else { + PaUtil_InitializeStreamRepresentation (&stream->streamRepresentation, + &paWasapi->blockingStreamInterface, streamCallback, userData); } - PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate ); + PaUtil_InitializeCpuLoadMeasurer (&stream->cpuLoadMeasurer, sampleRate); - if (outputParameters && inputParameters){ + if (outputParameters && inputParameters) { - //serious problem #1 - if (stream->in.period != stream->out.period){ - PRINT(("OpenStream: period discrepancy\n")); - goto error; - } + //serious problem #1 + if (stream->in.period != stream->out.period) { + PRINT ( ("OpenStream: period discrepancy\n")); + goto error; + } + + //serious problem #2 + if (stream->out.framesPerHostCallback != stream->in.framesPerHostCallback) { + PRINT ( ("OpenStream: framesPerHostCallback discrepancy\n")); + goto error; + } + } - //serious problem #2 - if (stream->out.framesPerHostCallback != stream->in.framesPerHostCallback){ - PRINT(("OpenStream: framesPerHostCallback discrepancy\n")); - goto error; - } - } + unsigned long framesPerHostCallback = (outputParameters) ? - unsigned long framesPerHostCallback = (outputParameters)? - stream->out.framesPerHostCallback: - stream->in.framesPerHostCallback; + stream->out.framesPerHostCallback: + stream->in.framesPerHostCallback; /* we assume a fixed host buffer size in this example, but the buffer processor can also support bounded and unknown host buffer sizes by passing paUtilBoundedHostBufferSize or paUtilUnknownHostBufferSize instead of paUtilFixedHostBufferSize below. */ - result = PaUtil_InitializeBufferProcessor( &stream->bufferProcessor, + result = PaUtil_InitializeBufferProcessor (&stream->bufferProcessor, inputChannelCount, inputSampleFormat, hostInputSampleFormat, outputChannelCount, outputSampleFormat, hostOutputSampleFormat, sampleRate, streamFlags, framesPerBuffer, framesPerHostCallback, paUtilFixedHostBufferSize, - streamCallback, userData ); - if( result != paNoError ) + streamCallback, userData); + + if (result != paNoError) goto error; @@ -1432,24 +1624,24 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, values. */ stream->streamRepresentation.streamInfo.inputLatency = - PaUtil_GetBufferProcessorInputLatency(&stream->bufferProcessor) - + ((inputParameters)?nano100ToSeconds(stream->in.latency) :0); + PaUtil_GetBufferProcessorInputLatency (&stream->bufferProcessor) + + ( (inputParameters) ?nano100ToSeconds (stream->in.latency) :0); stream->streamRepresentation.streamInfo.outputLatency = - PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor) - + ((outputParameters)?nano100ToSeconds(stream->out.latency) :0); + PaUtil_GetBufferProcessorOutputLatency (&stream->bufferProcessor) + + ( (outputParameters) ?nano100ToSeconds (stream->out.latency) :0); stream->streamRepresentation.streamInfo.sampleRate = sampleRate; - *s = (PaStream*)stream; + *s = (PaStream*) stream; return result; error: - if( stream ) - PaUtil_FreeMemory( stream ); + if (stream) + PaUtil_FreeMemory (stream); return result; } @@ -1465,65 +1657,67 @@ error: if ((punk) != NULL) \ { (punk)->Release(); (punk) = NULL; } -static PaError CloseStream( PaStream* s ) +static PaError CloseStream (PaStream* s) { PaError result = paNoError; - PaWinWasapiStream *stream = (PaWinWasapiStream*)s; + PaWinWasapiStream *stream = (PaWinWasapiStream*) s; /* IMPLEMENT ME: - additional stream closing + cleanup */ - SAFE_RELEASE(stream->out.client); - SAFE_RELEASE(stream->in.client); - SAFE_RELEASE(stream->cclient); - SAFE_RELEASE(stream->rclient); - SAFE_RELEASE(stream->inVol); - SAFE_RELEASE(stream->outVol); - CloseHandle(stream->hThread); - CloseHandle(stream->hNotificationEvent); + SAFE_RELEASE (stream->out.client); + SAFE_RELEASE (stream->in.client); + SAFE_RELEASE (stream->cclient); + SAFE_RELEASE (stream->rclient); + SAFE_RELEASE (stream->inVol); + SAFE_RELEASE (stream->outVol); + CloseHandle (stream->hThread); + CloseHandle (stream->hNotificationEvent); - PaUtil_TerminateBufferProcessor( &stream->bufferProcessor ); - PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation ); - PaUtil_FreeMemory( stream ); + PaUtil_TerminateBufferProcessor (&stream->bufferProcessor); + PaUtil_TerminateStreamRepresentation (&stream->streamRepresentation); + PaUtil_FreeMemory (stream); return result; } -DWORD WINAPI ProcThread(void *client); +DWORD WINAPI ProcThread (void *client); -static PaError StartStream( PaStream *s ) +static PaError StartStream (PaStream *s) { PaError result = paNoError; - PaWinWasapiStream *stream = (PaWinWasapiStream*)s; - - PaUtil_ResetBufferProcessor( &stream->bufferProcessor ); - - HRESULT hResult=S_OK; - - if (stream->out.client){ - hResult = stream->out.client->GetService(__uuidof(IAudioRenderClient),(void**)&stream->rclient); - logAUDCLNT_E(hResult); - if (hResult!=S_OK) - return paUnanticipatedHostError; - } - - if (stream->in.client){ - hResult = stream->in.client->GetService(__uuidof(IAudioCaptureClient),(void**)&stream->cclient); - logAUDCLNT_E(hResult); - if (hResult!=S_OK) - return paUnanticipatedHostError; - } + PaWinWasapiStream *stream = (PaWinWasapiStream*) s; + + PaUtil_ResetBufferProcessor (&stream->bufferProcessor); + + HRESULT hResult=S_OK; + + if (stream->out.client) { + hResult = stream->out.client->GetService (__uuidof (IAudioRenderClient), (void**) &stream->rclient); + logAUDCLNT_E (hResult); + + if (hResult!=S_OK) + return paUnanticipatedHostError; + } + + if (stream->in.client) { + hResult = stream->in.client->GetService (__uuidof (IAudioCaptureClient), (void**) &stream->cclient); + logAUDCLNT_E (hResult); + + if (hResult!=S_OK) + return paUnanticipatedHostError; + } // Create a thread for this client. - stream->hThread = CreateThread( - NULL, // no security attribute - 0, // default stack size - ProcThread, - (LPVOID) stream, // thread parameter - 0, // not suspended - &stream->dwThreadId); // returns thread ID + stream->hThread = CreateThread ( + NULL, // no security attribute + 0, // default stack size + ProcThread, + (LPVOID) stream, // thread parameter + 0, // not suspended + &stream->dwThreadId); // returns thread ID if (stream->hThread == NULL) return paUnanticipatedHostError; @@ -1532,16 +1726,17 @@ static PaError StartStream( PaStream *s ) } -static PaError StopStream( PaStream *s ) +static PaError StopStream (PaStream *s) { PaError result = paNoError; - PaWinWasapiStream *stream = (PaWinWasapiStream*)s; + PaWinWasapiStream *stream = (PaWinWasapiStream*) s; /* suppress unused variable warnings */ stream->closeRequest = true; //todo something MUCH better than this - while(stream->closeRequest) - Sleep(100); + + while (stream->closeRequest) + Sleep (100); /* IMPLEMENT ME, see portaudio.h for required behavior */ @@ -1551,16 +1746,17 @@ static PaError StopStream( PaStream *s ) } -static PaError AbortStream( PaStream *s ) +static PaError AbortStream (PaStream *s) { PaError result = paNoError; - PaWinWasapiStream *stream = (PaWinWasapiStream*)s; + PaWinWasapiStream *stream = (PaWinWasapiStream*) s; /* suppress unused variable warnings */ stream->closeRequest = true; //todo something MUCH better than this - while(stream->closeRequest) - Sleep(100); + + while (stream->closeRequest) + Sleep (100); /* IMPLEMENT ME, see portaudio.h for required behavior */ @@ -1568,42 +1764,42 @@ static PaError AbortStream( PaStream *s ) } -static PaError IsStreamStopped( PaStream *s ) +static PaError IsStreamStopped (PaStream *s) { - PaWinWasapiStream *stream = (PaWinWasapiStream*)s; + PaWinWasapiStream *stream = (PaWinWasapiStream*) s; return !stream->running; } -static PaError IsStreamActive( PaStream *s ) +static PaError IsStreamActive (PaStream *s) { - PaWinWasapiStream *stream = (PaWinWasapiStream*)s; + PaWinWasapiStream *stream = (PaWinWasapiStream*) s; return stream->running; } -static PaTime GetStreamTime( PaStream *s ) +static PaTime GetStreamTime (PaStream *s) { - PaWinWasapiStream *stream = (PaWinWasapiStream*)s; + PaWinWasapiStream *stream = (PaWinWasapiStream*) s; /* suppress unused variable warnings */ (void) stream; /* IMPLEMENT ME, see portaudio.h for required behavior*/ - //this is lame ds and mme does the same thing, quite useless method imho - //why dont we fetch the time in the pa callbacks? - //at least its doing to be clocked to something + //this is lame ds and mme does the same thing, quite useless method imho + //why dont we fetch the time in the pa callbacks? + //at least its doing to be clocked to something return PaUtil_GetTime(); } -static double GetStreamCpuLoad( PaStream* s ) +static double GetStreamCpuLoad (PaStream* s) { - PaWinWasapiStream *stream = (PaWinWasapiStream*)s; + PaWinWasapiStream *stream = (PaWinWasapiStream*) s; - return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer ); + return PaUtil_GetCpuLoad (&stream->cpuLoadMeasurer); } @@ -1613,11 +1809,11 @@ static double GetStreamCpuLoad( PaStream* s ) for blocking streams. */ -static PaError ReadStream( PaStream* s, +static PaError ReadStream (PaStream* s, void *buffer, - unsigned long frames ) + unsigned long frames) { - PaWinWasapiStream *stream = (PaWinWasapiStream*)s; + PaWinWasapiStream *stream = (PaWinWasapiStream*) s; /* suppress unused variable warnings */ (void) buffer; @@ -1630,11 +1826,11 @@ static PaError ReadStream( PaStream* s, } -static PaError WriteStream( PaStream* s, +static PaError WriteStream (PaStream* s, const void *buffer, - unsigned long frames ) + unsigned long frames) { - PaWinWasapiStream *stream = (PaWinWasapiStream*)s; + PaWinWasapiStream *stream = (PaWinWasapiStream*) s; /* suppress unused variable warnings */ (void) buffer; @@ -1647,9 +1843,9 @@ static PaError WriteStream( PaStream* s, } -static signed long GetStreamReadAvailable( PaStream* s ) +static signed long GetStreamReadAvailable (PaStream* s) { - PaWinWasapiStream *stream = (PaWinWasapiStream*)s; + PaWinWasapiStream *stream = (PaWinWasapiStream*) s; /* suppress unused variable warnings */ (void) stream; @@ -1660,9 +1856,9 @@ static signed long GetStreamReadAvailable( PaStream* s ) } -static signed long GetStreamWriteAvailable( PaStream* s ) +static signed long GetStreamWriteAvailable (PaStream* s) { - PaWinWasapiStream *stream = (PaWinWasapiStream*)s; + PaWinWasapiStream *stream = (PaWinWasapiStream*) s; /* suppress unused variable warnings */ (void) stream; @@ -1679,16 +1875,16 @@ static signed long GetStreamWriteAvailable( PaStream* s ) occur in a host implementation. */ -static void WaspiHostProcessingLoop( void *inputBuffer, long inputFrames, +static void WaspiHostProcessingLoop (void *inputBuffer, long inputFrames, void *outputBuffer, long outputFrames, - void *userData ) + void *userData) { - PaWinWasapiStream *stream = (PaWinWasapiStream*)userData; + PaWinWasapiStream *stream = (PaWinWasapiStream*) userData; PaStreamCallbackTimeInfo timeInfo = {0,0,0}; /* IMPLEMENT ME */ int callbackResult; unsigned long framesProcessed; - PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer ); + PaUtil_BeginCpuLoadMeasurement (&stream->cpuLoadMeasurer); /* @@ -1704,7 +1900,7 @@ static void WaspiHostProcessingLoop( void *inputBuffer, long inputFrames, - PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo, 0 /* IMPLEMENT ME: pass underflow/overflow flags when necessary */ ); + PaUtil_BeginBufferProcessing (&stream->bufferProcessor, &timeInfo, 0 /* IMPLEMENT ME: pass underflow/overflow flags when necessary */); /* depending on whether the host buffers are interleaved, non-interleaved @@ -1712,22 +1908,20 @@ static void WaspiHostProcessingLoop( void *inputBuffer, long inputFrames, PaUtil_SetNonInterleaved*Channel() or PaUtil_Set*Channel() here. */ - if( stream->bufferProcessor.inputChannelCount > 0 ) - { - PaUtil_SetInputFrameCount( &stream->bufferProcessor, inputFrames ); - PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, - 0, /* first channel of inputBuffer is channel 0 */ - inputBuffer, - 0 ); /* 0 - use inputChannelCount passed to init buffer processor */ + if (stream->bufferProcessor.inputChannelCount > 0) { + PaUtil_SetInputFrameCount (&stream->bufferProcessor, inputFrames); + PaUtil_SetInterleavedInputChannels (&stream->bufferProcessor, + 0, /* first channel of inputBuffer is channel 0 */ + inputBuffer, + 0); /* 0 - use inputChannelCount passed to init buffer processor */ } - if( stream->bufferProcessor.outputChannelCount > 0 ) - { - PaUtil_SetOutputFrameCount( &stream->bufferProcessor, outputFrames); - PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, - 0, /* first channel of outputBuffer is channel 0 */ - outputBuffer, - 0 ); /* 0 - use outputChannelCount passed to init buffer processor */ + if (stream->bufferProcessor.outputChannelCount > 0) { + PaUtil_SetOutputFrameCount (&stream->bufferProcessor, outputFrames); + PaUtil_SetInterleavedOutputChannels (&stream->bufferProcessor, + 0, /* first channel of outputBuffer is channel 0 */ + outputBuffer, + 0); /* 0 - use outputChannelCount passed to init buffer processor */ } /* you must pass a valid value of callback result to PaUtil_EndBufferProcessing() @@ -1737,7 +1931,8 @@ static void WaspiHostProcessingLoop( void *inputBuffer, long inputFrames, using PaUtil_IsBufferProcessorOuputEmpty( bufferProcessor ) */ callbackResult = paContinue; - framesProcessed = PaUtil_EndBufferProcessing( &stream->bufferProcessor, &callbackResult ); + + framesProcessed = PaUtil_EndBufferProcessing (&stream->bufferProcessor, &callbackResult); /* @@ -1745,134 +1940,147 @@ static void WaspiHostProcessingLoop( void *inputBuffer, long inputFrames, host format, do it here. */ - PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed ); + PaUtil_EndCpuLoadMeasurement (&stream->cpuLoadMeasurer, framesProcessed); - if( callbackResult == paContinue ) - { + if (callbackResult == paContinue) { /* nothing special to do */ - } - else if( callbackResult == paAbort ) - { + } else if (callbackResult == paAbort) { /* IMPLEMENT ME - finish playback immediately */ /* once finished, call the finished callback */ - if( stream->streamRepresentation.streamFinishedCallback != 0 ) - stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData ); - } - else - { + if (stream->streamRepresentation.streamFinishedCallback != 0) + stream->streamRepresentation.streamFinishedCallback (stream->streamRepresentation.userData); + } else { /* User callback has asked us to stop with paComplete or other non-zero value */ /* IMPLEMENT ME - finish playback once currently queued audio has completed */ /* once finished, call the finished callback */ - if( stream->streamRepresentation.streamFinishedCallback != 0 ) - stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData ); + if (stream->streamRepresentation.streamFinishedCallback != 0) + stream->streamRepresentation.streamFinishedCallback (stream->streamRepresentation.userData); } } -void -MMCSS_activate(){ +void +MMCSS_activate() +{ DWORD stuff=0; - HANDLE thCarac = pAvSetMmThreadCharacteristics("Pro Audio",&stuff); - if (!thCarac){ - PRINT(("AvSetMmThreadCharacteristics failed!\n")); + HANDLE thCarac = pAvSetMmThreadCharacteristics ("Pro Audio",&stuff); + + if (!thCarac) { + PRINT ( ("AvSetMmThreadCharacteristics failed!\n")); } - BOOL prio = pAvSetMmThreadPriority(thCarac,AVRT_PRIORITY_NORMAL); - if (!prio){ - PRINT(("AvSetMmThreadPriority failed!\n")); + BOOL prio = pAvSetMmThreadPriority (thCarac,AVRT_PRIORITY_NORMAL); + + if (!prio) { + PRINT ( ("AvSetMmThreadPriority failed!\n")); } - //debug + //debug { HANDLE hh = GetCurrentThread(); - int currprio = GetThreadPriority(hh); - DWORD currclass = GetPriorityClass(GetCurrentProcess()); - PRINT(("currprio 0x%X currclass 0x%X\n",currprio,currclass)); + int currprio = GetThreadPriority (hh); + DWORD currclass = GetPriorityClass (GetCurrentProcess()); + PRINT ( ("currprio 0x%X currclass 0x%X\n",currprio,currclass)); } } DWORD WINAPI -ProcThread(void* param){ - HRESULT hResult; - MMCSS_activate(); - - PaWinWasapiStream *stream = (PaWinWasapiStream*)param; - - stream->hNotificationEvent = CreateEvent(NULL, - FALSE, //bManualReset are we sure?? - FALSE, - "PAWASA"); - hResult = stream->out.client->SetEventHandle(stream->hNotificationEvent); - if (hResult != S_OK) - logAUDCLNT_E(hResult); - - if (stream->out.client){ - hResult = stream->out.client->Start(); - if (hResult != S_OK) - logAUDCLNT_E(hResult); - } - - stream->running = true; - bool bOne = false; - - while( !stream->closeRequest ) - { - //lets wait but have a 1 second timeout - DWORD dwResult = WaitForSingleObject(stream->hNotificationEvent, 1000); - switch( dwResult ) { - case WAIT_OBJECT_0: { - - unsigned long usingBS = stream->out.framesPerHostCallback; - - BYTE* indata = 0; - BYTE* outdata = 0; - - hResult = stream->rclient->GetBuffer(usingBS, &outdata); - - if (hResult != S_OK || !outdata) { - //logAUDCLNT_E(hResult); - //most probably shared mode and hResult=AUDCLNT_E_BUFFER_TOO_LARGE - UINT32 padding = 0; - hResult = stream->out.client->GetCurrentPadding(&padding); - if (padding == 0) - break; - usingBS = usingBS-padding; - if (usingBS == 0) - break;//huh? - hResult = stream->rclient->GetBuffer(usingBS, &outdata); - if (hResult != S_OK)//what can we do NOW?? - break; - //logAUDCLNT_E(hResult); - } - - WaspiHostProcessingLoop(indata, usingBS ,outdata, usingBS, stream); - - hResult = stream->rclient->ReleaseBuffer(usingBS, 0); - if (hResult != S_OK) - logAUDCLNT_E(hResult); - - /* This was suggested, but in my tests it doesnt seem to improve the - locking behaviour some drivers have running in exclusive mode. - if(!ResetEvent(stream->hNotificationEvent)){ - logAUDCLNT_E(hResult); - } - */ - - } - break; +ProcThread (void* param) +{ + HRESULT hResult; + MMCSS_activate(); + + PaWinWasapiStream *stream = (PaWinWasapiStream*) param; + + stream->hNotificationEvent = CreateEvent (NULL, + FALSE, //bManualReset are we sure?? + FALSE, + "PAWASA"); + hResult = stream->out.client->SetEventHandle (stream->hNotificationEvent); + + if (hResult != S_OK) + logAUDCLNT_E (hResult); + + if (stream->out.client) { + hResult = stream->out.client->Start(); + + if (hResult != S_OK) + logAUDCLNT_E (hResult); + } + + stream->running = true; + + bool bOne = false; + + while (!stream->closeRequest) { + //lets wait but have a 1 second timeout + DWORD dwResult = WaitForSingleObject (stream->hNotificationEvent, 1000); + + switch (dwResult) { + + case WAIT_OBJECT_0: { + + unsigned long usingBS = stream->out.framesPerHostCallback; + + BYTE* indata = 0; + BYTE* outdata = 0; + + hResult = stream->rclient->GetBuffer (usingBS, &outdata); + + if (hResult != S_OK || !outdata) { + //logAUDCLNT_E(hResult); + //most probably shared mode and hResult=AUDCLNT_E_BUFFER_TOO_LARGE + UINT32 padding = 0; + hResult = stream->out.client->GetCurrentPadding (&padding); + + if (padding == 0) + break; + + usingBS = usingBS-padding; + + if (usingBS == 0) + break;//huh? + + hResult = stream->rclient->GetBuffer (usingBS, &outdata); + + if (hResult != S_OK) //what can we do NOW?? + break; + + //logAUDCLNT_E(hResult); + } + + WaspiHostProcessingLoop (indata, usingBS ,outdata, usingBS, stream); + + hResult = stream->rclient->ReleaseBuffer (usingBS, 0); + + if (hResult != S_OK) + logAUDCLNT_E (hResult); + + /* This was suggested, but in my tests it doesnt seem to improve the + locking behaviour some drivers have running in exclusive mode. + if(!ResetEvent(stream->hNotificationEvent)){ + logAUDCLNT_E(hResult); + } + */ + + } + + break; } } - stream->out.client->Stop(); + + stream->out.client->Stop(); + stream->closeRequest = false; - - return 0; + + return 0; } @@ -1884,28 +2092,42 @@ ProcThread(void* param){ #if 0 - if(bFirst) { - float masteur; - hResult = stream->outVol->GetMasterVolumeLevelScalar(&masteur); - if (hResult != S_OK) - logAUDCLNT_E(hResult); - float chan1, chan2; - hResult = stream->outVol->GetChannelVolumeLevelScalar(0, &chan1); - if (hResult != S_OK) - logAUDCLNT_E(hResult); - hResult = stream->outVol->GetChannelVolumeLevelScalar(1, &chan2); - if (hResult != S_OK) - logAUDCLNT_E(hResult); - - BOOL bMute; - hResult = stream->outVol->GetMute(&bMute); - if (hResult != S_OK) - logAUDCLNT_E(hResult); - - stream->outVol->SetMasterVolumeLevelScalar(0.5, NULL); - stream->outVol->SetChannelVolumeLevelScalar(0, 0.5, NULL); - stream->outVol->SetChannelVolumeLevelScalar(1, 0.5, NULL); - stream->outVol->SetMute(FALSE, NULL); - bFirst = false; - } + +if (bFirst) +{ + float masteur; + hResult = stream->outVol->GetMasterVolumeLevelScalar (&masteur); + + if (hResult != S_OK) + logAUDCLNT_E (hResult); + + float chan1, chan2; + + hResult = stream->outVol->GetChannelVolumeLevelScalar (0, &chan1); + + if (hResult != S_OK) + logAUDCLNT_E (hResult); + + hResult = stream->outVol->GetChannelVolumeLevelScalar (1, &chan2); + + if (hResult != S_OK) + logAUDCLNT_E (hResult); + + BOOL bMute; + + hResult = stream->outVol->GetMute (&bMute); + + if (hResult != S_OK) + logAUDCLNT_E (hResult); + + stream->outVol->SetMasterVolumeLevelScalar (0.5, NULL); + + stream->outVol->SetChannelVolumeLevelScalar (0, 0.5, NULL); + + stream->outVol->SetChannelVolumeLevelScalar (1, 0.5, NULL); + + stream->outVol->SetMute (FALSE, NULL); + + bFirst = false; +} #endif \ No newline at end of file diff --git a/sflphone-common/src/account.cpp b/sflphone-common/src/account.cpp index 2ec89d6da14bf06efdb69e0b099a299259f44d7d..f5b542f57f34a97b02a1133a674aaa2c1b94bac6 100644 --- a/sflphone-common/src/account.cpp +++ b/sflphone-common/src/account.cpp @@ -41,7 +41,7 @@ void Account::loadConfig() p = Manager::instance().getConfigString (_accountID , CONFIG_ACCOUNT_TYPE); #ifdef USE_IAX - _enabled = (Manager::instance().getConfigString(_accountID, CONFIG_ACCOUNT_ENABLE) == "true") ? true : false; + _enabled = (Manager::instance().getConfigString (_accountID, CONFIG_ACCOUNT_ENABLE) == "true") ? true : false; #else if (p.c_str() == "IAX") diff --git a/sflphone-common/src/account.h b/sflphone-common/src/account.h index 723efeb4c277028429922eb9f75c5d4578081a74..324ec2d0d6c51b573fae076c77b1adcb2e5278cf 100644 --- a/sflphone-common/src/account.h +++ b/sflphone-common/src/account.h @@ -80,9 +80,8 @@ typedef enum RegistrationState { // SIP specific parameters #define SIP_PROXY "SIP.proxy" -#define SIP_STUN_SERVER "STUN.server" -#define SIP_USE_STUN "STUN.enable" -#define SIP_STUN_PORT "STUN.port" +#define STUN_SERVER "STUN.server" +#define STUN_ENABLE "STUN.enable" // SRTP specific parameters #define SRTP_ENABLE "SRTP.enable" diff --git a/sflphone-common/src/accountcreator.cpp b/sflphone-common/src/accountcreator.cpp index b45792a8f49be4ff3f31f8d0a97d506e667e6164..be0d6f8f353d8a01b95fe8fb35eaff6f00408d79 100644 --- a/sflphone-common/src/accountcreator.cpp +++ b/sflphone-common/src/accountcreator.cpp @@ -38,17 +38,20 @@ Account* AccountCreator::createAccount (AccountType type, AccountID accountID) { switch (type) { + case SIP_ACCOUNT: return new SIPAccount (accountID); break; + case SIP_DIRECT_IP_ACCOUNT: return new SIPAccount (IP2IP_PROFILE); break; - #ifdef USE_IAX +#ifdef USE_IAX + case IAX_ACCOUNT: return new IAXAccount (accountID); break; - #endif +#endif } return 0; diff --git a/sflphone-common/src/audio/audiortp/AudioRtpFactory.cpp b/sflphone-common/src/audio/audiortp/AudioRtpFactory.cpp index e0dd37fef36b62599726c99e73a15684be082579..6785f286e9710b79535442be38f9462dbd954203 100644 --- a/sflphone-common/src/audio/audiortp/AudioRtpFactory.cpp +++ b/sflphone-common/src/audio/audiortp/AudioRtpFactory.cpp @@ -1,7 +1,7 @@ /* * Copyright (C) 2009 Savoir-Faire Linux inc. * Author: Pierre-Luc Bacon <pierre-luc.bacon@savoirfairelinux.com> - * + * * 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 3 of the License, or @@ -10,12 +10,12 @@ * 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ - + #include "AudioRtpFactory.h" @@ -28,140 +28,160 @@ #include <assert.h> -namespace sfl { +namespace sfl +{ - AudioRtpFactory::AudioRtpFactory() : _rtpSession(NULL) - { - - } +AudioRtpFactory::AudioRtpFactory() : _rtpSession (NULL) +{ - AudioRtpFactory::AudioRtpFactory(SIPCall *ca) : _rtpSession(NULL) - { - assert(ca); - - try { - initAudioRtpSession(ca); - } catch (UnsupportedRtpSessionType& exception) { - throw exception; - } +} + +AudioRtpFactory::AudioRtpFactory (SIPCall *ca) : _rtpSession (NULL) +{ + assert (ca); + + try { + initAudioRtpSession (ca); + } catch (UnsupportedRtpSessionType& exception) { + throw exception; } +} + +AudioRtpFactory::~AudioRtpFactory() +{ + stop(); +} + +void AudioRtpFactory::initAudioRtpSession (SIPCall * ca) +{ + ost::MutexLock m (_audioRtpThreadMutex); - AudioRtpFactory::~AudioRtpFactory() - { + assert (ca); + + if (_rtpSession != NULL) { + _debugException ("An audio rtp thread was already created but not" \ + "destroyed. Forcing it before continuing.\n"); stop(); } - void AudioRtpFactory::initAudioRtpSession(SIPCall * ca) - { - ost::MutexLock m(_audioRtpThreadMutex); - - assert(ca); - - if (_rtpSession != NULL) { - _debugException("An audio rtp thread was already created but not" \ - "destroyed. Forcing it before continuing.\n"); - stop(); - } - - AccountID accountId = Manager::instance().getAccountFromCall (ca->getCallId()); - - bool srtpEnabled = false; - int keyExchangeProtocol = 1; - bool helloHashEnabled = true; - - // Check if it is an IP-to-IP call - if(accountId == AccountNULL) { - srtpEnabled = Manager::instance().getConfigBool(IP2IP_PROFILE, SRTP_ENABLE); - keyExchangeProtocol = Manager::instance().getConfigInt(IP2IP_PROFILE, SRTP_KEY_EXCHANGE); - _debug("Ip-to-ip profile selected with key exchange protocol number %d\n", keyExchangeProtocol); - helloHashEnabled = Manager::instance().getConfigBool(IP2IP_PROFILE, ZRTP_HELLO_HASH); - } else { - srtpEnabled = Manager::instance().getConfigBool(accountId, SRTP_ENABLE); - keyExchangeProtocol = Manager::instance().getConfigInt(accountId, SRTP_KEY_EXCHANGE); - _debug("Registered account %s profile selected with key exchange protocol number %d\n", accountId.c_str(), keyExchangeProtocol); - helloHashEnabled = Manager::instance().getConfigBool(accountId, ZRTP_HELLO_HASH); + AccountID accountId = Manager::instance().getAccountFromCall (ca->getCallId()); + + bool srtpEnabled = false; + int keyExchangeProtocol = 1; + bool helloHashEnabled = true; + + // Check if it is an IP-to-IP call + + if (accountId == AccountNULL) { + srtpEnabled = Manager::instance().getConfigBool (IP2IP_PROFILE, SRTP_ENABLE); + keyExchangeProtocol = Manager::instance().getConfigInt (IP2IP_PROFILE, SRTP_KEY_EXCHANGE); + _debug ("Ip-to-ip profile selected with key exchange protocol number %d\n", keyExchangeProtocol); + helloHashEnabled = Manager::instance().getConfigBool (IP2IP_PROFILE, ZRTP_HELLO_HASH); + } else { + srtpEnabled = Manager::instance().getConfigBool (accountId, SRTP_ENABLE); + keyExchangeProtocol = Manager::instance().getConfigInt (accountId, SRTP_KEY_EXCHANGE); + _debug ("Registered account %s profile selected with key exchange protocol number %d\n", accountId.c_str(), keyExchangeProtocol); + helloHashEnabled = Manager::instance().getConfigBool (accountId, ZRTP_HELLO_HASH); + } + + _debug ("Srtp enable: %d \n", srtpEnabled); + + if (srtpEnabled) { + std::string zidFilename (Manager::instance().getConfigString (SIGNALISATION, ZRTP_ZIDFILE)); + + switch (keyExchangeProtocol) { + + case Zrtp: + _rtpSession = new AudioZrtpSession (&Manager::instance(), ca, zidFilename); + _rtpSessionType = Zrtp; + + if (helloHashEnabled) { + // TODO: be careful with that. The hello hash is computed asynchronously. Maybe it's + // not even available at that point. + ca->getLocalSDP()->set_zrtp_hash (static_cast<AudioZrtpSession *> (_rtpSession)->getHelloHash()); + _debug ("Zrtp hello hash fed to SDP\n"); + } + + break; + + case Sdes: + + default: + throw UnsupportedRtpSessionType(); } - - _debug("Srtp enable: %d \n", srtpEnabled); - - if (srtpEnabled) { - std::string zidFilename(Manager::instance().getConfigString(SIGNALISATION, ZRTP_ZIDFILE)); - - switch(keyExchangeProtocol) { - case Zrtp: - _rtpSession = new AudioZrtpSession(&Manager::instance(), ca, zidFilename); - _rtpSessionType = Zrtp; - if (helloHashEnabled) { - // TODO: be careful with that. The hello hash is computed asynchronously. Maybe it's - // not even available at that point. - ca->getLocalSDP()->set_zrtp_hash(static_cast<AudioZrtpSession *>(_rtpSession)->getHelloHash()); - _debug("Zrtp hello hash fed to SDP\n"); - } - break; - case Sdes: - default: - throw UnsupportedRtpSessionType(); + } else { + _rtpSessionType = Symmetric; + _rtpSession = new AudioSymmetricRtpSession (&Manager::instance(), ca); + _debug ("Starting a symmetric unencrypted rtp session\n"); + } +} + +void AudioRtpFactory::start (void) +{ + if (_rtpSession == NULL) { + throw AudioRtpFactoryException ("_rtpSession was null when trying to start audio thread"); + } + + switch (_rtpSessionType) { + + case Sdes: + + case Symmetric: + _debug ("Starting symmetric rtp thread\n"); + + if (static_cast<AudioSymmetricRtpSession *> (_rtpSession)->startRtpThread() != 0) { + throw AudioRtpFactoryException ("Failed to start AudioSymmetricRtpSession thread"); } - } else { - _rtpSessionType = Symmetric; - _rtpSession = new AudioSymmetricRtpSession(&Manager::instance(), ca); - _debug("Starting a symmetric unencrypted rtp session\n"); - } + + break; + + case Zrtp: + + if (static_cast<AudioZrtpSession *> (_rtpSession)->startRtpThread() != 0) { + throw AudioRtpFactoryException ("Failed to start AudioZrtpSession thread"); + } + + break; } +} + +void AudioRtpFactory::stop (void) +{ + ost::MutexLock mutex (_audioRtpThreadMutex); + _debug ("Stopping audio rtp session\n"); + + if (_rtpSession == NULL) { + _debugException ("_rtpSession is null when trying to stop. Returning."); + return; + } + + try { + switch (_rtpSessionType) { - void AudioRtpFactory::start(void) - { - if (_rtpSession == NULL) { - throw AudioRtpFactoryException("_rtpSession was null when trying to start audio thread"); - } - - switch(_rtpSessionType) { case Sdes: + case Symmetric: - _debug("Starting symmetric rtp thread\n"); - if(static_cast<AudioSymmetricRtpSession *>(_rtpSession)->startRtpThread() != 0) { - throw AudioRtpFactoryException("Failed to start AudioSymmetricRtpSession thread"); - } + delete static_cast<AudioSymmetricRtpSession *> (_rtpSession); break; - case Zrtp: - if(static_cast<AudioZrtpSession *>(_rtpSession)->startRtpThread() != 0) { - throw AudioRtpFactoryException("Failed to start AudioZrtpSession thread"); - } - break; - } - } - void AudioRtpFactory::stop(void) - { - ost::MutexLock mutex(_audioRtpThreadMutex); - _debug("Stopping audio rtp session\n"); - if (_rtpSession == NULL) { - _debugException("_rtpSession is null when trying to stop. Returning."); - return; - } - try { - switch(_rtpSessionType) { - case Sdes: - case Symmetric: - delete static_cast<AudioSymmetricRtpSession *>(_rtpSession); - break; - case Zrtp: - delete static_cast<AudioZrtpSession *>(_rtpSession); - break; - } - _rtpSession = NULL; - } catch (...) { - _debugException("Exception caught when stopping the audio rtp session\n"); - throw AudioRtpFactoryException(); + case Zrtp: + delete static_cast<AudioZrtpSession *> (_rtpSession); + break; } + + _rtpSession = NULL; + } catch (...) { + _debugException ("Exception caught when stopping the audio rtp session\n"); + throw AudioRtpFactoryException(); } - - sfl::AudioZrtpSession * AudioRtpFactory::getAudioZrtpSession() - { - if ((_rtpSessionType == Zrtp) && (_rtpSessionType != NULL)) { - return static_cast<AudioZrtpSession *>(_rtpSession); - } else { - throw AudioRtpFactoryException(); - } +} + +sfl::AudioZrtpSession * AudioRtpFactory::getAudioZrtpSession() +{ + if ( (_rtpSessionType == Zrtp) && (_rtpSessionType != NULL)) { + return static_cast<AudioZrtpSession *> (_rtpSession); + } else { + throw AudioRtpFactoryException(); } } +} diff --git a/sflphone-common/src/audio/audiortp/AudioZrtpSession.cpp b/sflphone-common/src/audio/audiortp/AudioZrtpSession.cpp index 2b5fe9eb74e1b59599432fa7be2abea351a5c8cd..5961b170e279708a472f6f3509f060f70088aa25 100644 --- a/sflphone-common/src/audio/audiortp/AudioZrtpSession.cpp +++ b/sflphone-common/src/audio/audiortp/AudioZrtpSession.cpp @@ -10,7 +10,7 @@ * 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., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -28,46 +28,47 @@ #include <cstring> #include <cerrno> -namespace sfl { +namespace sfl +{ + +AudioZrtpSession::AudioZrtpSession (ManagerImpl * manager, SIPCall * sipcall, const std::string& zidFilename) : + ost::SymmetricZRTPSession (ost::InetHostAddress (sipcall->getLocalIp().c_str()), sipcall->getLocalAudioPort()), + AudioRtpSession<AudioZrtpSession> (manager, sipcall), + _zidFilename (zidFilename) +{ + _debug ("AudioZrtpSession initialized\n"); + initializeZid(); + startZrtp(); +} + +void AudioZrtpSession::initializeZid (void) +{ - AudioZrtpSession::AudioZrtpSession(ManagerImpl * manager, SIPCall * sipcall, const std::string& zidFilename) : - ost::SymmetricZRTPSession(ost::InetHostAddress(sipcall->getLocalIp().c_str()), sipcall->getLocalAudioPort()), - AudioRtpSession<AudioZrtpSession>(manager, sipcall), - _zidFilename(zidFilename) - { - _debug("AudioZrtpSession initialized\n"); - initializeZid(); - startZrtp(); + if (_zidFilename.empty()) { + throw ZrtpZidException(); } - - void AudioZrtpSession::initializeZid(void) - { - if(_zidFilename.empty()) { - throw ZrtpZidException(); - } + std::string zidCompleteFilename = std::string (HOMEDIR) + DIR_SEPARATOR_STR + "." + PROGDIR + "/" + _zidFilename; - std::string zidCompleteFilename = std::string(HOMEDIR) + DIR_SEPARATOR_STR + "." + PROGDIR + "/" + _zidFilename; - - if(initialize(zidCompleteFilename.c_str()) >= 0) { - _debug("Register callbacks\n"); - setEnableZrtp(true); - setUserCallback(new ZrtpSessionCallback(_ca)); - return; - } - - _debug("Initialization from ZID file failed. Trying to remove...\n"); - - if(remove(zidCompleteFilename.c_str())!=0) { - _debug("Failed to remove zid file because of: %s", strerror(errno)); - throw ZrtpZidException(); - } - - if(initialize(zidCompleteFilename.c_str()) < 0) { - _debug("ZRTP initialization failed\n"); - throw ZrtpZidException(); - } - + if (initialize (zidCompleteFilename.c_str()) >= 0) { + _debug ("Register callbacks\n"); + setEnableZrtp (true); + setUserCallback (new ZrtpSessionCallback (_ca)); return; } + + _debug ("Initialization from ZID file failed. Trying to remove...\n"); + + if (remove (zidCompleteFilename.c_str()) !=0) { + _debug ("Failed to remove zid file because of: %s", strerror (errno)); + throw ZrtpZidException(); + } + + if (initialize (zidCompleteFilename.c_str()) < 0) { + _debug ("ZRTP initialization failed\n"); + throw ZrtpZidException(); + } + + return; +} } diff --git a/sflphone-common/src/audio/audiortp/ZrtpSessionCallback.cpp b/sflphone-common/src/audio/audiortp/ZrtpSessionCallback.cpp index ee28caced8c92ca18a2fda56287a4dad30c341a7..1648112382c5a2ee5f5da5e847c2df0868143509 100644 --- a/sflphone-common/src/audio/audiortp/ZrtpSessionCallback.cpp +++ b/sflphone-common/src/audio/audiortp/ZrtpSessionCallback.cpp @@ -23,194 +23,205 @@ #include "dbus/dbusmanager.h" #include "dbus/callmanager.h" -#include <cstdlib> +#include <cstdlib> #include <string> #include <map> using namespace GnuZrtpCodes; + using namespace ost; + using namespace std; -namespace sfl { +namespace sfl +{ - ZrtpSessionCallback::ZrtpSessionCallback(SIPCall *sipcall): - _sipcall(sipcall) - { +ZrtpSessionCallback::ZrtpSessionCallback (SIPCall *sipcall) : + _sipcall (sipcall) +{ - if(_mapInitialized) { - return; - } - - _debug("Initialize callbacks\n"); - - /** - * Information Map - */ - - _infoMap.insert(pair<int32, std::string*>(InfoHelloReceived, new string("Hello received, preparing a Commit"))); - _infoMap.insert(pair<int32, std::string*>(InfoCommitDHGenerated, new string("Commit: Generated a public DH key"))); - _infoMap.insert(pair<int32, std::string*>(InfoRespCommitReceived, new string("Responder: Commit received, preparing DHPart1"))); - _infoMap.insert(pair<int32, std::string*>(InfoDH1DHGenerated, new string("DH1Part: Generated a public DH key"))); - _infoMap.insert(pair<int32, std::string*>(InfoInitDH1Received, new string("Initiator: DHPart1 received, preparing DHPart2"))); - _infoMap.insert(pair<int32, std::string*>(InfoRespDH2Received, new string("Responder: DHPart2 received, preparing Confirm1"))); - _infoMap.insert(pair<int32, std::string*>(InfoInitConf1Received, new string("Initiator: Confirm1 received, preparing Confirm2"))); - _infoMap.insert(pair<int32, std::string*>(InfoRespConf2Received, new string("Responder: Confirm2 received, preparing Conf2Ack"))); - _infoMap.insert(pair<int32, std::string*>(InfoRSMatchFound, new string("At least one retained secrets matches - security OK"))); - _infoMap.insert(pair<int32, std::string*>(InfoSecureStateOn, new string("Entered secure state"))); - _infoMap.insert(pair<int32, std::string*>(InfoSecureStateOff, new string("No more security for this session"))); - - /** - * Warning Map - */ - - _warningMap.insert(pair<int32, std::string*>(WarningDHAESmismatch, - new string("Commit contains an AES256 cipher but does not offer a Diffie-Helman 4096"))); - _warningMap.insert(pair<int32, std::string*>(WarningGoClearReceived, new string("Received a GoClear message"))); - _warningMap.insert(pair<int32, std::string*>(WarningDHShort, - new string("Hello offers an AES256 cipher but does not offer a Diffie-Helman 4096"))); - _warningMap.insert(pair<int32, std::string*>(WarningNoRSMatch, new string("No retained secret matches - verify SAS"))); - _warningMap.insert(pair<int32, std::string*>(WarningCRCmismatch, new string("Internal ZRTP packet checksum mismatch - packet dropped"))); - _warningMap.insert(pair<int32, std::string*>(WarningSRTPauthError, new string("Dropping packet because SRTP authentication failed!"))); - _warningMap.insert(pair<int32, std::string*>(WarningSRTPreplayError, new string("Dropping packet because SRTP replay check failed!"))); - - _severeMap.insert(pair<int32, std::string*>(SevereHelloHMACFailed, new string("Hash HMAC check of Hello failed!"))); - _severeMap.insert(pair<int32, std::string*>(SevereCommitHMACFailed, new string("Hash HMAC check of Commit failed!"))); - _severeMap.insert(pair<int32, std::string*>(SevereDH1HMACFailed, new string("Hash HMAC check of DHPart1 failed!"))); - _severeMap.insert(pair<int32, std::string*>(SevereDH2HMACFailed, new string("Hash HMAC check of DHPart2 failed!"))); - _severeMap.insert(pair<int32, std::string*>(SevereCannotSend, new string("Cannot send data - connection or peer down?"))); - _severeMap.insert(pair<int32, std::string*>(SevereProtocolError, new string("Internal protocol error occured!"))); - _severeMap.insert(pair<int32, std::string*>(SevereNoTimer, new string("Cannot start a timer - internal resources exhausted?"))); - _severeMap.insert(pair<int32, std::string*>(SevereTooMuchRetries, - new string("Too much retries during ZRTP negotiation - connection or peer down?"))); - - /** - * Zrtp protocol related messages map - */ - - _zrtpMap.insert(pair<int32, std::string*>(MalformedPacket, new string("Malformed packet (CRC OK, but wrong structure)"))); - _zrtpMap.insert(pair<int32, std::string*>(CriticalSWError, new string("Critical software error"))); - _zrtpMap.insert(pair<int32, std::string*>(UnsuppZRTPVersion, new string("Unsupported ZRTP version"))); - _zrtpMap.insert(pair<int32, std::string*>(HelloCompMismatch, new string("Hello components mismatch"))); - _zrtpMap.insert(pair<int32, std::string*>(UnsuppHashType, new string("Hash type not supported"))); - _zrtpMap.insert(pair<int32, std::string*>(UnsuppCiphertype, new string("Cipher type not supported"))); - _zrtpMap.insert(pair<int32, std::string*>(UnsuppPKExchange, new string("Public key exchange not supported"))); - _zrtpMap.insert(pair<int32, std::string*>(UnsuppSRTPAuthTag, new string("SRTP auth. tag not supported"))); - _zrtpMap.insert(pair<int32, std::string*>(UnsuppSASScheme, new string("SAS scheme not supported"))); - _zrtpMap.insert(pair<int32, std::string*>(NoSharedSecret, new string("No shared secret available, DH mode required"))); - _zrtpMap.insert(pair<int32, std::string*>(DHErrorWrongPV, new string("DH Error: bad pvi or pvr ( == 1, 0, or p-1)"))); - _zrtpMap.insert(pair<int32, std::string*>(DHErrorWrongHVI, new string("DH Error: hvi != hashed data"))); - _zrtpMap.insert(pair<int32, std::string*>(SASuntrustedMiTM, new string("Received relayed SAS from untrusted MiTM"))); - _zrtpMap.insert(pair<int32, std::string*>(ConfirmHMACWrong, new string("Auth. Error: Bad Confirm pkt HMAC"))); - _zrtpMap.insert(pair<int32, std::string*>(NonceReused, new string("Nonce reuse"))); - _zrtpMap.insert(pair<int32, std::string*>(EqualZIDHello, new string("Equal ZIDs in Hello"))); - _zrtpMap.insert(pair<int32, std::string*>(GoCleatNotAllowed, new string("GoClear packet received, but not allowed"))); - - _mapInitialized = true; + if (_mapInitialized) { + return; } - void - ZrtpSessionCallback::secureOn(std::string cipher) - { - _debug("Secure mode is on with cipher %s\n", cipher.c_str()); - DBusManager::instance().getCallManager()->secureOn(_sipcall->getCallId(), cipher); - } + _debug ("Initialize callbacks\n"); + + /** + * Information Map + */ + + _infoMap.insert (pair<int32, std::string*> (InfoHelloReceived, new string ("Hello received, preparing a Commit"))); + _infoMap.insert (pair<int32, std::string*> (InfoCommitDHGenerated, new string ("Commit: Generated a public DH key"))); + _infoMap.insert (pair<int32, std::string*> (InfoRespCommitReceived, new string ("Responder: Commit received, preparing DHPart1"))); + _infoMap.insert (pair<int32, std::string*> (InfoDH1DHGenerated, new string ("DH1Part: Generated a public DH key"))); + _infoMap.insert (pair<int32, std::string*> (InfoInitDH1Received, new string ("Initiator: DHPart1 received, preparing DHPart2"))); + _infoMap.insert (pair<int32, std::string*> (InfoRespDH2Received, new string ("Responder: DHPart2 received, preparing Confirm1"))); + _infoMap.insert (pair<int32, std::string*> (InfoInitConf1Received, new string ("Initiator: Confirm1 received, preparing Confirm2"))); + _infoMap.insert (pair<int32, std::string*> (InfoRespConf2Received, new string ("Responder: Confirm2 received, preparing Conf2Ack"))); + _infoMap.insert (pair<int32, std::string*> (InfoRSMatchFound, new string ("At least one retained secrets matches - security OK"))); + _infoMap.insert (pair<int32, std::string*> (InfoSecureStateOn, new string ("Entered secure state"))); + _infoMap.insert (pair<int32, std::string*> (InfoSecureStateOff, new string ("No more security for this session"))); + + /** + * Warning Map + */ + + _warningMap.insert (pair<int32, std::string*> (WarningDHAESmismatch, + new string ("Commit contains an AES256 cipher but does not offer a Diffie-Helman 4096"))); + _warningMap.insert (pair<int32, std::string*> (WarningGoClearReceived, new string ("Received a GoClear message"))); + _warningMap.insert (pair<int32, std::string*> (WarningDHShort, + new string ("Hello offers an AES256 cipher but does not offer a Diffie-Helman 4096"))); + _warningMap.insert (pair<int32, std::string*> (WarningNoRSMatch, new string ("No retained secret matches - verify SAS"))); + _warningMap.insert (pair<int32, std::string*> (WarningCRCmismatch, new string ("Internal ZRTP packet checksum mismatch - packet dropped"))); + _warningMap.insert (pair<int32, std::string*> (WarningSRTPauthError, new string ("Dropping packet because SRTP authentication failed!"))); + _warningMap.insert (pair<int32, std::string*> (WarningSRTPreplayError, new string ("Dropping packet because SRTP replay check failed!"))); + + _severeMap.insert (pair<int32, std::string*> (SevereHelloHMACFailed, new string ("Hash HMAC check of Hello failed!"))); + _severeMap.insert (pair<int32, std::string*> (SevereCommitHMACFailed, new string ("Hash HMAC check of Commit failed!"))); + _severeMap.insert (pair<int32, std::string*> (SevereDH1HMACFailed, new string ("Hash HMAC check of DHPart1 failed!"))); + _severeMap.insert (pair<int32, std::string*> (SevereDH2HMACFailed, new string ("Hash HMAC check of DHPart2 failed!"))); + _severeMap.insert (pair<int32, std::string*> (SevereCannotSend, new string ("Cannot send data - connection or peer down?"))); + _severeMap.insert (pair<int32, std::string*> (SevereProtocolError, new string ("Internal protocol error occured!"))); + _severeMap.insert (pair<int32, std::string*> (SevereNoTimer, new string ("Cannot start a timer - internal resources exhausted?"))); + _severeMap.insert (pair<int32, std::string*> (SevereTooMuchRetries, + new string ("Too much retries during ZRTP negotiation - connection or peer down?"))); + + /** + * Zrtp protocol related messages map + */ + + _zrtpMap.insert (pair<int32, std::string*> (MalformedPacket, new string ("Malformed packet (CRC OK, but wrong structure)"))); + _zrtpMap.insert (pair<int32, std::string*> (CriticalSWError, new string ("Critical software error"))); + _zrtpMap.insert (pair<int32, std::string*> (UnsuppZRTPVersion, new string ("Unsupported ZRTP version"))); + _zrtpMap.insert (pair<int32, std::string*> (HelloCompMismatch, new string ("Hello components mismatch"))); + _zrtpMap.insert (pair<int32, std::string*> (UnsuppHashType, new string ("Hash type not supported"))); + _zrtpMap.insert (pair<int32, std::string*> (UnsuppCiphertype, new string ("Cipher type not supported"))); + _zrtpMap.insert (pair<int32, std::string*> (UnsuppPKExchange, new string ("Public key exchange not supported"))); + _zrtpMap.insert (pair<int32, std::string*> (UnsuppSRTPAuthTag, new string ("SRTP auth. tag not supported"))); + _zrtpMap.insert (pair<int32, std::string*> (UnsuppSASScheme, new string ("SAS scheme not supported"))); + _zrtpMap.insert (pair<int32, std::string*> (NoSharedSecret, new string ("No shared secret available, DH mode required"))); + _zrtpMap.insert (pair<int32, std::string*> (DHErrorWrongPV, new string ("DH Error: bad pvi or pvr ( == 1, 0, or p-1)"))); + _zrtpMap.insert (pair<int32, std::string*> (DHErrorWrongHVI, new string ("DH Error: hvi != hashed data"))); + _zrtpMap.insert (pair<int32, std::string*> (SASuntrustedMiTM, new string ("Received relayed SAS from untrusted MiTM"))); + _zrtpMap.insert (pair<int32, std::string*> (ConfirmHMACWrong, new string ("Auth. Error: Bad Confirm pkt HMAC"))); + _zrtpMap.insert (pair<int32, std::string*> (NonceReused, new string ("Nonce reuse"))); + _zrtpMap.insert (pair<int32, std::string*> (EqualZIDHello, new string ("Equal ZIDs in Hello"))); + _zrtpMap.insert (pair<int32, std::string*> (GoCleatNotAllowed, new string ("GoClear packet received, but not allowed"))); + + _mapInitialized = true; +} - void - ZrtpSessionCallback::secureOff(void) - { - _debug("Secure mode is off\n"); - DBusManager::instance().getCallManager()->secureOff(_sipcall->getCallId()); - } +void +ZrtpSessionCallback::secureOn (std::string cipher) +{ + _debug ("Secure mode is on with cipher %s\n", cipher.c_str()); + DBusManager::instance().getCallManager()->secureOn (_sipcall->getCallId(), cipher); +} + +void +ZrtpSessionCallback::secureOff (void) +{ + _debug ("Secure mode is off\n"); + DBusManager::instance().getCallManager()->secureOff (_sipcall->getCallId()); +} + +void +ZrtpSessionCallback::showSAS (std::string sas, bool verified) +{ + _debug ("SAS is: %s\n", sas.c_str()); + DBusManager::instance().getCallManager()->showSAS (_sipcall->getCallId(), sas, verified); +} + +void +ZrtpSessionCallback::zrtpNotSuppOther() +{ + _debug ("Callee does not support ZRTP\n"); + DBusManager::instance().getCallManager()->zrtpNotSuppOther (_sipcall->getCallId()); +} + +void +ZrtpSessionCallback::showMessage (GnuZrtpCodes::MessageSeverity sev, int32_t subCode) +{ + string* msg; + + if (sev == Info) { + msg = _infoMap[subCode]; - void - ZrtpSessionCallback::showSAS(std::string sas, bool verified) - { - _debug("SAS is: %s\n", sas.c_str()); - DBusManager::instance().getCallManager()->showSAS(_sipcall->getCallId(), sas, verified); + if (msg != NULL) { + _debug ("ZRTP Debug:\n"); + } } - void - ZrtpSessionCallback::zrtpNotSuppOther() - { - _debug("Callee does not support ZRTP\n"); - DBusManager::instance().getCallManager()->zrtpNotSuppOther(_sipcall->getCallId()); + if (sev == Warning) { + msg = _warningMap[subCode]; + + if (msg != NULL) { + _debug ("ZRTP Debug:\n"); + } } - void - ZrtpSessionCallback::showMessage(GnuZrtpCodes::MessageSeverity sev, int32_t subCode) - { - string* msg; - if (sev == Info) { - msg = _infoMap[subCode]; - if (msg != NULL) { - _debug("ZRTP Debug:\n"); - } + if (sev == Severe) { + msg = _severeMap[subCode]; + + if (msg != NULL) { + _debug ("ZRTP Debug:\n"); } - if (sev == Warning) { - msg = _warningMap[subCode]; - if (msg != NULL) { - _debug("ZRTP Debug:\n"); - } + } + + if (sev == ZrtpError) { + if (subCode < 0) { // received an error packet from peer + subCode *= -1; + _debug ("Received an error packet from peer:\n"); + } else { + _debug ("Sent error packet to peer:\n"); } - if (sev == Severe) { - msg = _severeMap[subCode]; - if (msg != NULL) { - _debug("ZRTP Debug:\n"); - } + + msg = _zrtpMap[subCode]; + + if (msg != NULL) { + _debug ("ZRTP Debug: %s\n", msg->c_str()); } - if (sev == ZrtpError) { - if (subCode < 0) { // received an error packet from peer - subCode *= -1; - _debug("Received an error packet from peer:\n"); - } - else { - _debug("Sent error packet to peer:\n"); - } - - msg = _zrtpMap[subCode]; - if (msg != NULL) { - _debug("ZRTP Debug: %s\n", msg->c_str()); - } - } } +} - void - ZrtpSessionCallback::zrtpNegotiationFailed(MessageSeverity severity, int subCode) - { - string* msg; - if (severity == ZrtpError) { - if (subCode < 0) { // received an error packet from peer - subCode *= -1; - _debug("Received error packet: \n"); - } - else { - _debug("Sent error packet: \n"); - } - msg = _zrtpMap[subCode]; - if (msg != NULL) { - _debug("%s\n", msg->c_str()); - DBusManager::instance().getCallManager()->zrtpNegotiationFailed(_sipcall->getCallId(), *msg, "ZRTP"); - } +void +ZrtpSessionCallback::zrtpNegotiationFailed (MessageSeverity severity, int subCode) +{ + string* msg; + + if (severity == ZrtpError) { + if (subCode < 0) { // received an error packet from peer + subCode *= -1; + _debug ("Received error packet: \n"); + } else { + _debug ("Sent error packet: \n"); } - else { - msg = _severeMap[subCode]; - _debug("%s\n", msg->c_str()); - DBusManager::instance().getCallManager()->zrtpNegotiationFailed(_sipcall->getCallId(), *msg, "severe"); + + msg = _zrtpMap[subCode]; + + if (msg != NULL) { + _debug ("%s\n", msg->c_str()); + DBusManager::instance().getCallManager()->zrtpNegotiationFailed (_sipcall->getCallId(), *msg, "ZRTP"); } + } else { + msg = _severeMap[subCode]; + _debug ("%s\n", msg->c_str()); + DBusManager::instance().getCallManager()->zrtpNegotiationFailed (_sipcall->getCallId(), *msg, "severe"); } +} - void - ZrtpSessionCallback::confirmGoClear() - { - _debug("Received go clear message. Until confirmation, ZRTP won't send any data\n"); - DBusManager::instance().getCallManager()->zrtpNotSuppOther(_sipcall->getCallId()); - } +void +ZrtpSessionCallback::confirmGoClear() +{ + _debug ("Received go clear message. Until confirmation, ZRTP won't send any data\n"); + DBusManager::instance().getCallManager()->zrtpNotSuppOther (_sipcall->getCallId()); +} - map<int32, std::string*>ZrtpSessionCallback::_infoMap; - map<int32, std::string*>ZrtpSessionCallback::_warningMap; - map<int32, std::string*>ZrtpSessionCallback::_severeMap; - map<int32, std::string*>ZrtpSessionCallback::_zrtpMap; +map<int32, std::string*>ZrtpSessionCallback::_infoMap; +map<int32, std::string*>ZrtpSessionCallback::_warningMap; +map<int32, std::string*>ZrtpSessionCallback::_severeMap; +map<int32, std::string*>ZrtpSessionCallback::_zrtpMap; - bool ZrtpSessionCallback::_mapInitialized = false; +bool ZrtpSessionCallback::_mapInitialized = false; } - + diff --git a/sflphone-common/src/config/config.cpp b/sflphone-common/src/config/config.cpp index 4d91cdee2ca182aeac36adc069c970ec0e57d5d0..ec3f7bab8d0aef52ccd09d720cf020b1c3ce558e 100644 --- a/sflphone-common/src/config/config.cpp +++ b/sflphone-common/src/config/config.cpp @@ -48,22 +48,25 @@ ConfigTree::~ConfigTree() } } -void ConfigTree::addDefaultValue(const std::pair<std::string, std::string>& token, std::string section) +void ConfigTree::addDefaultValue (const std::pair<std::string, std::string>& token, std::string section) { - _defaultValueMap.insert(token); + _defaultValueMap.insert (token); + if (section.empty() == false) { - addConfigTreeItem(section, ConfigTreeItem(token.first, token.second, token.second, "string")); + addConfigTreeItem (section, ConfigTreeItem (token.first, token.second, token.second, "string")); } } -std::string ConfigTree::getDefaultValue(const std::string& key) +std::string ConfigTree::getDefaultValue (const std::string& key) { - _debug("Getting default value for %s\n", key.c_str()); + _debug ("Getting default value for %s\n", key.c_str()); std::map<std::string, std::string>::iterator it; - it = _defaultValueMap.find(key); + it = _defaultValueMap.find (key); + if (it == _defaultValueMap.end()) { - return std::string(""); + return std::string (""); } + return it->second; } @@ -142,11 +145,11 @@ ConfigTree::getConfigTreeItemValue (const std::string& section, const std::strin if (item != NULL) { return item->getValue(); - } - + } + _debug ("Option doesn't exist: [%s] %s\n", section.c_str(), itemName.c_str()); - - return getDefaultValue(itemName); + + return getDefaultValue (itemName); } // throw a ConfigTreeItemException if not found @@ -160,9 +163,10 @@ ConfigTree::getConfigTreeItemIntValue (const std::string& section, const std::st } bool -ConfigTree::getConfigTreeItemBoolValue(const std::string& section, const std::string& itemName) +ConfigTree::getConfigTreeItemBoolValue (const std::string& section, const std::string& itemName) { std::string configItem = getConfigTreeItemValue (section, itemName); + if (configItem == "true") { return true; } @@ -222,6 +226,7 @@ ConfigTree::setConfigTreeItem (const std::string& section, { SectionMap::iterator iter = _sections.find (section); + if (iter == _sections.end()) { // Not found, create section _sections[section] = new ItemMap; @@ -233,18 +238,19 @@ ConfigTree::setConfigTreeItem (const std::string& section, if (iterItem == iter->second->end()) { // If not found, search in our default list to find // something that would fit. - std::string defaultValue = getDefaultValue(itemName); + std::string defaultValue = getDefaultValue (itemName); addConfigTreeItem (section, ConfigTreeItem (itemName, value, defaultValue)); return true; - } + } - // Use default value if the value is empty. + // Use default value if the value is empty. if (value.empty() == true) { - iterItem->second.setValue(getDefaultValue(itemName)); + iterItem->second.setValue (getDefaultValue (itemName)); return true; } - iterItem->second.setValue(value); + iterItem->second.setValue (value); + return true; } diff --git a/sflphone-common/src/config/config.h b/sflphone-common/src/config/config.h index 9e6309d58b31481ea7c551f62badbdd270e8dcac..d265dbb5859e403689192550694e2d4768b33435 100644 --- a/sflphone-common/src/config/config.h +++ b/sflphone-common/src/config/config.h @@ -100,19 +100,19 @@ class ConfigTree ConfigTree(); ~ConfigTree(); /** - * Add a default value for a given key. - * It looks in a map of default values when + * Add a default value for a given key. + * It looks in a map of default values when * the value for a given key cannot be found. * - * @param section the section under which the given key/value pair - should go under. Note that this has no effect - when searching for a default value later on. Only + * @param section the section under which the given key/value pair + should go under. Note that this has no effect + when searching for a default value later on. Only one possible value is actually supported as a default - value for a given key. - @param token A default key/value pair. + value for a given key. + @param token A default key/value pair. */ - void addDefaultValue(const std::pair<std::string, std::string>& token, std::string section = std::string("")); - + void addDefaultValue (const std::pair<std::string, std::string>& token, std::string section = std::string ("")); + void createSection (const std::string& section); void removeSection (const std::string& section); /** @@ -138,9 +138,9 @@ class ConfigTree /** * Get a value. * - * If the key cannot be found in the actual file representation in - * memory, it check for a default value in the default value map. If it's - * not found there, it will return an empty string. + * If the key cannot be found in the actual file representation in + * memory, it check for a default value in the default value map. If it's + * not found there, it will return an empty string. * * @param section The name of the [section] in the .ini file. * @param itemName The name of the item= in the .ini file. @@ -149,7 +149,7 @@ class ConfigTree */ std::string getConfigTreeItemValue (const std::string& section, const std::string& itemName); int getConfigTreeItemIntValue (const std::string& section, const std::string& itemName); - bool getConfigTreeItemBoolValue(const std::string& section, const std::string& itemName); + bool getConfigTreeItemBoolValue (const std::string& section, const std::string& itemName); /** * Flush data to .ini file @@ -164,7 +164,7 @@ class ConfigTree bool getConfigTreeItemToken (const std::string& section, const std::string& itemName, TokenList& arg); private: - std::string getDefaultValue(const std::string& key); + std::string getDefaultValue (const std::string& key); ConfigTreeItem* getConfigTreeItem (const std::string& section, const std::string& itemName); /** @@ -173,7 +173,7 @@ class ConfigTree SectionMap _sections; std::map<std::string, std::string> _defaultValueMap; - + friend class ConfigTreeIterator; public: diff --git a/sflphone-common/src/dbus/callmanager.cpp b/sflphone-common/src/dbus/callmanager.cpp index 42cf7234d708bd8c314dad07153834c0eed1240c..d742a86ae0278bbe291f35f0595b7495a702159b 100644 --- a/sflphone-common/src/dbus/callmanager.cpp +++ b/sflphone-common/src/dbus/callmanager.cpp @@ -185,120 +185,127 @@ CallManager::startTone (const int32_t& start , const int32_t& type) // TODO: this will have to be adapted // for conferencing in order to get -// the right pointer for the given +// the right pointer for the given // callID. -sfl::AudioZrtpSession * CallManager::getAudioZrtpSession(void) +sfl::AudioZrtpSession * CallManager::getAudioZrtpSession (void) { SIPVoIPLink * link = NULL; link = dynamic_cast<SIPVoIPLink *> (Manager::instance().getAccountLink (AccountNULL)); + if (link == NULL) { _debug ("Failed to get sip link\n"); throw CallManagerException(); } - + sfl::AudioRtpFactory * audioRtp = NULL; + audioRtp = link->getAudioRtp(); + if (audioRtp == NULL) { _debug ("Failed to get AudioRtpFactory\n"); throw CallManagerException(); } - + sfl::AudioZrtpSession * zSession = NULL; + zSession = audioRtp->getAudioZrtpSession(); + if (zSession == NULL) { - _debug("Failed to get AudioZrtpSession\n"); + _debug ("Failed to get AudioZrtpSession\n"); throw CallManagerException(); - } - + } + return zSession; } void -CallManager::setSASVerified(const std::string& callID) +CallManager::setSASVerified (const std::string& callID) { - _debug("CallManager::setSASVerified received for account %s\n", callID.c_str()); - + _debug ("CallManager::setSASVerified received for account %s\n", callID.c_str()); + try { sfl::AudioZrtpSession * zSession; - zSession = getAudioZrtpSession(); + zSession = getAudioZrtpSession(); zSession->SASVerified(); } catch (...) { throw; } - + } void -CallManager::resetSASVerified(const std::string& callID) +CallManager::resetSASVerified (const std::string& callID) { - _debug("CallManager::resetSASVerified received for account %s\n", callID.c_str()); - + _debug ("CallManager::resetSASVerified received for account %s\n", callID.c_str()); + try { sfl::AudioZrtpSession * zSession; - zSession = getAudioZrtpSession(); + zSession = getAudioZrtpSession(); zSession->resetSASVerified(); } catch (...) { throw; } - + } void -CallManager::setConfirmGoClear(const std::string& callID) +CallManager::setConfirmGoClear (const std::string& callID) { - _debug("CallManager::setConfirmGoClear received for account %s\n", callID.c_str()); - + _debug ("CallManager::setConfirmGoClear received for account %s\n", callID.c_str()); + try { sfl::AudioZrtpSession * zSession; - zSession = getAudioZrtpSession(); + zSession = getAudioZrtpSession(); zSession->goClearOk(); } catch (...) { throw; } - + } void -CallManager::requestGoClear(const std::string& callID) +CallManager::requestGoClear (const std::string& callID) { - _debug("CallManager::requestGoClear received for account %s\n", callID.c_str()); - + _debug ("CallManager::requestGoClear received for account %s\n", callID.c_str()); + try { sfl::AudioZrtpSession * zSession; - zSession = getAudioZrtpSession(); + zSession = getAudioZrtpSession(); zSession->requestGoClear(); } catch (...) { throw; } - + } -void -CallManager::acceptEnrollment(const std::string& callID, const bool& accepted) { +void +CallManager::acceptEnrollment (const std::string& callID, const bool& accepted) +{ + + _debug ("CallManager::acceptEnrollment received for account %s\n", callID.c_str()); - _debug("CallManager::acceptEnrollment received for account %s\n", callID.c_str()); - try { sfl::AudioZrtpSession * zSession; - zSession = getAudioZrtpSession(); - zSession->acceptEnrollment(accepted); + zSession = getAudioZrtpSession(); + zSession->acceptEnrollment (accepted); } catch (...) { throw; } - + } -void -CallManager::setPBXEnrollment(const std::string& callID, const bool& yesNo) { +void +CallManager::setPBXEnrollment (const std::string& callID, const bool& yesNo) +{ - _debug("CallManager::setPBXEnrollment received for account %s\n", callID.c_str()); + _debug ("CallManager::setPBXEnrollment received for account %s\n", callID.c_str()); try { sfl::AudioZrtpSession * zSession; - zSession = getAudioZrtpSession(); - zSession->setPBXEnrollment(yesNo); + zSession = getAudioZrtpSession(); + zSession->setPBXEnrollment (yesNo); } catch (...) { throw; } - + } diff --git a/sflphone-common/src/dbus/configurationmanager-introspec.xml b/sflphone-common/src/dbus/configurationmanager-introspec.xml index f84e79f981f75086fe84858d8008c8fe7f32af09..d0400e9d4d252778d21daa0a18263ee238da8882 100644 --- a/sflphone-common/src/dbus/configurationmanager-introspec.xml +++ b/sflphone-common/src/dbus/configurationmanager-introspec.xml @@ -303,21 +303,6 @@ <arg type="i" name="port" direction="out"/> </method> - <method name="setStunServer"> - <arg type="s" name="server" direction="in"/> - </method> - - <method name="getStunServer"> - <arg type="s" name="server" direction="out"/> - </method> - - <method name="enableStun"> - </method> - - <method name="isStunEnabled"> - <arg type="i" name="state" direction="out"/> - </method> - <!-- Addressbook configuration --> <method name="getAddressbookSettings"> <annotation name="com.trolltech.QtDBus.QtTypeName.Out0" value="MapStringInt"/> diff --git a/sflphone-common/src/dbus/configurationmanager.cpp b/sflphone-common/src/dbus/configurationmanager.cpp index aee5f3cc6a9532f15946c2977d3590b39244507f..579700e824f04b00cc4c8b4509bb2895cf9c0039 100644 --- a/sflphone-common/src/dbus/configurationmanager.cpp +++ b/sflphone-common/src/dbus/configurationmanager.cpp @@ -46,177 +46,209 @@ std::map< std::string, std::string > ConfigurationManager::getTlsSettingsDefault (void) { _debug ("ConfigurationManager::getTlsDefaultSettings\n"); - + std::map<std::string, std::string> tlsSettingsDefault; - tlsSettingsDefault.insert(std::pair<std::string, std::string> (TLS_CA_LIST_FILE, "")); - tlsSettingsDefault.insert(std::pair<std::string, std::string> (TLS_CERTIFICATE_FILE, "")); - tlsSettingsDefault.insert(std::pair<std::string, std::string> (TLS_PRIVATE_KEY_FILE, "")); - tlsSettingsDefault.insert(std::pair<std::string, std::string> (TLS_PASSWORD, "")); - tlsSettingsDefault.insert(std::pair<std::string, std::string> (TLS_METHOD, "TLSv1")); - tlsSettingsDefault.insert(std::pair<std::string, std::string> (TLS_CIPHERS, "")); - tlsSettingsDefault.insert(std::pair<std::string, std::string> (TLS_SERVER_NAME, "")); - tlsSettingsDefault.insert(std::pair<std::string, std::string> (TLS_VERIFY_SERVER, "true")); - tlsSettingsDefault.insert(std::pair<std::string, std::string> (TLS_VERIFY_CLIENT, "true")); - tlsSettingsDefault.insert(std::pair<std::string, std::string> (TLS_REQUIRE_CLIENT_CERTIFICATE, "true")); - tlsSettingsDefault.insert(std::pair<std::string, std::string> (TLS_NEGOTIATION_TIMEOUT_SEC, "2")); - tlsSettingsDefault.insert(std::pair<std::string, std::string> (TLS_NEGOTIATION_TIMEOUT_MSEC, "0")); - + tlsSettingsDefault.insert (std::pair<std::string, std::string> (TLS_CA_LIST_FILE, "")); + tlsSettingsDefault.insert (std::pair<std::string, std::string> (TLS_CERTIFICATE_FILE, "")); + tlsSettingsDefault.insert (std::pair<std::string, std::string> (TLS_PRIVATE_KEY_FILE, "")); + tlsSettingsDefault.insert (std::pair<std::string, std::string> (TLS_PASSWORD, "")); + tlsSettingsDefault.insert (std::pair<std::string, std::string> (TLS_METHOD, "TLSv1")); + tlsSettingsDefault.insert (std::pair<std::string, std::string> (TLS_CIPHERS, "")); + tlsSettingsDefault.insert (std::pair<std::string, std::string> (TLS_SERVER_NAME, "")); + tlsSettingsDefault.insert (std::pair<std::string, std::string> (TLS_VERIFY_SERVER, "true")); + tlsSettingsDefault.insert (std::pair<std::string, std::string> (TLS_VERIFY_CLIENT, "true")); + tlsSettingsDefault.insert (std::pair<std::string, std::string> (TLS_REQUIRE_CLIENT_CERTIFICATE, "true")); + tlsSettingsDefault.insert (std::pair<std::string, std::string> (TLS_NEGOTIATION_TIMEOUT_SEC, "2")); + tlsSettingsDefault.insert (std::pair<std::string, std::string> (TLS_NEGOTIATION_TIMEOUT_MSEC, "0")); + return tlsSettingsDefault; } -std::map< std::string, std::string > -ConfigurationManager::getIp2IpDetails(void) +std::map< std::string, std::string > +ConfigurationManager::getIp2IpDetails (void) { - std::map<std::string, std::string> ip2ipAccountDetails; - - ip2ipAccountDetails.insert(std::pair<std::string, std::string> (SRTP_KEY_EXCHANGE, Manager::instance().getConfigString(IP2IP_PROFILE, SRTP_KEY_EXCHANGE))); - ip2ipAccountDetails.insert(std::pair<std::string, std::string> (SRTP_ENABLE, Manager::instance().getConfigString(IP2IP_PROFILE, SRTP_ENABLE))); - ip2ipAccountDetails.insert(std::pair<std::string, std::string> (ZRTP_DISPLAY_SAS, Manager::instance().getConfigString(IP2IP_PROFILE, ZRTP_DISPLAY_SAS))); - ip2ipAccountDetails.insert(std::pair<std::string, std::string> (ZRTP_HELLO_HASH, Manager::instance().getConfigString(IP2IP_PROFILE, ZRTP_HELLO_HASH))); - ip2ipAccountDetails.insert(std::pair<std::string, std::string> (ZRTP_NOT_SUPP_WARNING, Manager::instance().getConfigString(IP2IP_PROFILE, ZRTP_NOT_SUPP_WARNING))); - ip2ipAccountDetails.insert(std::pair<std::string, std::string> (ZRTP_DISPLAY_SAS_ONCE, Manager::instance().getConfigString(IP2IP_PROFILE, ZRTP_DISPLAY_SAS_ONCE))); - - std::map<std::string, std::string> tlsSettings; - tlsSettings = getTlsSettings(IP2IP_PROFILE); - std::copy(tlsSettings.begin(), tlsSettings.end(), std::inserter(ip2ipAccountDetails, ip2ipAccountDetails.end())); - - return ip2ipAccountDetails; - + std::map<std::string, std::string> ip2ipAccountDetails; + + ip2ipAccountDetails.insert (std::pair<std::string, std::string> (SRTP_KEY_EXCHANGE, Manager::instance().getConfigString (IP2IP_PROFILE, SRTP_KEY_EXCHANGE))); + ip2ipAccountDetails.insert (std::pair<std::string, std::string> (SRTP_ENABLE, Manager::instance().getConfigString (IP2IP_PROFILE, SRTP_ENABLE))); + ip2ipAccountDetails.insert (std::pair<std::string, std::string> (ZRTP_DISPLAY_SAS, Manager::instance().getConfigString (IP2IP_PROFILE, ZRTP_DISPLAY_SAS))); + ip2ipAccountDetails.insert (std::pair<std::string, std::string> (ZRTP_HELLO_HASH, Manager::instance().getConfigString (IP2IP_PROFILE, ZRTP_HELLO_HASH))); + ip2ipAccountDetails.insert (std::pair<std::string, std::string> (ZRTP_NOT_SUPP_WARNING, Manager::instance().getConfigString (IP2IP_PROFILE, ZRTP_NOT_SUPP_WARNING))); + ip2ipAccountDetails.insert (std::pair<std::string, std::string> (ZRTP_DISPLAY_SAS_ONCE, Manager::instance().getConfigString (IP2IP_PROFILE, ZRTP_DISPLAY_SAS_ONCE))); + + std::map<std::string, std::string> tlsSettings; + tlsSettings = getTlsSettings (IP2IP_PROFILE); + std::copy (tlsSettings.begin(), tlsSettings.end(), std::inserter (ip2ipAccountDetails, ip2ipAccountDetails.end())); + + return ip2ipAccountDetails; + } -void -ConfigurationManager::setIp2IpDetails(const std::map< std::string, std::string >& details ) +void +ConfigurationManager::setIp2IpDetails (const std::map< std::string, std::string >& details) { std::map<std::string, std::string> map_cpy = details; std::map<std::string, std::string>::iterator it; - - it = map_cpy.find(SRTP_ENABLE); + + it = map_cpy.find (SRTP_ENABLE); + if (it != details.end()) { - Manager::instance().setConfig(IP2IP_PROFILE, SRTP_ENABLE, it->second); + Manager::instance().setConfig (IP2IP_PROFILE, SRTP_ENABLE, it->second); } - - it = map_cpy.find(SRTP_KEY_EXCHANGE); + + it = map_cpy.find (SRTP_KEY_EXCHANGE); + if (it != details.end()) { - Manager::instance().setConfig(IP2IP_PROFILE, SRTP_KEY_EXCHANGE, it->second); + Manager::instance().setConfig (IP2IP_PROFILE, SRTP_KEY_EXCHANGE, it->second); } - - it = map_cpy.find(ZRTP_DISPLAY_SAS); + + it = map_cpy.find (ZRTP_DISPLAY_SAS); + if (it != details.end()) { - Manager::instance().setConfig(IP2IP_PROFILE, ZRTP_DISPLAY_SAS, it->second); + Manager::instance().setConfig (IP2IP_PROFILE, ZRTP_DISPLAY_SAS, it->second); } - it = map_cpy.find(ZRTP_NOT_SUPP_WARNING); + + it = map_cpy.find (ZRTP_NOT_SUPP_WARNING); + if (it != details.end()) { - Manager::instance().setConfig(IP2IP_PROFILE, ZRTP_NOT_SUPP_WARNING, it->second); + Manager::instance().setConfig (IP2IP_PROFILE, ZRTP_NOT_SUPP_WARNING, it->second); } - it = map_cpy.find(ZRTP_HELLO_HASH); + + it = map_cpy.find (ZRTP_HELLO_HASH); + if (it != details.end()) { - Manager::instance().setConfig(IP2IP_PROFILE, ZRTP_HELLO_HASH, it->second); + Manager::instance().setConfig (IP2IP_PROFILE, ZRTP_HELLO_HASH, it->second); } - it = map_cpy.find(ZRTP_DISPLAY_SAS_ONCE); + + it = map_cpy.find (ZRTP_DISPLAY_SAS_ONCE); + if (it != details.end()) { - Manager::instance().setConfig(IP2IP_PROFILE, ZRTP_DISPLAY_SAS_ONCE, it->second); + Manager::instance().setConfig (IP2IP_PROFILE, ZRTP_DISPLAY_SAS_ONCE, it->second); } - - setTlsSettings(IP2IP_PROFILE, details); - + + setTlsSettings (IP2IP_PROFILE, details); + Manager::instance().saveConfig(); - + // Update account details to the client side accountsChanged(); } -std::map< std::string, std::string > -ConfigurationManager::getTlsSettings(const std::string& section) -{ - std::map<std::string, std::string> tlsSettings; - tlsSettings.insert(std::pair<std::string, std::string> - (TLS_ENABLE, Manager::instance().getConfigString(section, TLS_ENABLE))); - tlsSettings.insert(std::pair<std::string, std::string> - (TLS_CA_LIST_FILE, Manager::instance().getConfigString(section, TLS_CA_LIST_FILE))); - tlsSettings.insert(std::pair<std::string, std::string> - (TLS_CERTIFICATE_FILE, Manager::instance().getConfigString(section, TLS_CERTIFICATE_FILE))); - tlsSettings.insert(std::pair<std::string, std::string> - (TLS_PRIVATE_KEY_FILE, Manager::instance().getConfigString(section, TLS_PRIVATE_KEY_FILE))); - tlsSettings.insert(std::pair<std::string, std::string> - (TLS_PASSWORD, Manager::instance().getConfigString(section, TLS_PASSWORD))); - tlsSettings.insert(std::pair<std::string, std::string> - (TLS_METHOD, Manager::instance().getConfigString(section, TLS_METHOD))); - tlsSettings.insert(std::pair<std::string, std::string> - (TLS_CIPHERS, Manager::instance().getConfigString(section, TLS_CIPHERS))); - tlsSettings.insert(std::pair<std::string, std::string> - (TLS_SERVER_NAME, Manager::instance().getConfigString(section, TLS_SERVER_NAME))); - tlsSettings.insert(std::pair<std::string, std::string> - (TLS_VERIFY_SERVER, Manager::instance().getConfigString(section, TLS_VERIFY_SERVER))); - tlsSettings.insert(std::pair<std::string, std::string> - (TLS_VERIFY_CLIENT, Manager::instance().getConfigString(section, TLS_VERIFY_CLIENT))); - tlsSettings.insert(std::pair<std::string, std::string> - (TLS_REQUIRE_CLIENT_CERTIFICATE, Manager::instance().getConfigString(section, TLS_REQUIRE_CLIENT_CERTIFICATE))); - tlsSettings.insert(std::pair<std::string, std::string> - (TLS_NEGOTIATION_TIMEOUT_SEC, Manager::instance().getConfigString(section, TLS_NEGOTIATION_TIMEOUT_SEC))); - tlsSettings.insert(std::pair<std::string, std::string> - (TLS_NEGOTIATION_TIMEOUT_MSEC, Manager::instance().getConfigString(section, TLS_NEGOTIATION_TIMEOUT_MSEC))); - return tlsSettings; -} - -void -ConfigurationManager::setTlsSettings(const std::string& section, const std::map< std::string, std::string >& details ) +std::map< std::string, std::string > +ConfigurationManager::getTlsSettings (const std::string& section) +{ + std::map<std::string, std::string> tlsSettings; + tlsSettings.insert (std::pair<std::string, std::string> + (TLS_ENABLE, Manager::instance().getConfigString (section, TLS_ENABLE))); + tlsSettings.insert (std::pair<std::string, std::string> + (TLS_CA_LIST_FILE, Manager::instance().getConfigString (section, TLS_CA_LIST_FILE))); + tlsSettings.insert (std::pair<std::string, std::string> + (TLS_CERTIFICATE_FILE, Manager::instance().getConfigString (section, TLS_CERTIFICATE_FILE))); + tlsSettings.insert (std::pair<std::string, std::string> + (TLS_PRIVATE_KEY_FILE, Manager::instance().getConfigString (section, TLS_PRIVATE_KEY_FILE))); + tlsSettings.insert (std::pair<std::string, std::string> + (TLS_PASSWORD, Manager::instance().getConfigString (section, TLS_PASSWORD))); + tlsSettings.insert (std::pair<std::string, std::string> + (TLS_METHOD, Manager::instance().getConfigString (section, TLS_METHOD))); + tlsSettings.insert (std::pair<std::string, std::string> + (TLS_CIPHERS, Manager::instance().getConfigString (section, TLS_CIPHERS))); + tlsSettings.insert (std::pair<std::string, std::string> + (TLS_SERVER_NAME, Manager::instance().getConfigString (section, TLS_SERVER_NAME))); + tlsSettings.insert (std::pair<std::string, std::string> + (TLS_VERIFY_SERVER, Manager::instance().getConfigString (section, TLS_VERIFY_SERVER))); + tlsSettings.insert (std::pair<std::string, std::string> + (TLS_VERIFY_CLIENT, Manager::instance().getConfigString (section, TLS_VERIFY_CLIENT))); + tlsSettings.insert (std::pair<std::string, std::string> + (TLS_REQUIRE_CLIENT_CERTIFICATE, Manager::instance().getConfigString (section, TLS_REQUIRE_CLIENT_CERTIFICATE))); + tlsSettings.insert (std::pair<std::string, std::string> + (TLS_NEGOTIATION_TIMEOUT_SEC, Manager::instance().getConfigString (section, TLS_NEGOTIATION_TIMEOUT_SEC))); + tlsSettings.insert (std::pair<std::string, std::string> + (TLS_NEGOTIATION_TIMEOUT_MSEC, Manager::instance().getConfigString (section, TLS_NEGOTIATION_TIMEOUT_MSEC))); + return tlsSettings; +} + +void +ConfigurationManager::setTlsSettings (const std::string& section, const std::map< std::string, std::string >& details) { std::map<std::string, std::string> map_cpy = details; std::map<std::string, std::string>::iterator it; - - it = map_cpy.find(TLS_ENABLE); + + it = map_cpy.find (TLS_ENABLE); + if (it != details.end()) { - Manager::instance().setConfig(section, TLS_ENABLE, it->second); + Manager::instance().setConfig (section, TLS_ENABLE, it->second); } - it = map_cpy.find(TLS_CA_LIST_FILE); + + it = map_cpy.find (TLS_CA_LIST_FILE); + if (it != map_cpy.end()) { - Manager::instance().setConfig(section, TLS_CA_LIST_FILE, it->second); + Manager::instance().setConfig (section, TLS_CA_LIST_FILE, it->second); } - it = map_cpy.find(TLS_CERTIFICATE_FILE); + + it = map_cpy.find (TLS_CERTIFICATE_FILE); + if (it != map_cpy.end()) { - Manager::instance().setConfig(section, TLS_CERTIFICATE_FILE, it->second); + Manager::instance().setConfig (section, TLS_CERTIFICATE_FILE, it->second); } - it = map_cpy.find(TLS_PRIVATE_KEY_FILE); + + it = map_cpy.find (TLS_PRIVATE_KEY_FILE); + if (it != map_cpy.end()) { - Manager::instance().setConfig(section, TLS_PRIVATE_KEY_FILE, it->second); + Manager::instance().setConfig (section, TLS_PRIVATE_KEY_FILE, it->second); } - it = map_cpy.find(TLS_PASSWORD); + + it = map_cpy.find (TLS_PASSWORD); + if (it != map_cpy.end()) { - Manager::instance().setConfig(section, TLS_PASSWORD, it->second); + Manager::instance().setConfig (section, TLS_PASSWORD, it->second); } - it = map_cpy.find(TLS_METHOD); + + it = map_cpy.find (TLS_METHOD); + if (it != map_cpy.end()) { - Manager::instance().setConfig(section, TLS_METHOD, it->second); + Manager::instance().setConfig (section, TLS_METHOD, it->second); } - it = map_cpy.find(TLS_CIPHERS); + + it = map_cpy.find (TLS_CIPHERS); + if (it != map_cpy.end()) { - Manager::instance().setConfig(section, TLS_CIPHERS, it->second); + Manager::instance().setConfig (section, TLS_CIPHERS, it->second); } - it = map_cpy.find(TLS_SERVER_NAME); + + it = map_cpy.find (TLS_SERVER_NAME); + if (it != map_cpy.end()) { - Manager::instance().setConfig(section, TLS_SERVER_NAME, it->second); - } - it = map_cpy.find(TLS_VERIFY_CLIENT); + Manager::instance().setConfig (section, TLS_SERVER_NAME, it->second); + } + + it = map_cpy.find (TLS_VERIFY_CLIENT); + if (it != map_cpy.end()) { - Manager::instance().setConfig(section, TLS_VERIFY_CLIENT, it->second); + Manager::instance().setConfig (section, TLS_VERIFY_CLIENT, it->second); } - it = map_cpy.find(TLS_REQUIRE_CLIENT_CERTIFICATE); + + it = map_cpy.find (TLS_REQUIRE_CLIENT_CERTIFICATE); + if (it != map_cpy.end()) { - Manager::instance().setConfig(section, TLS_REQUIRE_CLIENT_CERTIFICATE, it->second); + Manager::instance().setConfig (section, TLS_REQUIRE_CLIENT_CERTIFICATE, it->second); } - it = map_cpy.find(TLS_NEGOTIATION_TIMEOUT_SEC); + + it = map_cpy.find (TLS_NEGOTIATION_TIMEOUT_SEC); + if (it != map_cpy.end()) { - Manager::instance().setConfig(section, TLS_NEGOTIATION_TIMEOUT_SEC, it->second); - } - it = map_cpy.find(TLS_NEGOTIATION_TIMEOUT_MSEC); + Manager::instance().setConfig (section, TLS_NEGOTIATION_TIMEOUT_SEC, it->second); + } + + it = map_cpy.find (TLS_NEGOTIATION_TIMEOUT_MSEC); + if (it != map_cpy.end()) { - Manager::instance().setConfig(section, TLS_NEGOTIATION_TIMEOUT_MSEC, it->second); - } - + Manager::instance().setConfig (section, TLS_NEGOTIATION_TIMEOUT_MSEC, it->second); + } + Manager::instance().saveConfig(); - + // Update account details to the client side accountsChanged(); @@ -231,18 +263,18 @@ ConfigurationManager::getCredential (const std::string& accountID, const int32_t std::stringstream streamOut; streamOut << index; credentialIndex = streamOut.str(); - - std::string section = std::string("Credential") + std::string(":") + accountID + std::string(":") + credentialIndex; - + + std::string section = std::string ("Credential") + std::string (":") + accountID + std::string (":") + credentialIndex; + std::map<std::string, std::string> credentialInformation; - std::string username = Manager::instance().getConfigString(section, USERNAME); - std::string password = Manager::instance().getConfigString(section, PASSWORD); - std::string realm = Manager::instance().getConfigString(section, REALM); - - credentialInformation.insert(std::pair<std::string, std::string> (USERNAME, username)); - credentialInformation.insert(std::pair<std::string, std::string> (PASSWORD, password)); - credentialInformation.insert(std::pair<std::string, std::string> (REALM, realm)); - + std::string username = Manager::instance().getConfigString (section, USERNAME); + std::string password = Manager::instance().getConfigString (section, PASSWORD); + std::string realm = Manager::instance().getConfigString (section, REALM); + + credentialInformation.insert (std::pair<std::string, std::string> (USERNAME, username)); + credentialInformation.insert (std::pair<std::string, std::string> (PASSWORD, password)); + credentialInformation.insert (std::pair<std::string, std::string> (REALM, realm)); + return credentialInformation; } @@ -260,13 +292,13 @@ ConfigurationManager::setNumberOfCredential (const std::string& accountID, const Manager::instance().setConfig (accountID, CONFIG_CREDENTIAL_NUMBER, number); } } - + void ConfigurationManager::setCredential (const std::string& accountID, const int32_t& index, - const std::map< std::string, std::string >& details) + const std::map< std::string, std::string >& details) { _debug ("ConfigurationManager::setCredential received\n"); - Manager::instance().setCredential(accountID, index, details); + Manager::instance().setCredential (accountID, index, details); } void @@ -343,22 +375,22 @@ ConfigurationManager::getRingtoneList() std::vector< std::string > -ConfigurationManager::getCodecList(void) +ConfigurationManager::getCodecList (void) { _debug ("ConfigurationManager::getCodecList received\n"); return Manager::instance().getCodecList(); } std::vector<std::string> -ConfigurationManager::getSupportedTlsMethod(void) +ConfigurationManager::getSupportedTlsMethod (void) { _debug ("ConfigurationManager::getSupportedTlsMethod received\n"); std::vector<std::string> method; - method.push_back("Default"); - method.push_back("TLSv1"); - method.push_back("SSLv2"); - method.push_back("SSLv3"); - method.push_back("SSLv23"); + method.push_back ("Default"); + method.push_back ("TLSv1"); + method.push_back ("SSLv2"); + method.push_back ("SSLv3"); + method.push_back ("SSLv23"); return method; } @@ -480,19 +512,19 @@ ConfigurationManager::getRecordDeviceList() } bool -ConfigurationManager::isMd5CredentialHashing(void) +ConfigurationManager::isMd5CredentialHashing (void) { - bool isEnabled = Manager::instance().getConfigBool(PREFERENCES, CONFIG_MD5HASH); + bool isEnabled = Manager::instance().getConfigBool (PREFERENCES, CONFIG_MD5HASH); return isEnabled; } -void -ConfigurationManager::setMd5CredentialHashing(const bool& enabled) +void +ConfigurationManager::setMd5CredentialHashing (const bool& enabled) { if (enabled) { - Manager::instance().setConfig(PREFERENCES, CONFIG_MD5HASH, TRUE_STR); + Manager::instance().setConfig (PREFERENCES, CONFIG_MD5HASH, TRUE_STR); } else { - Manager::instance().setConfig(PREFERENCES, CONFIG_MD5HASH, FALSE_STR); + Manager::instance().setConfig (PREFERENCES, CONFIG_MD5HASH, FALSE_STR); } } @@ -692,30 +724,6 @@ ConfigurationManager::setSipPort (const int32_t& portNum) Manager::instance().setSipPort (portNum); } -std::string ConfigurationManager::getStunServer (void) -{ - _debug ("Manager received getStunServer\n") ; - return Manager::instance().getStunServer(); -} - -void ConfigurationManager::setStunServer (const std::string& server) -{ - _debug ("Manager received setStunServer\n") ; - Manager::instance().setStunServer (server); -} - -void ConfigurationManager::enableStun (void) -{ - _debug ("Manager received enableStun\n") ; - Manager::instance().enableStun(); -} - -int32_t ConfigurationManager::isStunEnabled (void) -{ - _debug ("Manager received isStunEnabled\n") ; - return Manager::instance().isStunEnabled(); -} - std::map<std::string, int32_t> ConfigurationManager::getAddressbookSettings (void) { return Manager::instance().getAddressbookSettings (); @@ -762,16 +770,17 @@ void ConfigurationManager::setHistory (const std::map <std::string, std::string> Manager::instance().receive_history_from_client (entries); } -std::vector<std::string> ConfigurationManager::getAllIpInterface(void) +std::vector<std::string> ConfigurationManager::getAllIpInterface (void) { _debug ("ConfigurationManager::getAllIpInterface received\n"); - + std::vector<std::string> vector; SIPVoIPLink * sipLink = NULL; sipLink = SIPVoIPLink::instance (""); + if (sipLink != NULL) { vector = sipLink->getAllIpInterface(); } - + return vector; } diff --git a/sflphone-common/src/dbus/configurationmanager.h b/sflphone-common/src/dbus/configurationmanager.h index 600ae00f0ed9f1197cb2c59fbc36614b7d1374be..08092c18d083e80289e3d3e215f1539b94f07cb0 100644 --- a/sflphone-common/src/dbus/configurationmanager.h +++ b/sflphone-common/src/dbus/configurationmanager.h @@ -117,10 +117,6 @@ public: void setPulseAppVolumeControl( void ); int32_t getSipPort( void ); void setSipPort( const int32_t& portNum); - std::string getStunServer( void ); - void setStunServer( const std::string& server ); - void enableStun (void); - int32_t isStunEnabled (void); std::map<std::string, int32_t> getAddressbookSettings (void); void setAddressbookSettings (const std::map<std::string, int32_t>& settings); diff --git a/sflphone-common/src/global.h b/sflphone-common/src/global.h index a660b9a8a5354734f9721a2d9bd6e7a42c470775..b8ebe7789fc3b28981603aba8ff010fe326d19ea 100644 --- a/sflphone-common/src/global.h +++ b/sflphone-common/src/global.h @@ -121,7 +121,6 @@ static const SOUND_FORMAT INT32 = 0x8; #define START_HIDDEN TRUE_STR /** SFlphone starts hidden at start-up or not */ #define WINDOW_POPUP TRUE_STR /** Popup mode */ #define NOTIFY_ALL TRUE_STR /** Desktop notification level 0: never notify */ -#define STUN_ENABLED TRUE_STR // Error codes for error handling #define NO_ERROR 0x0000 /** No error - Everything alright */ diff --git a/sflphone-common/src/history/historymanager.cpp b/sflphone-common/src/history/historymanager.cpp index 008361e059cb933ba223b30bbb29e6ed1452ee55..d56d3f67155aa3cd67a2b4bc380a3bf7c3f50170 100644 --- a/sflphone-common/src/history/historymanager.cpp +++ b/sflphone-common/src/history/historymanager.cpp @@ -109,7 +109,7 @@ int HistoryManager::load_history_items_map (Conf::ConfigTree *history_list, int bool HistoryManager::save_history_to_file (Conf::ConfigTree *history_list) { - _debug ("Saving history in XDG directory: %s\n", _history_path.data()); + _debug ("Saving history in XDG directory: %s\n", _history_path.data()); return history_list->saveConfigTree (_history_path.data()); } @@ -149,20 +149,18 @@ int HistoryManager::create_history_path (std::string path) std::string userdata, xdg_env, xdg_data; - xdg_data = std::string (HOMEDIR) + DIR_SEPARATOR_STR + ".local/share/sflphone"; + xdg_data = std::string (HOMEDIR) + DIR_SEPARATOR_STR + ".local/share/sflphone"; if (path == "") { - // If the environment variable is set (not null and not empty), we'll use it to save the history - // Else we 'll the standard one, ie: XDG_DATA_HOME = $HOMEDIR/.local/share/sflphone - if (XDG_DATA_HOME != NULL) - { - xdg_env = std::string (XDG_DATA_HOME); - (xdg_env.length() > 0) ? userdata = xdg_env - : userdata = xdg_data; - } - else - userdata = xdg_data; + // If the environment variable is set (not null and not empty), we'll use it to save the history + // Else we 'll the standard one, ie: XDG_DATA_HOME = $HOMEDIR/.local/share/sflphone + if (XDG_DATA_HOME != NULL) { + xdg_env = std::string (XDG_DATA_HOME); + (xdg_env.length() > 0) ? userdata = xdg_env + : userdata = xdg_data; + } else + userdata = xdg_data; if (mkdir (userdata.data(), 0755) != 0) { // If directory creation failed diff --git a/sflphone-common/src/iax/iaxvoiplink.h b/sflphone-common/src/iax/iaxvoiplink.h index 2a68d51e42ea0dd4b6f7572bbce11235c4d0e61b..a08c40a39a8aa78c9678fb2c25c528cb6d30b509 100644 --- a/sflphone-common/src/iax/iaxvoiplink.h +++ b/sflphone-common/src/iax/iaxvoiplink.h @@ -202,8 +202,6 @@ class IAXVoIPLink : public VoIPLink void updateAudiolayer( void ); - void setStunServer( const std::string &server ) {}; - private: /* diff --git a/sflphone-common/src/main.cpp b/sflphone-common/src/main.cpp index 5bb1db3f9d08cde9e9f5cfba46e9f59b0ad5060a..8de4f43532a81f419b9717a569bc79844057cad3 100644 --- a/sflphone-common/src/main.cpp +++ b/sflphone-common/src/main.cpp @@ -60,20 +60,19 @@ main (int argc, char **argv) unsigned int iPid = getpid(); char cPid[64], cOldPid[64]; sprintf (cPid,"%d", iPid); - std::string xdg_config, xdg_env, path; + std::string xdg_config, xdg_env, path; - xdg_config = std::string (HOMEDIR) + DIR_SEPARATOR_STR + ".cache/sflphone"; + xdg_config = std::string (HOMEDIR) + DIR_SEPARATOR_STR + ".cache/sflphone"; - if (XDG_CACHE_HOME != NULL) - { - xdg_env = std::string (XDG_CACHE_HOME); - (xdg_env.length() > 0) ? path = xdg_env - : path = xdg_config; - } - else - path = xdg_config; + if (XDG_CACHE_HOME != NULL) { + xdg_env = std::string (XDG_CACHE_HOME); + (xdg_env.length() > 0) ? path = xdg_env + : path = xdg_config; + } else + path = xdg_config; sprintf (sfldir, "%s", path.c_str ()); + sprintf (homepid, "%s/%s", path.c_str (), PIDFILE); if ( (fp = fopen (homepid,"r")) == NULL) { diff --git a/sflphone-common/src/managerimpl.cpp b/sflphone-common/src/managerimpl.cpp index 7995e97f9bb1a816568034492e7e48857484191e..4078b471a78f281275f039158ce4aff309a4c4ea 100644 --- a/sflphone-common/src/managerimpl.cpp +++ b/sflphone-common/src/managerimpl.cpp @@ -288,25 +288,31 @@ ManagerImpl::answerCall (const CallID& id) AccountID currentAccountId; currentAccountId = getAccountFromCall (id); - if(currentAccountId == AccountNULL) { - _debug("ManagerImpl::answerCall : AccountId is null\n"); + + if (currentAccountId == AccountNULL) { + _debug ("ManagerImpl::answerCall : AccountId is null\n"); } - + Call* currentCall = NULL; + currentCall = getAccountLink (currentAccountId)->getCall (id); + if (currentCall == NULL) { - _debug("ManagerImpl::answerCall : currentCall is null\n"); + _debug ("ManagerImpl::answerCall : currentCall is null\n"); } - + Call* lastCall = NULL; + if (!getCurrentCallId().empty()) { lastCall = getAccountLink (currentAccountId)->getCall (getCurrentCallId()); + if (lastCall == NULL) { - _debug("ManagerImpl::answerCall : lastCall is null\n"); + _debug ("ManagerImpl::answerCall : lastCall is null\n"); } } _debug ("ManagerImpl::answerCall :: current call->getState %i \n", currentCall->getState()); + _debug ("Try to answer call: %s\n", id.data()); if (lastCall != NULL) { @@ -324,10 +330,11 @@ ManagerImpl::answerCall (const CallID& id) // if it was waiting, it's waiting no more if (_dbus) _dbus->getCallManager()->callStateChanged (id, "CURRENT"); - + std::string codecName = Manager::instance().getCurrentCodecName (id); + if (_dbus) _dbus->getCallManager()->currentSelectedCodec (id,codecName.c_str()); - + removeWaitingCall (id); switchCall (id); @@ -1059,7 +1066,7 @@ void ManagerImpl::stopTone (bool stopAudio=true) { bool hasToPlayTone; - hasToPlayTone = getConfigBool(SIGNALISATION, PLAY_TONES); + hasToPlayTone = getConfigBool (SIGNALISATION, PLAY_TONES); if (!hasToPlayTone) return; @@ -1289,21 +1296,20 @@ int ManagerImpl::createSettingsPath (void) { - std::string xdg_config, xdg_env; + std::string xdg_config, xdg_env; - _debug ("XDG_CONFIG_HOME: %s\n", XDG_CONFIG_HOME); + _debug ("XDG_CONFIG_HOME: %s\n", XDG_CONFIG_HOME); - xdg_config = std::string (HOMEDIR) + DIR_SEPARATOR_STR + ".config" + DIR_SEPARATOR_STR + PROGDIR; + xdg_config = std::string (HOMEDIR) + DIR_SEPARATOR_STR + ".config" + DIR_SEPARATOR_STR + PROGDIR; //_path = std::string (HOMEDIR) + DIR_SEPARATOR_STR + "." + PROGDIR; - if (XDG_CONFIG_HOME != NULL) - { - xdg_env = std::string (XDG_CONFIG_HOME); - (xdg_env.length() > 0) ? _path = xdg_env - : _path = xdg_config; - } - else - _path = xdg_config; + + if (XDG_CONFIG_HOME != NULL) { + xdg_env = std::string (XDG_CONFIG_HOME); + (xdg_env.length() > 0) ? _path = xdg_env + : _path = xdg_config; + } else + _path = xdg_config; if (mkdir (_path.data(), 0700) != 0) { // If directory creation failed @@ -1325,124 +1331,139 @@ ManagerImpl::createSettingsPath (void) void ManagerImpl::initConfigFile (bool load_user_value, std::string alternate) { - _debug("ManagerImpl::InitConfigFile\n"); - + _debug ("ManagerImpl::InitConfigFile\n"); + // Default values, that will be overwritten by the call to - // 'populateFromFile' below. - + // 'populateFromFile' below. + // Peer to peer settings - _config.addDefaultValue(std::pair<std::string, std::string> (SRTP_ENABLE, FALSE_STR), IP2IP_PROFILE); - _config.addDefaultValue(std::pair<std::string, std::string> (SRTP_KEY_EXCHANGE, "1"), IP2IP_PROFILE); - _config.addDefaultValue(std::pair<std::string, std::string> (ZRTP_HELLO_HASH, TRUE_STR), IP2IP_PROFILE); - _config.addDefaultValue(std::pair<std::string, std::string> (ZRTP_DISPLAY_SAS, TRUE_STR), IP2IP_PROFILE); - _config.addDefaultValue(std::pair<std::string, std::string> (ZRTP_DISPLAY_SAS_ONCE, FALSE_STR), IP2IP_PROFILE); - _config.addDefaultValue(std::pair<std::string, std::string> (ZRTP_NOT_SUPP_WARNING, TRUE_STR), IP2IP_PROFILE); - _config.addDefaultValue(std::pair<std::string, std::string> (TLS_ENABLE, FALSE_STR), IP2IP_PROFILE); - _config.addDefaultValue(std::pair<std::string, std::string> (TLS_CA_LIST_FILE, EMPTY_FIELD), IP2IP_PROFILE); - _config.addDefaultValue(std::pair<std::string, std::string> (TLS_CERTIFICATE_FILE, EMPTY_FIELD), IP2IP_PROFILE); - _config.addDefaultValue(std::pair<std::string, std::string> (TLS_PRIVATE_KEY_FILE, EMPTY_FIELD), IP2IP_PROFILE); - _config.addDefaultValue(std::pair<std::string, std::string> (TLS_PASSWORD, EMPTY_FIELD), IP2IP_PROFILE); - _config.addDefaultValue(std::pair<std::string, std::string> (TLS_METHOD, "TLSv1"), IP2IP_PROFILE); - _config.addDefaultValue(std::pair<std::string, std::string> (TLS_CIPHERS, EMPTY_FIELD), IP2IP_PROFILE); - _config.addDefaultValue(std::pair<std::string, std::string> (TLS_SERVER_NAME, EMPTY_FIELD), IP2IP_PROFILE); - _config.addDefaultValue(std::pair<std::string, std::string> (TLS_VERIFY_SERVER, TRUE_STR), IP2IP_PROFILE); - _config.addDefaultValue(std::pair<std::string, std::string> (TLS_VERIFY_CLIENT, TRUE_STR), IP2IP_PROFILE); - _config.addDefaultValue(std::pair<std::string, std::string> (TLS_REQUIRE_CLIENT_CERTIFICATE, TRUE_STR), IP2IP_PROFILE); - _config.addDefaultValue(std::pair<std::string, std::string> (TLS_NEGOTIATION_TIMEOUT_SEC, "2"), IP2IP_PROFILE); - _config.addDefaultValue(std::pair<std::string, std::string> (TLS_NEGOTIATION_TIMEOUT_MSEC, "0"), IP2IP_PROFILE); - _config.addDefaultValue(std::pair<std::string, std::string> (LOCAL_PORT, DEFAULT_SIP_PORT), IP2IP_PROFILE); - _config.addDefaultValue(std::pair<std::string, std::string> (PUBLISHED_PORT, DEFAULT_SIP_PORT), IP2IP_PROFILE); - _config.addDefaultValue(std::pair<std::string, std::string> (LOCAL_ADDRESS, DEFAULT_ADDRESS), IP2IP_PROFILE); - _config.addDefaultValue(std::pair<std::string, std::string> (PUBLISHED_ADDRESS, DEFAULT_ADDRESS), IP2IP_PROFILE); - - // Init display name to the username under which + _config.addDefaultValue (std::pair<std::string, std::string> (SRTP_ENABLE, FALSE_STR), IP2IP_PROFILE); + _config.addDefaultValue (std::pair<std::string, std::string> (SRTP_KEY_EXCHANGE, "1"), IP2IP_PROFILE); + _config.addDefaultValue (std::pair<std::string, std::string> (ZRTP_HELLO_HASH, TRUE_STR), IP2IP_PROFILE); + _config.addDefaultValue (std::pair<std::string, std::string> (ZRTP_DISPLAY_SAS, TRUE_STR), IP2IP_PROFILE); + _config.addDefaultValue (std::pair<std::string, std::string> (ZRTP_DISPLAY_SAS_ONCE, FALSE_STR), IP2IP_PROFILE); + _config.addDefaultValue (std::pair<std::string, std::string> (ZRTP_NOT_SUPP_WARNING, TRUE_STR), IP2IP_PROFILE); + _config.addDefaultValue (std::pair<std::string, std::string> (TLS_ENABLE, FALSE_STR), IP2IP_PROFILE); + _config.addDefaultValue (std::pair<std::string, std::string> (TLS_CA_LIST_FILE, EMPTY_FIELD), IP2IP_PROFILE); + _config.addDefaultValue (std::pair<std::string, std::string> (TLS_CERTIFICATE_FILE, EMPTY_FIELD), IP2IP_PROFILE); + _config.addDefaultValue (std::pair<std::string, std::string> (TLS_PRIVATE_KEY_FILE, EMPTY_FIELD), IP2IP_PROFILE); + _config.addDefaultValue (std::pair<std::string, std::string> (TLS_PASSWORD, EMPTY_FIELD), IP2IP_PROFILE); + _config.addDefaultValue (std::pair<std::string, std::string> (TLS_METHOD, "TLSv1"), IP2IP_PROFILE); + _config.addDefaultValue (std::pair<std::string, std::string> (TLS_CIPHERS, EMPTY_FIELD), IP2IP_PROFILE); + _config.addDefaultValue (std::pair<std::string, std::string> (TLS_SERVER_NAME, EMPTY_FIELD), IP2IP_PROFILE); + _config.addDefaultValue (std::pair<std::string, std::string> (TLS_VERIFY_SERVER, TRUE_STR), IP2IP_PROFILE); + _config.addDefaultValue (std::pair<std::string, std::string> (TLS_VERIFY_CLIENT, TRUE_STR), IP2IP_PROFILE); + _config.addDefaultValue (std::pair<std::string, std::string> (TLS_REQUIRE_CLIENT_CERTIFICATE, TRUE_STR), IP2IP_PROFILE); + _config.addDefaultValue (std::pair<std::string, std::string> (TLS_NEGOTIATION_TIMEOUT_SEC, "2"), IP2IP_PROFILE); + _config.addDefaultValue (std::pair<std::string, std::string> (TLS_NEGOTIATION_TIMEOUT_MSEC, "0"), IP2IP_PROFILE); + _config.addDefaultValue (std::pair<std::string, std::string> (LOCAL_PORT, DEFAULT_SIP_PORT), IP2IP_PROFILE); + _config.addDefaultValue (std::pair<std::string, std::string> (PUBLISHED_PORT, DEFAULT_SIP_PORT), IP2IP_PROFILE); + _config.addDefaultValue (std::pair<std::string, std::string> (LOCAL_ADDRESS, DEFAULT_ADDRESS), IP2IP_PROFILE); + _config.addDefaultValue (std::pair<std::string, std::string> (PUBLISHED_ADDRESS, DEFAULT_ADDRESS), IP2IP_PROFILE); + _config.addDefaultValue (std::pair<std::string, std::string> (STUN_ENABLE, DFT_STUN_ENABLE), IP2IP_PROFILE); + _config.addDefaultValue (std::pair<std::string, std::string> (STUN_SERVER, DFT_STUN_SERVER), IP2IP_PROFILE); + + // Init display name to the username under which // this sflphone instance is running. - std::string diplayName(""); + std::string diplayName (""); uid_t uid = getuid(); + struct passwd * user_info = NULL; - user_info = getpwuid(uid); + user_info = getpwuid (uid); + if (user_info != NULL) { diplayName = user_info->pw_name; } - _config.addDefaultValue(std::pair<std::string, std::string> (DISPLAY_NAME, diplayName), IP2IP_PROFILE); - - // Signalisation settings - _config.addDefaultValue(std::pair<std::string, std::string> (SYMMETRIC, TRUE_STR), SIGNALISATION); - _config.addDefaultValue(std::pair<std::string, std::string> (PLAY_DTMF, TRUE_STR), SIGNALISATION); - _config.addDefaultValue(std::pair<std::string, std::string> (PLAY_TONES, TRUE_STR), SIGNALISATION); - _config.addDefaultValue(std::pair<std::string, std::string> (PULSE_LENGTH, DFT_PULSE_LENGTH_STR), SIGNALISATION); - _config.addDefaultValue(std::pair<std::string, std::string> (SEND_DTMF_AS, SIP_INFO_STR), SIGNALISATION); - _config.addDefaultValue(std::pair<std::string, std::string> (ZRTP_ZIDFILE, ZRTP_ZID_FILENAME), SIGNALISATION); - - // Audio settings - _config.addDefaultValue(std::pair<std::string, std::string> (ALSA_CARD_ID_IN, ALSA_DFT_CARD), AUDIO); - _config.addDefaultValue(std::pair<std::string, std::string> (ALSA_CARD_ID_OUT, ALSA_DFT_CARD), AUDIO); - _config.addDefaultValue(std::pair<std::string, std::string> (ALSA_SAMPLE_RATE, DFT_SAMPLE_RATE), AUDIO); - _config.addDefaultValue(std::pair<std::string, std::string> (ALSA_FRAME_SIZE, DFT_FRAME_SIZE), AUDIO); - _config.addDefaultValue(std::pair<std::string, std::string> (ALSA_PLUGIN, PCM_DEFAULT), AUDIO); - _config.addDefaultValue(std::pair<std::string, std::string> (RING_CHOICE, DFT_RINGTONE), AUDIO); - _config.addDefaultValue(std::pair<std::string, std::string> (VOLUME_SPKR, DFT_VOL_SPKR_STR), AUDIO); - _config.addDefaultValue(std::pair<std::string, std::string> (VOLUME_MICRO, DFT_VOL_MICRO_STR), AUDIO); - _config.addDefaultValue(std::pair<std::string, std::string> (RECORD_PATH,DFT_RECORD_PATH), AUDIO); - - // General settings - _config.addDefaultValue(std::pair<std::string, std::string> (ZONE_TONE, DFT_ZONE), PREFERENCES); - _config.addDefaultValue(std::pair<std::string, std::string> (CONFIG_RINGTONE, TRUE_STR), PREFERENCES); - _config.addDefaultValue(std::pair<std::string, std::string> (CONFIG_DIALPAD, TRUE_STR), PREFERENCES); - _config.addDefaultValue(std::pair<std::string, std::string> (CONFIG_SEARCHBAR, TRUE_STR), PREFERENCES); - _config.addDefaultValue(std::pair<std::string, std::string> (CONFIG_START, FALSE_STR), PREFERENCES); - _config.addDefaultValue(std::pair<std::string, std::string> (CONFIG_POPUP, TRUE_STR), PREFERENCES); - _config.addDefaultValue(std::pair<std::string, std::string> (CONFIG_NOTIFY, TRUE_STR), PREFERENCES); - _config.addDefaultValue(std::pair<std::string, std::string> (CONFIG_MAIL_NOTIFY, FALSE_STR), PREFERENCES); - _config.addDefaultValue(std::pair<std::string, std::string> (CONFIG_VOLUME, TRUE_STR), PREFERENCES); - _config.addDefaultValue(std::pair<std::string, std::string> (CONFIG_HISTORY_LIMIT, DFT_HISTORY_LIMIT), PREFERENCES); - _config.addDefaultValue(std::pair<std::string, std::string> (CONFIG_HISTORY_ENABLED, TRUE_STR), PREFERENCES); - _config.addDefaultValue(std::pair<std::string, std::string> (CONFIG_AUDIO, DFT_AUDIO_MANAGER), PREFERENCES); - _config.addDefaultValue(std::pair<std::string, std::string> (CONFIG_PA_VOLUME_CTRL, TRUE_STR), PREFERENCES); - _config.addDefaultValue(std::pair<std::string, std::string> (CONFIG_SIP_PORT, DFT_SIP_PORT), PREFERENCES); - _config.addDefaultValue(std::pair<std::string, std::string> (CONFIG_ACCOUNTS_ORDER, EMPTY_FIELD), PREFERENCES); - _config.addDefaultValue(std::pair<std::string, std::string> (CONFIG_MD5HASH, FALSE_STR), PREFERENCES); - - // Addressbook settings - _config.addDefaultValue(std::pair<std::string, std::string> (ADDRESSBOOK_ENABLE, TRUE_STR), ADDRESSBOOK); - _config.addDefaultValue(std::pair<std::string, std::string> (ADDRESSBOOK_MAX_RESULTS, "25"), ADDRESSBOOK); - _config.addDefaultValue(std::pair<std::string, std::string> (ADDRESSBOOK_DISPLAY_CONTACT_PHOTO, FALSE_STR), ADDRESSBOOK); - _config.addDefaultValue(std::pair<std::string, std::string> (ADDRESSBOOK_DISPLAY_PHONE_BUSINESS, TRUE_STR), ADDRESSBOOK); - _config.addDefaultValue(std::pair<std::string, std::string> (ADDRESSBOOK_DISPLAY_PHONE_HOME, FALSE_STR), ADDRESSBOOK); - _config.addDefaultValue(std::pair<std::string, std::string> (ADDRESSBOOK_DISPLAY_PHONE_MOBILE, FALSE_STR), ADDRESSBOOK); - - // Hooks settings - _config.addDefaultValue(std::pair<std::string, std::string> (URLHOOK_SIP_FIELD, HOOK_DEFAULT_SIP_FIELD), HOOKS); - _config.addDefaultValue(std::pair<std::string, std::string> (URLHOOK_COMMAND, HOOK_DEFAULT_URL_COMMAND), HOOKS); - _config.addDefaultValue(std::pair<std::string, std::string> (URLHOOK_SIP_ENABLED, FALSE_STR), HOOKS); - _config.addDefaultValue(std::pair<std::string, std::string> (URLHOOK_IAX2_ENABLED, FALSE_STR), HOOKS); - _config.addDefaultValue(std::pair<std::string, std::string> (PHONE_NUMBER_HOOK_ENABLED, FALSE_STR), HOOKS); - _config.addDefaultValue(std::pair<std::string, std::string> (PHONE_NUMBER_HOOK_ADD_PREFIX, EMPTY_FIELD), HOOKS); + + _config.addDefaultValue (std::pair<std::string, std::string> (DISPLAY_NAME, diplayName), IP2IP_PROFILE); + + // Signalisation settings + _config.addDefaultValue (std::pair<std::string, std::string> (SYMMETRIC, TRUE_STR), SIGNALISATION); + _config.addDefaultValue (std::pair<std::string, std::string> (PLAY_DTMF, TRUE_STR), SIGNALISATION); + _config.addDefaultValue (std::pair<std::string, std::string> (PLAY_TONES, TRUE_STR), SIGNALISATION); + _config.addDefaultValue (std::pair<std::string, std::string> (PULSE_LENGTH, DFT_PULSE_LENGTH_STR), SIGNALISATION); + _config.addDefaultValue (std::pair<std::string, std::string> (SEND_DTMF_AS, SIP_INFO_STR), SIGNALISATION); + _config.addDefaultValue (std::pair<std::string, std::string> (ZRTP_ZIDFILE, ZRTP_ZID_FILENAME), SIGNALISATION); + + // Audio settings + _config.addDefaultValue (std::pair<std::string, std::string> (ALSA_CARD_ID_IN, ALSA_DFT_CARD), AUDIO); + _config.addDefaultValue (std::pair<std::string, std::string> (ALSA_CARD_ID_OUT, ALSA_DFT_CARD), AUDIO); + _config.addDefaultValue (std::pair<std::string, std::string> (ALSA_SAMPLE_RATE, DFT_SAMPLE_RATE), AUDIO); + _config.addDefaultValue (std::pair<std::string, std::string> (ALSA_FRAME_SIZE, DFT_FRAME_SIZE), AUDIO); + _config.addDefaultValue (std::pair<std::string, std::string> (ALSA_PLUGIN, PCM_DEFAULT), AUDIO); + _config.addDefaultValue (std::pair<std::string, std::string> (RING_CHOICE, DFT_RINGTONE), AUDIO); + _config.addDefaultValue (std::pair<std::string, std::string> (VOLUME_SPKR, DFT_VOL_SPKR_STR), AUDIO); + _config.addDefaultValue (std::pair<std::string, std::string> (VOLUME_MICRO, DFT_VOL_MICRO_STR), AUDIO); + _config.addDefaultValue (std::pair<std::string, std::string> (RECORD_PATH,DFT_RECORD_PATH), AUDIO); + + // General settings + _config.addDefaultValue (std::pair<std::string, std::string> (ZONE_TONE, DFT_ZONE), PREFERENCES); + _config.addDefaultValue (std::pair<std::string, std::string> (CONFIG_RINGTONE, TRUE_STR), PREFERENCES); + _config.addDefaultValue (std::pair<std::string, std::string> (CONFIG_DIALPAD, TRUE_STR), PREFERENCES); + _config.addDefaultValue (std::pair<std::string, std::string> (CONFIG_SEARCHBAR, TRUE_STR), PREFERENCES); + _config.addDefaultValue (std::pair<std::string, std::string> (CONFIG_START, FALSE_STR), PREFERENCES); + _config.addDefaultValue (std::pair<std::string, std::string> (CONFIG_POPUP, TRUE_STR), PREFERENCES); + _config.addDefaultValue (std::pair<std::string, std::string> (CONFIG_NOTIFY, TRUE_STR), PREFERENCES); + _config.addDefaultValue (std::pair<std::string, std::string> (CONFIG_MAIL_NOTIFY, FALSE_STR), PREFERENCES); + _config.addDefaultValue (std::pair<std::string, std::string> (CONFIG_VOLUME, TRUE_STR), PREFERENCES); + _config.addDefaultValue (std::pair<std::string, std::string> (CONFIG_HISTORY_LIMIT, DFT_HISTORY_LIMIT), PREFERENCES); + _config.addDefaultValue (std::pair<std::string, std::string> (CONFIG_HISTORY_ENABLED, TRUE_STR), PREFERENCES); + _config.addDefaultValue (std::pair<std::string, std::string> (CONFIG_AUDIO, DFT_AUDIO_MANAGER), PREFERENCES); + _config.addDefaultValue (std::pair<std::string, std::string> (CONFIG_PA_VOLUME_CTRL, TRUE_STR), PREFERENCES); + _config.addDefaultValue (std::pair<std::string, std::string> (CONFIG_SIP_PORT, DFT_SIP_PORT), PREFERENCES); + _config.addDefaultValue (std::pair<std::string, std::string> (CONFIG_ACCOUNTS_ORDER, EMPTY_FIELD), PREFERENCES); + _config.addDefaultValue (std::pair<std::string, std::string> (CONFIG_MD5HASH, FALSE_STR), PREFERENCES); + + // Addressbook settings + _config.addDefaultValue (std::pair<std::string, std::string> (ADDRESSBOOK_ENABLE, TRUE_STR), ADDRESSBOOK); + _config.addDefaultValue (std::pair<std::string, std::string> (ADDRESSBOOK_MAX_RESULTS, "25"), ADDRESSBOOK); + _config.addDefaultValue (std::pair<std::string, std::string> (ADDRESSBOOK_DISPLAY_CONTACT_PHOTO, FALSE_STR), ADDRESSBOOK); + _config.addDefaultValue (std::pair<std::string, std::string> (ADDRESSBOOK_DISPLAY_PHONE_BUSINESS, TRUE_STR), ADDRESSBOOK); + _config.addDefaultValue (std::pair<std::string, std::string> (ADDRESSBOOK_DISPLAY_PHONE_HOME, FALSE_STR), ADDRESSBOOK); + _config.addDefaultValue (std::pair<std::string, std::string> (ADDRESSBOOK_DISPLAY_PHONE_MOBILE, FALSE_STR), ADDRESSBOOK); + + // Hooks settings + _config.addDefaultValue (std::pair<std::string, std::string> (URLHOOK_SIP_FIELD, HOOK_DEFAULT_SIP_FIELD), HOOKS); + _config.addDefaultValue (std::pair<std::string, std::string> (URLHOOK_COMMAND, HOOK_DEFAULT_URL_COMMAND), HOOKS); + _config.addDefaultValue (std::pair<std::string, std::string> (URLHOOK_SIP_ENABLED, FALSE_STR), HOOKS); + _config.addDefaultValue (std::pair<std::string, std::string> (URLHOOK_IAX2_ENABLED, FALSE_STR), HOOKS); + _config.addDefaultValue (std::pair<std::string, std::string> (PHONE_NUMBER_HOOK_ENABLED, FALSE_STR), HOOKS); + _config.addDefaultValue (std::pair<std::string, std::string> (PHONE_NUMBER_HOOK_ADD_PREFIX, EMPTY_FIELD), HOOKS); std::string path; // Loads config from ~/.sflphone/sflphonedrc or so.. + if (createSettingsPath() == 1 && load_user_value) { (alternate == "") ? path = _path : path = alternate; std::cout << path << std::endl; _exist = _config.populateFromFile (path); } - - // Globally shared default values (not to be populated from file) - _config.addDefaultValue(std::pair<std::string, std::string> (HOSTNAME, EMPTY_FIELD)); - _config.addDefaultValue(std::pair<std::string, std::string> (AUTHENTICATION_USERNAME, EMPTY_FIELD)); - _config.addDefaultValue(std::pair<std::string, std::string> (USERNAME, EMPTY_FIELD)); - _config.addDefaultValue(std::pair<std::string, std::string> (PASSWORD, EMPTY_FIELD)); - _config.addDefaultValue(std::pair<std::string, std::string> (REALM, DEFAULT_REALM)); - _config.addDefaultValue(std::pair<std::string, std::string> (CONFIG_ACCOUNT_REGISTRATION_EXPIRE, DFT_EXPIRE_VALUE)); - _config.addDefaultValue(std::pair<std::string, std::string> (CONFIG_ACCOUNT_RESOLVE_ONCE, FALSE_STR)); - _config.addDefaultValue(std::pair<std::string, std::string> (CONFIG_ACCOUNT_ALIAS, EMPTY_FIELD)); - _config.addDefaultValue(std::pair<std::string, std::string> (CONFIG_ACCOUNT_MAILBOX, EMPTY_FIELD)); - _config.addDefaultValue(std::pair<std::string, std::string> (CONFIG_ACCOUNT_ENABLE, TRUE_STR)); - _config.addDefaultValue(std::pair<std::string, std::string> (CONFIG_CREDENTIAL_NUMBER, "0")); - _config.addDefaultValue(std::pair<std::string, std::string> (CONFIG_ACCOUNT_TYPE, DEFAULT_ACCOUNT_TYPE)); - _config.addDefaultValue(std::pair<std::string, std::string> (STUN_ENABLE, DFT_STUN_ENABLE)); - _config.addDefaultValue(std::pair<std::string, std::string> (STUN_SERVER, DFT_STUN_SERVER)); - + + // Globally shared default values (not to be populated from file) + _config.addDefaultValue (std::pair<std::string, std::string> (HOSTNAME, EMPTY_FIELD)); + + _config.addDefaultValue (std::pair<std::string, std::string> (AUTHENTICATION_USERNAME, EMPTY_FIELD)); + + _config.addDefaultValue (std::pair<std::string, std::string> (USERNAME, EMPTY_FIELD)); + + _config.addDefaultValue (std::pair<std::string, std::string> (PASSWORD, EMPTY_FIELD)); + + _config.addDefaultValue (std::pair<std::string, std::string> (REALM, DEFAULT_REALM)); + + _config.addDefaultValue (std::pair<std::string, std::string> (CONFIG_ACCOUNT_REGISTRATION_EXPIRE, DFT_EXPIRE_VALUE)); + + _config.addDefaultValue (std::pair<std::string, std::string> (CONFIG_ACCOUNT_RESOLVE_ONCE, FALSE_STR)); + + _config.addDefaultValue (std::pair<std::string, std::string> (CONFIG_ACCOUNT_ALIAS, EMPTY_FIELD)); + + _config.addDefaultValue (std::pair<std::string, std::string> (CONFIG_ACCOUNT_MAILBOX, EMPTY_FIELD)); + + _config.addDefaultValue (std::pair<std::string, std::string> (CONFIG_ACCOUNT_ENABLE, TRUE_STR)); + + _config.addDefaultValue (std::pair<std::string, std::string> (CONFIG_CREDENTIAL_NUMBER, "0")); + + _config.addDefaultValue (std::pair<std::string, std::string> (CONFIG_ACCOUNT_TYPE, DEFAULT_ACCOUNT_TYPE)); + _setupLoaded = (_exist == 2) ? false : true; } @@ -1838,15 +1859,15 @@ ManagerImpl::setRecordPath (const std::string& recPath) } bool -ManagerImpl::getMd5CredentialHashing(void) +ManagerImpl::getMd5CredentialHashing (void) { - return getConfigBool(PREFERENCES, CONFIG_MD5HASH); + return getConfigBool (PREFERENCES, CONFIG_MD5HASH); } int ManagerImpl::getDialpad (void) { - if (getConfigString(PREFERENCES, CONFIG_DIALPAD) == TRUE_STR) { + if (getConfigString (PREFERENCES, CONFIG_DIALPAD) == TRUE_STR) { return 1; } else { return 0; @@ -1856,9 +1877,10 @@ ManagerImpl::getDialpad (void) void ManagerImpl::setDialpad (void) { - (getConfigString(PREFERENCES, CONFIG_DIALPAD) == TRUE_STR) ? setConfig(PREFERENCES, CONFIG_DIALPAD, FALSE_STR) : setConfig (PREFERENCES, CONFIG_DIALPAD, TRUE_STR); + (getConfigString (PREFERENCES, CONFIG_DIALPAD) == TRUE_STR) ? setConfig (PREFERENCES, CONFIG_DIALPAD, FALSE_STR) : setConfig (PREFERENCES, CONFIG_DIALPAD, TRUE_STR); } +/* std::string ManagerImpl::getStunServer (void) { return getConfigString (SIGNALISATION , STUN_SERVER); @@ -1871,23 +1893,24 @@ void ManagerImpl::setStunServer (const std::string &server) int ManagerImpl::isStunEnabled (void) { - return getConfigString(SIGNALISATION, STUN_ENABLE) == TRUE_STR ? 1:0; + return getConfigString (SIGNALISATION, STUN_ENABLE) == TRUE_STR ? 1:0; } + void ManagerImpl::enableStun (void) { - /* Update the config */ - (getConfigString(SIGNALISATION , STUN_ENABLE) == TRUE_STR) ? setConfig(SIGNALISATION , STUN_ENABLE , FALSE_STR) : setConfig (SIGNALISATION , STUN_ENABLE , TRUE_STR); + // Update the config + (getConfigString (SIGNALISATION , STUN_ENABLE) == TRUE_STR) ? setConfig (SIGNALISATION , STUN_ENABLE , FALSE_STR) : setConfig (SIGNALISATION , STUN_ENABLE , TRUE_STR); - /* Restart PJSIP */ + // Restart PJSIP this->restartPJSIP (); } - +*/ int ManagerImpl::getVolumeControls (void) { - if (getConfigString(PREFERENCES , CONFIG_VOLUME) == TRUE_STR) { + if (getConfigString (PREFERENCES , CONFIG_VOLUME) == TRUE_STR) { return 1; } else { return 0; @@ -1897,7 +1920,7 @@ ManagerImpl::getVolumeControls (void) void ManagerImpl::setVolumeControls (void) { - (getConfigString(PREFERENCES, CONFIG_VOLUME) == TRUE_STR) ? setConfig(PREFERENCES , CONFIG_VOLUME , FALSE_STR) : setConfig (PREFERENCES , CONFIG_VOLUME , TRUE_STR); + (getConfigString (PREFERENCES, CONFIG_VOLUME) == TRUE_STR) ? setConfig (PREFERENCES , CONFIG_VOLUME , FALSE_STR) : setConfig (PREFERENCES , CONFIG_VOLUME , TRUE_STR); } void @@ -1921,13 +1944,13 @@ ManagerImpl::isRecording (const CallID& id) void ManagerImpl::startHidden (void) { - (getConfigString(PREFERENCES, CONFIG_START) == START_HIDDEN) ? setConfig(PREFERENCES , CONFIG_START , FALSE_STR) : setConfig (PREFERENCES , CONFIG_START , TRUE_STR); + (getConfigString (PREFERENCES, CONFIG_START) == START_HIDDEN) ? setConfig (PREFERENCES , CONFIG_START , FALSE_STR) : setConfig (PREFERENCES , CONFIG_START , TRUE_STR); } int ManagerImpl::isStartHidden (void) { - return (getConfigBool(PREFERENCES, CONFIG_START) == true) ? 1:0; + return (getConfigBool (PREFERENCES, CONFIG_START) == true) ? 1:0; } void @@ -1971,25 +1994,25 @@ ManagerImpl::setSearchbar (void) int ManagerImpl::popupMode (void) { - return (getConfigBool(PREFERENCES, CONFIG_POPUP) == true) ? 1:0 ; + return (getConfigBool (PREFERENCES, CONFIG_POPUP) == true) ? 1:0 ; } int32_t ManagerImpl::getNotify (void) { - return (getConfigBool(PREFERENCES , CONFIG_NOTIFY) == true) ? 1:0; + return (getConfigBool (PREFERENCES , CONFIG_NOTIFY) == true) ? 1:0; } void ManagerImpl::setNotify (void) { - (getConfigString(PREFERENCES, CONFIG_NOTIFY) == NOTIFY_ALL) ? setConfig (PREFERENCES, CONFIG_NOTIFY , FALSE_STR) : setConfig (PREFERENCES, CONFIG_NOTIFY , TRUE_STR); + (getConfigString (PREFERENCES, CONFIG_NOTIFY) == NOTIFY_ALL) ? setConfig (PREFERENCES, CONFIG_NOTIFY , FALSE_STR) : setConfig (PREFERENCES, CONFIG_NOTIFY , TRUE_STR); } int32_t ManagerImpl::getMailNotify (void) { - return getConfigInt(PREFERENCES, CONFIG_MAIL_NOTIFY); + return getConfigInt (PREFERENCES, CONFIG_MAIL_NOTIFY); } int32_t @@ -2281,10 +2304,11 @@ void ManagerImpl::setMicVolume (unsigned short mic_vol) void ManagerImpl::setSipPort (int port) { - _debug("Setting to new port %d\n", port); + _debug ("Setting to new port %d\n", port); int prevPort = getConfigInt (PREFERENCES , CONFIG_SIP_PORT); - if(prevPort != port){ - setConfig(PREFERENCES, CONFIG_SIP_PORT, port); + + if (prevPort != port) { + setConfig (PREFERENCES, CONFIG_SIP_PORT, port); this->restartPJSIP (); } } @@ -2438,7 +2462,7 @@ ManagerImpl::getConfigBool (const std::string& section, const std::string& name) return false; } - + //THREAD=Main std::string ManagerImpl::getConfigString (const std::string& section, const std::string& @@ -2457,7 +2481,7 @@ ManagerImpl::getConfigString (const std::string& section, const std::string& bool ManagerImpl::setConfig (const std::string& section, const std::string& name, const std::string& value) { - _debug("ManagerImpl::setConfig %s %s %s\n", section.c_str(), name.c_str(), value.c_str()); + _debug ("ManagerImpl::setConfig %s %s %s\n", section.c_str(), name.c_str(), value.c_str()); return _config.setConfigTreeItem (section, name, value); } @@ -2502,6 +2526,7 @@ ManagerImpl::getAccountList() iter++; } } + // Otherelse, load the custom one // ie according to the saved order else { @@ -2518,118 +2543,124 @@ ManagerImpl::getAccountList() } - + return v; } std::map< std::string, std::string > ManagerImpl::getAccountDetails (const AccountID& accountID) { std::map<std::string, std::string> a; - + Account * account = _accountMap[accountID]; - if(account == NULL) { - _debug("Cannot getAccountDetails on a non-existing accountID. Defaults will be used.\n"); - } - - a.insert(std::pair<std::string, std::string> (CONFIG_ACCOUNT_ALIAS, getConfigString(accountID, CONFIG_ACCOUNT_ALIAS))); - a.insert(std::pair<std::string, std::string> (CONFIG_ACCOUNT_ENABLE, getConfigString(accountID, CONFIG_ACCOUNT_ENABLE))); - a.insert(std::pair<std::string, std::string> (CONFIG_ACCOUNT_RESOLVE_ONCE, getConfigString(accountID, CONFIG_ACCOUNT_RESOLVE_ONCE))); - a.insert(std::pair<std::string, std::string> (CONFIG_ACCOUNT_TYPE, getConfigString(accountID, CONFIG_ACCOUNT_TYPE))); - a.insert(std::pair<std::string, std::string> (HOSTNAME, getConfigString(accountID, HOSTNAME))); - a.insert(std::pair<std::string, std::string> (USERNAME, getConfigString(accountID, USERNAME))); - a.insert(std::pair<std::string, std::string> (PASSWORD, getConfigString(accountID, PASSWORD))); - a.insert(std::pair<std::string, std::string> (REALM, getConfigString(accountID, REALM))); - a.insert(std::pair<std::string, std::string> (AUTHENTICATION_USERNAME, getConfigString(accountID, AUTHENTICATION_USERNAME))); - a.insert(std::pair<std::string, std::string> (CONFIG_ACCOUNT_MAILBOX, getConfigString(accountID, CONFIG_ACCOUNT_MAILBOX))); - a.insert(std::pair<std::string, std::string> (CONFIG_ACCOUNT_REGISTRATION_EXPIRE, getConfigString(accountID, CONFIG_ACCOUNT_REGISTRATION_EXPIRE))); - a.insert(std::pair<std::string, std::string> (LOCAL_ADDRESS, getConfigString(accountID, LOCAL_ADDRESS))); - a.insert(std::pair<std::string, std::string> (PUBLISHED_ADDRESS, getConfigString(accountID, PUBLISHED_ADDRESS))); - a.insert(std::pair<std::string, std::string> (LOCAL_PORT, getConfigString(accountID, LOCAL_PORT))); - a.insert(std::pair<std::string, std::string> (PUBLISHED_PORT, getConfigString(accountID, PUBLISHED_PORT))); - a.insert(std::pair<std::string, std::string> (DISPLAY_NAME, getConfigString(accountID, DISPLAY_NAME))); - a.insert(std::pair<std::string, std::string> (STUN_ENABLE, getConfigString(accountID, STUN_ENABLE))); - a.insert(std::pair<std::string, std::string> (STUN_SERVER, getConfigString(accountID, STUN_SERVER))); - + + if (account == NULL) { + _debug ("Cannot getAccountDetails on a non-existing accountID. Defaults will be used.\n"); + } + + a.insert (std::pair<std::string, std::string> (CONFIG_ACCOUNT_ALIAS, getConfigString (accountID, CONFIG_ACCOUNT_ALIAS))); + + a.insert (std::pair<std::string, std::string> (CONFIG_ACCOUNT_ENABLE, getConfigString (accountID, CONFIG_ACCOUNT_ENABLE))); + a.insert (std::pair<std::string, std::string> (CONFIG_ACCOUNT_RESOLVE_ONCE, getConfigString (accountID, CONFIG_ACCOUNT_RESOLVE_ONCE))); + a.insert (std::pair<std::string, std::string> (CONFIG_ACCOUNT_TYPE, getConfigString (accountID, CONFIG_ACCOUNT_TYPE))); + a.insert (std::pair<std::string, std::string> (HOSTNAME, getConfigString (accountID, HOSTNAME))); + a.insert (std::pair<std::string, std::string> (USERNAME, getConfigString (accountID, USERNAME))); + a.insert (std::pair<std::string, std::string> (PASSWORD, getConfigString (accountID, PASSWORD))); + a.insert (std::pair<std::string, std::string> (REALM, getConfigString (accountID, REALM))); + a.insert (std::pair<std::string, std::string> (AUTHENTICATION_USERNAME, getConfigString (accountID, AUTHENTICATION_USERNAME))); + a.insert (std::pair<std::string, std::string> (CONFIG_ACCOUNT_MAILBOX, getConfigString (accountID, CONFIG_ACCOUNT_MAILBOX))); + a.insert (std::pair<std::string, std::string> (CONFIG_ACCOUNT_REGISTRATION_EXPIRE, getConfigString (accountID, CONFIG_ACCOUNT_REGISTRATION_EXPIRE))); + a.insert (std::pair<std::string, std::string> (LOCAL_ADDRESS, getConfigString (accountID, LOCAL_ADDRESS))); + a.insert (std::pair<std::string, std::string> (PUBLISHED_ADDRESS, getConfigString (accountID, PUBLISHED_ADDRESS))); + a.insert (std::pair<std::string, std::string> (LOCAL_PORT, getConfigString (accountID, LOCAL_PORT))); + a.insert (std::pair<std::string, std::string> (PUBLISHED_PORT, getConfigString (accountID, PUBLISHED_PORT))); + a.insert (std::pair<std::string, std::string> (DISPLAY_NAME, getConfigString (accountID, DISPLAY_NAME))); + a.insert (std::pair<std::string, std::string> (STUN_ENABLE, getConfigString (accountID, STUN_ENABLE))); + a.insert (std::pair<std::string, std::string> (STUN_SERVER, getConfigString (accountID, STUN_SERVER))); + RegistrationState state; std::string registrationStateCode; - std::string registrationStateDescription; + std::string registrationStateDescription; + if (account != NULL) { - state = account->getRegistrationState(); + state = account->getRegistrationState(); int code = account->getRegistrationStateDetailed().first; std::stringstream out; out << code; registrationStateCode = out.str(); - registrationStateDescription = account->getRegistrationStateDetailed().second; + registrationStateDescription = account->getRegistrationStateDetailed().second; } else { state = Unregistered; } - a.insert(std::pair<std::string, std::string> (REGISTRATION_STATUS, mapStateNumberToString (state))); - a.insert(std::pair<std::string, std::string> (REGISTRATION_STATE_CODE, registrationStateCode)); - a.insert(std::pair<std::string, std::string> (REGISTRATION_STATE_DESCRIPTION, registrationStateDescription)); - a.insert(std::pair<std::string, std::string> (SRTP_KEY_EXCHANGE, getConfigString(accountID, SRTP_KEY_EXCHANGE))); - a.insert(std::pair<std::string, std::string> (SRTP_ENABLE, getConfigString(accountID, SRTP_ENABLE))); - a.insert(std::pair<std::string, std::string> (ZRTP_DISPLAY_SAS, getConfigString(accountID, ZRTP_DISPLAY_SAS))); - a.insert(std::pair<std::string, std::string> (ZRTP_DISPLAY_SAS_ONCE, getConfigString(accountID, ZRTP_DISPLAY_SAS_ONCE))); - a.insert(std::pair<std::string, std::string> (ZRTP_HELLO_HASH, getConfigString(accountID, ZRTP_HELLO_HASH))); - a.insert(std::pair<std::string, std::string> (ZRTP_NOT_SUPP_WARNING, getConfigString(accountID, ZRTP_NOT_SUPP_WARNING))); - - a.insert(std::pair<std::string, std::string> (TLS_ENABLE, Manager::instance().getConfigString(accountID, TLS_ENABLE))); - a.insert(std::pair<std::string, std::string> (TLS_CA_LIST_FILE, Manager::instance().getConfigString(accountID, TLS_CA_LIST_FILE))); - a.insert(std::pair<std::string, std::string> (TLS_CERTIFICATE_FILE, Manager::instance().getConfigString(accountID, TLS_CERTIFICATE_FILE))); - a.insert(std::pair<std::string, std::string> (TLS_PRIVATE_KEY_FILE, Manager::instance().getConfigString(accountID, TLS_PRIVATE_KEY_FILE))); - a.insert(std::pair<std::string, std::string> (TLS_PASSWORD, Manager::instance().getConfigString(accountID, TLS_PASSWORD))); - a.insert(std::pair<std::string, std::string> (TLS_METHOD, Manager::instance().getConfigString(accountID, TLS_METHOD))); - a.insert(std::pair<std::string, std::string> (TLS_CIPHERS, Manager::instance().getConfigString(accountID, TLS_CIPHERS))); - a.insert(std::pair<std::string, std::string> (TLS_SERVER_NAME, Manager::instance().getConfigString(accountID, TLS_SERVER_NAME))); - a.insert(std::pair<std::string, std::string> (TLS_VERIFY_SERVER, Manager::instance().getConfigString(accountID, TLS_VERIFY_SERVER))); - a.insert(std::pair<std::string, std::string> (TLS_VERIFY_CLIENT, Manager::instance().getConfigString(accountID, TLS_VERIFY_CLIENT))); - a.insert(std::pair<std::string, std::string> (TLS_REQUIRE_CLIENT_CERTIFICATE, Manager::instance().getConfigString(accountID, TLS_REQUIRE_CLIENT_CERTIFICATE))); - a.insert(std::pair<std::string, std::string> (TLS_NEGOTIATION_TIMEOUT_SEC, Manager::instance().getConfigString(accountID, TLS_NEGOTIATION_TIMEOUT_SEC))); - a.insert(std::pair<std::string, std::string> (TLS_NEGOTIATION_TIMEOUT_MSEC, Manager::instance().getConfigString(accountID, TLS_NEGOTIATION_TIMEOUT_MSEC))); - + + a.insert (std::pair<std::string, std::string> (REGISTRATION_STATUS, mapStateNumberToString (state))); + + a.insert (std::pair<std::string, std::string> (REGISTRATION_STATE_CODE, registrationStateCode)); + a.insert (std::pair<std::string, std::string> (REGISTRATION_STATE_DESCRIPTION, registrationStateDescription)); + a.insert (std::pair<std::string, std::string> (SRTP_KEY_EXCHANGE, getConfigString (accountID, SRTP_KEY_EXCHANGE))); + a.insert (std::pair<std::string, std::string> (SRTP_ENABLE, getConfigString (accountID, SRTP_ENABLE))); + a.insert (std::pair<std::string, std::string> (ZRTP_DISPLAY_SAS, getConfigString (accountID, ZRTP_DISPLAY_SAS))); + a.insert (std::pair<std::string, std::string> (ZRTP_DISPLAY_SAS_ONCE, getConfigString (accountID, ZRTP_DISPLAY_SAS_ONCE))); + a.insert (std::pair<std::string, std::string> (ZRTP_HELLO_HASH, getConfigString (accountID, ZRTP_HELLO_HASH))); + a.insert (std::pair<std::string, std::string> (ZRTP_NOT_SUPP_WARNING, getConfigString (accountID, ZRTP_NOT_SUPP_WARNING))); + + a.insert (std::pair<std::string, std::string> (TLS_ENABLE, Manager::instance().getConfigString (accountID, TLS_ENABLE))); + a.insert (std::pair<std::string, std::string> (TLS_CA_LIST_FILE, Manager::instance().getConfigString (accountID, TLS_CA_LIST_FILE))); + a.insert (std::pair<std::string, std::string> (TLS_CERTIFICATE_FILE, Manager::instance().getConfigString (accountID, TLS_CERTIFICATE_FILE))); + a.insert (std::pair<std::string, std::string> (TLS_PRIVATE_KEY_FILE, Manager::instance().getConfigString (accountID, TLS_PRIVATE_KEY_FILE))); + a.insert (std::pair<std::string, std::string> (TLS_PASSWORD, Manager::instance().getConfigString (accountID, TLS_PASSWORD))); + a.insert (std::pair<std::string, std::string> (TLS_METHOD, Manager::instance().getConfigString (accountID, TLS_METHOD))); + a.insert (std::pair<std::string, std::string> (TLS_CIPHERS, Manager::instance().getConfigString (accountID, TLS_CIPHERS))); + a.insert (std::pair<std::string, std::string> (TLS_SERVER_NAME, Manager::instance().getConfigString (accountID, TLS_SERVER_NAME))); + a.insert (std::pair<std::string, std::string> (TLS_VERIFY_SERVER, Manager::instance().getConfigString (accountID, TLS_VERIFY_SERVER))); + a.insert (std::pair<std::string, std::string> (TLS_VERIFY_CLIENT, Manager::instance().getConfigString (accountID, TLS_VERIFY_CLIENT))); + a.insert (std::pair<std::string, std::string> (TLS_REQUIRE_CLIENT_CERTIFICATE, Manager::instance().getConfigString (accountID, TLS_REQUIRE_CLIENT_CERTIFICATE))); + a.insert (std::pair<std::string, std::string> (TLS_NEGOTIATION_TIMEOUT_SEC, Manager::instance().getConfigString (accountID, TLS_NEGOTIATION_TIMEOUT_SEC))); + a.insert (std::pair<std::string, std::string> (TLS_NEGOTIATION_TIMEOUT_MSEC, Manager::instance().getConfigString (accountID, TLS_NEGOTIATION_TIMEOUT_MSEC))); + return a; } /* Transform digest to string. * output must be at least PJSIP_MD5STRLEN+1 bytes. - * Helper function taken from sip_auth_client.c in + * Helper function taken from sip_auth_client.c in * pjproject-1.0.3. * * NOTE: THE OUTPUT STRING IS NOT NULL TERMINATED! */ -void ManagerImpl::digest2str(const unsigned char digest[], char *output) +void ManagerImpl::digest2str (const unsigned char digest[], char *output) { int i; + for (i = 0; i<16; ++i) { - pj_val_to_hex_digit(digest[i], output); + pj_val_to_hex_digit (digest[i], output); output += 2; - } + } } -std::string ManagerImpl::computeMd5HashFromCredential(const std::string& username, const std::string& password, const std::string& realm) +std::string ManagerImpl::computeMd5HashFromCredential (const std::string& username, const std::string& password, const std::string& realm) { pj_md5_context pms; unsigned char digest[16]; char ha1[PJSIP_MD5STRLEN]; - pj_str_t usernamePjFormat = pj_str(strdup(username.c_str())); - pj_str_t passwordPjFormat = pj_str(strdup(password.c_str())); - pj_str_t realmPjFormat = pj_str(strdup(realm.c_str())); + pj_str_t usernamePjFormat = pj_str (strdup (username.c_str())); + pj_str_t passwordPjFormat = pj_str (strdup (password.c_str())); + pj_str_t realmPjFormat = pj_str (strdup (realm.c_str())); /* Compute md5 hash = MD5(username ":" realm ":" password) */ - pj_md5_init(&pms); - MD5_APPEND( &pms, usernamePjFormat.ptr, usernamePjFormat.slen); - MD5_APPEND( &pms, ":", 1); - MD5_APPEND( &pms, realmPjFormat.ptr, realmPjFormat.slen); - MD5_APPEND( &pms, ":", 1); - MD5_APPEND( &pms, passwordPjFormat.ptr, passwordPjFormat.slen); - pj_md5_final(&pms, digest); + pj_md5_init (&pms); + MD5_APPEND (&pms, usernamePjFormat.ptr, usernamePjFormat.slen); + MD5_APPEND (&pms, ":", 1); + MD5_APPEND (&pms, realmPjFormat.ptr, realmPjFormat.slen); + MD5_APPEND (&pms, ":", 1); + MD5_APPEND (&pms, passwordPjFormat.ptr, passwordPjFormat.slen); + pj_md5_final (&pms, digest); - digest2str(digest, ha1); + digest2str (digest, ha1); char ha1_null_terminated[PJSIP_MD5STRLEN+1]; - memcpy(ha1_null_terminated, ha1, sizeof(char)*PJSIP_MD5STRLEN); + memcpy (ha1_null_terminated, ha1, sizeof (char) *PJSIP_MD5STRLEN); ha1_null_terminated[PJSIP_MD5STRLEN] = '\0'; std::string hashedDigest = ha1_null_terminated; @@ -2640,62 +2671,67 @@ void ManagerImpl::setCredential (const std::string& accountID, const int32_t& in { std::map<std::string, std::string>::iterator it; std::map<std::string, std::string> credentialInformation = details; - + std::string credentialIndex; std::stringstream streamOut; streamOut << index; credentialIndex = streamOut.str(); - - std::string section = "Credential" + std::string(":") + accountID + std::string(":") + credentialIndex; - - _debug("Setting credential in section %s\n", section.c_str()); - - it = credentialInformation.find(USERNAME); + + std::string section = "Credential" + std::string (":") + accountID + std::string (":") + credentialIndex; + + _debug ("Setting credential in section %s\n", section.c_str()); + + it = credentialInformation.find (USERNAME); std::string username; - if (it == credentialInformation.end()) { + + if (it == credentialInformation.end()) { username = EMPTY_FIELD; } else { username = it->second; } + Manager::instance().setConfig (section, USERNAME, username); - it = credentialInformation.find(REALM); + it = credentialInformation.find (REALM); std::string realm; - if (it == credentialInformation.end()) { + + if (it == credentialInformation.end()) { realm = EMPTY_FIELD; } else { realm = it->second; } + Manager::instance().setConfig (section, REALM, realm); - - it = credentialInformation.find(PASSWORD); + + it = credentialInformation.find (PASSWORD); std::string password; - if (it == credentialInformation.end()) { + + if (it == credentialInformation.end()) { password = EMPTY_FIELD; } else { password = it->second; } - - if(getMd5CredentialHashing()) { + + if (getMd5CredentialHashing()) { // TODO: Fix this. - // This is an extremly weak test in order to check + // This is an extremly weak test in order to check // if the password is a hashed value. This is done - // because deleteCredential() is called before this - // method. Therefore, we cannot check if the value - // is different from the one previously stored in - // the configuration file. This is to avoid to + // because deleteCredential() is called before this + // method. Therefore, we cannot check if the value + // is different from the one previously stored in + // the configuration file. This is to avoid to // re-hash a hashed password. - - if(password.length() != 32) { - password = computeMd5HashFromCredential(username, password, realm); + + if (password.length() != 32) { + password = computeMd5HashFromCredential (username, password, realm); } - } - + } + Manager::instance().setConfig (section, PASSWORD, password); } -//TODO: tidy this up. Make a macro or inline +//TODO: tidy this up. Make a macro or inline // method to reduce the if/else mess. // Even better, switch to XML ! @@ -2703,49 +2739,66 @@ void ManagerImpl::setAccountDetails (const std::string& accountID, const std::ma { std::string accountType; - std::map <std::string, std::string> map_cpy; - std::map<std::string, std::string>::iterator iter; + std::map <std::string, std::string> map_cpy; + std::map<std::string, std::string>::iterator iter; - // Work on a copy - map_cpy = details; + // Work on a copy + map_cpy = details; std::string username; std::string authenticationName; std::string password; - std::string realm; - - if((iter = map_cpy.find(AUTHENTICATION_USERNAME)) != map_cpy.end()) { authenticationName = iter->second; } - if((iter = map_cpy.find(USERNAME)) != map_cpy.end()) { username = iter->second; } - if((iter = map_cpy.find(PASSWORD)) != map_cpy.end()) { password = iter->second; } - if((iter = map_cpy.find(REALM)) != map_cpy.end()) { realm = iter->second; } - - setConfig(accountID, REALM, realm); - setConfig(accountID, USERNAME, username); - setConfig(accountID, AUTHENTICATION_USERNAME, authenticationName); - if(!getMd5CredentialHashing()) { - setConfig(accountID, PASSWORD, password); + std::string realm; + + if ( (iter = map_cpy.find (AUTHENTICATION_USERNAME)) != map_cpy.end()) { + authenticationName = iter->second; + } + + if ( (iter = map_cpy.find (USERNAME)) != map_cpy.end()) { + username = iter->second; + } + + if ( (iter = map_cpy.find (PASSWORD)) != map_cpy.end()) { + password = iter->second; + } + + if ( (iter = map_cpy.find (REALM)) != map_cpy.end()) { + realm = iter->second; + } + + setConfig (accountID, REALM, realm); + + setConfig (accountID, USERNAME, username); + setConfig (accountID, AUTHENTICATION_USERNAME, authenticationName); + + if (!getMd5CredentialHashing()) { + setConfig (accountID, PASSWORD, password); } else { // Make sure not to re-hash the password field if // it is already saved as a MD5 Hash. // TODO: This test is weak. Fix this. - if ((password.compare(getConfigString(accountID, PASSWORD)) != 0)) { - _debug("Password sent and password from config are different. Re-hashing\n"); + if ( (password.compare (getConfigString (accountID, PASSWORD)) != 0)) { + _debug ("Password sent and password from config are different. Re-hashing\n"); std::string hash; - if(authenticationName.empty()) { - hash = computeMd5HashFromCredential(username, password, realm); + + if (authenticationName.empty()) { + hash = computeMd5HashFromCredential (username, password, realm); } else { - hash = computeMd5HashFromCredential(authenticationName, password, realm); + hash = computeMd5HashFromCredential (authenticationName, password, realm); } - setConfig(accountID, PASSWORD, hash); + + setConfig (accountID, PASSWORD, hash); } } + std::string alias; + std::string mailbox; std::string accountEnable; std::string type; std::string resolveOnce; std::string registrationExpire; - + std::string hostname; std::string displayName; std::string localAddress; @@ -2753,105 +2806,206 @@ void ManagerImpl::setAccountDetails (const std::string& accountID, const std::ma std::string localPort; std::string publishedPort; std::string stunEnable; - std::string stunServer; +std::string stunServer; std::string srtpEnable; std::string zrtpDisplaySas; std::string zrtpDisplaySasOnce; std::string zrtpNotSuppWarning; std::string zrtpHelloHash; std::string srtpKeyExchange; - - std::string tlsEnable; + + std::string tlsEnable; std::string tlsCaListFile; - std::string tlsCertificateFile; - std::string tlsPrivateKeyFile; + std::string tlsCertificateFile; + std::string tlsPrivateKeyFile; std::string tlsPassword; std::string tlsMethod; std::string tlsCiphers; std::string tlsServerName; std::string tlsVerifyServer; - std::string tlsVerifyClient; - std::string tlsRequireClientCertificate; - std::string tlsNegotiationTimeoutSec; - std::string tlsNegotiationTimeoutMsec; - - if((iter = map_cpy.find(HOSTNAME)) != map_cpy.end()) { hostname = iter->second; } - if((iter = map_cpy.find(DISPLAY_NAME)) != map_cpy.end()) { displayName = iter->second; } - if((iter = map_cpy.find(LOCAL_ADDRESS)) != map_cpy.end()) { localAddress = iter->second; } - if((iter = map_cpy.find(PUBLISHED_ADDRESS)) != map_cpy.end()) { publishedAddress = iter->second; } - if((iter = map_cpy.find(LOCAL_PORT)) != map_cpy.end()) { localPort = iter->second; } - if((iter = map_cpy.find(PUBLISHED_PORT)) != map_cpy.end()) { publishedPort = iter->second; } - if((iter = map_cpy.find(STUN_ENABLE)) != map_cpy.end()) { stunEnable = iter->second; } - if((iter = map_cpy.find(STUN_SERVER)) != map_cpy.end()) { stunServer = iter->second; } - if((iter = map_cpy.find(SRTP_ENABLE)) != map_cpy.end()) { srtpEnable = iter->second; } - if((iter = map_cpy.find(ZRTP_DISPLAY_SAS)) != map_cpy.end()) { zrtpDisplaySas = iter->second; } - if((iter = map_cpy.find(ZRTP_DISPLAY_SAS_ONCE)) != map_cpy.end()) { zrtpDisplaySasOnce = iter->second; } - if((iter = map_cpy.find(ZRTP_NOT_SUPP_WARNING)) != map_cpy.end()) { zrtpNotSuppWarning = iter->second; } - if((iter = map_cpy.find(ZRTP_HELLO_HASH)) != map_cpy.end()) { zrtpHelloHash = iter->second; } - if((iter = map_cpy.find(SRTP_KEY_EXCHANGE)) != map_cpy.end()) { srtpKeyExchange = iter->second; } - - if((iter = map_cpy.find(CONFIG_ACCOUNT_ALIAS)) != map_cpy.end()) { alias = iter->second; } - if((iter = map_cpy.find(CONFIG_ACCOUNT_MAILBOX)) != map_cpy.end()) { mailbox = iter->second; } - if((iter = map_cpy.find(CONFIG_ACCOUNT_ENABLE)) != map_cpy.end()) { accountEnable = iter->second; } - if((iter = map_cpy.find(CONFIG_ACCOUNT_TYPE)) != map_cpy.end()) { type = iter->second; } - if((iter = map_cpy.find(CONFIG_ACCOUNT_RESOLVE_ONCE)) != map_cpy.end()) { resolveOnce = iter->second; } - if((iter = map_cpy.find(CONFIG_ACCOUNT_REGISTRATION_EXPIRE)) != map_cpy.end()) { registrationExpire = iter->second; } - - if((iter = map_cpy.find(TLS_ENABLE)) != map_cpy.end()) { tlsEnable = iter->second; } - if((iter = map_cpy.find(TLS_CA_LIST_FILE)) != map_cpy.end()) { tlsCaListFile = iter->second; } - if((iter = map_cpy.find(TLS_CERTIFICATE_FILE)) != map_cpy.end()) { tlsCertificateFile = iter->second; } - if((iter = map_cpy.find(TLS_PRIVATE_KEY_FILE)) != map_cpy.end()) { tlsPrivateKeyFile = iter->second; } - if((iter = map_cpy.find(TLS_PASSWORD)) != map_cpy.end()) { tlsPassword = iter->second; } - if((iter = map_cpy.find(TLS_METHOD)) != map_cpy.end()) { tlsMethod = iter->second; } - if((iter = map_cpy.find(TLS_CIPHERS)) != map_cpy.end()) { tlsCiphers = iter->second; } - if((iter = map_cpy.find(TLS_SERVER_NAME)) != map_cpy.end()) { tlsServerName = iter->second; } - if((iter = map_cpy.find(TLS_VERIFY_SERVER)) != map_cpy.end()) { tlsVerifyServer = iter->second; } - if((iter = map_cpy.find(TLS_VERIFY_CLIENT)) != map_cpy.end()) { tlsVerifyClient = iter->second; } - if((iter = map_cpy.find(TLS_REQUIRE_CLIENT_CERTIFICATE)) != map_cpy.end()) { tlsRequireClientCertificate = iter->second; } - if((iter = map_cpy.find(TLS_NEGOTIATION_TIMEOUT_SEC)) != map_cpy.end()) { tlsNegotiationTimeoutSec = iter->second; } - if((iter = map_cpy.find(TLS_NEGOTIATION_TIMEOUT_MSEC)) != map_cpy.end()) { tlsNegotiationTimeoutMsec = iter->second; } - - setConfig(accountID, HOSTNAME, hostname); - setConfig(accountID, LOCAL_ADDRESS, localAddress); - setConfig(accountID, PUBLISHED_ADDRESS, publishedAddress); - setConfig(accountID, LOCAL_PORT, localPort); - setConfig(accountID, PUBLISHED_PORT, publishedPort); - setConfig(accountID, DISPLAY_NAME, displayName); - setConfig(accountID, SRTP_ENABLE, srtpEnable); - setConfig(accountID, ZRTP_DISPLAY_SAS, zrtpDisplaySas); - setConfig(accountID, ZRTP_DISPLAY_SAS_ONCE, zrtpDisplaySasOnce); - setConfig(accountID, ZRTP_NOT_SUPP_WARNING, zrtpNotSuppWarning); - setConfig(accountID, ZRTP_HELLO_HASH, zrtpHelloHash); - setConfig(accountID, SRTP_KEY_EXCHANGE, srtpKeyExchange); - - setConfig(accountID, TLS_ENABLE, tlsEnable); - setConfig(accountID, TLS_CA_LIST_FILE, tlsCaListFile); - setConfig(accountID, TLS_CERTIFICATE_FILE, tlsCertificateFile); - setConfig(accountID, TLS_PRIVATE_KEY_FILE, tlsPrivateKeyFile); - setConfig(accountID, TLS_PASSWORD, tlsPassword); - setConfig(accountID, TLS_METHOD, tlsMethod); - setConfig(accountID, TLS_CIPHERS, tlsCiphers); - setConfig(accountID, TLS_SERVER_NAME, tlsServerName); - setConfig(accountID, TLS_VERIFY_SERVER, tlsVerifyServer); - setConfig(accountID, TLS_VERIFY_CLIENT, tlsVerifyClient); - setConfig(accountID, TLS_REQUIRE_CLIENT_CERTIFICATE, tlsRequireClientCertificate); - setConfig(accountID, TLS_NEGOTIATION_TIMEOUT_SEC, tlsNegotiationTimeoutSec); - setConfig(accountID, TLS_NEGOTIATION_TIMEOUT_MSEC, tlsNegotiationTimeoutMsec); - - setConfig(accountID, CONFIG_ACCOUNT_ALIAS, alias); - setConfig(accountID, CONFIG_ACCOUNT_MAILBOX, mailbox); - setConfig(accountID, CONFIG_ACCOUNT_ENABLE, accountEnable); - setConfig(accountID, CONFIG_ACCOUNT_TYPE, type); - setConfig(accountID, CONFIG_ACCOUNT_RESOLVE_ONCE, resolveOnce); - setConfig(accountID, CONFIG_ACCOUNT_REGISTRATION_EXPIRE, registrationExpire); - + std::string tlsVerifyClient; + std::string tlsRequireClientCertificate; + std::string tlsNegotiationTimeoutSec; + std::string tlsNegotiationTimeoutMsec; + + if ( (iter = map_cpy.find (HOSTNAME)) != map_cpy.end()) { + hostname = iter->second; + } + + if ( (iter = map_cpy.find (DISPLAY_NAME)) != map_cpy.end()) { + displayName = iter->second; + } + + if ( (iter = map_cpy.find (LOCAL_ADDRESS)) != map_cpy.end()) { + localAddress = iter->second; + } + + if ( (iter = map_cpy.find (PUBLISHED_ADDRESS)) != map_cpy.end()) { + publishedAddress = iter->second; + } + + if ( (iter = map_cpy.find (LOCAL_PORT)) != map_cpy.end()) { + localPort = iter->second; + } + + if ( (iter = map_cpy.find (PUBLISHED_PORT)) != map_cpy.end()) { + publishedPort = iter->second; + } + + if ( (iter = map_cpy.find (STUN_ENABLE)) != map_cpy.end()) { + stunEnable = iter->second; + } + + if ( (iter = map_cpy.find (STUN_SERVER)) != map_cpy.end()) { + stunServer = iter->second; + } + + if ( (iter = map_cpy.find (SRTP_ENABLE)) != map_cpy.end()) { + srtpEnable = iter->second; + } + + if ( (iter = map_cpy.find (ZRTP_DISPLAY_SAS)) != map_cpy.end()) { + zrtpDisplaySas = iter->second; + } + + if ( (iter = map_cpy.find (ZRTP_DISPLAY_SAS_ONCE)) != map_cpy.end()) { + zrtpDisplaySasOnce = iter->second; + } + + if ( (iter = map_cpy.find (ZRTP_NOT_SUPP_WARNING)) != map_cpy.end()) { + zrtpNotSuppWarning = iter->second; + } + + if ( (iter = map_cpy.find (ZRTP_HELLO_HASH)) != map_cpy.end()) { + zrtpHelloHash = iter->second; + } + + if ( (iter = map_cpy.find (SRTP_KEY_EXCHANGE)) != map_cpy.end()) { + srtpKeyExchange = iter->second; + } + + if ( (iter = map_cpy.find (CONFIG_ACCOUNT_ALIAS)) != map_cpy.end()) { + alias = iter->second; + } + + if ( (iter = map_cpy.find (CONFIG_ACCOUNT_MAILBOX)) != map_cpy.end()) { + mailbox = iter->second; + } + + if ( (iter = map_cpy.find (CONFIG_ACCOUNT_ENABLE)) != map_cpy.end()) { + accountEnable = iter->second; + } + + if ( (iter = map_cpy.find (CONFIG_ACCOUNT_TYPE)) != map_cpy.end()) { + type = iter->second; + } + + if ( (iter = map_cpy.find (CONFIG_ACCOUNT_RESOLVE_ONCE)) != map_cpy.end()) { + resolveOnce = iter->second; + } + + if ( (iter = map_cpy.find (CONFIG_ACCOUNT_REGISTRATION_EXPIRE)) != map_cpy.end()) { + registrationExpire = iter->second; + } + + if ( (iter = map_cpy.find (TLS_ENABLE)) != map_cpy.end()) { + tlsEnable = iter->second; + } + + if ( (iter = map_cpy.find (TLS_CA_LIST_FILE)) != map_cpy.end()) { + tlsCaListFile = iter->second; + } + + if ( (iter = map_cpy.find (TLS_CERTIFICATE_FILE)) != map_cpy.end()) { + tlsCertificateFile = iter->second; + } + + if ( (iter = map_cpy.find (TLS_PRIVATE_KEY_FILE)) != map_cpy.end()) { + tlsPrivateKeyFile = iter->second; + } + + if ( (iter = map_cpy.find (TLS_PASSWORD)) != map_cpy.end()) { + tlsPassword = iter->second; + } + + if ( (iter = map_cpy.find (TLS_METHOD)) != map_cpy.end()) { + tlsMethod = iter->second; + } + + if ( (iter = map_cpy.find (TLS_CIPHERS)) != map_cpy.end()) { + tlsCiphers = iter->second; + } + + if ( (iter = map_cpy.find (TLS_SERVER_NAME)) != map_cpy.end()) { + tlsServerName = iter->second; + } + + if ( (iter = map_cpy.find (TLS_VERIFY_SERVER)) != map_cpy.end()) { + tlsVerifyServer = iter->second; + } + + if ( (iter = map_cpy.find (TLS_VERIFY_CLIENT)) != map_cpy.end()) { + tlsVerifyClient = iter->second; + } + + if ( (iter = map_cpy.find (TLS_REQUIRE_CLIENT_CERTIFICATE)) != map_cpy.end()) { + tlsRequireClientCertificate = iter->second; + } + + if ( (iter = map_cpy.find (TLS_NEGOTIATION_TIMEOUT_SEC)) != map_cpy.end()) { + tlsNegotiationTimeoutSec = iter->second; + } + + if ( (iter = map_cpy.find (TLS_NEGOTIATION_TIMEOUT_MSEC)) != map_cpy.end()) { + tlsNegotiationTimeoutMsec = iter->second; + } + + setConfig (accountID, HOSTNAME, hostname); + + setConfig (accountID, LOCAL_ADDRESS, localAddress); + setConfig (accountID, PUBLISHED_ADDRESS, publishedAddress); + setConfig (accountID, LOCAL_PORT, localPort); + setConfig (accountID, PUBLISHED_PORT, publishedPort); + setConfig (accountID, DISPLAY_NAME, displayName); + setConfig (accountID, SRTP_ENABLE, srtpEnable); + setConfig (accountID, ZRTP_DISPLAY_SAS, zrtpDisplaySas); + setConfig (accountID, ZRTP_DISPLAY_SAS_ONCE, zrtpDisplaySasOnce); + setConfig (accountID, ZRTP_NOT_SUPP_WARNING, zrtpNotSuppWarning); + setConfig (accountID, ZRTP_HELLO_HASH, zrtpHelloHash); + setConfig (accountID, SRTP_KEY_EXCHANGE, srtpKeyExchange); + + setConfig (accountID, STUN_ENABLE, stunEnable); + setConfig (accountID, STUN_SERVER, stunServer); + + setConfig (accountID, TLS_ENABLE, tlsEnable); + setConfig (accountID, TLS_CA_LIST_FILE, tlsCaListFile); + setConfig (accountID, TLS_CERTIFICATE_FILE, tlsCertificateFile); + setConfig (accountID, TLS_PRIVATE_KEY_FILE, tlsPrivateKeyFile); + setConfig (accountID, TLS_PASSWORD, tlsPassword); + setConfig (accountID, TLS_METHOD, tlsMethod); + setConfig (accountID, TLS_CIPHERS, tlsCiphers); + setConfig (accountID, TLS_SERVER_NAME, tlsServerName); + setConfig (accountID, TLS_VERIFY_SERVER, tlsVerifyServer); + setConfig (accountID, TLS_VERIFY_CLIENT, tlsVerifyClient); + setConfig (accountID, TLS_REQUIRE_CLIENT_CERTIFICATE, tlsRequireClientCertificate); + setConfig (accountID, TLS_NEGOTIATION_TIMEOUT_SEC, tlsNegotiationTimeoutSec); + setConfig (accountID, TLS_NEGOTIATION_TIMEOUT_MSEC, tlsNegotiationTimeoutMsec); + + setConfig (accountID, CONFIG_ACCOUNT_ALIAS, alias); + setConfig (accountID, CONFIG_ACCOUNT_MAILBOX, mailbox); + setConfig (accountID, CONFIG_ACCOUNT_ENABLE, accountEnable); + setConfig (accountID, CONFIG_ACCOUNT_TYPE, type); + setConfig (accountID, CONFIG_ACCOUNT_RESOLVE_ONCE, resolveOnce); + setConfig (accountID, CONFIG_ACCOUNT_REGISTRATION_EXPIRE, registrationExpire); + saveConfig(); Account * acc = NULL; acc = getAccount (accountID); + if (acc != NULL) { acc->loadConfig(); - + if (acc->isEnabled()) { acc->unregisterVoIPLink(); acc->registerVoIPLink(); @@ -2859,12 +3013,12 @@ void ManagerImpl::setAccountDetails (const std::string& accountID, const std::ma acc->unregisterVoIPLink(); } } else { - _debug("ManagerImpl::setAccountDetails: account is NULL\n"); + _debug ("ManagerImpl::setAccountDetails: account is NULL\n"); } - + // Update account details to the client side if (_dbus) _dbus->getConfigurationManager()->accountsChanged(); - + } void @@ -2872,7 +3026,7 @@ ManagerImpl::sendRegister (const std::string& accountID , const int32_t& enable) { _debug ("ManagerImpl::sendRegister \n"); - + // Update the active field setConfig (accountID, CONFIG_ACCOUNT_ENABLE, (enable == 1) ? TRUE_STR:FALSE_STR); _debug ("ManagerImpl::sendRegister set config done\n"); @@ -2911,7 +3065,7 @@ ManagerImpl::addAccount (const std::map< std::string, std::string >& details) // Get the type accountType = (*details.find (CONFIG_ACCOUNT_TYPE)).second; - _debug ("%s\n", newAccountID.c_str()); + _debug ("%s\n", newAccountID.c_str()); /** @todo Verify the uniqueness, in case a program adds accounts, two in a row. */ @@ -2946,21 +3100,22 @@ ManagerImpl::addAccount (const std::map< std::string, std::string >& details) } void -ManagerImpl::deleteAllCredential(const AccountID& accountID) +ManagerImpl::deleteAllCredential (const AccountID& accountID) { int numberOfCredential = getConfigInt (accountID, CONFIG_CREDENTIAL_NUMBER); - + int i; - for(i = 0; i < numberOfCredential; i++) { + + for (i = 0; i < numberOfCredential; i++) { std::string credentialIndex; std::stringstream streamOut; streamOut << i; credentialIndex = streamOut.str(); - std::string section = "Credential" + std::string(":") + accountID + std::string(":") + credentialIndex; - + std::string section = "Credential" + std::string (":") + accountID + std::string (":") + credentialIndex; + _config.removeSection (section); } - + if (accountID.empty() == false) { setConfig (accountID, CONFIG_CREDENTIAL_NUMBER, 0); } @@ -2972,6 +3127,7 @@ ManagerImpl::removeAccount (const AccountID& accountID) // Get it down and dying Account* remAccount = NULL; remAccount = getAccount (accountID); + if (remAccount != NULL) { remAccount->unregisterVoIPLink(); _accountMap.erase (accountID); @@ -3101,22 +3257,23 @@ ManagerImpl::loadAccountMap() iter++; } - // Those calls that are placed to an uri that cannot be + // Those calls that are placed to an uri that cannot be // associated to an account are using that special account. - // An account, that is not account, in the sense of - // registration. This is useful since the Account object + // An account, that is not account, in the sense of + // registration. This is useful since the Account object // provides a handful of method that simplifies URI creation // and loading of various settings. _directIpAccount = AccountCreator::createAccount (AccountCreator::SIP_DIRECT_IP_ACCOUNT, ""); + if (_directIpAccount == NULL) { - _debug("Failed to create direct ip calls \"account\"\n"); + _debug ("Failed to create direct ip calls \"account\"\n"); } else { // Force the options to be loaded - // No registration in the sense of + // No registration in the sense of // the REGISTER method is performed. - _directIpAccount->registerVoIPLink(); + _directIpAccount->registerVoIPLink(); } - + _debug ("nbAccount loaded %i \n",nbAccount); return nbAccount; @@ -3155,16 +3312,18 @@ ManagerImpl::accountExists (const AccountID& accountID) Account* ManagerImpl::getAccount (const AccountID& accountID) { - // In our definition, + // In our definition, // this is the "direct ip calls account" if (accountID == AccountNULL) { return _directIpAccount; } - + AccountMap::iterator iter = _accountMap.find (accountID); + if (iter == _accountMap.end()) { return NULL; } + return iter->second; } @@ -3238,9 +3397,11 @@ VoIPLink* ManagerImpl::getAccountLink (const AccountID& accountID) { if (accountID!=AccountNULL) { Account* acc = getAccount (accountID); + if (acc) { return acc->getVoIPLink(); } + return 0; } else return SIPVoIPLink::instance (""); @@ -3397,7 +3558,7 @@ void ManagerImpl::check_call_configuration (const CallID& id, const std::string { Call::CallConfiguration config; - if (to.find(SIP_SCHEME) == 0 || to.find(SIPS_SCHEME) == 0) { + if (to.find (SIP_SCHEME) == 0 || to.find (SIPS_SCHEME) == 0) { _debug ("Sending Sip Call \n"); config = Call::IPtoIP; } else { diff --git a/sflphone-common/src/sip/Regex.cpp b/sflphone-common/src/sip/Regex.cpp index b285f227f5e3c11f9d24d8a64038fb79dd2ec07a..65478b14d9b9f2baa662756e2f6c39bba8e0c3e0 100644 --- a/sflphone-common/src/sip/Regex.cpp +++ b/sflphone-common/src/sip/Regex.cpp @@ -10,178 +10,196 @@ * but WITHOUT ANY WARRANTY; without even the implied warranty of * MEstatusHANTABILITY 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ - + #include "Regex.h" -#include <sstream> +#include <sstream> + +namespace sfl +{ + +const int MAX_SUBSTRINGS = 30; + +Regex::Regex (const std::string& pattern) : + _pattern (pattern) + ,_pcreOutputVector (NULL) + ,_re (NULL) +{ + compile(); +} + +Regex::~Regex() +{ + pcre_free (_re); + delete[] _pcreOutputVector; +} + +void Regex::compile (void) +{ + // Compile the pattern + int offset; + const char * error; + + _reMutex.enterMutex(); + _re = pcre_compile (_pattern.c_str(), 0, &error, &offset, NULL); -namespace sfl { + if (_re == NULL) { + std::string offsetStr; + std::stringstream ss; + ss << offset; + offsetStr = ss.str(); - const int MAX_SUBSTRINGS = 30; - - Regex::Regex(const std::string& pattern) : - _pattern(pattern) - ,_pcreOutputVector(NULL) - ,_re(NULL) - { - compile(); + std::string msg ("PCRE compiling failed at offset "); + + throw compile_error (msg); } - - Regex::~Regex() - { - pcre_free(_re); + + // Allocate space for + // the output vector + if (_pcreOutputVector != NULL) { delete[] _pcreOutputVector; } - - void Regex::compile(void) - { - // Compile the pattern - int offset; - const char * error; - - _reMutex.enterMutex(); - _re = pcre_compile(_pattern.c_str(), 0, &error, &offset, NULL); - - if (_re == NULL) { - std::string offsetStr; - std::stringstream ss; - ss << offset; - offsetStr = ss.str(); - - std::string msg("PCRE compiling failed at offset "); - - throw compile_error(msg); - } - - // Allocate space for - // the output vector - if (_pcreOutputVector != NULL) { - delete[] _pcreOutputVector; - } - _pcreOutputVector = new int[MAX_SUBSTRINGS]; - _reMutex.leaveMutex(); - } - - const std::vector<std::string>& Regex::findall(const std::string& subject) - { - // Execute the PCRE regex - int status; - - _reMutex.enterMutex(); - status = pcre_exec(_re, NULL, subject.c_str(), subject.length(), + + _pcreOutputVector = new int[MAX_SUBSTRINGS]; + + _reMutex.leaveMutex(); +} + +const std::vector<std::string>& Regex::findall (const std::string& subject) +{ + // Execute the PCRE regex + int status; + + _reMutex.enterMutex(); + status = pcre_exec (_re, NULL, subject.c_str(), subject.length(), 0, 0, _pcreOutputVector, MAX_SUBSTRINGS); - _reMutex.leaveMutex(); - - // Handle error cases - if (status < 0) { - - // Free the regular expression - pcre_free(_re); - - // Throw and exception - switch(status) { - case PCRE_ERROR_NOMATCH: - throw match_error("No match"); - break; - default: - std::string statusStr; - std::stringstream ss; - ss << status - 1; - statusStr = ss.str(); - - throw match_error(std::string("Matching error number ") + - statusStr + std::string(" occured")); - break; - } + _reMutex.leaveMutex(); + + // Handle error cases + + if (status < 0) { + + // Free the regular expression + pcre_free (_re); + + // Throw and exception + switch (status) { + + case PCRE_ERROR_NOMATCH: + throw match_error ("No match"); + break; + + default: + std::string statusStr; + std::stringstream ss; + ss << status - 1; + statusStr = ss.str(); + + throw match_error (std::string ("Matching error number ") + + statusStr + std::string (" occured")); + break; } - // Output_vector isn't big enough - if (status == 0) { - - status = MAX_SUBSTRINGS/3; - - std::string statusStr; - std::stringstream ss; - ss << status - 1; - statusStr = ss.str(); - - throw std::length_error(std::string("Output vector is not big enough. Has room for") - + statusStr + std::string("captured substrings\n")); - } - - // Copy the contents to the std::vector that will be - // handed to the user - int count = status; - const char **stringlist; - - _reMutex.enterMutex(); - status = pcre_get_substring_list(subject.c_str(), _pcreOutputVector, count, &stringlist); - if (status < 0) { - fprintf(stderr, "Get substring list failed"); - } else { - _outputVector.clear(); - - int i; - for (i = 0; i < count; i++) { - _outputVector.push_back(stringlist[i]); - } - - pcre_free_substring_list(stringlist); - - } - _reMutex.leaveMutex(); - - return _outputVector; + + } + + // Output_vector isn't big enough + if (status == 0) { + + status = MAX_SUBSTRINGS/3; + + std::string statusStr; + std::stringstream ss; + ss << status - 1; + statusStr = ss.str(); + + throw std::length_error (std::string ("Output vector is not big enough. Has room for") + + statusStr + std::string ("captured substrings\n")); } - - range Regex::finditer(const std::string& subject) - { - findall(subject); - std::vector<std::string>::iterator iterBegin = _outputVector.begin(); - std::vector<std::string>::iterator iterEnd = _outputVector.end(); - return range(iterBegin, iterEnd); + + // Copy the contents to the std::vector that will be + // handed to the user + int count = status; + + const char **stringlist; + + _reMutex.enterMutex(); + + status = pcre_get_substring_list (subject.c_str(), _pcreOutputVector, count, &stringlist); + + if (status < 0) { + fprintf (stderr, "Get substring list failed"); + } else { + _outputVector.clear(); + + int i; + + for (i = 0; i < count; i++) { + _outputVector.push_back (stringlist[i]); + } + + pcre_free_substring_list (stringlist); + } - std::string Regex::group(const std::string& groupName) - { - _reMutex.enterMutex(); - - // Executes the regex - findall(_subject); - - // Access the named substring - const char * substring; - std::string substringReturned; - - int rc = pcre_get_named_substring(_re, _subject.c_str(), _pcreOutputVector, - _outputVector.size(), groupName.c_str(), &substring); - - // Handle errors - if (rc < 0) { - - switch(rc) { - case PCRE_ERROR_NOMEMORY: - throw match_error("Couln't get memory"); - break; - case PCRE_ERROR_NOSUBSTRING: - throw match_error("No such captured substring"); - break; - default: - throw match_error("Error copying substring"); - } - - } else { - substringReturned = substring; - pcre_free_substring(substring); - } - _reMutex.leaveMutex(); - - return substringReturned; + _reMutex.leaveMutex(); + + return _outputVector; +} + +range Regex::finditer (const std::string& subject) +{ + findall (subject); + std::vector<std::string>::iterator iterBegin = _outputVector.begin(); + std::vector<std::string>::iterator iterEnd = _outputVector.end(); + return range (iterBegin, iterEnd); +} + +std::string Regex::group (const std::string& groupName) +{ + _reMutex.enterMutex(); + + // Executes the regex + findall (_subject); + + // Access the named substring + const char * substring; + std::string substringReturned; + + int rc = pcre_get_named_substring (_re, _subject.c_str(), _pcreOutputVector, + _outputVector.size(), groupName.c_str(), &substring); + + // Handle errors + + if (rc < 0) { + + switch (rc) { + + case PCRE_ERROR_NOMEMORY: + throw match_error ("Couln't get memory"); + break; + + case PCRE_ERROR_NOSUBSTRING: + throw match_error ("No such captured substring"); + break; + + default: + throw match_error ("Error copying substring"); + } + + } else { + substringReturned = substring; + pcre_free_substring (substring); } + + _reMutex.leaveMutex(); + + return substringReturned; +} } diff --git a/sflphone-common/src/sip/SdesNegotiator.cpp b/sflphone-common/src/sip/SdesNegotiator.cpp index cedfc5e909357f13170213cafcf3ddac105c8faf..76b9019baee766ff672e76a9d693c6349549d0ad 100644 --- a/sflphone-common/src/sip/SdesNegotiator.cpp +++ b/sflphone-common/src/sip/SdesNegotiator.cpp @@ -10,149 +10,155 @@ * 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ - + #include "SdesNegotiator.h" #include "Regex.h" -#include <iostream> +#include <iostream> #include <sstream> #include <algorithm> -#include <stdexcept> - -namespace sfl { - - struct CryptoAttribute { - std::string tag; - std::string cryptoSuite; - std::string keyParams; - std::string sessionParams; - }; - - SdesNegotiator::SdesNegotiator(const std::vector<CryptoSuiteDefinition>& localCapabilites, - const std::vector<std::string>& remoteAttribute) : - _remoteAttribute(remoteAttribute), - _localCapabilities(localCapabilites) - { - +#include <stdexcept> + +namespace sfl +{ + +struct CryptoAttribute { + std::string tag; + std::string cryptoSuite; + std::string keyParams; + std::string sessionParams; +}; + +SdesNegotiator::SdesNegotiator (const std::vector<CryptoSuiteDefinition>& localCapabilites, + const std::vector<std::string>& remoteAttribute) : + _remoteAttribute (remoteAttribute), + _localCapabilities (localCapabilites) +{ + +} + +void SdesNegotiator::parse (void) +{ + // The patterns below try to follow + // the ABNF grammar rules described in + // RFC4568 section 9.2 with the general + // syntax : + //a=crypto:tag 1*WSP crypto-suite 1*WSP key-params *(1*WSP session-param) + + Regex tagPattern, cryptoSuitePattern, keyParamsPattern, sessionParamPattern; + + try { + tagPattern = "^a=crypto:(?P<tag>[0-9]{1,9})"; + + cryptoSuitePattern = "[\x20\x09]+(?P<cryptoSuite>AES_CM_128_HMAC_SHA1_80|" \ + "AES_CM_128_HMAC_SHA1_32|" \ + "F8_128_HMAC_SHA1_80|" \ + "[A-Za-z0-9_]+)"; // srtp-crypto-suite-ext + + keyParamsPattern = "[\x20\x09]+(?P<srtpKeyMethod>inline|[A-Za-z0-9_]+)\\:" \ + "(?P<srtpKeyInfo>[A-Za-z0-9\x2B\x2F\x3D]+)\\|" \ + "2\\^(?P<lifetime>[0-9]+)\\|" \ + "(?P<mkiValue>[0-9]+)\\:" \ + "(?P<mkiLength>[0-9]{1,3})\\;?"; + + sessionParamPattern = "[\x20\x09]+(?P<sessionParam>(kdr\\=[0-9]{1,2}|" \ + "UNENCRYPTED_SRTP|" \ + "UNENCRYPTED_SRTCP|" \ + "UNAUTHENTICATED_SRTP|" \ + "FEC_ORDER=(?P<fecOrder>FEC_SRTP|SRTP_FEC)|" \ + "FEC_KEY=(?P<fecKey>" + keyParamsPattern.getPattern() + ")|" \ + "WSH=(?P<wsh>[0-9]{1,2})|" \ + "(?<!\\-)[[:graph:]]+))*"; // srtp-session-extension + + } catch (compile_error& exception) { + throw parse_error ("A compile exception occured on a pattern."); + } - - void SdesNegotiator::parse(void) - { - // The patterns below try to follow - // the ABNF grammar rules described in - // RFC4568 section 9.2 with the general - // syntax : - //a=crypto:tag 1*WSP crypto-suite 1*WSP key-params *(1*WSP session-param) - - Regex tagPattern, cryptoSuitePattern, keyParamsPattern, sessionParamPattern; - + + + // Take each line from the vector + // and parse its content + + std::vector<std::string>::iterator iter; + + for (iter = _remoteAttribute.begin(); iter != _remoteAttribute.end(); iter++) { + + std::cout << (*iter) << std::endl; + + // Check if the attribute + // starts with a=crypto + // and get the tag for this line + tagPattern << (*iter); + try { - tagPattern = "^a=crypto:(?P<tag>[0-9]{1,9})"; - - cryptoSuitePattern = "[\x20\x09]+(?P<cryptoSuite>AES_CM_128_HMAC_SHA1_80|" \ - "AES_CM_128_HMAC_SHA1_32|" \ - "F8_128_HMAC_SHA1_80|" \ - "[A-Za-z0-9_]+)"; // srtp-crypto-suite-ext - - keyParamsPattern = "[\x20\x09]+(?P<srtpKeyMethod>inline|[A-Za-z0-9_]+)\\:" \ - "(?P<srtpKeyInfo>[A-Za-z0-9\x2B\x2F\x3D]+)\\|" \ - "2\\^(?P<lifetime>[0-9]+)\\|" \ - "(?P<mkiValue>[0-9]+)\\:" \ - "(?P<mkiLength>[0-9]{1,3})\\;?"; - - sessionParamPattern = "[\x20\x09]+(?P<sessionParam>(kdr\\=[0-9]{1,2}|" \ - "UNENCRYPTED_SRTP|" \ - "UNENCRYPTED_SRTCP|" \ - "UNAUTHENTICATED_SRTP|" \ - "FEC_ORDER=(?P<fecOrder>FEC_SRTP|SRTP_FEC)|" \ - "FEC_KEY=(?P<fecKey>" + keyParamsPattern.getPattern() + ")|" \ - "WSH=(?P<wsh>[0-9]{1,2})|" \ - "(?<!\\-)[[:graph:]]+))*"; // srtp-session-extension - - } catch(compile_error& exception) { - throw parse_error("A compile exception occured on a pattern."); - + std::string tag = tagPattern.group ("tag"); + std::cout << "tag = " << tag << std::endl; + } catch (match_error& exception) { + throw parse_error ("Error while parsing the tag field"); } - - - // Take each line from the vector - // and parse its content - - std::vector<std::string>::iterator iter; - for (iter = _remoteAttribute.begin(); iter != _remoteAttribute.end(); iter++) { - - std::cout << (*iter) << std::endl; - - // Check if the attribute - // starts with a=crypto - // and get the tag for this line - tagPattern << (*iter); - try { - std::string tag = tagPattern.group("tag"); - std::cout << "tag = " << tag << std::endl; - } catch (match_error& exception) { - throw parse_error("Error while parsing the tag field"); - } - - // Check if the crypto - // suite is valid and retreive - // its value. - cryptoSuitePattern << (*iter); - try { - std::string cryptoSuite = cryptoSuitePattern.group("cryptoSuite"); - std::cout << "crypto-suite = " << cryptoSuite << std::endl; - } catch (match_error& exception) { - throw parse_error("Error while parsing the crypto-suite field"); - } - - // Parse one or more key-params - // field. - keyParamsPattern << (*iter); - try { - std::string srtpKeyMethod = keyParamsPattern.group("srtpKeyMethod"); - std::cout << "srtp-key-method = " << srtpKeyMethod << std::endl; - - std::string srtpKeyInfo = keyParamsPattern.group("srtpKeyInfo"); - std::cout << "srtp-key-info = " << srtpKeyInfo << std::endl; - - std::string lifetime = keyParamsPattern.group("lifetime"); - std::cout << "lifetime = " << lifetime << std::endl; - - std::string mkiValue = keyParamsPattern.group("mkiValue"); - std::cout << "mkiValue = " << mkiValue << std::endl; - - std::string mkiLength = keyParamsPattern.group("mkiLength"); - std::cout << "mkiLength = " << mkiLength << std::endl; - - } catch (match_error& exception) { - throw parse_error("Error while parsing the key-params field"); - } - - // Parse the optional session-param - // field - sessionParamPattern << (*iter); - try { - std::string sessionParam = sessionParamPattern.group("sessionParam"); - std::cout << "srtp-session-param = " << sessionParam << std::endl; - } catch (not_found& exception){ - // Thats totally find, do nothing - } catch (match_error& exception) { - throw parse_error("Error while parsing the crypto-suite field"); - } + // Check if the crypto + // suite is valid and retreive + // its value. + cryptoSuitePattern << (*iter); + + try { + std::string cryptoSuite = cryptoSuitePattern.group ("cryptoSuite"); + std::cout << "crypto-suite = " << cryptoSuite << std::endl; + } catch (match_error& exception) { + throw parse_error ("Error while parsing the crypto-suite field"); } - - - } - - bool SdesNegotiator::negotiate(void) - { - parse(); + + // Parse one or more key-params + // field. + keyParamsPattern << (*iter); + + try { + std::string srtpKeyMethod = keyParamsPattern.group ("srtpKeyMethod"); + std::cout << "srtp-key-method = " << srtpKeyMethod << std::endl; + + std::string srtpKeyInfo = keyParamsPattern.group ("srtpKeyInfo"); + std::cout << "srtp-key-info = " << srtpKeyInfo << std::endl; + + std::string lifetime = keyParamsPattern.group ("lifetime"); + std::cout << "lifetime = " << lifetime << std::endl; + + std::string mkiValue = keyParamsPattern.group ("mkiValue"); + std::cout << "mkiValue = " << mkiValue << std::endl; + + std::string mkiLength = keyParamsPattern.group ("mkiLength"); + std::cout << "mkiLength = " << mkiLength << std::endl; + + } catch (match_error& exception) { + throw parse_error ("Error while parsing the key-params field"); + } + + // Parse the optional session-param + // field + sessionParamPattern << (*iter); + + try { + std::string sessionParam = sessionParamPattern.group ("sessionParam"); + std::cout << "srtp-session-param = " << sessionParam << std::endl; + } catch (not_found& exception) { + // Thats totally find, do nothing + } catch (match_error& exception) { + throw parse_error ("Error while parsing the crypto-suite field"); + } + } + + +} + +bool SdesNegotiator::negotiate (void) +{ + parse(); +} } diff --git a/sflphone-common/src/sip/sdp.cpp b/sflphone-common/src/sip/sdp.cpp index 04a9630890f84d17f72e21714ebd8ec3b4e03b8c..d7be80a83a33a2467921497e7a2f9d86bea648ac 100644 --- a/sflphone-common/src/sip/sdp.cpp +++ b/sflphone-common/src/sip/sdp.cpp @@ -115,17 +115,19 @@ void Sdp::set_media_descriptor_line (sdpMedia *media, pjmedia_sdp_media** p_med) // Add the direction stream attr = (pjmedia_sdp_attr*) pj_pool_zalloc (_pool, sizeof (pjmedia_sdp_attr)); + pj_strdup2 (_pool, &attr->name, media->get_stream_direction_str().c_str()); + med->attr[ med->attr_count++] = attr; - - if(!_zrtp_hello_hash.empty()) { + + if (!_zrtp_hello_hash.empty()) { try { - sdp_add_zrtp_attribute(med,_zrtp_hello_hash); + sdp_add_zrtp_attribute (med,_zrtp_hello_hash); } catch (...) { throw; } - } else { - _debug("No hash specified\n"); + } else { + _debug ("No hash specified\n"); } *p_med = med; @@ -350,18 +352,18 @@ void Sdp::sdp_add_media_description() } } -void Sdp::sdp_add_zrtp_attribute(pjmedia_sdp_media* media, std::string hash) +void Sdp::sdp_add_zrtp_attribute (pjmedia_sdp_media* media, std::string hash) { - pjmedia_sdp_attr *attribute; + pjmedia_sdp_attr *attribute; char tempbuf[256]; int len; - - attribute = (pjmedia_sdp_attr*)pj_pool_zalloc( _pool, sizeof(pjmedia_sdp_attr) ); - attribute->name = pj_strdup3(_pool, "zrtp-hash"); - + attribute = (pjmedia_sdp_attr*) pj_pool_zalloc (_pool, sizeof (pjmedia_sdp_attr)); + + attribute->name = pj_strdup3 (_pool, "zrtp-hash"); + /* Format: ":version value" */ - len = pj_ansi_snprintf(tempbuf, sizeof(tempbuf), + len = pj_ansi_snprintf (tempbuf, sizeof (tempbuf), "%.*s %.*s", 4, ZRTP_VERSION, @@ -369,10 +371,10 @@ void Sdp::sdp_add_zrtp_attribute(pjmedia_sdp_media* media, std::string hash) hash.c_str()); attribute->value.slen = len; - attribute->value.ptr = (char*) pj_pool_alloc(_pool, attribute->value.slen+1); - pj_memcpy(attribute->value.ptr, tempbuf, attribute->value.slen+1); - - if(pjmedia_sdp_media_add_attr(media, attribute) != PJ_SUCCESS) { + attribute->value.ptr = (char*) pj_pool_alloc (_pool, attribute->value.slen+1); + pj_memcpy (attribute->value.ptr, tempbuf, attribute->value.slen+1); + + if (pjmedia_sdp_media_add_attr (media, attribute) != PJ_SUCCESS) { throw sdpException(); } } diff --git a/sflphone-common/src/sip/sipaccount.cpp b/sflphone-common/src/sip/sipaccount.cpp index 9184d3cc8966a5ee3ea8be284b4459ab37b65e3b..8a3d6c747d89e7cd6597bc6fd04939048f8677dc 100644 --- a/sflphone-common/src/sip/sipaccount.cpp +++ b/sflphone-common/src/sip/sipaccount.cpp @@ -26,21 +26,21 @@ SIPAccount::SIPAccount (const AccountID& accountID) : Account (accountID, "sip") - , _regc(NULL) - , _bRegister(false) - , _registrationExpire("") - , _localIpAddress("") - , _publishedIpAddress("") - , _localPort(atoi(DEFAULT_SIP_PORT)) - , _publishedPort(atoi(DEFAULT_SIP_PORT)) + , _regc (NULL) + , _bRegister (false) + , _registrationExpire ("") + , _localIpAddress ("") + , _publishedIpAddress ("") + , _localPort (atoi (DEFAULT_SIP_PORT)) + , _publishedPort (atoi (DEFAULT_SIP_PORT)) , _transportType (PJSIP_TRANSPORT_UNSPECIFIED) - , _resolveOnce(false) - , _credentialCount(0) - , _cred(NULL) - , _realm(DEFAULT_REALM) - , _authenticationUsername("") - , _tlsSetting(NULL) - , _displayName("") + , _resolveOnce (false) + , _credentialCount (0) + , _cred (NULL) + , _realm (DEFAULT_REALM) + , _authenticationUsername ("") + , _tlsSetting (NULL) + , _displayName ("") { /* SIPVoIPlink is used as a singleton, because we want to have only one link for all the SIP accounts created */ /* So instead of creating a new instance, we just fetch the static instance, or create one if it is not yet */ @@ -50,7 +50,7 @@ SIPAccount::SIPAccount (const AccountID& accountID) /* Represents the number of SIP accounts connected the same link */ dynamic_cast<SIPVoIPLink*> (_link)->incrementClients(); - + } SIPAccount::~SIPAccount() @@ -59,11 +59,11 @@ SIPAccount::~SIPAccount() dynamic_cast<SIPVoIPLink*> (_link)->decrementClients(); /* Delete accounts-related information */ _regc = NULL; - free(_cred); - free(_tlsSetting); + free (_cred); + free (_tlsSetting); } -int SIPAccount::initCredential(void) +int SIPAccount::initCredential (void) { int credentialCount = 0; credentialCount = Manager::instance().getConfigInt (_accountID, CONFIG_CREDENTIAL_NUMBER); @@ -71,83 +71,89 @@ int SIPAccount::initCredential(void) bool md5HashingEnabled = false; int dataType = 0; - md5HashingEnabled = Manager::instance().getConfigBool(PREFERENCES, CONFIG_MD5HASH); + md5HashingEnabled = Manager::instance().getConfigBool (PREFERENCES, CONFIG_MD5HASH); std::string digest; // Create the credential array - pjsip_cred_info * cred_info = (pjsip_cred_info *) malloc(sizeof(pjsip_cred_info)*(credentialCount)); + pjsip_cred_info * cred_info = (pjsip_cred_info *) malloc (sizeof (pjsip_cred_info) * (credentialCount)); + if (cred_info == NULL) { - _debug("Failed to set cred_info for account %s\n", _accountID.c_str()); + _debug ("Failed to set cred_info for account %s\n", _accountID.c_str()); return !SUCCESS; } - - pj_bzero (cred_info, sizeof(pjsip_cred_info)*credentialCount); - + + pj_bzero (cred_info, sizeof (pjsip_cred_info) *credentialCount); + // Use authentication username if provided + if (!_authenticationUsername.empty()) { - cred_info[0].username = pj_str(strdup(_authenticationUsername.c_str())); + cred_info[0].username = pj_str (strdup (_authenticationUsername.c_str())); } else { - cred_info[0].username = pj_str(strdup(_username.c_str())); + cred_info[0].username = pj_str (strdup (_username.c_str())); } - - // Set password - cred_info[0].data = pj_str(strdup(_password.c_str())); - + + // Set password + cred_info[0].data = pj_str (strdup (_password.c_str())); + // Set realm for that credential. * by default. - cred_info[0].realm = pj_str(strdup(_realm.c_str())); - + cred_info[0].realm = pj_str (strdup (_realm.c_str())); + // We want to make sure that the password is really // 32 characters long. Otherwise, pjsip will fail // on an assertion. if (md5HashingEnabled && _password.length() == 32) { - dataType = PJSIP_CRED_DATA_DIGEST; - _debug("Setting digest \n"); + dataType = PJSIP_CRED_DATA_DIGEST; + _debug ("Setting digest \n"); } else { dataType = PJSIP_CRED_DATA_PLAIN_PASSWD; } - - // Set the datatype + + // Set the datatype cred_info[0].data_type = dataType; - + // Set the secheme - cred_info[0].scheme = pj_str("digest"); - + cred_info[0].scheme = pj_str ( (char*)"digest"); + int i; + for (i = 1; i < credentialCount; i++) { std::string credentialIndex; std::stringstream streamOut; streamOut << i - 1; credentialIndex = streamOut.str(); - std::string section = std::string("Credential") + std::string(":") + _accountID + std::string(":") + credentialIndex; + std::string section = std::string ("Credential") + std::string (":") + _accountID + std::string (":") + credentialIndex; + + std::string username = Manager::instance().getConfigString (section, USERNAME); + std::string password = Manager::instance().getConfigString (section, PASSWORD); + std::string realm = Manager::instance().getConfigString (section, REALM); + + cred_info[i].username = pj_str (strdup (username.c_str())); + cred_info[i].data = pj_str (strdup (password.c_str())); + cred_info[i].realm = pj_str (strdup (realm.c_str())); - std::string username = Manager::instance().getConfigString(section, USERNAME); - std::string password = Manager::instance().getConfigString(section, PASSWORD); - std::string realm = Manager::instance().getConfigString(section, REALM); - - cred_info[i].username = pj_str(strdup(username.c_str())); - cred_info[i].data = pj_str(strdup(password.c_str())); - cred_info[i].realm = pj_str(strdup(realm.c_str())); - // We want to make sure that the password is really // 32 characters long. Otherwise, pjsip will fail // on an assertion. + if (md5HashingEnabled && _password.length() == 32) { - dataType = PJSIP_CRED_DATA_DIGEST; - _debug("Setting digest \n"); + dataType = PJSIP_CRED_DATA_DIGEST; + _debug ("Setting digest \n"); } else { dataType = PJSIP_CRED_DATA_PLAIN_PASSWD; } + cred_info[i].data_type = dataType; - - cred_info[i].scheme = pj_str("digest"); - - _debug("Setting credential %d realm = %s passwd = %s username = %s data_type = %d\n", i, realm.c_str(), password.c_str(), username.c_str(), cred_info[i].data_type); + + cred_info[i].scheme = pj_str ( (char*)"digest"); + + _debug ("Setting credential %d realm = %s passwd = %s username = %s data_type = %d\n", i, realm.c_str(), password.c_str(), username.c_str(), cred_info[i].data_type); } _credentialCount = credentialCount; + _cred = cred_info; - + return SUCCESS; } @@ -156,25 +162,34 @@ int SIPAccount::registerVoIPLink() { // Init general settings loadConfig(); - + if (_hostname.length() >= PJ_MAX_HOSTNAME) { return !SUCCESS; } - + // Init set of additional credentials, if supplied by the user initCredential(); - + // Init TLS settings if the user wants to use TLS - bool tlsEnabled = Manager::instance().getConfigBool(_accountID, TLS_ENABLE); + bool tlsEnabled = Manager::instance().getConfigBool (_accountID, TLS_ENABLE); + if (tlsEnabled) { _transportType = PJSIP_TRANSPORT_TLS; initTlsConfiguration(); } - + + // Init STUN settings for this account if the user selected it + bool stunEnabled = Manager::instance().getConfigBool (_accountID, STUN_ENABLE); + + if (stunEnabled) { + _transportType = PJSIP_TRANSPORT_START_OTHER; + initStunConfiguration (); + } + // In our definition of the // ip2ip profile (aka Direct IP Calls), // no registration should be performed - if (_accountID != IP2IP_PROFILE) { + if (_accountID != IP2IP_PROFILE) { int status = _link->sendRegister (_accountID); ASSERT (status , SUCCESS); } @@ -189,7 +204,7 @@ int SIPAccount::unregisterVoIPLink() if (_accountID == IP2IP_PROFILE) { return true; } - + if (_link->sendUnregister (_accountID)) { setRegistrationInfo (NULL); return true; @@ -198,64 +213,97 @@ int SIPAccount::unregisterVoIPLink() } -pjsip_ssl_method SIPAccount::sslMethodStringToPjEnum(const std::string& method) +pjsip_ssl_method SIPAccount::sslMethodStringToPjEnum (const std::string& method) { - if (method == "Default") { return PJSIP_SSL_UNSPECIFIED_METHOD; } - - if (method == "TLSv1") { return PJSIP_TLSV1_METHOD; } - - if (method == "SSLv2") { return PJSIP_SSLV2_METHOD; } - - if (method == "SSLv3") { return PJSIP_SSLV3_METHOD; } - - if (method == "SSLv23") { return PJSIP_SSLV23_METHOD; } - + if (method == "Default") { + return PJSIP_SSL_UNSPECIFIED_METHOD; + } + + if (method == "TLSv1") { + return PJSIP_TLSV1_METHOD; + } + + if (method == "SSLv2") { + return PJSIP_SSLV2_METHOD; + } + + if (method == "SSLv3") { + return PJSIP_SSLV3_METHOD; + } + + if (method == "SSLv23") { + return PJSIP_SSLV23_METHOD; + } + return PJSIP_SSL_UNSPECIFIED_METHOD; } -void SIPAccount::initTlsConfiguration(void) +void SIPAccount::initTlsConfiguration (void) { - /* + /* * Initialize structure to zero */ - _tlsSetting = (pjsip_tls_setting *) malloc(sizeof(pjsip_tls_setting)); - - assert(_tlsSetting); - - pjsip_tls_setting_default(_tlsSetting); - - std::string tlsCaListFile = Manager::instance().getConfigString(_accountID, TLS_CA_LIST_FILE); - std::string tlsCertificateFile = Manager::instance().getConfigString(_accountID, TLS_CERTIFICATE_FILE); - std::string tlsPrivateKeyFile = Manager::instance().getConfigString(_accountID, TLS_PRIVATE_KEY_FILE); - std::string tlsPassword = Manager::instance().getConfigString(_accountID, TLS_PASSWORD); - std::string tlsMethod = Manager::instance().getConfigString(_accountID, TLS_METHOD); - std::string tlsCiphers = Manager::instance().getConfigString(_accountID, TLS_CIPHERS); - std::string tlsServerName = Manager::instance().getConfigString(_accountID, TLS_SERVER_NAME); - bool tlsVerifyServer = Manager::instance().getConfigBool(_accountID, TLS_VERIFY_SERVER); - bool tlsVerifyClient = Manager::instance().getConfigBool(_accountID, TLS_VERIFY_CLIENT); - bool tlsRequireClientCertificate = Manager::instance().getConfigBool(_accountID, TLS_REQUIRE_CLIENT_CERTIFICATE); - std::string tlsNegotiationTimeoutSec = Manager::instance().getConfigString(_accountID, TLS_NEGOTIATION_TIMEOUT_SEC); - std::string tlsNegotiationTimeoutMsec = Manager::instance().getConfigString(_accountID, TLS_NEGOTIATION_TIMEOUT_MSEC); - - pj_cstr(&_tlsSetting->ca_list_file, tlsCaListFile.c_str()); - pj_cstr(&_tlsSetting->cert_file, tlsCertificateFile.c_str()); - pj_cstr(&_tlsSetting->privkey_file, tlsPrivateKeyFile.c_str()); - pj_cstr(&_tlsSetting->password, tlsPassword.c_str()); - _tlsSetting->method = sslMethodStringToPjEnum(tlsMethod); - pj_cstr(&_tlsSetting->ciphers, tlsCiphers.c_str()); - pj_cstr(&_tlsSetting->server_name, tlsServerName.c_str()); - + _tlsSetting = (pjsip_tls_setting *) malloc (sizeof (pjsip_tls_setting)); + + assert (_tlsSetting); + + pjsip_tls_setting_default (_tlsSetting); + + std::string tlsCaListFile = Manager::instance().getConfigString (_accountID, TLS_CA_LIST_FILE); + std::string tlsCertificateFile = Manager::instance().getConfigString (_accountID, TLS_CERTIFICATE_FILE); + std::string tlsPrivateKeyFile = Manager::instance().getConfigString (_accountID, TLS_PRIVATE_KEY_FILE); + std::string tlsPassword = Manager::instance().getConfigString (_accountID, TLS_PASSWORD); + std::string tlsMethod = Manager::instance().getConfigString (_accountID, TLS_METHOD); + std::string tlsCiphers = Manager::instance().getConfigString (_accountID, TLS_CIPHERS); + std::string tlsServerName = Manager::instance().getConfigString (_accountID, TLS_SERVER_NAME); + bool tlsVerifyServer = Manager::instance().getConfigBool (_accountID, TLS_VERIFY_SERVER); + bool tlsVerifyClient = Manager::instance().getConfigBool (_accountID, TLS_VERIFY_CLIENT); + bool tlsRequireClientCertificate = Manager::instance().getConfigBool (_accountID, TLS_REQUIRE_CLIENT_CERTIFICATE); + std::string tlsNegotiationTimeoutSec = Manager::instance().getConfigString (_accountID, TLS_NEGOTIATION_TIMEOUT_SEC); + std::string tlsNegotiationTimeoutMsec = Manager::instance().getConfigString (_accountID, TLS_NEGOTIATION_TIMEOUT_MSEC); + + pj_cstr (&_tlsSetting->ca_list_file, tlsCaListFile.c_str()); + pj_cstr (&_tlsSetting->cert_file, tlsCertificateFile.c_str()); + pj_cstr (&_tlsSetting->privkey_file, tlsPrivateKeyFile.c_str()); + pj_cstr (&_tlsSetting->password, tlsPassword.c_str()); + _tlsSetting->method = sslMethodStringToPjEnum (tlsMethod); + pj_cstr (&_tlsSetting->ciphers, tlsCiphers.c_str()); + pj_cstr (&_tlsSetting->server_name, tlsServerName.c_str()); + _tlsSetting->verify_server = (tlsVerifyServer == true) ? PJ_TRUE: PJ_FALSE; _tlsSetting->verify_client = (tlsVerifyClient == true) ? PJ_TRUE: PJ_FALSE; _tlsSetting->require_client_cert = (tlsRequireClientCertificate == true) ? PJ_TRUE: PJ_FALSE; - - _tlsSetting->timeout.sec = atol(tlsNegotiationTimeoutSec.c_str()); - _tlsSetting->timeout.msec = atol(tlsNegotiationTimeoutMsec.c_str()); - + + _tlsSetting->timeout.sec = atol (tlsNegotiationTimeoutSec.c_str()); + _tlsSetting->timeout.msec = atol (tlsNegotiationTimeoutMsec.c_str()); + +} + +void SIPAccount::initStunConfiguration (void) +{ + size_t pos; + std::string stunServer, serverName, serverPort; + + stunServer = Manager::instance().getConfigString (_accountID, STUN_SERVER); + + // Init STUN socket + pos = stunServer.find (':'); + + if (pos == std::string::npos) { + _stunServerName = pj_str ( (char*)stunServer.data()); + _stunPort = PJ_STUN_PORT; + //stun_status = pj_sockaddr_in_init (&stun_srv.ipv4, &stun_adr, (pj_uint16_t) 3478); + } else { + serverName = stunServer.substr (0, pos); + serverPort = stunServer.substr (pos + 1); + _stunPort = atoi (serverPort.data()); + _stunServerName = pj_str ( (char*)serverName.data()); + //stun_status = pj_sockaddr_in_init (&stun_srv.ipv4, &stun_adr, (pj_uint16_t) nPort); + } } void SIPAccount::loadConfig() -{ +{ // Load primary credential setUsername (Manager::instance().getConfigString (_accountID, USERNAME)); setPassword (Manager::instance().getConfigString (_accountID, PASSWORD)); @@ -263,24 +311,30 @@ void SIPAccount::loadConfig() _realm = Manager::instance().getConfigString (_accountID, REALM); _resolveOnce = Manager::instance().getConfigString (_accountID, CONFIG_ACCOUNT_RESOLVE_ONCE) == "1" ? true : false; - // Load general account settings + // Load general account settings setHostname (Manager::instance().getConfigString (_accountID, HOSTNAME)); + if (Manager::instance().getConfigString (_accountID, CONFIG_ACCOUNT_REGISTRATION_EXPIRE).empty()) { _registrationExpire = DFT_EXPIRE_VALUE; } else { _registrationExpire = Manager::instance().getConfigString (_accountID, CONFIG_ACCOUNT_REGISTRATION_EXPIRE); } - + // Load network settings - std::string localPort = Manager::instance().getConfigString(_accountID, LOCAL_PORT); - std::string publishedPort = Manager::instance().getConfigString(_accountID, PUBLISHED_PORT); + std::string localPort = Manager::instance().getConfigString (_accountID, LOCAL_PORT); + + std::string publishedPort = Manager::instance().getConfigString (_accountID, PUBLISHED_PORT); + + _localPort = atoi (localPort.c_str()); + + _publishedPort = atoi (publishedPort.c_str()); + + _localIpAddress = Manager::instance().getConfigString (_accountID, LOCAL_ADDRESS); + + _publishedIpAddress = Manager::instance().getConfigString (_accountID, PUBLISHED_ADDRESS); - _localPort = atoi(localPort.c_str()); - _publishedPort = atoi(publishedPort.c_str()); - _localIpAddress = Manager::instance().getConfigString(_accountID, LOCAL_ADDRESS); - _publishedIpAddress = Manager::instance().getConfigString(_accountID, PUBLISHED_ADDRESS); _transportType = PJSIP_TRANSPORT_UDP; - + // Account generic Account::loadConfig(); } @@ -292,9 +346,10 @@ bool SIPAccount::fullMatch (const std::string& username, const std::string& host bool SIPAccount::userMatch (const std::string& username) { - if(username.empty()) { + if (username.empty()) { return false; } + return (username == getUsername()); } @@ -303,20 +358,22 @@ bool SIPAccount::hostnameMatch (const std::string& hostname) return (hostname == getHostname()); } -std::string SIPAccount::getMachineName(void) +std::string SIPAccount::getMachineName (void) { std::string hostname; - hostname = std::string(pj_gethostname()->ptr, pj_gethostname()->slen); + hostname = std::string (pj_gethostname()->ptr, pj_gethostname()->slen); return hostname; } -std::string SIPAccount::getLoginName(void) +std::string SIPAccount::getLoginName (void) { std::string username; uid_t uid = getuid(); + struct passwd * user_info = NULL; - user_info = getpwuid(uid); + user_info = getpwuid (uid); + if (user_info != NULL) { username = user_info->pw_name; } @@ -325,19 +382,20 @@ std::string SIPAccount::getLoginName(void) } -std::string SIPAccount::getFromUri(void) +std::string SIPAccount::getFromUri (void) { char uri[PJSIP_MAX_URL_SIZE]; - + std::string scheme; std::string transport; std::string username = _username; std::string hostname = _hostname; - + // UDP does not require the transport specification + if (_transportType == PJSIP_TRANSPORT_TLS) { scheme = "sips:"; - transport = ";transport=" + std::string(pjsip_transport_get_type_name(_transportType)); + transport = ";transport=" + std::string (pjsip_transport_get_type_name (_transportType)); } else { scheme = "sip:"; transport = ""; @@ -347,118 +405,125 @@ std::string SIPAccount::getFromUri(void) if (_username.empty()) { username = getLoginName(); } - + // Get machine hostname if not provided if (_hostname.empty()) { hostname = getMachineName(); - } - - int len = pj_ansi_snprintf(uri, PJSIP_MAX_URL_SIZE, - "<%s%s@%s%s>", - scheme.c_str(), - username.c_str(), - hostname.c_str(), - transport.c_str()); - - return std::string(uri, len); + } + + int len = pj_ansi_snprintf (uri, PJSIP_MAX_URL_SIZE, + + "<%s%s@%s%s>", + scheme.c_str(), + username.c_str(), + hostname.c_str(), + transport.c_str()); + + return std::string (uri, len); } -std::string SIPAccount::getToUri(const std::string& username) +std::string SIPAccount::getToUri (const std::string& username) { char uri[PJSIP_MAX_URL_SIZE]; - + std::string scheme; std::string transport; std::string hostname = _hostname; - + // UDP does not require the transport specification + if (_transportType == PJSIP_TRANSPORT_TLS) { scheme = "sips:"; - transport = ";transport=" + std::string(pjsip_transport_get_type_name(_transportType)); + transport = ";transport=" + std::string (pjsip_transport_get_type_name (_transportType)); } else { scheme = "sip:"; transport = ""; } - + // Check if scheme is already specified - if (username.find("sip") == 0) { + if (username.find ("sip") == 0) { scheme = ""; } - + // Check if hostname is already specified - if (username.find("@") != std::string::npos) { + if (username.find ("@") != std::string::npos) { hostname = ""; - } - - int len = pj_ansi_snprintf(uri, PJSIP_MAX_URL_SIZE, - "<%s%s%s%s%s>", - scheme.c_str(), - username.c_str(), - (hostname.empty()) ? "" : "@", - hostname.c_str(), - transport.c_str()); - - return std::string(uri, len); + } + + int len = pj_ansi_snprintf (uri, PJSIP_MAX_URL_SIZE, + + "<%s%s%s%s%s>", + scheme.c_str(), + username.c_str(), + (hostname.empty()) ? "" : "@", + hostname.c_str(), + transport.c_str()); + + return std::string (uri, len); } -std::string SIPAccount::getServerUri(void) +std::string SIPAccount::getServerUri (void) { char uri[PJSIP_MAX_URL_SIZE]; - + std::string scheme; std::string transport; - + // UDP does not require the transport specification + if (_transportType == PJSIP_TRANSPORT_TLS) { scheme = "sips:"; - transport = ";transport=" + std::string(pjsip_transport_get_type_name(_transportType)); + transport = ";transport=" + std::string (pjsip_transport_get_type_name (_transportType)); } else { scheme = "sip:"; transport = ""; } - - int len = pj_ansi_snprintf(uri, PJSIP_MAX_URL_SIZE, - "<%s%s%s>", - scheme.c_str(), - _hostname.c_str(), - transport.c_str()); - - return std::string(uri, len); + + int len = pj_ansi_snprintf (uri, PJSIP_MAX_URL_SIZE, + + "<%s%s%s>", + scheme.c_str(), + _hostname.c_str(), + transport.c_str()); + + return std::string (uri, len); } -std::string SIPAccount::getContactHeader(const std::string& address, const std::string& port) +std::string SIPAccount::getContactHeader (const std::string& address, const std::string& port) { char contact[PJSIP_MAX_URL_SIZE]; const char * beginquote, * endquote; - + std::string scheme; std::string transport; // if IPV6, should be set to [] beginquote = endquote = ""; - + // UDP does not require the transport specification + if (_transportType == PJSIP_TRANSPORT_TLS) { scheme = "sips:"; - transport = ";transport=" + std::string(pjsip_transport_get_type_name(_transportType)); + transport = ";transport=" + std::string (pjsip_transport_get_type_name (_transportType)); } else { scheme = "sip:"; transport = ""; } - - int len = pj_ansi_snprintf(contact, PJSIP_MAX_URL_SIZE, - "%s%s<%s%s%s%s%s%s:%d%s>", - _displayName.c_str(), - (_displayName.empty() ? "" : " "), - scheme.c_str(), - _username.c_str(), - (_username.empty() ? "":"@"), - beginquote, - address.c_str(), - endquote, - atoi(port.c_str()), - transport.c_str()); - - return std::string(contact, len); + + int len = pj_ansi_snprintf (contact, PJSIP_MAX_URL_SIZE, + + "%s%s<%s%s%s%s%s%s:%d%s>", + _displayName.c_str(), + (_displayName.empty() ? "" : " "), + scheme.c_str(), + _username.c_str(), + (_username.empty() ? "":"@"), + beginquote, + address.c_str(), + endquote, + atoi (port.c_str()), + transport.c_str()); + + return std::string (contact, len); } diff --git a/sflphone-common/src/sip/sipaccount.h b/sflphone-common/src/sip/sipaccount.h index 62b2725798400815fd405e4f94ea9658fa933368..ba01d608feb211b22881c4660af35be030bb6739 100644 --- a/sflphone-common/src/sip/sipaccount.h +++ b/sflphone-common/src/sip/sipaccount.h @@ -120,12 +120,34 @@ class SIPAccount : public Account * TLS transport. */ inline pjsip_tls_setting * getTlsSetting(void) { return _tlsSetting; } + + /** + * @return pj_str_t , filled from the configuration + * file, that can be used directly by PJSIP to initialize + * an alternate UDP transport. + */ + inline pj_str_t getStunServerName(void) { return _stunServerName; } + + /** + * @return pj_uint8_t structure, filled from the configuration + * file, that can be used directly by PJSIP to initialize + * an alternate UDP transport. + */ + inline pj_uint16_t getStunPort (void) { return _stunPort; } + /** * @return bool Tells if current transport for that * account is set to TLS. */ inline bool isTlsEnabled(void) { return (_transportType == PJSIP_TRANSPORT_TLS) ? true: false; } + + /** + * @return bool Tells if current transport for that + * account is set to OTHER. + */ + inline bool isStunEnabled(void) { return (_transportType == PJSIP_TRANSPORT_START_OTHER) ? true: false; } + /* * @return pj_str_t "From" uri based on account information. @@ -240,6 +262,11 @@ class SIPAccount : public Account * */ void initTlsConfiguration(void); + + /* + * Initializes STUN config from the config file + */ + void initStunConfiguration (void); /* * Initializes set of additional credentials, if supplied by the user. @@ -292,6 +319,12 @@ class SIPAccount : public Account // The TLS settings, if tls is chosen as // a sip transport. pjsip_tls_setting * _tlsSetting; + + // The STUN server name, if applicable + pj_str_t _stunServerName; + + // The STUN server port, if applicable + pj_uint16_t _stunPort; // Display Name that can be used in SIP URI. std::string _displayName; diff --git a/sflphone-common/src/sip/sipvoiplink.cpp b/sflphone-common/src/sip/sipvoiplink.cpp index afaa83d7fbe46fea46c435b39d2bb8b369be34e2..8b867066ae82797577df0f8e5b38794abddfef3d 100644 --- a/sflphone-common/src/sip/sipvoiplink.cpp +++ b/sflphone-common/src/sip/sipvoiplink.cpp @@ -4,7 +4,7 @@ * Author: Emmanuel Milou <emmanuel.milou@savoirfairelinux.com> * Author: Yun Liu <yun.liu@savoirfairelinux.com> * Author: Pierre-Luc Bacon <pierre-luc.bacon@savoirfairelinux.com> - * + * * 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 3 of the License, or @@ -34,7 +34,9 @@ #include "pjsip/sip_endpoint.h" #include "pjsip/sip_transport_tls.h" -#include "pjsip/sip_uri.h" +#include "pjsip/sip_transport_tls.h" +#include "pjsip/sip_uri.h" +#include <pjnath.h> #include <netinet/in.h> #include <arpa/nameser.h> @@ -89,7 +91,7 @@ int getModId(); * @param call a SIPCall valid pointer * @return bool True */ -bool setCallAudioLocal (SIPCall* call, std::string localIP, bool stun, std::string server); +bool setCallAudioLocal (SIPCall* call, std::string localIP); void handle_incoming_options (pjsip_rx_data *rxdata); @@ -212,12 +214,10 @@ SIPVoIPLink* SIPVoIPLink::_instance = NULL; SIPVoIPLink::SIPVoIPLink (const AccountID& accountID) : VoIPLink (accountID) , _nbTryListenAddr (2) // number of times to try to start SIP listener - , _stunServer ("") , _localExternAddress ("") , _localExternPort (0) , _audiortp (new sfl::AudioRtpFactory()) - ,_regPort (atoi(DEFAULT_SIP_PORT)) - , _useStun (false) + ,_regPort (atoi (DEFAULT_SIP_PORT)) , _clients (0) { // to get random number for RANDOM_PORT @@ -372,7 +372,7 @@ SIPVoIPLink::getEvent() int SIPVoIPLink::sendRegister (AccountID id) { int expire_value; - + pj_status_t status; pj_str_t useragent; pjsip_tx_data *tdata; @@ -392,9 +392,9 @@ int SIPVoIPLink::sendRegister (AccountID id) } // Resolve hostname here and keep its - // IP address for the whole time the - // account is connected. This was a - // workaround meant to help issue + // IP address for the whole time the + // account is connected. This was a + // workaround meant to help issue // #1852 that we hope should be fixed // soon. if (account->isResolveOnce()) { @@ -431,26 +431,38 @@ int SIPVoIPLink::sendRegister (AccountID id) account->setHostname (addr_buf); } } - - // Launch a new TLS listener/transport + + // Launch a new TLS listener/transport // if the user did choose it. if (account->isTlsEnabled()) { - pj_status_t status; - - status = createTlsTransportRetryOnFailure(id); - + pj_status_t status; + + status = createTlsTransportRetryOnFailure (id); + if (status != PJ_SUCCESS) { - _debug("Failed to initialize TLS transport for account %s\n", id.c_str()); + _debug ("Failed to initialize TLS transport for account %s\n", id.c_str()); } } + // Launch a new UDP listener/transport, using the published address + if (account->isStunEnabled ()) { + pj_status_t status; + + status = createAlternateUdpTransport (id); + + if (status != PJ_SUCCESS) { + _debug ("Failed to initialize an other UDP transport with an externe published address for account %s\n", id.c_str()); + } + } + _mutexSIP.enterMutex(); + // Get the client registration information for this particular account regc = account->getRegistrationInfo(); account->setRegister (true); - // Set the expire value of the message from the config file + // Set the expire value of the message from the config file istringstream stream (account->getRegistrationExpire()); stream >> expire_value; @@ -458,7 +470,7 @@ int SIPVoIPLink::sendRegister (AccountID id) expire_value = PJSIP_REGC_EXPIRATION_NOT_SPECIFIED; } - // Update the state of the voip link + // Update the state of the voip link account->setRegistrationState (Trying); if (!validStunServer) { @@ -468,7 +480,7 @@ int SIPVoIPLink::sendRegister (AccountID id) return false; } - // Create the registration according to the account ID + // Create the registration according to the account ID status = pjsip_regc_create (_endpt, (void*) account, ®c_cb, ®c); if (status != PJ_SUCCESS) { @@ -479,37 +491,50 @@ int SIPVoIPLink::sendRegister (AccountID id) // Creates URI std::string fromUri; + std::string contactUri; + std::string srvUri; + std::string address; - + fromUri = account->getFromUri(); + srvUri = account->getServerUri(); - address = findLocalAddressFromUri(srvUri); - - int port = findLocalPortFromUri(srvUri); + + address = findLocalAddressFromUri (srvUri); + + int port = findLocalPortFromUri (srvUri); + std::stringstream ss; + std::string portStr; + ss << port; + ss >> portStr; - contactUri = account->getContactHeader(address, portStr); - - _debug("sendRegister: fromUri: %s serverUri: %s contactUri: %s\n", + + contactUri = account->getContactHeader (address, portStr); + + _debug ("sendRegister: fromUri: %s serverUri: %s contactUri: %s\n", fromUri.c_str(), srvUri.c_str(), contactUri.c_str()); - + pj_str_t pjFrom; - pj_cstr(&pjFrom, fromUri.c_str()); - + + pj_cstr (&pjFrom, fromUri.c_str()); + pj_str_t pjContact; - pj_cstr(&pjContact, contactUri.c_str()); - - pj_str_t pjSrv; - pj_cstr(&pjSrv, srvUri.c_str()); - - // Initializes registration - status = pjsip_regc_init (regc, &pjSrv, &pjFrom, &pjFrom, 1, &pjContact, expire_value); + + pj_cstr (&pjContact, contactUri.c_str()); + + pj_str_t pjSrv; + + pj_cstr (&pjSrv, srvUri.c_str()); + + // Initializes registration + status = pjsip_regc_init (regc, &pjSrv, &pjFrom, &pjFrom, 1, &pjContact, expire_value); if (status != PJ_SUCCESS) { _debug ("UserAgent: Unable to initialize account %d in sendRegister\n", status); @@ -518,10 +543,11 @@ int SIPVoIPLink::sendRegister (AccountID id) } pjsip_cred_info *cred = account->getCredInfo(); + int credential_count = account->getCredentialCount(); - _debug("setting %d credentials in sendRegister\n", credential_count); + _debug ("setting %d credentials in sendRegister\n", credential_count); pjsip_regc_set_credentials (regc, credential_count, cred); - + // Add User-Agent Header pj_list_init (&hdr_list); @@ -608,6 +634,7 @@ SIPVoIPLink::newOutgoingCall (const CallID& id, const std::string& toUrl) if (call) { account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (Manager::instance().getAccountFromCall (id))); + if (account == NULL) { _debug ("Error retrieving the account to the make the call with\n"); call->setConnectionState (Call::Disconnected); @@ -617,10 +644,11 @@ SIPVoIPLink::newOutgoingCall (const CallID& id, const std::string& toUrl) return call; } - std::string toUri = account->getToUri(toUrl); - call->setPeerNumber(toUri); + std::string toUri = account->getToUri (toUrl); + + call->setPeerNumber (toUri); - setCallAudioLocal (call, getLocalIPAddress(), useStun(), getStunServer()); + setCallAudioLocal (call, getLocalIPAddress()); try { _debug ("Creating new rtp session in newOutgoingCall\n"); @@ -942,6 +970,7 @@ SIPVoIPLink::transfer (const CallID& id, const std::string& to) std::string tmp_to; pjsip_evsub *sub; pjsip_tx_data *tdata; + struct pjsip_evsub_user xfer_cb; pj_status_t status; AccountID account_id; @@ -953,20 +982,22 @@ SIPVoIPLink::transfer (const CallID& id, const std::string& to) account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (account_id)); if (account == NULL) { - _debug("SIPVoIPLink::transfer account is null. Returning.\n"); + _debug ("SIPVoIPLink::transfer account is null. Returning.\n"); return false; } - + if (call==0) { _debug ("! SIP Failure: Call doesn't exist\n"); return false; } std::string dest; + pj_str_t pjDest; + if (to.find ("@") == std::string::npos) { - dest = account->getToUri(to); - pj_cstr(&pjDest, dest.c_str()); + dest = account->getToUri (to); + pj_cstr (&pjDest, dest.c_str()); } _debug ("Transfering to %s\n", dest.c_str()); @@ -1192,42 +1223,56 @@ SIPVoIPLink::SIPStartCall (SIPCall* call, const std::string& subject UNUSED) // Get the basic information about the callee account SIPAccount * account = NULL; + account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (id)); + if (account == NULL) { - _debug("Account is null in SIPStartCall\n"); + _debug ("Account is null in SIPStartCall\n"); return false; } - + // Creates URI std::string fromUri; + std::string toUri; + std::string contactUri; - + fromUri = account->getFromUri(); + toUri = call->getPeerNumber(); // expecting a fully well formed sip uri - - std::string address = findLocalAddressFromUri(toUri); - int port = findLocalPortFromUri(toUri); + + std::string address = findLocalAddressFromUri (toUri); + + int port = findLocalPortFromUri (toUri); + std::stringstream ss; + std::string portStr; + ss << port; + ss >> portStr; - contactUri = account->getContactHeader(address, portStr); - - _debug("SIPStartCall: fromUri: %s toUri: %s contactUri: %s\n", + + contactUri = account->getContactHeader (address, portStr); + + _debug ("SIPStartCall: fromUri: %s toUri: %s contactUri: %s\n", fromUri.c_str(), toUri.c_str(), contactUri.c_str()); - + pj_str_t pjFrom; - pj_cstr(&pjFrom, fromUri.c_str()); + + pj_cstr (&pjFrom, fromUri.c_str()); pj_str_t pjContact; - pj_cstr(&pjContact, contactUri.c_str()); + + pj_cstr (&pjContact, contactUri.c_str()); pj_str_t pjTo; - pj_cstr(&pjTo, toUri.c_str()); - + + pj_cstr (&pjTo, toUri.c_str()); + // Create the dialog (UAC) status = pjsip_dlg_create_uac (pjsip_ua_instance(), &pjFrom, &pjContact, @@ -1357,19 +1402,6 @@ SIPVoIPLink::getSIPCall (const CallID& id) return NULL; } - -void SIPVoIPLink::setStunServer (const std::string &server) -{ - if (server != "") { - - useStun (true); - _stunServer = server; - } else { - useStun (false); - _stunServer = std::string (""); - } -} - bool SIPVoIPLink::new_ip_to_ip_call (const CallID& id, const std::string& to) { SIPCall *call; @@ -1383,21 +1415,23 @@ bool SIPVoIPLink::new_ip_to_ip_call (const CallID& id, const std::string& to) if (call) { call->setCallConfiguration (Call::IPtoIP); - setCallAudioLocal (call, getLocalIPAddress(), useStun(), getStunServer()); + setCallAudioLocal (call, getLocalIPAddress()); call->initRecFileName(); - - AccountID accountId = Manager::instance().getAccountFromCall(id); + + AccountID accountId = Manager::instance().getAccountFromCall (id); SIPAccount * account = NULL; - account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount(accountId)); + account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (accountId)); + if (account == NULL) { - _debug("Account is null. Returning\n"); + _debug ("Account is null. Returning\n"); return !PJ_SUCCESS; } - _debug("toUri received in new_ip_to_ip call %s\n", to.c_str()); - std::string toUri = account->getToUri(to); - call->setPeerNumber(toUri); - _debug("toUri in new_ip_to_ip call %s\n", toUri.c_str()); + _debug ("toUri received in new_ip_to_ip call %s\n", to.c_str()); + + std::string toUri = account->getToUri (to); + call->setPeerNumber (toUri); + _debug ("toUri in new_ip_to_ip call %s\n", toUri.c_str()); // Building the local SDP offer call->getLocalSDP()->set_ip_address (getLocalIP()); call->getLocalSDP()->create_initial_offer(); @@ -1407,34 +1441,45 @@ bool SIPVoIPLink::new_ip_to_ip_call (const CallID& id, const std::string& to) } catch (...) { _debug ("! SIP Failure: Unable to create RTP Session in SIPVoIPLink::new_ip_to_ip_call (%s:%d)\n", __FILE__, __LINE__); } - + // Create URI std::string fromUri; + std::string contactUri; + fromUri = account->getFromUri(); - - std::string address = findLocalAddressFromUri(toUri); - int port = findLocalPortFromUri(toUri); + + std::string address = findLocalAddressFromUri (toUri); + + int port = findLocalPortFromUri (toUri); + std::stringstream ss; + std::string portStr; + ss << port; + ss >> portStr; - contactUri = account->getContactHeader(address, portStr); - - _debug("new_ip_to_ip_call: fromUri: %s toUri: %s contactUri: %s\n", + + contactUri = account->getContactHeader (address, portStr); + + _debug ("new_ip_to_ip_call: fromUri: %s toUri: %s contactUri: %s\n", fromUri.c_str(), toUri.c_str(), contactUri.c_str()); - + pj_str_t pjFrom; - pj_cstr(&pjFrom, fromUri.c_str()); + + pj_cstr (&pjFrom, fromUri.c_str()); pj_str_t pjTo; - pj_cstr(&pjTo, toUri.c_str()); + + pj_cstr (&pjTo, toUri.c_str()); pj_str_t pjContact; - pj_cstr(&pjContact, contactUri.c_str()); - + + pj_cstr (&pjContact, contactUri.c_str()); + // Create the dialog (UAC) // (Parameters are "strduped" inside this function) status = pjsip_dlg_create_uac (pjsip_ua_instance(), &pjFrom, &pjContact, &pjTo, NULL, &dialog); @@ -1619,10 +1664,10 @@ bool SIPVoIPLink::pjsip_init() port = _regPort; /* Retrieve the STUN configuration */ - useStun = Manager::instance().getConfigBool(SIGNALISATION, SIP_USE_STUN); - this->setStunServer (Manager::instance().getConfigString (SIGNALISATION, SIP_STUN_SERVER)); - this->useStun(useStun); + //useStun = Manager::instance().getConfigBool (SIGNALISATION, SIP_USE_STUN); + useStun = false; + /* if (useStun && !Manager::instance().isBehindNat (getStunServer(), port)) { port = RANDOM_SIP_PORT; @@ -1631,34 +1676,34 @@ bool SIPVoIPLink::pjsip_init() validStunServer = false; return false; // hoho we can't use the random sip port too... } - } + }*/ _localPort = port; - - // Retreive Direct IP Calls settings. - // This corresponds to the accountID set to + // Retrieve Direct IP Calls settings. + // This corresponds to the accountID set to // AccountNULL SIPAccount * account = NULL; bool directIpCallsTlsEnabled = false; - account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount(AccountNULL)); + account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (AccountNULL)); + if (account == NULL) { - _debug("Account is null"); + _debug ("Account is null"); } else { directIpCallsTlsEnabled = account->isTlsEnabled(); } - + if (useStun) { // set by last isBehindNat() call (ish)... - stunServerResolve(); + //stunServerResolve(); _localExternAddress = Manager::instance().getFirewallAddress(); - _localExternPort = Manager::instance().getFirewallPort(); + _localExternPort = Manager::instance().getFirewallPort(); } else { _localExternAddress = _localIPAddress; _localExternPort = _localPort; errPjsip = createUDPServer(); } - + // Create a UDP listener meant for all accounts // for which TLS was not enabled errPjsip = createUDPServer(); @@ -1669,7 +1714,7 @@ bool SIPVoIPLink::pjsip_init() if (errPjsip != PJ_SUCCESS && !useStun) { _debug ("UserAgent: Could not initialize SIP listener on port %d\n", _localExternPort); _localExternPort = _localPort = RANDOM_SIP_PORT; - + _debug ("UserAgent: Try to initialize SIP listener on port %d\n", _localExternPort); errPjsip = createUDPServer(); @@ -1677,15 +1722,15 @@ bool SIPVoIPLink::pjsip_init() _debug ("UserAgent: Fail to initialize SIP listener on port %d\n", _localExternPort); return errPjsip; } - } - - // If we use stun and UDP server creation + } + + // If we use stun and UDP server creation // failed, then just complain and return // since retrying on a random sip port - // would just go against the need of + // would just go against the need of // using it. if (errPjsip != PJ_SUCCESS && useStun) { - _debug("Could not create UDP server with STUN\n"); + _debug ("Could not create UDP server with STUN\n"); return errPjsip; } @@ -1693,72 +1738,91 @@ bool SIPVoIPLink::pjsip_init() // Create a TLS listener meant for Direct IP calls // if the user did enabled it. - if (directIpCallsTlsEnabled) { - errPjsip = createTlsTransportRetryOnFailure(AccountNULL); + + if (directIpCallsTlsEnabled) { + errPjsip = createTlsTransportRetryOnFailure (AccountNULL); } - + if (errPjsip != PJ_SUCCESS) { - _debug("pj_init(): could not start TLS transport for Direct Calls"); + _debug ("pj_init(): could not start TLS transport for Direct Calls"); } - + // TODO: For TLS, retry on random port, just we already do above // for UDP transport. - + // Initialize transaction layer status = pjsip_tsx_layer_init_module (_endpt); + PJ_ASSERT_RETURN (status == PJ_SUCCESS, 1); // Initialize UA layer module status = pjsip_ua_init_module (_endpt, NULL); + PJ_ASSERT_RETURN (status == PJ_SUCCESS, 1); // Initialize Replaces support. See the Replaces specification in RFC 3891 status = pjsip_replaces_init_module (_endpt); + PJ_ASSERT_RETURN (status == PJ_SUCCESS, 1); // Initialize 100rel support status = pjsip_100rel_init_module (_endpt); + PJ_ASSERT_RETURN (status == PJ_SUCCESS, 1); // Initialize and register sflphone module _mod_ua.name = pj_str ( (char*) name_mod.c_str()); + _mod_ua.id = -1; + _mod_ua.priority = PJSIP_MOD_PRIORITY_APPLICATION; + _mod_ua.on_rx_request = &mod_on_rx_request; + _mod_ua.on_rx_response = &mod_on_rx_response; status = pjsip_endpt_register_module (_endpt, &_mod_ua); + PJ_ASSERT_RETURN (status == PJ_SUCCESS, 1); // Init the event subscription module. // It extends PJSIP by supporting SUBSCRIBE and NOTIFY methods status = pjsip_evsub_init_module (_endpt); + PJ_ASSERT_RETURN (status == PJ_SUCCESS, 1); // Init xfer/REFER module status = pjsip_xfer_init_module (_endpt); + PJ_ASSERT_RETURN (status == PJ_SUCCESS, 1); status = enable_dns_srv_resolver (_endpt, &p_resv); + PJ_ASSERT_RETURN (status == PJ_SUCCESS, 1); // Init the callback for INVITE session: pj_bzero (&inv_cb, sizeof (inv_cb)); inv_cb.on_state_changed = &call_on_state_changed; + inv_cb.on_new_session = &call_on_forked; + inv_cb.on_media_update = &call_on_media_update; + inv_cb.on_tsx_state_changed = &call_on_tsx_changed; + inv_cb.on_rx_offer = &on_rx_offer; // Initialize session invite module status = pjsip_inv_usage_init (_endpt, &inv_cb); + PJ_ASSERT_RETURN (status == PJ_SUCCESS, 1); _debug ("UserAgent: VOIP callbacks initialized\n"); // Add endpoint capabilities (INFO, OPTIONS, etc) for this UA pj_str_t allowed[] = { { (char*) "INFO", 4}, { (char*) "REGISTER", 8}, { (char*) "OPTIONS", 7} }; // //{"INVITE", 6}, {"ACK",3}, {"BYE",3}, {"CANCEL",6} + accepted = pj_str ( (char*) "application/sdp"); // Register supported methods @@ -1776,51 +1840,58 @@ bool SIPVoIPLink::pjsip_init() return PJ_SUCCESS; } -pj_status_t SIPVoIPLink::stunServerResolve (void) +pj_status_t SIPVoIPLink::stunServerResolve (AccountID id) { - pj_str_t stun_adr; - pj_hostent he; + pj_str_t stun_adr, stunServer, hostPart; + pj_uint16_t stunPort; + pj_stun_sock_cb stun_sock_cb; + pj_stun_sock *stun_sock; pj_stun_config stunCfg; - pj_status_t stun_status; - pj_sockaddr stun_srv; - size_t pos; - std::string serverName, serverPort; - int nPort; - std::string stun_server; + pj_status_t status; + const int af = pj_AF_INET(); + + // Fetch the account information from the config file + SIPAccount * account = NULL; + account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (id)); - stun_server = getStunServer(); + if (account == NULL) { + _debug ("createTlsTransportRetryOnFailure: Account is null. Returning"); + return !PJ_SUCCESS; + } + // Get the STUN server name + stunServer = account->getStunServerName (); + stunPort = account->getStunPort (); // Initialize STUN configuration pj_stun_config_init (&stunCfg, &_cp.factory, 0, pjsip_endpt_get_ioqueue (_endpt), pjsip_endpt_get_timer_heap (_endpt)); - stun_status = PJ_EPENDING; + status = PJ_EPENDING; - // Init STUN socket - pos = stun_server.find (':'); + //pj_bzero (&stun_sock_cb, sizeof(stun_sock_cb)); + //stun_sock_cb.on_rx_data = &stun_sock_on_rx_data; + //stun_sock_cb.on_status = &stun_sock_on_status; - if (pos == std::string::npos) { - pj_strdup2 (_pool, &stun_adr, stun_server.data()); - stun_status = pj_sockaddr_in_init (&stun_srv.ipv4, &stun_adr, (pj_uint16_t) 3478); - } else { - serverName = stun_server.substr (0, pos); - serverPort = stun_server.substr (pos + 1); - nPort = atoi (serverPort.data()); - pj_strdup2 (_pool, &stun_adr, serverName.data()); - stun_status = pj_sockaddr_in_init (&stun_srv.ipv4, &stun_adr, (pj_uint16_t) nPort); - } + status = pj_stun_sock_create (&stunCfg, "stunresolve", pj_AF_INET(), &stun_sock_cb, NULL, NULL, &stun_sock); - if (stun_status != PJ_SUCCESS) { - _debug ("UserAgent: Unresolved stun server!\n"); - stun_status = pj_gethostbyname (&stun_adr, &he); + if (status != PJ_SUCCESS) { + char errmsg[PJ_ERR_MSG_SIZE]; + pj_strerror (status, errmsg, sizeof(errmsg)); + _debug ("Error creating STUN socket for %.*s: %s", (int)stunServer.slen, stunServer.ptr, errmsg); + return status; + } - if (stun_status == PJ_SUCCESS) { - pj_sockaddr_in_init (&stun_srv.ipv4, NULL, 0); - stun_srv.ipv4.sin_addr = * (pj_in_addr*) he.h_addr; - stun_srv.ipv4.sin_port = pj_htons ( (pj_uint16_t) 3478); - } - } + status = pj_stun_sock_start (stun_sock, &stunServer, stunPort, NULL); + + if (status != PJ_SUCCESS) { + char errmsg[PJ_ERR_MSG_SIZE]; + pj_strerror (status, errmsg, sizeof(errmsg)); + _debug ("Error starting STUN socket for %.*s: %s", (int)stunServer.slen, stunServer.ptr, errmsg); + pj_stun_sock_destroy (stun_sock); + stun_sock = NULL; + return status; + } - return stun_status; + return status; } int SIPVoIPLink::createUDPServer (void) @@ -1858,212 +1929,386 @@ int SIPVoIPLink::createUDPServer (void) return PJ_SUCCESS; } -std::string SIPVoIPLink::findLocalAddressFromUri(const std::string& uri) +std::string SIPVoIPLink::findLocalAddressFromUri (const std::string& uri) { pj_str_t localAddress; pjsip_transport_type_e transportType; // Find the transport that must be used with the given uri pj_str_t tmp; - pj_strdup2_with_null(_pool, &tmp, uri.c_str()); + pj_strdup2_with_null (_pool, &tmp, uri.c_str()); pjsip_uri * genericUri = NULL; - genericUri = pjsip_parse_uri(_pool, tmp.ptr, tmp.slen, 0); + genericUri = pjsip_parse_uri (_pool, tmp.ptr, tmp.slen, 0); pj_str_t pjMachineName; - pj_strdup(_pool, &pjMachineName, pj_gethostname()); - std::string machineName(pjMachineName.ptr, pjMachineName.slen); - + pj_strdup (_pool, &pjMachineName, pj_gethostname()); + std::string machineName (pjMachineName.ptr, pjMachineName.slen); + if (genericUri == NULL) { - _debug("genericUri is NULL in findLocalPortFromUri\n"); - return machineName; + _debug ("genericUri is NULL in findLocalPortFromUri\n"); + return machineName; } - + pjsip_sip_uri * sip_uri = NULL; - sip_uri = (pjsip_sip_uri*)pjsip_uri_get_uri(genericUri); + + sip_uri = (pjsip_sip_uri*) pjsip_uri_get_uri (genericUri); + if (sip_uri == NULL) { - _debug("Invalid uri in findLocalAddressFromTransport\n"); + _debug ("Invalid uri in findLocalAddressFromTransport\n"); return machineName; } - - if (PJSIP_URI_SCHEME_IS_SIPS(sip_uri)) { + + if (PJSIP_URI_SCHEME_IS_SIPS (sip_uri)) { transportType = PJSIP_TRANSPORT_TLS; } else { transportType = PJSIP_TRANSPORT_UDP; } - // Get the transport manager associated with + // Get the transport manager associated with // this endpoint pjsip_tpmgr * tpmgr = NULL; - tpmgr = pjsip_endpt_get_tpmgr(_endpt); + + tpmgr = pjsip_endpt_get_tpmgr (_endpt); + if (tpmgr == NULL) { - _debug("Unexpected: Cannot get tpmgr from endpoint.\n"); + _debug ("Unexpected: Cannot get tpmgr from endpoint.\n"); return machineName; } - + // Find the local address (and port) based on the registered - // transports and the transport type + // transports and the transport type int port; + pj_status_t status; - status = pjsip_tpmgr_find_local_addr(tpmgr, _pool, transportType, NULL, &localAddress, &port); + + status = pjsip_tpmgr_find_local_addr (tpmgr, _pool, transportType, NULL, &localAddress, &port); + if (status != PJ_SUCCESS) { - _debug("Failed to find local address from transport\n"); - return machineName; - } - - return std::string(localAddress.ptr, localAddress.slen); + _debug ("Failed to find local address from transport\n"); + return machineName; + } + + return std::string (localAddress.ptr, localAddress.slen); } -int SIPVoIPLink::findLocalPortFromUri(const std::string& uri) +int SIPVoIPLink::findLocalPortFromUri (const std::string& uri) { pj_str_t localAddress; pjsip_transport_type_e transportType; int port; - + // Find the transport that must be used with the given uri pj_str_t tmp; - pj_strdup2_with_null(_pool, &tmp, uri.c_str()); + pj_strdup2_with_null (_pool, &tmp, uri.c_str()); pjsip_uri * genericUri = NULL; - genericUri = pjsip_parse_uri(_pool, tmp.ptr, tmp.slen, 0); + genericUri = pjsip_parse_uri (_pool, tmp.ptr, tmp.slen, 0); + if (genericUri == NULL) { - _debug("genericUri is NULL in findLocalPortFromUri\n"); - return atoi(DEFAULT_SIP_PORT); + _debug ("genericUri is NULL in findLocalPortFromUri\n"); + return atoi (DEFAULT_SIP_PORT); } pjsip_sip_uri * sip_uri = NULL; - sip_uri = (pjsip_sip_uri*)pjsip_uri_get_uri(genericUri); + + sip_uri = (pjsip_sip_uri*) pjsip_uri_get_uri (genericUri); + if (sip_uri == NULL) { - _debug("Invalid uri in findLocalAddressFromTransport\n"); - return atoi(DEFAULT_SIP_PORT); + _debug ("Invalid uri in findLocalAddressFromTransport\n"); + return atoi (DEFAULT_SIP_PORT); } - - if (PJSIP_URI_SCHEME_IS_SIPS(sip_uri)) { + + if (PJSIP_URI_SCHEME_IS_SIPS (sip_uri)) { transportType = PJSIP_TRANSPORT_TLS; - port = atoi(DEFAULT_SIP_TLS_PORT); + port = atoi (DEFAULT_SIP_TLS_PORT); } else { transportType = PJSIP_TRANSPORT_UDP; - port = atoi(DEFAULT_SIP_PORT); + port = atoi (DEFAULT_SIP_PORT); } - // Get the transport manager associated with + // Get the transport manager associated with // this endpoint pjsip_tpmgr * tpmgr = NULL; - tpmgr = pjsip_endpt_get_tpmgr(_endpt); + + tpmgr = pjsip_endpt_get_tpmgr (_endpt); + if (tpmgr == NULL) { - _debug("Unexpected: Cannot get tpmgr from endpoint.\n"); + _debug ("Unexpected: Cannot get tpmgr from endpoint.\n"); return port; } - + // Find the local address (and port) based on the registered - // transports and the transport type + // transports and the transport type pj_status_t status; - status = pjsip_tpmgr_find_local_addr(tpmgr, _pool, transportType, NULL, &localAddress, &port); + + status = pjsip_tpmgr_find_local_addr (tpmgr, _pool, transportType, NULL, &localAddress, &port); + if (status != PJ_SUCCESS) { - _debug("Failed to find local address from transport\n"); - } - + _debug ("Failed to find local address from transport\n"); + } + return port; } -pj_status_t SIPVoIPLink::createTlsTransportRetryOnFailure(AccountID id) +pj_status_t SIPVoIPLink::createTlsTransportRetryOnFailure (AccountID id) { pj_status_t success; - + // Create a TLS listener. // Note that STUN cannot be used for // TCP NAT traversal. At the moment (20/08/09) - // user must supply the public address/port + // user must supply the public address/port // manually. - success = createTlsTransport(id); + success = createTlsTransport (id); - if (success != PJ_SUCCESS) { - unsigned int randomPort = RANDOM_SIP_PORT; + if (success != PJ_SUCCESS) { + unsigned int randomPort = RANDOM_SIP_PORT; // Update new port in the corresponding SIPAccount SIPAccount * account = NULL; - account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount(id)); + account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (id)); + if (account == NULL) { - _debug("createTlsTransportRetryOnFailure: Account is null. Returning"); + _debug ("createTlsTransportRetryOnFailure: Account is null. Returning"); return !PJ_SUCCESS; } - - account->setLocalPort((pj_uint16_t) randomPort); - - // Try to start the transport again on - // the new port. - success = createTlsTransport(id); + + account->setLocalPort ( (pj_uint16_t) randomPort); + + // Try to start the transport again on + // the new port. + success = createTlsTransport (id); + if (success != PJ_SUCCESS) { _debug ("createTlsTransportRetryOnFailure: failed to retry on random port %d\n", randomPort); return success; } - + _debug ("createTlsTransportRetryOnFailure: TLS transport listening on port %d\n", randomPort); - } - - return PJ_SUCCESS; + } + + return PJ_SUCCESS; } -pj_status_t SIPVoIPLink::createTlsTransport(AccountID id) +pj_status_t SIPVoIPLink::createAlternateUdpTransport (AccountID id) +{ + pj_sockaddr_in boundAddr, local_addr, bound_addr; + pjsip_host_port a_name; + pj_status_t status; + pj_str_t stunServer, pjAddress; + pj_str_t hostPart; + pj_uint16_t stunPort, port; + pj_sockaddr_in pub_addr; + pj_sock_t sock; + pj_sockaddr stunSrvSocket; + + /* + * Retrieve the account information + */ + SIPAccount * account = NULL; + account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (id)); + + if (account == NULL) { + _debug ("Account is null. Returning"); + return !PJ_SUCCESS; + } + + stunServer = account->getStunServerName (); + stunPort = account->getStunPort (); + + status = stunServerResolve (id); + + if (status != PJ_SUCCESS) { + _debug ("Error resolving STUN server: %s\n", status); + return status; + } + + // Init socket + sock = PJ_INVALID_SOCKET; + + _debug ("Initializing IPv4 socket on %s:%i\n", stunServer.ptr, stunPort); + status = pj_sockaddr_in_init (&boundAddr, &stunServer, 0); + if (status != PJ_SUCCESS) { + _debug ("Error when initializing IPv4 socket on %s:%i\n", stunServer.ptr, stunPort); + return status; + } + + // Create and bind the socket + status = pj_sock_socket (pj_AF_INET(), pj_SOCK_DGRAM(), 0, &sock); + if (status != PJ_SUCCESS) { + _debug ("Socket() error (%d)\n", status); + return status; + } + +/* + status = pj_sockaddr_in_set_str_addr (PJ_AF_INET, &stunSrvSocket, &pjAddress); + if (status != PJ_SUCCESS) { + _debug ("Failed to set published address in %d\n", __LINE__); + return status; + } +*/ +/* + pj_sockaddr_in_init (&local_addr, 0, 0); + + pj_uint16_t localUdpPort = account->getLocalPort(); + + if (localUdpPort != 0) { + local_addr.sin_port = pj_htons (localUdpPort); + } + + std::string localAddress = account->getLocalAddress(); + + if (!localAddress.empty()) { + pj_str_t pjAddress; + pj_cstr (&pjAddress, localAddress.c_str()); + + pj_status_t success; + success = pj_sockaddr_in_set_str_addr (&local_addr, &pjAddress); + + if (success != PJ_SUCCESS) { + _debug ("Failed to set published address in %d\n", __LINE__); + } + } + +*/ + /* Init published name + pj_bzero (&a_name, sizeof (pjsip_host_port)); + + pj_cstr (&a_name.host, (account->getPublishedAddress()).c_str()); + + a_name.port = account->getPublishedPort(); + + _debug ("Alternate UDP transport to be initialized with published address %.*s," + " published port %d, local address %s, local port %d\n", + (int) a_name.host.slen, a_name.host.ptr, + (int) a_name.port, localAddress.c_str(), (int) localUdpPort); + */ + status = pjstun_get_mapped_addr (&_cp.factory, 1, &sock, &stunServer, stunPort, &stunServer, stunPort, &pub_addr); + + if (status != PJ_SUCCESS) { + _debug ("Error contacting STUN server (%d)", status); + pj_sock_close(sock); + return status; + } + + _debug ( "Firewall address : %s:%d", + pj_inet_ntoa (pub_addr.sin_addr), + pj_ntohs(pub_addr.sin_port)); + + // Create UDP-Server (default port: 5060) + // char tmpIP[32]; + // strcpy (tmpIP, stunServer.ptr); + // pj_strdup2 (_pool, &a_name.host, tmpIP); + //a_name.port = (pj_uint16_t) stunPort; + a_name.host = pj_str (pj_inet_ntoa (pub_addr.sin_addr)); + a_name.port = pj_ntohs(pub_addr.sin_port); + + pjsip_udp_transport_attach2 (_endpt, PJSIP_TRANSPORT_UDP, sock, &a_name, 1, NULL); + if (status != PJ_SUCCESS) { + _debug ("Error creating alternate SIP UDP listener (%d)\n", status); + } + + return PJ_SUCCESS; + + // Init bound address to ANY + /* + pj_memset (&bound_addr, 0, sizeof (bound_addr)); + + bound_addr.sin_addr.s_addr = pj_htonl (PJ_INADDR_ANY); + bound_addr.sin_port = pj_htons ( (pj_uint16_t) _localPort); + bound_addr.sin_family = PJ_AF_INET; + pj_bzero (bound_addr.sin_zero, sizeof (bound_addr.sin_zero)); + + // Create UDP-Server (default port: 5060) + strcpy (tmpIP, stunServer.ptr); + pj_strdup2 (_pool, &a_name.host, tmpIP); + a_name.port = (pj_uint16_t) stunPort; + + //status = pjsip_udp_transport_start (_endpt, &bound_addr, &a_name, 1, NULL); + + if (status != PJ_SUCCESS) { + _debug ("UserAgent: (%d) Unable to start UDP transport!\n", status); + return -1; + } else { + _debug ("UserAgent: UDP server listening on port %d\n", _localExternPort); + } + + _debug ("Transport initialized successfully! \n"); + + return PJ_SUCCESS; +*/ +} + + + +pj_status_t SIPVoIPLink::createTlsTransport (AccountID id) { pjsip_tpfactory *tls; pj_sockaddr_in local_addr; - pjsip_host_port a_name; + pjsip_host_port a_name; pj_status_t status; /* Grab the tls settings, populated * from configuration file. */ SIPAccount * account = NULL; - account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount(id)); + account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (id)); + if (account == NULL) { - _debug("Account is null. Returning"); + _debug ("Account is null. Returning"); return !PJ_SUCCESS; } - - /** - * Init local address. - * If IP interface address is not specified, - * socket will be bound to PJ_INADDR_ANY. - * If user specified port is an empty string - * or if it is equal to 0, then the port will - * be chosen automatically by the OS. - */ - pj_sockaddr_in_init(&local_addr, 0, 0); + + /** + * Init local address. + * If IP interface address is not specified, + * socket will be bound to PJ_INADDR_ANY. + * If user specified port is an empty string + * or if it is equal to 0, then the port will + * be chosen automatically by the OS. + */ + pj_sockaddr_in_init (&local_addr, 0, 0); + pj_uint16_t localTlsPort = account->getLocalPort(); + if (localTlsPort != 0) { - local_addr.sin_port = pj_htons(localTlsPort); + local_addr.sin_port = pj_htons (localTlsPort); } - + std::string localAddress = account->getLocalAddress(); + if (!localAddress.empty()) { pj_str_t pjAddress; - pj_cstr(&pjAddress, (account->getLocalAddress()).c_str()); - - pj_status_t success; - success = pj_sockaddr_in_set_str_addr(&local_addr, &pjAddress); - if (success != PJ_SUCCESS) { - _debug("Failed to set local address in %d\n", __LINE__); - } - } - + pj_cstr (&pjAddress, (account->getLocalAddress()).c_str()); + + pj_status_t success; + success = pj_sockaddr_in_set_str_addr (&local_addr, &pjAddress); + + if (success != PJ_SUCCESS) { + _debug ("Failed to set local address in %d\n", __LINE__); + } + } + /* Init published name */ - pj_bzero(&a_name, sizeof(pjsip_host_port)); - pj_cstr(&a_name.host, (account->getPublishedAddress()).c_str()); + pj_bzero (&a_name, sizeof (pjsip_host_port)); + + pj_cstr (&a_name.host, (account->getPublishedAddress()).c_str()); + a_name.port = account->getPublishedPort(); - - /* Get TLS settings. Expected to be filled */ + + /* Get TLS settings. Expected to be filled */ pjsip_tls_setting * tls_setting = account->getTlsSetting(); - - _debug("TLS transport to be initialized with published address %.*s," - " published port %d, local address %s, local port %d\n", - (int)a_name.host.slen, a_name.host.ptr, - (int)a_name.port, localAddress.c_str(), (int)localTlsPort); - - status = pjsip_tls_transport_start(_endpt, tls_setting, &local_addr, &a_name, 1, &tls); - + + _debug ("TLS transport to be initialized with published address %.*s," + " published port %d, local address %s, local port %d\n", + (int) a_name.host.slen, a_name.host.ptr, + (int) a_name.port, localAddress.c_str(), (int) localTlsPort); + + status = pjsip_tls_transport_start (_endpt, tls_setting, &local_addr, &a_name, 1, &tls); + if (status != PJ_SUCCESS) { - _debug("Error creating SIP TLS listener (%d)\n", status); - } + _debug ("Error creating SIP TLS listener (%d)\n", status); + } return PJ_SUCCESS; } @@ -2226,11 +2471,11 @@ void call_on_state_changed (pjsip_inv_session *inv, pjsip_event *e) pj_status_t status; /* Retrieve the call information */ - SIPCall * call = NULL; + SIPCall * call = NULL; call = reinterpret_cast<SIPCall*> (inv->mod_data[_mod_ua.id]); if (call == NULL) { - _debug("Call is NULL in call_on_state_changed"); + _debug ("Call is NULL in call_on_state_changed"); return; } @@ -2239,23 +2484,25 @@ void call_on_state_changed (pjsip_inv_session *inv, pjsip_event *e) // If the call is a direct IP-to-IP call AccountID accId; - SIPVoIPLink * link = NULL; + + SIPVoIPLink * link = NULL; + if (call->getCallConfiguration () == Call::IPtoIP) { link = SIPVoIPLink::instance (""); } else { accId = Manager::instance().getAccountFromCall (call->getCallId()); link = dynamic_cast<SIPVoIPLink *> (Manager::instance().getAccountLink (accId)); } - + if (link == NULL) { - _debug("Link is NULL in call_on_state_changed"); + _debug ("Link is NULL in call_on_state_changed"); return; } - + // If this is an outgoing INVITE that was created because of // REFER/transfer, send NOTIFY to transferer. if (call->getXferSub() && e->type==PJSIP_EVENT_TSX_STATE) { - + int st_code = -1; pjsip_evsub_state ev_state = PJSIP_EVSUB_STATE_ACTIVE; @@ -2315,22 +2562,25 @@ void call_on_state_changed (pjsip_inv_session *inv, pjsip_event *e) return; } - + if (inv->state != PJSIP_INV_STATE_CONFIRMED) { - // Update UI with the current status code and description - //pjsip_transaction * tsx + // Update UI with the current status code and description + //pjsip_transaction * tsx pjsip_transaction * tsx = NULL; tsx = e->body.tsx_state.tsx; int statusCode; + if (tsx != NULL) { statusCode = tsx->status_code; } - const pj_str_t * description = pjsip_get_status_text(statusCode); + + const pj_str_t * description = pjsip_get_status_text (statusCode); + if (statusCode) { - DBusManager::instance().getCallManager()->sipCallStateChanged(call->getCallId(), std::string(description->ptr, description->slen), statusCode); - } + DBusManager::instance().getCallManager()->sipCallStateChanged (call->getCallId(), std::string (description->ptr, description->slen), statusCode); + } } - + // The call is ringing - We need to handle this case only on outgoing call if (inv->state == PJSIP_INV_STATE_EARLY && e->body.tsx_state.tsx->role == PJSIP_ROLE_UAC) { call->setConnectionState (Call::Ringing); @@ -2339,27 +2589,28 @@ void call_on_state_changed (pjsip_inv_session *inv, pjsip_event *e) // After 2xx is sent/received. else if (inv->state == PJSIP_INV_STATE_CONNECTING) { - status = call->getLocalSDP()->check_sdp_answer (inv, rdata); + status = call->getLocalSDP()->check_sdp_answer (inv, rdata); - if (status != PJ_SUCCESS) { + if (status != PJ_SUCCESS) { _debug ("Failed to check_incoming_sdp in call_on_state_changed\n"); return; - } + } } // After we sent or received a ACK - The connection is established else if (inv->state == PJSIP_INV_STATE_CONFIRMED) { - - link->SIPCallAnswered (call, rdata); - + + link->SIPCallAnswered (call, rdata); + } else if (inv->state == PJSIP_INV_STATE_DISCONNECTED) { - - _debug ("State: %s. Cause: %.*s\n", invitationStateMap[inv->state], (int)inv->cause_text.slen, inv->cause_text.ptr); + + _debug ("State: %s. Cause: %.*s\n", invitationStateMap[inv->state], (int) inv->cause_text.slen, inv->cause_text.ptr); switch (inv->cause) { /* The call terminates normally - BYE / CANCEL */ case PJSIP_SC_OK: + case PJSIP_SC_REQUEST_TERMINATED: accId = Manager::instance().getAccountFromCall (call->getCallId()); link = dynamic_cast<SIPVoIPLink *> (Manager::instance().getAccountLink (accId)); @@ -2367,15 +2618,23 @@ void call_on_state_changed (pjsip_inv_session *inv, pjsip_event *e) if (link) { link->SIPCallClosed (call); } + break; - + case PJSIP_SC_NOT_FOUND: /* peer not found */ + case PJSIP_SC_DECLINE: + case PJSIP_SC_REQUEST_TIMEOUT: /* request timeout */ + case PJSIP_SC_NOT_ACCEPTABLE_HERE: /* no compatible codecs */ + case PJSIP_SC_NOT_ACCEPTABLE_ANYWHERE: + case PJSIP_SC_UNSUPPORTED_MEDIA_TYPE: + case PJSIP_SC_UNAUTHORIZED: + case PJSIP_SC_REQUEST_PENDING: accId = Manager::instance().getAccountFromCall (call->getCallId()); link = dynamic_cast<SIPVoIPLink *> (Manager::instance().getAccountLink (accId)); @@ -2444,9 +2703,9 @@ void call_on_media_update (pjsip_inv_session *inv, pj_status_t status) try { call->setAudioStart (true); - link->getAudioRtp()->start(); - } catch(exception& rtpException) { - _debug("%s\n", rtpException.what()); + link->getAudioRtp()->start(); + } catch (exception& rtpException) { + _debug ("%s\n", rtpException.what()); } } @@ -2458,7 +2717,7 @@ void call_on_forked (pjsip_inv_session *inv, pjsip_event *e) void call_on_tsx_changed (pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e) { _debug ("call_on_tsx_changed to state %s\n", transactionStateMap[tsx->state]); - + if (tsx->role==PJSIP_ROLE_UAS && tsx->state==PJSIP_TSX_STATE_TRYING && pjsip_method_cmp (&tsx->method, &pjsip_refer_method) ==0) { /** Handle the refer method **/ @@ -2470,19 +2729,22 @@ void regc_cb (struct pjsip_regc_cbparam *param) { SIPAccount * account = NULL; account = static_cast<SIPAccount *> (param->token); + if (account == NULL) { - _debug("Account is NULL in regc_cb.\n"); + _debug ("Account is NULL in regc_cb.\n"); return; } - - assert(param); - const pj_str_t * description = pjsip_get_status_text(param->code); + + assert (param); + + const pj_str_t * description = pjsip_get_status_text (param->code); + if (param->code) { - DBusManager::instance().getCallManager()->registrationStateChanged(account->getAccountID(), std::string(description->ptr, description->slen), param->code); - std::pair<int, std::string> details(param->code, std::string(description->ptr, description->slen)); - account->setRegistrationStateDetailed(details); + DBusManager::instance().getCallManager()->registrationStateChanged (account->getAccountID(), std::string (description->ptr, description->slen), param->code); + std::pair<int, std::string> details (param->code, std::string (description->ptr, description->slen)); + account->setRegistrationStateDetailed (details); } - + if (param->status == PJ_SUCCESS) { if (param->code < 0 || param->code >= 300) { /* Sometimes, the status is OK, but we still failed. @@ -2491,18 +2753,25 @@ void regc_cb (struct pjsip_regc_cbparam *param) _debug ("UserAgent: The error is: %d\n", param->code); switch (param->code) { + case 606: account->setRegistrationState (ErrorConfStun); break; + case 503: + case 408: account->setRegistrationState (ErrorHost); break; + case 401: + case 403: + case 404: account->setRegistrationState (ErrorAuth); break; + default: account->setRegistrationState (Error); break; @@ -2592,13 +2861,14 @@ mod_on_rx_request (pjsip_rx_data *rdata) // Store the peer number char tmp[PJSIP_MAX_URL_SIZE]; - int length = pjsip_uri_print(PJSIP_URI_IN_FROMTO_HDR, - sip_uri, tmp, PJSIP_MAX_URL_SIZE); - - std::string peerNumber(tmp, length); + int length = pjsip_uri_print (PJSIP_URI_IN_FROMTO_HDR, + sip_uri, tmp, PJSIP_MAX_URL_SIZE); + + std::string peerNumber (tmp, length); // Get the server voicemail notification // Catch the NOTIFY message + if (rdata->msg_info.msg->line.req.method.id == PJSIP_OTHER_METHOD) { method_name = "NOTIFY"; // Retrieve all the message. Should contains only the method name but ... @@ -2675,7 +2945,7 @@ mod_on_rx_request (pjsip_rx_data *rdata) // Have to do some stuff with the SDP // Set the codec map, IP, peer number and so on... for the SIPCall object - setCallAudioLocal (call, link->getLocalIPAddress(), link->useStun(), link->getStunServer()); + setCallAudioLocal (call, link->getLocalIPAddress()); // We retrieve the remote sdp offer in the rdata struct to begin the negociation call->getLocalSDP()->set_ip_address (link->getLocalIPAddress()); @@ -3263,32 +3533,39 @@ void handle_incoming_options (pjsip_rx_data *rdata) /*****************************************************************************************************************/ -bool setCallAudioLocal (SIPCall* call, std::string localIP, bool stun, std::string server) +bool setCallAudioLocal (SIPCall* call, std::string localIP) { + SIPAccount *account = NULL; - // Setting Audio - unsigned int callLocalAudioPort = RANDOM_LOCAL_PORT; - unsigned int callLocalExternAudioPort = callLocalAudioPort; + if (call) { + account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (Manager::instance().getAccountFromCall (call->getCallId ()))); - if (stun) { - // If use Stun server - if (Manager::instance().isBehindNat (server, callLocalAudioPort)) { - callLocalExternAudioPort = Manager::instance().getFirewallPort(); - } - } + // Setting Audio + unsigned int callLocalAudioPort = RANDOM_LOCAL_PORT; + unsigned int callLocalExternAudioPort = callLocalAudioPort; - _debug (" Setting local audio port to: %d\n", callLocalAudioPort); + if (account->isStunEnabled ()) { + // If use Stun server + if (Manager::instance().isBehindNat (std::string (account->getStunServerName ().ptr), callLocalAudioPort)) { + callLocalExternAudioPort = Manager::instance().getFirewallPort(); + } + } - _debug (" Setting local audio port (external) to: %d\n", callLocalExternAudioPort); + _debug (" Setting local audio port to: %d\n", callLocalAudioPort); - // Set local audio port for SIPCall(id) - call->setLocalIp (localIP); - call->setLocalAudioPort (callLocalAudioPort); - call->setLocalExternAudioPort (callLocalExternAudioPort); + _debug (" Setting local audio port (external) to: %d\n", callLocalExternAudioPort); - call->getLocalSDP()->attribute_port_to_all_media (callLocalExternAudioPort); + // Set local audio port for SIPCall(id) + call->setLocalIp (localIP); + call->setLocalAudioPort (callLocalAudioPort); + call->setLocalExternAudioPort (callLocalExternAudioPort); - return true; + call->getLocalSDP()->attribute_port_to_all_media (callLocalExternAudioPort); + + return true; + } + + return false; } std::string fetch_header_value (pjsip_msg *msg, std::string field) @@ -3322,26 +3599,29 @@ std::string fetch_header_value (pjsip_msg *msg, std::string field) return url; } -std::vector<std::string> SIPVoIPLink::getAllIpInterface(void) +std::vector<std::string> SIPVoIPLink::getAllIpInterface (void) { pj_sockaddr addrList[16]; - unsigned int addrCnt = PJ_ARRAY_SIZE(addrList); - + unsigned int addrCnt = PJ_ARRAY_SIZE (addrList); + pj_status_t success; success = pj_enum_ip_interface (pj_AF_INET(), &addrCnt, addrList); - + std::vector<std::string> ifaceList; + if (success != PJ_SUCCESS) { return ifaceList; } - - _debug("Detecting available interfaces...\n"); + + _debug ("Detecting available interfaces...\n"); + int i; + for (i = 0; i < addrCnt; i++) { char tmpAddr[PJ_INET_ADDRSTRLEN]; - pj_sockaddr_print(&addrList[i], tmpAddr, sizeof(tmpAddr), 0); - ifaceList.push_back(std::string(tmpAddr)); - _debug("Local interface %s\n", tmpAddr); + pj_sockaddr_print (&addrList[i], tmpAddr, sizeof (tmpAddr), 0); + ifaceList.push_back (std::string (tmpAddr)); + _debug ("Local interface %s\n", tmpAddr); } } diff --git a/sflphone-common/src/sip/sipvoiplink.h b/sflphone-common/src/sip/sipvoiplink.h index f46c0a198ed556689c4ddfea41cc08054f6baef2..f7425bfd8f9d1311a48c5884859a9a1f4bf93481 100644 --- a/sflphone-common/src/sip/sipvoiplink.h +++ b/sflphone-common/src/sip/sipvoiplink.h @@ -49,7 +49,7 @@ namespace sfl { #define RANDOM_SIP_PORT rand() % 64000 + 1024 // To set the verbosity. From 0 (min) to 6 (max) -#define PJ_LOG_LEVEL 0 +#define PJ_LOG_LEVEL 6 /** * @file sipvoiplink.h @@ -185,22 +185,6 @@ class SIPVoIPLink : public VoIPLink */ bool carryingDTMFdigits(const CallID& id, char code); - /** - * If set to true, we check for a firewall - * @param use true if we use STUN - */ - inline void useStun(bool use) { _useStun=use; } - - inline bool useStun( void ) { return _useStun; } - - /** - * The name of the STUN server - * @param server Server FQDN/IP - */ - void setStunServer(const std::string& server); - - std::string getStunServer (void) { return _stunServer; } - /** * Terminate every call not hangup | brutal | Protected by mutex */ @@ -345,7 +329,7 @@ class SIPVoIPLink : public VoIPLink */ bool pjsip_shutdown(void); - pj_status_t stunServerResolve(); + pj_status_t stunServerResolve (AccountID id); /** Create SIP UDP Listener */ int createUDPServer(); @@ -377,6 +361,8 @@ class SIPVoIPLink : public VoIPLink * @return pj_status_t PJ_SUCCESS on success */ pj_status_t createTlsTransport(AccountID id); + + pj_status_t createAlternateUdpTransport (AccountID id); bool loadSIPLocalIP(); diff --git a/sflphone-common/src/sip/testRegex.cpp b/sflphone-common/src/sip/testRegex.cpp index e947932fc31b6df70c94bc0961ab29093c64ef5a..45152627743263436cfc1fc4b215aa79026498dd 100644 --- a/sflphone-common/src/sip/testRegex.cpp +++ b/sflphone-common/src/sip/testRegex.cpp @@ -3,33 +3,35 @@ #include <algorithm> std::string regularExpression = "^a=crypto:([0-9]{1,9})" \ - "[\x20\x09](AES_CM_128_HMAC_SHA1_80|AES_CM_128_HMAC_SHA1_32|F8_128_HMAC_SHA1_80|[A-Za-z0-9_]+)" \ - "[\x20\x09](inline|[A-Za-z0-9_]+)\\:([A-Za-z0-9\x2B\x2F\x3D]+)\\|2\\^([0-9]+)\\|([0-9]+)\\:([0-9]{1,3})\\;?" \ - "[\x20\x09]?(kdr\\=[0-9]{1,2}|UNENCRYPTED_SRTP|UNENCRYPTED_SRTCP|UNAUTHENTICATED_SRTP|(FEC_ORDER)=(FEC_SRTP|SRTP_FEC)" \ - "|(FEC_KEY)=|(WSH)=([0-9]{1,2})|(?<!\\-)[[:graph:]]+)*"; - + "[\x20\x09](AES_CM_128_HMAC_SHA1_80|AES_CM_128_HMAC_SHA1_32|F8_128_HMAC_SHA1_80|[A-Za-z0-9_]+)" \ + "[\x20\x09](inline|[A-Za-z0-9_]+)\\:([A-Za-z0-9\x2B\x2F\x3D]+)\\|2\\^([0-9]+)\\|([0-9]+)\\:([0-9]{1,3})\\;?" \ + "[\x20\x09]?(kdr\\=[0-9]{1,2}|UNENCRYPTED_SRTP|UNENCRYPTED_SRTCP|UNAUTHENTICATED_SRTP|(FEC_ORDER)=(FEC_SRTP|SRTP_FEC)" \ + "|(FEC_KEY)=|(WSH)=([0-9]{1,2})|(?<!\\-)[[:graph:]]+)*"; + std::string subject = "a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:d0RmdmcmVCspeEc3QGZiNWpVLFJhQX1cfHAwJSoj|2^20|1:32 kdr=12"; -void printSubstring(const std::string& substring) +void printSubstring (const std::string& substring) { std::cout << substring << std::endl; } -void testFindMethods(void) +void testFindMethods (void) { // Test the find methods // std::cout << "Testing pattern 1" << std::endl; - - sfl::Regex pattern(regularExpression); - - // Test the findall method - std::vector<std::string> substring = pattern.findall(subject); - std:for_each(substring.begin(), substring.end(), printSubstring); - + + sfl::Regex pattern (regularExpression); + + // Test the findall method + std::vector<std::string> substring = pattern.findall (subject); + +std: + for_each (substring.begin(), substring.end(), printSubstring); + // Test the finditer method - sfl::range range = pattern.finditer(subject); - std::for_each(range.first, range.second, printSubstring); + sfl::range range = pattern.finditer (subject); + std::for_each (range.first, range.second, printSubstring); // Instanciate a new Regex object // but set the pattern only after @@ -37,64 +39,64 @@ void testFindMethods(void) std::cout << std::endl << "Testing pattern 2" << std::endl; } -void testOperators(void) +void testOperators (void) { sfl::Regex pattern2; - - pattern2.setPattern(regularExpression); + + pattern2.setPattern (regularExpression); pattern2.compile(); - - sfl::range range = pattern2.finditer(subject); - std::for_each(range.first, range.second, printSubstring); - + + sfl::range range = pattern2.finditer (subject); + std::for_each (range.first, range.second, printSubstring); + // Instanciate a new Regex object // but set the pattern only after // the constructor was called. // Use the = operator to set the // regular expression. std::cout << std::endl << "Testing pattern 3" << std::endl; - + sfl::Regex pattern3; - + pattern3 = regularExpression; - - range = pattern3.finditer(subject); - std::for_each(range.first, range.second, printSubstring); - + + range = pattern3.finditer (subject); + std::for_each (range.first, range.second, printSubstring); + // Test the << and >> operators std::cout << std::endl << "Testing pattern 4" << std::endl; sfl::Regex pattern4; pattern4 = regularExpression; - + pattern4 << subject; - + std::vector<std::string> outputVector; pattern4 >> outputVector; - std::for_each(outputVector.begin(), outputVector.end(), printSubstring); + std::for_each (outputVector.begin(), outputVector.end(), printSubstring); } -void testGroup(void) +void testGroup (void) { std::cout << std::endl << "Testing group feature" << std::endl; - + sfl::Regex pattern; - + pattern = "^a=crypto:(?P<tag>[0-9]{1,9})"; - + pattern << subject; - - std::string substring = pattern.group("tag"); - + + std::string substring = pattern.group ("tag"); + std::cout << "Substring: " << substring << std::endl; } -int main(void) -{ +int main (void) +{ testFindMethods(); testOperators(); testGroup(); - + return 0; } diff --git a/sflphone-common/src/sip/testSdesNegotiator.cpp b/sflphone-common/src/sip/testSdesNegotiator.cpp index 52de8b6e11a4121386510182859e9f19250a22c4..46f360f293c7d0eb4f118e28164c21af76d7080b 100644 --- a/sflphone-common/src/sip/testSdesNegotiator.cpp +++ b/sflphone-common/src/sip/testSdesNegotiator.cpp @@ -2,17 +2,17 @@ #include <vector> #include <iostream> -int main(void) +int main (void) { -std::vector<sfl::CryptoSuiteDefinition> localCapabilities; -std::vector<std::string> remoteOffer; + std::vector<sfl::CryptoSuiteDefinition> localCapabilities; + std::vector<std::string> remoteOffer; -remoteOffer.push_back("a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:d0RmdmcmVCspeEc3QGZiNWpVLFJhQX1cfHAwJSoj|2^20|1:32"); -remoteOffer.push_back("a=crypto:1 AES_CM_128_HMAC_SHA1_32 inline:NzB4d1BINUAvLEw6UzF3WSJ+PSdFcGdUJShpX1Zj|2^20|1:32"); + remoteOffer.push_back ("a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:d0RmdmcmVCspeEc3QGZiNWpVLFJhQX1cfHAwJSoj|2^20|1:32"); + remoteOffer.push_back ("a=crypto:1 AES_CM_128_HMAC_SHA1_32 inline:NzB4d1BINUAvLEw6UzF3WSJ+PSdFcGdUJShpX1Zj|2^20|1:32"); -sfl::SdesNegotiator sdesNegotiator(localCapabilities, remoteOffer); + sfl::SdesNegotiator sdesNegotiator (localCapabilities, remoteOffer); -sdesNegotiator.negotiate(); + sdesNegotiator.negotiate(); -return 0; + return 0; } diff --git a/sflphone-common/src/user_cfg.h b/sflphone-common/src/user_cfg.h index 484a1c8dc56d4ac60acded65ee35e64150582706..652027dc7481634f47d04c5d084c446627a90e37 100644 --- a/sflphone-common/src/user_cfg.h +++ b/sflphone-common/src/user_cfg.h @@ -69,8 +69,6 @@ #define PULSE_LENGTH "DTMF.pulseLength" /** Length of the DTMF in millisecond */ #define SEND_DTMF_AS "DTMF.sendDTMFas" /** DTMF send mode */ #define SYMMETRIC "VoIPLink.symmetric" /** VoIP link type */ -#define STUN_ENABLE "STUN.enable" -#define STUN_SERVER "STUN.server" #define ADDRESSBOOK "Addressbook" /** Address book section */ #define ADDRESSBOOK_ENABLE "Addressbook.enable" /** Enable address book */ diff --git a/sflphone-common/src/voiplink.h b/sflphone-common/src/voiplink.h index df1740e8ac65f1cc1d866c2c596fafb87f75124e..b78646b41f1c597ddd35f5bedcacc130c4a97748 100644 --- a/sflphone-common/src/voiplink.h +++ b/sflphone-common/src/voiplink.h @@ -220,8 +220,6 @@ class VoIPLink { */ Call* getCall(const CallID& id); - virtual void setStunServer( const std::string &server ) = 0; - private: /** * ID of parent's Account diff --git a/sflphone-common/test/audiolayerTest.cpp b/sflphone-common/test/audiolayerTest.cpp index 60db813f2d3ea6a00e7fbef563399994b5270a64..92648bc20166977365ad0d5b0a34b7954f9e575e 100644 --- a/sflphone-common/test/audiolayerTest.cpp +++ b/sflphone-common/test/audiolayerTest.cpp @@ -66,8 +66,8 @@ void AudioLayerTest::testAudioLayerConfig() int sampling_rate = Manager::instance().getConfigInt (AUDIO, ALSA_SAMPLE_RATE); int frame_size = Manager::instance().getConfigInt (AUDIO, ALSA_FRAME_SIZE); - CPPUNIT_ASSERT ((int)Manager::instance().getAudioDriver()->getSampleRate() == sampling_rate); - CPPUNIT_ASSERT ((int)Manager::instance().getAudioDriver()->getFrameSize() == frame_size); + CPPUNIT_ASSERT ( (int) Manager::instance().getAudioDriver()->getSampleRate() == sampling_rate); + CPPUNIT_ASSERT ( (int) Manager::instance().getAudioDriver()->getFrameSize() == frame_size); } void AudioLayerTest::testAudioLayerSwitch() diff --git a/sflphone-common/test/rtpTest.cpp b/sflphone-common/test/rtpTest.cpp index 40fe27590d50c5e40eddc934a359b33d88bf26af..fba3f8aeb3adb7706dc05e415226983654a856cf 100644 --- a/sflphone-common/test/rtpTest.cpp +++ b/sflphone-common/test/rtpTest.cpp @@ -73,7 +73,7 @@ bool RtpTest::pjsipInit() return PJ_ENOMEM; } - return true; + return true; }