From 035a6b329e340df2e28e6078d93d212008664da3 Mon Sep 17 00:00:00 2001 From: Emmanuel Milou <emmanuel.milou@savoirfairelinux.com> Date: Fri, 3 Jul 2009 14:17:18 -0400 Subject: [PATCH] [#1777] Code indentation/formatting --- .../libs/dbus-c++/src/connection.cpp | 404 +- sflphone-common/libs/dbus-c++/src/debug.cpp | 21 +- .../libs/dbus-c++/src/dispatcher.cpp | 262 +- .../libs/dbus-c++/src/ecore-integration.cpp | 180 +- sflphone-common/libs/dbus-c++/src/error.cpp | 30 +- .../dbus-c++/src/eventloop-integration.cpp | 134 +- .../libs/dbus-c++/src/eventloop.cpp | 232 +- .../libs/dbus-c++/src/glib-integration.cpp | 329 +- .../libs/dbus-c++/src/interface.cpp | 161 +- .../libs/dbus-c++/src/introspection.cpp | 204 +- sflphone-common/libs/dbus-c++/src/message.cpp | 560 +- sflphone-common/libs/dbus-c++/src/object.cpp | 415 +- .../libs/dbus-c++/src/pendingcall.cpp | 102 +- .../libs/dbus-c++/src/property.cpp | 143 +- sflphone-common/libs/dbus-c++/src/server.cpp | 94 +- sflphone-common/libs/dbus-c++/src/types.cpp | 61 +- .../libs/dbus-c++/tools/generate_adaptor.cpp | 1288 +++-- .../libs/dbus-c++/tools/generate_proxy.cpp | 1187 ++-- .../libs/dbus-c++/tools/generator_utils.cpp | 251 +- .../libs/dbus-c++/tools/introspect.cpp | 58 +- sflphone-common/libs/dbus-c++/tools/xml.cpp | 378 +- .../libs/dbus-c++/tools/xml2cpp.cpp | 127 +- .../pjlib-util/include/pjlib-util/config.h | 18 +- .../pjproject-1.0.2/pjlib/include/pj/config.h | 226 +- .../pjlib/src/pj/addr_resolv_symbian.cpp | 218 +- .../pjlib/src/pj/exception_symbian.cpp | 42 +- .../pjlib/src/pj/ioqueue_symbian.cpp | 875 +-- .../pjlib/src/pj/ip_helper_symbian.cpp | 152 +- .../src/pj/log_writer_symbian_console.cpp | 20 +- .../pjlib/src/pj/os_core_symbian.cpp | 575 +- .../pjlib/src/pj/os_error_symbian.cpp | 163 +- .../pjlib/src/pj/pool_policy_new.cpp | 60 +- .../pjlib/src/pj/sock_select_symbian.cpp | 143 +- .../pjlib/src/pj/sock_symbian.cpp | 756 +-- .../pjlib/src/pj/timer_symbian.cpp | 212 +- .../pjlib/src/pj/unicode_symbian.cpp | 36 +- .../pjlib/src/pjlib++-test/main.cpp | 20 +- .../pjlib/src/pjlib-test/main_symbian.cpp | 102 +- .../pjmedia/include/pjmedia-codec/config.h | 8 +- .../pjmedia/include/pjmedia/config.h | 72 +- .../pjmedia/src/pjmedia/symbian_sound.cpp | 984 ++-- .../pjmedia/src/pjmedia/symbian_sound_aps.cpp | 1022 ++-- .../pjnath/include/pjnath/config.h | 30 +- .../src/pjsua_wince/pjsua_wince.cpp | 797 +-- .../pjsip-apps/src/pocketpj/PocketPJ.cpp | 54 +- .../pjsip-apps/src/pocketpj/PocketPJDlg.cpp | 893 +-- .../pjsip-apps/src/pocketpj/PopUpWnd.cpp | 219 +- .../pjsip-apps/src/pocketpj/SettingsDlg.cpp | 400 +- .../src/symbian_ua/main_symbian.cpp | 30 +- .../pjsip-apps/src/symbian_ua/ua.cpp | 1116 ++-- .../src/Symbian_ua_guiSettingItemListSets.cpp | 191 +- .../src/symbian_ua_gui/src/symbian_ua.cpp | 502 +- .../src/symbian_ua_guiAppUi.cpp | 340 +- .../src/symbian_ua_guiApplication.cpp | 54 +- .../src/symbian_ua_guiContainer.cpp | 383 +- .../src/symbian_ua_guiContainerView.cpp | 661 +-- .../src/symbian_ua_guiDocument.cpp | 48 +- .../src/symbian_ua_guiSettingItemList.cpp | 612 +- .../src/symbian_ua_guiSettingItemListView.cpp | 372 +- .../pjsip-apps/src/symsndtest/app_main.cpp | 377 +- .../src/symsndtest/main_symbian.cpp | 90 +- .../third_party/build/speex/config.h | 4 +- .../hostapi/asio/iasiothiscallresolver.cpp | 114 +- .../portaudio/src/hostapi/asio/pa_asio.cpp | 2992 +++++----- .../src/hostapi/wasapi/pa_win_wasapi.cpp | 1830 +++--- .../utilspp/singleton/LifetimeLibrary.cpp | 91 +- .../libs/utilspp/singleton/PrivateMembers.cpp | 42 +- sflphone-common/src/account.cpp | 31 +- sflphone-common/src/accountcreator.cpp | 31 +- sflphone-common/src/audio/alsalayer.cpp | 607 +- sflphone-common/src/audio/audiodevice.cpp | 8 +- sflphone-common/src/audio/audiofile.cpp | 217 +- sflphone-common/src/audio/audiolayer.cpp | 34 +- sflphone-common/src/audio/audioloop.cpp | 68 +- sflphone-common/src/audio/audiortp.cpp | 399 +- sflphone-common/src/audio/audiostream.cpp | 230 +- sflphone-common/src/audio/codecDescriptor.cpp | 477 +- sflphone-common/src/audio/codecs/alaw.cpp | 204 +- .../src/audio/codecs/celtcodec.cpp | 82 +- sflphone-common/src/audio/codecs/g722.cpp | 1348 ++--- sflphone-common/src/audio/codecs/gsmcodec.cpp | 107 +- .../src/audio/codecs/speexcodec_nb.cpp | 138 +- .../src/audio/codecs/speexcodec_ub.cpp | 140 +- .../src/audio/codecs/speexcodec_wb.cpp | 140 +- sflphone-common/src/audio/codecs/ulaw.cpp | 189 +- sflphone-common/src/audio/dtmf.cpp | 85 +- sflphone-common/src/audio/dtmfgenerator.cpp | 259 +- sflphone-common/src/audio/pulselayer.cpp | 481 +- sflphone-common/src/audio/ringbuffer.cpp | 271 +- sflphone-common/src/audio/tone.cpp | 168 +- sflphone-common/src/audio/tonegenerator.cpp | 46 +- sflphone-common/src/audio/tonelist.cpp | 190 +- sflphone-common/src/call.cpp | 123 +- sflphone-common/src/config/config.cpp | 504 +- sflphone-common/src/config/config.h | 287 +- sflphone-common/src/dbus/callmanager.cpp | 167 +- .../src/dbus/configurationmanager.cpp | 384 +- sflphone-common/src/dbus/contactmanager.cpp | 22 +- sflphone-common/src/dbus/dbusmanagerimpl.cpp | 31 +- sflphone-common/src/dbus/instance.cpp | 36 +- sflphone-common/src/eventthread.cpp | 32 +- sflphone-common/src/history/historyitem.cpp | 40 +- .../src/history/historymanager.cpp | 89 +- sflphone-common/src/hooks/urlhook.cpp | 3 +- sflphone-common/src/iaxaccount.cpp | 28 +- sflphone-common/src/iaxcall.cpp | 165 +- sflphone-common/src/iaxvoiplink.cpp | 629 ++- sflphone-common/src/main.cpp | 196 +- sflphone-common/src/managerimpl.cpp | 2789 ++++----- sflphone-common/src/numbercleaner.cpp | 16 +- sflphone-common/src/observer.cpp | 43 +- .../src/plug-in/audiorecorder/audiodsp.cpp | 49 +- .../src/plug-in/audiorecorder/audiorecord.cpp | 681 +-- .../src/plug-in/librarymanager.cpp | 50 +- sflphone-common/src/plug-in/pluginmanager.cpp | 110 +- .../src/plug-in/test/pluginTest.cpp | 17 +- sflphone-common/src/samplerateconverter.cpp | 202 +- sflphone-common/src/sdp.cpp | 277 +- sflphone-common/src/sdpmedia.cpp | 76 +- sflphone-common/src/sipaccount.cpp | 68 +- sflphone-common/src/sipcall.cpp | 23 +- sflphone-common/src/sipvoiplink.cpp | 5007 +++++++++-------- sflphone-common/src/voiplink.cpp | 67 +- sflphone-common/test/TestMain.cpp | 4 +- sflphone-common/test/audiolayerTest.cpp | 206 +- sflphone-common/test/audiorecorderTest.cpp | 48 +- sflphone-common/test/configurationTest.cpp | 132 +- sflphone-common/test/historyTest.cpp | 30 +- sflphone-common/test/hookmanagerTest.cpp | 17 +- sflphone-common/test/numbercleanerTest.cpp | 43 +- sflphone-common/test/pluginmanagerTest.cpp | 58 +- sflphone-common/test/rtpTest.cpp | 165 +- 132 files changed, 22760 insertions(+), 20671 deletions(-) diff --git a/sflphone-common/libs/dbus-c++/src/connection.cpp b/sflphone-common/libs/dbus-c++/src/connection.cpp index 9fb85a1550..b7b6729726 100644 --- a/sflphone-common/libs/dbus-c++/src/connection.cpp +++ b/sflphone-common/libs/dbus-c++/src/connection.cpp @@ -41,398 +41,396 @@ using namespace DBus; -Connection::Private::Private(DBusConnection *c, Server::Private *s) -: conn(c) , dispatcher(0), server(s) +Connection::Private::Private (DBusConnection *c, Server::Private *s) + : conn (c) , dispatcher (0), server (s) { - init(); + init(); } -Connection::Private::Private(DBusBusType type) +Connection::Private::Private (DBusBusType type) { - InternalError e; + InternalError e; - conn = dbus_bus_get_private(type, e); + conn = dbus_bus_get_private (type, e); - if (e) throw Error(e); + if (e) throw Error (e); - init(); + init(); } Connection::Private::~Private() { - debug_log("terminating connection 0x%08x", conn); + debug_log ("terminating connection 0x%08x", conn); + + detach_server(); + + if (dbus_connection_get_is_connected (conn)) { + std::vector<std::string>::iterator i = names.begin(); - detach_server(); + while (i != names.end()) { + debug_log ("%s: releasing bus name %s", dbus_bus_get_unique_name (conn), i->c_str()); + dbus_bus_release_name (conn, i->c_str(), NULL); + ++i; + } - if (dbus_connection_get_is_connected(conn)) - { - std::vector<std::string>::iterator i = names.begin(); + dbus_connection_close (conn); + } - while (i != names.end()) - { - debug_log("%s: releasing bus name %s", dbus_bus_get_unique_name(conn), i->c_str()); - dbus_bus_release_name(conn, i->c_str(), NULL); - ++i; - } - dbus_connection_close(conn); - } - dbus_connection_unref(conn); + dbus_connection_unref (conn); } void Connection::Private::init() { - dbus_connection_ref(conn); - dbus_connection_ref(conn); //todo: the library has to own another reference + dbus_connection_ref (conn); + dbus_connection_ref (conn); //todo: the library has to own another reference - disconn_filter = new Callback<Connection::Private, bool, const Message &>( - this, &Connection::Private::disconn_filter_function - ); + disconn_filter = new Callback<Connection::Private, bool, const Message &> ( + this, &Connection::Private::disconn_filter_function + ); - dbus_connection_add_filter(conn, message_filter_stub, &disconn_filter, NULL); // TODO: some assert at least + dbus_connection_add_filter (conn, message_filter_stub, &disconn_filter, NULL); // TODO: some assert at least - dbus_connection_set_dispatch_status_function(conn, dispatch_status_stub, this, 0); - dbus_connection_set_exit_on_disconnect(conn, false); //why was this set to true?? + dbus_connection_set_dispatch_status_function (conn, dispatch_status_stub, this, 0); + dbus_connection_set_exit_on_disconnect (conn, false); //why was this set to true?? } void Connection::Private::detach_server() { -/* Server::Private *tmp = server; + /* Server::Private *tmp = server; - server = NULL; + server = NULL; - if (tmp) - { - ConnectionList::iterator i; + if (tmp) + { + ConnectionList::iterator i; - for (i = tmp->connections.begin(); i != tmp->connections.end(); ++i) - { - if (i->_pvt.get() == this) - { - tmp->connections.erase(i); - break; - } - } - }*/ + for (i = tmp->connections.begin(); i != tmp->connections.end(); ++i) + { + if (i->_pvt.get() == this) + { + tmp->connections.erase(i); + break; + } + } + }*/ } bool Connection::Private::do_dispatch() { - debug_log("dispatching on %p", conn); + debug_log ("dispatching on %p", conn); - if (!dbus_connection_get_is_connected(conn)) - { - debug_log("connection terminated"); + if (!dbus_connection_get_is_connected (conn)) { + debug_log ("connection terminated"); - detach_server(); + detach_server(); - return true; - } + return true; + } - return dbus_connection_dispatch(conn) != DBUS_DISPATCH_DATA_REMAINS; + return dbus_connection_dispatch (conn) != DBUS_DISPATCH_DATA_REMAINS; } -void Connection::Private::dispatch_status_stub(DBusConnection *dc, DBusDispatchStatus status, void *data) +void Connection::Private::dispatch_status_stub (DBusConnection *dc, DBusDispatchStatus status, void *data) { - Private *p = static_cast<Private *>(data); + Private *p = static_cast<Private *> (data); - switch (status) - { - case DBUS_DISPATCH_DATA_REMAINS: - debug_log("some dispatching to do on %p", dc); - p->dispatcher->queue_connection(p); - break; + switch (status) { - case DBUS_DISPATCH_COMPLETE: - debug_log("all dispatching done on %p", dc); - break; + case DBUS_DISPATCH_DATA_REMAINS: + debug_log ("some dispatching to do on %p", dc); + p->dispatcher->queue_connection (p); + break; - case DBUS_DISPATCH_NEED_MEMORY: //uh oh... - debug_log("connection %p needs memory", dc); - break; - } + case DBUS_DISPATCH_COMPLETE: + debug_log ("all dispatching done on %p", dc); + break; + + case DBUS_DISPATCH_NEED_MEMORY: //uh oh... + debug_log ("connection %p needs memory", dc); + break; + } } -DBusHandlerResult Connection::Private::message_filter_stub(DBusConnection *conn, DBusMessage *dmsg, void *data) +DBusHandlerResult Connection::Private::message_filter_stub (DBusConnection *conn, DBusMessage *dmsg, void *data) { - MessageSlot *slot = static_cast<MessageSlot *>(data); + MessageSlot *slot = static_cast<MessageSlot *> (data); - Message msg = Message(new Message::Private(dmsg)); + Message msg = Message (new Message::Private (dmsg)); - return slot && !slot->empty() && slot->call(msg) - ? DBUS_HANDLER_RESULT_HANDLED - : DBUS_HANDLER_RESULT_NOT_YET_HANDLED; + return slot && !slot->empty() && slot->call (msg) + ? DBUS_HANDLER_RESULT_HANDLED + : DBUS_HANDLER_RESULT_NOT_YET_HANDLED; } -bool Connection::Private::disconn_filter_function(const Message &msg) +bool Connection::Private::disconn_filter_function (const Message &msg) { - if (msg.is_signal(DBUS_INTERFACE_LOCAL,"Disconnected")) - { - debug_log("%p disconnected by local bus", conn); - dbus_connection_close(conn); + if (msg.is_signal (DBUS_INTERFACE_LOCAL,"Disconnected")) { + debug_log ("%p disconnected by local bus", conn); + dbus_connection_close (conn); + + return true; + } - return true; - } - return false; + return false; } DBusDispatchStatus Connection::Private::dispatch_status() { - return dbus_connection_get_dispatch_status(conn); + return dbus_connection_get_dispatch_status (conn); } bool Connection::Private::has_something_to_dispatch() { - return dispatch_status() == DBUS_DISPATCH_DATA_REMAINS; + return dispatch_status() == DBUS_DISPATCH_DATA_REMAINS; } Connection Connection::SystemBus() { - return Connection(new Private(DBUS_BUS_SYSTEM)); + return Connection (new Private (DBUS_BUS_SYSTEM)); } Connection Connection::SessionBus() { - return Connection(new Private(DBUS_BUS_SESSION)); + return Connection (new Private (DBUS_BUS_SESSION)); } Connection Connection::ActivationBus() { - return Connection(new Private(DBUS_BUS_STARTER)); + return Connection (new Private (DBUS_BUS_STARTER)); } -Connection::Connection(const char *address, bool priv) +Connection::Connection (const char *address, bool priv) { - InternalError e; - DBusConnection *conn = priv - ? dbus_connection_open_private(address, e) - : dbus_connection_open(address, e); + InternalError e; + DBusConnection *conn = priv + ? dbus_connection_open_private (address, e) + : dbus_connection_open (address, e); - if (e) throw Error(e); + if (e) throw Error (e); - _pvt = new Private(conn); + _pvt = new Private (conn); - setup(default_dispatcher); + setup (default_dispatcher); - debug_log("connected to %s", address); + debug_log ("connected to %s", address); } -Connection::Connection(Connection::Private *p) -: _pvt(p) +Connection::Connection (Connection::Private *p) + : _pvt (p) { - setup(default_dispatcher); + setup (default_dispatcher); } -Connection::Connection(const Connection &c) -: _pvt(c._pvt) +Connection::Connection (const Connection &c) + : _pvt (c._pvt) { - dbus_connection_ref(_pvt->conn); + dbus_connection_ref (_pvt->conn); } Connection::~Connection() { - dbus_connection_unref(_pvt->conn); + dbus_connection_unref (_pvt->conn); } -Dispatcher *Connection::setup(Dispatcher *dispatcher) +Dispatcher *Connection::setup (Dispatcher *dispatcher) { - debug_log("registering stubs for connection %p", _pvt->conn); + debug_log ("registering stubs for connection %p", _pvt->conn); - if (!dispatcher) dispatcher = default_dispatcher; + if (!dispatcher) dispatcher = default_dispatcher; - if (!dispatcher) throw ErrorFailed("no default dispatcher set for new connection"); + if (!dispatcher) throw ErrorFailed ("no default dispatcher set for new connection"); - Dispatcher *prev = _pvt->dispatcher; + Dispatcher *prev = _pvt->dispatcher; - _pvt->dispatcher = dispatcher; + _pvt->dispatcher = dispatcher; - dispatcher->queue_connection(_pvt.get()); + dispatcher->queue_connection (_pvt.get()); - dbus_connection_set_watch_functions( - _pvt->conn, - Dispatcher::Private::on_add_watch, - Dispatcher::Private::on_rem_watch, - Dispatcher::Private::on_toggle_watch, - dispatcher, - 0 - ); + dbus_connection_set_watch_functions ( + _pvt->conn, + Dispatcher::Private::on_add_watch, + Dispatcher::Private::on_rem_watch, + Dispatcher::Private::on_toggle_watch, + dispatcher, + 0 + ); - dbus_connection_set_timeout_functions( - _pvt->conn, - Dispatcher::Private::on_add_timeout, - Dispatcher::Private::on_rem_timeout, - Dispatcher::Private::on_toggle_timeout, - dispatcher, - 0 - ); + dbus_connection_set_timeout_functions ( + _pvt->conn, + Dispatcher::Private::on_add_timeout, + Dispatcher::Private::on_rem_timeout, + Dispatcher::Private::on_toggle_timeout, + dispatcher, + 0 + ); - return prev; + return prev; } bool Connection::operator == (const Connection &c) const { - return _pvt->conn == c._pvt->conn; + return _pvt->conn == c._pvt->conn; } bool Connection::register_bus() { - InternalError e; + InternalError e; + + bool r = dbus_bus_register (_pvt->conn, e); - bool r = dbus_bus_register(_pvt->conn, e); - - if (e) throw (e); + if (e) throw (e); - return r; + return r; } bool Connection::connected() const { - return dbus_connection_get_is_connected(_pvt->conn); + return dbus_connection_get_is_connected (_pvt->conn); } void Connection::disconnect() { // dbus_connection_disconnect(_pvt->conn); // disappeared in 0.9x - dbus_connection_close(_pvt->conn); + dbus_connection_close (_pvt->conn); } -void Connection::exit_on_disconnect(bool exit) +void Connection::exit_on_disconnect (bool exit) { - dbus_connection_set_exit_on_disconnect(_pvt->conn, exit); + dbus_connection_set_exit_on_disconnect (_pvt->conn, exit); } -bool Connection::unique_name(const char *n) +bool Connection::unique_name (const char *n) { - return dbus_bus_set_unique_name(_pvt->conn, n); + return dbus_bus_set_unique_name (_pvt->conn, n); } const char *Connection::unique_name() const { - return dbus_bus_get_unique_name(_pvt->conn); + return dbus_bus_get_unique_name (_pvt->conn); } void Connection::flush() { - dbus_connection_flush(_pvt->conn); + dbus_connection_flush (_pvt->conn); } -void Connection::add_match(const char *rule) +void Connection::add_match (const char *rule) { - InternalError e; + InternalError e; - dbus_bus_add_match(_pvt->conn, rule, e); + dbus_bus_add_match (_pvt->conn, rule, e); - debug_log("%s: added match rule %s", unique_name(), rule); + debug_log ("%s: added match rule %s", unique_name(), rule); - if (e) throw Error(e); + if (e) throw Error (e); } -void Connection::remove_match(const char *rule) +void Connection::remove_match (const char *rule) { - InternalError e; - - dbus_bus_remove_match(_pvt->conn, rule, e); + InternalError e; + + dbus_bus_remove_match (_pvt->conn, rule, e); - debug_log("%s: removed match rule %s", unique_name(), rule); + debug_log ("%s: removed match rule %s", unique_name(), rule); - if (e) throw Error(e); + if (e) throw Error (e); } -bool Connection::add_filter(MessageSlot &s) +bool Connection::add_filter (MessageSlot &s) { - debug_log("%s: adding filter", unique_name()); - return dbus_connection_add_filter(_pvt->conn, Private::message_filter_stub, &s, NULL); + debug_log ("%s: adding filter", unique_name()); + return dbus_connection_add_filter (_pvt->conn, Private::message_filter_stub, &s, NULL); } -void Connection::remove_filter(MessageSlot &s) +void Connection::remove_filter (MessageSlot &s) { - debug_log("%s: removing filter", unique_name()); - dbus_connection_remove_filter(_pvt->conn, Private::message_filter_stub, &s); + debug_log ("%s: removing filter", unique_name()); + dbus_connection_remove_filter (_pvt->conn, Private::message_filter_stub, &s); } -bool Connection::send(const Message &msg, unsigned int *serial) +bool Connection::send (const Message &msg, unsigned int *serial) { - return dbus_connection_send(_pvt->conn, msg._pvt->msg, serial); + return dbus_connection_send (_pvt->conn, msg._pvt->msg, serial); } -Message Connection::send_blocking(Message &msg, int timeout) +Message Connection::send_blocking (Message &msg, int timeout) { - DBusMessage *reply; - InternalError e; - - reply = dbus_connection_send_with_reply_and_block(_pvt->conn, msg._pvt->msg, timeout, e); + DBusMessage *reply; + InternalError e; + + reply = dbus_connection_send_with_reply_and_block (_pvt->conn, msg._pvt->msg, timeout, e); - if (e) throw Error(e); + if (e) throw Error (e); - return Message(new Message::Private(reply), false); + return Message (new Message::Private (reply), false); } -PendingCall Connection::send_async(Message &msg, int timeout) +PendingCall Connection::send_async (Message &msg, int timeout) { - DBusPendingCall *pending; + DBusPendingCall *pending; + + if (!dbus_connection_send_with_reply (_pvt->conn, msg._pvt->msg, &pending, timeout)) { + throw ErrorNoMemory ("Unable to start asynchronous call"); + } - if (!dbus_connection_send_with_reply(_pvt->conn, msg._pvt->msg, &pending, timeout)) - { - throw ErrorNoMemory("Unable to start asynchronous call"); - } - return PendingCall(new PendingCall::Private(pending)); + return PendingCall (new PendingCall::Private (pending)); } -void Connection::request_name(const char *name, int flags) +void Connection::request_name (const char *name, int flags) { - InternalError e; + InternalError e; - debug_log("%s: registering bus name %s", unique_name(), name); + debug_log ("%s: registering bus name %s", unique_name(), name); - dbus_bus_request_name(_pvt->conn, name, flags, e); //we deliberately don't check return value + dbus_bus_request_name (_pvt->conn, name, flags, e); //we deliberately don't check return value - if (e) throw Error(e); + if (e) throw Error (e); // this->remove_match("destination"); - if (name) - { - _pvt->names.push_back(name); - std::string match = "destination='" + _pvt->names.back() + "'"; - add_match(match.c_str()); - } + if (name) { + _pvt->names.push_back (name); + std::string match = "destination='" + _pvt->names.back() + "'"; + add_match (match.c_str()); + } } -unsigned long Connection::sender_unix_uid(const char *sender) +unsigned long Connection::sender_unix_uid (const char *sender) { InternalError e; - - unsigned long ul = dbus_bus_get_unix_user(_pvt->conn, sender, e); - - if (e) throw Error(e); - + + unsigned long ul = dbus_bus_get_unix_user (_pvt->conn, sender, e); + + if (e) throw Error (e); + return ul; } -bool Connection::has_name(const char *name) -{ - InternalError e; +bool Connection::has_name (const char *name) +{ + InternalError e; - bool b = dbus_bus_name_has_owner(_pvt->conn, name, e); + bool b = dbus_bus_name_has_owner (_pvt->conn, name, e); - if (e) throw Error(e); + if (e) throw Error (e); - return b; + return b; } const std::vector<std::string>& Connection::names() { - return _pvt->names; + return _pvt->names; } -bool Connection::start_service(const char *name, unsigned long flags) +bool Connection::start_service (const char *name, unsigned long flags) { - InternalError e; + InternalError e; + + bool b = dbus_bus_start_service_by_name (_pvt->conn, name, flags, NULL, e); - bool b = dbus_bus_start_service_by_name(_pvt->conn, name, flags, NULL, e); + if (e) throw Error (e); - if (e) throw Error(e); - - return b; + return b; } diff --git a/sflphone-common/libs/dbus-c++/src/debug.cpp b/sflphone-common/libs/dbus-c++/src/debug.cpp index 4f97dae2dd..213a784d05 100644 --- a/sflphone-common/libs/dbus-c++/src/debug.cpp +++ b/sflphone-common/libs/dbus-c++/src/debug.cpp @@ -31,23 +31,22 @@ #include <cstdio> #include <stdlib.h> -static void _debug_log_default(const char *format, ...) +static void _debug_log_default (const char *format, ...) { #ifdef DEBUG - static int debug_env = getenv("DBUSXX_VERBOSE") ? 1 : 0; + static int debug_env = getenv ("DBUSXX_VERBOSE") ? 1 : 0; - if (debug_env) - { - va_list args; - va_start(args, format); + if (debug_env) { + va_list args; + va_start (args, format); - fprintf(stderr, "dbus-c++: "); - vfprintf(stderr, format, args); - fprintf(stderr, "\n"); + fprintf (stderr, "dbus-c++: "); + vfprintf (stderr, format, args); + fprintf (stderr, "\n"); - va_end(args); - } + va_end (args); + } #endif//DEBUG } diff --git a/sflphone-common/libs/dbus-c++/src/dispatcher.cpp b/sflphone-common/libs/dbus-c++/src/dispatcher.cpp index 2da4e86720..e71bae99fd 100644 --- a/sflphone-common/libs/dbus-c++/src/dispatcher.cpp +++ b/sflphone-common/libs/dbus-c++/src/dispatcher.cpp @@ -37,237 +37,237 @@ DBus::Dispatcher *DBus::default_dispatcher = NULL; using namespace DBus; -Timeout::Timeout(Timeout::Internal *i) -: _int(i) +Timeout::Timeout (Timeout::Internal *i) + : _int (i) { - dbus_timeout_set_data((DBusTimeout *)i, this, NULL); + dbus_timeout_set_data ( (DBusTimeout *) i, this, NULL); } int Timeout::interval() const { - return dbus_timeout_get_interval((DBusTimeout *)_int); + return dbus_timeout_get_interval ( (DBusTimeout *) _int); } bool Timeout::enabled() const { - return dbus_timeout_get_enabled((DBusTimeout *)_int); + return dbus_timeout_get_enabled ( (DBusTimeout *) _int); } bool Timeout::handle() { - return dbus_timeout_handle((DBusTimeout *)_int); + return dbus_timeout_handle ( (DBusTimeout *) _int); } /* */ -Watch::Watch(Watch::Internal *i) -: _int(i) +Watch::Watch (Watch::Internal *i) + : _int (i) { - dbus_watch_set_data((DBusWatch *)i, this, NULL); + dbus_watch_set_data ( (DBusWatch *) i, this, NULL); } int Watch::descriptor() const { #if HAVE_WIN32 - return dbus_watch_get_socket((DBusWatch*)_int); + return dbus_watch_get_socket ( (DBusWatch*) _int); #else - return dbus_watch_get_unix_fd((DBusWatch*)_int); + return dbus_watch_get_unix_fd ( (DBusWatch*) _int); #endif } int Watch::flags() const { - return dbus_watch_get_flags((DBusWatch *)_int); + return dbus_watch_get_flags ( (DBusWatch *) _int); } bool Watch::enabled() const { - return dbus_watch_get_enabled((DBusWatch *)_int); + return dbus_watch_get_enabled ( (DBusWatch *) _int); } -bool Watch::handle(int flags) +bool Watch::handle (int flags) { - return dbus_watch_handle((DBusWatch *)_int, flags); + return dbus_watch_handle ( (DBusWatch *) _int, flags); } /* */ -dbus_bool_t Dispatcher::Private::on_add_watch(DBusWatch *watch, void *data) +dbus_bool_t Dispatcher::Private::on_add_watch (DBusWatch *watch, void *data) { - Dispatcher *d = static_cast<Dispatcher *>(data); + Dispatcher *d = static_cast<Dispatcher *> (data); - Watch::Internal *w = reinterpret_cast<Watch::Internal *>(watch); + Watch::Internal *w = reinterpret_cast<Watch::Internal *> (watch); - d->add_watch(w); + d->add_watch (w); - return true; + return true; } -void Dispatcher::Private::on_rem_watch(DBusWatch *watch, void *data) +void Dispatcher::Private::on_rem_watch (DBusWatch *watch, void *data) { - Dispatcher *d = static_cast<Dispatcher *>(data); + Dispatcher *d = static_cast<Dispatcher *> (data); - Watch *w = static_cast<Watch *>(dbus_watch_get_data(watch)); + Watch *w = static_cast<Watch *> (dbus_watch_get_data (watch)); - d->rem_watch(w); + d->rem_watch (w); } -void Dispatcher::Private::on_toggle_watch(DBusWatch *watch, void *data) +void Dispatcher::Private::on_toggle_watch (DBusWatch *watch, void *data) { - Watch *w = static_cast<Watch *>(dbus_watch_get_data(watch)); + Watch *w = static_cast<Watch *> (dbus_watch_get_data (watch)); - w->toggle(); + w->toggle(); } -dbus_bool_t Dispatcher::Private::on_add_timeout(DBusTimeout *timeout, void *data) +dbus_bool_t Dispatcher::Private::on_add_timeout (DBusTimeout *timeout, void *data) { - Dispatcher *d = static_cast<Dispatcher *>(data); + Dispatcher *d = static_cast<Dispatcher *> (data); - Timeout::Internal *t = reinterpret_cast<Timeout::Internal *>(timeout); + Timeout::Internal *t = reinterpret_cast<Timeout::Internal *> (timeout); - d->add_timeout(t); + d->add_timeout (t); - return true; + return true; } -void Dispatcher::Private::on_rem_timeout(DBusTimeout *timeout, void *data) +void Dispatcher::Private::on_rem_timeout (DBusTimeout *timeout, void *data) { - Dispatcher *d = static_cast<Dispatcher *>(data); + Dispatcher *d = static_cast<Dispatcher *> (data); - Timeout *t = static_cast<Timeout *>(dbus_timeout_get_data(timeout)); + Timeout *t = static_cast<Timeout *> (dbus_timeout_get_data (timeout)); - d->rem_timeout(t); + d->rem_timeout (t); } -void Dispatcher::Private::on_toggle_timeout(DBusTimeout *timeout, void *data) +void Dispatcher::Private::on_toggle_timeout (DBusTimeout *timeout, void *data) { - Timeout *t = static_cast<Timeout *>(dbus_timeout_get_data(timeout)); + Timeout *t = static_cast<Timeout *> (dbus_timeout_get_data (timeout)); - t->toggle(); + t->toggle(); } -void Dispatcher::queue_connection(Connection::Private *cp) +void Dispatcher::queue_connection (Connection::Private *cp) { - _mutex_p.lock(); - _pending_queue.push_back(cp); - _mutex_p.unlock(); + _mutex_p.lock(); + _pending_queue.push_back (cp); + _mutex_p.unlock(); } bool Dispatcher::has_something_to_dispatch() { - _mutex_p.lock(); - bool has_something = false; - for(Connection::PrivatePList::iterator it = _pending_queue.begin(); - it != _pending_queue.end() && !has_something; - ++it) - { - has_something = (*it)->has_something_to_dispatch(); - } - - _mutex_p.unlock(); - return has_something; + _mutex_p.lock(); + bool has_something = false; + + for (Connection::PrivatePList::iterator it = _pending_queue.begin(); + it != _pending_queue.end() && !has_something; + ++it) { + has_something = (*it)->has_something_to_dispatch(); + } + + _mutex_p.unlock(); + + return has_something; } void Dispatcher::dispatch_pending() { - _mutex_p.lock(); + _mutex_p.lock(); + + // SEEME: dbus-glib is dispatching only one message at a time to not starve the loop/other things... + + while (_pending_queue.size() > 0) { + Connection::PrivatePList::iterator i, j; + + i = _pending_queue.begin(); - // SEEME: dbus-glib is dispatching only one message at a time to not starve the loop/other things... + while (i != _pending_queue.end()) { + j = i; - while (_pending_queue.size() > 0) - { - Connection::PrivatePList::iterator i, j; - - i = _pending_queue.begin(); + ++j; - while (i != _pending_queue.end()) - { - j = i; - - ++j; + if ( (*i)->do_dispatch()) + _pending_queue.erase (i); - if ((*i)->do_dispatch()) - _pending_queue.erase(i); + i = j; + } + } - i = j; - } - } - _mutex_p.unlock(); + _mutex_p.unlock(); } void DBus::_init_threading() { #ifdef DBUS_HAS_THREADS_INIT_DEFAULT - dbus_threads_init_default(); + dbus_threads_init_default(); #else - debug_log("Thread support is not enabled! Your D-Bus version is too old!"); + debug_log ("Thread support is not enabled! Your D-Bus version is too old!"); #endif//DBUS_HAS_THREADS_INIT_DEFAULT } -void DBus::_init_threading( - MutexNewFn m1, - MutexFreeFn m2, - MutexLockFn m3, - MutexUnlockFn m4, - CondVarNewFn c1, - CondVarFreeFn c2, - CondVarWaitFn c3, - CondVarWaitTimeoutFn c4, - CondVarWakeOneFn c5, - CondVarWakeAllFn c6 +void DBus::_init_threading ( + MutexNewFn m1, + MutexFreeFn m2, + MutexLockFn m3, + MutexUnlockFn m4, + CondVarNewFn c1, + CondVarFreeFn c2, + CondVarWaitFn c3, + CondVarWaitTimeoutFn c4, + CondVarWakeOneFn c5, + CondVarWakeAllFn c6 ) { #ifndef DBUS_HAS_RECURSIVE_MUTEX - DBusThreadFunctions functions = { - DBUS_THREAD_FUNCTIONS_MUTEX_NEW_MASK | - DBUS_THREAD_FUNCTIONS_MUTEX_FREE_MASK | - DBUS_THREAD_FUNCTIONS_MUTEX_LOCK_MASK | - DBUS_THREAD_FUNCTIONS_MUTEX_UNLOCK_MASK | - DBUS_THREAD_FUNCTIONS_CONDVAR_NEW_MASK | - DBUS_THREAD_FUNCTIONS_CONDVAR_FREE_MASK | - DBUS_THREAD_FUNCTIONS_CONDVAR_WAIT_MASK | - DBUS_THREAD_FUNCTIONS_CONDVAR_WAIT_TIMEOUT_MASK | - DBUS_THREAD_FUNCTIONS_CONDVAR_WAKE_ONE_MASK| - DBUS_THREAD_FUNCTIONS_CONDVAR_WAKE_ALL_MASK, - (DBusMutexNewFunction) m1, - (DBusMutexFreeFunction) m2, - (DBusMutexLockFunction) m3, - (DBusMutexUnlockFunction) m4, - (DBusCondVarNewFunction) c1, - (DBusCondVarFreeFunction) c2, - (DBusCondVarWaitFunction) c3, - (DBusCondVarWaitTimeoutFunction) c4, - (DBusCondVarWakeOneFunction) c5, - (DBusCondVarWakeAllFunction) c6 - }; + DBusThreadFunctions functions = { + DBUS_THREAD_FUNCTIONS_MUTEX_NEW_MASK | + DBUS_THREAD_FUNCTIONS_MUTEX_FREE_MASK | + DBUS_THREAD_FUNCTIONS_MUTEX_LOCK_MASK | + DBUS_THREAD_FUNCTIONS_MUTEX_UNLOCK_MASK | + DBUS_THREAD_FUNCTIONS_CONDVAR_NEW_MASK | + DBUS_THREAD_FUNCTIONS_CONDVAR_FREE_MASK | + DBUS_THREAD_FUNCTIONS_CONDVAR_WAIT_MASK | + DBUS_THREAD_FUNCTIONS_CONDVAR_WAIT_TIMEOUT_MASK | + DBUS_THREAD_FUNCTIONS_CONDVAR_WAKE_ONE_MASK| + DBUS_THREAD_FUNCTIONS_CONDVAR_WAKE_ALL_MASK, + (DBusMutexNewFunction) m1, + (DBusMutexFreeFunction) m2, + (DBusMutexLockFunction) m3, + (DBusMutexUnlockFunction) m4, + (DBusCondVarNewFunction) c1, + (DBusCondVarFreeFunction) c2, + (DBusCondVarWaitFunction) c3, + (DBusCondVarWaitTimeoutFunction) c4, + (DBusCondVarWakeOneFunction) c5, + (DBusCondVarWakeAllFunction) c6 + }; #else - DBusThreadFunctions functions = { - DBUS_THREAD_FUNCTIONS_RECURSIVE_MUTEX_NEW_MASK | - DBUS_THREAD_FUNCTIONS_RECURSIVE_MUTEX_FREE_MASK | - DBUS_THREAD_FUNCTIONS_RECURSIVE_MUTEX_LOCK_MASK | - DBUS_THREAD_FUNCTIONS_RECURSIVE_MUTEX_UNLOCK_MASK | - DBUS_THREAD_FUNCTIONS_CONDVAR_NEW_MASK | - DBUS_THREAD_FUNCTIONS_CONDVAR_FREE_MASK | - DBUS_THREAD_FUNCTIONS_CONDVAR_WAIT_MASK | - DBUS_THREAD_FUNCTIONS_CONDVAR_WAIT_TIMEOUT_MASK | - DBUS_THREAD_FUNCTIONS_CONDVAR_WAKE_ONE_MASK| - DBUS_THREAD_FUNCTIONS_CONDVAR_WAKE_ALL_MASK, - 0, 0, 0, 0, - (DBusCondVarNewFunction) c1, - (DBusCondVarFreeFunction) c2, - (DBusCondVarWaitFunction) c3, - (DBusCondVarWaitTimeoutFunction) c4, - (DBusCondVarWakeOneFunction) c5, - (DBusCondVarWakeAllFunction) c6, - (DBusRecursiveMutexNewFunction) m1, - (DBusRecursiveMutexFreeFunction) m2, - (DBusRecursiveMutexLockFunction) m3, - (DBusRecursiveMutexUnlockFunction) m4 - }; + DBusThreadFunctions functions = { + DBUS_THREAD_FUNCTIONS_RECURSIVE_MUTEX_NEW_MASK | + DBUS_THREAD_FUNCTIONS_RECURSIVE_MUTEX_FREE_MASK | + DBUS_THREAD_FUNCTIONS_RECURSIVE_MUTEX_LOCK_MASK | + DBUS_THREAD_FUNCTIONS_RECURSIVE_MUTEX_UNLOCK_MASK | + DBUS_THREAD_FUNCTIONS_CONDVAR_NEW_MASK | + DBUS_THREAD_FUNCTIONS_CONDVAR_FREE_MASK | + DBUS_THREAD_FUNCTIONS_CONDVAR_WAIT_MASK | + DBUS_THREAD_FUNCTIONS_CONDVAR_WAIT_TIMEOUT_MASK | + DBUS_THREAD_FUNCTIONS_CONDVAR_WAKE_ONE_MASK| + DBUS_THREAD_FUNCTIONS_CONDVAR_WAKE_ALL_MASK, + 0, 0, 0, 0, + (DBusCondVarNewFunction) c1, + (DBusCondVarFreeFunction) c2, + (DBusCondVarWaitFunction) c3, + (DBusCondVarWaitTimeoutFunction) c4, + (DBusCondVarWakeOneFunction) c5, + (DBusCondVarWakeAllFunction) c6, + (DBusRecursiveMutexNewFunction) m1, + (DBusRecursiveMutexFreeFunction) m2, + (DBusRecursiveMutexLockFunction) m3, + (DBusRecursiveMutexUnlockFunction) m4 + }; #endif//DBUS_HAS_RECURSIVE_MUTEX - dbus_threads_init(&functions); + dbus_threads_init (&functions); } diff --git a/sflphone-common/libs/dbus-c++/src/ecore-integration.cpp b/sflphone-common/libs/dbus-c++/src/ecore-integration.cpp index 2a5ef68970..d18d4b1136 100644 --- a/sflphone-common/libs/dbus-c++/src/ecore-integration.cpp +++ b/sflphone-common/libs/dbus-c++/src/ecore-integration.cpp @@ -31,183 +31,183 @@ using namespace DBus; -Ecore::BusTimeout::BusTimeout( Timeout::Internal* ti) -: Timeout(ti) +Ecore::BusTimeout::BusTimeout (Timeout::Internal* ti) + : Timeout (ti) { - _enable(); + _enable(); } Ecore::BusTimeout::~BusTimeout() { - _disable(); + _disable(); } void Ecore::BusTimeout::toggle() { - debug_log("ecore: timeout %p toggled (%s)", this, Timeout::enabled() ? "on":"off"); + debug_log ("ecore: timeout %p toggled (%s)", this, Timeout::enabled() ? "on":"off"); - if(Timeout::enabled()) _enable(); - else _disable(); + if (Timeout::enabled()) _enable(); + else _disable(); } -int Ecore::BusTimeout::timeout_handler( void *data ) +int Ecore::BusTimeout::timeout_handler (void *data) { - Ecore::BusTimeout* t = reinterpret_cast<Ecore::BusTimeout*>(data); + Ecore::BusTimeout* t = reinterpret_cast<Ecore::BusTimeout*> (data); - debug_log("Ecore::BusTimeout::timeout_handler( void *data )"); + debug_log ("Ecore::BusTimeout::timeout_handler( void *data )"); - t->handle(); + t->handle(); - return 1; // 1 -> reshedule in ecore for next timer interval + return 1; // 1 -> reshedule in ecore for next timer interval } void Ecore::BusTimeout::_enable() { - debug_log("Ecore::BusTimeout::_enable()"); - - _etimer = ecore_timer_add (((double)Timeout::interval())/1000, timeout_handler, this); + debug_log ("Ecore::BusTimeout::_enable()"); + + _etimer = ecore_timer_add ( ( (double) Timeout::interval()) /1000, timeout_handler, this); } void Ecore::BusTimeout::_disable() { - debug_log("Ecore::BusTimeout::_disable()"); + debug_log ("Ecore::BusTimeout::_disable()"); - ecore_timer_del (_etimer); + ecore_timer_del (_etimer); } -static bool watch_prepare( int *timeout ) +static bool watch_prepare (int *timeout) { - debug_log("ecore: watch_prepare"); + debug_log ("ecore: watch_prepare"); - *timeout = -1; - return false; + *timeout = -1; + return false; } -static bool watch_check( ) +static bool watch_check() { - debug_log("ecore: watch_check"); + debug_log ("ecore: watch_check"); - return true; + return true; } -static bool watch_dispatch( void *data ) +static bool watch_dispatch (void *data) { - debug_log("ecore: watch_dispatch"); + debug_log ("ecore: watch_dispatch"); - bool cb = true; - DBus::default_dispatcher->dispatch_pending(); //TODO: won't work in case of multiple dispatchers - return cb; + bool cb = true; + DBus::default_dispatcher->dispatch_pending(); //TODO: won't work in case of multiple dispatchers + return cb; } -Ecore::BusWatch::BusWatch( Watch::Internal* wi) -: Watch(wi) +Ecore::BusWatch::BusWatch (Watch::Internal* wi) + : Watch (wi) { - _enable(); + _enable(); } Ecore::BusWatch::~BusWatch() { - _disable(); + _disable(); } void Ecore::BusWatch::toggle() { - debug_log("ecore: watch %p toggled (%s)", this, Watch::enabled() ? "on":"off"); + debug_log ("ecore: watch %p toggled (%s)", this, Watch::enabled() ? "on":"off"); - if(Watch::enabled()) _enable(); - else _disable(); + if (Watch::enabled()) _enable(); + else _disable(); } -int Ecore::BusWatch::watch_handler_read( void *data, Ecore_Fd_Handler *fdh ) +int Ecore::BusWatch::watch_handler_read (void *data, Ecore_Fd_Handler *fdh) { - Ecore::BusWatch* w = reinterpret_cast<Ecore::BusWatch*>(data); + Ecore::BusWatch* w = reinterpret_cast<Ecore::BusWatch*> (data); + + debug_log ("ecore: watch_handler_read"); + + int flags = DBUS_WATCH_READABLE; - debug_log("ecore: watch_handler_read"); - - int flags = DBUS_WATCH_READABLE; - - watch_dispatch(NULL); + watch_dispatch (NULL); - w->handle(flags); + w->handle (flags); - return 1; + return 1; } -int Ecore::BusWatch::watch_handler_error( void *data, Ecore_Fd_Handler *fdh ) +int Ecore::BusWatch::watch_handler_error (void *data, Ecore_Fd_Handler *fdh) { - Ecore::BusWatch* w = reinterpret_cast<Ecore::BusWatch*>(data); + Ecore::BusWatch* w = reinterpret_cast<Ecore::BusWatch*> (data); - debug_log("ecore: watch_handler_error"); + debug_log ("ecore: watch_handler_error"); - int flags = DBUS_WATCH_ERROR; - - watch_dispatch(NULL); + int flags = DBUS_WATCH_ERROR; - return 1; + watch_dispatch (NULL); + + return 1; } void Ecore::BusWatch::_enable() { - debug_log("Ecore::BusWatch::_enable()"); - - int flags = Watch::flags(); - - fd_handler_read = ecore_main_fd_handler_add (Watch::descriptor(), - ECORE_FD_READ, - watch_handler_read, - this, - NULL, NULL); - - ecore_main_fd_handler_active_set(fd_handler_read, ECORE_FD_READ); - - fd_handler_error = ecore_main_fd_handler_add (Watch::descriptor(), - ECORE_FD_ERROR, - watch_handler_error, - this, - NULL, NULL); - - ecore_main_fd_handler_active_set(fd_handler_error, ECORE_FD_ERROR); + debug_log ("Ecore::BusWatch::_enable()"); + + int flags = Watch::flags(); + + fd_handler_read = ecore_main_fd_handler_add (Watch::descriptor(), + ECORE_FD_READ, + watch_handler_read, + this, + NULL, NULL); + + ecore_main_fd_handler_active_set (fd_handler_read, ECORE_FD_READ); + + fd_handler_error = ecore_main_fd_handler_add (Watch::descriptor(), + ECORE_FD_ERROR, + watch_handler_error, + this, + NULL, NULL); + + ecore_main_fd_handler_active_set (fd_handler_error, ECORE_FD_ERROR); } void Ecore::BusWatch::_disable() { - ecore_main_fd_handler_del (fd_handler_read); - ecore_main_fd_handler_del (fd_handler_error); + ecore_main_fd_handler_del (fd_handler_read); + ecore_main_fd_handler_del (fd_handler_error); } -void Ecore::BusDispatcher::attach( ) +void Ecore::BusDispatcher::attach() { } -Timeout* Ecore::BusDispatcher::add_timeout( Timeout::Internal* wi ) +Timeout* Ecore::BusDispatcher::add_timeout (Timeout::Internal* wi) { - Timeout* t = new Ecore::BusTimeout( wi ); + Timeout* t = new Ecore::BusTimeout (wi); - debug_log("ecore: added timeout %p (%s)", t, t->enabled() ? "on":"off"); + debug_log ("ecore: added timeout %p (%s)", t, t->enabled() ? "on":"off"); - return t; + return t; } -void Ecore::BusDispatcher::rem_timeout( Timeout* t ) +void Ecore::BusDispatcher::rem_timeout (Timeout* t) { - debug_log("ecore: removed timeout %p", t); + debug_log ("ecore: removed timeout %p", t); - delete t; + delete t; } -Watch* Ecore::BusDispatcher::add_watch( Watch::Internal* wi ) +Watch* Ecore::BusDispatcher::add_watch (Watch::Internal* wi) { - Watch* w = new Ecore::BusWatch(wi); + Watch* w = new Ecore::BusWatch (wi); - debug_log("ecore: added watch %p (%s) fd=%d flags=%d", - w, w->enabled() ? "on":"off", w->descriptor(), w->flags() - ); - return w; + debug_log ("ecore: added watch %p (%s) fd=%d flags=%d", + w, w->enabled() ? "on":"off", w->descriptor(), w->flags() + ); + return w; } -void Ecore::BusDispatcher::rem_watch( Watch* w ) +void Ecore::BusDispatcher::rem_watch (Watch* w) { - debug_log("ecore: removed watch %p", w); + debug_log ("ecore: removed watch %p", w); - delete w; + delete w; } diff --git a/sflphone-common/libs/dbus-c++/src/error.cpp b/sflphone-common/libs/dbus-c++/src/error.cpp index 840365bad4..89d91d1f39 100644 --- a/sflphone-common/libs/dbus-c++/src/error.cpp +++ b/sflphone-common/libs/dbus-c++/src/error.cpp @@ -39,23 +39,23 @@ using namespace DBus; */ Error::Error() -: _int(new InternalError) + : _int (new InternalError) {} -Error::Error(InternalError &i) -: _int(new InternalError(i)) +Error::Error (InternalError &i) + : _int (new InternalError (i)) {} -Error::Error(const char *name, const char *message) -: _int(new InternalError) +Error::Error (const char *name, const char *message) + : _int (new InternalError) { - set(name, message); + set (name, message); } -Error::Error(Message &m) -: _int(new InternalError) +Error::Error (Message &m) + : _int (new InternalError) { - dbus_set_error_from_message(&(_int->error), m._pvt->msg); + dbus_set_error_from_message (& (_int->error), m._pvt->msg); } Error::~Error() throw() @@ -64,26 +64,26 @@ Error::~Error() throw() const char *Error::name() const { - return _int->error.name; + return _int->error.name; } const char *Error::message() const { - return _int->error.message; + return _int->error.message; } bool Error::is_set() const { - return *(_int); + return * (_int); } -void Error::set(const char *name, const char *message) +void Error::set (const char *name, const char *message) { - dbus_set_error_const(&(_int->error), name, message); + dbus_set_error_const (& (_int->error), name, message); } const char *Error::what() const throw() { - return _int->error.message; + return _int->error.message; } diff --git a/sflphone-common/libs/dbus-c++/src/eventloop-integration.cpp b/sflphone-common/libs/dbus-c++/src/eventloop-integration.cpp index ed0cc23883..ec82dd22bd 100644 --- a/sflphone-common/libs/dbus-c++/src/eventloop-integration.cpp +++ b/sflphone-common/libs/dbus-c++/src/eventloop-integration.cpp @@ -34,133 +34,137 @@ using namespace DBus; -BusTimeout::BusTimeout(Timeout::Internal *ti, BusDispatcher *bd) -: Timeout(ti), DefaultTimeout(Timeout::interval(), true, bd) +BusTimeout::BusTimeout (Timeout::Internal *ti, BusDispatcher *bd) + : Timeout (ti), DefaultTimeout (Timeout::interval(), true, bd) { - DefaultTimeout::enabled(Timeout::enabled()); + DefaultTimeout::enabled (Timeout::enabled()); } void BusTimeout::toggle() { - debug_log("timeout %p toggled (%s)", this, Timeout::enabled() ? "on":"off"); + debug_log ("timeout %p toggled (%s)", this, Timeout::enabled() ? "on":"off"); - DefaultTimeout::enabled(Timeout::enabled()); + DefaultTimeout::enabled (Timeout::enabled()); } -BusWatch::BusWatch(Watch::Internal *wi, BusDispatcher *bd) -: Watch(wi), DefaultWatch(Watch::descriptor(), 0, bd) +BusWatch::BusWatch (Watch::Internal *wi, BusDispatcher *bd) + : Watch (wi), DefaultWatch (Watch::descriptor(), 0, bd) { - int flags = POLLHUP | POLLERR; + int flags = POLLHUP | POLLERR; - if (Watch::flags() & DBUS_WATCH_READABLE) - flags |= POLLIN; - if (Watch::flags() & DBUS_WATCH_WRITABLE) - flags |= POLLOUT; + if (Watch::flags() & DBUS_WATCH_READABLE) + flags |= POLLIN; - DefaultWatch::flags(flags); - DefaultWatch::enabled(Watch::enabled()); + if (Watch::flags() & DBUS_WATCH_WRITABLE) + flags |= POLLOUT; + + DefaultWatch::flags (flags); + + DefaultWatch::enabled (Watch::enabled()); } void BusWatch::toggle() { - debug_log("watch %p toggled (%s)", this, Watch::enabled() ? "on":"off"); + debug_log ("watch %p toggled (%s)", this, Watch::enabled() ? "on":"off"); - DefaultWatch::enabled(Watch::enabled()); + DefaultWatch::enabled (Watch::enabled()); } void BusDispatcher::enter() { - debug_log("entering dispatcher %p", this); + debug_log ("entering dispatcher %p", this); - _running = true; + _running = true; - while (_running) - { - do_iteration(); - } + while (_running) { + do_iteration(); + } - debug_log("leaving dispatcher %p", this); + debug_log ("leaving dispatcher %p", this); } void BusDispatcher::leave() { - _running = false; + _running = false; } void BusDispatcher::do_iteration() { - dispatch_pending(); - dispatch(); + dispatch_pending(); + dispatch(); } -Timeout *BusDispatcher::add_timeout(Timeout::Internal *ti) +Timeout *BusDispatcher::add_timeout (Timeout::Internal *ti) { - BusTimeout *bt = new BusTimeout(ti, this); + BusTimeout *bt = new BusTimeout (ti, this); - bt->expired = new Callback<BusDispatcher, void, DefaultTimeout &>(this, &BusDispatcher::timeout_expired); - bt->data(bt); + bt->expired = new Callback<BusDispatcher, void, DefaultTimeout &> (this, &BusDispatcher::timeout_expired); + bt->data (bt); - debug_log("added timeout %p (%s) interval=%d", - bt, ((Timeout *)bt)->enabled() ? "on":"off", ((Timeout *)bt)->interval()); + debug_log ("added timeout %p (%s) interval=%d", + bt, ( (Timeout *) bt)->enabled() ? "on":"off", ( (Timeout *) bt)->interval()); - return bt; + return bt; } -void BusDispatcher::rem_timeout(Timeout *t) +void BusDispatcher::rem_timeout (Timeout *t) { - debug_log("removed timeout %p", t); + debug_log ("removed timeout %p", t); - delete t; + delete t; } -Watch *BusDispatcher::add_watch(Watch::Internal *wi) +Watch *BusDispatcher::add_watch (Watch::Internal *wi) { - BusWatch *bw = new BusWatch(wi, this); + BusWatch *bw = new BusWatch (wi, this); - bw->ready = new Callback<BusDispatcher, void, DefaultWatch &>(this, &BusDispatcher::watch_ready); - bw->data(bw); + bw->ready = new Callback<BusDispatcher, void, DefaultWatch &> (this, &BusDispatcher::watch_ready); + bw->data (bw); - debug_log("added watch %p (%s) fd=%d flags=%d", - bw, ((Watch *)bw)->enabled() ? "on":"off", ((Watch *)bw)->descriptor(), ((Watch *)bw)->flags()); + debug_log ("added watch %p (%s) fd=%d flags=%d", + bw, ( (Watch *) bw)->enabled() ? "on":"off", ( (Watch *) bw)->descriptor(), ( (Watch *) bw)->flags()); - return bw; + return bw; } -void BusDispatcher::rem_watch(Watch *w) +void BusDispatcher::rem_watch (Watch *w) { - debug_log("removed watch %p", w); + debug_log ("removed watch %p", w); - delete w; + delete w; } -void BusDispatcher::timeout_expired(DefaultTimeout &et) +void BusDispatcher::timeout_expired (DefaultTimeout &et) { - debug_log("timeout %p expired", &et); + debug_log ("timeout %p expired", &et); - BusTimeout *timeout = reinterpret_cast<BusTimeout *>(et.data()); + BusTimeout *timeout = reinterpret_cast<BusTimeout *> (et.data()); - timeout->handle(); + timeout->handle(); } -void BusDispatcher::watch_ready(DefaultWatch &ew) +void BusDispatcher::watch_ready (DefaultWatch &ew) { - BusWatch *watch = reinterpret_cast<BusWatch *>(ew.data()); + BusWatch *watch = reinterpret_cast<BusWatch *> (ew.data()); + + debug_log ("watch %p ready, flags=%d state=%d", + watch, ( (Watch *) watch)->flags(), watch->state() + ); + + int flags = 0; + + if (watch->state() & POLLIN) + flags |= DBUS_WATCH_READABLE; - debug_log("watch %p ready, flags=%d state=%d", - watch, ((Watch *)watch)->flags(), watch->state() - ); + if (watch->state() & POLLOUT) + flags |= DBUS_WATCH_WRITABLE; - int flags = 0; + if (watch->state() & POLLHUP) + flags |= DBUS_WATCH_HANGUP; - if (watch->state() & POLLIN) - flags |= DBUS_WATCH_READABLE; - if (watch->state() & POLLOUT) - flags |= DBUS_WATCH_WRITABLE; - if (watch->state() & POLLHUP) - flags |= DBUS_WATCH_HANGUP; - if (watch->state() & POLLERR) - flags |= DBUS_WATCH_ERROR; + if (watch->state() & POLLERR) + flags |= DBUS_WATCH_ERROR; - watch->handle(flags); + watch->handle (flags); } diff --git a/sflphone-common/libs/dbus-c++/src/eventloop.cpp b/sflphone-common/libs/dbus-c++/src/eventloop.cpp index 7fac42cf89..656885aa10 100644 --- a/sflphone-common/libs/dbus-c++/src/eventloop.cpp +++ b/sflphone-common/libs/dbus-c++/src/eventloop.cpp @@ -35,64 +35,64 @@ using namespace DBus; -static double millis(timeval tv) +static double millis (timeval tv) { - return (tv.tv_sec *1000.0 + tv.tv_usec/1000.0); + return (tv.tv_sec *1000.0 + tv.tv_usec/1000.0); } - -DefaultTimeout::DefaultTimeout(int interval, bool repeat, DefaultMainLoop *ed) -: _enabled(true), _interval(interval), _repeat(repeat), _expiration(0), _data(0), _disp(ed) + +DefaultTimeout::DefaultTimeout (int interval, bool repeat, DefaultMainLoop *ed) + : _enabled (true), _interval (interval), _repeat (repeat), _expiration (0), _data (0), _disp (ed) { - timeval now; - gettimeofday(&now, NULL); + timeval now; + gettimeofday (&now, NULL); - _expiration = millis(now) + interval; + _expiration = millis (now) + interval; - _disp->_mutex_t.lock(); - _disp->_timeouts.push_back(this); - _disp->_mutex_t.unlock(); + _disp->_mutex_t.lock(); + _disp->_timeouts.push_back (this); + _disp->_mutex_t.unlock(); } DefaultTimeout::~DefaultTimeout() { - _disp->_mutex_t.lock(); - _disp->_timeouts.remove(this); - _disp->_mutex_t.unlock(); + _disp->_mutex_t.lock(); + _disp->_timeouts.remove (this); + _disp->_mutex_t.unlock(); } -DefaultWatch::DefaultWatch(int fd, int flags, DefaultMainLoop *ed) -: _enabled(true), _fd(fd), _flags(flags), _state(0), _data(0), _disp(ed) +DefaultWatch::DefaultWatch (int fd, int flags, DefaultMainLoop *ed) + : _enabled (true), _fd (fd), _flags (flags), _state (0), _data (0), _disp (ed) { - _disp->_mutex_w.lock(); - _disp->_watches.push_back(this); - _disp->_mutex_w.unlock(); + _disp->_mutex_w.lock(); + _disp->_watches.push_back (this); + _disp->_mutex_w.unlock(); } DefaultWatch::~DefaultWatch() { - _disp->_mutex_w.lock(); - _disp->_watches.remove(this); - _disp->_mutex_w.unlock(); + _disp->_mutex_w.lock(); + _disp->_watches.remove (this); + _disp->_mutex_w.unlock(); } DefaultMutex::DefaultMutex() { - pthread_mutex_init(&_mutex, NULL); + pthread_mutex_init (&_mutex, NULL); } DefaultMutex::~DefaultMutex() { - pthread_mutex_destroy(&_mutex); + pthread_mutex_destroy (&_mutex); } void DefaultMutex::lock() { - pthread_mutex_lock(&_mutex); + pthread_mutex_lock (&_mutex); } void DefaultMutex::unlock() { - pthread_mutex_unlock(&_mutex); + pthread_mutex_unlock (&_mutex); } DefaultMainLoop::DefaultMainLoop() @@ -101,130 +101,124 @@ DefaultMainLoop::DefaultMainLoop() DefaultMainLoop::~DefaultMainLoop() { - _mutex_w.lock(); - - DefaultWatches::iterator wi = _watches.begin(); - while (wi != _watches.end()) - { - DefaultWatches::iterator wmp = wi; - ++wmp; - _mutex_w.unlock(); - delete (*wi); - _mutex_w.lock(); - wi = wmp; - } - _mutex_w.unlock(); - - _mutex_t.lock(); - - DefaultTimeouts::iterator ti = _timeouts.begin(); - while (ti != _timeouts.end()) - { - DefaultTimeouts::iterator tmp = ti; - ++tmp; - _mutex_t.unlock(); - delete (*ti); - _mutex_t.lock(); - ti = tmp; - } - _mutex_t.unlock(); + _mutex_w.lock(); + + DefaultWatches::iterator wi = _watches.begin(); + + while (wi != _watches.end()) { + DefaultWatches::iterator wmp = wi; + ++wmp; + _mutex_w.unlock(); + delete (*wi); + _mutex_w.lock(); + wi = wmp; + } + + _mutex_w.unlock(); + + _mutex_t.lock(); + + DefaultTimeouts::iterator ti = _timeouts.begin(); + + while (ti != _timeouts.end()) { + DefaultTimeouts::iterator tmp = ti; + ++tmp; + _mutex_t.unlock(); + delete (*ti); + _mutex_t.lock(); + ti = tmp; + } + + _mutex_t.unlock(); } void DefaultMainLoop::dispatch() { - _mutex_w.lock(); + _mutex_w.lock(); + + int nfd = _watches.size(); + + pollfd fds[nfd]; - int nfd = _watches.size(); + DefaultWatches::iterator wi = _watches.begin(); - pollfd fds[nfd]; + for (nfd = 0; wi != _watches.end(); ++wi) { + if ( (*wi)->enabled()) { + fds[nfd].fd = (*wi)->descriptor(); + fds[nfd].events = (*wi)->flags(); + fds[nfd].revents = 0; - DefaultWatches::iterator wi = _watches.begin(); + ++nfd; + } + } - for (nfd = 0; wi != _watches.end(); ++wi) - { - if ((*wi)->enabled()) - { - fds[nfd].fd = (*wi)->descriptor(); - fds[nfd].events = (*wi)->flags(); - fds[nfd].revents = 0; + _mutex_w.unlock(); - ++nfd; - } - } - _mutex_w.unlock(); + int wait_min = 10000; - int wait_min = 10000; + DefaultTimeouts::iterator ti; - DefaultTimeouts::iterator ti; + _mutex_t.lock(); - _mutex_t.lock(); + for (ti = _timeouts.begin(); ti != _timeouts.end(); ++ti) { + if ( (*ti)->enabled() && (*ti)->interval() < wait_min) + wait_min = (*ti)->interval(); + } - for (ti = _timeouts.begin(); ti != _timeouts.end(); ++ti) - { - if ((*ti)->enabled() && (*ti)->interval() < wait_min) - wait_min = (*ti)->interval(); - } + _mutex_t.unlock(); - _mutex_t.unlock(); + poll (fds, nfd, wait_min); - poll(fds, nfd, wait_min); + timeval now; + gettimeofday (&now, NULL); - timeval now; - gettimeofday(&now, NULL); + double now_millis = millis (now); - double now_millis = millis(now); + _mutex_t.lock(); - _mutex_t.lock(); + ti = _timeouts.begin(); - ti = _timeouts.begin(); + while (ti != _timeouts.end()) { + DefaultTimeouts::iterator tmp = ti; + ++tmp; - while (ti != _timeouts.end()) - { - DefaultTimeouts::iterator tmp = ti; - ++tmp; + if ( (*ti)->enabled() && now_millis >= (*ti)->_expiration) { + (*ti)->expired (* (*ti)); - if ((*ti)->enabled() && now_millis >= (*ti)->_expiration) - { - (*ti)->expired(*(*ti)); + if ( (*ti)->_repeat) { + (*ti)->_expiration = now_millis + (*ti)->_interval; + } - if ((*ti)->_repeat) - { - (*ti)->_expiration = now_millis + (*ti)->_interval; - } + } - } + ti = tmp; + } - ti = tmp; - } + _mutex_t.unlock(); - _mutex_t.unlock(); + _mutex_w.lock(); - _mutex_w.lock(); + for (int j = 0; j < nfd; ++j) { + DefaultWatches::iterator wi; - for (int j = 0; j < nfd; ++j) - { - DefaultWatches::iterator wi; + for (wi = _watches.begin(); wi != _watches.end();) { + DefaultWatches::iterator tmp = wi; + ++tmp; - for (wi = _watches.begin(); wi != _watches.end();) - { - DefaultWatches::iterator tmp = wi; - ++tmp; + if ( (*wi)->enabled() && (*wi)->_fd == fds[j].fd) { + if (fds[j].revents) { + (*wi)->_state = fds[j].revents; - if ((*wi)->enabled() && (*wi)->_fd == fds[j].fd) - { - if (fds[j].revents) - { - (*wi)->_state = fds[j].revents; + (*wi)->ready (* (*wi)); - (*wi)->ready(*(*wi)); + fds[j].revents = 0; + } + } - fds[j].revents = 0; - } - } + wi = tmp; + } + } - wi = tmp; - } - } - _mutex_w.unlock(); + _mutex_w.unlock(); } diff --git a/sflphone-common/libs/dbus-c++/src/glib-integration.cpp b/sflphone-common/libs/dbus-c++/src/glib-integration.cpp index 491c950129..1739670bfc 100644 --- a/sflphone-common/libs/dbus-c++/src/glib-integration.cpp +++ b/sflphone-common/libs/dbus-c++/src/glib-integration.cpp @@ -30,170 +30,190 @@ using namespace DBus; -Glib::BusTimeout::BusTimeout(Timeout::Internal *ti, GMainContext *ctx, int priority) -: Timeout(ti), _ctx(ctx), _priority(priority), _source(NULL) +Glib::BusTimeout::BusTimeout (Timeout::Internal *ti, GMainContext *ctx, int priority) + : Timeout (ti), _ctx (ctx), _priority (priority), _source (NULL) { - if (Timeout::enabled()) - _enable(); + if (Timeout::enabled()) + _enable(); } Glib::BusTimeout::~BusTimeout() { - _disable(); + _disable(); } void Glib::BusTimeout::toggle() { - debug_log("glib: timeout %p toggled (%s)", this, Timeout::enabled() ? "on":"off"); + debug_log ("glib: timeout %p toggled (%s)", this, Timeout::enabled() ? "on":"off"); - if (Timeout::enabled()) _enable(); - else _disable(); + if (Timeout::enabled()) _enable(); + else _disable(); } -gboolean Glib::BusTimeout::timeout_handler(gpointer data) +gboolean Glib::BusTimeout::timeout_handler (gpointer data) { - Glib::BusTimeout *t = reinterpret_cast<Glib::BusTimeout *>(data); + Glib::BusTimeout *t = reinterpret_cast<Glib::BusTimeout *> (data); - t->handle(); + t->handle(); - return TRUE; + return TRUE; } void Glib::BusTimeout::_enable() { - if (_source) - _disable(); // be sane + if (_source) + _disable(); // be sane - _source = g_timeout_source_new(Timeout::interval()); - g_source_set_priority(_source, _priority); - g_source_set_callback(_source, timeout_handler, this, NULL); - g_source_attach(_source, _ctx); + _source = g_timeout_source_new (Timeout::interval()); + + g_source_set_priority (_source, _priority); + + g_source_set_callback (_source, timeout_handler, this, NULL); + + g_source_attach (_source, _ctx); } void Glib::BusTimeout::_disable() { - if (_source) - { - g_source_destroy(_source); - _source = NULL; - } + if (_source) { + g_source_destroy (_source); + _source = NULL; + } } -struct BusSource -{ - GSource source; - GPollFD poll; +struct BusSource { + GSource source; + GPollFD poll; }; -static gboolean watch_prepare(GSource *source, gint *timeout) +static gboolean watch_prepare (GSource *source, gint *timeout) { - //debug_log("glib: watch_prepare"); + //debug_log("glib: watch_prepare"); - *timeout = -1; - return FALSE; + *timeout = -1; + return FALSE; } -static gboolean watch_check(GSource *source) +static gboolean watch_check (GSource *source) { - //debug_log("glib: watch_check"); + //debug_log("glib: watch_check"); - BusSource *io = (BusSource *)source; - return io->poll.revents ? TRUE : FALSE; + BusSource *io = (BusSource *) source; + return io->poll.revents ? TRUE : FALSE; } -static gboolean watch_dispatch(GSource *source, GSourceFunc callback, gpointer data) +static gboolean watch_dispatch (GSource *source, GSourceFunc callback, gpointer data) { - debug_log("glib: watch_dispatch"); + debug_log ("glib: watch_dispatch"); - gboolean cb = callback(data); - return cb; + gboolean cb = callback (data); + return cb; } static GSourceFuncs watch_funcs = { - watch_prepare, - watch_check, - watch_dispatch, - NULL + watch_prepare, + watch_check, + watch_dispatch, + NULL }; -Glib::BusWatch::BusWatch(Watch::Internal *wi, GMainContext *ctx, int priority) -: Watch(wi), _ctx(ctx), _priority(priority), _source(NULL) +Glib::BusWatch::BusWatch (Watch::Internal *wi, GMainContext *ctx, int priority) + : Watch (wi), _ctx (ctx), _priority (priority), _source (NULL) { - if (Watch::enabled()) - _enable(); + if (Watch::enabled()) + _enable(); } Glib::BusWatch::~BusWatch() { - _disable(); + _disable(); } void Glib::BusWatch::toggle() { - debug_log("glib: watch %p toggled (%s)", this, Watch::enabled() ? "on":"off"); + debug_log ("glib: watch %p toggled (%s)", this, Watch::enabled() ? "on":"off"); - if (Watch::enabled()) _enable(); - else _disable(); + if (Watch::enabled()) _enable(); + else _disable(); } -gboolean Glib::BusWatch::watch_handler(gpointer data) +gboolean Glib::BusWatch::watch_handler (gpointer data) { - Glib::BusWatch *w = reinterpret_cast<Glib::BusWatch *>(data); + Glib::BusWatch *w = reinterpret_cast<Glib::BusWatch *> (data); + + BusSource *io = (BusSource *) (w->_source); + + int flags = 0; + + if (io->poll.revents &G_IO_IN) + flags |= DBUS_WATCH_READABLE; + + if (io->poll.revents &G_IO_OUT) + flags |= DBUS_WATCH_WRITABLE; - BusSource *io = (BusSource *)(w->_source); + if (io->poll.revents &G_IO_ERR) + flags |= DBUS_WATCH_ERROR; - int flags = 0; - if (io->poll.revents &G_IO_IN) - flags |= DBUS_WATCH_READABLE; - if (io->poll.revents &G_IO_OUT) - flags |= DBUS_WATCH_WRITABLE; - if (io->poll.revents &G_IO_ERR) - flags |= DBUS_WATCH_ERROR; - if (io->poll.revents &G_IO_HUP) - flags |= DBUS_WATCH_HANGUP; + if (io->poll.revents &G_IO_HUP) + flags |= DBUS_WATCH_HANGUP; - w->handle(flags); + w->handle (flags); - return TRUE; + return TRUE; } void Glib::BusWatch::_enable() { - if (_source) - _disable(); // be sane - _source = g_source_new(&watch_funcs, sizeof(BusSource)); - g_source_set_priority(_source, _priority); - g_source_set_callback(_source, watch_handler, this, NULL); - - int flags = Watch::flags(); - int condition = 0; - - if (flags &DBUS_WATCH_READABLE) - condition |= G_IO_IN; - if (flags &DBUS_WATCH_WRITABLE) - condition |= G_IO_OUT; - if (flags &DBUS_WATCH_ERROR) - condition |= G_IO_ERR; - if (flags &DBUS_WATCH_HANGUP) - condition |= G_IO_HUP; - - GPollFD *poll = &(((BusSource *)_source)->poll); - poll->fd = Watch::descriptor(); - poll->events = condition; - poll->revents = 0; - - g_source_add_poll(_source, poll); - g_source_attach(_source, _ctx); + if (_source) + _disable(); // be sane + + _source = g_source_new (&watch_funcs, sizeof (BusSource)); + + g_source_set_priority (_source, _priority); + + g_source_set_callback (_source, watch_handler, this, NULL); + + int flags = Watch::flags(); + + int condition = 0; + + if (flags &DBUS_WATCH_READABLE) + condition |= G_IO_IN; + + if (flags &DBUS_WATCH_WRITABLE) + condition |= G_IO_OUT; + + if (flags &DBUS_WATCH_ERROR) + condition |= G_IO_ERR; + + if (flags &DBUS_WATCH_HANGUP) + condition |= G_IO_HUP; + + GPollFD *poll = & ( ( (BusSource *) _source)->poll); + + poll->fd = Watch::descriptor(); + + poll->events = condition; + + poll->revents = 0; + + g_source_add_poll (_source, poll); + + g_source_attach (_source, _ctx); } void Glib::BusWatch::_disable() { - if (!_source) - return; - GPollFD *poll = &(((BusSource *)_source)->poll); - g_source_remove_poll(_source, poll); - g_source_destroy(_source); - _source = NULL; + if (!_source) + return; + + GPollFD *poll = & ( ( (BusSource *) _source)->poll); + + g_source_remove_poll (_source, poll); + + g_source_destroy (_source); + + _source = NULL; } /* @@ -201,114 +221,113 @@ void Glib::BusWatch::_disable() * there are messages to dispatch queued up but no IO pending. * (fixes also a previous problem of code not working in case of multiple dispatchers) */ -struct DispatcherSource -{ - GSource source; - Dispatcher *dispatcher; + +struct DispatcherSource { + GSource source; + Dispatcher *dispatcher; }; -static gboolean dispatcher_prepare(GSource *source, gint *timeout) +static gboolean dispatcher_prepare (GSource *source, gint *timeout) { - Dispatcher *dispatcher = ((DispatcherSource*)source)->dispatcher; - - *timeout = -1; + Dispatcher *dispatcher = ( (DispatcherSource*) source)->dispatcher; + + *timeout = -1; - return dispatcher->has_something_to_dispatch()? TRUE:FALSE; + return dispatcher->has_something_to_dispatch() ? TRUE:FALSE; } -static gboolean dispatcher_check(GSource *source) +static gboolean dispatcher_check (GSource *source) { - return FALSE; + return FALSE; } static gboolean -dispatcher_dispatch(GSource *source, - GSourceFunc callback, - gpointer user_data) +dispatcher_dispatch (GSource *source, + GSourceFunc callback, + gpointer user_data) { - Dispatcher *dispatcher = ((DispatcherSource*)source)->dispatcher; + Dispatcher *dispatcher = ( (DispatcherSource*) source)->dispatcher; - dispatcher->dispatch_pending(); - return TRUE; + dispatcher->dispatch_pending(); + return TRUE; } static const GSourceFuncs dispatcher_funcs = { - dispatcher_prepare, - dispatcher_check, - dispatcher_dispatch, - NULL + dispatcher_prepare, + dispatcher_check, + dispatcher_dispatch, + NULL }; Glib::BusDispatcher::BusDispatcher() -: _ctx(NULL), _priority(G_PRIORITY_DEFAULT), _source(NULL) + : _ctx (NULL), _priority (G_PRIORITY_DEFAULT), _source (NULL) { } Glib::BusDispatcher::~BusDispatcher() { - if (_source) - { - GSource *temp = _source; - _source = NULL; + if (_source) { + GSource *temp = _source; + _source = NULL; - g_source_destroy (temp); - g_source_unref (temp); - } + g_source_destroy (temp); + g_source_unref (temp); + } - if (_ctx) - g_main_context_unref(_ctx); + if (_ctx) + g_main_context_unref (_ctx); } -void Glib::BusDispatcher::attach(GMainContext *ctx) +void Glib::BusDispatcher::attach (GMainContext *ctx) { - g_assert(_ctx == NULL); // just to be sane + g_assert (_ctx == NULL); // just to be sane + + _ctx = ctx ? ctx : g_main_context_default(); + g_main_context_ref (_ctx); - _ctx = ctx ? ctx : g_main_context_default(); - g_main_context_ref(_ctx); - - // create the source for dispatching messages - _source = g_source_new((GSourceFuncs *) &dispatcher_funcs, - sizeof(DispatcherSource)); + // create the source for dispatching messages + _source = g_source_new ( (GSourceFuncs *) &dispatcher_funcs, + sizeof (DispatcherSource)); - ((DispatcherSource*)_source)->dispatcher = this; - g_source_attach (_source, _ctx); + ( (DispatcherSource*) _source)->dispatcher = this; + g_source_attach (_source, _ctx); } -Timeout *Glib::BusDispatcher::add_timeout(Timeout::Internal *wi) +Timeout *Glib::BusDispatcher::add_timeout (Timeout::Internal *wi) { - Timeout *t = new Glib::BusTimeout(wi, _ctx, _priority); + Timeout *t = new Glib::BusTimeout (wi, _ctx, _priority); - debug_log("glib: added timeout %p (%s)", t, t->enabled() ? "on":"off"); + debug_log ("glib: added timeout %p (%s)", t, t->enabled() ? "on":"off"); - return t; + return t; } -void Glib::BusDispatcher::rem_timeout(Timeout *t) +void Glib::BusDispatcher::rem_timeout (Timeout *t) { - debug_log("glib: removed timeout %p", t); + debug_log ("glib: removed timeout %p", t); - delete t; + delete t; } -Watch *Glib::BusDispatcher::add_watch(Watch::Internal *wi) +Watch *Glib::BusDispatcher::add_watch (Watch::Internal *wi) { - Watch *w = new Glib::BusWatch(wi, _ctx, _priority); + Watch *w = new Glib::BusWatch (wi, _ctx, _priority); - debug_log("glib: added watch %p (%s) fd=%d flags=%d", - w, w->enabled() ? "on":"off", w->descriptor(), w->flags() - ); - return w; + debug_log ("glib: added watch %p (%s) fd=%d flags=%d", + w, w->enabled() ? "on":"off", w->descriptor(), w->flags() + ); + return w; } -void Glib::BusDispatcher::rem_watch(Watch *w) +void Glib::BusDispatcher::rem_watch (Watch *w) { - debug_log("glib: removed watch %p", w); + debug_log ("glib: removed watch %p", w); - delete w; + delete w; } -void Glib::BusDispatcher::set_priority(int priority) +void Glib::BusDispatcher::set_priority (int priority) { - _priority = priority; + _priority = priority; } diff --git a/sflphone-common/libs/dbus-c++/src/interface.cpp b/sflphone-common/libs/dbus-c++/src/interface.cpp index b0360ac979..aefcd1dea9 100644 --- a/sflphone-common/libs/dbus-c++/src/interface.cpp +++ b/sflphone-common/libs/dbus-c++/src/interface.cpp @@ -32,138 +32,135 @@ using namespace DBus; -Interface::Interface(const std::string &name) -: _name(name) +Interface::Interface (const std::string &name) + : _name (name) {} Interface::~Interface() {} -InterfaceAdaptor *AdaptorBase::find_interface(const std::string &name) +InterfaceAdaptor *AdaptorBase::find_interface (const std::string &name) { - InterfaceAdaptorTable::const_iterator ii = _interfaces.find(name); + InterfaceAdaptorTable::const_iterator ii = _interfaces.find (name); - return ii != _interfaces.end() ? ii->second : NULL; + return ii != _interfaces.end() ? ii->second : NULL; } -InterfaceAdaptor::InterfaceAdaptor(const std::string &name) -: Interface(name) +InterfaceAdaptor::InterfaceAdaptor (const std::string &name) + : Interface (name) { - debug_log("adding interface %s", name.c_str()); + debug_log ("adding interface %s", name.c_str()); - _interfaces[name] = this; + _interfaces[name] = this; } -Message InterfaceAdaptor::dispatch_method(const CallMessage &msg) +Message InterfaceAdaptor::dispatch_method (const CallMessage &msg) { - const char *name = msg.member(); - - MethodTable::iterator mi = _methods.find(name); - if (mi != _methods.end()) - { - return mi->second.call(msg); - } - else - { - return ErrorMessage(msg, DBUS_ERROR_UNKNOWN_METHOD, name); - } + const char *name = msg.member(); + + MethodTable::iterator mi = _methods.find (name); + + if (mi != _methods.end()) { + return mi->second.call (msg); + } else { + return ErrorMessage (msg, DBUS_ERROR_UNKNOWN_METHOD, name); + } } -void InterfaceAdaptor::emit_signal(const SignalMessage &sig) +void InterfaceAdaptor::emit_signal (const SignalMessage &sig) { - SignalMessage &sig2 = const_cast<SignalMessage &>(sig); + SignalMessage &sig2 = const_cast<SignalMessage &> (sig); - if (sig2.interface() == NULL) - sig2.interface(name().c_str()); + if (sig2.interface() == NULL) + sig2.interface (name().c_str()); - _emit_signal(sig2); + _emit_signal (sig2); } -Variant *InterfaceAdaptor::get_property(const std::string &name) +Variant *InterfaceAdaptor::get_property (const std::string &name) { - PropertyTable::iterator pti = _properties.find(name); + PropertyTable::iterator pti = _properties.find (name); + + if (pti != _properties.end()) { + if (!pti->second.read) + throw ErrorAccessDenied ("property is not readable"); - if (pti != _properties.end()) - { - if (!pti->second.read) - throw ErrorAccessDenied("property is not readable"); + return & (pti->second.value); + } - return &(pti->second.value); - } - return NULL; + return NULL; } -void InterfaceAdaptor::set_property(const std::string &name, Variant &value) +void InterfaceAdaptor::set_property (const std::string &name, Variant &value) { - PropertyTable::iterator pti = _properties.find(name); + PropertyTable::iterator pti = _properties.find (name); + + if (pti != _properties.end()) { + if (!pti->second.write) + throw ErrorAccessDenied ("property is not writeable"); + + Signature sig = value.signature(); - if (pti != _properties.end()) - { - if (!pti->second.write) - throw ErrorAccessDenied("property is not writeable"); + if (pti->second.sig != sig) + throw ErrorInvalidSignature ("property expects a different type"); - Signature sig = value.signature(); + pti->second.value = value; - if (pti->second.sig != sig) - throw ErrorInvalidSignature("property expects a different type"); + return; + } - pti->second.value = value; - return; - } - throw ErrorFailed("requested property not found"); + throw ErrorFailed ("requested property not found"); } -InterfaceProxy *ProxyBase::find_interface(const std::string &name) +InterfaceProxy *ProxyBase::find_interface (const std::string &name) { - InterfaceProxyTable::const_iterator ii = _interfaces.find(name); + InterfaceProxyTable::const_iterator ii = _interfaces.find (name); - return ii != _interfaces.end() ? ii->second : NULL; + return ii != _interfaces.end() ? ii->second : NULL; } -InterfaceProxy::InterfaceProxy(const std::string &name) -: Interface(name) +InterfaceProxy::InterfaceProxy (const std::string &name) + : Interface (name) { - debug_log("adding interface %s", name.c_str()); + debug_log ("adding interface %s", name.c_str()); - _interfaces[name] = this; + _interfaces[name] = this; } -bool InterfaceProxy::dispatch_signal(const SignalMessage &msg) +bool InterfaceProxy::dispatch_signal (const SignalMessage &msg) { - const char *name = msg.member(); - - SignalTable::iterator si = _signals.find(name); - if (si != _signals.end()) - { - si->second.call(msg); - // Here we always return false because there might be - // another InterfaceProxy listening for the same signal. - // This way we instruct libdbus-1 to go on dispatching - // the signal. - return false; - } - else - { - return false; - } + const char *name = msg.member(); + + SignalTable::iterator si = _signals.find (name); + + if (si != _signals.end()) { + si->second.call (msg); + // Here we always return false because there might be + // another InterfaceProxy listening for the same signal. + // This way we instruct libdbus-1 to go on dispatching + // the signal. + return false; + } else { + return false; + } } -Message InterfaceProxy::invoke_method(const CallMessage &call) +Message InterfaceProxy::invoke_method (const CallMessage &call) { - CallMessage &call2 = const_cast<CallMessage &>(call); + CallMessage &call2 = const_cast<CallMessage &> (call); - if (call.interface() == NULL) - call2.interface(name().c_str()); + if (call.interface() == NULL) + call2.interface (name().c_str()); - return _invoke_method(call2); + return _invoke_method (call2); } -bool InterfaceProxy::invoke_method_noreply(const CallMessage &call) +bool InterfaceProxy::invoke_method_noreply (const CallMessage &call) { - CallMessage &call2 = const_cast<CallMessage &>(call); + CallMessage &call2 = const_cast<CallMessage &> (call); - if (call.interface() == NULL) - call2.interface(name().c_str()); + if (call.interface() == NULL) + call2.interface (name().c_str()); - return _invoke_method_noreply(call2); + return _invoke_method_noreply (call2); } diff --git a/sflphone-common/libs/dbus-c++/src/introspection.cpp b/sflphone-common/libs/dbus-c++/src/introspection.cpp index 11fa883af8..41f6439f4a 100644 --- a/sflphone-common/libs/dbus-c++/src/introspection.cpp +++ b/sflphone-common/libs/dbus-c++/src/introspection.cpp @@ -38,156 +38,150 @@ using namespace DBus; static const char *introspectable_name = "org.freedesktop.DBus.Introspectable"; IntrospectableAdaptor::IntrospectableAdaptor() -: InterfaceAdaptor(introspectable_name) + : InterfaceAdaptor (introspectable_name) { - register_method(IntrospectableAdaptor, Introspect, Introspect); + register_method (IntrospectableAdaptor, Introspect, Introspect); } -Message IntrospectableAdaptor::Introspect(const CallMessage &call) +Message IntrospectableAdaptor::Introspect (const CallMessage &call) { - debug_log("requested introspection data"); + debug_log ("requested introspection data"); - std::ostringstream xml; + std::ostringstream xml; - xml << DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE; + xml << DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE; - const std::string path = object()->path(); + const std::string path = object()->path(); - xml << "<node name=\"" << path << "\">"; + xml << "<node name=\"" << path << "\">"; - InterfaceAdaptorTable::const_iterator iti; + InterfaceAdaptorTable::const_iterator iti; - for (iti = _interfaces.begin(); iti != _interfaces.end(); ++iti) - { - debug_log("introspecting interface %s", iti->first.c_str()); + for (iti = _interfaces.begin(); iti != _interfaces.end(); ++iti) { + debug_log ("introspecting interface %s", iti->first.c_str()); - IntrospectedInterface *const intro = iti->second->introspect(); - if (intro) - { - xml << "\n\t<interface name=\"" << intro->name << "\">"; + IntrospectedInterface *const intro = iti->second->introspect(); - for (const IntrospectedProperty *p = intro->properties; p->name; ++p) - { - std::string access; + if (intro) { + xml << "\n\t<interface name=\"" << intro->name << "\">"; - if (p->read) access += "read"; - if (p->write) access += "write"; + for (const IntrospectedProperty *p = intro->properties; p->name; ++p) { + std::string access; - xml << "\n\t\t<property name=\"" << p->name << "\"" - << " type=\"" << p->type << "\"" - << " access=\"" << access << "\"/>"; - } + if (p->read) access += "read"; - for (const IntrospectedMethod *m = intro->methods; m->args; ++m) - { - xml << "\n\t\t<method name=\"" << m->name << "\">"; + if (p->write) access += "write"; - for (const IntrospectedArgument *a = m->args; a->type; ++a) - { - xml << "\n\t\t\t<arg direction=\"" << (a->in ? "in" : "out") << "\"" - << " type=\"" << a->type << "\""; + xml << "\n\t\t<property name=\"" << p->name << "\"" + << " type=\"" << p->type << "\"" + << " access=\"" << access << "\"/>"; + } - if (a->name) xml << " name=\"" << a->name << "\""; + for (const IntrospectedMethod *m = intro->methods; m->args; ++m) { + xml << "\n\t\t<method name=\"" << m->name << "\">"; - xml << "/>"; - } + for (const IntrospectedArgument *a = m->args; a->type; ++a) { + xml << "\n\t\t\t<arg direction=\"" << (a->in ? "in" : "out") << "\"" + << " type=\"" << a->type << "\""; - xml << "\n\t\t</method>"; - } + if (a->name) xml << " name=\"" << a->name << "\""; - for (const IntrospectedMethod *m = intro->signals; m->args; ++m) - { - xml << "\n\t\t<signal name=\"" << m->name << "\">"; + xml << "/>"; + } - for (const IntrospectedArgument *a = m->args; a->type; ++a) - { - xml << "<arg type=\"" << a->type << "\""; + xml << "\n\t\t</method>"; + } - if (a->name) xml << " name=\"" << a->name << "\""; + for (const IntrospectedMethod *m = intro->signals; m->args; ++m) { + xml << "\n\t\t<signal name=\"" << m->name << "\">"; - xml << "/>"; - } - xml << "\n\t\t</signal>"; - } + for (const IntrospectedArgument *a = m->args; a->type; ++a) { + xml << "<arg type=\"" << a->type << "\""; - xml << "\n\t</interface>"; - } - } + if (a->name) xml << " name=\"" << a->name << "\""; - const ObjectPathList nodes = ObjectAdaptor::child_nodes_from_prefix(path + '/'); - ObjectPathList::const_iterator oni; + xml << "/>"; + } - for (oni = nodes.begin(); oni != nodes.end(); ++oni) - { - xml << "\n\t<node name=\"" << (*oni) << "\"/>"; - } + xml << "\n\t\t</signal>"; + } - /* broken - const ObjectAdaptorPList children = ObjectAdaptor::from_path_prefix(path + '/'); + xml << "\n\t</interface>"; + } + } - ObjectAdaptorPList::const_iterator oci; + const ObjectPathList nodes = ObjectAdaptor::child_nodes_from_prefix (path + '/'); - for (oci = children.begin(); oci != children.end(); ++oci) - { - std::string name = (*oci)->path().substr(path.length()+1); - name.substr(name.find('/')); + ObjectPathList::const_iterator oni; - xml << "<node name=\"" << name << "\"/>"; - } - */ + for (oni = nodes.begin(); oni != nodes.end(); ++oni) { + xml << "\n\t<node name=\"" << (*oni) << "\"/>"; + } - xml << "\n</node>"; + /* broken + const ObjectAdaptorPList children = ObjectAdaptor::from_path_prefix(path + '/'); - ReturnMessage reply(call); - MessageIter wi = reply.writer(); - wi.append_string(xml.str().c_str()); - return reply; + ObjectAdaptorPList::const_iterator oci; + + for (oci = children.begin(); oci != children.end(); ++oci) + { + std::string name = (*oci)->path().substr(path.length()+1); + name.substr(name.find('/')); + + xml << "<node name=\"" << name << "\"/>"; + } + */ + + xml << "\n</node>"; + + ReturnMessage reply (call); + + MessageIter wi = reply.writer(); + + wi.append_string (xml.str().c_str()); + + return reply; } IntrospectedInterface *const IntrospectableAdaptor::introspect() const { - static IntrospectedArgument Introspect_args[] = - { - { "data", "s", false }, - { 0, 0, 0 } - }; - static IntrospectedMethod Introspectable_methods[] = - { - { "Introspect", Introspect_args }, - { 0, 0 } - }; - static IntrospectedMethod Introspectable_signals[] = - { - { 0, 0 } - }; - static IntrospectedProperty Introspectable_properties[] = - { - { 0, 0, 0, 0 } - }; - static IntrospectedInterface Introspectable_interface = - { - introspectable_name, - Introspectable_methods, - Introspectable_signals, - Introspectable_properties - }; - return &Introspectable_interface; + static IntrospectedArgument Introspect_args[] = { + { "data", "s", false }, + { 0, 0, 0 } + }; + static IntrospectedMethod Introspectable_methods[] = { + { "Introspect", Introspect_args }, + { 0, 0 } + }; + static IntrospectedMethod Introspectable_signals[] = { + { 0, 0 } + }; + static IntrospectedProperty Introspectable_properties[] = { + { 0, 0, 0, 0 } + }; + static IntrospectedInterface Introspectable_interface = { + introspectable_name, + Introspectable_methods, + Introspectable_signals, + Introspectable_properties + }; + return &Introspectable_interface; } IntrospectableProxy::IntrospectableProxy() -: InterfaceProxy(introspectable_name) + : InterfaceProxy (introspectable_name) {} std::string IntrospectableProxy::Introspect() { - DBus::CallMessage call; + DBus::CallMessage call; - call.member("Introspect"); + call.member ("Introspect"); - DBus::Message ret = invoke_method(call); + DBus::Message ret = invoke_method (call); - DBus::MessageIter ri = ret.reader(); - const char *str = ri.get_string(); + DBus::MessageIter ri = ret.reader(); + const char *str = ri.get_string(); - return str; + return str; } diff --git a/sflphone-common/libs/dbus-c++/src/message.cpp b/sflphone-common/libs/dbus-c++/src/message.cpp index aa920b3767..4f3425e08d 100644 --- a/sflphone-common/libs/dbus-c++/src/message.cpp +++ b/sflphone-common/libs/dbus-c++/src/message.cpp @@ -40,531 +40,537 @@ using namespace DBus; int MessageIter::type() { - return dbus_message_iter_get_arg_type((DBusMessageIter *)&_iter); + return dbus_message_iter_get_arg_type ( (DBusMessageIter *) &_iter); } bool MessageIter::at_end() { - return type() == DBUS_TYPE_INVALID; + return type() == DBUS_TYPE_INVALID; } bool MessageIter::has_next() { - return dbus_message_iter_has_next((DBusMessageIter *)&_iter); + return dbus_message_iter_has_next ( (DBusMessageIter *) &_iter); } MessageIter &MessageIter::operator ++() { - dbus_message_iter_next((DBusMessageIter *)&_iter); - return (*this); + dbus_message_iter_next ( (DBusMessageIter *) &_iter); + return (*this); } -MessageIter MessageIter::operator ++(int) +MessageIter MessageIter::operator ++ (int) { - MessageIter copy(*this); - ++(*this); - return copy; + MessageIter copy (*this); + ++ (*this); + return copy; } -bool MessageIter::append_basic(int type_id, void *value) +bool MessageIter::append_basic (int type_id, void *value) { - return dbus_message_iter_append_basic((DBusMessageIter *)&_iter, type_id, value); + return dbus_message_iter_append_basic ( (DBusMessageIter *) &_iter, type_id, value); } -void MessageIter::get_basic(int type_id, void *ptr) +void MessageIter::get_basic (int type_id, void *ptr) { - if (type() != type_id) - throw ErrorInvalidArgs("type mismatch"); + if (type() != type_id) + throw ErrorInvalidArgs ("type mismatch"); - dbus_message_iter_get_basic((DBusMessageIter *)_iter, ptr); + dbus_message_iter_get_basic ( (DBusMessageIter *) _iter, ptr); } -bool MessageIter::append_byte(unsigned char b) +bool MessageIter::append_byte (unsigned char b) { - return append_basic(DBUS_TYPE_BYTE, &b); + return append_basic (DBUS_TYPE_BYTE, &b); } unsigned char MessageIter::get_byte() -{ - unsigned char b; - get_basic(DBUS_TYPE_BYTE, &b); - return b; +{ + unsigned char b; + get_basic (DBUS_TYPE_BYTE, &b); + return b; } -bool MessageIter::append_bool(bool b) +bool MessageIter::append_bool (bool b) { - dbus_bool_t db = b; - return append_basic(DBUS_TYPE_BOOLEAN, &db); + dbus_bool_t db = b; + return append_basic (DBUS_TYPE_BOOLEAN, &db); } -bool MessageIter::get_bool() +bool MessageIter::get_bool() { - dbus_bool_t db; - get_basic(DBUS_TYPE_BOOLEAN, &db); - return (bool)db; + dbus_bool_t db; + get_basic (DBUS_TYPE_BOOLEAN, &db); + return (bool) db; } -bool MessageIter::append_int16(signed short i) +bool MessageIter::append_int16 (signed short i) { - return append_basic(DBUS_TYPE_INT16, &i); + return append_basic (DBUS_TYPE_INT16, &i); } signed short MessageIter::get_int16() -{ - signed short i; - get_basic(DBUS_TYPE_INT16, &i); - return i; +{ + signed short i; + get_basic (DBUS_TYPE_INT16, &i); + return i; } -bool MessageIter::append_uint16(unsigned short u) +bool MessageIter::append_uint16 (unsigned short u) { - return append_basic(DBUS_TYPE_UINT16, &u); + return append_basic (DBUS_TYPE_UINT16, &u); } unsigned short MessageIter::get_uint16() -{ - unsigned short u; - get_basic(DBUS_TYPE_UINT16, &u); - return u; +{ + unsigned short u; + get_basic (DBUS_TYPE_UINT16, &u); + return u; } -bool MessageIter::append_int32(signed int i) +bool MessageIter::append_int32 (signed int i) { - return append_basic(DBUS_TYPE_INT32, &i); + return append_basic (DBUS_TYPE_INT32, &i); } signed int MessageIter::get_int32() -{ - signed int i; - get_basic(DBUS_TYPE_INT32, &i); - return i; +{ + signed int i; + get_basic (DBUS_TYPE_INT32, &i); + return i; } -bool MessageIter::append_uint32(unsigned int u) +bool MessageIter::append_uint32 (unsigned int u) { - return append_basic(DBUS_TYPE_UINT32, &u); + return append_basic (DBUS_TYPE_UINT32, &u); } unsigned int MessageIter::get_uint32() -{ - unsigned int u; - get_basic(DBUS_TYPE_UINT32, &u); - return u; +{ + unsigned int u; + get_basic (DBUS_TYPE_UINT32, &u); + return u; } signed long long MessageIter::get_int64() { - signed long long i; - get_basic(DBUS_TYPE_INT64, &i); - return i; + signed long long i; + get_basic (DBUS_TYPE_INT64, &i); + return i; } -bool MessageIter::append_int64(signed long long i) +bool MessageIter::append_int64 (signed long long i) { - return append_basic(DBUS_TYPE_INT64, &i); + return append_basic (DBUS_TYPE_INT64, &i); } unsigned long long MessageIter::get_uint64() { - unsigned long long u; - get_basic(DBUS_TYPE_UINT64, &u); - return u; + unsigned long long u; + get_basic (DBUS_TYPE_UINT64, &u); + return u; } -bool MessageIter::append_uint64(unsigned long long u) +bool MessageIter::append_uint64 (unsigned long long u) { - return append_basic(DBUS_TYPE_UINT64, &u); + return append_basic (DBUS_TYPE_UINT64, &u); } double MessageIter::get_double() { - double d; - get_basic(DBUS_TYPE_DOUBLE, &d); - return d; + double d; + get_basic (DBUS_TYPE_DOUBLE, &d); + return d; } -bool MessageIter::append_double(double d) +bool MessageIter::append_double (double d) { - return append_basic(DBUS_TYPE_DOUBLE, &d); + return append_basic (DBUS_TYPE_DOUBLE, &d); } -bool MessageIter::append_string(const char *chars) +bool MessageIter::append_string (const char *chars) { - return append_basic(DBUS_TYPE_STRING, &chars); + return append_basic (DBUS_TYPE_STRING, &chars); } const char *MessageIter::get_string() { - char *chars; - get_basic(DBUS_TYPE_STRING, &chars); - return chars; + char *chars; + get_basic (DBUS_TYPE_STRING, &chars); + return chars; } -bool MessageIter::append_path(const char *chars) +bool MessageIter::append_path (const char *chars) { - return append_basic(DBUS_TYPE_OBJECT_PATH, &chars); + return append_basic (DBUS_TYPE_OBJECT_PATH, &chars); } const char *MessageIter::get_path() { - char *chars; - get_basic(DBUS_TYPE_OBJECT_PATH, &chars); - return chars; + char *chars; + get_basic (DBUS_TYPE_OBJECT_PATH, &chars); + return chars; } -bool MessageIter::append_signature(const char *chars) +bool MessageIter::append_signature (const char *chars) { - return append_basic(DBUS_TYPE_SIGNATURE, &chars); + return append_basic (DBUS_TYPE_SIGNATURE, &chars); } const char *MessageIter::get_signature() { - char *chars; - get_basic(DBUS_TYPE_SIGNATURE, &chars); - return chars; + char *chars; + get_basic (DBUS_TYPE_SIGNATURE, &chars); + return chars; } -MessageIter MessageIter::recurse() +MessageIter MessageIter::recurse() { - MessageIter iter(msg()); - dbus_message_iter_recurse((DBusMessageIter *)&_iter, (DBusMessageIter *)&(iter._iter)); - return iter; + MessageIter iter (msg()); + dbus_message_iter_recurse ( (DBusMessageIter *) &_iter, (DBusMessageIter *) & (iter._iter)); + return iter; } char *MessageIter::signature() const { - return dbus_message_iter_get_signature((DBusMessageIter *)&_iter); + return dbus_message_iter_get_signature ( (DBusMessageIter *) &_iter); } -bool MessageIter::append_array(char type, const void *ptr, size_t length) +bool MessageIter::append_array (char type, const void *ptr, size_t length) { - return dbus_message_iter_append_fixed_array((DBusMessageIter *)&_iter, type, &ptr, length); + return dbus_message_iter_append_fixed_array ( (DBusMessageIter *) &_iter, type, &ptr, length); } int MessageIter::array_type() { - return dbus_message_iter_get_element_type((DBusMessageIter *)&_iter); + return dbus_message_iter_get_element_type ( (DBusMessageIter *) &_iter); } -int MessageIter::get_array(void *ptr) +int MessageIter::get_array (void *ptr) { - int length; - dbus_message_iter_get_fixed_array((DBusMessageIter *)&_iter, ptr, &length); - return length; + int length; + dbus_message_iter_get_fixed_array ( (DBusMessageIter *) &_iter, ptr, &length); + return length; } bool MessageIter::is_array() { - return dbus_message_iter_get_arg_type((DBusMessageIter *)&_iter) == DBUS_TYPE_ARRAY; + return dbus_message_iter_get_arg_type ( (DBusMessageIter *) &_iter) == DBUS_TYPE_ARRAY; } bool MessageIter::is_dict() { - return is_array() && dbus_message_iter_get_element_type((DBusMessageIter *)_iter) == DBUS_TYPE_DICT_ENTRY; + return is_array() && dbus_message_iter_get_element_type ( (DBusMessageIter *) _iter) == DBUS_TYPE_DICT_ENTRY; } -MessageIter MessageIter::new_array(const char *sig) +MessageIter MessageIter::new_array (const char *sig) { - MessageIter arr(msg()); - dbus_message_iter_open_container( - (DBusMessageIter *)&_iter, DBUS_TYPE_ARRAY, sig, (DBusMessageIter *)&(arr._iter) - ); - return arr; + MessageIter arr (msg()); + dbus_message_iter_open_container ( + (DBusMessageIter *) &_iter, DBUS_TYPE_ARRAY, sig, (DBusMessageIter *) & (arr._iter) + ); + return arr; } -MessageIter MessageIter::new_variant(const char *sig) +MessageIter MessageIter::new_variant (const char *sig) { - MessageIter var(msg()); - dbus_message_iter_open_container( - (DBusMessageIter *)_iter, DBUS_TYPE_VARIANT, sig, (DBusMessageIter *)&(var._iter) - ); - return var; + MessageIter var (msg()); + dbus_message_iter_open_container ( + (DBusMessageIter *) _iter, DBUS_TYPE_VARIANT, sig, (DBusMessageIter *) & (var._iter) + ); + return var; } MessageIter MessageIter::new_struct() { - MessageIter stu(msg()); - dbus_message_iter_open_container( - (DBusMessageIter *)_iter, DBUS_TYPE_STRUCT, NULL, (DBusMessageIter *)&(stu._iter) - ); - return stu; + MessageIter stu (msg()); + dbus_message_iter_open_container ( + (DBusMessageIter *) _iter, DBUS_TYPE_STRUCT, NULL, (DBusMessageIter *) & (stu._iter) + ); + return stu; } MessageIter MessageIter::new_dict_entry() { - MessageIter ent(msg()); - dbus_message_iter_open_container( - (DBusMessageIter *)_iter, DBUS_TYPE_DICT_ENTRY, NULL, (DBusMessageIter *)&(ent._iter) - ); - return ent; -} - -void MessageIter::close_container(MessageIter &container) -{ - dbus_message_iter_close_container((DBusMessageIter *)&_iter, (DBusMessageIter *)&(container._iter)); -} - -static bool is_basic_type(int typecode) -{ - switch (typecode) - { - case 'y': - case 'b': - case 'n': - case 'q': - case 'i': - case 'u': - case 'x': - case 't': - case 'd': - case 's': - case 'o': - case 'g': - return true; - default: - return false; - } -} - -void MessageIter::copy_data(MessageIter &to) -{ - for (MessageIter &from = *this; !from.at_end(); ++from) - { - if (is_basic_type(from.type())) - { - debug_log("copying basic type: %c", from.type()); - - unsigned char value[8]; - from.get_basic(from.type(), &value); - to.append_basic(from.type(), &value); - } - else - { - MessageIter from_container = from.recurse(); - char *sig = from_container.signature(); - - debug_log("copying compound type: %c[%s]", from.type(), sig); - - MessageIter to_container (to.msg()); - dbus_message_iter_open_container - ( - (DBusMessageIter *)&(to._iter), - from.type(), - from.type() == DBUS_TYPE_VARIANT ? NULL : sig, - (DBusMessageIter *)&(to_container._iter) - ); - - from_container.copy_data(to_container); - to.close_container(to_container); - free(sig); - } - } + MessageIter ent (msg()); + dbus_message_iter_open_container ( + (DBusMessageIter *) _iter, DBUS_TYPE_DICT_ENTRY, NULL, (DBusMessageIter *) & (ent._iter) + ); + return ent; +} + +void MessageIter::close_container (MessageIter &container) +{ + dbus_message_iter_close_container ( (DBusMessageIter *) &_iter, (DBusMessageIter *) & (container._iter)); +} + +static bool is_basic_type (int typecode) +{ + switch (typecode) { + + case 'y': + + case 'b': + + case 'n': + + case 'q': + + case 'i': + + case 'u': + + case 'x': + + case 't': + + case 'd': + + case 's': + + case 'o': + + case 'g': + return true; + + default: + return false; + } +} + +void MessageIter::copy_data (MessageIter &to) +{ + for (MessageIter &from = *this; !from.at_end(); ++from) { + if (is_basic_type (from.type())) { + debug_log ("copying basic type: %c", from.type()); + + unsigned char value[8]; + from.get_basic (from.type(), &value); + to.append_basic (from.type(), &value); + } else { + MessageIter from_container = from.recurse(); + char *sig = from_container.signature(); + + debug_log ("copying compound type: %c[%s]", from.type(), sig); + + MessageIter to_container (to.msg()); + dbus_message_iter_open_container + ( + (DBusMessageIter *) & (to._iter), + from.type(), + from.type() == DBUS_TYPE_VARIANT ? NULL : sig, + (DBusMessageIter *) & (to_container._iter) + ); + + from_container.copy_data (to_container); + to.close_container (to_container); + free (sig); + } + } } /* */ Message::Message() -: _pvt(new Private) + : _pvt (new Private) { } -Message::Message(Message::Private *p, bool incref) -: _pvt(p) +Message::Message (Message::Private *p, bool incref) + : _pvt (p) { - if (_pvt->msg && incref) dbus_message_ref(_pvt->msg); + if (_pvt->msg && incref) dbus_message_ref (_pvt->msg); } -Message::Message(const Message &m) -: _pvt(m._pvt) +Message::Message (const Message &m) + : _pvt (m._pvt) { - dbus_message_ref(_pvt->msg); + dbus_message_ref (_pvt->msg); } Message::~Message() { - dbus_message_unref(_pvt->msg); + dbus_message_unref (_pvt->msg); } Message &Message::operator = (const Message &m) { - if (&m != this) - { - dbus_message_unref(_pvt->msg); - _pvt = m._pvt; - dbus_message_ref(_pvt->msg); - } - return *this; + if (&m != this) { + dbus_message_unref (_pvt->msg); + _pvt = m._pvt; + dbus_message_ref (_pvt->msg); + } + + return *this; } Message Message::copy() { - Private *pvt = new Private(dbus_message_copy(_pvt->msg)); - return Message(pvt); + Private *pvt = new Private (dbus_message_copy (_pvt->msg)); + return Message (pvt); } -bool Message::append(int first_type, ...) +bool Message::append (int first_type, ...) { - va_list vl; - va_start(vl, first_type); + va_list vl; + va_start (vl, first_type); - bool b = dbus_message_append_args_valist(_pvt->msg, first_type, vl); + bool b = dbus_message_append_args_valist (_pvt->msg, first_type, vl); - va_end(vl); - return b; + va_end (vl); + return b; } void Message::terminate() { - dbus_message_append_args(_pvt->msg, DBUS_TYPE_INVALID); + dbus_message_append_args (_pvt->msg, DBUS_TYPE_INVALID); } int Message::type() const { - return dbus_message_get_type(_pvt->msg); + return dbus_message_get_type (_pvt->msg); } int Message::serial() const { - return dbus_message_get_serial(_pvt->msg); + return dbus_message_get_serial (_pvt->msg); } int Message::reply_serial() const { - return dbus_message_get_reply_serial(_pvt->msg); + return dbus_message_get_reply_serial (_pvt->msg); } -bool Message::reply_serial(int s) +bool Message::reply_serial (int s) { - return dbus_message_set_reply_serial(_pvt->msg, s); + return dbus_message_set_reply_serial (_pvt->msg, s); } const char *Message::sender() const { - return dbus_message_get_sender(_pvt->msg); + return dbus_message_get_sender (_pvt->msg); } -bool Message::sender(const char *s) +bool Message::sender (const char *s) { - return dbus_message_set_sender(_pvt->msg, s); + return dbus_message_set_sender (_pvt->msg, s); } const char *Message::destination() const { - return dbus_message_get_destination(_pvt->msg); + return dbus_message_get_destination (_pvt->msg); } -bool Message::destination(const char *s) +bool Message::destination (const char *s) { - return dbus_message_set_destination(_pvt->msg, s); + return dbus_message_set_destination (_pvt->msg, s); } bool Message::is_error() const { - return type() == DBUS_MESSAGE_TYPE_ERROR; + return type() == DBUS_MESSAGE_TYPE_ERROR; } -bool Message::is_signal(const char *interface, const char *member) const +bool Message::is_signal (const char *interface, const char *member) const { - return dbus_message_is_signal(_pvt->msg, interface, member); + return dbus_message_is_signal (_pvt->msg, interface, member); } MessageIter Message::writer() { - MessageIter iter(*this); - dbus_message_iter_init_append(_pvt->msg, (DBusMessageIter *)&(iter._iter)); - return iter; + MessageIter iter (*this); + dbus_message_iter_init_append (_pvt->msg, (DBusMessageIter *) & (iter._iter)); + return iter; } MessageIter Message::reader() const { - MessageIter iter(const_cast<Message &>(*this)); - dbus_message_iter_init(_pvt->msg, (DBusMessageIter *)&(iter._iter)); - return iter; + MessageIter iter (const_cast<Message &> (*this)); + dbus_message_iter_init (_pvt->msg, (DBusMessageIter *) & (iter._iter)); + return iter; } -/* +/* */ ErrorMessage::ErrorMessage() { - _pvt->msg = dbus_message_new(DBUS_MESSAGE_TYPE_ERROR); + _pvt->msg = dbus_message_new (DBUS_MESSAGE_TYPE_ERROR); } -ErrorMessage::ErrorMessage(const Message &to_reply, const char *name, const char *message) +ErrorMessage::ErrorMessage (const Message &to_reply, const char *name, const char *message) { - _pvt->msg = dbus_message_new_error(to_reply._pvt->msg, name, message); + _pvt->msg = dbus_message_new_error (to_reply._pvt->msg, name, message); } bool ErrorMessage::operator == (const ErrorMessage &m) const { - return dbus_message_is_error(_pvt->msg, m.name()); + return dbus_message_is_error (_pvt->msg, m.name()); } const char *ErrorMessage::name() const { - return dbus_message_get_error_name(_pvt->msg); + return dbus_message_get_error_name (_pvt->msg); } -bool ErrorMessage::name(const char *n) +bool ErrorMessage::name (const char *n) { - return dbus_message_set_error_name(_pvt->msg, n); + return dbus_message_set_error_name (_pvt->msg, n); } /* */ -SignalMessage::SignalMessage(const char *name) +SignalMessage::SignalMessage (const char *name) { - _pvt->msg = dbus_message_new(DBUS_MESSAGE_TYPE_SIGNAL); - member(name); + _pvt->msg = dbus_message_new (DBUS_MESSAGE_TYPE_SIGNAL); + member (name); } -SignalMessage::SignalMessage(const char *path, const char *interface, const char *name) +SignalMessage::SignalMessage (const char *path, const char *interface, const char *name) { - _pvt->msg = dbus_message_new_signal(path, interface, name); + _pvt->msg = dbus_message_new_signal (path, interface, name); } bool SignalMessage::operator == (const SignalMessage &m) const { - return dbus_message_is_signal(_pvt->msg, m.interface(), m.member()); + return dbus_message_is_signal (_pvt->msg, m.interface(), m.member()); } -const char *SignalMessage::interface() const -{ - return dbus_message_get_interface(_pvt->msg); -} +const char *SignalMessage::interface() const { + return dbus_message_get_interface (_pvt->msg); + } -bool SignalMessage::interface(const char *i) -{ - return dbus_message_set_interface(_pvt->msg, i); +bool SignalMessage::interface (const char *i) { + return dbus_message_set_interface (_pvt->msg, i); } const char *SignalMessage::member() const { - return dbus_message_get_member(_pvt->msg); + return dbus_message_get_member (_pvt->msg); } -bool SignalMessage::member(const char *m) +bool SignalMessage::member (const char *m) { - return dbus_message_set_member(_pvt->msg, m); + return dbus_message_set_member (_pvt->msg, m); } const char *SignalMessage::path() const { - return dbus_message_get_path(_pvt->msg); + return dbus_message_get_path (_pvt->msg); } char ** SignalMessage::path_split() const { - char ** p; - dbus_message_get_path_decomposed(_pvt->msg, &p); //todo: return as a std::vector ? - return p; + char ** p; + dbus_message_get_path_decomposed (_pvt->msg, &p); //todo: return as a std::vector ? + return p; } -bool SignalMessage::path(const char *p) +bool SignalMessage::path (const char *p) { - return dbus_message_set_path(_pvt->msg, p); + return dbus_message_set_path (_pvt->msg, p); } /* @@ -572,71 +578,69 @@ bool SignalMessage::path(const char *p) CallMessage::CallMessage() { - _pvt->msg = dbus_message_new(DBUS_MESSAGE_TYPE_METHOD_CALL); + _pvt->msg = dbus_message_new (DBUS_MESSAGE_TYPE_METHOD_CALL); } -CallMessage::CallMessage(const char *dest, const char *path, const char *iface, const char *method) +CallMessage::CallMessage (const char *dest, const char *path, const char *iface, const char *method) { - _pvt->msg = dbus_message_new_method_call(dest, path, iface, method); + _pvt->msg = dbus_message_new_method_call (dest, path, iface, method); } bool CallMessage::operator == (const CallMessage &m) const { - return dbus_message_is_method_call(_pvt->msg, m.interface(), m.member()); + return dbus_message_is_method_call (_pvt->msg, m.interface(), m.member()); } -const char *CallMessage::interface() const -{ - return dbus_message_get_interface(_pvt->msg); -} +const char *CallMessage::interface() const { + return dbus_message_get_interface (_pvt->msg); + } -bool CallMessage::interface(const char *i) -{ - return dbus_message_set_interface(_pvt->msg, i); +bool CallMessage::interface (const char *i) { + return dbus_message_set_interface (_pvt->msg, i); } const char *CallMessage::member() const { - return dbus_message_get_member(_pvt->msg); + return dbus_message_get_member (_pvt->msg); } -bool CallMessage::member(const char *m) +bool CallMessage::member (const char *m) { - return dbus_message_set_member(_pvt->msg, m); + return dbus_message_set_member (_pvt->msg, m); } const char *CallMessage::path() const { - return dbus_message_get_path(_pvt->msg); + return dbus_message_get_path (_pvt->msg); } char ** CallMessage::path_split() const { - char ** p; - dbus_message_get_path_decomposed(_pvt->msg, &p); - return p; + char ** p; + dbus_message_get_path_decomposed (_pvt->msg, &p); + return p; } -bool CallMessage::path(const char *p) +bool CallMessage::path (const char *p) { - return dbus_message_set_path(_pvt->msg, p); + return dbus_message_set_path (_pvt->msg, p); } const char *CallMessage::signature() const { - return dbus_message_get_signature(_pvt->msg); + return dbus_message_get_signature (_pvt->msg); } /* */ -ReturnMessage::ReturnMessage(const CallMessage &callee) +ReturnMessage::ReturnMessage (const CallMessage &callee) { - _pvt = new Private(dbus_message_new_method_return(callee._pvt->msg)); + _pvt = new Private (dbus_message_new_method_return (callee._pvt->msg)); } const char *ReturnMessage::signature() const { - return dbus_message_get_signature(_pvt->msg); + return dbus_message_get_signature (_pvt->msg); } diff --git a/sflphone-common/libs/dbus-c++/src/object.cpp b/sflphone-common/libs/dbus-c++/src/object.cpp index f7d0916031..4fa8cd15d1 100644 --- a/sflphone-common/libs/dbus-c++/src/object.cpp +++ b/sflphone-common/libs/dbus-c++/src/object.cpp @@ -39,8 +39,8 @@ using namespace DBus; -Object::Object(Connection &conn, const Path &path, const char *service) -: _conn(conn), _path(path), _service(service ? service : "") +Object::Object (Connection &conn, const Path &path, const char *service) + : _conn (conn), _path (path), _service (service ? service : "") { } @@ -48,330 +48,315 @@ Object::~Object() { } -struct ObjectAdaptor::Private -{ - static void unregister_function_stub(DBusConnection *, void *); - static DBusHandlerResult message_function_stub(DBusConnection *, DBusMessage *, void *); +struct ObjectAdaptor::Private { + static void unregister_function_stub (DBusConnection *, void *); + static DBusHandlerResult message_function_stub (DBusConnection *, DBusMessage *, void *); }; -static DBusObjectPathVTable _vtable = -{ - ObjectAdaptor::Private::unregister_function_stub, - ObjectAdaptor::Private::message_function_stub, - NULL, NULL, NULL, NULL +static DBusObjectPathVTable _vtable = { + ObjectAdaptor::Private::unregister_function_stub, + ObjectAdaptor::Private::message_function_stub, + NULL, NULL, NULL, NULL }; -void ObjectAdaptor::Private::unregister_function_stub(DBusConnection *conn, void *data) +void ObjectAdaptor::Private::unregister_function_stub (DBusConnection *conn, void *data) { - //TODO: what do we have to do here ? + //TODO: what do we have to do here ? } -DBusHandlerResult ObjectAdaptor::Private::message_function_stub(DBusConnection *, DBusMessage *dmsg, void *data) +DBusHandlerResult ObjectAdaptor::Private::message_function_stub (DBusConnection *, DBusMessage *dmsg, void *data) { - ObjectAdaptor *o = static_cast<ObjectAdaptor *>(data); - - if (o) - { - Message msg(new Message::Private(dmsg)); - - debug_log("in object %s", o->path().c_str()); - debug_log(" got message #%d from %s to %s", - msg.serial(), - msg.sender(), - msg.destination() - ); - - return o->handle_message(msg) - ? DBUS_HANDLER_RESULT_HANDLED - : DBUS_HANDLER_RESULT_NOT_YET_HANDLED; - } - else - { - return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; - } + ObjectAdaptor *o = static_cast<ObjectAdaptor *> (data); + + if (o) { + Message msg (new Message::Private (dmsg)); + + debug_log ("in object %s", o->path().c_str()); + debug_log (" got message #%d from %s to %s", + msg.serial(), + msg.sender(), + msg.destination() + ); + + return o->handle_message (msg) + ? DBUS_HANDLER_RESULT_HANDLED + : DBUS_HANDLER_RESULT_NOT_YET_HANDLED; + } else { + return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; + } } typedef std::map<Path, ObjectAdaptor *> ObjectAdaptorTable; static ObjectAdaptorTable _adaptor_table; -ObjectAdaptor *ObjectAdaptor::from_path(const Path &path) +ObjectAdaptor *ObjectAdaptor::from_path (const Path &path) { - ObjectAdaptorTable::iterator ati = _adaptor_table.find(path); + ObjectAdaptorTable::iterator ati = _adaptor_table.find (path); - if (ati != _adaptor_table.end()) - return ati->second; + if (ati != _adaptor_table.end()) + return ati->second; - return NULL; + return NULL; } -ObjectAdaptorPList ObjectAdaptor::from_path_prefix(const std::string &prefix) +ObjectAdaptorPList ObjectAdaptor::from_path_prefix (const std::string &prefix) { - ObjectAdaptorPList ali; + ObjectAdaptorPList ali; - ObjectAdaptorTable::iterator ati = _adaptor_table.begin(); + ObjectAdaptorTable::iterator ati = _adaptor_table.begin(); - size_t plen = prefix.length(); + size_t plen = prefix.length(); - while (ati != _adaptor_table.end()) - { - if (!strncmp(ati->second->path().c_str(), prefix.c_str(), plen)) - ali.push_back(ati->second); + while (ati != _adaptor_table.end()) { + if (!strncmp (ati->second->path().c_str(), prefix.c_str(), plen)) + ali.push_back (ati->second); - ++ati; - } + ++ati; + } - return ali; + return ali; } -ObjectPathList ObjectAdaptor::child_nodes_from_prefix(const std::string &prefix) +ObjectPathList ObjectAdaptor::child_nodes_from_prefix (const std::string &prefix) { - ObjectPathList ali; + ObjectPathList ali; + + ObjectAdaptorTable::iterator ati = _adaptor_table.begin(); + + size_t plen = prefix.length(); - ObjectAdaptorTable::iterator ati = _adaptor_table.begin(); + while (ati != _adaptor_table.end()) { + if (!strncmp (ati->second->path().c_str(), prefix.c_str(), plen)) { + std::string p = ati->second->path().substr (plen); + p = p.substr (0,p.find ('/')); + ali.push_back (p); + } - size_t plen = prefix.length(); + ++ati; + } - while (ati != _adaptor_table.end()) - { - if (!strncmp(ati->second->path().c_str(), prefix.c_str(), plen)) - { - std::string p = ati->second->path().substr(plen); - p = p.substr(0,p.find('/')); - ali.push_back(p); - } - ++ati; - } + ali.sort(); - ali.sort(); - ali.unique(); + ali.unique(); - return ali; + return ali; } -ObjectAdaptor::ObjectAdaptor(Connection &conn, const Path &path) -: Object(conn, path, conn.unique_name()) +ObjectAdaptor::ObjectAdaptor (Connection &conn, const Path &path) + : Object (conn, path, conn.unique_name()) { - register_obj(); + register_obj(); } ObjectAdaptor::~ObjectAdaptor() { - unregister_obj(); + unregister_obj(); } void ObjectAdaptor::register_obj() { - debug_log("registering local object %s", path().c_str()); + debug_log ("registering local object %s", path().c_str()); - if (!dbus_connection_register_object_path(conn()._pvt->conn, path().c_str(), &_vtable, this)) - { - throw ErrorNoMemory("unable to register object path"); - } + if (!dbus_connection_register_object_path (conn()._pvt->conn, path().c_str(), &_vtable, this)) { + throw ErrorNoMemory ("unable to register object path"); + } - _adaptor_table[path()] = this; + _adaptor_table[path() ] = this; } void ObjectAdaptor::unregister_obj() { - _adaptor_table.erase(path()); + _adaptor_table.erase (path()); - debug_log("unregistering local object %s", path().c_str()); + debug_log ("unregistering local object %s", path().c_str()); - dbus_connection_unregister_object_path(conn()._pvt->conn, path().c_str()); + dbus_connection_unregister_object_path (conn()._pvt->conn, path().c_str()); } -void ObjectAdaptor::_emit_signal(SignalMessage &sig) +void ObjectAdaptor::_emit_signal (SignalMessage &sig) { - sig.path(path().c_str()); + sig.path (path().c_str()); - conn().send(sig); + conn().send (sig); } -struct ReturnLaterError -{ - const Tag *tag; +struct ReturnLaterError { + const Tag *tag; }; -bool ObjectAdaptor::handle_message(const Message &msg) +bool ObjectAdaptor::handle_message (const Message &msg) { - switch (msg.type()) - { - case DBUS_MESSAGE_TYPE_METHOD_CALL: - { - const CallMessage &cmsg = reinterpret_cast<const CallMessage &>(msg); - const char *member = cmsg.member(); - const char *interface = cmsg.interface(); - - debug_log(" invoking method %s.%s", interface, member); - - InterfaceAdaptor *ii = find_interface(interface); - if (ii) - { - try - { - Message ret = ii->dispatch_method(cmsg); - conn().send(ret); - } - catch(Error &e) - { - ErrorMessage em(cmsg, e.name(), e.message()); - conn().send(em); - } - catch(ReturnLaterError &rle) - { - _continuations[rle.tag] = new Continuation(conn(), cmsg, rle.tag); - } - return true; - } - else - { - return false; - } - } - default: - { - return false; - } - } + switch (msg.type()) { + + case DBUS_MESSAGE_TYPE_METHOD_CALL: { + const CallMessage &cmsg = reinterpret_cast<const CallMessage &> (msg); + const char *member = cmsg.member(); + + const char *interface = cmsg.interface(); + + debug_log (" invoking method %s.%s", interface, member); + + InterfaceAdaptor *ii = find_interface (interface); + + if (ii) { + try { + Message ret = ii->dispatch_method (cmsg); + conn().send (ret); + } catch (Error &e) { + ErrorMessage em (cmsg, e.name(), e.message()); + conn().send (em); + } catch (ReturnLaterError &rle) { + _continuations[rle.tag] = new Continuation (conn(), cmsg, rle.tag); + } + + return true; + } else { + return false; + } + } + + default: { + return false; + } + } } -void ObjectAdaptor::return_later(const Tag *tag) +void ObjectAdaptor::return_later (const Tag *tag) { - ReturnLaterError rle = { tag }; - throw rle; + ReturnLaterError rle = { tag }; + throw rle; } -void ObjectAdaptor::return_now(Continuation *ret) +void ObjectAdaptor::return_now (Continuation *ret) { - ret->_conn.send(ret->_return); + ret->_conn.send (ret->_return); - ContinuationMap::iterator di = _continuations.find(ret->_tag); + ContinuationMap::iterator di = _continuations.find (ret->_tag); - delete di->second; + delete di->second; - _continuations.erase(di); + _continuations.erase (di); } -void ObjectAdaptor::return_error(Continuation *ret, const Error error) +void ObjectAdaptor::return_error (Continuation *ret, const Error error) { - ret->_conn.send(ErrorMessage(ret->_call, error.name(), error.message())); + ret->_conn.send (ErrorMessage (ret->_call, error.name(), error.message())); - ContinuationMap::iterator di = _continuations.find(ret->_tag); + ContinuationMap::iterator di = _continuations.find (ret->_tag); - delete di->second; + delete di->second; - _continuations.erase(di); + _continuations.erase (di); } -ObjectAdaptor::Continuation *ObjectAdaptor::find_continuation(const Tag *tag) +ObjectAdaptor::Continuation *ObjectAdaptor::find_continuation (const Tag *tag) { - ContinuationMap::iterator di = _continuations.find(tag); + ContinuationMap::iterator di = _continuations.find (tag); - return di != _continuations.end() ? di->second : NULL; + return di != _continuations.end() ? di->second : NULL; } -ObjectAdaptor::Continuation::Continuation(Connection &conn, const CallMessage &call, const Tag *tag) -: _conn(conn), _call(call), _return(_call), _tag(tag) +ObjectAdaptor::Continuation::Continuation (Connection &conn, const CallMessage &call, const Tag *tag) + : _conn (conn), _call (call), _return (_call), _tag (tag) { - _writer = _return.writer(); //todo: verify + _writer = _return.writer(); //todo: verify } /* */ -ObjectProxy::ObjectProxy(Connection &conn, const Path &path, const char *service) -: Object(conn, path, service) +ObjectProxy::ObjectProxy (Connection &conn, const Path &path, const char *service) + : Object (conn, path, service) { - register_obj(); + register_obj(); } ObjectProxy::~ObjectProxy() { - unregister_obj(); + unregister_obj(); } void ObjectProxy::register_obj() { - debug_log("registering remote object %s", path().c_str()); - - _filtered = new Callback<ObjectProxy, bool, const Message &>(this, &ObjectProxy::handle_message); - - conn().add_filter(_filtered); - - InterfaceProxyTable::const_iterator ii = _interfaces.begin(); - while (ii != _interfaces.end()) - { - std::string im = "type='signal',interface='"+ii->first+"',path='"+path()+"'"; - conn().add_match(im.c_str()); - ++ii; - } + debug_log ("registering remote object %s", path().c_str()); + + _filtered = new Callback<ObjectProxy, bool, const Message &> (this, &ObjectProxy::handle_message); + + conn().add_filter (_filtered); + + InterfaceProxyTable::const_iterator ii = _interfaces.begin(); + + while (ii != _interfaces.end()) { + std::string im = "type='signal',interface='"+ii->first+"',path='"+path() +"'"; + conn().add_match (im.c_str()); + ++ii; + } } void ObjectProxy::unregister_obj() { - debug_log("unregistering remote object %s", path().c_str()); - - InterfaceProxyTable::const_iterator ii = _interfaces.begin(); - while (ii != _interfaces.end()) - { - std::string im = "type='signal',interface='"+ii->first+"',path='"+path()+"'"; - conn().remove_match(im.c_str()); - ++ii; - } - conn().remove_filter(_filtered); + debug_log ("unregistering remote object %s", path().c_str()); + + InterfaceProxyTable::const_iterator ii = _interfaces.begin(); + + while (ii != _interfaces.end()) { + std::string im = "type='signal',interface='"+ii->first+"',path='"+path() +"'"; + conn().remove_match (im.c_str()); + ++ii; + } + + conn().remove_filter (_filtered); } -Message ObjectProxy::_invoke_method(CallMessage &call) +Message ObjectProxy::_invoke_method (CallMessage &call) { - if (call.path() == NULL) - call.path(path().c_str()); + if (call.path() == NULL) + call.path (path().c_str()); - if (call.destination() == NULL) - call.destination(service().c_str()); + if (call.destination() == NULL) + call.destination (service().c_str()); - return conn().send_blocking(call); + return conn().send_blocking (call); } -bool ObjectProxy::_invoke_method_noreply(CallMessage &call) +bool ObjectProxy::_invoke_method_noreply (CallMessage &call) { - if (call.path() == NULL) - call.path(path().c_str()); + if (call.path() == NULL) + call.path (path().c_str()); - if (call.destination() == NULL) - call.destination(service().c_str()); + if (call.destination() == NULL) + call.destination (service().c_str()); - return conn().send(call); + return conn().send (call); } -bool ObjectProxy::handle_message(const Message &msg) +bool ObjectProxy::handle_message (const Message &msg) { - switch (msg.type()) - { - case DBUS_MESSAGE_TYPE_SIGNAL: - { - const SignalMessage &smsg = reinterpret_cast<const SignalMessage &>(msg); - const char *interface = smsg.interface(); - const char *member = smsg.member(); - const char *objpath = smsg.path(); - - if (objpath != path()) return false; - - debug_log("filtered signal %s(in %s) from %s to object %s", - member, interface, msg.sender(), objpath); - - InterfaceProxy *ii = find_interface(interface); - if (ii) - { - return ii->dispatch_signal(smsg); - } - else - { - return false; - } - } - default: - { - return false; - } - } + switch (msg.type()) { + + case DBUS_MESSAGE_TYPE_SIGNAL: { + const SignalMessage &smsg = reinterpret_cast<const SignalMessage &> (msg); + + const char *interface = smsg.interface(); + const char *member = smsg.member(); + const char *objpath = smsg.path(); + + if (objpath != path()) return false; + + debug_log ("filtered signal %s(in %s) from %s to object %s", + member, interface, msg.sender(), objpath); + + InterfaceProxy *ii = find_interface (interface); + + if (ii) { + return ii->dispatch_signal (smsg); + } else { + return false; + } + } + + default: { + return false; + } + } } diff --git a/sflphone-common/libs/dbus-c++/src/pendingcall.cpp b/sflphone-common/libs/dbus-c++/src/pendingcall.cpp index 3757d8fd1d..775561c21c 100644 --- a/sflphone-common/libs/dbus-c++/src/pendingcall.cpp +++ b/sflphone-common/libs/dbus-c++/src/pendingcall.cpp @@ -35,108 +35,104 @@ using namespace DBus; -PendingCall::Private::Private(DBusPendingCall *dpc) -: call(dpc), dataslot(-1) +PendingCall::Private::Private (DBusPendingCall *dpc) + : call (dpc), dataslot (-1) { - if (!dbus_pending_call_allocate_data_slot(&dataslot)) - { - throw ErrorNoMemory("Unable to allocate data slot"); - } + if (!dbus_pending_call_allocate_data_slot (&dataslot)) { + throw ErrorNoMemory ("Unable to allocate data slot"); + } } PendingCall::Private::~Private() { - if (dataslot != -1) - { - dbus_pending_call_allocate_data_slot(&dataslot); - } + if (dataslot != -1) { + dbus_pending_call_allocate_data_slot (&dataslot); + } } -void PendingCall::Private::notify_stub(DBusPendingCall *dpc, void *data) +void PendingCall::Private::notify_stub (DBusPendingCall *dpc, void *data) { - PendingCall::Private *pvt = static_cast<PendingCall::Private *>(data); + PendingCall::Private *pvt = static_cast<PendingCall::Private *> (data); - PendingCall pc(pvt); - pvt->slot(pc); + PendingCall pc (pvt); + pvt->slot (pc); } -PendingCall::PendingCall(PendingCall::Private *p) -: _pvt(p) +PendingCall::PendingCall (PendingCall::Private *p) + : _pvt (p) { - if (!dbus_pending_call_set_notify(_pvt->call, Private::notify_stub, p, NULL)) - { - throw ErrorNoMemory("Unable to initialize pending call"); - } + if (!dbus_pending_call_set_notify (_pvt->call, Private::notify_stub, p, NULL)) { + throw ErrorNoMemory ("Unable to initialize pending call"); + } } -PendingCall::PendingCall(const PendingCall &c) -: _pvt(c._pvt) +PendingCall::PendingCall (const PendingCall &c) + : _pvt (c._pvt) { - dbus_pending_call_ref(_pvt->call); + dbus_pending_call_ref (_pvt->call); } PendingCall::~PendingCall() { - dbus_pending_call_unref(_pvt->call); + dbus_pending_call_unref (_pvt->call); } PendingCall &PendingCall::operator = (const PendingCall &c) { - if (&c != this) - { - dbus_pending_call_unref(_pvt->call); - _pvt = c._pvt; - dbus_pending_call_ref(_pvt->call); - } - return *this; + if (&c != this) { + dbus_pending_call_unref (_pvt->call); + _pvt = c._pvt; + dbus_pending_call_ref (_pvt->call); + } + + return *this; } bool PendingCall::completed() { - return dbus_pending_call_get_completed(_pvt->call); + return dbus_pending_call_get_completed (_pvt->call); } void PendingCall::cancel() { - dbus_pending_call_cancel(_pvt->call); + dbus_pending_call_cancel (_pvt->call); } void PendingCall::block() { - dbus_pending_call_block(_pvt->call); + dbus_pending_call_block (_pvt->call); } -void PendingCall::data(void *p) +void PendingCall::data (void *p) { - if (!dbus_pending_call_set_data(_pvt->call, _pvt->dataslot, p, NULL)) - { - throw ErrorNoMemory("Unable to initialize data slot"); - } + if (!dbus_pending_call_set_data (_pvt->call, _pvt->dataslot, p, NULL)) { + throw ErrorNoMemory ("Unable to initialize data slot"); + } } void *PendingCall::data() { - return dbus_pending_call_get_data(_pvt->call, _pvt->dataslot); + return dbus_pending_call_get_data (_pvt->call, _pvt->dataslot); } Slot<void, PendingCall &>& PendingCall::slot() { - return _pvt->slot; + return _pvt->slot; } Message PendingCall::steal_reply() { - DBusMessage *dmsg = dbus_pending_call_steal_reply(_pvt->call); - if (!dmsg) - { - dbus_bool_t callComplete = dbus_pending_call_get_completed(_pvt->call); - - if (callComplete) - throw ErrorNoReply("No reply available"); - else - throw ErrorNoReply("Call not complete"); - } - - return Message(new Message::Private(dmsg)); + DBusMessage *dmsg = dbus_pending_call_steal_reply (_pvt->call); + + if (!dmsg) { + dbus_bool_t callComplete = dbus_pending_call_get_completed (_pvt->call); + + if (callComplete) + throw ErrorNoReply ("No reply available"); + else + throw ErrorNoReply ("Call not complete"); + } + + return Message (new Message::Private (dmsg)); } diff --git a/sflphone-common/libs/dbus-c++/src/property.cpp b/sflphone-common/libs/dbus-c++/src/property.cpp index 15a2f5bcbd..e8b02fdade 100644 --- a/sflphone-common/libs/dbus-c++/src/property.cpp +++ b/sflphone-common/libs/dbus-c++/src/property.cpp @@ -35,120 +35,115 @@ using namespace DBus; static const char *properties_name = "org.freedesktop.DBus.Properties"; PropertiesAdaptor::PropertiesAdaptor() -: InterfaceAdaptor(properties_name) + : InterfaceAdaptor (properties_name) { - register_method(PropertiesAdaptor, Get, Get); - register_method(PropertiesAdaptor, Set, Set); + register_method (PropertiesAdaptor, Get, Get); + register_method (PropertiesAdaptor, Set, Set); } -Message PropertiesAdaptor::Get(const CallMessage &call) +Message PropertiesAdaptor::Get (const CallMessage &call) { - MessageIter ri = call.reader(); + MessageIter ri = call.reader(); - std::string iface_name; - std::string property_name; + std::string iface_name; + std::string property_name; - ri >> iface_name >> property_name; + ri >> iface_name >> property_name; - debug_log("requesting property %s on interface %s", property_name.c_str(), iface_name.c_str()); + debug_log ("requesting property %s on interface %s", property_name.c_str(), iface_name.c_str()); - InterfaceAdaptor *interface = (InterfaceAdaptor *) find_interface(iface_name); + InterfaceAdaptor *interface = (InterfaceAdaptor *) find_interface (iface_name); - if (!interface) - throw ErrorFailed("requested interface not found"); + if (!interface) + throw ErrorFailed ("requested interface not found"); - Variant *value = interface->get_property(property_name); + Variant *value = interface->get_property (property_name); - if (!value) - throw ErrorFailed("requested property not found"); + if (!value) + throw ErrorFailed ("requested property not found"); - on_get_property(*interface, property_name, *value); + on_get_property (*interface, property_name, *value); - ReturnMessage reply(call); + ReturnMessage reply (call); - MessageIter wi = reply.writer(); + MessageIter wi = reply.writer(); - wi << *value; - return reply; + wi << *value; + + return reply; } -Message PropertiesAdaptor::Set(const CallMessage &call) +Message PropertiesAdaptor::Set (const CallMessage &call) { - MessageIter ri = call.reader(); + MessageIter ri = call.reader(); - std::string iface_name; - std::string property_name; - Variant value; + std::string iface_name; + std::string property_name; + Variant value; - ri >> iface_name >> property_name >> value; + ri >> iface_name >> property_name >> value; - InterfaceAdaptor *interface = (InterfaceAdaptor *) find_interface(iface_name); + InterfaceAdaptor *interface = (InterfaceAdaptor *) find_interface (iface_name); - if (!interface) - throw ErrorFailed("requested interface not found"); + if (!interface) + throw ErrorFailed ("requested interface not found"); - on_set_property(*interface, property_name, value); + on_set_property (*interface, property_name, value); - interface->set_property(property_name, value); + interface->set_property (property_name, value); - ReturnMessage reply(call); + ReturnMessage reply (call); - return reply; + return reply; } IntrospectedInterface *const PropertiesAdaptor::introspect() const { - static IntrospectedArgument Get_args[] = - { - { "interface_name", "s", true }, - { "property_name", "s", true }, - { "value", "v", false }, - { 0, 0, 0 } - }; - static IntrospectedArgument Set_args[] = - { - { "interface_name", "s", true }, - { "property_name", "s", true }, - { "value", "v", true }, - { 0, 0, 0 } - }; - static IntrospectedMethod Properties_methods[] = - { - { "Get", Get_args }, - { "Set", Set_args }, - { 0, 0 } - }; - static IntrospectedMethod Properties_signals[] = - { - { 0, 0 } - }; - static IntrospectedProperty Properties_properties[] = - { - { 0, 0, 0, 0 } - }; - static IntrospectedInterface Properties_interface = - { - properties_name, - Properties_methods, - Properties_signals, - Properties_properties - }; - return &Properties_interface; + static IntrospectedArgument Get_args[] = { + { "interface_name", "s", true }, + { "property_name", "s", true }, + { "value", "v", false }, + { 0, 0, 0 } + }; + static IntrospectedArgument Set_args[] = { + { "interface_name", "s", true }, + { "property_name", "s", true }, + { "value", "v", true }, + { 0, 0, 0 } + }; + static IntrospectedMethod Properties_methods[] = { + { "Get", Get_args }, + { "Set", Set_args }, + { 0, 0 } + }; + static IntrospectedMethod Properties_signals[] = { + { 0, 0 } + }; + static IntrospectedProperty Properties_properties[] = { + { 0, 0, 0, 0 } + }; + static IntrospectedInterface Properties_interface = { + properties_name, + Properties_methods, + Properties_signals, + Properties_properties + }; + return &Properties_interface; } PropertiesProxy::PropertiesProxy() -: InterfaceProxy(properties_name) + : InterfaceProxy (properties_name) { } -Variant PropertiesProxy::Get(const std::string &iface, const std::string &property) +Variant PropertiesProxy::Get (const std::string &iface, const std::string &property) { //todo - Variant v; - return v; + Variant v; + return v; } -void PropertiesProxy::Set(const std::string &iface, const std::string &property, const Variant &value) +void PropertiesProxy::Set (const std::string &iface, const std::string &property, const Variant &value) { //todo } diff --git a/sflphone-common/libs/dbus-c++/src/server.cpp b/sflphone-common/libs/dbus-c++/src/server.cpp index 0c652e5510..b3dbfe267b 100644 --- a/sflphone-common/libs/dbus-c++/src/server.cpp +++ b/sflphone-common/libs/dbus-c++/src/server.cpp @@ -35,8 +35,8 @@ using namespace DBus; -Server::Private::Private(DBusServer *s) -: server(s) +Server::Private::Private (DBusServer *s) + : server (s) { } @@ -44,34 +44,35 @@ Server::Private::~Private() { } -void Server::Private::on_new_conn_cb(DBusServer *server, DBusConnection *conn, void *data) +void Server::Private::on_new_conn_cb (DBusServer *server, DBusConnection *conn, void *data) { - Server *s = static_cast<Server *>(data); + Server *s = static_cast<Server *> (data); - Connection nc (new Connection::Private(conn, s->_pvt.get())); + Connection nc (new Connection::Private (conn, s->_pvt.get())); - s->_pvt->connections.push_back(nc); + s->_pvt->connections.push_back (nc); - s->on_new_connection(nc); + s->on_new_connection (nc); - debug_log("incoming connection 0x%08x", conn); + debug_log ("incoming connection 0x%08x", conn); } -Server::Server(const char *address) +Server::Server (const char *address) { - InternalError e; - DBusServer *server = dbus_server_listen(address, e); + InternalError e; + DBusServer *server = dbus_server_listen (address, e); - if (e) throw Error(e); + if (e) throw Error (e); - debug_log("server 0x%08x listening on %s", server, address); + debug_log ("server 0x%08x listening on %s", server, address); - _pvt = new Private(server); + _pvt = new Private (server); - dbus_server_set_new_connection_function(_pvt->server, Private::on_new_conn_cb, this, NULL); + dbus_server_set_new_connection_function (_pvt->server, Private::on_new_conn_cb, this, NULL); - setup(default_dispatcher); + setup (default_dispatcher); } + /* Server::Server(const Server &s) : _pvt(s._pvt) @@ -81,49 +82,50 @@ Server::Server(const Server &s) */ Server::~Server() { - dbus_server_unref(_pvt->server); + dbus_server_unref (_pvt->server); } -Dispatcher *Server::setup(Dispatcher *dispatcher) +Dispatcher *Server::setup (Dispatcher *dispatcher) { - debug_log("registering stubs for server %p", _pvt->server); - - Dispatcher *prev = _pvt->dispatcher; - - dbus_server_set_watch_functions( - _pvt->server, - Dispatcher::Private::on_add_watch, - Dispatcher::Private::on_rem_watch, - Dispatcher::Private::on_toggle_watch, - dispatcher, - 0 - ); - - dbus_server_set_timeout_functions( - _pvt->server, - Dispatcher::Private::on_add_timeout, - Dispatcher::Private::on_rem_timeout, - Dispatcher::Private::on_toggle_timeout, - dispatcher, - 0 - ); - - _pvt->dispatcher = dispatcher; - - return prev; + debug_log ("registering stubs for server %p", _pvt->server); + + Dispatcher *prev = _pvt->dispatcher; + + dbus_server_set_watch_functions ( + _pvt->server, + Dispatcher::Private::on_add_watch, + Dispatcher::Private::on_rem_watch, + Dispatcher::Private::on_toggle_watch, + dispatcher, + 0 + ); + + dbus_server_set_timeout_functions ( + _pvt->server, + Dispatcher::Private::on_add_timeout, + Dispatcher::Private::on_rem_timeout, + Dispatcher::Private::on_toggle_timeout, + dispatcher, + 0 + ); + + _pvt->dispatcher = dispatcher; + + return prev; } bool Server::operator == (const Server &s) const { - return _pvt->server == s._pvt->server; + return _pvt->server == s._pvt->server; } bool Server::listening() const { - return dbus_server_get_is_connected(_pvt->server); + return dbus_server_get_is_connected (_pvt->server); } + void Server::disconnect() { - dbus_server_disconnect(_pvt->server); + dbus_server_disconnect (_pvt->server); } diff --git a/sflphone-common/libs/dbus-c++/src/types.cpp b/sflphone-common/libs/dbus-c++/src/types.cpp index 117cca30b5..d8100258e6 100644 --- a/sflphone-common/libs/dbus-c++/src/types.cpp +++ b/sflphone-common/libs/dbus-c++/src/types.cpp @@ -37,70 +37,71 @@ using namespace DBus; Variant::Variant() -: _msg(CallMessage()) // dummy message used as temporary storage for variant data + : _msg (CallMessage()) // dummy message used as temporary storage for variant data { } -Variant::Variant(MessageIter &it) -: _msg(CallMessage()) +Variant::Variant (MessageIter &it) + : _msg (CallMessage()) { - MessageIter vi = it.recurse(); - MessageIter mi = _msg.writer(); - vi.copy_data(mi); + MessageIter vi = it.recurse(); + MessageIter mi = _msg.writer(); + vi.copy_data (mi); } Variant &Variant::operator = (const Variant &v) { - if (&v != this) - { - _msg = v._msg; - } - return *this; + if (&v != this) { + _msg = v._msg; + } + + return *this; } void Variant::clear() { - CallMessage empty; - _msg = empty; + CallMessage empty; + _msg = empty; } const Signature Variant::signature() const { - char *sigbuf = reader().signature(); + char *sigbuf = reader().signature(); - Signature signature = sigbuf; + Signature signature = sigbuf; - free(sigbuf); + free (sigbuf); - return signature; + return signature; } MessageIter &operator << (MessageIter &iter, const Variant &val) { - const Signature sig = val.signature(); + const Signature sig = val.signature(); - MessageIter rit = val.reader(); - MessageIter wit = iter.new_variant(sig.c_str()); + MessageIter rit = val.reader(); + MessageIter wit = iter.new_variant (sig.c_str()); - rit.copy_data(wit); + rit.copy_data (wit); - iter.close_container(wit); + iter.close_container (wit); - return iter; + return iter; } MessageIter &operator >> (MessageIter &iter, Variant &val) { - if (iter.type() != DBUS_TYPE_VARIANT) - throw ErrorInvalidArgs("variant type expected"); + if (iter.type() != DBUS_TYPE_VARIANT) + throw ErrorInvalidArgs ("variant type expected"); + + val.clear(); - val.clear(); + MessageIter vit = iter.recurse(); - MessageIter vit = iter.recurse(); - MessageIter mit = val.writer(); + MessageIter mit = val.writer(); - vit.copy_data(mit); + vit.copy_data (mit); - return ++iter; + return ++iter; } diff --git a/sflphone-common/libs/dbus-c++/tools/generate_adaptor.cpp b/sflphone-common/libs/dbus-c++/tools/generate_adaptor.cpp index 891ecfc3c2..c8f0cd6abb 100644 --- a/sflphone-common/libs/dbus-c++/tools/generate_adaptor.cpp +++ b/sflphone-common/libs/dbus-c++/tools/generate_adaptor.cpp @@ -30,6 +30,7 @@ #include "generate_adaptor.h" using namespace std; + using namespace DBus; extern const char *tab; @@ -38,685 +39,654 @@ extern const char *dbus_includes; /*! Generate adaptor code for a XML introspection */ -void generate_adaptor(Xml::Document &doc, const char *filename) +void generate_adaptor (Xml::Document &doc, const char *filename) { - ostringstream body; - ostringstream head; - vector <string> include_vector; - - head << header; - string filestring = filename; - underscorize(filestring); - - string cond_comp = "__dbusxx__" + filestring + "__ADAPTOR_MARSHAL_H"; - - head << "#ifndef " << cond_comp << endl - << "#define " << cond_comp << endl; - - head << dbus_includes; - - Xml::Node &root = *(doc.root); - Xml::Nodes interfaces = root["interface"]; - - // iterate over all interface definitions - for (Xml::Nodes::iterator i = interfaces.begin(); i != interfaces.end(); ++i) - { - Xml::Node &iface = **i; - Xml::Nodes methods = iface["method"]; - Xml::Nodes signals = iface["signal"]; - Xml::Nodes properties = iface["property"]; - Xml::Nodes ms; - ms.insert(ms.end(), methods.begin(), methods.end()); - ms.insert(ms.end(), signals.begin(), signals.end()); - - // gets the name of a interface: <interface name="XYZ"> - string ifacename = iface.get("name"); - - // these interface names are skipped. - if (ifacename == "org.freedesktop.DBus.Introspectable" - ||ifacename == "org.freedesktop.DBus.Properties") - { - cerr << "skipping interface " << ifacename << endl; - continue; - } - - istringstream ss(ifacename); - string nspace; - unsigned int nspaces = 0; - - // prints all the namespaces defined with <interface name="X.Y.Z"> - while (ss.str().find('.', ss.tellg()) != string::npos) - { - getline(ss, nspace, '.'); - - body << "namespace " << nspace << " {" << endl; - - ++nspaces; - } - body << endl; - - string ifaceclass; - - getline(ss, ifaceclass); + ostringstream body; + ostringstream head; + vector <string> include_vector; + + head << header; + string filestring = filename; + underscorize (filestring); + + string cond_comp = "__dbusxx__" + filestring + "__ADAPTOR_MARSHAL_H"; + + head << "#ifndef " << cond_comp << endl + << "#define " << cond_comp << endl; + + head << dbus_includes; + + Xml::Node &root = * (doc.root); + Xml::Nodes interfaces = root["interface"]; + + // iterate over all interface definitions + + for (Xml::Nodes::iterator i = interfaces.begin(); i != interfaces.end(); ++i) { + Xml::Node &iface = **i; + Xml::Nodes methods = iface["method"]; + Xml::Nodes signals = iface["signal"]; + Xml::Nodes properties = iface["property"]; + Xml::Nodes ms; + ms.insert (ms.end(), methods.begin(), methods.end()); + ms.insert (ms.end(), signals.begin(), signals.end()); + + // gets the name of a interface: <interface name="XYZ"> + string ifacename = iface.get ("name"); + + // these interface names are skipped. + + if (ifacename == "org.freedesktop.DBus.Introspectable" + ||ifacename == "org.freedesktop.DBus.Properties") { + cerr << "skipping interface " << ifacename << endl; + continue; + } + + istringstream ss (ifacename); + + string nspace; + unsigned int nspaces = 0; + + // prints all the namespaces defined with <interface name="X.Y.Z"> + + while (ss.str().find ('.', ss.tellg()) != string::npos) { + getline (ss, nspace, '.'); + + body << "namespace " << nspace << " {" << endl; + + ++nspaces; + } + + body << endl; + + string ifaceclass; + + getline (ss, ifaceclass); // a "_adaptor" is added to class name to distinguish between proxy and adaptor - ifaceclass += "_adaptor"; + ifaceclass += "_adaptor"; - cerr << "generating code for interface " << ifacename << "..." << endl; + cerr << "generating code for interface " << ifacename << "..." << endl; // the code from class definiton up to opening of the constructor is generated... - body << "class " << ifaceclass << endl - << ": public ::DBus::InterfaceAdaptor" << endl - << "{" << endl - << "public:" << endl - << endl - << tab << ifaceclass << "()" << endl - << tab << ": ::DBus::InterfaceAdaptor(\"" << ifacename << "\")" << endl - << tab << "{" << endl; + body << "class " << ifaceclass << endl + << ": public ::DBus::InterfaceAdaptor" << endl + << "{" << endl + << "public:" << endl + << endl + << tab << ifaceclass << "()" << endl + << tab << ": ::DBus::InterfaceAdaptor(\"" << ifacename << "\")" << endl + << tab << "{" << endl; // generates code to bind the properties - for (Xml::Nodes::iterator pi = properties.begin(); pi != properties.end(); ++pi) - { - Xml::Node &property = **pi; - - body << tab << tab << "bind_property(" - << property.get("name") << ", " - << "\"" << property.get("type") << "\", " - << (property.get("access").find("read") != string::npos - ? "true" - : "false") - << ", " - << (property.get("access").find("write") != string::npos - ? "true" - : "false") - << ");" << endl; - } - - // generate code to register all methods - for (Xml::Nodes::iterator mi = methods.begin(); mi != methods.end(); ++mi) - { - Xml::Node &method = **mi; - - body << tab << tab << "register_method(" - << ifaceclass << ", " << method.get("name") << ", "<< stub_name(method.get("name")) - << ");" << endl; - } - - body << tab << "}" << endl - << endl; - - body << tab << "::DBus::IntrospectedInterface *const introspect() const " << endl - << tab << "{" << endl; - - // generate the introspect arguments - for (Xml::Nodes::iterator mi = ms.begin(); mi != ms.end(); ++mi) - { - Xml::Node &method = **mi; - Xml::Nodes args = method["arg"]; - - body << tab << tab << "static ::DBus::IntrospectedArgument " << method.get("name") << "_args[] = " << endl - << tab << tab << "{" << endl; - - for (Xml::Nodes::iterator ai = args.begin(); ai != args.end(); ++ai) - { - Xml::Node &arg = **ai; - - body << tab << tab << tab << "{ "; - - if (arg.get("name").length()) - { - body << "\"" << arg.get("name") << "\", "; - } - else - { - body << "0, "; - } - body << "\"" << arg.get("type") << "\", " - << (arg.get("direction") == "in" ? "true" : "false") - << " }," << endl; - } - body << tab << tab << tab << "{ 0, 0, 0 }" << endl - << tab << tab << "};" << endl; - } - - body << tab << tab << "static ::DBus::IntrospectedMethod " << ifaceclass << "_methods[] = " << endl - << tab << tab << "{" << endl; - - // generate the introspect methods - for (Xml::Nodes::iterator mi = methods.begin(); mi != methods.end(); ++mi) - { - Xml::Node &method = **mi; - - body << tab << tab << tab << "{ \"" << method.get("name") << "\", " << method.get("name") << "_args }," << endl; - } - - body << tab << tab << tab << "{ 0, 0 }" << endl - << tab << tab << "};" << endl; - - body << tab << tab << "static ::DBus::IntrospectedMethod " << ifaceclass << "_signals[] = " << endl - << tab << tab << "{" << endl; - - for (Xml::Nodes::iterator si = signals.begin(); si != signals.end(); ++si) - { - Xml::Node &method = **si; - - body << tab << tab << tab << "{ \"" << method.get("name") << "\", " << method.get("name") << "_args }," << endl; - } - - body << tab << tab << tab << "{ 0, 0 }" << endl - << tab << tab << "};" << endl; - - body << tab << tab << "static ::DBus::IntrospectedProperty " << ifaceclass << "_properties[] = " << endl - << tab << tab << "{" << endl; - - for (Xml::Nodes::iterator pi = properties.begin(); pi != properties.end(); ++pi) - { - Xml::Node &property = **pi; - - body << tab << tab << tab << "{ " - << "\"" << property.get("name") << "\", " - << "\"" << property.get("type") << "\", " - << (property.get("access").find("read") != string::npos - ? "true" - : "false") - << ", " - << (property.get("access").find("write") != string::npos - ? "true" - : "false") - << " }," << endl; - } - - - body << tab << tab << tab << "{ 0, 0, 0, 0 }" << endl - << tab << tab << "};" << endl; - - // generate the Introspected interface - body << tab << tab << "static ::DBus::IntrospectedInterface " << ifaceclass << "_interface = " << endl - << tab << tab << "{" << endl - << tab << tab << tab << "\"" << ifacename << "\"," << endl - << tab << tab << tab << ifaceclass << "_methods," << endl - << tab << tab << tab << ifaceclass << "_signals," << endl - << tab << tab << tab << ifaceclass << "_properties" << endl - << tab << tab << "};" << endl - << tab << tab << "return &" << ifaceclass << "_interface;" << endl - << tab << "}" << endl - << endl; - - body << "public:" << endl - << endl - << tab << "/* properties exposed by this interface, use" << endl - << tab << " * property() and property(value) to get and set a particular property" << endl - << tab << " */" << endl; - - // generate the properties code - for (Xml::Nodes::iterator pi = properties.begin(); pi != properties.end(); ++pi) - { - Xml::Node &property = **pi; - string name = property.get("name"); - string type = property.get("type"); - string type_name = signature_to_type(type); - - body << tab << "::DBus::PropertyAdaptor< " << type_name << " > " << name << ";" << endl; - } - - body << endl; - - body << "public:" << endl - << endl - << tab << "/* methods exported by this interface," << endl - << tab << " * you will have to implement them in your ObjectAdaptor" << endl - << tab << " */" << endl; - - // generate the methods code - for (Xml::Nodes::iterator mi = methods.begin(); mi != methods.end(); ++mi) - { - Xml::Node &method = **mi; - Xml::Nodes args = method["arg"]; - Xml::Nodes args_in = args.select("direction","in"); - Xml::Nodes args_out = args.select("direction","out"); - Xml::Nodes annotations = args["annotation"]; - Xml::Nodes annotations_object = annotations.select("name","org.freedesktop.DBus.Object"); - string arg_object; - - if (annotations_object.size() > 0) - { - arg_object = annotations_object.front()->get("value"); - } - - body << tab << "virtual "; - - // return type is 'void' if none or multible return values - if (args_out.size() == 0 || args_out.size() > 1) - { - body << "void "; - } - else if (args_out.size() == 1) - { - // generate basic or object return type - if (arg_object.length()) - { - body << arg_object << " "; - } - else - { - body << signature_to_type(args_out.front()->get("type")) << " "; - } - } - - // generate the method name - body << method.get("name") << "("; - - // generate the methods 'in' variables - unsigned int i = 0; - for (Xml::Nodes::iterator ai = args_in.begin(); ai != args_in.end(); ++ai, ++i) - { - Xml::Node &arg = **ai; - Xml::Nodes annotations = arg["annotation"]; - Xml::Nodes annotations_object = annotations.select("name","org.freedesktop.DBus.Object"); - string arg_name = arg.get("name"); - string arg_object; - - if (annotations_object.size() > 0) - { - arg_object = annotations_object.front()->get("value"); - } - - // generate basic signature only if no object name available... - if (!arg_object.length()) - { - body << "const " << signature_to_type(arg.get("type")) << "& "; - } - // ...or generate object style if available - else - { - body << "const " << arg_object << "& "; - - // store a object name to later generate header includes - include_vector.push_back (arg_object); + + for (Xml::Nodes::iterator pi = properties.begin(); pi != properties.end(); ++pi) { + Xml::Node &property = **pi; + + body << tab << tab << "bind_property(" + << property.get ("name") << ", " + << "\"" << property.get ("type") << "\", " + << (property.get ("access").find ("read") != string::npos + ? "true" + : "false") + << ", " + << (property.get ("access").find ("write") != string::npos + ? "true" + : "false") + << ");" << endl; } - if (arg_name.length()) - body << arg_name; - - if ((i+1 != args_in.size() || args_out.size() > 1)) - body << ", "; - } - - // generate the method 'out' variables if multibe 'out' values exist - if (args_out.size() > 1) - { - unsigned int i = 0; - for (Xml::Nodes::iterator ao = args_out.begin(); ao != args_out.end(); ++ao, ++i) - { - Xml::Node &arg = **ao; - Xml::Nodes annotations = arg["annotation"]; - Xml::Nodes annotations_object = annotations.select("name","org.freedesktop.DBus.Object"); - string arg_name = arg.get("name"); - string arg_object; - - if (annotations_object.size() > 0) - { - arg_object = annotations_object.front()->get("value"); - } - - // generate basic signature only if no object name available... - if (!arg_object.length()) - { - body << "const " << signature_to_type(arg.get("type")) << "& "; - } - // ...or generate object style if available - else - { - body << "const " << arg_object << "& "; - - // store a object name to later generate header includes - include_vector.push_back (arg_object); - } - - if (arg_name.length()) - body << " " << arg_name; - - if (i+1 != args_out.size()) - body << ", "; - } - } - body << ") = 0;" << endl; - } - - body << endl - << "public:" << endl - << endl - << tab << "/* signal emitters for this interface" << endl - << tab << " */" << endl; - - // generate the signals code - for (Xml::Nodes::iterator si = signals.begin(); si != signals.end(); ++si) - { - Xml::Node &signal = **si; - Xml::Nodes args = signal["arg"]; - - body << tab << "void " << signal.get("name") << "("; - - // generate the signal arguments - unsigned int i = 0; - for (Xml::Nodes::iterator a = args.begin(); a != args.end(); ++a, ++i) - { - Xml::Node &arg = **a; - Xml::Nodes annotations = arg["annotation"]; - Xml::Nodes annotations_object = annotations.select("name","org.freedesktop.DBus.Object"); - string arg_object; - - if (annotations_object.size() > 0) - { - arg_object = annotations_object.front()->get("value"); - } - - // generate basic signature only if no object name available... - if (!arg_object.length()) - { - body << "const " << signature_to_type(arg.get("type")) << "& arg" << i+1; + // generate code to register all methods + for (Xml::Nodes::iterator mi = methods.begin(); mi != methods.end(); ++mi) { + Xml::Node &method = **mi; + + body << tab << tab << "register_method(" + << ifaceclass << ", " << method.get ("name") << ", "<< stub_name (method.get ("name")) + << ");" << endl; } - // ...or generate object style if available - else - { - body << "const " << arg_object << "& arg" << i+1; - - // store a object name to later generate header includes - include_vector.push_back (arg_object); + + body << tab << "}" << endl + + << endl; + + body << tab << "::DBus::IntrospectedInterface *const introspect() const " << endl + << tab << "{" << endl; + + // generate the introspect arguments + + for (Xml::Nodes::iterator mi = ms.begin(); mi != ms.end(); ++mi) { + Xml::Node &method = **mi; + Xml::Nodes args = method["arg"]; + + body << tab << tab << "static ::DBus::IntrospectedArgument " << method.get ("name") << "_args[] = " << endl + << tab << tab << "{" << endl; + + for (Xml::Nodes::iterator ai = args.begin(); ai != args.end(); ++ai) { + Xml::Node &arg = **ai; + + body << tab << tab << tab << "{ "; + + if (arg.get ("name").length()) { + body << "\"" << arg.get ("name") << "\", "; + } else { + body << "0, "; + } + + body << "\"" << arg.get ("type") << "\", " + + << (arg.get ("direction") == "in" ? "true" : "false") + << " }," << endl; + } + + body << tab << tab << tab << "{ 0, 0, 0 }" << endl + + << tab << tab << "};" << endl; } - - if (i+1 != args.size()) - body << ", "; - } - - body << ")" << endl - << tab << "{" << endl - << tab << tab << "::DBus::SignalMessage sig(\"" << signal.get("name") <<"\");" << endl; - - // generate the signal body - if (args.size() > 0) - { - body << tab << tab << "::DBus::MessageIter wi = sig.writer();" << endl; - - unsigned int i = 0; - for (Xml::Nodes::iterator a = args.begin(); a != args.end(); ++a, ++i) - { - Xml::Node &arg = **a; - Xml::Nodes annotations = arg["annotation"]; - Xml::Nodes annotations_object = annotations.select("name","org.freedesktop.DBus.Object"); - string arg_object; - - if (annotations_object.size() > 0) - { - arg_object = annotations_object.front()->get("value"); - } - - if (arg_object.length()) - { - body << tab << tab << signature_to_type(arg.get("type")) << " _arg" << i+1 << ";" << endl; - body << tab << tab << "_arg" << i+1 << " << " << "arg" << i+1 << ";" << endl; - - body << tab << tab << "wi << _arg" << i+1 << ";" << endl; - } - else - { - body << tab << tab << "wi << arg" << i+1 << ";" << endl; - } - } - } - - // emit the signal in method body - body << tab << tab << "emit_signal(sig);" << endl - << tab << "}" << endl; - } - - body << endl - << "private:" << endl - << endl - << tab << "/* unmarshalers (to unpack the DBus message before calling the actual interface method)" << endl - << tab << " */" << endl; - - // generate the unmarshalers - for (Xml::Nodes::iterator mi = methods.begin(); mi != methods.end(); ++mi) - { - Xml::Node &method = **mi; - Xml::Nodes args = method["arg"]; - Xml::Nodes args_in = args.select("direction","in"); - Xml::Nodes args_out = args.select("direction","out"); - - body << tab << "::DBus::Message " << stub_name(method.get("name")) << "(const ::DBus::CallMessage &call)" << endl - << tab << "{" << endl - << tab << tab << "::DBus::MessageIter ri = call.reader();" << endl - << endl; - - // generate the 'in' variables - unsigned int i = 1; - for (Xml::Nodes::iterator ai = args_in.begin(); ai != args_in.end(); ++ai, ++i) - { - Xml::Node &arg = **ai; - - body << tab << tab << signature_to_type(arg.get("type")) << " argin" << i << ";" << " "; - body << "ri >> argin" << i << ";" << endl; - } - - // generate the 'in' object variables - i = 1; - for (Xml::Nodes::iterator ai = args_in.begin(); ai != args_in.end(); ++ai, ++i) - { - Xml::Node &arg = **ai; - Xml::Nodes annotations = arg["annotation"]; - Xml::Nodes annotations_object = annotations.select("name","org.freedesktop.DBus.Object"); - string arg_object; - - if (annotations_object.size() > 0) - { - arg_object = annotations_object.front()->get("value"); + + body << tab << tab << "static ::DBus::IntrospectedMethod " << ifaceclass << "_methods[] = " << endl + + << tab << tab << "{" << endl; + + // generate the introspect methods + + for (Xml::Nodes::iterator mi = methods.begin(); mi != methods.end(); ++mi) { + Xml::Node &method = **mi; + + body << tab << tab << tab << "{ \"" << method.get ("name") << "\", " << method.get ("name") << "_args }," << endl; } - - if (arg_object.length()) - { - body << tab << tab << arg_object << " _argin" << i << ";"; - body << " " << "_argin" << i << " << " << "argin" << i << ";" << endl; + + body << tab << tab << tab << "{ 0, 0 }" << endl + + << tab << tab << "};" << endl; + + body << tab << tab << "static ::DBus::IntrospectedMethod " << ifaceclass << "_signals[] = " << endl + << tab << tab << "{" << endl; + + for (Xml::Nodes::iterator si = signals.begin(); si != signals.end(); ++si) { + Xml::Node &method = **si; + + body << tab << tab << tab << "{ \"" << method.get ("name") << "\", " << method.get ("name") << "_args }," << endl; } - } - - // generate 'out' variables - if (args_out.size() > 0) - { - unsigned int i = 1; - for (Xml::Nodes::iterator ao = args_out.begin(); ao != args_out.end(); ++ao, ++i) - { - Xml::Node &arg = **ao; - - body << tab << tab << signature_to_type(arg.get("type")) << " argout" << i; - - if (args_out.size() == 1) // a single 'out' parameter will be assigned - { - body << " = "; - } - else // multible 'out' parameters will be handled as parameters below - { - body << ";" << endl; - } - } - } - - // generate 'out' object variables - if (args_out.size() > 0) - { - unsigned int i = 1; - for (Xml::Nodes::iterator ao = args_out.begin(); ao != args_out.end(); ++ao, ++i) - { - Xml::Node &arg = **ao; - Xml::Nodes annotations = arg["annotation"]; - Xml::Nodes annotations_object = annotations.select("name","org.freedesktop.DBus.Object"); - string arg_object; - - if (annotations_object.size() > 0) - { - arg_object = annotations_object.front()->get("value"); - } - - // generate object types - if (arg_object.length()) - { - body << tab << tab << arg_object << " _argout" << i << ";" << endl; - } - } - } - - // generate in '<<' operation - i = 0; - for (Xml::Nodes::iterator ai = args_in.begin(); ai != args_in.end(); ++ai, ++i) - { - Xml::Node &arg = **ai; - Xml::Nodes annotations = arg["annotation"]; - Xml::Nodes annotations_object = annotations.select("name","org.freedesktop.DBus.Object"); - string arg_object; - - if (annotations_object.size() > 0) - { - arg_object = annotations_object.front()->get("value"); + + body << tab << tab << tab << "{ 0, 0 }" << endl + + << tab << tab << "};" << endl; + + body << tab << tab << "static ::DBus::IntrospectedProperty " << ifaceclass << "_properties[] = " << endl + << tab << tab << "{" << endl; + + for (Xml::Nodes::iterator pi = properties.begin(); pi != properties.end(); ++pi) { + Xml::Node &property = **pi; + + body << tab << tab << tab << "{ " + << "\"" << property.get ("name") << "\", " + << "\"" << property.get ("type") << "\", " + << (property.get ("access").find ("read") != string::npos + ? "true" + : "false") + << ", " + << (property.get ("access").find ("write") != string::npos + ? "true" + : "false") + << " }," << endl; } - } - - // do correct indent - if (args_out.size() != 1 ) - { - body << tab << tab; - } - - body << method.get("name") << "("; - - // generate call stub parameters - i = 0; - for (Xml::Nodes::iterator ai = args_in.begin(); ai != args_in.end(); ++ai, ++i) - { - Xml::Node &arg = **ai; - Xml::Nodes annotations = arg["annotation"]; - Xml::Nodes annotations_object = annotations.select("name","org.freedesktop.DBus.Object"); - string arg_object; - - if (annotations_object.size() > 0) - { - arg_object = annotations_object.front()->get("value"); + + + body << tab << tab << tab << "{ 0, 0, 0, 0 }" << endl + + << tab << tab << "};" << endl; + + // generate the Introspected interface + body << tab << tab << "static ::DBus::IntrospectedInterface " << ifaceclass << "_interface = " << endl + << tab << tab << "{" << endl + << tab << tab << tab << "\"" << ifacename << "\"," << endl + << tab << tab << tab << ifaceclass << "_methods," << endl + << tab << tab << tab << ifaceclass << "_signals," << endl + << tab << tab << tab << ifaceclass << "_properties" << endl + << tab << tab << "};" << endl + << tab << tab << "return &" << ifaceclass << "_interface;" << endl + << tab << "}" << endl + << endl; + + body << "public:" << endl + << endl + << tab << "/* properties exposed by this interface, use" << endl + << tab << " * property() and property(value) to get and set a particular property" << endl + << tab << " */" << endl; + + // generate the properties code + + for (Xml::Nodes::iterator pi = properties.begin(); pi != properties.end(); ++pi) { + Xml::Node &property = **pi; + string name = property.get ("name"); + string type = property.get ("type"); + string type_name = signature_to_type (type); + + body << tab << "::DBus::PropertyAdaptor< " << type_name << " > " << name << ";" << endl; } - - if (arg_object.length()) - { - body << "_argin" << i+1; + + body << endl; + + body << "public:" << endl + << endl + << tab << "/* methods exported by this interface," << endl + << tab << " * you will have to implement them in your ObjectAdaptor" << endl + << tab << " */" << endl; + + // generate the methods code + + for (Xml::Nodes::iterator mi = methods.begin(); mi != methods.end(); ++mi) { + Xml::Node &method = **mi; + Xml::Nodes args = method["arg"]; + Xml::Nodes args_in = args.select ("direction","in"); + Xml::Nodes args_out = args.select ("direction","out"); + Xml::Nodes annotations = args["annotation"]; + Xml::Nodes annotations_object = annotations.select ("name","org.freedesktop.DBus.Object"); + string arg_object; + + if (annotations_object.size() > 0) { + arg_object = annotations_object.front()->get ("value"); + } + + body << tab << "virtual "; + + // return type is 'void' if none or multible return values + + if (args_out.size() == 0 || args_out.size() > 1) { + body << "void "; + } else if (args_out.size() == 1) { + // generate basic or object return type + if (arg_object.length()) { + body << arg_object << " "; + } else { + body << signature_to_type (args_out.front()->get ("type")) << " "; + } + } + + // generate the method name + body << method.get ("name") << "("; + + // generate the methods 'in' variables + unsigned int i = 0; + + for (Xml::Nodes::iterator ai = args_in.begin(); ai != args_in.end(); ++ai, ++i) { + Xml::Node &arg = **ai; + Xml::Nodes annotations = arg["annotation"]; + Xml::Nodes annotations_object = annotations.select ("name","org.freedesktop.DBus.Object"); + string arg_name = arg.get ("name"); + string arg_object; + + if (annotations_object.size() > 0) { + arg_object = annotations_object.front()->get ("value"); + } + + // generate basic signature only if no object name available... + if (!arg_object.length()) { + body << "const " << signature_to_type (arg.get ("type")) << "& "; + } + + // ...or generate object style if available + else { + body << "const " << arg_object << "& "; + + // store a object name to later generate header includes + include_vector.push_back (arg_object); + } + + if (arg_name.length()) + body << arg_name; + + if ( (i+1 != args_in.size() || args_out.size() > 1)) + body << ", "; + } + + // generate the method 'out' variables if multibe 'out' values exist + if (args_out.size() > 1) { + unsigned int i = 0; + + for (Xml::Nodes::iterator ao = args_out.begin(); ao != args_out.end(); ++ao, ++i) { + Xml::Node &arg = **ao; + Xml::Nodes annotations = arg["annotation"]; + Xml::Nodes annotations_object = annotations.select ("name","org.freedesktop.DBus.Object"); + string arg_name = arg.get ("name"); + string arg_object; + + if (annotations_object.size() > 0) { + arg_object = annotations_object.front()->get ("value"); + } + + // generate basic signature only if no object name available... + if (!arg_object.length()) { + body << "const " << signature_to_type (arg.get ("type")) << "& "; + } + + // ...or generate object style if available + else { + body << "const " << arg_object << "& "; + + // store a object name to later generate header includes + include_vector.push_back (arg_object); + } + + if (arg_name.length()) + body << " " << arg_name; + + if (i+1 != args_out.size()) + body << ", "; + } + } + + body << ") = 0;" << endl; } - else - { - body << "argin" << i+1; + + body << endl + + << "public:" << endl + << endl + << tab << "/* signal emitters for this interface" << endl + << tab << " */" << endl; + + // generate the signals code + + for (Xml::Nodes::iterator si = signals.begin(); si != signals.end(); ++si) { + Xml::Node &signal = **si; + Xml::Nodes args = signal["arg"]; + + body << tab << "void " << signal.get ("name") << "("; + + // generate the signal arguments + unsigned int i = 0; + + for (Xml::Nodes::iterator a = args.begin(); a != args.end(); ++a, ++i) { + Xml::Node &arg = **a; + Xml::Nodes annotations = arg["annotation"]; + Xml::Nodes annotations_object = annotations.select ("name","org.freedesktop.DBus.Object"); + string arg_object; + + if (annotations_object.size() > 0) { + arg_object = annotations_object.front()->get ("value"); + } + + // generate basic signature only if no object name available... + if (!arg_object.length()) { + body << "const " << signature_to_type (arg.get ("type")) << "& arg" << i+1; + } + + // ...or generate object style if available + else { + body << "const " << arg_object << "& arg" << i+1; + + // store a object name to later generate header includes + include_vector.push_back (arg_object); + } + + if (i+1 != args.size()) + body << ", "; + } + + body << ")" << endl + + << tab << "{" << endl + << tab << tab << "::DBus::SignalMessage sig(\"" << signal.get ("name") <<"\");" << endl; + + // generate the signal body + + if (args.size() > 0) { + body << tab << tab << "::DBus::MessageIter wi = sig.writer();" << endl; + + unsigned int i = 0; + + for (Xml::Nodes::iterator a = args.begin(); a != args.end(); ++a, ++i) { + Xml::Node &arg = **a; + Xml::Nodes annotations = arg["annotation"]; + Xml::Nodes annotations_object = annotations.select ("name","org.freedesktop.DBus.Object"); + string arg_object; + + if (annotations_object.size() > 0) { + arg_object = annotations_object.front()->get ("value"); + } + + if (arg_object.length()) { + body << tab << tab << signature_to_type (arg.get ("type")) << " _arg" << i+1 << ";" << endl; + body << tab << tab << "_arg" << i+1 << " << " << "arg" << i+1 << ";" << endl; + + body << tab << tab << "wi << _arg" << i+1 << ";" << endl; + } else { + body << tab << tab << "wi << arg" << i+1 << ";" << endl; + } + } + } + + // emit the signal in method body + body << tab << tab << "emit_signal(sig);" << endl + << tab << "}" << endl; } - if ((i+1 != args_in.size() || args_out.size() > 1)) - body << ", "; - } - - if (args_out.size() > 1) - { - i = 0; - for (Xml::Nodes::iterator ao = args_out.begin(); ao != args_out.end(); ++ao, ++i) - { - Xml::Node &arg = **ao; - Xml::Nodes annotations = arg["annotation"]; - Xml::Nodes annotations_object = annotations.select("name","org.freedesktop.DBus.Object"); - string arg_object; - - if (annotations_object.size() > 0) - { - arg_object = annotations_object.front()->get("value"); - } - - if (arg_object.length()) - { - body << "_argout" << i+1; - } - else - { - body << "argout" << i+1; - } - - if (i+1 != args_out.size()) - body << ", "; + body << endl + + << "private:" << endl + << endl + << tab << "/* unmarshalers (to unpack the DBus message before calling the actual interface method)" << endl + << tab << " */" << endl; + + // generate the unmarshalers + + for (Xml::Nodes::iterator mi = methods.begin(); mi != methods.end(); ++mi) { + Xml::Node &method = **mi; + Xml::Nodes args = method["arg"]; + Xml::Nodes args_in = args.select ("direction","in"); + Xml::Nodes args_out = args.select ("direction","out"); + + body << tab << "::DBus::Message " << stub_name (method.get ("name")) << "(const ::DBus::CallMessage &call)" << endl + << tab << "{" << endl + << tab << tab << "::DBus::MessageIter ri = call.reader();" << endl + << endl; + + // generate the 'in' variables + unsigned int i = 1; + + for (Xml::Nodes::iterator ai = args_in.begin(); ai != args_in.end(); ++ai, ++i) { + Xml::Node &arg = **ai; + + body << tab << tab << signature_to_type (arg.get ("type")) << " argin" << i << ";" << " "; + body << "ri >> argin" << i << ";" << endl; + } + + // generate the 'in' object variables + i = 1; + + for (Xml::Nodes::iterator ai = args_in.begin(); ai != args_in.end(); ++ai, ++i) { + Xml::Node &arg = **ai; + Xml::Nodes annotations = arg["annotation"]; + Xml::Nodes annotations_object = annotations.select ("name","org.freedesktop.DBus.Object"); + string arg_object; + + if (annotations_object.size() > 0) { + arg_object = annotations_object.front()->get ("value"); + } + + if (arg_object.length()) { + body << tab << tab << arg_object << " _argin" << i << ";"; + body << " " << "_argin" << i << " << " << "argin" << i << ";" << endl; + } + } + + // generate 'out' variables + if (args_out.size() > 0) { + unsigned int i = 1; + + for (Xml::Nodes::iterator ao = args_out.begin(); ao != args_out.end(); ++ao, ++i) { + Xml::Node &arg = **ao; + + body << tab << tab << signature_to_type (arg.get ("type")) << " argout" << i; + + if (args_out.size() == 1) { // a single 'out' parameter will be assigned + body << " = "; + } else { // multible 'out' parameters will be handled as parameters below + body << ";" << endl; + } + } + } + + // generate 'out' object variables + if (args_out.size() > 0) { + unsigned int i = 1; + + for (Xml::Nodes::iterator ao = args_out.begin(); ao != args_out.end(); ++ao, ++i) { + Xml::Node &arg = **ao; + Xml::Nodes annotations = arg["annotation"]; + Xml::Nodes annotations_object = annotations.select ("name","org.freedesktop.DBus.Object"); + string arg_object; + + if (annotations_object.size() > 0) { + arg_object = annotations_object.front()->get ("value"); + } + + // generate object types + if (arg_object.length()) { + body << tab << tab << arg_object << " _argout" << i << ";" << endl; + } + } + } + + // generate in '<<' operation + i = 0; + + for (Xml::Nodes::iterator ai = args_in.begin(); ai != args_in.end(); ++ai, ++i) { + Xml::Node &arg = **ai; + Xml::Nodes annotations = arg["annotation"]; + Xml::Nodes annotations_object = annotations.select ("name","org.freedesktop.DBus.Object"); + string arg_object; + + if (annotations_object.size() > 0) { + arg_object = annotations_object.front()->get ("value"); + } + } + + // do correct indent + if (args_out.size() != 1) { + body << tab << tab; + } + + body << method.get ("name") << "("; + + // generate call stub parameters + i = 0; + + for (Xml::Nodes::iterator ai = args_in.begin(); ai != args_in.end(); ++ai, ++i) { + Xml::Node &arg = **ai; + Xml::Nodes annotations = arg["annotation"]; + Xml::Nodes annotations_object = annotations.select ("name","org.freedesktop.DBus.Object"); + string arg_object; + + if (annotations_object.size() > 0) { + arg_object = annotations_object.front()->get ("value"); + } + + if (arg_object.length()) { + body << "_argin" << i+1; + } else { + body << "argin" << i+1; + } + + if ( (i+1 != args_in.size() || args_out.size() > 1)) + body << ", "; + } + + if (args_out.size() > 1) { + i = 0; + + for (Xml::Nodes::iterator ao = args_out.begin(); ao != args_out.end(); ++ao, ++i) { + Xml::Node &arg = **ao; + Xml::Nodes annotations = arg["annotation"]; + Xml::Nodes annotations_object = annotations.select ("name","org.freedesktop.DBus.Object"); + string arg_object; + + if (annotations_object.size() > 0) { + arg_object = annotations_object.front()->get ("value"); + } + + if (arg_object.length()) { + body << "_argout" << i+1; + } else { + body << "argout" << i+1; + } + + if (i+1 != args_out.size()) + body << ", "; + } + } + + body << ");" << endl; + + body << tab << tab << "::DBus::ReturnMessage reply(call);" << endl; + + if (args_out.size() > 0) { + body << tab << tab << "::DBus::MessageIter wi = reply.writer();" << endl; + + // generate out '<<' operation + i = 0; + + for (Xml::Nodes::iterator ao = args_out.begin(); ao != args_out.end(); ++ao, ++i) { + Xml::Node &arg = **ao; + Xml::Nodes annotations = arg["annotation"]; + Xml::Nodes annotations_object = annotations.select ("name","org.freedesktop.DBus.Object"); + string arg_object; + + if (annotations_object.size() > 0) { + arg_object = annotations_object.front()->get ("value"); + } + + if (arg_object.length()) { + body << tab << tab << "argout" << i+1 << " << " << "_argout" << i+1 << ";" << endl; + } + } + + for (unsigned int i = 0; i < args_out.size(); ++i) { + body << tab << tab << "wi << argout" << i+1 << ";" << endl; + } + } + + body << tab << tab << "return reply;" << endl; + + body << tab << "}" << endl; } - } - - body << ");" << endl; - - body << tab << tab << "::DBus::ReturnMessage reply(call);" << endl; - - if (args_out.size() > 0) - { - body << tab << tab << "::DBus::MessageIter wi = reply.writer();" << endl; - - // generate out '<<' operation - i = 0; - for (Xml::Nodes::iterator ao = args_out.begin(); ao != args_out.end(); ++ao, ++i) - { - Xml::Node &arg = **ao; - Xml::Nodes annotations = arg["annotation"]; - Xml::Nodes annotations_object = annotations.select("name","org.freedesktop.DBus.Object"); - string arg_object; - - if (annotations_object.size() > 0) - { - arg_object = annotations_object.front()->get("value"); - } - - if (arg_object.length()) - { - body << tab << tab << "argout" << i+1 << " << " << "_argout" << i+1 << ";" << endl; - } + + body << "};" << endl + + << endl; + + for (unsigned int i = 0; i < nspaces; ++i) { + body << "} "; } - for (unsigned int i = 0; i < args_out.size(); ++i) - { - body << tab << tab << "wi << argout" << i+1 << ";" << endl; - } - } - - body << tab << tab << "return reply;" << endl; - - body << tab << "}" << endl; - } - - body << "};" << endl - << endl; - - for (unsigned int i = 0; i < nspaces; ++i) - { - body << "} "; - } - body << endl; - } - - body << "#endif //" << cond_comp << endl; - - // remove all duplicates in the header include vector - vector<string>::const_iterator vec_end_it = unique (include_vector.begin (), include_vector.end ()); - - for (vector<string>::const_iterator vec_it = include_vector.begin (); - vec_it != vec_end_it; - ++vec_it) - { - const string &include = *vec_it; - - head << "#include " << "\"" << include << ".h" << "\"" << endl; - } - head << endl; - - ofstream file(filename); - if (file.bad()) - { - cerr << "unable to write file " << filename << endl; - exit(-1); - } - - file << head.str (); - file << body.str (); - - file.close(); + body << endl; + } + + body << "#endif //" << cond_comp << endl; + + // remove all duplicates in the header include vector + vector<string>::const_iterator vec_end_it = unique (include_vector.begin (), include_vector.end ()); + + for (vector<string>::const_iterator vec_it = include_vector.begin (); + vec_it != vec_end_it; + ++vec_it) { + const string &include = *vec_it; + + head << "#include " << "\"" << include << ".h" << "\"" << endl; + } + + head << endl; + + ofstream file (filename); + + if (file.bad()) { + cerr << "unable to write file " << filename << endl; + exit (-1); + } + + file << head.str (); + + file << body.str (); + + file.close(); } diff --git a/sflphone-common/libs/dbus-c++/tools/generate_proxy.cpp b/sflphone-common/libs/dbus-c++/tools/generate_proxy.cpp index f3615a0d48..288dfa4845 100644 --- a/sflphone-common/libs/dbus-c++/tools/generate_proxy.cpp +++ b/sflphone-common/libs/dbus-c++/tools/generate_proxy.cpp @@ -30,6 +30,7 @@ #include "generate_proxy.h" using namespace std; + using namespace DBus; extern const char *tab; @@ -38,628 +39,586 @@ extern const char *dbus_includes; /*! Generate proxy code for a XML introspection */ -void generate_proxy(Xml::Document &doc, const char *filename) +void generate_proxy (Xml::Document &doc, const char *filename) { - ostringstream body; - ostringstream head; - vector <string> include_vector; - - head << header; - string filestring = filename; - underscorize(filestring); - - string cond_comp = "__dbusxx__" + filestring + "__PROXY_MARSHAL_H"; - - head << "#ifndef " << cond_comp << endl - << "#define " << cond_comp << endl; - - head << dbus_includes; - - Xml::Node &root = *(doc.root); - Xml::Nodes interfaces = root["interface"]; - - // iterate over all interface definitions - for (Xml::Nodes::iterator i = interfaces.begin(); i != interfaces.end(); ++i) - { - Xml::Node &iface = **i; - Xml::Nodes methods = iface["method"]; - Xml::Nodes signals = iface["signal"]; - Xml::Nodes properties = iface["property"]; - Xml::Nodes ms; - ms.insert(ms.end(), methods.begin(), methods.end()); - ms.insert(ms.end(), signals.begin(), signals.end()); - - // gets the name of a interface: <interface name="XYZ"> - string ifacename = iface.get("name"); - - // these interface names are skipped. - if (ifacename == "org.freedesktop.DBus.Introspectable" - ||ifacename == "org.freedesktop.DBus.Properties") - { - cerr << "skipping interface " << ifacename << endl; - continue; - } - - istringstream ss(ifacename); - string nspace; - unsigned int nspaces = 0; - - // prints all the namespaces defined with <interface name="X.Y.Z"> - while (ss.str().find('.', ss.tellg()) != string::npos) - { - getline(ss, nspace, '.'); - - body << "namespace " << nspace << " {" << endl; - - ++nspaces; - } - body << endl; - - string ifaceclass; - - getline(ss, ifaceclass); - - // a "_proxy" is added to class name to distinguish between proxy and adaptor - ifaceclass += "_proxy"; - - cerr << "generating code for interface " << ifacename << "..." << endl; - - // the code from class definiton up to opening of the constructor is generated... - body << "class " << ifaceclass << endl - << ": public ::DBus::InterfaceProxy" << endl - << "{" << endl - << "public:" << endl - << endl - << tab << ifaceclass << "()" << endl - << tab << ": ::DBus::InterfaceProxy(\"" << ifacename << "\")" << endl - << tab << "{" << endl; - - // generates code to connect all the signal stubs; this is still inside the constructor - for (Xml::Nodes::iterator si = signals.begin(); si != signals.end(); ++si) - { - Xml::Node &signal = **si; - - string marshname = "_" + signal.get("name") + "_stub"; - - body << tab << tab << "connect_signal(" - << ifaceclass << ", " << signal.get("name") << ", " << stub_name(signal.get("name")) - << ");" << endl; - } - - // the constructor ends here - body << tab << "}" << endl - << endl; - - // write public block header for properties - body << "public:" << endl << endl - << tab << "/* properties exported by this interface */" << endl; - - // this loop generates all properties - for (Xml::Nodes::iterator pi = properties.begin (); - pi != properties.end (); ++pi) - { - Xml::Node & property = **pi; - string prop_name = property.get ("name"); - string property_access = property.get ("access"); - if (property_access == "read" || property_access == "readwrite") - { - body << tab << tab << "const " << signature_to_type (property.get("type")) - << " " << prop_name << "() {" << endl; - body << tab << tab << tab << "::DBus::CallMessage call ;\n "; - body << tab << tab << tab - << "call.member(\"Get\"); call.interface(\"org.freedesktop.DBus.Properties\");" - << endl; - body << tab << tab << tab - << "::DBus::MessageIter wi = call.writer(); " << endl; - body << tab << tab << tab - << "const std::string interface_name = \"" << ifacename << "\";" - << endl; - body << tab << tab << tab - << "const std::string property_name = \"" << prop_name << "\";" - << endl; - body << tab << tab << tab << "wi << interface_name;" << endl; - body << tab << tab << tab << "wi << property_name;" << endl; - body << tab << tab << tab - << "::DBus::Message ret = this->invoke_method (call);" << endl; - // TODO: support invoke_method_NoReply for properties - body << tab << tab << tab - << "::DBus::MessageIter ri = ret.reader ();" << endl; - body << tab << tab << tab << "::DBus::Variant argout; " << endl; - body << tab << tab << tab << "ri >> argout;" << endl; - body << tab << tab << tab << "return argout;" << endl; - body << tab << tab << "};" << endl; - } - - if (property_access == "write" || property_access == "readwrite") - { - body << tab << tab << "void " << prop_name << "( const "<< signature_to_type (property.get("type")) << " & input" << ") {" << endl; - body << tab << tab << tab << "::DBus::CallMessage call ;\n "; - body << tab << tab << tab <<"call.member(\"Set\"); call.interface( \"org.freedesktop.DBus.Properties\");"<< endl; - body << tab << tab << tab <<"::DBus::MessageIter wi = call.writer(); " << endl; - body << tab << tab << tab <<"::DBus::Variant value;" << endl; - body << tab << tab << tab <<"::DBus::MessageIter vi = value.writer ();" << endl; - body << tab << tab << tab <<"vi << input;" << endl; - body << tab << tab << tab <<"const std::string interface_name = \"" << ifacename << "\";" << endl; - body << tab << tab << tab <<"const std::string property_name = \"" << prop_name << "\";"<< endl; - body << tab << tab << tab <<"wi << interface_name;" << endl; - body << tab << tab << tab <<"wi << property_name;" << endl; - body << tab << tab << tab <<"wi << value;" << endl; - body << tab << tab << tab <<"::DBus::Message ret = this->invoke_method (call);" << endl; - // TODO: support invoke_method_noreply for properties - body << tab << tab << "};" << endl; - } - } - - // write public block header for methods - body << "public:" << endl - << endl - << tab << "/* methods exported by this interface," << endl - << tab << " * this functions will invoke the corresponding methods on the remote objects" << endl - << tab << " */" << endl; - - // this loop generates all methods - for (Xml::Nodes::iterator mi = methods.begin(); mi != methods.end(); ++mi) - { - Xml::Node &method = **mi; - Xml::Nodes args = method["arg"]; - Xml::Nodes args_in = args.select("direction","in"); - Xml::Nodes args_out = args.select("direction","out"); - Xml::Nodes annotations = args["annotation"]; - Xml::Nodes method_annotations = method["annotation"]; - Xml::Nodes annotations_noreply = method_annotations.select("name","org.freedesktop.DBus.Method.NoReply"); - Xml::Nodes annotations_object = annotations.select("name","org.freedesktop.DBus.Object"); - string arg_object; - bool annotation_noreply_value = false; - - // parse method level noreply annotations - if (annotations_noreply.size() > 0) - { - string annotation_noreply_value_str = annotations_noreply.front()->get("value"); - - if (annotation_noreply_value_str == "true") - { - annotation_noreply_value = true; - } - } - - if (annotations_object.size() > 0) - { - arg_object = annotations_object.front()->get("value"); - } - - if (args_out.size() == 0 || args_out.size() > 1) - { - body << tab << "void "; - } - else if (args_out.size() == 1) - { - if (arg_object.length()) - { - body << tab << arg_object << " "; - } - else - { - body << tab << signature_to_type(args_out.front()->get("type")) << " "; - } - } - - body << method.get("name") << "("; - - // generate all 'in' arguments for a method signature - unsigned int i = 0; - for (Xml::Nodes::iterator ai = args_in.begin(); ai != args_in.end(); ++ai, ++i) - { - Xml::Node &arg = **ai; - Xml::Nodes annotations = arg["annotation"]; - Xml::Nodes annotations_object = annotations.select("name","org.freedesktop.DBus.Object"); - string arg_object; - - if (annotations_object.size() > 0) - { - arg_object = annotations_object.front()->get("value"); - } - - // generate basic signature only if no object name available... - if (!arg_object.length()) - { - body << "const " << signature_to_type(arg.get("type")) << "& "; - } - // ...or generate object style if available - else - { - body << "const " << arg_object << "& "; - - // store a object name to later generate header includes - include_vector.push_back (arg_object); - } - - string arg_name = arg.get("name"); - if (arg_name.length()) - body << arg_name; - else - body << "argin" << i; - - if ((i+1 != args_in.size() || args_out.size() > 1)) - body << ", "; - } - - if (args_out.size() > 1) - { - // generate all 'out' arguments for a method signature - unsigned int j = 0; - for (Xml::Nodes::iterator ao = args_out.begin(); ao != args_out.end(); ++ao, ++j) - { - Xml::Node &arg = **ao; - Xml::Nodes annotations = arg["annotation"]; - Xml::Nodes annotations_object = annotations.select("name","org.freedesktop.DBus.Object"); - string arg_object; - - if (annotations_object.size() > 0) - { - arg_object = annotations_object.front()->get("value"); - } - - // generate basic signature only if no object name available... - if (!arg_object.length()) - { - body << signature_to_type(arg.get("type")) << "&"; - } - // ...or generate object style if available - else - { - body << arg_object << "& "; - - // store a object name to later generate header includes - include_vector.push_back (arg_object); - } - - string arg_name = arg.get("name"); - if (arg_name.length()) - body << " " << arg_name; - else - body << " argout" << j; - - if (j+1 != args_out.size()) - body << ", "; - } - } - body << ")" << endl; - - body << tab << "{" << endl - << tab << tab << "::DBus::CallMessage call;" << endl; - - if (args_in.size() > 0) - { - body << tab << tab << "::DBus::MessageIter wi = call.writer();" << endl - << endl; - } - - // generate all 'in' arguments for a method body - i = 0; - for (Xml::Nodes::iterator ai = args_in.begin(); ai != args_in.end(); ++ai, ++i) - { - Xml::Node &arg = **ai; - string arg_name = arg.get("name"); - Xml::Nodes annotations = arg["annotation"]; - Xml::Nodes annotations_object = annotations.select("name","org.freedesktop.DBus.Object"); - string arg_object; - - if (annotations_object.size() > 0) - { - arg_object = annotations_object.front()->get("value"); - } - - if (!arg_name.length()) - { - arg_name = "argin"; - arg_name += toString <uint> (i); - } - - // generate extra code to wrap object - if (arg_object.length()) - { - body << tab << tab << signature_to_type(arg.get("type")) << "_" << arg_name << ";" << endl; - body << tab << tab << "_" << arg_name << " << " << arg_name << ";" << endl; - - arg_name = string ("_") + arg_name; - } - - body << tab << tab << "wi << " << arg_name << ";" << endl; - } - - body << tab << tab << "call.member(\"" << method.get("name") << "\");" << endl; - - // generate noreply/reply method calls - if (annotation_noreply_value) - { - if (args_out.size ()) - { - cerr << "Function: " << method.get("name") << ":" << endl; - cerr << "Option 'org.freedesktop.DBus.Method.NoReply' not allowed for methods with 'out' variables!" << endl << "-> Option ignored!" << endl; - - body << tab << tab << "::DBus::Message ret = invoke_method (call);" << endl; - } - else - { - body << tab << tab << "assert (invoke_method_noreply (call));" << endl; // will only assert in case of no memory - } - } - else - { - body << tab << tab << "::DBus::Message ret = invoke_method (call);" << endl; - } - - if (args_out.size() > 0) - { - body << tab << tab << "::DBus::MessageIter ri = ret.reader();" << endl - << endl; - } - - // generate 'out' values as return if only one existing - if (args_out.size() == 1) - { - Xml::Nodes annotations = args_out["annotation"]; - Xml::Nodes annotations_object = annotations.select("name","org.freedesktop.DBus.Object"); - string arg_object; - - if (annotations_object.size() > 0) - { - arg_object = annotations_object.front()->get("value"); - } - - if (arg_object.length()) - { - body << tab << tab << arg_object << " _argout;" << endl; - } + ostringstream body; + ostringstream head; + vector <string> include_vector; - body << tab << tab << signature_to_type(args_out.front()->get("type")) << " argout;" << endl; - - body << tab << tab << "ri >> argout;" << endl; - - if (arg_object.length()) - { - body << tab << tab << "_argout << argout;" << endl; - body << tab << tab << "return _argout;" << endl; - } - else - { - body << tab << tab << "return argout;" << endl; - } - } - else if (args_out.size() > 1) - { - // generate multible 'out' value - unsigned int i = 0; - for (Xml::Nodes::iterator ao = args_out.begin(); ao != args_out.end(); ++ao, ++i) - { - Xml::Node &arg = **ao; - string arg_name = arg.get("name"); - Xml::Nodes annotations = arg["annotation"]; - Xml::Nodes annotations_object = annotations.select("name","org.freedesktop.DBus.Object"); - string arg_object; - - if (annotations_object.size() > 0) - { - arg_object = annotations_object.front()->get("value"); - } - - if (!arg_name.length()) - { - arg_name = "argout" + toString <uint> (i); - } - - if (arg_object.length()) - { - body << tab << tab << signature_to_type(arg.get("type")) << "_" << arg_name << ";" << endl; - } - - if (arg_object.length()) - { - body << tab << tab << "ri >> " << "_" << arg_name << ";" << endl; - } - else - { - body << tab << tab << "ri >> " << arg_name << ";" << endl; - } - - if (arg_object.length()) - { - body << tab << tab << arg_name << " << " << "_" << arg_name << ";" << endl; - } - } - } - - body << tab << "}" << endl - << endl; - } - - // write public block header for signals - body << endl - << "public:" << endl - << endl - << tab << "/* signal handlers for this interface" << endl - << tab << " */" << endl; - - // this loop generates all signals - for (Xml::Nodes::iterator si = signals.begin(); si != signals.end(); ++si) - { - Xml::Node &signal = **si; - Xml::Nodes args = signal["arg"]; - - body << tab << "virtual void " << signal.get("name") << "("; - - // this loop generates all argument for a signal - unsigned int i = 0; - for (Xml::Nodes::iterator ai = args.begin(); ai != args.end(); ++ai, ++i) - { - Xml::Node &arg = **ai; - string arg_name = arg.get("name"); - Xml::Nodes annotations = arg["annotation"]; - Xml::Nodes annotations_object = annotations.select("name","org.freedesktop.DBus.Object"); - string arg_object; - - if (annotations_object.size() > 0) - { - arg_object = annotations_object.front()->get("value"); - } - - // generate basic signature only if no object name available... - if (!arg_object.length()) - { - body << "const " << signature_to_type(arg.get("type")) << "& "; + head << header; + string filestring = filename; + underscorize (filestring); + + string cond_comp = "__dbusxx__" + filestring + "__PROXY_MARSHAL_H"; + + head << "#ifndef " << cond_comp << endl + << "#define " << cond_comp << endl; + + head << dbus_includes; + + Xml::Node &root = * (doc.root); + Xml::Nodes interfaces = root["interface"]; + + // iterate over all interface definitions + + for (Xml::Nodes::iterator i = interfaces.begin(); i != interfaces.end(); ++i) { + Xml::Node &iface = **i; + Xml::Nodes methods = iface["method"]; + Xml::Nodes signals = iface["signal"]; + Xml::Nodes properties = iface["property"]; + Xml::Nodes ms; + ms.insert (ms.end(), methods.begin(), methods.end()); + ms.insert (ms.end(), signals.begin(), signals.end()); + + // gets the name of a interface: <interface name="XYZ"> + string ifacename = iface.get ("name"); + + // these interface names are skipped. + + if (ifacename == "org.freedesktop.DBus.Introspectable" + ||ifacename == "org.freedesktop.DBus.Properties") { + cerr << "skipping interface " << ifacename << endl; + continue; } - // ...or generate object style if available - else - { - body << "const " << arg_object << "& "; - - // store a object name to later generate header includes - include_vector.push_back (arg_object); + + istringstream ss (ifacename); + + string nspace; + unsigned int nspaces = 0; + + // prints all the namespaces defined with <interface name="X.Y.Z"> + + while (ss.str().find ('.', ss.tellg()) != string::npos) { + getline (ss, nspace, '.'); + + body << "namespace " << nspace << " {" << endl; + + ++nspaces; } - - if (arg_name.length()) - body << arg_name; - else - body << "argin" << i; - - if ((ai+1 != args.end())) - body << ", "; - } - body << ") = 0;" << endl; - } - - // write private block header for unmarshalers - body << endl - << "private:" << endl - << endl - << tab << "/* unmarshalers (to unpack the DBus message before calling the actual signal handler)" << endl - << tab << " */" << endl; - - // generate all the unmarshalers - for (Xml::Nodes::iterator si = signals.begin(); si != signals.end(); ++si) - { - Xml::Node &signal = **si; - Xml::Nodes args = signal["arg"]; - - body << tab << "void " << stub_name(signal.get("name")) << "(const ::DBus::SignalMessage &sig)" << endl - << tab << "{" << endl; - - if (args.size() > 0) - { - body << tab << tab << "::DBus::MessageIter ri = sig.reader();" << endl - << endl; - } - - unsigned int i = 0; - for (Xml::Nodes::iterator ai = args.begin(); ai != args.end(); ++ai, ++i) - { - Xml::Node &arg = **ai; - string arg_name = arg.get("name"); - Xml::Nodes annotations = arg["annotation"]; - Xml::Nodes annotations_object = annotations.select("name","org.freedesktop.DBus.Object"); - string arg_object; - - if (annotations_object.size() > 0) - { - arg_object = annotations_object.front()->get("value"); - } - - body << tab << tab << signature_to_type(arg.get("type")) << " " ; - - // use a default if no arg name given - if (!arg_name.length()) - { - arg_name = "arg" + toString <uint> (i); + + body << endl; + + string ifaceclass; + + getline (ss, ifaceclass); + + // a "_proxy" is added to class name to distinguish between proxy and adaptor + ifaceclass += "_proxy"; + + cerr << "generating code for interface " << ifacename << "..." << endl; + + // the code from class definiton up to opening of the constructor is generated... + body << "class " << ifaceclass << endl + << ": public ::DBus::InterfaceProxy" << endl + << "{" << endl + << "public:" << endl + << endl + << tab << ifaceclass << "()" << endl + << tab << ": ::DBus::InterfaceProxy(\"" << ifacename << "\")" << endl + << tab << "{" << endl; + + // generates code to connect all the signal stubs; this is still inside the constructor + + for (Xml::Nodes::iterator si = signals.begin(); si != signals.end(); ++si) { + Xml::Node &signal = **si; + + string marshname = "_" + signal.get ("name") + "_stub"; + + body << tab << tab << "connect_signal(" + << ifaceclass << ", " << signal.get ("name") << ", " << stub_name (signal.get ("name")) + << ");" << endl; } - - body << arg_name << ";" << endl; - body << tab << tab << "ri >> " << arg_name << ";" << endl; - - // if a object type is used create a local variable and insert values with '<<' operation - if (arg_object.length()) - { - body << tab << tab << arg_object << " _" << arg_name << ";" << endl; - body << tab << tab << "_" << arg_name << " << " << arg_name << ";" << endl; - - // store a object name to later generate header includes - include_vector.push_back (arg_object); + + // the constructor ends here + body << tab << "}" << endl + << endl; + + // write public block header for properties + body << "public:" << endl << endl + << tab << "/* properties exported by this interface */" << endl; + + // this loop generates all properties + for (Xml::Nodes::iterator pi = properties.begin (); + pi != properties.end (); ++pi) { + Xml::Node & property = **pi; + string prop_name = property.get ("name"); + string property_access = property.get ("access"); + + if (property_access == "read" || property_access == "readwrite") { + body << tab << tab << "const " << signature_to_type (property.get ("type")) + << " " << prop_name << "() {" << endl; + body << tab << tab << tab << "::DBus::CallMessage call ;\n "; + body << tab << tab << tab + << "call.member(\"Get\"); call.interface(\"org.freedesktop.DBus.Properties\");" + << endl; + body << tab << tab << tab + << "::DBus::MessageIter wi = call.writer(); " << endl; + body << tab << tab << tab + << "const std::string interface_name = \"" << ifacename << "\";" + << endl; + body << tab << tab << tab + << "const std::string property_name = \"" << prop_name << "\";" + << endl; + body << tab << tab << tab << "wi << interface_name;" << endl; + body << tab << tab << tab << "wi << property_name;" << endl; + body << tab << tab << tab + << "::DBus::Message ret = this->invoke_method (call);" << endl; + // TODO: support invoke_method_NoReply for properties + body << tab << tab << tab + << "::DBus::MessageIter ri = ret.reader ();" << endl; + body << tab << tab << tab << "::DBus::Variant argout; " << endl; + body << tab << tab << tab << "ri >> argout;" << endl; + body << tab << tab << tab << "return argout;" << endl; + body << tab << tab << "};" << endl; + } + + if (property_access == "write" || property_access == "readwrite") { + body << tab << tab << "void " << prop_name << "( const "<< signature_to_type (property.get ("type")) << " & input" << ") {" << endl; + body << tab << tab << tab << "::DBus::CallMessage call ;\n "; + body << tab << tab << tab <<"call.member(\"Set\"); call.interface( \"org.freedesktop.DBus.Properties\");"<< endl; + body << tab << tab << tab <<"::DBus::MessageIter wi = call.writer(); " << endl; + body << tab << tab << tab <<"::DBus::Variant value;" << endl; + body << tab << tab << tab <<"::DBus::MessageIter vi = value.writer ();" << endl; + body << tab << tab << tab <<"vi << input;" << endl; + body << tab << tab << tab <<"const std::string interface_name = \"" << ifacename << "\";" << endl; + body << tab << tab << tab <<"const std::string property_name = \"" << prop_name << "\";"<< endl; + body << tab << tab << tab <<"wi << interface_name;" << endl; + body << tab << tab << tab <<"wi << property_name;" << endl; + body << tab << tab << tab <<"wi << value;" << endl; + body << tab << tab << tab <<"::DBus::Message ret = this->invoke_method (call);" << endl; + // TODO: support invoke_method_noreply for properties + body << tab << tab << "};" << endl; + } } - } - - body << tab << tab << signal.get("name") << "("; - - // generate all arguments for the call to the virtual function - unsigned int j = 0; - for (Xml::Nodes::iterator ai = args.begin(); ai != args.end(); ++ai, ++j) - { - Xml::Node &arg = **ai; - string arg_name = arg.get("name"); - Xml::Nodes annotations = arg["annotation"]; - Xml::Nodes annotations_object = annotations.select("name","org.freedesktop.DBus.Object"); - string arg_object; - - if (annotations_object.size() > 0) - { - arg_object = annotations_object.front()->get("value"); + + // write public block header for methods + body << "public:" << endl + << endl + << tab << "/* methods exported by this interface," << endl + << tab << " * this functions will invoke the corresponding methods on the remote objects" << endl + << tab << " */" << endl; + + // this loop generates all methods + for (Xml::Nodes::iterator mi = methods.begin(); mi != methods.end(); ++mi) { + Xml::Node &method = **mi; + Xml::Nodes args = method["arg"]; + Xml::Nodes args_in = args.select ("direction","in"); + Xml::Nodes args_out = args.select ("direction","out"); + Xml::Nodes annotations = args["annotation"]; + Xml::Nodes method_annotations = method["annotation"]; + Xml::Nodes annotations_noreply = method_annotations.select ("name","org.freedesktop.DBus.Method.NoReply"); + Xml::Nodes annotations_object = annotations.select ("name","org.freedesktop.DBus.Object"); + string arg_object; + bool annotation_noreply_value = false; + + // parse method level noreply annotations + + if (annotations_noreply.size() > 0) { + string annotation_noreply_value_str = annotations_noreply.front()->get ("value"); + + if (annotation_noreply_value_str == "true") { + annotation_noreply_value = true; + } + } + + if (annotations_object.size() > 0) { + arg_object = annotations_object.front()->get ("value"); + } + + if (args_out.size() == 0 || args_out.size() > 1) { + body << tab << "void "; + } else if (args_out.size() == 1) { + if (arg_object.length()) { + body << tab << arg_object << " "; + } else { + body << tab << signature_to_type (args_out.front()->get ("type")) << " "; + } + } + + body << method.get ("name") << "("; + + // generate all 'in' arguments for a method signature + unsigned int i = 0; + + for (Xml::Nodes::iterator ai = args_in.begin(); ai != args_in.end(); ++ai, ++i) { + Xml::Node &arg = **ai; + Xml::Nodes annotations = arg["annotation"]; + Xml::Nodes annotations_object = annotations.select ("name","org.freedesktop.DBus.Object"); + string arg_object; + + if (annotations_object.size() > 0) { + arg_object = annotations_object.front()->get ("value"); + } + + // generate basic signature only if no object name available... + if (!arg_object.length()) { + body << "const " << signature_to_type (arg.get ("type")) << "& "; + } + + // ...or generate object style if available + else { + body << "const " << arg_object << "& "; + + // store a object name to later generate header includes + include_vector.push_back (arg_object); + } + + string arg_name = arg.get ("name"); + + if (arg_name.length()) + body << arg_name; + else + body << "argin" << i; + + if ( (i+1 != args_in.size() || args_out.size() > 1)) + body << ", "; + } + + if (args_out.size() > 1) { + // generate all 'out' arguments for a method signature + unsigned int j = 0; + + for (Xml::Nodes::iterator ao = args_out.begin(); ao != args_out.end(); ++ao, ++j) { + Xml::Node &arg = **ao; + Xml::Nodes annotations = arg["annotation"]; + Xml::Nodes annotations_object = annotations.select ("name","org.freedesktop.DBus.Object"); + string arg_object; + + if (annotations_object.size() > 0) { + arg_object = annotations_object.front()->get ("value"); + } + + // generate basic signature only if no object name available... + if (!arg_object.length()) { + body << signature_to_type (arg.get ("type")) << "&"; + } + + // ...or generate object style if available + else { + body << arg_object << "& "; + + // store a object name to later generate header includes + include_vector.push_back (arg_object); + } + + string arg_name = arg.get ("name"); + + if (arg_name.length()) + body << " " << arg_name; + else + body << " argout" << j; + + if (j+1 != args_out.size()) + body << ", "; + } + } + + body << ")" << endl; + + body << tab << "{" << endl + << tab << tab << "::DBus::CallMessage call;" << endl; + + if (args_in.size() > 0) { + body << tab << tab << "::DBus::MessageIter wi = call.writer();" << endl + << endl; + } + + // generate all 'in' arguments for a method body + i = 0; + + for (Xml::Nodes::iterator ai = args_in.begin(); ai != args_in.end(); ++ai, ++i) { + Xml::Node &arg = **ai; + string arg_name = arg.get ("name"); + Xml::Nodes annotations = arg["annotation"]; + Xml::Nodes annotations_object = annotations.select ("name","org.freedesktop.DBus.Object"); + string arg_object; + + if (annotations_object.size() > 0) { + arg_object = annotations_object.front()->get ("value"); + } + + if (!arg_name.length()) { + arg_name = "argin"; + arg_name += toString <uint> (i); + } + + // generate extra code to wrap object + if (arg_object.length()) { + body << tab << tab << signature_to_type (arg.get ("type")) << "_" << arg_name << ";" << endl; + body << tab << tab << "_" << arg_name << " << " << arg_name << ";" << endl; + + arg_name = string ("_") + arg_name; + } + + body << tab << tab << "wi << " << arg_name << ";" << endl; + } + + body << tab << tab << "call.member(\"" << method.get ("name") << "\");" << endl; + + // generate noreply/reply method calls + + if (annotation_noreply_value) { + if (args_out.size ()) { + cerr << "Function: " << method.get ("name") << ":" << endl; + cerr << "Option 'org.freedesktop.DBus.Method.NoReply' not allowed for methods with 'out' variables!" << endl << "-> Option ignored!" << endl; + + body << tab << tab << "::DBus::Message ret = invoke_method (call);" << endl; + } else { + body << tab << tab << "assert (invoke_method_noreply (call));" << endl; // will only assert in case of no memory + } + } else { + body << tab << tab << "::DBus::Message ret = invoke_method (call);" << endl; + } + + if (args_out.size() > 0) { + body << tab << tab << "::DBus::MessageIter ri = ret.reader();" << endl + << endl; + } + + // generate 'out' values as return if only one existing + if (args_out.size() == 1) { + Xml::Nodes annotations = args_out["annotation"]; + Xml::Nodes annotations_object = annotations.select ("name","org.freedesktop.DBus.Object"); + string arg_object; + + if (annotations_object.size() > 0) { + arg_object = annotations_object.front()->get ("value"); + } + + if (arg_object.length()) { + body << tab << tab << arg_object << " _argout;" << endl; + } + + body << tab << tab << signature_to_type (args_out.front()->get ("type")) << " argout;" << endl; + + body << tab << tab << "ri >> argout;" << endl; + + if (arg_object.length()) { + body << tab << tab << "_argout << argout;" << endl; + body << tab << tab << "return _argout;" << endl; + } else { + body << tab << tab << "return argout;" << endl; + } + } else if (args_out.size() > 1) { + // generate multible 'out' value + unsigned int i = 0; + + for (Xml::Nodes::iterator ao = args_out.begin(); ao != args_out.end(); ++ao, ++i) { + Xml::Node &arg = **ao; + string arg_name = arg.get ("name"); + Xml::Nodes annotations = arg["annotation"]; + Xml::Nodes annotations_object = annotations.select ("name","org.freedesktop.DBus.Object"); + string arg_object; + + if (annotations_object.size() > 0) { + arg_object = annotations_object.front()->get ("value"); + } + + if (!arg_name.length()) { + arg_name = "argout" + toString <uint> (i); + } + + if (arg_object.length()) { + body << tab << tab << signature_to_type (arg.get ("type")) << "_" << arg_name << ";" << endl; + } + + if (arg_object.length()) { + body << tab << tab << "ri >> " << "_" << arg_name << ";" << endl; + } else { + body << tab << tab << "ri >> " << arg_name << ";" << endl; + } + + if (arg_object.length()) { + body << tab << tab << arg_name << " << " << "_" << arg_name << ";" << endl; + } + } + } + + body << tab << "}" << endl + + << endl; } - - if (!arg_name.length()) - { - arg_name = "arg" + toString <uint> (j); + + // write public block header for signals + body << endl + << "public:" << endl + << endl + << tab << "/* signal handlers for this interface" << endl + << tab << " */" << endl; + + // this loop generates all signals + for (Xml::Nodes::iterator si = signals.begin(); si != signals.end(); ++si) { + Xml::Node &signal = **si; + Xml::Nodes args = signal["arg"]; + + body << tab << "virtual void " << signal.get ("name") << "("; + + // this loop generates all argument for a signal + unsigned int i = 0; + + for (Xml::Nodes::iterator ai = args.begin(); ai != args.end(); ++ai, ++i) { + Xml::Node &arg = **ai; + string arg_name = arg.get ("name"); + Xml::Nodes annotations = arg["annotation"]; + Xml::Nodes annotations_object = annotations.select ("name","org.freedesktop.DBus.Object"); + string arg_object; + + if (annotations_object.size() > 0) { + arg_object = annotations_object.front()->get ("value"); + } + + // generate basic signature only if no object name available... + if (!arg_object.length()) { + body << "const " << signature_to_type (arg.get ("type")) << "& "; + } + + // ...or generate object style if available + else { + body << "const " << arg_object << "& "; + + // store a object name to later generate header includes + include_vector.push_back (arg_object); + } + + if (arg_name.length()) + body << arg_name; + else + body << "argin" << i; + + if ( (ai+1 != args.end())) + body << ", "; + } + + body << ") = 0;" << endl; } - - if (arg_object.length()) - { - body << "_" << arg_name; + + // write private block header for unmarshalers + body << endl + << "private:" << endl + << endl + << tab << "/* unmarshalers (to unpack the DBus message before calling the actual signal handler)" << endl + << tab << " */" << endl; + + // generate all the unmarshalers + for (Xml::Nodes::iterator si = signals.begin(); si != signals.end(); ++si) { + Xml::Node &signal = **si; + Xml::Nodes args = signal["arg"]; + + body << tab << "void " << stub_name (signal.get ("name")) << "(const ::DBus::SignalMessage &sig)" << endl + << tab << "{" << endl; + + if (args.size() > 0) { + body << tab << tab << "::DBus::MessageIter ri = sig.reader();" << endl + << endl; + } + + unsigned int i = 0; + + for (Xml::Nodes::iterator ai = args.begin(); ai != args.end(); ++ai, ++i) { + Xml::Node &arg = **ai; + string arg_name = arg.get ("name"); + Xml::Nodes annotations = arg["annotation"]; + Xml::Nodes annotations_object = annotations.select ("name","org.freedesktop.DBus.Object"); + string arg_object; + + if (annotations_object.size() > 0) { + arg_object = annotations_object.front()->get ("value"); + } + + body << tab << tab << signature_to_type (arg.get ("type")) << " " ; + + // use a default if no arg name given + + if (!arg_name.length()) { + arg_name = "arg" + toString <uint> (i); + } + + body << arg_name << ";" << endl; + + body << tab << tab << "ri >> " << arg_name << ";" << endl; + + // if a object type is used create a local variable and insert values with '<<' operation + + if (arg_object.length()) { + body << tab << tab << arg_object << " _" << arg_name << ";" << endl; + body << tab << tab << "_" << arg_name << " << " << arg_name << ";" << endl; + + // store a object name to later generate header includes + include_vector.push_back (arg_object); + } + } + + body << tab << tab << signal.get ("name") << "("; + + // generate all arguments for the call to the virtual function + unsigned int j = 0; + + for (Xml::Nodes::iterator ai = args.begin(); ai != args.end(); ++ai, ++j) { + Xml::Node &arg = **ai; + string arg_name = arg.get ("name"); + Xml::Nodes annotations = arg["annotation"]; + Xml::Nodes annotations_object = annotations.select ("name","org.freedesktop.DBus.Object"); + string arg_object; + + if (annotations_object.size() > 0) { + arg_object = annotations_object.front()->get ("value"); + } + + if (!arg_name.length()) { + arg_name = "arg" + toString <uint> (j); + } + + if (arg_object.length()) { + body << "_" << arg_name; + } else { + body << arg_name; + } + + if (ai+1 != args.end()) + body << ", "; + } + + body << ");" << endl; + + body << tab << "}" << endl; } - else - { - body << arg_name; + + body << "};" << endl + + << endl; + + for (unsigned int i = 0; i < nspaces; ++i) { + body << "} "; } - - if (ai+1 != args.end()) - body << ", "; - } - - body << ");" << endl; - - body << tab << "}" << endl; - } - - body << "};" << endl - << endl; - - for (unsigned int i = 0; i < nspaces; ++i) - { - body << "} "; - } - body << endl; - } - - body << "#endif //" << cond_comp << endl; - - // remove all duplicates in the header include vector - vector<string>::const_iterator vec_end_it = unique (include_vector.begin (), include_vector.end ()); - - for (vector<string>::const_iterator vec_it = include_vector.begin (); - vec_it != vec_end_it; - ++vec_it) - { - const string &include = *vec_it; - - head << "#include " << "\"" << include << ".h" << "\"" << endl; - } - head << endl; - - ofstream file(filename); - if (file.bad()) - { - cerr << "unable to write file " << filename << endl; - exit(-1); - } - - file << head.str (); - file << body.str (); - - file.close(); + + body << endl; + } + + body << "#endif //" << cond_comp << endl; + + // remove all duplicates in the header include vector + vector<string>::const_iterator vec_end_it = unique (include_vector.begin (), include_vector.end ()); + + for (vector<string>::const_iterator vec_it = include_vector.begin (); + vec_it != vec_end_it; + ++vec_it) { + const string &include = *vec_it; + + head << "#include " << "\"" << include << ".h" << "\"" << endl; + } + + head << endl; + + ofstream file (filename); + + if (file.bad()) { + cerr << "unable to write file " << filename << endl; + exit (-1); + } + + file << head.str (); + + file << body.str (); + + file.close(); } diff --git a/sflphone-common/libs/dbus-c++/tools/generator_utils.cpp b/sflphone-common/libs/dbus-c++/tools/generator_utils.cpp index e08ad27227..9b5a364966 100644 --- a/sflphone-common/libs/dbus-c++/tools/generator_utils.cpp +++ b/sflphone-common/libs/dbus-c++/tools/generator_utils.cpp @@ -42,125 +42,132 @@ const char *dbus_includes = "\n\ #include <cassert>\n\ "; -void underscorize(string &str) -{ - for (unsigned int i = 0; i < str.length(); ++i) - { - if (!isalpha(str[i]) && !isdigit(str[i])) str[i] = '_'; - } -} - -string stub_name(string name) -{ - underscorize(name); - - return "_" + name + "_stub"; -} - -const char *atomic_type_to_string(char t) -{ - static struct { char type; const char *name; } atos[] = - { - { 'y', "uint8_t" }, - { 'b', "bool" }, - { 'n', "int16_t" }, - { 'q', "uint16_t" }, - { 'i', "int32_t" }, - { 'u', "uint32_t" }, - { 'x', "int64_t" }, - { 't', "uint64_t" }, - { 'd', "double" }, - { 's', "std::string" }, - { 'o', "::DBus::Path" }, - { 'g', "::DBus::Signature" }, - { 'v', "::DBus::Variant" }, - { '\0', "" } - }; - int i; - - for (i = 0; atos[i].type; ++i) - { - if (atos[i].type == t) break; - } - return atos[i].name; -} - -void _parse_signature(const string &signature, string &type, unsigned int &i) -{ - for (; i < signature.length(); ++i) - { - switch (signature[i]) - { - case 'a': - { - switch (signature[++i]) - { - case '{': - { - type += "std::map< "; - - const char *atom = atomic_type_to_string(signature[++i]); - if (!atom) - { - cerr << "invalid signature" << endl; - exit(-1); - } - type += atom; - type += ", "; - ++i; - break; - } - default: - { - type += "std::vector< "; - break; - } - } - _parse_signature(signature, type, i); - type += " >"; - continue; - } - case '(': - { - type += "::DBus::Struct< "; - ++i; - _parse_signature(signature, type, i); - type += " >"; - if (signature[i+1]) - { - type += ", "; - } - continue; - } - case ')': - case '}': - { - return; - } - default: - { - const char *atom = atomic_type_to_string(signature[i]); - if (!atom) - { - cerr << "invalid signature" << endl; - exit(-1); - } - type += atom; - - if (signature[i+1] != ')' && signature[i+1] != '}' && i+1 < signature.length()) - { - type += ", "; - } - break; - } - } - } -} - -string signature_to_type(const string &signature) -{ - string type; - unsigned int i = 0; - _parse_signature(signature, type, i); - return type; -} + void underscorize (string &str) + { + for (unsigned int i = 0; i < str.length(); ++i) { + if (!isalpha (str[i]) && !isdigit (str[i])) str[i] = '_'; + } + } + + string stub_name (string name) + { + underscorize (name); + + return "_" + name + "_stub"; + } + + const char *atomic_type_to_string (char t) + { + + static struct { + char type; + const char *name; + } atos[] = { + + { 'y', "uint8_t" }, + { 'b', "bool" }, + { 'n', "int16_t" }, + { 'q', "uint16_t" }, + { 'i', "int32_t" }, + { 'u', "uint32_t" }, + { 'x', "int64_t" }, + { 't', "uint64_t" }, + { 'd', "double" }, + { 's', "std::string" }, + { 'o', "::DBus::Path" }, + { 'g', "::DBus::Signature" }, + { 'v', "::DBus::Variant" }, + { '\0', "" } + }; + int i; + + for (i = 0; atos[i].type; ++i) { + if (atos[i].type == t) break; + } + + return atos[i].name; + } + + void _parse_signature (const string &signature, string &type, unsigned int &i) + { + for (; i < signature.length(); ++i) { + switch (signature[i]) { + + case 'a': { + switch (signature[++i]) { + + case '{': { + type += "std::map< "; + + const char *atom = atomic_type_to_string (signature[++i]); + + if (!atom) { + cerr << "invalid signature" << endl; + exit (-1); + } + + type += atom; + + type += ", "; + ++i; + break; + } + + default: { + type += "std::vector< "; + break; + } + } + + _parse_signature (signature, type, i); + + type += " >"; + continue; + } + + case '(': { + type += "::DBus::Struct< "; + ++i; + _parse_signature (signature, type, i); + type += " >"; + + if (signature[i+1]) { + type += ", "; + } + + continue; + } + + case ')': + + case '}': { + return; + } + + default: { + const char *atom = atomic_type_to_string (signature[i]); + + if (!atom) { + cerr << "invalid signature" << endl; + exit (-1); + } + + type += atom; + + if (signature[i+1] != ')' && signature[i+1] != '}' && i+1 < signature.length()) { + type += ", "; + } + + break; + } + } + } + } + + string signature_to_type (const string &signature) + { + string type; + unsigned int i = 0; + _parse_signature (signature, type, i); + return type; + } diff --git a/sflphone-common/libs/dbus-c++/tools/introspect.cpp b/sflphone-common/libs/dbus-c++/tools/introspect.cpp index 8ce9f3a74c..88a7673961 100644 --- a/sflphone-common/libs/dbus-c++/tools/introspect.cpp +++ b/sflphone-common/libs/dbus-c++/tools/introspect.cpp @@ -32,48 +32,42 @@ static bool systembus; static char *path; static char *service; -void niam(int sig) +void niam (int sig) { - DBus::Connection conn = systembus ? DBus::Connection::SystemBus() : DBus::Connection::SessionBus(); + DBus::Connection conn = systembus ? DBus::Connection::SystemBus() : DBus::Connection::SessionBus(); - IntrospectedObject io(conn, path, service); + IntrospectedObject io (conn, path, service); - std::cout << io.Introspect(); + std::cout << io.Introspect(); - dispatcher.leave(); + dispatcher.leave(); } -int main(int argc, char ** argv) +int main (int argc, char ** argv) { - signal(SIGTERM, niam); - signal(SIGINT, niam); - signal(SIGALRM, niam); + signal (SIGTERM, niam); + signal (SIGINT, niam); + signal (SIGALRM, niam); - if (argc == 1) - { - std::cerr << std::endl << "Usage: " << argv[0] << " [--system] <object_path> [<destination>]" << std::endl << std::endl; - } - else - { - if (strcmp(argv[1], "--system")) - { - systembus = false; - path = argv[1]; - service = argc > 2 ? argv[2] : 0; - } - else - { - systembus = true; - path = argv[2]; - service = argc > 3 ? argv[3] : 0; - } + if (argc == 1) { + std::cerr << std::endl << "Usage: " << argv[0] << " [--system] <object_path> [<destination>]" << std::endl << std::endl; + } else { + if (strcmp (argv[1], "--system")) { + systembus = false; + path = argv[1]; + service = argc > 2 ? argv[2] : 0; + } else { + systembus = true; + path = argv[2]; + service = argc > 3 ? argv[3] : 0; + } - DBus::default_dispatcher = &dispatcher; + DBus::default_dispatcher = &dispatcher; - alarm(1); + alarm (1); - dispatcher.enter(); - } + dispatcher.enter(); + } - return 0; + return 0; } diff --git a/sflphone-common/libs/dbus-c++/tools/xml.cpp b/sflphone-common/libs/dbus-c++/tools/xml.cpp index 68ae5a64da..2ba8635a3c 100644 --- a/sflphone-common/libs/dbus-c++/tools/xml.cpp +++ b/sflphone-common/libs/dbus-c++/tools/xml.cpp @@ -30,286 +30,276 @@ std::istream &operator >> (std::istream &in, DBus::Xml::Document &doc) { - std::stringbuf xmlbuf; - in.get(xmlbuf, '\0'); - doc.from_xml(xmlbuf.str()); + std::stringbuf xmlbuf; + in.get (xmlbuf, '\0'); + doc.from_xml (xmlbuf.str()); - return in; + return in; } std::ostream &operator << (std::ostream &out, const DBus::Xml::Document &doc) { - return out << doc.to_xml(); + return out << doc.to_xml(); } using namespace DBus; + using namespace DBus::Xml; -Error::Error(const char *error, int line, int column) +Error::Error (const char *error, int line, int column) { - std::ostringstream estream; + std::ostringstream estream; - estream << "line " << line << ", column " << column << ": " << error; + estream << "line " << line << ", column " << column << ": " << error; - _error = estream.str(); + _error = estream.str(); } -Node::Node(const char *n, const char ** a) -: name(n) +Node::Node (const char *n, const char ** a) + : name (n) { - if (a) - for (int i = 0; a[i]; i += 2) - { - _attrs[a[i]] = a[i+1]; + if (a) + for (int i = 0; a[i]; i += 2) { + _attrs[a[i]] = a[i+1]; - //debug_log("xml:\t%s = %s", a[i], a[i+1]); - } + //debug_log("xml:\t%s = %s", a[i], a[i+1]); + } } -Nodes Nodes::operator[](const std::string &key) +Nodes Nodes::operator[] (const std::string &key) { - Nodes result; + Nodes result; + + for (iterator i = begin(); i != end(); ++i) { + Nodes part = (**i) [key]; - for (iterator i = begin(); i != end(); ++i) - { - Nodes part = (**i)[key]; + result.insert (result.end(), part.begin(), part.end()); + } - result.insert(result.end(), part.begin(), part.end()); - } - return result; + return result; } -Nodes Nodes::select(const std::string &attr, const std::string &value) +Nodes Nodes::select (const std::string &attr, const std::string &value) { - Nodes result; - - for (iterator i = begin(); i != end(); ++i) - { - if ((*i)->get(attr) == value) - result.insert(result.end(), *i); - } - return result; + Nodes result; + + for (iterator i = begin(); i != end(); ++i) { + if ( (*i)->get (attr) == value) + result.insert (result.end(), *i); + } + + return result; } -Nodes Node::operator[](const std::string &key) +Nodes Node::operator[] (const std::string &key) { - Nodes result; + Nodes result; - if (key.length() == 0) return result; + if (key.length() == 0) return result; - for (Children::iterator i = children.begin(); i != children.end(); ++i) - { - if (i->name == key) - result.push_back(&(*i)); - } - return result; + for (Children::iterator i = children.begin(); i != children.end(); ++i) { + if (i->name == key) + result.push_back (& (*i)); + } + + return result; } -std::string Node::get(const std::string &attribute) +std::string Node::get (const std::string &attribute) { - if (_attrs.find(attribute) != _attrs.end()) - return _attrs[attribute]; - else - return ""; + if (_attrs.find (attribute) != _attrs.end()) + return _attrs[attribute]; + else + return ""; } -void Node::set(const std::string &attribute, std::string value) +void Node::set (const std::string &attribute, std::string value) { - if (value.length()) - _attrs[attribute] = value; - else - _attrs.erase(value); + if (value.length()) + _attrs[attribute] = value; + else + _attrs.erase (value); } std::string Node::to_xml() const { - std::string xml; - int depth = 0; + std::string xml; + int depth = 0; - _raw_xml(xml, depth); + _raw_xml (xml, depth); - return xml; + return xml; } -void Node::_raw_xml(std::string &xml, int &depth) const +void Node::_raw_xml (std::string &xml, int &depth) const { - xml.append(depth *2, ' '); - xml.append("<"+name); - - for (Attributes::const_iterator i = _attrs.begin(); i != _attrs.end(); ++i) - { - xml.append(" "+i->first+"=\""+i->second+"\""); - } - - if (cdata.length() == 0 && children.size() == 0) - { - xml.append("/>\n"); - } - else - { - xml.append(">"); - - if (cdata.length()) - { - xml.append(cdata); - } - - if (children.size()) - { - xml.append("\n"); - depth++; - - for (Children::const_iterator i = children.begin(); i != children.end(); ++i) - { - i->_raw_xml(xml, depth); - } - - depth--; - xml.append(depth *2, ' '); - } - xml.append("</"+name+">\n"); - } + xml.append (depth *2, ' '); + xml.append ("<"+name); + + for (Attributes::const_iterator i = _attrs.begin(); i != _attrs.end(); ++i) { + xml.append (" "+i->first+"=\""+i->second+"\""); + } + + if (cdata.length() == 0 && children.size() == 0) { + xml.append ("/>\n"); + } else { + xml.append (">"); + + if (cdata.length()) { + xml.append (cdata); + } + + if (children.size()) { + xml.append ("\n"); + depth++; + + for (Children::const_iterator i = children.begin(); i != children.end(); ++i) { + i->_raw_xml (xml, depth); + } + + depth--; + + xml.append (depth *2, ' '); + } + + xml.append ("</"+name+">\n"); + } } Document::Document() -: root(0), _depth(0) + : root (0), _depth (0) { } - -Document::Document(const std::string &xml) -: root(0), _depth(0) + +Document::Document (const std::string &xml) + : root (0), _depth (0) { - from_xml(xml); + from_xml (xml); } Document::~Document() { - delete root; + delete root; } -struct Document::Expat -{ - static void start_doctype_decl_handler( - void *data, const XML_Char *name, const XML_Char *sysid, const XML_Char *pubid, int has_internal_subset - ); - static void end_doctype_decl_handler(void *data); - static void start_element_handler(void *data, const XML_Char *name, const XML_Char **atts); - static void character_data_handler(void *data, const XML_Char *chars, int len); - static void end_element_handler(void *data, const XML_Char *name); +struct Document::Expat { + static void start_doctype_decl_handler ( + void *data, const XML_Char *name, const XML_Char *sysid, const XML_Char *pubid, int has_internal_subset + ); + static void end_doctype_decl_handler (void *data); + static void start_element_handler (void *data, const XML_Char *name, const XML_Char **atts); + static void character_data_handler (void *data, const XML_Char *chars, int len); + static void end_element_handler (void *data, const XML_Char *name); }; -void Document::from_xml(const std::string &xml) +void Document::from_xml (const std::string &xml) { - _depth = 0; - delete root; - root = 0; - - XML_Parser parser = XML_ParserCreate("UTF-8"); - - XML_SetUserData(parser, this); - - XML_SetDoctypeDeclHandler( - parser, - Document::Expat::start_doctype_decl_handler, - Document::Expat::end_doctype_decl_handler - ); - - XML_SetElementHandler( - parser, - Document::Expat::start_element_handler, - Document::Expat::end_element_handler - ); - - XML_SetCharacterDataHandler( - parser, - Document::Expat::character_data_handler - ); - - XML_Status status = XML_Parse(parser, xml.c_str(), xml.length(), true); - - if (status == XML_STATUS_ERROR) - { - const char *error = XML_ErrorString(XML_GetErrorCode(parser)); - int line = XML_GetCurrentLineNumber(parser); - int column = XML_GetCurrentColumnNumber(parser); - - XML_ParserFree(parser); - - throw Error(error, line, column); - } - else - { - XML_ParserFree(parser); - } + _depth = 0; + delete root; + root = 0; + + XML_Parser parser = XML_ParserCreate ("UTF-8"); + + XML_SetUserData (parser, this); + + XML_SetDoctypeDeclHandler ( + parser, + Document::Expat::start_doctype_decl_handler, + Document::Expat::end_doctype_decl_handler + ); + + XML_SetElementHandler ( + parser, + Document::Expat::start_element_handler, + Document::Expat::end_element_handler + ); + + XML_SetCharacterDataHandler ( + parser, + Document::Expat::character_data_handler + ); + + XML_Status status = XML_Parse (parser, xml.c_str(), xml.length(), true); + + if (status == XML_STATUS_ERROR) { + const char *error = XML_ErrorString (XML_GetErrorCode (parser)); + int line = XML_GetCurrentLineNumber (parser); + int column = XML_GetCurrentColumnNumber (parser); + + XML_ParserFree (parser); + + throw Error (error, line, column); + } else { + XML_ParserFree (parser); + } } std::string Document::to_xml() const { - return root->to_xml(); + return root->to_xml(); } -void Document::Expat::start_doctype_decl_handler( - void *data, const XML_Char *name, const XML_Char *sysid, const XML_Char *pubid, int has_internal_subset +void Document::Expat::start_doctype_decl_handler ( + void *data, const XML_Char *name, const XML_Char *sysid, const XML_Char *pubid, int has_internal_subset ) { } -void Document::Expat::end_doctype_decl_handler(void *data) +void Document::Expat::end_doctype_decl_handler (void *data) { } -void Document::Expat::start_element_handler(void *data, const XML_Char *name, const XML_Char **atts) +void Document::Expat::start_element_handler (void *data, const XML_Char *name, const XML_Char **atts) { - Document *doc = (Document *)data; - - //debug_log("xml:%d -> %s", doc->_depth, name); - - if (!doc->root) - { - doc->root = new Node(name, atts); - } - else - { - Node::Children *cld = &(doc->root->children); - - for (int i = 1; i < doc->_depth; ++i) - { - cld = &(cld->back().children); - } - cld->push_back(Node(name, atts)); - - //std::cerr << doc->to_xml() << std::endl; - } - doc->_depth++; + Document *doc = (Document *) data; + + //debug_log("xml:%d -> %s", doc->_depth, name); + + if (!doc->root) { + doc->root = new Node (name, atts); + } else { + Node::Children *cld = & (doc->root->children); + + for (int i = 1; i < doc->_depth; ++i) { + cld = & (cld->back().children); + } + + cld->push_back (Node (name, atts)); + + //std::cerr << doc->to_xml() << std::endl; + } + + doc->_depth++; } -void Document::Expat::character_data_handler(void *data, const XML_Char *chars, int len) +void Document::Expat::character_data_handler (void *data, const XML_Char *chars, int len) { - Document *doc = (Document *)data; + Document *doc = (Document *) data; + + Node *nod = doc->root; + + for (int i = 1; i < doc->_depth; ++i) { + nod = & (nod->children.back()); + } - Node *nod = doc->root; + int x, y; - for (int i = 1; i < doc->_depth; ++i) - { - nod = &(nod->children.back()); - } - int x, y; + x = 0; + y = len-1; - x = 0; - y = len-1; + while (isspace (chars[y]) && y > 0) --y; - while (isspace(chars[y]) && y > 0) --y; - while (isspace(chars[x]) && x < y) ++x; + while (isspace (chars[x]) && x < y) ++x; - nod->cdata = std::string(chars, x, y+1); + nod->cdata = std::string (chars, x, y+1); } -void Document::Expat::end_element_handler(void *data, const XML_Char *name) +void Document::Expat::end_element_handler (void *data, const XML_Char *name) { - Document *doc = (Document *)data; + Document *doc = (Document *) data; - //debug_log("xml:%d <- %s", doc->_depth, name); + //debug_log("xml:%d <- %s", doc->_depth, name); - doc->_depth--; + doc->_depth--; } diff --git a/sflphone-common/libs/dbus-c++/tools/xml2cpp.cpp b/sflphone-common/libs/dbus-c++/tools/xml2cpp.cpp index 81cd18ea5e..3284d76675 100644 --- a/sflphone-common/libs/dbus-c++/tools/xml2cpp.cpp +++ b/sflphone-common/libs/dbus-c++/tools/xml2cpp.cpp @@ -37,15 +37,16 @@ #include "generate_proxy.h" using namespace std; + using namespace DBus; //typedef map<string,string> TypeCache; -void usage(const char *argv0) +void usage (const char *argv0) { - cerr << endl << "Usage: " << argv0 << " <xmlfile> [ --proxy=<outfile.h> ] [ --adaptor=<outfile.h> ]" - << endl << endl; - exit(-1); + cerr << endl << "Usage: " << argv0 << " <xmlfile> [ --proxy=<outfile.h> ] [ --adaptor=<outfile.h> ]" + << endl << endl; + exit (-1); } /*int char_to_atomic_type(char t) @@ -61,68 +62,60 @@ bool is_atomic_type(const string &type) return type.length() == 1 && char_to_atomic_type(type[0]) != DBUS_TYPE_INVALID; }*/ -int main(int argc, char ** argv) +int main (int argc, char ** argv) { - if (argc < 2) - { - usage(argv[0]); - } - - bool proxy_mode, adaptor_mode; - char *proxy, *adaptor; - - proxy_mode = false; - proxy = 0; - - adaptor_mode = false; - adaptor = 0; - - for (int a = 1; a < argc; ++a) - { - if (!strncmp(argv[a], "--proxy=", 8)) - { - proxy_mode = true; - proxy = argv[a] +8; - } - else - if (!strncmp(argv[a], "--adaptor=", 10)) - { - adaptor_mode = true; - adaptor = argv[a] +10; - } - } - - if (!proxy_mode && !adaptor_mode) usage(argv[0]); - - ifstream xmlfile(argv[1]); - - if (xmlfile.bad()) - { - cerr << "unable to open file " << argv[1] << endl; - return -1; - } - - Xml::Document doc; - - try - { - xmlfile >> doc; - //cout << doc.to_xml(); - } - catch(Xml::Error &e) - { - cerr << "error parsing " << argv[1] << ": " << e.what() << endl; - return -1; - } - - if (!doc.root) - { - cerr << "empty document" << endl; - return -1; - } - - if (proxy_mode) generate_proxy(doc, proxy); - if (adaptor_mode) generate_adaptor(doc, adaptor); - - return 0; + if (argc < 2) { + usage (argv[0]); + } + + bool proxy_mode, adaptor_mode; + + char *proxy, *adaptor; + + proxy_mode = false; + proxy = 0; + + adaptor_mode = false; + adaptor = 0; + + for (int a = 1; a < argc; ++a) { + if (!strncmp (argv[a], "--proxy=", 8)) { + proxy_mode = true; + proxy = argv[a] +8; + } else + if (!strncmp (argv[a], "--adaptor=", 10)) { + adaptor_mode = true; + adaptor = argv[a] +10; + } + } + + if (!proxy_mode && !adaptor_mode) usage (argv[0]); + + ifstream xmlfile (argv[1]); + + if (xmlfile.bad()) { + cerr << "unable to open file " << argv[1] << endl; + return -1; + } + + Xml::Document doc; + + try { + xmlfile >> doc; + //cout << doc.to_xml(); + } catch (Xml::Error &e) { + cerr << "error parsing " << argv[1] << ": " << e.what() << endl; + return -1; + } + + if (!doc.root) { + cerr << "empty document" << endl; + return -1; + } + + if (proxy_mode) generate_proxy (doc, proxy); + + if (adaptor_mode) generate_adaptor (doc, adaptor); + + return 0; } diff --git a/sflphone-common/libs/pjproject-1.0.2/pjlib-util/include/pjlib-util/config.h b/sflphone-common/libs/pjproject-1.0.2/pjlib-util/include/pjlib-util/config.h index f1e5b1e993..84259301c0 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjlib-util/include/pjlib-util/config.h +++ b/sflphone-common/libs/pjproject-1.0.2/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-1.0.2/pjlib/include/pj/config.h b/sflphone-common/libs/pjproject-1.0.2/pjlib/include/pj/config.h index 2d0e163927..70120c9f96 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjlib/include/pj/config.h +++ b/sflphone-common/libs/pjproject-1.0.2/pjlib/include/pj/config.h @@ -1,5 +1,5 @@ /* $Id: config.h 2527 2009-03-23 11:57:55Z 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 @@ -408,7 +408,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 @@ -437,14 +437,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. @@ -474,7 +474,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) @@ -483,21 +483,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. */ @@ -511,8 +511,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 @@ -533,7 +533,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. @@ -588,14 +588,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" @@ -712,7 +712,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! @@ -729,7 +729,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 @@ -749,7 +749,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 @@ -757,7 +757,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 @@ -766,49 +766,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. */ @@ -832,7 +832,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 @@ -845,7 +845,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 @@ -940,7 +940,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 @@ -956,7 +956,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) @@ -1046,19 +1046,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-1.0.2/pjlib/src/pj/addr_resolv_symbian.cpp b/sflphone-common/libs/pjproject-1.0.2/pjlib/src/pj/addr_resolv_symbian.cpp index 8c96d46279..05e2312d14 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjlib/src/pj/addr_resolv_symbian.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/pjlib/src/pj/addr_resolv_symbian.cpp @@ -1,5 +1,5 @@ /* $Id: addr_resolv_symbian.cpp 2482 2009-03-02 15:50: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 <pj/addr_resolv.h> #include <pj/assert.h> @@ -27,170 +27,188 @@ #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); // 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_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-1.0.2/pjlib/src/pj/exception_symbian.cpp b/sflphone-common/libs/pjproject-1.0.2/pjlib/src/pj/exception_symbian.cpp index e54cebddf9..14ded02ed9 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjlib/src/pj/exception_symbian.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/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-1.0.2/pjlib/src/pj/ioqueue_symbian.cpp b/sflphone-common/libs/pjproject-1.0.2/pjlib/src/pj/ioqueue_symbian.cpp index 5b77488d92..ceb23e258d 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjlib/src/pj/ioqueue_symbian.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/pjlib/src/pj/ioqueue_symbian.cpp @@ -1,5 +1,5 @@ /* $Id: ioqueue_symbian.cpp 2482 2009-03-02 15:50: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 <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,18 +201,20 @@ 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); - sock_->Socket().Recv(aBufferPtr_, flags, iStatus); + aAddress_.SetAddress (0); + aAddress_.SetPort (0); + sock_->Socket().Recv (aBufferPtr_, flags, iStatus); } SetActive(); + return PJ_EPENDING; } @@ -224,19 +222,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; @@ -244,10 +242,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; @@ -257,16 +255,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; } @@ -274,54 +272,56 @@ void CIoqueueCallback::HandleReadCompletion() // // Handle asynchronous Accept() completion. // -CPjSocket *CIoqueueCallback::HandleAcceptCompletion() +CPjSocket *CIoqueueCallback::HandleAcceptCompletion() { - CPjSocket *pjNewSock = new CPjSocket(get_pj_socket()->GetAf(), - 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(), + 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; } @@ -335,58 +335,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++; @@ -398,31 +404,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) - ; + ; } @@ -430,8 +437,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; }; @@ -439,7 +446,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"; } @@ -448,15 +455,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; } @@ -465,79 +472,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; @@ -547,7 +555,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(); } @@ -557,13 +565,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; } @@ -572,88 +581,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()); } @@ -662,14 +674,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; } @@ -677,19 +689,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); } @@ -698,57 +711,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(); @@ -756,11 +772,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). @@ -772,45 +788,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). @@ -818,25 +837,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-1.0.2/pjlib/src/pj/ip_helper_symbian.cpp b/sflphone-common/libs/pjproject-1.0.2/pjlib/src/pj/ip_helper_symbian.cpp index 9f634a0b8b..3cf3845870 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjlib/src/pj/ip_helper_symbian.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/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-1.0.2/pjlib/src/pj/log_writer_symbian_console.cpp b/sflphone-common/libs/pjproject-1.0.2/pjlib/src/pj/log_writer_symbian_console.cpp index 8f627cf149..34d4a40254 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjlib/src/pj/log_writer_symbian_console.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/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-1.0.2/pjlib/src/pj/os_core_symbian.cpp b/sflphone-common/libs/pjproject-1.0.2/pjlib/src/pj/os_core_symbian.cpp index 9f2d1e6958..b7f44b7903 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjlib/src/pj/os_core_symbian.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/pjlib/src/pj/os_core_symbian.cpp @@ -1,5 +1,5 @@ /* $Id: os_core_symbian.cpp 2482 2009-03-02 15:50: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 <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,166 +324,177 @@ 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); - - /* Initialize exception ID for the pool. + return PJ_RETURN_OS_ERROR (err); + + /* 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; } } @@ -490,7 +502,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; } @@ -499,9 +511,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; } @@ -509,10 +521,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; } @@ -520,9 +532,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; } @@ -530,9 +542,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; } @@ -540,22 +552,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; } @@ -563,21 +575,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; @@ -586,25 +598,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; } @@ -612,27 +624,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; } @@ -643,20 +655,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; @@ -665,10 +679,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; } @@ -677,12 +691,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; @@ -691,12 +705,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]; } @@ -706,11 +720,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; } @@ -719,9 +733,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; } @@ -729,8 +743,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; } @@ -739,7 +753,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; } @@ -748,7 +762,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; } @@ -757,7 +771,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; } @@ -766,16 +780,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; } @@ -784,8 +798,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; } @@ -794,8 +808,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; @@ -805,14 +819,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; @@ -821,55 +835,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; } @@ -886,7 +900,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 */ } @@ -895,7 +909,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 */ } @@ -906,17 +920,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; @@ -929,14 +943,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; } } @@ -944,14 +958,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; } } @@ -959,7 +973,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; @@ -969,56 +983,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-1.0.2/pjlib/src/pj/os_error_symbian.cpp b/sflphone-common/libs/pjproject-1.0.2/pjlib/src/pj/os_error_symbian.cpp index 31707b97c3..bb57cd9663 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjlib/src/pj/os_error_symbian.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/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-1.0.2/pjlib/src/pj/pool_policy_new.cpp b/sflphone-common/libs/pjproject-1.0.2/pjlib/src/pj/pool_policy_new.cpp index e22040a2f4..6f99c068c3 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjlib/src/pj/pool_policy_new.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/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-1.0.2/pjlib/src/pj/sock_select_symbian.cpp b/sflphone-common/libs/pjproject-1.0.2/pjlib/src/pj/sock_select_symbian.cpp index 727bcfdf8b..48170ff6d0 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjlib/src/pj/sock_select_symbian.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/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-1.0.2/pjlib/src/pj/sock_symbian.cpp b/sflphone-common/libs/pjproject-1.0.2/pjlib/src/pj/sock_symbian.cpp index be9a9615bf..29858afab1 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjlib/src/pj/sock_symbian.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/pjlib/src/pj/sock_symbian.cpp @@ -1,5 +1,5 @@ /* $Id: sock_symbian.cpp 2482 2009-03-02 15:50: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 <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,34 +116,34 @@ 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) { TProtocolDesc aProtocol; TInt err; - err = sock_.Socket().Info(aProtocol); - User::LeaveIfError(err); + err = sock_.Socket().Info (aProtocol); + User::LeaveIfError (err); isDatagram_ = (aProtocol.iSockType == KSockDatagram); 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; } @@ -155,27 +155,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(); } @@ -186,40 +188,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_; } @@ -232,10 +235,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 @@ -244,10 +247,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 @@ -256,10 +259,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 @@ -268,10 +271,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 @@ -281,25 +284,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 }; @@ -313,48 +316,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: @@ -362,88 +369,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; - if (size < PJ_INET_ADDRSTRLEN) - return PJ_ETOOSMALL; + pj_memcpy (&inaddr, src, 4); - pj_memcpy(&inaddr, src, 4); + /* Symbian IP address is in host byte order */ + TInetAddr temp_addr ( (TUint32) pj_ntohl (inaddr.s_addr), (TUint) 0); - /* 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; + temp_addr.Output (str16); + + 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; + + pj_memcpy (ip6.u.iAddr8, src, 16); + + TInetAddr temp_addr (ip6, (TUint) 0); - if (size < PJ_INET6_ADDRSTRLEN) - return PJ_ETOOSMALL; + temp_addr.Output (str16); - TIp6Addr ip6; - pj_memcpy(ip6.u.iAddr8, src, 16); + pj_unicode_to_ansi ( (const wchar_t*) str16.PtrZ(), str16.Length(), + dst, size); - 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; + return PJ_SUCCESS; } else { - pj_assert(!"Unsupport address family"); - return PJ_EINVAL; + pj_assert (!"Unsupport address family"); + return PJ_EINVAL; } } @@ -451,7 +466,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; @@ -459,66 +474,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, rSock); - *p_sock = (pj_sock_t)pjSock; + CPjSocket *pjSock = new CPjSocket (af, rSock); + + *p_sock = (pj_sock_t) pjSock; return PJ_SUCCESS; } @@ -527,64 +546,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; @@ -595,318 +615,326 @@ 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); + + 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()); + 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; 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(); - 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); - rSock.Recv(data, flags, reqStatus, recvLen); - User::WaitForRequest(reqStatus); + rSock.Recv (data, flags, reqStatus, recvLen); + 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()); } } @@ -915,99 +943,103 @@ 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(), newSock); - newPjSock->SetConnected(true); + CPjSocket *newPjSock = new CPjSocket (pjSock->GetAf(), 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-1.0.2/pjlib/src/pj/timer_symbian.cpp b/sflphone-common/libs/pjproject-1.0.2/pjlib/src/pj/timer_symbian.cpp index 0a9dd8a937..4aff5f9564 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjlib/src/pj/timer_symbian.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/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-1.0.2/pjlib/src/pj/unicode_symbian.cpp b/sflphone-common/libs/pjproject-1.0.2/pjlib/src/pj/unicode_symbian.cpp index e9eb957f95..c1ce1e52e5 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjlib/src/pj/unicode_symbian.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/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-1.0.2/pjlib/src/pjlib++-test/main.cpp b/sflphone-common/libs/pjproject-1.0.2/pjlib/src/pjlib++-test/main.cpp index 6b749ad62d..f69f4cc75a 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjlib/src/pjlib++-test/main.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/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-1.0.2/pjlib/src/pjlib-test/main_symbian.cpp b/sflphone-common/libs/pjproject-1.0.2/pjlib/src/pjlib-test/main_symbian.cpp index e57b080d50..d1fd7828f3 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjlib/src/pjlib-test/main_symbian.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/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; } @@ -53,7 +55,7 @@ LOCAL_C void MainL() // test_main(); - console->Printf(_L(" [press any key]\n")); + console->Printf (_L (" [press any key]\n")); console->Getch(); CActiveScheduler::Stop(); @@ -61,60 +63,61 @@ LOCAL_C void MainL() 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); } class ProgramStarter : public CActive { -public: - static ProgramStarter *NewL(); - void Start(); - -protected: - ProgramStarter(); - void ConstructL(); - virtual void RunL(); - virtual void DoCancel(); - TInt RunError(TInt aError); - -private: - RTimer timer_; + + public: + static ProgramStarter *NewL(); + void Start(); + + protected: + ProgramStarter(); + void ConstructL(); + virtual void RunL(); + virtual void DoCancel(); + TInt RunError (TInt aError); + + private: + RTimer timer_; }; ProgramStarter::ProgramStarter() -: CActive(EPriorityNormal) + : CActive (EPriorityNormal) { } void ProgramStarter::ConstructL() { timer_.CreateLocal(); - CActiveScheduler::Add(this); + CActiveScheduler::Add (this); } ProgramStarter *ProgramStarter::NewL() { ProgramStarter *self = new (ELeave) ProgramStarter; - CleanupStack::PushL(self); + CleanupStack::PushL (self); self->ConstructL(); - CleanupStack::Pop(self); + CleanupStack::Pop (self); return self; } void ProgramStarter::Start() { - timer_.After(iStatus, 0); + timer_.After (iStatus, 0); SetActive(); } @@ -127,67 +130,74 @@ void ProgramStarter::DoCancel() { } -TInt ProgramStarter::RunError(TInt aError) +TInt ProgramStarter::RunError (TInt aError) { - PJ_UNUSED_ARG(aError); + PJ_UNUSED_ARG (aError); return KErrNone; } 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); ProgramStarter *starter = ProgramStarter::NewL(); starter->Start(); CActiveScheduler::Start(); - } +} // Global Functions -static void log_writer(int level, const char *buf, int len) +static void log_writer (int level, const char *buf, int len) { 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); - console->Write(aBuf); + pj_ansi_to_unicode (buf, len, buf16, PJ_ARRAY_SIZE (buf16)); + + TPtrC16 aBuf ( (const TUint16*) buf16, (TInt) len); + console->Write (aBuf); } 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; + __UHEAP_MARKEND; + return KErrNone; - } +} #endif /* if 0 */ diff --git a/sflphone-common/libs/pjproject-1.0.2/pjmedia/include/pjmedia-codec/config.h b/sflphone-common/libs/pjproject-1.0.2/pjmedia/include/pjmedia-codec/config.h index 88847b9c4e..3b1af93cb6 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjmedia/include/pjmedia-codec/config.h +++ b/sflphone-common/libs/pjproject-1.0.2/pjmedia/include/pjmedia-codec/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 __PJMEDIA_CODEC_CONFIG_H__ #define __PJMEDIA_CODEC_CONFIG_H__ @@ -118,7 +118,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 @@ -130,7 +130,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 diff --git a/sflphone-common/libs/pjproject-1.0.2/pjmedia/include/pjmedia/config.h b/sflphone-common/libs/pjproject-1.0.2/pjmedia/include/pjmedia/config.h index 866359e4c1..d52d0996ae 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjmedia/include/pjmedia/config.h +++ b/sflphone-common/libs/pjproject-1.0.2/pjmedia/include/pjmedia/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 __PJMEDIA_CONFIG_H__ #define __PJMEDIA_CONFIG_H__ @@ -60,7 +60,7 @@ /** Constant for Win32 MME sound backend. */ #define PJMEDIA_SOUND_WIN32_MME_SOUND 3 -/** When this is set, pjmedia will not provide any sound device backend. +/** When this is set, pjmedia will not provide any sound device backend. * Application will have to provide its own sound device backend * and link the application with it. */ @@ -106,7 +106,7 @@ /** * Specify whether delay buffer is used for sound device. - * When delay buffer is enabled, the sound device callback + * When delay buffer is enabled, the sound device callback * will be called one after another evenly. * The delay buffer also performs the best delay calculation * for the sound device, and will try to limit the delay caused @@ -137,21 +137,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. * @@ -165,7 +165,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). * @@ -248,13 +248,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: @@ -294,7 +294,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 @@ -302,7 +302,7 @@ /** * Max packet size to support. */ -#ifndef PJMEDIA_MAX_MTU +#ifndef PJMEDIA_MAX_MTU # define PJMEDIA_MAX_MTU 1500 #endif @@ -310,7 +310,7 @@ /** * DTMF/telephone-event duration, in timestamp. */ -#ifndef PJMEDIA_DTMF_DURATION +#ifndef PJMEDIA_DTMF_DURATION # define PJMEDIA_DTMF_DURATION 1600 /* in timestamp */ #endif @@ -320,7 +320,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 @@ -361,9 +361,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). @@ -375,7 +375,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) @@ -394,7 +394,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). */ @@ -404,13 +404,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. @@ -462,7 +462,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. @@ -490,7 +490,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. @@ -544,12 +544,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. */ @@ -565,7 +565,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. */ @@ -580,7 +580,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. * @@ -600,7 +600,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. @@ -688,8 +688,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. */ diff --git a/sflphone-common/libs/pjproject-1.0.2/pjmedia/src/pjmedia/symbian_sound.cpp b/sflphone-common/libs/pjproject-1.0.2/pjmedia/src/pjmedia/symbian_sound.cpp index 9aa762fa40..57e8ddbd6e 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjmedia/src/pjmedia/symbian_sound.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/pjmedia/src/pjmedia/symbian_sound.cpp @@ -1,5 +1,5 @@ /* $Id: symbian_sound.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 <pjmedia/sound.h> #include <pjmedia/errno.h> @@ -28,7 +28,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> @@ -45,8 +45,7 @@ #define POOL_SIZE 512 #define POOL_INC 512 -static pjmedia_snd_dev_info symbian_snd_dev_info = -{ +static pjmedia_snd_dev_info symbian_snd_dev_info = { "Symbian Sound Device", 1, 1, @@ -54,13 +53,14 @@ static pjmedia_snd_dev_info symbian_snd_dev_info = }; class CPjAudioInputEngine; + class CPjAudioOutputEngine; -/* - * PJMEDIA Sound Stream instance +/* + * PJMEDIA Sound Stream instance */ -struct pjmedia_snd_stream -{ + +struct pjmedia_snd_stream { // Pool pj_pool_t *pool; @@ -83,22 +83,45 @@ static pj_pool_factory *snd_pool_factory; /* * 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; } } @@ -106,13 +129,18 @@ static TInt get_clock_rate_cap(unsigned clock_rate) /* * 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; } } @@ -120,82 +148,83 @@ static TInt get_channel_cap(unsigned channel_count) /* * 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(pjmedia_snd_stream *parent_strm, - pjmedia_snd_rec_cb rec_cb, - void *user_data); - - static CPjAudioInputEngine *NewLC(pjmedia_snd_stream *parent_strm, - pjmedia_snd_rec_cb rec_cb, - void *user_data); - - pj_status_t StartRecord(); - void Stop(); - -private: - State state_; - pjmedia_snd_stream *parentStrm_; - pjmedia_snd_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_; - - // in some SymbianOS (e.g: OSv9.1), sometimes recorded size != requested framesize - // so let's provide a buffer to make sure the rec callback returns framesize as requested. - TUint8 *frameRecBuf_; - TInt frameRecBufLen_; - - CPjAudioInputEngine(pjmedia_snd_stream *parent_strm, - pjmedia_snd_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 (pjmedia_snd_stream *parent_strm, + pjmedia_snd_rec_cb rec_cb, + void *user_data); + + static CPjAudioInputEngine *NewLC (pjmedia_snd_stream *parent_strm, + pjmedia_snd_rec_cb rec_cb, + void *user_data); + + pj_status_t StartRecord(); + void Stop(); + + private: + State state_; + pjmedia_snd_stream *parentStrm_; + pjmedia_snd_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_; + + // in some SymbianOS (e.g: OSv9.1), sometimes recorded size != requested framesize + // so let's provide a buffer to make sure the rec callback returns framesize as requested. + TUint8 *frameRecBuf_; + TInt frameRecBufLen_; + + CPjAudioInputEngine (pjmedia_snd_stream *parent_strm, + pjmedia_snd_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(pjmedia_snd_stream *parent_strm, - pjmedia_snd_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->samples_per_frame * parent_strm->channel_count * BYTES_PER_SAMPLE), - frameRecBuf_(NULL), frameRecBufLen_(0) +CPjAudioInputEngine::CPjAudioInputEngine (pjmedia_snd_stream *parent_strm, + pjmedia_snd_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->samples_per_frame * parent_strm->channel_count * BYTES_PER_SAMPLE), + frameRecBuf_ (NULL), frameRecBufLen_ (0) { } @@ -205,7 +234,7 @@ CPjAudioInputEngine::~CPjAudioInputEngine() delete iStreamBuffer_; iStreamBuffer_ = NULL; - + delete [] frameRecBuf_; frameRecBuf_ = NULL; frameRecBufLen_ = 0; @@ -213,33 +242,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(pjmedia_snd_stream *parent, - pjmedia_snd_rec_cb rec_cb, - void *user_data) +CPjAudioInputEngine *CPjAudioInputEngine::NewLC (pjmedia_snd_stream *parent, + pjmedia_snd_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(pjmedia_snd_stream *parent, - pjmedia_snd_rec_cb rec_cb, - void *user_data) +CPjAudioInputEngine *CPjAudioInputEngine::NewL (pjmedia_snd_stream *parent, + pjmedia_snd_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; } @@ -249,42 +278,48 @@ 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_->channel_count); - iStreamSettings.iSampleRate = get_clock_rate_cap(parentStrm_->clock_rate); - pj_assert(iStreamSettings.iChannels != 0 && - iStreamSettings.iSampleRate != 0); + iStreamSettings.iChannels = get_channel_cap (parentStrm_->channel_count); + + iStreamSettings.iSampleRate = get_clock_rate_cap (parentStrm_->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_->clock_rate, + parentStrm_->channel_count)); - PJ_LOG(4,(THIS_FILE, "Opening sound device for capture, " - "clock rate=%d, channel count=%d..", - parentStrm_->clock_rate, - parentStrm_->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; } @@ -293,96 +328,104 @@ 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.Size() < frameLen_) { - pj_memcpy(frameRecBuf_ + frameRecBufLen_, (void*) aBuffer.Ptr(), aBuffer.Size()); - frameRecBufLen_ += aBuffer.Size(); + pj_memcpy (frameRecBuf_ + frameRecBufLen_, (void*) aBuffer.Ptr(), aBuffer.Size()); + frameRecBufLen_ += aBuffer.Size(); } if (frameRecBufLen_) { - while (frameRecBufLen_ >= frameLen_) { - // Call the callback. - recCb_(userData_, timeStamp_, frameRecBuf_, frameLen_); - // Increment timestamp. - timeStamp_ += parentStrm_->samples_per_frame; - - frameRecBufLen_ -= frameLen_; - pj_memmove(frameRecBuf_, frameRecBuf_+frameLen_, frameRecBufLen_); - } + while (frameRecBufLen_ >= frameLen_) { + // Call the callback. + recCb_ (userData_, timeStamp_, frameRecBuf_, frameLen_); + // Increment timestamp. + timeStamp_ += parentStrm_->samples_per_frame; + + frameRecBufLen_ -= frameLen_; + pj_memmove (frameRecBuf_, frameRecBuf_+frameLen_, frameRecBufLen_); + } } else { - // Call the callback. - recCb_(userData_, timeStamp_, (void*) aBuffer.Ptr(), aBuffer.Size()); - // Increment timestamp. - timeStamp_ += parentStrm_->samples_per_frame; + // Call the callback. + recCb_ (userData_, timeStamp_, (void*) aBuffer.Ptr(), aBuffer.Size()); + // Increment timestamp. + timeStamp_ += parentStrm_->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) { - snd_perror("Error in MaiscRecordComplete()", aError); + snd_perror ("Error in MaiscRecordComplete()", aError); } } @@ -397,55 +440,55 @@ void CPjAudioInputEngine::MaiscRecordComplete(TInt aError) class CPjAudioOutputEngine : public CBase, MMdaAudioOutputStreamCallback { -public: - enum State - { - STATE_INACTIVE, - STATE_ACTIVE, - }; - - ~CPjAudioOutputEngine(); - - static CPjAudioOutputEngine *NewL(pjmedia_snd_stream *parent_strm, - pjmedia_snd_play_cb play_cb, - void *user_data); - - static CPjAudioOutputEngine *NewLC(pjmedia_snd_stream *parent_strm, - pjmedia_snd_play_cb rec_cb, - void *user_data); - - pj_status_t StartPlay(); - void Stop(); - -private: - State state_; - pjmedia_snd_stream *parentStrm_; - pjmedia_snd_play_cb playCb_; - void *userData_; - CMdaAudioOutputStream *iOutputStream_; - TUint8 *frameBuf_; - unsigned frameBufSize_; - TPtrC8 frame_; - TInt lastError_; - unsigned timestamp_; - - CPjAudioOutputEngine(pjmedia_snd_stream *parent_strm, - pjmedia_snd_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 (pjmedia_snd_stream *parent_strm, + pjmedia_snd_play_cb play_cb, + void *user_data); + + static CPjAudioOutputEngine *NewLC (pjmedia_snd_stream *parent_strm, + pjmedia_snd_play_cb rec_cb, + void *user_data); + + pj_status_t StartPlay(); + void Stop(); + + private: + State state_; + pjmedia_snd_stream *parentStrm_; + pjmedia_snd_play_cb playCb_; + void *userData_; + CMdaAudioOutputStream *iOutputStream_; + TUint8 *frameBuf_; + unsigned frameBufSize_; + TPtrC8 frame_; + TInt lastError_; + unsigned timestamp_; + + CPjAudioOutputEngine (pjmedia_snd_stream *parent_strm, + pjmedia_snd_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(pjmedia_snd_stream *parent_strm, - pjmedia_snd_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 (pjmedia_snd_stream *parent_strm, + pjmedia_snd_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) { } @@ -453,37 +496,37 @@ CPjAudioOutputEngine::CPjAudioOutputEngine(pjmedia_snd_stream *parent_strm, void CPjAudioOutputEngine::ConstructL() { frameBufSize_ = parentStrm_->samples_per_frame * - parentStrm_->channel_count * - BYTES_PER_SAMPLE; + parentStrm_->channel_count * + BYTES_PER_SAMPLE; frameBuf_ = new TUint8[frameBufSize_]; } CPjAudioOutputEngine::~CPjAudioOutputEngine() { Stop(); - delete [] frameBuf_; + delete [] frameBuf_; } CPjAudioOutputEngine * -CPjAudioOutputEngine::NewLC(pjmedia_snd_stream *parent_strm, - pjmedia_snd_play_cb rec_cb, - void *user_data) -{ - CPjAudioOutputEngine* self = new (ELeave) CPjAudioOutputEngine(parent_strm, - rec_cb, - user_data); - CleanupStack::PushL(self); +CPjAudioOutputEngine::NewLC (pjmedia_snd_stream *parent_strm, + pjmedia_snd_play_cb rec_cb, + void *user_data) +{ + CPjAudioOutputEngine* self = new (ELeave) CPjAudioOutputEngine (parent_strm, + rec_cb, + user_data); + CleanupStack::PushL (self); self->ConstructL(); return self; } CPjAudioOutputEngine * -CPjAudioOutputEngine::NewL(pjmedia_snd_stream *parent_strm, - pjmedia_snd_play_cb play_cb, - void *user_data) +CPjAudioOutputEngine::NewL (pjmedia_snd_stream *parent_strm, + pjmedia_snd_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; } @@ -491,36 +534,42 @@ 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_->channel_count); - iStreamSettings.iSampleRate = get_clock_rate_cap(parentStrm_->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_->clock_rate, - parentStrm_->channel_count)); + iStreamSettings.iChannels = get_channel_cap (parentStrm_->channel_count); + + iStreamSettings.iSampleRate = get_clock_rate_cap (parentStrm_->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_->clock_rate, + parentStrm_->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; } @@ -529,109 +578,115 @@ 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 - // Wait until it's actually stopped - while (lastError_ == KRequestPending) - pj_symbianos_poll(-1, 100); + 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_->channel_count); - iSettings.iSampleRate = get_clock_rate_cap(parentStrm_->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. - pj_status_t status; - status = playCb_(this->userData_, timestamp_, frameBuf_, - frameBufSize_); - if (status != PJ_SUCCESS) { - this->Stop(); - return; - } - - // 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_->channel_count); + iSettings.iSampleRate = get_clock_rate_cap (parentStrm_->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. + pj_status_t status; + status = playCb_ (this->userData_, timestamp_, frameBuf_, + frameBufSize_); + + if (status != PJ_SUCCESS) { + this->Stop(); + return; + } + + // 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. + // Buffer successfully written, feed another one. + + // Call callback to retrieve frame from upstream. + pj_status_t status; + status = playCb_ (this->userData_, timestamp_, frameBuf_, + frameBufSize_); - // Call callback to retrieve frame from upstream. - pj_status_t status; - status = playCb_(this->userData_, timestamp_, frameBuf_, - frameBufSize_); - if (status != PJ_SUCCESS) { - this->Stop(); - return; - } + if (status != PJ_SUCCESS) { + this->Stop(); + return; + } - // Increment timestamp. - timestamp_ += (frameBufSize_ / BYTES_PER_SAMPLE); + // Increment timestamp. + timestamp_ += (frameBufSize_ / BYTES_PER_SAMPLE); - // Write to playback stream. - frame_.Set(frameBuf_, frameBufSize_); - iOutputStream_->WriteL(frame_); + // 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) { - snd_perror("Error in MaoscPlayComplete()", aError); + snd_perror ("Error in MaoscPlayComplete()", aError); } } @@ -643,7 +698,7 @@ void CPjAudioOutputEngine::MaoscPlayComplete(TInt aError) /* * Initialize sound subsystem. */ -PJ_DEF(pj_status_t) pjmedia_snd_init(pj_pool_factory *factory) +PJ_DEF (pj_status_t) pjmedia_snd_init (pj_pool_factory *factory) { snd_pool_factory = factory; return PJ_SUCCESS; @@ -652,7 +707,7 @@ PJ_DEF(pj_status_t) pjmedia_snd_init(pj_pool_factory *factory) /* * Get device count. */ -PJ_DEF(int) pjmedia_snd_get_dev_count(void) +PJ_DEF (int) pjmedia_snd_get_dev_count (void) { /* Always return 1 */ return 1; @@ -661,13 +716,14 @@ PJ_DEF(int) pjmedia_snd_get_dev_count(void) /* * Get device info. */ -PJ_DEF(const pjmedia_snd_dev_info*) pjmedia_snd_get_dev_info(unsigned index) +PJ_DEF (const pjmedia_snd_dev_info*) pjmedia_snd_get_dev_info (unsigned index) { /* Always return the default sound device */ if (index == (unsigned)-1) - index = 0; + index = 0; + + PJ_ASSERT_RETURN (index==0, NULL); - PJ_ASSERT_RETURN(index==0, NULL); return &symbian_snd_dev_info; } @@ -676,174 +732,209 @@ PJ_DEF(const pjmedia_snd_dev_info*) pjmedia_snd_get_dev_info(unsigned index) /* * Open sound recorder stream. */ -PJ_DEF(pj_status_t) pjmedia_snd_open_rec( int index, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - pjmedia_snd_rec_cb rec_cb, - void *user_data, - pjmedia_snd_stream **p_snd_strm) +PJ_DEF (pj_status_t) pjmedia_snd_open_rec (int index, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + pjmedia_snd_rec_cb rec_cb, + void *user_data, + pjmedia_snd_stream **p_snd_strm) { pj_pool_t *pool; pjmedia_snd_stream *strm; if (index==-1) index = 0; - - PJ_ASSERT_RETURN(index == 0, PJ_EINVAL); - PJ_ASSERT_RETURN(clock_rate && channel_count && samples_per_frame && - bits_per_sample && rec_cb && p_snd_strm, PJ_EINVAL); - pool = pj_pool_create(snd_pool_factory, POOL_NAME, POOL_SIZE, POOL_INC, - NULL); + PJ_ASSERT_RETURN (index == 0, PJ_EINVAL); + + PJ_ASSERT_RETURN (clock_rate && channel_count && samples_per_frame && + bits_per_sample && rec_cb && p_snd_strm, PJ_EINVAL); + + pool = pj_pool_create (snd_pool_factory, POOL_NAME, POOL_SIZE, POOL_INC, + NULL); + if (!pool) - return PJ_ENOMEM; + return PJ_ENOMEM; + + strm = (pjmedia_snd_stream*) pj_pool_zalloc (pool, + sizeof (pjmedia_snd_stream)); - strm = (pjmedia_snd_stream*) pj_pool_zalloc(pool, - sizeof(pjmedia_snd_stream)); strm->dir = PJMEDIA_DIR_CAPTURE; + strm->pool = pool; + strm->clock_rate = clock_rate; + strm->channel_count = channel_count; + strm->samples_per_frame = samples_per_frame; - PJ_ASSERT_RETURN(bits_per_sample == 16, PJ_EINVAL); - PJ_ASSERT_RETURN(get_clock_rate_cap(clock_rate) != 0, PJ_EINVAL); - PJ_ASSERT_RETURN(get_channel_cap(channel_count) != 0, PJ_EINVAL); + PJ_ASSERT_RETURN (bits_per_sample == 16, PJ_EINVAL); + + PJ_ASSERT_RETURN (get_clock_rate_cap (clock_rate) != 0, PJ_EINVAL); + + PJ_ASSERT_RETURN (get_channel_cap (channel_count) != 0, PJ_EINVAL); // Create the input stream. - TRAPD(err, strm->inEngine = CPjAudioInputEngine::NewL(strm, rec_cb, - user_data)); + TRAPD (err, strm->inEngine = CPjAudioInputEngine::NewL (strm, rec_cb, + user_data)); + if (err != KErrNone) { - pj_pool_release(pool); - return PJ_RETURN_OS_ERROR(err); + pj_pool_release (pool); + return PJ_RETURN_OS_ERROR (err); } // Done. *p_snd_strm = strm; + return PJ_SUCCESS; } -PJ_DEF(pj_status_t) pjmedia_snd_open_player( int index, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - pjmedia_snd_play_cb play_cb, - void *user_data, - pjmedia_snd_stream **p_snd_strm ) +PJ_DEF (pj_status_t) pjmedia_snd_open_player (int index, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + pjmedia_snd_play_cb play_cb, + void *user_data, + pjmedia_snd_stream **p_snd_strm) { pj_pool_t *pool; pjmedia_snd_stream *strm; if (index == -1) index = 0; - - PJ_ASSERT_RETURN(index == 0, PJ_EINVAL); - PJ_ASSERT_RETURN(clock_rate && channel_count && samples_per_frame && - bits_per_sample && play_cb && p_snd_strm, PJ_EINVAL); - pool = pj_pool_create(snd_pool_factory, POOL_NAME, POOL_SIZE, POOL_INC, - NULL); + PJ_ASSERT_RETURN (index == 0, PJ_EINVAL); + + PJ_ASSERT_RETURN (clock_rate && channel_count && samples_per_frame && + bits_per_sample && play_cb && p_snd_strm, PJ_EINVAL); + + pool = pj_pool_create (snd_pool_factory, POOL_NAME, POOL_SIZE, POOL_INC, + NULL); + if (!pool) - return PJ_ENOMEM; + return PJ_ENOMEM; + + strm = (pjmedia_snd_stream*) pj_pool_zalloc (pool, + sizeof (pjmedia_snd_stream)); + + strm->dir = PJMEDIA_DIR_PLAYBACK; - strm = (pjmedia_snd_stream*) pj_pool_zalloc(pool, - sizeof(pjmedia_snd_stream)); - strm->dir = PJMEDIA_DIR_PLAYBACK; strm->pool = pool; + strm->clock_rate = clock_rate; + strm->channel_count = channel_count; + strm->samples_per_frame = samples_per_frame; - PJ_ASSERT_RETURN(bits_per_sample == 16, PJ_EINVAL); - PJ_ASSERT_RETURN(get_clock_rate_cap(clock_rate) != 0, PJ_EINVAL); - PJ_ASSERT_RETURN(get_channel_cap(channel_count) != 0, PJ_EINVAL); + PJ_ASSERT_RETURN (bits_per_sample == 16, PJ_EINVAL); + + PJ_ASSERT_RETURN (get_clock_rate_cap (clock_rate) != 0, PJ_EINVAL); + + PJ_ASSERT_RETURN (get_channel_cap (channel_count) != 0, PJ_EINVAL); // Create the output stream. - TRAPD(err, strm->outEngine = CPjAudioOutputEngine::NewL(strm, play_cb, - user_data)); + TRAPD (err, strm->outEngine = CPjAudioOutputEngine::NewL (strm, play_cb, + user_data)); + if (err != KErrNone) { - pj_pool_release(pool); - return PJ_RETURN_OS_ERROR(err); + pj_pool_release (pool); + return PJ_RETURN_OS_ERROR (err); } // Done. *p_snd_strm = strm; + return PJ_SUCCESS; } -PJ_DEF(pj_status_t) pjmedia_snd_open( int rec_id, - int play_id, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - pjmedia_snd_rec_cb rec_cb, - pjmedia_snd_play_cb play_cb, - void *user_data, - pjmedia_snd_stream **p_snd_strm) +PJ_DEF (pj_status_t) pjmedia_snd_open (int rec_id, + int play_id, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + pjmedia_snd_rec_cb rec_cb, + pjmedia_snd_play_cb play_cb, + void *user_data, + pjmedia_snd_stream **p_snd_strm) { pj_pool_t *pool; pjmedia_snd_stream *strm; if (rec_id == -1) rec_id = 0; + if (play_id == -1) play_id = 0; - - PJ_ASSERT_RETURN(rec_id == 0 && play_id == 0, PJ_EINVAL); - PJ_ASSERT_RETURN(clock_rate && channel_count && samples_per_frame && - bits_per_sample && rec_cb && play_cb && p_snd_strm, - PJ_EINVAL); - - pool = pj_pool_create(snd_pool_factory, POOL_NAME, POOL_SIZE, POOL_INC, - NULL); + + PJ_ASSERT_RETURN (rec_id == 0 && play_id == 0, PJ_EINVAL); + + PJ_ASSERT_RETURN (clock_rate && channel_count && samples_per_frame && + bits_per_sample && rec_cb && play_cb && p_snd_strm, + PJ_EINVAL); + + pool = pj_pool_create (snd_pool_factory, POOL_NAME, POOL_SIZE, POOL_INC, + NULL); + if (!pool) - return PJ_ENOMEM; + return PJ_ENOMEM; + + strm = (pjmedia_snd_stream*) pj_pool_zalloc (pool, + sizeof (pjmedia_snd_stream)); - strm = (pjmedia_snd_stream*) pj_pool_zalloc(pool, - sizeof(pjmedia_snd_stream)); strm->dir = PJMEDIA_DIR_CAPTURE_PLAYBACK; + strm->pool = pool; + strm->clock_rate = clock_rate; + strm->channel_count = channel_count; + strm->samples_per_frame = samples_per_frame; - PJ_ASSERT_RETURN(bits_per_sample == 16, PJ_EINVAL); - PJ_ASSERT_RETURN(get_clock_rate_cap(clock_rate) != 0, PJ_EINVAL); - PJ_ASSERT_RETURN(get_channel_cap(channel_count) != 0, PJ_EINVAL); + PJ_ASSERT_RETURN (bits_per_sample == 16, PJ_EINVAL); + + PJ_ASSERT_RETURN (get_clock_rate_cap (clock_rate) != 0, PJ_EINVAL); + + PJ_ASSERT_RETURN (get_channel_cap (channel_count) != 0, PJ_EINVAL); // Create the output stream. - TRAPD(err, strm->outEngine = CPjAudioOutputEngine::NewL(strm, play_cb, - user_data)); + TRAPD (err, strm->outEngine = CPjAudioOutputEngine::NewL (strm, play_cb, + user_data)); + if (err != KErrNone) { - pj_pool_release(pool); - return PJ_RETURN_OS_ERROR(err); + pj_pool_release (pool); + return PJ_RETURN_OS_ERROR (err); } // Create the input stream. - TRAPD(err1, strm->inEngine = CPjAudioInputEngine::NewL(strm, rec_cb, - user_data)); + TRAPD (err1, strm->inEngine = CPjAudioInputEngine::NewL (strm, rec_cb, + user_data)); + if (err1 != KErrNone) { strm->inEngine = NULL; delete strm->outEngine; - strm->outEngine = NULL; - pj_pool_release(pool); - return PJ_RETURN_OS_ERROR(err1); + strm->outEngine = NULL; + pj_pool_release (pool); + return PJ_RETURN_OS_ERROR (err1); } // Done. *p_snd_strm = strm; + return PJ_SUCCESS; } /* * Get stream info. */ -PJ_DEF(pj_status_t) pjmedia_snd_stream_get_info(pjmedia_snd_stream *strm, - pjmedia_snd_stream_info *pi) +PJ_DEF (pj_status_t) pjmedia_snd_stream_get_info (pjmedia_snd_stream *strm, + pjmedia_snd_stream_info *pi) { - PJ_ASSERT_RETURN(strm && pi, PJ_EINVAL); + PJ_ASSERT_RETURN (strm && pi, PJ_EINVAL); - pj_bzero(pi, sizeof(*pi)); + pj_bzero (pi, sizeof (*pi)); pi->dir = strm->dir; pi->play_id = 0; pi->rec_id = 0; @@ -860,71 +951,74 @@ PJ_DEF(pj_status_t) pjmedia_snd_stream_get_info(pjmedia_snd_stream *strm, } -PJ_DEF(pj_status_t) pjmedia_snd_stream_start(pjmedia_snd_stream *stream) +PJ_DEF (pj_status_t) pjmedia_snd_stream_start (pjmedia_snd_stream *stream) { pj_status_t status; - - PJ_ASSERT_RETURN(stream != NULL, PJ_EINVAL); - + + PJ_ASSERT_RETURN (stream != NULL, PJ_EINVAL); + if (stream->outEngine) { - status = stream->outEngine->StartPlay(); - if (status != PJ_SUCCESS) - return status; + status = stream->outEngine->StartPlay(); + + if (status != PJ_SUCCESS) + return status; } - + if (stream->inEngine) { - status = stream->inEngine->StartRecord(); - if (status != PJ_SUCCESS) - return status; + status = stream->inEngine->StartRecord(); + + if (status != PJ_SUCCESS) + return status; } - + return PJ_SUCCESS; } -PJ_DEF(pj_status_t) pjmedia_snd_stream_stop(pjmedia_snd_stream *stream) +PJ_DEF (pj_status_t) pjmedia_snd_stream_stop (pjmedia_snd_stream *stream) { - PJ_ASSERT_RETURN(stream != NULL, PJ_EINVAL); - + PJ_ASSERT_RETURN (stream != NULL, PJ_EINVAL); + if (stream->inEngine) { - stream->inEngine->Stop(); + stream->inEngine->Stop(); } - + if (stream->outEngine) { - stream->outEngine->Stop(); + stream->outEngine->Stop(); } - + return PJ_SUCCESS; } -PJ_DEF(pj_status_t) pjmedia_snd_stream_close(pjmedia_snd_stream *stream) +PJ_DEF (pj_status_t) pjmedia_snd_stream_close (pjmedia_snd_stream *stream) { pj_pool_t *pool; - - PJ_ASSERT_RETURN(stream != NULL, PJ_EINVAL); - + + PJ_ASSERT_RETURN (stream != NULL, PJ_EINVAL); + if (stream->inEngine) { - delete stream->inEngine; - stream->inEngine = NULL; + delete stream->inEngine; + stream->inEngine = NULL; } if (stream->outEngine) { - delete stream->outEngine; - stream->outEngine = NULL; + delete stream->outEngine; + stream->outEngine = NULL; } - + pool = stream->pool; - if (pool) { - stream->pool = NULL; - pj_pool_release(pool); + + if (pool) { + stream->pool = NULL; + pj_pool_release (pool); } - + return PJ_SUCCESS; } -PJ_DEF(pj_status_t) pjmedia_snd_deinit(void) +PJ_DEF (pj_status_t) pjmedia_snd_deinit (void) { /* Nothing to do */ return PJ_SUCCESS; @@ -934,11 +1028,11 @@ PJ_DEF(pj_status_t) pjmedia_snd_deinit(void) /* * Set sound latency. */ -PJ_DEF(pj_status_t) pjmedia_snd_set_latency(unsigned input_latency, - unsigned output_latency) +PJ_DEF (pj_status_t) pjmedia_snd_set_latency (unsigned input_latency, + unsigned output_latency) { /* Nothing to do */ - PJ_UNUSED_ARG(input_latency); - PJ_UNUSED_ARG(output_latency); + PJ_UNUSED_ARG (input_latency); + PJ_UNUSED_ARG (output_latency); return PJ_SUCCESS; } diff --git a/sflphone-common/libs/pjproject-1.0.2/pjmedia/src/pjmedia/symbian_sound_aps.cpp b/sflphone-common/libs/pjproject-1.0.2/pjmedia/src/pjmedia/symbian_sound_aps.cpp index 85cf6106ae..9dcaf61030 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjmedia/src/pjmedia/symbian_sound_aps.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/pjmedia/src/pjmedia/symbian_sound_aps.cpp @@ -1,5 +1,5 @@ /* $Id: symbian_sound_aps.cpp 2540 2009-03-23 13:18:19Z 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/sound.h> #include <pjmedia/alaw_ulaw.h> @@ -46,8 +46,7 @@ # define TRACE_(st) #endif -static pjmedia_snd_dev_info symbian_snd_dev_info = -{ +static pjmedia_snd_dev_info symbian_snd_dev_info = { "Symbian Sound Device (APS)", 1, 1, @@ -61,13 +60,14 @@ extern TPtrC APP_UID; static pj_bool_t act_loudspeaker = PJ_FALSE; /* Forward declaration of CPjAudioEngine */ + class CPjAudioEngine; -/* - * PJMEDIA Sound Stream instance +/* + * PJMEDIA Sound Stream instance */ -struct pjmedia_snd_stream -{ + +struct pjmedia_snd_stream { // Pool pj_pool_t *pool; @@ -87,274 +87,305 @@ static pj_pool_factory *snd_pool_factory; /* * 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)); } - + ////////////////////////////////////////////////////////////////////////////// // /** * Abstract class for handler of callbacks from APS client. */ + class MQueueHandlerObserver { -public: - virtual void InputStreamInitialized(const TInt aStatus) = 0; - virtual void OutputStreamInitialized(const TInt aStatus) = 0; - virtual void NotifyError(const TInt aError) = 0; - virtual void RecCb(TAPSCommBuffer &buffer) = 0; - virtual void PlayCb(TAPSCommBuffer &buffer) = 0; + public: + virtual void InputStreamInitialized (const TInt aStatus) = 0; + virtual void OutputStreamInitialized (const TInt aStatus) = 0; + virtual void NotifyError (const TInt aError) = 0; + + virtual void RecCb (TAPSCommBuffer &buffer) = 0; + virtual void PlayCb (TAPSCommBuffer &buffer) = 0; }; /** * 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, - TQueueHandlerType aType) - { - CQueueHandler* self = new (ELeave) CQueueHandler(aObserver, aQ, 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, + TQueueHandlerType aType) { + CQueueHandler* self = new (ELeave) CQueueHandler (aObserver, aQ, 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, - TQueueHandlerType aType) - : CActive(CActive::EPriorityHigh), - iQ(aQ), 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(); + } + + private: + // Constructor + CQueueHandler (MQueueHandlerObserver* aObserver, + RMsgQueue<TAPSCommBuffer>* aQ, + TQueueHandlerType aType) + : CActive (CActive::EPriorityHigh), + iQ (aQ), iObserver (aObserver), iType (aType) { + CActiveScheduler::Add (this); - // Second phase constructor - void ConstructL() {} - - // Inherited from CActive - void DoCancel() { iQ->CancelDataAvailable(); } - - void RunL() { - if (iStatus != KErrNone) { - iObserver->NotifyError(iStatus.Int()); - return; - } - - 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); - } - break; - - // Callbacks from the APS main thread - case EPlayCommQueue: - switch (buffer.iCommand) { - case EAPSPlayData: - if (buffer.iStatus == KErrUnderflow) { - iObserver->PlayCb(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: - if (buffer.iStatus == KErrNone) { - iObserver->InputStreamInitialized(buffer.iStatus); - break; - } - case EAPSRecordData: - iObserver->NotifyError(buffer.iStatus); - break; - default: - break; - } - break; - - default: - break; + // use lower priority for comm queues + + if ( (iType == ERecordCommQueue) || (iType == EPlayCommQueue)) + SetPriority (CActive::EPriorityStandard); } - // issue next request - iQ->NotifyDataAvailable(iStatus); - SetActive(); - } + // Second phase constructor + void ConstructL() {} + + // Inherited from CActive + void DoCancel() { + iQ->CancelDataAvailable(); + } + + void RunL() { + if (iStatus != KErrNone) { + iObserver->NotifyError (iStatus.Int()); + return; + } + + 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); + } + + break; + + // Callbacks from the APS main thread - // Data - RMsgQueue<TAPSCommBuffer> *iQ; // (not owned) - MQueueHandlerObserver *iObserver; // (not owned) - TQueueHandlerType iType; + case EPlayCommQueue: + + switch (buffer.iCommand) { + + case EAPSPlayData: + + if (buffer.iStatus == KErrUnderflow) { + iObserver->PlayCb (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: + + if (buffer.iStatus == KErrNone) { + iObserver->InputStreamInitialized (buffer.iStatus); + break; + } + + case EAPSRecordData: + + iObserver->NotifyError (buffer.iStatus); + break; + + default: + break; + } + + break; + + default: + break; + } + + // issue next request + iQ->NotifyDataAvailable (iStatus); + + SetActive(); + } + + // Data + RMsgQueue<TAPSCommBuffer> *iQ; // (not owned) + MQueueHandlerObserver *iObserver; // (not owned) + TQueueHandlerType iType; }; /* * Implementation: Symbian Input & Output Stream. */ + class CPjAudioEngine : public CBase, MQueueHandlerObserver { -public: - enum State - { - STATE_NULL, - STATE_READY, - STATE_STREAMING - }; - - ~CPjAudioEngine(); - - static CPjAudioEngine *NewL(pjmedia_snd_stream *parent_strm, - pjmedia_snd_rec_cb rec_cb, - pjmedia_snd_play_cb play_cb, - void *user_data); - - TInt StartL(); - void Stop(); - - TInt ActivateSpeaker(TBool active); - -private: - CPjAudioEngine(pjmedia_snd_stream *parent_strm, - pjmedia_snd_rec_cb rec_cb, - pjmedia_snd_play_cb play_cb, - void *user_data); - 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); - - virtual void RecCb(TAPSCommBuffer &buffer); - virtual void PlayCb(TAPSCommBuffer &buffer); - - State state_; - pjmedia_snd_stream *parentStrm_; - pjmedia_snd_rec_cb recCb_; - pjmedia_snd_play_cb playCb_; - void *userData_; - pj_uint32_t TsPlay_; - pj_uint32_t TsRec_; - - RAPSSession iSession; - TAPSInitSettings iSettings; - RMsgQueue<TAPSCommBuffer> iReadQ; - RMsgQueue<TAPSCommBuffer> iReadCommQ; - RMsgQueue<TAPSCommBuffer> iWriteQ; - RMsgQueue<TAPSCommBuffer> iWriteCommQ; - - CQueueHandler *iPlayCommHandler; - CQueueHandler *iRecCommHandler; - CQueueHandler *iRecHandler; - - static pj_uint8_t aps_samples_per_frame; - - pj_int16_t *play_buf; - pj_uint16_t play_buf_len; - pj_uint16_t play_buf_start; - pj_int16_t *rec_buf; - pj_uint16_t rec_buf_len; + + public: + enum State { + STATE_NULL, + STATE_READY, + STATE_STREAMING + }; + + ~CPjAudioEngine(); + + static CPjAudioEngine *NewL (pjmedia_snd_stream *parent_strm, + pjmedia_snd_rec_cb rec_cb, + pjmedia_snd_play_cb play_cb, + void *user_data); + + TInt StartL(); + void Stop(); + + TInt ActivateSpeaker (TBool active); + + private: + CPjAudioEngine (pjmedia_snd_stream *parent_strm, + pjmedia_snd_rec_cb rec_cb, + pjmedia_snd_play_cb play_cb, + void *user_data); + 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); + + virtual void RecCb (TAPSCommBuffer &buffer); + virtual void PlayCb (TAPSCommBuffer &buffer); + + State state_; + pjmedia_snd_stream *parentStrm_; + pjmedia_snd_rec_cb recCb_; + pjmedia_snd_play_cb playCb_; + void *userData_; + pj_uint32_t TsPlay_; + pj_uint32_t TsRec_; + + RAPSSession iSession; + TAPSInitSettings iSettings; + RMsgQueue<TAPSCommBuffer> iReadQ; + RMsgQueue<TAPSCommBuffer> iReadCommQ; + RMsgQueue<TAPSCommBuffer> iWriteQ; + RMsgQueue<TAPSCommBuffer> iWriteCommQ; + + CQueueHandler *iPlayCommHandler; + CQueueHandler *iRecCommHandler; + CQueueHandler *iRecHandler; + + static pj_uint8_t aps_samples_per_frame; + + pj_int16_t *play_buf; + pj_uint16_t play_buf_len; + pj_uint16_t play_buf_start; + pj_int16_t *rec_buf; + pj_uint16_t rec_buf_len; }; pj_uint8_t CPjAudioEngine::aps_samples_per_frame = 0; -CPjAudioEngine* CPjAudioEngine::NewL(pjmedia_snd_stream *parent_strm, - pjmedia_snd_rec_cb rec_cb, - pjmedia_snd_play_cb play_cb, - void *user_data) +CPjAudioEngine* CPjAudioEngine::NewL (pjmedia_snd_stream *parent_strm, + pjmedia_snd_rec_cb rec_cb, + pjmedia_snd_play_cb play_cb, + void *user_data) { - CPjAudioEngine* self = new (ELeave) CPjAudioEngine(parent_strm, - rec_cb, play_cb, - user_data); - CleanupStack::PushL(self); + CPjAudioEngine* self = new (ELeave) CPjAudioEngine (parent_strm, + rec_cb, play_cb, + user_data); + CleanupStack::PushL (self); self->ConstructL(); - CleanupStack::Pop(self); + CleanupStack::Pop (self); return self; } -CPjAudioEngine::CPjAudioEngine(pjmedia_snd_stream *parent_strm, - pjmedia_snd_rec_cb rec_cb, - pjmedia_snd_play_cb play_cb, - void *user_data) - : state_(STATE_NULL), - parentStrm_(parent_strm), - recCb_(rec_cb), - playCb_(play_cb), - userData_(user_data), - iPlayCommHandler(0), - iRecCommHandler(0), - iRecHandler(0) +CPjAudioEngine::CPjAudioEngine (pjmedia_snd_stream *parent_strm, + pjmedia_snd_rec_cb rec_cb, + pjmedia_snd_play_cb play_cb, + void *user_data) + : state_ (STATE_NULL), + parentStrm_ (parent_strm), + recCb_ (rec_cb), + playCb_ (play_cb), + userData_ (user_data), + iPlayCommHandler (0), + iRecCommHandler (0), + iRecHandler (0) { } @@ -372,51 +403,59 @@ 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_->dir != PJMEDIA_DIR_PLAYBACK) { - iReadQ.Close(); - iReadCommQ.Close(); - } - iWriteQ.Close(); - iWriteCommQ.Close(); + if (parentStrm_->dir != PJMEDIA_DIR_PLAYBACK) { + iReadQ.Close(); + iReadCommQ.Close(); + } + + iWriteQ.Close(); + + iWriteCommQ.Close(); } } TInt CPjAudioEngine::InitPlayL() { if (state_ == STATE_STREAMING || state_ == STATE_READY) - return 0; + return 0; + + TInt err = iSession.InitializePlayer (iSettings); - TInt err = iSession.InitializePlayer(iSettings); 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 = iSettings.iGlobal; - buf2.Append(_L("PlayQueue")); + + buf2.Append (_L ("PlayQueue")); + TBuf<128> buf3 = iSettings.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, - CQueueHandler::EPlayCommQueue); + iPlayCommHandler = CQueueHandler::NewL (this, + &iWriteCommQ, + CQueueHandler::EPlayCommQueue); // Start observing APS callbacks on output stream message queue iPlayCommHandler->Start(); @@ -427,48 +466,53 @@ TInt CPjAudioEngine::InitPlayL() TInt CPjAudioEngine::InitRecL() { if (state_ == STATE_STREAMING || state_ == STATE_READY) - return 0; + return 0; // Initialize input stream device - TInt err = iSession.InitializeRecorder(iSettings); + TInt err = iSession.InitializeRecorder (iSettings); + if (err != KErrNone) { - snd_perror("Failed to initialize recorder", err); - return err; + snd_perror ("Failed to initialize recorder", err); + return err; } TBuf<128> buf1 = iSettings.iGlobal; - buf1.Append(_L("RecordQueue")); + + buf1.Append (_L ("RecordQueue")); TBuf<128> buf4 = iSettings.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 - iRecCommHandler = CQueueHandler::NewL(this, - &iReadCommQ, - CQueueHandler::ERecordCommQueue); + iRecCommHandler = CQueueHandler::NewL (this, + &iReadCommQ, + CQueueHandler::ERecordCommQueue); // Start observing APS callbacks from on input stream message queue iRecCommHandler->Start(); - + return 0; } TInt CPjAudioEngine::StartL() { TInt err = iSession.Connect(); + if (err != KErrNone && err != KErrAlreadyExists) - return err; + return err; if (state_ == STATE_READY) - return StartStreamL(); + return StartStreamL(); - // Even if only capturer are opened, playback thread of APS Server need + // 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. return InitPlayL(); } @@ -485,54 +529,60 @@ void CPjAudioEngine::Stop() void CPjAudioEngine::ConstructL() { - iSettings.iFourCC = TFourCC(KMCPFourCCIdG711); + iSettings.iFourCC = TFourCC (KMCPFourCCIdG711); iSettings.iGlobal = APP_UID; - iSettings.iPriority = TMdaPriority(100); - iSettings.iPreference = TMdaPriorityPreference(0x05210001); + iSettings.iPriority = TMdaPriority (100); + iSettings.iPreference = TMdaPriorityPreference (0x05210001); iSettings.iSettings.iChannels = EMMFMono; iSettings.iSettings.iSampleRate = EMMFSampleRate8000Hz; iSettings.iSettings.iVolume = 0; - + /* play_buf size is samples per frame of parent stream. */ - play_buf = (pj_int16_t*)pj_pool_alloc(parentStrm_->pool, - parentStrm_->samples_per_frame << 1); + play_buf = (pj_int16_t*) pj_pool_alloc (parentStrm_->pool, + parentStrm_->samples_per_frame << 1); play_buf_len = 0; play_buf_start = 0; - + /* rec_buf size is samples per frame of parent stream. */ - rec_buf = (pj_int16_t*)pj_pool_alloc(parentStrm_->pool, - parentStrm_->samples_per_frame << 1); + rec_buf = (pj_int16_t*) pj_pool_alloc (parentStrm_->pool, + parentStrm_->samples_per_frame << 1); rec_buf_len = 0; } TInt CPjAudioEngine::StartStreamL() { if (state_ == STATE_STREAMING) - return 0; + return 0; - iSession.SetCng(EFalse); - iSession.SetVadMode(EFalse); - iSession.SetPlc(EFalse); - iSession.SetEncoderMode(EULawOr30ms); - iSession.SetDecoderMode(EULawOr30ms); - iSession.ActivateLoudspeaker(act_loudspeaker); + iSession.SetCng (EFalse); + + iSession.SetVadMode (EFalse); + + iSession.SetPlc (EFalse); + + iSession.SetEncoderMode (EULawOr30ms); + + iSession.SetDecoderMode (EULawOr30ms); + + iSession.ActivateLoudspeaker (act_loudspeaker); // Not only playback if (parentStrm_->dir != PJMEDIA_DIR_PLAYBACK) { - iRecHandler = CQueueHandler::NewL(this, &iReadQ, - CQueueHandler::ERecordQueue); - iRecHandler->Start(); - iSession.Read(); - TRACE_((THIS_FILE, "APS recorder started")); + iRecHandler = CQueueHandler::NewL (this, &iReadQ, + CQueueHandler::ERecordQueue); + iRecHandler->Start(); + iSession.Read(); + TRACE_ ( (THIS_FILE, "APS recorder started")); } // Not only capture if (parentStrm_->dir != PJMEDIA_DIR_CAPTURE) { - iSession.Write(); - TRACE_((THIS_FILE, "APS player started")); + iSession.Write(); + TRACE_ ( (THIS_FILE, "APS player started")); } state_ = STATE_STREAMING; + return 0; } @@ -540,117 +590,121 @@ TInt CPjAudioEngine::StartStreamL() // Inherited from MQueueHandlerObserver // -void CPjAudioEngine::InputStreamInitialized(const TInt aStatus) +void CPjAudioEngine::InputStreamInitialized (const TInt aStatus) { - TRACE_((THIS_FILE, "InputStreamInitialized %d", aStatus)); + TRACE_ ( (THIS_FILE, "InputStreamInitialized %d", aStatus)); state_ = STATE_READY; + if (aStatus == KErrNone) { - StartStreamL(); + StartStreamL(); } } -void CPjAudioEngine::OutputStreamInitialized(const TInt aStatus) +void CPjAudioEngine::OutputStreamInitialized (const TInt aStatus) { - TRACE_((THIS_FILE, "OutputStreamInitialized %d", aStatus)); + TRACE_ ( (THIS_FILE, "OutputStreamInitialized %d", aStatus)); if (aStatus == KErrNone) { - if (parentStrm_->dir == PJMEDIA_DIR_PLAYBACK) { - state_ = STATE_READY; - // Only playback, start directly - StartStreamL(); - } else - InitRecL(); + if (parentStrm_->dir == PJMEDIA_DIR_PLAYBACK) { + state_ = STATE_READY; + // Only playback, start directly + StartStreamL(); + } 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); } -void CPjAudioEngine::RecCb(TAPSCommBuffer &buffer) +void CPjAudioEngine::RecCb (TAPSCommBuffer &buffer) { - pj_assert(buffer.iBuffer[0] == 1 && buffer.iBuffer[1] == 0); + pj_assert (buffer.iBuffer[0] == 1 && buffer.iBuffer[1] == 0); - /* Detect the recorder G.711 frame size, player frame size will follow - * this recorder frame size. + /* Detect the recorder G.711 frame size, player frame size will follow + * this recorder frame size. */ + if (CPjAudioEngine::aps_samples_per_frame == 0) { - CPjAudioEngine::aps_samples_per_frame = buffer.iBuffer.Length() < 160? - 80 : 160; - TRACE_((THIS_FILE, "Detected APS G.711 frame size = %u samples", - CPjAudioEngine::aps_samples_per_frame)); + CPjAudioEngine::aps_samples_per_frame = buffer.iBuffer.Length() < 160? + 80 : 160; + TRACE_ ( (THIS_FILE, "Detected APS G.711 frame size = %u samples", + CPjAudioEngine::aps_samples_per_frame)); } /* Decode APS buffer (coded in G.711) and put the PCM result into rec_buf. - * Whenever rec_buf is full, call parent stream callback. - */ + * Whenever rec_buf is full, call parent stream callback. + */ unsigned dec_len = 0; while (dec_len < CPjAudioEngine::aps_samples_per_frame) { - unsigned tmp; - - tmp = PJ_MIN(parentStrm_->samples_per_frame - rec_buf_len, - CPjAudioEngine::aps_samples_per_frame - dec_len); - pjmedia_ulaw_decode(&rec_buf[rec_buf_len], - buffer.iBuffer.Ptr() + 2 + dec_len, - tmp); - rec_buf_len += tmp; - dec_len += tmp; - - pj_assert(rec_buf_len <= parentStrm_->samples_per_frame); - - if (rec_buf_len == parentStrm_->samples_per_frame) { - recCb_(userData_, 0, rec_buf, rec_buf_len << 1); - rec_buf_len = 0; - } + unsigned tmp; + + tmp = PJ_MIN (parentStrm_->samples_per_frame - rec_buf_len, + CPjAudioEngine::aps_samples_per_frame - dec_len); + pjmedia_ulaw_decode (&rec_buf[rec_buf_len], + buffer.iBuffer.Ptr() + 2 + dec_len, + tmp); + rec_buf_len += tmp; + dec_len += tmp; + + pj_assert (rec_buf_len <= parentStrm_->samples_per_frame); + + if (rec_buf_len == parentStrm_->samples_per_frame) { + recCb_ (userData_, 0, rec_buf, rec_buf_len << 1); + rec_buf_len = 0; + } } } -void CPjAudioEngine::PlayCb(TAPSCommBuffer &buffer) +void CPjAudioEngine::PlayCb (TAPSCommBuffer &buffer) { buffer.iCommand = CQueueHandler::EAPSPlayData; buffer.iStatus = 0; buffer.iBuffer.Zero(); - buffer.iBuffer.Append(1); - buffer.iBuffer.Append(0); + buffer.iBuffer.Append (1); + buffer.iBuffer.Append (0); /* Send 10ms silence frame if frame size hasn't been known. */ + if (CPjAudioEngine::aps_samples_per_frame == 0) { - pjmedia_zero_samples(play_buf, 80); - pjmedia_ulaw_encode((pj_uint8_t*)play_buf, play_buf, 80); - buffer.iBuffer.Append((TUint8*)play_buf, 80); - iWriteQ.Send(buffer); - return; + pjmedia_zero_samples (play_buf, 80); + pjmedia_ulaw_encode ( (pj_uint8_t*) play_buf, play_buf, 80); + buffer.iBuffer.Append ( (TUint8*) play_buf, 80); + iWriteQ.Send (buffer); + return; } - + unsigned enc_len = 0; - + /* Call parent stream callback to get PCM samples to play, - * encode the PCM samples into G.711 and put it into APS buffer. + * encode the PCM samples into G.711 and put it into APS buffer. */ + while (enc_len < CPjAudioEngine::aps_samples_per_frame) { - if (play_buf_len == 0) { - playCb_(userData_, 0, play_buf, parentStrm_->samples_per_frame<<1); - play_buf_len = parentStrm_->samples_per_frame; - play_buf_start = 0; - } - - unsigned tmp; - - tmp = PJ_MIN(play_buf_len, - CPjAudioEngine::aps_samples_per_frame - enc_len); - pjmedia_ulaw_encode((pj_uint8_t*)&play_buf[play_buf_start], - &play_buf[play_buf_start], - tmp); - buffer.iBuffer.Append((TUint8*)&play_buf[play_buf_start], tmp); - enc_len += tmp; - play_buf_len -= tmp; - play_buf_start += tmp; + if (play_buf_len == 0) { + playCb_ (userData_, 0, play_buf, parentStrm_->samples_per_frame<<1); + play_buf_len = parentStrm_->samples_per_frame; + play_buf_start = 0; + } + + unsigned tmp; + + tmp = PJ_MIN (play_buf_len, + CPjAudioEngine::aps_samples_per_frame - enc_len); + pjmedia_ulaw_encode ( (pj_uint8_t*) &play_buf[play_buf_start], + &play_buf[play_buf_start], + tmp); + buffer.iBuffer.Append ( (TUint8*) &play_buf[play_buf_start], tmp); + enc_len += tmp; + play_buf_len -= tmp; + play_buf_start += tmp; } - iWriteQ.Send(buffer); + iWriteQ.Send (buffer); } // @@ -658,14 +712,16 @@ void CPjAudioEngine::PlayCb(TAPSCommBuffer &buffer) ///////////////////////////////////////////////////////////// -TInt CPjAudioEngine::ActivateSpeaker(TBool active) +TInt CPjAudioEngine::ActivateSpeaker (TBool active) { if (state_ == STATE_READY || state_ == STATE_STREAMING) { - iSession.ActivateLoudspeaker(active); - return KErrNone; + iSession.ActivateLoudspeaker (active); + return KErrNone; } + return KErrNotReady; } + ////////////////////////////////////////////////////////////////////////////// // @@ -673,7 +729,7 @@ TInt CPjAudioEngine::ActivateSpeaker(TBool active) /* * Initialize sound subsystem. */ -PJ_DEF(pj_status_t) pjmedia_snd_init(pj_pool_factory *factory) +PJ_DEF (pj_status_t) pjmedia_snd_init (pj_pool_factory *factory) { snd_pool_factory = factory; return PJ_SUCCESS; @@ -682,7 +738,7 @@ PJ_DEF(pj_status_t) pjmedia_snd_init(pj_pool_factory *factory) /* * Get device count. */ -PJ_DEF(int) pjmedia_snd_get_dev_count(void) +PJ_DEF (int) pjmedia_snd_get_dev_count (void) { /* Always return 1 */ return 1; @@ -691,60 +747,69 @@ PJ_DEF(int) pjmedia_snd_get_dev_count(void) /* * Get device info. */ -PJ_DEF(const pjmedia_snd_dev_info*) pjmedia_snd_get_dev_info(unsigned index) +PJ_DEF (const pjmedia_snd_dev_info*) pjmedia_snd_get_dev_info (unsigned index) { /* Always return the default sound device */ if (index == (unsigned)-1) - index = 0; + index = 0; + + PJ_ASSERT_RETURN (index==0, NULL); - PJ_ASSERT_RETURN(index==0, NULL); return &symbian_snd_dev_info; } -static pj_status_t sound_open(pjmedia_dir dir, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - pjmedia_snd_rec_cb rec_cb, - pjmedia_snd_play_cb play_cb, - void *user_data, - pjmedia_snd_stream **p_snd_strm) +static pj_status_t sound_open (pjmedia_dir dir, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + pjmedia_snd_rec_cb rec_cb, + pjmedia_snd_play_cb play_cb, + void *user_data, + pjmedia_snd_stream **p_snd_strm) { pj_pool_t *pool; pjmedia_snd_stream *strm; - PJ_ASSERT_RETURN(p_snd_strm, PJ_EINVAL); - PJ_ASSERT_RETURN(clock_rate == 8000 && channel_count == 1 && - bits_per_sample == 16, PJ_ENOTSUP); - PJ_ASSERT_RETURN((dir == PJMEDIA_DIR_CAPTURE_PLAYBACK && rec_cb && play_cb) - || (dir == PJMEDIA_DIR_CAPTURE && rec_cb && !play_cb) - || (dir == PJMEDIA_DIR_PLAYBACK && !rec_cb && play_cb), - PJ_EINVAL); + PJ_ASSERT_RETURN (p_snd_strm, PJ_EINVAL); + PJ_ASSERT_RETURN (clock_rate == 8000 && channel_count == 1 && + bits_per_sample == 16, PJ_ENOTSUP); + PJ_ASSERT_RETURN ( (dir == PJMEDIA_DIR_CAPTURE_PLAYBACK && rec_cb && play_cb) + || (dir == PJMEDIA_DIR_CAPTURE && rec_cb && !play_cb) + || (dir == PJMEDIA_DIR_PLAYBACK && !rec_cb && play_cb), + PJ_EINVAL); + + pool = pj_pool_create (snd_pool_factory, POOL_NAME, POOL_SIZE, POOL_INC, + NULL); - pool = pj_pool_create(snd_pool_factory, POOL_NAME, POOL_SIZE, POOL_INC, - NULL); if (!pool) - return PJ_ENOMEM; + return PJ_ENOMEM; + + strm = (pjmedia_snd_stream*) pj_pool_zalloc (pool, + sizeof (pjmedia_snd_stream)); - strm = (pjmedia_snd_stream*) pj_pool_zalloc(pool, - sizeof(pjmedia_snd_stream)); strm->dir = dir; + strm->pool = pool; + strm->clock_rate = clock_rate; + strm->channel_count = channel_count; + strm->samples_per_frame = samples_per_frame; // Create the audio engine. - TRAPD(err, strm->engine = CPjAudioEngine::NewL(strm, rec_cb, play_cb, - user_data)); + TRAPD (err, strm->engine = CPjAudioEngine::NewL (strm, rec_cb, play_cb, + user_data)); + if (err != KErrNone) { - pj_pool_release(pool); - return PJ_RETURN_OS_ERROR(err); + pj_pool_release (pool); + return PJ_RETURN_OS_ERROR (err); } // Done. *p_snd_strm = strm; + return PJ_SUCCESS; } @@ -753,69 +818,73 @@ static pj_status_t sound_open(pjmedia_dir dir, /* * Open sound recorder stream. */ -PJ_DEF(pj_status_t) pjmedia_snd_open_rec( int index, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - pjmedia_snd_rec_cb rec_cb, - void *user_data, - pjmedia_snd_stream **p_snd_strm) +PJ_DEF (pj_status_t) pjmedia_snd_open_rec (int index, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + pjmedia_snd_rec_cb rec_cb, + void *user_data, + pjmedia_snd_stream **p_snd_strm) { if (index < 0) index = 0; - PJ_ASSERT_RETURN(index == 0, PJ_EINVAL); - return sound_open(PJMEDIA_DIR_CAPTURE, clock_rate, channel_count, - samples_per_frame, bits_per_sample, rec_cb, NULL, - user_data, p_snd_strm); + PJ_ASSERT_RETURN (index == 0, PJ_EINVAL); + + return sound_open (PJMEDIA_DIR_CAPTURE, clock_rate, channel_count, + samples_per_frame, bits_per_sample, rec_cb, NULL, + user_data, p_snd_strm); } -PJ_DEF(pj_status_t) pjmedia_snd_open_player( int index, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - pjmedia_snd_play_cb play_cb, - void *user_data, - pjmedia_snd_stream **p_snd_strm ) +PJ_DEF (pj_status_t) pjmedia_snd_open_player (int index, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + pjmedia_snd_play_cb play_cb, + void *user_data, + pjmedia_snd_stream **p_snd_strm) { if (index < 0) index = 0; - PJ_ASSERT_RETURN(index == 0, PJ_EINVAL); - return sound_open(PJMEDIA_DIR_PLAYBACK, clock_rate, channel_count, - samples_per_frame, bits_per_sample, NULL, play_cb, - user_data, p_snd_strm); + PJ_ASSERT_RETURN (index == 0, PJ_EINVAL); + + return sound_open (PJMEDIA_DIR_PLAYBACK, clock_rate, channel_count, + samples_per_frame, bits_per_sample, NULL, play_cb, + user_data, p_snd_strm); } -PJ_DEF(pj_status_t) pjmedia_snd_open( int rec_id, - int play_id, - unsigned clock_rate, - unsigned channel_count, - unsigned samples_per_frame, - unsigned bits_per_sample, - pjmedia_snd_rec_cb rec_cb, - pjmedia_snd_play_cb play_cb, - void *user_data, - pjmedia_snd_stream **p_snd_strm) +PJ_DEF (pj_status_t) pjmedia_snd_open (int rec_id, + int play_id, + unsigned clock_rate, + unsigned channel_count, + unsigned samples_per_frame, + unsigned bits_per_sample, + pjmedia_snd_rec_cb rec_cb, + pjmedia_snd_play_cb play_cb, + void *user_data, + pjmedia_snd_stream **p_snd_strm) { if (rec_id < 0) rec_id = 0; + if (play_id < 0) play_id = 0; - PJ_ASSERT_RETURN(play_id == 0 && rec_id == 0, PJ_EINVAL); - return sound_open(PJMEDIA_DIR_CAPTURE_PLAYBACK, clock_rate, channel_count, - samples_per_frame, bits_per_sample, rec_cb, play_cb, - user_data, p_snd_strm); + PJ_ASSERT_RETURN (play_id == 0 && rec_id == 0, PJ_EINVAL); + + return sound_open (PJMEDIA_DIR_CAPTURE_PLAYBACK, clock_rate, channel_count, + samples_per_frame, bits_per_sample, rec_cb, play_cb, + user_data, p_snd_strm); } /* * Get stream info. */ -PJ_DEF(pj_status_t) pjmedia_snd_stream_get_info(pjmedia_snd_stream *strm, - pjmedia_snd_stream_info *pi) +PJ_DEF (pj_status_t) pjmedia_snd_stream_get_info (pjmedia_snd_stream *strm, + pjmedia_snd_stream_info *pi) { - PJ_ASSERT_RETURN(strm && pi, PJ_EINVAL); + PJ_ASSERT_RETURN (strm && pi, PJ_EINVAL); - pj_bzero(pi, sizeof(*pi)); + pj_bzero (pi, sizeof (*pi)); pi->dir = strm->dir; pi->play_id = 0; pi->rec_id = 0; @@ -831,54 +900,56 @@ PJ_DEF(pj_status_t) pjmedia_snd_stream_get_info(pjmedia_snd_stream *strm, } -PJ_DEF(pj_status_t) pjmedia_snd_stream_start(pjmedia_snd_stream *stream) +PJ_DEF (pj_status_t) pjmedia_snd_stream_start (pjmedia_snd_stream *stream) { - PJ_ASSERT_RETURN(stream != NULL, PJ_EINVAL); - + PJ_ASSERT_RETURN (stream != NULL, 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; } -PJ_DEF(pj_status_t) pjmedia_snd_stream_stop(pjmedia_snd_stream *stream) +PJ_DEF (pj_status_t) pjmedia_snd_stream_stop (pjmedia_snd_stream *stream) { - PJ_ASSERT_RETURN(stream != NULL, PJ_EINVAL); - + PJ_ASSERT_RETURN (stream != NULL, PJ_EINVAL); + if (stream->engine) { - stream->engine->Stop(); + stream->engine->Stop(); } - + return PJ_SUCCESS; } -PJ_DEF(pj_status_t) pjmedia_snd_stream_close(pjmedia_snd_stream *stream) +PJ_DEF (pj_status_t) pjmedia_snd_stream_close (pjmedia_snd_stream *stream) { pj_pool_t *pool; - - PJ_ASSERT_RETURN(stream != NULL, PJ_EINVAL); - + + PJ_ASSERT_RETURN (stream != NULL, PJ_EINVAL); + if (stream->engine) { - delete stream->engine; - stream->engine = NULL; + delete stream->engine; + stream->engine = NULL; } pool = stream->pool; - if (pool) { - stream->pool = NULL; - pj_pool_release(pool); + + if (pool) { + stream->pool = NULL; + pj_pool_release (pool); } - + return PJ_SUCCESS; } -PJ_DEF(pj_status_t) pjmedia_snd_deinit(void) +PJ_DEF (pj_status_t) pjmedia_snd_deinit (void) { /* Nothing to do */ return PJ_SUCCESS; @@ -888,12 +959,12 @@ PJ_DEF(pj_status_t) pjmedia_snd_deinit(void) /* * Set sound latency. */ -PJ_DEF(pj_status_t) pjmedia_snd_set_latency(unsigned input_latency, - unsigned output_latency) +PJ_DEF (pj_status_t) pjmedia_snd_set_latency (unsigned input_latency, + unsigned output_latency) { /* Nothing to do */ - PJ_UNUSED_ARG(input_latency); - PJ_UNUSED_ARG(output_latency); + PJ_UNUSED_ARG (input_latency); + PJ_UNUSED_ARG (output_latency); return PJ_SUCCESS; } @@ -901,19 +972,20 @@ PJ_DEF(pj_status_t) pjmedia_snd_set_latency(unsigned input_latency, /* * Activate/deactivate loudspeaker. */ -PJ_DEF(pj_status_t) pjmedia_snd_aps_activate_loudspeaker( - pjmedia_snd_stream *stream, - pj_bool_t active) +PJ_DEF (pj_status_t) pjmedia_snd_aps_activate_loudspeaker ( + pjmedia_snd_stream *stream, + pj_bool_t active) { if (stream == NULL) { - act_loudspeaker = active; + act_loudspeaker = active; } else { - if (stream->engine == NULL) - return PJ_EINVAL; + if (stream->engine == NULL) + return PJ_EINVAL; + + TInt err = stream->engine->ActivateSpeaker (active); - TInt err = stream->engine->ActivateSpeaker(active); - if (err != KErrNone) - return PJ_RETURN_OS_ERROR(err); + if (err != KErrNone) + return PJ_RETURN_OS_ERROR (err); } return PJ_SUCCESS; diff --git a/sflphone-common/libs/pjproject-1.0.2/pjnath/include/pjnath/config.h b/sflphone-common/libs/pjproject-1.0.2/pjnath/include/pjnath/config.h index b7bf109010..d2f79be003 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjnath/include/pjnath/config.h +++ b/sflphone-common/libs/pjproject-1.0.2/pjnath/include/pjnath/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 __PJNATH_CONFIG_H__ #define __PJNATH_CONFIG_H__ @@ -65,9 +65,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. */ @@ -78,7 +78,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). @@ -201,8 +201,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 @@ -211,7 +211,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. */ @@ -270,10 +270,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 @@ -304,15 +304,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-1.0.2/pjsip-apps/src/pjsua_wince/pjsua_wince.cpp b/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/pjsua_wince/pjsua_wince.cpp index 1e9bbb1692..9ca242e83c 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/pjsua_wince/pjsua_wince.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/pjsua_wince/pjsua_wince.cpp @@ -54,15 +54,15 @@ static HWND hwndActionButton, hwndExitButton; // // STUN server #if 1 - // 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,7 +298,7 @@ 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) { } @@ -292,9 +306,9 @@ static void on_buddy_state(pjsua_buddy_id 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) { } @@ -302,14 +316,14 @@ static void on_pager(pjsua_call_id call_id, const pj_str_t *from, /** * 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) { } -static BOOL OnInitStack(void) +static BOOL OnInitStack (void) { pjsua_config cfg; pjsua_logging_config log_cfg; @@ -323,139 +337,170 @@ 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; + 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; 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; @@ -464,39 +509,38 @@ 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; - + // 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; @@ -505,34 +549,34 @@ 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); } /* 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)); } } -BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) +BOOL InitInstance (HINSTANCE hInstance, int nCmdShow) { HWND hWnd; TCHAR szTitle[MAX_LOADSTRING]; @@ -541,221 +585,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-1.0.2/pjsip-apps/src/pocketpj/PocketPJ.cpp b/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/pocketpj/PocketPJ.cpp index 2d42d96e2e..cc75d884ba 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/pocketpj/PocketPJ.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/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-1.0.2/pjsip-apps/src/pocketpj/PocketPJDlg.cpp b/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/pocketpj/PocketPJDlg.cpp index 6178f6c671..ca8014a245 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/pocketpj/PocketPJDlg.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/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; @@ -182,203 +188,244 @@ 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), 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), 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; - PopUp_Modify(POPUP_REGISTRATION, POPUP_EL_TITLE1, acc_text); - PopUp_Modify(POPUP_REGISTRATION, POPUP_EL_TITLE2, "Registering.."); - PopUp_Modify(POPUP_REGISTRATION, POPUP_EL_TITLE3, ""); + m_AccId.SetWindowText (acc_text); - SetTimer(TIMER_ID, 100, NULL); + 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); 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) { 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; + } + } } } @@ -386,91 +433,102 @@ 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) { 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) { } 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)) ); - acc_text += " (OK)"; - m_AccId.SetWindowText(acc_text); + /* Registration success */ + HBITMAP old = m_BtnAcc.SetBitmap (::LoadBitmap (AfxGetInstanceHandle(), MAKEINTRESOURCE (IDB_ONLINE))); + 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) { theDlg->OnRegState(); } -void CPocketPJDlg::on_buddy_state(pjsua_buddy_id buddy_id) +void CPocketPJDlg::on_buddy_state (pjsua_buddy_id 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) { } @@ -479,143 +537,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); - m_Cfg.SaveRegistry(); + if (dlg.DoModal() != IDOK) { + return; + } - if (Restart()) - break; + m_Cfg.SaveRegistry(); + + 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; } @@ -626,124 +691,134 @@ 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(); + 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-1.0.2/pjsip-apps/src/pocketpj/PopUpWnd.cpp b/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/pocketpj/PopUpWnd.cpp index 1f1654f062..a92d2454e2 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/pocketpj/PopUpWnd.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/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-1.0.2/pjsip-apps/src/pocketpj/SettingsDlg.cpp b/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/pocketpj/SettingsDlg.cpp index 1357044ae2..6d963f81fa 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/pocketpj/SettingsDlg.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/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-1.0.2/pjsip-apps/src/symbian_ua/main_symbian.cpp b/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/symbian_ua/main_symbian.cpp index 8a7f6029c8..d7f3f0ec63 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/symbian_ua/main_symbian.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/symbian_ua/main_symbian.cpp @@ -1,5 +1,5 @@ /* $Id: main_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 "ua.h" @@ -29,7 +29,7 @@ CConsoleBase* console; // Needed by APS -TPtrC APP_UID = _L("A000000D"); +TPtrC APP_UID = _L ("A000000D"); //////////////////////////////////////////////////////////////////////////// @@ -37,13 +37,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; } @@ -60,22 +60,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-1.0.2/pjsip-apps/src/symbian_ua/ua.cpp b/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/symbian_ua/ua.cpp index 1aae6fffaf..6e790f246d 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/symbian_ua/ua.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/symbian_ua/ua.cpp @@ -1,5 +1,5 @@ /* $Id: ua.cpp 2482 2009-03-02 15:50: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 <pjsua-lib/pjsua.h> #include <pjsua-lib/pjsua_internal.h> @@ -60,15 +60,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 @@ -92,179 +92,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); + + pj_ansi_to_unicode (buf, len, buf16, PJ_ARRAY_SIZE (buf16)); - TPtrC16 aBuf((const TUint16*)buf16, (TInt)len); + TPtrC16 aBuf ( (const TUint16*) buf16, (TInt) len); //RDebug::Print(aBuf); - console->Write(aBuf); - + console->Write (aBuf); + } /* @@ -277,63 +278,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(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_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 = LOG_LEVEL; log_cfg.console_level = LOG_LEVEL; log_cfg.cb = &log_writer; //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; @@ -345,88 +362,96 @@ static pj_status_t app_startup() 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 - - 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 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; } /* 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; } @@ -437,299 +462,333 @@ 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 PrintMenu() +static void PrintMenu() { - PJ_LOG(3, (THIS_FILE, "\n\n" - "Menu:\n" - " d Dump states\n" - " D Dump states detail\n" - " P Dump pool factory\n" - " l Start loopback audio device\n" - " L Stop loopback audio device\n" - " m Call " SIP_DST_URI "\n" - " a Answer call\n" - " g Hangup all calls\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, "\n\n" + "Menu:\n" + " d Dump states\n" + " D Dump states detail\n" + " P Dump pool factory\n" + " l Start loopback audio device\n" + " L Stop loopback audio device\n" + " m Call " SIP_DST_URI "\n" + " a Answer call\n" + " g Hangup all calls\n" + " s Subscribe " SIP_DST_URI "\n" + " S Unsubscribe presence\n" + " o Set account online\n" + " O Set account offline\n" + " w Quit\n")); } // Implementation: called when read has completed. -void ConsoleUI::RunL() +void ConsoleUI::RunL() { TKeyCode kc = con_->KeyCode(); pj_bool_t reschedule = PJ_TRUE; - + switch (kc) { - case 'w': - CActiveScheduler::Stop(); - reschedule = PJ_FALSE; - break; - case 'D': - case 'd': - pjsua_dump(kc == 'D'); - break; - case 'p': - case 'P': - pj_pool_factory_dump(pjsua_get_pool_factory(), PJ_TRUE); - break; - case 'l': - pjsua_conf_connect(0, 0); - break; - case 'L': - pjsua_conf_disconnect(0, 0); - 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 'w': + CActiveScheduler::Stop(); + reschedule = PJ_FALSE; + break; + + case 'D': + + case 'd': + pjsua_dump (kc == 'D'); + break; + + case 'p': + + case 'P': + pj_pool_factory_dump (pjsua_get_pool_factory(), PJ_TRUE); + break; + + case 'l': + pjsua_conf_connect (0, 0); + break; + + case 'L': + pjsua_conf_disconnect (0, 0); + 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; } PrintMenu(); - + 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() { } @@ -738,96 +797,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.")); - PrintMenu(); - } - - 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.")); + + PrintMenu(); + } + + Start(); + } + + RConnection& conn_; + RSocketServ& sserver_; + TNifProgressBuf nif_progress_; }; //////////////////////////////////////////////////////////////////////////// -int ua_main() +int ua_main() { RSocketServ aSocketServer; RConnection aConn; @@ -836,81 +907,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(); + PrintMenu(); // 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-1.0.2/pjsip-apps/src/symbian_ua_gui/src/Symbian_ua_guiSettingItemListSets.cpp b/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/symbian_ua_gui/src/Symbian_ua_guiSettingItemListSets.cpp index 6d7522938b..69d842c37d 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/symbian_ua_gui/src/Symbian_ua_guiSettingItemListSets.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/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-1.0.2/pjsip-apps/src/symbian_ua_gui/src/symbian_ua.cpp b/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/symbian_ua_gui/src/symbian_ua.cpp index f722336a1b..1e56a4f9fe 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/symbian_ua_gui/src/symbian_ua.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/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-1.0.2/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiAppUi.cpp b/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiAppUi.cpp index ac399510b2..ab66bb2780 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiAppUi.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/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-1.0.2/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiApplication.cpp b/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiApplication.cpp index dc60fecd64..d32c672d6c 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiApplication.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/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-1.0.2/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiContainer.cpp b/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiContainer.cpp index 777217c7de..1ff6ff8bd9 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiContainer.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/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-1.0.2/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiContainerView.cpp b/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiContainerView.cpp index 661c210eac..a01d8f353c 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiContainerView.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/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-1.0.2/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiDocument.cpp b/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiDocument.cpp index 8eb54f8d74..209c9ebcec 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiDocument.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/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-1.0.2/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiSettingItemList.cpp b/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiSettingItemList.cpp index 27f3d6e5ce..15fba37ca3 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiSettingItemList.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/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-1.0.2/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiSettingItemListView.cpp b/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiSettingItemListView.cpp index 243ff994c5..2a158b4bb5 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/symbian_ua_gui/src/symbian_ua_guiSettingItemListView.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/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-1.0.2/pjsip-apps/src/symsndtest/app_main.cpp b/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/symsndtest/app_main.cpp index 22b74bb757..f0168a54bf 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/symsndtest/app_main.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/symsndtest/app_main.cpp @@ -1,5 +1,5 @@ /* $Id: app_main.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 <pjmedia/delaybuf.h> #include <pjmedia/sound.h> @@ -44,205 +44,219 @@ 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_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)); - 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)); + char errmsg[PJ_ERR_MSG_SIZE]; + pj_strerror (status, errmsg, sizeof (errmsg)); + PJ_LOG (1, (THIS_FILE, "Error: %s: %s", title, errmsg)); } /* Application init */ -static pj_status_t app_init() +static pj_status_t app_init() { unsigned i, count; 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_snd_init(&cp.factory); + status = pjmedia_snd_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_snd_get_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) { - const pjmedia_snd_dev_info *info; - - info = pjmedia_snd_get_dev_info(i); - PJ_LOG(3, (THIS_FILE, "%d: %s %d/%d %dHz", - i, info->name, info->input_count, info->output_count, - info->default_samples_per_sec)); + const pjmedia_snd_dev_info *info; + + info = pjmedia_snd_get_dev_info (i); + 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; } /* Sound capture callback */ -static pj_status_t rec_cb(void *user_data, - pj_uint32_t timestamp, - void *input, - unsigned size) +static pj_status_t rec_cb (void *user_data, + pj_uint32_t timestamp, + void *input, + unsigned size) { - PJ_UNUSED_ARG(user_data); - PJ_UNUSED_ARG(timestamp); - PJ_UNUSED_ARG(size); + PJ_UNUSED_ARG (user_data); + PJ_UNUSED_ARG (timestamp); + PJ_UNUSED_ARG (size); - pjmedia_delay_buf_put(delaybuf, (pj_int16_t*)input); + pjmedia_delay_buf_put (delaybuf, (pj_int16_t*) input); if (size != SAMPLES_PER_FRAME*2) { - PJ_LOG(3, (THIS_FILE, "Size captured = %u", - size)); + PJ_LOG (3, (THIS_FILE, "Size captured = %u", + size)); } ++rec_cnt; + return PJ_SUCCESS; } /* Play cb */ -static pj_status_t play_cb(void *user_data, - pj_uint32_t timestamp, - void *output, - unsigned size) +static pj_status_t play_cb (void *user_data, + pj_uint32_t timestamp, + void *output, + unsigned size) { - PJ_UNUSED_ARG(user_data); - PJ_UNUSED_ARG(timestamp); - PJ_UNUSED_ARG(size); - - pjmedia_delay_buf_get(delaybuf, (pj_int16_t*)output); - + PJ_UNUSED_ARG (user_data); + PJ_UNUSED_ARG (timestamp); + PJ_UNUSED_ARG (size); + + pjmedia_delay_buf_get (delaybuf, (pj_int16_t*) output); + ++play_cnt; - return PJ_SUCCESS; + return PJ_SUCCESS; } /* Start sound */ -static pj_status_t snd_start(unsigned flag) +static pj_status_t snd_start (unsigned flag) { 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; } - + if (flag==PJMEDIA_DIR_CAPTURE_PLAYBACK) - status = pjmedia_snd_open(-1, -1, CLOCK_RATE, CHANNEL_COUNT, - SAMPLES_PER_FRAME, BITS_PER_SAMPLE, - &rec_cb, &play_cb, NULL, &strm); + status = pjmedia_snd_open (-1, -1, CLOCK_RATE, CHANNEL_COUNT, + SAMPLES_PER_FRAME, BITS_PER_SAMPLE, + &rec_cb, &play_cb, NULL, &strm); else if (flag==PJMEDIA_DIR_CAPTURE) - status = pjmedia_snd_open_rec(-1, CLOCK_RATE, CHANNEL_COUNT, - SAMPLES_PER_FRAME, BITS_PER_SAMPLE, - &rec_cb, NULL, &strm); + status = pjmedia_snd_open_rec (-1, CLOCK_RATE, CHANNEL_COUNT, + SAMPLES_PER_FRAME, BITS_PER_SAMPLE, + &rec_cb, NULL, &strm); else - status = pjmedia_snd_open_player(-1, CLOCK_RATE, CHANNEL_COUNT, - SAMPLES_PER_FRAME, BITS_PER_SAMPLE, - &play_cb, NULL, &strm); - + status = pjmedia_snd_open_player (-1, CLOCK_RATE, CHANNEL_COUNT, + SAMPLES_PER_FRAME, BITS_PER_SAMPLE, + &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_snd_stream_start (strm); - status = pjmedia_snd_stream_start(strm); if (status != PJ_SUCCESS) { - app_perror("snd start", status); - pjmedia_snd_stream_close(strm); - strm = NULL; - return status; + app_perror ("snd start", status); + pjmedia_snd_stream_close (strm); + strm = NULL; + return status; } return PJ_SUCCESS; } /* Stop sound */ -static pj_status_t snd_stop() +static pj_status_t snd_stop() { pj_time_val now; 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_snd_stream_close(strm); + + status = pjmedia_snd_stream_close (strm); + strm = NULL; - - 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_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)); return status; } /* Shutdown application */ -static void app_fini() +static void app_fini() { if (strm) - snd_stop(); - + snd_stop(); + pjmedia_snd_deinit(); - 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(); } @@ -253,121 +267,132 @@ static void app_fini() */ #include <e32base.h> -class ConsoleUI : public CActive +class ConsoleUI : public CActive { -public: - ConsoleUI(CActiveSchedulerWait *asw, CConsoleBase *con); - - // Run console UI - void Run(); - - // Stop - void Stop(); - -protected: - // Cancel asynchronous read. - void DoCancel(); - - // Implementation: called when read has completed. - void RunL(); - -private: - CActiveSchedulerWait *asw_; - CConsoleBase *con_; + + public: + ConsoleUI (CActiveSchedulerWait *asw, CConsoleBase *con); + + // Run console UI + void Run(); + + // Stop + void Stop(); + + protected: + // Cancel asynchronous read. + void DoCancel(); + + // Implementation: called when read has completed. + void RunL(); + + private: + CActiveSchedulerWait *asw_; + CConsoleBase *con_; }; -ConsoleUI::ConsoleUI(CActiveSchedulerWait *asw, CConsoleBase *con) -: CActive(EPriorityHigh), asw_(asw), con_(con) +ConsoleUI::ConsoleUI (CActiveSchedulerWait *asw, CConsoleBase *con) + : CActive (EPriorityHigh), asw_ (asw), con_ (con) { - CActiveScheduler::Add(this); + CActiveScheduler::Add (this); } // 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() { DoCancel(); } // Cancel asynchronous read. -void ConsoleUI::DoCancel() +void ConsoleUI::DoCancel() { con_->ReadCancel(); } -static void PrintMenu() +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. -void ConsoleUI::RunL() +void ConsoleUI::RunL() { TKeyCode kc = con_->KeyCode(); pj_bool_t reschedule = PJ_TRUE; - + switch (kc) { - case 'w': - asw_->AsyncStop(); - 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': + asw_->AsyncStop(); + 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(); } //////////////////////////////////////////////////////////////////////////// -int app_main() +int app_main() { if (app_init() != PJ_SUCCESS) return -1; - + // Run the UI CActiveSchedulerWait *asw = new CActiveSchedulerWait; - ConsoleUI *con = new ConsoleUI(asw, console); - + + ConsoleUI *con = new ConsoleUI (asw, console); + con->Run(); - + PrintMenu(); + asw->Start(); - + delete con; + delete asw; - + app_fini(); + return 0; } diff --git a/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/symsndtest/main_symbian.cpp b/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/symsndtest/main_symbian.cpp index e33ff6969f..512a0e1767 100644 --- a/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/symsndtest/main_symbian.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/pjsip-apps/src/symsndtest/main_symbian.cpp @@ -1,5 +1,5 @@ /* $Id: main_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 <e32std.h> @@ -29,36 +29,38 @@ CConsoleBase* console; // Needed by APS -TPtrC APP_UID = _L("A000000D"); +TPtrC APP_UID = _L ("A000000D"); int app_main(); //////////////////////////////////////////////////////////////////////////// + class MyTask : public CActive { -public: - static MyTask *NewL(CActiveSchedulerWait *asw); - ~MyTask(); - void Start(); - -protected: - MyTask(CActiveSchedulerWait *asw); - void ConstructL(); - virtual void RunL(); - virtual void DoCancel(); - -private: - RTimer timer_; - CActiveSchedulerWait *asw_; + + public: + static MyTask *NewL (CActiveSchedulerWait *asw); + ~MyTask(); + void Start(); + + protected: + MyTask (CActiveSchedulerWait *asw); + void ConstructL(); + virtual void RunL(); + virtual void DoCancel(); + + private: + RTimer timer_; + CActiveSchedulerWait *asw_; }; -MyTask::MyTask(CActiveSchedulerWait *asw) -: CActive(EPriorityNormal), asw_(asw) +MyTask::MyTask (CActiveSchedulerWait *asw) + : CActive (EPriorityNormal), asw_ (asw) { } -MyTask::~MyTask() +MyTask::~MyTask() { timer_.Close(); } @@ -66,23 +68,23 @@ MyTask::~MyTask() void MyTask::ConstructL() { timer_.CreateLocal(); - CActiveScheduler::Add(this); + CActiveScheduler::Add (this); } -MyTask *MyTask::NewL(CActiveSchedulerWait *asw) +MyTask *MyTask::NewL (CActiveSchedulerWait *asw) { - MyTask *self = new (ELeave) MyTask(asw); - CleanupStack::PushL(self); + MyTask *self = new (ELeave) MyTask (asw); + CleanupStack::PushL (self); self->ConstructL(); - CleanupStack::Pop(self); + CleanupStack::Pop (self); return self; } void MyTask::Start() { - timer_.After(iStatus, 0); + timer_.After (iStatus, 0); SetActive(); } @@ -102,24 +104,24 @@ void MyTask::DoCancel() LOCAL_C void DoStartL() { CActiveScheduler *scheduler = new (ELeave) CActiveScheduler; - CleanupStack::PushL(scheduler); - CActiveScheduler::Install(scheduler); + CleanupStack::PushL (scheduler); + CActiveScheduler::Install (scheduler); CActiveSchedulerWait *asw = new CActiveSchedulerWait; - CleanupStack::PushL(asw); - - MyTask *task = MyTask::NewL(asw); + CleanupStack::PushL (asw); + + MyTask *task = MyTask::NewL (asw); task->Start(); asw->Start(); - + delete task; - - CleanupStack::Pop(asw); + + CleanupStack::Pop (asw); delete asw; - - CActiveScheduler::Install(NULL); - CleanupStack::Pop(scheduler); + + CActiveScheduler::Install (NULL); + CleanupStack::Pop (scheduler); delete scheduler; } @@ -136,22 +138,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-1.0.2/third_party/build/speex/config.h b/sflphone-common/libs/pjproject-1.0.2/third_party/build/speex/config.h index ba7be7a6e2..e04c40be4f 100644 --- a/sflphone-common/libs/pjproject-1.0.2/third_party/build/speex/config.h +++ b/sflphone-common/libs/pjproject-1.0.2/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-1.0.2/third_party/portaudio/src/hostapi/asio/iasiothiscallresolver.cpp b/sflphone-common/libs/pjproject-1.0.2/third_party/portaudio/src/hostapi/asio/iasiothiscallresolver.cpp index 8dfefbd67b..1b4b33781f 100644 --- a/sflphone-common/libs/pjproject-1.0.2/third_party/portaudio/src/hostapi/asio/iasiothiscallresolver.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/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-1.0.2/third_party/portaudio/src/hostapi/asio/pa_asio.cpp b/sflphone-common/libs/pjproject-1.0.2/third_party/portaudio/src/hostapi/asio/pa_asio.cpp index 1ba67e92ae..cf54465cfa 100644 --- a/sflphone-common/libs/pjproject-1.0.2/third_party/portaudio/src/hostapi/asio/pa_asio.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/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-1.0.2/third_party/portaudio/src/hostapi/wasapi/pa_win_wasapi.cpp b/sflphone-common/libs/pjproject-1.0.2/third_party/portaudio/src/hostapi/wasapi/pa_win_wasapi.cpp index f13a7f2302..0653b138b0 100644 --- a/sflphone-common/libs/pjproject-1.0.2/third_party/portaudio/src/hostapi/wasapi/pa_win_wasapi.cpp +++ b/sflphone-common/libs/pjproject-1.0.2/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/libs/utilspp/singleton/LifetimeLibrary.cpp b/sflphone-common/libs/utilspp/singleton/LifetimeLibrary.cpp index e58932ebde..7f7afac3b2 100644 --- a/sflphone-common/libs/utilspp/singleton/LifetimeLibrary.cpp +++ b/sflphone-common/libs/utilspp/singleton/LifetimeLibrary.cpp @@ -2,71 +2,70 @@ #include "LifetimeLibrary.hpp" utilspp::LifetimeLibraryImpl::LifetimeLibraryImpl() - : - mTrackerArray( NULL ), - mNbElements( 0 ) + : + mTrackerArray (NULL), + mNbElements (0) {} utilspp::LifetimeLibraryImpl::~LifetimeLibraryImpl() { - terminate(); + terminate(); } void -utilspp::LifetimeLibraryImpl::add( utilspp::PrivateMembers::LifetimeTracker *tracker ) +utilspp::LifetimeLibraryImpl::add (utilspp::PrivateMembers::LifetimeTracker *tracker) { - utilspp::PrivateMembers::TrackerArray newArray = static_cast< - utilspp::PrivateMembers::TrackerArray >(std::realloc(mTrackerArray, - mNbElements + 1)); - if( newArray == NULL ) - { - throw std::bad_alloc(); - } + utilspp::PrivateMembers::TrackerArray newArray = static_cast< + utilspp::PrivateMembers::TrackerArray > (std::realloc (mTrackerArray, + mNbElements + 1)); - mTrackerArray = newArray; + if (newArray == NULL) { + throw std::bad_alloc(); + } - utilspp::PrivateMembers::TrackerArray pos = - std::upper_bound(mTrackerArray, - mTrackerArray + mNbElements, - tracker, - &utilspp::PrivateMembers::LifetimeTracker::compare); - std::copy_backward(pos, - mTrackerArray + mNbElements, - mTrackerArray + mNbElements + 1); - - *pos = tracker; - mNbElements++; + mTrackerArray = newArray; + + utilspp::PrivateMembers::TrackerArray pos = + std::upper_bound (mTrackerArray, + mTrackerArray + mNbElements, + tracker, + &utilspp::PrivateMembers::LifetimeTracker::compare); + std::copy_backward (pos, + mTrackerArray + mNbElements, + mTrackerArray + mNbElements + 1); + + *pos = tracker; + mNbElements++; }; void utilspp::LifetimeLibraryImpl::terminate() { - //The number of elements MUST always be equal or over zero. - assert( mNbElements >= 0 ); + //The number of elements MUST always be equal or over zero. + assert (mNbElements >= 0); + + while (mNbElements > 0) { + //At this point the mTrackerArray MUST not be NULL. + assert (mTrackerArray != NULL); + + //Pick the element at the top of the stack. + utilspp::PrivateMembers::LifetimeTracker* top = + mTrackerArray[mNbElements - 1]; - while( mNbElements > 0 ) - { - //At this point the mTrackerArray MUST not be NULL. - assert( mTrackerArray != NULL ); - - //Pick the element at the top of the stack. - utilspp::PrivateMembers::LifetimeTracker* top = - mTrackerArray[mNbElements - 1]; + //Remove that object off the stack. + //Don't check errors-realloc with less memory, cause that can't fail. + mTrackerArray = + static_cast< utilspp::PrivateMembers::TrackerArray > + (std::realloc (mTrackerArray, --mNbElements)); - //Remove that object off the stack. - //Don't check errors-realloc with less memory, cause that can't fail. - mTrackerArray = - static_cast< utilspp::PrivateMembers::TrackerArray > - (std::realloc(mTrackerArray, --mNbElements)); - - //Destroy the element. - delete top; - } + //Destroy the element. + delete top; + } } -unsigned int -utilspp::getLongevity( utilspp::LifetimeLibraryImpl * ) +unsigned int +utilspp::getLongevity (utilspp::LifetimeLibraryImpl *) { - return 0; + return 0; } diff --git a/sflphone-common/libs/utilspp/singleton/PrivateMembers.cpp b/sflphone-common/libs/utilspp/singleton/PrivateMembers.cpp index 901c9bcc1d..194fbda664 100644 --- a/sflphone-common/libs/utilspp/singleton/PrivateMembers.cpp +++ b/sflphone-common/libs/utilspp/singleton/PrivateMembers.cpp @@ -3,44 +3,44 @@ #include "PrivateMembers.hpp" utilspp::PrivateMembers::TrackerArray - utilspp::PrivateMembers::mTrackerArray = NULL; +utilspp::PrivateMembers::mTrackerArray = NULL; int utilspp::PrivateMembers::mNbElements = 0; -utilspp::PrivateMembers::LifetimeTracker::LifetimeTracker( unsigned int - longevity ) -: -mLongevity( longevity ) +utilspp::PrivateMembers::LifetimeTracker::LifetimeTracker (unsigned int + longevity) + : + mLongevity (longevity) {} utilspp::PrivateMembers::LifetimeTracker::~LifetimeTracker() {} bool -utilspp::PrivateMembers::LifetimeTracker::compare( - const LifetimeTracker *l, - const LifetimeTracker *r - ) +utilspp::PrivateMembers::LifetimeTracker::compare ( + const LifetimeTracker *l, + const LifetimeTracker *r +) { - return l->mLongevity < r->mLongevity; + return l->mLongevity < r->mLongevity; } void utilspp::PrivateMembers::atExitFunc() { - assert((mTrackerArray != NULL) && - (mNbElements > 0)); + assert ( (mTrackerArray != NULL) && + (mNbElements > 0)); - //Pick the element at the top of the stack. - LifetimeTracker* top = mTrackerArray[mNbElements - 1]; + //Pick the element at the top of the stack. + LifetimeTracker* top = mTrackerArray[mNbElements - 1]; - //Remove that object off the stack. - //Don't check errors-realloc with less memory, cause that can't fail. - mTrackerArray = static_cast< - utilspp::PrivateMembers::TrackerArray >(std::realloc(mTrackerArray, - --mNbElements)); + //Remove that object off the stack. + //Don't check errors-realloc with less memory, cause that can't fail. + mTrackerArray = static_cast< + utilspp::PrivateMembers::TrackerArray > (std::realloc (mTrackerArray, + --mNbElements)); - //Destroy the element. - delete top; + //Destroy the element. + delete top; } diff --git a/sflphone-common/src/account.cpp b/sflphone-common/src/account.cpp index 34b96eed45..e22cf874d0 100644 --- a/sflphone-common/src/account.cpp +++ b/sflphone-common/src/account.cpp @@ -22,10 +22,10 @@ #include "account.h" #include "manager.h" -Account::Account(const AccountID& accountID, std::string type) : - _accountID(accountID), _link(NULL), _enabled(false), _type(type) +Account::Account (const AccountID& accountID, std::string type) : + _accountID (accountID), _link (NULL), _enabled (false), _type (type) { - setRegistrationState(Unregistered); + setRegistrationState (Unregistered); } Account::~Account() @@ -36,24 +36,27 @@ void Account::loadConfig() { std::string p; - p = Manager::instance().getConfigString( _accountID , CONFIG_ACCOUNT_TYPE ); -#ifdef USE_IAX - _enabled = Manager::instance().getConfigInt(_accountID, CONFIG_ACCOUNT_ENABLE) ? true : false; + p = Manager::instance().getConfigString (_accountID , CONFIG_ACCOUNT_TYPE); +#ifdef USE_IAX + _enabled = Manager::instance().getConfigInt (_accountID, CONFIG_ACCOUNT_ENABLE) ? true : false; #else - if( p.c_str() == "IAX" ) + + if (p.c_str() == "IAX") _enabled = false; else - _enabled = Manager::instance().getConfigInt(_accountID, CONFIG_ACCOUNT_ENABLE) ? true : false; + _enabled = Manager::instance().getConfigInt (_accountID, CONFIG_ACCOUNT_ENABLE) ? true : false; + #endif } -void Account::setRegistrationState( RegistrationState state ) { - +void Account::setRegistrationState (RegistrationState state) +{ + if (state != _registrationState) { - _debug("Account::setRegistrationState\n"); - _registrationState = state; + _debug ("Account::setRegistrationState\n"); + _registrationState = state; - // Notify the client - Manager::instance().connectionStatusNotification(); + // Notify the client + Manager::instance().connectionStatusNotification(); } } diff --git a/sflphone-common/src/accountcreator.cpp b/sflphone-common/src/accountcreator.cpp index c196597e78..e3b5855f20 100644 --- a/sflphone-common/src/accountcreator.cpp +++ b/sflphone-common/src/accountcreator.cpp @@ -2,17 +2,17 @@ * Copyright (C) 2006-2007 Savoir-Faire Linux inc. * Author: Alexandre Bourget <alexandre.bourget@savoirfairelinux.com> * Author: Yan Morin <yan.morin@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 * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -32,19 +32,22 @@ AccountCreator::~AccountCreator() { } -Account* -AccountCreator::createAccount(AccountType type, AccountID accountID) +Account* +AccountCreator::createAccount (AccountType type, AccountID accountID) { - switch(type) { - case SIP_ACCOUNT: - return new SIPAccount(accountID); - break; + switch (type) { + + case SIP_ACCOUNT: + return new SIPAccount (accountID); + break; #ifdef USE_IAX - case IAX_ACCOUNT: - return new IAXAccount(accountID); - break; + + case IAX_ACCOUNT: + return new IAXAccount (accountID); + break; #endif - } - return 0; + } + + return 0; } diff --git a/sflphone-common/src/audio/alsalayer.cpp b/sflphone-common/src/audio/alsalayer.cpp index 2a3939bfc3..55ed04817f 100644 --- a/sflphone-common/src/audio/alsalayer.cpp +++ b/sflphone-common/src/audio/alsalayer.cpp @@ -22,107 +22,114 @@ int framesPerBufferAlsa = 2048; // Constructor - AlsaLayer::AlsaLayer( ManagerImpl* manager ) - : AudioLayer( manager , ALSA ) - , _PlaybackHandle(NULL) - , _CaptureHandle(NULL) - , _periodSize() - , _audioPlugin() - , IDSoundCards() - , _is_prepared_playback (false) - , _is_running_playback (false) - , _is_open_playback (false) - , _is_prepared_capture (false) - , _is_running_capture (false) - , _is_open_capture (false) - , _trigger_request (false) - +AlsaLayer::AlsaLayer (ManagerImpl* manager) + : AudioLayer (manager , ALSA) + , _PlaybackHandle (NULL) + , _CaptureHandle (NULL) + , _periodSize() + , _audioPlugin() + , IDSoundCards() + , _is_prepared_playback (false) + , _is_running_playback (false) + , _is_open_playback (false) + , _is_prepared_capture (false) + , _is_running_capture (false) + , _is_open_capture (false) + , _trigger_request (false) + { - _debug(" Constructor of AlsaLayer called\n"); + _debug (" Constructor of AlsaLayer called\n"); /* Instanciate the audio thread */ _audioThread = new AudioThread (this); } // Destructor -AlsaLayer::~AlsaLayer (void) -{ - _debug("Destructor of AlsaLayer called\n"); +AlsaLayer::~AlsaLayer (void) +{ + _debug ("Destructor of AlsaLayer called\n"); closeLayer(); } bool AlsaLayer::closeLayer() { - _debugAlsa("Close ALSA streams\n"); - + _debugAlsa ("Close ALSA streams\n"); + try { - /* Stop the audio thread first */ - if (_audioThread) - { - delete _audioThread; _audioThread=NULL; + /* Stop the audio thread first */ + if (_audioThread) { + delete _audioThread; + _audioThread=NULL; } - } - catch(...) { - _debugException("! ARTP Exception: when stopping audiortp\n"); + } catch (...) { + _debugException ("! ARTP Exception: when stopping audiortp\n"); throw; } - + /* Then close the audio devices */ closeCaptureStream(); + closePlaybackStream(); - + _CaptureHandle = 0; + _PlaybackHandle = 0; return true; } - bool -AlsaLayer::openDevice (int indexIn, int indexOut, int sampleRate, int frameSize, int stream , std::string plugin) +bool +AlsaLayer::openDevice (int indexIn, int indexOut, int sampleRate, int frameSize, int stream , std::string plugin) { - /* Close the devices before open it */ - if (stream == SFL_PCM_BOTH && is_capture_open() == true && is_playback_open() == true) - { + /* Close the devices before open it */ + if (stream == SFL_PCM_BOTH && is_capture_open() == true && is_playback_open() == true) { closeCaptureStream(); closePlaybackStream(); - } - else if ((stream == SFL_PCM_CAPTURE || stream == SFL_PCM_BOTH) && is_capture_open() == true) + } else if ( (stream == SFL_PCM_CAPTURE || stream == SFL_PCM_BOTH) && is_capture_open() == true) closeCaptureStream (); - else if ((stream == SFL_PCM_PLAYBACK || stream == SFL_PCM_BOTH) && is_playback_open () == true) + else if ( (stream == SFL_PCM_PLAYBACK || stream == SFL_PCM_BOTH) && is_playback_open () == true) closePlaybackStream (); _indexIn = indexIn; + _indexOut = indexOut; + _sampleRate = sampleRate; - _frameSize = frameSize; + + _frameSize = frameSize; + _audioPlugin = plugin; - _debugAlsa(" Setting AlsaLayer: device in=%2d, out=%2d\n", _indexIn, _indexOut); - _debugAlsa(" : alsa plugin=%s\n", _audioPlugin.c_str()); - _debugAlsa(" : nb channel in=%2d, out=%2d\n", _inChannel, _outChannel); - _debugAlsa(" : sample rate=%5d, format=%s\n", _sampleRate, SFLDataFormatString); + _debugAlsa (" Setting AlsaLayer: device in=%2d, out=%2d\n", _indexIn, _indexOut); - ost::MutexLock lock( _mutex ); - - std::string pcmp = buildDeviceTopo( plugin , indexOut , 0); - std::string pcmc = buildDeviceTopo( PCM_PLUGHW , indexIn , 0); + _debugAlsa (" : alsa plugin=%s\n", _audioPlugin.c_str()); - return open_device( pcmp , pcmc , stream); + _debugAlsa (" : nb channel in=%2d, out=%2d\n", _inChannel, _outChannel); + + _debugAlsa (" : sample rate=%5d, format=%s\n", _sampleRate, SFLDataFormatString); + + ost::MutexLock lock (_mutex); + + std::string pcmp = buildDeviceTopo (plugin , indexOut , 0); + + std::string pcmc = buildDeviceTopo (PCM_PLUGHW , indexIn , 0); + + return open_device (pcmp , pcmc , stream); } - void -AlsaLayer::startStream(void) +void +AlsaLayer::startStream (void) { _debug ("Start ALSA streams\n"); prepareCaptureStream (); startCaptureStream (); startPlaybackStream (); -} +} - void -AlsaLayer::stopStream(void) +void +AlsaLayer::stopStream (void) { _debug ("AlsaLayer::stopStream :: Stop ALSA streams\n"); stopCaptureStream (); @@ -134,9 +141,9 @@ AlsaLayer::stopStream(void) flushMic (); } - int +int AlsaLayer::canGetMic() -{ +{ int avail; if (!_CaptureHandle) @@ -144,44 +151,45 @@ AlsaLayer::canGetMic() avail = snd_pcm_avail_update (_CaptureHandle); - if (avail == -EPIPE) - { + if (avail == -EPIPE) { stop_capture (); return 0; - } - else - return ((avail<0)?0:avail); + } else + return ( (avail<0) ?0:avail); /* - if(_CaptureHandle) + if(_CaptureHandle) return _micRingBuffer.AvailForGet(); else return 0;*/ } - int -AlsaLayer::getMic(void *buffer, int toCopy) +int +AlsaLayer::getMic (void *buffer, int toCopy) { /* if( _CaptureHandle ){ return _micRingBuffer.Get(buffer, toCopy,100); - } + } else return 0;*/ - int res = 0; - if( _CaptureHandle ) - { - res = read( buffer, toCopy); - adjustVolume (buffer, toCopy, SFL_PCM_CAPTURE); - } - return res; + int res = 0; + + if (_CaptureHandle) { + res = read (buffer, toCopy); + adjustVolume (buffer, toCopy, SFL_PCM_CAPTURE); + } + + return res; } -bool AlsaLayer::isCaptureActive(void) { - ost::MutexLock guard( _mutex ); - if( _CaptureHandle ) - return (snd_pcm_state( _CaptureHandle) == SND_PCM_STATE_RUNNING ? true : false); +bool AlsaLayer::isCaptureActive (void) +{ + ost::MutexLock guard (_mutex); + + if (_CaptureHandle) + return (snd_pcm_state (_CaptureHandle) == SND_PCM_STATE_RUNNING ? true : false); else return false; } @@ -189,12 +197,12 @@ bool AlsaLayer::isCaptureActive(void) { ////////////////////////////////////////////////////////////////////////////////////////////// ///////////////// ALSA PRIVATE FUNCTIONS //////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////// - + void AlsaLayer::stopCaptureStream (void) { - int err; + int err; - if(_CaptureHandle){ + if (_CaptureHandle) { err = snd_pcm_drop (_CaptureHandle); stop_capture (); @@ -204,8 +212,9 @@ void AlsaLayer::stopCaptureStream (void) void AlsaLayer::closeCaptureStream (void) { - if( is_capture_prepared() == true && is_capture_running() == true ) + if (is_capture_prepared() == true && is_capture_running() == true) stopCaptureStream (); + if (is_capture_open()) snd_pcm_close (_CaptureHandle); @@ -214,8 +223,8 @@ void AlsaLayer::closeCaptureStream (void) void AlsaLayer::startCaptureStream (void) { - if(_CaptureHandle){ - _debug("Start the capture\n"); + if (_CaptureHandle) { + _debug ("Start the capture\n"); snd_pcm_start (_CaptureHandle); start_capture(); } @@ -223,9 +232,9 @@ void AlsaLayer::startCaptureStream (void) void AlsaLayer::prepareCaptureStream (void) { - if (is_capture_open() ) { - if(snd_pcm_prepare (_CaptureHandle) < 0) - _debug(""); + if (is_capture_open()) { + if (snd_pcm_prepare (_CaptureHandle) < 0) + _debug (""); else prepare_capture (); } @@ -233,7 +242,7 @@ void AlsaLayer::prepareCaptureStream (void) void AlsaLayer::stopPlaybackStream (void) { - if( _PlaybackHandle){ + if (_PlaybackHandle) { snd_pcm_drop (_PlaybackHandle); stop_playback (); } @@ -242,9 +251,10 @@ void AlsaLayer::stopPlaybackStream (void) void AlsaLayer::closePlaybackStream (void) { - if( is_playback_prepared() == true && is_playback_running() == true ) + if (is_playback_prepared() == true && is_playback_running() == true) stopPlaybackStream (); - if (is_playback_open()) + + if (is_playback_open()) snd_pcm_close (_PlaybackHandle); close_playback (); @@ -252,7 +262,7 @@ void AlsaLayer::closePlaybackStream (void) void AlsaLayer::startPlaybackStream (void) { - if( _PlaybackHandle){ + if (_PlaybackHandle) { snd_pcm_start (_PlaybackHandle); start_playback(); } @@ -260,13 +270,15 @@ void AlsaLayer::startPlaybackStream (void) void AlsaLayer::preparePlaybackStream (void) { - if(is_playback_open()){ - if( snd_pcm_prepare (_PlaybackHandle) < 0) _debug("Error preparing the device\n"); + if (is_playback_open()) { + if (snd_pcm_prepare (_PlaybackHandle) < 0) _debug ("Error preparing the device\n"); + prepare_playback (); } } -bool AlsaLayer::alsa_set_params( snd_pcm_t *pcm_handle, int type, int rate ){ +bool AlsaLayer::alsa_set_params (snd_pcm_t *pcm_handle, int type, int rate) +{ snd_pcm_hw_params_t *hwparams = NULL; snd_pcm_sw_params_t *swparams = NULL; @@ -279,116 +291,133 @@ bool AlsaLayer::alsa_set_params( snd_pcm_t *pcm_handle, int type, int rate ){ int periodsize = 1024; /* Allocate the snd_pcm_hw_params_t struct */ - snd_pcm_hw_params_malloc( &hwparams ); + snd_pcm_hw_params_malloc (&hwparams); _periodSize = 940; /* Full configuration space */ - if( (err = snd_pcm_hw_params_any(pcm_handle, hwparams)) < 0) { - _debugAlsa(" Cannot initialize hardware parameter structure (%s)\n", snd_strerror(err)); + + if ( (err = snd_pcm_hw_params_any (pcm_handle, hwparams)) < 0) { + _debugAlsa (" Cannot initialize hardware parameter structure (%s)\n", snd_strerror (err)); return false; } - if( (err = snd_pcm_hw_params_set_access( pcm_handle, hwparams, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0) { - _debugAlsa(" Cannot set access type (%s)\n", snd_strerror(err)); + if ( (err = snd_pcm_hw_params_set_access (pcm_handle, hwparams, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0) { + _debugAlsa (" Cannot set access type (%s)\n", snd_strerror (err)); return false; } /* Set sample format */ format = SND_PCM_FORMAT_S16_LE; - if( (err = snd_pcm_hw_params_set_format( pcm_handle, hwparams, (snd_pcm_format_t)format)) < 0) { - _debugAlsa(" Cannot set sample format (%s)\n", snd_strerror(err)); + + if ( (err = snd_pcm_hw_params_set_format (pcm_handle, hwparams, (snd_pcm_format_t) format)) < 0) { + _debugAlsa (" Cannot set sample format (%s)\n", snd_strerror (err)); return false; } - + /* Set sample rate. If we can't set to the desired exact value, we set to the nearest acceptable */ dir=0; + rate = getSampleRate(); + exact_ivalue = rate; - if( (err = snd_pcm_hw_params_set_rate_near( pcm_handle, hwparams, &exact_ivalue, &dir) < 0)) { - _debugAlsa(" Cannot set sample rate (%s)\n", snd_strerror(err)); + + if ( (err = snd_pcm_hw_params_set_rate_near (pcm_handle, hwparams, &exact_ivalue, &dir) < 0)) { + _debugAlsa (" Cannot set sample rate (%s)\n", snd_strerror (err)); return false; } - if( dir!= 0 ){ - _debugAlsa(" (%i) The choosen rate %d Hz is not supported by your hardware.\nUsing %d Hz instead.\n ",type ,rate, exact_ivalue); + + if (dir!= 0) { + _debugAlsa (" (%i) The choosen rate %d Hz is not supported by your hardware.\nUsing %d Hz instead.\n ",type ,rate, exact_ivalue); } /* Set the number of channels */ - if( (err = snd_pcm_hw_params_set_channels( pcm_handle, hwparams, 1)) < 0){ - _debugAlsa(" Cannot set channel count (%s)\n", snd_strerror(err)); + if ( (err = snd_pcm_hw_params_set_channels (pcm_handle, hwparams, 1)) < 0) { + _debugAlsa (" Cannot set channel count (%s)\n", snd_strerror (err)); return false; } /* Set the buffer size in frames */ exact_lvalue = periodsize; + dir=0; - if( (err = snd_pcm_hw_params_set_period_size_near( pcm_handle, hwparams, &exact_lvalue , &dir)) < 0) { - _debugAlsa(" Cannot set period time (%s)\n", snd_strerror(err)); + + if ( (err = snd_pcm_hw_params_set_period_size_near (pcm_handle, hwparams, &exact_lvalue , &dir)) < 0) { + _debugAlsa (" Cannot set period time (%s)\n", snd_strerror (err)); return false; } - if(dir!=0) { - _debugAlsa("(%i) The choosen period size %d bytes is not supported by your hardware.\nUsing %d instead.\n ", type, (int)periodsize, (int)exact_lvalue); + + if (dir!=0) { + _debugAlsa ("(%i) The choosen period size %d bytes is not supported by your hardware.\nUsing %d instead.\n ", type, (int) periodsize, (int) exact_lvalue); } + periodsize = exact_lvalue; + _periodSize = exact_lvalue; /* Set the number of fragments */ exact_ivalue = periods; dir=0; - if( (err = snd_pcm_hw_params_set_periods_near( pcm_handle, hwparams, &exact_ivalue, &dir)) < 0) { - _debugAlsa(" Cannot set periods number (%s)\n", snd_strerror(err)); + + if ( (err = snd_pcm_hw_params_set_periods_near (pcm_handle, hwparams, &exact_ivalue, &dir)) < 0) { + _debugAlsa (" Cannot set periods number (%s)\n", snd_strerror (err)); return false; } - if(dir!=0) { - _debugAlsa(" The choosen period number %i bytes is not supported by your hardware.\nUsing %i instead.\n ", periods, exact_ivalue); + + if (dir!=0) { + _debugAlsa (" The choosen period number %i bytes is not supported by your hardware.\nUsing %i instead.\n ", periods, exact_ivalue); } + periods=exact_ivalue; /* Set the hw parameters */ - if( (err = snd_pcm_hw_params( pcm_handle, hwparams )) < 0) { - _debugAlsa(" Cannot set hw parameters (%s)\n", snd_strerror(err)); + + if ( (err = snd_pcm_hw_params (pcm_handle, hwparams)) < 0) { + _debugAlsa (" Cannot set hw parameters (%s)\n", snd_strerror (err)); return false; } - snd_pcm_hw_params_free( hwparams ); + snd_pcm_hw_params_free (hwparams); /* Set the sw parameters */ - snd_pcm_sw_params_malloc( &swparams ); - snd_pcm_sw_params_current( pcm_handle, swparams ); + snd_pcm_sw_params_malloc (&swparams); + snd_pcm_sw_params_current (pcm_handle, swparams); /* Set the start threshold */ - if( (err = snd_pcm_sw_params_set_start_threshold( pcm_handle, swparams, 2700 /*periodsize*2*/ )) < 0 ) { - _debugAlsa(" Cannot set start threshold (%s)\n", snd_strerror(err)); + + if ( (err = snd_pcm_sw_params_set_start_threshold (pcm_handle, swparams, 2700 /*periodsize*2*/)) < 0) { + _debugAlsa (" Cannot set start threshold (%s)\n", snd_strerror (err)); return false; } - if( (err = snd_pcm_sw_params( pcm_handle, swparams)) < 0 ) { - _debugAlsa(" Cannot set sw parameters (%s)\n", snd_strerror(err)); + + if ( (err = snd_pcm_sw_params (pcm_handle, swparams)) < 0) { + _debugAlsa (" Cannot set sw parameters (%s)\n", snd_strerror (err)); return false; } - snd_pcm_sw_params_free( swparams ); + snd_pcm_sw_params_free (swparams); return true; } - bool -AlsaLayer::open_device(std::string pcm_p, std::string pcm_c, int flag) +bool +AlsaLayer::open_device (std::string pcm_p, std::string pcm_c, int flag) { int err; - - if(flag == SFL_PCM_BOTH || flag == SFL_PCM_PLAYBACK) - { - // if((err = snd_pcm_open(&_PlaybackHandle, pcm_p.c_str(), SND_PCM_STREAM_PLAYBACK, 0 )) < 0){ - if((err = snd_pcm_open(&_PlaybackHandle, pcm_p.c_str(), SND_PCM_STREAM_PLAYBACK, 0 )) < 0){ - _debugAlsa("Error while opening playback device %s\n", pcm_p.c_str()); - setErrorMessage( ALSA_PLAYBACK_DEVICE ); + + if (flag == SFL_PCM_BOTH || flag == SFL_PCM_PLAYBACK) { + // if((err = snd_pcm_open(&_PlaybackHandle, pcm_p.c_str(), SND_PCM_STREAM_PLAYBACK, 0 )) < 0){ + if ( (err = snd_pcm_open (&_PlaybackHandle, pcm_p.c_str(), SND_PCM_STREAM_PLAYBACK, 0)) < 0) { + _debugAlsa ("Error while opening playback device %s\n", pcm_p.c_str()); + setErrorMessage (ALSA_PLAYBACK_DEVICE); close_playback (); return false; } - if(!alsa_set_params( _PlaybackHandle, 1, getSampleRate() )){ - _debug("playback failed\n"); - snd_pcm_close( _PlaybackHandle ); + + if (!alsa_set_params (_PlaybackHandle, 1, getSampleRate())) { + _debug ("playback failed\n"); + snd_pcm_close (_PlaybackHandle); close_playback (); return false; } @@ -396,104 +425,117 @@ AlsaLayer::open_device(std::string pcm_p, std::string pcm_c, int flag) open_playback (); } - if(flag == SFL_PCM_BOTH || flag == SFL_PCM_CAPTURE) - { - if( (err = snd_pcm_open(&_CaptureHandle, pcm_c.c_str(), SND_PCM_STREAM_CAPTURE, 0)) < 0){ - _debugAlsa("Error while opening capture device %s\n", pcm_c.c_str()); - setErrorMessage( ALSA_CAPTURE_DEVICE ); + if (flag == SFL_PCM_BOTH || flag == SFL_PCM_CAPTURE) { + if ( (err = snd_pcm_open (&_CaptureHandle, pcm_c.c_str(), SND_PCM_STREAM_CAPTURE, 0)) < 0) { + _debugAlsa ("Error while opening capture device %s\n", pcm_c.c_str()); + setErrorMessage (ALSA_CAPTURE_DEVICE); close_capture (); return false; } - if(!alsa_set_params( _CaptureHandle, 0, 8000 )){ - _debug("capture failed\n"); - snd_pcm_close( _CaptureHandle ); + + if (!alsa_set_params (_CaptureHandle, 0, 8000)) { + _debug ("capture failed\n"); + snd_pcm_close (_CaptureHandle); close_capture (); return false; } open_capture (); + prepare_capture (); } /* Start the secondary audio thread for callbacks */ - try{ + try { _audioThread->start(); - } - catch (...) { - _debugException("Fail to start audio thread\n"); + } catch (...) { + _debugException ("Fail to start audio thread\n"); } return true; } //TODO first frame causes broken pipe (underrun) because not enough data are send --> make the handle wait to be ready - int -AlsaLayer::write(void* buffer, int length) +int +AlsaLayer::write (void* buffer, int length) { - if (_trigger_request == true) - { + if (_trigger_request == true) { _trigger_request = false; startPlaybackStream (); } - snd_pcm_uframes_t frames = snd_pcm_bytes_to_frames( _PlaybackHandle, length); + snd_pcm_uframes_t frames = snd_pcm_bytes_to_frames (_PlaybackHandle, length); + int err; - if ((err=snd_pcm_writei( _PlaybackHandle , buffer , frames ))<0) - { - switch(err) { - case -EPIPE: - case -ESTRPIPE: - case -EIO: + + if ( (err=snd_pcm_writei (_PlaybackHandle , buffer , frames)) <0) { + switch (err) { + + case -EPIPE: + + case -ESTRPIPE: + + case -EIO: //_debugAlsa(" XRUN playback ignored (%s)\n", snd_strerror(err)); handle_xrun_playback(); - if (snd_pcm_writei( _PlaybackHandle , buffer , frames )<0) + + if (snd_pcm_writei (_PlaybackHandle , buffer , frames) <0) _debugAlsa ("XRUN handling failed\n"); + _trigger_request = true; + break; + default: //_debugAlsa ("Write error unknown - dropping frames **********************************: %s\n", snd_strerror(err)); stopPlaybackStream (); + break; } } - return ( err > 0 )? err : 0 ; + return (err > 0) ? err : 0 ; } - int -AlsaLayer::read( void* buffer, int toCopy) +int +AlsaLayer::read (void* buffer, int toCopy) { //ost::MutexLock lock( _mutex ); - + int samples; - if(snd_pcm_state( _CaptureHandle ) == SND_PCM_STATE_XRUN) - { + if (snd_pcm_state (_CaptureHandle) == SND_PCM_STATE_XRUN) { prepareCaptureStream (); startCaptureStream (); } - - snd_pcm_uframes_t frames = snd_pcm_bytes_to_frames( _CaptureHandle, toCopy ); - if(( samples = snd_pcm_readi( _CaptureHandle, buffer, frames)) < 0 ) { - switch (samples) - { + + snd_pcm_uframes_t frames = snd_pcm_bytes_to_frames (_CaptureHandle, toCopy); + + if ( (samples = snd_pcm_readi (_CaptureHandle, buffer, frames)) < 0) { + switch (samples) { + case -EPIPE: + case -ESTRPIPE: + case -EIO: - _debugAlsa(" XRUN capture ignored (%s)\n", snd_strerror(samples)); + _debugAlsa (" XRUN capture ignored (%s)\n", snd_strerror (samples)); handle_xrun_capture(); //samples = snd_pcm_readi( _CaptureHandle, buffer, frames); //if (samples<0) samples=0; break; + case EPERM: - _debugAlsa(" Capture EPERM (%s)\n", snd_strerror(samples)); + _debugAlsa (" Capture EPERM (%s)\n", snd_strerror (samples)); prepareCaptureStream (); startCaptureStream (); break; + default: //_debugAlsa("%s\n", snd_strerror(samples)); break; } + return 0; } @@ -501,37 +543,36 @@ AlsaLayer::read( void* buffer, int toCopy) } - void -AlsaLayer::handle_xrun_capture( void ) +void +AlsaLayer::handle_xrun_capture (void) { snd_pcm_status_t* status; - snd_pcm_status_alloca( &status ); + snd_pcm_status_alloca (&status); - int res = snd_pcm_status( _CaptureHandle, status ); - if( res <= 0){ - if(snd_pcm_status_get_state(status) == SND_PCM_STATE_XRUN ){ + int res = snd_pcm_status (_CaptureHandle, status); + + if (res <= 0) { + if (snd_pcm_status_get_state (status) == SND_PCM_STATE_XRUN) { stopCaptureStream (); prepareCaptureStream (); startCaptureStream (); } - } - else - _debugAlsa(" Get status failed\n"); + } else + _debugAlsa (" Get status failed\n"); } - void -AlsaLayer::handle_xrun_playback( void ) +void +AlsaLayer::handle_xrun_playback (void) { - int state; + int state; snd_pcm_status_t* status; - snd_pcm_status_alloca( &status ); + snd_pcm_status_alloca (&status); - if( (state = snd_pcm_status( _PlaybackHandle, status )) < 0 ) _debugAlsa(" Error: Cannot get playback handle status (%s)\n" , snd_strerror( state ) ); - else - { - state = snd_pcm_status_get_state( status ); - if( state == SND_PCM_STATE_XRUN ) - { + if ( (state = snd_pcm_status (_PlaybackHandle, status)) < 0) _debugAlsa (" Error: Cannot get playback handle status (%s)\n" , snd_strerror (state)); + else { + state = snd_pcm_status_get_state (status); + + if (state == SND_PCM_STATE_XRUN) { stopPlaybackStream (); preparePlaybackStream (); _trigger_request = true; @@ -539,26 +580,32 @@ AlsaLayer::handle_xrun_playback( void ) } } - std::string -AlsaLayer::buildDeviceTopo( std::string plugin, int card, int subdevice ) +std::string +AlsaLayer::buildDeviceTopo (std::string plugin, int card, int subdevice) { std::string pcm = plugin; std::stringstream ss,ss1; - if( pcm == "default" || pcm == "pulse") + + if (pcm == "default" || pcm == "pulse") return pcm; + ss << card; - pcm.append(":"); - pcm.append(ss.str()); - if( subdevice != 0 ){ - pcm.append(","); + + pcm.append (":"); + + pcm.append (ss.str()); + + if (subdevice != 0) { + pcm.append (","); ss1 << subdevice; - pcm.append(ss1.str()); + pcm.append (ss1.str()); } + return pcm; } - std::vector<std::string> -AlsaLayer::getSoundCardsInfo( int stream ) +std::vector<std::string> +AlsaLayer::getSoundCardsInfo (int stream) { std::vector<std::string> cards_id; HwIDPair p; @@ -566,81 +613,88 @@ AlsaLayer::getSoundCardsInfo( int stream ) snd_ctl_t* handle; snd_ctl_card_info_t *info; snd_pcm_info_t* pcminfo; - snd_ctl_card_info_alloca( &info ); - snd_pcm_info_alloca( &pcminfo ); + snd_ctl_card_info_alloca (&info); + snd_pcm_info_alloca (&pcminfo); int numCard = -1 ; std::string description; - if(snd_card_next( &numCard ) < 0 || numCard < 0) + if (snd_card_next (&numCard) < 0 || numCard < 0) return cards_id; - while(numCard >= 0){ + while (numCard >= 0) { std::stringstream ss; ss << numCard; std::string name= "hw:"; - name.append(ss.str()); - - if( snd_ctl_open( &handle, name.c_str(), 0) == 0 ){ - if( snd_ctl_card_info( handle, info) == 0){ - snd_pcm_info_set_device( pcminfo , 0); - snd_pcm_info_set_stream( pcminfo, ( stream == SFL_PCM_CAPTURE )? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK ); - if( snd_ctl_pcm_info ( handle ,pcminfo ) < 0) _debugAlsa(" Cannot get info\n"); - else{ - _debugAlsa("card %i : %s [%s]\n", - numCard, - snd_ctl_card_info_get_id(info), - snd_ctl_card_info_get_name( info )); - description = snd_ctl_card_info_get_name( info ); - description.append(" - "); - description.append(snd_pcm_info_get_name( pcminfo )); - cards_id.push_back( description ); - // The number of the sound card is associated with a string description - p = HwIDPair( numCard , description ); - IDSoundCards.push_back( p ); + name.append (ss.str()); + + if (snd_ctl_open (&handle, name.c_str(), 0) == 0) { + if (snd_ctl_card_info (handle, info) == 0) { + snd_pcm_info_set_device (pcminfo , 0); + snd_pcm_info_set_stream (pcminfo, (stream == SFL_PCM_CAPTURE) ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK); + + if (snd_ctl_pcm_info (handle ,pcminfo) < 0) _debugAlsa (" Cannot get info\n"); + else { + _debugAlsa ("card %i : %s [%s]\n", + numCard, + snd_ctl_card_info_get_id (info), + snd_ctl_card_info_get_name (info)); + description = snd_ctl_card_info_get_name (info); + description.append (" - "); + description.append (snd_pcm_info_get_name (pcminfo)); + cards_id.push_back (description); + // The number of the sound card is associated with a string description + p = HwIDPair (numCard , description); + IDSoundCards.push_back (p); } } - snd_ctl_close( handle ); + + snd_ctl_close (handle); } - if ( snd_card_next( &numCard ) < 0 ) { + + if (snd_card_next (&numCard) < 0) { break; } } + return cards_id; } - bool -AlsaLayer::soundCardIndexExist( int card , int stream ) +bool +AlsaLayer::soundCardIndexExist (int card , int stream) { snd_ctl_t* handle; snd_pcm_info_t *pcminfo; - snd_pcm_info_alloca( &pcminfo ); + snd_pcm_info_alloca (&pcminfo); std::string name = "hw:"; std::stringstream ss; ss << card ; - name.append(ss.str()); - if(snd_ctl_open( &handle, name.c_str(), 0) == 0 ){ - snd_pcm_info_set_stream( pcminfo , ( stream == SFL_PCM_PLAYBACK )? SND_PCM_STREAM_PLAYBACK : SND_PCM_STREAM_CAPTURE ); - if( snd_ctl_pcm_info( handle , pcminfo ) < 0) return false; + name.append (ss.str()); + + if (snd_ctl_open (&handle, name.c_str(), 0) == 0) { + snd_pcm_info_set_stream (pcminfo , (stream == SFL_PCM_PLAYBACK) ? SND_PCM_STREAM_PLAYBACK : SND_PCM_STREAM_CAPTURE); + + if (snd_ctl_pcm_info (handle , pcminfo) < 0) return false; else return true; - } - else + } else return false; -} +} - int -AlsaLayer::soundCardGetIndex( std::string description ) +int +AlsaLayer::soundCardGetIndex (std::string description) { unsigned int i; - for( i = 0 ; i < IDSoundCards.size() ; i++ ) - { + + for (i = 0 ; i < IDSoundCards.size() ; i++) { HwIDPair p = IDSoundCards[i]; - if( p.second == description ) + + if (p.second == description) return p.first ; } + // else return the default one return 0; } @@ -648,7 +702,7 @@ AlsaLayer::soundCardGetIndex( std::string description ) void AlsaLayer::audioCallback (void) { - int toGet, toPut, urgentAvail, normalAvail, micAvailAlsa, micAvailPut, maxBytes; + int toGet, toPut, urgentAvail, normalAvail, micAvailAlsa, micAvailPut, maxBytes; unsigned short spkrVolume, micVolume; AudioLoop *tone; @@ -661,46 +715,52 @@ void AlsaLayer::audioCallback (void) // AvailForGet tell the number of chars inside the buffer // framePerBuffer are the number of data for one channel (left) urgentAvail = _urgentRingBuffer.AvailForGet(); + if (urgentAvail > 0) { - // Urgent data (dtmf, incoming call signal) come first. - toGet = (urgentAvail < (int)(framesPerBufferAlsa * sizeof(SFLDataFormat))) ? urgentAvail : framesPerBufferAlsa * sizeof(SFLDataFormat); - out = (SFLDataFormat*)malloc(toGet * sizeof(SFLDataFormat) ); - _urgentRingBuffer.Get(out, toGet, spkrVolume); + // Urgent data (dtmf, incoming call signal) come first. + toGet = (urgentAvail < (int) (framesPerBufferAlsa * sizeof (SFLDataFormat))) ? urgentAvail : framesPerBufferAlsa * sizeof (SFLDataFormat); + out = (SFLDataFormat*) malloc (toGet * sizeof (SFLDataFormat)); + _urgentRingBuffer.Get (out, toGet, spkrVolume); /* Play the sound */ - write( out , toGet ); - free(out); out=0; + write (out , toGet); + free (out); + out=0; // Consume the regular one as well (same amount of bytes) - _voiceRingBuffer.Discard(toGet); + _voiceRingBuffer.Discard (toGet); } else { tone = _manager->getTelephoneTone(); - toGet = 940 ; - maxBytes = toGet * sizeof(SFLDataFormat) ; - if ( tone != 0) { - out = (SFLDataFormat*)malloc(maxBytes * sizeof(SFLDataFormat)); - tone->getNext(out, toGet, spkrVolume); + toGet = 940 ; + maxBytes = toGet * sizeof (SFLDataFormat) ; + + if (tone != 0) { + out = (SFLDataFormat*) malloc (maxBytes * sizeof (SFLDataFormat)); + tone->getNext (out, toGet, spkrVolume); write (out , maxBytes); - } else if ( (tone=_manager->getTelephoneFile()) != 0 ) { - out = (SFLDataFormat*)malloc(maxBytes * sizeof(SFLDataFormat) ); - tone->getNext(out, toGet, spkrVolume); + } else if ( (tone=_manager->getTelephoneFile()) != 0) { + out = (SFLDataFormat*) malloc (maxBytes * sizeof (SFLDataFormat)); + tone->getNext (out, toGet, spkrVolume); write (out , maxBytes); } else { // If nothing urgent, play the regular sound samples normalAvail = _voiceRingBuffer.AvailForGet(); - toGet = (normalAvail < (int)(framesPerBufferAlsa * sizeof(SFLDataFormat))) ? normalAvail : framesPerBufferAlsa * sizeof(SFLDataFormat); - out = (SFLDataFormat*)malloc(framesPerBufferAlsa * sizeof(SFLDataFormat)); + toGet = (normalAvail < (int) (framesPerBufferAlsa * sizeof (SFLDataFormat))) ? normalAvail : framesPerBufferAlsa * sizeof (SFLDataFormat); + out = (SFLDataFormat*) malloc (framesPerBufferAlsa * sizeof (SFLDataFormat)); if (toGet) { - _voiceRingBuffer.Get(out, toGet, spkrVolume); + _voiceRingBuffer.Get (out, toGet, spkrVolume); write (out, toGet); } else { - bzero(out, framesPerBufferAlsa * sizeof(SFLDataFormat)); + bzero (out, framesPerBufferAlsa * sizeof (SFLDataFormat)); } } - free(out); out=0; + + free (out); + + out=0; } - - // Additionally handle the mic's audio stream - //if(is_capture_running()){ + + // Additionally handle the mic's audio stream + //if(is_capture_running()){ /*micAvailAlsa = snd_pcm_avail_update(_CaptureHandle); if(micAvailAlsa > 0) { micAvailPut = _micRingBuffer.AvailForPut(); @@ -708,28 +768,29 @@ void AlsaLayer::audioCallback (void) in = (SFLDataFormat*)malloc(toPut * sizeof(SFLDataFormat)); toPut = read (in, toPut); if (in != 0) - { + { _micRingBuffer.Put(in, toPut, 100); } free(in); in=0; }*/ } -void* AlsaLayer::adjustVolume( void* buffer , int len, int stream ) +void* AlsaLayer::adjustVolume (void* buffer , int len, int stream) { int vol, i, size; SFLDataFormat *src = NULL; - (stream == SFL_PCM_PLAYBACK)? vol = _manager->getSpkrVolume() : vol = _manager->getMicVolume(); + (stream == SFL_PCM_PLAYBACK) ? vol = _manager->getSpkrVolume() : vol = _manager->getMicVolume(); src = (SFLDataFormat*) buffer; - if( vol != 100 ) - { - size = len / sizeof(SFLDataFormat); - for( i = 0 ; i < size ; i++ ){ + if (vol != 100) { + size = len / sizeof (SFLDataFormat); + + for (i = 0 ; i < size ; i++) { src[i] = src[i] * vol / 100 ; } } - return src ; + + return src ; } diff --git a/sflphone-common/src/audio/audiodevice.cpp b/sflphone-common/src/audio/audiodevice.cpp index f82ce075a2..07c3edb4f2 100644 --- a/sflphone-common/src/audio/audiodevice.cpp +++ b/sflphone-common/src/audio/audiodevice.cpp @@ -22,13 +22,13 @@ const double AudioDevice::DEFAULT_RATE = 8000.0; -AudioDevice::AudioDevice(int id, const std::string& name) : - _id(id), _name(name), _rate(DEFAULT_RATE) +AudioDevice::AudioDevice (int id, const std::string& name) : + _id (id), _name (name), _rate (DEFAULT_RATE) { - _rate = DEFAULT_RATE; + _rate = DEFAULT_RATE; } -AudioDevice::~AudioDevice() +AudioDevice::~AudioDevice() { } diff --git a/sflphone-common/src/audio/audiofile.cpp b/sflphone-common/src/audio/audiofile.cpp index 5d639f296f..82518c850b 100644 --- a/sflphone-common/src/audio/audiofile.cpp +++ b/sflphone-common/src/audio/audiofile.cpp @@ -2,10 +2,10 @@ * Copyright (C) 2005-2007 Savoir-Faire Linux inc. * Author: Yan Morin <yan.morin@savoirfairelinux.com> * - * Inspired by tonegenerator of + * Inspired by tonegenerator of * Laurielle Lea <laurielle.lea@savoirfairelinux.com> (2004) * Inspired by ringbuffer of Audacity Project - * + * * 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 @@ -28,10 +28,10 @@ #include <cstring> AudioFile::AudioFile() - : AudioLoop(), - _filename(), - _codec(NULL), - _start(false) + : AudioLoop(), + _filename(), + _codec (NULL), + _start (false) { } @@ -42,114 +42,125 @@ AudioFile::~AudioFile() // load file in mono format bool -AudioFile::loadFile(const std::string& filename, AudioCodec* codec , unsigned int sampleRate=8000) +AudioFile::loadFile (const std::string& filename, AudioCodec* codec , unsigned int sampleRate=8000) { - _codec = codec; + _codec = codec; - // if the filename was already load, with the same samplerate - // we do nothing - if ( strcmp(_filename.c_str(), filename.c_str()) == 0 && _sampleRate == (int)sampleRate) { - return true; - } else { - // reset to 0 - delete [] _buffer; _buffer = 0; - _size = 0; - _pos = 0; - } - - - - // no filename to load - if (filename.empty()) { - _debug("Unable to open audio file: filename is empty\n"); - return false; - } - - std::fstream file; - file.open(filename.c_str(), std::fstream::in); - if (!file.is_open()) { - // unable to load the file - _debug("Unable to open audio file %s\n", filename.c_str()); - return false; - } - - // get length of file: - file.seekg (0, std::ios::end); - int length = file.tellg(); - file.seekg (0, std::ios::beg); - - // allocate memory: - char fileBuffer[length]; - - // read data as a block: - file.read (fileBuffer,length); - file.close(); - - - // Decode file.ul - // expandedsize is the number of bytes, not the number of int - // expandedsize should be exactly two time more, else failed - int16 monoBuffer[length]; - int expandedsize = (int)_codec->codecDecode (monoBuffer, (unsigned char *) fileBuffer, length); - if (expandedsize != length*2) { - _debug("Audio file error on loading audio file!"); - return false; - } - unsigned int nbSampling = expandedsize/sizeof(int16); - - // we need to change the sample rating here: - // case 1: we don't have to resample : only do splitting and convert - if ( sampleRate == 8000 ) { - // just s - _size = nbSampling; - _buffer = new SFLDataFormat[_size]; + // if the filename was already load, with the same samplerate + // we do nothing + + if (strcmp (_filename.c_str(), filename.c_str()) == 0 && _sampleRate == (int) sampleRate) { + return true; + } else { + // reset to 0 + delete [] _buffer; + _buffer = 0; + _size = 0; + _pos = 0; + } + + + + // no filename to load + if (filename.empty()) { + _debug ("Unable to open audio file: filename is empty\n"); + return false; + } + + std::fstream file; + + file.open (filename.c_str(), std::fstream::in); + + if (!file.is_open()) { + // unable to load the file + _debug ("Unable to open audio file %s\n", filename.c_str()); + return false; + } + + // get length of file: + file.seekg (0, std::ios::end); + + int length = file.tellg(); + + file.seekg (0, std::ios::beg); + + // allocate memory: + char fileBuffer[length]; + + // read data as a block: + file.read (fileBuffer,length); + + file.close(); + + + // Decode file.ul + // expandedsize is the number of bytes, not the number of int + // expandedsize should be exactly two time more, else failed + int16 monoBuffer[length]; + + int expandedsize = (int) _codec->codecDecode (monoBuffer, (unsigned char *) fileBuffer, length); + + if (expandedsize != length*2) { + _debug ("Audio file error on loading audio file!"); + return false; + } + + unsigned int nbSampling = expandedsize/sizeof (int16); + + // we need to change the sample rating here: + // case 1: we don't have to resample : only do splitting and convert + + if (sampleRate == 8000) { + // just s + _size = nbSampling; + _buffer = new SFLDataFormat[_size]; #ifdef DATAFORMAT_IS_FLOAT - // src to dest - src_short_to_float_array(monoBuffer, _buffer, nbSampling); + // src to dest + src_short_to_float_array (monoBuffer, _buffer, nbSampling); #else - // dest to src - memcpy(_buffer, monoBuffer, _size*sizeof(SFLDataFormat)); + // dest to src + memcpy (_buffer, monoBuffer, _size*sizeof (SFLDataFormat)); #endif - } else { - // case 2: we need to convert it and split it - // convert here - double factord = (double)sampleRate / 8000; - float* floatBufferIn = new float[nbSampling]; - int sizeOut = (int)(ceil(factord*nbSampling)); - src_short_to_float_array(monoBuffer, floatBufferIn, nbSampling); - SFLDataFormat* bufferTmp = new SFLDataFormat[sizeOut]; - - SRC_DATA src_data; - src_data.data_in = floatBufferIn; - src_data.input_frames = nbSampling; - src_data.output_frames = sizeOut; - src_data.src_ratio = factord; + } else { + // case 2: we need to convert it and split it + // convert here + double factord = (double) sampleRate / 8000; + float* floatBufferIn = new float[nbSampling]; + int sizeOut = (int) (ceil (factord*nbSampling)); + src_short_to_float_array (monoBuffer, floatBufferIn, nbSampling); + SFLDataFormat* bufferTmp = new SFLDataFormat[sizeOut]; + + SRC_DATA src_data; + src_data.data_in = floatBufferIn; + src_data.input_frames = nbSampling; + src_data.output_frames = sizeOut; + src_data.src_ratio = factord; #ifdef DATAFORMAT_IS_FLOAT - // case number 2.1: the output is float32 : convert directly in _bufferTmp - src_data.data_out = bufferTmp; - src_simple (&src_data, SRC_SINC_BEST_QUALITY, 1); + // case number 2.1: the output is float32 : convert directly in _bufferTmp + src_data.data_out = bufferTmp; + src_simple (&src_data, SRC_SINC_BEST_QUALITY, 1); #else - // case number 2.2: the output is int16 : convert and change to int16 - float* floatBufferOut = new float[sizeOut]; - src_data.data_out = floatBufferOut; + // case number 2.2: the output is int16 : convert and change to int16 + float* floatBufferOut = new float[sizeOut]; + src_data.data_out = floatBufferOut; - src_simple (&src_data, SRC_SINC_BEST_QUALITY, 1); - src_float_to_short_array(floatBufferOut, bufferTmp, src_data.output_frames_gen); + src_simple (&src_data, SRC_SINC_BEST_QUALITY, 1); + src_float_to_short_array (floatBufferOut, bufferTmp, src_data.output_frames_gen); - delete [] floatBufferOut; + delete [] floatBufferOut; #endif - delete [] floatBufferIn; - nbSampling = src_data.output_frames_gen; - - // if we are in mono, we send the bufferTmp location and don't delete it - // else we split the audio in 2 and put it into buffer - _size = nbSampling; - _buffer = bufferTmp; // just send the buffer pointer; - bufferTmp = 0; - } - - return true; + delete [] floatBufferIn; + nbSampling = src_data.output_frames_gen; + + // if we are in mono, we send the bufferTmp location and don't delete it + // else we split the audio in 2 and put it into buffer + _size = nbSampling; + _buffer = bufferTmp; // just send the buffer pointer; + bufferTmp = 0; + } + + return true; } diff --git a/sflphone-common/src/audio/audiolayer.cpp b/sflphone-common/src/audio/audiolayer.cpp index 3eea4392c7..68eca5a9c7 100644 --- a/sflphone-common/src/audio/audiolayer.cpp +++ b/sflphone-common/src/audio/audiolayer.cpp @@ -6,12 +6,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -21,33 +21,35 @@ void AudioLayer::flushMain (void) { - ost::MutexLock guard(_mutex); + ost::MutexLock guard (_mutex); _voiceRingBuffer.flush(); } void AudioLayer::flushUrgent (void) { - ost::MutexLock guard(_mutex); + ost::MutexLock guard (_mutex); _urgentRingBuffer.flush(); } void AudioLayer::flushMic (void) { - ost::MutexLock guard(_mutex); + ost::MutexLock guard (_mutex); _micRingBuffer.flush(); } -int AudioLayer::putUrgent(void* buffer, int toCopy) +int AudioLayer::putUrgent (void* buffer, int toCopy) { int a; - ost::MutexLock guard(_mutex); + ost::MutexLock guard (_mutex); a = _urgentRingBuffer.AvailForPut(); - if ( a >= toCopy ) { - return _urgentRingBuffer.Put(buffer, toCopy, _defaultVolume); + + if (a >= toCopy) { + return _urgentRingBuffer.Put (buffer, toCopy, _defaultVolume); } else { - return _urgentRingBuffer.Put(buffer, a, _defaultVolume); + return _urgentRingBuffer.Put (buffer, a, _defaultVolume); } + return 0; } @@ -55,14 +57,16 @@ int AudioLayer::putMain (void *buffer, int toCopy) { int a; - ost::MutexLock guard(_mutex); + ost::MutexLock guard (_mutex); a = _voiceRingBuffer.AvailForPut(); - if ( a >= toCopy ) { - return _voiceRingBuffer.Put(buffer, toCopy, _defaultVolume); + + if (a >= toCopy) { + return _voiceRingBuffer.Put (buffer, toCopy, _defaultVolume); } else { - _debug("Chopping sound, Ouch! RingBuffer full ?\n"); - return _voiceRingBuffer.Put(buffer, a, _defaultVolume); + _debug ("Chopping sound, Ouch! RingBuffer full ?\n"); + return _voiceRingBuffer.Put (buffer, a, _defaultVolume); } + return 0; } diff --git a/sflphone-common/src/audio/audioloop.cpp b/sflphone-common/src/audio/audioloop.cpp index ecf85d1b03..633192de44 100644 --- a/sflphone-common/src/audio/audioloop.cpp +++ b/sflphone-common/src/audio/audioloop.cpp @@ -2,10 +2,10 @@ * Copyright (C) 2005 Savoir-Faire Linux inc. * Author: Yan Morin <yan.morin@savoirfairelinux.com> * - * Inspired by tonegenerator of + * Inspired by tonegenerator of * Laurielle Lea <laurielle.lea@savoirfairelinux.com> (2004) * Inspired by ringbuffer of Audacity Project - * + * * 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 @@ -24,42 +24,52 @@ #include <math.h> #include <strings.h> -AudioLoop::AudioLoop():_buffer(0), _size(0), _pos(0), _sampleRate(0) +AudioLoop::AudioLoop() :_buffer (0), _size (0), _pos (0), _sampleRate (0) { } AudioLoop::~AudioLoop() { - delete [] _buffer; _buffer = 0; + delete [] _buffer; + _buffer = 0; } int -AudioLoop::getNext(SFLDataFormat* output, int nb, short volume) +AudioLoop::getNext (SFLDataFormat* output, int nb, short volume) { - int copied = 0; - int block; - int pos = _pos; - while(nb) { - block = nb; - if ( block > (_size-pos) ) { - block = _size-pos; - } - // src, dest, len - bcopy(_buffer+pos, output, block*sizeof(SFLDataFormat)); // short>char conversion - if (volume!=100) { - for (int i=0;i<block;i++) { - *output = (*output * volume)/100; - output++; - } - } else { - output += block; // this is the destination... + int copied = 0; + int block; + int pos = _pos; + + while (nb) { + block = nb; + + if (block > (_size-pos)) { + block = _size-pos; + } + + // src, dest, len + bcopy (_buffer+pos, output, block*sizeof (SFLDataFormat)); // short>char conversion + + if (volume!=100) { + for (int i=0;i<block;i++) { + *output = (*output * volume) /100; + output++; + } + } else { + output += block; // this is the destination... + } + + // should adjust sound here, in output??? + pos = (pos + block) % _size; + + nb -= block; + + copied += block; } - // should adjust sound here, in output??? - pos = (pos + block ) % _size; - nb -= block; - copied += block; - } - _pos = pos; - return copied; + + _pos = pos; + + return copied; } diff --git a/sflphone-common/src/audio/audiortp.cpp b/sflphone-common/src/audio/audiortp.cpp index 40b9f03dfa..b16147e9e8 100644 --- a/sflphone-common/src/audio/audiortp.cpp +++ b/sflphone-common/src/audio/audiortp.cpp @@ -42,53 +42,59 @@ #include "../sipcall.h" //////////////////////////////////////////////////////////////////////////////// -// AudioRtp +// AudioRtp //////////////////////////////////////////////////////////////////////////////// -AudioRtp::AudioRtp() :_RTXThread(0), _symmetric(), _threadMutex() +AudioRtp::AudioRtp() :_RTXThread (0), _symmetric(), _threadMutex() { } -AudioRtp::~AudioRtp (void) { - delete _RTXThread; _RTXThread = 0; +AudioRtp::~AudioRtp (void) +{ + delete _RTXThread; + _RTXThread = 0; } -void -AudioRtp::createNewSession (SIPCall *ca) { +void +AudioRtp::createNewSession (SIPCall *ca) +{ - ost::MutexLock m(_threadMutex); + ost::MutexLock m (_threadMutex); - _debug("AudioRtp::Create new rtp session\n"); + _debug ("AudioRtp::Create new rtp session\n"); // something should stop the thread before... - if ( _RTXThread != 0 ) { - _debug("**********************************************************\n"); - _debug("! ARTP Failure: Thread already exists..., stopping it\n"); - _debug("**********************************************************\n"); - delete _RTXThread; _RTXThread = 0; + + if (_RTXThread != 0) { + _debug ("**********************************************************\n"); + _debug ("! ARTP Failure: Thread already exists..., stopping it\n"); + _debug ("**********************************************************\n"); + delete _RTXThread; + _RTXThread = 0; } // Start RTP Send/Receive threads - _symmetric = Manager::instance().getConfigInt(SIGNALISATION,SYMMETRIC) ? true : false; + _symmetric = Manager::instance().getConfigInt (SIGNALISATION,SYMMETRIC) ? true : false; + _RTXThread = new AudioRtpRTX (ca, _symmetric); } int -AudioRtp::start(void) +AudioRtp::start (void) { - if(_RTXThread == 0) { - _debug("! ARTP Failure: Cannot start audiortp thread since not yet created\n"); + if (_RTXThread == 0) { + _debug ("! ARTP Failure: Cannot start audiortp thread since not yet created\n"); throw AudioRtpException(); } try { if (_RTXThread->start() != 0) { - _debug("! ARTP Failure: unable to start RTX Thread\n"); + _debug ("! ARTP Failure: unable to start RTX Thread\n"); return -1; } - } catch(...) { - _debugException("! ARTP Failure: when trying to start a thread"); + } catch (...) { + _debugException ("! ARTP Failure: when trying to start a thread"); throw; } @@ -97,23 +103,27 @@ AudioRtp::start(void) bool -AudioRtp::closeRtpSession () { +AudioRtp::closeRtpSession () +{ - ost::MutexLock m(_threadMutex); + ost::MutexLock m (_threadMutex); // This will make RTP threads finish. - _debug("AudioRtp::Stopping rtp session\n"); - + _debug ("AudioRtp::Stopping rtp session\n"); + try { - delete _RTXThread; _RTXThread = 0; - } catch(...) { - _debugException("! ARTP Exception: when stopping audiortp\n"); + delete _RTXThread; + _RTXThread = 0; + } catch (...) { + _debugException ("! ARTP Exception: when stopping audiortp\n"); throw; } + // AudioLayer* audiolayer = Manager::instance().getAudioDriver(); // audiolayer->stopStream(); - _debug("AudioRtp::Audio rtp stopped\n"); + _debug ("AudioRtp::Audio rtp stopped\n"); + return true; } @@ -126,9 +136,10 @@ AudioRtp::getRTX() void -AudioRtp::setRecording() { +AudioRtp::setRecording() +{ - _debug("AudioRtp::setRecording\n"); + _debug ("AudioRtp::setRecording\n"); _RTXThread->_ca->setRecording(); } @@ -140,18 +151,18 @@ AudioRtp::setRecording() { //////////////////////////////////////////////////////////////////////////////// // AudioRtpRTX Class // //////////////////////////////////////////////////////////////////////////////// -AudioRtpRTX::AudioRtpRTX (SIPCall *sipcall, bool sym) : time(new ost::Time()), _ca(sipcall), _sessionSend(NULL), _sessionRecv(NULL), _session(NULL), - _sym(sym), micData(NULL), micDataConverted(NULL), micDataEncoded(NULL), spkrDataDecoded(NULL), spkrDataConverted(NULL), - converter(NULL), _layerSampleRate(),_codecSampleRate(), _layerFrameSize(), _audiocodec(NULL) +AudioRtpRTX::AudioRtpRTX (SIPCall *sipcall, bool sym) : time (new ost::Time()), _ca (sipcall), _sessionSend (NULL), _sessionRecv (NULL), _session (NULL), + _sym (sym), micData (NULL), micDataConverted (NULL), micDataEncoded (NULL), spkrDataDecoded (NULL), spkrDataConverted (NULL), + converter (NULL), _layerSampleRate(),_codecSampleRate(), _layerFrameSize(), _audiocodec (NULL) { - setCancel(cancelDefault); + setCancel (cancelDefault); // AudioRtpRTX should be close if we change sample rate // TODO: Change bind address according to user settings. // TODO: this should be the local ip not the external (router) IP std::string localipConfig = _ca->getLocalIp(); // _ca->getLocalIp(); - ost::InetHostAddress local_ip(localipConfig.c_str()); - + ost::InetHostAddress local_ip (localipConfig.c_str()); + _debug ("%i\n", _ca->getLocalAudioPort()); _session = new ost::SymmetricRTPSession (local_ip, _ca->getLocalAudioPort()); // _session = new ost::RTPSessionBase(local_ip, _ca->getLocalAudioPort()); @@ -170,45 +181,55 @@ AudioRtpRTX::AudioRtpRTX (SIPCall *sipcall, bool sym) : time(new ost::Time()), _ _payloadIsSet = false; _remoteIpIsSet = false; - + } -AudioRtpRTX::~AudioRtpRTX () { +AudioRtpRTX::~AudioRtpRTX () +{ - _debug("Delete AudioRtpRTX instance\n"); + _debug ("Delete AudioRtpRTX instance\n"); try { this->terminate(); - } catch(...) { - _debugException("! ARTP: Thread destructor didn't terminate correctly"); + } catch (...) { + _debugException ("! ARTP: Thread destructor didn't terminate correctly"); throw; } + _ca = 0; - delete [] micData; micData = NULL; - delete [] micDataConverted; micDataConverted = NULL; - delete [] micDataEncoded; micDataEncoded = NULL; + delete [] micData; + micData = NULL; + delete [] micDataConverted; + micDataConverted = NULL; + delete [] micDataEncoded; + micDataEncoded = NULL; - delete [] spkrDataDecoded; spkrDataDecoded = NULL; - delete [] spkrDataConverted; spkrDataConverted = NULL; + delete [] spkrDataDecoded; + spkrDataDecoded = NULL; + delete [] spkrDataConverted; + spkrDataConverted = NULL; - delete time; time = NULL; + delete time; + time = NULL; - delete converter; converter = NULL; + delete converter; + converter = NULL; // _session->terminate(); - delete _session; _session = NULL; + delete _session; + _session = NULL; - _debug("AudioRtpRTX instance deleted\n"); + _debug ("AudioRtpRTX instance deleted\n"); } - void +void AudioRtpRTX::initBuffers() { - converter = new SamplerateConverter( _layerSampleRate , _layerFrameSize ); + converter = new SamplerateConverter (_layerSampleRate , _layerFrameSize); int nbSamplesMax = (int) (_layerSampleRate * _layerFrameSize /1000); @@ -221,104 +242,114 @@ AudioRtpRTX::initBuffers() } - void -AudioRtpRTX::initAudioRtpSession (void) +void +AudioRtpRTX::initAudioRtpSession (void) { try { - - _session->setSchedulingTimeout(100000); - _session->setExpireTimeout(1000000); + _session->setSchedulingTimeout (100000); + _session->setExpireTimeout (1000000); - } catch(...) { - _debugException("! ARTP Failure: initialisation failed"); + + } catch (...) { + _debugException ("! ARTP Failure: initialisation failed"); throw; - } + } } void -AudioRtpRTX::setRtpSessionMedia(void) +AudioRtpRTX::setRtpSessionMedia (void) { - if (_ca == 0) { _debug(" !ARTP: No call, can't init RTP media\n"); return; } + if (_ca == 0) { + _debug (" !ARTP: No call, can't init RTP media\n"); + return; + } _audiocodec = _ca->getLocalSDP()->get_session_media (); - if (_audiocodec == NULL) { _debug(" !ARTP: No audiocodec, can't init RTP media\n"); return; } + if (_audiocodec == NULL) { + _debug (" !ARTP: No audiocodec, can't init RTP media\n"); + return; + } - _debug("Init audio RTP session: codec payload %i\n", _audiocodec->getPayload()); + _debug ("Init audio RTP session: codec payload %i\n", _audiocodec->getPayload()); - if (_audiocodec == NULL) { return; } + if (_audiocodec == NULL) { + return; + } _codecSampleRate = _audiocodec->getClockRate(); + _codecFrameSize = _audiocodec->getFrameSize(); - if( _audiocodec->getPayload() == 9 ) { - _debug("We Are G722\n"); - _payloadIsSet = _session->setPayloadFormat(ost::DynamicPayloadFormat((ost::PayloadType) _audiocodec->getPayload(), _audiocodec->getClockRate())); - } - else if ( _audiocodec->hasDynamicPayload() ) { - _debug("We Are Dynamic\n"); - _payloadIsSet = _session->setPayloadFormat(ost::DynamicPayloadFormat((ost::PayloadType) _audiocodec->getPayload(), _audiocodec->getClockRate())); + if (_audiocodec->getPayload() == 9) { + _debug ("We Are G722\n"); + _payloadIsSet = _session->setPayloadFormat (ost::DynamicPayloadFormat ( (ost::PayloadType) _audiocodec->getPayload(), _audiocodec->getClockRate())); + } else if (_audiocodec->hasDynamicPayload()) { + _debug ("We Are Dynamic\n"); + _payloadIsSet = _session->setPayloadFormat (ost::DynamicPayloadFormat ( (ost::PayloadType) _audiocodec->getPayload(), _audiocodec->getClockRate())); + } else if (!_audiocodec->hasDynamicPayload() && _audiocodec->getPayload() != 9) { + _debug ("We Are Static\n"); + _payloadIsSet = _session->setPayloadFormat (ost::StaticPayloadFormat ( (ost::StaticPayloadType) _audiocodec->getPayload())); } - else if ( !_audiocodec->hasDynamicPayload() && _audiocodec->getPayload() != 9) { - _debug("We Are Static\n"); - _payloadIsSet = _session->setPayloadFormat(ost::StaticPayloadFormat((ost::StaticPayloadType) _audiocodec->getPayload())); - } - - + + } void -AudioRtpRTX::setRtpSessionRemoteIp(void) +AudioRtpRTX::setRtpSessionRemoteIp (void) { - if (!_remoteIpIsSet){ + if (!_remoteIpIsSet) { + + _debug ("++++++++++++++++++++++++++ SET IP ADDRESS ++++++++++++++++++++++++++++\n"); + + if (_ca == 0) { + _debug (" !ARTP: No call, can't init RTP media \n"); + return; + } - _debug("++++++++++++++++++++++++++ SET IP ADDRESS ++++++++++++++++++++++++++++\n"); + ost::InetHostAddress remote_ip (_ca->getLocalSDP()->get_remote_ip().c_str()); - if (_ca == 0) { _debug(" !ARTP: No call, can't init RTP media \n"); return; } + _debug ("Init audio RTP session: remote ip %s\n", _ca->getLocalSDP()->get_remote_ip().data()); - ost::InetHostAddress remote_ip(_ca->getLocalSDP()->get_remote_ip().c_str()); - _debug("Init audio RTP session: remote ip %s\n", _ca->getLocalSDP()->get_remote_ip().data()); - if (!remote_ip) - { - _debug(" !ARTP Thread Error: Target IP address [%s] is not correct!\n", _ca->getLocalSDP()->get_remote_ip().data()); + if (!remote_ip) { + _debug (" !ARTP Thread Error: Target IP address [%s] is not correct!\n", _ca->getLocalSDP()->get_remote_ip().data()); return; } - _debug("++++Address: %s, audioport: %d\n", _ca->getLocalSDP()->get_remote_ip().c_str(), _ca->getLocalSDP()->get_remote_audio_port()); - _debug("++++Audioport: %d\n", (int)_ca->getLocalSDP()->get_remote_audio_port()); + _debug ("++++Address: %s, audioport: %d\n", _ca->getLocalSDP()->get_remote_ip().c_str(), _ca->getLocalSDP()->get_remote_audio_port()); + + _debug ("++++Audioport: %d\n", (int) _ca->getLocalSDP()->get_remote_audio_port()); - if (!_session->addDestination (remote_ip, (unsigned short)_ca->getLocalSDP()->get_remote_audio_port() )) - { - _debug(" !ARTP Thread Error: can't add destination to session!\n"); + if (!_session->addDestination (remote_ip, (unsigned short) _ca->getLocalSDP()->get_remote_audio_port())) { + _debug (" !ARTP Thread Error: can't add destination to session!\n"); return; } + _remoteIpIsSet = true; - } - else - { - _debug("+++++++++++++++++++++++ IP ADDRESS ALREADY SET ++++++++++++++++++++++++\n"); + } else { + _debug ("+++++++++++++++++++++++ IP ADDRESS ALREADY SET ++++++++++++++++++++++++\n"); } } -float -AudioRtpRTX::computeCodecFrameSize(int codecSamplePerFrame, int codecClockRate) +float +AudioRtpRTX::computeCodecFrameSize (int codecSamplePerFrame, int codecClockRate) { - return ( (float)codecSamplePerFrame * 1000.0 ) / (float)codecClockRate; + return ( (float) codecSamplePerFrame * 1000.0) / (float) codecClockRate; } int -AudioRtpRTX::computeNbByteAudioLayer(float codecFrameSize) +AudioRtpRTX::computeNbByteAudioLayer (float codecFrameSize) { - return (int)((float)_layerSampleRate * codecFrameSize * (float)sizeof(SFLDataFormat) / 1000.0); + return (int) ( (float) _layerSampleRate * codecFrameSize * (float) sizeof (SFLDataFormat) / 1000.0); } @@ -327,11 +358,11 @@ AudioRtpRTX::processDataEncode() { // compute codec framesize in ms - float fixed_codec_framesize = computeCodecFrameSize(_audiocodec->getFrameSize(), _audiocodec->getClockRate()); + float fixed_codec_framesize = computeCodecFrameSize (_audiocodec->getFrameSize(), _audiocodec->getClockRate()); // compute nb of byte to get coresponding to 20 ms at audio layer frame size (44.1 khz) - int maxBytesToGet = computeNbByteAudioLayer(fixed_codec_framesize); - + int maxBytesToGet = computeNbByteAudioLayer (fixed_codec_framesize); + // available bytes inside ringbuffer int availBytesFromMic = _audiolayer->canGetMic(); @@ -339,10 +370,10 @@ AudioRtpRTX::processDataEncode() int bytesAvail = (availBytesFromMic < maxBytesToGet) ? availBytesFromMic : maxBytesToGet; if (bytesAvail == 0) - return 0; + return 0; // Get bytes from micRingBuffer to data_from_mic - int nbSample = _audiolayer->getMic( micData , bytesAvail ) / sizeof(SFLDataFormat); + int nbSample = _audiolayer->getMic (micData , bytesAvail) / sizeof (SFLDataFormat); // nb bytes to be sent over RTP int compSize = 0; @@ -352,21 +383,21 @@ AudioRtpRTX::processDataEncode() int nb_sample_up = nbSample; // _debug("_nbSample audiolayer->getMic(): %i \n", nbSample); - + // Store the length of the mic buffer in samples for recording _nSamplesMic = nbSample; - // int nbSamplesMax = _layerFrameSize * _audiocodec->getClockRate() / 1000; - nbSample = reSampleData(micData , micDataConverted, _audiocodec->getClockRate(), nb_sample_up, DOWN_SAMPLING); + // int nbSamplesMax = _layerFrameSize * _audiocodec->getClockRate() / 1000; + nbSample = reSampleData (micData , micDataConverted, _audiocodec->getClockRate(), nb_sample_up, DOWN_SAMPLING); - compSize = _audiocodec->codecEncode( micDataEncoded, micDataConverted, nbSample*sizeof(int16)); + compSize = _audiocodec->codecEncode (micDataEncoded, micDataConverted, nbSample*sizeof (int16)); } else { // no resampling required // int nbSamplesMax = _codecFrameSize; - compSize = _audiocodec->codecEncode( micDataEncoded, micData, nbSample*sizeof(int16)); + compSize = _audiocodec->codecEncode (micDataEncoded, micData, nbSample*sizeof (int16)); } @@ -375,42 +406,45 @@ AudioRtpRTX::processDataEncode() void -AudioRtpRTX::processDataDecode(unsigned char* spkrData, unsigned int size, int& countTime) +AudioRtpRTX::processDataDecode (unsigned char* spkrData, unsigned int size, int& countTime) { if (_audiocodec != NULL) { - // Return the size of data in bytes - int expandedSize = _audiocodec->codecDecode( spkrDataDecoded , spkrData , size); + // Return the size of data in bytes + int expandedSize = _audiocodec->codecDecode (spkrDataDecoded , spkrData , size); // buffer _receiveDataDecoded ----> short int or int16, coded on 2 bytes - int nbSample = expandedSize / sizeof(SFLDataFormat); + int nbSample = expandedSize / sizeof (SFLDataFormat); + + // test if resampling is required - // test if resampling is required if (_audiocodec->getClockRate() != _layerSampleRate) { // Do sample rate conversion int nb_sample_down = nbSample; - nbSample = reSampleData(spkrDataDecoded, spkrDataConverted, _codecSampleRate, nb_sample_down, UP_SAMPLING); + nbSample = reSampleData (spkrDataDecoded, spkrDataConverted, _codecSampleRate, nb_sample_down, UP_SAMPLING); // Store the number of samples for recording _nSamplesSpkr = nbSample; - // put data in audio layer, size in byte - _audiolayer->putMain (spkrDataConverted, nbSample * sizeof(SFLDataFormat)); + // put data in audio layer, size in byte + _audiolayer->putMain (spkrDataConverted, nbSample * sizeof (SFLDataFormat)); } else { // Stor the number of samples for recording _nSamplesSpkr = nbSample; - // put data in audio layer, size in byte - _audiolayer->putMain (spkrDataDecoded, nbSample * sizeof(SFLDataFormat)); + // put data in audio layer, size in byte + _audiolayer->putMain (spkrDataDecoded, nbSample * sizeof (SFLDataFormat)); } - // Notify (with a beep) an incoming call when there is already a call + // Notify (with a beep) an incoming call when there is already a call countTime += time->getSecond(); + if (Manager::instance().incomingCallWaiting() > 0) { countTime = countTime % 500; // more often... + if (countTime == 0) { Manager::instance().notificationIncomingCall(); } @@ -421,8 +455,8 @@ AudioRtpRTX::processDataDecode(unsigned char* spkrData, unsigned int size, int& } } - void -AudioRtpRTX::sendSessionFromMic(int timestamp) +void +AudioRtpRTX::sendSessionFromMic (int timestamp) { // STEP: // 1. get data from mic @@ -432,22 +466,32 @@ AudioRtpRTX::sendSessionFromMic(int timestamp) timestamp += time->getSecond(); // no call, so we do nothing - if (_ca==0) { _debug(" !ARTP: No call associated (mic)\n"); return; } + + if (_ca==0) { + _debug (" !ARTP: No call associated (mic)\n"); + return; + } // AudioLayer* audiolayer = Manager::instance().getAudioDriver(); - if (!_audiolayer) { _debug(" !ARTP: No audiolayer available for MIC\n"); return; } + if (!_audiolayer) { + _debug (" !ARTP: No audiolayer available for MIC\n"); + return; + } + + if (!_audiocodec) { + _debug (" !ARTP: No audiocodec available for MIC\n"); + return; + } - if (!_audiocodec) { _debug(" !ARTP: No audiocodec available for MIC\n"); return; } - int compSize = processDataEncode(); - _debug("compSize: %i ", compSize); + _debug ("compSize: %i ", compSize); // putData put the data on RTP queue, sendImmediate bypass this queue - _session->putData(timestamp, micDataEncoded, compSize); + _session->putData (timestamp, micDataEncoded, compSize); // _session->sendImmediate(timestamp, micDataEncoded, compSize); - - + + } @@ -455,51 +499,59 @@ void AudioRtpRTX::receiveSessionForSpkr (int& countTime) { - if (_ca == 0) { return; } + if (_ca == 0) { + return; + } - if (!_audiolayer) { _debug(" !ARTP: No audiolayer available for SPEAKER\n"); return; } + if (!_audiolayer) { + _debug (" !ARTP: No audiolayer available for SPEAKER\n"); + return; + } - if (!_audiocodec) { _debug(" !ARTP: No audiocodec available for SPEAKER\n"); return; } + if (!_audiocodec) { + _debug (" !ARTP: No audiocodec available for SPEAKER\n"); + return; + } const ost::AppDataUnit* adu = NULL; - - adu = _session->getData(_session->getFirstTimestamp()); + + adu = _session->getData (_session->getFirstTimestamp()); // _debug("payloadType: %i\n", adu->getType()); - + if (adu == NULL) { // _debug("No RTP audio stream\n"); return; } - unsigned char* spkrData = (unsigned char*)adu->getData(); // data in char + unsigned char* spkrData = (unsigned char*) adu->getData(); // data in char + unsigned int size = adu->getSize(); // size in char - processDataDecode(spkrData, size, countTime); - + processDataDecode (spkrData, size, countTime); + } -int -AudioRtpRTX::reSampleData(SFLDataFormat *input, SFLDataFormat *output, int sampleRate_codec, int nbSamples, int status) +int +AudioRtpRTX::reSampleData (SFLDataFormat *input, SFLDataFormat *output, int sampleRate_codec, int nbSamples, int status) { - if(status==UP_SAMPLING){ - return converter->upsampleData( input, output, sampleRate_codec , _layerSampleRate , nbSamples ); - } - else if(status==DOWN_SAMPLING){ - return converter->downsampleData( micData , micDataConverted , sampleRate_codec , _layerSampleRate , nbSamples ); - } - else + if (status==UP_SAMPLING) { + return converter->upsampleData (input, output, sampleRate_codec , _layerSampleRate , nbSamples); + } else if (status==DOWN_SAMPLING) { + return converter->downsampleData (micData , micDataConverted , sampleRate_codec , _layerSampleRate , nbSamples); + } else - return 0; + return 0; } void -AudioRtpRTX::run () { - +AudioRtpRTX::run () +{ + int sessionWaiting; initBuffers(); @@ -507,57 +559,60 @@ AudioRtpRTX::run () { setRtpSessionRemoteIp(); setRtpSessionMedia(); - int timestep = _codecFrameSize; + int timestep = _codecFrameSize; int timestamp = _session->getCurrentTimestamp(); // for mic int countTime = 0; // for receive - + int threadSleep = 0; + if (_codecSampleRate != 0) threadSleep = (_codecFrameSize * 1000) / _codecSampleRate; else threadSleep = _layerFrameSize; - TimerPort::setTimer(threadSleep); + TimerPort::setTimer (threadSleep); _audiolayer->startStream(); _session->startRunning(); - _debug("- ARTP Action: Start call %s\n",_ca->getCallId().c_str()); + _debug ("- ARTP Action: Start call %s\n",_ca->getCallId().c_str()); + while (!testCancel()) { // Send session sessionWaiting = _session->isWaiting(); - sendSessionFromMic(timestamp); + sendSessionFromMic (timestamp); timestamp += timestep; - // timestamp = _session->getCurrentTimestamp(); + // timestamp = _session->getCurrentTimestamp(); // Recv session - receiveSessionForSpkr(countTime); - + receiveSessionForSpkr (countTime); + // Let's wait for the next transmit cycle - if(sessionWaiting == 1){ + + if (sessionWaiting == 1) { // Record mic and speaker during conversation - _ca->recAudio.recData(spkrDataConverted,micData,_nSamplesSpkr,_nSamplesMic); - } - else { + _ca->recAudio.recData (spkrDataConverted,micData,_nSamplesSpkr,_nSamplesMic); + } else { // Record mic only while leaving a message - _ca->recAudio.recData(micData,_nSamplesMic); + _ca->recAudio.recData (micData,_nSamplesMic); } // Let's wait for the next transmit cycle - Thread::sleep(TimerPort::getTimer()); + Thread::sleep (TimerPort::getTimer()); + // TimerPort::incTimer(20); // 'frameSize' ms - TimerPort::incTimer(threadSleep); + TimerPort::incTimer (threadSleep); } - + // _audiolayer->stopStream(); - _debug("- ARTP Action: Stop call %s\n",_ca->getCallId().c_str()); - - + _debug ("- ARTP Action: Stop call %s\n",_ca->getCallId().c_str()); + + } diff --git a/sflphone-common/src/audio/audiostream.cpp b/sflphone-common/src/audio/audiostream.cpp index cbe0008bfe..8054c1e10e 100644 --- a/sflphone-common/src/audio/audiostream.cpp +++ b/sflphone-common/src/audio/audiostream.cpp @@ -6,12 +6,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -23,143 +23,149 @@ static pa_channel_map channel_map ; -AudioStream::AudioStream( pa_context* context, int type, std::string desc, double vol UNUSED ) - : _audiostream(NULL), _streamType(type), _streamDescription(desc), flag(PA_STREAM_AUTO_TIMING_UPDATE), sample_spec(), _volume() -{ - sample_spec.format = PA_SAMPLE_S16LE; - sample_spec.rate = 44100; - sample_spec.channels = 1; - channel_map.channels = 1; - pa_cvolume_set( &_volume , 1 , PA_VOLUME_NORM ) ; // * vol / 100 ; - - _context = context; +AudioStream::AudioStream (pa_context* context, int type, std::string desc, double vol UNUSED) + : _audiostream (NULL), _streamType (type), _streamDescription (desc), flag (PA_STREAM_AUTO_TIMING_UPDATE), sample_spec(), _volume() +{ + sample_spec.format = PA_SAMPLE_S16LE; + sample_spec.rate = 44100; + sample_spec.channels = 1; + channel_map.channels = 1; + pa_cvolume_set (&_volume , 1 , PA_VOLUME_NORM) ; // * vol / 100 ; + + _context = context; - // connectStream(); -} + // connectStream(); +} AudioStream::~AudioStream() -{ - disconnectStream(); +{ + disconnectStream(); } bool AudioStream::connectStream() { - ost::MutexLock guard(_mutex); + ost::MutexLock guard (_mutex); - if(!_audiostream) - _audiostream = createStream( _context ); + if (!_audiostream) + _audiostream = createStream (_context); - return true; + return true; } bool -AudioStream::disconnectStream( void ) -{ - ost::MutexLock guard(_mutex); +AudioStream::disconnectStream (void) +{ + ost::MutexLock guard (_mutex); - _debug("Destroy audio streams\n"); - pa_stream_disconnect( _audiostream ); - pa_stream_unref( _audiostream ); + _debug ("Destroy audio streams\n"); + pa_stream_disconnect (_audiostream); + pa_stream_unref (_audiostream); - _audiostream = NULL; + _audiostream = NULL; - return true; -} + return true; +} -void -AudioStream::stream_state_callback( pa_stream* s, void* user_data UNUSED ) +void +AudioStream::stream_state_callback (pa_stream* s, void* user_data UNUSED) { - - - _debug("AudioStream::stream_state_callback :: The state of the stream changed\n"); - assert(s); - switch(pa_stream_get_state(s)){ - case PA_STREAM_CREATING: - _debug("Stream is creating...\n"); - break; - case PA_STREAM_TERMINATED: - _debug("Stream is terminating...\n" ); - PulseLayer::streamState++; - break; - case PA_STREAM_READY: - - _debug("Stream successfully created, connected to %s\n", pa_stream_get_device_name( s )); - // pa_stream_cork( s, 0, NULL, NULL); - break; - case PA_STREAM_UNCONNECTED: - _debug("Stream unconnected\n"); - break; - case PA_STREAM_FAILED: - default: - _debug("Stream error - Sink/Source doesn't exists: %s\n" , pa_strerror(pa_context_errno(pa_stream_get_context(s)))); - exit(0); - break; - } + + + _debug ("AudioStream::stream_state_callback :: The state of the stream changed\n"); + assert (s); + + switch (pa_stream_get_state (s)) { + + case PA_STREAM_CREATING: + _debug ("Stream is creating...\n"); + break; + + case PA_STREAM_TERMINATED: + _debug ("Stream is terminating...\n"); + PulseLayer::streamState++; + break; + + case PA_STREAM_READY: + + _debug ("Stream successfully created, connected to %s\n", pa_stream_get_device_name (s)); + // pa_stream_cork( s, 0, NULL, NULL); + break; + + case PA_STREAM_UNCONNECTED: + _debug ("Stream unconnected\n"); + break; + + case PA_STREAM_FAILED: + + default: + _debug ("Stream error - Sink/Source doesn't exists: %s\n" , pa_strerror (pa_context_errno (pa_stream_get_context (s)))); + exit (0); + break; + } } -pa_stream_state_t -AudioStream::getStreamState(void) { +pa_stream_state_t +AudioStream::getStreamState (void) +{ - ost::MutexLock guard(_mutex); - return pa_stream_get_state(_audiostream); + ost::MutexLock guard (_mutex); + return pa_stream_get_state (_audiostream); } - pa_stream* -AudioStream::createStream( pa_context* c ) +pa_stream* +AudioStream::createStream (pa_context* c) { - ost::MutexLock guard(_mutex); - - pa_stream* s; - //pa_cvolume cv; - - assert(pa_sample_spec_valid(&sample_spec)); - assert(pa_channel_map_valid(&channel_map)); - - pa_buffer_attr* attributes = (pa_buffer_attr*)malloc( sizeof(pa_buffer_attr) ); - if( !( s = pa_stream_new( c, _streamDescription.c_str() , &sample_spec, &channel_map ) ) ) - _debug("%s: pa_stream_new() failed : %s\n" , _streamDescription.c_str(), pa_strerror( pa_context_errno( c))); - - assert( s ); - - if( _streamType == PLAYBACK_STREAM ){ - attributes->maxlength = 60000; - attributes->tlength = 4096; - attributes->prebuf = 4096; - attributes->minreq = 940; - attributes->fragsize = 4096; - // pa_stream_connect_playback( s , NULL , attributes, PA_STREAM_INTERPOLATE_TIMING, &_volume, NULL); - pa_stream_connect_playback( s , NULL , attributes, PA_STREAM_START_CORKED, &_volume, NULL); - } - else if( _streamType == CAPTURE_STREAM ){ - - // attributes->maxlength = 66500; - // attributes->fragsize = (uint32_t)-1; - - attributes->maxlength = 60000; - attributes->tlength = 4096; - attributes->prebuf = 4096; - attributes->minreq = 940; - attributes->fragsize = 4096; - - pa_stream_connect_record( s , NULL , attributes , PA_STREAM_START_CORKED ); - // pa_stream_connect_record( s , NULL , attributes , PA_STREAM_INTERPOLATE_TIMING ); - } - else if( _streamType == UPLOAD_STREAM ){ - pa_stream_connect_upload( s , 1024 ); - } - else{ - _debug( "Stream type unknown \n"); - } - - pa_stream_set_state_callback( s , stream_state_callback, NULL); - - free(attributes); - - return s; + ost::MutexLock guard (_mutex); + + pa_stream* s; + //pa_cvolume cv; + + assert (pa_sample_spec_valid (&sample_spec)); + assert (pa_channel_map_valid (&channel_map)); + + pa_buffer_attr* attributes = (pa_buffer_attr*) malloc (sizeof (pa_buffer_attr)); + + if (! (s = pa_stream_new (c, _streamDescription.c_str() , &sample_spec, &channel_map))) + _debug ("%s: pa_stream_new() failed : %s\n" , _streamDescription.c_str(), pa_strerror (pa_context_errno (c))); + + assert (s); + + if (_streamType == PLAYBACK_STREAM) { + attributes->maxlength = 60000; + attributes->tlength = 4096; + attributes->prebuf = 4096; + attributes->minreq = 940; + attributes->fragsize = 4096; + // pa_stream_connect_playback( s , NULL , attributes, PA_STREAM_INTERPOLATE_TIMING, &_volume, NULL); + pa_stream_connect_playback (s , NULL , attributes, PA_STREAM_START_CORKED, &_volume, NULL); + } else if (_streamType == CAPTURE_STREAM) { + + // attributes->maxlength = 66500; + // attributes->fragsize = (uint32_t)-1; + + attributes->maxlength = 60000; + attributes->tlength = 4096; + attributes->prebuf = 4096; + attributes->minreq = 940; + attributes->fragsize = 4096; + + pa_stream_connect_record (s , NULL , attributes , PA_STREAM_START_CORKED); + // pa_stream_connect_record( s , NULL , attributes , PA_STREAM_INTERPOLATE_TIMING ); + } else if (_streamType == UPLOAD_STREAM) { + pa_stream_connect_upload (s , 1024); + } else { + _debug ("Stream type unknown \n"); + } + + pa_stream_set_state_callback (s , stream_state_callback, NULL); + + free (attributes); + + return s; } diff --git a/sflphone-common/src/audio/codecDescriptor.cpp b/sflphone-common/src/audio/codecDescriptor.cpp index 1b927cfa16..d0fa1da927 100644 --- a/sflphone-common/src/audio/codecDescriptor.cpp +++ b/sflphone-common/src/audio/codecDescriptor.cpp @@ -3,17 +3,17 @@ * Author: Yan Morin <yan.morin@savoirfairelinux.com> * Author: Laurielle Lea <laurielle.lea@savoirfairelinux.com> * Author: Emmanuel Milou <emmanuel.milou@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 * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -24,7 +24,7 @@ #include "codecDescriptor.h" -CodecDescriptor::CodecDescriptor() : _CodecsMap(), _codecOrder(), _Cache(), _nbCodecs(), _CodecInMemory() +CodecDescriptor::CodecDescriptor() : _CodecsMap(), _codecOrder(), _Cache(), _nbCodecs(), _CodecInMemory() { } @@ -32,304 +32,337 @@ CodecDescriptor::~CodecDescriptor() { } - void -CodecDescriptor::deleteHandlePointer( void ) +void +CodecDescriptor::deleteHandlePointer (void) { - int i; - for( i = 0 ; (unsigned int)i < _CodecInMemory.size() ; i++) - { - unloadCodec( _CodecInMemory[i] ); - } + int i; + + for (i = 0 ; (unsigned int) i < _CodecInMemory.size() ; i++) { + unloadCodec (_CodecInMemory[i]); + } } - void +void CodecDescriptor::init() { - std::vector<AudioCodec*> CodecDynamicList = scanCodecDirectory(); - _nbCodecs = CodecDynamicList.size(); - if( _nbCodecs <= 0 ){ - _debug(" Error - No codecs available in directory %s\n" , CODECS_DIR); - } - - int i; - for( i = 0 ; i < _nbCodecs ; i++ ) { - _CodecsMap[(AudioCodecType)CodecDynamicList[i]->getPayload()] = CodecDynamicList[i]; - _debug("%s\n" , CodecDynamicList[i]->getCodecName().c_str()); - } + std::vector<AudioCodec*> CodecDynamicList = scanCodecDirectory(); + _nbCodecs = CodecDynamicList.size(); + + if (_nbCodecs <= 0) { + _debug (" Error - No codecs available in directory %s\n" , CODECS_DIR); + } + + int i; + + for (i = 0 ; i < _nbCodecs ; i++) { + _CodecsMap[ (AudioCodecType) CodecDynamicList[i]->getPayload() ] = CodecDynamicList[i]; + _debug ("%s\n" , CodecDynamicList[i]->getCodecName().c_str()); + } } - void +void CodecDescriptor::setDefaultOrder() { - _codecOrder.clear(); - CodecsMap::iterator iter = _CodecsMap.begin(); - while( iter != _CodecsMap.end()) - { - _codecOrder.push_back(iter->first); - iter->second->setState( true ); - iter ++ ; - } + _codecOrder.clear(); + CodecsMap::iterator iter = _CodecsMap.begin(); + + while (iter != _CodecsMap.end()) { + _codecOrder.push_back (iter->first); + iter->second->setState (true); + iter ++ ; + } } - std::string -CodecDescriptor::getCodecName(AudioCodecType payload) +std::string +CodecDescriptor::getCodecName (AudioCodecType payload) { - std::string resNull = ""; - CodecsMap::iterator iter = _CodecsMap.find(payload); - if (iter!=_CodecsMap.end()) { - return (iter->second->getCodecName()); - } - return resNull; + std::string resNull = ""; + CodecsMap::iterator iter = _CodecsMap.find (payload); + + if (iter!=_CodecsMap.end()) { + return (iter->second->getCodecName()); + } + + return resNull; } - AudioCodec* -CodecDescriptor::getCodec(AudioCodecType payload) +AudioCodec* +CodecDescriptor::getCodec (AudioCodecType payload) { - CodecsMap::iterator iter = _CodecsMap.find(payload); - if (iter!=_CodecsMap.end()) { - return (iter->second); - } - return NULL; + CodecsMap::iterator iter = _CodecsMap.find (payload); + + if (iter!=_CodecsMap.end()) { + return (iter->second); + } + + return NULL; } - bool -CodecDescriptor::isActive(AudioCodecType payload) +bool +CodecDescriptor::isActive (AudioCodecType payload) { - int i; - for(i=0 ; (unsigned int)i < _codecOrder.size() ; i++) - { - if(_codecOrder[i] == payload) - return true; - } - return false; + int i; + + for (i=0 ; (unsigned int) i < _codecOrder.size() ; i++) { + if (_codecOrder[i] == payload) + return true; + } + + return false; } - void -CodecDescriptor::removeCodec(AudioCodecType payload UNUSED) +void +CodecDescriptor::removeCodec (AudioCodecType payload UNUSED) { } - void -CodecDescriptor::addCodec(AudioCodecType payload UNUSED) +void +CodecDescriptor::addCodec (AudioCodecType payload UNUSED) { } - double -CodecDescriptor::getBitRate(AudioCodecType payload) +double +CodecDescriptor::getBitRate (AudioCodecType payload) { - CodecsMap::iterator iter = _CodecsMap.find(payload); - if (iter!=_CodecsMap.end()) - return (iter->second->getBitRate()); - else - return 0.0; + CodecsMap::iterator iter = _CodecsMap.find (payload); + + if (iter!=_CodecsMap.end()) + return (iter->second->getBitRate()); + else + return 0.0; } - double -CodecDescriptor::getBandwidthPerCall(AudioCodecType payload) +double +CodecDescriptor::getBandwidthPerCall (AudioCodecType payload) { - CodecsMap::iterator iter = _CodecsMap.find(payload); - if (iter!=_CodecsMap.end()) - return (iter->second->getBandwidth()); - else - return 0.0; + CodecsMap::iterator iter = _CodecsMap.find (payload); + + if (iter!=_CodecsMap.end()) + return (iter->second->getBandwidth()); + else + return 0.0; } - int -CodecDescriptor::getSampleRate(AudioCodecType payload) +int +CodecDescriptor::getSampleRate (AudioCodecType payload) { - CodecsMap::iterator iter = _CodecsMap.find(payload); - if (iter!=_CodecsMap.end()) - return (iter->second->getClockRate()); - else - return 0; + CodecsMap::iterator iter = _CodecsMap.find (payload); + + if (iter!=_CodecsMap.end()) + return (iter->second->getClockRate()); + else + return 0; } - int -CodecDescriptor::getChannel(AudioCodecType payload) +int +CodecDescriptor::getChannel (AudioCodecType payload) { - CodecsMap::iterator iter = _CodecsMap.find(payload); - if (iter!=_CodecsMap.end()) - return (iter->second->getChannel()); - else - return 0; + CodecsMap::iterator iter = _CodecsMap.find (payload); + + if (iter!=_CodecsMap.end()) + return (iter->second->getChannel()); + else + return 0; } - void -CodecDescriptor::saveActiveCodecs(const std::vector<std::string>& list) +void +CodecDescriptor::saveActiveCodecs (const std::vector<std::string>& list) { - _codecOrder.clear(); - // list contains the ordered payload of active codecs picked by the user - // we used the CodecOrder vector to save the order. - int i=0; - int payload; - size_t size = list.size(); - while( (unsigned int)i < size ) - { - payload = std::atoi(list[i].data()); - if( isCodecLoaded( payload ) ) { - _codecOrder.push_back((AudioCodecType)payload); - _CodecsMap.find((AudioCodecType)payload)->second->setState( true ); + _codecOrder.clear(); + // list contains the ordered payload of active codecs picked by the user + // we used the CodecOrder vector to save the order. + int i=0; + int payload; + size_t size = list.size(); + + while ( (unsigned int) i < size) { + payload = std::atoi (list[i].data()); + + if (isCodecLoaded (payload)) { + _codecOrder.push_back ( (AudioCodecType) payload); + _CodecsMap.find ( (AudioCodecType) payload)->second->setState (true); + } + + i++; } - i++; - } } - std::vector<AudioCodec*> -CodecDescriptor::scanCodecDirectory( void ) +std::vector<AudioCodec*> +CodecDescriptor::scanCodecDirectory (void) { - std::vector<AudioCodec*> codecs; - std::string tmp; - int i; - - std::string libDir = std::string(CODECS_DIR).append("/"); - std::string homeDir = std::string(HOMEDIR) + DIR_SEPARATOR_STR + "." + PROGDIR + "/"; - std::vector<std::string> dirToScan; - dirToScan.push_back(homeDir); - dirToScan.push_back(libDir); - - for( i = 0 ; (unsigned int)i < dirToScan.size() ; i++ ) - { - std::string dirStr = dirToScan[i]; - _debug("Scanning %s to find audio codecs....\n", dirStr.c_str()); - DIR *dir = opendir( dirStr.c_str() ); - AudioCodec* audioCodec; - if( dir ){ - dirent *dirStruct; - while( (dirStruct = readdir( dir )) ) { - tmp = dirStruct -> d_name ; - if( tmp == CURRENT_DIR || tmp == PARENT_DIR){} - else{ - if( seemsValid( tmp ) && !alreadyInCache( tmp )) - { - //_debug("Codec : %s\n", tmp.c_str()); - _Cache.push_back( tmp ); - audioCodec = loadCodec( dirStr.append(tmp) ); - codecs.push_back( audioCodec ); - dirStr = dirToScan[i]; - } - } - } + std::vector<AudioCodec*> codecs; + std::string tmp; + int i; + + std::string libDir = std::string (CODECS_DIR).append ("/"); + std::string homeDir = std::string (HOMEDIR) + DIR_SEPARATOR_STR + "." + PROGDIR + "/"; + std::vector<std::string> dirToScan; + dirToScan.push_back (homeDir); + dirToScan.push_back (libDir); + + for (i = 0 ; (unsigned int) i < dirToScan.size() ; i++) { + std::string dirStr = dirToScan[i]; + _debug ("Scanning %s to find audio codecs....\n", dirStr.c_str()); + DIR *dir = opendir (dirStr.c_str()); + AudioCodec* audioCodec; + + if (dir) { + dirent *dirStruct; + + while ( (dirStruct = readdir (dir))) { + tmp = dirStruct -> d_name ; + if (tmp == CURRENT_DIR || tmp == PARENT_DIR) {} else { + if (seemsValid (tmp) && !alreadyInCache (tmp)) { + //_debug("Codec : %s\n", tmp.c_str()); + _Cache.push_back (tmp); + audioCodec = loadCodec (dirStr.append (tmp)); + codecs.push_back (audioCodec); + dirStr = dirToScan[i]; + } + } + } + } + + closedir (dir); } - closedir( dir ); - } - return codecs; + + return codecs; } - AudioCodec* -CodecDescriptor::loadCodec( std::string path ) +AudioCodec* +CodecDescriptor::loadCodec (std::string path) { - //_debug("Load path %s\n", path.c_str()); - CodecHandlePointer p; - using std::cerr; - void * codecHandle = dlopen( path.c_str() , RTLD_LAZY ); - if( !codecHandle ) - cerr << dlerror() << '\n'; - dlerror(); - create_t* createCodec = (create_t*)dlsym( codecHandle , "create" ); - if( dlerror() ) - cerr << dlerror() << '\n'; - AudioCodec* a = createCodec(); - p = CodecHandlePointer( a, codecHandle ); - _CodecInMemory.push_back(p); - - return a; + //_debug("Load path %s\n", path.c_str()); + CodecHandlePointer p; + using std::cerr; + void * codecHandle = dlopen (path.c_str() , RTLD_LAZY); + + if (!codecHandle) + cerr << dlerror() << '\n'; + + dlerror(); + + create_t* createCodec = (create_t*) dlsym (codecHandle , "create"); + + if (dlerror()) + cerr << dlerror() << '\n'; + + AudioCodec* a = createCodec(); + + p = CodecHandlePointer (a, codecHandle); + + _CodecInMemory.push_back (p); + + return a; } - void -CodecDescriptor::unloadCodec( CodecHandlePointer p ) +void +CodecDescriptor::unloadCodec (CodecHandlePointer p) { - // _debug("Unload codec %s\n", p.first->getCodecName().c_str()); - using std::cerr; - destroy_t* destroyCodec = (destroy_t*)dlsym( p.second , "destroy"); - if(dlerror()) - cerr << dlerror() << '\n'; - destroyCodec(p.first); - dlclose(p.second); + // _debug("Unload codec %s\n", p.first->getCodecName().c_str()); + using std::cerr; + destroy_t* destroyCodec = (destroy_t*) dlsym (p.second , "destroy"); + + if (dlerror()) + cerr << dlerror() << '\n'; + + destroyCodec (p.first); + + dlclose (p.second); } - AudioCodec* -CodecDescriptor::getFirstCodecAvailable( void ) +AudioCodec* +CodecDescriptor::getFirstCodecAvailable (void) { - CodecsMap::iterator iter = _CodecsMap.begin(); - if( iter != _CodecsMap.end()) - return iter->second; - else - return NULL; + CodecsMap::iterator iter = _CodecsMap.begin(); + + if (iter != _CodecsMap.end()) + return iter->second; + else + return NULL; } - bool -CodecDescriptor::seemsValid( std::string lib) +bool +CodecDescriptor::seemsValid (std::string lib) { - // The name of the shared library seems valid <==> it looks like libcodec_xxx.so - // We check this - std::string begin = SFL_CODEC_VALID_PREFIX; - std::string end = SFL_CODEC_VALID_EXTEN; - - // First : check the length of the file name. - // If it is shorter than begin.length() + end.length() , not a SFL shared library - if( lib.length() <= begin.length() + end.length() ) - return false; + // The name of the shared library seems valid <==> it looks like libcodec_xxx.so + // We check this + std::string begin = SFL_CODEC_VALID_PREFIX; + std::string end = SFL_CODEC_VALID_EXTEN; - // Second: check the extension of the file name. - // If it is different than SFL_CODEC_VALID_EXTEN , not a SFL shared library - if( lib.substr( lib.length() - end.length() , lib.length()) != end ) - return false; + // First : check the length of the file name. + // If it is shorter than begin.length() + end.length() , not a SFL shared library + + if (lib.length() <= begin.length() + end.length()) + return false; + + // Second: check the extension of the file name. + // If it is different than SFL_CODEC_VALID_EXTEN , not a SFL shared library + if (lib.substr (lib.length() - end.length() , lib.length()) != end) + return false; #ifdef HAVE_SPEEX_CODEC - // Nothing special + // Nothing special #else - if( lib.substr(begin.length() , lib.length() - begin.length() - end.length()) == SPEEX_STRING_DESCRIPTION) - return false; + if (lib.substr (begin.length() , lib.length() - begin.length() - end.length()) == SPEEX_STRING_DESCRIPTION) + return false; + #endif #ifdef HAVE_GSM_CODEC - // Nothing special + // Nothing special #else - if( lib.substr(begin.length() , lib.length() - begin.length() - end.length()) == GSM_STRING_DESCRIPTION ) - return false; + if (lib.substr (begin.length() , lib.length() - begin.length() - end.length()) == GSM_STRING_DESCRIPTION) + return false; + #endif #ifdef BUILD_ILBC - // Nothing special + // Nothing special #else - if( lib.substr(begin.length() , lib.length() - begin.length() - end.length()) == ILBC_STRING_DESCRIPTION ) - return false; + if (lib.substr (begin.length() , lib.length() - begin.length() - end.length()) == ILBC_STRING_DESCRIPTION) + return false; + #endif - if(lib.substr(0, begin.length()) == begin) - if(lib.substr(lib.length() - end.length() , end.length() ) == end) - return true; + if (lib.substr (0, begin.length()) == begin) + if (lib.substr (lib.length() - end.length() , end.length()) == end) + return true; + else + return false; else - return false; - else - return false; + return false; } - bool -CodecDescriptor::alreadyInCache( std::string lib ) +bool +CodecDescriptor::alreadyInCache (std::string lib) { - int i; - for( i = 0 ; (unsigned int)i < _Cache.size() ; i++ ) - { - if( _Cache[i] == lib ){ - return true;} - } - return false; + int i; + + for (i = 0 ; (unsigned int) i < _Cache.size() ; i++) { + if (_Cache[i] == lib) { + return true; + } + } + + return false; } bool -CodecDescriptor::isCodecLoaded( int payload ) +CodecDescriptor::isCodecLoaded (int payload) { - CodecsMap::iterator iter = _CodecsMap.begin(); - while( iter != _CodecsMap.end()) - { - if( iter -> first == payload) - return true; - iter++; - } - return false; + CodecsMap::iterator iter = _CodecsMap.begin(); + + while (iter != _CodecsMap.end()) { + if (iter -> first == payload) + return true; + + iter++; + } + + return false; } diff --git a/sflphone-common/src/audio/codecs/alaw.cpp b/sflphone-common/src/audio/codecs/alaw.cpp index c0e0c02c94..e8a3928a72 100644 --- a/sflphone-common/src/audio/codecs/alaw.cpp +++ b/sflphone-common/src/audio/codecs/alaw.cpp @@ -2,7 +2,7 @@ * Copyright (C) 2004-2005 Savoir-Faire Linux inc. * Author: Yan Morin <yan.morin@savoirfairelinux.com> * Author: Laurielle Lea <laurielle.lea@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 @@ -12,7 +12,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. @@ -21,113 +21,115 @@ #include "../common.h" #include "audiocodec.h" -class Alaw : public AudioCodec { -public: - // 8 PCMA A 8000 1 [RFC3551] - Alaw(int payload=0) - : AudioCodec(payload, "PCMA") - { - _clockRate = 8000; - _frameSize = 160; // samples, 20 ms at 8kHz - _channel = 1; - _bitrate = 64; - _bandwidth = 80; - } - - virtual ~Alaw(){} - virtual int codecDecode (short *dst, unsigned char *src, unsigned int size) - { - // _debug("Decoded by alaw \n"); - int16* end = dst+size; - while(dst<end) - *dst++ = ALawDecode(*src++); - return size<<1; - } - - virtual int codecEncode (unsigned char *dst, short *src, unsigned int size) - { - // _debug("Encoded by alaw \n"); - size >>= 1; - uint8* end = dst+size; - while(dst<end) - *dst++ = ALawEncode(*src++); - return size; - } - - - - int ALawDecode(uint8 alaw) - { - alaw ^= 0x55; // A-law has alternate bits inverted for transmission - uint sign = alaw&0x80; - int linear = alaw&0x1f; - linear <<= 4; - linear += 8; // Add a 'half' bit (0x08) to place PCM value in middle of range - - alaw &= 0x7f; - if(alaw>=0x20) - { - linear |= 0x100; // Put in MSB - uint shift = (alaw>>4)-1; - linear <<= shift; - } - - if(!sign) - return -linear; - else - return linear; - } - - - uint8 ALawEncode (int16 pcm16) - { - int p = pcm16; - uint a; // u-law value we are forming - - if(p<0) - { - p = ~p; - a = 0x00; // sign = 0 - } - else - { - //+ve value - a = 0x80; //sign = 1 - } - //calculate segment and interval numbers - p >>= 4; - if(p>=0x20) - { - if(p>=0x100) - { - p >>= 4; - a += 0x40; - } - if(p>=0x40) - { - p >>= 2; - a += 0x20; - } - if(p>=0x20) - { - p >>= 1; - a += 0x10; - } +class Alaw : public AudioCodec +{ + + public: + // 8 PCMA A 8000 1 [RFC3551] + Alaw (int payload=0) + : AudioCodec (payload, "PCMA") { + _clockRate = 8000; + _frameSize = 160; // samples, 20 ms at 8kHz + _channel = 1; + _bitrate = 64; + _bandwidth = 80; + } + + virtual ~Alaw() {} + + virtual int codecDecode (short *dst, unsigned char *src, unsigned int size) { + // _debug("Decoded by alaw \n"); + int16* end = dst+size; + + while (dst<end) + *dst++ = ALawDecode (*src++); + + return size<<1; + } + + virtual int codecEncode (unsigned char *dst, short *src, unsigned int size) { + // _debug("Encoded by alaw \n"); + size >>= 1; + uint8* end = dst+size; + + while (dst<end) + *dst++ = ALawEncode (*src++); + + return size; + } + + + + int ALawDecode (uint8 alaw) { + alaw ^= 0x55; // A-law has alternate bits inverted for transmission + uint sign = alaw&0x80; + int linear = alaw&0x1f; + linear <<= 4; + linear += 8; // Add a 'half' bit (0x08) to place PCM value in middle of range + + alaw &= 0x7f; + + if (alaw>=0x20) { + linear |= 0x100; // Put in MSB + uint shift = (alaw>>4)-1; + linear <<= shift; + } + + if (!sign) + return -linear; + else + return linear; + } + + + uint8 ALawEncode (int16 pcm16) { + int p = pcm16; + uint a; // u-law value we are forming + + if (p<0) { + p = ~p; + a = 0x00; // sign = 0 + } else { + //+ve value + a = 0x80; //sign = 1 + } + + //calculate segment and interval numbers + p >>= 4; + + if (p>=0x20) { + if (p>=0x100) { + p >>= 4; + a += 0x40; + } + + if (p>=0x40) { + p >>= 2; + a += 0x20; } - // a&0x70 now holds segment value and 'p' the interval number - a += p; // a now equal to encoded A-law value - return a^0x55; // A-law has alternate bits inverted for transmission - } + if (p>=0x20) { + p >>= 1; + a += 0x10; + } + } + + // a&0x70 now holds segment value and 'p' the interval number + a += p; // a now equal to encoded A-law value + + return a^0x55; // A-law has alternate bits inverted for transmission + } }; // the class factories -extern "C" AudioCodec* create() { - return new Alaw(8); +extern "C" AudioCodec* create() +{ + return new Alaw (8); } -extern "C" void destroy(AudioCodec* a) { +extern "C" void destroy (AudioCodec* a) +{ delete a; } diff --git a/sflphone-common/src/audio/codecs/celtcodec.cpp b/sflphone-common/src/audio/codecs/celtcodec.cpp index 574b11394f..93cf4470d4 100644 --- a/sflphone-common/src/audio/codecs/celtcodec.cpp +++ b/sflphone-common/src/audio/codecs/celtcodec.cpp @@ -22,31 +22,31 @@ #include <celt/celt.h> -class Celt : public AudioCodec{ +class Celt : public AudioCodec +{ + public: - Celt(int payload=0) - : AudioCodec(payload, "celt") - { - _clockRate = 44100; - _frameSize = 512; // fixed frameSize, TODO: support variable size from 64 to 512 - _channel = 1; - _bitrate = 0; - _bandwidth = 0; - initCelt(); - } - - Celt( const Celt& ); - Celt& operator=(const Celt&); + Celt (int payload=0) + : AudioCodec (payload, "celt") { + _clockRate = 44100; + _frameSize = 512; // fixed frameSize, TODO: support variable size from 64 to 512 + _channel = 1; + _bitrate = 0; + _bandwidth = 0; + initCelt(); + } + + Celt (const Celt&); + Celt& operator= (const Celt&); void initCelt() { - printf("init celt"); - - mode = celt_mode_create(_clockRate, _channel, _frameSize, NULL); + printf ("init celt"); + + mode = celt_mode_create (_clockRate, _channel, _frameSize, NULL); // celt_mode_info(mode, CELT_GET_LOOKAHEAD, &skip); - if (mode == NULL) - { - printf("failed to create a mode\n"); + if (mode == NULL) { + printf ("failed to create a mode\n"); } // bytes_per_packet = 1024; @@ -58,35 +58,33 @@ class Celt : public AudioCodec{ // celt_mode_info(mode, CELT_GET_FRAME_SIZE, &frame_size); // celt_mode_info(mode, CELT_GET_NB_CHANNELS, &_channel); - enc = celt_encoder_create(mode); - dec = celt_decoder_create(mode); + enc = celt_encoder_create (mode); + + dec = celt_decoder_create (mode); + + celt_encoder_ctl (enc,CELT_SET_COMPLEXITY (10)); - celt_encoder_ctl(enc,CELT_SET_COMPLEXITY(10)); - } - ~Celt() - { + ~Celt() { terminateCelt(); } void terminateCelt() { - - celt_encoder_destroy(enc); - celt_decoder_destroy(dec); + + celt_encoder_destroy (enc); + celt_decoder_destroy (dec); } - virtual int codecDecode (short *dst, unsigned char *src, unsigned int size) - { + virtual int codecDecode (short *dst, unsigned char *src, unsigned int size) { int err = 0; - err = celt_decode(dec, src, size, (celt_int16_t*)dst); - return _frameSize * sizeof(celt_int16_t); + err = celt_decode (dec, src, size, (celt_int16_t*) dst); + return _frameSize * sizeof (celt_int16_t); } - virtual int codecEncode (unsigned char *dst, short *src, unsigned int size) - { + virtual int codecEncode (unsigned char *dst, short *src, unsigned int size) { int len = 0; - len = celt_encode(enc, (celt_int16_t *)src, (celt_int16_t *)src, dst, 512); + len = celt_encode (enc, (celt_int16_t *) src, (celt_int16_t *) src, dst, 512); // returns the number of bytes writen return len; } @@ -94,20 +92,22 @@ class Celt : public AudioCodec{ private: CELTMode *mode; - + CELTEncoder *enc; CELTDecoder *dec; celt_int32_t _celt_frame_size; celt_int32_t skip; - + }; // the class factories -extern "C" AudioCodec* create() { - return new Celt(115); +extern "C" AudioCodec* create() +{ + return new Celt (115); } -extern "C" void destroy(AudioCodec* a) { +extern "C" void destroy (AudioCodec* a) +{ delete a; } diff --git a/sflphone-common/src/audio/codecs/g722.cpp b/sflphone-common/src/audio/codecs/g722.cpp index 8608d310c9..45db24c5df 100644 --- a/sflphone-common/src/audio/codecs/g722.cpp +++ b/sflphone-common/src/audio/codecs/g722.cpp @@ -8,12 +8,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -32,99 +32,99 @@ #define FALSE 0 -class G722 : public AudioCodec { -public: +class G722 : public AudioCodec +{ + + public: - G722(int payload=9) - : AudioCodec(payload, "G722") - { - _clockRate = 16000; - _frameSize = 320; // samples, 10 ms at 16kHz - _channel = 1; - _bitrate = 64; - _bandwidth = 80; + G722 (int payload=9) + : AudioCodec (payload, "G722") { + _clockRate = 16000; + _frameSize = 320; // samples, 10 ms at 16kHz + _channel = 1; + _bitrate = 64; + _bandwidth = 80; - decode_s = new g722_decode_state_t; - encode_s = new g722_encode_state_t; + decode_s = new g722_decode_state_t; + encode_s = new g722_encode_state_t; - g722_decode_init(64000, 0); - g722_encode_init(64000, 0); + g722_decode_init (64000, 0); + g722_encode_init (64000, 0); - } + } - virtual int codecDecode (short *dst, unsigned char *src, unsigned int size) { + virtual int codecDecode (short *dst, unsigned char *src, unsigned int size) { - int in_byte = size; - int out_samples; + int in_byte = size; + int out_samples; - out_samples = g722_decode((int16_t*) dst, (const uint8_t*) src, in_byte); + out_samples = g722_decode ( (int16_t*) dst, (const uint8_t*) src, in_byte); return out_samples * 2; - } + } + + virtual int codecEncode (unsigned char *dst, short *src, unsigned int size) { - virtual int codecEncode (unsigned char *dst, short *src, unsigned int size) { + // 2 bytes per sample (int16) + int in_samples = size / 2; + int out_bytes; - // 2 bytes per sample (int16) - int in_samples = size / 2; - int out_bytes; + out_bytes = g722_encode ( (uint8_t*) dst, (const int16_t*) src, in_samples); - out_bytes = g722_encode((uint8_t*) dst, (const int16_t*) src, in_samples); + return out_bytes; + } - return out_bytes; - } + void g722_encode_init (int rate, int options) { - void g722_encode_init(int rate, int options) - { - - encode_s->itu_test_mode = FALSE; + encode_s->itu_test_mode = FALSE; - // 8 => 64 kbps; 7 => 56 kbps; 6 => 48 kbps + // 8 => 64 kbps; 7 => 56 kbps; 6 => 48 kbps encode_s->bits_per_sample = 8; - // Enable 8khz mode, encode using lower subband only + // Enable 8khz mode, encode using lower subband only encode_s->eight_k = FALSE; - // Never set packed TRUE when using 64 kbps + // Never set packed TRUE when using 64 kbps encode_s->packed = FALSE; encode_s->band[0].det = 32; - encode_s->band[1].det = 8; - } + encode_s->band[1].det = 8; + } + + void g722_decode_init (int rate, int options) { - void g722_decode_init(int rate, int options) - { - - decode_s->itu_test_mode = FALSE; + decode_s->itu_test_mode = FALSE; // 8 => 64 kbps; 7 => 56 kbps; 6 => 48 kbps - decode_s->bits_per_sample = 8; + decode_s->bits_per_sample = 8; - // Enable 8khz mode, encode using lower subband only + // Enable 8khz mode, encode using lower subband only decode_s->eight_k = FALSE; // Never set packed TRUE when using 64 kbps decode_s->packed = FALSE; decode_s->band[0].det = 32; - decode_s->band[1].det = 8; - } + decode_s->band[1].det = 8; + } - int16_t saturate(int32_t amp) - { + int16_t saturate (int32_t amp) { int16_t amp16; /* Hopefully this is optimised for the common case - not clipping */ amp16 = (int16_t) amp; + if (amp == amp16) return amp16; + if (amp > INT16_MAX) return INT16_MAX; + return INT16_MIN; } - void block4_encode(int band, int d) - { + void block4_encode (int band, int d) { int wd1; int wd2; int wd3; @@ -132,612 +132,650 @@ public: /* Block 4, RECONS */ encode_s->band[band].d[0] = d; - encode_s->band[band].r[0] = saturate(encode_s->band[band].s + d); + encode_s->band[band].r[0] = saturate (encode_s->band[band].s + d); /* Block 4, PARREC */ - encode_s->band[band].p[0] = saturate(encode_s->band[band].sz + d); + encode_s->band[band].p[0] = saturate (encode_s->band[band].sz + d); /* Block 4, UPPOL2 */ - for (i = 0; i < 3; i++) - encode_s->band[band].sg[i] = encode_s->band[band].p[i] >> 15; - wd1 = saturate(encode_s->band[band].a[1] << 2); - - wd2 = (encode_s->band[band].sg[0] == encode_s->band[band].sg[1]) ? -wd1 : wd1; - if (wd2 > 32767) - wd2 = 32767; - wd3 = (wd2 >> 7) + ((encode_s->band[band].sg[0] == encode_s->band[band].sg[2]) ? 128 : -128); - wd3 += (encode_s->band[band].a[2]*32512) >> 15; - if (wd3 > 12288) - wd3 = 12288; - else if (wd3 < -12288) - wd3 = -12288; - encode_s->band[band].ap[2] = wd3; - - /* Block 4, UPPOL1 */ - encode_s->band[band].sg[0] = encode_s->band[band].p[0] >> 15; - encode_s->band[band].sg[1] = encode_s->band[band].p[1] >> 15; - wd1 = (encode_s->band[band].sg[0] == encode_s->band[band].sg[1]) ? 192 : -192; - wd2 = (encode_s->band[band].a[1]*32640) >> 15; - - encode_s->band[band].ap[1] = saturate(wd1 + wd2); - wd3 = saturate(15360 - encode_s->band[band].ap[2]); - if (encode_s->band[band].ap[1] > wd3) - encode_s->band[band].ap[1] = wd3; - else if (encode_s->band[band].ap[1] < -wd3) - encode_s->band[band].ap[1] = -wd3; - - /* Block 4, UPZERO */ - wd1 = (d == 0) ? 0 : 128; - encode_s->band[band].sg[0] = d >> 15; - for (i = 1; i < 7; i++) - { - encode_s->band[band].sg[i] = encode_s->band[band].d[i] >> 15; - wd2 = (encode_s->band[band].sg[i] == encode_s->band[band].sg[0]) ? wd1 : -wd1; - wd3 = (encode_s->band[band].b[i]*32640) >> 15; - encode_s->band[band].bp[i] = saturate(wd2 + wd3); - } - - /* Block 4, DELAYA */ - for (i = 6; i > 0; i--) - { - encode_s->band[band].d[i] = encode_s->band[band].d[i - 1]; - encode_s->band[band].b[i] = encode_s->band[band].bp[i]; - } - - for (i = 2; i > 0; i--) - { - encode_s->band[band].r[i] = encode_s->band[band].r[i - 1]; - encode_s->band[band].p[i] = encode_s->band[band].p[i - 1]; - encode_s->band[band].a[i] = encode_s->band[band].ap[i]; - } - - /* Block 4, FILTEP */ - wd1 = saturate(encode_s->band[band].r[1] + encode_s->band[band].r[1]); - wd1 = (encode_s->band[band].a[1]*wd1) >> 15; - wd2 = saturate(encode_s->band[band].r[2] + encode_s->band[band].r[2]); - wd2 = (encode_s->band[band].a[2]*wd2) >> 15; - encode_s->band[band].sp = saturate(wd1 + wd2); - - /* Block 4, FILTEZ */ - encode_s->band[band].sz = 0; - for (i = 6; i > 0; i--) - { - wd1 = saturate(encode_s->band[band].d[i] + encode_s->band[band].d[i]); - encode_s->band[band].sz += (encode_s->band[band].b[i]*wd1) >> 15; - } - encode_s->band[band].sz = saturate(encode_s->band[band].sz); - - /* Block 4, PREDIC */ - encode_s->band[band].s = saturate(encode_s->band[band].sp + encode_s->band[band].sz); - - } - - void block4_decode(int band, int d) - { - int wd1; - int wd2; - int wd3; - int i; - - /* Block 4, RECONS */ - decode_s->band[band].d[0] = d; - decode_s->band[band].r[0] = saturate(decode_s->band[band].s + d); - - /* Block 4, PARREC */ - decode_s->band[band].p[0] = saturate(decode_s->band[band].sz + d); - - /* Block 4, UPPOL2 */ - for (i = 0; i < 3; i++) - decode_s->band[band].sg[i] = decode_s->band[band].p[i] >> 15; - wd1 = saturate(decode_s->band[band].a[1] << 2); - - wd2 = (decode_s->band[band].sg[0] == decode_s->band[band].sg[1]) ? -wd1 : wd1; - if (wd2 > 32767) - wd2 = 32767; - wd3 = (decode_s->band[band].sg[0] == decode_s->band[band].sg[2]) ? 128 : -128; - wd3 += (wd2 >> 7); - wd3 += (decode_s->band[band].a[2]*32512) >> 15; - if (wd3 > 12288) - wd3 = 12288; - else if (wd3 < -12288) - wd3 = -12288; - decode_s->band[band].ap[2] = wd3; - - /* Block 4, UPPOL1 */ - decode_s->band[band].sg[0] = decode_s->band[band].p[0] >> 15; - decode_s->band[band].sg[1] = decode_s->band[band].p[1] >> 15; - wd1 = (decode_s->band[band].sg[0] == decode_s->band[band].sg[1]) ? 192 : -192; - wd2 = (decode_s->band[band].a[1]*32640) >> 15; - - decode_s->band[band].ap[1] = saturate(wd1 + wd2); - wd3 = saturate(15360 - decode_s->band[band].ap[2]); - if (decode_s->band[band].ap[1] > wd3) - decode_s->band[band].ap[1] = wd3; - else if (decode_s->band[band].ap[1] < -wd3) - decode_s->band[band].ap[1] = -wd3; - - /* Block 4, UPZERO */ - wd1 = (d == 0) ? 0 : 128; - decode_s->band[band].sg[0] = d >> 15; - for (i = 1; i < 7; i++) - { - decode_s->band[band].sg[i] = decode_s->band[band].d[i] >> 15; - wd2 = (decode_s->band[band].sg[i] == decode_s->band[band].sg[0]) ? wd1 : -wd1; - wd3 = (decode_s->band[band].b[i]*32640) >> 15; - decode_s->band[band].bp[i] = saturate(wd2 + wd3); - } - - /* Block 4, DELAYA */ - for (i = 6; i > 0; i--) - { - decode_s->band[band].d[i] = decode_s->band[band].d[i - 1]; - decode_s->band[band].b[i] = decode_s->band[band].bp[i]; - } - - for (i = 2; i > 0; i--) - { - decode_s->band[band].r[i] = decode_s->band[band].r[i - 1]; - decode_s->band[band].p[i] = decode_s->band[band].p[i - 1]; - decode_s->band[band].a[i] = decode_s->band[band].ap[i]; - } - - /* Block 4, FILTEP */ - wd1 = saturate(decode_s->band[band].r[1] + decode_s->band[band].r[1]); - wd1 = (decode_s->band[band].a[1]*wd1) >> 15; - wd2 = saturate(decode_s->band[band].r[2] + decode_s->band[band].r[2]); - wd2 = (decode_s->band[band].a[2]*wd2) >> 15; - decode_s->band[band].sp = saturate(wd1 + wd2); - - /* Block 4, FILTEZ */ - decode_s->band[band].sz = 0; - for (i = 6; i > 0; i--) - { - wd1 = saturate(decode_s->band[band].d[i] + decode_s->band[band].d[i]); - decode_s->band[band].sz += (decode_s->band[band].b[i]*wd1) >> 15; - } - decode_s->band[band].sz = saturate(decode_s->band[band].sz); - - /* Block 4, PREDIC */ - decode_s->band[band].s = saturate(decode_s->band[band].sp + decode_s->band[band].sz); - } - - int g722_encode_release() - { - delete decode_s; + + for (i = 0; i < 3; i++) + encode_s->band[band].sg[i] = encode_s->band[band].p[i] >> 15; + + wd1 = saturate (encode_s->band[band].a[1] << 2); + + wd2 = (encode_s->band[band].sg[0] == encode_s->band[band].sg[1]) ? -wd1 : wd1; + + if (wd2 > 32767) + wd2 = 32767; + + wd3 = (wd2 >> 7) + ( (encode_s->band[band].sg[0] == encode_s->band[band].sg[2]) ? 128 : -128); + + wd3 += (encode_s->band[band].a[2]*32512) >> 15; + + if (wd3 > 12288) + wd3 = 12288; + else if (wd3 < -12288) + wd3 = -12288; + + encode_s->band[band].ap[2] = wd3; + + /* Block 4, UPPOL1 */ + encode_s->band[band].sg[0] = encode_s->band[band].p[0] >> 15; + + encode_s->band[band].sg[1] = encode_s->band[band].p[1] >> 15; + + wd1 = (encode_s->band[band].sg[0] == encode_s->band[band].sg[1]) ? 192 : -192; + + wd2 = (encode_s->band[band].a[1]*32640) >> 15; + + encode_s->band[band].ap[1] = saturate (wd1 + wd2); + + wd3 = saturate (15360 - encode_s->band[band].ap[2]); + + if (encode_s->band[band].ap[1] > wd3) + encode_s->band[band].ap[1] = wd3; + else if (encode_s->band[band].ap[1] < -wd3) + encode_s->band[band].ap[1] = -wd3; + + /* Block 4, UPZERO */ + wd1 = (d == 0) ? 0 : 128; + + encode_s->band[band].sg[0] = d >> 15; + + for (i = 1; i < 7; i++) { + encode_s->band[band].sg[i] = encode_s->band[band].d[i] >> 15; + wd2 = (encode_s->band[band].sg[i] == encode_s->band[band].sg[0]) ? wd1 : -wd1; + wd3 = (encode_s->band[band].b[i]*32640) >> 15; + encode_s->band[band].bp[i] = saturate (wd2 + wd3); + } + + /* Block 4, DELAYA */ + for (i = 6; i > 0; i--) { + encode_s->band[band].d[i] = encode_s->band[band].d[i - 1]; + encode_s->band[band].b[i] = encode_s->band[band].bp[i]; + } + + for (i = 2; i > 0; i--) { + encode_s->band[band].r[i] = encode_s->band[band].r[i - 1]; + encode_s->band[band].p[i] = encode_s->band[band].p[i - 1]; + encode_s->band[band].a[i] = encode_s->band[band].ap[i]; + } + + /* Block 4, FILTEP */ + wd1 = saturate (encode_s->band[band].r[1] + encode_s->band[band].r[1]); + + wd1 = (encode_s->band[band].a[1]*wd1) >> 15; + + wd2 = saturate (encode_s->band[band].r[2] + encode_s->band[band].r[2]); + + wd2 = (encode_s->band[band].a[2]*wd2) >> 15; + + encode_s->band[band].sp = saturate (wd1 + wd2); + + /* Block 4, FILTEZ */ + encode_s->band[band].sz = 0; + + for (i = 6; i > 0; i--) { + wd1 = saturate (encode_s->band[band].d[i] + encode_s->band[band].d[i]); + encode_s->band[band].sz += (encode_s->band[band].b[i]*wd1) >> 15; + } + + encode_s->band[band].sz = saturate (encode_s->band[band].sz); + + /* Block 4, PREDIC */ + encode_s->band[band].s = saturate (encode_s->band[band].sp + encode_s->band[band].sz); + + } + + void block4_decode (int band, int d) { + int wd1; + int wd2; + int wd3; + int i; + + /* Block 4, RECONS */ + decode_s->band[band].d[0] = d; + decode_s->band[band].r[0] = saturate (decode_s->band[band].s + d); + + /* Block 4, PARREC */ + decode_s->band[band].p[0] = saturate (decode_s->band[band].sz + d); + + /* Block 4, UPPOL2 */ + + for (i = 0; i < 3; i++) + decode_s->band[band].sg[i] = decode_s->band[band].p[i] >> 15; + + wd1 = saturate (decode_s->band[band].a[1] << 2); + + wd2 = (decode_s->band[band].sg[0] == decode_s->band[band].sg[1]) ? -wd1 : wd1; + + if (wd2 > 32767) + wd2 = 32767; + + wd3 = (decode_s->band[band].sg[0] == decode_s->band[band].sg[2]) ? 128 : -128; + + wd3 += (wd2 >> 7); + + wd3 += (decode_s->band[band].a[2]*32512) >> 15; + + if (wd3 > 12288) + wd3 = 12288; + else if (wd3 < -12288) + wd3 = -12288; + + decode_s->band[band].ap[2] = wd3; + + /* Block 4, UPPOL1 */ + decode_s->band[band].sg[0] = decode_s->band[band].p[0] >> 15; + + decode_s->band[band].sg[1] = decode_s->band[band].p[1] >> 15; + + wd1 = (decode_s->band[band].sg[0] == decode_s->band[band].sg[1]) ? 192 : -192; + + wd2 = (decode_s->band[band].a[1]*32640) >> 15; + + decode_s->band[band].ap[1] = saturate (wd1 + wd2); + + wd3 = saturate (15360 - decode_s->band[band].ap[2]); + + if (decode_s->band[band].ap[1] > wd3) + decode_s->band[band].ap[1] = wd3; + else if (decode_s->band[band].ap[1] < -wd3) + decode_s->band[band].ap[1] = -wd3; + + /* Block 4, UPZERO */ + wd1 = (d == 0) ? 0 : 128; + + decode_s->band[band].sg[0] = d >> 15; + + for (i = 1; i < 7; i++) { + decode_s->band[band].sg[i] = decode_s->band[band].d[i] >> 15; + wd2 = (decode_s->band[band].sg[i] == decode_s->band[band].sg[0]) ? wd1 : -wd1; + wd3 = (decode_s->band[band].b[i]*32640) >> 15; + decode_s->band[band].bp[i] = saturate (wd2 + wd3); + } + + /* Block 4, DELAYA */ + for (i = 6; i > 0; i--) { + decode_s->band[band].d[i] = decode_s->band[band].d[i - 1]; + decode_s->band[band].b[i] = decode_s->band[band].bp[i]; + } + + for (i = 2; i > 0; i--) { + decode_s->band[band].r[i] = decode_s->band[band].r[i - 1]; + decode_s->band[band].p[i] = decode_s->band[band].p[i - 1]; + decode_s->band[band].a[i] = decode_s->band[band].ap[i]; + } + + /* Block 4, FILTEP */ + wd1 = saturate (decode_s->band[band].r[1] + decode_s->band[band].r[1]); + + wd1 = (decode_s->band[band].a[1]*wd1) >> 15; + + wd2 = saturate (decode_s->band[band].r[2] + decode_s->band[band].r[2]); + + wd2 = (decode_s->band[band].a[2]*wd2) >> 15; + + decode_s->band[band].sp = saturate (wd1 + wd2); + + /* Block 4, FILTEZ */ + decode_s->band[band].sz = 0; + + for (i = 6; i > 0; i--) { + wd1 = saturate (decode_s->band[band].d[i] + decode_s->band[band].d[i]); + decode_s->band[band].sz += (decode_s->band[band].b[i]*wd1) >> 15; + } + + decode_s->band[band].sz = saturate (decode_s->band[band].sz); + + /* Block 4, PREDIC */ + decode_s->band[band].s = saturate (decode_s->band[band].sp + decode_s->band[band].sz); + } + + int g722_encode_release() { + delete decode_s; + } + + + int g722_decode_release() { + delete encode_s; + } + + int g722_decode (int16_t amp[], const uint8_t g722_data[], int len) { + static const int wl[8] = {-60, -30, 58, 172, 334, 538, 1198, 3042 }; + static const int rl42[16] = {0, 7, 6, 5, 4, 3, 2, 1, 7, 6, 5, 4, 3, 2, 1, 0 }; + static const int ilb[32] = { + 2048, 2093, 2139, 2186, 2233, 2282, 2332, + 2383, 2435, 2489, 2543, 2599, 2656, 2714, + 2774, 2834, 2896, 2960, 3025, 3091, 3158, + 3228, 3298, 3371, 3444, 3520, 3597, 3676, + 3756, 3838, 3922, 4008 + }; + static const int wh[3] = {0, -214, 798}; + static const int rh2[4] = {2, 1, 2, 1}; + static const int qm2[4] = {-7408, -1616, 7408, 1616}; + static const int qm4[16] = { + 0, -20456, -12896, -8968, + -6288, -4240, -2584, -1200, + 20456, 12896, 8968, 6288, + 4240, 2584, 1200, 0 + }; + static const int qm5[32] = { + -280, -280, -23352, -17560, + -14120, -11664, -9752, -8184, + -6864, -5712, -4696, -3784, + -2960, -2208, -1520, -880, + 23352, 17560, 14120, 11664, + 9752, 8184, 6864, 5712, + 4696, 3784, 2960, 2208, + 1520, 880, 280, -280 + }; + static const int qm6[64] = { + -136, -136, -136, -136, + -24808, -21904, -19008, -16704, + -14984, -13512, -12280, -11192, + -10232, -9360, -8576, -7856, + -7192, -6576, -6000, -5456, + -4944, -4464, -4008, -3576, + -3168, -2776, -2400, -2032, + -1688, -1360, -1040, -728, + 24808, 21904, 19008, 16704, + 14984, 13512, 12280, 11192, + 10232, 9360, 8576, 7856, + 7192, 6576, 6000, 5456, + 4944, 4464, 4008, 3576, + 3168, 2776, 2400, 2032, + 1688, 1360, 1040, 728, + 432, 136, -432, -136 + }; + static const int qmf_coeffs[12] = { + 3, -11, 12, 32, -210, 951, 3876, -805, 362, -156, 53, -11, + }; + + int dlowt; + int rlow; + int ihigh; + int dhigh; + int rhigh; + int xout1; + int xout2; + int wd1; + int wd2; + int wd3; + int code; + int outlen; + int i; + int j; + + outlen = 0; + rhigh = 0; + + for (j = 0; j < len;) { + if (decode_s->packed) { + /* Unpack the code bits */ + if (decode_s->in_bits < decode_s->bits_per_sample) { + decode_s->in_buffer |= (g722_data[j++] << decode_s->in_bits); + decode_s->in_bits += 8; + } + + code = decode_s->in_buffer & ( (1 << decode_s->bits_per_sample) - 1); + + decode_s->in_buffer >>= decode_s->bits_per_sample; + decode_s->in_bits -= decode_s->bits_per_sample; + } else { + code = g722_data[j++]; + } + + switch (decode_s->bits_per_sample) { + + default: + + case 8: + wd1 = code & 0x3F; + ihigh = (code >> 6) & 0x03; + wd2 = qm6[wd1]; + wd1 >>= 2; + break; + + case 7: + wd1 = code & 0x1F; + ihigh = (code >> 5) & 0x03; + wd2 = qm5[wd1]; + wd1 >>= 1; + break; + + case 6: + wd1 = code & 0x0F; + ihigh = (code >> 4) & 0x03; + wd2 = qm4[wd1]; + break; + } + + /* Block 5L, LOW BAND INVQBL */ + wd2 = (decode_s->band[0].det*wd2) >> 15; + + /* Block 5L, RECONS */ + rlow = decode_s->band[0].s + wd2; + + /* Block 6L, LIMIT */ + if (rlow > 16383) + rlow = 16383; + else if (rlow < -16384) + rlow = -16384; + + /* Block 2L, INVQAL */ + wd2 = qm4[wd1]; + + dlowt = (decode_s->band[0].det*wd2) >> 15; + + /* Block 3L, LOGSCL */ + wd2 = rl42[wd1]; + + wd1 = (decode_s->band[0].nb*127) >> 7; + + wd1 += wl[wd2]; + + if (wd1 < 0) + wd1 = 0; + else if (wd1 > 18432) + wd1 = 18432; + + decode_s->band[0].nb = wd1; + + /* Block 3L, SCALEL */ + wd1 = (decode_s->band[0].nb >> 6) & 31; + + wd2 = 8 - (decode_s->band[0].nb >> 11); + + wd3 = (wd2 < 0) ? (ilb[wd1] << -wd2) : (ilb[wd1] >> wd2); + + decode_s->band[0].det = wd3 << 2; + + block4_decode (0, dlowt); + + if (!decode_s->eight_k) { + /* Block 2H, INVQAH */ + wd2 = qm2[ihigh]; + dhigh = (decode_s->band[1].det*wd2) >> 15; + /* Block 5H, RECONS */ + rhigh = dhigh + decode_s->band[1].s; + /* Block 6H, LIMIT */ + + if (rhigh > 16383) + rhigh = 16383; + else if (rhigh < -16384) + rhigh = -16384; + + /* Block 2H, INVQAH */ + wd2 = rh2[ihigh]; + + wd1 = (decode_s->band[1].nb*127) >> 7; + + wd1 += wh[wd2]; + + if (wd1 < 0) + wd1 = 0; + else if (wd1 > 22528) + wd1 = 22528; + + decode_s->band[1].nb = wd1; + + /* Block 3H, SCALEH */ + wd1 = (decode_s->band[1].nb >> 6) & 31; + + wd2 = 10 - (decode_s->band[1].nb >> 11); + + wd3 = (wd2 < 0) ? (ilb[wd1] << -wd2) : (ilb[wd1] >> wd2); + + decode_s->band[1].det = wd3 << 2; + + block4_decode (1, dhigh); + } + + if (decode_s->itu_test_mode) { + amp[outlen++] = (int16_t) (rlow << 1); + amp[outlen++] = (int16_t) (rhigh << 1); + } else { + if (decode_s->eight_k) { + amp[outlen++] = (int16_t) rlow; + } else { + /* Apply the receive QMF */ + for (i = 0; i < 22; i++) + decode_s->x[i] = decode_s->x[i + 2]; + + decode_s->x[22] = rlow + rhigh; + + decode_s->x[23] = rlow - rhigh; + + xout1 = 0; + + xout2 = 0; + + for (i = 0; i < 12; i++) { + xout2 += decode_s->x[2*i]*qmf_coeffs[i]; + xout1 += decode_s->x[2*i + 1]*qmf_coeffs[11 - i]; + } + + amp[outlen++] = (int16_t) (xout1 >> 12); + + amp[outlen++] = (int16_t) (xout2 >> 12); + } + } + } + + return outlen; + } + + int g722_encode (uint8_t g722_data[], const int16_t amp[], int len) { + static const int q6[32] = { + 0, 35, 72, 110, 150, 190, 233, 276, + 323, 370, 422, 473, 530, 587, 650, 714, + 786, 858, 940, 1023, 1121, 1219, 1339, 1458, + 1612, 1765, 1980, 2195, 2557, 2919, 0, 0 + }; + static const int iln[32] = { + 0, 63, 62, 31, 30, 29, 28, 27, + 26, 25, 24, 23, 22, 21, 20, 19, + 18, 17, 16, 15, 14, 13, 12, 11, + 10, 9, 8, 7, 6, 5, 4, 0 + }; + static const int ilp[32] = { + 0, 61, 60, 59, 58, 57, 56, 55, + 54, 53, 52, 51, 50, 49, 48, 47, + 46, 45, 44, 43, 42, 41, 40, 39, + 38, 37, 36, 35, 34, 33, 32, 0 + }; + static const int wl[8] = { + -60, -30, 58, 172, 334, 538, 1198, 3042 + }; + static const int rl42[16] = { + 0, 7, 6, 5, 4, 3, 2, 1, 7, 6, 5, 4, 3, 2, 1, 0 + }; + static const int ilb[32] = { + 2048, 2093, 2139, 2186, 2233, 2282, 2332, + 2383, 2435, 2489, 2543, 2599, 2656, 2714, + 2774, 2834, 2896, 2960, 3025, 3091, 3158, + 3228, 3298, 3371, 3444, 3520, 3597, 3676, + 3756, 3838, 3922, 4008 + }; + static const int qm4[16] = { + 0, -20456, -12896, -8968, + -6288, -4240, -2584, -1200, + 20456, 12896, 8968, 6288, + 4240, 2584, 1200, 0 + }; + static const int qm2[4] = { + -7408, -1616, 7408, 1616 + }; + static const int qmf_coeffs[12] = { + 3, -11, 12, 32, -210, 951, 3876, -805, 362, -156, 53, -11, + }; + static const int ihn[3] = {0, 1, 0}; + static const int ihp[3] = {0, 3, 2}; + static const int wh[3] = {0, -214, 798}; + static const int rh2[4] = {2, 1, 2, 1}; + + int dlow; + int dhigh; + int el; + int wd; + int wd1; + int ril; + int wd2; + int il4; + int ih2; + int wd3; + int eh; + int mih; + int i; + int j; + /* Low and high band PCM from the QMF */ + int xlow; + int xhigh; + int g722_bytes; + /* Even and odd tap accumulators */ + int sumeven; + int sumodd; + int ihigh; + int ilow; + int code; + + g722_bytes = 0; + xhigh = 0; + + for (j = 0; j < len;) { + if (encode_s->itu_test_mode) { + xlow = + xhigh = amp[j++] >> 1; + } else { + if (encode_s->eight_k) { + xlow = amp[j++]; + } else { + /* Apply the transmit QMF */ + /* Shuffle the buffer down */ + for (i = 0; i < 22; i++) + encode_s->x[i] = encode_s->x[i + 2]; + + encode_s->x[22] = amp[j++]; + + encode_s->x[23] = amp[j++]; + + /* Discard every other QMF output */ + sumeven = 0; + + sumodd = 0; + + for (i = 0; i < 12; i++) { + sumodd += encode_s->x[2*i]*qmf_coeffs[i]; + sumeven += encode_s->x[2*i + 1]*qmf_coeffs[11 - i]; + } + + xlow = (sumeven + sumodd) >> 13; + + xhigh = (sumeven - sumodd) >> 13; + } + } + + /* Block 1L, SUBTRA */ + el = saturate (xlow - encode_s->band[0].s); + + /* Block 1L, QUANTL */ + wd = (el >= 0) ? el : - (el + 1); + + for (i = 1; i < 30; i++) { + wd1 = (q6[i]*encode_s->band[0].det) >> 12; + + if (wd < wd1) + break; + } + + ilow = (el < 0) ? iln[i] : ilp[i]; + + /* Block 2L, INVQAL */ + ril = ilow >> 2; + wd2 = qm4[ril]; + dlow = (encode_s->band[0].det*wd2) >> 15; + + /* Block 3L, LOGSCL */ + il4 = rl42[ril]; + wd = (encode_s->band[0].nb*127) >> 7; + encode_s->band[0].nb = wd + wl[il4]; + + if (encode_s->band[0].nb < 0) + encode_s->band[0].nb = 0; + else if (encode_s->band[0].nb > 18432) + encode_s->band[0].nb = 18432; + + /* Block 3L, SCALEL */ + wd1 = (encode_s->band[0].nb >> 6) & 31; + + wd2 = 8 - (encode_s->band[0].nb >> 11); + + wd3 = (wd2 < 0) ? (ilb[wd1] << -wd2) : (ilb[wd1] >> wd2); + + encode_s->band[0].det = wd3 << 2; + + block4_encode (0, dlow); + + if (encode_s->eight_k) { + /* Just leave the high bits as zero */ + code = (0xC0 | ilow) >> (8 - encode_s->bits_per_sample); + } else { + /* Block 1H, SUBTRA */ + eh = saturate (xhigh - encode_s->band[1].s); + + /* Block 1H, QUANTH */ + wd = (eh >= 0) ? eh : - (eh + 1); + wd1 = (564*encode_s->band[1].det) >> 12; + mih = (wd >= wd1) ? 2 : 1; + ihigh = (eh < 0) ? ihn[mih] : ihp[mih]; + + /* Block 2H, INVQAH */ + wd2 = qm2[ihigh]; + dhigh = (encode_s->band[1].det*wd2) >> 15; + + /* Block 3H, LOGSCH */ + ih2 = rh2[ihigh]; + wd = (encode_s->band[1].nb*127) >> 7; + encode_s->band[1].nb = wd + wh[ih2]; + + if (encode_s->band[1].nb < 0) + encode_s->band[1].nb = 0; + else if (encode_s->band[1].nb > 22528) + encode_s->band[1].nb = 22528; + + /* Block 3H, SCALEH */ + wd1 = (encode_s->band[1].nb >> 6) & 31; + + wd2 = 10 - (encode_s->band[1].nb >> 11); + + wd3 = (wd2 < 0) ? (ilb[wd1] << -wd2) : (ilb[wd1] >> wd2); + + encode_s->band[1].det = wd3 << 2; + + block4_encode (1, dhigh); + + code = ( (ihigh << 6) | ilow) >> (8 - encode_s->bits_per_sample); + } + + if (encode_s->packed) { + /* Pack the code bits */ + encode_s->out_buffer |= (code << encode_s->out_bits); + encode_s->out_bits += encode_s->bits_per_sample; + + if (encode_s->out_bits >= 8) { + g722_data[g722_bytes++] = (uint8_t) (encode_s->out_buffer & 0xFF); + encode_s->out_bits -= 8; + encode_s->out_buffer >>= 8; + } + } else { + g722_data[g722_bytes++] = (uint8_t) code; + } + } + + return g722_bytes; } - - - int g722_decode_release() - { - delete encode_s; - } - - int g722_decode(int16_t amp[], const uint8_t g722_data[], int len) - { - static const int wl[8] = {-60, -30, 58, 172, 334, 538, 1198, 3042 }; - static const int rl42[16] = {0, 7, 6, 5, 4, 3, 2, 1, 7, 6, 5, 4, 3, 2, 1, 0 }; - static const int ilb[32] = - { - 2048, 2093, 2139, 2186, 2233, 2282, 2332, - 2383, 2435, 2489, 2543, 2599, 2656, 2714, - 2774, 2834, 2896, 2960, 3025, 3091, 3158, - 3228, 3298, 3371, 3444, 3520, 3597, 3676, - 3756, 3838, 3922, 4008 - }; - static const int wh[3] = {0, -214, 798}; - static const int rh2[4] = {2, 1, 2, 1}; - static const int qm2[4] = {-7408, -1616, 7408, 1616}; - static const int qm4[16] = - { - 0, -20456, -12896, -8968, - -6288, -4240, -2584, -1200, - 20456, 12896, 8968, 6288, - 4240, 2584, 1200, 0 - }; - static const int qm5[32] = - { - -280, -280, -23352, -17560, - -14120, -11664, -9752, -8184, - -6864, -5712, -4696, -3784, - -2960, -2208, -1520, -880, - 23352, 17560, 14120, 11664, - 9752, 8184, 6864, 5712, - 4696, 3784, 2960, 2208, - 1520, 880, 280, -280 - }; - static const int qm6[64] = - { - -136, -136, -136, -136, - -24808, -21904, -19008, -16704, - -14984, -13512, -12280, -11192, - -10232, -9360, -8576, -7856, - -7192, -6576, -6000, -5456, - -4944, -4464, -4008, -3576, - -3168, -2776, -2400, -2032, - -1688, -1360, -1040, -728, - 24808, 21904, 19008, 16704, - 14984, 13512, 12280, 11192, - 10232, 9360, 8576, 7856, - 7192, 6576, 6000, 5456, - 4944, 4464, 4008, 3576, - 3168, 2776, 2400, 2032, - 1688, 1360, 1040, 728, - 432, 136, -432, -136 - }; - static const int qmf_coeffs[12] = - { - 3, -11, 12, 32, -210, 951, 3876, -805, 362, -156, 53, -11, - }; - - int dlowt; - int rlow; - int ihigh; - int dhigh; - int rhigh; - int xout1; - int xout2; - int wd1; - int wd2; - int wd3; - int code; - int outlen; - int i; - int j; - - outlen = 0; - rhigh = 0; - for (j = 0; j < len; ) - { - if (decode_s->packed) - { - /* Unpack the code bits */ - if (decode_s->in_bits < decode_s->bits_per_sample) - { - decode_s->in_buffer |= (g722_data[j++] << decode_s->in_bits); - decode_s->in_bits += 8; - } - code = decode_s->in_buffer & ((1 << decode_s->bits_per_sample) - 1); - decode_s->in_buffer >>= decode_s->bits_per_sample; - decode_s->in_bits -= decode_s->bits_per_sample; - } - else - { - code = g722_data[j++]; - } - - switch (decode_s->bits_per_sample) - { - default: - case 8: - wd1 = code & 0x3F; - ihigh = (code >> 6) & 0x03; - wd2 = qm6[wd1]; - wd1 >>= 2; - break; - case 7: - wd1 = code & 0x1F; - ihigh = (code >> 5) & 0x03; - wd2 = qm5[wd1]; - wd1 >>= 1; - break; - case 6: - wd1 = code & 0x0F; - ihigh = (code >> 4) & 0x03; - wd2 = qm4[wd1]; - break; - } - /* Block 5L, LOW BAND INVQBL */ - wd2 = (decode_s->band[0].det*wd2) >> 15; - /* Block 5L, RECONS */ - rlow = decode_s->band[0].s + wd2; - /* Block 6L, LIMIT */ - if (rlow > 16383) - rlow = 16383; - else if (rlow < -16384) - rlow = -16384; - - /* Block 2L, INVQAL */ - wd2 = qm4[wd1]; - dlowt = (decode_s->band[0].det*wd2) >> 15; - - /* Block 3L, LOGSCL */ - wd2 = rl42[wd1]; - wd1 = (decode_s->band[0].nb*127) >> 7; - wd1 += wl[wd2]; - if (wd1 < 0) - wd1 = 0; - else if (wd1 > 18432) - wd1 = 18432; - decode_s->band[0].nb = wd1; - - /* Block 3L, SCALEL */ - wd1 = (decode_s->band[0].nb >> 6) & 31; - wd2 = 8 - (decode_s->band[0].nb >> 11); - wd3 = (wd2 < 0) ? (ilb[wd1] << -wd2) : (ilb[wd1] >> wd2); - decode_s->band[0].det = wd3 << 2; - - block4_decode(0, dlowt); - - if (!decode_s->eight_k) - { - /* Block 2H, INVQAH */ - wd2 = qm2[ihigh]; - dhigh = (decode_s->band[1].det*wd2) >> 15; - /* Block 5H, RECONS */ - rhigh = dhigh + decode_s->band[1].s; - /* Block 6H, LIMIT */ - if (rhigh > 16383) - rhigh = 16383; - else if (rhigh < -16384) - rhigh = -16384; - - /* Block 2H, INVQAH */ - wd2 = rh2[ihigh]; - wd1 = (decode_s->band[1].nb*127) >> 7; - wd1 += wh[wd2]; - if (wd1 < 0) - wd1 = 0; - else if (wd1 > 22528) - wd1 = 22528; - decode_s->band[1].nb = wd1; - - /* Block 3H, SCALEH */ - wd1 = (decode_s->band[1].nb >> 6) & 31; - wd2 = 10 - (decode_s->band[1].nb >> 11); - wd3 = (wd2 < 0) ? (ilb[wd1] << -wd2) : (ilb[wd1] >> wd2); - decode_s->band[1].det = wd3 << 2; - - block4_decode(1, dhigh); - } - - if (decode_s->itu_test_mode) - { - amp[outlen++] = (int16_t) (rlow << 1); - amp[outlen++] = (int16_t) (rhigh << 1); - } - else - { - if (decode_s->eight_k) - { - amp[outlen++] = (int16_t) rlow; - } - else - { - /* Apply the receive QMF */ - for (i = 0; i < 22; i++) - decode_s->x[i] = decode_s->x[i + 2]; - decode_s->x[22] = rlow + rhigh; - decode_s->x[23] = rlow - rhigh; - - xout1 = 0; - xout2 = 0; - for (i = 0; i < 12; i++) - { - xout2 += decode_s->x[2*i]*qmf_coeffs[i]; - xout1 += decode_s->x[2*i + 1]*qmf_coeffs[11 - i]; - } - amp[outlen++] = (int16_t) (xout1 >> 12); - amp[outlen++] = (int16_t) (xout2 >> 12); - } - } - } - return outlen; - } - - int g722_encode(uint8_t g722_data[], const int16_t amp[], int len) - { - static const int q6[32] = - { - 0, 35, 72, 110, 150, 190, 233, 276, - 323, 370, 422, 473, 530, 587, 650, 714, - 786, 858, 940, 1023, 1121, 1219, 1339, 1458, - 1612, 1765, 1980, 2195, 2557, 2919, 0, 0 - }; - static const int iln[32] = - { - 0, 63, 62, 31, 30, 29, 28, 27, - 26, 25, 24, 23, 22, 21, 20, 19, - 18, 17, 16, 15, 14, 13, 12, 11, - 10, 9, 8, 7, 6, 5, 4, 0 - }; - static const int ilp[32] = - { - 0, 61, 60, 59, 58, 57, 56, 55, - 54, 53, 52, 51, 50, 49, 48, 47, - 46, 45, 44, 43, 42, 41, 40, 39, - 38, 37, 36, 35, 34, 33, 32, 0 - }; - static const int wl[8] = - { - -60, -30, 58, 172, 334, 538, 1198, 3042 - }; - static const int rl42[16] = - { - 0, 7, 6, 5, 4, 3, 2, 1, 7, 6, 5, 4, 3, 2, 1, 0 - }; - static const int ilb[32] = - { - 2048, 2093, 2139, 2186, 2233, 2282, 2332, - 2383, 2435, 2489, 2543, 2599, 2656, 2714, - 2774, 2834, 2896, 2960, 3025, 3091, 3158, - 3228, 3298, 3371, 3444, 3520, 3597, 3676, - 3756, 3838, 3922, 4008 - }; - static const int qm4[16] = - { - 0, -20456, -12896, -8968, - -6288, -4240, -2584, -1200, - 20456, 12896, 8968, 6288, - 4240, 2584, 1200, 0 - }; - static const int qm2[4] = - { - -7408, -1616, 7408, 1616 - }; - static const int qmf_coeffs[12] = - { - 3, -11, 12, 32, -210, 951, 3876, -805, 362, -156, 53, -11, - }; - static const int ihn[3] = {0, 1, 0}; - static const int ihp[3] = {0, 3, 2}; - static const int wh[3] = {0, -214, 798}; - static const int rh2[4] = {2, 1, 2, 1}; - - int dlow; - int dhigh; - int el; - int wd; - int wd1; - int ril; - int wd2; - int il4; - int ih2; - int wd3; - int eh; - int mih; - int i; - int j; - /* Low and high band PCM from the QMF */ - int xlow; - int xhigh; - int g722_bytes; - /* Even and odd tap accumulators */ - int sumeven; - int sumodd; - int ihigh; - int ilow; - int code; - - g722_bytes = 0; - xhigh = 0; - for (j = 0; j < len; ) - { - if (encode_s->itu_test_mode) - { - xlow = - xhigh = amp[j++] >> 1; - } - else - { - if (encode_s->eight_k) - { - xlow = amp[j++]; - } - else - { - /* Apply the transmit QMF */ - /* Shuffle the buffer down */ - for (i = 0; i < 22; i++) - encode_s->x[i] = encode_s->x[i + 2]; - encode_s->x[22] = amp[j++]; - encode_s->x[23] = amp[j++]; - - /* Discard every other QMF output */ - sumeven = 0; - sumodd = 0; - for (i = 0; i < 12; i++) - { - sumodd += encode_s->x[2*i]*qmf_coeffs[i]; - sumeven += encode_s->x[2*i + 1]*qmf_coeffs[11 - i]; - } - xlow = (sumeven + sumodd) >> 13; - xhigh = (sumeven - sumodd) >> 13; - } - } - /* Block 1L, SUBTRA */ - el = saturate(xlow - encode_s->band[0].s); - - /* Block 1L, QUANTL */ - wd = (el >= 0) ? el : -(el + 1); - - for (i = 1; i < 30; i++) - { - wd1 = (q6[i]*encode_s->band[0].det) >> 12; - if (wd < wd1) - break; - } - ilow = (el < 0) ? iln[i] : ilp[i]; - - /* Block 2L, INVQAL */ - ril = ilow >> 2; - wd2 = qm4[ril]; - dlow = (encode_s->band[0].det*wd2) >> 15; - - /* Block 3L, LOGSCL */ - il4 = rl42[ril]; - wd = (encode_s->band[0].nb*127) >> 7; - encode_s->band[0].nb = wd + wl[il4]; - if (encode_s->band[0].nb < 0) - encode_s->band[0].nb = 0; - else if (encode_s->band[0].nb > 18432) - encode_s->band[0].nb = 18432; - - /* Block 3L, SCALEL */ - wd1 = (encode_s->band[0].nb >> 6) & 31; - wd2 = 8 - (encode_s->band[0].nb >> 11); - wd3 = (wd2 < 0) ? (ilb[wd1] << -wd2) : (ilb[wd1] >> wd2); - encode_s->band[0].det = wd3 << 2; - - block4_encode(0, dlow); - - if (encode_s->eight_k) - { - /* Just leave the high bits as zero */ - code = (0xC0 | ilow) >> (8 - encode_s->bits_per_sample); - } - else - { - /* Block 1H, SUBTRA */ - eh = saturate(xhigh - encode_s->band[1].s); - - /* Block 1H, QUANTH */ - wd = (eh >= 0) ? eh : -(eh + 1); - wd1 = (564*encode_s->band[1].det) >> 12; - mih = (wd >= wd1) ? 2 : 1; - ihigh = (eh < 0) ? ihn[mih] : ihp[mih]; - - /* Block 2H, INVQAH */ - wd2 = qm2[ihigh]; - dhigh = (encode_s->band[1].det*wd2) >> 15; - - /* Block 3H, LOGSCH */ - ih2 = rh2[ihigh]; - wd = (encode_s->band[1].nb*127) >> 7; - encode_s->band[1].nb = wd + wh[ih2]; - if (encode_s->band[1].nb < 0) - encode_s->band[1].nb = 0; - else if (encode_s->band[1].nb > 22528) - encode_s->band[1].nb = 22528; - - /* Block 3H, SCALEH */ - wd1 = (encode_s->band[1].nb >> 6) & 31; - wd2 = 10 - (encode_s->band[1].nb >> 11); - wd3 = (wd2 < 0) ? (ilb[wd1] << -wd2) : (ilb[wd1] >> wd2); - encode_s->band[1].det = wd3 << 2; - - block4_encode(1, dhigh); - code = ((ihigh << 6) | ilow) >> (8 - encode_s->bits_per_sample); - } - - if (encode_s->packed) - { - /* Pack the code bits */ - encode_s->out_buffer |= (code << encode_s->out_bits); - encode_s->out_bits += encode_s->bits_per_sample; - if (encode_s->out_bits >= 8) - { - g722_data[g722_bytes++] = (uint8_t) (encode_s->out_buffer & 0xFF); - encode_s->out_bits -= 8; - encode_s->out_buffer >>= 8; - } - } - else - { - g722_data[g722_bytes++] = (uint8_t) code; - } - } - return g722_bytes; - } private: @@ -748,11 +786,13 @@ public: }; // the class factories -extern "C" AudioCodec* create() { - return new G722(9); +extern "C" AudioCodec* create() +{ + return new G722 (9); } -extern "C" void destroy(AudioCodec* a) { +extern "C" void destroy (AudioCodec* a) +{ delete a; } diff --git a/sflphone-common/src/audio/codecs/gsmcodec.cpp b/sflphone-common/src/audio/codecs/gsmcodec.cpp index 6f5a4269ec..8543dec2b5 100644 --- a/sflphone-common/src/audio/codecs/gsmcodec.cpp +++ b/sflphone-common/src/audio/codecs/gsmcodec.cpp @@ -20,63 +20,72 @@ #include "audiocodec.h" -extern "C"{ +extern "C" +{ #include <gsm/gsm.h> } /** * GSM audio codec C++ class (over gsm/gsm.h) */ -class Gsm : public AudioCodec { -public: - // _payload should be 3 - Gsm (int payload=3): AudioCodec(payload, "GSM"), _decode_gsmhandle(NULL), _encode_gsmhandle(NULL){ - _clockRate = 8000; - _frameSize = 160; // samples, 20 ms at 8kHz - _channel = 1; - _bitrate = 13.3; - _bandwidth = 29.2; - - if (!(_decode_gsmhandle = gsm_create() )) - printf("ERROR: decode_gsm_create\n"); - if (!(_encode_gsmhandle = gsm_create() )) - printf("AudioCodec: ERROR: encode_gsm_create\n"); - } - - Gsm( const Gsm& ); - - Gsm& operator=( const Gsm& ); - - virtual ~Gsm (void){ - gsm_destroy(_decode_gsmhandle); - gsm_destroy(_encode_gsmhandle); - } - - virtual int codecDecode (short * dst, unsigned char * src, unsigned int size){ - // _debug("Decoded by gsm \n"); - (void)size; - if(gsm_decode(_decode_gsmhandle, (gsm_byte*)src, (gsm_signal*)dst) < 0) - printf("ERROR: gsm_decode\n"); - return 320; - } - - virtual int codecEncode (unsigned char * dst, short * src, unsigned int size){ - - // _debug("Encoded by gsm \n"); - (void)size; - gsm_encode(_encode_gsmhandle, (gsm_signal*)src, (gsm_byte*) dst); - return 33; - } - -private: - gsm _decode_gsmhandle; - gsm _encode_gsmhandle; + +class Gsm : public AudioCodec +{ + + public: + // _payload should be 3 + Gsm (int payload=3) : AudioCodec (payload, "GSM"), _decode_gsmhandle (NULL), _encode_gsmhandle (NULL) { + _clockRate = 8000; + _frameSize = 160; // samples, 20 ms at 8kHz + _channel = 1; + _bitrate = 13.3; + _bandwidth = 29.2; + + if (! (_decode_gsmhandle = gsm_create())) + printf ("ERROR: decode_gsm_create\n"); + + if (! (_encode_gsmhandle = gsm_create())) + printf ("AudioCodec: ERROR: encode_gsm_create\n"); + } + + Gsm (const Gsm&); + + Gsm& operator= (const Gsm&); + + virtual ~Gsm (void) { + gsm_destroy (_decode_gsmhandle); + gsm_destroy (_encode_gsmhandle); + } + + virtual int codecDecode (short * dst, unsigned char * src, unsigned int size) { + // _debug("Decoded by gsm \n"); + (void) size; + + if (gsm_decode (_decode_gsmhandle, (gsm_byte*) src, (gsm_signal*) dst) < 0) + printf ("ERROR: gsm_decode\n"); + + return 320; + } + + virtual int codecEncode (unsigned char * dst, short * src, unsigned int size) { + + // _debug("Encoded by gsm \n"); + (void) size; + gsm_encode (_encode_gsmhandle, (gsm_signal*) src, (gsm_byte*) dst); + return 33; + } + + private: + gsm _decode_gsmhandle; + gsm _encode_gsmhandle; }; -extern "C" AudioCodec* create(){ - return new Gsm(3); +extern "C" AudioCodec* create() +{ + return new Gsm (3); } -extern "C" void destroy(AudioCodec* a){ - delete a; +extern "C" void destroy (AudioCodec* a) +{ + delete a; } diff --git a/sflphone-common/src/audio/codecs/speexcodec_nb.cpp b/sflphone-common/src/audio/codecs/speexcodec_nb.cpp index 96f7c63db4..60d86bb129 100644 --- a/sflphone-common/src/audio/codecs/speexcodec_nb.cpp +++ b/sflphone-common/src/audio/codecs/speexcodec_nb.cpp @@ -23,50 +23,51 @@ #include <speex/speex.h> #include <speex/speex_preprocess.h> -class Speex : public AudioCodec{ +class Speex : public AudioCodec +{ + public: - Speex(int payload=0) - : AudioCodec(payload, "speex"), - _speexModePtr(NULL), - _speex_dec_bits(), - _speex_enc_bits(), - _speex_dec_state(), - _speex_enc_state(), - _speex_frame_size(), - _preprocess_state() - { - _clockRate = 8000; - _frameSize = 160; // samples, 20 ms at 8kHz - _channel = 1; - _bitrate = 0; - _bandwidth = 0; - initSpeex(); - } - - Speex( const Speex& ); - Speex& operator=(const Speex&); - - void initSpeex() { - - int _samplingRate = 8000; + Speex (int payload=0) + : AudioCodec (payload, "speex"), + _speexModePtr (NULL), + _speex_dec_bits(), + _speex_enc_bits(), + _speex_dec_state(), + _speex_enc_state(), + _speex_frame_size(), + _preprocess_state() { + _clockRate = 8000; + _frameSize = 160; // samples, 20 ms at 8kHz + _channel = 1; + _bitrate = 0; + _bandwidth = 0; + initSpeex(); + } + + Speex (const Speex&); + Speex& operator= (const Speex&); + + void initSpeex() { + + int _samplingRate = 8000; // 8000 HZ --> Narrow-band mode // TODO Manage the other modes - _speexModePtr = &speex_nb_mode; - // _speexModePtr = &speex_wb_mode; + _speexModePtr = &speex_nb_mode; + // _speexModePtr = &speex_wb_mode; // Init the decoder struct - speex_bits_init(&_speex_dec_bits); - _speex_dec_state = speex_decoder_init(_speexModePtr); + speex_bits_init (&_speex_dec_bits); + _speex_dec_state = speex_decoder_init (_speexModePtr); // Init the encoder struct - speex_bits_init(&_speex_enc_bits); - _speex_enc_state = speex_encoder_init(_speexModePtr); + speex_bits_init (&_speex_enc_bits); + _speex_enc_state = speex_encoder_init (_speexModePtr); + + speex_encoder_ctl (_speex_enc_state,SPEEX_SET_SAMPLING_RATE,&_clockRate); - speex_encoder_ctl(_speex_enc_state,SPEEX_SET_SAMPLING_RATE,&_clockRate); + speex_decoder_ctl (_speex_dec_state, SPEEX_GET_FRAME_SIZE, &_speex_frame_size); - speex_decoder_ctl(_speex_dec_state, SPEEX_GET_FRAME_SIZE, &_speex_frame_size); - #ifdef HAVE_SPEEXDSP_LIB int enable = 1; @@ -74,63 +75,60 @@ class Speex : public AudioCodec{ int complex = 10; int attenuation = -10; - speex_encoder_ctl(_speex_enc_state, SPEEX_SET_VAD, &enable); - speex_encoder_ctl(_speex_enc_state, SPEEX_SET_DTX, &enable); - speex_encoder_ctl(_speex_enc_state, SPEEX_SET_VBR_QUALITY, &quality); - speex_encoder_ctl(_speex_enc_state, SPEEX_SET_COMPLEXITY, &complex); + speex_encoder_ctl (_speex_enc_state, SPEEX_SET_VAD, &enable); + speex_encoder_ctl (_speex_enc_state, SPEEX_SET_DTX, &enable); + speex_encoder_ctl (_speex_enc_state, SPEEX_SET_VBR_QUALITY, &quality); + speex_encoder_ctl (_speex_enc_state, SPEEX_SET_COMPLEXITY, &complex); // Init the decoder struct - speex_decoder_ctl(_speex_dec_state, SPEEX_GET_FRAME_SIZE, &_speex_frame_size); + speex_decoder_ctl (_speex_dec_state, SPEEX_GET_FRAME_SIZE, &_speex_frame_size); // Init the preprocess struct - _preprocess_state = speex_preprocess_state_init(_speex_frame_size,_clockRate); - speex_preprocess_ctl(_preprocess_state, SPEEX_PREPROCESS_SET_DENOISE, &enable); - speex_preprocess_ctl(_preprocess_state, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &attenuation); - speex_preprocess_ctl(_preprocess_state, SPEEX_PREPROCESS_SET_VAD, &enable); - speex_preprocess_ctl(_preprocess_state, SPEEX_PREPROCESS_SET_AGC, &enable); + _preprocess_state = speex_preprocess_state_init (_speex_frame_size,_clockRate); + speex_preprocess_ctl (_preprocess_state, SPEEX_PREPROCESS_SET_DENOISE, &enable); + speex_preprocess_ctl (_preprocess_state, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &attenuation); + speex_preprocess_ctl (_preprocess_state, SPEEX_PREPROCESS_SET_VAD, &enable); + speex_preprocess_ctl (_preprocess_state, SPEEX_PREPROCESS_SET_AGC, &enable); #endif - + } - ~Speex() - { + ~Speex() { terminateSpeex(); } void terminateSpeex() { // Destroy the decoder struct - speex_bits_destroy(&_speex_dec_bits); - speex_decoder_destroy(_speex_dec_state); + speex_bits_destroy (&_speex_dec_bits); + speex_decoder_destroy (_speex_dec_state); _speex_dec_state = 0; // Destroy the encoder struct - speex_bits_destroy(&_speex_enc_bits); - speex_encoder_destroy(_speex_enc_state); + speex_bits_destroy (&_speex_enc_bits); + speex_encoder_destroy (_speex_enc_state); _speex_enc_state = 0; } - virtual int codecDecode (short *dst, unsigned char *src, unsigned int size) - { - + virtual int codecDecode (short *dst, unsigned char *src, unsigned int size) { + int ratio = 320 / _speex_frame_size; - speex_bits_read_from(&_speex_dec_bits, (char*)src, size); - speex_decode_int(_speex_dec_state, &_speex_dec_bits, dst); + speex_bits_read_from (&_speex_dec_bits, (char*) src, size); + speex_decode_int (_speex_dec_state, &_speex_dec_bits, dst); - return _speex_frame_size * ratio; + return _speex_frame_size * ratio; } - virtual int codecEncode (unsigned char *dst, short *src, unsigned int size) - { - speex_bits_reset(&_speex_enc_bits); + virtual int codecEncode (unsigned char *dst, short *src, unsigned int size) { + speex_bits_reset (&_speex_enc_bits); #ifdef HAVE_SPEEXDSP_LIB - - speex_preprocess_run(_preprocess_state, src); -#endif - - speex_encode_int(_speex_enc_state, src, &_speex_enc_bits); - int nbBytes = speex_bits_write(&_speex_enc_bits, (char*)dst, size); + speex_preprocess_run (_preprocess_state, src); +#endif + + + speex_encode_int (_speex_enc_state, src, &_speex_enc_bits); + int nbBytes = speex_bits_write (&_speex_enc_bits, (char*) dst, size); return nbBytes; } @@ -146,11 +144,13 @@ class Speex : public AudioCodec{ }; // the class factories -extern "C" AudioCodec* create() { - return new Speex(110); +extern "C" AudioCodec* create() +{ + return new Speex (110); } -extern "C" void destroy(AudioCodec* a) { +extern "C" void destroy (AudioCodec* a) +{ delete a; } diff --git a/sflphone-common/src/audio/codecs/speexcodec_ub.cpp b/sflphone-common/src/audio/codecs/speexcodec_ub.cpp index bce7e952e4..05c6dec9eb 100644 --- a/sflphone-common/src/audio/codecs/speexcodec_ub.cpp +++ b/sflphone-common/src/audio/codecs/speexcodec_ub.cpp @@ -23,50 +23,51 @@ #include <speex/speex.h> #include <speex/speex_preprocess.h> -class Speex : public AudioCodec{ +class Speex : public AudioCodec +{ + public: - Speex(int payload=0) - : AudioCodec(payload, "speex"), - _speexModePtr(NULL), - _speex_dec_bits(), - _speex_enc_bits(), - _speex_dec_state(), - _speex_enc_state(), - _speex_frame_size(), - _preprocess_state() - { - _clockRate = 32000; - _frameSize = 320; // 10 ms at 32 kHz - _channel = 1; - _bitrate = 0; - _bandwidth = 0; - initSpeex(); - } - - Speex( const Speex& ); - Speex& operator=(const Speex&); - - void initSpeex() { - - // int _samplingRate = 32000; + Speex (int payload=0) + : AudioCodec (payload, "speex"), + _speexModePtr (NULL), + _speex_dec_bits(), + _speex_enc_bits(), + _speex_dec_state(), + _speex_enc_state(), + _speex_frame_size(), + _preprocess_state() { + _clockRate = 32000; + _frameSize = 320; // 10 ms at 32 kHz + _channel = 1; + _bitrate = 0; + _bandwidth = 0; + initSpeex(); + } + + Speex (const Speex&); + Speex& operator= (const Speex&); + + void initSpeex() { + + // int _samplingRate = 32000; // 8000 HZ --> Narrow-band mode // TODO Manage the other modes - _speexModePtr = &speex_wb_mode; - // _speexModePtr = &speex_wb_mode; + _speexModePtr = &speex_wb_mode; + // _speexModePtr = &speex_wb_mode; // Init the decoder struct - speex_bits_init(&_speex_dec_bits); - _speex_dec_state = speex_decoder_init(_speexModePtr); + speex_bits_init (&_speex_dec_bits); + _speex_dec_state = speex_decoder_init (_speexModePtr); // Init the encoder struct - speex_bits_init(&_speex_enc_bits); - _speex_enc_state = speex_encoder_init(_speexModePtr); + speex_bits_init (&_speex_enc_bits); + _speex_enc_state = speex_encoder_init (_speexModePtr); + + speex_encoder_ctl (_speex_enc_state,SPEEX_SET_SAMPLING_RATE,&_clockRate); - speex_encoder_ctl(_speex_enc_state,SPEEX_SET_SAMPLING_RATE,&_clockRate); + speex_decoder_ctl (_speex_dec_state, SPEEX_GET_FRAME_SIZE, &_speex_frame_size); - speex_decoder_ctl(_speex_dec_state, SPEEX_GET_FRAME_SIZE, &_speex_frame_size); - #ifdef HAVE_SPEEXDSP_LIB int enable = 1; @@ -74,65 +75,62 @@ class Speex : public AudioCodec{ int complex = 10; int attenuation = -10; - speex_encoder_ctl(_speex_enc_state, SPEEX_SET_VAD, &enable); - speex_encoder_ctl(_speex_enc_state, SPEEX_SET_DTX, &enable); + speex_encoder_ctl (_speex_enc_state, SPEEX_SET_VAD, &enable); + speex_encoder_ctl (_speex_enc_state, SPEEX_SET_DTX, &enable); // speex_encoder_ctl(_speex_enc_state, SPEEX_SET_VBR_QUALITY, &quality); - speex_encoder_ctl(_speex_enc_state, SPEEX_SET_COMPLEXITY, &complex); + speex_encoder_ctl (_speex_enc_state, SPEEX_SET_COMPLEXITY, &complex); // Init the decoder struct - speex_decoder_ctl(_speex_dec_state, SPEEX_GET_FRAME_SIZE, &_speex_frame_size); + speex_decoder_ctl (_speex_dec_state, SPEEX_GET_FRAME_SIZE, &_speex_frame_size); // Init the preprocess struct - _preprocess_state = speex_preprocess_state_init(_speex_frame_size,_clockRate); - speex_preprocess_ctl(_preprocess_state, SPEEX_PREPROCESS_SET_DENOISE, &enable); - speex_preprocess_ctl(_preprocess_state, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &attenuation); - speex_preprocess_ctl(_preprocess_state, SPEEX_PREPROCESS_SET_VAD, &enable); - speex_preprocess_ctl(_preprocess_state, SPEEX_PREPROCESS_SET_AGC, &enable); + _preprocess_state = speex_preprocess_state_init (_speex_frame_size,_clockRate); + speex_preprocess_ctl (_preprocess_state, SPEEX_PREPROCESS_SET_DENOISE, &enable); + speex_preprocess_ctl (_preprocess_state, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &attenuation); + speex_preprocess_ctl (_preprocess_state, SPEEX_PREPROCESS_SET_VAD, &enable); + speex_preprocess_ctl (_preprocess_state, SPEEX_PREPROCESS_SET_AGC, &enable); #endif - + } - ~Speex() - { + ~Speex() { terminateSpeex(); } void terminateSpeex() { // Destroy the decoder struct - speex_bits_destroy(&_speex_dec_bits); - speex_decoder_destroy(_speex_dec_state); + speex_bits_destroy (&_speex_dec_bits); + speex_decoder_destroy (_speex_dec_state); _speex_dec_state = 0; // Destroy the encoder struct - speex_bits_destroy(&_speex_enc_bits); - speex_encoder_destroy(_speex_enc_state); + speex_bits_destroy (&_speex_enc_bits); + speex_encoder_destroy (_speex_enc_state); _speex_enc_state = 0; } - virtual int codecDecode (short *dst, unsigned char *src, unsigned int size) - { - - // int ratio = 320 / _speex_frame_size; - speex_bits_read_from(&_speex_dec_bits, (char*)src, size); - speex_decode_int(_speex_dec_state, &_speex_dec_bits, dst); + virtual int codecDecode (short *dst, unsigned char *src, unsigned int size) { + + // int ratio = 320 / _speex_frame_size; + speex_bits_read_from (&_speex_dec_bits, (char*) src, size); + speex_decode_int (_speex_dec_state, &_speex_dec_bits, dst); - // return the nuber of byte, not the number of sample + // return the nuber of byte, not the number of sample return _speex_frame_size * 2; } - virtual int codecEncode (unsigned char *dst, short *src, unsigned int size) - { - speex_bits_reset(&_speex_enc_bits); + virtual int codecEncode (unsigned char *dst, short *src, unsigned int size) { + speex_bits_reset (&_speex_enc_bits); #ifdef HAVE_SPEEXDSP_LIB - - speex_preprocess_run(_preprocess_state, src); -#endif - - speex_encode_int(_speex_enc_state, src, &_speex_enc_bits); - speex_bits_nbytes(&_speex_enc_bits); - int nbBytes = speex_bits_write(&_speex_enc_bits, (char*)dst, size); + speex_preprocess_run (_preprocess_state, src); +#endif + + + speex_encode_int (_speex_enc_state, src, &_speex_enc_bits); + speex_bits_nbytes (&_speex_enc_bits); + int nbBytes = speex_bits_write (&_speex_enc_bits, (char*) dst, size); return nbBytes; } @@ -148,11 +146,13 @@ class Speex : public AudioCodec{ }; // the class factories -extern "C" AudioCodec* create() { - return new Speex(112); +extern "C" AudioCodec* create() +{ + return new Speex (112); } -extern "C" void destroy(AudioCodec* a) { +extern "C" void destroy (AudioCodec* a) +{ delete a; } diff --git a/sflphone-common/src/audio/codecs/speexcodec_wb.cpp b/sflphone-common/src/audio/codecs/speexcodec_wb.cpp index dc93f39ec1..065609ceea 100644 --- a/sflphone-common/src/audio/codecs/speexcodec_wb.cpp +++ b/sflphone-common/src/audio/codecs/speexcodec_wb.cpp @@ -23,50 +23,51 @@ #include <speex/speex.h> #include <speex/speex_preprocess.h> -class Speex : public AudioCodec{ +class Speex : public AudioCodec +{ + public: - Speex(int payload=0) - : AudioCodec(payload, "speex"), - _speexModePtr(NULL), - _speex_dec_bits(), - _speex_enc_bits(), - _speex_dec_state(), - _speex_enc_state(), - _speex_frame_size(), - _preprocess_state() - { - _clockRate = 16000; - _frameSize = 320; // 20 ms at 16 kHz - _channel = 1; - _bitrate = 0; - _bandwidth = 0; - initSpeex(); - } - - Speex( const Speex& ); - Speex& operator=(const Speex&); - - void initSpeex() { - - int _samplingRate = 16000; + Speex (int payload=0) + : AudioCodec (payload, "speex"), + _speexModePtr (NULL), + _speex_dec_bits(), + _speex_enc_bits(), + _speex_dec_state(), + _speex_enc_state(), + _speex_frame_size(), + _preprocess_state() { + _clockRate = 16000; + _frameSize = 320; // 20 ms at 16 kHz + _channel = 1; + _bitrate = 0; + _bandwidth = 0; + initSpeex(); + } + + Speex (const Speex&); + Speex& operator= (const Speex&); + + void initSpeex() { + + int _samplingRate = 16000; // 8000 HZ --> Narrow-band mode // TODO Manage the other modes - _speexModePtr = &speex_wb_mode; - // _speexModePtr = &speex_wb_mode; + _speexModePtr = &speex_wb_mode; + // _speexModePtr = &speex_wb_mode; // Init the decoder struct - speex_bits_init(&_speex_dec_bits); - _speex_dec_state = speex_decoder_init(_speexModePtr); + speex_bits_init (&_speex_dec_bits); + _speex_dec_state = speex_decoder_init (_speexModePtr); // Init the encoder struct - speex_bits_init(&_speex_enc_bits); - _speex_enc_state = speex_encoder_init(_speexModePtr); + speex_bits_init (&_speex_enc_bits); + _speex_enc_state = speex_encoder_init (_speexModePtr); - speex_encoder_ctl(_speex_enc_state,SPEEX_SET_SAMPLING_RATE,&_clockRate); + speex_encoder_ctl (_speex_enc_state,SPEEX_SET_SAMPLING_RATE,&_clockRate); + + speex_decoder_ctl (_speex_dec_state, SPEEX_GET_FRAME_SIZE, &_speex_frame_size); - speex_decoder_ctl(_speex_dec_state, SPEEX_GET_FRAME_SIZE, &_speex_frame_size); - #ifdef HAVE_SPEEXDSP_LIB int enable = 1; @@ -74,65 +75,62 @@ class Speex : public AudioCodec{ int complex = 10; int attenuation = -10; - speex_encoder_ctl(_speex_enc_state, SPEEX_SET_VAD, &enable); - speex_encoder_ctl(_speex_enc_state, SPEEX_SET_DTX, &enable); - speex_encoder_ctl(_speex_enc_state, SPEEX_SET_VBR_QUALITY, &quality); - speex_encoder_ctl(_speex_enc_state, SPEEX_SET_COMPLEXITY, &complex); + speex_encoder_ctl (_speex_enc_state, SPEEX_SET_VAD, &enable); + speex_encoder_ctl (_speex_enc_state, SPEEX_SET_DTX, &enable); + speex_encoder_ctl (_speex_enc_state, SPEEX_SET_VBR_QUALITY, &quality); + speex_encoder_ctl (_speex_enc_state, SPEEX_SET_COMPLEXITY, &complex); // Init the decoder struct - speex_decoder_ctl(_speex_dec_state, SPEEX_GET_FRAME_SIZE, &_speex_frame_size); + speex_decoder_ctl (_speex_dec_state, SPEEX_GET_FRAME_SIZE, &_speex_frame_size); // Init the preprocess struct - _preprocess_state = speex_preprocess_state_init(_speex_frame_size,_clockRate); - speex_preprocess_ctl(_preprocess_state, SPEEX_PREPROCESS_SET_DENOISE, &enable); - speex_preprocess_ctl(_preprocess_state, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &attenuation); - speex_preprocess_ctl(_preprocess_state, SPEEX_PREPROCESS_SET_VAD, &enable); - speex_preprocess_ctl(_preprocess_state, SPEEX_PREPROCESS_SET_AGC, &enable); + _preprocess_state = speex_preprocess_state_init (_speex_frame_size,_clockRate); + speex_preprocess_ctl (_preprocess_state, SPEEX_PREPROCESS_SET_DENOISE, &enable); + speex_preprocess_ctl (_preprocess_state, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &attenuation); + speex_preprocess_ctl (_preprocess_state, SPEEX_PREPROCESS_SET_VAD, &enable); + speex_preprocess_ctl (_preprocess_state, SPEEX_PREPROCESS_SET_AGC, &enable); #endif - + } - ~Speex() - { + ~Speex() { terminateSpeex(); } void terminateSpeex() { // Destroy the decoder struct - speex_bits_destroy(&_speex_dec_bits); - speex_decoder_destroy(_speex_dec_state); + speex_bits_destroy (&_speex_dec_bits); + speex_decoder_destroy (_speex_dec_state); _speex_dec_state = 0; // Destroy the encoder struct - speex_bits_destroy(&_speex_enc_bits); - speex_encoder_destroy(_speex_enc_state); + speex_bits_destroy (&_speex_enc_bits); + speex_encoder_destroy (_speex_enc_state); _speex_enc_state = 0; } - virtual int codecDecode (short *dst, unsigned char *src, unsigned int size) - { + virtual int codecDecode (short *dst, unsigned char *src, unsigned int size) { int ratio = 320 / _speex_frame_size; - speex_bits_read_from(&_speex_dec_bits, (char*)src, size); - speex_decode_int(_speex_dec_state, &_speex_dec_bits, dst); + speex_bits_read_from (&_speex_dec_bits, (char*) src, size); + speex_decode_int (_speex_dec_state, &_speex_dec_bits, dst); - return 2 * _speex_frame_size * ratio; + return 2 * _speex_frame_size * ratio; } - virtual int codecEncode (unsigned char *dst, short *src, unsigned int size) - { - speex_bits_reset(&_speex_enc_bits); + virtual int codecEncode (unsigned char *dst, short *src, unsigned int size) { + speex_bits_reset (&_speex_enc_bits); #ifdef HAVE_SPEEXDSP_LIB - - speex_preprocess_run(_preprocess_state, src); -#endif - - printf("Codec::codecEncode() size %i\n", size); - speex_encode_int(_speex_enc_state, src, &_speex_enc_bits); - int nbBytes = speex_bits_write(&_speex_enc_bits, (char*)dst, size); - printf("Codec::codecEncode() nbBytes %i\n", nbBytes); + + speex_preprocess_run (_preprocess_state, src); +#endif + + printf ("Codec::codecEncode() size %i\n", size); + speex_encode_int (_speex_enc_state, src, &_speex_enc_bits); + int nbBytes = speex_bits_write (&_speex_enc_bits, (char*) dst, size); + printf ("Codec::codecEncode() nbBytes %i\n", nbBytes); return nbBytes; } @@ -147,11 +145,13 @@ class Speex : public AudioCodec{ }; // the class factories -extern "C" AudioCodec* create() { - return new Speex(111); +extern "C" AudioCodec* create() +{ + return new Speex (111); } -extern "C" void destroy(AudioCodec* a) { +extern "C" void destroy (AudioCodec* a) +{ delete a; } diff --git a/sflphone-common/src/audio/codecs/ulaw.cpp b/sflphone-common/src/audio/codecs/ulaw.cpp index 588ff212ca..9b619c31ec 100644 --- a/sflphone-common/src/audio/codecs/ulaw.cpp +++ b/sflphone-common/src/audio/codecs/ulaw.cpp @@ -7,12 +7,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -23,100 +23,105 @@ #include "../common.h" #include "audiocodec.h" -class Ulaw : public AudioCodec { -public: - // 0 PCMU A 8000 1 [RFC3551] - Ulaw(int payload=0) - : AudioCodec(payload, "PCMU") - { - _clockRate = 8000; - _frameSize = 160; // samples, 20 ms at 8kHz - _channel = 1; - _bitrate = 64; - _bandwidth = 80; - } - - virtual int codecDecode (short *dst, unsigned char *src, unsigned int size) { - // _debug("Decoded by ulaw"); - int16* end = dst+size; - while(dst<end) - *dst++ = ULawDecode(*src++); - return size<<1; - } - - virtual int codecEncode (unsigned char *dst, short *src, unsigned int size) { - // _debug("Encoded by ulaw \n"); - size >>= 1; - uint8* end = dst+size; - while(dst<end) - *dst++ = ULawEncode(*src++); - return size; - } - - int ULawDecode(uint8 ulaw) - { - ulaw ^= 0xff; // u-law has all bits inverted for transmission - int linear = ulaw&0x0f; - linear <<= 3; - linear |= 0x84; // Set MSB (0x80) and a 'half' bit (0x04) to place PCM value in middle of range - - uint shift = ulaw>>4; - shift &= 7; - linear <<= shift; - linear -= 0x84; // Subract uLaw bias - - if(ulaw&0x80) - return -linear; - else - return linear; - } - - uint8 ULawEncode(int16 pcm16) - { - int p = pcm16; - uint u; // u-law value we are forming - - if(p<0) - { - p = ~p; - u = 0x80^0x10^0xff; // Sign bit = 1 (^0x10 because this will get inverted later) ^0xff ^0xff to invert final u-Law code - } - else{ - u = 0x00^0x10^0xff; // Sign bit = 0 (-0x10 because this amount extra will get added later) ^0xff to invert final u-Law code - } - - p += 0x84; // Add uLaw bias - - if(p>0x7f00) - p = 0x7f00; // Clip to 15 bits - // Calculate segment and interval numbers - p >>= 3; // Shift down to 13bit - if(p>=0x100) - { - p >>= 4; - u ^= 0x40; - } - if(p>=0x40) - { - p >>= 2; - u ^= 0x20; - } - if(p>=0x20) - { - p >>= 1; - u ^= 0x10; - } - u ^= p; // u now equal to encoded u-law value (with all bits inverted) - - return u; - } +class Ulaw : public AudioCodec +{ + + public: + // 0 PCMU A 8000 1 [RFC3551] + Ulaw (int payload=0) + : AudioCodec (payload, "PCMU") { + _clockRate = 8000; + _frameSize = 160; // samples, 20 ms at 8kHz + _channel = 1; + _bitrate = 64; + _bandwidth = 80; + } + + virtual int codecDecode (short *dst, unsigned char *src, unsigned int size) { + // _debug("Decoded by ulaw"); + int16* end = dst+size; + + while (dst<end) + *dst++ = ULawDecode (*src++); + + return size<<1; + } + + virtual int codecEncode (unsigned char *dst, short *src, unsigned int size) { + // _debug("Encoded by ulaw \n"); + size >>= 1; + uint8* end = dst+size; + + while (dst<end) + *dst++ = ULawEncode (*src++); + + return size; + } + + int ULawDecode (uint8 ulaw) { + ulaw ^= 0xff; // u-law has all bits inverted for transmission + int linear = ulaw&0x0f; + linear <<= 3; + linear |= 0x84; // Set MSB (0x80) and a 'half' bit (0x04) to place PCM value in middle of range + + uint shift = ulaw>>4; + shift &= 7; + linear <<= shift; + linear -= 0x84; // Subract uLaw bias + + if (ulaw&0x80) + return -linear; + else + return linear; + } + + uint8 ULawEncode (int16 pcm16) { + int p = pcm16; + uint u; // u-law value we are forming + + if (p<0) { + p = ~p; + u = 0x80^0x10^0xff; // Sign bit = 1 (^0x10 because this will get inverted later) ^0xff ^0xff to invert final u-Law code + } else { + u = 0x00^0x10^0xff; // Sign bit = 0 (-0x10 because this amount extra will get added later) ^0xff to invert final u-Law code + } + + p += 0x84; // Add uLaw bias + + if (p>0x7f00) + p = 0x7f00; // Clip to 15 bits + + // Calculate segment and interval numbers + p >>= 3; // Shift down to 13bit + + if (p>=0x100) { + p >>= 4; + u ^= 0x40; + } + + if (p>=0x40) { + p >>= 2; + u ^= 0x20; + } + + if (p>=0x20) { + p >>= 1; + u ^= 0x10; + } + + u ^= p; // u now equal to encoded u-law value (with all bits inverted) + + return u; + } }; // the class factories -extern "C" AudioCodec* create() { - return new Ulaw(0); +extern "C" AudioCodec* create() +{ + return new Ulaw (0); } -extern "C" void destroy(AudioCodec* a) { +extern "C" void destroy (AudioCodec* a) +{ delete a; } diff --git a/sflphone-common/src/audio/dtmf.cpp b/sflphone-common/src/audio/dtmf.cpp index c6ba907aae..22fc94b952 100644 --- a/sflphone-common/src/audio/dtmf.cpp +++ b/sflphone-common/src/audio/dtmf.cpp @@ -1,21 +1,21 @@ /* * Copyright (C) 2004-2006 Savoir-Faire Linux inc. * Author : Yan Morin <yan.morin@savoirfairelinux.com> - * Author : Laurielle Lea <laurielle.lea@savoirfairelinux.com> + * Author : Laurielle Lea <laurielle.lea@savoirfairelinux.com> * * Portions Copyright (c) 2000 Billy Biggs <bbiggs@div8.net> * Portions Copyright (c) 2004 Wirlab <kphone@wirlab.net> - * + * * 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 * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -23,56 +23,57 @@ #include "dtmf.h" -DTMF::DTMF (unsigned int sampleRate) -: currentTone(0), newTone(0), dtmfgenerator(sampleRate) +DTMF::DTMF (unsigned int sampleRate) + : currentTone (0), newTone (0), dtmfgenerator (sampleRate) { } -DTMF::~DTMF (void) +DTMF::~DTMF (void) { } -void -DTMF::startTone (char code) +void +DTMF::startTone (char code) { - newTone = code; + newTone = code; } -bool -DTMF::generateDTMF (SFLDataFormat* buffer, size_t n) +bool +DTMF::generateDTMF (SFLDataFormat* buffer, size_t n) { - if (!buffer) return false; + if (!buffer) return false; + + try { + if (currentTone != 0) { + // Currently generating a DTMF tone + if (currentTone == newTone) { + // Continue generating the same tone + dtmfgenerator.getNextSamples (buffer, n); + return true; + } else if (newTone != 0) { + // New tone requested + dtmfgenerator.getSamples (buffer, n, newTone); + currentTone = newTone; + return true; + } else { + // Stop requested + currentTone = newTone; + return false; + } + } else { + // Not generating any DTMF tone + if (newTone) { + // Requested to generate a DTMF tone + dtmfgenerator.getSamples (buffer, n, newTone); + currentTone = newTone; + return true; + } - try { - if (currentTone != 0) { - // Currently generating a DTMF tone - if (currentTone == newTone) { - // Continue generating the same tone - dtmfgenerator.getNextSamples(buffer, n); - return true; - } else if (newTone != 0) { - // New tone requested - dtmfgenerator.getSamples(buffer, n, newTone); - currentTone = newTone; - return true; - } else { - // Stop requested - currentTone = newTone; + return false; + } + } catch (DTMFException e) { + // invalid key return false; - } - } else { - // Not generating any DTMF tone - if (newTone) { - // Requested to generate a DTMF tone - dtmfgenerator.getSamples(buffer, n, newTone); - currentTone = newTone; - return true; - } - return false; } - } catch(DTMFException e) { - // invalid key - return false; - } } diff --git a/sflphone-common/src/audio/dtmfgenerator.cpp b/sflphone-common/src/audio/dtmfgenerator.cpp index f35f1e50ac..da6e7f0c1c 100644 --- a/sflphone-common/src/audio/dtmfgenerator.cpp +++ b/sflphone-common/src/audio/dtmfgenerator.cpp @@ -1,7 +1,7 @@ /* * Copyright (C) 2004-2005 Savoir-Faire Linux inc. * Author: Yan Morin <yan.morin@savoirfairelinux.com> - * Author: Laurielle Lea <laurielle.lea@savoirfairelinux.com> + * Author: Laurielle Lea <laurielle.lea@savoirfairelinux.com> * * Portions (c) 2003 iptel.org * @@ -9,12 +9,12 @@ * under the terms of the GNU Library General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at your * option) any later version. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public * License for more details. - * + * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, @@ -32,26 +32,26 @@ * Tone frequencies */ const DTMFGenerator::DTMFTone DTMFGenerator::tones[NUM_TONES] = { - {'0', 941, 1336}, - {'1', 697, 1209}, - {'2', 697, 1336}, - {'3', 697, 1477}, - {'4', 770, 1209}, - {'5', 770, 1336}, - {'6', 770, 1477}, - {'7', 852, 1209}, - {'8', 852, 1336}, - {'9', 852, 1477}, - {'A', 697, 1633}, - {'B', 770, 1633}, - {'C', 852, 1633}, - {'D', 941, 1633}, - {'*', 941, 1209}, - {'#', 941, 1477} + {'0', 941, 1336}, + {'1', 697, 1209}, + {'2', 697, 1336}, + {'3', 697, 1477}, + {'4', 770, 1209}, + {'5', 770, 1336}, + {'6', 770, 1477}, + {'7', 852, 1209}, + {'8', 852, 1336}, + {'9', 852, 1477}, + {'A', 697, 1633}, + {'B', 770, 1633}, + {'C', 852, 1633}, + {'D', 941, 1633}, + {'*', 941, 1209}, + {'#', 941, 1477} }; -DTMFException::DTMFException(const char* _reason) throw() : reason(_reason) +DTMFException::DTMFException (const char* _reason) throw() : reason (_reason) { } @@ -62,7 +62,7 @@ DTMFException::~DTMFException() throw() const char* DTMFException::what() const throw() { - return reason; + return reason; } @@ -70,64 +70,121 @@ const char* DTMFException::what() const throw() /* * Initialize the generator */ -DTMFGenerator::DTMFGenerator(unsigned int sampleRate) : state(), _sampleRate(sampleRate), tone("", sampleRate) +DTMFGenerator::DTMFGenerator (unsigned int sampleRate) : state(), _sampleRate (sampleRate), tone ("", sampleRate) { - state.offset = 0; - state.sample = 0; + state.offset = 0; + state.sample = 0; - for(int i = 0; i < NUM_TONES; i++) { - samples[i] = generateSample(i); - } + for (int i = 0; i < NUM_TONES; i++) { + samples[i] = generateSample (i); + } } - -DTMFGenerator::~DTMFGenerator() { - for(int i = 0; i < NUM_TONES; i++) { - delete[] samples[i]; samples[i] = NULL; - } + +DTMFGenerator::~DTMFGenerator() +{ + for (int i = 0; i < NUM_TONES; i++) { + delete[] samples[i]; + samples[i] = NULL; + } } /* * Get n samples of the signal of code code */ -void DTMFGenerator::getSamples(SFLDataFormat* buffer, size_t n, unsigned char code) throw(DTMFException) { - size_t i; - if (!buffer) { - throw DTMFException("Invalid parameter value"); - } - - switch(code) { - case '0': state.sample = samples[0]; break; - case '1': state.sample = samples[1]; break; - case '2': state.sample = samples[2]; break; - case '3': state.sample = samples[3]; break; - case '4': state.sample = samples[4]; break; - case '5': state.sample = samples[5]; break; - case '6': state.sample = samples[6]; break; - case '7': state.sample = samples[7]; break; - case '8': state.sample = samples[8]; break; - case '9': state.sample = samples[9]; break; - case 'A': - case 'a': state.sample = samples[10]; break; - case 'B': - case 'b': state.sample = samples[11]; break; - case 'C': - case 'c': state.sample = samples[12]; break; - case 'D': - case 'd': state.sample = samples[13]; break; - case '*': state.sample = samples[14]; break; - case '#': state.sample = samples[15]; break; - default: - throw DTMFException("Invalid code"); - return; - break; - } - - for(i = 0; i < n; i++) { - buffer[i] = state.sample[i % _sampleRate]; - } - - state.offset = i % _sampleRate; +void DTMFGenerator::getSamples (SFLDataFormat* buffer, size_t n, unsigned char code) throw (DTMFException) +{ + size_t i; + + if (!buffer) { + throw DTMFException ("Invalid parameter value"); + } + + switch (code) { + + case '0': + state.sample = samples[0]; + break; + + case '1': + state.sample = samples[1]; + break; + + case '2': + state.sample = samples[2]; + break; + + case '3': + state.sample = samples[3]; + break; + + case '4': + state.sample = samples[4]; + break; + + case '5': + state.sample = samples[5]; + break; + + case '6': + state.sample = samples[6]; + break; + + case '7': + state.sample = samples[7]; + break; + + case '8': + state.sample = samples[8]; + break; + + case '9': + state.sample = samples[9]; + break; + + case 'A': + + case 'a': + state.sample = samples[10]; + break; + + case 'B': + + case 'b': + state.sample = samples[11]; + break; + + case 'C': + + case 'c': + state.sample = samples[12]; + break; + + case 'D': + + case 'd': + state.sample = samples[13]; + break; + + case '*': + state.sample = samples[14]; + break; + + case '#': + state.sample = samples[15]; + break; + + default: + throw DTMFException ("Invalid code"); + return; + break; + } + + for (i = 0; i < n; i++) { + buffer[i] = state.sample[i % _sampleRate]; + } + + state.offset = i % _sampleRate; } @@ -135,45 +192,47 @@ void DTMFGenerator::getSamples(SFLDataFormat* buffer, size_t n, unsigned char co * Get next n samples (continues where previous call to * genSample or genNextSamples stopped */ -void DTMFGenerator::getNextSamples(SFLDataFormat* buffer, size_t n) throw(DTMFException) +void DTMFGenerator::getNextSamples (SFLDataFormat* buffer, size_t n) throw (DTMFException) { - size_t i; + size_t i; - if (!buffer) { - throw DTMFException("Invalid parameter"); - } + if (!buffer) { + throw DTMFException ("Invalid parameter"); + } - if (state.sample == 0) { - throw DTMFException("DTMF generator not initialized"); - } + if (state.sample == 0) { + throw DTMFException ("DTMF generator not initialized"); + } - for(i = 0; i < n; i++) { - buffer[i] = state.sample[(state.offset + i) % _sampleRate]; - } - - state.offset = (state.offset + i) % _sampleRate; + for (i = 0; i < n; i++) { + buffer[i] = state.sample[ (state.offset + i) % _sampleRate]; + } + + state.offset = (state.offset + i) % _sampleRate; } /* * Generate a tone sample */ -SFLDataFormat* DTMFGenerator::generateSample(unsigned char code) throw (DTMFException) { - SFLDataFormat* ptr; - - try { - ptr = new SFLDataFormat[_sampleRate]; - if (!ptr) { - throw new DTMFException("No memory left"); - return 0; - } - - tone.genSin(ptr, tones[code].higher, tones[code].lower, _sampleRate); - - return ptr; - } catch(...) { - throw new DTMFException("No memory left"); - return 0; - } +SFLDataFormat* DTMFGenerator::generateSample (unsigned char code) throw (DTMFException) +{ + SFLDataFormat* ptr; + + try { + ptr = new SFLDataFormat[_sampleRate]; + + if (!ptr) { + throw new DTMFException ("No memory left"); + return 0; + } + + tone.genSin (ptr, tones[code].higher, tones[code].lower, _sampleRate); + + return ptr; + } catch (...) { + throw new DTMFException ("No memory left"); + return 0; + } } diff --git a/sflphone-common/src/audio/pulselayer.cpp b/sflphone-common/src/audio/pulselayer.cpp index 0e044e2001..9d586d2041 100644 --- a/sflphone-common/src/audio/pulselayer.cpp +++ b/sflphone-common/src/audio/pulselayer.cpp @@ -23,148 +23,164 @@ int framesPerBuffer = 2048; int PulseLayer::streamState; -static void audioCallback ( pa_stream* s, size_t bytes, void* userdata ) -{ - assert( s && bytes ); - assert( bytes > 0 ); - static_cast<PulseLayer*>(userdata)->processData(); +static void audioCallback (pa_stream* s, size_t bytes, void* userdata) +{ + assert (s && bytes); + assert (bytes > 0); + static_cast<PulseLayer*> (userdata)->processData(); } - PulseLayer::PulseLayer(ManagerImpl* manager) - : AudioLayer( manager , PULSEAUDIO ) - , context(NULL) - , m(NULL) - , playback() - , record() +PulseLayer::PulseLayer (ManagerImpl* manager) + : AudioLayer (manager , PULSEAUDIO) + , context (NULL) + , m (NULL) + , playback() + , record() { PulseLayer::streamState = 0; - _debug("PulseLayer::Pulse audio constructor: Create context\n"); - + _debug ("PulseLayer::Pulse audio constructor: Create context\n"); + } // Destructor -PulseLayer::~PulseLayer (void) -{ +PulseLayer::~PulseLayer (void) +{ closeLayer (); - // pa_context_disconnect( context ); + // pa_context_disconnect( context ); // pa_context_unref( context ); } bool -PulseLayer::closeLayer( void ) -{ - _debug("PulseLayer::closeLayer :: Destroy pulselayer\n"); +PulseLayer::closeLayer (void) +{ + _debug ("PulseLayer::closeLayer :: Destroy pulselayer\n"); - playback->disconnectStream(); + playback->disconnectStream(); record->disconnectStream(); - while(PulseLayer::streamState != 2); - PulseLayer::streamState = 0; + while (PulseLayer::streamState != 2); + + PulseLayer::streamState = 0; //TODO Remove this ugly hack - sleep(2); + sleep (2); + + pa_context_disconnect (context); - pa_context_disconnect( context ); - pa_context_unref( context ); + pa_context_unref (context); return true; } void -PulseLayer::connectPulseAudioServer( void ) +PulseLayer::connectPulseAudioServer (void) { - _debug("PulseLayer::connectPulseAudioServer \n"); - pa_context_flags_t flag = PA_CONTEXT_NOAUTOSPAWN ; + _debug ("PulseLayer::connectPulseAudioServer \n"); + pa_context_flags_t flag = PA_CONTEXT_NOAUTOSPAWN ; - pa_threaded_mainloop_lock( m ); + pa_threaded_mainloop_lock (m); - _debug("Connect the context to the server\n"); - pa_context_connect( context, NULL , flag , NULL ); + _debug ("Connect the context to the server\n"); + pa_context_connect (context, NULL , flag , NULL); - pa_context_set_state_callback(context, context_state_callback, this); - pa_threaded_mainloop_wait( m ); + pa_context_set_state_callback (context, context_state_callback, this); + pa_threaded_mainloop_wait (m); // Run the main loop - if( pa_context_get_state( context ) != PA_CONTEXT_READY ){ - _debug("Error connecting to pulse audio server\n"); - pa_threaded_mainloop_unlock( m ); + + if (pa_context_get_state (context) != PA_CONTEXT_READY) { + _debug ("Error connecting to pulse audio server\n"); + pa_threaded_mainloop_unlock (m); } - pa_threaded_mainloop_unlock( m ); + pa_threaded_mainloop_unlock (m); + //serverinfo(); //muteAudioApps(99); - _debug("Context creation done\n"); + _debug ("Context creation done\n"); } -void PulseLayer::context_state_callback( pa_context* c, void* user_data ) +void PulseLayer::context_state_callback (pa_context* c, void* user_data) { - _debug("PulseLayer::context_state_callback ::The state of the context changed\n"); - PulseLayer* pulse = (PulseLayer*)user_data; - assert(c && pulse->m); - switch(pa_context_get_state(c)){ + _debug ("PulseLayer::context_state_callback ::The state of the context changed\n"); + PulseLayer* pulse = (PulseLayer*) user_data; + assert (c && pulse->m); + + switch (pa_context_get_state (c)) { + case PA_CONTEXT_CONNECTING: + case PA_CONTEXT_AUTHORIZING: + case PA_CONTEXT_SETTING_NAME: - _debug("Waiting....\n"); + _debug ("Waiting....\n"); break; + case PA_CONTEXT_READY: - pulse->createStreams( c ); - _debug("Connection to PulseAudio server established\n"); - + pulse->createStreams (c); + _debug ("Connection to PulseAudio server established\n"); + break; + case PA_CONTEXT_TERMINATED: - _debug("Context terminated\n"); + _debug ("Context terminated\n"); break; + case PA_CONTEXT_FAILED: + default: - _debug(" Error : %s\n" , pa_strerror(pa_context_errno(c))); + _debug (" Error : %s\n" , pa_strerror (pa_context_errno (c))); pulse->disconnectPulseAudioServer(); - exit(0); + exit (0); break; } } -bool PulseLayer::disconnectPulseAudioServer( void ) +bool PulseLayer::disconnectPulseAudioServer (void) { - _debug(" PulseLayer::disconnectPulseAudioServer( void ) \n"); + _debug (" PulseLayer::disconnectPulseAudioServer( void ) \n"); - if( playback ){ - // playback->disconnectStream(); - delete playback; playback=NULL; + if (playback) { + // playback->disconnectStream(); + delete playback; + playback=NULL; } - if( record ){ - // record->disconnectStream(); - delete record; record=NULL; + + if (record) { + // record->disconnectStream(); + delete record; + record=NULL; } + if (!playback && !record) - return true; + return true; else - return false; + return false; } -bool PulseLayer::createStreams( pa_context* c ) +bool PulseLayer::createStreams (pa_context* c) { - _debug("PulseLayer::createStreams \n"); - - playback = new AudioStream(c, PLAYBACK_STREAM, PLAYBACK_STREAM_NAME, _manager->getSpkrVolume()); + _debug ("PulseLayer::createStreams \n"); + + playback = new AudioStream (c, PLAYBACK_STREAM, PLAYBACK_STREAM_NAME, _manager->getSpkrVolume()); playback->connectStream(); - pa_stream_set_write_callback( playback->pulseStream(), audioCallback, this); + pa_stream_set_write_callback (playback->pulseStream(), audioCallback, this); // pa_stream_set_overflow_callback( playback->pulseStream() , overflow , this); // pa_stream_set_suspended_callback( playback->pulseStream(), stream_suspended_callback, this); - - record = new AudioStream(c, CAPTURE_STREAM, CAPTURE_STREAM_NAME , _manager->getMicVolume()); + + record = new AudioStream (c, CAPTURE_STREAM, CAPTURE_STREAM_NAME , _manager->getMicVolume()); record->connectStream(); - pa_stream_set_read_callback( record->pulseStream() , audioCallback, this); + pa_stream_set_read_callback (record->pulseStream() , audioCallback, this); // pa_stream_set_underflow_callback( record->pulseStream() , underflow , this); // pa_stream_set_suspended_callback(record->pulseStream(), stream_suspended_callback, this); - pa_threaded_mainloop_signal(m , 0); + pa_threaded_mainloop_signal (m , 0); isCorked = true; @@ -172,143 +188,142 @@ bool PulseLayer::createStreams( pa_context* c ) } -bool PulseLayer::openDevice(int indexIn UNUSED, int indexOut UNUSED, int sampleRate, int frameSize , int stream UNUSED, std::string plugin UNUSED) +bool PulseLayer::openDevice (int indexIn UNUSED, int indexOut UNUSED, int sampleRate, int frameSize , int stream UNUSED, std::string plugin UNUSED) { - _debug("PulseLayer::openDevice \n"); + _debug ("PulseLayer::openDevice \n"); _sampleRate = sampleRate; - _frameSize = frameSize; + _frameSize = frameSize; m = pa_threaded_mainloop_new(); - assert(m); + assert (m); - if( pa_threaded_mainloop_start( m ) < 0 ){ - _debug("Failed starting the mainloop\n"); + if (pa_threaded_mainloop_start (m) < 0) { + _debug ("Failed starting the mainloop\n"); } // Instanciate a context - if( !(context = pa_context_new( pa_threaded_mainloop_get_api( m ) , "SFLphone" ))) - _debug("Error while creating the context\n"); + if (! (context = pa_context_new (pa_threaded_mainloop_get_api (m) , "SFLphone"))) + _debug ("Error while creating the context\n"); - assert(context); + assert (context); connectPulseAudioServer(); - + // startStream(); - _debug("Connection Done!! \n"); + _debug ("Connection Done!! \n"); } -void PulseLayer::closeCaptureStream( void ) +void PulseLayer::closeCaptureStream (void) { } -void PulseLayer::closePlaybackStream( void ) -{ +void PulseLayer::closePlaybackStream (void) +{ } int PulseLayer::canGetMic() { - if( record ) + if (record) return _micRingBuffer.AvailForGet(); else return 0; } -int PulseLayer::getMic(void *buffer, int toCopy) +int PulseLayer::getMic (void *buffer, int toCopy) { - if( record ){ - return _micRingBuffer.Get(buffer, toCopy, 100); - } - else + if (record) { + return _micRingBuffer.Get (buffer, toCopy, 100); + } else return 0; } -void PulseLayer::startStream (void) +void PulseLayer::startStream (void) { - _debug("PulseLayer::Start stream\n"); - _urgentRingBuffer.flush(); - _micRingBuffer.flush(); - _voiceRingBuffer.flush(); + _debug ("PulseLayer::Start stream\n"); + _urgentRingBuffer.flush(); + _micRingBuffer.flush(); + _voiceRingBuffer.flush(); + + pa_threaded_mainloop_lock (m); - pa_threaded_mainloop_lock(m); - - pa_stream_cork( playback->pulseStream(), 0, NULL, NULL); - pa_stream_cork( record->pulseStream(), 0, NULL, NULL); - - pa_threaded_mainloop_unlock(m); + pa_stream_cork (playback->pulseStream(), 0, NULL, NULL); + pa_stream_cork (record->pulseStream(), 0, NULL, NULL); - isCorked = false; + pa_threaded_mainloop_unlock (m); + + isCorked = false; } - void -PulseLayer::stopStream (void) +void +PulseLayer::stopStream (void) { - _debug("PulseLayer::Stop stream\n"); - pa_stream_flush( playback->pulseStream(), NULL, NULL ); - pa_stream_flush( record->pulseStream(), NULL, NULL ); - - flushMic(); - flushMain(); - flushUrgent(); + _debug ("PulseLayer::Stop stream\n"); + pa_stream_flush (playback->pulseStream(), NULL, NULL); + pa_stream_flush (record->pulseStream(), NULL, NULL); - pa_stream_cork( playback->pulseStream(), 1, NULL, NULL); - pa_stream_cork( record->pulseStream(), 1, NULL, NULL); + flushMic(); + flushMain(); + flushUrgent(); + + pa_stream_cork (playback->pulseStream(), 1, NULL, NULL); + pa_stream_cork (record->pulseStream(), 1, NULL, NULL); + + isCorked = true; - isCorked = true; - } -void PulseLayer::underflow ( pa_stream* s UNUSED, void* userdata UNUSED ) -{ - _debug("PulseLayer::Buffer Underflow\n"); +void PulseLayer::underflow (pa_stream* s UNUSED, void* userdata UNUSED) +{ + _debug ("PulseLayer::Buffer Underflow\n"); } -void PulseLayer::overflow ( pa_stream* s, void* userdata UNUSED ) -{ +void PulseLayer::overflow (pa_stream* s, void* userdata UNUSED) +{ //PulseLayer* pulse = (PulseLayer*) userdata; - pa_stream_drop( s ); - pa_stream_trigger( s, NULL, NULL); + pa_stream_drop (s); + pa_stream_trigger (s, NULL, NULL); } -void PulseLayer::stream_suspended_callback(pa_stream *s, void *userdata UNUSED ) +void PulseLayer::stream_suspended_callback (pa_stream *s, void *userdata UNUSED) { - + } -void PulseLayer::processData( void ) +void PulseLayer::processData (void) { - // Handle the mic - // We check if the stream is ready - if( (record->pulseStream()) && (pa_stream_get_state( record->pulseStream()) == PA_STREAM_READY)) - readFromMic(); + // Handle the mic + // We check if the stream is ready + if ( (record->pulseStream()) && (pa_stream_get_state (record->pulseStream()) == PA_STREAM_READY)) + readFromMic(); + + // _debug("PulseLayer::processData() playback->pulseStream() \n"); - // _debug("PulseLayer::processData() playback->pulseStream() \n"); - - // Handle the data for the speakers - if( (playback->pulseStream()) && (pa_stream_get_state( playback->pulseStream()) == PA_STREAM_READY)){ + // Handle the data for the speakers + if ( (playback->pulseStream()) && (pa_stream_get_state (playback->pulseStream()) == PA_STREAM_READY)) { // If the playback buffer is full, we don't overflow it; wait for it to have free space - if( pa_stream_writable_size(playback->pulseStream()) == 0 ) + if (pa_stream_writable_size (playback->pulseStream()) == 0) return; - + writeToSpeaker(); } } -void PulseLayer::writeToSpeaker( void ) -{ +void PulseLayer::writeToSpeaker (void) +{ /** Bytes available in the urgent ringbuffer ( reserved for DTMF ) */ - int urgentAvail; + int urgentAvail; /** Bytes available in the regular ringbuffer ( reserved for voice ) */ - int normalAvail; + int normalAvail; int toGet; int toPlay; @@ -316,104 +331,106 @@ void PulseLayer::writeToSpeaker( void ) urgentAvail = _urgentRingBuffer.AvailForGet(); if (urgentAvail > 0) { - // Urgent data (dtmf, incoming call signal) come first. + // Urgent data (dtmf, incoming call signal) come first. //_debug("Play urgent!: %i\e" , urgentAvail); - toGet = (urgentAvail < (int)(framesPerBuffer * sizeof(SFLDataFormat))) ? urgentAvail : framesPerBuffer * sizeof(SFLDataFormat); - out = (SFLDataFormat*)pa_xmalloc(toGet * sizeof(SFLDataFormat) ); - _urgentRingBuffer.Get(out, toGet, 100); - pa_stream_write( playback->pulseStream() , out , toGet , pa_xfree, 0 , PA_SEEK_RELATIVE); + toGet = (urgentAvail < (int) (framesPerBuffer * sizeof (SFLDataFormat))) ? urgentAvail : framesPerBuffer * sizeof (SFLDataFormat); + out = (SFLDataFormat*) pa_xmalloc (toGet * sizeof (SFLDataFormat)); + _urgentRingBuffer.Get (out, toGet, 100); + pa_stream_write (playback->pulseStream() , out , toGet , pa_xfree, 0 , PA_SEEK_RELATIVE); // Consume the regular one as well (same amount of bytes) - _voiceRingBuffer.Discard(toGet); - } - else - { + _voiceRingBuffer.Discard (toGet); + } else { AudioLoop* tone = _manager->getTelephoneTone(); - if ( tone != 0) { + + if (tone != 0) { toGet = framesPerBuffer; - out = (SFLDataFormat*)pa_xmalloc(toGet * sizeof(SFLDataFormat) ); - tone->getNext(out, toGet , 100); - pa_stream_write( playback->pulseStream() , out , toGet * sizeof(SFLDataFormat) , pa_xfree, 0 , PA_SEEK_RELATIVE); - } - if ( (tone=_manager->getTelephoneFile()) != 0 ) { + out = (SFLDataFormat*) pa_xmalloc (toGet * sizeof (SFLDataFormat)); + tone->getNext (out, toGet , 100); + pa_stream_write (playback->pulseStream() , out , toGet * sizeof (SFLDataFormat) , pa_xfree, 0 , PA_SEEK_RELATIVE); + } + + if ( (tone=_manager->getTelephoneFile()) != 0) { toGet = framesPerBuffer; - toPlay = ( (int)(toGet * sizeof(SFLDataFormat)) > framesPerBuffer )? framesPerBuffer : toGet * sizeof(SFLDataFormat) ; - out = (SFLDataFormat*)pa_xmalloc(toPlay); - tone->getNext(out, toPlay/2 , 100); - pa_stream_write( playback->pulseStream() , out , toPlay , pa_xfree, 0 , PA_SEEK_RELATIVE) ; - } - else { - out = (SFLDataFormat*)pa_xmalloc(framesPerBuffer * sizeof(SFLDataFormat)); + toPlay = ( (int) (toGet * sizeof (SFLDataFormat)) > framesPerBuffer) ? framesPerBuffer : toGet * sizeof (SFLDataFormat) ; + out = (SFLDataFormat*) pa_xmalloc (toPlay); + tone->getNext (out, toPlay/2 , 100); + pa_stream_write (playback->pulseStream() , out , toPlay , pa_xfree, 0 , PA_SEEK_RELATIVE) ; + } else { + out = (SFLDataFormat*) pa_xmalloc (framesPerBuffer * sizeof (SFLDataFormat)); normalAvail = _voiceRingBuffer.AvailForGet(); - toGet = (normalAvail < (int)(framesPerBuffer * sizeof(SFLDataFormat))) ? normalAvail : framesPerBuffer * sizeof(SFLDataFormat); + toGet = (normalAvail < (int) (framesPerBuffer * sizeof (SFLDataFormat))) ? normalAvail : framesPerBuffer * sizeof (SFLDataFormat); + if (toGet) { - _voiceRingBuffer.Get(out, toGet, 100); - _voiceRingBuffer.Discard(toGet); - } - else { - bzero(out, framesPerBuffer * sizeof(SFLDataFormat)); + _voiceRingBuffer.Get (out, toGet, 100); + _voiceRingBuffer.Discard (toGet); + } else { + bzero (out, framesPerBuffer * sizeof (SFLDataFormat)); } - pa_stream_write( playback->pulseStream() , out , toGet , NULL, 0 , PA_SEEK_RELATIVE); - pa_xfree(out); + pa_stream_write (playback->pulseStream() , out , toGet , NULL, 0 , PA_SEEK_RELATIVE); + + pa_xfree (out); } } } -void PulseLayer::readFromMic( void ) +void PulseLayer::readFromMic (void) { const char* data; size_t r; - if( pa_stream_peek( record->pulseStream() , (const void**)&data , &r ) < 0 || !data ){ + if (pa_stream_peek (record->pulseStream() , (const void**) &data , &r) < 0 || !data) { //_debug("pa_stream_peek() failed: %s\n" , pa_strerror( pa_context_errno( context) )); } - if( data != 0 ){ - _micRingBuffer.Put( (void*)data ,r, 100); + if (data != 0) { + _micRingBuffer.Put ( (void*) data ,r, 100); } - if( pa_stream_drop( record->pulseStream() ) < 0 ) { + if (pa_stream_drop (record->pulseStream()) < 0) { //_debug("pa_stream_drop() failed: %s\n" , pa_strerror( pa_context_errno( context) )); } } -static void retrieve_server_info(pa_context *c UNUSED, const pa_server_info *i, void *userdata UNUSED) +static void retrieve_server_info (pa_context *c UNUSED, const pa_server_info *i, void *userdata UNUSED) { - _debug("Server Info: Process owner : %s\n" , i->user_name); - _debug("\t\tServer name : %s - Server version = %s\n" , i->server_name, i->server_version); - _debug("\t\tDefault sink name : %s\n" , i->default_sink_name); - _debug("\t\tDefault source name : %s\n" , i->default_source_name); + _debug ("Server Info: Process owner : %s\n" , i->user_name); + _debug ("\t\tServer name : %s - Server version = %s\n" , i->server_name, i->server_version); + _debug ("\t\tDefault sink name : %s\n" , i->default_sink_name); + _debug ("\t\tDefault source name : %s\n" , i->default_source_name); } -static void reduce_sink_list_cb(pa_context *c UNUSED, const pa_sink_input_info *i, int eol, void *userdata) +static void reduce_sink_list_cb (pa_context *c UNUSED, const pa_sink_input_info *i, int eol, void *userdata) { PulseLayer* pulse = (PulseLayer*) userdata; - if( !eol ){ - //_debug("Sink Info: index : %i\n" , i->index); - //_debug("\t\tClient : %i\n" , i->client); - //_debug("\t\tVolume : %i\n" , i->volume.values[0]); - //_debug("\t\tChannels : %i\n" , i->volume.channels); - if( strcmp( i->name , PLAYBACK_STREAM_NAME ) != 0) - pulse->setSinkVolume( i->index , i->volume.channels, 10 ); - } + + if (!eol) { + //_debug("Sink Info: index : %i\n" , i->index); + //_debug("\t\tClient : %i\n" , i->client); + //_debug("\t\tVolume : %i\n" , i->volume.values[0]); + //_debug("\t\tChannels : %i\n" , i->volume.channels); + if (strcmp (i->name , PLAYBACK_STREAM_NAME) != 0) + pulse->setSinkVolume (i->index , i->volume.channels, 10); + } } -static void restore_sink_list_cb(pa_context *c UNUSED, const pa_sink_input_info *i, int eol, void *userdata) +static void restore_sink_list_cb (pa_context *c UNUSED, const pa_sink_input_info *i, int eol, void *userdata) { PulseLayer* pulse = (PulseLayer*) userdata; - if( !eol ){ - //_debug("Sink Info: index : %i\n" , i->index); - //_debug("\t\tSink name : -%s-\n" , i->name); - //_debug("\t\tClient : %i\n" , i->client); - //_debug("\t\tVolume : %i\n" , i->volume.values[0]); - //_debug("\t\tChannels : %i\n" , i->volume.channels); - if( strcmp( i->name , PLAYBACK_STREAM_NAME ) != 0) - pulse->setSinkVolume( i->index , i->volume.channels, 100); - } + + if (!eol) { + //_debug("Sink Info: index : %i\n" , i->index); + //_debug("\t\tSink name : -%s-\n" , i->name); + //_debug("\t\tClient : %i\n" , i->client); + //_debug("\t\tVolume : %i\n" , i->volume.values[0]); + //_debug("\t\tChannels : %i\n" , i->volume.channels); + if (strcmp (i->name , PLAYBACK_STREAM_NAME) != 0) + pulse->setSinkVolume (i->index , i->volume.channels, 100); + } } -static void set_playback_volume_cb(pa_context *c UNUSED, const pa_sink_input_info *i, int eol, void *userdata) +static void set_playback_volume_cb (pa_context *c UNUSED, const pa_sink_input_info *i, int eol, void *userdata) { PulseLayer* pulse; int volume; @@ -421,13 +438,13 @@ static void set_playback_volume_cb(pa_context *c UNUSED, const pa_sink_input_inf pulse = (PulseLayer*) userdata; volume = pulse->getSpkrVolume(); - if( !eol ){ - if( strcmp( i->name , PLAYBACK_STREAM_NAME ) == 0) - pulse->setSinkVolume( i->index , i->volume.channels, volume ); - } + if (!eol) { + if (strcmp (i->name , PLAYBACK_STREAM_NAME) == 0) + pulse->setSinkVolume (i->index , i->volume.channels, volume); + } } -static void set_capture_volume_cb(pa_context *c UNUSED, const pa_source_output_info *i, int eol, void *userdata) +static void set_capture_volume_cb (pa_context *c UNUSED, const pa_source_output_info *i, int eol, void *userdata) { PulseLayer* pulse; int volume; @@ -435,65 +452,65 @@ static void set_capture_volume_cb(pa_context *c UNUSED, const pa_source_output_i pulse = (PulseLayer*) userdata; volume = pulse->getMicVolume(); - if( !eol ){ - if( strcmp( i->name , CAPTURE_STREAM_NAME ) == 0) - pulse->setSourceVolume( i->index , i->channel_map.channels, volume ); - } + if (!eol) { + if (strcmp (i->name , CAPTURE_STREAM_NAME) == 0) + pulse->setSourceVolume (i->index , i->channel_map.channels, volume); + } } - void -PulseLayer::reducePulseAppsVolume( void ) +void +PulseLayer::reducePulseAppsVolume (void) { - pa_context_get_sink_input_info_list( context , reduce_sink_list_cb , this ); + pa_context_get_sink_input_info_list (context , reduce_sink_list_cb , this); } - void -PulseLayer::restorePulseAppsVolume( void ) +void +PulseLayer::restorePulseAppsVolume (void) { - pa_context_get_sink_input_info_list( context , restore_sink_list_cb , this ); + pa_context_get_sink_input_info_list (context , restore_sink_list_cb , this); } - void -PulseLayer::serverinfo( void ) +void +PulseLayer::serverinfo (void) { - pa_context_get_server_info( context , retrieve_server_info , NULL ); + pa_context_get_server_info (context , retrieve_server_info , NULL); } -void PulseLayer::setSinkVolume( int index, int channels, int volume ) +void PulseLayer::setSinkVolume (int index, int channels, int volume) { pa_cvolume cvolume; - pa_volume_t vol = PA_VOLUME_NORM * ((double)volume / 100) ; + pa_volume_t vol = PA_VOLUME_NORM * ( (double) volume / 100) ; - pa_cvolume_set( &cvolume , channels , vol); - _debug("Set sink volume of index %i\n" , index); - pa_context_set_sink_input_volume( context, index, &cvolume, NULL, NULL) ; + pa_cvolume_set (&cvolume , channels , vol); + _debug ("Set sink volume of index %i\n" , index); + pa_context_set_sink_input_volume (context, index, &cvolume, NULL, NULL) ; } -void PulseLayer::setSourceVolume( int index, int channels, int volume ) +void PulseLayer::setSourceVolume (int index, int channels, int volume) { pa_cvolume cvolume; - pa_volume_t vol = PA_VOLUME_NORM * ((double)volume / 100) ; + pa_volume_t vol = PA_VOLUME_NORM * ( (double) volume / 100) ; - pa_cvolume_set( &cvolume , channels , vol); - _debug("Set source volume of index %i\n" , index); - pa_context_set_source_volume_by_index(context, index, &cvolume, NULL, NULL); + pa_cvolume_set (&cvolume , channels , vol); + _debug ("Set source volume of index %i\n" , index); + pa_context_set_source_volume_by_index (context, index, &cvolume, NULL, NULL); } -void PulseLayer::setPlaybackVolume( int volume ) +void PulseLayer::setPlaybackVolume (int volume) { - setSpkrVolume( volume ); - pa_context_get_sink_input_info_list( context , set_playback_volume_cb , this ); + setSpkrVolume (volume); + pa_context_get_sink_input_info_list (context , set_playback_volume_cb , this); } -void PulseLayer::setCaptureVolume( int volume ) +void PulseLayer::setCaptureVolume (int volume) { - setMicVolume( volume ); - pa_context_get_source_output_info_list( context , set_capture_volume_cb , this ); + setMicVolume (volume); + pa_context_get_source_output_info_list (context , set_capture_volume_cb , this); } diff --git a/sflphone-common/src/audio/ringbuffer.cpp b/sflphone-common/src/audio/ringbuffer.cpp index 52317ffffb..991ad2103a 100644 --- a/sflphone-common/src/audio/ringbuffer.cpp +++ b/sflphone-common/src/audio/ringbuffer.cpp @@ -1,179 +1,208 @@ /* * Copyright (C) 2004, 2005, 2006 Savoir-Faire Linux inc. * Author: Yan Morin <yan.morin@savoirfairelinux.com> - * Author: Laurielle Lea <laurielle.lea@savoirfairelinux.com> + * Author: Laurielle Lea <laurielle.lea@savoirfairelinux.com> * * Portions (c) Dominic Mazzoni (Audacity) - * + * * 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 * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <assert.h> -#include <stdlib.h> -#include <string.h> +#include <stdlib.h> +#include <string.h> #include "ringbuffer.h" #include "../global.h" - + #define MIN_BUFFER_SIZE 1280 // Create a ring buffer with 'size' bytes -RingBuffer::RingBuffer(int size): mStart( 0 ), mEnd( 0 ) - , mBufferSize( size > MIN_BUFFER_SIZE ? size : MIN_BUFFER_SIZE ) - , mBuffer(NULL) +RingBuffer::RingBuffer (int size) : mStart (0), mEnd (0) + , mBufferSize (size > MIN_BUFFER_SIZE ? size : MIN_BUFFER_SIZE) + , mBuffer (NULL) { mBuffer = new unsigned char[mBufferSize]; - assert (mBuffer != NULL); + assert (mBuffer != NULL); } // Free memory on object deletion -RingBuffer::~RingBuffer() { - delete[] mBuffer; mBuffer = NULL; +RingBuffer::~RingBuffer() +{ + delete[] mBuffer; + mBuffer = NULL; } void -RingBuffer::flush (void) { - mStart = 0; - mEnd = 0; -} - -int -RingBuffer::Len() const { - return (mEnd + mBufferSize - mStart) % mBufferSize; +RingBuffer::flush (void) +{ + mStart = 0; + mEnd = 0; } -void -RingBuffer::debug() { - _debug("Start=%d; End=%d; BufferSize=%d\n", mStart, mEnd, mBufferSize); +int +RingBuffer::Len() const +{ + return (mEnd + mBufferSize - mStart) % mBufferSize; +} + +void +RingBuffer::debug() +{ + _debug ("Start=%d; End=%d; BufferSize=%d\n", mStart, mEnd, mBufferSize); } - + // // For the writer only: // -int -RingBuffer::AvailForPut() const { - // Always keep 4 bytes safe (?) - return (mBufferSize-4) - Len(); -} +int +RingBuffer::AvailForPut() const +{ + // Always keep 4 bytes safe (?) + return (mBufferSize-4) - Len(); +} // This one puts some data inside the ring buffer. // Change the volume if it's not 100 -int -RingBuffer::Put(void* buffer, int toCopy, unsigned short volume) { - samplePtr src; - int block; - int copied; - int pos; - int len = Len(); - - if (toCopy > (mBufferSize-4) - len) - toCopy = (mBufferSize-4) - len; - - src = (samplePtr) buffer; - - - copied = 0; - pos = mEnd; - - while(toCopy) { - block = toCopy; - - // Wrap block around ring ? - if (block > (mBufferSize - pos)) { - // Fill in to the end of the buffer - block = mBufferSize - pos; - } - - // Gain adjustment (when Mic vol. is changed) - if (volume != 100) { - SFLDataFormat* start = (SFLDataFormat*) src; - int nbSample = block / sizeof(SFLDataFormat); - for (int i=0; i<nbSample; i++) { start[i] = start[i] * volume / 100; } - } - - // bcopy(src, dest, len) - //fprintf(stderr, "has %d put %d\t", len, block); - bcopy (src, mBuffer + pos, block); - src += block; - pos = (pos + block) % mBufferSize; - toCopy -= block; - copied += block; - } - - mEnd = pos; - - // How many items copied. - return copied; +int +RingBuffer::Put (void* buffer, int toCopy, unsigned short volume) +{ + samplePtr src; + int block; + int copied; + int pos; + int len = Len(); + + if (toCopy > (mBufferSize-4) - len) + toCopy = (mBufferSize-4) - len; + + src = (samplePtr) buffer; + + + copied = 0; + + pos = mEnd; + + while (toCopy) { + block = toCopy; + + // Wrap block around ring ? + + if (block > (mBufferSize - pos)) { + // Fill in to the end of the buffer + block = mBufferSize - pos; + } + + // Gain adjustment (when Mic vol. is changed) + if (volume != 100) { + SFLDataFormat* start = (SFLDataFormat*) src; + int nbSample = block / sizeof (SFLDataFormat); + + for (int i=0; i<nbSample; i++) { + start[i] = start[i] * volume / 100; + } + } + + // bcopy(src, dest, len) + //fprintf(stderr, "has %d put %d\t", len, block); + bcopy (src, mBuffer + pos, block); + + src += block; + + pos = (pos + block) % mBufferSize; + + toCopy -= block; + + copied += block; + } + + mEnd = pos; + + // How many items copied. + return copied; } // // For the reader only: // -int -RingBuffer::AvailForGet() const { - // Used space - return Len(); +int +RingBuffer::AvailForGet() const +{ + // Used space + return Len(); } // Get will move 'toCopy' bytes from the internal FIFO to 'buffer' -int -RingBuffer::Get(void *buffer, int toCopy, unsigned short volume) { - samplePtr dest; - int block; - int copied; - int len = Len(); - - if (toCopy > len) - toCopy = len; - - dest = (samplePtr) buffer; - copied = 0; - - //fprintf(stderr, "G"); - while(toCopy) { - block = toCopy; - if (block > (mBufferSize - mStart)) { - block = mBufferSize - mStart; - } - - if(volume!=100) { - SFLDataFormat* start = (SFLDataFormat*)(mBuffer + mStart); - int nbSample = block / sizeof(SFLDataFormat); - for (int i=0; i<nbSample; i++) { start[i] = start[i] * volume / 100; } - } - // bcopy(src, dest, len) - bcopy (mBuffer + mStart, dest, block); - dest += block; - mStart = (mStart + block) % mBufferSize; - toCopy -= block; - copied += block; - } - - return copied; +int +RingBuffer::Get (void *buffer, int toCopy, unsigned short volume) +{ + samplePtr dest; + int block; + int copied; + int len = Len(); + + if (toCopy > len) + toCopy = len; + + dest = (samplePtr) buffer; + + copied = 0; + + //fprintf(stderr, "G"); + while (toCopy) { + block = toCopy; + + if (block > (mBufferSize - mStart)) { + block = mBufferSize - mStart; + } + + if (volume!=100) { + SFLDataFormat* start = (SFLDataFormat*) (mBuffer + mStart); + int nbSample = block / sizeof (SFLDataFormat); + + for (int i=0; i<nbSample; i++) { + start[i] = start[i] * volume / 100; + } + } + + // bcopy(src, dest, len) + bcopy (mBuffer + mStart, dest, block); + + dest += block; + + mStart = (mStart + block) % mBufferSize; + + toCopy -= block; + + copied += block; + } + + return copied; } // Used to discard some bytes. -int -RingBuffer::Discard(int toDiscard) { - int len = Len(); +int +RingBuffer::Discard (int toDiscard) +{ + int len = Len(); - if (toDiscard > len) - toDiscard = len; + if (toDiscard > len) + toDiscard = len; - mStart = (mStart + toDiscard) % mBufferSize; + mStart = (mStart + toDiscard) % mBufferSize; - return toDiscard; + return toDiscard; } diff --git a/sflphone-common/src/audio/tone.cpp b/sflphone-common/src/audio/tone.cpp index ac6cfda8b7..d8849cbf32 100644 --- a/sflphone-common/src/audio/tone.cpp +++ b/sflphone-common/src/audio/tone.cpp @@ -2,10 +2,10 @@ * Copyright (C) 2005, 2006 Savoir-Faire Linux inc. * Author: Yan Morin <yan.morin@savoirfairelinux.com> * - * Inspired by tonegenerator of + * Inspired by tonegenerator of * Laurielle Lea <laurielle.lea@savoirfairelinux.com> (2004) * Inspired by ringbuffer of Audacity Project - * + * * 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 @@ -28,102 +28,116 @@ #include <cstdlib> #include <strings.h> -Tone::Tone(const std::string& definition, unsigned int sampleRate) : AudioLoop(), _sampleRate(sampleRate) +Tone::Tone (const std::string& definition, unsigned int sampleRate) : AudioLoop(), _sampleRate (sampleRate) { - genBuffer(definition); // allocate memory with definition parameter + genBuffer (definition); // allocate memory with definition parameter } Tone::~Tone() { } -void -Tone::genBuffer(const std::string& definition) +void +Tone::genBuffer (const std::string& definition) { - if (definition.empty()) { return; } - _size = 0; + if (definition.empty()) { + return; + } - SFLDataFormat* buffer = new SFLDataFormat[SIZEBUF]; //1kb - SFLDataFormat* bufferPos = buffer; + _size = 0; - // Number of format sections - std::string::size_type posStart = 0; // position of precedent comma - std::string::size_type posEnd = 0; // position of the next comma + SFLDataFormat* buffer = new SFLDataFormat[SIZEBUF]; //1kb + SFLDataFormat* bufferPos = buffer; - std::string s; // portion of frequency - int count; // number of int for one sequence + // Number of format sections + std::string::size_type posStart = 0; // position of precedent comma + std::string::size_type posEnd = 0; // position of the next comma - std::string::size_type deflen = definition.length(); - do { - posEnd = definition.find(',', posStart); - if (posEnd == std::string::npos) { - posEnd = deflen; - } + std::string s; // portion of frequency + int count; // number of int for one sequence - { - // Sample string: "350+440" or "350+440/2000,244+655/2000" - int freq1, freq2, time; - s = definition.substr(posStart, posEnd-posStart); - - // The 1st frequency is before the first + or the / - std::string::size_type pos_plus = s.find('+'); - std::string::size_type pos_slash = s.find('/'); - std::string::size_type len = s.length(); - std::string::size_type endfrequency = 0; - - if ( pos_slash == std::string::npos ) { - time = 0; - endfrequency = len; - } else { - time = atoi((s.substr(pos_slash+1,len-pos_slash-1)).data()); - endfrequency = pos_slash; - } - - // without a plus = 1 frequency - if (pos_plus == std::string::npos ) { - freq1 = atoi((s.substr(0,endfrequency)).data()); - freq2 = 0; - } else { - freq1 = atoi((s.substr(0,pos_plus)).data()); - freq2 = atoi((s.substr(pos_plus+1, endfrequency-pos_plus-1)).data()); - } - - // If there is time or if it's unlimited - if (time == 0) { - count = _sampleRate; - } else { - count = (_sampleRate * time) / 1000; - } - // Generate SAMPLING_RATE samples of sinus, buffer is the result - genSin(bufferPos, freq1, freq2, count); - - // To concatenate the different buffers for each section. - _size += (count); - bufferPos += (count); - } + std::string::size_type deflen = definition.length(); + + do { + posEnd = definition.find (',', posStart); + + if (posEnd == std::string::npos) { + posEnd = deflen; + } + + { + // Sample string: "350+440" or "350+440/2000,244+655/2000" + int freq1, freq2, time; + s = definition.substr (posStart, posEnd-posStart); + + // The 1st frequency is before the first + or the / + std::string::size_type pos_plus = s.find ('+'); + std::string::size_type pos_slash = s.find ('/'); + std::string::size_type len = s.length(); + std::string::size_type endfrequency = 0; + + if (pos_slash == std::string::npos) { + time = 0; + endfrequency = len; + } else { + time = atoi ( (s.substr (pos_slash+1,len-pos_slash-1)).data()); + endfrequency = pos_slash; + } + + // without a plus = 1 frequency + if (pos_plus == std::string::npos) { + freq1 = atoi ( (s.substr (0,endfrequency)).data()); + freq2 = 0; + } else { + freq1 = atoi ( (s.substr (0,pos_plus)).data()); + freq2 = atoi ( (s.substr (pos_plus+1, endfrequency-pos_plus-1)).data()); + } - posStart = posEnd+1; - } while (posStart < deflen); + // If there is time or if it's unlimited + if (time == 0) { + count = _sampleRate; + } else { + count = (_sampleRate * time) / 1000; + } - _buffer = new SFLDataFormat[_size]; - // src, dest, tocopy - bcopy(buffer, _buffer, _size*sizeof(SFLDataFormat)); // copy char, not SFLDataFormat. - delete[] buffer; buffer=0; bufferPos=0; + // Generate SAMPLING_RATE samples of sinus, buffer is the result + genSin (bufferPos, freq1, freq2, count); + + // To concatenate the different buffers for each section. + _size += (count); + + bufferPos += (count); + } + + posStart = posEnd+1; + } while (posStart < deflen); + + _buffer = new SFLDataFormat[_size]; + + // src, dest, tocopy + bcopy (buffer, _buffer, _size*sizeof (SFLDataFormat)); // copy char, not SFLDataFormat. + + delete[] buffer; + + buffer=0; + + bufferPos=0; } void -Tone::genSin(SFLDataFormat* buffer, int frequency1, int frequency2, int nb) +Tone::genSin (SFLDataFormat* buffer, int frequency1, int frequency2, int nb) { - double pi2 = 6.28318520; - double var1 = pi2 * (double)frequency1 / (double)_sampleRate; - double var2 = pi2 * (double)frequency2 / (double)_sampleRate; + double pi2 = 6.28318520; + double var1 = pi2 * (double) frequency1 / (double) _sampleRate; + double var2 = pi2 * (double) frequency2 / (double) _sampleRate; - // softer - double amp = (double)SFLDataAmplitude; - for(int t = 0; t < nb; t++) { - buffer[t] = (SFLDataFormat)(amp * ((sin(var1 * t) + sin(var2 * t)))); - } + // softer + double amp = (double) SFLDataAmplitude; + + for (int t = 0; t < nb; t++) { + buffer[t] = (SFLDataFormat) (amp * ( (sin (var1 * t) + sin (var2 * t)))); + } } diff --git a/sflphone-common/src/audio/tonegenerator.cpp b/sflphone-common/src/audio/tonegenerator.cpp index f053bfa9b8..6fc84d5373 100644 --- a/sflphone-common/src/audio/tonegenerator.cpp +++ b/sflphone-common/src/audio/tonegenerator.cpp @@ -2,26 +2,26 @@ * Copyright (C) 2004-2005 Savoir-Faire Linux inc. * Author: Yan Morin <yan.morin@savoirfairelinux.com> * Author: Laurielle Lea <laurielle.lea@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 * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ - + */ + #include <fstream> -#include <math.h> +#include <math.h> #include <stdlib.h> - + #include "tonegenerator.h" #include "../global.h" @@ -31,28 +31,30 @@ int AMPLITUDE = 32767; // ToneGenerator implementation /////////////////////////////////////////////////////////////////////////////// -ToneGenerator::ToneGenerator (unsigned int sampleRate): sample(NULL), freq1(), freq2(), time(), totalbytes(), _sampleRate(sampleRate) -{ +ToneGenerator::ToneGenerator (unsigned int sampleRate) : sample (NULL), freq1(), freq2(), time(), totalbytes(), _sampleRate (sampleRate) +{ } -ToneGenerator::~ToneGenerator (void) { +ToneGenerator::~ToneGenerator (void) +{ } /** - * Calculate superposition of 2 sinus + * Calculate superposition of 2 sinus * */ void -ToneGenerator::generateSin (int lowerfreq, int higherfreq, int16* ptr, int len) const { - double var1, var2; - - var1 = (double)2 * (double)M_PI * (double)higherfreq / (double)_sampleRate; - var2 = (double)2 * (double)M_PI * (double)lowerfreq / (double)_sampleRate; - - double amp = (double)(AMPLITUDE >> 2); - - for(int t = 0; t < len; t++) { - ptr[t] = (int16)(amp * ((sin(var1 * t) + sin(var2 * t)))); - } +ToneGenerator::generateSin (int lowerfreq, int higherfreq, int16* ptr, int len) const +{ + double var1, var2; + + var1 = (double) 2 * (double) M_PI * (double) higherfreq / (double) _sampleRate; + var2 = (double) 2 * (double) M_PI * (double) lowerfreq / (double) _sampleRate; + + double amp = (double) (AMPLITUDE >> 2); + + for (int t = 0; t < len; t++) { + ptr[t] = (int16) (amp * ( (sin (var1 * t) + sin (var2 * t)))); + } } diff --git a/sflphone-common/src/audio/tonelist.cpp b/sflphone-common/src/audio/tonelist.cpp index e3c739e3f5..d28d3a5520 100644 --- a/sflphone-common/src/audio/tonelist.cpp +++ b/sflphone-common/src/audio/tonelist.cpp @@ -2,9 +2,9 @@ * Copyright (C) 2005 Savoir-Faire Linux inc. * Author: Yan Morin <yan.morin@savoirfairelinux.com> * - * Inspired by tonegenerator of + * Inspired by tonegenerator of * Laurielle Lea <laurielle.lea@savoirfairelinux.com> (2004) - * + * * 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 @@ -21,128 +21,136 @@ */ #include "tonelist.h" -ToneList::ToneList() : _nbTone( TONE_NBTONE ) , - _nbCountry( TONE_NBCOUNTRY ), - _defaultCountryId( ZID_NORTH_AMERICA ){ - initToneDefinition(); +ToneList::ToneList() : _nbTone (TONE_NBTONE) , + _nbCountry (TONE_NBCOUNTRY), + _defaultCountryId (ZID_NORTH_AMERICA) +{ + initToneDefinition(); } -ToneList::~ToneList() { +ToneList::~ToneList() +{ } -void -ToneList::initToneDefinition() +void +ToneList::initToneDefinition() { - _toneZone[ZID_NORTH_AMERICA][Tone::TONE_DIALTONE] = "350+440"; - _toneZone[ZID_NORTH_AMERICA][Tone::TONE_BUSY] = "480+620/500,0/500"; - _toneZone[ZID_NORTH_AMERICA][Tone::TONE_RINGTONE] = "440+480/2000,0/4000"; - _toneZone[ZID_NORTH_AMERICA][Tone::TONE_CONGESTION] = "480+620/250,0/250"; - - _toneZone[ZID_FRANCE][Tone::TONE_DIALTONE] = "440"; - _toneZone[ZID_FRANCE][Tone::TONE_BUSY] = "440/500,0/500"; - _toneZone[ZID_FRANCE][Tone::TONE_RINGTONE] = "440/1500,0/3500"; - _toneZone[ZID_FRANCE][Tone::TONE_CONGESTION] = "440/250,0/250"; - - _toneZone[ZID_AUSTRALIA][Tone::TONE_DIALTONE] = "413+438"; - _toneZone[ZID_AUSTRALIA][Tone::TONE_BUSY] = "425/375,0/375"; - _toneZone[ZID_AUSTRALIA][Tone::TONE_RINGTONE] = - "413+438/400,0/200,413+438/400,0/2000"; - _toneZone[ZID_AUSTRALIA][Tone::TONE_CONGESTION] = "425/375,0/375,420/375,8/375"; - - _toneZone[ZID_UNITED_KINGDOM][Tone::TONE_DIALTONE] = "350+440"; - _toneZone[ZID_UNITED_KINGDOM][Tone::TONE_BUSY] = "400/375,0/375"; - _toneZone[ZID_UNITED_KINGDOM][Tone::TONE_RINGTONE] = - "400+450/400,0/200,400+450/400,0/2000"; - _toneZone[ZID_UNITED_KINGDOM][Tone::TONE_CONGESTION] = - "400/400,0/350,400/225,0/525"; - - _toneZone[ZID_SPAIN][Tone::TONE_DIALTONE] = "425"; - _toneZone[ZID_SPAIN][Tone::TONE_BUSY] = "425/200,0/200"; - _toneZone[ZID_SPAIN][Tone::TONE_RINGTONE] = "425/1500,0/3000"; - _toneZone[ZID_SPAIN][Tone::TONE_CONGESTION] = - "425/200,0/200,425/200,0/200,425/200,0/600"; - - _toneZone[ZID_ITALY][Tone::TONE_DIALTONE] = "425/600,0/1000,425/200,0/200"; - _toneZone[ZID_ITALY][Tone::TONE_BUSY] = "425/500,0/500"; - _toneZone[ZID_ITALY][Tone::TONE_RINGTONE] = "425/1000,0/4000"; - _toneZone[ZID_ITALY][Tone::TONE_CONGESTION] = "425/200,0/200"; - - _toneZone[ZID_JAPAN][Tone::TONE_DIALTONE] = "400"; - _toneZone[ZID_JAPAN][Tone::TONE_BUSY] = "400/500,0/500"; - _toneZone[ZID_JAPAN][Tone::TONE_RINGTONE] = "400+15/1000,0/2000"; - _toneZone[ZID_JAPAN][Tone::TONE_CONGESTION] = "400/500,0/500"; + _toneZone[ZID_NORTH_AMERICA][Tone::TONE_DIALTONE] = "350+440"; + _toneZone[ZID_NORTH_AMERICA][Tone::TONE_BUSY] = "480+620/500,0/500"; + _toneZone[ZID_NORTH_AMERICA][Tone::TONE_RINGTONE] = "440+480/2000,0/4000"; + _toneZone[ZID_NORTH_AMERICA][Tone::TONE_CONGESTION] = "480+620/250,0/250"; + + _toneZone[ZID_FRANCE][Tone::TONE_DIALTONE] = "440"; + _toneZone[ZID_FRANCE][Tone::TONE_BUSY] = "440/500,0/500"; + _toneZone[ZID_FRANCE][Tone::TONE_RINGTONE] = "440/1500,0/3500"; + _toneZone[ZID_FRANCE][Tone::TONE_CONGESTION] = "440/250,0/250"; + + _toneZone[ZID_AUSTRALIA][Tone::TONE_DIALTONE] = "413+438"; + _toneZone[ZID_AUSTRALIA][Tone::TONE_BUSY] = "425/375,0/375"; + _toneZone[ZID_AUSTRALIA][Tone::TONE_RINGTONE] = + "413+438/400,0/200,413+438/400,0/2000"; + _toneZone[ZID_AUSTRALIA][Tone::TONE_CONGESTION] = "425/375,0/375,420/375,8/375"; + + _toneZone[ZID_UNITED_KINGDOM][Tone::TONE_DIALTONE] = "350+440"; + _toneZone[ZID_UNITED_KINGDOM][Tone::TONE_BUSY] = "400/375,0/375"; + _toneZone[ZID_UNITED_KINGDOM][Tone::TONE_RINGTONE] = + "400+450/400,0/200,400+450/400,0/2000"; + _toneZone[ZID_UNITED_KINGDOM][Tone::TONE_CONGESTION] = + "400/400,0/350,400/225,0/525"; + + _toneZone[ZID_SPAIN][Tone::TONE_DIALTONE] = "425"; + _toneZone[ZID_SPAIN][Tone::TONE_BUSY] = "425/200,0/200"; + _toneZone[ZID_SPAIN][Tone::TONE_RINGTONE] = "425/1500,0/3000"; + _toneZone[ZID_SPAIN][Tone::TONE_CONGESTION] = + "425/200,0/200,425/200,0/200,425/200,0/600"; + + _toneZone[ZID_ITALY][Tone::TONE_DIALTONE] = "425/600,0/1000,425/200,0/200"; + _toneZone[ZID_ITALY][Tone::TONE_BUSY] = "425/500,0/500"; + _toneZone[ZID_ITALY][Tone::TONE_RINGTONE] = "425/1000,0/4000"; + _toneZone[ZID_ITALY][Tone::TONE_CONGESTION] = "425/200,0/200"; + + _toneZone[ZID_JAPAN][Tone::TONE_DIALTONE] = "400"; + _toneZone[ZID_JAPAN][Tone::TONE_BUSY] = "400/500,0/500"; + _toneZone[ZID_JAPAN][Tone::TONE_RINGTONE] = "400+15/1000,0/2000"; + _toneZone[ZID_JAPAN][Tone::TONE_CONGESTION] = "400/500,0/500"; } std::string -ToneList::getDefinition(COUNTRYID countryId, Tone::TONEID toneId) +ToneList::getDefinition (COUNTRYID countryId, Tone::TONEID toneId) { - if (toneId == Tone::TONE_NULL) { return ""; } - return _toneZone[countryId][toneId]; + if (toneId == Tone::TONE_NULL) { + return ""; + } + + return _toneZone[countryId][toneId]; } -ToneList::COUNTRYID -ToneList::getCountryId(const std::string& countryName) +ToneList::COUNTRYID +ToneList::getCountryId (const std::string& countryName) { - if (countryName.compare("North America") == 0) { - return ZID_NORTH_AMERICA; - } else if (countryName.compare("France") == 0) { - return ZID_FRANCE; - } else if (countryName.compare("Australia") == 0) { - return ZID_AUSTRALIA; - } else if (countryName.compare("United Kingdom") == 0) { - return ZID_UNITED_KINGDOM; - } else if (countryName.compare("Spain") == 0) { - return ZID_SPAIN; - } else if (countryName.compare("Italy") == 0) { - return ZID_ITALY; - } else if (countryName.compare("Japan") == 0) { - return ZID_JAPAN; - } else { - return _defaultCountryId; // default, we don't want segmentation fault - } + if (countryName.compare ("North America") == 0) { + return ZID_NORTH_AMERICA; + } else if (countryName.compare ("France") == 0) { + return ZID_FRANCE; + } else if (countryName.compare ("Australia") == 0) { + return ZID_AUSTRALIA; + } else if (countryName.compare ("United Kingdom") == 0) { + return ZID_UNITED_KINGDOM; + } else if (countryName.compare ("Spain") == 0) { + return ZID_SPAIN; + } else if (countryName.compare ("Italy") == 0) { + return ZID_ITALY; + } else if (countryName.compare ("Japan") == 0) { + return ZID_JAPAN; + } else { + return _defaultCountryId; // default, we don't want segmentation fault + } } -TelephoneTone::TelephoneTone(const std::string& countryName, unsigned int sampleRate) : - _currentTone( Tone::TONE_NULL ), - _toneList() +TelephoneTone::TelephoneTone (const std::string& countryName, unsigned int sampleRate) : + _currentTone (Tone::TONE_NULL), + _toneList() { - ToneList::COUNTRYID countryId = _toneList.getCountryId(countryName); - _tone[Tone::TONE_DIALTONE] = new Tone(_toneList.getDefinition(countryId, Tone::TONE_DIALTONE), sampleRate); - _tone[Tone::TONE_BUSY] = new Tone(_toneList.getDefinition(countryId, Tone::TONE_BUSY), sampleRate); - _tone[Tone::TONE_RINGTONE] = new Tone(_toneList.getDefinition(countryId, Tone::TONE_RINGTONE), sampleRate); - _tone[Tone::TONE_CONGESTION] = new Tone(_toneList.getDefinition(countryId, Tone::TONE_CONGESTION), sampleRate); + ToneList::COUNTRYID countryId = _toneList.getCountryId (countryName); + _tone[Tone::TONE_DIALTONE] = new Tone (_toneList.getDefinition (countryId, Tone::TONE_DIALTONE), sampleRate); + _tone[Tone::TONE_BUSY] = new Tone (_toneList.getDefinition (countryId, Tone::TONE_BUSY), sampleRate); + _tone[Tone::TONE_RINGTONE] = new Tone (_toneList.getDefinition (countryId, Tone::TONE_RINGTONE), sampleRate); + _tone[Tone::TONE_CONGESTION] = new Tone (_toneList.getDefinition (countryId, Tone::TONE_CONGESTION), sampleRate); } -TelephoneTone::~TelephoneTone() +TelephoneTone::~TelephoneTone() { - for (int i=0; i<_toneList.getNbTone(); i++) { - delete _tone[i]; _tone[i] = 0; - } + for (int i=0; i<_toneList.getNbTone(); i++) { + delete _tone[i]; + _tone[i] = 0; + } } void -TelephoneTone::setCurrentTone(Tone::TONEID toneId) +TelephoneTone::setCurrentTone (Tone::TONEID toneId) { - if ( toneId != Tone::TONE_NULL && _currentTone != toneId ) { - _tone[toneId]->reset(); - } - _currentTone = toneId; + if (toneId != Tone::TONE_NULL && _currentTone != toneId) { + _tone[toneId]->reset(); + } + + _currentTone = toneId; } Tone* TelephoneTone::getCurrentTone() { - if ( _currentTone == Tone::TONE_NULL ) { - return 0; - } - return _tone[_currentTone]; + if (_currentTone == Tone::TONE_NULL) { + return 0; + } + + return _tone[_currentTone]; } bool TelephoneTone::shouldPlay() { - return (( _currentTone != Tone::TONE_NULL ) ? true : false ); + return ( (_currentTone != Tone::TONE_NULL) ? true : false); } diff --git a/sflphone-common/src/call.cpp b/sflphone-common/src/call.cpp index 60513cf962..d2cb79ae39 100644 --- a/sflphone-common/src/call.cpp +++ b/sflphone-common/src/call.cpp @@ -20,146 +20,155 @@ #include "call.h" #include "manager.h" -Call::Call(const CallID& id, Call::CallType type) - : _callMutex() - , _audioStarted(false) - , _localIPAddress("") - , _localAudioPort(0) - , _localExternalAudioPort(0) - , _id(id) - , _type(type) - , _connectionState(Call::Disconnected) - , _callState(Call::Inactive) - , _callConfig (Call::Classic) - , _peerName() - , _peerNumber() +Call::Call (const CallID& id, Call::CallType type) + : _callMutex() + , _audioStarted (false) + , _localIPAddress ("") + , _localAudioPort (0) + , _localExternalAudioPort (0) + , _id (id) + , _type (type) + , _connectionState (Call::Disconnected) + , _callState (Call::Inactive) + , _callConfig (Call::Classic) + , _peerName() + , _peerNumber() { - + FILE_TYPE fileType = FILE_WAV; SOUND_FORMAT soundFormat = INT16; - recAudio.setRecordingOption(fileType,soundFormat,44100, Manager::instance().getConfigString (AUDIO, RECORD_PATH),id); - // _debug("CALL::Constructor for this clss is called \n"); + recAudio.setRecordingOption (fileType,soundFormat,44100, Manager::instance().getConfigString (AUDIO, RECORD_PATH),id); + // _debug("CALL::Constructor for this clss is called \n"); } Call::~Call() { - // _debug("CALL::~Call(): Destructor for this clss is called \n"); - - if(recAudio.isOpenFile()) { - // _debug("CALL::~Call(): A recording file is open, close it \n"); - recAudio.closeFile(); - } + // _debug("CALL::~Call(): Destructor for this clss is called \n"); + + if (recAudio.isOpenFile()) { + // _debug("CALL::~Call(): A recording file is open, close it \n"); + recAudio.closeFile(); + } } -void -Call::setConnectionState(ConnectionState state) +void +Call::setConnectionState (ConnectionState state) { - ost::MutexLock m(_callMutex); - _connectionState = state; + ost::MutexLock m (_callMutex); + _connectionState = state; } Call::ConnectionState -Call::getConnectionState() +Call::getConnectionState() { - ost::MutexLock m(_callMutex); - return _connectionState; + ost::MutexLock m (_callMutex); + return _connectionState; } -void -Call::setState(CallState state) +void +Call::setState (CallState state) { - ost::MutexLock m(_callMutex); - _callState = state; + ost::MutexLock m (_callMutex); + _callState = state; } Call::CallState -Call::getState() +Call::getState() { - ost::MutexLock m(_callMutex); - return _callState; + ost::MutexLock m (_callMutex); + return _callState; } std::string Call::getStateStr () { CallState state = getState(); - _debug("getStateStr , state = %d\n", state); + _debug ("getStateStr , state = %d\n", state); std::string state_str; - + switch (state) { + case Active: state_str = "CURRENT"; break; + case Hold: state_str = "HOLD"; break; + case Busy: state_str = "BUSY"; break; + case Inactive: state_str = "INACTIVE"; break; + case Refused: + case Error: + default: state_str = "FAILURE"; break; } + return state_str; } -const std::string& +const std::string& Call::getLocalIp() { - ost::MutexLock m(_callMutex); - return _localIPAddress; + ost::MutexLock m (_callMutex); + return _localIPAddress; } -unsigned int +unsigned int Call::getLocalAudioPort() { - ost::MutexLock m(_callMutex); - return _localAudioPort; + ost::MutexLock m (_callMutex); + return _localAudioPort; } -void -Call::setAudioStart(bool start) +void +Call::setAudioStart (bool start) { - ost::MutexLock m(_callMutex); - _audioStarted = start; + ost::MutexLock m (_callMutex); + _audioStarted = start; } -bool +bool Call::isAudioStarted() { - ost::MutexLock m(_callMutex); - return _audioStarted; + ost::MutexLock m (_callMutex); + return _audioStarted; } void Call::setRecording() { - recAudio.setRecording(); + recAudio.setRecording(); } -void -Call::initRecFileName() { - recAudio.initFileName(_peerNumber); +void +Call::initRecFileName() +{ + recAudio.initFileName (_peerNumber); } void Call::stopRecording() { - recAudio.stopRecording(); + recAudio.stopRecording(); } bool Call::isRecording() { - return recAudio.isRecording(); + return recAudio.isRecording(); } diff --git a/sflphone-common/src/config/config.cpp b/sflphone-common/src/config/config.cpp index 2c26e20317..9c6bb914ba 100644 --- a/sflphone-common/src/config/config.cpp +++ b/sflphone-common/src/config/config.cpp @@ -23,60 +23,68 @@ #include <fstream> #include <cstdlib> -namespace Conf { +namespace Conf +{ // ctor -ConfigTree::ConfigTree():_sections() +ConfigTree::ConfigTree() :_sections() { } // dtor -ConfigTree::~ConfigTree() +ConfigTree::~ConfigTree() { - // erase every new ItemMap (by CreateSection) - SectionMap::iterator iter = _sections.begin(); - while(iter != _sections.end()) { - delete iter->second; iter->second = NULL; - iter++; - } + // erase every new ItemMap (by CreateSection) + SectionMap::iterator iter = _sections.begin(); + + while (iter != _sections.end()) { + delete iter->second; + iter->second = NULL; + iter++; + } } /** * Create the section only if it doesn't exists */ void -ConfigTree::createSection(const std::string& section) { - // if we doesn't find the item, create it - if (_sections.find(section) == _sections.end()) { - _sections[section] = new ItemMap; - } +ConfigTree::createSection (const std::string& section) +{ + // if we doesn't find the item, create it + if (_sections.find (section) == _sections.end()) { + _sections[section] = new ItemMap; + } } /** * Remove the section only if it exists */ void -ConfigTree::removeSection(const std::string& section) { - // if we doesn't find the item, create it - SectionMap::iterator iter = _sections.find(section); - if (iter != _sections.end()) { - _sections.erase(iter); - } +ConfigTree::removeSection (const std::string& section) +{ + // if we doesn't find the item, create it + SectionMap::iterator iter = _sections.find (section); + + if (iter != _sections.end()) { + _sections.erase (iter); + } } /** Retrieve the sections as an array */ TokenList ConfigTree::getSections() { - TokenList sections; - - SectionMap::iterator iter = _sections.begin(); - while(iter != _sections.end()) { - // add to token list the: iter->second; - sections.push_back(iter->first); - iter++; - } - return sections; + TokenList sections; + + SectionMap::iterator iter = _sections.begin(); + + while (iter != _sections.end()) { + // add to token list the: iter->second; + sections.push_back (iter->first); + iter++; + } + + return sections; } @@ -84,69 +92,76 @@ ConfigTree::getSections() * Add the config item only if it exists.. * If the section doesn't exists, create it */ -void -ConfigTree::addConfigTreeItem(const std::string& section, const ConfigTreeItem item) +void +ConfigTree::addConfigTreeItem (const std::string& section, const ConfigTreeItem item) { - // if we doesn't find the item, create it - SectionMap::iterator iter = _sections.find(section); - if ( iter == _sections.end()) { - _sections[section] = new ItemMap; - iter = _sections.find(section); - } - // be prudent here - if (iter != _sections.end()) { - std::string name = item.getName(); - - if ( iter->second->find(name) == iter->second->end()) { - (*(iter->second))[name] = item; + // if we doesn't find the item, create it + SectionMap::iterator iter = _sections.find (section); + + if (iter == _sections.end()) { + _sections[section] = new ItemMap; + iter = _sections.find (section); + } + + // be prudent here + if (iter != _sections.end()) { + std::string name = item.getName(); + + if (iter->second->find (name) == iter->second->end()) { + (* (iter->second)) [name] = item; + } } - } } // throw a ConfigTreeItemException if not found -std::string -ConfigTree::getConfigTreeItemValue(const std::string& section, const std::string& itemName) +std::string +ConfigTree::getConfigTreeItemValue (const std::string& section, const std::string& itemName) { - ConfigTreeItem* item = getConfigTreeItem(section, itemName); - if (item != NULL) { - return item->getValue(); - } else { - _debug("Option doesn't exist: [%s] %s\n", section.c_str(), itemName.c_str()); - /** @todo If item doesn't exist, we should check against the default values for those - * types of information, and return the default value. - * ... - * Maybe this should be implemented when called ? When we need a bit of configuration, - * we call the getConfig with a defaultValue as parameter, in that context we know best - * what would be the default value, rather than inside this generic configuration - * management class. - */ - } - return ""; + ConfigTreeItem* item = getConfigTreeItem (section, itemName); + + if (item != NULL) { + return item->getValue(); + } else { + _debug ("Option doesn't exist: [%s] %s\n", section.c_str(), itemName.c_str()); + /** @todo If item doesn't exist, we should check against the default values for those + * types of information, and return the default value. + * ... + * Maybe this should be implemented when called ? When we need a bit of configuration, + * we call the getConfig with a defaultValue as parameter, in that context we know best + * what would be the default value, rather than inside this generic configuration + * management class. + */ + } + + return ""; } // throw a ConfigTreeItemException if not found -int -ConfigTree::getConfigTreeItemIntValue(const std::string& section, const std::string& itemName) +int +ConfigTree::getConfigTreeItemIntValue (const std::string& section, const std::string& itemName) { - std::string configItem = getConfigTreeItemValue(section, itemName); - int retval = atoi(configItem.data()); + std::string configItem = getConfigTreeItemValue (section, itemName); + int retval = atoi (configItem.data()); - return retval; + return retval; } bool -ConfigTree::getConfigTreeItemToken(const std::string& section, const std::string& itemName, TokenList& arg) { - ConfigTreeItem *item = getConfigTreeItem(section, itemName); - if (item) { - arg.clear(); - arg.push_back(section); - arg.push_back(itemName); - arg.push_back(item->getType()); - arg.push_back(item->getValue()); - arg.push_back(item->getDefaultValue()); - return true; - } - return false; +ConfigTree::getConfigTreeItemToken (const std::string& section, const std::string& itemName, TokenList& arg) +{ + ConfigTreeItem *item = getConfigTreeItem (section, itemName); + + if (item) { + arg.clear(); + arg.push_back (section); + arg.push_back (itemName); + arg.push_back (item->getType()); + arg.push_back (item->getValue()); + arg.push_back (item->getDefaultValue()); + return true; + } + + return false; } @@ -154,17 +169,22 @@ ConfigTree::getConfigTreeItemToken(const std::string& section, const std::string /** * Return a ConfigTreeItem or NULL if not found */ -ConfigTreeItem* -ConfigTree::getConfigTreeItem(const std::string& section, const std::string& itemName) { - SectionMap::iterator iter = _sections.find(section); - if ( iter == _sections.end()) { - return NULL; - } - ItemMap::iterator iterItem = iter->second->find(itemName); - if ( iterItem == iter->second->end()) { - return NULL; - } - return &(iterItem->second); +ConfigTreeItem* +ConfigTree::getConfigTreeItem (const std::string& section, const std::string& itemName) +{ + SectionMap::iterator iter = _sections.find (section); + + if (iter == _sections.end()) { + return NULL; + } + + ItemMap::iterator iterItem = iter->second->find (itemName); + + if (iterItem == iter->second->end()) { + return NULL; + } + + return & (iterItem->second); } /** @@ -172,60 +192,71 @@ ConfigTree::getConfigTreeItem(const std::string& section, const std::string& ite * * @todo Élimier les 45,000 classes qui servent à rien pour Conf. */ -bool -ConfigTree::setConfigTreeItem(const std::string& section, - const std::string& itemName, - const std::string& value) { - - SectionMap::iterator iter = _sections.find(section); - if ( iter == _sections.end()) { - // Not found, create section - _sections[section] = new ItemMap; - iter = _sections.find(section); - } - - ItemMap::iterator iterItem = iter->second->find(itemName); - if ( iterItem == iter->second->end()) { - // Item not found, create it, defaults to type "string" - addConfigTreeItem(section, ConfigTreeItem(itemName, value, "string")); +bool +ConfigTree::setConfigTreeItem (const std::string& section, + const std::string& itemName, + const std::string& value) +{ + + SectionMap::iterator iter = _sections.find (section); + + if (iter == _sections.end()) { + // Not found, create section + _sections[section] = new ItemMap; + iter = _sections.find (section); + } + + ItemMap::iterator iterItem = iter->second->find (itemName); + + if (iterItem == iter->second->end()) { + // Item not found, create it, defaults to type "string" + addConfigTreeItem (section, ConfigTreeItem (itemName, value, "string")); + return true; + } + + iterItem->second.setValue (value); + return true; - } - iterItem->second.setValue(value); - return true; } // Save config to a file (ini format) // return false if empty, no config, or enable to open // return true if everything is ok -bool -ConfigTree::saveConfigTree(const std::string& fileName) { - if (fileName.empty() && _sections.begin() == _sections.end() ) { - return false; - } +bool +ConfigTree::saveConfigTree (const std::string& fileName) +{ + if (fileName.empty() && _sections.begin() == _sections.end()) { + return false; + } - std::fstream file; - file.open(fileName.data(), std::fstream::out); + std::fstream file; - if (!file.is_open()) { - return false; - } - - // for each section, for each item... - SectionMap::iterator iter = _sections.begin(); - while(iter != _sections.end()) { - file << "[" << iter->first << "]" << std::endl; - ItemMap::iterator iterItem = iter->second->begin(); - while ( iterItem != iter->second->end() ) { - file << iterItem->first << "=" << iterItem->second.getValue() << std::endl; - iterItem++; + file.open (fileName.data(), std::fstream::out); + + if (!file.is_open()) { + return false; } - file << std::endl; - iter++; - } + // for each section, for each item... + SectionMap::iterator iter = _sections.begin(); - file.close(); - return true; + while (iter != _sections.end()) { + file << "[" << iter->first << "]" << std::endl; + ItemMap::iterator iterItem = iter->second->begin(); + + while (iterItem != iter->second->end()) { + file << iterItem->first << "=" << iterItem->second.getValue() << std::endl; + iterItem++; + } + + file << std::endl; + + iter++; + } + + file.close(); + + return true; } // Create the tree from an existing ini file @@ -233,116 +264,137 @@ ConfigTree::saveConfigTree(const std::string& fileName) { // 1 = OK // 2 = unable to open int -ConfigTree::populateFromFile(const std::string& fileName) { - bool out = false; - if (fileName.empty()) { - return 0; - } - - std::fstream file; - file.open(fileName.data(), std::fstream::in); - - if (!file.is_open()) { - file.open(fileName.data(), std::fstream::out); - out = true; +ConfigTree::populateFromFile (const std::string& fileName) +{ + bool out = false; + + if (fileName.empty()) { + return 0; + } + + std::fstream file; + + file.open (fileName.data(), std::fstream::in); + if (!file.is_open()) { - return 0; + file.open (fileName.data(), std::fstream::out); + out = true; + + if (!file.is_open()) { + return 0; + } + + file.close(); + + return 2; } - file.close(); - return 2; - } - // get length of file: - file.seekg (0, std::ios::end); - int length = file.tellg(); - file.seekg (0, std::ios::beg); - - if ( length == 0 ) { - file.close(); - return 2; // should load config - } - - std::string line; - std::string section(""); - std::string key(""); - std::string val(""); - std::string::size_type pos; - - while (!file.eof()) { - // Read the file line by line - std::getline(file, line); - if (!line.empty()) { - if (line[0] == '[') { - // If the line is a section - pos = line.find(']'); - section = line.substr(1, pos - 1); - } else if (line[0] != '#') { - // If the line is "key=value" and doesn't begin with '#'(comments) - - pos = line.find('='); - key = line.substr(0, pos); - val = line.substr(pos + 1, line.length() - pos); - - if (key.length() > 0 && val.length() > 0) { - setConfigTreeItem(section, key, val); + + // get length of file: + file.seekg (0, std::ios::end); + + int length = file.tellg(); + + file.seekg (0, std::ios::beg); + + if (length == 0) { + file.close(); + return 2; // should load config + } + + std::string line; + + std::string section (""); + std::string key (""); + std::string val (""); + std::string::size_type pos; + + while (!file.eof()) { + // Read the file line by line + std::getline (file, line); + + if (!line.empty()) { + if (line[0] == '[') { + // If the line is a section + pos = line.find (']'); + section = line.substr (1, pos - 1); + } else if (line[0] != '#') { + // If the line is "key=value" and doesn't begin with '#'(comments) + + pos = line.find ('='); + key = line.substr (0, pos); + val = line.substr (pos + 1, line.length() - pos); + + if (key.length() > 0 && val.length() > 0) { + setConfigTreeItem (section, key, val); + } + } } - } } - } - - file.close(); - return 1; + + file.close(); + + return 1; } TokenList ConfigTreeIterator::begin() { - TokenList tk; - _iter = _tree->_sections.begin(); - if (_iter!=_tree->_sections.end()) { - _iterItem = _iter->second->begin(); - if (_iterItem!=_iter->second->end()) { - tk.push_back(_iter->first); - tk.push_back(_iterItem->first); - tk.push_back(_iterItem->second.getType()); - tk.push_back(_iterItem->second.getValue()); - tk.push_back(_iterItem->second.getDefaultValue()); + TokenList tk; + _iter = _tree->_sections.begin(); + + if (_iter!=_tree->_sections.end()) { + _iterItem = _iter->second->begin(); + + if (_iterItem!=_iter->second->end()) { + tk.push_back (_iter->first); + tk.push_back (_iterItem->first); + tk.push_back (_iterItem->second.getType()); + tk.push_back (_iterItem->second.getValue()); + tk.push_back (_iterItem->second.getDefaultValue()); + } } - } - return tk; + + return tk; } TokenList ConfigTreeIterator::next() { - TokenList tk; - // we return tk empty if we are at the end of the list... - if (_iter==_tree->_sections.end()) { - return tk; - } - if (_iterItem!=_iter->second->end()) { - _iterItem++; - } - if (_iterItem==_iter->second->end()) { - // if we increment, and we are at the end of a section - _iter++; - if (_iter!=_tree->_sections.end()) { - _iterItem = _iter->second->begin(); - if (_iterItem!=_iter->second->end()) { - tk.push_back(_iter->first); - tk.push_back(_iterItem->first); - tk.push_back(_iterItem->second.getType()); - tk.push_back(_iterItem->second.getValue()); - tk.push_back(_iterItem->second.getDefaultValue()); - } + TokenList tk; + // we return tk empty if we are at the end of the list... + + if (_iter==_tree->_sections.end()) { + return tk; + } + + if (_iterItem!=_iter->second->end()) { + _iterItem++; + } + + if (_iterItem==_iter->second->end()) { + // if we increment, and we are at the end of a section + _iter++; + + if (_iter!=_tree->_sections.end()) { + _iterItem = _iter->second->begin(); + + if (_iterItem!=_iter->second->end()) { + tk.push_back (_iter->first); + tk.push_back (_iterItem->first); + tk.push_back (_iterItem->second.getType()); + tk.push_back (_iterItem->second.getValue()); + tk.push_back (_iterItem->second.getDefaultValue()); + } + } + } else { + tk.push_back (_iter->first); + tk.push_back (_iterItem->first); + tk.push_back (_iterItem->second.getType()); + tk.push_back (_iterItem->second.getValue()); + tk.push_back (_iterItem->second.getDefaultValue()); } - } else { - tk.push_back(_iter->first); - tk.push_back(_iterItem->first); - tk.push_back(_iterItem->second.getType()); - tk.push_back(_iterItem->second.getValue()); - tk.push_back(_iterItem->second.getDefaultValue()); - } - return tk; + + return tk; } } // end namespace ConfigTree diff --git a/sflphone-common/src/config/config.h b/sflphone-common/src/config/config.h index e929426b5e..0872889486 100644 --- a/sflphone-common/src/config/config.h +++ b/sflphone-common/src/config/config.h @@ -29,153 +29,184 @@ * @file config.h * @brief Configuration namespace for ConfigTree object (like .ini files) */ -namespace Conf { - class ConfigTreeItem; - typedef std::map<std::string, ConfigTreeItem> ItemMap; - typedef std::map<std::string, ItemMap*> SectionMap; - typedef std::list<std::string> TokenList; +namespace Conf +{ + +class ConfigTreeItem; +typedef std::map<std::string, ConfigTreeItem> ItemMap; +typedef std::map<std::string, ItemMap*> SectionMap; +typedef std::list<std::string> TokenList; + +class ConfigTreeItemException +{ - class ConfigTreeItemException { public: - /** - * Constructor - * */ - ConfigTreeItemException() {} - - /** - * Destructor - * */ - ~ConfigTreeItemException() {} - }; - - class ConfigTree; - class ConfigTreeIterator - { + /** + * Constructor + * */ + ConfigTreeItemException() {} + + /** + * Destructor + * */ + ~ConfigTreeItemException() {} +}; + +class ConfigTree; + +class ConfigTreeIterator +{ + public: - /** - * Parsing method - * @return TokenList - */ - TokenList begin(); - - /** - * Parsing method - * @return TokenList - */ - const TokenList& end() const { return _endToken; } - - /** - * Parsing method - * @return TokenList - */ - TokenList next(); + /** + * Parsing method + * @return TokenList + */ + TokenList begin(); + + /** + * Parsing method + * @return TokenList + */ + const TokenList& end() const { + return _endToken; + } + + /** + * Parsing method + * @return TokenList + */ + TokenList next(); private: - friend class ConfigTree; - ConfigTreeIterator(ConfigTree *configTree) : _tree(configTree), _endToken(), _iter(), _iterItem() {} - ConfigTreeIterator(const Conf::ConfigTreeIterator&); - ConfigTreeIterator& operator=(const Conf::ConfigTreeIterator&); + friend class ConfigTree; + ConfigTreeIterator (ConfigTree *configTree) : _tree (configTree), _endToken(), _iter(), _iterItem() {} + + ConfigTreeIterator (const Conf::ConfigTreeIterator&); + ConfigTreeIterator& operator= (const Conf::ConfigTreeIterator&); - ConfigTree* _tree; - TokenList _endToken; - SectionMap::iterator _iter; - ItemMap::iterator _iterItem; - }; + ConfigTree* _tree; + TokenList _endToken; + SectionMap::iterator _iter; + ItemMap::iterator _iterItem; +}; + +class ConfigTree +{ - class ConfigTree { public: - ConfigTree(); - ~ConfigTree(); - - void createSection(const std::string& section); - void removeSection(const std::string& section); - /** - * Return an array of strings, listing the sections of the config file - * - * This will be mainly used to filter which sections are an - * "Account" definition. - * - * @return array Strings of the sections - */ - TokenList getSections(); - - void addConfigTreeItem(const std::string& section, const ConfigTreeItem item); - /** - * Set a configuration value. - * - * @param section Write to this [section] of the .ini file - * @param itemName The itemName= in the .ini file - * @param value The value to assign to that itemName - */ - bool setConfigTreeItem(const std::string& section, const std::string& itemName, const std::string& value); - - /** - * Get a value. - * - * This function does all the validity tests, so none are needed throughout - * the program. - * - * @param section The name of the [section] in the .ini file. - * @param itemName The name of the item= in the .ini file. - * @return The value of the corresponding item. The default value if the section exists - * but the item doesn't. - */ - std::string getConfigTreeItemValue(const std::string& section, const std::string& itemName); - int getConfigTreeItemIntValue(const std::string& section, const std::string& itemName); - - /** - * Flush data to .ini file - */ - bool saveConfigTree(const std::string& fileName); - - /** - * Load data (and fill ConfigTree) from disk - */ - int populateFromFile(const std::string& fileName); - - bool getConfigTreeItemToken(const std::string& section, const std::string& itemName, TokenList& arg); + ConfigTree(); + ~ConfigTree(); + + void createSection (const std::string& section); + void removeSection (const std::string& section); + /** + * Return an array of strings, listing the sections of the config file + * + * This will be mainly used to filter which sections are an + * "Account" definition. + * + * @return array Strings of the sections + */ + TokenList getSections(); + + void addConfigTreeItem (const std::string& section, const ConfigTreeItem item); + /** + * Set a configuration value. + * + * @param section Write to this [section] of the .ini file + * @param itemName The itemName= in the .ini file + * @param value The value to assign to that itemName + */ + bool setConfigTreeItem (const std::string& section, const std::string& itemName, const std::string& value); + + /** + * Get a value. + * + * This function does all the validity tests, so none are needed throughout + * the program. + * + * @param section The name of the [section] in the .ini file. + * @param itemName The name of the item= in the .ini file. + * @return The value of the corresponding item. The default value if the section exists + * but the item doesn't. + */ + std::string getConfigTreeItemValue (const std::string& section, const std::string& itemName); + int getConfigTreeItemIntValue (const std::string& section, const std::string& itemName); + + /** + * Flush data to .ini file + */ + bool saveConfigTree (const std::string& fileName); + + /** + * Load data (and fill ConfigTree) from disk + */ + int populateFromFile (const std::string& fileName); + + bool getConfigTreeItemToken (const std::string& section, const std::string& itemName, TokenList& arg); private: - ConfigTreeItem* getConfigTreeItem(const std::string& section, const std::string& itemName); + ConfigTreeItem* getConfigTreeItem (const std::string& section, const std::string& itemName); + + /** + * List of sections. Each sections has an ItemList as child + */ + SectionMap _sections; - /** - * List of sections. Each sections has an ItemList as child - */ - SectionMap _sections; - friend class ConfigTreeIterator; + friend class ConfigTreeIterator; public: - ConfigTreeIterator createIterator() { - return ConfigTreeIterator(this); - } - }; + ConfigTreeIterator createIterator() { + return ConfigTreeIterator (this); + } +}; + +class ConfigTreeItem +{ - class ConfigTreeItem { public: - ConfigTreeItem() : _name(""), _value(""), _defaultValue(""), _type("string") {} - // defaultvalue = value - ConfigTreeItem(const std::string& name, const std::string& value, const std::string& type) : - _name(name), _value(value), - _defaultValue(value), _type(type) {} - ConfigTreeItem(const std::string& name, const std::string& value, const std::string& defaultValue, const std::string& type) : - _name(name), _value(value), - _defaultValue(defaultValue), _type(type) {} - ~ConfigTreeItem() {} - - void setValue(const std::string& value) { _value = value; } - const std::string getName() const { return _name; } - const std::string getValue() const { return _value; } - const std::string getDefaultValue() const { return _defaultValue; } - const std::string getType() const { return _type; } + ConfigTreeItem() : _name (""), _value (""), _defaultValue (""), _type ("string") {} + + // defaultvalue = value + ConfigTreeItem (const std::string& name, const std::string& value, const std::string& type) : + _name (name), _value (value), + _defaultValue (value), _type (type) {} + + ConfigTreeItem (const std::string& name, const std::string& value, const std::string& defaultValue, const std::string& type) : + _name (name), _value (value), + _defaultValue (defaultValue), _type (type) {} + + ~ConfigTreeItem() {} + + void setValue (const std::string& value) { + _value = value; + } + + const std::string getName() const { + return _name; + } + + const std::string getValue() const { + return _value; + } + + const std::string getDefaultValue() const { + return _defaultValue; + } + + const std::string getType() const { + return _type; + } private: - std::string _name; - std::string _value; - std::string _defaultValue; - std::string _type; - }; + std::string _name; + std::string _value; + std::string _defaultValue; + std::string _type; +}; } // end namespace ConfigTree diff --git a/sflphone-common/src/dbus/callmanager.cpp b/sflphone-common/src/dbus/callmanager.cpp index a2d2cb43e9..88f2e349a1 100644 --- a/sflphone-common/src/dbus/callmanager.cpp +++ b/sflphone-common/src/dbus/callmanager.cpp @@ -3,17 +3,17 @@ * Copyright (C) 2007 Savoir-Faire Linux inc. * Author: Pierre-Luc Beaudoin <pierre-luc.beaudoin@savoirfairelinux.com> * Author: Alexandre Bourget <alexandre.bourget@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 * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -24,127 +24,126 @@ const char* CallManager::SERVER_PATH = "/org/sflphone/SFLphone/CallManager"; -CallManager::CallManager( DBus::Connection& connection ) -: DBus::ObjectAdaptor(connection, SERVER_PATH) +CallManager::CallManager (DBus::Connection& connection) + : DBus::ObjectAdaptor (connection, SERVER_PATH) { } void -CallManager::placeCall( const std::string& accountID, - const std::string& callID, - const std::string& to ) +CallManager::placeCall (const std::string& accountID, + const std::string& callID, + const std::string& to) { - _debug("CallManager::placeCall received\n"); + _debug ("CallManager::placeCall received\n"); // Check if a destination number is available - if( to == "") _debug("No number entered - Call stopped\n"); - else Manager::instance().outgoingCall(accountID, callID, to); + + if (to == "") _debug ("No number entered - Call stopped\n"); + else Manager::instance().outgoingCall (accountID, callID, to); } void -CallManager::refuse( const std::string& callID ) +CallManager::refuse (const std::string& callID) { - _debug("CallManager::refuse received\n"); - Manager::instance().refuseCall(callID); + _debug ("CallManager::refuse received\n"); + Manager::instance().refuseCall (callID); } void -CallManager::accept( const std::string& callID ) +CallManager::accept (const std::string& callID) { - _debug("CallManager::accept received\n"); - Manager::instance().answerCall(callID); + _debug ("CallManager::accept received\n"); + Manager::instance().answerCall (callID); } void -CallManager::hangUp( const std::string& callID ) +CallManager::hangUp (const std::string& callID) { - _debug("CallManager::hangUp received\n"); - Manager::instance().hangupCall(callID); + _debug ("CallManager::hangUp received\n"); + Manager::instance().hangupCall (callID); } void -CallManager::hold( const std::string& callID ) +CallManager::hold (const std::string& callID) { - _debug("CallManager::hold received\n"); - Manager::instance().onHoldCall(callID); - + _debug ("CallManager::hold received\n"); + Manager::instance().onHoldCall (callID); + } void -CallManager::unhold( const std::string& callID ) +CallManager::unhold (const std::string& callID) { - _debug("CallManager::unhold received\n"); - Manager::instance().offHoldCall(callID); + _debug ("CallManager::unhold received\n"); + Manager::instance().offHoldCall (callID); } void -CallManager::transfert( const std::string& callID, const std::string& to ) +CallManager::transfert (const std::string& callID, const std::string& to) { - _debug("CallManager::transfert received\n"); - Manager::instance().transferCall(callID, to); + _debug ("CallManager::transfert received\n"); + Manager::instance().transferCall (callID, to); } void -CallManager::setVolume( const std::string& device, const double& value ) +CallManager::setVolume (const std::string& device, const double& value) { - _debug("CallManager::setVolume received\n"); - if(device == "speaker") - { - Manager::instance().setSpkrVolume((int)(value*100.0)); - } - else if (device == "mic") - { - Manager::instance().setMicVolume((int)(value*100.0)); + _debug ("CallManager::setVolume received\n"); + + if (device == "speaker") { + Manager::instance().setSpkrVolume ( (int) (value*100.0)); + } else if (device == "mic") { + Manager::instance().setMicVolume ( (int) (value*100.0)); } - volumeChanged(device, value); + + volumeChanged (device, value); } -double -CallManager::getVolume( const std::string& device ) +double +CallManager::getVolume (const std::string& device) { - _debug("CallManager::getVolume received \n"); - if(device == "speaker") - { - _debug("Current speaker = %d\n", Manager::instance().getSpkrVolume()); - return Manager::instance().getSpkrVolume()/100.0; - } - else if (device == "mic") - { - _debug("Current mic = %d\n", Manager::instance().getMicVolume()); - return Manager::instance().getMicVolume()/100.0; + _debug ("CallManager::getVolume received \n"); + + if (device == "speaker") { + _debug ("Current speaker = %d\n", Manager::instance().getSpkrVolume()); + return Manager::instance().getSpkrVolume() /100.0; + } else if (device == "mic") { + _debug ("Current mic = %d\n", Manager::instance().getMicVolume()); + return Manager::instance().getMicVolume() /100.0; } + return 0; } void -CallManager::setRecording(const std::string& callID) -{ - _debug("CallManager::setRecording received\n"); - Manager::instance().setRecordingCall(callID); +CallManager::setRecording (const std::string& callID) +{ + _debug ("CallManager::setRecording received\n"); + Manager::instance().setRecordingCall (callID); } bool -CallManager::getIsRecording(const std::string& callID) -{ - _debug("CallManager::getIsRecording received \n"); - return Manager::instance().isRecording(callID); +CallManager::getIsRecording (const std::string& callID) +{ + _debug ("CallManager::getIsRecording received \n"); + return Manager::instance().isRecording (callID); } std::string -CallManager::getCurrentCodecName(const std::string& callID) -{ - _debug("CallManager::getCurrentCodecName received %s \n",Manager::instance().getCurrentCodecName(callID).c_str()); - return Manager::instance().getCurrentCodecName(callID).c_str(); +CallManager::getCurrentCodecName (const std::string& callID) +{ + _debug ("CallManager::getCurrentCodecName received %s \n",Manager::instance().getCurrentCodecName (callID).c_str()); + return Manager::instance().getCurrentCodecName (callID).c_str(); } -std::map< std::string, std::string > -CallManager::getCallDetails( const std::string& callID ) +std::map< std::string, std::string > +CallManager::getCallDetails (const std::string& callID) { - _debug("CallManager::getCallDetails received\n"); + _debug ("CallManager::getCallDetails received\n"); return Manager::instance().getCallDetails (callID); } @@ -153,31 +152,29 @@ CallManager::getCallList (void) { return Manager::instance().getCallList(); } - -std::string -CallManager::getCurrentCallID( ) + +std::string +CallManager::getCurrentCallID() { - _debug("CallManager::getCurrentCallID received\n"); + _debug ("CallManager::getCurrentCallID received\n"); return Manager::instance().getCurrentCallId(); } -void -CallManager::playDTMF( const std::string& key ) +void +CallManager::playDTMF (const std::string& key) { - Manager::instance().sendDtmf(Manager::instance().getCurrentCallId(), key.c_str()[0]); + Manager::instance().sendDtmf (Manager::instance().getCurrentCallId(), key.c_str() [0]); } -void -CallManager::startTone( const int32_t& start , const int32_t& type ) +void +CallManager::startTone (const int32_t& start , const int32_t& type) { - if( start == true ) - { - if( type == 0 ) - Manager::instance().playTone(); - else - Manager::instance().playToneWithMessage(); - } - else - Manager::instance().stopTone(true); + if (start == true) { + if (type == 0) + Manager::instance().playTone(); + else + Manager::instance().playToneWithMessage(); + } else + Manager::instance().stopTone (true); } diff --git a/sflphone-common/src/dbus/configurationmanager.cpp b/sflphone-common/src/dbus/configurationmanager.cpp index 4681011f2f..c9dfc7d529 100644 --- a/sflphone-common/src/dbus/configurationmanager.cpp +++ b/sflphone-common/src/dbus/configurationmanager.cpp @@ -28,294 +28,299 @@ const char* ConfigurationManager::SERVER_PATH = "/org/sflphone/SFLphone/Configur - ConfigurationManager::ConfigurationManager( DBus::Connection& connection ) -: DBus::ObjectAdaptor(connection, SERVER_PATH) +ConfigurationManager::ConfigurationManager (DBus::Connection& connection) + : DBus::ObjectAdaptor (connection, SERVER_PATH) { } - - std::map< std::string, std::string > -ConfigurationManager::getAccountDetails( const std::string& accountID ) + +std::map< std::string, std::string > +ConfigurationManager::getAccountDetails (const std::string& accountID) { - _debug("ConfigurationManager::getAccountDetails\n"); - return Manager::instance().getAccountDetails(accountID); + _debug ("ConfigurationManager::getAccountDetails\n"); + return Manager::instance().getAccountDetails (accountID); } - void -ConfigurationManager::setAccountDetails( const std::string& accountID, - const std::map< std::string, std::string >& details ) +void +ConfigurationManager::setAccountDetails (const std::string& accountID, + const std::map< std::string, std::string >& details) { - _debug("ConfigurationManager::setAccountDetails received\n"); - Manager::instance().setAccountDetails(accountID, details); + _debug ("ConfigurationManager::setAccountDetails received\n"); + Manager::instance().setAccountDetails (accountID, details); } - void -ConfigurationManager::sendRegister( const std::string& accountID, const int32_t& expire ) +void +ConfigurationManager::sendRegister (const std::string& accountID, const int32_t& expire) { - _debug("ConfigurationManager::sendRegister received\n"); - Manager::instance().sendRegister(accountID, expire); + _debug ("ConfigurationManager::sendRegister received\n"); + Manager::instance().sendRegister (accountID, expire); } - std::string -ConfigurationManager::addAccount( const std::map< std::string, std::string >& details ) +std::string +ConfigurationManager::addAccount (const std::map< std::string, std::string >& details) { - _debug("ConfigurationManager::addAccount received\n"); - return Manager::instance().addAccount(details); + _debug ("ConfigurationManager::addAccount received\n"); + return Manager::instance().addAccount (details); } - void -ConfigurationManager::removeAccount( const std::string& accoundID ) +void +ConfigurationManager::removeAccount (const std::string& accoundID) { - _debug("ConfigurationManager::removeAccount received\n"); - return Manager::instance().removeAccount(accoundID); + _debug ("ConfigurationManager::removeAccount received\n"); + return Manager::instance().removeAccount (accoundID); } std::vector< std::string > -ConfigurationManager::getAccountList( ) +ConfigurationManager::getAccountList() { - _debug("ConfigurationManager::getAccountList received\n"); - return Manager::instance().getAccountList(); + _debug ("ConfigurationManager::getAccountList received\n"); + return Manager::instance().getAccountList(); } std::vector< std::string > -ConfigurationManager::getToneLocaleList( ) +ConfigurationManager::getToneLocaleList() { - std::vector< std::string > ret; - _debug("ConfigurationManager::getToneLocaleList received\n"); - return ret; + std::vector< std::string > ret; + _debug ("ConfigurationManager::getToneLocaleList received\n"); + return ret; } - std::string -ConfigurationManager::getVersion( ) +std::string +ConfigurationManager::getVersion() { - std::string ret(""); - _debug("ConfigurationManager::getVersion received\n"); - return ret; + std::string ret (""); + _debug ("ConfigurationManager::getVersion received\n"); + return ret; } - std::vector< std::string > -ConfigurationManager::getRingtoneList( ) +std::vector< std::string > +ConfigurationManager::getRingtoneList() { - std::vector< std::string > ret; - _debug("ConfigurationManager::getRingtoneList received\n"); - return ret; + std::vector< std::string > ret; + _debug ("ConfigurationManager::getRingtoneList received\n"); + return ret; } - std::vector< std::string > -ConfigurationManager::getCodecList( ) +std::vector< std::string > +ConfigurationManager::getCodecList() { - _debug("ConfigurationManager::getRingtoneList received\n"); - return Manager::instance().getCodecList(); + _debug ("ConfigurationManager::getRingtoneList received\n"); + return Manager::instance().getCodecList(); } - std::vector< std::string > -ConfigurationManager::getCodecDetails( const int32_t& payload ) +std::vector< std::string > +ConfigurationManager::getCodecDetails (const int32_t& payload) { - _debug("ConfigurationManager::getRingtoneList received\n"); - return Manager::instance().getCodecDetails( payload ); + _debug ("ConfigurationManager::getRingtoneList received\n"); + return Manager::instance().getCodecDetails (payload); } - std::vector< std::string > -ConfigurationManager::getActiveCodecList( ) +std::vector< std::string > +ConfigurationManager::getActiveCodecList() { - _debug("ConfigurationManager::getActiveCodecList received\n"); - return Manager::instance().getActiveCodecList(); + _debug ("ConfigurationManager::getActiveCodecList received\n"); + return Manager::instance().getActiveCodecList(); } void -ConfigurationManager::setActiveCodecList( const std::vector< std::string >& list ) +ConfigurationManager::setActiveCodecList (const std::vector< std::string >& list) { - _debug("ConfigurationManager::setActiveCodecList received\n"); - Manager::instance().setActiveCodecList(list); + _debug ("ConfigurationManager::setActiveCodecList received\n"); + Manager::instance().setActiveCodecList (list); } // Audio devices related methods - std::vector< std::string > +std::vector< std::string > ConfigurationManager::getInputAudioPluginList() { - _debug("ConfigurationManager::getInputAudioPluginList received\n"); - return Manager::instance().getInputAudioPluginList(); + _debug ("ConfigurationManager::getInputAudioPluginList received\n"); + return Manager::instance().getInputAudioPluginList(); } - std::vector< std::string > +std::vector< std::string > ConfigurationManager::getOutputAudioPluginList() { - _debug("ConfigurationManager::getOutputAudioPluginList received\n"); - return Manager::instance().getOutputAudioPluginList(); + _debug ("ConfigurationManager::getOutputAudioPluginList received\n"); + return Manager::instance().getOutputAudioPluginList(); } - void -ConfigurationManager::setInputAudioPlugin(const std::string& audioPlugin) +void +ConfigurationManager::setInputAudioPlugin (const std::string& audioPlugin) { - _debug("ConfigurationManager::setInputAudioPlugin received\n"); - return Manager::instance().setInputAudioPlugin(audioPlugin); + _debug ("ConfigurationManager::setInputAudioPlugin received\n"); + return Manager::instance().setInputAudioPlugin (audioPlugin); } - void -ConfigurationManager::setOutputAudioPlugin(const std::string& audioPlugin) +void +ConfigurationManager::setOutputAudioPlugin (const std::string& audioPlugin) { - _debug("ConfigurationManager::setOutputAudioPlugin received\n"); - return Manager::instance().setOutputAudioPlugin(audioPlugin); + _debug ("ConfigurationManager::setOutputAudioPlugin received\n"); + return Manager::instance().setOutputAudioPlugin (audioPlugin); } - std::vector< std::string > +std::vector< std::string > ConfigurationManager::getAudioOutputDeviceList() { - _debug("ConfigurationManager::getAudioOutputDeviceList received\n"); - return Manager::instance().getAudioOutputDeviceList(); + _debug ("ConfigurationManager::getAudioOutputDeviceList received\n"); + return Manager::instance().getAudioOutputDeviceList(); } + void -ConfigurationManager::setAudioOutputDevice(const int32_t& index) +ConfigurationManager::setAudioOutputDevice (const int32_t& index) { - _debug("ConfigurationManager::setAudioOutputDevice received\n"); - return Manager::instance().setAudioOutputDevice(index); + _debug ("ConfigurationManager::setAudioOutputDevice received\n"); + return Manager::instance().setAudioOutputDevice (index); } + std::vector< std::string > ConfigurationManager::getAudioInputDeviceList() { - _debug("ConfigurationManager::getAudioInputDeviceList received\n"); - return Manager::instance().getAudioInputDeviceList(); + _debug ("ConfigurationManager::getAudioInputDeviceList received\n"); + return Manager::instance().getAudioInputDeviceList(); } + void -ConfigurationManager::setAudioInputDevice(const int32_t& index) +ConfigurationManager::setAudioInputDevice (const int32_t& index) { - _debug("ConfigurationManager::setAudioInputDevice received\n"); - return Manager::instance().setAudioInputDevice(index); + _debug ("ConfigurationManager::setAudioInputDevice received\n"); + return Manager::instance().setAudioInputDevice (index); } + std::vector< std::string > ConfigurationManager::getCurrentAudioDevicesIndex() { - _debug("ConfigurationManager::getCurrentAudioDeviceIndex received\n"); - return Manager::instance().getCurrentAudioDevicesIndex(); + _debug ("ConfigurationManager::getCurrentAudioDeviceIndex received\n"); + return Manager::instance().getCurrentAudioDevicesIndex(); } - int32_t -ConfigurationManager::getAudioDeviceIndex(const std::string& name) + +int32_t +ConfigurationManager::getAudioDeviceIndex (const std::string& name) { - _debug("ConfigurationManager::getAudioDeviceIndex received\n"); - return Manager::instance().getAudioDeviceIndex(name); + _debug ("ConfigurationManager::getAudioDeviceIndex received\n"); + return Manager::instance().getAudioDeviceIndex (name); } std::string -ConfigurationManager::getCurrentAudioOutputPlugin( void ) +ConfigurationManager::getCurrentAudioOutputPlugin (void) { - _debug("ConfigurationManager::getCurrentAudioOutputPlugin received\n"); - return Manager::instance().getCurrentAudioOutputPlugin(); + _debug ("ConfigurationManager::getCurrentAudioOutputPlugin received\n"); + return Manager::instance().getCurrentAudioOutputPlugin(); } - std::vector< std::string > -ConfigurationManager::getPlaybackDeviceList( ) +std::vector< std::string > +ConfigurationManager::getPlaybackDeviceList() { - std::vector< std::string > ret; - _debug("ConfigurationManager::getPlaybackDeviceList received\n"); - return ret; + std::vector< std::string > ret; + _debug ("ConfigurationManager::getPlaybackDeviceList received\n"); + return ret; } - std::vector< std::string > -ConfigurationManager::getRecordDeviceList( ) +std::vector< std::string > +ConfigurationManager::getRecordDeviceList() { - std::vector< std::string > ret; - _debug("ConfigurationManager::getRecordDeviceList received\n"); - return ret; + std::vector< std::string > ret; + _debug ("ConfigurationManager::getRecordDeviceList received\n"); + return ret; } int32_t -ConfigurationManager::isIax2Enabled( void ) +ConfigurationManager::isIax2Enabled (void) { - return Manager::instance().isIax2Enabled( ); + return Manager::instance().isIax2Enabled(); } void -ConfigurationManager::ringtoneEnabled( void ) +ConfigurationManager::ringtoneEnabled (void) { - Manager::instance().ringtoneEnabled( ); + Manager::instance().ringtoneEnabled(); } int32_t -ConfigurationManager::isRingtoneEnabled( void ) +ConfigurationManager::isRingtoneEnabled (void) { - return Manager::instance().isRingtoneEnabled( ); + return Manager::instance().isRingtoneEnabled(); } std::string -ConfigurationManager::getRingtoneChoice( void ) +ConfigurationManager::getRingtoneChoice (void) { - return Manager::instance().getRingtoneChoice( ); + return Manager::instance().getRingtoneChoice(); } void -ConfigurationManager::setRingtoneChoice( const std::string& tone ) +ConfigurationManager::setRingtoneChoice (const std::string& tone) { - Manager::instance().setRingtoneChoice( tone ); + Manager::instance().setRingtoneChoice (tone); } std::string -ConfigurationManager::getRecordPath( void ) +ConfigurationManager::getRecordPath (void) { - return Manager::instance().getRecordPath( ); + return Manager::instance().getRecordPath(); } void -ConfigurationManager::setRecordPath( const std::string& recPath) +ConfigurationManager::setRecordPath (const std::string& recPath) { - Manager::instance().setRecordPath( recPath ); + Manager::instance().setRecordPath (recPath); } int32_t -ConfigurationManager::getDialpad( void ) +ConfigurationManager::getDialpad (void) { - return Manager::instance().getDialpad( ); + return Manager::instance().getDialpad(); } void -ConfigurationManager::setDialpad( void ) +ConfigurationManager::setDialpad (void) { - Manager::instance().setDialpad( ); + Manager::instance().setDialpad(); } int32_t -ConfigurationManager::getSearchbar( void ) +ConfigurationManager::getSearchbar (void) { - return Manager::instance().getSearchbar( ); + return Manager::instance().getSearchbar(); } void -ConfigurationManager::setSearchbar( void ) +ConfigurationManager::setSearchbar (void) { - Manager::instance().setSearchbar( ); + Manager::instance().setSearchbar(); } int32_t -ConfigurationManager::getVolumeControls( void ) +ConfigurationManager::getVolumeControls (void) { - return Manager::instance().getVolumeControls( ); + return Manager::instance().getVolumeControls(); } void -ConfigurationManager::setVolumeControls( void ) +ConfigurationManager::setVolumeControls (void) { - Manager::instance().setVolumeControls( ); + Manager::instance().setVolumeControls(); } int32_t -ConfigurationManager::getHistoryLimit( void ) +ConfigurationManager::getHistoryLimit (void) { - return Manager::instance().getHistoryLimit(); + return Manager::instance().getHistoryLimit(); } void ConfigurationManager::setHistoryLimit (const int32_t& days) { - Manager::instance().setHistoryLimit (days); + Manager::instance().setHistoryLimit (days); } @@ -323,157 +328,164 @@ void ConfigurationManager::setHistoryEnabled (void) { Manager::instance ().setHistoryEnabled (); } - + int32_t ConfigurationManager::getHistoryEnabled (void) { return Manager::instance ().getHistoryEnabled (); } - void -ConfigurationManager::startHidden( void ) +void +ConfigurationManager::startHidden (void) { - _debug("Manager received startHidden\n"); - Manager::instance().startHidden( ); + _debug ("Manager received startHidden\n"); + Manager::instance().startHidden(); } int32_t -ConfigurationManager::isStartHidden( void ) +ConfigurationManager::isStartHidden (void) { - _debug("Manager received isStartHidden\n"); - return Manager::instance().isStartHidden( ); + _debug ("Manager received isStartHidden\n"); + return Manager::instance().isStartHidden(); } void -ConfigurationManager::switchPopupMode( void ) +ConfigurationManager::switchPopupMode (void) { - _debug("Manager received switchPopupMode\n"); - Manager::instance().switchPopupMode( ); + _debug ("Manager received switchPopupMode\n"); + Manager::instance().switchPopupMode(); } int32_t -ConfigurationManager::popupMode( void ) +ConfigurationManager::popupMode (void) { - _debug("Manager received popupMode\n"); - return Manager::instance().popupMode( ); + _debug ("Manager received popupMode\n"); + return Manager::instance().popupMode(); } void -ConfigurationManager::setNotify( void ) +ConfigurationManager::setNotify (void) { - _debug("Manager received setNotify\n"); - Manager::instance().setNotify( ); + _debug ("Manager received setNotify\n"); + Manager::instance().setNotify(); } int32_t -ConfigurationManager::getNotify( void ) +ConfigurationManager::getNotify (void) { - _debug("Manager received getNotify\n"); - return Manager::instance().getNotify( ); + _debug ("Manager received getNotify\n"); + return Manager::instance().getNotify(); } void -ConfigurationManager::setAudioManager( const int32_t& api ) +ConfigurationManager::setAudioManager (const int32_t& api) { - _debug("Manager received setAudioManager\n"); - Manager::instance().setAudioManager( api ); + _debug ("Manager received setAudioManager\n"); + Manager::instance().setAudioManager (api); } int32_t -ConfigurationManager::getAudioManager( void ) +ConfigurationManager::getAudioManager (void) { - _debug("Manager received getAudioManager\n"); - return Manager::instance().getAudioManager( ); + _debug ("Manager received getAudioManager\n"); + return Manager::instance().getAudioManager(); } void -ConfigurationManager::setMailNotify( void ) +ConfigurationManager::setMailNotify (void) { - _debug("Manager received setMailNotify\n"); - Manager::instance().setMailNotify( ); + _debug ("Manager received setMailNotify\n"); + Manager::instance().setMailNotify(); } int32_t -ConfigurationManager::getMailNotify( void ) +ConfigurationManager::getMailNotify (void) { - _debug("Manager received getMailNotify\n"); - return Manager::instance().getMailNotify( ); + _debug ("Manager received getMailNotify\n"); + return Manager::instance().getMailNotify(); } int32_t -ConfigurationManager::getPulseAppVolumeControl( void ) +ConfigurationManager::getPulseAppVolumeControl (void) { - return Manager::instance().getPulseAppVolumeControl(); + return Manager::instance().getPulseAppVolumeControl(); } void -ConfigurationManager::setPulseAppVolumeControl( void ) +ConfigurationManager::setPulseAppVolumeControl (void) { - Manager::instance().setPulseAppVolumeControl(); + Manager::instance().setPulseAppVolumeControl(); } int32_t -ConfigurationManager::getSipPort( void ) +ConfigurationManager::getSipPort (void) { - return Manager::instance().getSipPort(); + return Manager::instance().getSipPort(); } void -ConfigurationManager::setSipPort( const int32_t& portNum ) +ConfigurationManager::setSipPort (const int32_t& portNum) { - _debug("Manager received setSipPort: %d\n", portNum); - Manager::instance().setSipPort(portNum); + _debug ("Manager received setSipPort: %d\n", portNum); + Manager::instance().setSipPort (portNum); } -std::string ConfigurationManager::getStunServer( void ) +std::string ConfigurationManager::getStunServer (void) { - _debug("Manager received getStunServer\n") ; + _debug ("Manager received getStunServer\n") ; return Manager::instance().getStunServer(); } -void ConfigurationManager::setStunServer( const std::string& server ) +void ConfigurationManager::setStunServer (const std::string& server) { - _debug("Manager received setStunServer\n") ; - Manager::instance().setStunServer( server ); + _debug ("Manager received setStunServer\n") ; + Manager::instance().setStunServer (server); } void ConfigurationManager::enableStun (void) { - _debug("Manager received enableStun\n") ; + _debug ("Manager received enableStun\n") ; Manager::instance().enableStun(); } int32_t ConfigurationManager::isStunEnabled (void) { - _debug("Manager received isStunEnabled\n") ; + _debug ("Manager received isStunEnabled\n") ; return Manager::instance().isStunEnabled(); } -std::map<std::string, int32_t> ConfigurationManager::getAddressbookSettings (void) { +std::map<std::string, int32_t> ConfigurationManager::getAddressbookSettings (void) +{ return Manager::instance().getAddressbookSettings (); } -void ConfigurationManager::setAddressbookSettings (const std::map<std::string, int32_t>& settings) { +void ConfigurationManager::setAddressbookSettings (const std::map<std::string, int32_t>& settings) +{ Manager::instance().setAddressbookSettings (settings); } -std::vector< std::string > ConfigurationManager::getAddressbookList ( void ) { +std::vector< std::string > ConfigurationManager::getAddressbookList (void) +{ return Manager::instance().getAddressbookList(); } -void ConfigurationManager::setAddressbookList( const std::vector< std::string >& list ) { - _debug("Manager received setAddressbookList\n") ; - Manager::instance().setAddressbookList(list); +void ConfigurationManager::setAddressbookList (const std::vector< std::string >& list) +{ + _debug ("Manager received setAddressbookList\n") ; + Manager::instance().setAddressbookList (list); } -std::map<std::string,std::string> ConfigurationManager::getHookSettings (void) { +std::map<std::string,std::string> ConfigurationManager::getHookSettings (void) +{ return Manager::instance().getHookSettings (); } -void ConfigurationManager::setHookSettings (const std::map<std::string, std::string>& settings) { +void ConfigurationManager::setHookSettings (const std::map<std::string, std::string>& settings) +{ Manager::instance().setHookSettings (settings); } -void ConfigurationManager::setAccountsOrder (const std::string& order) { +void ConfigurationManager::setAccountsOrder (const std::string& order) +{ Manager::instance().setAccountsOrder (order); } diff --git a/sflphone-common/src/dbus/contactmanager.cpp b/sflphone-common/src/dbus/contactmanager.cpp index 885585c40e..2764d30e56 100644 --- a/sflphone-common/src/dbus/contactmanager.cpp +++ b/sflphone-common/src/dbus/contactmanager.cpp @@ -1,17 +1,17 @@ /* * Copyright (C) 2008 Savoir-Faire Linux inc. * Author: Guillaume Carmel-Archambault <guillaume.carmel-archambault@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 * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -23,27 +23,27 @@ const char* ContactManager::SERVER_PATH = "/org/sflphone/SFLphone/ContactManager"; std::map< std::string, std::string > -ContactManager::getContacts( const std::string& accountID UNUSED) +ContactManager::getContacts (const std::string& accountID UNUSED) { - // TODO + // TODO std::map< std::string, std::string > ret; return ret; } void -ContactManager::setContacts( const std::string& accountID UNUSED, const std::map< std::string UNUSED, std::string >& details UNUSED) +ContactManager::setContacts (const std::string& accountID UNUSED, const std::map< std::string UNUSED, std::string >& details UNUSED) { - // TODO + // TODO } void -ContactManager::setPresence( const std::string& accountID UNUSED, const std::string& presence UNUSED, const std::string& additionalInfo UNUSED) +ContactManager::setPresence (const std::string& accountID UNUSED, const std::string& presence UNUSED, const std::string& additionalInfo UNUSED) { - // TODO + // TODO } void -ContactManager::setContactPresence( const std::string& accountID UNUSED, const std::string& presence UNUSED, const std::string& additionalInfo UNUSED) +ContactManager::setContactPresence (const std::string& accountID UNUSED, const std::string& presence UNUSED, const std::string& additionalInfo UNUSED) { - // TODO + // TODO } diff --git a/sflphone-common/src/dbus/dbusmanagerimpl.cpp b/sflphone-common/src/dbus/dbusmanagerimpl.cpp index c2103892f7..fce993fd79 100644 --- a/sflphone-common/src/dbus/dbusmanagerimpl.cpp +++ b/sflphone-common/src/dbus/dbusmanagerimpl.cpp @@ -1,53 +1,54 @@ /* * Copyright (C) 2007 Savoir-Faire Linux inc. * Author: Pierre-Luc Beaudoin <pierre-luc.beaudoin@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 * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ - + #include <dbusmanagerimpl.h> #include "manager.h" const char* DBusManagerImpl::SERVER_NAME = "org.sflphone.SFLphone"; -int -DBusManagerImpl::exec(){ - +int +DBusManagerImpl::exec() +{ + DBus::default_dispatcher = &_dispatcher; DBus::Connection conn = DBus::Connection::SessionBus(); - conn.request_name(SERVER_NAME); + conn.request_name (SERVER_NAME); - _callManager = new CallManager(conn); - _configurationManager = new ConfigurationManager(conn); - _instanceManager = new Instance(conn); + _callManager = new CallManager (conn); + _configurationManager = new ConfigurationManager (conn); + _instanceManager = new Instance (conn); // Register accounts Manager::instance().initRegisterAccounts(); //getEvents(); - _debug("Starting DBus event loop\n"); + _debug ("Starting DBus event loop\n"); _dispatcher.enter(); return 1; } - + void DBusManagerImpl::exit() { - + _dispatcher.leave(); - + } diff --git a/sflphone-common/src/dbus/instance.cpp b/sflphone-common/src/dbus/instance.cpp index 4e880722e7..233978ae63 100644 --- a/sflphone-common/src/dbus/instance.cpp +++ b/sflphone-common/src/dbus/instance.cpp @@ -1,17 +1,17 @@ /* * Copyright (C) 2007 Savoir-Faire Linux inc. * Author: Pierre-Luc Beaudoin <pierre-luc.beaudoin@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 * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -22,30 +22,30 @@ const char* Instance::SERVER_PATH = "/org/sflphone/SFLphone/Instance"; -Instance::Instance( DBus::Connection& connection ) -: DBus::ObjectAdaptor(connection, SERVER_PATH) +Instance::Instance (DBus::Connection& connection) + : DBus::ObjectAdaptor (connection, SERVER_PATH) { - count = 0; + count = 0; } void -Instance::Register( const int32_t& pid UNUSED, - const std::string& name UNUSED) +Instance::Register (const int32_t& pid UNUSED, + const std::string& name UNUSED) { - _debug("Instance::register received\n"); + _debug ("Instance::register received\n"); count++; } void -Instance::Unregister( const int32_t& pid UNUSED) +Instance::Unregister (const int32_t& pid UNUSED) { - _debug("Instance::unregister received\n"); + _debug ("Instance::unregister received\n"); count --; - if(count <= 0) - { - + if (count <= 0) { + + Manager::instance().terminate(); DBusManager::instance().exit(); @@ -53,11 +53,11 @@ Instance::Unregister( const int32_t& pid UNUSED) } } -int32_t -Instance::getRegistrationCount( void ) +int32_t +Instance::getRegistrationCount (void) { - - return count; + + return count; } diff --git a/sflphone-common/src/eventthread.cpp b/sflphone-common/src/eventthread.cpp index 0ecc444b41..b111c11c1b 100644 --- a/sflphone-common/src/eventthread.cpp +++ b/sflphone-common/src/eventthread.cpp @@ -6,12 +6,12 @@ * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -22,39 +22,39 @@ #include "audio/alsalayer.h" /********************************** Voiplink thread *************************************/ -EventThread::EventThread( VoIPLink *link ) - : Thread(), _linkthread(link) +EventThread::EventThread (VoIPLink *link) + : Thread(), _linkthread (link) { - setCancel( cancelDeferred ); + setCancel (cancelDeferred); } /** - * Reimplementation of run() + * Reimplementation of run() */ -void EventThread::run (void) +void EventThread::run (void) { - while(!testCancel()) { - _linkthread->getEvent(); - } -} + while (!testCancel()) { + _linkthread->getEvent(); + } +} /********************************************************************************************/ AudioThread::AudioThread (AlsaLayer *alsa) - : Thread(), _alsa(alsa) + : Thread(), _alsa (alsa) { setCancel (cancelDeferred); } /** - * Reimplementation of run() + * Reimplementation of run() */ -void AudioThread::run (void) +void AudioThread::run (void) { - while(!testCancel()) { + while (!testCancel()) { _alsa->audioCallback(); - Thread::sleep(3); + Thread::sleep (3); } } diff --git a/sflphone-common/src/history/historyitem.cpp b/sflphone-common/src/history/historyitem.cpp index 354b1d267f..90a5ff02a5 100644 --- a/sflphone-common/src/history/historyitem.cpp +++ b/sflphone-common/src/history/historyitem.cpp @@ -27,48 +27,55 @@ #define EMPTY_STRING "empty" HistoryItem::HistoryItem (std::string timestamp_start, CallType call_type, std::string timestamp_stop, std::string name, std::string number, std::string account_id) - : _timestamp_start (timestamp_start), _call_type (call_type), _timestamp_stop (timestamp_stop), _name (name), _number (number), _account_id (account_id) + : _timestamp_start (timestamp_start), _call_type (call_type), _timestamp_stop (timestamp_stop), _name (name), _number (number), _account_id (account_id) { } HistoryItem::HistoryItem (std::string timestamp, std::string serialized_form) - : _timestamp_start (timestamp) + : _timestamp_start (timestamp) { size_t pos; std::string tmp, id, name, number, stop, account; int indice=0; - while (serialized_form.find(ITEM_SEPARATOR, 0) != std::string::npos) - { + while (serialized_form.find (ITEM_SEPARATOR, 0) != std::string::npos) { pos = serialized_form.find (ITEM_SEPARATOR, 0); tmp = serialized_form.substr (0, pos); serialized_form.erase (0, pos + 1); - switch (indice) - { + + switch (indice) { + case 0: // The call type id = tmp; break; + case 1: // The number field number = tmp; break; + case 2: // The name field name = tmp; break; + case 3: // The end timestamp stop = tmp; break; + case 4: // The account ID account = tmp; break; + default: // error std::cout <<"[ERROR] unserialized form not recognized."<<std::endl; break; - } + } + indice ++; } - _call_type = (CallType)atoi (id.c_str()); + _call_type = (CallType) atoi (id.c_str()); + _number = number; (name == EMPTY_STRING) ? _name = "" : _name = name; _timestamp_stop = stop; @@ -80,7 +87,8 @@ HistoryItem::~HistoryItem () // TODO } -bool HistoryItem::save (Conf::ConfigTree **history){ +bool HistoryItem::save (Conf::ConfigTree **history) +{ std::string section, timestamp; std::stringstream call_type; @@ -90,11 +98,11 @@ bool HistoryItem::save (Conf::ConfigTree **history){ section = get_timestamp (); call_type << _call_type; - res = ( (*history)->setConfigTreeItem(section, "type", call_type.str()) - && (*history)->setConfigTreeItem(section, "timestamp_stop", _timestamp_stop) - && (*history)->setConfigTreeItem(section, "number", _number) - && (*history)->setConfigTreeItem(section, "accountid", _account_id) - && (*history)->setConfigTreeItem(section, "name", _name) ); + res = ( (*history)->setConfigTreeItem (section, "type", call_type.str()) + && (*history)->setConfigTreeItem (section, "timestamp_stop", _timestamp_stop) + && (*history)->setConfigTreeItem (section, "number", _number) + && (*history)->setConfigTreeItem (section, "accountid", _account_id) + && (*history)->setConfigTreeItem (section, "name", _name)); return res; } @@ -106,10 +114,10 @@ std::string HistoryItem::serialize (void) std::string name, accountID; // Replace empty string with a valid standard string value - (_name == "")? name = EMPTY_STRING : name = _name; + (_name == "") ? name = EMPTY_STRING : name = _name; // For the account ID, check also if the accountID corresponds to an existing account // ie the account may have been removed - (_account_id == "" || non_valid_account (_account_id))? accountID = "empty" : accountID = _account_id; + (_account_id == "" || non_valid_account (_account_id)) ? accountID = "empty" : accountID = _account_id; // Serialize it res << _call_type << separator << _number << separator << name << separator << _timestamp_stop << separator << accountID; diff --git a/sflphone-common/src/history/historymanager.cpp b/sflphone-common/src/history/historymanager.cpp index 9c114309b2..8cb5fc7b9f 100644 --- a/sflphone-common/src/history/historymanager.cpp +++ b/sflphone-common/src/history/historymanager.cpp @@ -23,11 +23,13 @@ #include <cc++/file.h> #include <time.h> -HistoryManager::HistoryManager () : _history_loaded (false), _history_path (""){ +HistoryManager::HistoryManager () : _history_loaded (false), _history_path ("") +{ } -HistoryManager::~HistoryManager () { +HistoryManager::~HistoryManager () +{ // Clear the history map _history_items.clear (); @@ -45,7 +47,7 @@ int HistoryManager::load_history (int limit, std::string path) bool HistoryManager::save_history (void) { Conf::ConfigTree history_list; - + save_history_items_map (&history_list); return save_history_to_file (&history_list); } @@ -55,7 +57,7 @@ bool HistoryManager::load_history_from_file (Conf::ConfigTree *history_list) bool exist; exist = history_list->populateFromFile (_history_path); - _history_loaded = (exist == 2 ) ? false : true; + _history_loaded = (exist == 2) ? false : true; return exist; } @@ -64,14 +66,14 @@ int HistoryManager::load_history_items_map (Conf::ConfigTree *history_list, int { short nb_items = 0; - Conf::TokenList sections; + Conf::TokenList sections; HistoryItem *item; Conf::TokenList::iterator iter; std::string number, name, accountID, timestamp_start, timestamp_stop; - CallType type; + CallType type; int history_limit; time_t current_timestamp; - + // We want to save only the items recent enough (ie compared to CONFIG_HISTORY_LIMIT) // Get the current timestamp (void) time (¤t_timestamp); @@ -80,7 +82,7 @@ int HistoryManager::load_history_items_map (Conf::ConfigTree *history_list, int sections = history_list->getSections(); iter = sections.begin(); - while(iter != sections.end()) { + while (iter != sections.end()) { type = (CallType) getConfigInt (*iter, "type", history_list); timestamp_stop = getConfigString (*iter, "timestamp_stop", history_list); @@ -90,8 +92,8 @@ int HistoryManager::load_history_items_map (Conf::ConfigTree *history_list, int timestamp_start = *iter; // Make a check on the start timestamp to know it is loadable according to CONFIG_HISTORY_LIMIT - if ( atoi (timestamp_start.c_str ()) >= ((int) current_timestamp - history_limit)) - { + + if (atoi (timestamp_start.c_str ()) >= ( (int) current_timestamp - history_limit)) { item = new HistoryItem (timestamp_start, type, timestamp_stop, name, number, accountID); add_new_history_entry (item); nb_items ++; @@ -112,20 +114,21 @@ bool HistoryManager::save_history_to_file (Conf::ConfigTree *history_list) int HistoryManager::save_history_items_map (Conf::ConfigTree *history_list) { HistoryItemMap::iterator iter; - HistoryItem *item; + HistoryItem *item; int items_saved = 0; iter = _history_items.begin (); - while (iter != _history_items.end ()) - { - item = iter->second; + while (iter != _history_items.end ()) { + item = iter->second; + if (item) { if (item->save (&history_list)) items_saved ++; } else { std::cout << "[DEBUG]: can't save NULL history item." << std::endl; } + iter ++; } @@ -135,55 +138,56 @@ int HistoryManager::save_history_items_map (Conf::ConfigTree *history_list) void HistoryManager::add_new_history_entry (HistoryItem *new_item) { // Add it in the map - _history_items [new_item->get_timestamp ()] = new_item; + _history_items [new_item->get_timestamp () ] = new_item; } -int HistoryManager::create_history_path (std::string path) { +int HistoryManager::create_history_path (std::string path) +{ std::string filename; - if (path == "") - { - filename = std::string(HOMEDIR) + DIR_SEPARATOR_STR + "." + PROGDIR; + if (path == "") { + filename = std::string (HOMEDIR) + DIR_SEPARATOR_STR + "." + PROGDIR; if (mkdir (filename.data(), 0755) != 0) { // If directory creation failed if (errno != EEXIST) { - _debug("Cannot create directory: %s\n", strerror(errno)); + _debug ("Cannot create directory: %s\n", strerror (errno)); return -1; } } // Load user's history _history_path = filename + DIR_SEPARATOR_STR + "history"; - } - else - set_history_path (path); - + } else + set_history_path (path); + return 0; } // throw an Conf::ConfigTreeItemException if not found - int -HistoryManager::getConfigInt(const std::string& section, const std::string& name, Conf::ConfigTree *history_list) +int +HistoryManager::getConfigInt (const std::string& section, const std::string& name, Conf::ConfigTree *history_list) { try { - return history_list->getConfigTreeItemIntValue(section, name); + return history_list->getConfigTreeItemIntValue (section, name); } catch (Conf::ConfigTreeItemException& e) { throw e; } + return 0; } - std::string -HistoryManager::getConfigString(const std::string& section, const std::string& name, Conf::ConfigTree *history_list) +std::string +HistoryManager::getConfigString (const std::string& section, const std::string& name, Conf::ConfigTree *history_list) { try { - return history_list->getConfigTreeItemValue(section, name); + return history_list->getConfigTreeItemValue (section, name); } catch (Conf::ConfigTreeItemException& e) { throw e; } + return ""; } @@ -192,18 +196,19 @@ std::map <std::string, std::string> HistoryManager::get_history_serialized (void std::map <std::string, std::string> serialized; HistoryItemMap::iterator iter; HistoryItem *current; - std::string res, key; + std::string res, key; iter = _history_items.begin (); - while (iter != _history_items.end()) - { + + while (iter != _history_items.end()) { current = iter->second; - if (current) - { + + if (current) { key = current->get_timestamp (); res = current->serialize (); serialized [key] = res; - } + } + iter ++; } @@ -216,7 +221,7 @@ int HistoryManager::set_serialized_history (std::map <std::string, std::string> std::map <std::string, std::string>::iterator iter; HistoryItem *new_item; int items_added = 0; - int history_limit; + int history_limit; time_t current_timestamp; // Clear the existing history @@ -227,17 +232,17 @@ int HistoryManager::set_serialized_history (std::map <std::string, std::string> (void) time (¤t_timestamp); history_limit = get_unix_timestamp_equivalent (limit); iter = history.begin (); - while (iter != history.end ()) - { - if (atoi (iter->first.c_str ()) >= ((int) current_timestamp - history_limit)) - { + + while (iter != history.end ()) { + if (atoi (iter->first.c_str ()) >= ( (int) current_timestamp - history_limit)) { new_item = new HistoryItem (iter->first, iter->second); add_new_history_entry (new_item); items_added ++; } + iter ++; } - + return items_added; } diff --git a/sflphone-common/src/hooks/urlhook.cpp b/sflphone-common/src/hooks/urlhook.cpp index 5ea82be051..cdf27b8fa0 100644 --- a/sflphone-common/src/hooks/urlhook.cpp +++ b/sflphone-common/src/hooks/urlhook.cpp @@ -24,7 +24,8 @@ UrlHook::UrlHook () { } UrlHook::~UrlHook () { } -int UrlHook::addAction (std::string field_value, std::string command){ +int UrlHook::addAction (std::string field_value, std::string command) +{ std::string command_bg; diff --git a/sflphone-common/src/iaxaccount.cpp b/sflphone-common/src/iaxaccount.cpp index 504a1cc710..48e2eb691c 100644 --- a/sflphone-common/src/iaxaccount.cpp +++ b/sflphone-common/src/iaxaccount.cpp @@ -3,17 +3,17 @@ * * Author: Emmanuel Milou <emmanuel.milou@savoirfairelinux.com> * Author: Alexandre Bourget <alexandre.bourget@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 * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -22,10 +22,10 @@ #include "iaxaccount.h" #include "iaxvoiplink.h" -IAXAccount::IAXAccount(const AccountID& accountID) - : Account(accountID, "iax2") +IAXAccount::IAXAccount (const AccountID& accountID) + : Account (accountID, "iax2") { - _link = new IAXVoIPLink(accountID); + _link = new IAXVoIPLink (accountID); } @@ -40,26 +40,26 @@ int IAXAccount::registerVoIPLink() _link->init(); // Stuff needed for IAX registration - setHostname(Manager::instance().getConfigString(_accountID, HOSTNAME)); - setUsername(Manager::instance().getConfigString(_accountID, USERNAME)); - setPassword(Manager::instance().getConfigString(_accountID, PASSWORD)); + setHostname (Manager::instance().getConfigString (_accountID, HOSTNAME)); + setUsername (Manager::instance().getConfigString (_accountID, USERNAME)); + setPassword (Manager::instance().getConfigString (_accountID, PASSWORD)); - _link->sendRegister( _accountID ); + _link->sendRegister (_accountID); return SUCCESS; } - int +int IAXAccount::unregisterVoIPLink() { - _link->sendUnregister( _accountID ); + _link->sendUnregister (_accountID); _link->terminate(); return SUCCESS; } - void -IAXAccount::loadConfig() +void +IAXAccount::loadConfig() { // Account generic Account::loadConfig(); diff --git a/sflphone-common/src/iaxcall.cpp b/sflphone-common/src/iaxcall.cpp index c2fc71c6ba..bdf9392328 100644 --- a/sflphone-common/src/iaxcall.cpp +++ b/sflphone-common/src/iaxcall.cpp @@ -21,34 +21,46 @@ #include "iaxcall.h" #include "global.h" // for _debug -IAXCall::IAXCall(const CallID& id, Call::CallType type) : Call(id, type), _session(NULL) +IAXCall::IAXCall (const CallID& id, Call::CallType type) : Call (id, type), _session (NULL) { } -IAXCall::~IAXCall() +IAXCall::~IAXCall() { - _session = NULL; // just to be sure to don't have unknown pointer, do not delete it! + _session = NULL; // just to be sure to don't have unknown pointer, do not delete it! } void -IAXCall::setFormat(int format) +IAXCall::setFormat (int format) { - _format = format; - switch(format) { - case AST_FORMAT_ULAW: - setAudioCodec(PAYLOAD_CODEC_ULAW); break; - case AST_FORMAT_GSM: - setAudioCodec(PAYLOAD_CODEC_GSM); break; - case AST_FORMAT_ALAW: - setAudioCodec(PAYLOAD_CODEC_ALAW); break; - case AST_FORMAT_ILBC: - setAudioCodec(PAYLOAD_CODEC_ILBC_20); break; - case AST_FORMAT_SPEEX: - setAudioCodec(PAYLOAD_CODEC_SPEEX_8000); break; - default: - setAudioCodec((AudioCodecType) -1); - break; - } + _format = format; + + switch (format) { + + case AST_FORMAT_ULAW: + setAudioCodec (PAYLOAD_CODEC_ULAW); + break; + + case AST_FORMAT_GSM: + setAudioCodec (PAYLOAD_CODEC_GSM); + break; + + case AST_FORMAT_ALAW: + setAudioCodec (PAYLOAD_CODEC_ALAW); + break; + + case AST_FORMAT_ILBC: + setAudioCodec (PAYLOAD_CODEC_ILBC_20); + break; + + case AST_FORMAT_SPEEX: + setAudioCodec (PAYLOAD_CODEC_SPEEX_8000); + break; + + default: + setAudioCodec ( (AudioCodecType) -1); + break; + } } @@ -61,66 +73,89 @@ IAXCall::getSupportedFormat() map = getCodecMap().getActiveCodecs(); - for(iter=0 ; iter < map.size() ; iter++){ - switch(map[iter]) { - case PAYLOAD_CODEC_ULAW: - format |= AST_FORMAT_ULAW; break; - case PAYLOAD_CODEC_GSM: - format |= AST_FORMAT_GSM; break; - case PAYLOAD_CODEC_ALAW: - format |= AST_FORMAT_ALAW; break; - case PAYLOAD_CODEC_ILBC_20: - format |= AST_FORMAT_ILBC; break; - case PAYLOAD_CODEC_SPEEX_8000: - format |= AST_FORMAT_SPEEX; - break; - default: - break; + for (iter=0 ; iter < map.size() ; iter++) { + switch (map[iter]) { + + case PAYLOAD_CODEC_ULAW: + format |= AST_FORMAT_ULAW; + break; + + case PAYLOAD_CODEC_GSM: + format |= AST_FORMAT_GSM; + break; + + case PAYLOAD_CODEC_ALAW: + format |= AST_FORMAT_ALAW; + break; + + case PAYLOAD_CODEC_ILBC_20: + format |= AST_FORMAT_ILBC; + break; + + case PAYLOAD_CODEC_SPEEX_8000: + format |= AST_FORMAT_SPEEX; + break; + + default: + break; + } } - } - return format; + + return format; } int -IAXCall::getFirstMatchingFormat(int needles) +IAXCall::getFirstMatchingFormat (int needles) { - CodecOrder map = getCodecMap().getActiveCodecs(); - int format = 0; - unsigned int iter; - - for(iter=0 ; iter < map.size() ; iter++) { - switch(map[iter]) { - case PAYLOAD_CODEC_ULAW: - format = AST_FORMAT_ULAW; break; - case PAYLOAD_CODEC_GSM: - format = AST_FORMAT_GSM; break; - case PAYLOAD_CODEC_ALAW: - format = AST_FORMAT_ALAW; - break; - case PAYLOAD_CODEC_ILBC_20: - format = AST_FORMAT_ILBC; break; - case PAYLOAD_CODEC_SPEEX_8000: - format = AST_FORMAT_SPEEX; break; - default: - break; + CodecOrder map = getCodecMap().getActiveCodecs(); + int format = 0; + unsigned int iter; + + for (iter=0 ; iter < map.size() ; iter++) { + switch (map[iter]) { + + case PAYLOAD_CODEC_ULAW: + format = AST_FORMAT_ULAW; + break; + + case PAYLOAD_CODEC_GSM: + format = AST_FORMAT_GSM; + break; + + case PAYLOAD_CODEC_ALAW: + format = AST_FORMAT_ALAW; + break; + + case PAYLOAD_CODEC_ILBC_20: + format = AST_FORMAT_ILBC; + break; + + case PAYLOAD_CODEC_SPEEX_8000: + format = AST_FORMAT_SPEEX; + break; + + default: + break; + } + + // Return the first that matches + if (format & needles) + return format; + } - // Return the first that matches - if (format & needles) - return format; - - } - return 0; + + return 0; } CodecDescriptor& IAXCall::getCodecMap() { - return _codecMap; + return _codecMap; } AudioCodecType IAXCall::getAudioCodec() { - return _audioCodec; + return _audioCodec; } diff --git a/sflphone-common/src/iaxvoiplink.cpp b/sflphone-common/src/iaxvoiplink.cpp index e15f22f50f..a5b29b3850 100644 --- a/sflphone-common/src/iaxvoiplink.cpp +++ b/sflphone-common/src/iaxvoiplink.cpp @@ -2,17 +2,17 @@ * Copyright (C) 2006-2007 Savoir-Faire Linux inc. * Author: Alexandre Bourget <alexandre.bourget@savoirfairelinux.com> * Author: Yan Morin <yan.morin@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 * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -40,22 +40,22 @@ #define CHK_VALID_CALL if (call == NULL) { _debug("IAX: Call doesn't exists\n"); \ return false; } - IAXVoIPLink::IAXVoIPLink(const AccountID& accountID) -: VoIPLink(accountID) +IAXVoIPLink::IAXVoIPLink (const AccountID& accountID) + : VoIPLink (accountID) { // _debug("IAXVoIPLink::IAXVoIPLink : creating eventhread \n "); - _evThread = new EventThread(this); + _evThread = new EventThread (this); _regSession = NULL; _nextRefreshStamp = 0; // to get random number for RANDOM_PORT - srand (time(NULL)); + srand (time (NULL)); audiolayer = NULL; converter = new SamplerateConverter(); - int nbSamplesMax = (int) ( converter->getFrequence() * converter->getFramesize() / 1000 ); + int nbSamplesMax = (int) (converter->getFrequence() * converter->getFramesize() / 1000); micData = new SFLDataFormat[nbSamplesMax]; micDataConverted = new SFLDataFormat[nbSamplesMax]; @@ -70,7 +70,8 @@ IAXVoIPLink::~IAXVoIPLink() { - delete _evThread; _evThread = NULL; + delete _evThread; + _evThread = NULL; _regSession = NULL; // shall not delete it terminate(); @@ -78,15 +79,20 @@ IAXVoIPLink::~IAXVoIPLink() delete converter; - delete [] micData; micData = NULL; - delete [] micDataConverted; micDataConverted = NULL; - delete [] micDataEncoded; micDataEncoded = NULL; - - delete [] spkrDataDecoded; spkrDataDecoded = NULL; - delete [] spkrDataConverted; spkrDataConverted = NULL; + delete [] micData; + micData = NULL; + delete [] micDataConverted; + micDataConverted = NULL; + delete [] micDataEncoded; + micDataEncoded = NULL; + + delete [] spkrDataDecoded; + spkrDataDecoded = NULL; + delete [] spkrDataConverted; + spkrDataConverted = NULL; } - bool +bool IAXVoIPLink::init() { // If it was done, don't do it again, until we call terminate() @@ -94,24 +100,28 @@ IAXVoIPLink::init() return false; bool returnValue = false; + // _localAddress = "127.0.0.1"; // port 0 is default // iax_enable_debug(); have to enable debug when compiling iax... int port = IAX_DEFAULT_PORTNO; + int last_port = 0; + int nbTry = 3; while (port != IAX_FAILURE && nbTry) { last_port = port; - port = iax_init(port); - if ( port < 0 ) { - _debug("IAX Warning: already initialize on port %d\n", last_port); + port = iax_init (port); + + if (port < 0) { + _debug ("IAX Warning: already initialize on port %d\n", last_port); port = RANDOM_IAX_PORT; } else if (port == IAX_FAILURE) { - _debug("IAX Fail to start on port %d", last_port); + _debug ("IAX Fail to start on port %d", last_port); port = RANDOM_IAX_PORT; } else { - _debug("IAX Info: listening on port %d\n", last_port); + _debug ("IAX Info: listening on port %d\n", last_port); _localPort = last_port; returnValue = true; _evThread->start(); @@ -119,68 +129,77 @@ IAXVoIPLink::init() audiolayer = Manager::instance().getAudioDriver(); break; } + nbTry--; - initDone(true); + initDone (true); } + if (port == IAX_FAILURE || nbTry==0) { - _debug("Fail to initialize iax\n"); + _debug ("Fail to initialize iax\n"); - initDone(false); + initDone (false); } return returnValue; } - void +void IAXVoIPLink::terminate() { // If it was done, don't do it again, until we call init() if (!initDone()) return; - // iaxc_shutdown(); + // iaxc_shutdown(); // Hangup all calls terminateIAXCall(); - initDone(false); + initDone (false); } - void +void IAXVoIPLink::terminateIAXCall() { std::string reason = "Dumped Call"; - ost::MutexLock m(_callMapMutex); + ost::MutexLock m (_callMapMutex); CallMap::iterator iter = _callMap.begin(); IAXCall *call; - while( iter != _callMap.end() ) { - call = dynamic_cast<IAXCall*>(iter->second); + + while (iter != _callMap.end()) { + call = dynamic_cast<IAXCall*> (iter->second); + if (call) { _mutexIAX.enterMutex(); - iax_hangup(call->getSession(), (char*)reason.c_str()); + iax_hangup (call->getSession(), (char*) reason.c_str()); _mutexIAX.leaveMutex(); - call->setSession(NULL); - delete call; call = NULL; + call->setSession (NULL); + delete call; + call = NULL; } + iter++; } + _callMap.clear(); } -void IAXVoIPLink::terminateOneCall(const CallID& id) +void IAXVoIPLink::terminateOneCall (const CallID& id) { - IAXCall* call = getIAXCall(id); - if(call){ - _debug("IAXVoIPLink::terminateOneCall()::the call is deleted, should close recording file \n"); - delete call; call = 0; + IAXCall* call = getIAXCall (id); + + if (call) { + _debug ("IAXVoIPLink::terminateOneCall()::the call is deleted, should close recording file \n"); + delete call; + call = 0; } } - void -IAXVoIPLink::getEvent() +void +IAXVoIPLink::getEvent() { IAXCall* call = NULL; @@ -188,7 +207,7 @@ IAXVoIPLink::getEvent() _mutexIAX.enterMutex(); iax_event* event = NULL; - while ( (event = iax_get_event(IAX_NONBLOCKING)) != NULL ) { + while ( (event = iax_get_event (IAX_NONBLOCKING)) != NULL) { // If we received an 'ACK', libiax2 tells apps to ignore them. if (event->etype == IAX_EVENT_NULL) { continue; @@ -196,53 +215,53 @@ IAXVoIPLink::getEvent() //_debug ("Receive IAX Event: %d (0x%x)\n", event->etype, event->etype); - call = iaxFindCallBySession(event->session); + call = iaxFindCallBySession (event->session); if (call) { // We know that call, deal with it - iaxHandleCallEvent(event, call); - //_audiocodec = Manager::instance().getCodecDescriptorMap().getCodec( call -> getAudioCodec() ); - } - else if (event->session && event->session == _regSession) { + iaxHandleCallEvent (event, call); + //_audiocodec = Manager::instance().getCodecDescriptorMap().getCodec( call -> getAudioCodec() ); + } else if (event->session && event->session == _regSession) { // This is a registration session, deal with it - iaxHandleRegReply(event); - } - else { + iaxHandleRegReply (event); + } else { // We've got an event before it's associated with any call - iaxHandlePrecallEvent(event); + iaxHandlePrecallEvent (event); } // _debug("IAXVoIPLink::getEvent() : timestamp %i \n",event->ts); - iax_event_free(event); + iax_event_free (event); } + _mutexIAX.leaveMutex(); - - if(call){ - call->recAudio.recData(spkrDataConverted,micData,nbSampleForRec_,nbSampleForRec_); + + if (call) { + call->recAudio.recData (spkrDataConverted,micData,nbSampleForRec_,nbSampleForRec_); } // Do the doodle-moodle to send audio from the microphone to the IAX channel. sendAudioFromMic(); // Refresh registration. - if (_nextRefreshStamp && _nextRefreshStamp - 2 < time(NULL)) { - sendRegister(""); + if (_nextRefreshStamp && _nextRefreshStamp - 2 < time (NULL)) { + sendRegister (""); } - + // reinitialize speaker buffer for recording (when recording a voice mail) for (int i = 0; i < nbSampleForRec_; i++) spkrDataConverted[i] = 0; - + // thread wait 3 millisecond - _evThread->sleep(3); - free(event); + _evThread->sleep (3); + + free (event); } - void -IAXVoIPLink::sendAudioFromMic(void) +void +IAXVoIPLink::sendAudioFromMic (void) { // _debug("IAXVoIPLink::sendAudioFromMic"); @@ -254,14 +273,14 @@ IAXVoIPLink::sendAudioFromMic(void) // TODO Find out a better way to do it updateAudiolayer(); - currentCall = getIAXCall(Manager::instance().getCurrentCallId()); + currentCall = getIAXCall (Manager::instance().getCurrentCallId()); if (!currentCall) { // Let's mind our own business. return; } - if( currentCall -> getAudioCodec() < 0 ) + if (currentCall -> getAudioCodec() < 0) return; // Just make sure the currentCall is in state to receive audio right now. @@ -274,13 +293,15 @@ IAXVoIPLink::sendAudioFromMic(void) return; } - ac = currentCall->getCodecMap().getCodec( currentCall -> getAudioCodec() ); + ac = currentCall->getCodecMap().getCodec (currentCall -> getAudioCodec()); + if (!ac) { // Audio codec still not determined. if (audiolayer) { // To keep latency low.. audiolayer->flushMic(); } + return; } @@ -289,7 +310,7 @@ IAXVoIPLink::sendAudioFromMic(void) // we have to get 20ms of data from the mic *20/1000 = /50 // rate/50 shall be lower than IAX__20S_48KHZ_MAX - maxBytesToGet = audiolayer->getSampleRate()* audiolayer->getFrameSize() / 1000 * sizeof(SFLDataFormat); + maxBytesToGet = audiolayer->getSampleRate() * audiolayer->getFrameSize() / 1000 * sizeof (SFLDataFormat); // available bytes inside ringbuffer availBytesFromMic = audiolayer->canGetMic(); @@ -301,57 +322,64 @@ IAXVoIPLink::sendAudioFromMic(void) // take the lowest bytesAvail = (availBytesFromMic < maxBytesToGet) ? availBytesFromMic : maxBytesToGet; + //_debug("available = %d, maxBytesToGet = %d\n", availBytesFromMic, maxBytesToGet); // Get bytes from micRingBuffer to data_from_mic - nbSample_ = audiolayer->getMic( micData, bytesAvail ) / sizeof(SFLDataFormat); - + nbSample_ = audiolayer->getMic (micData, bytesAvail) / sizeof (SFLDataFormat); + // Store the number of samples for recording - nbSampleForRec_ = nbSample_; - - // _debug("IAXVoIPLink::sendAudioFromMic : %i \n",nbSampleForRec_); + nbSampleForRec_ = nbSample_; + + // _debug("IAXVoIPLink::sendAudioFromMic : %i \n",nbSampleForRec_); // resample - nbSample_ = converter->downsampleData( micData , micDataConverted , (int)ac ->getClockRate() , (int)audiolayer->getSampleRate() , nbSample_ ); + nbSample_ = converter->downsampleData (micData , micDataConverted , (int) ac ->getClockRate() , (int) audiolayer->getSampleRate() , nbSample_); // for the mono: range = 0 to IAX_FRAME2SEND * sizeof(int16) - compSize = ac->codecEncode( micDataEncoded, micDataConverted , nbSample_*sizeof(int16)); + compSize = ac->codecEncode (micDataEncoded, micDataConverted , nbSample_*sizeof (int16)); // Send it out! _mutexIAX.enterMutex(); + // Make sure the session and the call still exists. if (currentCall->getSession() && micDataEncoded != NULL) { - if (iax_send_voice(currentCall->getSession(), currentCall->getFormat(), micDataEncoded, compSize, nbSample_) == -1) { - _debug("IAX: Error sending voice data.\n"); + if (iax_send_voice (currentCall->getSession(), currentCall->getFormat(), micDataEncoded, compSize, nbSample_) == -1) { + _debug ("IAX: Error sending voice data.\n"); } } + _mutexIAX.leaveMutex(); } } - IAXCall* -IAXVoIPLink::getIAXCall(const CallID& id) +IAXCall* +IAXVoIPLink::getIAXCall (const CallID& id) { - Call* call = getCall(id); + Call* call = getCall (id); + if (call) { - return dynamic_cast<IAXCall*>(call); + return dynamic_cast<IAXCall*> (call); } + return NULL; } - int -IAXVoIPLink::sendRegister(AccountID id) +int +IAXVoIPLink::sendRegister (AccountID id) { IAXAccount *account; bool result; result = false; account = dynamic_cast<IAXAccount *> (getAccountPtr()); + if (account->getHostname().empty()) { return false; } + if (account->getUsername().empty()) { return false; } @@ -361,23 +389,23 @@ IAXVoIPLink::sendRegister(AccountID id) // Always use a brand new session if (_regSession) { - iax_destroy(_regSession); + iax_destroy (_regSession); } _regSession = iax_session_new(); if (!_regSession) { - _debug("Error when generating new session for register"); + _debug ("Error when generating new session for register"); } else { - _debug("IAX Sending registration to %s with user %s\n", account->getHostname().c_str() , account->getUsername().c_str() ); - int val = iax_register(_regSession, account->getHostname().data(), account->getUsername().data(), account->getPassword().data(), 120); + _debug ("IAX Sending registration to %s with user %s\n", account->getHostname().c_str() , account->getUsername().c_str()); + int val = iax_register (_regSession, account->getHostname().data(), account->getUsername().data(), account->getPassword().data(), 120); _debug ("Return value: %d\n", val); // set the time-out to 15 seconds, after that, resend a registration request. // until we unregister. - _nextRefreshStamp = time(NULL) + 10; + _nextRefreshStamp = time (NULL) + 10; result = true; - account->setRegistrationState(Trying); + account->setRegistrationState (Trying); } // unlock @@ -386,163 +414,174 @@ IAXVoIPLink::sendRegister(AccountID id) return result; } - int -IAXVoIPLink::sendUnregister(AccountID id) +int +IAXVoIPLink::sendUnregister (AccountID id) { IAXAccount *account; - account = dynamic_cast<IAXAccount*>(getAccountPtr()); - if(!account) + account = dynamic_cast<IAXAccount*> (getAccountPtr()); + + if (!account) return 1; _mutexIAX.enterMutex(); + if (_regSession) { /** @todo Should send a REGREL in sendUnregister()... */ //iax_send_regrel(); doesn't exist yet :) - iax_destroy(_regSession); + iax_destroy (_regSession); _regSession = NULL; } + _mutexIAX.leaveMutex(); _nextRefreshStamp = 0; - _debug("IAX2 send unregister\n"); - account->setRegistrationState(Unregistered); + _debug ("IAX2 send unregister\n"); + account->setRegistrationState (Unregistered); return SUCCESS; } - Call* -IAXVoIPLink::newOutgoingCall(const CallID& id, const std::string& toUrl) +Call* +IAXVoIPLink::newOutgoingCall (const CallID& id, const std::string& toUrl) { - IAXCall* call = new IAXCall(id, Call::Outgoing); - call->setCodecMap(Manager::instance().getCodecDescriptorMap()); + IAXCall* call = new IAXCall (id, Call::Outgoing); + call->setCodecMap (Manager::instance().getCodecDescriptorMap()); if (call) { - call->setPeerNumber(toUrl); + call->setPeerNumber (toUrl); call->initRecFileName(); - - if ( iaxOutgoingInvite(call) ) { - call->setConnectionState(Call::Progressing); - call->setState(Call::Active); - addCall(call); + + if (iaxOutgoingInvite (call)) { + call->setConnectionState (Call::Progressing); + call->setState (Call::Active); + addCall (call); } else { - delete call; call = NULL; + delete call; + call = NULL; } } + return call; } - bool -IAXVoIPLink::answer(const CallID& id) +bool +IAXVoIPLink::answer (const CallID& id) { - IAXCall* call = getIAXCall(id); - call->setCodecMap(Manager::instance().getCodecDescriptorMap()); + IAXCall* call = getIAXCall (id); + call->setCodecMap (Manager::instance().getCodecDescriptorMap()); CHK_VALID_CALL; _mutexIAX.enterMutex(); - iax_answer(call->getSession()); + iax_answer (call->getSession()); _mutexIAX.leaveMutex(); - call->setState(Call::Active); - call->setConnectionState(Call::Connected); + call->setState (Call::Active); + call->setConnectionState (Call::Connected); // Start audio audiolayer->startStream(); return true; } - bool -IAXVoIPLink::hangup(const CallID& id) +bool +IAXVoIPLink::hangup (const CallID& id) { - _debug("IAXVoIPLink::hangup() : function called once hangup \n"); - IAXCall* call = getIAXCall(id); + _debug ("IAXVoIPLink::hangup() : function called once hangup \n"); + IAXCall* call = getIAXCall (id); std::string reason = "Dumped Call"; CHK_VALID_CALL; _mutexIAX.enterMutex(); - - iax_hangup(call->getSession(), (char*) reason.c_str()); + + iax_hangup (call->getSession(), (char*) reason.c_str()); _mutexIAX.leaveMutex(); - call->setSession(NULL); - if (Manager::instance().isCurrentCall(id)) { + call->setSession (NULL); + + if (Manager::instance().isCurrentCall (id)) { // stop audio audiolayer->stopStream(); } - terminateOneCall(id); - removeCall(id); - return true; + + terminateOneCall (id); + + removeCall (id); + return true; } -bool -IAXVoIPLink::peerHungup(const CallID& id) +bool +IAXVoIPLink::peerHungup (const CallID& id) { - _debug("IAXVoIPLink::peerHangup() : function called once hangup \n"); - IAXCall* call = getIAXCall(id); + _debug ("IAXVoIPLink::peerHangup() : function called once hangup \n"); + IAXCall* call = getIAXCall (id); std::string reason = "Dumped Call"; CHK_VALID_CALL; _mutexIAX.enterMutex(); - + _mutexIAX.leaveMutex(); - call->setSession(NULL); - if (Manager::instance().isCurrentCall(id)) { + call->setSession (NULL); + + if (Manager::instance().isCurrentCall (id)) { // stop audio audiolayer->stopStream(); } - terminateOneCall(id); - removeCall(id); - return true; + + terminateOneCall (id); + + removeCall (id); + return true; } - bool -IAXVoIPLink::onhold(const CallID& id) +bool +IAXVoIPLink::onhold (const CallID& id) { - IAXCall* call = getIAXCall(id); + IAXCall* call = getIAXCall (id); CHK_VALID_CALL; //if (call->getState() == Call::Hold) { _debug("Call is already on hold\n"); return false; } _mutexIAX.enterMutex(); - iax_quelch_moh(call->getSession() , MUSIC_ONHOLD); + iax_quelch_moh (call->getSession() , MUSIC_ONHOLD); _mutexIAX.leaveMutex(); - call->setState(Call::Hold); + call->setState (Call::Hold); return true; } - bool -IAXVoIPLink::offhold(const CallID& id) +bool +IAXVoIPLink::offhold (const CallID& id) { - IAXCall* call = getIAXCall(id); + IAXCall* call = getIAXCall (id); CHK_VALID_CALL; //if (call->getState() == Call::Active) { _debug("Call is already active\n"); return false; } _mutexIAX.enterMutex(); - iax_unquelch(call->getSession()); + iax_unquelch (call->getSession()); _mutexIAX.leaveMutex(); audiolayer->startStream(); - call->setState(Call::Active); + call->setState (Call::Active); return true; } - bool -IAXVoIPLink::transfer(const CallID& id, const std::string& to) +bool +IAXVoIPLink::transfer (const CallID& id, const std::string& to) { - IAXCall* call = getIAXCall(id); + IAXCall* call = getIAXCall (id); CHK_VALID_CALL; - char callto[to.length()+1]; - strcpy(callto, to.c_str()); + char callto[to.length() +1]; + strcpy (callto, to.c_str()); _mutexIAX.enterMutex(); - iax_transfer(call->getSession(), callto); + iax_transfer (call->getSession(), callto); _mutexIAX.leaveMutex(); return true; @@ -551,143 +590,154 @@ IAXVoIPLink::transfer(const CallID& id, const std::string& to) // removeCall(id); } - bool -IAXVoIPLink::refuse(const CallID& id) +bool +IAXVoIPLink::refuse (const CallID& id) { - IAXCall* call = getIAXCall(id); + IAXCall* call = getIAXCall (id); std::string reason = "Call rejected manually."; CHK_VALID_CALL; _mutexIAX.enterMutex(); - iax_reject(call->getSession(), (char*) reason.c_str()); + iax_reject (call->getSession(), (char*) reason.c_str()); _mutexIAX.leaveMutex(); // terminateOneCall(id); - removeCall(id); + removeCall (id); return true; } -void -IAXVoIPLink::setRecording(const CallID& id) +void +IAXVoIPLink::setRecording (const CallID& id) { - _debug("IAXVoIPLink::setRecording()!"); + _debug ("IAXVoIPLink::setRecording()!"); - IAXCall* call = getIAXCall(id); + IAXCall* call = getIAXCall (id); - call->setRecording(); + call->setRecording(); } -bool -IAXVoIPLink::isRecording(const CallID& id) +bool +IAXVoIPLink::isRecording (const CallID& id) { - _debug("IAXVoIPLink::setRecording()!"); + _debug ("IAXVoIPLink::setRecording()!"); - IAXCall* call = getIAXCall(id); + IAXCall* call = getIAXCall (id); - return call->isRecording(); + return call->isRecording(); } - bool -IAXVoIPLink::carryingDTMFdigits(const CallID& id, char code) +bool +IAXVoIPLink::carryingDTMFdigits (const CallID& id, char code) { - IAXCall* call = getIAXCall(id); + IAXCall* call = getIAXCall (id); CHK_VALID_CALL; _mutexIAX.enterMutex(); - iax_send_dtmf(call->getSession(), code); + iax_send_dtmf (call->getSession(), code); _mutexIAX.leaveMutex(); return true; } -std::string +std::string IAXVoIPLink::getCurrentCodecName() { - IAXCall *call = getIAXCall(Manager::instance().getCurrentCallId()); - - AudioCodec *ac = call->getCodecMap().getCodec(call->getAudioCodec()); - + IAXCall *call = getIAXCall (Manager::instance().getCurrentCallId()); + + AudioCodec *ac = call->getCodecMap().getCodec (call->getAudioCodec()); + return ac->getCodecName(); } - bool -IAXVoIPLink::iaxOutgoingInvite(IAXCall* call) +bool +IAXVoIPLink::iaxOutgoingInvite (IAXCall* call) { + struct iax_session *newsession; - ost::MutexLock m(_mutexIAX); + ost::MutexLock m (_mutexIAX); std::string username, strNum; char *lang=NULL; int wait, audio_format_preferred, audio_format_capability; IAXAccount *account; newsession = iax_session_new(); + if (!newsession) { - _debug("IAX Error: Can't make new session for a new call\n"); + _debug ("IAX Error: Can't make new session for a new call\n"); return false; } - call->setSession(newsession); + + call->setSession (newsession); account = dynamic_cast<IAXAccount*> (getAccountPtr()); username = account->getUsername(); - strNum = username + ":" + account->getPassword() + "@" + account->getHostname() + "/" + call->getPeerNumber(); + strNum = username + ":" + account->getPassword() + "@" + account->getHostname() + "/" + call->getPeerNumber(); wait = 0; /** @todo Make preference dynamic, and configurable */ - audio_format_preferred = call->getFirstMatchingFormat(call->getSupportedFormat()); + audio_format_preferred = call->getFirstMatchingFormat (call->getSupportedFormat()); audio_format_capability = call->getSupportedFormat(); - _debug("IAX New call: %s\n", strNum.c_str()); - iax_call(newsession, username.c_str(), username.c_str(), strNum.c_str(), lang, wait, audio_format_preferred, audio_format_capability); + _debug ("IAX New call: %s\n", strNum.c_str()); + iax_call (newsession, username.c_str(), username.c_str(), strNum.c_str(), lang, wait, audio_format_preferred, audio_format_capability); return true; } - IAXCall* -IAXVoIPLink::iaxFindCallBySession(struct iax_session* session) +IAXCall* +IAXVoIPLink::iaxFindCallBySession (struct iax_session* session) { // access to callMap shoud use that - // the code below is like findSIPCallWithCid() - ost::MutexLock m(_callMapMutex); + // the code below is like findSIPCallWithCid() + ost::MutexLock m (_callMapMutex); IAXCall* call = NULL; CallMap::iterator iter = _callMap.begin(); - while(iter != _callMap.end()) { - call = dynamic_cast<IAXCall*>(iter->second); + + while (iter != _callMap.end()) { + call = dynamic_cast<IAXCall*> (iter->second); + if (call && call->getSession() == session) { return call; } + iter++; } + return NULL; // not found } - void -IAXVoIPLink::iaxHandleCallEvent(iax_event* event, IAXCall* call) +void +IAXVoIPLink::iaxHandleCallEvent (iax_event* event, IAXCall* call) { // call should not be 0 // note activity? // CallID id = call->getCallId(); - switch(event->etype) { + switch (event->etype) { + case IAX_EVENT_HANGUP: - if (Manager::instance().isCurrentCall(id)) { + + if (Manager::instance().isCurrentCall (id)) { // stop audio audiolayer->stopStream(); } - Manager::instance().peerHungupCall(id); + + Manager::instance().peerHungupCall (id); + /* - _debug("IAXVoIPLink::iaxHandleCallEvent, peer hangup have been called"); + _debug("IAXVoIPLink::iaxHandleCallEvent, peer hangup have been called"); std::string reason = "Dumped Call"; _mutexIAX.enterMutex(); iax_hangup(call->getSession(), (char*)reason.c_str()); @@ -695,83 +745,94 @@ IAXVoIPLink::iaxHandleCallEvent(iax_event* event, IAXCall* call) call->setSession(NULL); audiolayer->stopStream(); terminateOneCall(id); - */ - removeCall(id); + */ + removeCall (id); break; case IAX_EVENT_REJECT: - //Manager::instance().peerHungupCall(id); - if (Manager::instance().isCurrentCall(id)) { + //Manager::instance().peerHungupCall(id); + + if (Manager::instance().isCurrentCall (id)) { // stop audio audiolayer->stopStream(); } - call->setConnectionState(Call::Connected); - call->setState(Call::Error); - Manager::instance().callFailure(id); + + call->setConnectionState (Call::Connected); + + call->setState (Call::Error); + Manager::instance().callFailure (id); // terminateOneCall(id); - removeCall(id); + removeCall (id); break; case IAX_EVENT_ACCEPT: // Call accepted over there by the computer, not the user yet. + if (event->ies.format) { - call->setFormat(event->ies.format); + call->setFormat (event->ies.format); } + break; case IAX_EVENT_ANSWER: - if (call->getConnectionState() != Call::Connected){ - call->setConnectionState(Call::Connected); - call->setState(Call::Active); + + if (call->getConnectionState() != Call::Connected) { + call->setConnectionState (Call::Connected); + call->setState (Call::Active); audiolayer->startStream(); if (event->ies.format) { // Should not get here, should have been set in EVENT_ACCEPT - call->setFormat(event->ies.format); + call->setFormat (event->ies.format); } - Manager::instance().peerAnsweredCall(id); + Manager::instance().peerAnsweredCall (id); + // start audio here? } else { // deja connecté ? } + break; case IAX_EVENT_BUSY: - call->setConnectionState(Call::Connected); - call->setState(Call::Busy); - Manager::instance().callBusy(id); + call->setConnectionState (Call::Connected); + call->setState (Call::Busy); + Manager::instance().callBusy (id); // terminateOneCall(id); - removeCall(id); + removeCall (id); break; case IAX_EVENT_VOICE: //if (!audiolayer->isCaptureActive ()) - // audiolayer->startStream (); + // audiolayer->startStream (); // _debug("IAX_EVENT_VOICE: \n"); - iaxHandleVoiceEvent(event, call); + iaxHandleVoiceEvent (event, call); break; case IAX_EVENT_TEXT: break; case IAX_EVENT_RINGA: - call->setConnectionState(Call::Ringing); - Manager::instance().peerRingingCall(call->getCallId()); + call->setConnectionState (Call::Ringing); + Manager::instance().peerRingingCall (call->getCallId()); break; - case IAX_IE_MSGCOUNT: + case IAX_IE_MSGCOUNT: break; + case IAX_EVENT_PONG: break; case IAX_EVENT_URL: + if (Manager::instance().getConfigString (HOOKS, URLHOOK_IAX2_ENABLED) == "1") { - if (strcmp((char*)event->data, "") != 0) { + if (strcmp ( (char*) event->data, "") != 0) { _debug ("> IAX_EVENT_URL received: %s\n", event->data); - urlhook->addAction ((char*)event->data, Manager::instance().getConfigString (HOOKS, URLHOOK_COMMAND)); + urlhook->addAction ( (char*) event->data, Manager::instance().getConfigString (HOOKS, URLHOOK_COMMAND)); } } + break; case IAX_EVENT_TIMEOUT: @@ -781,24 +842,25 @@ IAXVoIPLink::iaxHandleCallEvent(iax_event* event, IAXCall* call) break; default: - _debug("Unknown event type (in call event): %d\n", event->etype); + _debug ("Unknown event type (in call event): %d\n", event->etype); } } /* Handle audio event, VOICE packet received */ - void -IAXVoIPLink::iaxHandleVoiceEvent(iax_event* event, IAXCall* call) -{ +void +IAXVoIPLink::iaxHandleVoiceEvent (iax_event* event, IAXCall* call) +{ unsigned char *data; unsigned int size, max, nbInt16; - int expandedSize, nbSample_; + int expandedSize, nbSample_; AudioCodec *ac; // If we receive datalen == 0, some things of the jitter buffer in libiax2/iax.c // were triggered + if (!event->datalen) { // Skip this empty packet. //_debug("IAX: Skipping empty jitter-buffer interpolated packet\n"); @@ -810,39 +872,43 @@ IAXVoIPLink::iaxHandleVoiceEvent(iax_event* event, IAXCall* call) // as per http://tools.ietf.org/id/draft-guy-iax-03.txt // - subclass holds the voiceformat property. if (event->subclass && event->subclass != call->getFormat()) { - call->setFormat(event->subclass); + call->setFormat (event->subclass); } + //_debug("Receive: len=%d, format=%d, _receiveDataDecoded=%p\n", event->datalen, call->getFormat(), _receiveDataDecoded); - ac = call->getCodecMap().getCodec( call -> getAudioCodec() ); + ac = call->getCodecMap().getCodec (call -> getAudioCodec()); + + data = (unsigned char*) event->data; - data = (unsigned char*)event->data; size = event->datalen; // Decode data with relevant codec - max = (int)( ac->getClockRate() * audiolayer->getFrameSize() / 1000 ); + max = (int) (ac->getClockRate() * audiolayer->getFrameSize() / 1000); if (size > max) { - _debug("The size %d is bigger than expected %d. Packet cropped. Ouch!\n", size, max); + _debug ("The size %d is bigger than expected %d. Packet cropped. Ouch!\n", size, max); size = max; } - expandedSize = ac->codecDecode( spkrDataDecoded , data , size ); - nbInt16 = expandedSize/sizeof(int16); + expandedSize = ac->codecDecode (spkrDataDecoded , data , size); + + nbInt16 = expandedSize/sizeof (int16); if (nbInt16 > max) { - _debug("We have decoded an IAX VOICE packet larger than expected: %i VS %i. Cropping.\n", nbInt16, max); + _debug ("We have decoded an IAX VOICE packet larger than expected: %i VS %i. Cropping.\n", nbInt16, max); nbInt16 = max; } nbSample_ = nbInt16; + // resample - nbInt16 = converter->upsampleData( spkrDataDecoded , spkrDataConverted , ac->getClockRate() , audiolayer->getSampleRate() , nbSample_); + nbInt16 = converter->upsampleData (spkrDataDecoded , spkrDataConverted , ac->getClockRate() , audiolayer->getSampleRate() , nbSample_); /* Write the data to the mic ring buffer */ - audiolayer->putMain (spkrDataConverted , nbInt16 * sizeof(SFLDataFormat)); + audiolayer->putMain (spkrDataConverted , nbInt16 * sizeof (SFLDataFormat)); } else { - _debug("IAX: incoming audio, but no sound card open"); + _debug ("IAX: incoming audio, but no sound card open"); } } @@ -850,25 +916,25 @@ IAXVoIPLink::iaxHandleVoiceEvent(iax_event* event, IAXCall* call) /** * Handle the registration process */ - void -IAXVoIPLink::iaxHandleRegReply(iax_event* event) +void +IAXVoIPLink::iaxHandleRegReply (iax_event* event) { int new_voicemails; std::string account_id; IAXAccount *account; - + account_id = getAccountID(); - account = dynamic_cast<IAXAccount *>(Manager::instance().getAccount(account_id)); + account = dynamic_cast<IAXAccount *> (Manager::instance().getAccount (account_id)); if (event->etype == IAX_EVENT_REGREJ) { /* Authentication failed! */ _mutexIAX.enterMutex(); - iax_destroy(_regSession); + iax_destroy (_regSession); _mutexIAX.leaveMutex(); _regSession = NULL; // Update the account registration state - account->setRegistrationState(ErrorAuth); + account->setRegistrationState (ErrorAuth); } else if (event->etype == IAX_EVENT_REGACK) { @@ -876,25 +942,25 @@ IAXVoIPLink::iaxHandleRegReply(iax_event* event) _mutexIAX.enterMutex(); // Looking for the voicemail information - //if( event->ies != 0 ) + //if( event->ies != 0 ) //new_voicemails = processIAXMsgCount(event->ies.msgcount); //_debug("iax voicemail number notification: %i\n", new_voicemails); // Notify the client if new voicemail waiting for the current account //account_id = getAccountID(); //Manager::instance().startVoiceMessageNotification(account_id.c_str(), new_voicemails); - iax_destroy(_regSession); + iax_destroy (_regSession); _mutexIAX.leaveMutex(); _regSession = NULL; // I mean, save the timestamp, so that we re-register again in the REFRESH time. // Defaults to 60, as per draft-guy-iax-03. - _nextRefreshStamp = time(NULL) + (event->ies.refresh ? event->ies.refresh : 60); - account->setRegistrationState(Registered); + _nextRefreshStamp = time (NULL) + (event->ies.refresh ? event->ies.refresh : 60); + account->setRegistrationState (Registered); } } -int IAXVoIPLink::processIAXMsgCount( int msgcount ) +int IAXVoIPLink::processIAXMsgCount (int msgcount) { // IAX sends the message count under a specific format: @@ -907,7 +973,7 @@ int IAXVoIPLink::processIAXMsgCount( int msgcount ) // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // For now we just need the new messages informations. - // Thus: + // Thus: // 0 <= msgcount <= 255 => msgcount new messages, 0 old messages // msgcount >= 256 => msgcount/256 old messages , msgcount%256 new messages (RULES) @@ -916,107 +982,114 @@ int IAXVoIPLink::processIAXMsgCount( int msgcount ) } - void -IAXVoIPLink::iaxHandlePrecallEvent(iax_event* event) +void +IAXVoIPLink::iaxHandlePrecallEvent (iax_event* event) { IAXCall* call = NULL; CallID id; std::string reason = "Error ringing user."; - switch(event->etype) { + switch (event->etype) { + case IAX_EVENT_REGACK: + case IAX_EVENT_REGREJ: - _debug("IAX Registration Event in a pre-call setup\n"); + _debug ("IAX Registration Event in a pre-call setup\n"); break; case IAX_EVENT_REGREQ: // Received when someone wants to register to us!?! // Asterisk receives and answers to that, not us, we're a phone. - _debug("Registration by a peer, don't allow it\n"); + _debug ("Registration by a peer, don't allow it\n"); break; case IAX_EVENT_CONNECT: // We've got an incoming call! Yikes! - _debug("> IAX_EVENT_CONNECT (receive)\n"); + _debug ("> IAX_EVENT_CONNECT (receive)\n"); id = Manager::instance().getNewCallID(); - call = new IAXCall(id, Call::Incoming); + call = new IAXCall (id, Call::Incoming); if (!call) { - _debug("! IAX Failure: unable to create an incoming call"); + _debug ("! IAX Failure: unable to create an incoming call"); return; } // Setup the new IAXCall // Associate the call to the session. - call->setSession(event->session); + call->setSession (event->session); // setCallAudioLocal(call); - call->setCodecMap(Manager::instance().getCodecDescriptorMap()); - call->setConnectionState(Call::Progressing); + call->setCodecMap (Manager::instance().getCodecDescriptorMap()); + + call->setConnectionState (Call::Progressing); if (event->ies.calling_number) - call->setPeerNumber(std::string(event->ies.calling_number)); - if (event->ies.calling_name) - call->setPeerName(std::string(event->ies.calling_name)); - + call->setPeerNumber (std::string (event->ies.calling_number)); + + if (event->ies.calling_name) + call->setPeerName (std::string (event->ies.calling_name)); + // if peerNumber exist append it to the name string call->initRecFileName(); - if (Manager::instance().incomingCall(call, getAccountID())) { + if (Manager::instance().incomingCall (call, getAccountID())) { /** @todo Faudra considérer éventuellement le champ CODEC PREFS pour * l'établissement du codec de transmission */ // Remote lists its capabilities - int format = call->getFirstMatchingFormat(event->ies.capability); + int format = call->getFirstMatchingFormat (event->ies.capability); // Remote asks for preferred codec voiceformat - int pref_format = call->getFirstMatchingFormat(event->ies.format); + int pref_format = call->getFirstMatchingFormat (event->ies.format); // Priority to remote's suggestion. In case it's a forwarding, no transcoding // will be needed from the server, thus less latency. + if (pref_format) format = pref_format; - iax_accept(event->session, format); - iax_ring_announce(event->session); + iax_accept (event->session, format); + + iax_ring_announce (event->session); - addCall(call); + addCall (call); } else { // reject call, unable to add it - iax_reject(event->session, (char*)reason.c_str()); + iax_reject (event->session, (char*) reason.c_str()); - delete call; call = NULL; + delete call; + call = NULL; } break; case IAX_EVENT_HANGUP: // Remote peer hung up - call = iaxFindCallBySession(event->session); + call = iaxFindCallBySession (event->session); id = call->getCallId(); - _debug("IAXVoIPLink::hungup::iaxHandlePrecallEvent"); - Manager::instance().peerHungupCall(id); + _debug ("IAXVoIPLink::hungup::iaxHandlePrecallEvent"); + Manager::instance().peerHungupCall (id); // terminateOneCall(id); - removeCall(id); + removeCall (id); break; case IAX_EVENT_TIMEOUT: // timeout for an unknown session break; - case IAX_IE_MSGCOUNT: + case IAX_IE_MSGCOUNT: //_debug("messssssssssssssssssssssssssssssssssssssssssssssssages\n"); break; default: - _debug("Unknown event type (in precall): %d\n", event->etype); + _debug ("Unknown event type (in precall): %d\n", event->etype); } } -void IAXVoIPLink::updateAudiolayer( void ) +void IAXVoIPLink::updateAudiolayer (void) { _mutexIAX.enterMutex(); audiolayer = NULL; diff --git a/sflphone-common/src/main.cpp b/sflphone-common/src/main.cpp index 85f9170e57..5eb4ced27b 100644 --- a/sflphone-common/src/main.cpp +++ b/sflphone-common/src/main.cpp @@ -3,17 +3,17 @@ * Author: Alexandre Bourget <alexandre.bourget@savoirfairelinux.com> * Author: Yan Morin <yan.morin@savoirfairelinux.com> * Author: Laurielle Lea <laurielle.lea@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 2 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -35,101 +35,107 @@ #include "audio/audiolayer.h" int -main (int argc, char **argv) { - int exit_code = 0; - - //setlocale (LC_ALL, ""); - //bindtextdomain (PACKAGE, LOCALEDIR); - //textdomain (PACKAGE); - - if (argc == 2 && strcmp(argv[1], "--help") == 0) { - - - printf("%1$s Daemon %2$s, by Savoir-Faire Linux 2004-2009\n\n", - PROGNAME, - SFLPHONED_VERSION); - printf("USAGE: sflphoned [--help]\nParameters: \n --help\tfor this message\n\n --port=3999\tchange the session port\n\n"); - printf("See http://www.sflphone.org/ for more information\n"); - - } else { - FILE *fp; - char homepid[128]; - char sfldir[128]; - - unsigned int iPid = getpid(); - char cPid[64], cOldPid[64]; - sprintf(cPid,"%d", iPid); - - sprintf(homepid, "%s/.%s/%s", HOMEDIR, PROGDIR, PIDFILE); - sprintf(sfldir, "%s/.%s", HOMEDIR, PROGDIR); - - if( (fp = fopen(homepid,"r")) == NULL ){ - // Check if $HOME/.sflphone directory exists or not. - DIR *dir; - if ( (dir = opendir (sfldir)) == NULL) { - //Create it - if ( mkdir(sfldir, 0755) != 0){ - fprintf(stderr, "Creating directory %s failed. Exited.\n", sfldir ); - exit(-1); - } - } - - // PID file doesn't exists, create and write pid in it - if( (fp = fopen(homepid,"w")) == NULL ){ - fprintf(stderr, "Creating PID file %s failed. Exited.\n", homepid); - exit(-1); - } else { - fputs(cPid , fp ); - fclose( fp ); - } +main (int argc, char **argv) +{ + int exit_code = 0; + + //setlocale (LC_ALL, ""); + //bindtextdomain (PACKAGE, LOCALEDIR); + //textdomain (PACKAGE); + + if (argc == 2 && strcmp (argv[1], "--help") == 0) { + + + printf ("%1$s Daemon %2$s, by Savoir-Faire Linux 2004-2009\n\n", + PROGNAME, + SFLPHONED_VERSION); + printf ("USAGE: sflphoned [--help]\nParameters: \n --help\tfor this message\n\n --port=3999\tchange the session port\n\n"); + printf ("See http://www.sflphone.org/ for more information\n"); + } else { - // PID file exists. Check the former process still alive or not. If alive, give user a hint. - fgets( cOldPid, 64, fp ); - fclose(fp); - if (kill(atoi(cOldPid), 0) == SUCCESS) { - fprintf(stderr, "There is already a sflphoned daemon running in the system. Starting Failed.\n"); - exit(-1); - } else { - if( (fp = fopen(homepid,"w")) == NULL ){ - fprintf(stderr, "Writing to PID file %s failed. Exited.\n", homepid); - exit(-1); - } else { - fputs(cPid , fp ); - fclose( fp ); - } - - } - } - - int sessionPort = 0; - if (argc == 2) { - char* ptrPort = strstr(argv[1], "--port="); - if (ptrPort != 0) { - sessionPort = atoi(ptrPort+7); - } - } - bool initOK = false; - try { - _debug("Initialize manager in main \n"); - Manager::instance().initConfigFile(); - Manager::instance().init(); - initOK = true; - } - catch (std::exception &e) { - std::cerr << e.what() << std::endl; - exit_code = -1; - } - catch (...) { - fprintf(stderr, "An exception occured when initializing the system.\n"); - exit_code = -1; - } - if (initOK) { - Manager::instance().setDBusManager(&DBusManager::instance()); - exit_code = DBusManager::instance().exec(); // UI Loop + FILE *fp; + char homepid[128]; + char sfldir[128]; + + unsigned int iPid = getpid(); + char cPid[64], cOldPid[64]; + sprintf (cPid,"%d", iPid); + + sprintf (homepid, "%s/.%s/%s", HOMEDIR, PROGDIR, PIDFILE); + sprintf (sfldir, "%s/.%s", HOMEDIR, PROGDIR); + + if ( (fp = fopen (homepid,"r")) == NULL) { + // Check if $HOME/.sflphone directory exists or not. + DIR *dir; + + if ( (dir = opendir (sfldir)) == NULL) { + //Create it + if (mkdir (sfldir, 0755) != 0) { + fprintf (stderr, "Creating directory %s failed. Exited.\n", sfldir); + exit (-1); + } + } + + // PID file doesn't exists, create and write pid in it + if ( (fp = fopen (homepid,"w")) == NULL) { + fprintf (stderr, "Creating PID file %s failed. Exited.\n", homepid); + exit (-1); + } else { + fputs (cPid , fp); + fclose (fp); + } + } else { + // PID file exists. Check the former process still alive or not. If alive, give user a hint. + fgets (cOldPid, 64, fp); + fclose (fp); + + if (kill (atoi (cOldPid), 0) == SUCCESS) { + fprintf (stderr, "There is already a sflphoned daemon running in the system. Starting Failed.\n"); + exit (-1); + } else { + if ( (fp = fopen (homepid,"w")) == NULL) { + fprintf (stderr, "Writing to PID file %s failed. Exited.\n", homepid); + exit (-1); + } else { + fputs (cPid , fp); + fclose (fp); + } + + } + } + + int sessionPort = 0; + + if (argc == 2) { + char* ptrPort = strstr (argv[1], "--port="); + + if (ptrPort != 0) { + sessionPort = atoi (ptrPort+7); + } + } + + bool initOK = false; + + try { + _debug ("Initialize manager in main \n"); + Manager::instance().initConfigFile(); + Manager::instance().init(); + initOK = true; + } catch (std::exception &e) { + std::cerr << e.what() << std::endl; + exit_code = -1; + } catch (...) { + fprintf (stderr, "An exception occured when initializing the system.\n"); + exit_code = -1; + } + + if (initOK) { + Manager::instance().setDBusManager (&DBusManager::instance()); + exit_code = DBusManager::instance().exec(); // UI Loop + } } - } - return exit_code; + return exit_code; } // EOF diff --git a/sflphone-common/src/managerimpl.cpp b/sflphone-common/src/managerimpl.cpp index d4f6720b44..7a49b2c04a 100644 --- a/sflphone-common/src/managerimpl.cpp +++ b/sflphone-common/src/managerimpl.cpp @@ -54,30 +54,30 @@ (_config.addConfigTreeItem(section, Conf::ConfigTreeItem(std::string(name), std::string(value), type_int))) ManagerImpl::ManagerImpl (void) - : _hasTriedToRegister(false) + : _hasTriedToRegister (false) , _config() - , _currentCallId2() + , _currentCallId2() , _currentCallMutex() - , _codecBuilder(NULL) - , _audiodriver(NULL) - , _dtmfKey(NULL) + , _codecBuilder (NULL) + , _audiodriver (NULL) + , _dtmfKey (NULL) , _codecDescriptorMap() , _toneMutex() - , _telephoneTone(NULL) + , _telephoneTone (NULL) , _audiofile() - , _spkr_volume(0) - , _mic_volume(0) + , _spkr_volume (0) + , _mic_volume (0) , _mutex() - , _dbus(NULL) + , _dbus (NULL) , _waitingCall() , _waitingCallMutex() - , _nbIncomingWaitingCall(0) - , _path("") - , _exist(0) - , _setupLoaded(false) + , _nbIncomingWaitingCall (0) + , _path ("") + , _exist (0) + , _setupLoaded (false) , _firewallPort() - , _firewallAddr("") - , _hasZeroconf(false) + , _firewallAddr ("") + , _hasZeroconf (false) , _callAccountMap() , _callAccountMapMutex() , _callConfigMap() @@ -87,31 +87,32 @@ ManagerImpl::ManagerImpl (void) { // initialize random generator for call id - srand (time(NULL)); + srand (time (NULL)); _cleaner = new NumberCleaner (); _history = new HistoryManager (); #ifdef TEST - testAccountMap(); - loadAccountMap(); - testCallAccountMap(); - unloadAccountMap(); + testAccountMap(); + loadAccountMap(); + testCallAccountMap(); + unloadAccountMap(); #endif - // should be call before initConfigFile - // loadAccountMap();, called in init() now. + // should be call before initConfigFile + // loadAccountMap();, called in init() now. } // never call if we use only the singleton... ManagerImpl::~ManagerImpl (void) { // terminate(); - delete _cleaner; _cleaner=0; - _debug("%s stop correctly.\n", PROGNAME); + delete _cleaner; + _cleaner=0; + _debug ("%s stop correctly.\n", PROGNAME); } - void +void ManagerImpl::init() { // Load accounts, init map @@ -120,10 +121,11 @@ ManagerImpl::init() initVolume(); if (_exist == 0) { - _debug("Cannot create config file in your home directory\n"); + _debug ("Cannot create config file in your home directory\n"); } initAudioDriver(); + selectAudioDriver(); // Initialize the list of supported audio codecs @@ -134,12 +136,12 @@ ManagerImpl::init() if (audiolayer != 0) { unsigned int sampleRate = audiolayer->getSampleRate(); - _debugInit("Load Telephone Tone"); - std::string country = getConfigString(PREFERENCES, ZONE_TONE); - _telephoneTone = new TelephoneTone(country, sampleRate); + _debugInit ("Load Telephone Tone"); + std::string country = getConfigString (PREFERENCES, ZONE_TONE); + _telephoneTone = new TelephoneTone (country, sampleRate); - _debugInit("Loading DTMF key"); - _dtmfKey = new DTMF(sampleRate); + _debugInit ("Loading DTMF key"); + _dtmfKey = new DTMF (sampleRate); } if (audiolayer == 0) @@ -152,48 +154,56 @@ ManagerImpl::init() void ManagerImpl::terminate() { - _debug("ManagerImpl::terminate \n"); + _debug ("ManagerImpl::terminate \n"); saveConfig(); unloadAccountMap(); - _debug("Unload DTMF Key \n"); + _debug ("Unload DTMF Key \n"); delete _dtmfKey; - _debug("Unload Audio Driver \n"); - delete _audiodriver; _audiodriver = NULL; + _debug ("Unload Audio Driver \n"); + delete _audiodriver; + _audiodriver = NULL; - _debug("Unload Telephone Tone \n"); - delete _telephoneTone; _telephoneTone = NULL; + _debug ("Unload Telephone Tone \n"); + delete _telephoneTone; + _telephoneTone = NULL; - _debug("Unload Audio Codecs \n"); + _debug ("Unload Audio Codecs \n"); _codecDescriptorMap.deleteHandlePointer(); } bool -ManagerImpl::isCurrentCall(const CallID& callId) { - return (_currentCallId2 == callId ? true : false); +ManagerImpl::isCurrentCall (const CallID& callId) +{ + return (_currentCallId2 == callId ? true : false); } bool -ManagerImpl::hasCurrentCall() { - _debug("Current call ID = %s\n", _currentCallId2.c_str()); - if ( _currentCallId2 != "") { - return true; - } - return false; +ManagerImpl::hasCurrentCall() +{ + _debug ("Current call ID = %s\n", _currentCallId2.c_str()); + + if (_currentCallId2 != "") { + return true; + } + + return false; } const CallID& -ManagerImpl::getCurrentCallId() { - return _currentCallId2; +ManagerImpl::getCurrentCallId() +{ + return _currentCallId2; } void -ManagerImpl::switchCall(const CallID& id ) { - ost::MutexLock m(_currentCallMutex); - _currentCallId2 = id; +ManagerImpl::switchCall (const CallID& id) +{ + ost::MutexLock m (_currentCallMutex); + _currentCallId2 = id; } @@ -202,19 +212,20 @@ ManagerImpl::switchCall(const CallID& id ) { /////////////////////////////////////////////////////////////////////////////// /* Main Thread */ - bool -ManagerImpl::outgoingCall(const std::string& accountid, const CallID& id, const std::string& to) +bool +ManagerImpl::outgoingCall (const std::string& accountid, const CallID& id, const std::string& to) { std::string pattern, to_cleaned; Call::CallConfiguration callConfig; SIPVoIPLink *siplink; - _debug("ManagerImpl::outgoingCall() method \n"); + _debug ("ManagerImpl::outgoingCall() method \n"); - if (getConfigString (HOOKS, PHONE_NUMBER_HOOK_ENABLED) == "1") - _cleaner->set_phone_number_prefix (getConfigString (HOOKS, PHONE_NUMBER_HOOK_ADD_PREFIX )); + if (getConfigString (HOOKS, PHONE_NUMBER_HOOK_ENABLED) == "1") + _cleaner->set_phone_number_prefix (getConfigString (HOOKS, PHONE_NUMBER_HOOK_ADD_PREFIX)); else _cleaner->set_phone_number_prefix (""); + to_cleaned = _cleaner->clean (to); /* Check what kind of call we are dealing with */ @@ -223,215 +234,239 @@ ManagerImpl::outgoingCall(const std::string& accountid, const CallID& id, const if (callConfig == Call::IPtoIP) { _debug ("Start IP to IP call\n"); /* We need to retrieve the sip voiplink instance */ - siplink = SIPVoIPLink::instance(""); + siplink = SIPVoIPLink::instance (""); + if (siplink->new_ip_to_ip_call (id, to_cleaned)) { switchCall (id); return true; - } - else { + } else { callFailure (id); } + return false; } - if (!accountExists(accountid)) { - _debug("! Manager Error: Outgoing Call: account doesn't exist\n"); + if (!accountExists (accountid)) { + _debug ("! Manager Error: Outgoing Call: account doesn't exist\n"); return false; } - if (getAccountFromCall(id) != AccountNULL) { - _debug("! Manager Error: Outgoing Call: call id already exists\n"); + if (getAccountFromCall (id) != AccountNULL) { + _debug ("! Manager Error: Outgoing Call: call id already exists\n"); return false; } if (hasCurrentCall()) { - _debug("* Manager Info: there is currently a call, try to hold it\n"); - onHoldCall(getCurrentCallId()); + _debug ("* Manager Info: there is currently a call, try to hold it\n"); + onHoldCall (getCurrentCallId()); } - _debug("- Manager Action: Adding Outgoing Call %s on account %s\n", id.data(), accountid.data()); - associateCallToAccount( id, accountid ); - if ( getAccountLink(accountid)->newOutgoingCall(id, to_cleaned) ) { - switchCall(id); + _debug ("- Manager Action: Adding Outgoing Call %s on account %s\n", id.data(), accountid.data()); + + associateCallToAccount (id, accountid); + + if (getAccountLink (accountid)->newOutgoingCall (id, to_cleaned)) { + switchCall (id); return true; } else { - callFailure(id); - _debug("! Manager Error: An error occur, the call was not created\n"); + callFailure (id); + _debug ("! Manager Error: An error occur, the call was not created\n"); } + return false; } //THREAD=Main : for outgoing Call - bool -ManagerImpl::answerCall(const CallID& id) +bool +ManagerImpl::answerCall (const CallID& id) { - bool isActive = false; + bool isActive = false; + + stopTone (true); - stopTone(true); + AccountID currentaccountid = getAccountFromCall (id); + Call* currentcall = getAccountLink (currentaccountid)->getCall (getCurrentCallId()); + _debug ("ManagerImpl::answerCall :: current call->getState %i \n",currentcall->getState()); - AccountID currentaccountid = getAccountFromCall( id ); - Call* currentcall = getAccountLink(currentaccountid)->getCall(getCurrentCallId()); - _debug("ManagerImpl::answerCall :: current call->getState %i \n",currentcall->getState()); + if (currentcall->getState() == 1) + isActive = true; - if (currentcall->getState() == 1) - isActive = true; + // stopTone(false); + _debug ("Try to answer call: %s\n", id.data()); - // stopTone(false); - _debug("Try to answer call: %s\n", id.data()); - AccountID accountid = getAccountFromCall( id ); - if (accountid == AccountNULL) { - _debug("Answering Call: Call doesn't exists\n"); - //return false; - } + AccountID accountid = getAccountFromCall (id); - // if (id != getCurrentCallId()) { - if (isActive) { - _debug("* Manager Info: there is currently a call, try to hold it\n"); + if (accountid == AccountNULL) { + _debug ("Answering Call: Call doesn't exists\n"); + //return false; + } - onHoldCall(getCurrentCallId()); - } + // if (id != getCurrentCallId()) { + if (isActive) { + _debug ("* Manager Info: there is currently a call, try to hold it\n"); - if (!getAccountLink(accountid)->answer(id)) { - // error when receiving... - removeCallAccount(id); - return false; - } + onHoldCall (getCurrentCallId()); + } + + if (!getAccountLink (accountid)->answer (id)) { + // error when receiving... + removeCallAccount (id); + return false; + } - // if it was waiting, it's waiting no more - if (_dbus) _dbus->getCallManager()->callStateChanged(id, "CURRENT"); - removeWaitingCall(id); - switchCall(id); + // if it was waiting, it's waiting no more + if (_dbus) _dbus->getCallManager()->callStateChanged (id, "CURRENT"); - // std::string codecName = getCurrentCodecName(id); - // _debug("ManagerImpl::hangupCall(): broadcast codec name %s \n",codecName.c_str()); - // if (_dbus) _dbus->getCallManager()->currentSelectedCodec(id,codecName.c_str()); + removeWaitingCall (id); - return true; + switchCall (id); + + // std::string codecName = getCurrentCodecName(id); + // _debug("ManagerImpl::hangupCall(): broadcast codec name %s \n",codecName.c_str()); + // if (_dbus) _dbus->getCallManager()->currentSelectedCodec(id,codecName.c_str()); + + return true; } //THREAD=Main - bool -ManagerImpl::hangupCall(const CallID& id) +bool +ManagerImpl::hangupCall (const CallID& id) { - _debug("ManagerImpl::hangupCall()\n"); + _debug ("ManagerImpl::hangupCall()\n"); PulseLayer *pulselayer; AccountID accountid; bool returnValue; AudioLayer *audiolayer; - stopTone(false); + stopTone (false); /* Broadcast a signal over DBus */ - if (_dbus) _dbus->getCallManager()->callStateChanged(id, "HUNGUP"); - _debug("Stop audio stream\n"); + if (_dbus) _dbus->getCallManager()->callStateChanged (id, "HUNGUP"); + + _debug ("Stop audio stream\n"); + audiolayer = getAudioDriver(); int nbCalls = getCallList().size(); - _debug("nbCalls %i \n", nbCalls); + _debug ("nbCalls %i \n", nbCalls); - // stop stream - if (!(nbCalls > 1)) + // stop stream + if (! (nbCalls > 1)) audiolayer->stopStream(); /* Direct IP to IP call */ if (getConfigFromCall (id) == Call::IPtoIP) { returnValue = SIPVoIPLink::instance (AccountNULL)->hangup (id); } + /* Classic call, attached to an account */ else { - accountid = getAccountFromCall( id ); + accountid = getAccountFromCall (id); + if (accountid == AccountNULL) { - _debug("! Manager Hangup Call: Call doesn't exists\n"); + _debug ("! Manager Hangup Call: Call doesn't exists\n"); return false; } - returnValue = getAccountLink(accountid)->hangup(id); - removeCallAccount(id); + + returnValue = getAccountLink (accountid)->hangup (id); + + removeCallAccount (id); } - switchCall(""); + switchCall (""); - if( _audiodriver->getLayerType() == PULSEAUDIO && getConfigInt( PREFERENCES , CONFIG_PA_VOLUME_CTRL ) ) { + if (_audiodriver->getLayerType() == PULSEAUDIO && getConfigInt (PREFERENCES , CONFIG_PA_VOLUME_CTRL)) { pulselayer = dynamic_cast<PulseLayer *> (getAudioDriver()); - if(pulselayer) pulselayer->restorePulseAppsVolume(); + + if (pulselayer) pulselayer->restorePulseAppsVolume(); } - + return returnValue; } //THREAD=Main - bool +bool ManagerImpl::cancelCall (const CallID& id) { AccountID accountid; bool returnValue; - stopTone(true); + stopTone (true); /* Direct IP to IP call */ + if (getConfigFromCall (id) == Call::IPtoIP) { returnValue = SIPVoIPLink::instance (AccountNULL)->cancel (id); } /* Classic call, attached to an account */ else { - accountid = getAccountFromCall( id ); + accountid = getAccountFromCall (id); + if (accountid == AccountNULL) { - _debug("! Manager Cancel Call: Call doesn't exists\n"); + _debug ("! Manager Cancel Call: Call doesn't exists\n"); return false; } - returnValue = getAccountLink(accountid)->cancel(id); - removeCallAccount(id); + + returnValue = getAccountLink (accountid)->cancel (id); + + removeCallAccount (id); } // it could be a waiting call? - removeWaitingCall(id); - switchCall(""); + removeWaitingCall (id); + + switchCall (""); return returnValue; } //THREAD=Main - bool -ManagerImpl::onHoldCall(const CallID& id) +bool +ManagerImpl::onHoldCall (const CallID& id) { AccountID accountid; bool returnValue; CallID call_id; - stopTone(true); + stopTone (true); call_id = id; /* Direct IP to IP call */ + if (getConfigFromCall (id) == Call::IPtoIP) { returnValue = SIPVoIPLink::instance (AccountNULL)-> onhold (id); } /* Classic call, attached to an account */ else { - accountid = getAccountFromCall( id ); + accountid = getAccountFromCall (id); + if (accountid == AccountNULL) { - _debug("Manager On Hold Call: Account ID %s or callid %s doesn't exists\n", accountid.c_str(), id.c_str()); + _debug ("Manager On Hold Call: Account ID %s or callid %s doesn't exists\n", accountid.c_str(), id.c_str()); return false; } - returnValue = getAccountLink(accountid)->onhold(id); + + returnValue = getAccountLink (accountid)->onhold (id); } - removeWaitingCall(id); - switchCall(""); + removeWaitingCall (id); + + switchCall (""); - if (_dbus) _dbus->getCallManager()->callStateChanged(call_id, "HOLD"); + if (_dbus) _dbus->getCallManager()->callStateChanged (call_id, "HOLD"); return returnValue; } //THREAD=Main - bool -ManagerImpl::offHoldCall(const CallID& id) +bool +ManagerImpl::offHoldCall (const CallID& id) { AccountID accountid; @@ -439,14 +474,14 @@ ManagerImpl::offHoldCall(const CallID& id) std::string codecName; CallID call_id; - stopTone(false); + stopTone (false); call_id = id; //Place current call on hold if it isn't - if (hasCurrentCall()) - { + + if (hasCurrentCall()) { _debug ("Put the current call (ID=%s) on hold\n", getCurrentCallId().c_str()); - onHoldCall(getCurrentCallId()); + onHoldCall (getCurrentCallId()); } /* Direct IP to IP call */ @@ -457,211 +492,243 @@ ManagerImpl::offHoldCall(const CallID& id) /* Classic call, attached to an account */ else { - accountid = getAccountFromCall( id ); + accountid = getAccountFromCall (id); + if (accountid == AccountNULL) { - _debug("Manager OffHold Call: Call doesn't exists\n"); + _debug ("Manager OffHold Call: Call doesn't exists\n"); return false; } - _debug("Setting OFFHOLD, Account %s, callid %s\n", accountid.c_str(), id.c_str()); - rec = getAccountLink(accountid)->isRecording(id); - returnValue = getAccountLink(accountid)->offhold(id); + + _debug ("Setting OFFHOLD, Account %s, callid %s\n", accountid.c_str(), id.c_str()); + + rec = getAccountLink (accountid)->isRecording (id); + returnValue = getAccountLink (accountid)->offhold (id); } - if (_dbus){ + if (_dbus) { if (rec) - _dbus->getCallManager()->callStateChanged(call_id, "UNHOLD_RECORD"); + _dbus->getCallManager()->callStateChanged (call_id, "UNHOLD_RECORD"); else - _dbus->getCallManager()->callStateChanged(call_id, "UNHOLD_CURRENT"); + _dbus->getCallManager()->callStateChanged (call_id, "UNHOLD_CURRENT"); } - switchCall(id); + switchCall (id); - codecName = getCurrentCodecName(id); + codecName = getCurrentCodecName (id); // _debug("ManagerImpl::hangupCall(): broadcast codec name %s \n",codecName.c_str()); - if (_dbus) _dbus->getCallManager()->currentSelectedCodec(id,codecName.c_str()); + + if (_dbus) _dbus->getCallManager()->currentSelectedCodec (id,codecName.c_str()); return returnValue; } //THREAD=Main - bool -ManagerImpl::transferCall(const CallID& id, const std::string& to) +bool +ManagerImpl::transferCall (const CallID& id, const std::string& to) { AccountID accountid; bool returnValue; - stopTone(true); + stopTone (true); /* Direct IP to IP call */ + if (getConfigFromCall (id) == Call::IPtoIP) { returnValue = SIPVoIPLink::instance (AccountNULL)-> transfer (id, to); } /* Classic call, attached to an account */ else { - accountid = getAccountFromCall( id ); + accountid = getAccountFromCall (id); + if (accountid == AccountNULL) { - _debug("! Manager Transfer Call: Call doesn't exists\n"); + _debug ("! Manager Transfer Call: Call doesn't exists\n"); return false; } - returnValue = getAccountLink(accountid)->transfer(id, to); - removeCallAccount(id); + + returnValue = getAccountLink (accountid)->transfer (id, to); + + removeCallAccount (id); } - removeWaitingCall(id); - switchCall(""); + removeWaitingCall (id); + + switchCall (""); + + if (_dbus) _dbus->getCallManager()->callStateChanged (id, "HUNGUP"); - if (_dbus) _dbus->getCallManager()->callStateChanged(id, "HUNGUP"); return returnValue; } void ManagerImpl::transferFailed() { - if(_dbus) _dbus->getCallManager()->transferFailed(); + if (_dbus) _dbus->getCallManager()->transferFailed(); } void ManagerImpl::transferSucceded() { - if(_dbus) _dbus->getCallManager()->transferSucceded(); + if (_dbus) _dbus->getCallManager()->transferSucceded(); } //THREAD=Main : Call:Incoming - bool +bool ManagerImpl::refuseCall (const CallID& id) { AccountID accountid; bool returnValue; - stopTone(true); + stopTone (true); + + /* Direct IP to IP call */ - /* Direct IP to IP call */ if (getConfigFromCall (id) == Call::IPtoIP) { returnValue = SIPVoIPLink::instance (AccountNULL)-> refuse (id); } /* Classic call, attached to an account */ else { - accountid = getAccountFromCall( id ); + accountid = getAccountFromCall (id); + if (accountid == AccountNULL) { - _debug("! Manager OffHold Call: Call doesn't exists\n"); + _debug ("! Manager OffHold Call: Call doesn't exists\n"); return false; } - returnValue = getAccountLink(accountid)->refuse(id); - removeCallAccount(id); + + returnValue = getAccountLink (accountid)->refuse (id); + + removeCallAccount (id); } // if the call was outgoing or established, we didn't refuse it // so the method did nothing if (returnValue) { - removeWaitingCall(id); - if (_dbus) _dbus->getCallManager()->callStateChanged(id, "HUNGUP"); - switchCall(""); + removeWaitingCall (id); + + if (_dbus) _dbus->getCallManager()->callStateChanged (id, "HUNGUP"); + + switchCall (""); } + return returnValue; } //THREAD=Main - bool +bool ManagerImpl::saveConfig (void) { - _debug("Saving Configuration...\n"); - setConfig(AUDIO, VOLUME_SPKR, getSpkrVolume()); - setConfig(AUDIO, VOLUME_MICRO, getMicVolume()); + _debug ("Saving Configuration...\n"); + setConfig (AUDIO, VOLUME_SPKR, getSpkrVolume()); + setConfig (AUDIO, VOLUME_MICRO, getMicVolume()); - _setupLoaded = _config.saveConfigTree(_path.data()); - return _setupLoaded; + _setupLoaded = _config.saveConfigTree (_path.data()); + return _setupLoaded; } //THREAD=Main - int +int ManagerImpl::initRegisterAccounts() { int status; bool flag = true; AccountMap::iterator iter; - _debugInit("Initiate VoIP Links Registration"); + _debugInit ("Initiate VoIP Links Registration"); iter = _accountMap.begin(); /* Loop on the account map previously loaded */ - while( iter != _accountMap.end() ) { - if ( iter->second ) { + + while (iter != _accountMap.end()) { + if (iter->second) { iter->second->loadConfig(); /* If the account is set as enabled, try to register */ - if ( iter->second->isEnabled() ) { - status = iter->second->registerVoIPLink(); - if (status != SUCCESS){ - flag = false; + + if (iter->second->isEnabled()) { + status = iter->second->registerVoIPLink(); + + if (status != SUCCESS) { + flag = false; } } } + iter++; } // calls the client notification here in case of errors at startup... - if( _audiodriver -> getErrorMessage() != -1 ) - notifyErrClient( _audiodriver -> getErrorMessage() ); + if (_audiodriver -> getErrorMessage() != -1) + notifyErrClient (_audiodriver -> getErrorMessage()); + + ASSERT (flag, true); - ASSERT( flag, true ); return SUCCESS; } //THREAD=Main - bool -ManagerImpl::sendDtmf(const CallID& id, char code) +bool +ManagerImpl::sendDtmf (const CallID& id, char code) { - AccountID accountid = getAccountFromCall( id ); - if (accountid == AccountNULL) { - //_debug("Send DTMF: call doesn't exists\n"); - playDtmf(code, false); - return false; - } - - int sendType = getConfigInt(SIGNALISATION, SEND_DTMF_AS); - bool returnValue = false; - switch (sendType) { - case 0: // SIP INFO - playDtmf(code , true); - returnValue = getAccountLink(accountid)->carryingDTMFdigits(id, code); - break; - - case 1: // Audio way - break; - case 2: // rfc 2833 - break; - default: // unknown - error config? - break; - } - return returnValue; + AccountID accountid = getAccountFromCall (id); + + if (accountid == AccountNULL) { + //_debug("Send DTMF: call doesn't exists\n"); + playDtmf (code, false); + return false; + } + + int sendType = getConfigInt (SIGNALISATION, SEND_DTMF_AS); + + bool returnValue = false; + + switch (sendType) { + + case 0: // SIP INFO + playDtmf (code , true); + returnValue = getAccountLink (accountid)->carryingDTMFdigits (id, code); + break; + + case 1: // Audio way + break; + + case 2: // rfc 2833 + break; + + default: // unknown - error config? + break; + } + + return returnValue; } //THREAD=Main | VoIPLink - bool -ManagerImpl::playDtmf(char code, bool isTalking) +bool +ManagerImpl::playDtmf (char code, bool isTalking) { int hasToPlayTone, pulselen, layer, size; bool ret = false; AudioLayer *audiolayer; SFLDataFormat *buf; - stopTone(false); + stopTone (false); + + hasToPlayTone = getConfigInt (SIGNALISATION, PLAY_DTMF); - hasToPlayTone = getConfigInt(SIGNALISATION, PLAY_DTMF); if (!hasToPlayTone) return false; // length in milliseconds - pulselen = getConfigInt(SIGNALISATION, PULSE_LENGTH); + pulselen = getConfigInt (SIGNALISATION, PULSE_LENGTH); + if (!pulselen) return false; // numbers of int = length in milliseconds / 1000 (number of seconds) // = number of seconds * SAMPLING_RATE by SECONDS audiolayer = getAudioDriver(); + layer = audiolayer->getLayerType(); // fast return, no sound, so no dtmf @@ -672,61 +739,70 @@ ManagerImpl::playDtmf(char code, bool isTalking) // size (n sampling) = time_ms * sampling/s // --------------------- // ms/s - size = (int)(pulselen * ((float)audiolayer->getSampleRate()/1000)); + size = (int) (pulselen * ( (float) audiolayer->getSampleRate() /1000)); // this buffer is for mono // TODO <-- this should be global and hide if same size buf = new SFLDataFormat[size]; // Handle dtmf - _dtmfKey->startTone(code); + _dtmfKey->startTone (code); // copy the sound - if ( _dtmfKey->generateDTMF(buf, size) ) { + if (_dtmfKey->generateDTMF (buf, size)) { // Put buffer to urgentRingBuffer // put the size in bytes... // so size * 1 channel (mono) * sizeof (bytes for the data) audiolayer->startStream(); - audiolayer->putUrgent (buf, size * sizeof(SFLDataFormat)); + audiolayer->putUrgent (buf, size * sizeof (SFLDataFormat)); } + ret = true; // TODO Cache the DTMF - delete[] buf; buf = 0; + delete[] buf; + buf = 0; return ret; } // Multi-thread bool -ManagerImpl::incomingCallWaiting() { - return (_nbIncomingWaitingCall > 0) ? true : false; +ManagerImpl::incomingCallWaiting() +{ + return (_nbIncomingWaitingCall > 0) ? true : false; } void -ManagerImpl::addWaitingCall(const CallID& id) { - ost::MutexLock m(_waitingCallMutex); - _waitingCall.insert(id); - _nbIncomingWaitingCall++; +ManagerImpl::addWaitingCall (const CallID& id) +{ + ost::MutexLock m (_waitingCallMutex); + _waitingCall.insert (id); + _nbIncomingWaitingCall++; } void -ManagerImpl::removeWaitingCall(const CallID& id) { - ost::MutexLock m(_waitingCallMutex); - // should return more than 1 if it erase a call - if (_waitingCall.erase(id)) { - _nbIncomingWaitingCall--; - } +ManagerImpl::removeWaitingCall (const CallID& id) +{ + ost::MutexLock m (_waitingCallMutex); + // should return more than 1 if it erase a call + + if (_waitingCall.erase (id)) { + _nbIncomingWaitingCall--; + } } bool -ManagerImpl::isWaitingCall(const CallID& id) { - CallIDSet::iterator iter = _waitingCall.find(id); - if (iter != _waitingCall.end()) { - return false; - } - return true; +ManagerImpl::isWaitingCall (const CallID& id) +{ + CallIDSet::iterator iter = _waitingCall.find (id); + + if (iter != _waitingCall.end()) { + return false; + } + + return true; } /////////////////////////////////////////////////////////////////////////////// @@ -734,47 +810,49 @@ ManagerImpl::isWaitingCall(const CallID& id) { //////////////////////////////////////////////////////////////////////////////// // SipEvent Thread bool -ManagerImpl::incomingCall(Call* call, const AccountID& accountId) +ManagerImpl::incomingCall (Call* call, const AccountID& accountId) { PulseLayer *pulselayer; std::string from, number; - stopTone(true); + stopTone (true); - _debug("Incoming call %s for account %s\n", call->getCallId().data(), accountId.c_str()); + _debug ("Incoming call %s for account %s\n", call->getCallId().data(), accountId.c_str()); - associateCallToAccount(call->getCallId(), accountId); + associateCallToAccount (call->getCallId(), accountId); if (accountId==AccountNULL) associateConfigToCall (call->getCallId(), Call::IPtoIP); - _debug("ManagerImpl::incomingCall :: hasCurrentCall() %i \n",hasCurrentCall()); + _debug ("ManagerImpl::incomingCall :: hasCurrentCall() %i \n",hasCurrentCall()); - if ( !hasCurrentCall() ) { - call->setConnectionState(Call::Ringing); + if (!hasCurrentCall()) { + call->setConnectionState (Call::Ringing); ringtone(); - switchCall(call->getCallId()); + switchCall (call->getCallId()); } + /* else { addWaitingCall(call->getCallId()); } */ - addWaitingCall(call->getCallId()); + addWaitingCall (call->getCallId()); from = call->getPeerName(); + number = call->getPeerNumber(); if (from != "" && number != "") { - from.append(" <"); - from.append(number); - from.append(">"); - } else if ( from.empty() ) { - from.append("<"); - from.append(number); - from.append(">"); + from.append (" <"); + from.append (number); + from.append (">"); + } else if (from.empty()) { + from.append ("<"); + from.append (number); + from.append (">"); } /* @@ -787,14 +865,15 @@ ManagerImpl::incomingCall(Call* call, const AccountID& accountId) */ /* Broadcast a signal over DBus */ - if (_dbus) _dbus->getCallManager()->incomingCall(accountId, call->getCallId(), from); + if (_dbus) _dbus->getCallManager()->incomingCall (accountId, call->getCallId(), from); //if (_dbus) _dbus->getCallManager()->callStateChanged(call->getCallId(), "INCOMING"); // Reduce volume of the other pulseaudio-connected audio applications - if( _audiodriver->getLayerType() == PULSEAUDIO && getConfigInt( PREFERENCES , CONFIG_PA_VOLUME_CTRL ) ) { + if (_audiodriver->getLayerType() == PULSEAUDIO && getConfigInt (PREFERENCES , CONFIG_PA_VOLUME_CTRL)) { pulselayer = dynamic_cast<PulseLayer *> (getAudioDriver()); - if(pulselayer) pulselayer->reducePulseAppsVolume(); + + if (pulselayer) pulselayer->reducePulseAppsVolume(); } return true; @@ -802,111 +881,126 @@ ManagerImpl::incomingCall(Call* call, const AccountID& accountId) //THREAD=VoIP void -ManagerImpl::incomingMessage(const AccountID& accountId, const std::string& message) { - if (_dbus) { - _dbus->getCallManager()->incomingMessage(accountId, message); - } +ManagerImpl::incomingMessage (const AccountID& accountId, const std::string& message) +{ + if (_dbus) { + _dbus->getCallManager()->incomingMessage (accountId, message); + } } //THREAD=VoIP CALL=Outgoing - void -ManagerImpl::peerAnsweredCall(const CallID& id) +void +ManagerImpl::peerAnsweredCall (const CallID& id) { - if (isCurrentCall(id)) { - stopTone(false); + if (isCurrentCall (id)) { + stopTone (false); } - if (_dbus) _dbus->getCallManager()->callStateChanged(id, "CURRENT"); + if (_dbus) _dbus->getCallManager()->callStateChanged (id, "CURRENT"); - std::string codecName = getCurrentCodecName(id); - // _debug("ManagerImpl::hangupCall(): broadcast codec name %s \n",codecName.c_str()); - if (_dbus) _dbus->getCallManager()->currentSelectedCodec(id,codecName.c_str()); + std::string codecName = getCurrentCodecName (id); + + // _debug("ManagerImpl::hangupCall(): broadcast codec name %s \n",codecName.c_str()); + if (_dbus) _dbus->getCallManager()->currentSelectedCodec (id,codecName.c_str()); } //THREAD=VoIP Call=Outgoing - void -ManagerImpl::peerRingingCall(const CallID& id) +void +ManagerImpl::peerRingingCall (const CallID& id) { - if (isCurrentCall(id)) { - ringback(); - } - if (_dbus) _dbus->getCallManager()->callStateChanged(id, "RINGING"); + if (isCurrentCall (id)) { + ringback(); + } + + if (_dbus) _dbus->getCallManager()->callStateChanged (id, "RINGING"); } //THREAD=VoIP Call=Outgoing/Ingoing - void -ManagerImpl::peerHungupCall(const CallID& id) +void +ManagerImpl::peerHungupCall (const CallID& id) { PulseLayer *pulselayer; AccountID accountid; bool returnValue; /* Direct IP to IP call */ + if (getConfigFromCall (id) == Call::IPtoIP) { SIPVoIPLink::instance (AccountNULL)->hangup (id); } - else - { - accountid = getAccountFromCall( id ); + else { + accountid = getAccountFromCall (id); + if (accountid == AccountNULL) { - _debug("peerHungupCall: Call doesn't exists\n"); + _debug ("peerHungupCall: Call doesn't exists\n"); return; } - returnValue = getAccountLink(accountid)->peerHungup(id); + + returnValue = getAccountLink (accountid)->peerHungup (id); } /* Broadcast a signal over DBus */ - if (_dbus) _dbus->getCallManager()->callStateChanged(id, "HUNGUP"); + if (_dbus) _dbus->getCallManager()->callStateChanged (id, "HUNGUP"); - if (isCurrentCall(id)) { - stopTone(true); - switchCall(""); + if (isCurrentCall (id)) { + stopTone (true); + switchCall (""); } - removeWaitingCall(id); - removeCallAccount(id); + removeWaitingCall (id); - if( _audiodriver->getLayerType() == PULSEAUDIO && getConfigInt( PREFERENCES , CONFIG_PA_VOLUME_CTRL ) ) { + removeCallAccount (id); + + if (_audiodriver->getLayerType() == PULSEAUDIO && getConfigInt (PREFERENCES , CONFIG_PA_VOLUME_CTRL)) { pulselayer = dynamic_cast<PulseLayer *> (getAudioDriver()); - if(pulselayer) pulselayer->restorePulseAppsVolume(); + + if (pulselayer) pulselayer->restorePulseAppsVolume(); } } //THREAD=VoIP void -ManagerImpl::callBusy(const CallID& id) { - _debug("Call busy\n"); +ManagerImpl::callBusy (const CallID& id) +{ + _debug ("Call busy\n"); + + if (_dbus) _dbus->getCallManager()->callStateChanged (id, "BUSY"); + + if (isCurrentCall (id)) { + playATone (Tone::TONE_BUSY); + switchCall (""); + } - if (_dbus) _dbus->getCallManager()->callStateChanged(id, "BUSY"); - if (isCurrentCall(id) ) { - playATone(Tone::TONE_BUSY); - switchCall(""); - } - removeCallAccount(id); - removeWaitingCall(id); + removeCallAccount (id); + + removeWaitingCall (id); } //THREAD=VoIP - void -ManagerImpl::callFailure(const CallID& id) +void +ManagerImpl::callFailure (const CallID& id) { - if (_dbus) _dbus->getCallManager()->callStateChanged(id, "FAILURE"); - _debug("CALL ID = %s\n" , id.c_str()); - if (isCurrentCall(id) ) { - playATone(Tone::TONE_BUSY); - switchCall(""); - } - removeCallAccount(id); - removeWaitingCall(id); + if (_dbus) _dbus->getCallManager()->callStateChanged (id, "FAILURE"); + + _debug ("CALL ID = %s\n" , id.c_str()); + + if (isCurrentCall (id)) { + playATone (Tone::TONE_BUSY); + switchCall (""); + } + + removeCallAccount (id); + + removeWaitingCall (id); } //THREAD=VoIP - void -ManagerImpl::startVoiceMessageNotification(const AccountID& accountId, int nb_msg) +void +ManagerImpl::startVoiceMessageNotification (const AccountID& accountId, int nb_msg) { - if (_dbus) _dbus->getCallManager()->voiceMailNotify(accountId, nb_msg) ; + if (_dbus) _dbus->getCallManager()->voiceMailNotify (accountId, nb_msg) ; } void ManagerImpl::connectionStatusNotification() @@ -918,14 +1012,15 @@ void ManagerImpl::connectionStatusNotification() /** * Multi Thread */ -bool ManagerImpl::playATone(Tone::TONEID toneId) +bool ManagerImpl::playATone (Tone::TONEID toneId) { int hasToPlayTone; AudioLoop *audioloop; AudioLayer *audiolayer; unsigned int nbSamples; - hasToPlayTone = getConfigInt(SIGNALISATION, PLAY_TONES); + hasToPlayTone = getConfigInt (SIGNALISATION, PLAY_TONES); + if (!hasToPlayTone) return false; @@ -933,19 +1028,20 @@ bool ManagerImpl::playATone(Tone::TONEID toneId) if (_telephoneTone != 0) { _toneMutex.enterMutex(); - _telephoneTone->setCurrentTone(toneId); + _telephoneTone->setCurrentTone (toneId); _toneMutex.leaveMutex(); audioloop = getTelephoneTone(); nbSamples = audioloop->getSize(); SFLDataFormat buf[nbSamples]; - if ( audiolayer ){ - audiolayer->putUrgent( buf, nbSamples ); + if (audiolayer) { + audiolayer->putUrgent (buf, nbSamples); } else return false; - } - return true; + } + + return true; } /** @@ -956,20 +1052,23 @@ void ManagerImpl::stopTone (bool stopAudio=true) int hasToPlayTone; AudioLayer *audiolayer; - hasToPlayTone = getConfigInt(SIGNALISATION, PLAY_TONES); + hasToPlayTone = getConfigInt (SIGNALISATION, PLAY_TONES); + if (!hasToPlayTone) return; - + // if (stopAudio) { // audiolayer = getAudioDriver(); // if (audiolayer) audiolayer->stopStream(); // } - + _toneMutex.enterMutex(); + if (_telephoneTone != 0) { - _telephoneTone->setCurrentTone(Tone::TONE_NULL); + _telephoneTone->setCurrentTone (Tone::TONE_NULL); } + _toneMutex.leaveMutex(); // for ringing tone.. @@ -981,43 +1080,45 @@ void ManagerImpl::stopTone (bool stopAudio=true) /** * Multi Thread */ - bool +bool ManagerImpl::playTone() { - playATone(Tone::TONE_DIALTONE); - return true; + playATone (Tone::TONE_DIALTONE); + return true; } /** * Multi Thread */ - bool +bool ManagerImpl::playToneWithMessage() { - playATone(Tone::TONE_CONGESTION); - return true; + playATone (Tone::TONE_CONGESTION); + return true; } /** * Multi Thread */ void -ManagerImpl::congestion () { - playATone(Tone::TONE_CONGESTION); +ManagerImpl::congestion () +{ + playATone (Tone::TONE_CONGESTION); } /** * Multi Thread */ void -ManagerImpl::ringback () { - playATone(Tone::TONE_RINGTONE); +ManagerImpl::ringback () +{ + playATone (Tone::TONE_RINGTONE); } /** * Multi Thread */ - void +void ManagerImpl::ringtone() { std::string ringchoice; @@ -1028,29 +1129,34 @@ ManagerImpl::ringtone() // stopTone(true); - if( isRingtoneEnabled() ) - { + if (isRingtoneEnabled()) { //TODO Comment this because it makes the daemon crashes since the main thread //synchronizes the ringtone thread. - ringchoice = getConfigString(AUDIO, RING_CHOICE); + ringchoice = getConfigString (AUDIO, RING_CHOICE); //if there is no / inside the path - if ( ringchoice.find(DIR_SEPARATOR_CH) == std::string::npos ) { + + if (ringchoice.find (DIR_SEPARATOR_CH) == std::string::npos) { // check inside global share directory - ringchoice = std::string(PROGSHAREDIR) + DIR_SEPARATOR_STR + RINGDIR + DIR_SEPARATOR_STR + ringchoice; + ringchoice = std::string (PROGSHAREDIR) + DIR_SEPARATOR_STR + RINGDIR + DIR_SEPARATOR_STR + ringchoice; } audiolayer = getAudioDriver(); + layer = audiolayer->getLayerType(); + if (audiolayer == 0) return; samplerate = audiolayer->getSampleRate(); + codecForTone = _codecDescriptorMap.getFirstCodecAvailable(); _toneMutex.enterMutex(); - loadFile = _audiofile.loadFile(ringchoice, codecForTone , samplerate); + + loadFile = _audiofile.loadFile (ringchoice, codecForTone , samplerate); + _toneMutex.leaveMutex(); if (loadFile) { @@ -1058,115 +1164,119 @@ ManagerImpl::ringtone() _toneMutex.enterMutex(); _audiofile.start(); _toneMutex.leaveMutex(); - if(CHECK_INTERFACE( layer, ALSA )){ + + if (CHECK_INTERFACE (layer, ALSA)) { //ringback(); - } - else{ + } else { audiolayer->startStream(); } } else { ringback(); } - } - else - { + } else { ringback(); } } - AudioLoop* +AudioLoop* ManagerImpl::getTelephoneTone() { - // _debug("ManagerImpl::getTelephoneTone()\n"); - if(_telephoneTone != 0) { - ost::MutexLock m(_toneMutex); - return _telephoneTone->getCurrentTone(); - } - else { - return 0; - } + // _debug("ManagerImpl::getTelephoneTone()\n"); + if (_telephoneTone != 0) { + ost::MutexLock m (_toneMutex); + return _telephoneTone->getCurrentTone(); + } else { + return 0; + } } - AudioLoop* +AudioLoop* ManagerImpl::getTelephoneFile() { - // _debug("ManagerImpl::getTelephoneFile()\n"); - ost::MutexLock m(_toneMutex); - if(_audiofile.isStarted()) { - return &_audiofile; - } else { - return 0; - } + // _debug("ManagerImpl::getTelephoneFile()\n"); + ost::MutexLock m (_toneMutex); + + if (_audiofile.isStarted()) { + return &_audiofile; + } else { + return 0; + } } -void ManagerImpl::notificationIncomingCall(void) +void ManagerImpl::notificationIncomingCall (void) { AudioLayer *audiolayer; std::ostringstream frequency; unsigned int samplerate, nbSampling; audiolayer = getAudioDriver(); + if (audiolayer != 0) { samplerate = audiolayer->getSampleRate(); frequency << "440/" << FRAME_PER_BUFFER; - Tone tone(frequency.str(), samplerate); + Tone tone (frequency.str(), samplerate); nbSampling = tone.getSize(); SFLDataFormat buf[nbSampling]; - tone.getNext(buf, tone.getSize()); + tone.getNext (buf, tone.getSize()); /* Put the data in the urgent ring buffer */ - audiolayer->putUrgent (buf, sizeof(SFLDataFormat)*nbSampling); + audiolayer->putUrgent (buf, sizeof (SFLDataFormat) *nbSampling); } } /** * Multi Thread */ - bool +bool ManagerImpl::getStunInfo (StunAddress4& stunSvrAddr, int port) { - StunAddress4 mappedAddr; - struct in_addr in; - char* addr; - - //int fd3, fd4; - // bool ok = stunOpenSocketPair(stunSvrAddr, &mappedAddr, &fd3, &fd4, port); - int fd1 = stunOpenSocket(stunSvrAddr, &mappedAddr, port); - bool ok = (fd1 == -1 || fd1 == INVALID_SOCKET) ? false : true; - if (ok) { - closesocket(fd1); - //closesocket(fd3); - //closesocket(fd4); - _firewallPort = mappedAddr.port; - // Convert ipv4 address to host byte ordering - in.s_addr = ntohl (mappedAddr.addr); - addr = inet_ntoa(in); - _firewallAddr = std::string(addr); - _debug("STUN Firewall: [%s:%d]\n", _firewallAddr.data(), _firewallPort); - return true; - } else { - _debug("Opening a stun socket pair failed\n"); - } - return false; + StunAddress4 mappedAddr; + + struct in_addr in; + char* addr; + + //int fd3, fd4; + // bool ok = stunOpenSocketPair(stunSvrAddr, &mappedAddr, &fd3, &fd4, port); + int fd1 = stunOpenSocket (stunSvrAddr, &mappedAddr, port); + bool ok = (fd1 == -1 || fd1 == INVALID_SOCKET) ? false : true; + + if (ok) { + closesocket (fd1); + //closesocket(fd3); + //closesocket(fd4); + _firewallPort = mappedAddr.port; + // Convert ipv4 address to host byte ordering + in.s_addr = ntohl (mappedAddr.addr); + addr = inet_ntoa (in); + _firewallAddr = std::string (addr); + _debug ("STUN Firewall: [%s:%d]\n", _firewallAddr.data(), _firewallPort); + return true; + } else { + _debug ("Opening a stun socket pair failed\n"); + } + + return false; } - bool -ManagerImpl::behindNat(const std::string& svr, int port) +bool +ManagerImpl::behindNat (const std::string& svr, int port) { - StunAddress4 stunSvrAddr; - stunSvrAddr.addr = 0; + StunAddress4 stunSvrAddr; + stunSvrAddr.addr = 0; - // Convert char* to StunAddress4 structure - bool ret = stunParseServerName ((char*)svr.data(), stunSvrAddr); - if (!ret) { - _debug("SIP: Stun server address (%s) is not valid\n", svr.data()); - return 0; - } + // Convert char* to StunAddress4 structure + bool ret = stunParseServerName ( (char*) svr.data(), stunSvrAddr); + + if (!ret) { + _debug ("SIP: Stun server address (%s) is not valid\n", svr.data()); + return 0; + } + + // Firewall address + _debug ("STUN server: %s\n", svr.data()); - // Firewall address - _debug("STUN server: %s\n", svr.data()); - return getStunInfo(stunSvrAddr, port); + return getStunInfo (stunSvrAddr, port); } @@ -1179,564 +1289,577 @@ ManagerImpl::behindNat(const std::string& svr, int port) -1: error directory */ int -ManagerImpl::createSettingsPath (void) { - _path = std::string(HOMEDIR) + DIR_SEPARATOR_STR + "." + PROGDIR; +ManagerImpl::createSettingsPath (void) +{ + _path = std::string (HOMEDIR) + DIR_SEPARATOR_STR + "." + PROGDIR; - if (mkdir (_path.data(), 0755) != 0) { - // If directory creation failed - if (errno != EEXIST) { - _debug("Cannot create directory: %s\n", strerror(errno)); - return -1; + if (mkdir (_path.data(), 0755) != 0) { + // If directory creation failed + if (errno != EEXIST) { + _debug ("Cannot create directory: %s\n", strerror (errno)); + return -1; + } } - } - // Load user's configuration - _path = _path + DIR_SEPARATOR_STR + PROGNAME + "rc"; - return 1; + // Load user's configuration + _path = _path + DIR_SEPARATOR_STR + PROGNAME + "rc"; + + return 1; } /** * Initialization: Main Thread */ - void +void ManagerImpl::initConfigFile (bool load_user_value, std::string alternate) { - std::string mes = gettext("Init config file\n"); - _debug("%s",mes.c_str()); - - std::string type_str("string"); - std::string type_int("int"); - - std::string section, path; - - // Default values, that will be overwritten by the call to - // 'populateFromFile' below. - section = SIGNALISATION; - fill_config_int(SYMMETRIC, YES_STR); - fill_config_int(PLAY_DTMF, YES_STR); - fill_config_int(PLAY_TONES, YES_STR); - fill_config_int(PULSE_LENGTH, DFT_PULSE_LENGTH_STR); - fill_config_int(SEND_DTMF_AS, SIP_INFO_STR); - fill_config_int(STUN_ENABLE, DFT_STUN_ENABLE); - fill_config_int(STUN_SERVER, DFT_STUN_SERVER); - - section = AUDIO; - fill_config_int(ALSA_CARD_ID_IN, ALSA_DFT_CARD); - fill_config_int(ALSA_CARD_ID_OUT, ALSA_DFT_CARD); - fill_config_int(ALSA_SAMPLE_RATE, DFT_SAMPLE_RATE); - fill_config_int(ALSA_FRAME_SIZE, DFT_FRAME_SIZE); - fill_config_str(ALSA_PLUGIN, PCM_DEFAULT); - fill_config_str(RING_CHOICE, DFT_RINGTONE); - fill_config_int(VOLUME_SPKR, DFT_VOL_SPKR_STR); - fill_config_int(VOLUME_MICRO, DFT_VOL_MICRO_STR); - fill_config_str(RECORD_PATH,DFT_RECORD_PATH); - - section = PREFERENCES; - fill_config_str(ZONE_TONE, DFT_ZONE); - fill_config_int(CONFIG_ZEROCONF, CONFIG_ZEROCONF_DEFAULT_STR); - fill_config_int(CONFIG_RINGTONE, YES_STR); - fill_config_int(CONFIG_DIALPAD, YES_STR); - fill_config_int(CONFIG_SEARCHBAR, YES_STR); - fill_config_int(CONFIG_START, NO_STR); - fill_config_int(CONFIG_POPUP, YES_STR); - fill_config_int(CONFIG_NOTIFY , YES_STR); - fill_config_int(CONFIG_MAIL_NOTIFY , NO_STR); - fill_config_int(CONFIG_VOLUME , YES_STR); - fill_config_int(CONFIG_HISTORY_LIMIT, DFT_HISTORY_LIMIT); - fill_config_int(CONFIG_HISTORY_ENABLED, YES_STR); - fill_config_int(REGISTRATION_EXPIRE , DFT_EXPIRE_VALUE); - fill_config_int(CONFIG_AUDIO , DFT_AUDIO_MANAGER); - fill_config_int(CONFIG_PA_VOLUME_CTRL , YES_STR); - fill_config_int(CONFIG_SIP_PORT, DFT_SIP_PORT); - fill_config_str(CONFIG_ACCOUNTS_ORDER, ""); - - section = ADDRESSBOOK; - fill_config_int (ADDRESSBOOK_ENABLE, YES_STR); - fill_config_int (ADDRESSBOOK_MAX_RESULTS, "25"); - fill_config_int (ADDRESSBOOK_DISPLAY_CONTACT_PHOTO, NO_STR); - fill_config_int (ADDRESSBOOK_DISPLAY_PHONE_BUSINESS, YES_STR); - fill_config_int (ADDRESSBOOK_DISPLAY_PHONE_HOME, NO_STR); - fill_config_int (ADDRESSBOOK_DISPLAY_PHONE_MOBILE, NO_STR); - - section = HOOKS; - fill_config_str (URLHOOK_SIP_FIELD, HOOK_DEFAULT_SIP_FIELD); - fill_config_str (URLHOOK_COMMAND, HOOK_DEFAULT_URL_COMMAND); - fill_config_str (URLHOOK_SIP_ENABLED, NO_STR); - fill_config_str (URLHOOK_IAX2_ENABLED, NO_STR); - fill_config_str (PHONE_NUMBER_HOOK_ENABLED, NO_STR); - fill_config_str (PHONE_NUMBER_HOOK_ADD_PREFIX, ""); + std::string mes = gettext ("Init config file\n"); + _debug ("%s",mes.c_str()); + + std::string type_str ("string"); + std::string type_int ("int"); + + std::string section, path; + + // Default values, that will be overwritten by the call to + // 'populateFromFile' below. + section = SIGNALISATION; + fill_config_int (SYMMETRIC, YES_STR); + fill_config_int (PLAY_DTMF, YES_STR); + fill_config_int (PLAY_TONES, YES_STR); + fill_config_int (PULSE_LENGTH, DFT_PULSE_LENGTH_STR); + fill_config_int (SEND_DTMF_AS, SIP_INFO_STR); + fill_config_int (STUN_ENABLE, DFT_STUN_ENABLE); + fill_config_int (STUN_SERVER, DFT_STUN_SERVER); + + section = AUDIO; + fill_config_int (ALSA_CARD_ID_IN, ALSA_DFT_CARD); + fill_config_int (ALSA_CARD_ID_OUT, ALSA_DFT_CARD); + fill_config_int (ALSA_SAMPLE_RATE, DFT_SAMPLE_RATE); + fill_config_int (ALSA_FRAME_SIZE, DFT_FRAME_SIZE); + fill_config_str (ALSA_PLUGIN, PCM_DEFAULT); + fill_config_str (RING_CHOICE, DFT_RINGTONE); + fill_config_int (VOLUME_SPKR, DFT_VOL_SPKR_STR); + fill_config_int (VOLUME_MICRO, DFT_VOL_MICRO_STR); + fill_config_str (RECORD_PATH,DFT_RECORD_PATH); + + section = PREFERENCES; + fill_config_str (ZONE_TONE, DFT_ZONE); + fill_config_int (CONFIG_ZEROCONF, CONFIG_ZEROCONF_DEFAULT_STR); + fill_config_int (CONFIG_RINGTONE, YES_STR); + fill_config_int (CONFIG_DIALPAD, YES_STR); + fill_config_int (CONFIG_SEARCHBAR, YES_STR); + fill_config_int (CONFIG_START, NO_STR); + fill_config_int (CONFIG_POPUP, YES_STR); + fill_config_int (CONFIG_NOTIFY , YES_STR); + fill_config_int (CONFIG_MAIL_NOTIFY , NO_STR); + fill_config_int (CONFIG_VOLUME , YES_STR); + fill_config_int (CONFIG_HISTORY_LIMIT, DFT_HISTORY_LIMIT); + fill_config_int (CONFIG_HISTORY_ENABLED, YES_STR); + fill_config_int (REGISTRATION_EXPIRE , DFT_EXPIRE_VALUE); + fill_config_int (CONFIG_AUDIO , DFT_AUDIO_MANAGER); + fill_config_int (CONFIG_PA_VOLUME_CTRL , YES_STR); + fill_config_int (CONFIG_SIP_PORT, DFT_SIP_PORT); + fill_config_str (CONFIG_ACCOUNTS_ORDER, ""); + + section = ADDRESSBOOK; + fill_config_int (ADDRESSBOOK_ENABLE, YES_STR); + fill_config_int (ADDRESSBOOK_MAX_RESULTS, "25"); + fill_config_int (ADDRESSBOOK_DISPLAY_CONTACT_PHOTO, NO_STR); + fill_config_int (ADDRESSBOOK_DISPLAY_PHONE_BUSINESS, YES_STR); + fill_config_int (ADDRESSBOOK_DISPLAY_PHONE_HOME, NO_STR); + fill_config_int (ADDRESSBOOK_DISPLAY_PHONE_MOBILE, NO_STR); + + section = HOOKS; + fill_config_str (URLHOOK_SIP_FIELD, HOOK_DEFAULT_SIP_FIELD); + fill_config_str (URLHOOK_COMMAND, HOOK_DEFAULT_URL_COMMAND); + fill_config_str (URLHOOK_SIP_ENABLED, NO_STR); + fill_config_str (URLHOOK_IAX2_ENABLED, NO_STR); + fill_config_str (PHONE_NUMBER_HOOK_ENABLED, NO_STR); + fill_config_str (PHONE_NUMBER_HOOK_ADD_PREFIX, ""); // Loads config from ~/.sflphone/sflphonedrc or so.. + if (createSettingsPath() == 1 && load_user_value) { - - (alternate == "")? path = _path : path = alternate; + + (alternate == "") ? path = _path : path = alternate; std::cout << path << std::endl; - - _exist = _config.populateFromFile(path); - } - _setupLoaded = (_exist == 2 ) ? false : true; + _exist = _config.populateFromFile (path); + } + + _setupLoaded = (_exist == 2) ? false : true; } /** * Initialization: Main Thread */ - void +void ManagerImpl::initAudioCodec (void) { - _debugInit("Active Codecs List"); - // init list of all supported codecs - _codecDescriptorMap.init(); - // if the user never set the codec list, use the default configuration - if(getConfigString(AUDIO, "ActiveCodecs") == ""){ - _codecDescriptorMap.setDefaultOrder(); - } - // else retrieve the one set in the user config file - else{ - std::vector<std::string> active_list = retrieveActiveCodecs(); - setActiveCodecList(active_list); - } + _debugInit ("Active Codecs List"); + // init list of all supported codecs + _codecDescriptorMap.init(); + // if the user never set the codec list, use the default configuration + + if (getConfigString (AUDIO, "ActiveCodecs") == "") { + _codecDescriptorMap.setDefaultOrder(); + } + + // else retrieve the one set in the user config file + else { + std::vector<std::string> active_list = retrieveActiveCodecs(); + setActiveCodecList (active_list); + } } - void -ManagerImpl::setActiveCodecList(const std::vector< std::string >& list) +void +ManagerImpl::setActiveCodecList (const std::vector< std::string >& list) { - _debug("Set active codecs list\n"); - _codecDescriptorMap.saveActiveCodecs(list); - // setConfig - std::string s = serialize(list); - printf("%s\n", s.c_str()); - setConfig("Audio", "ActiveCodecs", s); + _debug ("Set active codecs list\n"); + _codecDescriptorMap.saveActiveCodecs (list); + // setConfig + std::string s = serialize (list); + printf ("%s\n", s.c_str()); + setConfig ("Audio", "ActiveCodecs", s); } - std::vector<std::string> +std::vector<std::string> ManagerImpl::retrieveActiveCodecs() { - std::string s = getConfigString(AUDIO, "ActiveCodecs"); - return unserialize(s); + std::string s = getConfigString (AUDIO, "ActiveCodecs"); + return unserialize (s); } - std::vector<std::string> -ManagerImpl::unserialize(std::string s) { +std::vector<std::string> +ManagerImpl::unserialize (std::string s) +{ - std::vector<std::string> list; - std::string temp; + std::vector<std::string> list; + std::string temp; - while (s.find("/", 0) != std::string::npos) - { - size_t pos = s.find("/", 0); - temp = s.substr(0, pos); - s.erase(0, pos + 1); - list.push_back(temp); - } + while (s.find ("/", 0) != std::string::npos) { + size_t pos = s.find ("/", 0); + temp = s.substr (0, pos); + s.erase (0, pos + 1); + list.push_back (temp); + } - return list; + return list; } - std::string -ManagerImpl::serialize(std::vector<std::string> v) +std::string +ManagerImpl::serialize (std::vector<std::string> v) { - unsigned int i; - std::string res; - for(i=0;i<v.size();i++) - { - res += v[i] + "/"; - } - return res; + unsigned int i; + std::string res; + + for (i=0;i<v.size();i++) { + res += v[i] + "/"; + } + + return res; } - std::vector <std::string> -ManagerImpl::getActiveCodecList( void ) +std::vector <std::string> +ManagerImpl::getActiveCodecList (void) { - _debug("Get Active codecs list\n"); - std::vector< std::string > v; - CodecOrder active = _codecDescriptorMap.getActiveCodecs(); - unsigned int i=0; - size_t size = active.size(); - while(i<size) - { - std::stringstream ss; - ss << active[i]; - v.push_back((ss.str()).data()); - _debug("%s\n", ss.str().data()); - i++; - } - return v; + _debug ("Get Active codecs list\n"); + std::vector< std::string > v; + CodecOrder active = _codecDescriptorMap.getActiveCodecs(); + unsigned int i=0; + size_t size = active.size(); + + while (i<size) { + std::stringstream ss; + ss << active[i]; + v.push_back ( (ss.str()).data()); + _debug ("%s\n", ss.str().data()); + i++; + } + + return v; } /** * Send the list of codecs to the client through DBus. */ - std::vector< std::string > -ManagerImpl::getCodecList( void ) +std::vector< std::string > +ManagerImpl::getCodecList (void) { - std::vector<std::string> list; - //CodecMap codecs = _codecDescriptorMap.getCodecMap(); - CodecsMap codecs = _codecDescriptorMap.getCodecsMap(); - CodecOrder order = _codecDescriptorMap.getActiveCodecs(); - CodecsMap::iterator iter = codecs.begin(); + std::vector<std::string> list; + //CodecMap codecs = _codecDescriptorMap.getCodecMap(); + CodecsMap codecs = _codecDescriptorMap.getCodecsMap(); + CodecOrder order = _codecDescriptorMap.getActiveCodecs(); + CodecsMap::iterator iter = codecs.begin(); - while(iter!=codecs.end()) - { - std::stringstream ss; - if( iter->second != NULL ) - { - ss << iter->first; - list.push_back((ss.str()).data()); + while (iter!=codecs.end()) { + std::stringstream ss; + + if (iter->second != NULL) { + ss << iter->first; + list.push_back ( (ss.str()).data()); + } + + iter++; } - iter++; - } - return list; + + return list; } - std::vector<std::string> -ManagerImpl::getCodecDetails( const int32_t& payload ) +std::vector<std::string> +ManagerImpl::getCodecDetails (const int32_t& payload) { - std::vector<std::string> v; - std::stringstream ss; + std::vector<std::string> v; + std::stringstream ss; - v.push_back(_codecDescriptorMap.getCodecName((AudioCodecType)payload)); - ss << _codecDescriptorMap.getSampleRate((AudioCodecType)payload); - v.push_back((ss.str()).data()); - ss.str(""); - ss << _codecDescriptorMap.getBitRate((AudioCodecType)payload); - v.push_back((ss.str()).data()); - ss.str(""); - ss << _codecDescriptorMap.getBandwidthPerCall((AudioCodecType)payload); - v.push_back((ss.str()).data()); - ss.str(""); + v.push_back (_codecDescriptorMap.getCodecName ( (AudioCodecType) payload)); + ss << _codecDescriptorMap.getSampleRate ( (AudioCodecType) payload); + v.push_back ( (ss.str()).data()); + ss.str (""); + ss << _codecDescriptorMap.getBitRate ( (AudioCodecType) payload); + v.push_back ( (ss.str()).data()); + ss.str (""); + ss << _codecDescriptorMap.getBandwidthPerCall ( (AudioCodecType) payload); + v.push_back ( (ss.str()).data()); + ss.str (""); - return v; + return v; } std::string -ManagerImpl::getCurrentCodecName(const CallID& id) +ManagerImpl::getCurrentCodecName (const CallID& id) { - // _debug("ManagerImpl::getCurrentCodecName method called \n"); - AccountID accountid = getAccountFromCall(id); - // _debug("ManagerImpl::getCurrentCodecName : %s \n",getAccountLink(accountid)->getCurrentCodecName().c_str()); - return getAccountLink(accountid)->getCurrentCodecName(); + // _debug("ManagerImpl::getCurrentCodecName method called \n"); + AccountID accountid = getAccountFromCall (id); + // _debug("ManagerImpl::getCurrentCodecName : %s \n",getAccountLink(accountid)->getCurrentCodecName().c_str()); + return getAccountLink (accountid)->getCurrentCodecName(); } /** * Get list of supported input audio plugin */ - std::vector<std::string> -ManagerImpl::getInputAudioPluginList(void) +std::vector<std::string> +ManagerImpl::getInputAudioPluginList (void) { - std::vector<std::string> v; - _debug("Get input audio plugin list\n"); + std::vector<std::string> v; + _debug ("Get input audio plugin list\n"); - v.push_back("default"); - v.push_back("surround40"); - v.push_back("plug:hw"); + v.push_back ("default"); + v.push_back ("surround40"); + v.push_back ("plug:hw"); - return v; + return v; } /** * Get list of supported output audio plugin */ - std::vector<std::string> -ManagerImpl::getOutputAudioPluginList(void) +std::vector<std::string> +ManagerImpl::getOutputAudioPluginList (void) { - std::vector<std::string> v; - _debug("Get output audio plugin list\n"); + std::vector<std::string> v; + _debug ("Get output audio plugin list\n"); - v.push_back( PCM_DEFAULT ); - v.push_back( PCM_DMIX ); + v.push_back (PCM_DEFAULT); + v.push_back (PCM_DMIX); - return v; + return v; } /** * Set input audio plugin */ - void -ManagerImpl::setInputAudioPlugin(const std::string& audioPlugin) -{ - int layer = _audiodriver -> getLayerType(); - if(CHECK_INTERFACE( layer , ALSA )) - { - _debug("Set input audio plugin\n"); - _audiodriver -> setErrorMessage( -1 ); - _audiodriver -> openDevice( _audiodriver -> getIndexIn(), - _audiodriver -> getIndexOut(), - _audiodriver -> getSampleRate(), - _audiodriver -> getFrameSize(), - SFL_PCM_CAPTURE, - audioPlugin); - if( _audiodriver -> getErrorMessage() != -1) - notifyErrClient( _audiodriver -> getErrorMessage() ); -}else{} +void +ManagerImpl::setInputAudioPlugin (const std::string& audioPlugin) +{ + int layer = _audiodriver -> getLayerType(); + + if (CHECK_INTERFACE (layer , ALSA)) { + _debug ("Set input audio plugin\n"); + _audiodriver -> setErrorMessage (-1); + _audiodriver -> openDevice (_audiodriver -> getIndexIn(), + _audiodriver -> getIndexOut(), + _audiodriver -> getSampleRate(), + _audiodriver -> getFrameSize(), + SFL_PCM_CAPTURE, + audioPlugin); + + if (_audiodriver -> getErrorMessage() != -1) + notifyErrClient (_audiodriver -> getErrorMessage()); + } else {} } /** * Set output audio plugin */ - void -ManagerImpl::setOutputAudioPlugin(const std::string& audioPlugin) +void +ManagerImpl::setOutputAudioPlugin (const std::string& audioPlugin) { int res; - _debug("Set output audio plugin\n"); - _audiodriver -> setErrorMessage( -1 ); - res = _audiodriver -> openDevice( _audiodriver -> getIndexIn(), - _audiodriver -> getIndexOut(), - _audiodriver -> getSampleRate(), - _audiodriver -> getFrameSize(), - SFL_PCM_BOTH, - audioPlugin); - if( _audiodriver -> getErrorMessage() != -1) - notifyErrClient( _audiodriver -> getErrorMessage() ); - // set config - if(res) setConfig( AUDIO , ALSA_PLUGIN , audioPlugin ); + _debug ("Set output audio plugin\n"); + _audiodriver -> setErrorMessage (-1); + res = _audiodriver -> openDevice (_audiodriver -> getIndexIn(), + _audiodriver -> getIndexOut(), + _audiodriver -> getSampleRate(), + _audiodriver -> getFrameSize(), + SFL_PCM_BOTH, + audioPlugin); + + if (_audiodriver -> getErrorMessage() != -1) + notifyErrClient (_audiodriver -> getErrorMessage()); + + // set config + if (res) setConfig (AUDIO , ALSA_PLUGIN , audioPlugin); } /** * Get list of supported audio output device */ - std::vector<std::string> -ManagerImpl::getAudioOutputDeviceList(void) +std::vector<std::string> +ManagerImpl::getAudioOutputDeviceList (void) { - _debug("Get audio output device list\n"); - AlsaLayer *layer; + _debug ("Get audio output device list\n"); + AlsaLayer *layer; + + layer = dynamic_cast<AlsaLayer*> (getAudioDriver ()); - layer = dynamic_cast<AlsaLayer*> (getAudioDriver ()); - if (layer) return layer -> getSoundCardsInfo(SFL_PCM_PLAYBACK); + if (layer) return layer -> getSoundCardsInfo (SFL_PCM_PLAYBACK); } /** * Set audio output device */ - void -ManagerImpl::setAudioOutputDevice(const int index) +void +ManagerImpl::setAudioOutputDevice (const int index) { AlsaLayer *alsalayer; std::string alsaplugin; - _debug("Set audio output device: %i\n", index); + _debug ("Set audio output device: %i\n", index); - _audiodriver -> setErrorMessage( -1 ); + _audiodriver -> setErrorMessage (-1); alsalayer = dynamic_cast<AlsaLayer*> (getAudioDriver ()); alsaplugin = alsalayer->getAudioPlugin (); - _audiodriver->openDevice(_audiodriver->getIndexIn(), index, _audiodriver->getSampleRate(), _audiodriver->getFrameSize(), SFL_PCM_PLAYBACK, alsaplugin ); + _audiodriver->openDevice (_audiodriver->getIndexIn(), index, _audiodriver->getSampleRate(), _audiodriver->getFrameSize(), SFL_PCM_PLAYBACK, alsaplugin); - if( _audiodriver -> getErrorMessage() != -1) - notifyErrClient( _audiodriver -> getErrorMessage() ); + if (_audiodriver -> getErrorMessage() != -1) + notifyErrClient (_audiodriver -> getErrorMessage()); // set config - setConfig( AUDIO , ALSA_CARD_ID_OUT , index ); + setConfig (AUDIO , ALSA_CARD_ID_OUT , index); } /** * Get list of supported audio input device */ - std::vector<std::string> -ManagerImpl::getAudioInputDeviceList(void) +std::vector<std::string> +ManagerImpl::getAudioInputDeviceList (void) { - _debug("Get audio input device list\n"); - AlsaLayer *audiolayer; + _debug ("Get audio input device list\n"); + AlsaLayer *audiolayer; - audiolayer = dynamic_cast<AlsaLayer *> ( getAudioDriver()); - if(audiolayer) return audiolayer->getSoundCardsInfo(SFL_PCM_CAPTURE); + audiolayer = dynamic_cast<AlsaLayer *> (getAudioDriver()); + + if (audiolayer) return audiolayer->getSoundCardsInfo (SFL_PCM_CAPTURE); } /** * Set audio input device */ - void -ManagerImpl::setAudioInputDevice(const int index) +void +ManagerImpl::setAudioInputDevice (const int index) { AlsaLayer *alsalayer; std::string alsaplugin; - _debug("Set audio input device %i\n", index); + _debug ("Set audio input device %i\n", index); - _audiodriver -> setErrorMessage( -1 ); + _audiodriver -> setErrorMessage (-1); alsalayer = dynamic_cast<AlsaLayer*> (getAudioDriver ()); alsaplugin = alsalayer->getAudioPlugin (); - _audiodriver->openDevice(index, _audiodriver->getIndexOut(), _audiodriver->getSampleRate(), _audiodriver->getFrameSize(), SFL_PCM_CAPTURE, alsaplugin ); + _audiodriver->openDevice (index, _audiodriver->getIndexOut(), _audiodriver->getSampleRate(), _audiodriver->getFrameSize(), SFL_PCM_CAPTURE, alsaplugin); - if( _audiodriver -> getErrorMessage() != -1) - notifyErrClient( _audiodriver -> getErrorMessage() ); + if (_audiodriver -> getErrorMessage() != -1) + notifyErrClient (_audiodriver -> getErrorMessage()); // set config - setConfig( AUDIO , ALSA_CARD_ID_IN , index ); + setConfig (AUDIO , ALSA_CARD_ID_IN , index); } /** * Get string array representing integer indexes of output and input device */ - std::vector<std::string> +std::vector<std::string> ManagerImpl::getCurrentAudioDevicesIndex() { - _debug("Get current audio devices index\n"); - std::vector<std::string> v; - std::stringstream ssi , sso; - sso << _audiodriver->getIndexOut(); - v.push_back( sso.str() ); - ssi << _audiodriver->getIndexIn(); - v.push_back( ssi.str() ); - return v; + _debug ("Get current audio devices index\n"); + std::vector<std::string> v; + std::stringstream ssi , sso; + sso << _audiodriver->getIndexOut(); + v.push_back (sso.str()); + ssi << _audiodriver->getIndexIn(); + v.push_back (ssi.str()); + return v; } - int -ManagerImpl::isIax2Enabled( void ) +int +ManagerImpl::isIax2Enabled (void) { - //return ( IAX2_ENABLED ) ? true : false; + //return ( IAX2_ENABLED ) ? true : false; #ifdef USE_IAX - return true; + return true; #else - return false; + return false; #endif } - int -ManagerImpl::isRingtoneEnabled( void ) +int +ManagerImpl::isRingtoneEnabled (void) { - return getConfigInt( PREFERENCES , CONFIG_RINGTONE ); + return getConfigInt (PREFERENCES , CONFIG_RINGTONE); } - void -ManagerImpl::ringtoneEnabled( void ) +void +ManagerImpl::ringtoneEnabled (void) { - ( getConfigInt( PREFERENCES , CONFIG_RINGTONE ) == RINGTONE_ENABLED )? setConfig(PREFERENCES , CONFIG_RINGTONE , NO_STR ) : setConfig( PREFERENCES , CONFIG_RINGTONE , YES_STR ); + (getConfigInt (PREFERENCES , CONFIG_RINGTONE) == RINGTONE_ENABLED) ? setConfig (PREFERENCES , CONFIG_RINGTONE , NO_STR) : setConfig (PREFERENCES , CONFIG_RINGTONE , YES_STR); } std::string -ManagerImpl::getRingtoneChoice( void ) -{ - // we need the absolute path - std::string tone_name = getConfigString( AUDIO , RING_CHOICE ); - std::string tone_path ; - if( tone_name.find( DIR_SEPARATOR_CH ) == std::string::npos ) - { - // check in ringtone directory ($(PREFIX)/share/sflphone/ringtones) - tone_path = std::string(PROGSHAREDIR) + DIR_SEPARATOR_STR + RINGDIR + DIR_SEPARATOR_STR + tone_name ; - } - else - { - // the absolute has been saved; do nothing - tone_path = tone_name ; - } - _debug("%s\n", tone_path.c_str()); - return tone_path; +ManagerImpl::getRingtoneChoice (void) +{ + // we need the absolute path + std::string tone_name = getConfigString (AUDIO , RING_CHOICE); + std::string tone_path ; + + if (tone_name.find (DIR_SEPARATOR_CH) == std::string::npos) { + // check in ringtone directory ($(PREFIX)/share/sflphone/ringtones) + tone_path = std::string (PROGSHAREDIR) + DIR_SEPARATOR_STR + RINGDIR + DIR_SEPARATOR_STR + tone_name ; + } else { + // the absolute has been saved; do nothing + tone_path = tone_name ; + } + + _debug ("%s\n", tone_path.c_str()); + + return tone_path; } void -ManagerImpl::setRingtoneChoice( const std::string& tone ) +ManagerImpl::setRingtoneChoice (const std::string& tone) { - // we save the absolute path - setConfig( AUDIO , RING_CHOICE , tone ); + // we save the absolute path + setConfig (AUDIO , RING_CHOICE , tone); } std::string -ManagerImpl::getRecordPath( void ) +ManagerImpl::getRecordPath (void) { - return getConfigString( AUDIO, RECORD_PATH ); + return getConfigString (AUDIO, RECORD_PATH); } void -ManagerImpl::setRecordPath( const std::string& recPath) +ManagerImpl::setRecordPath (const std::string& recPath) { - _debug("ManagerImpl::setRecordPath(%s)! \n", recPath.c_str()); - setConfig( AUDIO, RECORD_PATH, recPath); + _debug ("ManagerImpl::setRecordPath(%s)! \n", recPath.c_str()); + setConfig (AUDIO, RECORD_PATH, recPath); } int -ManagerImpl::getDialpad( void ) +ManagerImpl::getDialpad (void) { - return getConfigInt( PREFERENCES , CONFIG_DIALPAD ); + return getConfigInt (PREFERENCES , CONFIG_DIALPAD); } void -ManagerImpl::setDialpad( void ) +ManagerImpl::setDialpad (void) { - ( getConfigInt( PREFERENCES , CONFIG_DIALPAD ) == DISPLAY_DIALPAD )? setConfig(PREFERENCES , CONFIG_DIALPAD , NO_STR ) : setConfig( PREFERENCES , CONFIG_DIALPAD , YES_STR ); + (getConfigInt (PREFERENCES , CONFIG_DIALPAD) == DISPLAY_DIALPAD) ? setConfig (PREFERENCES , CONFIG_DIALPAD , NO_STR) : setConfig (PREFERENCES , CONFIG_DIALPAD , YES_STR); } -std::string ManagerImpl::getStunServer( void ) +std::string ManagerImpl::getStunServer (void) { - return getConfigString(SIGNALISATION , STUN_SERVER); + return getConfigString (SIGNALISATION , STUN_SERVER); } -void ManagerImpl::setStunServer( const std::string &server ) +void ManagerImpl::setStunServer (const std::string &server) { - setConfig(SIGNALISATION , STUN_SERVER, server ); + setConfig (SIGNALISATION , STUN_SERVER, server); } int ManagerImpl::isStunEnabled (void) { - return getConfigInt(SIGNALISATION , STUN_ENABLE); + return getConfigInt (SIGNALISATION , STUN_ENABLE); } void ManagerImpl::enableStun (void) { /* Update the config */ - ( getConfigInt( SIGNALISATION , STUN_ENABLE ) == STUN_ENABLED )? setConfig(SIGNALISATION , STUN_ENABLE , NO_STR ) : setConfig( SIGNALISATION , STUN_ENABLE , YES_STR ); + (getConfigInt (SIGNALISATION , STUN_ENABLE) == STUN_ENABLED) ? setConfig (SIGNALISATION , STUN_ENABLE , NO_STR) : setConfig (SIGNALISATION , STUN_ENABLE , YES_STR); /* Restart PJSIP */ this->restartPJSIP (); } - int -ManagerImpl::getVolumeControls( void ) +int +ManagerImpl::getVolumeControls (void) { - return getConfigInt( PREFERENCES , CONFIG_VOLUME ); + return getConfigInt (PREFERENCES , CONFIG_VOLUME); } void -ManagerImpl::setVolumeControls( void ) +ManagerImpl::setVolumeControls (void) { - ( getConfigInt( PREFERENCES , CONFIG_VOLUME ) == DISPLAY_VOLUME_CONTROLS )? setConfig(PREFERENCES , CONFIG_VOLUME , NO_STR ) : setConfig( PREFERENCES , CONFIG_VOLUME , YES_STR ); + (getConfigInt (PREFERENCES , CONFIG_VOLUME) == DISPLAY_VOLUME_CONTROLS) ? setConfig (PREFERENCES , CONFIG_VOLUME , NO_STR) : setConfig (PREFERENCES , CONFIG_VOLUME , YES_STR); } void -ManagerImpl::setRecordingCall(const CallID& id) +ManagerImpl::setRecordingCall (const CallID& id) { - _debug("ManagerImpl::setRecording()! \n"); - AccountID accountid = getAccountFromCall( id ); + _debug ("ManagerImpl::setRecording()! \n"); + AccountID accountid = getAccountFromCall (id); - getAccountLink(accountid)->setRecording(id); + getAccountLink (accountid)->setRecording (id); } bool -ManagerImpl::isRecording(const CallID& id) +ManagerImpl::isRecording (const CallID& id) { - _debug("ManagerImpl::isRecording()! \n"); - AccountID accountid = getAccountFromCall( id ); + _debug ("ManagerImpl::isRecording()! \n"); + AccountID accountid = getAccountFromCall (id); - return getAccountLink(accountid)->isRecording(id); + return getAccountLink (accountid)->isRecording (id); } void -ManagerImpl::startHidden( void ) +ManagerImpl::startHidden (void) { - ( getConfigInt( PREFERENCES , CONFIG_START ) == START_HIDDEN)? setConfig(PREFERENCES , CONFIG_START , NO_STR ) : setConfig( PREFERENCES , CONFIG_START , YES_STR ); + (getConfigInt (PREFERENCES , CONFIG_START) == START_HIDDEN) ? setConfig (PREFERENCES , CONFIG_START , NO_STR) : setConfig (PREFERENCES , CONFIG_START , YES_STR); } int -ManagerImpl::isStartHidden( void ) +ManagerImpl::isStartHidden (void) { - return getConfigInt( PREFERENCES , CONFIG_START ); + return getConfigInt (PREFERENCES , CONFIG_START); } void -ManagerImpl::switchPopupMode( void ) +ManagerImpl::switchPopupMode (void) { - ( getConfigInt( PREFERENCES , CONFIG_POPUP ) == WINDOW_POPUP)? setConfig(PREFERENCES , CONFIG_POPUP , NO_STR ) : setConfig( PREFERENCES , CONFIG_POPUP , YES_STR ); + (getConfigInt (PREFERENCES , CONFIG_POPUP) == WINDOW_POPUP) ? setConfig (PREFERENCES , CONFIG_POPUP , NO_STR) : setConfig (PREFERENCES , CONFIG_POPUP , YES_STR); } void ManagerImpl::setHistoryLimit (const int& days) @@ -1756,161 +1879,164 @@ int ManagerImpl::getHistoryEnabled (void) void ManagerImpl::setHistoryEnabled (void) { - ( getConfigInt (PREFERENCES, CONFIG_HISTORY_ENABLED) == 1) ? setConfig (PREFERENCES, CONFIG_HISTORY_ENABLED, NO_STR) : setConfig(PREFERENCES, CONFIG_HISTORY_ENABLED, YES_STR); + (getConfigInt (PREFERENCES, CONFIG_HISTORY_ENABLED) == 1) ? setConfig (PREFERENCES, CONFIG_HISTORY_ENABLED, NO_STR) : setConfig (PREFERENCES, CONFIG_HISTORY_ENABLED, YES_STR); } int -ManagerImpl::getSearchbar( void ) +ManagerImpl::getSearchbar (void) { - return getConfigInt( PREFERENCES , CONFIG_SEARCHBAR ); + return getConfigInt (PREFERENCES , CONFIG_SEARCHBAR); } void -ManagerImpl::setSearchbar( void ) +ManagerImpl::setSearchbar (void) { - ( getConfigInt( PREFERENCES , CONFIG_SEARCHBAR ) == 1)? setConfig(PREFERENCES , CONFIG_SEARCHBAR , NO_STR ) : setConfig( PREFERENCES , CONFIG_SEARCHBAR , YES_STR ); + (getConfigInt (PREFERENCES , CONFIG_SEARCHBAR) == 1) ? setConfig (PREFERENCES , CONFIG_SEARCHBAR , NO_STR) : setConfig (PREFERENCES , CONFIG_SEARCHBAR , YES_STR); } int -ManagerImpl::popupMode( void ) +ManagerImpl::popupMode (void) { - return getConfigInt( PREFERENCES , CONFIG_POPUP ); + return getConfigInt (PREFERENCES , CONFIG_POPUP); } int32_t -ManagerImpl::getNotify( void ) +ManagerImpl::getNotify (void) { - return getConfigInt( PREFERENCES , CONFIG_NOTIFY ); + return getConfigInt (PREFERENCES , CONFIG_NOTIFY); } void -ManagerImpl::setNotify( void ) +ManagerImpl::setNotify (void) { - ( getConfigInt( PREFERENCES , CONFIG_NOTIFY ) == NOTIFY_ALL )? setConfig( PREFERENCES , CONFIG_NOTIFY , NO_STR ) : setConfig( PREFERENCES , CONFIG_NOTIFY , YES_STR ); + (getConfigInt (PREFERENCES , CONFIG_NOTIFY) == NOTIFY_ALL) ? setConfig (PREFERENCES , CONFIG_NOTIFY , NO_STR) : setConfig (PREFERENCES , CONFIG_NOTIFY , YES_STR); } int32_t -ManagerImpl::getMailNotify( void ) +ManagerImpl::getMailNotify (void) { - return getConfigInt( PREFERENCES , CONFIG_MAIL_NOTIFY ); + return getConfigInt (PREFERENCES , CONFIG_MAIL_NOTIFY); } int32_t -ManagerImpl::getPulseAppVolumeControl( void ) +ManagerImpl::getPulseAppVolumeControl (void) { - return getConfigInt( PREFERENCES , CONFIG_PA_VOLUME_CTRL ); + return getConfigInt (PREFERENCES , CONFIG_PA_VOLUME_CTRL); } void -ManagerImpl::setPulseAppVolumeControl( void ) +ManagerImpl::setPulseAppVolumeControl (void) { - (getConfigInt( PREFERENCES , CONFIG_PA_VOLUME_CTRL ) == 1)? setConfig( PREFERENCES , CONFIG_PA_VOLUME_CTRL , NO_STR) : setConfig( PREFERENCES , CONFIG_PA_VOLUME_CTRL , YES_STR) ; + (getConfigInt (PREFERENCES , CONFIG_PA_VOLUME_CTRL) == 1) ? setConfig (PREFERENCES , CONFIG_PA_VOLUME_CTRL , NO_STR) : setConfig (PREFERENCES , CONFIG_PA_VOLUME_CTRL , YES_STR) ; } -void ManagerImpl::setAudioManager( const int32_t& api ) +void ManagerImpl::setAudioManager (const int32_t& api) { int type, samplerate, framesize, numCardIn, numCardOut; std::string alsaPlugin; - _debug( "Setting audio manager \n"); + _debug ("Setting audio manager \n"); - if(!_audiodriver) + if (!_audiodriver) return; type = _audiodriver->getLayerType(); - if(type == api){ - _debug( "Audio manager chosen already in use. No changes made. \n"); + if (type == api) { + _debug ("Audio manager chosen already in use. No changes made. \n"); return; } - setConfig( PREFERENCES , CONFIG_AUDIO , api) ; + setConfig (PREFERENCES , CONFIG_AUDIO , api) ; + switchAudioManager(); return; -/* - int manager; + /* + int manager; - _debug(" ManagerImpl::setAudioManager :: %i \n",api); + _debug(" ManagerImpl::setAudioManager :: %i \n",api); - manager = api; - if( manager == PULSEAUDIO ) - { - if(app_is_running("pulseaudio") != 0) + manager = api; + if( manager == PULSEAUDIO ) { - // The pulseaudio daemon is not running - manager = ALSA; - notifyErrClient(PULSEAUDIO_NOT_RUNNING); + if(app_is_running("pulseaudio") != 0) + { + // The pulseaudio daemon is not running + manager = ALSA; + notifyErrClient(PULSEAUDIO_NOT_RUNNING); + } } - } - if(manager == api) - { - // it means that we can change the audio manager - setConfig( PREFERENCES , CONFIG_AUDIO , api) ; - switchAudioManager(); - } -*/ + if(manager == api) + { + // it means that we can change the audio manager + setConfig( PREFERENCES , CONFIG_AUDIO , api) ; + switchAudioManager(); + } + */ } int32_t -ManagerImpl::getAudioManager( void ) +ManagerImpl::getAudioManager (void) { - return getConfigInt( PREFERENCES , CONFIG_AUDIO ); + return getConfigInt (PREFERENCES , CONFIG_AUDIO); } int -ManagerImpl::getRegistrationExpireValue( void) +ManagerImpl::getRegistrationExpireValue (void) { - return getConfigInt( PREFERENCES , REGISTRATION_EXPIRE ); + return getConfigInt (PREFERENCES , REGISTRATION_EXPIRE); } void -ManagerImpl::setMailNotify( void ) +ManagerImpl::setMailNotify (void) { - ( getConfigInt( PREFERENCES , CONFIG_MAIL_NOTIFY ) == NOTIFY_ALL )? setConfig( PREFERENCES , CONFIG_MAIL_NOTIFY , NO_STR ) : setConfig( PREFERENCES , CONFIG_MAIL_NOTIFY , YES_STR ); + (getConfigInt (PREFERENCES , CONFIG_MAIL_NOTIFY) == NOTIFY_ALL) ? setConfig (PREFERENCES , CONFIG_MAIL_NOTIFY , NO_STR) : setConfig (PREFERENCES , CONFIG_MAIL_NOTIFY , YES_STR); } void -ManagerImpl::notifyErrClient( const int32_t& errCode ) +ManagerImpl::notifyErrClient (const int32_t& errCode) { - if( _dbus ){ - _debug("NOTIFY ERR NUMBER %i\n" , errCode); - _dbus -> getConfigurationManager() -> errorAlert( errCode ); - } + if (_dbus) { + _debug ("NOTIFY ERR NUMBER %i\n" , errCode); + _dbus -> getConfigurationManager() -> errorAlert (errCode); + } } - int -ManagerImpl::getAudioDeviceIndex(const std::string name) +int +ManagerImpl::getAudioDeviceIndex (const std::string name) { AlsaLayer *alsalayer; - _debug("Get audio device index\n"); + _debug ("Get audio device index\n"); alsalayer = dynamic_cast<AlsaLayer *> (getAudioDriver()); - if(alsalayer) return alsalayer -> soundCardGetIndex( name ); + + if (alsalayer) return alsalayer -> soundCardGetIndex (name); } - std::string -ManagerImpl::getCurrentAudioOutputPlugin( void ) +std::string +ManagerImpl::getCurrentAudioOutputPlugin (void) { AlsaLayer *alsalayer; - _debug("Get alsa plugin\n"); + _debug ("Get alsa plugin\n"); alsalayer = dynamic_cast<AlsaLayer *> (getAudioDriver()); - if(alsalayer) return alsalayer -> getAudioPlugin (); - else return getConfigString( AUDIO , ALSA_PLUGIN ); + + if (alsalayer) return alsalayer -> getAudioPlugin (); + else return getConfigString (AUDIO , ALSA_PLUGIN); } -int ManagerImpl::app_is_running( std::string process ) +int ManagerImpl::app_is_running (std::string process) { std::ostringstream cmd; cmd << "ps -C " << process; - return system(cmd.str().c_str()); + return system (cmd.str().c_str()); } @@ -1918,50 +2044,45 @@ int ManagerImpl::app_is_running( std::string process ) * Initialization: Main Thread */ bool -ManagerImpl::initAudioDriver(void) +ManagerImpl::initAudioDriver (void) { int error; - _debugInit("AudioLayer Creation"); + _debugInit ("AudioLayer Creation"); - if( getConfigInt( PREFERENCES , CONFIG_AUDIO ) == ALSA ) - { - _audiodriver = new AlsaLayer( this ); - } - else if( getConfigInt( PREFERENCES , CONFIG_AUDIO ) == PULSEAUDIO ) - { - if( app_is_running("pulseaudio") == 0 ) - { - _audiodriver = new PulseLayer( this ); - } else - { - _audiodriver = new AlsaLayer( this ); - setConfig( PREFERENCES, CONFIG_AUDIO, ALSA); + if (getConfigInt (PREFERENCES , CONFIG_AUDIO) == ALSA) { + _audiodriver = new AlsaLayer (this); + } else if (getConfigInt (PREFERENCES , CONFIG_AUDIO) == PULSEAUDIO) { + if (app_is_running ("pulseaudio") == 0) { + _audiodriver = new PulseLayer (this); + } else { + _audiodriver = new AlsaLayer (this); + setConfig (PREFERENCES, CONFIG_AUDIO, ALSA); } - } - else - _debug("Error - Audio API unknown\n"); + } else + _debug ("Error - Audio API unknown\n"); - if (_audiodriver == 0) { - _debug("Init audio driver error\n"); - return false; - } else { - error = getAudioDriver()->getErrorMessage(); - if (error == -1) { - _debug("Init audio driver: %i\n", error); - return false; + if (_audiodriver == 0) { + _debug ("Init audio driver error\n"); + return false; + } else { + error = getAudioDriver()->getErrorMessage(); + + if (error == -1) { + _debug ("Init audio driver: %i\n", error); + return false; + } } - } - return true; + return true; } /** * Initialization: Main Thread and gui */ - void +void ManagerImpl::selectAudioDriver (void) { int layer, numCardIn, numCardOut, sampleRate, frameSize; @@ -1969,42 +2090,46 @@ ManagerImpl::selectAudioDriver (void) AlsaLayer *alsalayer; layer = _audiodriver->getLayerType(); - _debug("Audio layer type: %i\n" , layer); + _debug ("Audio layer type: %i\n" , layer); /* Retrieve the global devices info from the user config */ - alsaPlugin = getConfigString( AUDIO , ALSA_PLUGIN ); - numCardIn = getConfigInt( AUDIO , ALSA_CARD_ID_IN ); - numCardOut = getConfigInt( AUDIO , ALSA_CARD_ID_OUT ); - sampleRate = getConfigInt( AUDIO , ALSA_SAMPLE_RATE ); + alsaPlugin = getConfigString (AUDIO , ALSA_PLUGIN); + numCardIn = getConfigInt (AUDIO , ALSA_CARD_ID_IN); + numCardOut = getConfigInt (AUDIO , ALSA_CARD_ID_OUT); + sampleRate = getConfigInt (AUDIO , ALSA_SAMPLE_RATE); + if (sampleRate <=0 || sampleRate > 48000) { sampleRate = 44100; } - frameSize = getConfigInt( AUDIO , ALSA_FRAME_SIZE ); + + frameSize = getConfigInt (AUDIO , ALSA_FRAME_SIZE); /* Only for the ALSA layer, we check the sound card information */ - if (layer == ALSA) - { + + if (layer == ALSA) { alsalayer = dynamic_cast<AlsaLayer*> (getAudioDriver ()); - if( !alsalayer -> soundCardIndexExist( numCardIn , SFL_PCM_CAPTURE ) ) - { - _debug(" Card with index %i doesn't exist or cannot capture. Switch to 0.\n", numCardIn); + + if (!alsalayer -> soundCardIndexExist (numCardIn , SFL_PCM_CAPTURE)) { + _debug (" Card with index %i doesn't exist or cannot capture. Switch to 0.\n", numCardIn); numCardIn = ALSA_DFT_CARD_ID ; - setConfig( AUDIO , ALSA_CARD_ID_IN , ALSA_DFT_CARD_ID ); + setConfig (AUDIO , ALSA_CARD_ID_IN , ALSA_DFT_CARD_ID); } - if( !alsalayer -> soundCardIndexExist( numCardOut , SFL_PCM_PLAYBACK ) ) - { - _debug(" Card with index %i doesn't exist or cannot playback . Switch to 0.\n", numCardOut); + + if (!alsalayer -> soundCardIndexExist (numCardOut , SFL_PCM_PLAYBACK)) { + _debug (" Card with index %i doesn't exist or cannot playback . Switch to 0.\n", numCardOut); numCardOut = ALSA_DFT_CARD_ID ; - setConfig( AUDIO , ALSA_CARD_ID_OUT , ALSA_DFT_CARD_ID ); + setConfig (AUDIO , ALSA_CARD_ID_OUT , ALSA_DFT_CARD_ID); } } - _audiodriver->setErrorMessage(-1); + _audiodriver->setErrorMessage (-1); + /* Open the audio devices */ - _audiodriver->openDevice( numCardIn , numCardOut, sampleRate, frameSize, SFL_PCM_BOTH, alsaPlugin ); + _audiodriver->openDevice (numCardIn , numCardOut, sampleRate, frameSize, SFL_PCM_BOTH, alsaPlugin); /* Notify the error if there is one */ - if( _audiodriver -> getErrorMessage() != -1 ) - notifyErrClient( _audiodriver -> getErrorMessage()); + + if (_audiodriver -> getErrorMessage() != -1) + notifyErrClient (_audiodriver -> getErrorMessage()); } @@ -2013,46 +2138,60 @@ void ManagerImpl::switchAudioManager (void) int type, samplerate, framesize, numCardIn, numCardOut; std::string alsaPlugin; - _debug( "Switching audio manager \n"); + _debug ("Switching audio manager \n"); - if(!_audiodriver) + if (!_audiodriver) return; type = _audiodriver->getLayerType(); - samplerate = getConfigInt( AUDIO , ALSA_SAMPLE_RATE ); - framesize = getConfigInt( AUDIO , ALSA_FRAME_SIZE ); - alsaPlugin = getConfigString( AUDIO , ALSA_PLUGIN ); - numCardIn = getConfigInt( AUDIO , ALSA_CARD_ID_IN ); - numCardOut = getConfigInt( AUDIO , ALSA_CARD_ID_OUT ); - _debug("Deleting current layer... \n" ); + samplerate = getConfigInt (AUDIO , ALSA_SAMPLE_RATE); + + framesize = getConfigInt (AUDIO , ALSA_FRAME_SIZE); + + alsaPlugin = getConfigString (AUDIO , ALSA_PLUGIN); + + numCardIn = getConfigInt (AUDIO , ALSA_CARD_ID_IN); + + numCardOut = getConfigInt (AUDIO , ALSA_CARD_ID_OUT); + + _debug ("Deleting current layer... \n"); + //_audiodriver->closeLayer(); - delete _audiodriver; _audiodriver = NULL; + delete _audiodriver; + + _audiodriver = NULL; + + switch (type) { - switch( type ){ case ALSA: - _debug("Creating Pulseaudio layer...\n"); - _audiodriver = new PulseLayer( this ); + _debug ("Creating Pulseaudio layer...\n"); + _audiodriver = new PulseLayer (this); break; + case PULSEAUDIO: - _debug("Creating ALSA layer...\n"); - _audiodriver = new AlsaLayer( this ); + _debug ("Creating ALSA layer...\n"); + _audiodriver = new AlsaLayer (this); break; + default: - _debug("Error: audio layer unknown\n"); + _debug ("Error: audio layer unknown\n"); } - _audiodriver->setErrorMessage(-1); - _audiodriver->openDevice( numCardIn , numCardOut, samplerate, framesize, SFL_PCM_BOTH, alsaPlugin ); - if( _audiodriver -> getErrorMessage() != -1 ) - notifyErrClient( _audiodriver -> getErrorMessage()); + _audiodriver->setErrorMessage (-1); + + _audiodriver->openDevice (numCardIn , numCardOut, samplerate, framesize, SFL_PCM_BOTH, alsaPlugin); + + if (_audiodriver -> getErrorMessage() != -1) + notifyErrClient (_audiodriver -> getErrorMessage()); + + _debug ("Current device: %i \n", type); - _debug("Current device: %i \n", type); - _debug("has current call: %i \n", hasCurrentCall()); + _debug ("has current call: %i \n", hasCurrentCall()); // need to stop audio streams if there is currently no call - if( (type != PULSEAUDIO) && (!hasCurrentCall())) { - // _debug("There is currently a call!!\n"); + if ( (type != PULSEAUDIO) && (!hasCurrentCall())) { + // _debug("There is currently a call!!\n"); _audiodriver->stopStream(); } @@ -2062,16 +2201,16 @@ void ManagerImpl::switchAudioManager (void) * Init the volume for speakers/micro from 0 to 100 value * Initialization: Main Thread */ - void +void ManagerImpl::initVolume() { - _debugInit("Initiate Volume"); - setSpkrVolume(getConfigInt(AUDIO, VOLUME_SPKR)); - setMicVolume(getConfigInt(AUDIO, VOLUME_MICRO)); + _debugInit ("Initiate Volume"); + setSpkrVolume (getConfigInt (AUDIO, VOLUME_SPKR)); + setMicVolume (getConfigInt (AUDIO, VOLUME_MICRO)); } -void ManagerImpl::setSpkrVolume(unsigned short spkr_vol) +void ManagerImpl::setSpkrVolume (unsigned short spkr_vol) { PulseLayer *pulselayer = NULL; @@ -2080,25 +2219,24 @@ void ManagerImpl::setSpkrVolume(unsigned short spkr_vol) /* Only for PulseAudio */ pulselayer = dynamic_cast<PulseLayer*> (getAudioDriver()); - if (pulselayer) - { - if( pulselayer->getLayerType() == PULSEAUDIO ) - { - if(pulselayer) pulselayer->setPlaybackVolume (spkr_vol); + + if (pulselayer) { + if (pulselayer->getLayerType() == PULSEAUDIO) { + if (pulselayer) pulselayer->setPlaybackVolume (spkr_vol); } } } -void ManagerImpl::setMicVolume(unsigned short mic_vol) +void ManagerImpl::setMicVolume (unsigned short mic_vol) { _mic_volume = mic_vol; } -void ManagerImpl::setSipPort( int port ) +void ManagerImpl::setSipPort (int port) { } -int ManagerImpl::getSipPort( void ) +int ManagerImpl::getSipPort (void) { return 5060; } @@ -2108,120 +2246,173 @@ int ManagerImpl::getSipPort( void ) /** * Main Thread */ - bool -ManagerImpl::getCallStatus(const std::string& sequenceId UNUSED) -{ - if (!_dbus) { return false; } - ost::MutexLock m(_callAccountMapMutex); - CallAccountMap::iterator iter = _callAccountMap.begin(); - TokenList tk; - std::string code; - std::string status; - std::string destination; - std::string number; - - while (iter != _callAccountMap.end()) - { - Call* call = getAccountLink(iter->second)->getCall(iter->first); - Call::ConnectionState state = call->getConnectionState(); - if (state != Call::Connected) { - switch(state) { - case Call::Trying: code="110"; status = "Trying"; break; - case Call::Ringing: code="111"; status = "Ringing"; break; - case Call::Progressing: code="125"; status = "Progressing"; break; - case Call::Disconnected: code="125"; status = "Disconnected"; break; - default: code=""; status= ""; - } - } else { - switch (call->getState()) { - case Call::Active: code="112"; status = "Established"; break; - case Call::Hold: code="114"; status = "Held"; break; - case Call::Busy: code="113"; status = "Busy"; break; - case Call::Refused: code="125"; status = "Refused"; break; - case Call::Error: code="125"; status = "Error"; break; - case Call::Inactive: code="125"; status = "Inactive"; break; - } - } - - // No Congestion - // No Wrong Number - // 116 <CSeq> <call-id> <acc> <destination> Busy - destination = call->getPeerName(); - number = call->getPeerNumber(); - if (number!="") { - destination.append(" <"); - destination.append(number); - destination.append(">"); +bool +ManagerImpl::getCallStatus (const std::string& sequenceId UNUSED) +{ + if (!_dbus) { + return false; } - tk.push_back(iter->second); - tk.push_back(destination); - tk.push_back(status); - tk.clear(); - iter++; - } + ost::MutexLock m (_callAccountMapMutex); + + CallAccountMap::iterator iter = _callAccountMap.begin(); + TokenList tk; + std::string code; + std::string status; + std::string destination; + std::string number; + + while (iter != _callAccountMap.end()) { + Call* call = getAccountLink (iter->second)->getCall (iter->first); + Call::ConnectionState state = call->getConnectionState(); + + if (state != Call::Connected) { + switch (state) { + + case Call::Trying: + code="110"; + status = "Trying"; + break; - return true; + case Call::Ringing: + code="111"; + status = "Ringing"; + break; + + case Call::Progressing: + code="125"; + status = "Progressing"; + break; + + case Call::Disconnected: + code="125"; + status = "Disconnected"; + break; + + default: + code=""; + status= ""; + } + } else { + switch (call->getState()) { + + case Call::Active: + code="112"; + status = "Established"; + break; + + case Call::Hold: + code="114"; + status = "Held"; + break; + + case Call::Busy: + code="113"; + status = "Busy"; + break; + + case Call::Refused: + code="125"; + status = "Refused"; + break; + + case Call::Error: + code="125"; + status = "Error"; + break; + + case Call::Inactive: + code="125"; + status = "Inactive"; + break; + } + } + + // No Congestion + // No Wrong Number + // 116 <CSeq> <call-id> <acc> <destination> Busy + destination = call->getPeerName(); + + number = call->getPeerNumber(); + + if (number!="") { + destination.append (" <"); + destination.append (number); + destination.append (">"); + } + + tk.push_back (iter->second); + + tk.push_back (destination); + tk.push_back (status); + tk.clear(); + + iter++; + } + + return true; } //THREAD=Main - bool -ManagerImpl::getConfig(const std::string& section, const std::string& name, TokenList& arg) +bool +ManagerImpl::getConfig (const std::string& section, const std::string& name, TokenList& arg) { - return _config.getConfigTreeItemToken(section, name, arg); + return _config.getConfigTreeItemToken (section, name, arg); } //THREAD=Main // throw an Conf::ConfigTreeItemException if not found - int -ManagerImpl::getConfigInt(const std::string& section, const std::string& name) +int +ManagerImpl::getConfigInt (const std::string& section, const std::string& name) { - try { - return _config.getConfigTreeItemIntValue(section, name); - } catch (Conf::ConfigTreeItemException& e) { - throw e; - } - return 0; + try { + return _config.getConfigTreeItemIntValue (section, name); + } catch (Conf::ConfigTreeItemException& e) { + throw e; + } + + return 0; } //THREAD=Main std::string -ManagerImpl::getConfigString(const std::string& section, const std::string& - name) +ManagerImpl::getConfigString (const std::string& section, const std::string& + name) { - try { - return _config.getConfigTreeItemValue(section, name); - } catch (Conf::ConfigTreeItemException& e) { - throw e; - } - return ""; + try { + return _config.getConfigTreeItemValue (section, name); + } catch (Conf::ConfigTreeItemException& e) { + throw e; + } + + return ""; } //THREAD=Main - bool -ManagerImpl::setConfig(const std::string& section, const std::string& name, const std::string& value) +bool +ManagerImpl::setConfig (const std::string& section, const std::string& name, const std::string& value) { - return _config.setConfigTreeItem(section, name, value); + return _config.setConfigTreeItem (section, name, value); } //THREAD=Main - bool -ManagerImpl::setConfig(const std::string& section, const std::string& name, int value) +bool +ManagerImpl::setConfig (const std::string& section, const std::string& name, int value) { - std::ostringstream valueStream; - valueStream << value; - return _config.setConfigTreeItem(section, name, valueStream.str()); + std::ostringstream valueStream; + valueStream << value; + return _config.setConfigTreeItem (section, name, valueStream.str()); } -void ManagerImpl::setAccountsOrder (const std::string& order) +void ManagerImpl::setAccountsOrder (const std::string& order) { - _debug("Set accounts order : %s\n", order.c_str() ); + _debug ("Set accounts order : %s\n", order.c_str()); // Set the new config setConfig (PREFERENCES, CONFIG_ACCOUNTS_ORDER, order); } - std::vector< std::string > +std::vector< std::string > ManagerImpl::getAccountList() { std::vector< std::string > v; @@ -2233,99 +2424,100 @@ ManagerImpl::getAccountList() // If no order has been set, load the default one // ie according to the creation date. + if (account_order.size () == 0) { iter = _accountMap.begin (); - while ( iter != _accountMap.end() ) { - if ( iter->second != 0 ) { - v.push_back(iter->first.data()); + + while (iter != _accountMap.end()) { + if (iter->second != 0) { + v.push_back (iter->first.data()); } + iter++; - } + } } // Otherelse, load the custom one // ie according to the saved order else { - + for (i=0; i<account_order.size (); i++) { // This account has not been loaded, so we ignore it - if ( (iter=_accountMap.find (account_order[i])) != _accountMap.end() ) - { + if ( (iter=_accountMap.find (account_order[i])) != _accountMap.end()) { // If the account is valid - if (iter->second != 0) - { + if (iter->second != 0) { v.push_back (iter->first.data ()); } } } - + } - + return v; } -std::map< std::string, std::string > ManagerImpl::getAccountDetails(const AccountID& accountID) +std::map< std::string, std::string > ManagerImpl::getAccountDetails (const AccountID& accountID) { - std::map<std::string, std::string> a; - std::string accountType; - RegistrationState state; + std::map<std::string, std::string> a; + std::string accountType; + RegistrationState state; - state = _accountMap[accountID]->getRegistrationState(); - accountType = getConfigString(accountID, CONFIG_ACCOUNT_TYPE); + state = _accountMap[accountID]->getRegistrationState(); + accountType = getConfigString (accountID, CONFIG_ACCOUNT_TYPE); - 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) == "1" ? "TRUE": "FALSE")); - a.insert( std::pair<std::string, std::string>( - "Status", - (state == Registered ? "REGISTERED": - (state == Unregistered ? "UNREGISTERED": - (state == Trying ? "TRYING": - (state == ErrorAuth ? "ERROR_AUTH": - (state == ErrorNetwork ? "ERROR_NETWORK": - (state == ErrorHost ? "ERROR_HOST": - (state == ErrorExistStun ? "ERROR_EXIST_STUN": - (state == ErrorConfStun ? "ERROR_CONF_STUN": - (state == Error ? "ERROR": "ERROR"))))))))) - ) - ); + 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) == "1" ? "TRUE": "FALSE")); + a.insert (std::pair<std::string, std::string> ( + "Status", + (state == Registered ? "REGISTERED": + (state == Unregistered ? "UNREGISTERED": + (state == Trying ? "TRYING": + (state == ErrorAuth ? "ERROR_AUTH": + (state == ErrorNetwork ? "ERROR_NETWORK": + (state == ErrorHost ? "ERROR_HOST": + (state == ErrorExistStun ? "ERROR_EXIST_STUN": + (state == ErrorConfStun ? "ERROR_CONF_STUN": + (state == Error ? "ERROR": "ERROR"))))))))) + ) + ); - a.insert( std::pair<std::string, std::string>( CONFIG_ACCOUNT_TYPE, accountType ) ); - 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>( HOSTNAME, getConfigString(accountID, HOSTNAME) ) ); - 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_TYPE, accountType)); + 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> (HOSTNAME, getConfigString (accountID, HOSTNAME))); + a.insert (std::pair<std::string, std::string> (CONFIG_ACCOUNT_MAILBOX, getConfigString (accountID, CONFIG_ACCOUNT_MAILBOX))); - return a; + return a; } -void ManagerImpl::setAccountDetails( const std::string& accountID, const std::map< std::string, std::string >& details ) +void ManagerImpl::setAccountDetails (const std::string& accountID, const std::map< std::string, std::string >& details) { std::string accountType; Account *acc; VoIPLink *link; - accountType = (*details.find(CONFIG_ACCOUNT_TYPE)).second; + accountType = (*details.find (CONFIG_ACCOUNT_TYPE)).second; - setConfig(accountID, CONFIG_ACCOUNT_ALIAS, (*details.find(CONFIG_ACCOUNT_ALIAS)).second); - setConfig(accountID, CONFIG_ACCOUNT_ENABLE, (*details.find(CONFIG_ACCOUNT_ENABLE)).second == "TRUE" ? "1": "0" ); - setConfig(accountID, CONFIG_ACCOUNT_TYPE, accountType); - setConfig(accountID, USERNAME, (*details.find(USERNAME)).second); - setConfig(accountID, PASSWORD, (*details.find(PASSWORD)).second); - setConfig(accountID, HOSTNAME, (*details.find(HOSTNAME)).second); - setConfig(accountID, CONFIG_ACCOUNT_MAILBOX,(*details.find(CONFIG_ACCOUNT_MAILBOX)).second); + setConfig (accountID, CONFIG_ACCOUNT_ALIAS, (*details.find (CONFIG_ACCOUNT_ALIAS)).second); + setConfig (accountID, CONFIG_ACCOUNT_ENABLE, (*details.find (CONFIG_ACCOUNT_ENABLE)).second == "TRUE" ? "1": "0"); + setConfig (accountID, CONFIG_ACCOUNT_TYPE, accountType); + setConfig (accountID, USERNAME, (*details.find (USERNAME)).second); + setConfig (accountID, PASSWORD, (*details.find (PASSWORD)).second); + setConfig (accountID, HOSTNAME, (*details.find (HOSTNAME)).second); + setConfig (accountID, CONFIG_ACCOUNT_MAILBOX, (*details.find (CONFIG_ACCOUNT_MAILBOX)).second); saveConfig(); - acc = getAccount(accountID); + acc = getAccount (accountID); acc->loadConfig(); - if (acc->isEnabled()){ + + if (acc->isEnabled()) { acc->unregisterVoIPLink(); acc->registerVoIPLink(); - } - else + } else acc->unregisterVoIPLink(); // Update account details to the client side @@ -2334,33 +2526,34 @@ void ManagerImpl::setAccountDetails( const std::string& accountID, const std::ma } void -ManagerImpl::sendRegister( const std::string& accountID , const int32_t& expire ) +ManagerImpl::sendRegister (const std::string& accountID , const int32_t& expire) { - _debug("ManagerImpl::sendRegister \n"); - // Update the active field - setConfig( accountID, CONFIG_ACCOUNT_ENABLE, expire ); - _debug("ManagerImpl::sendRegister set config done\n"); + _debug ("ManagerImpl::sendRegister \n"); + // Update the active field + setConfig (accountID, CONFIG_ACCOUNT_ENABLE, expire); + _debug ("ManagerImpl::sendRegister set config done\n"); - Account* acc = getAccount(accountID); - acc->loadConfig(); - _debug("ManagerImpl::sendRegister acc->loadconfig done\n"); + Account* acc = getAccount (accountID); + acc->loadConfig(); + _debug ("ManagerImpl::sendRegister acc->loadconfig done\n"); - // Test on the freshly updated value - if ( acc->isEnabled() ) { - // Verify we aren't already registered, then register - _debug("Send register for account %s\n" , accountID.c_str()); - acc->registerVoIPLink(); - } else { - // Verify we are already registered, then unregister - _debug("Send unregister for account %s\n" , accountID.c_str()); - acc->unregisterVoIPLink(); - } + // Test on the freshly updated value + + if (acc->isEnabled()) { + // Verify we aren't already registered, then register + _debug ("Send register for account %s\n" , accountID.c_str()); + acc->registerVoIPLink(); + } else { + // Verify we are already registered, then unregister + _debug ("Send unregister for account %s\n" , accountID.c_str()); + acc->unregisterVoIPLink(); + } } - std::string -ManagerImpl::addAccount(const std::map< std::string, std::string >& details) +std::string +ManagerImpl::addAccount (const std::map< std::string, std::string >& details) { /** @todo Deal with both the _accountMap and the Configuration */ @@ -2369,33 +2562,33 @@ ManagerImpl::addAccount(const std::map< std::string, std::string >& details) std::stringstream accountID; AccountID newAccountID; - accountID << "Account:" << time(NULL); + accountID << "Account:" << time (NULL); newAccountID = accountID.str(); - + // Get the type - accountType = (*details.find(CONFIG_ACCOUNT_TYPE)).second; + accountType = (*details.find (CONFIG_ACCOUNT_TYPE)).second; /** @todo Verify the uniqueness, in case a program adds accounts, two in a row. */ if (accountType == "SIP") { - newAccount = AccountCreator::createAccount(AccountCreator::SIP_ACCOUNT, newAccountID); - } - else if (accountType == "IAX") { - newAccount = AccountCreator::createAccount(AccountCreator::IAX_ACCOUNT, newAccountID); - } - else { - _debug("Unknown %s param when calling addAccount(): %s\n", CONFIG_ACCOUNT_TYPE, accountType.c_str()); + newAccount = AccountCreator::createAccount (AccountCreator::SIP_ACCOUNT, newAccountID); + } else if (accountType == "IAX") { + newAccount = AccountCreator::createAccount (AccountCreator::IAX_ACCOUNT, newAccountID); + } else { + _debug ("Unknown %s param when calling addAccount(): %s\n", CONFIG_ACCOUNT_TYPE, accountType.c_str()); return ""; } + _accountMap[newAccountID] = newAccount; - setAccountDetails(accountID.str(), details); + + setAccountDetails (accountID.str(), details); // Add the newly created account in the account order list account_list = getConfigString (PREFERENCES, CONFIG_ACCOUNTS_ORDER); - if (account_list != "") - { + + if (account_list != "") { newAccountID += "/"; - // Prepend the new account + // Prepend the new account account_list.insert (0, newAccountID); setConfig (PREFERENCES, CONFIG_ACCOUNTS_ORDER, account_list); } @@ -2403,83 +2596,90 @@ ManagerImpl::addAccount(const std::map< std::string, std::string >& details) saveConfig(); if (_dbus) _dbus->getConfigurationManager()->accountsChanged(); + return newAccountID; } - void -ManagerImpl::removeAccount(const AccountID& accountID) +void +ManagerImpl::removeAccount (const AccountID& accountID) { - // Get it down and dying - Account* remAccount = getAccount(accountID); + // Get it down and dying + Account* remAccount = getAccount (accountID); + + if (remAccount) { + remAccount->unregisterVoIPLink(); + _accountMap.erase (accountID); + delete remAccount; + } - if (remAccount) { - remAccount->unregisterVoIPLink(); - _accountMap.erase(accountID); - delete remAccount; - } + _config.removeSection (accountID); - _config.removeSection(accountID); + saveConfig(); - saveConfig(); + _debug ("REMOVE ACCOUNT\n"); - _debug("REMOVE ACCOUNT\n"); - if (_dbus) _dbus->getConfigurationManager()->accountsChanged(); + if (_dbus) _dbus->getConfigurationManager()->accountsChanged(); } // ACCOUNT handling - bool -ManagerImpl::associateCallToAccount(const CallID& callID, const AccountID& accountID) -{ - if (getAccountFromCall(callID) == AccountNULL) { // nothing with the same ID - if ( accountExists(accountID) ) { // account id exist in AccountMap - ost::MutexLock m(_callAccountMapMutex); - _callAccountMap[callID] = accountID; - _debug("Associate Call %s with Account %s\n", callID.data(), accountID.data()); - return true; +bool +ManagerImpl::associateCallToAccount (const CallID& callID, const AccountID& accountID) +{ + if (getAccountFromCall (callID) == AccountNULL) { // nothing with the same ID + if (accountExists (accountID)) { // account id exist in AccountMap + ost::MutexLock m (_callAccountMapMutex); + _callAccountMap[callID] = accountID; + _debug ("Associate Call %s with Account %s\n", callID.data(), accountID.data()); + return true; + } else { + return false; + } } else { - return false; + return false; } - } else { - return false; - } } - AccountID -ManagerImpl::getAccountFromCall(const CallID& callID) +AccountID +ManagerImpl::getAccountFromCall (const CallID& callID) { - ost::MutexLock m(_callAccountMapMutex); - CallAccountMap::iterator iter = _callAccountMap.find(callID); - if ( iter == _callAccountMap.end()) { - return AccountNULL; - } else { - return iter->second; - } + ost::MutexLock m (_callAccountMapMutex); + CallAccountMap::iterator iter = _callAccountMap.find (callID); + + if (iter == _callAccountMap.end()) { + return AccountNULL; + } else { + return iter->second; + } } - bool -ManagerImpl::removeCallAccount(const CallID& callID) +bool +ManagerImpl::removeCallAccount (const CallID& callID) { - ost::MutexLock m(_callAccountMapMutex); - if ( _callAccountMap.erase(callID) ) { - return true; - } - return false; + ost::MutexLock m (_callAccountMapMutex); + + if (_callAccountMap.erase (callID)) { + return true; + } + + return false; } - CallID +CallID ManagerImpl::getNewCallID() { - std::ostringstream random_id("s"); - random_id << (unsigned)rand(); + std::ostringstream random_id ("s"); + random_id << (unsigned) rand(); + + // when it's not found, it return "" + // generate, something like s10000s20000s4394040 - // when it's not found, it return "" - // generate, something like s10000s20000s4394040 - while (getAccountFromCall(random_id.str()) != AccountNULL) { - random_id.clear(); - random_id << "s"; - random_id << (unsigned)rand(); - } - return random_id.str(); + while (getAccountFromCall (random_id.str()) != AccountNULL) { + random_id.clear(); + random_id << "s"; + random_id << (unsigned) rand(); + } + + return random_id.str(); } std::vector <std::string> ManagerImpl::loadAccountOrder (void) @@ -2493,7 +2693,7 @@ std::vector <std::string> ManagerImpl::loadAccountOrder (void) } - short +short ManagerImpl::loadAccountMap() { @@ -2504,125 +2704,134 @@ ManagerImpl::loadAccountMap() std::vector <std::string> account_order; TokenList::iterator iter = sections.begin(); - - while(iter != sections.end()) { + + while (iter != sections.end()) { // Check if it starts with "Account:" (SIP and IAX pour le moment) - if ((int)(iter->find("Account:")) == -1) { + if ( (int) (iter->find ("Account:")) == -1) { iter++; continue; } - accountType = getConfigString(*iter, CONFIG_ACCOUNT_TYPE); - + accountType = getConfigString (*iter, CONFIG_ACCOUNT_TYPE); + if (accountType == "SIP") { - tmpAccount = AccountCreator::createAccount(AccountCreator::SIP_ACCOUNT, *iter); + tmpAccount = AccountCreator::createAccount (AccountCreator::SIP_ACCOUNT, *iter); } - + else if (accountType == "IAX") { - tmpAccount = AccountCreator::createAccount(AccountCreator::IAX_ACCOUNT, *iter); + tmpAccount = AccountCreator::createAccount (AccountCreator::IAX_ACCOUNT, *iter); } - + else { - _debug("Unknown %s param in config file (%s)\n", CONFIG_ACCOUNT_TYPE, accountType.c_str()); + _debug ("Unknown %s param in config file (%s)\n", CONFIG_ACCOUNT_TYPE, accountType.c_str()); } if (tmpAccount != NULL) { - _debug(" %s \n", iter->c_str()); - _accountMap[iter->c_str()] = tmpAccount; + _debug (" %s \n", iter->c_str()); + _accountMap[iter->c_str() ] = tmpAccount; nbAccount++; } iter++; } - - _debug("nbAccount loaded %i \n",nbAccount); + + _debug ("nbAccount loaded %i \n",nbAccount); + return nbAccount; } - void +void ManagerImpl::unloadAccountMap() { - AccountMap::iterator iter = _accountMap.begin(); - while ( iter != _accountMap.end() ) { + AccountMap::iterator iter = _accountMap.begin(); + + while (iter != _accountMap.end()) { - _debug("-> Deleting account %s\n", iter->first.c_str()); - delete iter->second; iter->second = 0; + _debug ("-> Deleting account %s\n", iter->first.c_str()); + delete iter->second; + iter->second = 0; - iter++; - } - _accountMap.clear(); + iter++; + } + + _accountMap.clear(); } - bool -ManagerImpl::accountExists(const AccountID& accountID) +bool +ManagerImpl::accountExists (const AccountID& accountID) { - AccountMap::iterator iter = _accountMap.find(accountID); - if ( iter == _accountMap.end() ) { - return false; - } - return true; + AccountMap::iterator iter = _accountMap.find (accountID); + + if (iter == _accountMap.end()) { + return false; + } + + return true; } - Account* -ManagerImpl::getAccount(const AccountID& accountID) +Account* +ManagerImpl::getAccount (const AccountID& accountID) { - AccountMap::iterator iter = _accountMap.find(accountID); - if ( iter == _accountMap.end() ) { - return 0; - } - return iter->second; + AccountMap::iterator iter = _accountMap.find (accountID); + + if (iter == _accountMap.end()) { + return 0; + } + + return iter->second; } AccountID -ManagerImpl::getAccountIdFromNameAndServer(const std::string& userName, const std::string& server) -{ - AccountMap::iterator iter; - SIPAccount *account; - _debug("getAccountIdFromNameAndServer : username = %s , server = %s\n", userName.c_str(), server.c_str()); - // Try to find the account id from username and server name by full match - for(iter = _accountMap.begin(); iter != _accountMap.end(); ++iter) { - _debug("for : account = %s\n", iter->first.c_str()); - account = dynamic_cast<SIPAccount *>(iter->second); - _debug("account != NULL = %i\n", (account != NULL)); - if (account != NULL){ - if(account->fullMatch(userName, server)) - { - _debug("fullMatch\n"); - return iter->first; - } - } - } - - // We failed! Then only match the hostname - for(iter = _accountMap.begin(); iter != _accountMap.end(); ++iter) { - account = dynamic_cast<SIPAccount *>(iter->second); - if ( account != NULL ) { - if(account->hostnameMatch(server)) - { - _debug("hostnameMatch\n"); - return iter->first; - } - } - } - - // We failed! Then only match the username - for(iter = _accountMap.begin(); iter != _accountMap.end(); ++iter) { - account = dynamic_cast<SIPAccount *>(iter->second); - if ( account != NULL ) { - if(account->userMatch(userName)) - { - _debug("userMatch\n"); - return iter->first; - } - } - } - - // Failed again! return AccountNULL - return AccountNULL; -} - -AccountMap ManagerImpl::getSipAccountMap( void ) +ManagerImpl::getAccountIdFromNameAndServer (const std::string& userName, const std::string& server) +{ + AccountMap::iterator iter; + SIPAccount *account; + _debug ("getAccountIdFromNameAndServer : username = %s , server = %s\n", userName.c_str(), server.c_str()); + // Try to find the account id from username and server name by full match + + for (iter = _accountMap.begin(); iter != _accountMap.end(); ++iter) { + _debug ("for : account = %s\n", iter->first.c_str()); + account = dynamic_cast<SIPAccount *> (iter->second); + _debug ("account != NULL = %i\n", (account != NULL)); + + if (account != NULL) { + if (account->fullMatch (userName, server)) { + _debug ("fullMatch\n"); + return iter->first; + } + } + } + + // We failed! Then only match the hostname + for (iter = _accountMap.begin(); iter != _accountMap.end(); ++iter) { + account = dynamic_cast<SIPAccount *> (iter->second); + + if (account != NULL) { + if (account->hostnameMatch (server)) { + _debug ("hostnameMatch\n"); + return iter->first; + } + } + } + + // We failed! Then only match the username + for (iter = _accountMap.begin(); iter != _accountMap.end(); ++iter) { + account = dynamic_cast<SIPAccount *> (iter->second); + + if (account != NULL) { + if (account->userMatch (userName)) { + _debug ("userMatch\n"); + return iter->first; + } + } + } + + // Failed again! return AccountNULL + return AccountNULL; +} + +AccountMap ManagerImpl::getSipAccountMap (void) { AccountMap::iterator iter; @@ -2630,13 +2839,14 @@ AccountMap ManagerImpl::getSipAccountMap( void ) AccountID id; Account *account; - for(iter = _accountMap.begin(); iter != _accountMap.end(); ++iter) { - if( iter->second->getType() == "sip" ){ + for (iter = _accountMap.begin(); iter != _accountMap.end(); ++iter) { + if (iter->second->getType() == "sip") { //id = iter->first; //account = iter->second; //sipaccounts.insert( std::pair<id, account> ); } } + return sipaccounts; } @@ -2648,28 +2858,28 @@ void ManagerImpl::restartPJSIP (void) this->unregisterCurSIPAccounts(); /* Terminate and initialize the PJSIP library */ - if (siplink) - { + if (siplink) { siplink->terminate (); - siplink = SIPVoIPLink::instance(""); + siplink = SIPVoIPLink::instance (""); siplink->init (); } /* Then register all enabled SIP accounts */ - this->registerCurSIPAccounts(siplink); + this->registerCurSIPAccounts (siplink); } -VoIPLink* ManagerImpl::getAccountLink(const AccountID& accountID) +VoIPLink* ManagerImpl::getAccountLink (const AccountID& accountID) { if (accountID!=AccountNULL) { - Account* acc = getAccount(accountID); - if ( acc ) { + Account* acc = getAccount (accountID); + + if (acc) { return acc->getVoIPLink(); } + return 0; - } - else - return SIPVoIPLink::instance(""); + } else + return SIPVoIPLink::instance (""); } VoIPLink* ManagerImpl::getSIPAccountLink() @@ -2677,12 +2887,15 @@ VoIPLink* ManagerImpl::getSIPAccountLink() /* We are looking for the first SIP account we met because all the SIP accounts have the same voiplink */ Account *account; AccountMap::iterator iter; - for(iter = _accountMap.begin(); iter != _accountMap.end(); ++iter) { + + for (iter = _accountMap.begin(); iter != _accountMap.end(); ++iter) { account = iter->second; - if( account->getType() == "sip" ){ + + if (account->getType() == "sip") { return account->getVoIPLink(); } } + return NULL; } @@ -2690,12 +2903,12 @@ VoIPLink* ManagerImpl::getSIPAccountLink() pjsip_regc -*getSipRegcFromID(const AccountID& id UNUSED) +*getSipRegcFromID (const AccountID& id UNUSED) { - /*SIPAccount *tmp = dynamic_cast<SIPAccount *>getAccount(id); - if(tmp != NULL) - return tmp->getSipRegc(); - else*/ + /*SIPAccount *tmp = dynamic_cast<SIPAccount *>getAccount(id); + if(tmp != NULL) + return tmp->getSipRegc(); + else*/ return NULL; } @@ -2704,45 +2917,51 @@ void ManagerImpl::unregisterCurSIPAccounts() Account *current; AccountMap::iterator iter = _accountMap.begin(); - while( iter != _accountMap.end() ) { + + while (iter != _accountMap.end()) { current = iter->second; + if (current) { - if ( current->isEnabled() && current->getType() == "sip") { - current->unregisterVoIPLink(); + if (current->isEnabled() && current->getType() == "sip") { + current->unregisterVoIPLink(); } } - iter++; + + iter++; } } -void ManagerImpl::registerCurSIPAccounts(VoIPLink *link) +void ManagerImpl::registerCurSIPAccounts (VoIPLink *link) { Account *current; AccountMap::iterator iter = _accountMap.begin(); - while( iter != _accountMap.end() ) { + while (iter != _accountMap.end()) { current = iter->second; if (current) { if (current->isEnabled() && current->getType() == "sip") { //current->setVoIPLink(link); - current->registerVoIPLink(); + current->registerVoIPLink(); } } + current = NULL; - iter++; + + iter++; } } -std::map<std::string, int32_t> ManagerImpl::getAddressbookSettings () { +std::map<std::string, int32_t> ManagerImpl::getAddressbookSettings () +{ std::map<std::string, int32_t> settings; - settings.insert (std::pair<std::string, int32_t> ("ADDRESSBOOK_ENABLE", getConfigInt (ADDRESSBOOK, ADDRESSBOOK_ENABLE)) ); - settings.insert (std::pair<std::string, int32_t> ("ADDRESSBOOK_MAX_RESULTS", getConfigInt (ADDRESSBOOK, ADDRESSBOOK_MAX_RESULTS)) ); + settings.insert (std::pair<std::string, int32_t> ("ADDRESSBOOK_ENABLE", getConfigInt (ADDRESSBOOK, ADDRESSBOOK_ENABLE))); + settings.insert (std::pair<std::string, int32_t> ("ADDRESSBOOK_MAX_RESULTS", getConfigInt (ADDRESSBOOK, ADDRESSBOOK_MAX_RESULTS))); settings.insert (std::pair<std::string, int32_t> ("ADDRESSBOOK_DISPLAY_CONTACT_PHOTO", getConfigInt (ADDRESSBOOK, ADDRESSBOOK_DISPLAY_CONTACT_PHOTO))); settings.insert (std::pair<std::string, int32_t> ("ADDRESSBOOK_DISPLAY_PHONE_BUSINESS", getConfigInt (ADDRESSBOOK, ADDRESSBOOK_DISPLAY_PHONE_BUSINESS))); settings.insert (std::pair<std::string, int32_t> ("ADDRESSBOOK_DISPLAY_PHONE_HOME", getConfigInt (ADDRESSBOOK, ADDRESSBOOK_DISPLAY_PHONE_HOME))); @@ -2751,55 +2970,60 @@ std::map<std::string, int32_t> ManagerImpl::getAddressbookSettings () { return settings; } -void ManagerImpl::setAddressbookSettings (const std::map<std::string, int32_t>& settings){ +void ManagerImpl::setAddressbookSettings (const std::map<std::string, int32_t>& settings) +{ - setConfig(ADDRESSBOOK, ADDRESSBOOK_ENABLE, (*settings.find("ADDRESSBOOK_ENABLE")).second); - setConfig(ADDRESSBOOK, ADDRESSBOOK_MAX_RESULTS, (*settings.find("ADDRESSBOOK_MAX_RESULTS")).second); - setConfig(ADDRESSBOOK, ADDRESSBOOK_DISPLAY_CONTACT_PHOTO , (*settings.find("ADDRESSBOOK_DISPLAY_CONTACT_PHOTO")).second); - setConfig(ADDRESSBOOK, ADDRESSBOOK_DISPLAY_PHONE_BUSINESS , (*settings.find("ADDRESSBOOK_DISPLAY_PHONE_BUSINESS")).second); - setConfig(ADDRESSBOOK, ADDRESSBOOK_DISPLAY_PHONE_HOME , (*settings.find("ADDRESSBOOK_DISPLAY_PHONE_HOME")).second); - setConfig(ADDRESSBOOK, ADDRESSBOOK_DISPLAY_PHONE_MOBILE , (*settings.find("ADDRESSBOOK_DISPLAY_PHONE_MOBILE")).second); + setConfig (ADDRESSBOOK, ADDRESSBOOK_ENABLE, (*settings.find ("ADDRESSBOOK_ENABLE")).second); + setConfig (ADDRESSBOOK, ADDRESSBOOK_MAX_RESULTS, (*settings.find ("ADDRESSBOOK_MAX_RESULTS")).second); + setConfig (ADDRESSBOOK, ADDRESSBOOK_DISPLAY_CONTACT_PHOTO , (*settings.find ("ADDRESSBOOK_DISPLAY_CONTACT_PHOTO")).second); + setConfig (ADDRESSBOOK, ADDRESSBOOK_DISPLAY_PHONE_BUSINESS , (*settings.find ("ADDRESSBOOK_DISPLAY_PHONE_BUSINESS")).second); + setConfig (ADDRESSBOOK, ADDRESSBOOK_DISPLAY_PHONE_HOME , (*settings.find ("ADDRESSBOOK_DISPLAY_PHONE_HOME")).second); + setConfig (ADDRESSBOOK, ADDRESSBOOK_DISPLAY_PHONE_MOBILE , (*settings.find ("ADDRESSBOOK_DISPLAY_PHONE_MOBILE")).second); // Write it to the configuration file saveConfig (); } - void -ManagerImpl::setAddressbookList(const std::vector< std::string >& list){ +void +ManagerImpl::setAddressbookList (const std::vector< std::string >& list) +{ - std::string s = serialize(list); - setConfig(ADDRESSBOOK, ADDRESSBOOK_LIST, s); + std::string s = serialize (list); + setConfig (ADDRESSBOOK, ADDRESSBOOK_LIST, s); } - std::vector <std::string> -ManagerImpl::getAddressbookList( void ){ +std::vector <std::string> +ManagerImpl::getAddressbookList (void) +{ - std::string s = getConfigString(ADDRESSBOOK, ADDRESSBOOK_LIST); - return unserialize(s); + std::string s = getConfigString (ADDRESSBOOK, ADDRESSBOOK_LIST); + return unserialize (s); } -std::map<std::string, std::string> ManagerImpl::getHookSettings () { +std::map<std::string, std::string> ManagerImpl::getHookSettings () +{ std::map<std::string, std::string> settings; - settings.insert (std::pair<std::string, std::string> ("URLHOOK_SIP_FIELD", getConfigString (HOOKS, URLHOOK_SIP_FIELD)) ); - settings.insert (std::pair<std::string, std::string> ("URLHOOK_COMMAND", getConfigString (HOOKS, URLHOOK_COMMAND)) ); - settings.insert (std::pair<std::string, std::string> ("URLHOOK_SIP_ENABLED", getConfigString (HOOKS, URLHOOK_SIP_ENABLED)) ); - settings.insert (std::pair<std::string, std::string> ("URLHOOK_IAX2_ENABLED", getConfigString (HOOKS, URLHOOK_IAX2_ENABLED)) ); - settings.insert (std::pair<std::string, std::string> ("PHONE_NUMBER_HOOK_ENABLED", getConfigString (HOOKS, PHONE_NUMBER_HOOK_ENABLED)) ); - settings.insert (std::pair<std::string, std::string> ("PHONE_NUMBER_HOOK_ADD_PREFIX", getConfigString (HOOKS, PHONE_NUMBER_HOOK_ADD_PREFIX)) ); + settings.insert (std::pair<std::string, std::string> ("URLHOOK_SIP_FIELD", getConfigString (HOOKS, URLHOOK_SIP_FIELD))); + settings.insert (std::pair<std::string, std::string> ("URLHOOK_COMMAND", getConfigString (HOOKS, URLHOOK_COMMAND))); + settings.insert (std::pair<std::string, std::string> ("URLHOOK_SIP_ENABLED", getConfigString (HOOKS, URLHOOK_SIP_ENABLED))); + settings.insert (std::pair<std::string, std::string> ("URLHOOK_IAX2_ENABLED", getConfigString (HOOKS, URLHOOK_IAX2_ENABLED))); + settings.insert (std::pair<std::string, std::string> ("PHONE_NUMBER_HOOK_ENABLED", getConfigString (HOOKS, PHONE_NUMBER_HOOK_ENABLED))); + settings.insert (std::pair<std::string, std::string> ("PHONE_NUMBER_HOOK_ADD_PREFIX", getConfigString (HOOKS, PHONE_NUMBER_HOOK_ADD_PREFIX))); return settings; } -void ManagerImpl::setHookSettings (const std::map<std::string, std::string>& settings){ +void ManagerImpl::setHookSettings (const std::map<std::string, std::string>& settings) +{ - setConfig(HOOKS, URLHOOK_SIP_FIELD, (*settings.find("URLHOOK_SIP_FIELD")).second); - setConfig(HOOKS, URLHOOK_COMMAND, (*settings.find("URLHOOK_COMMAND")).second); - setConfig(HOOKS, URLHOOK_SIP_ENABLED, (*settings.find("URLHOOK_SIP_ENABLED")).second); - setConfig(HOOKS, URLHOOK_IAX2_ENABLED, (*settings.find("URLHOOK_IAX2_ENABLED")).second); - setConfig(HOOKS, PHONE_NUMBER_HOOK_ENABLED, (*settings.find("PHONE_NUMBER_HOOK_ENABLED")).second); - setConfig(HOOKS, PHONE_NUMBER_HOOK_ADD_PREFIX, (*settings.find("PHONE_NUMBER_HOOK_ADD_PREFIX")).second); + setConfig (HOOKS, URLHOOK_SIP_FIELD, (*settings.find ("URLHOOK_SIP_FIELD")).second); + setConfig (HOOKS, URLHOOK_COMMAND, (*settings.find ("URLHOOK_COMMAND")).second); + setConfig (HOOKS, URLHOOK_SIP_ENABLED, (*settings.find ("URLHOOK_SIP_ENABLED")).second); + setConfig (HOOKS, URLHOOK_IAX2_ENABLED, (*settings.find ("URLHOOK_IAX2_ENABLED")).second); + setConfig (HOOKS, PHONE_NUMBER_HOOK_ENABLED, (*settings.find ("PHONE_NUMBER_HOOK_ENABLED")).second); + setConfig (HOOKS, PHONE_NUMBER_HOOK_ADD_PREFIX, (*settings.find ("PHONE_NUMBER_HOOK_ADD_PREFIX")).second); // Write it to the configuration file saveConfig (); @@ -2808,7 +3032,8 @@ void ManagerImpl::setHookSettings (const std::map<std::string, std::string>& set -void ManagerImpl::check_call_configuration (const CallID& id, const std::string &to, Call::CallConfiguration *callConfig) { +void ManagerImpl::check_call_configuration (const CallID& id, const std::string &to, Call::CallConfiguration *callConfig) +{ std::string pattern; Call::CallConfiguration config; @@ -2816,47 +3041,56 @@ void ManagerImpl::check_call_configuration (const CallID& id, const std::string /* For an IP-to-IP call, we don't need any account */ /* Pattern looked for : ip:xxx.xxx.xxx.xxx */ pattern = to.substr (0,4); + if (pattern==IP_TO_IP_PATTERN) { - _debug("Sending Sip Call \n"); + _debug ("Sending Sip Call \n"); config = Call::IPtoIP; } else { config = Call::Classic; } + associateConfigToCall (id, config); + *callConfig = config; } -bool ManagerImpl::associateConfigToCall (const CallID& callID, Call::CallConfiguration config) { +bool ManagerImpl::associateConfigToCall (const CallID& callID, Call::CallConfiguration config) +{ - if (getConfigFromCall(callID) == CallConfigNULL) { // nothing with the same ID + if (getConfigFromCall (callID) == CallConfigNULL) { // nothing with the same ID _callConfigMap[callID] = config; - _debug("Associate Call %s with config %i\n", callID.data(), config); + _debug ("Associate Call %s with config %i\n", callID.data(), config); return true; } else { return false; } } -Call::CallConfiguration ManagerImpl::getConfigFromCall(const CallID& callID) { +Call::CallConfiguration ManagerImpl::getConfigFromCall (const CallID& callID) +{ + + CallConfigMap::iterator iter = _callConfigMap.find (callID); - CallConfigMap::iterator iter = _callConfigMap.find(callID); - if ( iter == _callConfigMap.end()) { - return (Call::CallConfiguration)CallConfigNULL; + if (iter == _callConfigMap.end()) { + return (Call::CallConfiguration) CallConfigNULL; } else { return iter->second; } } -bool ManagerImpl::removeCallConfig(const CallID& callID) { +bool ManagerImpl::removeCallConfig (const CallID& callID) +{ - if ( _callConfigMap.erase(callID) ) { + if (_callConfigMap.erase (callID)) { return true; } + return false; } -std::map< std::string, std::string > ManagerImpl::getCallDetails(const CallID& callID) { +std::map< std::string, std::string > ManagerImpl::getCallDetails (const CallID& callID) +{ std::map<std::string, std::string> call_details; AccountID accountid; @@ -2872,25 +3106,25 @@ std::map< std::string, std::string > ManagerImpl::getCallDetails(const CallID& c // So first we fetch the account accountid = getAccountFromCall (callID); - _debug("%s\n",callID.c_str()); + _debug ("%s\n",callID.c_str()); // Then the VoIP link this account is linked with (IAX2 or SIP) + if ( (account=getAccount (accountid)) != 0) { link = account->getVoIPLink (); + if (link) { call = link->getCall (callID); } } - if (call) - { + + if (call) { type << call->getCallType (); call_details.insert (std::pair<std::string, std::string> ("ACCOUNTID", accountid)); call_details.insert (std::pair<std::string, std::string> ("PEER_NUMBER", call->getPeerNumber ())); call_details.insert (std::pair<std::string, std::string> ("PEER_NAME", call->getPeerName ())); call_details.insert (std::pair<std::string, std::string> ("CALL_STATE", call->getStateStr ())); call_details.insert (std::pair<std::string, std::string> ("CALL_TYPE", type.str ())); - } - else - { + } else { _debug ("Error: Managerimpl - getCallDetails ()\n"); call_details.insert (std::pair<std::string, std::string> ("ACCOUNTID", AccountNULL)); call_details.insert (std::pair<std::string, std::string> ("PEER_NUMBER", "Unknown")); @@ -2898,6 +3132,7 @@ std::map< std::string, std::string > ManagerImpl::getCallDetails(const CallID& c call_details.insert (std::pair<std::string, std::string> ("CALL_STATE", "UNKNOWN")); call_details.insert (std::pair<std::string, std::string> ("CALL_TYPE", "0")); } + return call_details; } @@ -2905,8 +3140,8 @@ std::map< std::string, std::string > ManagerImpl::getCallDetails(const CallID& c std::map<std::string, std::string> ManagerImpl::send_history_to_client (void) { return _history->get_history_serialized (); -} - +} + void ManagerImpl::receive_history_from_client (std::map<std::string, std::string> history) { _history->set_serialized_history (history, Manager::instance().getConfigInt (PREFERENCES, CONFIG_HISTORY_LIMIT)); @@ -2914,7 +3149,7 @@ void ManagerImpl::receive_history_from_client (std::map<std::string, std::string } - std::vector< std::string > +std::vector< std::string > ManagerImpl::getCallList (void) { std::vector< std::string > v; @@ -2923,9 +3158,9 @@ ManagerImpl::getCallList (void) CallAccountMap::iterator iter = _callAccountMap.begin (); while (iter != _callAccountMap.end ()) { - v.push_back(iter->first.data()); + v.push_back (iter->first.data()); iter++; - } - + } + return v; } diff --git a/sflphone-common/src/numbercleaner.cpp b/sflphone-common/src/numbercleaner.cpp index afc07724f4..b583ca5945 100644 --- a/sflphone-common/src/numbercleaner.cpp +++ b/sflphone-common/src/numbercleaner.cpp @@ -22,13 +22,16 @@ #include <iostream> -NumberCleaner::NumberCleaner (void) : _prefix("") { +NumberCleaner::NumberCleaner (void) : _prefix ("") +{ } -NumberCleaner::~NumberCleaner (void) { +NumberCleaner::~NumberCleaner (void) +{ } -std::string NumberCleaner::clean (std::string to_clean) { +std::string NumberCleaner::clean (std::string to_clean) +{ strip_char (" ", &to_clean); strip_char ("-", &to_clean); @@ -38,11 +41,12 @@ std::string NumberCleaner::clean (std::string to_clean) { return to_clean.insert (0, this->get_phone_number_prefix ()); } -void NumberCleaner::strip_char (std::string to_strip, std::string *num) { +void NumberCleaner::strip_char (std::string to_strip, std::string *num) +{ std::size_t pos; - - while ( (pos=(*num).find (to_strip)) != std::string::npos) { + + while ( (pos= (*num).find (to_strip)) != std::string::npos) { *num = (*num).erase (pos, 1); } } diff --git a/sflphone-common/src/observer.cpp b/sflphone-common/src/observer.cpp index f7820b5d31..40ac49de63 100644 --- a/sflphone-common/src/observer.cpp +++ b/sflphone-common/src/observer.cpp @@ -19,35 +19,40 @@ #include "observer.h" #include <algorithm> -namespace Pattern { -void -Subject::attach(Observer& observer) +namespace Pattern { - if (std::find(_observers.begin(), _observers.end(), &observer) == _observers.end()) { - _observers.push_back(&observer); - } + +void +Subject::attach (Observer& observer) +{ + if (std::find (_observers.begin(), _observers.end(), &observer) == _observers.end()) { + _observers.push_back (&observer); + } } -void -Subject::detach(Observer& observer) +void +Subject::detach (Observer& observer) { - std::list<Observer*>::iterator iter = std::find(_observers.begin(), _observers.end(), &observer); - if ( iter != _observers.end()) { - _observers.erase(iter); - } + std::list<Observer*>::iterator iter = std::find (_observers.begin(), _observers.end(), &observer); + + if (iter != _observers.end()) { + _observers.erase (iter); + } } -void +void Subject::notify() { - std::list<Observer*>::iterator iter = _observers.begin(); - while( iter != _observers.end()) { - if (*iter) { - (*iter)->update(); + std::list<Observer*>::iterator iter = _observers.begin(); + + while (iter != _observers.end()) { + if (*iter) { + (*iter)->update(); + } + + iter++; } - iter++; - } } } // end of namespace diff --git a/sflphone-common/src/plug-in/audiorecorder/audiodsp.cpp b/sflphone-common/src/plug-in/audiorecorder/audiodsp.cpp index 8179df12a8..49ea4417cc 100644 --- a/sflphone-common/src/plug-in/audiorecorder/audiodsp.cpp +++ b/sflphone-common/src/plug-in/audiorecorder/audiodsp.cpp @@ -22,47 +22,48 @@ AudioDSP::AudioDSP() { - bufPointer_ = 0; - bufferLength_ = 1024; - circBuffer_ = new float[bufferLength_]; + bufPointer_ = 0; + bufferLength_ = 1024; + circBuffer_ = new float[bufferLength_]; } AudioDSP::~AudioDSP() { - - delete[] circBuffer_; + + delete[] circBuffer_; } -float AudioDSP::getRMS(int data) +float AudioDSP::getRMS (int data) { - // printf("AudioDSP::getRMS() : bufPointer_ %i \n ", bufPointer_); - printf("AudioDSP::getRMS() : %i \n", data); - circBuffer_[bufPointer_++] = (float)data; - - if(bufPointer_ >= bufferLength_) - bufPointer_ = 0; + // printf("AudioDSP::getRMS() : bufPointer_ %i \n ", bufPointer_); + printf ("AudioDSP::getRMS() : %i \n", data); + circBuffer_[bufPointer_++] = (float) data; + + if (bufPointer_ >= bufferLength_) + bufPointer_ = 0; - return computeRMS(); -} + return computeRMS(); +} float AudioDSP::computeRMS() { - rms = 0.0; + rms = 0.0; + + + for (int i = 0; i < bufferLength_; i++) { + // printf("AudioDSP::computeRMS() : i_ %i \n ", i); + rms += (float) (circBuffer_[i]*circBuffer_[i]); + } + + rms = sqrt (rms / (float) bufferLength_); - - for(int i = 0; i < bufferLength_; i++){ - // printf("AudioDSP::computeRMS() : i_ %i \n ", i); - rms += (float)(circBuffer_[i]*circBuffer_[i]); - } - rms = sqrt(rms / (float)bufferLength_); + // printf("AudioDSP::computeRMS() : RMS VALUE: %f \n", rms); + return rms; - // printf("AudioDSP::computeRMS() : RMS VALUE: %f \n", rms); - return rms; - } diff --git a/sflphone-common/src/plug-in/audiorecorder/audiorecord.cpp b/sflphone-common/src/plug-in/audiorecorder/audiorecord.cpp index 25703101d9..44a33bb280 100644 --- a/sflphone-common/src/plug-in/audiorecorder/audiorecord.cpp +++ b/sflphone-common/src/plug-in/audiorecorder/audiorecord.cpp @@ -20,448 +20,499 @@ #include "audiorecord.h" // structure for the wave header + struct wavhdr { - char riff[4]; // "RIFF" - SINT32 file_size; // in bytes - char wave[4]; // "WAVE" - char fmt[4]; // "fmt " - SINT32 chunk_size; // in bytes (16 for PCM) - SINT16 format_tag; // 1=PCM, 2=ADPCM, 3=IEEE float, 6=A-Law, 7=Mu-Law - SINT16 num_chans; // 1=mono, 2=stereo - SINT32 sample_rate; - SINT32 bytes_per_sec; - SINT16 bytes_per_samp; // 2=16-bit mono, 4=16-bit stereo - SINT16 bits_per_samp; - char data[4]; // "data" - SINT32 data_length; // in bytes + char riff[4]; // "RIFF" + SINT32 file_size; // in bytes + char wave[4]; // "WAVE" + char fmt[4]; // "fmt " + SINT32 chunk_size; // in bytes (16 for PCM) + SINT16 format_tag; // 1=PCM, 2=ADPCM, 3=IEEE float, 6=A-Law, 7=Mu-Law + SINT16 num_chans; // 1=mono, 2=stereo + SINT32 sample_rate; + SINT32 bytes_per_sec; + SINT16 bytes_per_samp; // 2=16-bit mono, 4=16-bit stereo + SINT16 bits_per_samp; + char data[4]; // "data" + SINT32 data_length; // in bytes }; -AudioRecord::AudioRecord(){ - - sndSmplRate_ = 44100; - channels_ = 1; - byteCounter_ = 0; - recordingEnabled_ = false; - fp = 0; - nbSamplesMax_ = 3000; +AudioRecord::AudioRecord() +{ - createFilename(); + sndSmplRate_ = 44100; + channels_ = 1; + byteCounter_ = 0; + recordingEnabled_ = false; + fp = 0; + nbSamplesMax_ = 3000; - mixBuffer_ = new SFLDataFormat[nbSamplesMax_]; - micBuffer_ = new SFLDataFormat[nbSamplesMax_]; - spkBuffer_ = new SFLDataFormat[nbSamplesMax_]; + createFilename(); + + mixBuffer_ = new SFLDataFormat[nbSamplesMax_]; + micBuffer_ = new SFLDataFormat[nbSamplesMax_]; + spkBuffer_ = new SFLDataFormat[nbSamplesMax_]; } -AudioRecord::~AudioRecord() { +AudioRecord::~AudioRecord() +{ delete [] mixBuffer_; delete [] micBuffer_; delete [] spkBuffer_; } -void AudioRecord::setSndSamplingRate(int smplRate){ - sndSmplRate_ = smplRate; +void AudioRecord::setSndSamplingRate (int smplRate) +{ + sndSmplRate_ = smplRate; } -void AudioRecord::setRecordingOption(FILE_TYPE type, SOUND_FORMAT format, int sndSmplRate, std::string path, std::string id){ - - - fileType_ = type; - sndFormat_ = format; - channels_ = 1; - sndSmplRate_ = sndSmplRate; - call_id_ = id; - - savePath_ = path + "/"; - -} +void AudioRecord::setRecordingOption (FILE_TYPE type, SOUND_FORMAT format, int sndSmplRate, std::string path, std::string id) +{ + fileType_ = type; + sndFormat_ = format; + channels_ = 1; + sndSmplRate_ = sndSmplRate; + call_id_ = id; + + savePath_ = path + "/"; -void AudioRecord::initFileName( std::string peerNumber){ - - std::string fName; - - fName = fileName_; - fName.append("-"+peerNumber); - - if (fileType_ == FILE_RAW){ - if ( strstr(fileName_, ".raw") == NULL){ - printf("AudioRecord::openFile::concatenate .raw file extension: name : %s \n", fileName_); - fName.append(".raw"); - } - } - else if (fileType_ == FILE_WAV){ - if ( strstr(fileName_, ".wav") == NULL){ - printf("AudioRecord::openFile::concatenate .wav file extension: name : %s \n", fileName_); - fName.append(".wav"); - } - } - - savePath_.append(fName); } -void AudioRecord::openFile(){ - - - _debug("AudioRecord::openFile()\n"); - - bool result = false; - - _debug("AudioRecord::openFile()\n"); - if(isFileExist()) { - _debug("AudioRecord::Filename does not exist, creating one \n"); - byteCounter_ = 0; - - if(fileType_ == FILE_RAW){ - result = setRawFile(); - } - else if (fileType_ == FILE_WAV){ - result = setWavFile(); - } - } - else { - _debug("AudioRecord::Filename already exist opening it \n"); - if(fileType_ == FILE_RAW){ - result = openExistingRawFile(); - } - else if (fileType_ == FILE_WAV){ - result = openExistingWavFile(); - } - } + + +void AudioRecord::initFileName (std::string peerNumber) +{ + + std::string fName; + + fName = fileName_; + fName.append ("-"+peerNumber); + + if (fileType_ == FILE_RAW) { + if (strstr (fileName_, ".raw") == NULL) { + printf ("AudioRecord::openFile::concatenate .raw file extension: name : %s \n", fileName_); + fName.append (".raw"); + } + } else if (fileType_ == FILE_WAV) { + if (strstr (fileName_, ".wav") == NULL) { + printf ("AudioRecord::openFile::concatenate .wav file extension: name : %s \n", fileName_); + fName.append (".wav"); + } + } + + savePath_.append (fName); } +void AudioRecord::openFile() +{ + + + _debug ("AudioRecord::openFile()\n"); -void AudioRecord::closeFile() { + bool result = false; - if (fp == 0) return; + _debug ("AudioRecord::openFile()\n"); - if (fileType_ == FILE_RAW) - fclose(fp); - else if (fileType_ == FILE_WAV) - this->closeWavFile(); + if (isFileExist()) { + _debug ("AudioRecord::Filename does not exist, creating one \n"); + byteCounter_ = 0; - + if (fileType_ == FILE_RAW) { + result = setRawFile(); + } else if (fileType_ == FILE_WAV) { + result = setWavFile(); + } + } else { + _debug ("AudioRecord::Filename already exist opening it \n"); + if (fileType_ == FILE_RAW) { + result = openExistingRawFile(); + } else if (fileType_ == FILE_WAV) { + result = openExistingWavFile(); + } + } } -bool AudioRecord::isOpenFile() { - - if(fp){ - _debug("AudioRecord::isOpenFile(): file already openend\n"); - return true; - } - else { - _debug("AudioRecord::isOpenFIle(): file not openend \n"); - return false; - } +void AudioRecord::closeFile() +{ + + if (fp == 0) return; + + if (fileType_ == FILE_RAW) + fclose (fp); + else if (fileType_ == FILE_WAV) + this->closeWavFile(); + + + } -bool AudioRecord::isFileExist() { - _debug("AudioRecord::isFileExist(): try to open name : %s \n", fileName_); - - if(fopen(fileName_,"rb")==0) { - return true; - } - - return false; +bool AudioRecord::isOpenFile() +{ + + if (fp) { + _debug ("AudioRecord::isOpenFile(): file already openend\n"); + return true; + } else { + _debug ("AudioRecord::isOpenFIle(): file not openend \n"); + return false; + } } -bool AudioRecord::isRecording() { - _debug("AudioRecording::isRecording() %i \n", recordingEnabled_); - - - if(recordingEnabled_) - return true; - else + +bool AudioRecord::isFileExist() +{ + _debug ("AudioRecord::isFileExist(): try to open name : %s \n", fileName_); + + if (fopen (fileName_,"rb") ==0) { + return true; + } + return false; } +bool AudioRecord::isRecording() +{ + _debug ("AudioRecording::isRecording() %i \n", recordingEnabled_); + -bool AudioRecord::setRecording() { - _debug("AudioRecord::setRecording() \n"); - - if (isOpenFile()){ - _debug("AuioRecord::setRecording()::file already opened \n"); - if(!recordingEnabled_) - recordingEnabled_ = true; - else - recordingEnabled_ = false; - } - else { - _debug("AudioRecord::setRecording():Opening the wave file in call during call instantiation \n"); - openFile(); - - recordingEnabled_ = true; // once opend file, start recording - } - + if (recordingEnabled_) + return true; + else + return false; } -void AudioRecord::stopRecording() { - _debug("AudioRecording::stopRecording() \n"); - if(recordingEnabled_) - recordingEnabled_ = false; +bool AudioRecord::setRecording() +{ + _debug ("AudioRecord::setRecording() \n"); + + if (isOpenFile()) { + _debug ("AuioRecord::setRecording()::file already opened \n"); + + if (!recordingEnabled_) + recordingEnabled_ = true; + else + recordingEnabled_ = false; + } else { + _debug ("AudioRecord::setRecording():Opening the wave file in call during call instantiation \n"); + openFile(); + + recordingEnabled_ = true; // once opend file, start recording + } + +} + +void AudioRecord::stopRecording() +{ + _debug ("AudioRecording::stopRecording() \n"); + + if (recordingEnabled_) + recordingEnabled_ = false; } -void AudioRecord::createFilename(){ - +void AudioRecord::createFilename() +{ + time_t rawtime; + struct tm * timeinfo; - rawtime = time(NULL); - timeinfo = localtime ( &rawtime ); + rawtime = time (NULL); + timeinfo = localtime (&rawtime); stringstream out; - + // DATE out << timeinfo->tm_year+1900; + if (timeinfo->tm_mon < 9) // january is 01, not 1 - out << 0; + out << 0; + out << timeinfo->tm_mon+1; + if (timeinfo->tm_mday < 10) // 01 02 03, not 1 2 3 - out << 0; + out << 0; + out << timeinfo->tm_mday; - + out << '-'; - + // hour if (timeinfo->tm_hour < 10) // 01 02 03, not 1 2 3 - out << 0; + out << 0; + out << timeinfo->tm_hour; + out << ':'; + if (timeinfo->tm_min < 10) // 01 02 03, not 1 2 3 - out << 0; + out << 0; + out << timeinfo->tm_min; + out << ':'; + if (timeinfo->tm_sec < 10) // 01 02 03, not 1 2 3 - out << 0; + out << 0; + out << timeinfo->tm_sec; // fileName_ = out.str(); - strncpy(fileName_, out.str().c_str(), 8192); + strncpy (fileName_, out.str().c_str(), 8192); - printf("AudioRecord::createFilename::filename for this call %s \n",fileName_); + printf ("AudioRecord::createFilename::filename for this call %s \n",fileName_); } -bool AudioRecord::setRawFile() { +bool AudioRecord::setRawFile() +{ - fp = fopen(savePath_.c_str(), "wb"); - if ( !fp ) { - _debug("AudioRecord::setRawFile() : could not create RAW file!\n"); - return false; - } + fp = fopen (savePath_.c_str(), "wb"); - if ( sndFormat_ != INT16 ) { // TODO need to change INT16 to SINT16 - sndFormat_ = INT16; - _debug("AudioRecord::setRawFile() : using 16-bit signed integer data format for file.\n"); - } + if (!fp) { + _debug ("AudioRecord::setRawFile() : could not create RAW file!\n"); + return false; + } + + if (sndFormat_ != INT16) { // TODO need to change INT16 to SINT16 + sndFormat_ = INT16; + _debug ("AudioRecord::setRawFile() : using 16-bit signed integer data format for file.\n"); + } - _debug("AudioRecord:setRawFile() : created RAW file.\n"); - return true; + _debug ("AudioRecord:setRawFile() : created RAW file.\n"); + + return true; } -bool AudioRecord::setWavFile() { - - fp = fopen(savePath_.c_str(), "wb"); - if ( !fp ) { - _debug("AudioRecord::setWavFile() : could not create WAV file.\n"); - return false; - } - - struct wavhdr hdr = {"RIF", 44, "WAV", "fmt", 16, 1, 1, - 44100, 0, 2, 16, "dat", 0}; - hdr.riff[3] = 'F'; - hdr.wave[3] = 'E'; - hdr.fmt[3] = ' '; - hdr.data[3] = 'a'; - hdr.num_chans = channels_; - if ( sndFormat_ == INT16 ) { // TODO need to write INT16 to SINT16 - hdr.bits_per_samp = 16; - } - hdr.bytes_per_samp = (SINT16) (channels_ * hdr.bits_per_samp / 8); - hdr.bytes_per_sec = (SINT32) (hdr.sample_rate * hdr.bytes_per_samp); - - - if ( fwrite(&hdr, 4, 11, fp) != 11) { - _debug("AudioRecord::setWavFile() : could not write WAV header for file. \n"); - return false; - } +bool AudioRecord::setWavFile() +{ + + fp = fopen (savePath_.c_str(), "wb"); + + if (!fp) { + _debug ("AudioRecord::setWavFile() : could not create WAV file.\n"); + return false; + } + + struct wavhdr hdr = {"RIF", 44, "WAV", "fmt", 16, 1, 1, + 44100, 0, 2, 16, "dat", 0 + }; + + hdr.riff[3] = 'F'; + + hdr.wave[3] = 'E'; + + hdr.fmt[3] = ' '; + + hdr.data[3] = 'a'; + + hdr.num_chans = channels_; + + if (sndFormat_ == INT16) { // TODO need to write INT16 to SINT16 + hdr.bits_per_samp = 16; + } + + hdr.bytes_per_samp = (SINT16) (channels_ * hdr.bits_per_samp / 8); + + hdr.bytes_per_sec = (SINT32) (hdr.sample_rate * hdr.bytes_per_samp); + + + if (fwrite (&hdr, 4, 11, fp) != 11) { + _debug ("AudioRecord::setWavFile() : could not write WAV header for file. \n"); + return false; + } + + _debug ("AudioRecord::setWavFile() : created WAV file. \n"); - _debug("AudioRecord::setWavFile() : created WAV file. \n"); - return true; + return true; } bool AudioRecord::openExistingRawFile() -{ - fp = fopen(fileName_, "ab+"); - if ( !fp ) { - _debug("AudioRecord::openExistingRawFile() : could not create RAW file!\n"); - return false; - } +{ + fp = fopen (fileName_, "ab+"); + + if (!fp) { + _debug ("AudioRecord::openExistingRawFile() : could not create RAW file!\n"); + return false; + } } bool AudioRecord::openExistingWavFile() -{ - _debug("AudioRecord::openExistingWavFile() \n"); +{ + _debug ("AudioRecord::openExistingWavFile() \n"); - fp = fopen(fileName_, "rb+"); - if ( !fp ) { - _debug("AudioRecord::openExistingWavFile() : could not open WAV file rb+!\n"); - return false; - } + fp = fopen (fileName_, "rb+"); - printf("AudioRecord::openExistingWavFile()::Tried to open %s \n",fileName_); - - if(fseek(fp, 40, SEEK_SET) != 0) // jump to data length - _debug("AudioRecord::OpenExistingWavFile: 1.Couldn't seek offset 40 in the file \n"); - - if(fread(&byteCounter_, 4, 1, fp)) - _debug("AudioRecord::OpenExistingWavFile : bytecounter Read successfully \n"); - - if(fseek (fp, 0 , SEEK_END) != 0) - _debug("AudioRecors::OpenExistingWavFile : 2.Couldn't seek at the en of the file \n"); + if (!fp) { + _debug ("AudioRecord::openExistingWavFile() : could not open WAV file rb+!\n"); + return false; + } - printf("AudioRecord::OpenExistingWavFile : Byte counter after oppening : %d \n",(int)byteCounter_); + printf ("AudioRecord::openExistingWavFile()::Tried to open %s \n",fileName_); - if ( fclose( fp ) != 0) - _debug("AudioRecord::openExistingWavFile()::ERROR: can't close file r+ \n"); + if (fseek (fp, 40, SEEK_SET) != 0) // jump to data length + _debug ("AudioRecord::OpenExistingWavFile: 1.Couldn't seek offset 40 in the file \n"); + if (fread (&byteCounter_, 4, 1, fp)) + _debug ("AudioRecord::OpenExistingWavFile : bytecounter Read successfully \n"); - - fp = fopen(fileName_, "ab+"); - if ( !fp ) { - _debug("AudioRecord::openExistingWavFile() : could not createopen WAV file ab+!\n"); - return false; - } + if (fseek (fp, 0 , SEEK_END) != 0) + _debug ("AudioRecors::OpenExistingWavFile : 2.Couldn't seek at the en of the file \n"); + + printf ("AudioRecord::OpenExistingWavFile : Byte counter after oppening : %d \n", (int) byteCounter_); + + if (fclose (fp) != 0) + _debug ("AudioRecord::openExistingWavFile()::ERROR: can't close file r+ \n"); + + + + fp = fopen (fileName_, "ab+"); + + if (!fp) { + _debug ("AudioRecord::openExistingWavFile() : could not createopen WAV file ab+!\n"); + return false; + } + + if (fseek (fp, 4 , SEEK_END) != 0) + _debug ("AudioRecors::OpenExistingWavFile : 2.Couldn't seek at the en of the file \n"); - if(fseek (fp, 4 , SEEK_END) != 0) - _debug("AudioRecors::OpenExistingWavFile : 2.Couldn't seek at the en of the file \n"); - } -void AudioRecord::closeWavFile() +void AudioRecord::closeWavFile() { - if (fp == 0){ - _debug("AudioRecord:: Can't closeWavFile, a file has not yet been opened!\n"); - return; - } - - - SINT32 bytes = byteCounter_ * channels_; - - fseek(fp, 40, SEEK_SET); // jump to data length - if (ferror(fp))perror("AudioRecord::closeWavFile()::ERROR: can't reach offset 40\n"); - - fwrite(&bytes, sizeof(SINT32), 1, fp); - if (ferror(fp))perror("AudioRecord::closeWavFile()::ERROR: can't write bytes for data length \n"); - printf("AudioRecord::closeWavFile : data bytes: %i \n",(int)bytes); - - bytes = byteCounter_ * channels_ + 44; // + 44 for the wave header - fseek(fp, 4, SEEK_SET); // jump to file size - if (ferror(fp))perror("AudioRecord::closeWavFile()::ERROR: can't reach offset 4\n"); - - fwrite(&bytes, 4, 1, fp); - if (ferror(fp))perror("AudioRecord::closeWavFile()::ERROR: can't reach offset 4\n"); - - printf("AudioRecord::closeWavFile : bytes : %i \n",(int)bytes); - - if ( fclose( fp ) != 0) - _debug("AudioRecord::closeWavFile()::ERROR: can't close file\n"); - + if (fp == 0) { + _debug ("AudioRecord:: Can't closeWavFile, a file has not yet been opened!\n"); + return; + } -} -void AudioRecord::recSpkrData(SFLDataFormat* buffer, int nSamples) { + SINT32 bytes = byteCounter_ * channels_; - if (recordingEnabled_) { - - nbSamplesMic_ = nSamples; + fseek (fp, 40, SEEK_SET); // jump to data length - for(int i = 0; i < nbSamplesMic_; i++) - micBuffer_[i] = buffer[i]; - } + if (ferror (fp)) perror ("AudioRecord::closeWavFile()::ERROR: can't reach offset 40\n"); - return; -} + fwrite (&bytes, sizeof (SINT32), 1, fp); + + if (ferror (fp)) perror ("AudioRecord::closeWavFile()::ERROR: can't write bytes for data length \n"); + + printf ("AudioRecord::closeWavFile : data bytes: %i \n", (int) bytes); + + bytes = byteCounter_ * channels_ + 44; // + 44 for the wave header + + fseek (fp, 4, SEEK_SET); // jump to file size + if (ferror (fp)) perror ("AudioRecord::closeWavFile()::ERROR: can't reach offset 4\n"); -void AudioRecord::recMicData(SFLDataFormat* buffer, int nSamples) { + fwrite (&bytes, 4, 1, fp); - if (recordingEnabled_) { + if (ferror (fp)) perror ("AudioRecord::closeWavFile()::ERROR: can't reach offset 4\n"); - nbSamplesSpk_ = nSamples; + printf ("AudioRecord::closeWavFile : bytes : %i \n", (int) bytes); - for(int i = 0; i < nbSamplesSpk_; i++) - spkBuffer_[i] = buffer[i]; + if (fclose (fp) != 0) + _debug ("AudioRecord::closeWavFile()::ERROR: can't close file\n"); - } - return; } +void AudioRecord::recSpkrData (SFLDataFormat* buffer, int nSamples) +{ -void AudioRecord::recData(SFLDataFormat* buffer, int nSamples) { + if (recordingEnabled_) { - if (recordingEnabled_) { + nbSamplesMic_ = nSamples; - if (fp == 0){ - _debug("AudioRecord: Can't record data, a file has not yet been opened!\n"); - return; + for (int i = 0; i < nbSamplesMic_; i++) + micBuffer_[i] = buffer[i]; } - - - - if ( sndFormat_ == INT16 ) { // TODO change INT16 to SINT16 - if ( fwrite(buffer, sizeof(SFLDataFormat), nSamples, fp) != nSamples) - _debug("AudioRecord: Could not record data! \n"); - else { - fflush(fp); - byteCounter_ += (unsigned long)(nSamples*sizeof(SFLDataFormat)); - } - } - } - - return; + + return; } -void AudioRecord::recData(SFLDataFormat* buffer_1, SFLDataFormat* buffer_2, int nSamples_1, int nSamples_2) { +void AudioRecord::recMicData (SFLDataFormat* buffer, int nSamples) +{ + + if (recordingEnabled_) { + + nbSamplesSpk_ = nSamples; - if (recordingEnabled_) { + for (int i = 0; i < nbSamplesSpk_; i++) + spkBuffer_[i] = buffer[i]; - if (fp == 0){ - _debug("AudioRecord: Can't record data, a file has not yet been opened!\n"); - return; } + return; +} + + +void AudioRecord::recData (SFLDataFormat* buffer, int nSamples) +{ + + if (recordingEnabled_) { - if ( sndFormat_ == INT16 ) { // TODO change INT16 to SINT16 - for (int k=0; k<nSamples_1; k++){ - - mixBuffer_[k] = (buffer_1[k]+buffer_2[k]); - - - if ( fwrite(&mixBuffer_[k], 2, 1, fp) != 1) - _debug("AudioRecord: Could not record data!\n"); - else { - fflush(fp); + if (fp == 0) { + _debug ("AudioRecord: Can't record data, a file has not yet been opened!\n"); + return; + } + + + + if (sndFormat_ == INT16) { // TODO change INT16 to SINT16 + if (fwrite (buffer, sizeof (SFLDataFormat), nSamples, fp) != nSamples) + _debug ("AudioRecord: Could not record data! \n"); + else { + fflush (fp); + byteCounter_ += (unsigned long) (nSamples*sizeof (SFLDataFormat)); + } } - } } - - byteCounter_ += (unsigned long)(nSamples_1*sizeof(SFLDataFormat)); - } + return; +} + + +void AudioRecord::recData (SFLDataFormat* buffer_1, SFLDataFormat* buffer_2, int nSamples_1, int nSamples_2) +{ + + if (recordingEnabled_) { + + if (fp == 0) { + _debug ("AudioRecord: Can't record data, a file has not yet been opened!\n"); + return; + } + - return; + if (sndFormat_ == INT16) { // TODO change INT16 to SINT16 + for (int k=0; k<nSamples_1; k++) { + + mixBuffer_[k] = (buffer_1[k]+buffer_2[k]); + + + if (fwrite (&mixBuffer_[k], 2, 1, fp) != 1) + _debug ("AudioRecord: Could not record data!\n"); + else { + fflush (fp); + } + } + } + + byteCounter_ += (unsigned long) (nSamples_1*sizeof (SFLDataFormat)); + + } + + return; } diff --git a/sflphone-common/src/plug-in/librarymanager.cpp b/sflphone-common/src/plug-in/librarymanager.cpp index 138b59f5f4..0c8c1040bd 100644 --- a/sflphone-common/src/plug-in/librarymanager.cpp +++ b/sflphone-common/src/plug-in/librarymanager.cpp @@ -19,9 +19,9 @@ #include "librarymanager.h" - - LibraryManager::LibraryManager (const std::string &filename) - : _filename(filename), _handlePtr(NULL) + +LibraryManager::LibraryManager (const std::string &filename) + : _filename (filename), _handlePtr (NULL) { _handlePtr = loadLibrary (filename); } @@ -36,16 +36,19 @@ LibraryManager::LibraryHandle LibraryManager::loadLibrary (const std::string &fi LibraryHandle pluginHandlePtr = NULL; const char *error; - _debug("Loading dynamic library %s\n", filename.c_str()); + _debug ("Loading dynamic library %s\n", filename.c_str()); /* Load the library */ - pluginHandlePtr = dlopen( filename.c_str(), RTLD_LAZY ); - if( !pluginHandlePtr ) { + pluginHandlePtr = dlopen (filename.c_str(), RTLD_LAZY); + + if (!pluginHandlePtr) { error = dlerror(); - _debug("Error while opening plug-in: %s\n", error); + _debug ("Error while opening plug-in: %s\n", error); return NULL; } + dlerror(); + return pluginHandlePtr; } @@ -54,13 +57,15 @@ int LibraryManager::unloadLibrary () if (_handlePtr == NULL) return 1; - _debug("Unloading dynamic library ...\n"); - dlclose( _handlePtr ); - if (dlerror()) - { - _debug("Error unloading the library : %s\n...", dlerror()); + _debug ("Unloading dynamic library ...\n"); + + dlclose (_handlePtr); + + if (dlerror()) { + _debug ("Error unloading the library : %s\n...", dlerror()); return 1; } + return 0; } @@ -68,19 +73,18 @@ int LibraryManager::resolveSymbol (const std::string &symbol, SymbolHandle *symb { SymbolHandle sy = 0; - if (_handlePtr){ + if (_handlePtr) { try { - sy = dlsym(_handlePtr, symbol.c_str()); - if(sy != NULL) { + sy = dlsym (_handlePtr, symbol.c_str()); + + if (sy != NULL) { *symbolPtr = sy; return 0; } - } - catch (...) {} - - throw LibraryManagerException ( _filename, symbol, LibraryManagerException::symbolNotFound); - } - else + } catch (...) {} + + throw LibraryManagerException (_filename, symbol, LibraryManagerException::symbolNotFound); + } else return 1; } @@ -88,8 +92,8 @@ int LibraryManager::resolveSymbol (const std::string &symbol, SymbolHandle *symb /************************************************************************************************/ LibraryManagerException::LibraryManagerException (const std::string &libraryName, const std::string &details, Reason reason) : - _reason (reason), _details (""), std::runtime_error ("") - + _reason (reason), _details (""), std::runtime_error ("") + { if (_reason == loadingFailed) _details = "Error when loading " + libraryName + "\n" + details; diff --git a/sflphone-common/src/plug-in/pluginmanager.cpp b/sflphone-common/src/plug-in/pluginmanager.cpp index 9ecf6d9949..80197f6cce 100644 --- a/sflphone-common/src/plug-in/pluginmanager.cpp +++ b/sflphone-common/src/plug-in/pluginmanager.cpp @@ -24,17 +24,18 @@ PluginManager* PluginManager::_instance = 0; - PluginManager* +PluginManager* PluginManager::instance() { - if(!_instance){ + if (!_instance) { return new PluginManager(); } + return _instance; } PluginManager::PluginManager() -:_loadedPlugins() + :_loadedPlugins() { _instance = this; } @@ -44,7 +45,7 @@ PluginManager::~PluginManager() _instance = 0; } - int +int PluginManager::loadPlugins (const std::string &path) { std::string pluginDir, current; @@ -57,91 +58,92 @@ PluginManager::loadPlugins (const std::string &path) const std::string cDir = "."; /* The directory in which plugins are dropped. Default: /usr/lib/sflphone/plugins/ */ - ( path == "" )? pluginDir = std::string(PLUGINS_DIR).append("/"):pluginDir = path; - _debug("Loading plugins from %s...\n", pluginDir.c_str()); + (path == "") ? pluginDir = std::string (PLUGINS_DIR).append ("/") :pluginDir = path; + _debug ("Loading plugins from %s...\n", pluginDir.c_str()); - dir = opendir( pluginDir.c_str() ); + dir = opendir (pluginDir.c_str()); /* Test if the directory exists or is readable */ - if( dir ){ + + if (dir) { /* Read the directory */ - while( (dirStruct=readdir(dir)) ){ + while ( (dirStruct=readdir (dir))) { /* Get the name of the current item in the directory */ current = dirStruct->d_name; /* Test if the current item is not the parent or the current directory */ - if( current != pDir && current != cDir ){ + + if (current != pDir && current != cDir) { /* Load the dynamic library */ - library = loadDynamicLibrary( pluginDir + current ); + library = loadDynamicLibrary (pluginDir + current); /* Instanciate the plugin object */ - if(instanciatePlugin (library, &plugin) != 0) - { - _debug("Error instanciating the plugin ...\n"); + + if (instanciatePlugin (library, &plugin) != 0) { + _debug ("Error instanciating the plugin ...\n"); return 1; } /* Regitering the current plugin */ - if(registerPlugin (plugin, library) != 0) - { - _debug("Error registering the plugin ...\n"); + if (registerPlugin (plugin, library) != 0) { + _debug ("Error registering the plugin ...\n"); return 1; } } } - } - else + } else return 1; /* Close the directory */ - closedir( dir ); + closedir (dir); return 0; } -int +int PluginManager::unloadPlugins (void) { PluginInfo *info; - if(_loadedPlugins.empty()) return 0; + if (_loadedPlugins.empty()) return 0; /* Use an iterator on the loaded plugins map */ pluginMap::iterator iter; iter = _loadedPlugins.begin(); - while( iter != _loadedPlugins.end() ) { + + while (iter != _loadedPlugins.end()) { info = iter->second; - - if (deletePlugin (info) != 0) - { - _debug("Error deleting the plugin ... \n"); + + if (deletePlugin (info) != 0) { + _debug ("Error deleting the plugin ... \n"); return 1; } - + unloadDynamicLibrary (info->_libraryPtr); - - if (unregisterPlugin (info) != 0) - { - _debug("Error unregistering the plugin ... \n"); + + if (unregisterPlugin (info) != 0) { + _debug ("Error unregistering the plugin ... \n"); return 1; } iter++; } + return 0; } - bool +bool PluginManager::isPluginLoaded (const std::string &name) { - if(_loadedPlugins.empty()) return false; + if (_loadedPlugins.empty()) return false; /* Use an iterator on the loaded plugins map */ pluginMap::iterator iter; + iter = _loadedPlugins.find (name); /* Returns map::end if the specified key has not been found */ - if(iter==_loadedPlugins.end()) + if (iter==_loadedPlugins.end()) return false; /* Returns the plugin pointer */ @@ -149,22 +151,22 @@ PluginManager::isPluginLoaded (const std::string &name) } - LibraryManager* -PluginManager::loadDynamicLibrary (const std::string& filename) +LibraryManager* +PluginManager::loadDynamicLibrary (const std::string& filename) { /* Load the library through the library manager */ return new LibraryManager (filename); } - int -PluginManager::unloadDynamicLibrary (LibraryManager *libraryPtr) +int +PluginManager::unloadDynamicLibrary (LibraryManager *libraryPtr) { - _debug("Unloading dynamic library ...\n"); + _debug ("Unloading dynamic library ...\n"); /* Close it */ return libraryPtr->unloadLibrary (); } - int +int PluginManager::instanciatePlugin (LibraryManager *libraryPtr, Plugin **plugin) { createFunc *createPlugin; @@ -172,12 +174,15 @@ PluginManager::instanciatePlugin (LibraryManager *libraryPtr, Plugin **plugin) if (libraryPtr->resolveSymbol ("createPlugin", &symbol) != 0) return 1; - createPlugin = (createFunc*)symbol; + + createPlugin = (createFunc*) symbol; + *plugin = createPlugin(); + return 0; } - int +int PluginManager::deletePlugin (PluginInfo *plugin) { destroyFunc *destroyPlugin; @@ -185,24 +190,29 @@ PluginManager::deletePlugin (PluginInfo *plugin) if (plugin->_libraryPtr->resolveSymbol ("destroyPlugin", &symbol) != 0) return 1; - destroyPlugin = (destroyFunc*)symbol; + + destroyPlugin = (destroyFunc*) symbol; + /* Call it */ destroyPlugin (plugin->_plugin); + return 0; } - int +int PluginManager::registerPlugin (Plugin *plugin, LibraryManager *library) { std::string key; PluginInfo *p_info; - if( plugin==0 ) + if (plugin==0) return 1; - + p_info = new PluginInfo(); + /* Retrieve information from the plugin */ plugin->initFunc (&p_info); + key = p_info->_name; //p_info->_plugin = plugin; @@ -210,10 +220,11 @@ PluginManager::registerPlugin (Plugin *plugin, LibraryManager *library) /* Add the data in the loaded plugin map */ _loadedPlugins[ key ] = p_info; + return 0; } -int +int PluginManager::unregisterPlugin (PluginInfo *plugin) { pluginMap::iterator iter; @@ -221,10 +232,11 @@ PluginManager::unregisterPlugin (PluginInfo *plugin) key = plugin->_name; - if (!isPluginLoaded(key)) + if (!isPluginLoaded (key)) return 1; iter = _loadedPlugins.find (key); + _loadedPlugins.erase (iter); return 0; diff --git a/sflphone-common/src/plug-in/test/pluginTest.cpp b/sflphone-common/src/plug-in/test/pluginTest.cpp index cbd1b1d760..9bef60f3a4 100644 --- a/sflphone-common/src/plug-in/test/pluginTest.cpp +++ b/sflphone-common/src/plug-in/test/pluginTest.cpp @@ -22,12 +22,13 @@ #define MAJOR_VERSION 1 #define MINOR_VERSION 0 -class PluginTest : public Plugin { +class PluginTest : public Plugin +{ public: - PluginTest( const std::string &name ) - :Plugin( name ) { - } + PluginTest (const std::string &name) + :Plugin (name) { + } virtual int initFunc (PluginInfo **info) { @@ -40,10 +41,12 @@ class PluginTest : public Plugin { } }; -extern "C" Plugin* createPlugin (void){ - return new PluginTest("mytest"); +extern "C" Plugin* createPlugin (void) +{ + return new PluginTest ("mytest"); } -extern "C" void destroyPlugin (Plugin *p){ +extern "C" void destroyPlugin (Plugin *p) +{ delete p; } diff --git a/sflphone-common/src/samplerateconverter.cpp b/sflphone-common/src/samplerateconverter.cpp index e1990f930e..ccdb09da23 100644 --- a/sflphone-common/src/samplerateconverter.cpp +++ b/sflphone-common/src/samplerateconverter.cpp @@ -1,7 +1,7 @@ /* * Copyright (C) 2008 Savoir-Faire Linux inc. * Author: Emmanuel Milou <emmanuel.milou@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,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. @@ -18,114 +18,124 @@ #include "samplerateconverter.h" -SamplerateConverter::SamplerateConverter( void ) - : _frequence(Manager::instance().getConfigInt( AUDIO , ALSA_SAMPLE_RATE )) //44100 - , _framesize(Manager::instance().getConfigInt( AUDIO , ALSA_FRAME_SIZE )) - , _floatBufferDownMic(NULL) - , _floatBufferUpMic(NULL) - , _src_state_mic(NULL) - , _floatBufferDownSpkr(NULL) - , _floatBufferUpSpkr(NULL) - , _src_state_spkr(NULL) - , _src_err(0) +SamplerateConverter::SamplerateConverter (void) + : _frequence (Manager::instance().getConfigInt (AUDIO , ALSA_SAMPLE_RATE)) //44100 + , _framesize (Manager::instance().getConfigInt (AUDIO , ALSA_FRAME_SIZE)) + , _floatBufferDownMic (NULL) + , _floatBufferUpMic (NULL) + , _src_state_mic (NULL) + , _floatBufferDownSpkr (NULL) + , _floatBufferUpSpkr (NULL) + , _src_state_spkr (NULL) + , _src_err (0) { - init(); + init(); } -SamplerateConverter::SamplerateConverter( int freq , int fs ) - : _frequence(freq) - , _framesize(fs) - , _floatBufferDownMic(NULL) - , _floatBufferUpMic(NULL) - , _src_state_mic(NULL) - , _floatBufferDownSpkr(NULL) - , _floatBufferUpSpkr(NULL) - , _src_state_spkr(NULL) - , _src_err(0) -{ - init(); +SamplerateConverter::SamplerateConverter (int freq , int fs) + : _frequence (freq) + , _framesize (fs) + , _floatBufferDownMic (NULL) + , _floatBufferUpMic (NULL) + , _src_state_mic (NULL) + , _floatBufferDownSpkr (NULL) + , _floatBufferUpSpkr (NULL) + , _src_state_spkr (NULL) + , _src_err (0) +{ + init(); } -SamplerateConverter::~SamplerateConverter( void ) { +SamplerateConverter::~SamplerateConverter (void) +{ - delete [] _floatBufferUpMic; _floatBufferUpMic = NULL; - delete [] _floatBufferDownMic; _floatBufferDownMic = NULL; + delete [] _floatBufferUpMic; + _floatBufferUpMic = NULL; + delete [] _floatBufferDownMic; + _floatBufferDownMic = NULL; - delete [] _floatBufferUpSpkr; _floatBufferUpSpkr = NULL; - delete [] _floatBufferDownSpkr; _floatBufferDownSpkr = NULL; + delete [] _floatBufferUpSpkr; + _floatBufferUpSpkr = NULL; + delete [] _floatBufferDownSpkr; + _floatBufferDownSpkr = NULL; - // libSamplerateConverter-related - _src_state_mic = src_delete(_src_state_mic); - _src_state_spkr = src_delete(_src_state_spkr); + // libSamplerateConverter-related + _src_state_mic = src_delete (_src_state_mic); + _src_state_spkr = src_delete (_src_state_spkr); } -void SamplerateConverter::init( void ) { - - // libSamplerateConverter-related - // Set the converter type for the upsampling and the downsampling - // interpolator SRC_SINC_BEST_QUALITY - // interpolator SRC_SINC_FASTEST - // interpolator SRC_LINEAR - _src_state_mic = src_new(SRC_SINC_FASTEST, 1, &_src_err); - _src_state_spkr = src_new(SRC_SINC_FASTEST, 1, &_src_err); - - int nbSamplesMax = (int) ( getFrequence() * getFramesize() / 1000 ); - _floatBufferDownMic = new float32[nbSamplesMax]; - _floatBufferUpMic = new float32[nbSamplesMax]; - _floatBufferDownSpkr = new float32[nbSamplesMax]; - _floatBufferUpSpkr = new float32[nbSamplesMax]; +void SamplerateConverter::init (void) +{ + + // libSamplerateConverter-related + // Set the converter type for the upsampling and the downsampling + // interpolator SRC_SINC_BEST_QUALITY + // interpolator SRC_SINC_FASTEST + // interpolator SRC_LINEAR + _src_state_mic = src_new (SRC_SINC_FASTEST, 1, &_src_err); + _src_state_spkr = src_new (SRC_SINC_FASTEST, 1, &_src_err); + + int nbSamplesMax = (int) (getFrequence() * getFramesize() / 1000); + _floatBufferDownMic = new float32[nbSamplesMax]; + _floatBufferUpMic = new float32[nbSamplesMax]; + _floatBufferDownSpkr = new float32[nbSamplesMax]; + _floatBufferUpSpkr = new float32[nbSamplesMax]; } //TODO Add ifdef for int16 or float32 type -int SamplerateConverter::upsampleData( SFLDataFormat* dataIn , SFLDataFormat* dataOut, int samplerate1 , int samplerate2 , int nbSamples ){ - - double upsampleFactor = (double)samplerate2 / samplerate1 ; - //_debug("factor = %f\n" , upsampleFactor); - int nbSamplesMax = (int) ( samplerate2 * getFramesize() / 1000 ); - if( upsampleFactor != 1 && dataIn != NULL ) - { - SRC_DATA src_data; - src_data.data_in = _floatBufferDownSpkr; - src_data.data_out = _floatBufferUpSpkr; - src_data.input_frames = nbSamples; - src_data.output_frames = (int) floor(upsampleFactor * nbSamples); - src_data.src_ratio = upsampleFactor; - src_data.end_of_input = 0; // More data will come - //_debug("upsample %d %d %f %d\n" , src_data.input_frames , src_data.output_frames, src_data.src_ratio , nbSamples); - src_short_to_float_array( dataIn , _floatBufferDownSpkr, nbSamples); - //_debug("upsample %d %f %d\n" , src_data.output_frames, src_data.src_ratio , nbSamples); - src_process(_src_state_spkr, &src_data); - //_debug("upsample %d %d %d\n" , samplerate1, samplerate2 , nbSamples); - nbSamples = ( src_data.output_frames_gen > nbSamplesMax) ? nbSamplesMax : src_data.output_frames_gen; - src_float_to_short_array(_floatBufferUpSpkr, dataOut, nbSamples); - //_debug("upsample %d %d %d\n" , samplerate1, samplerate2 , nbSamples); - } - return nbSamples; +int SamplerateConverter::upsampleData (SFLDataFormat* dataIn , SFLDataFormat* dataOut, int samplerate1 , int samplerate2 , int nbSamples) +{ + + double upsampleFactor = (double) samplerate2 / samplerate1 ; + //_debug("factor = %f\n" , upsampleFactor); + int nbSamplesMax = (int) (samplerate2 * getFramesize() / 1000); + + if (upsampleFactor != 1 && dataIn != NULL) { + SRC_DATA src_data; + src_data.data_in = _floatBufferDownSpkr; + src_data.data_out = _floatBufferUpSpkr; + src_data.input_frames = nbSamples; + src_data.output_frames = (int) floor (upsampleFactor * nbSamples); + src_data.src_ratio = upsampleFactor; + src_data.end_of_input = 0; // More data will come + //_debug("upsample %d %d %f %d\n" , src_data.input_frames , src_data.output_frames, src_data.src_ratio , nbSamples); + src_short_to_float_array (dataIn , _floatBufferDownSpkr, nbSamples); + //_debug("upsample %d %f %d\n" , src_data.output_frames, src_data.src_ratio , nbSamples); + src_process (_src_state_spkr, &src_data); + //_debug("upsample %d %d %d\n" , samplerate1, samplerate2 , nbSamples); + nbSamples = (src_data.output_frames_gen > nbSamplesMax) ? nbSamplesMax : src_data.output_frames_gen; + src_float_to_short_array (_floatBufferUpSpkr, dataOut, nbSamples); + //_debug("upsample %d %d %d\n" , samplerate1, samplerate2 , nbSamples); + } + + return nbSamples; } //TODO Add ifdef for int16 or float32 type -int SamplerateConverter::downsampleData( SFLDataFormat* dataIn , SFLDataFormat* dataOut , int samplerate1 , int samplerate2 , int nbSamples ){ - - double downsampleFactor = (double)samplerate1 / samplerate2; - //_debug("factor = %f\n" , downsampleFactor); - int nbSamplesMax = (int) ( samplerate1 * getFramesize() / 1000 ); - if ( downsampleFactor != 1 ) - { - SRC_DATA src_data; - src_data.data_in = _floatBufferUpMic; - src_data.data_out = _floatBufferDownMic; - src_data.input_frames = nbSamples; - src_data.output_frames = (int) floor(downsampleFactor * nbSamples); - src_data.src_ratio = downsampleFactor; - src_data.end_of_input = 0; // More data will come - //_debug("downsample %d %f %d\n" , src_data.output_frames, src_data.src_ratio , nbSamples); - src_short_to_float_array( dataIn, _floatBufferUpMic, nbSamples ); - //_debug("downsample %d %f %d\n" , src_data.output_frames, src_data.src_ratio , nbSamples); - src_process(_src_state_mic, &src_data); - //_debug("downsample %d %f %d\n" , src_data.output_frames, src_data.src_ratio , nbSamples); - nbSamples = ( src_data.output_frames_gen > nbSamplesMax) ? nbSamplesMax : src_data.output_frames_gen; - //_debug("downsample %d %f %d\n" , src_data.output_frames, src_data.src_ratio , nbSamples); - src_float_to_short_array( _floatBufferDownMic , dataOut , nbSamples ); - } - return nbSamples; +int SamplerateConverter::downsampleData (SFLDataFormat* dataIn , SFLDataFormat* dataOut , int samplerate1 , int samplerate2 , int nbSamples) +{ + + double downsampleFactor = (double) samplerate1 / samplerate2; + //_debug("factor = %f\n" , downsampleFactor); + int nbSamplesMax = (int) (samplerate1 * getFramesize() / 1000); + + if (downsampleFactor != 1) { + SRC_DATA src_data; + src_data.data_in = _floatBufferUpMic; + src_data.data_out = _floatBufferDownMic; + src_data.input_frames = nbSamples; + src_data.output_frames = (int) floor (downsampleFactor * nbSamples); + src_data.src_ratio = downsampleFactor; + src_data.end_of_input = 0; // More data will come + //_debug("downsample %d %f %d\n" , src_data.output_frames, src_data.src_ratio , nbSamples); + src_short_to_float_array (dataIn, _floatBufferUpMic, nbSamples); + //_debug("downsample %d %f %d\n" , src_data.output_frames, src_data.src_ratio , nbSamples); + src_process (_src_state_mic, &src_data); + //_debug("downsample %d %f %d\n" , src_data.output_frames, src_data.src_ratio , nbSamples); + nbSamples = (src_data.output_frames_gen > nbSamplesMax) ? nbSamplesMax : src_data.output_frames_gen; + //_debug("downsample %d %f %d\n" , src_data.output_frames, src_data.src_ratio , nbSamples); + src_float_to_short_array (_floatBufferDownMic , dataOut , nbSamples); + } + + return nbSamples; } diff --git a/sflphone-common/src/sdp.cpp b/sflphone-common/src/sdp.cpp index 1995c293aa..1a4005d4c7 100644 --- a/sflphone-common/src/sdp.cpp +++ b/sflphone-common/src/sdp.cpp @@ -23,24 +23,25 @@ #include "manager.h" -static const pj_str_t STR_AUDIO = { (char*)"audio", 5}; -static const pj_str_t STR_VIDEO = { (char*)"video", 5}; -static const pj_str_t STR_IN = { (char*)"IN", 2 }; -static const pj_str_t STR_IP4 = { (char*)"IP4", 3}; -static const pj_str_t STR_IP6 = { (char*)"IP6", 3}; -static const pj_str_t STR_RTP_AVP = { (char*)"RTP/AVP", 7 }; -static const pj_str_t STR_SDP_NAME = { (char*)"sflphone", 8 }; -static const pj_str_t STR_SENDRECV = { (char*)"sendrecv", 8 }; -static const pj_str_t STR_RTPMAP = { (char*)"rtpmap", 6 }; - - -Sdp::Sdp( pj_pool_t *pool ) - : _local_media_cap(), _session_media(0), _ip_addr( "" ), _local_offer( NULL ), _negociated_offer(NULL), _negociator(NULL), _pool(NULL), _local_extern_audio_port(0) +static const pj_str_t STR_AUDIO = { (char*) "audio", 5}; +static const pj_str_t STR_VIDEO = { (char*) "video", 5}; +static const pj_str_t STR_IN = { (char*) "IN", 2 }; +static const pj_str_t STR_IP4 = { (char*) "IP4", 3}; +static const pj_str_t STR_IP6 = { (char*) "IP6", 3}; +static const pj_str_t STR_RTP_AVP = { (char*) "RTP/AVP", 7 }; +static const pj_str_t STR_SDP_NAME = { (char*) "sflphone", 8 }; +static const pj_str_t STR_SENDRECV = { (char*) "sendrecv", 8 }; +static const pj_str_t STR_RTPMAP = { (char*) "rtpmap", 6 }; + + +Sdp::Sdp (pj_pool_t *pool) + : _local_media_cap(), _session_media (0), _ip_addr (""), _local_offer (NULL), _negociated_offer (NULL), _negociator (NULL), _pool (NULL), _local_extern_audio_port (0) { _pool = pool; } -Sdp::~Sdp() { +Sdp::~Sdp() +{ //unsigned int k; @@ -51,12 +52,13 @@ Sdp::~Sdp() { }*/ //for( k=0; k<_local_media_cap.size(); k++ ){ - // delete _local_media_cap[k]; - //_local_media_cap[k] = 0; + // delete _local_media_cap[k]; + //_local_media_cap[k] = 0; //} } -void Sdp::set_media_descriptor_line( sdpMedia *media, pjmedia_sdp_media** p_med ) { +void Sdp::set_media_descriptor_line (sdpMedia *media, pjmedia_sdp_media** p_med) +{ pjmedia_sdp_media* med; pjmedia_sdp_rtpmap rtpmap; @@ -65,11 +67,11 @@ void Sdp::set_media_descriptor_line( sdpMedia *media, pjmedia_sdp_media** p_med int count, i; std::string tmp; - med = PJ_POOL_ZALLOC_T( _pool, pjmedia_sdp_media ); + med = PJ_POOL_ZALLOC_T (_pool, pjmedia_sdp_media); // Get the right media format - pj_strdup(_pool, &med->desc.media, - ( media->get_media_type() == MIME_TYPE_AUDIO ) ? &STR_AUDIO : &STR_VIDEO ); + pj_strdup (_pool, &med->desc.media, + (media->get_media_type() == MIME_TYPE_AUDIO) ? &STR_AUDIO : &STR_VIDEO); med->desc.port_count = 1; med->desc.port = media->get_port(); pj_strdup (_pool, &med->desc.transport, &STR_RTP_AVP); @@ -79,37 +81,44 @@ void Sdp::set_media_descriptor_line( sdpMedia *media, pjmedia_sdp_media** p_med med->desc.fmt_count = count; // add the payload list - for(i=0; i<count; i++){ - codec = media->get_media_codec_list()[i]; - tmp = this->convert_int_to_string (codec->getPayload ()); + + for (i=0; i<count; i++) { + codec = media->get_media_codec_list() [i]; + tmp = this->convert_int_to_string (codec->getPayload ()); _debug ("%s\n", tmp.c_str()); - pj_strdup2( _pool, &med->desc.fmt[i], tmp.c_str()); + pj_strdup2 (_pool, &med->desc.fmt[i], tmp.c_str()); // Add a rtpmap field for each codec // We could add one only for dynamic payloads because the codecs with static RTP payloads // are entirely defined in the RFC 3351, but if we want to add other attributes like an asymmetric // connection, the rtpmap attribute will be useful to specify for which codec it is applicable rtpmap.pt = med->desc.fmt[i]; - rtpmap.enc_name = pj_str( (char*) codec->getCodecName().c_str() ); + rtpmap.enc_name = pj_str ( (char*) codec->getCodecName().c_str()); rtpmap.clock_rate = codec->getClockRate(); // Add the channel number only if different from 1 - if( codec->getChannel() > 1 ) - rtpmap.param = pj_str( (char*) codec->getChannel() ); + + if (codec->getChannel() > 1) + rtpmap.param = pj_str ( (char*) codec->getChannel()); else rtpmap.param.slen = 0; - pjmedia_sdp_rtpmap_to_attr( _pool, &rtpmap, &attr ); + + pjmedia_sdp_rtpmap_to_attr (_pool, &rtpmap, &attr); + med->attr[med->attr_count++] = attr; } // 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()); + 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; *p_med = med; } -int Sdp::create_local_offer (){ +int Sdp::create_local_offer () +{ pj_status_t status; _debug ("Create local offer\n"); @@ -119,8 +128,8 @@ int Sdp::create_local_offer (){ // Reference: RFC 4566 [5] /* Create and initialize basic SDP session */ - this->_local_offer = PJ_POOL_ZALLOC_T(_pool, pjmedia_sdp_session); - this->_local_offer->conn = PJ_POOL_ZALLOC_T(_pool, pjmedia_sdp_conn); + this->_local_offer = PJ_POOL_ZALLOC_T (_pool, pjmedia_sdp_session); + this->_local_offer->conn = PJ_POOL_ZALLOC_T (_pool, pjmedia_sdp_conn); /* Initialize the fields of the struct */ sdp_add_protocol(); @@ -129,39 +138,44 @@ int Sdp::create_local_offer (){ sdp_add_connection_info(); sdp_add_timing(); //sdp_addAttributes( _pool ); - sdp_add_media_description( ); + sdp_add_media_description(); //toString (); // Validate the sdp session - status = pjmedia_sdp_validate( this->_local_offer ); + status = pjmedia_sdp_validate (this->_local_offer); + if (status != PJ_SUCCESS) return status; return PJ_SUCCESS; } -int Sdp::create_initial_offer( ){ +int Sdp::create_initial_offer() +{ pj_status_t status; pjmedia_sdp_neg_state state; _debug ("Create initial offer\n"); // Build the SDP session descriptor - status = create_local_offer( ); + status = create_local_offer(); + if (status != PJ_SUCCESS) { - return status; + return status; } // Create the SDP negociator instance with local offer - status = pjmedia_sdp_neg_create_w_local_offer( _pool, get_local_sdp_session(), &_negociator); - state = pjmedia_sdp_neg_get_state( _negociator ); + status = pjmedia_sdp_neg_create_w_local_offer (_pool, get_local_sdp_session(), &_negociator); - PJ_ASSERT_RETURN( status == PJ_SUCCESS, 1 ); + state = pjmedia_sdp_neg_get_state (_negociator); + + PJ_ASSERT_RETURN (status == PJ_SUCCESS, 1); return PJ_SUCCESS; } -int Sdp::receiving_initial_offer( pjmedia_sdp_session* remote ){ +int Sdp::receiving_initial_offer (pjmedia_sdp_session* remote) +{ // Create the SDP negociator instance by calling // pjmedia_sdp_neg_create_w_remote_offer with the remote offer, and by providing the local offer ( optional ) @@ -174,31 +188,36 @@ int Sdp::receiving_initial_offer( pjmedia_sdp_session* remote ){ // pjmedia_sdp_neg_create_w_remote_offer with the remote offer, and by providing the local offer ( optional ) // Build the local offer to respond - status = create_local_offer( ); + status = create_local_offer(); + if (status != PJ_SUCCESS) { - return status; + return status; } // Retrieve some useful remote information this->fetch_media_transport_info_from_remote_sdp (remote); - status = pjmedia_sdp_neg_create_w_remote_offer( _pool, - get_local_sdp_session(), remote, &_negociator ); - state = pjmedia_sdp_neg_get_state( _negociator ); - PJ_ASSERT_RETURN( status == PJ_SUCCESS, 1 ); + status = pjmedia_sdp_neg_create_w_remote_offer (_pool, + get_local_sdp_session(), remote, &_negociator); + + state = pjmedia_sdp_neg_get_state (_negociator); + + PJ_ASSERT_RETURN (status == PJ_SUCCESS, 1); return PJ_SUCCESS; } -void Sdp::sdp_add_protocol( void ){ +void Sdp::sdp_add_protocol (void) +{ this->_local_offer->origin.version = 0; } -void Sdp::sdp_add_origin( void ){ +void Sdp::sdp_add_origin (void) +{ pj_time_val tv; - pj_gettimeofday(&tv); + pj_gettimeofday (&tv); - this->_local_offer->origin.user = pj_str(pj_gethostname()->ptr); + this->_local_offer->origin.user = pj_str (pj_gethostname()->ptr); // Use Network Time Protocol format timestamp to ensure uniqueness. this->_local_offer->origin.id = tv.sec + 2208988800UL; // The type of network ( IN for INternet ) @@ -206,22 +225,25 @@ void Sdp::sdp_add_origin( void ){ // The type of address this->_local_offer->origin.addr_type = STR_IP4; // The address of the machine from which the session was created - this->_local_offer->origin.addr = pj_str( (char*)_ip_addr.c_str() ); + this->_local_offer->origin.addr = pj_str ( (char*) _ip_addr.c_str()); } -void Sdp::sdp_add_session_name( void ){ +void Sdp::sdp_add_session_name (void) +{ this->_local_offer->name = STR_SDP_NAME; } -void Sdp::sdp_add_connection_info( void ){ +void Sdp::sdp_add_connection_info (void) +{ this->_local_offer->conn->net_type = _local_offer->origin.net_type; this->_local_offer->conn->addr_type = _local_offer->origin.addr_type; this->_local_offer->conn->addr = _local_offer->origin.addr; } -void Sdp::sdp_add_timing( void ){ +void Sdp::sdp_add_timing (void) +{ // RFC 3264: An offer/answer model session description protocol // As the session is created and destroyed through an external signaling mean (SIP), the line // should have a value of "0 0". @@ -229,48 +251,55 @@ void Sdp::sdp_add_timing( void ){ this->_local_offer->time.start = this->_local_offer->time.stop = 0; } -void Sdp::sdp_add_attributes( ){ +void Sdp::sdp_add_attributes() +{ pjmedia_sdp_attr *a; this->_local_offer->attr_count = 1; - a = PJ_POOL_ZALLOC_T(_pool, pjmedia_sdp_attr); + a = PJ_POOL_ZALLOC_T (_pool, pjmedia_sdp_attr); a->name=STR_SENDRECV; _local_offer->attr[0] = a; } -void Sdp::sdp_add_media_description( ){ +void Sdp::sdp_add_media_description() +{ pjmedia_sdp_media* med; int nb_media, i; - med = PJ_POOL_ZALLOC_T(_pool, pjmedia_sdp_media); + med = PJ_POOL_ZALLOC_T (_pool, pjmedia_sdp_media); nb_media = get_local_media_cap().size(); this->_local_offer->media_count = nb_media; - for( i=0; i<nb_media; i++ ){ - set_media_descriptor_line( get_local_media_cap()[i], &med ); + for (i=0; i<nb_media; i++) { + set_media_descriptor_line (get_local_media_cap() [i], &med); this->_local_offer->media[i] = med; } } -std::string Sdp::media_to_string( void ){ +std::string Sdp::media_to_string (void) +{ int size, i; std::ostringstream res; size = _local_media_cap.size(); - for( i = 0; i < size ; i++ ){ + + for (i = 0; i < size ; i++) { res << _local_media_cap[i]->to_string(); } res << std::endl; + return res.str(); } -void Sdp::clean_session_media(){ +void Sdp::clean_session_media() +{ _session_media.clear(); } -void Sdp::set_negociated_offer( const pjmedia_sdp_session *sdp ){ +void Sdp::set_negociated_offer (const pjmedia_sdp_session *sdp) +{ int nb_media, nb_codecs; int i,j, port; @@ -280,10 +309,10 @@ void Sdp::set_negociated_offer( const pjmedia_sdp_session *sdp ){ CodecsMap codecs_list; CodecsMap::iterator iter; AudioCodec *codec_to_add; - pjmedia_sdp_attr *attribute; + pjmedia_sdp_attr *attribute; pjmedia_sdp_rtpmap *rtpmap; - _negociated_offer = (pjmedia_sdp_session*)sdp; + _negociated_offer = (pjmedia_sdp_session*) sdp; //this->fetch_remote_ip_from_sdp ((pjmedia_sdp_session*)sdp); @@ -291,32 +320,38 @@ void Sdp::set_negociated_offer( const pjmedia_sdp_session *sdp ){ // retrieve the media information nb_media = _negociated_offer->media_count; - for( i=0; i<nb_media ; i++ ){ - // Retrieve the media + + for (i=0; i<nb_media ; i++) { + // Retrieve the media current = _negociated_offer->media[i]; type = current->desc.media.ptr; port = current->desc.port; - media = new sdpMedia( type, port ); + media = new sdpMedia (type, port); // Retrieve the payload nb_codecs = current->desc.fmt_count; // Must be one - for( j=0 ; j<nb_codecs ; j++ ){ - attribute = pjmedia_sdp_media_find_attr(current, &STR_RTPMAP, NULL); - // pj_strtoul(attribute->pt) - pjmedia_sdp_attr_to_rtpmap(_pool, attribute, &rtpmap); - - // _debug("================== set_negociated_offer ===================== %i\n", pj_strtoul(&rtpmap->pt)); + + for (j=0 ; j<nb_codecs ; j++) { + attribute = pjmedia_sdp_media_find_attr (current, &STR_RTPMAP, NULL); + // pj_strtoul(attribute->pt) + pjmedia_sdp_attr_to_rtpmap (_pool, attribute, &rtpmap); + + // _debug("================== set_negociated_offer ===================== %i\n", pj_strtoul(&rtpmap->pt)); // _debug("================== set_negociated_offer ===================== %s\n", current->desc.fmt[j].ptr); - // _debug("================== set_negociated_offer ===================== %i\n", atoi(current->desc.fmt[j].ptr)); - iter = codecs_list.find((AudioCodecType)pj_strtoul(&rtpmap->pt)); + // _debug("================== set_negociated_offer ===================== %i\n", atoi(current->desc.fmt[j].ptr)); + iter = codecs_list.find ( (AudioCodecType) pj_strtoul (&rtpmap->pt)); + if (iter==codecs_list.end()) return; - media->add_codec(iter->second); + + media->add_codec (iter->second); } - _session_media.push_back(media); + + _session_media.push_back (media); } } -AudioCodec* Sdp::get_session_media( void ){ +AudioCodec* Sdp::get_session_media (void) +{ int nb_media; int nb_codec; @@ -327,18 +362,22 @@ AudioCodec* Sdp::get_session_media( void ){ media_list = get_session_media_list (); nb_media = media_list.size(); + if (nb_media > 0) { nb_codec = media_list[0]->get_media_codec_list().size(); + if (nb_codec > 0) { - codec = media_list[0]->get_media_codec_list()[0]; + codec = media_list[0]->get_media_codec_list() [0]; } } + return codec; } -void Sdp::toString (void) { +void Sdp::toString (void) +{ std::ostringstream sdp; int count, i; @@ -364,16 +403,19 @@ void Sdp::toString (void) { sdp << _local_offer->media[0]->desc.port << " "; sdp << _local_offer->media[0]->desc.transport.ptr << " "; count = _local_offer->media[0]->desc.fmt_count; + for (i=0; i<count; i++) { sdp << _local_offer->media[0]->desc.fmt[i].ptr << " "; } + sdp << "\n"; _debug ("LOCAL SDP: \n%s\n", sdp.str().c_str()); } -void Sdp::set_local_media_capabilities () { +void Sdp::set_local_media_capabilities () +{ CodecOrder selected_codecs; int i; @@ -387,84 +429,95 @@ void Sdp::set_local_media_capabilities () { _debug ("Fetch local media capabilities .......... %i\n" , get_local_extern_audio_port()); /* Only one audio media used right now */ - audio = new sdpMedia(MIME_TYPE_AUDIO); + audio = new sdpMedia (MIME_TYPE_AUDIO); audio->set_port (get_local_extern_audio_port()); /* We retrieve the codecs selected by the user */ - selected_codecs = Manager::instance().getCodecDescriptorMap().getActiveCodecs(); + selected_codecs = Manager::instance().getCodecDescriptorMap().getActiveCodecs(); codecs_list = Manager::instance().getCodecDescriptorMap().getCodecsMap(); - for (i=0; i<selected_codecs.size(); i++){ - iter=codecs_list.find(selected_codecs[i]); - if (iter!=codecs_list.end()){ + + for (i=0; i<selected_codecs.size(); i++) { + iter=codecs_list.find (selected_codecs[i]); + + if (iter!=codecs_list.end()) { audio->add_codec (iter->second); } - } + } + _local_media_cap.push_back (audio); } -void Sdp::attribute_port_to_all_media (int port) { +void Sdp::attribute_port_to_all_media (int port) +{ std::vector<sdpMedia*> medias; - int i, size; + int i, size; set_local_extern_audio_port (port); - medias = get_local_media_cap (); + medias = get_local_media_cap (); size = medias.size(); - for(i=0; i<size; i++) { + for (i=0; i<size; i++) { medias[i]->set_port (port); - } + } } -std::string Sdp::convert_int_to_string (int value) { +std::string Sdp::convert_int_to_string (int value) +{ std::ostringstream result; result << value; return result.str(); } -void Sdp::fetch_remote_ip_from_sdp (pjmedia_sdp_session *r_sdp) { +void Sdp::fetch_remote_ip_from_sdp (pjmedia_sdp_session *r_sdp) +{ std::string remote_ip; remote_ip = r_sdp->conn->addr.ptr; - _debug(" Remote IP from fetching SDP: %s\n", remote_ip.c_str()); - this->set_remote_ip(remote_ip); + _debug (" Remote IP from fetching SDP: %s\n", remote_ip.c_str()); + this->set_remote_ip (remote_ip); } -void Sdp::fetch_remote_audio_port_from_sdp (pjmedia_sdp_media *r_media){ +void Sdp::fetch_remote_audio_port_from_sdp (pjmedia_sdp_media *r_media) +{ int remote_port; - + remote_port = r_media->desc.port; - _debug(" Remote Audio Port from fetching SDP: %d\n", remote_port); - this->set_remote_audio_port(remote_port); + _debug (" Remote Audio Port from fetching SDP: %d\n", remote_port); + this->set_remote_audio_port (remote_port); } -void Sdp::fetch_media_transport_info_from_remote_sdp (pjmedia_sdp_session *remote_sdp) { +void Sdp::fetch_media_transport_info_from_remote_sdp (pjmedia_sdp_session *remote_sdp) +{ - _debug("Fetching media from sdp\n"); + _debug ("Fetching media from sdp\n"); pjmedia_sdp_media *r_media; this->get_remote_sdp_media_from_offer (remote_sdp, &r_media); - if (r_media==NULL){ - _debug("SDP Failure: no remote sdp media found in the remote offer\n"); + if (r_media==NULL) { + _debug ("SDP Failure: no remote sdp media found in the remote offer\n"); return; } - + this->fetch_remote_audio_port_from_sdp (r_media); + this->fetch_remote_ip_from_sdp (remote_sdp); } -void Sdp::get_remote_sdp_media_from_offer (pjmedia_sdp_session* remote_sdp, pjmedia_sdp_media** r_media){ +void Sdp::get_remote_sdp_media_from_offer (pjmedia_sdp_session* remote_sdp, pjmedia_sdp_media** r_media) +{ int count, i; count = remote_sdp->media_count; *r_media = NULL; - for(i = 0; i < count; ++i) { - if(pj_stricmp2(&remote_sdp->media[i]->desc.media, "audio") == 0) { + + for (i = 0; i < count; ++i) { + if (pj_stricmp2 (&remote_sdp->media[i]->desc.media, "audio") == 0) { *r_media = remote_sdp->media[i]; return; } diff --git a/sflphone-common/src/sdpmedia.cpp b/sflphone-common/src/sdpmedia.cpp index fe2ef7615c..4cd5a8b99c 100644 --- a/sflphone-common/src/sdpmedia.cpp +++ b/sflphone-common/src/sdpmedia.cpp @@ -23,16 +23,14 @@ #include <sstream> #include <iostream> -static const char* streamDirectionStr[] = -{ +static const char* streamDirectionStr[] = { "sendrecv", "sendonly", "recvonly", "inactive" }; -static const char* mediaTypeStr[] = -{ +static const char* mediaTypeStr[] = { "audio", "video", "application", @@ -41,30 +39,34 @@ static const char* mediaTypeStr[] = "message" }; -sdpMedia::sdpMedia( int type ) - : _media_type( (mediaType)type ), _codec_list(0), _port( 0 ), _stream_type( SEND_RECEIVE ){} +sdpMedia::sdpMedia (int type) + : _media_type ( (mediaType) type), _codec_list (0), _port (0), _stream_type (SEND_RECEIVE) {} -sdpMedia::sdpMedia( std::string type, int port, std::string dir) - : _media_type( (mediaType)-1), _codec_list(0), _port(port), - _stream_type((streamDirection)-1){ +sdpMedia::sdpMedia (std::string type, int port, std::string dir) + : _media_type ( (mediaType)-1), _codec_list (0), _port (port), + _stream_type ( (streamDirection)-1) +{ unsigned int i; const char* tmp; - for( i=0 ; i<MEDIA_COUNT ; i++){ + for (i=0 ; i<MEDIA_COUNT ; i++) { tmp = mediaTypeStr[i]; - if( strcmp(type.c_str(), tmp) == 0 ){ - _media_type = (mediaType)i; + + if (strcmp (type.c_str(), tmp) == 0) { + _media_type = (mediaType) i; break; } } - if( strcmp( dir.c_str(), "default") == 0 ) + if (strcmp (dir.c_str(), "default") == 0) dir = DEFAULT_STREAM_DIRECTION; - for( i=0; i<DIR_COUNT; i++ ){ + + for (i=0; i<DIR_COUNT; i++) { tmp = streamDirectionStr[i]; - if( strcmp(dir.c_str(), tmp) == 0){ - _stream_type = (streamDirection)i; + + if (strcmp (dir.c_str(), tmp) == 0) { + _stream_type = (streamDirection) i; break; } } @@ -74,29 +76,34 @@ sdpMedia::sdpMedia( std::string type, int port, std::string dir) sdpMedia::~sdpMedia() { int i; - for(i=0; i<(int)_codec_list.size(); i++) + + for (i=0; i< (int) _codec_list.size(); i++) delete _codec_list[i]; } -std::string sdpMedia::get_media_type_str( void ){ +std::string sdpMedia::get_media_type_str (void) +{ std::string value; // Test the range to be sure we know the media - if( _media_type >= 0 && _media_type < MEDIA_COUNT ) + + if (_media_type >= 0 && _media_type < MEDIA_COUNT) value = mediaTypeStr[ _media_type ]; else value = "unknown"; + return value; } -void sdpMedia::add_codec( AudioCodec* codec ){ - +void sdpMedia::add_codec (AudioCodec* codec) +{ + _codec_list.push_back (codec); } -void sdpMedia::remove_codec( std::string codecName ) +void sdpMedia::remove_codec (std::string codecName) { // Look for the codec by its encoding name int i; @@ -107,37 +114,43 @@ void sdpMedia::remove_codec( std::string codecName ) size = _codec_list.size(); std::cout << "vector size: " << size << std::endl; - for( i=0 ; i<size ; i++ ){ + for (i=0 ; i<size ; i++) { std::cout << _codec_list[i]->getCodecName().c_str() << std::endl; - if( strcmp(_codec_list[i]->getCodecName().c_str(), codecName.c_str()) == 0 ){ + + if (strcmp (_codec_list[i]->getCodecName().c_str(), codecName.c_str()) == 0) { std::cout << "erase " <<_codec_list[i]->getCodecName() << std::endl; - iter = _codec_list.begin()+i; - _codec_list.erase(iter); + iter = _codec_list.begin() +i; + _codec_list.erase (iter); break; } } } -void sdpMedia::clear_codec_list( void ) { +void sdpMedia::clear_codec_list (void) +{ // Erase every codecs from the list _codec_list.clear(); } -std::string sdpMedia::get_stream_direction_str( void ) { +std::string sdpMedia::get_stream_direction_str (void) +{ std::string value; // Test the range of the value - if( _stream_type >= 0 && _stream_type < DIR_COUNT ) + + if (_stream_type >= 0 && _stream_type < DIR_COUNT) value = streamDirectionStr[ _stream_type ]; else value = "unknown"; + return value; } -std::string sdpMedia::to_string( void ){ +std::string sdpMedia::to_string (void) +{ std::ostringstream display; int size, i; @@ -146,7 +159,8 @@ std::string sdpMedia::to_string( void ){ display << get_media_type_str(); display << ":" << get_port(); display << ":"; - for(i=0; i<size; i++){ + + for (i=0; i<size; i++) { display << _codec_list[i]->getCodecName() << "/"; } diff --git a/sflphone-common/src/sipaccount.cpp b/sflphone-common/src/sipaccount.cpp index 31502460a3..3d141db0ef 100644 --- a/sflphone-common/src/sipaccount.cpp +++ b/sflphone-common/src/sipaccount.cpp @@ -1,18 +1,18 @@ /* * Copyright (C) 2006-2009 Savoir-Faire Linux inc. - * + * * Author: Emmanuel Milou <emmanuel.milou@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 * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -22,22 +22,22 @@ #include "manager.h" #include "user_cfg.h" -SIPAccount::SIPAccount(const AccountID& accountID) - : Account(accountID, "sip") - , _cred(NULL) - , _contact("") - , _bRegister(false) - , _regc() +SIPAccount::SIPAccount (const AccountID& accountID) + : Account (accountID, "sip") + , _cred (NULL) + , _contact ("") + , _bRegister (false) + , _regc() { /* 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 */ /* The SIP library initialization is done in the SIPVoIPLink constructor */ /* The SIP voip link is now independant of the account ID as it can manage several SIP accounts */ - _link = SIPVoIPLink::instance(""); - + _link = SIPVoIPLink::instance (""); + /* Represents the number of SIP accounts connected the same link */ dynamic_cast<SIPVoIPLink*> (_link)->incrementClients(); - + } SIPAccount::~SIPAccount() @@ -46,7 +46,8 @@ SIPAccount::~SIPAccount() dynamic_cast<SIPVoIPLink*> (_link)->decrementClients(); /* Delete accounts-related information */ _regc = NULL; - delete _cred; _cred = NULL; + delete _cred; + _cred = NULL; } int SIPAccount::registerVoIPLink() @@ -55,48 +56,47 @@ int SIPAccount::registerVoIPLink() /* Retrieve the account information */ /* Stuff needed for SIP registration */ - setHostname(Manager::instance().getConfigString(_accountID, HOSTNAME)); - setUsername(Manager::instance().getConfigString(_accountID, USERNAME)); - setPassword(Manager::instance().getConfigString(_accountID, PASSWORD)); + setHostname (Manager::instance().getConfigString (_accountID, HOSTNAME)); + setUsername (Manager::instance().getConfigString (_accountID, USERNAME)); + setPassword (Manager::instance().getConfigString (_accountID, PASSWORD)); /* Start registration */ - status = _link->sendRegister( _accountID ); - ASSERT( status , SUCCESS ); + status = _link->sendRegister (_accountID); + ASSERT (status , SUCCESS); return SUCCESS; } int SIPAccount::unregisterVoIPLink() { - _debug("unregister account %s\n" , getAccountID().c_str()); - - if(_link->sendUnregister( _accountID )){ + _debug ("unregister account %s\n" , getAccountID().c_str()); + + if (_link->sendUnregister (_accountID)) { setRegistrationInfo (NULL); return true; - } - else + } else return false; - + } -void SIPAccount::loadConfig() +void SIPAccount::loadConfig() { - // Account generic - Account::loadConfig(); + // Account generic + Account::loadConfig(); } -bool SIPAccount::fullMatch(const std::string& username, const std::string& hostname) +bool SIPAccount::fullMatch (const std::string& username, const std::string& hostname) { - return (userMatch (username) && hostnameMatch (hostname)); + return (userMatch (username) && hostnameMatch (hostname)); } -bool SIPAccount::userMatch(const std::string& username) +bool SIPAccount::userMatch (const std::string& username) { - return (username == getUsername()); + return (username == getUsername()); } -bool SIPAccount::hostnameMatch(const std::string& hostname) +bool SIPAccount::hostnameMatch (const std::string& hostname) { - return (hostname == getHostname()); + return (hostname == getHostname()); } diff --git a/sflphone-common/src/sipcall.cpp b/sflphone-common/src/sipcall.cpp index 43aabe0620..8f1017ce0a 100644 --- a/sflphone-common/src/sipcall.cpp +++ b/sflphone-common/src/sipcall.cpp @@ -24,23 +24,24 @@ #include "global.h" // for _debug -SIPCall::SIPCall(const CallID& id, Call::CallType type, pj_pool_t *pool) : Call(id, type) - , _cid(0) - , _did(0) - , _tid(0) - , _xferSub(NULL) - , _invSession(NULL) - , _local_sdp(0) +SIPCall::SIPCall (const CallID& id, Call::CallType type, pj_pool_t *pool) : Call (id, type) + , _cid (0) + , _did (0) + , _tid (0) + , _xferSub (NULL) + , _invSession (NULL) + , _local_sdp (0) { _local_sdp = new Sdp (pool); - _debug("SIPCALL::Constructor for this clss is called \n"); + _debug ("SIPCALL::Constructor for this clss is called \n"); } -SIPCall::~SIPCall() +SIPCall::~SIPCall() { - delete _local_sdp; _local_sdp = 0; - _debug("SIPCALL::Destructor for this clss is called \n"); + delete _local_sdp; + _local_sdp = 0; + _debug ("SIPCALL::Destructor for this clss is called \n"); } diff --git a/sflphone-common/src/sipvoiplink.cpp b/sflphone-common/src/sipvoiplink.cpp index f1e8f2cf9f..6d8d8f4b96 100644 --- a/sflphone-common/src/sipvoiplink.cpp +++ b/sflphone-common/src/sipvoiplink.cpp @@ -32,7 +32,7 @@ #define CAN_REINVITE 1 -const pj_str_t STR_USER_AGENT = { ( char* ) "User-Agent", 10 }; +const pj_str_t STR_USER_AGENT = { (char*) "User-Agent", 10 }; /**************** EXTERN VARIABLES AND FUNCTIONS (callbacks) **************************/ @@ -42,7 +42,7 @@ const pj_str_t STR_USER_AGENT = { ( char* ) "User-Agent", 10 }; * @param rdata The request data * @param r_sdp The pjmedia_sdp_media to stock the remote SDP */ -void get_remote_sdp_from_offer ( pjsip_rx_data *rdata, pjmedia_sdp_session** r_sdp ); +void get_remote_sdp_from_offer (pjsip_rx_data *rdata, pjmedia_sdp_session** r_sdp); int getModId(); @@ -52,11 +52,11 @@ 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, bool stun, std::string server); -void handle_incoming_options ( pjsip_rx_data *rxdata ); +void handle_incoming_options (pjsip_rx_data *rxdata); -std::string fetch_header_value ( pjsip_msg *msg, std::string field ); +std::string fetch_header_value (pjsip_msg *msg, std::string field); /* * The global pool factory @@ -92,7 +92,7 @@ UrlHook *urlhook; /** * Get the number of voicemail waiting in a SIP message */ -void set_voicemail_info ( AccountID account, pjsip_msg_body *body ); +void set_voicemail_info (AccountID account, pjsip_msg_body *body); // Documentated from the PJSIP Developer's Guide, available on the pjsip website/ @@ -103,7 +103,7 @@ void set_voicemail_info ( AccountID account, pjsip_msg_body *body ); * @param inv A pointer on a pjsip_inv_session structure * @param e A pointer on a pjsip_event structure */ -void call_on_state_changed ( pjsip_inv_session *inv, pjsip_event *e ); +void call_on_state_changed (pjsip_inv_session *inv, pjsip_event *e); /* * Session callback @@ -112,7 +112,7 @@ void call_on_state_changed ( pjsip_inv_session *inv, pjsip_event *e ); * @param inv A pointer on a pjsip_inv_session structure * @param status A pj_status_t structure */ -void call_on_media_update ( pjsip_inv_session *inv UNUSED, pj_status_t status UNUSED ); +void call_on_media_update (pjsip_inv_session *inv UNUSED, pj_status_t status UNUSED); /* * Called when the invite usage module has created a new dialog and invite @@ -121,7 +121,7 @@ void call_on_media_update ( pjsip_inv_session *inv UNUSED, pj_status_t status UN * @param inv A pointer on a pjsip_inv_session structure * @param e A pointer on a pjsip_event structure */ -void call_on_forked ( pjsip_inv_session *inv, pjsip_event *e ); +void call_on_forked (pjsip_inv_session *inv, pjsip_event *e); /* * Session callback @@ -132,2887 +132,2938 @@ void call_on_forked ( pjsip_inv_session *inv, pjsip_event *e ); * @param tsx A pointer on a pjsip_transaction structure * @param e A pointer on a pjsip_event structure */ -void call_on_tsx_changed ( pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e ); +void call_on_tsx_changed (pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e); -void on_rx_offer ( pjsip_inv_session *inv, const pjmedia_sdp_session *offer ); +void on_rx_offer (pjsip_inv_session *inv, const pjmedia_sdp_session *offer); /* * Registration callback */ -void regc_cb ( struct pjsip_regc_cbparam *param ); +void regc_cb (struct pjsip_regc_cbparam *param); /* * Called to handle incoming requests outside dialogs * @param rdata * @return pj_bool_t */ -pj_bool_t mod_on_rx_request ( pjsip_rx_data *rdata ); +pj_bool_t mod_on_rx_request (pjsip_rx_data *rdata); /* * Called to handle incoming response * @param rdata * @return pj_bool_t */ -pj_bool_t mod_on_rx_response ( pjsip_rx_data *rdata UNUSED ) ; +pj_bool_t mod_on_rx_response (pjsip_rx_data *rdata UNUSED) ; /* * Transfer callbacks */ -void xfer_func_cb ( pjsip_evsub *sub, pjsip_event *event ); -void xfer_svr_cb ( pjsip_evsub *sub, pjsip_event *event ); -void onCallTransfered ( pjsip_inv_session *inv, pjsip_rx_data *rdata ); +void xfer_func_cb (pjsip_evsub *sub, pjsip_event *event); +void xfer_svr_cb (pjsip_evsub *sub, pjsip_event *event); +void onCallTransfered (pjsip_inv_session *inv, pjsip_rx_data *rdata); /*************************************************************************************************/ 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 AudioRtp() ) - ,_regPort ( DEFAULT_SIP_PORT ) - , _useStun ( false ) - , _clients ( 0 ) +SIPVoIPLink::SIPVoIPLink (const AccountID& accountID) + : VoIPLink (accountID) + , _nbTryListenAddr (2) // number of times to try to start SIP listener + , _stunServer ("") + , _localExternAddress ("") + , _localExternPort (0) + , _audiortp (new AudioRtp()) + ,_regPort (DEFAULT_SIP_PORT) + , _useStun (false) + , _clients (0) { - // to get random number for RANDOM_PORT - srand ( time ( NULL ) ); + // to get random number for RANDOM_PORT + srand (time (NULL)); - urlhook = new UrlHook (); + urlhook = new UrlHook (); - /* Start pjsip initialization step */ - init(); + /* Start pjsip initialization step */ + init(); } SIPVoIPLink::~SIPVoIPLink() { - terminate(); + terminate(); } -SIPVoIPLink* SIPVoIPLink::instance ( const AccountID& id ) +SIPVoIPLink* SIPVoIPLink::instance (const AccountID& id) { - if ( !_instance ) - { - _instance = new SIPVoIPLink ( id ); - } + if (!_instance) { + _instance = new SIPVoIPLink (id); + } - return _instance; + return _instance; } -void SIPVoIPLink::decrementClients ( void ) +void SIPVoIPLink::decrementClients (void) { - _clients--; - if ( _clients == 0 ) - { - terminate(); - SIPVoIPLink::_instance=NULL; - } + _clients--; + + if (_clients == 0) { + terminate(); + SIPVoIPLink::_instance=NULL; + } } bool SIPVoIPLink::init() { - if ( initDone() ) - return false; + if (initDone()) + return false; + + /* Instanciate the C++ thread */ + _evThread = new EventThread (this); - /* Instanciate the C++ thread */ - _evThread = new EventThread ( this ); + /* Initialize the pjsip library */ + pjsip_init(); - /* Initialize the pjsip library */ - pjsip_init(); - initDone ( true ); + initDone (true); - return true; + return true; } void SIPVoIPLink::terminate() { - if ( _evThread ) - { - delete _evThread; _evThread = NULL; - } + if (_evThread) { + delete _evThread; + _evThread = NULL; + } + + /* Clean shutdown of pjsip library */ + if (initDone()) { + pjsip_shutdown(); + } - /* Clean shutdown of pjsip library */ - if ( initDone() ) - { - pjsip_shutdown(); - } - initDone ( false ); + initDone (false); } void SIPVoIPLink::terminateSIPCall() { - ost::MutexLock m ( _callMapMutex ); - CallMap::iterator iter = _callMap.begin(); - SIPCall *call; - while ( iter != _callMap.end() ) - { - call = dynamic_cast<SIPCall*> ( iter->second ); - if ( call ) - { - // terminate the sip call - delete call; call = 0; - } - iter++; - } - _callMap.clear(); + ost::MutexLock m (_callMapMutex); + CallMap::iterator iter = _callMap.begin(); + SIPCall *call; + + while (iter != _callMap.end()) { + call = dynamic_cast<SIPCall*> (iter->second); + + if (call) { + // terminate the sip call + delete call; + call = 0; + } + + iter++; + } + + _callMap.clear(); } void -SIPVoIPLink::terminateOneCall ( const CallID& id ) +SIPVoIPLink::terminateOneCall (const CallID& id) { - SIPCall *call = getSIPCall ( id ); - if ( call ) - { - // terminate the sip call - delete call; call = 0; - } + SIPCall *call = getSIPCall (id); + + if (call) { + // terminate the sip call + delete call; + call = 0; + } } -void get_remote_sdp_from_offer ( pjsip_rx_data *rdata, pjmedia_sdp_session** r_sdp ) +void get_remote_sdp_from_offer (pjsip_rx_data *rdata, pjmedia_sdp_session** r_sdp) { - pjmedia_sdp_session *sdp; - pjsip_msg *msg; - pjsip_msg_body *body; + pjmedia_sdp_session *sdp; + pjsip_msg *msg; + pjsip_msg_body *body; + + // Get the message + msg = rdata->msg_info.msg; + // Get the body message + body = msg->body; - // Get the message - msg = rdata->msg_info.msg; - // Get the body message - body = msg->body; + // Parse the remote request to get the sdp session - // Parse the remote request to get the sdp session - if ( body ) - { - pjmedia_sdp_parse ( rdata->tp_info.pool, ( char* ) body->data, body->len, &sdp ); - *r_sdp = sdp; - } + if (body) { + pjmedia_sdp_parse (rdata->tp_info.pool, (char*) body->data, body->len, &sdp); + *r_sdp = sdp; + } - else - *r_sdp = NULL; + else + *r_sdp = NULL; } -std::string SIPVoIPLink::get_useragent_name ( void ) +std::string SIPVoIPLink::get_useragent_name (void) { - std::ostringstream useragent; - useragent << PROGNAME << "/" << SFLPHONED_VERSION; - return useragent.str(); + std::ostringstream useragent; + useragent << PROGNAME << "/" << SFLPHONED_VERSION; + return useragent.str(); } void SIPVoIPLink::getEvent() { - // We have to register the external thread so it could access the pjsip framework - if ( !pj_thread_is_registered() ) - pj_thread_register ( NULL, desc, &thread ); - - // PJSIP polling - pj_time_val timeout = {0, 10}; - pjsip_endpt_handle_events ( _endpt, &timeout ); - -} - -int SIPVoIPLink::sendRegister ( AccountID id ) -{ - pj_status_t status; - int expire_value; - char contactTmp[256]; - pj_str_t svr, aor, contact, useragent; - pjsip_tx_data *tdata; - std::string tmp, hostname, username, password; - SIPAccount *account; - pjsip_regc *regc; - pjsip_generic_string_hdr *h; - pjsip_hdr hdr_list; - - account = dynamic_cast<SIPAccount *> ( Manager::instance().getAccount ( id ) ); - hostname = account->getHostname(); - username = account->getUsername(); - password = account->getPassword(); - - _mutexSIP.enterMutex(); - - /* Get the client registration information for this particular account */ - regc = account->getRegistrationInfo(); - /* TODO If the registration already exists, delete it */ - /*if(regc) { - status = pjsip_regc_destroy(regc); - regc = NULL; - PJ_ASSERT_RETURN( status == PJ_SUCCESS, 1 ); - }*/ - - account->setRegister ( true ); - - /* Set the expire value of the message from the config file */ - expire_value = Manager::instance().getRegistrationExpireValue(); - - /* Update the state of the voip link */ - account->setRegistrationState ( Trying ); - - if ( !validStunServer ) - { - account->setRegistrationState ( ErrorExistStun ); - account->setRegister ( false ); - _mutexSIP.leaveMutex(); - return false; - } - - /* Create the registration according to the account ID */ - status = pjsip_regc_create ( _endpt, ( void* ) account, ®c_cb, ®c ); - if ( status != PJ_SUCCESS ) - { - _debug ( "UserAgent: Unable to create regc.\n" ); - _mutexSIP.leaveMutex(); - return false; - } - - tmp = "sip:" + hostname; - pj_strdup2 ( _pool, &svr, tmp.data() ); - - // tmp = "<sip:" + username + "@" + hostname + ";transport=tls>"; - tmp = "<sip:" + username + "@" + hostname + ">"; - pj_strdup2 ( _pool, &aor, tmp.data() ); - - _debug("<sip:%s@%s:%d>\n", username.data(), _localExternAddress.data(), _localExternPort ); - sprintf ( contactTmp, "<sip:%s@%s:%d>", username.data(), _localExternAddress.data(), _localExternPort ); - pj_strdup2 ( _pool, &contact, contactTmp ); - account->setContact ( contactTmp ); - - status = pjsip_regc_init ( regc, &svr, &aor, &aor, 1, &contact, 600 ); //timeout); - if ( status != PJ_SUCCESS ) - { - _debug ( "UserAgent: Unable to initialize regc. %d\n", status ); //, regc->str_srv_url.ptr); - _mutexSIP.leaveMutex(); - return false; - } - - pjsip_cred_info *cred = account->getCredInfo(); - - if ( !cred ) - cred = new pjsip_cred_info(); - - pj_bzero ( cred, sizeof ( pjsip_cred_info ) ); - pj_strdup2 ( _pool, &cred->username, username.data() ); - cred->data_type = PJSIP_CRED_DATA_PLAIN_PASSWD; - pj_strdup2 ( _pool, &cred->data, password.data() ); - pj_strdup2 ( _pool, &cred->realm, "*" ); - pj_strdup2 ( _pool, &cred->scheme, "digest" ); - pjsip_regc_set_credentials ( regc, 1, cred ); - - account->setCredInfo ( cred ); - - // Add User-Agent Header - pj_list_init ( &hdr_list ); - useragent = pj_str ( ( char* ) get_useragent_name ().c_str() ); - h = pjsip_generic_string_hdr_create ( _pool, &STR_USER_AGENT, &useragent ); - pj_list_push_back ( &hdr_list, ( pjsip_hdr* ) h ); - pjsip_regc_add_headers ( regc, &hdr_list ); - - status = pjsip_regc_register ( regc, PJ_TRUE, &tdata ); - if ( status != PJ_SUCCESS ) - { - _debug ( "UserAgent: Unable to register regc.\n" ); - _mutexSIP.leaveMutex(); - return false; - } - - status = pjsip_regc_send ( regc, tdata ); - if ( status != PJ_SUCCESS ) - { - _debug ( "UserAgent: Unable to send regc request.\n" ); - _mutexSIP.leaveMutex(); - return false; - } - - _mutexSIP.leaveMutex(); - - account->setRegistrationInfo ( regc ); - - return true; -} + // We have to register the external thread so it could access the pjsip framework + if (!pj_thread_is_registered()) + pj_thread_register (NULL, desc, &thread); -int -SIPVoIPLink::sendUnregister ( AccountID id ) -{ - pj_status_t status = 0; - pjsip_tx_data *tdata = NULL; - SIPAccount *account; - pjsip_regc *regc; - - account = dynamic_cast<SIPAccount *> ( Manager::instance().getAccount ( id ) ); - regc = account->getRegistrationInfo(); - - if ( !account->isRegister() ) - { - account->setRegistrationState ( Unregistered ); - return true; - } - - if ( regc ) - { - status = pjsip_regc_unregister ( regc, &tdata ); - if ( status != PJ_SUCCESS ) - { - _debug ( "UserAgent: Unable to unregister regc.\n" ); - return false; - } - - status = pjsip_regc_send ( regc, tdata ); - if ( status != PJ_SUCCESS ) - { - _debug ( "UserAgent: Unable to send regc request.\n" ); - return false; - } - } - else - { - _debug ( "UserAgent: regc is null!\n" ); - return false; - } - - //account->setRegistrationInfo(regc); - account->setRegister ( false ); - - return true; -} + // PJSIP polling + pj_time_val timeout = {0, 10}; + + pjsip_endpt_handle_events (_endpt, &timeout); -Call* -SIPVoIPLink::newOutgoingCall ( const CallID& id, const std::string& toUrl ) -{ - Account* account; - pj_status_t status; - - SIPCall* call = new SIPCall ( id, Call::Outgoing, _pool ); - - - if ( call ) - { - account = dynamic_cast<SIPAccount *> ( Manager::instance().getAccount ( Manager::instance().getAccountFromCall ( id ) ) ); - if ( !account ) - { - _debug ( "Error retrieving the account to the make the call with\n" ); - call->setConnectionState ( Call::Disconnected ); - call->setState ( Call::Error ); - delete call; call=0; - return call; - } - - call->setPeerNumber ( getSipTo ( toUrl, account->getHostname() ) ); - setCallAudioLocal ( call, getLocalIPAddress(), useStun(), getStunServer() ); - - - try { - _debug("CREATE NEW RTP SESSION FROM NEWOUTGOINGCALL\n"); - _audiortp->createNewSession (call); - } catch (...) { - _debug("Failed to create rtp thread from newOutGoingCall\n"); - } - - - - - call->initRecFileName(); - - _debug ( "Try to make a call to: %s with call ID: %s\n", toUrl.data(), id.data() ); - // Building the local SDP offer - call->getLocalSDP()->set_ip_address ( getLocalIP() ); - status = call->getLocalSDP()->create_initial_offer(); - if ( status != PJ_SUCCESS ) - { - delete call; call=0; - return call; - } - - if ( SIPOutgoingInvite ( call ) ) - { - - call->setConnectionState ( Call::Progressing ); - call->setState ( Call::Active ); - addCall ( call ); - - // _audiortp->start(); - - // call->setAudioStart ( true ); - - - } - else - { - delete call; call = 0; - } - } - return call; } -bool -SIPVoIPLink::answer ( const CallID& id ) +int SIPVoIPLink::sendRegister (AccountID id) { + pj_status_t status; + int expire_value; + char contactTmp[256]; + pj_str_t svr, aor, contact, useragent; + pjsip_tx_data *tdata; + std::string tmp, hostname, username, password; + SIPAccount *account; + pjsip_regc *regc; + pjsip_generic_string_hdr *h; + pjsip_hdr hdr_list; - int i; - SIPCall *call; - pj_status_t status; - pjsip_tx_data *tdata; - Sdp *local_sdp; - pjsip_inv_session *inv_session; + account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (id)); + hostname = account->getHostname(); + username = account->getUsername(); + password = account->getPassword(); - _debug ( "SIPVoIPLink::answer: start answering \n" ); + _mutexSIP.enterMutex(); - call = getSIPCall ( id ); + /* Get the client registration information for this particular account */ + regc = account->getRegistrationInfo(); + /* TODO If the registration already exists, delete it */ + /*if(regc) { + status = pjsip_regc_destroy(regc); + regc = NULL; + PJ_ASSERT_RETURN( status == PJ_SUCCESS, 1 ); + }*/ - if ( call==0 ) - { - _debug ( "! SIP Failure: SIPCall doesn't exists\n" ); - return false; - } + account->setRegister (true); - local_sdp = call->getLocalSDP(); + /* Set the expire value of the message from the config file */ + expire_value = Manager::instance().getRegistrationExpireValue(); - try { - _audiortp->createNewSession (call); - } catch (...) { - _debug("Failed to create rtp thread from answer\n"); - } + /* Update the state of the voip link */ + account->setRegistrationState (Trying); - inv_session = call->getInvSession(); - status = local_sdp->start_negociation (); + if (!validStunServer) { + account->setRegistrationState (ErrorExistStun); + account->setRegister (false); + _mutexSIP.leaveMutex(); + return false; + } - if ( status == PJ_SUCCESS ) - { + /* Create the registration according to the account ID */ + status = pjsip_regc_create (_endpt, (void*) account, ®c_cb, ®c); - _debug ( "SIPVoIPLink::answer:UserAgent: Negociation success! : call %s \n", call->getCallId().c_str() ); - // Create and send a 200(OK) response - status = pjsip_inv_answer ( inv_session, PJSIP_SC_OK, NULL, NULL, &tdata ); - PJ_ASSERT_RETURN ( status == PJ_SUCCESS, 1 ); - status = pjsip_inv_send_msg ( inv_session, tdata ); - PJ_ASSERT_RETURN ( status == PJ_SUCCESS, 1 ); + if (status != PJ_SUCCESS) { + _debug ("UserAgent: Unable to create regc.\n"); + _mutexSIP.leaveMutex(); + return false; + } - call->setConnectionState ( Call::Connected ); - call->setState ( Call::Active ); + tmp = "sip:" + hostname; - ; + pj_strdup2 (_pool, &svr, tmp.data()); - return true; - } - else - { - // Create and send a 488/Not acceptable here - // because the SDP negociation failed - status = pjsip_inv_answer ( inv_session, PJSIP_SC_NOT_ACCEPTABLE_HERE, NULL, NULL, - &tdata ); - PJ_ASSERT_RETURN ( status == PJ_SUCCESS, 1 ); - status = pjsip_inv_send_msg ( inv_session, tdata ); - PJ_ASSERT_RETURN ( status == PJ_SUCCESS, 1 ); + // tmp = "<sip:" + username + "@" + hostname + ";transport=tls>"; + tmp = "<sip:" + username + "@" + hostname + ">"; + pj_strdup2 (_pool, &aor, tmp.data()); - // Terminate the call - _debug ( "SIPVoIPLink::answer: fail terminate call %s \n",call->getCallId().c_str() ); - terminateOneCall ( call->getCallId() ); - removeCall ( call->getCallId() ); - return false; - } -} + _debug ("<sip:%s@%s:%d>\n", username.data(), _localExternAddress.data(), _localExternPort); + sprintf (contactTmp, "<sip:%s@%s:%d>", username.data(), _localExternAddress.data(), _localExternPort); + pj_strdup2 (_pool, &contact, contactTmp); + account->setContact (contactTmp); -bool -SIPVoIPLink::hangup ( const CallID& id ) -{ - pj_status_t status; - pjsip_tx_data *tdata = NULL; - SIPCall* call; + status = pjsip_regc_init (regc, &svr, &aor, &aor, 1, &contact, 600); //timeout); - call = getSIPCall ( id ); + if (status != PJ_SUCCESS) { + _debug ("UserAgent: Unable to initialize regc. %d\n", status); //, regc->str_srv_url.ptr); + _mutexSIP.leaveMutex(); + return false; + } - if ( call==0 ) { _debug ( "! SIP Error: Call doesn't exist\n" ); return false; } + pjsip_cred_info *cred = account->getCredInfo(); - // User hangup current call. Notify peer - status = pjsip_inv_end_session ( call->getInvSession(), 404, NULL, &tdata ); - if ( status != PJ_SUCCESS ) - return false; + if (!cred) + cred = new pjsip_cred_info(); + pj_bzero (cred, sizeof (pjsip_cred_info)); - if ( tdata == NULL ) - return true; - // _debug("Some tdata info: %",); + pj_strdup2 (_pool, &cred->username, username.data()); - status = pjsip_inv_send_msg ( call->getInvSession(), tdata ); - if ( status != PJ_SUCCESS ) - return false; + cred->data_type = PJSIP_CRED_DATA_PLAIN_PASSWD; + pj_strdup2 (_pool, &cred->data, password.data()); - call->getInvSession()->mod_data[getModId() ] = NULL; + pj_strdup2 (_pool, &cred->realm, "*"); + pj_strdup2 (_pool, &cred->scheme, "digest"); - // Release RTP thread - if ( Manager::instance().isCurrentCall ( id ) ) - { - _debug ( "* SIP Info: Stopping AudioRTP for hangup\n" ); - _audiortp->closeRtpSession(); - } + pjsip_regc_set_credentials (regc, 1, cred); - terminateOneCall ( id ); - removeCall ( id ); + account->setCredInfo (cred); - return true; -} + // Add User-Agent Header + pj_list_init (&hdr_list); -bool -SIPVoIPLink::peerHungup ( const CallID& id ) -{ - pj_status_t status; - pjsip_tx_data *tdata = NULL; - SIPCall* call; + useragent = pj_str ( (char*) get_useragent_name ().c_str()); - call = getSIPCall ( id ); + h = pjsip_generic_string_hdr_create (_pool, &STR_USER_AGENT, &useragent); - if ( call==0 ) { _debug ( "! SIP Error: Call doesn't exist\n" ); return false; } + pj_list_push_back (&hdr_list, (pjsip_hdr*) h); - // User hangup current call. Notify peer - status = pjsip_inv_end_session ( call->getInvSession(), 404, NULL, &tdata ); - if ( status != PJ_SUCCESS ) - return false; + pjsip_regc_add_headers (regc, &hdr_list); - if ( tdata == NULL ) - return true; + status = pjsip_regc_register (regc, PJ_TRUE, &tdata); - status = pjsip_inv_send_msg ( call->getInvSession(), tdata ); - if ( status != PJ_SUCCESS ) - return false; + if (status != PJ_SUCCESS) { + _debug ("UserAgent: Unable to register regc.\n"); + _mutexSIP.leaveMutex(); + return false; + } + + status = pjsip_regc_send (regc, tdata); - call->getInvSession()->mod_data[getModId() ] = NULL; + if (status != PJ_SUCCESS) { + _debug ("UserAgent: Unable to send regc request.\n"); + _mutexSIP.leaveMutex(); + return false; + } - // Release RTP thread - if ( Manager::instance().isCurrentCall ( id ) ) - { - _debug ( "* SIP Info: Stopping AudioRTP for hangup\n" ); - _audiortp->closeRtpSession(); - } + _mutexSIP.leaveMutex(); - terminateOneCall ( id ); - removeCall ( id ); + account->setRegistrationInfo (regc); - return true; + return true; } -bool -SIPVoIPLink::cancel ( const CallID& id ) +int +SIPVoIPLink::sendUnregister (AccountID id) { - SIPCall* call = getSIPCall ( id ); - if ( call==0 ) { _debug ( "! SIP Error: Call doesn't exist\n" ); return false; } + pj_status_t status = 0; + pjsip_tx_data *tdata = NULL; + SIPAccount *account; + pjsip_regc *regc; + + account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (id)); + regc = account->getRegistrationInfo(); + + if (!account->isRegister()) { + account->setRegistrationState (Unregistered); + return true; + } + + if (regc) { + status = pjsip_regc_unregister (regc, &tdata); + + if (status != PJ_SUCCESS) { + _debug ("UserAgent: Unable to unregister regc.\n"); + return false; + } + + status = pjsip_regc_send (regc, tdata); - _debug ( "- SIP Action: Cancel call %s [cid: %3d]\n", id.data(), call->getCid() ); + if (status != PJ_SUCCESS) { + _debug ("UserAgent: Unable to send regc request.\n"); + return false; + } + } else { + _debug ("UserAgent: regc is null!\n"); + return false; + } - terminateOneCall ( id ); - removeCall ( id ); + //account->setRegistrationInfo(regc); + account->setRegister (false); - return true; + return true; } -bool -SIPVoIPLink::onhold ( const CallID& id ) +Call* +SIPVoIPLink::newOutgoingCall (const CallID& id, const std::string& toUrl) { + Account* account; + pj_status_t status; - pj_status_t status; - SIPCall* call; + SIPCall* call = new SIPCall (id, Call::Outgoing, _pool); - call = getSIPCall ( id ); - if ( call==0 ) { _debug ( "! SIP Error: call doesn't exist\n" ); return false; } + if (call) { + account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (Manager::instance().getAccountFromCall (id))); + if (!account) { + _debug ("Error retrieving the account to the make the call with\n"); + call->setConnectionState (Call::Disconnected); + call->setState (Call::Error); + delete call; + call=0; + return call; + } - // Stop sound - call->setAudioStart ( false ); - call->setState ( Call::Hold ); + call->setPeerNumber (getSipTo (toUrl, account->getHostname())); - _debug ( "* SIP Info: Stopping AudioRTP for onhold action\n" ); - _audiortp->closeRtpSession(); + setCallAudioLocal (call, getLocalIPAddress(), useStun(), getStunServer()); - /* Create re-INVITE with new offer */ - status = inv_session_reinvite ( call, "sendonly" ); - if ( status != PJ_SUCCESS ) - return false; - return true; -} + try { + _debug ("CREATE NEW RTP SESSION FROM NEWOUTGOINGCALL\n"); + _audiortp->createNewSession (call); + } catch (...) { + _debug ("Failed to create rtp thread from newOutGoingCall\n"); + } + -int SIPVoIPLink::inv_session_reinvite ( SIPCall *call, std::string direction ) -{ - pj_status_t status; - pjsip_tx_data *tdata; - pjmedia_sdp_session *local_sdp; - pjmedia_sdp_attr *attr; - local_sdp = call->getLocalSDP()->get_local_sdp_session(); + call->initRecFileName(); - if ( local_sdp == NULL ) - { - _debug ( "! SIP Failure: unable to find local_sdp\n" ); - return !PJ_SUCCESS; - } + _debug ("Try to make a call to: %s with call ID: %s\n", toUrl.data(), id.data()); + // Building the local SDP offer + call->getLocalSDP()->set_ip_address (getLocalIP()); + status = call->getLocalSDP()->create_initial_offer(); - // reinvite only if connected - // Build the local SDP offer - status = call->getLocalSDP()->create_initial_offer( ); - if ( status != PJ_SUCCESS ) - return 1; // !PJ_SUCCESS + if (status != PJ_SUCCESS) { + delete call; + call=0; + return call; + } - pjmedia_sdp_media_remove_all_attr ( local_sdp->media[0], "sendrecv" ); - attr = pjmedia_sdp_attr_create ( _pool, direction.c_str(), NULL ); - pjmedia_sdp_media_add_attr ( local_sdp->media[0], attr ); + if (SIPOutgoingInvite (call)) { - // Build the reinvite request - - status = pjsip_inv_reinvite ( call->getInvSession(), NULL, - local_sdp, &tdata ); - if ( status != PJ_SUCCESS ) - return 1; // !PJ_SUCCESS + call->setConnectionState (Call::Progressing); + call->setState (Call::Active); + addCall (call); - // Send it - status = pjsip_inv_send_msg ( call->getInvSession(), tdata ); - if ( status != PJ_SUCCESS ) - return 1; // !PJ_SUCCESS + // _audiortp->start(); - return PJ_SUCCESS; -} + // call->setAudioStart ( true ); + + + } else { + delete call; + call = 0; + } + } + return call; +} bool -SIPVoIPLink::offhold ( const CallID& id ) +SIPVoIPLink::answer (const CallID& id) { - SIPCall *call; - pj_status_t status; - call = getSIPCall ( id ); + int i; + SIPCall *call; + pj_status_t status; + pjsip_tx_data *tdata; + Sdp *local_sdp; + pjsip_inv_session *inv_session; - if ( call==0 ) - { - _debug ( "! SIP Error: Call doesn't exist\n" ); - return false; - } + _debug ("SIPVoIPLink::answer: start answering \n"); - try { - _audiortp->createNewSession (call); - } catch (...) { - _debug ( "! SIP Failure: Unable to create RTP Session (%s:%d)\n", __FILE__, __LINE__ ); - } + call = getSIPCall (id); - /* Create re-INVITE with new offer */ - status = inv_session_reinvite ( call, "sendrecv" ); - if ( status != PJ_SUCCESS ) - return false; + if (call==0) { + _debug ("! SIP Failure: SIPCall doesn't exists\n"); + return false; + } - // Enable audio - _debug ( "* SIP Info: Starting AudioRTP when offhold\n" ); - call->setState ( Call::Active ); - // it's sure that this is the current call id... + local_sdp = call->getLocalSDP(); - _audiortp->start(); + try { + _audiortp->createNewSession (call); + } catch (...) { + _debug ("Failed to create rtp thread from answer\n"); + } - call->setAudioStart ( true ); + inv_session = call->getInvSession(); - return true; -} + status = local_sdp->start_negociation (); -bool -SIPVoIPLink::transfer ( const CallID& id, const std::string& to ) -{ - - SIPCall *call; - std::string tmp_to; - pjsip_evsub *sub; - pjsip_tx_data *tdata; - struct pjsip_evsub_user xfer_cb; - pj_status_t status; - pj_str_t dest; - AccountID account_id; - Account* account; - - call = getSIPCall ( id ); - call->stopRecording(); - account_id = Manager::instance().getAccountFromCall ( id ); - account = dynamic_cast<SIPAccount *> ( Manager::instance().getAccount ( account_id ) ); - - if ( call==0 ) - { - _debug ( "! SIP Failure: Call doesn't exist\n" ); - return false; - } - - tmp_to = SIPToHeader ( to ); - if ( account ) - { - if ( tmp_to.find ( "@" ) == std::string::npos ) - { - tmp_to = tmp_to + "@" + account->getHostname(); - } - } - - else - { - - } - - _debug ( "In transfer, tmp_to is %s\n", tmp_to.data() ); - - pj_strdup2 ( _pool, &dest, tmp_to.data() ); - - /* Create xfer client subscription. */ - pj_bzero ( &xfer_cb, sizeof ( xfer_cb ) ); - xfer_cb.on_evsub_state = &xfer_func_cb; - - status = pjsip_xfer_create_uac ( call->getInvSession()->dlg, &xfer_cb, &sub ); - if ( status != PJ_SUCCESS ) - { - _debug ( "UserAgent: Unable to create xfer -- %d\n", status ); - return false; - } - - /* Associate this voiplink of call with the client subscription - * We can not just associate call with the client subscription - * because after this function, we can not find the cooresponding - * voiplink from the call any more. But the voiplink is useful! - */ - pjsip_evsub_set_mod_data ( sub, getModId(), this ); - - _debug ( "SIP port listener = %i ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++", _localExternPort ); - - /* - * Create REFER request. - */ - status = pjsip_xfer_initiate ( sub, &dest, &tdata ); - if ( status != PJ_SUCCESS ) - { - _debug ( "UserAgent: Unable to create REFER request -- %d\n", status ); - return false; - } - - /* Send. */ - status = pjsip_xfer_send_request ( sub, tdata ); - if ( status != PJ_SUCCESS ) - { - _debug ( "UserAgent: Unable to send REFER request -- %d\n", status ); - return false; - } - - return true; -} + if (status == PJ_SUCCESS) { -bool SIPVoIPLink::transferStep2() -{ - _audiortp->closeRtpSession(); - return true; + _debug ("SIPVoIPLink::answer:UserAgent: Negociation success! : call %s \n", call->getCallId().c_str()); + // Create and send a 200(OK) response + status = pjsip_inv_answer (inv_session, PJSIP_SC_OK, NULL, NULL, &tdata); + PJ_ASSERT_RETURN (status == PJ_SUCCESS, 1); + status = pjsip_inv_send_msg (inv_session, tdata); + PJ_ASSERT_RETURN (status == PJ_SUCCESS, 1); + + call->setConnectionState (Call::Connected); + call->setState (Call::Active); + + ; + + return true; + } else { + // Create and send a 488/Not acceptable here + // because the SDP negociation failed + status = pjsip_inv_answer (inv_session, PJSIP_SC_NOT_ACCEPTABLE_HERE, NULL, NULL, + &tdata); + PJ_ASSERT_RETURN (status == PJ_SUCCESS, 1); + status = pjsip_inv_send_msg (inv_session, tdata); + PJ_ASSERT_RETURN (status == PJ_SUCCESS, 1); + + // Terminate the call + _debug ("SIPVoIPLink::answer: fail terminate call %s \n",call->getCallId().c_str()); + terminateOneCall (call->getCallId()); + removeCall (call->getCallId()); + return false; + } } bool -SIPVoIPLink::refuse ( const CallID& id ) +SIPVoIPLink::hangup (const CallID& id) { - SIPCall *call; - pj_status_t status; - pjsip_tx_data *tdata; + pj_status_t status; + pjsip_tx_data *tdata = NULL; + SIPCall* call; + call = getSIPCall (id); - call = getSIPCall ( id ); + if (call==0) { + _debug ("! SIP Error: Call doesn't exist\n"); + return false; + } - if ( call==0 ) - { - _debug ( "Call doesn't exist\n" ); - return false; - } + // User hangup current call. Notify peer + status = pjsip_inv_end_session (call->getInvSession(), 404, NULL, &tdata); - // can't refuse outgoing call or connected - if ( !call->isIncoming() || call->getConnectionState() == Call::Connected ) - { - _debug ( "It's not an incoming call, or it's already answered\n" ); - return false; - } + if (status != PJ_SUCCESS) + return false; - // User refuse current call. Notify peer - status = pjsip_inv_end_session ( call->getInvSession(), PJSIP_SC_DECLINE, NULL, &tdata ); //603 - if ( status != PJ_SUCCESS ) - return false; - status = pjsip_inv_send_msg ( call->getInvSession(), tdata ); - if ( status != PJ_SUCCESS ) - return false; + if (tdata == NULL) + return true; - call->getInvSession()->mod_data[getModId() ] = NULL; + // _debug("Some tdata info: %",); - terminateOneCall ( id ); - return true; -} + status = pjsip_inv_send_msg (call->getInvSession(), tdata); + + if (status != PJ_SUCCESS) + return false; + + + call->getInvSession()->mod_data[getModId() ] = NULL; -void -SIPVoIPLink::setRecording ( const CallID& id ) -{ - SIPCall* call = getSIPCall ( id ); - if ( call ) - call->setRecording(); + // Release RTP thread + if (Manager::instance().isCurrentCall (id)) { + _debug ("* SIP Info: Stopping AudioRTP for hangup\n"); + _audiortp->closeRtpSession(); + } + + terminateOneCall (id); - // _audiortp->setRecording(); + removeCall (id); + + return true; } bool -SIPVoIPLink::isRecording ( const CallID& id ) +SIPVoIPLink::peerHungup (const CallID& id) { - SIPCall* call = getSIPCall ( id ); - _debug ( "call->isRecording() %i \n",call->isRecording() ); - if ( call ) - return call->isRecording(); - else - return false; -} + pj_status_t status; + pjsip_tx_data *tdata = NULL; + SIPCall* call; + call = getSIPCall (id); -std::string -SIPVoIPLink::getCurrentCodecName() -{ + if (call==0) { + _debug ("! SIP Error: Call doesn't exist\n"); + return false; + } - SIPCall *call; - AudioCodec *ac = NULL; - std::string name = ""; + // User hangup current call. Notify peer + status = pjsip_inv_end_session (call->getInvSession(), 404, NULL, &tdata); - call = getSIPCall ( Manager::instance().getCurrentCallId() ); - if ( call ) - ac = call->getLocalSDP()->get_session_media(); + if (status != PJ_SUCCESS) + return false; - if ( ac ) - name = ac->getCodecName(); + if (tdata == NULL) + return true; - return name; -} + status = pjsip_inv_send_msg (call->getInvSession(), tdata); -bool -SIPVoIPLink::carryingDTMFdigits ( const CallID& id, char code ) -{ - - SIPCall *call; - int duration; - const int body_len = 1000; - char *dtmf_body; - pj_status_t status; - pjsip_tx_data *tdata; - pj_str_t methodName, content; - pjsip_method method; - pjsip_media_type ctype; - - call = getSIPCall ( id ); - - if ( call==0 ) - { - _debug ( "Call doesn't exist\n" ); - return false; - } - - duration = Manager::instance().getConfigInt ( SIGNALISATION, PULSE_LENGTH ); - dtmf_body = new char[body_len]; - - snprintf ( dtmf_body, body_len - 1, "Signal=%c\r\nDuration=%d\r\n", code, duration ); - - pj_strdup2 ( _pool, &methodName, "INFO" ); - pjsip_method_init_np ( &method, &methodName ); - - /* Create request message. */ - status = pjsip_dlg_create_request ( call->getInvSession()->dlg, &method, -1, &tdata ); - if ( status != PJ_SUCCESS ) - { - _debug ( "UserAgent: Unable to create INFO request -- %d\n", status ); - return false; - } - - /* Get MIME type */ - pj_strdup2 ( _pool, &ctype.type, "application" ); - pj_strdup2 ( _pool, &ctype.subtype, "dtmf-relay" ); - - /* Create "application/dtmf-relay" message body. */ - pj_strdup2 ( _pool, &content, dtmf_body ); - tdata->msg->body = pjsip_msg_body_create ( tdata->pool, &ctype.type, &ctype.subtype, &content ); - if ( tdata->msg->body == NULL ) - { - _debug ( "UserAgent: Unable to create msg body!\n" ); - pjsip_tx_data_dec_ref ( tdata ); - return false; - } - - /* Send the request. */ - status = pjsip_dlg_send_request ( call->getInvSession()->dlg, tdata, getModId(), NULL ); - if ( status != PJ_SUCCESS ) - { - _debug ( "UserAgent: Unable to send MESSAGE request -- %d\n", status ); - return false; - } - - return true; + if (status != PJ_SUCCESS) + return false; + + call->getInvSession()->mod_data[getModId() ] = NULL; + + // Release RTP thread + if (Manager::instance().isCurrentCall (id)) { + _debug ("* SIP Info: Stopping AudioRTP for hangup\n"); + _audiortp->closeRtpSession(); + } + + terminateOneCall (id); + + removeCall (id); + + return true; } bool -SIPVoIPLink::SIPOutgoingInvite ( SIPCall* call ) +SIPVoIPLink::cancel (const CallID& id) { - // If no SIP proxy setting for direct call with only IP address - if ( !SIPStartCall ( call, "" ) ) - { - _debug ( "! SIP Failure: call not started\n" ); - return false; - } - return true; -} + SIPCall* call = getSIPCall (id); -bool -SIPVoIPLink::SIPStartCall ( SIPCall* call, const std::string& subject UNUSED ) -{ - std::string strTo, strFrom; - pj_status_t status; - pjsip_dialog *dialog; - pjsip_tx_data *tdata; - pj_str_t from, to, contact; - AccountID id; - SIPAccount *account; - pjsip_inv_session *inv; - - if ( !call ) - return false; - - id = Manager::instance().getAccountFromCall ( call->getCallId() ); - // Get the basic information about the callee account - account = dynamic_cast<SIPAccount *> ( Manager::instance().getAccount ( id ) ); - - strTo = getSipTo ( call->getPeerNumber(), account->getHostname() ); - _debug ( " To: %s\n", strTo.data() ); - - // Generate the from URI - strFrom = "sip:" + account->getUsername() + "@" + account->getHostname(); - _debug( " From: %s\n", strFrom.c_str()); - - // pjsip need the from and to information in pj_str_t format - pj_strdup2 ( _pool, &from, strFrom.data() ); - pj_strdup2 ( _pool, &to, strTo.data() ); - pj_strdup2 ( _pool, &contact, account->getContact().data() ); - - //_debug("%s %s %s\n", from.ptr, contact.ptr, to.ptr); - // create the dialog (UAC) - status = pjsip_dlg_create_uac ( pjsip_ua_instance(), &from, - &contact, - &to, - NULL, - &dialog ); - if ( status != PJ_SUCCESS ) - { - _debug ( "UAC creation failed\n" ); - return false; - } - - // Create the invite session for this call - status = pjsip_inv_create_uac ( dialog, call->getLocalSDP()->get_local_sdp_session(), 0, &inv ); - PJ_ASSERT_RETURN ( status == PJ_SUCCESS, false ); - - // Set auth information - pjsip_auth_clt_set_credentials ( &dialog->auth_sess, 1, account->getCredInfo() ); - - // Associate current call in the invite session - inv->mod_data[getModId() ] = call; - - status = pjsip_inv_invite ( inv, &tdata ); - PJ_ASSERT_RETURN ( status == PJ_SUCCESS, false ); - - // Associate current invite session in the call - call->setInvSession ( inv ); - - status = pjsip_inv_send_msg ( inv, tdata ); - if ( status != PJ_SUCCESS ) - { - return false; - } - - return true; -} - -std::string SIPVoIPLink::getSipTo ( const std::string& to_url, std::string hostname ) -{ - // Form the From header field basis on configuration panel - //bool isRegistered = (_eXosipRegID == EXOSIP_ERROR_STD) ? false : true; - - // add a @host if we are registered and there is no one inside the url - if ( to_url.find ( "@" ) == std::string::npos ) // && isRegistered) { - { - if ( !hostname.empty() ) - { - return SIPToHeader ( to_url + "@" + hostname ); - } - } - return SIPToHeader ( to_url ); -} - -std::string SIPVoIPLink::SIPToHeader ( const std::string& to ) -{ - if ( to.find ( "sip:" ) == std::string::npos ) - { - return ( "sip:" + to ); - } - else - { - return to; - } + if (call==0) { + _debug ("! SIP Error: Call doesn't exist\n"); + return false; + } + + _debug ("- SIP Action: Cancel call %s [cid: %3d]\n", id.data(), call->getCid()); + + terminateOneCall (id); + removeCall (id); + + return true; } bool -SIPVoIPLink::SIPCheckUrl ( const std::string& url UNUSED ) +SIPVoIPLink::onhold (const CallID& id) { - return true; -} -void -SIPVoIPLink::SIPCallServerFailure ( SIPCall *call ) -{ - //if (!event->response) { return; } - //switch(event->response->status_code) { - //case SIP_SERVICE_UNAVAILABLE: // 500 - //case SIP_BUSY_EVRYWHERE: // 600 - //case SIP_DECLINE: // 603 - //SIPCall* call = findSIPCallWithCid(event->cid); - if ( call != 0 ) - { - _debug ( "Server error!\n" ); - CallID id = call->getCallId(); - Manager::instance().callFailure ( id ); - terminateOneCall ( id ); - removeCall ( id ); - } - //break; - //} -} + pj_status_t status; + SIPCall* call; -void -SIPVoIPLink::SIPCallClosed ( SIPCall *call ) -{ + call = getSIPCall (id); + + if (call==0) { + _debug ("! SIP Error: call doesn't exist\n"); + return false; + } + + + // Stop sound + call->setAudioStart (false); + + call->setState (Call::Hold); + _debug ("* SIP Info: Stopping AudioRTP for onhold action\n"); - // it was without did before - //SIPCall* call = findSIPCallWithCid(event->cid); - if ( !call ) { return; } + _audiortp->closeRtpSession(); - CallID id = call->getCallId(); - //call->setDid(event->did); - if ( Manager::instance().isCurrentCall ( id ) ) - { - call->setAudioStart ( false ); - _debug ( "* SIP Info: Stopping AudioRTP when closing\n" ); - _audiortp->closeRtpSession(); - } - _debug ( "After close RTP\n" ); - Manager::instance().peerHungupCall ( id ); - terminateOneCall ( id ); - removeCall ( id ); - _debug ( "After remove call ID\n" ); + /* Create re-INVITE with new offer */ + status = inv_session_reinvite (call, "sendonly"); + + if (status != PJ_SUCCESS) + return false; + + return true; } -void -SIPVoIPLink::SIPCallReleased ( SIPCall *call ) +int SIPVoIPLink::inv_session_reinvite (SIPCall *call, std::string direction) { - // do cleanup if exists - // only cid because did is always 0 in these case.. - //SIPCall* call = findSIPCallWithCid(event->cid); - if ( !call ) { return; } - // if we are here.. something when wrong before... - _debug ( "SIP call release\n" ); - CallID id = call->getCallId(); - Manager::instance().callFailure ( id ); - terminateOneCall ( id ); - removeCall ( id ); -} + pj_status_t status; + pjsip_tx_data *tdata; + pjmedia_sdp_session *local_sdp; + pjmedia_sdp_attr *attr; + local_sdp = call->getLocalSDP()->get_local_sdp_session(); -void -SIPVoIPLink::SIPCallAnswered ( SIPCall *call, pjsip_rx_data *rdata ) -{ + if (local_sdp == NULL) { + _debug ("! SIP Failure: unable to find local_sdp\n"); + return !PJ_SUCCESS; + } + + // reinvite only if connected + // Build the local SDP offer + status = call->getLocalSDP()->create_initial_offer(); - _debug ( "SIPCallAnswered\n" ); + if (status != PJ_SUCCESS) + return 1; // !PJ_SUCCESS - pjmedia_sdp_session *r_sdp; + pjmedia_sdp_media_remove_all_attr (local_sdp->media[0], "sendrecv"); - if ( !call ) - { - _debug ( "! SIP Failure: unknown call\n" ); - return; - } + attr = pjmedia_sdp_attr_create (_pool, direction.c_str(), NULL); - if ( call->getConnectionState() != Call::Connected ) - { - _debug ( "Get remote SDP from offer\n" ); - get_remote_sdp_from_offer ( rdata, &r_sdp ); - if ( r_sdp==NULL ) - { - _debug ( "SIP Failure: no remote sdp session\n" ); - return; - } - _debug ( "Get remote media information from offer\n" ); - call->getLocalSDP()->fetch_media_transport_info_from_remote_sdp ( r_sdp ); + pjmedia_sdp_media_add_attr (local_sdp->media[0], attr); - // _audiortp->getRTX()->setRtpSessionRemoteIp(); + // Build the reinvite request - _debug ( "Update call state , id = %s\n", call->getCallId().c_str() ); - call->setConnectionState ( Call::Connected ); - call->setState ( Call::Active ); + status = pjsip_inv_reinvite (call->getInvSession(), NULL, + local_sdp, &tdata); - Manager::instance().peerAnsweredCall ( call->getCallId() ); - if (Manager::instance().isCurrentCall(call->getCallId())) - { - /* - _debug("CREATE NEW RTP SESSION FROM SIPCALLANSWERED\n"); - try { - _audiortp->createNewSession (call); - call->setAudioStart(true); - } catch (...) { - _debug("Failed to create rtp thread from answer\n"); - } - */ - - call->setAudioStart(true); + if (status != PJ_SUCCESS) + return 1; // !PJ_SUCCESS - _audiortp->start(); + // Send it + status = pjsip_inv_send_msg (call->getInvSession(), tdata); - } + if (status != PJ_SUCCESS) + return 1; // !PJ_SUCCESS - } - else - { - _debug ( "* SIP Info: Answering call (on/off hold to send ACK)\n" ); - } + return PJ_SUCCESS; } -SIPCall* -SIPVoIPLink::getSIPCall ( const CallID& id ) +bool +SIPVoIPLink::offhold (const CallID& id) { - Call* call = getCall ( id ); - if ( call ) - { - return dynamic_cast<SIPCall*> ( call ); - } - return NULL; -} + SIPCall *call; + pj_status_t status; + call = getSIPCall (id); -void SIPVoIPLink::setStunServer ( const std::string &server ) -{ - if ( server != "" ) - { + if (call==0) { + _debug ("! SIP Error: Call doesn't exist\n"); + return false; + } - useStun ( true ); - _stunServer = server; - } - else - { - useStun ( false ); - _stunServer = std::string ( "" ); - } -} + try { + _audiortp->createNewSession (call); + } catch (...) { + _debug ("! SIP Failure: Unable to create RTP Session (%s:%d)\n", __FILE__, __LINE__); + } -bool SIPVoIPLink::new_ip_to_ip_call ( const CallID& id, const std::string& to ) -{ - SIPCall *call; - pj_status_t status; - std::string uri_from, uri_to, hostname; - std::ostringstream uri_contact; - pj_str_t from, str_to, contact; - pjsip_dialog *dialog; - pjsip_inv_session *inv; - pjsip_tx_data *tdata; + /* Create re-INVITE with new offer */ + status = inv_session_reinvite (call, "sendrecv"); - /* Create the call */ - call = new SIPCall ( id, Call::Outgoing, _pool ); + if (status != PJ_SUCCESS) + return false; - if ( call ) - { + // Enable audio + _debug ("* SIP Info: Starting AudioRTP when offhold\n"); - call->setCallConfiguration ( Call::IPtoIP ); - call->setPeerNumber ( getSipTo ( to, getLocalIPAddress() ) ); + call->setState (Call::Active); - // Generate the from URI - hostname = pj_gethostname()->ptr; - uri_from = "sip:" + hostname + "@" + getLocalIPAddress() ; + // it's sure that this is the current call id... - // Generate the from URI - uri_to = "sip:" + to.substr ( 4, to.length() ); + _audiortp->start(); - _debug ( "get local ip address: %s \n", getLocalIPAddress().c_str() ); - // Generate the to URI - setCallAudioLocal ( call, getLocalIPAddress(), useStun(), getStunServer() ); + call->setAudioStart (true); - call->initRecFileName(); + return true; +} - // Building the local SDP offer - call->getLocalSDP()->set_ip_address ( getLocalIP() ); - call->getLocalSDP()->create_initial_offer(); - - try { - _audiortp->createNewSession (call); - } catch (...) { - _debug ( "! SIP Failure: Unable to create RTP Session in SIPVoIPLink::new_ip_to_ip_call (%s:%d)\n", __FILE__, __LINE__ ); - } - +bool +SIPVoIPLink::transfer (const CallID& id, const std::string& to) +{ - // Generate the contact URI - // uri_contact << "<" << uri_from << ":" << call->getLocalSDP()->get_local_extern_audio_port() << ">"; - uri_contact << "<" << uri_from << ":" << _localExternPort << ">"; + SIPCall *call; + std::string tmp_to; + pjsip_evsub *sub; + pjsip_tx_data *tdata; - // pjsip need the from and to information in pj_str_t format - pj_strdup2 ( _pool, &from, uri_from.data() ); - pj_strdup2 ( _pool, &str_to, uri_to.data() ); - pj_strdup2 ( _pool, &contact, uri_contact.str().data() ); + struct pjsip_evsub_user xfer_cb; + pj_status_t status; + pj_str_t dest; + AccountID account_id; + Account* account; - // create the dialog (UAC) - status = pjsip_dlg_create_uac ( pjsip_ua_instance(), &from, &contact, &str_to, NULL, &dialog ); - PJ_ASSERT_RETURN ( status == PJ_SUCCESS, false ); + call = getSIPCall (id); + call->stopRecording(); + account_id = Manager::instance().getAccountFromCall (id); + account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (account_id)); - // Create the invite session for this call - status = pjsip_inv_create_uac ( dialog, call->getLocalSDP()->get_local_sdp_session(), 0, &inv ); - PJ_ASSERT_RETURN ( status == PJ_SUCCESS, false ); + if (call==0) { + _debug ("! SIP Failure: Call doesn't exist\n"); + return false; + } - // Associate current call in the invite session - inv->mod_data[getModId() ] = call; + tmp_to = SIPToHeader (to); - status = pjsip_inv_invite ( inv, &tdata ); - PJ_ASSERT_RETURN ( status == PJ_SUCCESS, false ); + if (account) { + if (tmp_to.find ("@") == std::string::npos) { + tmp_to = tmp_to + "@" + account->getHostname(); + } + } - // Associate current invite session in the call - call->setInvSession ( inv ); + else { - status = pjsip_inv_send_msg ( inv, tdata ); - if ( status != PJ_SUCCESS ) - { - delete call; call = 0; - return false; - } + } - call->setConnectionState ( Call::Progressing ); - call->setState ( Call::Active ); - addCall ( call ); + _debug ("In transfer, tmp_to is %s\n", tmp_to.data()); - // _audiortp->start(); + pj_strdup2 (_pool, &dest, tmp_to.data()); - // call->setAudioStart ( true ); + /* Create xfer client subscription. */ + pj_bzero (&xfer_cb, sizeof (xfer_cb)); + xfer_cb.on_evsub_state = &xfer_func_cb; - return true; - } - else - return false; -} + status = pjsip_xfer_create_uac (call->getInvSession()->dlg, &xfer_cb, &sub); + if (status != PJ_SUCCESS) { + _debug ("UserAgent: Unable to create xfer -- %d\n", status); + return false; + } -/////////////////////////////////////////////////////////////////////////////// -// Private functions -/////////////////////////////////////////////////////////////////////////////// + /* Associate this voiplink of call with the client subscription + * We can not just associate call with the client subscription + * because after this function, we can not find the cooresponding + * voiplink from the call any more. But the voiplink is useful! + */ + pjsip_evsub_set_mod_data (sub, getModId(), this); + _debug ("SIP port listener = %i ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++", _localExternPort); -bool get_dns_server_addresses ( std::vector<std::string> *servers ) -{ + /* + * Create REFER request. + */ + status = pjsip_xfer_initiate (sub, &dest, &tdata); - int server_count, i; - std::vector<std::string> nameservers; - struct sockaddr_in current_server; - in_addr address; + if (status != PJ_SUCCESS) { + _debug ("UserAgent: Unable to create REFER request -- %d\n", status); + return false; + } - // Read configuration files - if ( res_init () != 0 ) - { - _debug ( "Resolver initialization failed\n" ); - return false; - } + /* Send. */ + status = pjsip_xfer_send_request (sub, tdata); - server_count = _res.nscount; - for ( i=0; i<server_count; i++ ) - { - current_server = ( struct sockaddr_in ) _res.nsaddr_list[i]; - address = current_server.sin_addr; - nameservers.push_back ( inet_ntoa ( address ) ); - } + if (status != PJ_SUCCESS) { + _debug ("UserAgent: Unable to send REFER request -- %d\n", status); + return false; + } - //nameservers.push_back ("192.168.50.3"); - *servers = nameservers; + return true; +} - return true; +bool SIPVoIPLink::transferStep2() +{ + _audiortp->closeRtpSession(); + return true; } -pj_status_t SIPVoIPLink::enable_dns_srv_resolver ( pjsip_endpoint *endpt, pj_dns_resolver **p_resv ) +bool +SIPVoIPLink::refuse (const CallID& id) { + SIPCall *call; + pj_status_t status; + pjsip_tx_data *tdata; - pj_status_t status; - pj_dns_resolver *resv; - std::vector <std::string> dns_servers; - pj_uint16_t port = 5353; - pjsip_resolver_t *res; - int scount, i; - // Create the DNS resolver instance - status = pjsip_endpt_create_resolver ( endpt, &resv ); - if ( status != PJ_SUCCESS ) - { - _debug ( "Error creating the DNS resolver instance\n" ); - return status; - } + call = getSIPCall (id); - if ( !get_dns_server_addresses ( &dns_servers ) ) - { - _debug ( "Error while fetching DNS information\n" ); - return -1; - } + if (call==0) { + _debug ("Call doesn't exist\n"); + return false; + } + + // can't refuse outgoing call or connected + if (!call->isIncoming() || call->getConnectionState() == Call::Connected) { + _debug ("It's not an incoming call, or it's already answered\n"); + return false; + } - // Build the nameservers list needed by pjsip - scount = dns_servers.size (); - pj_str_t nameservers[scount]; + // User refuse current call. Notify peer + status = pjsip_inv_end_session (call->getInvSession(), PJSIP_SC_DECLINE, NULL, &tdata); //603 - for ( i = 0; i<scount; i++ ) - { - nameservers[i] = pj_str ( ( char* ) dns_servers[i].c_str() ); - } + if (status != PJ_SUCCESS) + return false; - // Update the name servers for the DNS resolver - status = pj_dns_resolver_set_ns ( resv, scount, nameservers, NULL ); - if ( status != PJ_SUCCESS ) - { - _debug ( "Error updating the name servers for the DNS resolver\n" ); - return status; - } + status = pjsip_inv_send_msg (call->getInvSession(), tdata); - // Set the DNS resolver instance of the SIP resolver engine - status = pjsip_endpt_set_resolver ( endpt, resv ); - if ( status != PJ_SUCCESS ) - { - _debug ( "Error setting the DNS resolver instance of the SIP resolver engine\n" ); - return status; - } + if (status != PJ_SUCCESS) + return false; - *p_resv = resv; + call->getInvSession()->mod_data[getModId() ] = NULL; - return PJ_SUCCESS; + terminateOneCall (id); + return true; } - -bool SIPVoIPLink::pjsip_init() +void +SIPVoIPLink::setRecording (const CallID& id) { - pj_status_t status; - int errPjsip = 0; - int port; - pjsip_inv_callback inv_cb; - pj_str_t accepted; - std::string name_mod; - bool useStun; - validStunServer = true; - pj_dns_resolver *p_resv; - - name_mod = "sflphone"; - - // Init PJLIB: must be called before any call to the pjsip library - status = pj_init(); - // Use pjsip macros for sanity check - PJ_ASSERT_RETURN ( status == PJ_SUCCESS, 1 ); - - // Init PJLIB-UTIL library - status = pjlib_util_init(); - PJ_ASSERT_RETURN ( status == PJ_SUCCESS, 1 ); - - // Set the pjsip log level - pj_log_set_level ( PJ_LOG_LEVEL ); - - // Init PJNATH - status = pjnath_init(); - PJ_ASSERT_RETURN ( status == PJ_SUCCESS, 1 ); - - // Create a pool factory to allocate memory - pj_caching_pool_init ( &_cp, &pj_pool_factory_default_policy, 0 ); - - // Create memory pool for application. - _pool = pj_pool_create ( &_cp.factory, "sflphone", 4000, 4000, NULL ); - - if ( !_pool ) - { - _debug ( "UserAgent: Could not initialize memory pool\n" ); - return PJ_ENOMEM; - } - - // Create the SIP endpoint - status = pjsip_endpt_create ( &_cp.factory, pj_gethostname()->ptr, &_endpt ); - PJ_ASSERT_RETURN ( status == PJ_SUCCESS, 1 ); - - /* Start resolving STUN server */ - // if we useStun and we failed to receive something on port 5060, we try a random port - // If use STUN server, firewall address setup - if ( !loadSIPLocalIP() ) - { - _debug ( "UserAgent: Unable to determine network capabilities\n" ); - return false; - } - - port = _regPort; - - /* Retrieve the STUN configuration */ - useStun = Manager::instance().getConfigInt ( SIGNALISATION, SIP_USE_STUN ); - this->setStunServer ( Manager::instance().getConfigString ( SIGNALISATION, SIP_STUN_SERVER ) ); - this->useStun ( useStun!=0 ? true : false ); - - if ( useStun && !Manager::instance().behindNat ( getStunServer(), port ) ) - { - port = RANDOM_SIP_PORT; - if ( !Manager::instance().behindNat ( getStunServer(), port ) ) - { - _debug ( "UserAgent: Unable to check NAT setting\n" ); - validStunServer = false; - return false; // hoho we can't use the random sip port too... - } - } - - _localPort = port; - if ( useStun ) - { - // set by last behindNat() call (ish)... - stunServerResolve(); - _localExternAddress = Manager::instance().getFirewallAddress(); - _localExternPort = Manager::instance().getFirewallPort(); - errPjsip = createUDPServer(); - if ( errPjsip != 0 ) - { - _debug ( "UserAgent: Could not initialize SIP listener on port %d\n", port ); - return errPjsip; - } - } - else - { - _localExternAddress = _localIPAddress; - _localExternPort = _localPort; - errPjsip = createUDPServer(); - if ( errPjsip != 0 ) - { - _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(); - if ( errPjsip != 0 ) - { - _debug ( "UserAgent: Fail to initialize SIP listener on port %d\n", _localExternPort ); - return errPjsip; - } - } - } - - _debug ( "UserAgent: SIP Init -- listening on port %d\n", _localExternPort ); - - // 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 - pjsip_endpt_add_capability ( _endpt, &_mod_ua, PJSIP_H_ALLOW, NULL, PJ_ARRAY_SIZE ( allowed ), allowed ); - - // Register "application/sdp" in ACCEPT header - pjsip_endpt_add_capability ( _endpt, &_mod_ua, PJSIP_H_ACCEPT, NULL, 1, &accepted ); - - _debug ( "UserAgent: pjsip version %s for %s initialized\n", pj_get_version(), PJ_OS_NAME ); - - // Create the secondary thread to poll sip events - _evThread->start(); - - /* Done! */ - return PJ_SUCCESS; + SIPCall* call = getSIPCall (id); + + if (call) + call->setRecording(); + + // _audiortp->setRecording(); } -pj_status_t SIPVoIPLink::stunServerResolve ( void ) +bool +SIPVoIPLink::isRecording (const CallID& id) { - pj_str_t stun_adr; - pj_hostent he; - 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; + SIPCall* call = getSIPCall (id); + _debug ("call->isRecording() %i \n",call->isRecording()); + + if (call) + return call->isRecording(); + else + return false; +} - stun_server = getStunServer(); - // Initialize STUN configuration - pj_stun_config_init ( &stunCfg, &_cp.factory, 0, pjsip_endpt_get_ioqueue ( _endpt ), pjsip_endpt_get_timer_heap ( _endpt ) ); +std::string +SIPVoIPLink::getCurrentCodecName() +{ - stun_status = PJ_EPENDING; + SIPCall *call; + AudioCodec *ac = NULL; + std::string name = ""; - // Init STUN socket - pos = stun_server.find ( ':' ); - 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 ); - } + call = getSIPCall (Manager::instance().getCurrentCallId()); - if ( stun_status != PJ_SUCCESS ) - { - _debug ( "UserAgent: Unresolved stun server!\n" ); - stun_status = pj_gethostbyname ( &stun_adr, &he ); + if (call) + ac = call->getLocalSDP()->get_session_media(); - 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 ); - } - } + if (ac) + name = ac->getCodecName(); - return stun_status; + return name; } -int SIPVoIPLink::createUDPServer ( void ) +bool +SIPVoIPLink::carryingDTMFdigits (const CallID& id, char code) { - pj_status_t status; - pj_sockaddr_in bound_addr; - pjsip_host_port a_name; - char tmpIP[32]; - pj_sock_t sock; + SIPCall *call; + int duration; + const int body_len = 1000; + char *dtmf_body; + pj_status_t status; + pjsip_tx_data *tdata; + pj_str_t methodName, content; + pjsip_method method; + pjsip_media_type ctype; + call = getSIPCall (id); - // Init bound address to ANY - pj_memset ( &bound_addr, 0, sizeof ( bound_addr ) ); + if (call==0) { + _debug ("Call doesn't exist\n"); + return false; + } + duration = Manager::instance().getConfigInt (SIGNALISATION, PULSE_LENGTH); - 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 ) ); + dtmf_body = new char[body_len]; - // Create UDP-Server (default port: 5060) - strcpy ( tmpIP, _localExternAddress.data() ); - pj_strdup2 ( _pool, &a_name.host, tmpIP ); - a_name.port = ( pj_uint16_t ) _localExternPort; + snprintf (dtmf_body, body_len - 1, "Signal=%c\r\nDuration=%d\r\n", code, duration); + pj_strdup2 (_pool, &methodName, "INFO"); + pjsip_method_init_np (&method, &methodName); - 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 ); - } + /* Create request message. */ + status = pjsip_dlg_create_request (call->getInvSession()->dlg, &method, -1, &tdata); + if (status != PJ_SUCCESS) { + _debug ("UserAgent: Unable to create INFO request -- %d\n", status); + return false; + } - _debug ( "Transport initialized successfully! \n" ); - return PJ_SUCCESS; -} + /* Get MIME type */ + pj_strdup2 (_pool, &ctype.type, "application"); + pj_strdup2 (_pool, &ctype.subtype, "dtmf-relay"); + /* Create "application/dtmf-relay" message body. */ + pj_strdup2 (_pool, &content, dtmf_body); + tdata->msg->body = pjsip_msg_body_create (tdata->pool, &ctype.type, &ctype.subtype, &content); + if (tdata->msg->body == NULL) { + _debug ("UserAgent: Unable to create msg body!\n"); + pjsip_tx_data_dec_ref (tdata); + return false; + } -bool SIPVoIPLink::loadSIPLocalIP() -{ + /* Send the request. */ + status = pjsip_dlg_send_request (call->getInvSession()->dlg, tdata, getModId(), NULL); - bool returnValue = true; + if (status != PJ_SUCCESS) { + _debug ("UserAgent: Unable to send MESSAGE request -- %d\n", status); + return false; + } - if ( _localIPAddress == "127.0.0.1" ) - { - pj_sockaddr ip_addr; - if ( pj_gethostip ( pj_AF_INET(), &ip_addr ) != PJ_SUCCESS ) - { - // Update the registration state if no network capabilities found - _debug ( "UserAgent: Get host ip failed!\n" ); - returnValue = false; - } - else - { - _localIPAddress = std::string ( pj_inet_ntoa ( ip_addr.ipv4.sin_addr ) ); - _debug ( "UserAgent: Checking network, setting local IP address to: %s\n", _localIPAddress.data() ); - } - } - return returnValue; + return true; } -void SIPVoIPLink::busy_sleep ( unsigned msec ) +bool +SIPVoIPLink::SIPOutgoingInvite (SIPCall* call) { -#if defined(PJ_SYMBIAN) && PJ_SYMBIAN != 0 - /* Ideally we shouldn't call pj_thread_sleep() and rather - * CActiveScheduler::WaitForAnyRequest() here, but that will - * drag in Symbian header and it doesn't look pretty. - */ - pj_thread_sleep ( msec ); -#else - pj_time_val timeout, now, tv; - - pj_gettimeofday ( &timeout ); - timeout.msec += msec; - pj_time_val_normalize ( &timeout ); - - tv.sec = 0; - tv.msec = 10; - pj_time_val_normalize ( &tv ); - - do - { - pjsip_endpt_handle_events ( _endpt, &tv ); - pj_gettimeofday ( &now ); - } - while ( PJ_TIME_VAL_LT ( now, timeout ) ); -#endif + // If no SIP proxy setting for direct call with only IP address + if (!SIPStartCall (call, "")) { + _debug ("! SIP Failure: call not started\n"); + return false; + } + + return true; } -bool SIPVoIPLink::pjsip_shutdown ( void ) +bool +SIPVoIPLink::SIPStartCall (SIPCall* call, const std::string& subject UNUSED) { - if ( _endpt ) - { - _debug ( "UserAgent: Shutting down...\n" ); - busy_sleep ( 1000 ); - } + std::string strTo, strFrom; + pj_status_t status; + pjsip_dialog *dialog; + pjsip_tx_data *tdata; + pj_str_t from, to, contact; + AccountID id; + SIPAccount *account; + pjsip_inv_session *inv; - pj_thread_join ( thread ); - pj_thread_destroy ( thread ); - thread = NULL; + if (!call) + return false; - /* Destroy endpoint. */ - if ( _endpt ) - { - pjsip_endpt_destroy ( _endpt ); - _endpt = NULL; - } + id = Manager::instance().getAccountFromCall (call->getCallId()); - /* Destroy pool and pool factory. */ - if ( _pool ) - { - pj_pool_release ( _pool ); - _pool = NULL; - pj_caching_pool_destroy ( &_cp ); - } + // Get the basic information about the callee account + account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (id)); - /* Shutdown PJLIB */ - pj_shutdown(); + strTo = getSipTo (call->getPeerNumber(), account->getHostname()); - /* Done. */ -} + _debug (" To: %s\n", strTo.data()); -int getModId() -{ - return _mod_ua.id; -} + // Generate the from URI + strFrom = "sip:" + account->getUsername() + "@" + account->getHostname(); -void set_voicemail_info ( AccountID account, pjsip_msg_body *body ) -{ + _debug (" From: %s\n", strFrom.c_str()); - int voicemail, pos_begin, pos_end; - std::string voice_str = "Voice-Message: "; - std::string delimiter = "/"; - std::string msg_body, voicemail_str; + // pjsip need the from and to information in pj_str_t format + pj_strdup2 (_pool, &from, strFrom.data()); - _debug ( "UserAgent: checking the voice message!\n" ); - // The voicemail message is formated like that: - // Voice-Message: 1/0 . 1 is the number we want to retrieve in this case + pj_strdup2 (_pool, &to, strTo.data()); - // We get the notification body - msg_body = ( char* ) body->data; + pj_strdup2 (_pool, &contact, account->getContact().data()); - // We need the position of the first character of the string voice_str - pos_begin = msg_body.find ( voice_str ); - // We need the position of the delimiter - pos_end = msg_body.find ( delimiter ); + //_debug("%s %s %s\n", from.ptr, contact.ptr, to.ptr); + // create the dialog (UAC) + status = pjsip_dlg_create_uac (pjsip_ua_instance(), &from, + &contact, + &to, + NULL, + &dialog); - // So our voicemail number between the both index - try - { + if (status != PJ_SUCCESS) { + _debug ("UAC creation failed\n"); + return false; + } - voicemail_str = msg_body.substr ( pos_begin + voice_str.length(), pos_end - ( pos_begin + voice_str.length() ) ); - std::cout << "voicemail number : " << voicemail_str << std::endl; - voicemail = atoi ( voicemail_str.c_str() ); - } - catch ( std::out_of_range& e ) - { - std::cerr << e.what() << std::endl; - } + // Create the invite session for this call + status = pjsip_inv_create_uac (dialog, call->getLocalSDP()->get_local_sdp_session(), 0, &inv); - // We need now to notify the manager - if ( voicemail != 0 ) - Manager::instance().startVoiceMessageNotification ( account, voicemail ); -} + PJ_ASSERT_RETURN (status == PJ_SUCCESS, false); -void SIPVoIPLink::handle_reinvite ( SIPCall *call ) -{ - - // Close the previous RTP session - _audiortp->closeRtpSession (); - call->setAudioStart ( false ); + // Set auth information + pjsip_auth_clt_set_credentials (&dialog->auth_sess, 1, account->getCredInfo()); - _debug("Create new rtp session from handle_reinvite \n"); - try { - _audiortp->createNewSession (call); - } catch (...) { - _debug ( "! SIP Failure: Unable to create RTP Session (%s:%d)\n", __FILE__, __LINE__ ); - } + // Associate current call in the invite session + inv->mod_data[getModId() ] = call; - _audiortp->start(); + status = pjsip_inv_invite (inv, &tdata); - call->setAudioStart ( true ); - + PJ_ASSERT_RETURN (status == PJ_SUCCESS, false); -} + // Associate current invite session in the call + call->setInvSession (inv); + status = pjsip_inv_send_msg (inv, tdata); -/*******************************/ -/* CALLBACKS IMPLEMENTATION */ -/*******************************/ + if (status != PJ_SUCCESS) { + return false; + } -void call_on_state_changed ( pjsip_inv_session *inv, pjsip_event *e ) -{ - - _debug("--------------------- call_on_state_changed --------------------- %i\n", inv->state); - - SIPCall *call; - AccountID accId; - SIPVoIPLink *link; - pjsip_rx_data *rdata; - - - /* Retrieve the call information */ - call = reinterpret_cast<SIPCall*> ( inv->mod_data[_mod_ua.id] ); - if ( !call ) - return; - - //Retrieve the body message - rdata = e->body.tsx_state.src.rdata; - - - /* 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; - - switch ( call->getInvSession()->state ) - { - case PJSIP_INV_STATE_NULL: - case PJSIP_INV_STATE_CALLING: - /* Do nothing */ - break; - - case PJSIP_INV_STATE_EARLY: - case PJSIP_INV_STATE_CONNECTING: - st_code = e->body.tsx_state.tsx->status_code; - ev_state = PJSIP_EVSUB_STATE_ACTIVE; - break; - - case PJSIP_INV_STATE_CONFIRMED: - /* When state is confirmed, send the final 200/OK and terminate - * subscription. - */ - st_code = e->body.tsx_state.tsx->status_code; - ev_state = PJSIP_EVSUB_STATE_TERMINATED; - break; - - case PJSIP_INV_STATE_DISCONNECTED: - st_code = e->body.tsx_state.tsx->status_code; - ev_state = PJSIP_EVSUB_STATE_TERMINATED; - break; - - case PJSIP_INV_STATE_INCOMING: - /* Nothing to do. Just to keep gcc from complaining about - * unused enums. - */ - break; - } - - if ( st_code != -1 ) - { - pjsip_tx_data *tdata; - pj_status_t status; - - status = pjsip_xfer_notify ( call->getXferSub(), - ev_state, st_code, - NULL, &tdata ); - if ( status != PJ_SUCCESS ) - { - _debug ( "UserAgent: Unable to create NOTIFY -- %d\n", status ); - } - else - { - status = pjsip_xfer_send_request ( call->getXferSub(), tdata ); - if ( status != PJ_SUCCESS ) - { - _debug ( "UserAgent: Unable to send NOTIFY -- %d\n", status ); - } - } - } - } - else - { - - // 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 ); - Manager::instance().peerRingingCall ( call->getCallId() ); - } - - // We receive a ACK - The connection is established - else if ( inv->state == PJSIP_INV_STATE_CONFIRMED ) - { - - /* If the call is a direct IP-to-IP call */ - 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 ) - link->SIPCallAnswered ( call, rdata ); - } - - else if ( inv->state == PJSIP_INV_STATE_DISCONNECTED ) - { - int count = 0; - _debug("------------------- Call disconnected ---------------------\n"); - _debug("State: %i, Disconnection cause: %i\n", inv->state, inv->cause); - switch ( inv->cause ) - { - /* The call terminates normally - BYE / CANCEL */ - case PJSIP_SC_OK: - case PJSIP_SC_DECLINE: - case PJSIP_SC_REQUEST_TERMINATED: - - accId = Manager::instance().getAccountFromCall ( call->getCallId() ); - link = dynamic_cast<SIPVoIPLink *> ( Manager::instance().getAccountLink ( accId ) ); - if ( link ) - { - link->SIPCallClosed ( call ); - } - break; - - /* The call connection failed */ - case PJSIP_SC_NOT_FOUND: /* peer not found */ - 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 ) ); - if ( link ) - { - link->SIPCallServerFailure ( call ); - } - break; - default: - _debug ( "sipvoiplink.cpp - line 1635 : Unhandled call state. This is probably a bug.\n" ); - break; - } - } - - - } -} - -void call_on_media_update ( pjsip_inv_session *inv, pj_status_t status ) -{ - - _debug("--------------------- call_on_media_update --------------------- \n"); - - AccountID accId; - SIPVoIPLink *link; - - const pjmedia_sdp_session *r_sdp; - SIPCall *call; - - if ( status != PJ_SUCCESS ) - { - _debug ( "Error while negociating the offer\n" ); - return; - } - - // Get the new sdp, result of the negociation - pjmedia_sdp_neg_get_active_local ( inv->neg, &r_sdp ); - - call = reinterpret_cast<SIPCall *> ( inv->mod_data[getModId() ] ); - - if(!call){_debug("Call declined by peer, SDP negociation stopped\n"); return;} - - // Clean the resulting sdp offer to create a new one (in case of a reinvite) - call->getLocalSDP()->clean_session_media(); - // Set the fresh negociated one - call->getLocalSDP()->set_negociated_offer ( r_sdp ); - // call->getLocalSDP()->fetch_media_transport_info_from_remote_sdp( r_sdp ); - // call->getLocalSDP()->fetch_remote_ip_from_sdp( r_sdp ); - // call->getLocalSDP()->fetch_remote_audio_port_from_sdp( r_sdp ); - - accId = Manager::instance().getAccountFromCall ( call->getCallId() ); - link = dynamic_cast<SIPVoIPLink *> ( Manager::instance().getAccountLink ( accId ) ); - - if(!link){_debug("No Voip Account Link, impossible to init RTP session with SDP info"); return;} - - if (call->getState() != Call::Hold) - { - _debug("Set media parameters in RTP session\n"); - // link->_audiortp->getRTX()->setRtpSessionMedia(); - // link->_audiortp->getRTX()->setRtpSessionRemoteIp(); - - // link->_audiortp->start(); - - // call->setAudioStart ( true ); - // link->_audiortp->start(); - } - else { - _debug("Didn't set RTP parameters since call is on hold\n"); - } - - -} - -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 --------------------- %i\n", 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 **/ - onCallTransfered ( inv, e->body.tsx_state.src.rdata ); - } -} - -void regc_cb ( struct pjsip_regc_cbparam *param ) + return true; +} + +std::string SIPVoIPLink::getSipTo (const std::string& to_url, std::string hostname) { + // Form the From header field basis on configuration panel + //bool isRegistered = (_eXosipRegID == EXOSIP_ERROR_STD) ? false : true; + + // add a @host if we are registered and there is no one inside the url + if (to_url.find ("@") == std::string::npos) { // && isRegistered) { + if (!hostname.empty()) { + return SIPToHeader (to_url + "@" + hostname); + } + } - //AccountID *id = static_cast<AccountID *> (param->token); - SIPAccount *account; + return SIPToHeader (to_url); +} - //_debug("UserAgent: Account ID is %s, Register result: %d, Status: %d\n", id->data(), param->status, param->code); - account = static_cast<SIPAccount *> ( param->token ); - if ( !account ) - return; +std::string SIPVoIPLink::SIPToHeader (const std::string& to) +{ + if (to.find ("sip:") == std::string::npos) { + return ("sip:" + to); + } else { + return to; + } +} - if ( param->status == PJ_SUCCESS ) - { - if ( param->code < 0 || param->code >= 300 ) - { - /* Sometimes, the status is OK, but we still failed. - * So checking the code for real result - */ - _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; - } - account->setRegister ( false ); - } - else - { - // Registration/Unregistration is success +bool +SIPVoIPLink::SIPCheckUrl (const std::string& url UNUSED) +{ + return true; +} - if ( account->isRegister() ) - account->setRegistrationState ( Registered ); - else - { - account->setRegistrationState ( Unregistered ); - account->setRegister ( false ); - } - } - } - else - { - account->setRegistrationState ( ErrorAuth ); - account->setRegister ( false ); - } +void +SIPVoIPLink::SIPCallServerFailure (SIPCall *call) +{ + //if (!event->response) { return; } + //switch(event->response->status_code) { + //case SIP_SERVICE_UNAVAILABLE: // 500 + //case SIP_BUSY_EVRYWHERE: // 600 + //case SIP_DECLINE: // 603 + //SIPCall* call = findSIPCallWithCid(event->cid); + if (call != 0) { + _debug ("Server error!\n"); + CallID id = call->getCallId(); + Manager::instance().callFailure (id); + terminateOneCall (id); + removeCall (id); + } + //break; + //} } -pj_bool_t -mod_on_rx_request ( pjsip_rx_data *rdata ) -{ - - - pj_status_t status; - pj_str_t reason; - unsigned options = 0; - pjsip_dialog* dialog; - pjsip_tx_data *tdata; - AccountID account_id; - pjsip_uri *uri; - pjsip_sip_uri *sip_uri; - std::string userName, server, caller, callerServer, peerNumber; - SIPVoIPLink *link; - CallID id; - SIPCall* call; - pjsip_inv_session *inv; - pjmedia_sdp_session *r_sdp; - - // voicemail part - std::string method_name; - std::string request; - - // Handle the incoming call invite in this function - _debug ( "UserAgent: Callback on_rx_request is involved! \n" ); - - /* First, let's got the username and server name from the invite. - * We will use them to detect which account is the callee. - */ - uri = rdata->msg_info.to->uri; - sip_uri = ( pjsip_sip_uri * ) pjsip_uri_get_uri ( uri ); - - userName = std::string ( sip_uri->user.ptr, sip_uri->user.slen ); - server = std::string ( sip_uri->host.ptr, sip_uri->host.slen ); - - std::cout << userName << " ------------------ " << server << std::endl; - - // Get the account id of callee from username and server - account_id = Manager::instance().getAccountIdFromNameAndServer ( userName, server ); - - /* If we don't find any account to receive the call */ - if ( account_id == AccountNULL ) - { - _debug ( "UserAgent: Username %s doesn't match any account!\n",userName.c_str() ); - //return false; - } - - /* Get the voip link associated to the incoming call */ - /* The account must before have been associated to the call in ManagerImpl */ - link = dynamic_cast<SIPVoIPLink *> ( Manager::instance().getAccountLink ( account_id ) ); - - /* If we can't find any voIP link to handle the incoming call */ - if ( link == 0 ) - { - _debug ( "ERROR: can not retrieve the voiplink from the account ID...\n" ); - return false; - } - - _debug ( "UserAgent: The receiver is : %s@%s\n", userName.data(), server.data() ); - _debug ( "UserAgent: The callee account id is %s\n", account_id.c_str() ); - - /* Now, it is the time to find the information of the caller */ - uri = rdata->msg_info.from->uri; - sip_uri = ( pjsip_sip_uri * ) pjsip_uri_get_uri ( uri ); - - - /* Retrieve only the fisrt characters */ - caller = std::string ( sip_uri->user.ptr, sip_uri->user.slen ); - callerServer = std::string ( sip_uri->host.ptr, sip_uri->host.slen ); - peerNumber = caller + "@" + callerServer; - - // 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 ... - request = rdata->msg_info.msg->line.req.method.name.ptr; - // Check if the message is a notification - if ( request.find ( method_name ) != ( size_t )-1 ) - { - /* Notify the right account */ - set_voicemail_info ( account_id, rdata->msg_info.msg->body ); - request.find ( method_name ); - } - pjsip_endpt_respond_stateless ( _endpt, rdata, PJSIP_SC_OK, NULL, NULL, NULL ); - return true; - } - - // Handle an OPTIONS message - if ( rdata->msg_info.msg->line.req.method.id == PJSIP_OPTIONS_METHOD ) - { - handle_incoming_options ( rdata ); - return true; - } - - // Respond statelessly any non-INVITE requests with 500 - if ( rdata->msg_info.msg->line.req.method.id != PJSIP_INVITE_METHOD ) - { - if ( rdata->msg_info.msg->line.req.method.id != PJSIP_ACK_METHOD ) - { - pj_strdup2 ( _pool, &reason, "user agent unable to handle this request " ); - pjsip_endpt_respond_stateless ( _endpt, rdata, PJSIP_SC_METHOD_NOT_ALLOWED, &reason, NULL, - NULL ); - return true; - } - } - - // Verify that we can handle the request - status = pjsip_inv_verify_request ( rdata, &options, NULL, NULL, _endpt, NULL ); - if ( status != PJ_SUCCESS ) - { - pj_strdup2 ( _pool, &reason, "user agent unable to handle this INVITE " ); - pjsip_endpt_respond_stateless ( _endpt, rdata, PJSIP_SC_METHOD_NOT_ALLOWED, &reason, NULL, - NULL ); - return true; - } - - /******************************************* URL HOOK *********************************************/ - - if ( Manager::instance().getConfigString ( HOOKS, URLHOOK_SIP_ENABLED ) == "1" ) - { - - std::string header_value; - - header_value = fetch_header_value ( rdata->msg_info.msg, Manager::instance().getConfigString ( HOOKS, URLHOOK_SIP_FIELD ) ); - - if (header_value.size () < header_value.max_size()) - { - if ( header_value!="" ) - { - urlhook->addAction ( header_value, - Manager::instance().getConfigString ( HOOKS, URLHOOK_COMMAND ) ); - } - } - else - throw length_error ("Url exceeds std::string max_size\n"); +void +SIPVoIPLink::SIPCallClosed (SIPCall *call) +{ - } - /************************************************************************************************/ + // it was without did before + //SIPCall* call = findSIPCallWithCid(event->cid); + if (!call) { + return; + } - // Generate a new call ID for the incoming call! - id = Manager::instance().getNewCallID(); - call = new SIPCall ( id, Call::Incoming, _pool ); + CallID id = call->getCallId(); - /* If an error occured at the call creation */ - if ( !call ) - { - _debug ( "UserAgent: unable to create an incoming call" ); - return false; - } + //call->setDid(event->did); - // 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() ); - // We retrieve the remote sdp offer in the rdata struct to begin the negociation - call->getLocalSDP()->set_ip_address ( link->getLocalIPAddress() ); - get_remote_sdp_from_offer ( rdata, &r_sdp ); -// _debug("r_sdp = %s\n", r_sdp); - status = call->getLocalSDP()->receiving_initial_offer ( r_sdp ); - if ( status!=PJ_SUCCESS ) - { - delete call; call=0; - return false; - } + if (Manager::instance().isCurrentCall (id)) { + call->setAudioStart (false); + _debug ("* SIP Info: Stopping AudioRTP when closing\n"); + _audiortp->closeRtpSession(); + } + _debug ("After close RTP\n"); - call->setConnectionState ( Call::Progressing ); - call->setPeerNumber ( peerNumber ); + Manager::instance().peerHungupCall (id); + terminateOneCall (id); + removeCall (id); + _debug ("After remove call ID\n"); +} - call->initRecFileName(); +void +SIPVoIPLink::SIPCallReleased (SIPCall *call) +{ + // do cleanup if exists + // only cid because did is always 0 in these case.. + //SIPCall* call = findSIPCallWithCid(event->cid); + if (!call) { + return; + } - // Notify UI there is an incoming call - if ( Manager::instance().incomingCall ( call, account_id ) ) - { - // Add this call to the callAccountMap in ManagerImpl - Manager::instance().getAccountLink ( account_id )->addCall ( call ); - } - else - { - // Fail to notify UI - delete call; - call = NULL; - _debug ( "UserAgent: Fail to notify UI!\n" ); - return false; - } - - - /* Create the local dialog (UAS) */ - status = pjsip_dlg_create_uas ( pjsip_ua_instance(), rdata, NULL, &dialog ); - if ( status != PJ_SUCCESS ) - { - pjsip_endpt_respond_stateless ( _endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, &reason, NULL, - NULL ); - return true; - } - - - // Specify media capability during invite session creation - status = pjsip_inv_create_uas ( dialog, rdata, call->getLocalSDP()->get_local_sdp_session(), 0, &inv ); - PJ_ASSERT_RETURN ( status == PJ_SUCCESS, 1 ); - - // Associate the call in the invite session - inv->mod_data[_mod_ua.id] = call; - - // Send a 180/Ringing response - status = pjsip_inv_initial_answer ( inv, rdata, PJSIP_SC_RINGING, NULL, NULL, &tdata ); - PJ_ASSERT_RETURN ( status == PJ_SUCCESS, 1 ); - - status = pjsip_inv_send_msg ( inv, tdata ); - PJ_ASSERT_RETURN ( status == PJ_SUCCESS, 1 ); - - // Associate invite session to the current call - call->setInvSession ( inv ); - - // Update the connection state - call->setConnectionState ( Call::Ringing ); - - /* Done */ - return true; - -} - -pj_bool_t mod_on_rx_response ( pjsip_rx_data *rdata UNUSED ) -{ - - return PJ_SUCCESS; -} - -void onCallTransfered ( pjsip_inv_session *inv, pjsip_rx_data *rdata ) -{ - - pj_status_t status; - pjsip_tx_data *tdata; - SIPCall *existing_call; - const pj_str_t str_refer_to = { ( char* ) "Refer-To", 8}; - const pj_str_t str_refer_sub = { ( char* ) "Refer-Sub", 9 }; - const pj_str_t str_ref_by = { ( char* ) "Referred-By", 11 }; - pjsip_generic_string_hdr *refer_to; - pjsip_generic_string_hdr *refer_sub; - pjsip_hdr *ref_by_hdr; - pj_bool_t no_refer_sub = PJ_FALSE; - char *uri; - std::string tmp; - pjsip_status_code code; - pjsip_evsub *sub; - - existing_call = ( SIPCall * ) inv->mod_data[_mod_ua.id]; - - /* Find the Refer-To header */ - refer_to = ( pjsip_generic_string_hdr* ) - pjsip_msg_find_hdr_by_name ( rdata->msg_info.msg, &str_refer_to, NULL ); - - if ( refer_to == NULL ) - { - /* Invalid Request. - * No Refer-To header! - */ - _debug ( "UserAgent: Received REFER without Refer-To header!\n" ); - pjsip_dlg_respond ( inv->dlg, rdata, 400, NULL, NULL, NULL ); - return; - } - - /* Find optional Refer-Sub header */ - refer_sub = ( pjsip_generic_string_hdr* ) - pjsip_msg_find_hdr_by_name ( rdata->msg_info.msg, &str_refer_sub, NULL ); - - if ( refer_sub ) - { - if ( !pj_strnicmp2 ( &refer_sub->hvalue, "true", 4 ) ==0 ) - no_refer_sub = PJ_TRUE; - } - - /* Find optional Referred-By header (to be copied onto outgoing INVITE - * request. - */ - ref_by_hdr = ( pjsip_hdr* ) - pjsip_msg_find_hdr_by_name ( rdata->msg_info.msg, &str_ref_by, - NULL ); - - /* Notify callback */ - code = PJSIP_SC_ACCEPTED; - - _debug ( "UserAgent: Call to %.*s is being transfered to %.*s\n", - ( int ) inv->dlg->remote.info_str.slen, - inv->dlg->remote.info_str.ptr, - ( int ) refer_to->hvalue.slen, - refer_to->hvalue.ptr ); - - if ( no_refer_sub ) - { - /* - * Always answer with 2xx. - */ - pjsip_tx_data *tdata; - const pj_str_t str_false = { ( char* ) "false", 5}; - pjsip_hdr *hdr; - - status = pjsip_dlg_create_response ( inv->dlg, rdata, code, NULL, - &tdata ); - if ( status != PJ_SUCCESS ) - { - _debug ( "UserAgent: Unable to create 2xx response to REFER -- %d\n", status ); - return; - } - - /* Add Refer-Sub header */ - hdr = ( pjsip_hdr* ) - pjsip_generic_string_hdr_create ( tdata->pool, &str_refer_sub, - &str_false ); - pjsip_msg_add_hdr ( tdata->msg, hdr ); - - - /* Send answer */ - status = pjsip_dlg_send_response ( inv->dlg, pjsip_rdata_get_tsx ( rdata ), - tdata ); - if ( status != PJ_SUCCESS ) - { - _debug ( "UserAgent: Unable to create 2xx response to REFER -- %d\n", status ); - return; - } - - /* Don't have subscription */ - sub = NULL; - - } - else - { - struct pjsip_evsub_user xfer_cb; - pjsip_hdr hdr_list; - - /* Init callback */ - pj_bzero ( &xfer_cb, sizeof ( xfer_cb ) ); - xfer_cb.on_evsub_state = &xfer_svr_cb; - - /* Init addiTHIS_FILE, THIS_FILE, tional header list to be sent with REFER response */ - pj_list_init ( &hdr_list ); - - /* Create transferee event subscription */ - status = pjsip_xfer_create_uas ( inv->dlg, &xfer_cb, rdata, &sub ); - if ( status != PJ_SUCCESS ) - { - _debug ( "UserAgent: Unable to create xfer uas -- %d\n", status ); - pjsip_dlg_respond ( inv->dlg, rdata, 500, NULL, NULL, NULL ); - return; - } - - /* If there's Refer-Sub header and the value is "true", send back - * Refer-Sub in the response with value "true" too. - */ - if ( refer_sub ) - { - const pj_str_t str_true = { ( char* ) "true", 4 }; - pjsip_hdr *hdr; - - hdr = ( pjsip_hdr* ) - pjsip_generic_string_hdr_create ( inv->dlg->pool, - &str_refer_sub, - &str_true ); - pj_list_push_back ( &hdr_list, hdr ); - - } - - /* Accept the REFER request, send 2xx. */ - pjsip_xfer_accept ( sub, rdata, code, &hdr_list ); - - /* Create initial NOTIFY request */ - status = pjsip_xfer_notify ( sub, PJSIP_EVSUB_STATE_ACTIVE, - 100, NULL, &tdata ); - if ( status != PJ_SUCCESS ) - { - _debug ( "UserAgent: Unable to create NOTIFY to REFER -- %d", status ); - return; - } - - /* Send initial NOTIFY request */ - status = pjsip_xfer_send_request ( sub, tdata ); - if ( status != PJ_SUCCESS ) - { - _debug ( "UserAgent: Unable to send NOTIFY to REFER -- %d\n", status ); - return; - } - } - - /* We're cheating here. - * We need to get a null terminated string from a pj_str_t. - * So grab the pointer from the hvalue and NULL terminate it, knowing - * that the NULL position will be occupied by a newline. - */ - uri = refer_to->hvalue.ptr; - uri[refer_to->hvalue.slen] = '\0'; - - /* Now make the outgoing call. */ - tmp = std::string ( uri ); - - if ( existing_call == NULL ) - { - _debug ( "UserAgent: Call doesn't exist!\n" ); - return; - } - - AccountID accId = Manager::instance().getAccountFromCall ( existing_call->getCallId() ); - CallID newCallId = Manager::instance().getNewCallID(); - - if ( !Manager::instance().outgoingCall ( accId, newCallId, tmp ) ) - { - - /* Notify xferer about the error (if we have subscription) */ - if ( sub ) - { - status = pjsip_xfer_notify ( sub, PJSIP_EVSUB_STATE_TERMINATED, - 500, NULL, &tdata ); - if ( status != PJ_SUCCESS ) - { - _debug ( "UserAgent: Unable to create NOTIFY to REFER -- %d\n", status ); - return; - } - status = pjsip_xfer_send_request ( sub, tdata ); - if ( status != PJ_SUCCESS ) - { - _debug ( "UserAgent: Unable to send NOTIFY to REFER -- %d\n", status ); - return; - } - } - return; - } - - SIPCall* newCall; - SIPVoIPLink *link = dynamic_cast<SIPVoIPLink *> ( Manager::instance().getAccountLink ( accId ) ); - if ( link ) - { - newCall = dynamic_cast<SIPCall *> ( link->getCall ( newCallId ) ); - if ( !newCall ) - { - _debug ( "UserAgent: can not find the call from sipvoiplink!\n" ); - return; - } - } - - if ( sub ) - { - /* Put the server subscription in inv_data. - * Subsequent state changed in pjsua_inv_on_state_changed() will be - * reported back to the server subscription. - */ - newCall->setXferSub ( sub ); - - /* Put the invite_data in the subscription. */ - pjsip_evsub_set_mod_data ( sub, _mod_ua.id, - newCall ); - } -} - - - -void xfer_func_cb ( pjsip_evsub *sub, pjsip_event *event ) -{ - - - PJ_UNUSED_ARG ( event ); - - /* - * When subscription is accepted (got 200/OK to REFER), check if - * subscription suppressed. - */ - if ( pjsip_evsub_get_state ( sub ) == PJSIP_EVSUB_STATE_ACCEPTED ) - { - - _debug ( "Transfer accepted! Waiting for notifications. \n" ); - - } - /* - * On incoming NOTIFY, notify application about call transfer progress. - */ - else if ( pjsip_evsub_get_state ( sub ) == PJSIP_EVSUB_STATE_ACTIVE || - pjsip_evsub_get_state ( sub ) == PJSIP_EVSUB_STATE_TERMINATED ) - { - pjsip_msg *msg; - pjsip_msg_body *body; - pjsip_status_line status_line; - pj_bool_t is_last; - pj_bool_t cont; - pj_status_t status; - - std::string noresource; - std::string ringing; - std::string request; - - noresource = "noresource"; - ringing = "Ringing"; - - - SIPVoIPLink *link = reinterpret_cast<SIPVoIPLink *> ( pjsip_evsub_get_mod_data ( sub, _mod_ua.id ) ); - - /* When subscription is terminated, clear the xfer_sub member of - * the inv_data. - */ - - if ( pjsip_evsub_get_state ( sub ) == PJSIP_EVSUB_STATE_TERMINATED ) - { - pjsip_evsub_set_mod_data ( sub, _mod_ua.id, NULL ); - _debug ( "UserAgent: Xfer client subscription terminated\n" ); - - } - - if ( !link || !event ) - { - /* Application is not interested with call progress status */ - _debug ( "UserAgent: Either link or event is empty!\n" ); - return; - } - - - - /* This better be a NOTIFY request */ - if ( event->type == PJSIP_EVENT_TSX_STATE && - event->body.tsx_state.type == PJSIP_EVENT_RX_MSG ) - { - - pjsip_rx_data *rdata; - - rdata = event->body.tsx_state.src.rdata; - - - /* Check if there's body */ - msg = rdata->msg_info.msg; - body = msg->body; - if ( !body ) - { - // if (call->getCallConfiguration () == Call::IPtoIP) { - // _debug("UserAgent: IptoIp NOTIFY without message body\n"); - // } - // else{ - _debug ( "UserAgent: Warning! Received NOTIFY without message body\n" ); - return; - // } - } + // if we are here.. something when wrong before... + _debug ("SIP call release\n"); + CallID id = call->getCallId(); + Manager::instance().callFailure (id); - /* Check for appropriate content */ - if ( pj_stricmp2 ( &body->content_type.type, "message" ) != 0 || - pj_stricmp2 ( &body->content_type.subtype, "sipfrag" ) != 0 ) - { - _debug ( "UserAgent: Warning! Received NOTIFY with non message/sipfrag content\n" ); - return; - } + terminateOneCall (id); - /* Try to parse the content */ - status = pjsip_parse_status_line ( ( char* ) body->data, body->len, - &status_line ); - if ( status != PJ_SUCCESS ) - { - _debug ( "UserAgent: Warning! Received NOTIFY with invalid message/sipfrag content\n" ); - return; - } + removeCall (id); +} - } - else - { - _debug ( "UserAgent: Set code to 500!\n" ); - status_line.code = 500; - status_line.reason = *pjsip_get_status_text ( 500 ); - } +void +SIPVoIPLink::SIPCallAnswered (SIPCall *call, pjsip_rx_data *rdata) +{ - if ( event->body.rx_msg.rdata->msg_info.msg_buf != NULL ) - { - request = event->body.rx_msg.rdata->msg_info.msg_buf; - if ( request.find ( noresource ) != -1 ) - { - _debug ( "UserAgent: NORESOURCE for transfer!\n" ); - link->transferStep2(); - pjsip_evsub_terminate ( sub, PJ_TRUE ); + _debug ("SIPCallAnswered\n"); - Manager::instance().transferFailed(); - return; - } + pjmedia_sdp_session *r_sdp; - if ( request.find ( ringing ) != -1 ) - { - _debug ( "UserAgent: transfered call RINGING!\n" ); - link->transferStep2(); - pjsip_evsub_terminate ( sub, PJ_TRUE ); + if (!call) { + _debug ("! SIP Failure: unknown call\n"); + return; + } - Manager::instance().transferSucceded(); - return; - } - } + if (call->getConnectionState() != Call::Connected) { + _debug ("Get remote SDP from offer\n"); + get_remote_sdp_from_offer (rdata, &r_sdp); + if (r_sdp==NULL) { + _debug ("SIP Failure: no remote sdp session\n"); + return; + } - // Get current call - SIPCall *call = dynamic_cast<SIPCall *> ( link->getCall ( Manager::instance().getCurrentCallId() ) ); - if ( !call ) - { - _debug ( "UserAgent: Call doesn't exit!\n" ); - return; - } + _debug ("Get remote media information from offer\n"); + call->getLocalSDP()->fetch_media_transport_info_from_remote_sdp (r_sdp); - /* Notify application */ - is_last = ( pjsip_evsub_get_state ( sub ) ==PJSIP_EVSUB_STATE_TERMINATED ); - cont = !is_last; + // _audiortp->getRTX()->setRtpSessionRemoteIp(); - if ( status_line.code/100 == 2 ) - { + _debug ("Update call state , id = %s\n", call->getCallId().c_str()); + call->setConnectionState (Call::Connected); + call->setState (Call::Active); - _debug ( "UserAgent: Try to stop rtp!\n" ); - pjsip_tx_data *tdata; + Manager::instance().peerAnsweredCall (call->getCallId()); - status = pjsip_inv_end_session ( call->getInvSession(), PJSIP_SC_GONE, NULL, &tdata ); - if ( status != PJ_SUCCESS ) - { - _debug ( "UserAgent: Fail to create end session msg!\n" ); - } - else - { - status = pjsip_inv_send_msg ( call->getInvSession(), tdata ); - if ( status != PJ_SUCCESS ) - _debug ( "UserAgent: Fail to send end session msg!\n" ); - } + if (Manager::instance().isCurrentCall (call->getCallId())) { + /* + _debug("CREATE NEW RTP SESSION FROM SIPCALLANSWERED\n"); + try { + _audiortp->createNewSession (call); + call->setAudioStart(true); + } catch (...) { + _debug("Failed to create rtp thread from answer\n"); + } + */ - link->transferStep2(); - cont = PJ_FALSE; - } + call->setAudioStart (true); - if ( !cont ) - { - pjsip_evsub_set_mod_data ( sub, _mod_ua.id, NULL ); - } + _audiortp->start(); - } + } + } else { + _debug ("* SIP Info: Answering call (on/off hold to send ACK)\n"); + } } -void xfer_svr_cb ( pjsip_evsub *sub, pjsip_event *event ) +SIPCall* +SIPVoIPLink::getSIPCall (const CallID& id) { + Call* call = getCall (id); + if (call) { + return dynamic_cast<SIPCall*> (call); + } - PJ_UNUSED_ARG ( event ); - - /* - * When subscription is terminated, clear the xfer_sub member of - * the inv_data. - */ - if ( pjsip_evsub_get_state ( sub ) == PJSIP_EVSUB_STATE_TERMINATED ) - { - SIPCall *call; + return NULL; +} - call = ( SIPCall* ) pjsip_evsub_get_mod_data ( sub, _mod_ua.id ); - if ( !call ) - return; - pjsip_evsub_set_mod_data ( sub, _mod_ua.id, NULL ); - call->setXferSub ( NULL ); +void SIPVoIPLink::setStunServer (const std::string &server) +{ + if (server != "") { - _debug ( "UserAgent: Xfer server subscription terminated\n" ); - } + useStun (true); + _stunServer = server; + } else { + useStun (false); + _stunServer = std::string (""); + } } -void on_rx_offer ( pjsip_inv_session *inv, const pjmedia_sdp_session *offer ) +bool SIPVoIPLink::new_ip_to_ip_call (const CallID& id, const std::string& to) { + SIPCall *call; + pj_status_t status; + std::string uri_from, uri_to, hostname; + std::ostringstream uri_contact; + pj_str_t from, str_to, contact; + pjsip_dialog *dialog; + pjsip_inv_session *inv; + pjsip_tx_data *tdata; + /* Create the call */ + call = new SIPCall (id, Call::Outgoing, _pool); -#ifdef CAN_REINVITE - _debug ( "reinvite SIP\n" ); + if (call) { - SIPCall *call; - pj_status_t status; - AccountID accId; - SIPVoIPLink *link; + call->setCallConfiguration (Call::IPtoIP); + call->setPeerNumber (getSipTo (to, getLocalIPAddress())); - call = ( SIPCall* ) inv->mod_data[getModId() ]; - if ( !call ) - return; + // Generate the from URI + hostname = pj_gethostname()->ptr; + uri_from = "sip:" + hostname + "@" + getLocalIPAddress() ; - accId = Manager::instance().getAccountFromCall ( call->getCallId() ); - link = dynamic_cast<SIPVoIPLink *> ( Manager::instance().getAccountLink ( accId ) ); + // Generate the from URI + uri_to = "sip:" + to.substr (4, to.length()); - call->getLocalSDP()->receiving_initial_offer ( ( pjmedia_sdp_session* ) offer ); - status=pjsip_inv_set_sdp_answer ( call->getInvSession(), call->getLocalSDP()->get_local_sdp_session() ); - if ( link ) - link->handle_reinvite ( call ); -#endif + _debug ("get local ip address: %s \n", getLocalIPAddress().c_str()); + // Generate the to URI + setCallAudioLocal (call, getLocalIPAddress(), useStun(), getStunServer()); -} + call->initRecFileName(); -void handle_incoming_options ( pjsip_rx_data *rdata ) -{ + // Building the local SDP offer + call->getLocalSDP()->set_ip_address (getLocalIP()); + call->getLocalSDP()->create_initial_offer(); + try { + _audiortp->createNewSession (call); + } catch (...) { + _debug ("! SIP Failure: Unable to create RTP Session in SIPVoIPLink::new_ip_to_ip_call (%s:%d)\n", __FILE__, __LINE__); + } - pjsip_tx_data *tdata; - pjsip_response_addr res_addr; - const pjsip_hdr *cap_hdr; - pj_status_t status; - /* Create basic response. */ - status = pjsip_endpt_create_response ( _endpt, rdata, PJSIP_SC_OK, NULL, &tdata ); - if ( status != PJ_SUCCESS ) - { - return; - } + // Generate the contact URI + // uri_contact << "<" << uri_from << ":" << call->getLocalSDP()->get_local_extern_audio_port() << ">"; + uri_contact << "<" << uri_from << ":" << _localExternPort << ">"; - /* Add Allow header */ - cap_hdr = pjsip_endpt_get_capability ( _endpt, PJSIP_H_ALLOW, NULL ); - if ( cap_hdr ) - { - pjsip_msg_add_hdr ( tdata->msg, ( pjsip_hdr* ) pjsip_hdr_clone ( tdata->pool, cap_hdr ) ); - } + // pjsip need the from and to information in pj_str_t format + pj_strdup2 (_pool, &from, uri_from.data()); - /* Add Accept header */ - cap_hdr = pjsip_endpt_get_capability ( _endpt, PJSIP_H_ACCEPT, NULL ); - if ( cap_hdr ) - { - pjsip_msg_add_hdr ( tdata->msg, ( pjsip_hdr* ) pjsip_hdr_clone ( tdata->pool, cap_hdr ) ); - } + pj_strdup2 (_pool, &str_to, uri_to.data()); - /* Add Supported header */ - cap_hdr = pjsip_endpt_get_capability ( _endpt, PJSIP_H_SUPPORTED, NULL ); - if ( cap_hdr ) - { - pjsip_msg_add_hdr ( tdata->msg, ( pjsip_hdr* ) pjsip_hdr_clone ( tdata->pool, cap_hdr ) ); - } + pj_strdup2 (_pool, &contact, uri_contact.str().data()); - /* Add Allow-Events header from the evsub module */ - cap_hdr = pjsip_evsub_get_allow_events_hdr ( NULL ); - if ( cap_hdr ) - { - pjsip_msg_add_hdr ( tdata->msg, ( pjsip_hdr* ) pjsip_hdr_clone ( tdata->pool, cap_hdr ) ); - } + // create the dialog (UAC) + status = pjsip_dlg_create_uac (pjsip_ua_instance(), &from, &contact, &str_to, NULL, &dialog); - /* Send response statelessly */ - pjsip_get_response_addr ( tdata->pool, rdata, &res_addr ); - status = pjsip_endpt_send_response ( _endpt, &res_addr, tdata, NULL, NULL ); - if ( status != PJ_SUCCESS ) - pjsip_tx_data_dec_ref ( tdata ); -} + PJ_ASSERT_RETURN (status == PJ_SUCCESS, false); -/*****************************************************************************************************************/ + // Create the invite session for this call + status = pjsip_inv_create_uac (dialog, call->getLocalSDP()->get_local_sdp_session(), 0, &inv); + PJ_ASSERT_RETURN (status == PJ_SUCCESS, false); -bool setCallAudioLocal ( SIPCall* call, std::string localIP, bool stun, std::string server ) -{ + // Associate current call in the invite session + inv->mod_data[getModId() ] = call; - // Setting Audio - unsigned int callLocalAudioPort = RANDOM_LOCAL_PORT; - unsigned int callLocalExternAudioPort = callLocalAudioPort; - if ( stun ) - { - // If use Stun server - if ( Manager::instance().behindNat ( server, callLocalAudioPort ) ) - { - callLocalExternAudioPort = Manager::instance().getFirewallPort(); - } - } - _debug ( " Setting local audio port to: %d\n", callLocalAudioPort ); - _debug ( " Setting local audio port (external) to: %d\n", callLocalExternAudioPort ); + status = pjsip_inv_invite (inv, &tdata); - // Set local audio port for SIPCall(id) - call->setLocalIp ( localIP ); - call->setLocalAudioPort ( callLocalAudioPort ); - call->setLocalExternAudioPort ( callLocalExternAudioPort ); + PJ_ASSERT_RETURN (status == PJ_SUCCESS, false); - call->getLocalSDP()->attribute_port_to_all_media ( callLocalExternAudioPort ); + // Associate current invite session in the call + call->setInvSession (inv); - return true; -} + status = pjsip_inv_send_msg (inv, tdata); -std::string fetch_header_value ( pjsip_msg *msg, std::string field ) -{ + if (status != PJ_SUCCESS) { + delete call; + call = 0; + return false; + } + + call->setConnectionState (Call::Progressing); + call->setState (Call::Active); + addCall (call); - pj_str_t name; - pjsip_generic_string_hdr * hdr; - std::string value, url; - size_t pos; + // _audiortp->start(); - std::cout << "fetch header value" << std::endl; + // call->setAudioStart ( true ); - /* Convert the field name into pjsip type */ - name = pj_str ( ( char* ) field.c_str() ); + return true; + } else + return false; +} - /* Get the header value and convert into string*/ - hdr = ( pjsip_generic_string_hdr* ) pjsip_msg_find_hdr_by_name ( msg, &name, NULL ); - if ( !hdr ) - return ""; +/////////////////////////////////////////////////////////////////////////////// +// Private functions +/////////////////////////////////////////////////////////////////////////////// + + +bool get_dns_server_addresses (std::vector<std::string> *servers) +{ + + int server_count, i; + std::vector<std::string> nameservers; + + struct sockaddr_in current_server; + in_addr address; + + // Read configuration files + + if (res_init () != 0) { + _debug ("Resolver initialization failed\n"); + return false; + } + + server_count = _res.nscount; + + for (i=0; i<server_count; i++) { + current_server = (struct sockaddr_in) _res.nsaddr_list[i]; + address = current_server.sin_addr; + nameservers.push_back (inet_ntoa (address)); + } + + //nameservers.push_back ("192.168.50.3"); + *servers = nameservers; + + return true; +} + +pj_status_t SIPVoIPLink::enable_dns_srv_resolver (pjsip_endpoint *endpt, pj_dns_resolver **p_resv) +{ + + pj_status_t status; + pj_dns_resolver *resv; + std::vector <std::string> dns_servers; + pj_uint16_t port = 5353; + pjsip_resolver_t *res; + int scount, i; + + // Create the DNS resolver instance + status = pjsip_endpt_create_resolver (endpt, &resv); + + if (status != PJ_SUCCESS) { + _debug ("Error creating the DNS resolver instance\n"); + return status; + } + + if (!get_dns_server_addresses (&dns_servers)) { + _debug ("Error while fetching DNS information\n"); + return -1; + } + + // Build the nameservers list needed by pjsip + scount = dns_servers.size (); + + pj_str_t nameservers[scount]; + + for (i = 0; i<scount; i++) { + nameservers[i] = pj_str ( (char*) dns_servers[i].c_str()); + } + + // Update the name servers for the DNS resolver + status = pj_dns_resolver_set_ns (resv, scount, nameservers, NULL); + + if (status != PJ_SUCCESS) { + _debug ("Error updating the name servers for the DNS resolver\n"); + return status; + } + + // Set the DNS resolver instance of the SIP resolver engine + status = pjsip_endpt_set_resolver (endpt, resv); + + if (status != PJ_SUCCESS) { + _debug ("Error setting the DNS resolver instance of the SIP resolver engine\n"); + return status; + } + + *p_resv = resv; + + return PJ_SUCCESS; + +} + + +bool SIPVoIPLink::pjsip_init() +{ + pj_status_t status; + int errPjsip = 0; + int port; + pjsip_inv_callback inv_cb; + pj_str_t accepted; + std::string name_mod; + bool useStun; + validStunServer = true; + pj_dns_resolver *p_resv; + + name_mod = "sflphone"; + + // Init PJLIB: must be called before any call to the pjsip library + status = pj_init(); + // Use pjsip macros for sanity check + PJ_ASSERT_RETURN (status == PJ_SUCCESS, 1); + + // Init PJLIB-UTIL library + status = pjlib_util_init(); + PJ_ASSERT_RETURN (status == PJ_SUCCESS, 1); + + // Set the pjsip log level + pj_log_set_level (PJ_LOG_LEVEL); + + // Init PJNATH + status = pjnath_init(); + PJ_ASSERT_RETURN (status == PJ_SUCCESS, 1); + + // Create a pool factory to allocate memory + pj_caching_pool_init (&_cp, &pj_pool_factory_default_policy, 0); + + // Create memory pool for application. + _pool = pj_pool_create (&_cp.factory, "sflphone", 4000, 4000, NULL); + + if (!_pool) { + _debug ("UserAgent: Could not initialize memory pool\n"); + return PJ_ENOMEM; + } + + // Create the SIP endpoint + status = pjsip_endpt_create (&_cp.factory, pj_gethostname()->ptr, &_endpt); + + PJ_ASSERT_RETURN (status == PJ_SUCCESS, 1); + + /* Start resolving STUN server */ + // if we useStun and we failed to receive something on port 5060, we try a random port + // If use STUN server, firewall address setup + if (!loadSIPLocalIP()) { + _debug ("UserAgent: Unable to determine network capabilities\n"); + return false; + } + + port = _regPort; + + /* Retrieve the STUN configuration */ + useStun = Manager::instance().getConfigInt (SIGNALISATION, SIP_USE_STUN); + this->setStunServer (Manager::instance().getConfigString (SIGNALISATION, SIP_STUN_SERVER)); + this->useStun (useStun!=0 ? true : false); + + if (useStun && !Manager::instance().behindNat (getStunServer(), port)) { + port = RANDOM_SIP_PORT; + + if (!Manager::instance().behindNat (getStunServer(), port)) { + _debug ("UserAgent: Unable to check NAT setting\n"); + validStunServer = false; + return false; // hoho we can't use the random sip port too... + } + } + + _localPort = port; + + if (useStun) { + // set by last behindNat() call (ish)... + stunServerResolve(); + _localExternAddress = Manager::instance().getFirewallAddress(); + _localExternPort = Manager::instance().getFirewallPort(); + errPjsip = createUDPServer(); + + if (errPjsip != 0) { + _debug ("UserAgent: Could not initialize SIP listener on port %d\n", port); + return errPjsip; + } + } else { + _localExternAddress = _localIPAddress; + _localExternPort = _localPort; + errPjsip = createUDPServer(); + + if (errPjsip != 0) { + _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(); + + if (errPjsip != 0) { + _debug ("UserAgent: Fail to initialize SIP listener on port %d\n", _localExternPort); + return errPjsip; + } + } + } + + _debug ("UserAgent: SIP Init -- listening on port %d\n", _localExternPort); + + // 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 + pjsip_endpt_add_capability (_endpt, &_mod_ua, PJSIP_H_ALLOW, NULL, PJ_ARRAY_SIZE (allowed), allowed); + + // Register "application/sdp" in ACCEPT header + pjsip_endpt_add_capability (_endpt, &_mod_ua, PJSIP_H_ACCEPT, NULL, 1, &accepted); + + _debug ("UserAgent: pjsip version %s for %s initialized\n", pj_get_version(), PJ_OS_NAME); + + // Create the secondary thread to poll sip events + _evThread->start(); + + /* Done! */ + return PJ_SUCCESS; +} + +pj_status_t SIPVoIPLink::stunServerResolve (void) +{ + pj_str_t stun_adr; + pj_hostent he; + 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; + + stun_server = getStunServer(); + + // 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; + + // Init STUN socket + pos = stun_server.find (':'); + + 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); + } + + if (stun_status != PJ_SUCCESS) { + _debug ("UserAgent: Unresolved stun server!\n"); + stun_status = pj_gethostbyname (&stun_adr, &he); + + 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); + } + } + + return stun_status; +} + +int SIPVoIPLink::createUDPServer (void) +{ + + pj_status_t status; + pj_sockaddr_in bound_addr; + pjsip_host_port a_name; + char tmpIP[32]; + pj_sock_t sock; + + + // 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, _localExternAddress.data()); + pj_strdup2 (_pool, &a_name.host, tmpIP); + a_name.port = (pj_uint16_t) _localExternPort; + + + 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; +} + + + + + +bool SIPVoIPLink::loadSIPLocalIP() +{ + + bool returnValue = true; + + if (_localIPAddress == "127.0.0.1") { + pj_sockaddr ip_addr; + + if (pj_gethostip (pj_AF_INET(), &ip_addr) != PJ_SUCCESS) { + // Update the registration state if no network capabilities found + _debug ("UserAgent: Get host ip failed!\n"); + returnValue = false; + } else { + _localIPAddress = std::string (pj_inet_ntoa (ip_addr.ipv4.sin_addr)); + _debug ("UserAgent: Checking network, setting local IP address to: %s\n", _localIPAddress.data()); + } + } + + return returnValue; +} + +void SIPVoIPLink::busy_sleep (unsigned msec) +{ +#if defined(PJ_SYMBIAN) && PJ_SYMBIAN != 0 + /* Ideally we shouldn't call pj_thread_sleep() and rather + * CActiveScheduler::WaitForAnyRequest() here, but that will + * drag in Symbian header and it doesn't look pretty. + */ + pj_thread_sleep (msec); +#else + pj_time_val timeout, now, tv; + + pj_gettimeofday (&timeout); + timeout.msec += msec; + pj_time_val_normalize (&timeout); + + tv.sec = 0; + tv.msec = 10; + pj_time_val_normalize (&tv); + + do { + pjsip_endpt_handle_events (_endpt, &tv); + pj_gettimeofday (&now); + } while (PJ_TIME_VAL_LT (now, timeout)); + +#endif +} + +bool SIPVoIPLink::pjsip_shutdown (void) +{ + if (_endpt) { + _debug ("UserAgent: Shutting down...\n"); + busy_sleep (1000); + } + + pj_thread_join (thread); + + pj_thread_destroy (thread); + thread = NULL; + + /* Destroy endpoint. */ + + if (_endpt) { + pjsip_endpt_destroy (_endpt); + _endpt = NULL; + } + + /* Destroy pool and pool factory. */ + if (_pool) { + pj_pool_release (_pool); + _pool = NULL; + pj_caching_pool_destroy (&_cp); + } + + /* Shutdown PJLIB */ + pj_shutdown(); + + /* Done. */ +} + +int getModId() +{ + return _mod_ua.id; +} + +void set_voicemail_info (AccountID account, pjsip_msg_body *body) +{ + + int voicemail, pos_begin, pos_end; + std::string voice_str = "Voice-Message: "; + std::string delimiter = "/"; + std::string msg_body, voicemail_str; + + _debug ("UserAgent: checking the voice message!\n"); + // The voicemail message is formated like that: + // Voice-Message: 1/0 . 1 is the number we want to retrieve in this case + + // We get the notification body + msg_body = (char*) body->data; + + // We need the position of the first character of the string voice_str + pos_begin = msg_body.find (voice_str); + // We need the position of the delimiter + pos_end = msg_body.find (delimiter); + + // So our voicemail number between the both index + + try { + + voicemail_str = msg_body.substr (pos_begin + voice_str.length(), pos_end - (pos_begin + voice_str.length())); + std::cout << "voicemail number : " << voicemail_str << std::endl; + voicemail = atoi (voicemail_str.c_str()); + } catch (std::out_of_range& e) { + std::cerr << e.what() << std::endl; + } + + // We need now to notify the manager + if (voicemail != 0) + Manager::instance().startVoiceMessageNotification (account, voicemail); +} + +void SIPVoIPLink::handle_reinvite (SIPCall *call) +{ + + // Close the previous RTP session + _audiortp->closeRtpSession (); + call->setAudioStart (false); + + _debug ("Create new rtp session from handle_reinvite \n"); + + try { + _audiortp->createNewSession (call); + } catch (...) { + _debug ("! SIP Failure: Unable to create RTP Session (%s:%d)\n", __FILE__, __LINE__); + } + + _audiortp->start(); + + call->setAudioStart (true); + + +} + + +/*******************************/ +/* CALLBACKS IMPLEMENTATION */ +/*******************************/ + +void call_on_state_changed (pjsip_inv_session *inv, pjsip_event *e) +{ + + _debug ("--------------------- call_on_state_changed --------------------- %i\n", inv->state); + + SIPCall *call; + AccountID accId; + SIPVoIPLink *link; + pjsip_rx_data *rdata; + + + /* Retrieve the call information */ + call = reinterpret_cast<SIPCall*> (inv->mod_data[_mod_ua.id]); + + if (!call) + return; + + //Retrieve the body message + rdata = e->body.tsx_state.src.rdata; + + + /* 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; + + switch (call->getInvSession()->state) { + + case PJSIP_INV_STATE_NULL: + + case PJSIP_INV_STATE_CALLING: + /* Do nothing */ + break; + + case PJSIP_INV_STATE_EARLY: + + case PJSIP_INV_STATE_CONNECTING: + st_code = e->body.tsx_state.tsx->status_code; + ev_state = PJSIP_EVSUB_STATE_ACTIVE; + break; + + case PJSIP_INV_STATE_CONFIRMED: + /* When state is confirmed, send the final 200/OK and terminate + * subscription. + */ + st_code = e->body.tsx_state.tsx->status_code; + ev_state = PJSIP_EVSUB_STATE_TERMINATED; + break; + + case PJSIP_INV_STATE_DISCONNECTED: + st_code = e->body.tsx_state.tsx->status_code; + ev_state = PJSIP_EVSUB_STATE_TERMINATED; + break; + + case PJSIP_INV_STATE_INCOMING: + /* Nothing to do. Just to keep gcc from complaining about + * unused enums. + */ + break; + } + + if (st_code != -1) { + pjsip_tx_data *tdata; + pj_status_t status; + + status = pjsip_xfer_notify (call->getXferSub(), + ev_state, st_code, + NULL, &tdata); + + if (status != PJ_SUCCESS) { + _debug ("UserAgent: Unable to create NOTIFY -- %d\n", status); + } else { + status = pjsip_xfer_send_request (call->getXferSub(), tdata); + + if (status != PJ_SUCCESS) { + _debug ("UserAgent: Unable to send NOTIFY -- %d\n", status); + } + } + } + } else { + + // 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); + Manager::instance().peerRingingCall (call->getCallId()); + } + + // We receive a ACK - The connection is established + else if (inv->state == PJSIP_INV_STATE_CONFIRMED) { + + /* If the call is a direct IP-to-IP call */ + 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) + link->SIPCallAnswered (call, rdata); + } + + else if (inv->state == PJSIP_INV_STATE_DISCONNECTED) { + int count = 0; + _debug ("------------------- Call disconnected ---------------------\n"); + _debug ("State: %i, Disconnection cause: %i\n", inv->state, inv->cause); + + switch (inv->cause) { + /* The call terminates normally - BYE / CANCEL */ + + case PJSIP_SC_OK: + + case PJSIP_SC_DECLINE: + + case PJSIP_SC_REQUEST_TERMINATED: + + accId = Manager::instance().getAccountFromCall (call->getCallId()); + link = dynamic_cast<SIPVoIPLink *> (Manager::instance().getAccountLink (accId)); + + if (link) { + link->SIPCallClosed (call); + } + + break; + + /* The call connection failed */ + + case PJSIP_SC_NOT_FOUND: /* peer not found */ + + 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)); + + if (link) { + link->SIPCallServerFailure (call); + } + + break; + + default: + _debug ("sipvoiplink.cpp - line 1635 : Unhandled call state. This is probably a bug.\n"); + break; + } + } + + + } +} + +void call_on_media_update (pjsip_inv_session *inv, pj_status_t status) +{ + + _debug ("--------------------- call_on_media_update --------------------- \n"); + + AccountID accId; + SIPVoIPLink *link; + + const pjmedia_sdp_session *r_sdp; + SIPCall *call; + + if (status != PJ_SUCCESS) { + _debug ("Error while negociating the offer\n"); + return; + } + + // Get the new sdp, result of the negociation + pjmedia_sdp_neg_get_active_local (inv->neg, &r_sdp); + + call = reinterpret_cast<SIPCall *> (inv->mod_data[getModId() ]); + + if (!call) { + _debug ("Call declined by peer, SDP negociation stopped\n"); + return; + } + + // Clean the resulting sdp offer to create a new one (in case of a reinvite) + call->getLocalSDP()->clean_session_media(); + + // Set the fresh negociated one + call->getLocalSDP()->set_negociated_offer (r_sdp); + + // call->getLocalSDP()->fetch_media_transport_info_from_remote_sdp( r_sdp ); + // call->getLocalSDP()->fetch_remote_ip_from_sdp( r_sdp ); + // call->getLocalSDP()->fetch_remote_audio_port_from_sdp( r_sdp ); + + accId = Manager::instance().getAccountFromCall (call->getCallId()); + + link = dynamic_cast<SIPVoIPLink *> (Manager::instance().getAccountLink (accId)); + + if (!link) { + _debug ("No Voip Account Link, impossible to init RTP session with SDP info"); + return; + } + + if (call->getState() != Call::Hold) { + _debug ("Set media parameters in RTP session\n"); + // link->_audiortp->getRTX()->setRtpSessionMedia(); + // link->_audiortp->getRTX()->setRtpSessionRemoteIp(); + + // link->_audiortp->start(); + + // call->setAudioStart ( true ); + // link->_audiortp->start(); + } else { + _debug ("Didn't set RTP parameters since call is on hold\n"); + } + + +} + +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 --------------------- %i\n", 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 **/ + onCallTransfered (inv, e->body.tsx_state.src.rdata); + } +} + +void regc_cb (struct pjsip_regc_cbparam *param) +{ + + //AccountID *id = static_cast<AccountID *> (param->token); + SIPAccount *account; + + //_debug("UserAgent: Account ID is %s, Register result: %d, Status: %d\n", id->data(), param->status, param->code); + account = static_cast<SIPAccount *> (param->token); + + if (!account) + return; + + if (param->status == PJ_SUCCESS) { + if (param->code < 0 || param->code >= 300) { + /* Sometimes, the status is OK, but we still failed. + * So checking the code for real result + */ + _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; + } + + account->setRegister (false); + } else { + // Registration/Unregistration is success + + if (account->isRegister()) + account->setRegistrationState (Registered); + else { + account->setRegistrationState (Unregistered); + account->setRegister (false); + } + } + } else { + account->setRegistrationState (ErrorAuth); + account->setRegister (false); + } + +} + +pj_bool_t +mod_on_rx_request (pjsip_rx_data *rdata) +{ + + + pj_status_t status; + pj_str_t reason; + unsigned options = 0; + pjsip_dialog* dialog; + pjsip_tx_data *tdata; + AccountID account_id; + pjsip_uri *uri; + pjsip_sip_uri *sip_uri; + std::string userName, server, caller, callerServer, peerNumber; + SIPVoIPLink *link; + CallID id; + SIPCall* call; + pjsip_inv_session *inv; + pjmedia_sdp_session *r_sdp; + + // voicemail part + std::string method_name; + std::string request; + + // Handle the incoming call invite in this function + _debug ("UserAgent: Callback on_rx_request is involved! \n"); + + /* First, let's got the username and server name from the invite. + * We will use them to detect which account is the callee. + */ + uri = rdata->msg_info.to->uri; + sip_uri = (pjsip_sip_uri *) pjsip_uri_get_uri (uri); + + userName = std::string (sip_uri->user.ptr, sip_uri->user.slen); + server = std::string (sip_uri->host.ptr, sip_uri->host.slen); + + std::cout << userName << " ------------------ " << server << std::endl; + + // Get the account id of callee from username and server + account_id = Manager::instance().getAccountIdFromNameAndServer (userName, server); + + /* If we don't find any account to receive the call */ + + if (account_id == AccountNULL) { + _debug ("UserAgent: Username %s doesn't match any account!\n",userName.c_str()); + //return false; + } + + /* Get the voip link associated to the incoming call */ + /* The account must before have been associated to the call in ManagerImpl */ + link = dynamic_cast<SIPVoIPLink *> (Manager::instance().getAccountLink (account_id)); + + /* If we can't find any voIP link to handle the incoming call */ + if (link == 0) { + _debug ("ERROR: can not retrieve the voiplink from the account ID...\n"); + return false; + } + + _debug ("UserAgent: The receiver is : %s@%s\n", userName.data(), server.data()); + + _debug ("UserAgent: The callee account id is %s\n", account_id.c_str()); + + /* Now, it is the time to find the information of the caller */ + uri = rdata->msg_info.from->uri; + sip_uri = (pjsip_sip_uri *) pjsip_uri_get_uri (uri); + + + /* Retrieve only the fisrt characters */ + caller = std::string (sip_uri->user.ptr, sip_uri->user.slen); + callerServer = std::string (sip_uri->host.ptr, sip_uri->host.slen); + peerNumber = caller + "@" + callerServer; + + // 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 ... + request = rdata->msg_info.msg->line.req.method.name.ptr; + // Check if the message is a notification + + if (request.find (method_name) != (size_t)-1) { + /* Notify the right account */ + set_voicemail_info (account_id, rdata->msg_info.msg->body); + request.find (method_name); + } + + pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_OK, NULL, NULL, NULL); + + return true; + } + + // Handle an OPTIONS message + if (rdata->msg_info.msg->line.req.method.id == PJSIP_OPTIONS_METHOD) { + handle_incoming_options (rdata); + return true; + } + + // Respond statelessly any non-INVITE requests with 500 + if (rdata->msg_info.msg->line.req.method.id != PJSIP_INVITE_METHOD) { + if (rdata->msg_info.msg->line.req.method.id != PJSIP_ACK_METHOD) { + pj_strdup2 (_pool, &reason, "user agent unable to handle this request "); + pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_METHOD_NOT_ALLOWED, &reason, NULL, + NULL); + return true; + } + } + + // Verify that we can handle the request + status = pjsip_inv_verify_request (rdata, &options, NULL, NULL, _endpt, NULL); + + if (status != PJ_SUCCESS) { + pj_strdup2 (_pool, &reason, "user agent unable to handle this INVITE "); + pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_METHOD_NOT_ALLOWED, &reason, NULL, + NULL); + return true; + } + + /******************************************* URL HOOK *********************************************/ + + if (Manager::instance().getConfigString (HOOKS, URLHOOK_SIP_ENABLED) == "1") { + + std::string header_value; + + header_value = fetch_header_value (rdata->msg_info.msg, Manager::instance().getConfigString (HOOKS, URLHOOK_SIP_FIELD)); + + if (header_value.size () < header_value.max_size()) { + if (header_value!="") { + urlhook->addAction (header_value, + Manager::instance().getConfigString (HOOKS, URLHOOK_COMMAND)); + } + } else + throw length_error ("Url exceeds std::string max_size\n"); + + } + + /************************************************************************************************/ + + // Generate a new call ID for the incoming call! + id = Manager::instance().getNewCallID(); + + call = new SIPCall (id, Call::Incoming, _pool); + + /* If an error occured at the call creation */ + if (!call) { + _debug ("UserAgent: unable to create an incoming call"); + return false; + } + + // 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()); + + // We retrieve the remote sdp offer in the rdata struct to begin the negociation + call->getLocalSDP()->set_ip_address (link->getLocalIPAddress()); + + get_remote_sdp_from_offer (rdata, &r_sdp); + +// _debug("r_sdp = %s\n", r_sdp); + status = call->getLocalSDP()->receiving_initial_offer (r_sdp); + + if (status!=PJ_SUCCESS) { + delete call; + call=0; + return false; + } + + + call->setConnectionState (Call::Progressing); + + call->setPeerNumber (peerNumber); + + call->initRecFileName(); + + // Notify UI there is an incoming call + + if (Manager::instance().incomingCall (call, account_id)) { + // Add this call to the callAccountMap in ManagerImpl + Manager::instance().getAccountLink (account_id)->addCall (call); + } else { + // Fail to notify UI + delete call; + call = NULL; + _debug ("UserAgent: Fail to notify UI!\n"); + return false; + } + + + /* Create the local dialog (UAS) */ + status = pjsip_dlg_create_uas (pjsip_ua_instance(), rdata, NULL, &dialog); + + if (status != PJ_SUCCESS) { + pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, &reason, NULL, + NULL); + return true; + } + + + // Specify media capability during invite session creation + status = pjsip_inv_create_uas (dialog, rdata, call->getLocalSDP()->get_local_sdp_session(), 0, &inv); + + PJ_ASSERT_RETURN (status == PJ_SUCCESS, 1); + + // Associate the call in the invite session + inv->mod_data[_mod_ua.id] = call; + + // Send a 180/Ringing response + status = pjsip_inv_initial_answer (inv, rdata, PJSIP_SC_RINGING, NULL, NULL, &tdata); + + PJ_ASSERT_RETURN (status == PJ_SUCCESS, 1); + + status = pjsip_inv_send_msg (inv, tdata); + + PJ_ASSERT_RETURN (status == PJ_SUCCESS, 1); + + // Associate invite session to the current call + call->setInvSession (inv); + + // Update the connection state + call->setConnectionState (Call::Ringing); + + /* Done */ + return true; + +} + +pj_bool_t mod_on_rx_response (pjsip_rx_data *rdata UNUSED) +{ + + return PJ_SUCCESS; +} + +void onCallTransfered (pjsip_inv_session *inv, pjsip_rx_data *rdata) +{ + + pj_status_t status; + pjsip_tx_data *tdata; + SIPCall *existing_call; + const pj_str_t str_refer_to = { (char*) "Refer-To", 8}; + const pj_str_t str_refer_sub = { (char*) "Refer-Sub", 9 }; + const pj_str_t str_ref_by = { (char*) "Referred-By", 11 }; + pjsip_generic_string_hdr *refer_to; + pjsip_generic_string_hdr *refer_sub; + pjsip_hdr *ref_by_hdr; + pj_bool_t no_refer_sub = PJ_FALSE; + char *uri; + std::string tmp; + pjsip_status_code code; + pjsip_evsub *sub; + + existing_call = (SIPCall *) inv->mod_data[_mod_ua.id]; + + /* Find the Refer-To header */ + refer_to = (pjsip_generic_string_hdr*) + pjsip_msg_find_hdr_by_name (rdata->msg_info.msg, &str_refer_to, NULL); + + if (refer_to == NULL) { + /* Invalid Request. + * No Refer-To header! + */ + _debug ("UserAgent: Received REFER without Refer-To header!\n"); + pjsip_dlg_respond (inv->dlg, rdata, 400, NULL, NULL, NULL); + return; + } + + /* Find optional Refer-Sub header */ + refer_sub = (pjsip_generic_string_hdr*) + pjsip_msg_find_hdr_by_name (rdata->msg_info.msg, &str_refer_sub, NULL); + + if (refer_sub) { + if (!pj_strnicmp2 (&refer_sub->hvalue, "true", 4) ==0) + no_refer_sub = PJ_TRUE; + } + + /* Find optional Referred-By header (to be copied onto outgoing INVITE + * request. + */ + ref_by_hdr = (pjsip_hdr*) + pjsip_msg_find_hdr_by_name (rdata->msg_info.msg, &str_ref_by, + NULL); + + /* Notify callback */ + code = PJSIP_SC_ACCEPTED; + + _debug ("UserAgent: Call to %.*s is being transfered to %.*s\n", + (int) inv->dlg->remote.info_str.slen, + inv->dlg->remote.info_str.ptr, + (int) refer_to->hvalue.slen, + refer_to->hvalue.ptr); + + if (no_refer_sub) { + /* + * Always answer with 2xx. + */ + pjsip_tx_data *tdata; + const pj_str_t str_false = { (char*) "false", 5}; + pjsip_hdr *hdr; + + status = pjsip_dlg_create_response (inv->dlg, rdata, code, NULL, + &tdata); + + if (status != PJ_SUCCESS) { + _debug ("UserAgent: Unable to create 2xx response to REFER -- %d\n", status); + return; + } + + /* Add Refer-Sub header */ + hdr = (pjsip_hdr*) + pjsip_generic_string_hdr_create (tdata->pool, &str_refer_sub, + &str_false); + + pjsip_msg_add_hdr (tdata->msg, hdr); + + + /* Send answer */ + status = pjsip_dlg_send_response (inv->dlg, pjsip_rdata_get_tsx (rdata), + tdata); + + if (status != PJ_SUCCESS) { + _debug ("UserAgent: Unable to create 2xx response to REFER -- %d\n", status); + return; + } + + /* Don't have subscription */ + sub = NULL; + + } else { + + struct pjsip_evsub_user xfer_cb; + pjsip_hdr hdr_list; + + /* Init callback */ + pj_bzero (&xfer_cb, sizeof (xfer_cb)); + xfer_cb.on_evsub_state = &xfer_svr_cb; + + /* Init addiTHIS_FILE, THIS_FILE, tional header list to be sent with REFER response */ + pj_list_init (&hdr_list); + + /* Create transferee event subscription */ + status = pjsip_xfer_create_uas (inv->dlg, &xfer_cb, rdata, &sub); + + if (status != PJ_SUCCESS) { + _debug ("UserAgent: Unable to create xfer uas -- %d\n", status); + pjsip_dlg_respond (inv->dlg, rdata, 500, NULL, NULL, NULL); + return; + } + + /* If there's Refer-Sub header and the value is "true", send back + * Refer-Sub in the response with value "true" too. + */ + if (refer_sub) { + const pj_str_t str_true = { (char*) "true", 4 }; + pjsip_hdr *hdr; + + hdr = (pjsip_hdr*) + pjsip_generic_string_hdr_create (inv->dlg->pool, + &str_refer_sub, + &str_true); + pj_list_push_back (&hdr_list, hdr); + + } + + /* Accept the REFER request, send 2xx. */ + pjsip_xfer_accept (sub, rdata, code, &hdr_list); + + /* Create initial NOTIFY request */ + status = pjsip_xfer_notify (sub, PJSIP_EVSUB_STATE_ACTIVE, + 100, NULL, &tdata); + + if (status != PJ_SUCCESS) { + _debug ("UserAgent: Unable to create NOTIFY to REFER -- %d", status); + return; + } + + /* Send initial NOTIFY request */ + status = pjsip_xfer_send_request (sub, tdata); + + if (status != PJ_SUCCESS) { + _debug ("UserAgent: Unable to send NOTIFY to REFER -- %d\n", status); + return; + } + } + + /* We're cheating here. + * We need to get a null terminated string from a pj_str_t. + * So grab the pointer from the hvalue and NULL terminate it, knowing + * that the NULL position will be occupied by a newline. + */ + uri = refer_to->hvalue.ptr; + + uri[refer_to->hvalue.slen] = '\0'; + + /* Now make the outgoing call. */ + tmp = std::string (uri); + + if (existing_call == NULL) { + _debug ("UserAgent: Call doesn't exist!\n"); + return; + } + + AccountID accId = Manager::instance().getAccountFromCall (existing_call->getCallId()); + + CallID newCallId = Manager::instance().getNewCallID(); + + if (!Manager::instance().outgoingCall (accId, newCallId, tmp)) { + + /* Notify xferer about the error (if we have subscription) */ + if (sub) { + status = pjsip_xfer_notify (sub, PJSIP_EVSUB_STATE_TERMINATED, + 500, NULL, &tdata); + + if (status != PJ_SUCCESS) { + _debug ("UserAgent: Unable to create NOTIFY to REFER -- %d\n", status); + return; + } + + status = pjsip_xfer_send_request (sub, tdata); + + if (status != PJ_SUCCESS) { + _debug ("UserAgent: Unable to send NOTIFY to REFER -- %d\n", status); + return; + } + } + + return; + } + + SIPCall* newCall; + + SIPVoIPLink *link = dynamic_cast<SIPVoIPLink *> (Manager::instance().getAccountLink (accId)); + + if (link) { + newCall = dynamic_cast<SIPCall *> (link->getCall (newCallId)); + + if (!newCall) { + _debug ("UserAgent: can not find the call from sipvoiplink!\n"); + return; + } + } + + if (sub) { + /* Put the server subscription in inv_data. + * Subsequent state changed in pjsua_inv_on_state_changed() will be + * reported back to the server subscription. + */ + newCall->setXferSub (sub); + + /* Put the invite_data in the subscription. */ + pjsip_evsub_set_mod_data (sub, _mod_ua.id, + newCall); + } +} + + + +void xfer_func_cb (pjsip_evsub *sub, pjsip_event *event) +{ + + + PJ_UNUSED_ARG (event); + + /* + * When subscription is accepted (got 200/OK to REFER), check if + * subscription suppressed. + */ + + if (pjsip_evsub_get_state (sub) == PJSIP_EVSUB_STATE_ACCEPTED) { + + _debug ("Transfer accepted! Waiting for notifications. \n"); + + } + + /* + * On incoming NOTIFY, notify application about call transfer progress. + */ + else if (pjsip_evsub_get_state (sub) == PJSIP_EVSUB_STATE_ACTIVE || + pjsip_evsub_get_state (sub) == PJSIP_EVSUB_STATE_TERMINATED) { + pjsip_msg *msg; + pjsip_msg_body *body; + pjsip_status_line status_line; + pj_bool_t is_last; + pj_bool_t cont; + pj_status_t status; + + std::string noresource; + std::string ringing; + std::string request; + + noresource = "noresource"; + ringing = "Ringing"; + + + SIPVoIPLink *link = reinterpret_cast<SIPVoIPLink *> (pjsip_evsub_get_mod_data (sub, _mod_ua.id)); + + /* When subscription is terminated, clear the xfer_sub member of + * the inv_data. + */ + + if (pjsip_evsub_get_state (sub) == PJSIP_EVSUB_STATE_TERMINATED) { + pjsip_evsub_set_mod_data (sub, _mod_ua.id, NULL); + _debug ("UserAgent: Xfer client subscription terminated\n"); + + } + + if (!link || !event) { + /* Application is not interested with call progress status */ + _debug ("UserAgent: Either link or event is empty!\n"); + return; + } + + + + /* This better be a NOTIFY request */ + if (event->type == PJSIP_EVENT_TSX_STATE && + event->body.tsx_state.type == PJSIP_EVENT_RX_MSG) { + + pjsip_rx_data *rdata; + + rdata = event->body.tsx_state.src.rdata; + + + /* Check if there's body */ + msg = rdata->msg_info.msg; + body = msg->body; + + if (!body) { + // if (call->getCallConfiguration () == Call::IPtoIP) { + // _debug("UserAgent: IptoIp NOTIFY without message body\n"); + // } + // else{ + _debug ("UserAgent: Warning! Received NOTIFY without message body\n"); + return; + // } + } + + + + /* Check for appropriate content */ + if (pj_stricmp2 (&body->content_type.type, "message") != 0 || + pj_stricmp2 (&body->content_type.subtype, "sipfrag") != 0) { + _debug ("UserAgent: Warning! Received NOTIFY with non message/sipfrag content\n"); + return; + } + + /* Try to parse the content */ + status = pjsip_parse_status_line ( (char*) body->data, body->len, + &status_line); + + if (status != PJ_SUCCESS) { + _debug ("UserAgent: Warning! Received NOTIFY with invalid message/sipfrag content\n"); + return; + } + + } else { + _debug ("UserAgent: Set code to 500!\n"); + status_line.code = 500; + status_line.reason = *pjsip_get_status_text (500); + } + + + if (event->body.rx_msg.rdata->msg_info.msg_buf != NULL) { + request = event->body.rx_msg.rdata->msg_info.msg_buf; + + if (request.find (noresource) != -1) { + _debug ("UserAgent: NORESOURCE for transfer!\n"); + link->transferStep2(); + pjsip_evsub_terminate (sub, PJ_TRUE); + + Manager::instance().transferFailed(); + return; + } + + if (request.find (ringing) != -1) { + _debug ("UserAgent: transfered call RINGING!\n"); + link->transferStep2(); + pjsip_evsub_terminate (sub, PJ_TRUE); + + Manager::instance().transferSucceded(); + return; + } + } + + + // Get current call + SIPCall *call = dynamic_cast<SIPCall *> (link->getCall (Manager::instance().getCurrentCallId())); + + if (!call) { + _debug ("UserAgent: Call doesn't exit!\n"); + return; + } + + + /* Notify application */ + is_last = (pjsip_evsub_get_state (sub) ==PJSIP_EVSUB_STATE_TERMINATED); + + cont = !is_last; + + if (status_line.code/100 == 2) { + + _debug ("UserAgent: Try to stop rtp!\n"); + pjsip_tx_data *tdata; + + status = pjsip_inv_end_session (call->getInvSession(), PJSIP_SC_GONE, NULL, &tdata); + + if (status != PJ_SUCCESS) { + _debug ("UserAgent: Fail to create end session msg!\n"); + } else { + status = pjsip_inv_send_msg (call->getInvSession(), tdata); + + if (status != PJ_SUCCESS) + _debug ("UserAgent: Fail to send end session msg!\n"); + } + + link->transferStep2(); + + cont = PJ_FALSE; + } + + if (!cont) { + pjsip_evsub_set_mod_data (sub, _mod_ua.id, NULL); + } + + } + +} + + +void xfer_svr_cb (pjsip_evsub *sub, pjsip_event *event) +{ + + + PJ_UNUSED_ARG (event); + + /* + * When subscription is terminated, clear the xfer_sub member of + * the inv_data. + */ + + if (pjsip_evsub_get_state (sub) == PJSIP_EVSUB_STATE_TERMINATED) { + SIPCall *call; + + call = (SIPCall*) pjsip_evsub_get_mod_data (sub, _mod_ua.id); + + if (!call) + return; + + pjsip_evsub_set_mod_data (sub, _mod_ua.id, NULL); + + call->setXferSub (NULL); + + _debug ("UserAgent: Xfer server subscription terminated\n"); + } +} + +void on_rx_offer (pjsip_inv_session *inv, const pjmedia_sdp_session *offer) +{ + + +#ifdef CAN_REINVITE + _debug ("reinvite SIP\n"); + + SIPCall *call; + pj_status_t status; + AccountID accId; + SIPVoIPLink *link; + + call = (SIPCall*) inv->mod_data[getModId() ]; + + if (!call) + return; + + accId = Manager::instance().getAccountFromCall (call->getCallId()); + + link = dynamic_cast<SIPVoIPLink *> (Manager::instance().getAccountLink (accId)); + + call->getLocalSDP()->receiving_initial_offer ( (pjmedia_sdp_session*) offer); + + status=pjsip_inv_set_sdp_answer (call->getInvSession(), call->getLocalSDP()->get_local_sdp_session()); + + if (link) + link->handle_reinvite (call); + +#endif + +} + +void handle_incoming_options (pjsip_rx_data *rdata) +{ + + + pjsip_tx_data *tdata; + pjsip_response_addr res_addr; + const pjsip_hdr *cap_hdr; + pj_status_t status; + + /* Create basic response. */ + status = pjsip_endpt_create_response (_endpt, rdata, PJSIP_SC_OK, NULL, &tdata); + + if (status != PJ_SUCCESS) { + return; + } + + /* Add Allow header */ + cap_hdr = pjsip_endpt_get_capability (_endpt, PJSIP_H_ALLOW, NULL); + + if (cap_hdr) { + pjsip_msg_add_hdr (tdata->msg, (pjsip_hdr*) pjsip_hdr_clone (tdata->pool, cap_hdr)); + } + + /* Add Accept header */ + cap_hdr = pjsip_endpt_get_capability (_endpt, PJSIP_H_ACCEPT, NULL); + + if (cap_hdr) { + pjsip_msg_add_hdr (tdata->msg, (pjsip_hdr*) pjsip_hdr_clone (tdata->pool, cap_hdr)); + } + + /* Add Supported header */ + cap_hdr = pjsip_endpt_get_capability (_endpt, PJSIP_H_SUPPORTED, NULL); + + if (cap_hdr) { + pjsip_msg_add_hdr (tdata->msg, (pjsip_hdr*) pjsip_hdr_clone (tdata->pool, cap_hdr)); + } + + /* Add Allow-Events header from the evsub module */ + cap_hdr = pjsip_evsub_get_allow_events_hdr (NULL); + + if (cap_hdr) { + pjsip_msg_add_hdr (tdata->msg, (pjsip_hdr*) pjsip_hdr_clone (tdata->pool, cap_hdr)); + } + + /* Send response statelessly */ + pjsip_get_response_addr (tdata->pool, rdata, &res_addr); + + status = pjsip_endpt_send_response (_endpt, &res_addr, tdata, NULL, NULL); + + if (status != PJ_SUCCESS) + pjsip_tx_data_dec_ref (tdata); +} + +/*****************************************************************************************************************/ + + +bool setCallAudioLocal (SIPCall* call, std::string localIP, bool stun, std::string server) +{ + + // Setting Audio + unsigned int callLocalAudioPort = RANDOM_LOCAL_PORT; + unsigned int callLocalExternAudioPort = callLocalAudioPort; + + if (stun) { + // If use Stun server + if (Manager::instance().behindNat (server, callLocalAudioPort)) { + callLocalExternAudioPort = Manager::instance().getFirewallPort(); + } + } + + _debug (" Setting local audio port to: %d\n", callLocalAudioPort); + + _debug (" Setting local audio port (external) to: %d\n", callLocalExternAudioPort); + + // Set local audio port for SIPCall(id) + call->setLocalIp (localIP); + call->setLocalAudioPort (callLocalAudioPort); + call->setLocalExternAudioPort (callLocalExternAudioPort); + + call->getLocalSDP()->attribute_port_to_all_media (callLocalExternAudioPort); + + return true; +} + +std::string fetch_header_value (pjsip_msg *msg, std::string field) +{ + + + pj_str_t name; + pjsip_generic_string_hdr * hdr; + std::string value, url; + size_t pos; + + std::cout << "fetch header value" << std::endl; + + /* Convert the field name into pjsip type */ + name = pj_str ( (char*) field.c_str()); + + /* Get the header value and convert into string*/ + hdr = (pjsip_generic_string_hdr*) pjsip_msg_find_hdr_by_name (msg, &name, NULL); + + if (!hdr) + return ""; + + value = hdr->hvalue.ptr; + + if ( (pos=value.find ("\n")) == std::string::npos) { + return ""; + } - value = hdr->hvalue.ptr; - if ( ( pos=value.find ( "\n" ) ) == std::string::npos ) - { - return ""; - } + url = value.substr (0, pos); - url = value.substr ( 0, pos ); - return url; + return url; } diff --git a/sflphone-common/src/voiplink.cpp b/sflphone-common/src/voiplink.cpp index 825edac881..52a28cd88f 100644 --- a/sflphone-common/src/voiplink.cpp +++ b/sflphone-common/src/voiplink.cpp @@ -24,63 +24,72 @@ #include "voiplink.h" #include "manager.h" -VoIPLink::VoIPLink(const AccountID& accountID) : _accountID(accountID), _localIPAddress("127.0.0.1"), _localPort(0), _initDone(false) +VoIPLink::VoIPLink (const AccountID& accountID) : _accountID (accountID), _localIPAddress ("127.0.0.1"), _localPort (0), _initDone (false) { } -VoIPLink::~VoIPLink (void) +VoIPLink::~VoIPLink (void) { clearCallMap(); } -bool VoIPLink::addCall(Call* call) +bool VoIPLink::addCall (Call* call) { if (call) { - if (getCall(call->getCallId()) == NULL) { - ost::MutexLock m(_callMapMutex); - _callMap[call->getCallId()] = call; + if (getCall (call->getCallId()) == NULL) { + ost::MutexLock m (_callMapMutex); + _callMap[call->getCallId() ] = call; } - } + } + return false; } -bool VoIPLink::removeCall(const CallID& id) +bool VoIPLink::removeCall (const CallID& id) { - ost::MutexLock m(_callMapMutex); - if (_callMap.erase(id)) { + ost::MutexLock m (_callMapMutex); + + if (_callMap.erase (id)) { return true; - } + } + return false; } -Call* VoIPLink::getCall(const CallID& id) +Call* VoIPLink::getCall (const CallID& id) { - ost::MutexLock m(_callMapMutex); - CallMap::iterator iter = _callMap.find(id); - if ( iter != _callMap.end() ) { - return iter->second; - } - return NULL; + ost::MutexLock m (_callMapMutex); + CallMap::iterator iter = _callMap.find (id); + + if (iter != _callMap.end()) { + return iter->second; + } + + return NULL; } bool VoIPLink::clearCallMap() { - ost::MutexLock m(_callMapMutex); - CallMap::iterator iter = _callMap.begin(); - while( iter != _callMap.end() ) { - // if (iter) ? - delete iter->second; iter->second = 0; - iter++; - } - _callMap.clear(); - return true; + ost::MutexLock m (_callMapMutex); + CallMap::iterator iter = _callMap.begin(); + + while (iter != _callMap.end()) { + // if (iter) ? + delete iter->second; + iter->second = 0; + iter++; + } + + _callMap.clear(); + + return true; } -Account* VoIPLink::getAccountPtr(void) +Account* VoIPLink::getAccountPtr (void) { Account* account; AccountID id; id = getAccountID(); - return Manager::instance().getAccount(id); + return Manager::instance().getAccount (id); } diff --git a/sflphone-common/test/TestMain.cpp b/sflphone-common/test/TestMain.cpp index 1bca8aeab1..d6e9f932bf 100644 --- a/sflphone-common/test/TestMain.cpp +++ b/sflphone-common/test/TestMain.cpp @@ -1,10 +1,10 @@ #include <cppunit/TextTestRunner.h> #include <cppunit/extensions/TestFactoryRegistry.h> -int main(int argc, const char* argv[]) +int main (int argc, const char* argv[]) { CppUnit::TextTestRunner runner; - runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest()); + runner.addTest (CppUnit::TestFactoryRegistry::getRegistry().makeTest()); return runner.run(); diff --git a/sflphone-common/test/audiolayerTest.cpp b/sflphone-common/test/audiolayerTest.cpp index 4a4b6396f3..880ec84740 100644 --- a/sflphone-common/test/audiolayerTest.cpp +++ b/sflphone-common/test/audiolayerTest.cpp @@ -30,7 +30,8 @@ using std::endl; -void AudioLayerTest::setUp(){ +void AudioLayerTest::setUp() +{ // Instanciate the manager Manager::instance().initConfigFile(); @@ -57,150 +58,157 @@ void AudioLayerTest::setUp(){ // get a pointer to the audio layer // _audiodriver = Manager::instance().getAudioDriver(); - + } -void AudioLayerTest::testAudioLayerConfig(){ - int sampling_rate = Manager::instance().getConfigInt(AUDIO, ALSA_SAMPLE_RATE); - int frame_size = Manager::instance().getConfigInt(AUDIO, ALSA_FRAME_SIZE); +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(Manager::instance().getAudioDriver()->getSampleRate() == sampling_rate); - CPPUNIT_ASSERT(Manager::instance().getAudioDriver()->getFrameSize() == frame_size); + CPPUNIT_ASSERT (Manager::instance().getAudioDriver()->getSampleRate() == sampling_rate); + CPPUNIT_ASSERT (Manager::instance().getAudioDriver()->getFrameSize() == frame_size); } -void AudioLayerTest::testAudioLayerSwitch(){ - - _debug("---------- AudioLayerTest::testAudioLayerSwitch ---------------------------\n"); - - - int previous_layer = Manager::instance().getAudioDriver()->getLayerType(); - - for(int i = 0; i < 2; i++) { - _debug("---------- AudioLayerTest::testAudioLayerSwitch - %i -------------\n",i); - Manager::instance().switchAudioManager(); - if(previous_layer == ALSA) { - CPPUNIT_ASSERT(Manager::instance().getAudioDriver()->getLayerType() == PULSEAUDIO); - } - else { - CPPUNIT_ASSERT(Manager::instance().getAudioDriver()->getLayerType() == ALSA); +void AudioLayerTest::testAudioLayerSwitch() +{ + + _debug ("---------- AudioLayerTest::testAudioLayerSwitch ---------------------------\n"); + + + int previous_layer = Manager::instance().getAudioDriver()->getLayerType(); + + for (int i = 0; i < 2; i++) { + _debug ("---------- AudioLayerTest::testAudioLayerSwitch - %i -------------\n",i); + Manager::instance().switchAudioManager(); + + if (previous_layer == ALSA) { + CPPUNIT_ASSERT (Manager::instance().getAudioDriver()->getLayerType() == PULSEAUDIO); + } else { + CPPUNIT_ASSERT (Manager::instance().getAudioDriver()->getLayerType() == ALSA); + } + + previous_layer = Manager::instance().getAudioDriver()->getLayerType(); + + usleep (100000); } - previous_layer = Manager::instance().getAudioDriver()->getLayerType(); - usleep(100000); - } } -void AudioLayerTest::testPulseConnect(){ +void AudioLayerTest::testPulseConnect() +{ - _debug("---------- AudioLayerTest::testPulseConnect ---------------------------\n"); + _debug ("---------- AudioLayerTest::testPulseConnect ---------------------------\n"); - ManagerImpl* manager; - manager = &Manager::instance(); + ManagerImpl* manager; + manager = &Manager::instance(); - _pulselayer = new PulseLayer(manager); + _pulselayer = new PulseLayer (manager); - CPPUNIT_ASSERT(_pulselayer->getLayerType() == PULSEAUDIO); + CPPUNIT_ASSERT (_pulselayer->getLayerType() == PULSEAUDIO); - std::string alsaPlugin; - int numCardIn, numCardOut, sampleRate, frameSize; - - alsaPlugin = manager->getConfigString( AUDIO , ALSA_PLUGIN ); - numCardIn = manager->getConfigInt( AUDIO , ALSA_CARD_ID_IN ); - numCardOut = manager->getConfigInt( AUDIO , ALSA_CARD_ID_OUT ); - sampleRate = manager->getConfigInt( AUDIO , ALSA_SAMPLE_RATE ); - frameSize = manager->getConfigInt(AUDIO, ALSA_FRAME_SIZE ); - - CPPUNIT_ASSERT(_pulselayer->getPlaybackStream() == NULL); - CPPUNIT_ASSERT(_pulselayer->getRecordStream() == NULL); + std::string alsaPlugin; + int numCardIn, numCardOut, sampleRate, frameSize; - _pulselayer->setErrorMessage(-1); - try { - CPPUNIT_ASSERT(_pulselayer->openDevice(numCardIn, numCardOut, sampleRate, frameSize, SFL_PCM_BOTH, alsaPlugin) == true); - } - catch (...) { - _debug("Exception occured wile opening device! \n"); - } + alsaPlugin = manager->getConfigString (AUDIO , ALSA_PLUGIN); + numCardIn = manager->getConfigInt (AUDIO , ALSA_CARD_ID_IN); + numCardOut = manager->getConfigInt (AUDIO , ALSA_CARD_ID_OUT); + sampleRate = manager->getConfigInt (AUDIO , ALSA_SAMPLE_RATE); + frameSize = manager->getConfigInt (AUDIO, ALSA_FRAME_SIZE); - usleep(100000); + CPPUNIT_ASSERT (_pulselayer->getPlaybackStream() == NULL); + CPPUNIT_ASSERT (_pulselayer->getRecordStream() == NULL); - CPPUNIT_ASSERT(_pulselayer->getPlaybackStream() != NULL); - CPPUNIT_ASSERT(_pulselayer->getRecordStream() != NULL); + _pulselayer->setErrorMessage (-1); - CPPUNIT_ASSERT(_pulselayer->getPlaybackStream()->pulseStream() != NULL); - CPPUNIT_ASSERT(_pulselayer->getRecordStream()->pulseStream() != NULL); + try { + CPPUNIT_ASSERT (_pulselayer->openDevice (numCardIn, numCardOut, sampleRate, frameSize, SFL_PCM_BOTH, alsaPlugin) == true); + } catch (...) { + _debug ("Exception occured wile opening device! \n"); + } + + usleep (100000); + + CPPUNIT_ASSERT (_pulselayer->getPlaybackStream() != NULL); + CPPUNIT_ASSERT (_pulselayer->getRecordStream() != NULL); + + CPPUNIT_ASSERT (_pulselayer->getPlaybackStream()->pulseStream() != NULL); + CPPUNIT_ASSERT (_pulselayer->getRecordStream()->pulseStream() != NULL); - // Must return Access failure "PA_ERR_ACCESS" == 2 - CPPUNIT_ASSERT(_pulselayer->getPlaybackStream()->getStreamState() == 2); - CPPUNIT_ASSERT(_pulselayer->getRecordStream()->getStreamState() == 2); + // Must return Access failure "PA_ERR_ACCESS" == 2 + CPPUNIT_ASSERT (_pulselayer->getPlaybackStream()->getStreamState() == 2); + CPPUNIT_ASSERT (_pulselayer->getRecordStream()->getStreamState() == 2); - CPPUNIT_ASSERT(_pulselayer->createStreams(_pulselayer->context) == true); + CPPUNIT_ASSERT (_pulselayer->createStreams (_pulselayer->context) == true); - // usleep(1000000); + // usleep(1000000); - CPPUNIT_ASSERT(_pulselayer->getPlaybackStream()->pulseStream() != NULL); - CPPUNIT_ASSERT(_pulselayer->getPlaybackStream()->pulseStream() != NULL); + CPPUNIT_ASSERT (_pulselayer->getPlaybackStream()->pulseStream() != NULL); + CPPUNIT_ASSERT (_pulselayer->getPlaybackStream()->pulseStream() != NULL); - // Must return No error "PA_OK" == 1 - CPPUNIT_ASSERT(_pulselayer->getPlaybackStream()->getStreamState() == 1); - CPPUNIT_ASSERT(_pulselayer->getRecordStream()->getStreamState() == 1); + // Must return No error "PA_OK" == 1 + CPPUNIT_ASSERT (_pulselayer->getPlaybackStream()->getStreamState() == 1); + CPPUNIT_ASSERT (_pulselayer->getRecordStream()->getStreamState() == 1); - CPPUNIT_ASSERT(_pulselayer->getPlaybackStream()->disconnectStream() == true); - CPPUNIT_ASSERT(_pulselayer->getRecordStream()->disconnectStream() == true); + CPPUNIT_ASSERT (_pulselayer->getPlaybackStream()->disconnectStream() == true); + CPPUNIT_ASSERT (_pulselayer->getRecordStream()->disconnectStream() == true); - // _debug("%i\n",_pulselayer->getPlaybackStream()->getStreamState()); + // _debug("%i\n",_pulselayer->getPlaybackStream()->getStreamState()); - CPPUNIT_ASSERT(_pulselayer->getPlaybackStream()->connectStream() == true); - CPPUNIT_ASSERT(_pulselayer->getRecordStream()->connectStream() == true); + CPPUNIT_ASSERT (_pulselayer->getPlaybackStream()->connectStream() == true); + CPPUNIT_ASSERT (_pulselayer->getRecordStream()->connectStream() == true); - CPPUNIT_ASSERT(_pulselayer->getPlaybackStream()->getStreamState() == 1); - CPPUNIT_ASSERT(_pulselayer->getRecordStream()->getStreamState() == 1); + CPPUNIT_ASSERT (_pulselayer->getPlaybackStream()->getStreamState() == 1); + CPPUNIT_ASSERT (_pulselayer->getRecordStream()->getStreamState() == 1); - CPPUNIT_ASSERT(_pulselayer->getPlaybackStream()->connectStream() == true); - CPPUNIT_ASSERT(_pulselayer->getRecordStream()->connectStream() == true); + CPPUNIT_ASSERT (_pulselayer->getPlaybackStream()->connectStream() == true); + CPPUNIT_ASSERT (_pulselayer->getRecordStream()->connectStream() == true); - CPPUNIT_ASSERT(_pulselayer->getPlaybackStream()->getStreamState() == 1); - CPPUNIT_ASSERT(_pulselayer->getRecordStream()->getStreamState() == 1); + CPPUNIT_ASSERT (_pulselayer->getPlaybackStream()->getStreamState() == 1); + CPPUNIT_ASSERT (_pulselayer->getRecordStream()->getStreamState() == 1); - // usleep(1000000); - CPPUNIT_ASSERT(_pulselayer->disconnectPulseAudioServer() == true); + // usleep(1000000); + CPPUNIT_ASSERT (_pulselayer->disconnectPulseAudioServer() == true); } -void AudioLayerTest::testAlsaConnect(){ +void AudioLayerTest::testAlsaConnect() +{ - _debug("---------- AudioLayerTest::testAlsaConnect ---------------------------\n"); + _debug ("---------- AudioLayerTest::testAlsaConnect ---------------------------\n"); + + int layer = Manager::instance().getAudioDriver()->getLayerType(); + + int type, samplerate, framesize, numCardIn, numCardOut; + std::string alsaPlugin; + + if (layer != ALSA) { + Manager::instance().switchAudioManager(); + usleep (100000); + } - int layer = Manager::instance().getAudioDriver()->getLayerType(); + // _audiolayer = Manager::instance().getAudioDriver(); - int type, samplerate, framesize, numCardIn, numCardOut; - std::string alsaPlugin; + // CPPUNIT_ASSERT(_audiolayer->closeLayer() == true); + // usleep(100000); - if (layer != ALSA) { - Manager::instance().switchAudioManager(); - usleep(100000); - } + // delete _audiolayer; _audiolayer == NULL; - // _audiolayer = Manager::instance().getAudioDriver(); - - // CPPUNIT_ASSERT(_audiolayer->closeLayer() == true); - // usleep(100000); + Manager::instance().setConfig (PREFERENCES, CONFIG_AUDIO, ALSA); - // delete _audiolayer; _audiolayer == NULL; - Manager::instance().setConfig( PREFERENCES, CONFIG_AUDIO, ALSA); + // _audiolayer->setErrorMessage(-1); + // CPPUNIT_ASSERT(Manager::instance().initAudioDriver() == true); - - // _audiolayer->setErrorMessage(-1); - // CPPUNIT_ASSERT(Manager::instance().initAudioDriver() == true); + // _audiolayer = Manager::instance().getAudioDriver(); - // _audiolayer = Manager::instance().getAudioDriver(); - - // CPPUNIT_ASSERT(_audiolayer->getLayerType() == ALSA); + // CPPUNIT_ASSERT(_audiolayer->getLayerType() == ALSA); } -void AudioLayerTest::tearDown(){ +void AudioLayerTest::tearDown() +{ // Delete the audio recorder module // delete _ar; _ar = NULL; } diff --git a/sflphone-common/test/audiorecorderTest.cpp b/sflphone-common/test/audiorecorderTest.cpp index 9c0bf863ed..fc349f08c2 100644 --- a/sflphone-common/test/audiorecorderTest.cpp +++ b/sflphone-common/test/audiorecorderTest.cpp @@ -25,33 +25,37 @@ using std::cout; using std::endl; -void AudioRecorderTest::setUp(){ +void AudioRecorderTest::setUp() +{ // Instanciate the object _ar = new AudioRecord(); } -void AudioRecorderTest::testRecordData(){ - -/* - FILE_TYPE ft = FILE_WAV; - SOUND_FORMAT sf = INT16; - _ar->setSndSamplingRate(44100); - _ar->openFile("theWavFile.wav",ft,sf); - - cout << "file opened!\n"; - - SFLDataFormat buf [2]; - for (SFLDataFormat i = -32768; i < 32767; i++ ){ - buf[0] = i; - buf[1] = i; - _ar->recData(buf,2); - } - - _ar->closeFile(); -*/ +void AudioRecorderTest::testRecordData() +{ + + /* + FILE_TYPE ft = FILE_WAV; + SOUND_FORMAT sf = INT16; + _ar->setSndSamplingRate(44100); + _ar->openFile("theWavFile.wav",ft,sf); + + cout << "file opened!\n"; + + SFLDataFormat buf [2]; + for (SFLDataFormat i = -32768; i < 32767; i++ ){ + buf[0] = i; + buf[1] = i; + _ar->recData(buf,2); + } + + _ar->closeFile(); + */ } -void AudioRecorderTest::tearDown(){ +void AudioRecorderTest::tearDown() +{ // Delete the audio recorder module - delete _ar; _ar = NULL; + delete _ar; + _ar = NULL; } diff --git a/sflphone-common/test/configurationTest.cpp b/sflphone-common/test/configurationTest.cpp index 8208c9944f..228d6347af 100644 --- a/sflphone-common/test/configurationTest.cpp +++ b/sflphone-common/test/configurationTest.cpp @@ -25,46 +25,51 @@ using std::cout; using std::endl; -void ConfigurationTest::setUp(){ +void ConfigurationTest::setUp() +{ // Load the default configuration Manager::instance().initConfigFile(); } -void ConfigurationTest::testDefaultValueAudio(){ - CPPUNIT_ASSERT( Manager::instance().getConfigString( AUDIO, ALSA_CARD_ID_IN ) == ALSA_DFT_CARD) ; - CPPUNIT_ASSERT( Manager::instance().getConfigString( AUDIO, ALSA_CARD_ID_OUT ) == ALSA_DFT_CARD ); - CPPUNIT_ASSERT( Manager::instance().getConfigString( AUDIO, ALSA_SAMPLE_RATE ) == DFT_SAMPLE_RATE); - CPPUNIT_ASSERT( Manager::instance().getConfigString( AUDIO, ALSA_FRAME_SIZE ) == DFT_FRAME_SIZE) ; - CPPUNIT_ASSERT( Manager::instance().getConfigString( AUDIO, ALSA_PLUGIN ) == PCM_DEFAULT ); - CPPUNIT_ASSERT( Manager::instance().getConfigString( AUDIO, VOLUME_SPKR ) == DFT_VOL_SPKR_STR); - CPPUNIT_ASSERT( Manager::instance().getConfigString( AUDIO, VOLUME_MICRO ) == DFT_VOL_MICRO_STR); +void ConfigurationTest::testDefaultValueAudio() +{ + CPPUNIT_ASSERT (Manager::instance().getConfigString (AUDIO, ALSA_CARD_ID_IN) == ALSA_DFT_CARD) ; + CPPUNIT_ASSERT (Manager::instance().getConfigString (AUDIO, ALSA_CARD_ID_OUT) == ALSA_DFT_CARD); + CPPUNIT_ASSERT (Manager::instance().getConfigString (AUDIO, ALSA_SAMPLE_RATE) == DFT_SAMPLE_RATE); + CPPUNIT_ASSERT (Manager::instance().getConfigString (AUDIO, ALSA_FRAME_SIZE) == DFT_FRAME_SIZE) ; + CPPUNIT_ASSERT (Manager::instance().getConfigString (AUDIO, ALSA_PLUGIN) == PCM_DEFAULT); + CPPUNIT_ASSERT (Manager::instance().getConfigString (AUDIO, VOLUME_SPKR) == DFT_VOL_SPKR_STR); + CPPUNIT_ASSERT (Manager::instance().getConfigString (AUDIO, VOLUME_MICRO) == DFT_VOL_MICRO_STR); } -void ConfigurationTest::testDefaultValuePreferences(){ - CPPUNIT_ASSERT( Manager::instance().getConfigString( PREFERENCES, ZONE_TONE ) == DFT_ZONE ); - CPPUNIT_ASSERT( Manager::instance().getConfigString( PREFERENCES, CONFIG_ZEROCONF ) == CONFIG_ZEROCONF_DEFAULT_STR ); - CPPUNIT_ASSERT( Manager::instance().getConfigString( PREFERENCES, CONFIG_DIALPAD ) == YES_STR ); - CPPUNIT_ASSERT( Manager::instance().getConfigString( PREFERENCES, CONFIG_RINGTONE ) == YES_STR ); - CPPUNIT_ASSERT( Manager::instance().getConfigString( PREFERENCES, CONFIG_SEARCHBAR ) == YES_STR ); - CPPUNIT_ASSERT( Manager::instance().getConfigString( PREFERENCES, CONFIG_START ) == NO_STR ); - CPPUNIT_ASSERT( Manager::instance().getConfigString( PREFERENCES, CONFIG_POPUP ) == YES_STR ); - CPPUNIT_ASSERT( Manager::instance().getConfigString( PREFERENCES, CONFIG_NOTIFY ) == YES_STR ); - CPPUNIT_ASSERT( Manager::instance().getConfigString( PREFERENCES, CONFIG_MAIL_NOTIFY ) == NO_STR ); - CPPUNIT_ASSERT( Manager::instance().getConfigString( PREFERENCES, CONFIG_VOLUME ) == YES_STR ); - CPPUNIT_ASSERT( Manager::instance().getConfigString( PREFERENCES, REGISTRATION_EXPIRE ) == DFT_EXPIRE_VALUE ); - CPPUNIT_ASSERT( Manager::instance().getConfigString( PREFERENCES, CONFIG_AUDIO ) == DFT_AUDIO_MANAGER ); +void ConfigurationTest::testDefaultValuePreferences() +{ + CPPUNIT_ASSERT (Manager::instance().getConfigString (PREFERENCES, ZONE_TONE) == DFT_ZONE); + CPPUNIT_ASSERT (Manager::instance().getConfigString (PREFERENCES, CONFIG_ZEROCONF) == CONFIG_ZEROCONF_DEFAULT_STR); + CPPUNIT_ASSERT (Manager::instance().getConfigString (PREFERENCES, CONFIG_DIALPAD) == YES_STR); + CPPUNIT_ASSERT (Manager::instance().getConfigString (PREFERENCES, CONFIG_RINGTONE) == YES_STR); + CPPUNIT_ASSERT (Manager::instance().getConfigString (PREFERENCES, CONFIG_SEARCHBAR) == YES_STR); + CPPUNIT_ASSERT (Manager::instance().getConfigString (PREFERENCES, CONFIG_START) == NO_STR); + CPPUNIT_ASSERT (Manager::instance().getConfigString (PREFERENCES, CONFIG_POPUP) == YES_STR); + CPPUNIT_ASSERT (Manager::instance().getConfigString (PREFERENCES, CONFIG_NOTIFY) == YES_STR); + CPPUNIT_ASSERT (Manager::instance().getConfigString (PREFERENCES, CONFIG_MAIL_NOTIFY) == NO_STR); + CPPUNIT_ASSERT (Manager::instance().getConfigString (PREFERENCES, CONFIG_VOLUME) == YES_STR); + CPPUNIT_ASSERT (Manager::instance().getConfigString (PREFERENCES, REGISTRATION_EXPIRE) == DFT_EXPIRE_VALUE); + CPPUNIT_ASSERT (Manager::instance().getConfigString (PREFERENCES, CONFIG_AUDIO) == DFT_AUDIO_MANAGER); } -void ConfigurationTest::testDefaultValueSignalisation(){ - CPPUNIT_ASSERT( Manager::instance().getConfigString( SIGNALISATION , SYMMETRIC ) == YES_STR ); - CPPUNIT_ASSERT( Manager::instance().getConfigString( SIGNALISATION , PLAY_DTMF ) == YES_STR ); - CPPUNIT_ASSERT( Manager::instance().getConfigString( SIGNALISATION , PLAY_TONES ) == YES_STR ); - CPPUNIT_ASSERT( Manager::instance().getConfigString( SIGNALISATION , PULSE_LENGTH ) == DFT_PULSE_LENGTH_STR ); - CPPUNIT_ASSERT( Manager::instance().getConfigString( SIGNALISATION , SEND_DTMF_AS ) == SIP_INFO_STR ); +void ConfigurationTest::testDefaultValueSignalisation() +{ + CPPUNIT_ASSERT (Manager::instance().getConfigString (SIGNALISATION , SYMMETRIC) == YES_STR); + CPPUNIT_ASSERT (Manager::instance().getConfigString (SIGNALISATION , PLAY_DTMF) == YES_STR); + CPPUNIT_ASSERT (Manager::instance().getConfigString (SIGNALISATION , PLAY_TONES) == YES_STR); + CPPUNIT_ASSERT (Manager::instance().getConfigString (SIGNALISATION , PULSE_LENGTH) == DFT_PULSE_LENGTH_STR); + CPPUNIT_ASSERT (Manager::instance().getConfigString (SIGNALISATION , SEND_DTMF_AS) == SIP_INFO_STR); } -void ConfigurationTest::testLoadSIPAccount(){ +void ConfigurationTest::testLoadSIPAccount() +{ AccountMap accounts; Account *current; @@ -73,65 +78,70 @@ void ConfigurationTest::testLoadSIPAccount(){ // Load the account from the user file nb_account = Manager::instance().loadAccountMap(); - CPPUNIT_ASSERT_EQUAL( 1, nb_account ); + CPPUNIT_ASSERT_EQUAL (1, nb_account); // Save the account information accounts = Manager::instance()._accountMap; - - AccountMap::iterator iter = accounts.begin(); - CPPUNIT_ASSERT( Manager::instance().accountExists( iter->first ) == true ); - - while( iter != accounts.end() ){ + + AccountMap::iterator iter = accounts.begin(); + CPPUNIT_ASSERT (Manager::instance().accountExists (iter->first) == true); + + while (iter != accounts.end()) { current = iter->second; - CPPUNIT_ASSERT( iter->first == current->getAccountID() ); - CPPUNIT_ASSERT( 0 == current->getVoIPLink() ); + CPPUNIT_ASSERT (iter->first == current->getAccountID()); + CPPUNIT_ASSERT (0 == current->getVoIPLink()); iter++; } -} +} -void ConfigurationTest::testUnloadSIPAccount(){ +void ConfigurationTest::testUnloadSIPAccount() +{ AccountMap accounts; // Load the accounts from the user file - Manager::instance().loadAccountMap(); + Manager::instance().loadAccountMap(); // Unload the accounts Manager::instance().unloadAccountMap(); // Save the account information accounts = Manager::instance()._accountMap; - - AccountMap::iterator iter = accounts.begin(); - CPPUNIT_ASSERT( Manager::instance().accountExists( iter->first ) == false ); - - if( iter != accounts.end() ){ - CPPUNIT_FAIL("Unload account map failed\n"); + + AccountMap::iterator iter = accounts.begin(); + CPPUNIT_ASSERT (Manager::instance().accountExists (iter->first) == false); + + if (iter != accounts.end()) { + CPPUNIT_FAIL ("Unload account map failed\n"); } } -void ConfigurationTest::testInitVolume(){ - +void ConfigurationTest::testInitVolume() +{ + Manager::instance().initVolume(); - CPPUNIT_ASSERT( Manager::instance().getConfigInt( AUDIO, VOLUME_SPKR) == Manager::instance().getSpkrVolume() ); - CPPUNIT_ASSERT( Manager::instance().getConfigInt( AUDIO, VOLUME_MICRO) == Manager::instance().getMicVolume() ); + CPPUNIT_ASSERT (Manager::instance().getConfigInt (AUDIO, VOLUME_SPKR) == Manager::instance().getSpkrVolume()); + CPPUNIT_ASSERT (Manager::instance().getConfigInt (AUDIO, VOLUME_MICRO) == Manager::instance().getMicVolume()); } -void ConfigurationTest::testInitAudioDriver(){ - +void ConfigurationTest::testInitAudioDriver() +{ + // Load the audio driver Manager::instance().initAudioDriver(); - + // Check the creation - if( Manager::instance().getAudioDriver() == NULL ) - CPPUNIT_FAIL("Error while loading audio layer"); + + if (Manager::instance().getAudioDriver() == NULL) + CPPUNIT_FAIL ("Error while loading audio layer"); // Check if it has been created with the right type - if( Manager::instance().getConfigInt( PREFERENCES, CONFIG_AUDIO ) == ALSA ) - CPPUNIT_ASSERT_EQUAL( Manager::instance().getAudioDriver()->getLayerType(), ALSA ); - else if( Manager::instance().getConfigInt( PREFERENCES, CONFIG_AUDIO ) == PULSEAUDIO ) - CPPUNIT_ASSERT_EQUAL( Manager::instance().getAudioDriver()->getLayerType(), PULSEAUDIO ); + if (Manager::instance().getConfigInt (PREFERENCES, CONFIG_AUDIO) == ALSA) + CPPUNIT_ASSERT_EQUAL (Manager::instance().getAudioDriver()->getLayerType(), ALSA); + else if (Manager::instance().getConfigInt (PREFERENCES, CONFIG_AUDIO) == PULSEAUDIO) + CPPUNIT_ASSERT_EQUAL (Manager::instance().getAudioDriver()->getLayerType(), PULSEAUDIO); else - CPPUNIT_FAIL("Wrong audio layer type"); + CPPUNIT_FAIL ("Wrong audio layer type"); } -void ConfigurationTest::testSelectAudioDriver(){ +void ConfigurationTest::testSelectAudioDriver() +{ } diff --git a/sflphone-common/test/historyTest.cpp b/sflphone-common/test/historyTest.cpp index 6800a27202..105cee3001 100644 --- a/sflphone-common/test/historyTest.cpp +++ b/sflphone-common/test/historyTest.cpp @@ -32,12 +32,14 @@ using std::endl; #define CONFIG_SAMPLE "sflphonedrc-sample" #define HUGE_HISTORY_LIMIT 20000 -void HistoryTest::setUp(){ +void HistoryTest::setUp() +{ // Instanciate the cleaner singleton history = new HistoryManager (); } -void HistoryTest::test_create_history_path () { +void HistoryTest::test_create_history_path () +{ int result; std::string path; @@ -108,18 +110,18 @@ void HistoryTest::test_get_history_serialized () std::map <std::string, std::string>::iterator iter; std::string tmp; - // Load the sample user config - Manager::instance().initConfigFile(true, CONFIG_SAMPLE); + // Load the sample user config + Manager::instance().initConfigFile (true, CONFIG_SAMPLE); Manager::instance().loadAccountMap (); CPPUNIT_ASSERT (history->load_history (HUGE_HISTORY_LIMIT, HISTORY_SAMPLE) == HISTORY_SAMPLE_SIZE); res = history->get_history_serialized (); - CPPUNIT_ASSERT (res.size()==HISTORY_SAMPLE_SIZE); + CPPUNIT_ASSERT (res.size() ==HISTORY_SAMPLE_SIZE); // Warning - If you change the history-sample file, you must change the following lines also so that the tests could work // The reference here is the file history-sample in this test directory // The serialized form is: calltype%to%from%callid - + // Check the first tmp = "0|514-276-5468|Savoir-faire Linux|144562458|empty"; CPPUNIT_ASSERT (tmp == res ["144562436"]); @@ -150,7 +152,7 @@ void HistoryTest::test_set_serialized_history () map_test.clear (); map_test = history->get_history_serialized (); - CPPUNIT_ASSERT (map_test.size()==3); + CPPUNIT_ASSERT (map_test.size() ==3); // Check the first tmp = "0|514-276-5468|Savoir-faire Linux|144562458|empty"; @@ -181,16 +183,16 @@ void HistoryTest::test_set_serialized_history_with_limit () current_2 << (current - 5*day) << std::endl; current_3 << (current - 11*day) << std::endl; - map_test[current_1.str ()] = "0|514-276-5468|Savoir-faire Linux|144562458|empty"; - map_test[current_2.str ()] = "2|136|Emmanuel Milou|747638765|Account:1239059899"; - map_test[current_3.str ()] = "1|5143848557|empty|775354987|Account:43789459478"; + map_test[current_1.str () ] = "0|514-276-5468|Savoir-faire Linux|144562458|empty"; + map_test[current_2.str () ] = "2|136|Emmanuel Milou|747638765|Account:1239059899"; + map_test[current_3.str () ] = "1|5143848557|empty|775354987|Account:43789459478"; CPPUNIT_ASSERT (history->load_history (HUGE_HISTORY_LIMIT, HISTORY_SAMPLE) == HISTORY_SAMPLE_SIZE); // We use different value of history limit // 10 days - the last entry should not be saved CPPUNIT_ASSERT (history->set_serialized_history (map_test, 10) == 2); CPPUNIT_ASSERT (history->get_history_size () == 2); - + // 4 days - the two last entries should not be saved CPPUNIT_ASSERT (history->set_serialized_history (map_test, 4) == 1); CPPUNIT_ASSERT (history->get_history_size () == 1); @@ -200,7 +202,9 @@ void HistoryTest::test_set_serialized_history_with_limit () CPPUNIT_ASSERT (history->get_history_size () == 0); } -void HistoryTest::tearDown(){ +void HistoryTest::tearDown() +{ // Delete the history object - delete history; history=0; + delete history; + history=0; } diff --git a/sflphone-common/test/hookmanagerTest.cpp b/sflphone-common/test/hookmanagerTest.cpp index b62da774d4..d5b8cb6a80 100644 --- a/sflphone-common/test/hookmanagerTest.cpp +++ b/sflphone-common/test/hookmanagerTest.cpp @@ -27,26 +27,31 @@ using std::cout; using std::endl; -void HookManagerTest::setUp(){ +void HookManagerTest::setUp() +{ // Instanciate the hook manager singleton urlhook = new UrlHook (); } -void HookManagerTest::testAddAction (){ +void HookManagerTest::testAddAction () +{ int status; status = urlhook->addAction ("www.google.ca", "x-www-browser"); - CPPUNIT_ASSERT (status == 0); + CPPUNIT_ASSERT (status == 0); } -void HookManagerTest::testLargeUrl (){ +void HookManagerTest::testLargeUrl () +{ std::string url; std::cout << url.max_size() << std::endl; } -void HookManagerTest::tearDown(){ +void HookManagerTest::tearDown() +{ // Delete the hook manager object - delete urlhook; urlhook=0; + delete urlhook; + urlhook=0; } diff --git a/sflphone-common/test/numbercleanerTest.cpp b/sflphone-common/test/numbercleanerTest.cpp index f6c9a22d80..03dca41604 100644 --- a/sflphone-common/test/numbercleanerTest.cpp +++ b/sflphone-common/test/numbercleanerTest.cpp @@ -42,70 +42,85 @@ using std::cout; using std::endl; -void NumberCleanerTest::setUp(){ +void NumberCleanerTest::setUp() +{ // Instanciate the cleaner singleton cleaner = new NumberCleaner (); } -void NumberCleanerTest::test_format_1 (void) { +void NumberCleanerTest::test_format_1 (void) +{ CPPUNIT_ASSERT (cleaner->clean (NUMBER_TEST_1) == VALID_NUMBER); } -void NumberCleanerTest::test_format_2 (void) { +void NumberCleanerTest::test_format_2 (void) +{ CPPUNIT_ASSERT (cleaner->clean (NUMBER_TEST_2) == VALID_NUMBER); } -void NumberCleanerTest::test_format_3 (void) { +void NumberCleanerTest::test_format_3 (void) +{ CPPUNIT_ASSERT (cleaner->clean (NUMBER_TEST_3) == VALID_NUMBER); } -void NumberCleanerTest::test_format_4 (void) { +void NumberCleanerTest::test_format_4 (void) +{ CPPUNIT_ASSERT (cleaner->clean (NUMBER_TEST_4) == VALID_NUMBER); } -void NumberCleanerTest::test_format_5 (void) { +void NumberCleanerTest::test_format_5 (void) +{ CPPUNIT_ASSERT (cleaner->clean (NUMBER_TEST_5) == VALID_NUMBER); } -void NumberCleanerTest::test_format_6 (void) { +void NumberCleanerTest::test_format_6 (void) +{ CPPUNIT_ASSERT (cleaner->clean (NUMBER_TEST_6) == VALID_NUMBER); } -void NumberCleanerTest::test_format_7 (void) { +void NumberCleanerTest::test_format_7 (void) +{ CPPUNIT_ASSERT (cleaner->clean (NUMBER_TEST_7) == VALID_NUMBER); } -void NumberCleanerTest::test_format_8 (void) { +void NumberCleanerTest::test_format_8 (void) +{ CPPUNIT_ASSERT (cleaner->clean (NUMBER_TEST_8) == VALID_NUMBER); } -void NumberCleanerTest::test_format_9 (void) { +void NumberCleanerTest::test_format_9 (void) +{ CPPUNIT_ASSERT (cleaner->clean (NUMBER_TEST_9) == VALID_NUMBER); } -void NumberCleanerTest::test_format_10 (void) { +void NumberCleanerTest::test_format_10 (void) +{ cleaner->set_phone_number_prefix ("9"); CPPUNIT_ASSERT (cleaner->get_phone_number_prefix () == "9"); CPPUNIT_ASSERT (cleaner->clean (NUMBER_TEST_1) == VALID_PREPENDED_NUMBER); } -void NumberCleanerTest::test_format_11 (void) { +void NumberCleanerTest::test_format_11 (void) +{ cleaner->set_phone_number_prefix ("9"); CPPUNIT_ASSERT (cleaner->get_phone_number_prefix () == "9"); CPPUNIT_ASSERT (cleaner->clean (NUMBER_TEST_10) == VALID_EXTENSION); } -void NumberCleanerTest::tearDown(){ + +void NumberCleanerTest::tearDown() +{ // Delete the cleaner object - delete cleaner; cleaner=0; + delete cleaner; + cleaner=0; } diff --git a/sflphone-common/test/pluginmanagerTest.cpp b/sflphone-common/test/pluginmanagerTest.cpp index 96994b6925..86b4890c6f 100644 --- a/sflphone-common/test/pluginmanagerTest.cpp +++ b/sflphone-common/test/pluginmanagerTest.cpp @@ -31,65 +31,81 @@ using std::endl; #define PLUGIN_TEST_NAME "/usr/lib/sflphone/plugins/libplugintest.so" -void PluginManagerTest::setUp(){ +void PluginManagerTest::setUp() +{ // Instanciate the plugin manager singleton _pm = PluginManager::instance(); library = 0; plugin = 0; } -void PluginManagerTest::testLoadDynamicLibrary(){ - CPPUNIT_ASSERT(_pm->loadDynamicLibrary(PLUGIN_TEST_NAME) != NULL); +void PluginManagerTest::testLoadDynamicLibrary() +{ + CPPUNIT_ASSERT (_pm->loadDynamicLibrary (PLUGIN_TEST_NAME) != NULL); } -void PluginManagerTest::testUnloadDynamicLibrary(){ - library = _pm->loadDynamicLibrary(PLUGIN_TEST_NAME); - CPPUNIT_ASSERT(library != NULL); - CPPUNIT_ASSERT(_pm->unloadDynamicLibrary(library) == 0 ); +void PluginManagerTest::testUnloadDynamicLibrary() +{ + library = _pm->loadDynamicLibrary (PLUGIN_TEST_NAME); + CPPUNIT_ASSERT (library != NULL); + CPPUNIT_ASSERT (_pm->unloadDynamicLibrary (library) == 0); } -void PluginManagerTest::testInstanciatePlugin(){ +void PluginManagerTest::testInstanciatePlugin() +{ library = _pm->loadDynamicLibrary (PLUGIN_TEST_NAME); - CPPUNIT_ASSERT(library != NULL); + CPPUNIT_ASSERT (library != NULL); CPPUNIT_ASSERT (_pm->instanciatePlugin (library, &plugin) == 0); CPPUNIT_ASSERT (plugin!=NULL); } -void PluginManagerTest::testInitPlugin(){ +void PluginManagerTest::testInitPlugin() +{ library = _pm->loadDynamicLibrary (PLUGIN_TEST_NAME); - CPPUNIT_ASSERT(library != NULL); + CPPUNIT_ASSERT (library != NULL); CPPUNIT_ASSERT (_pm->instanciatePlugin (library, &plugin) == 0); CPPUNIT_ASSERT (plugin!=NULL); CPPUNIT_ASSERT (plugin->getPluginName() == PLUGIN_TEST_DESC); } -void PluginManagerTest::testRegisterPlugin(){ +void PluginManagerTest::testRegisterPlugin() +{ library = _pm->loadDynamicLibrary (PLUGIN_TEST_NAME); - CPPUNIT_ASSERT(library != NULL); + CPPUNIT_ASSERT (library != NULL); CPPUNIT_ASSERT (_pm->instanciatePlugin (library, &plugin) == 0); CPPUNIT_ASSERT (_pm->isPluginLoaded (PLUGIN_TEST_DESC) == false); CPPUNIT_ASSERT (_pm->registerPlugin (plugin, library) == 0); CPPUNIT_ASSERT (_pm->isPluginLoaded (PLUGIN_TEST_DESC) == true); } -void PluginManagerTest::testLoadPlugins (){ +void PluginManagerTest::testLoadPlugins () +{ CPPUNIT_ASSERT (_pm->loadPlugins (PLUGIN_TEST_DIR) == 0); CPPUNIT_ASSERT (_pm->isPluginLoaded (PLUGIN_TEST_DESC) == true); } -void PluginManagerTest::testUnloadPlugins (){ +void PluginManagerTest::testUnloadPlugins () +{ CPPUNIT_ASSERT (_pm->loadPlugins (PLUGIN_TEST_DIR) == 0); CPPUNIT_ASSERT (_pm->isPluginLoaded (PLUGIN_TEST_DESC) == true); CPPUNIT_ASSERT (_pm->unloadPlugins () == 0); CPPUNIT_ASSERT (_pm->isPluginLoaded (PLUGIN_TEST_DESC) == false); } -void PluginManagerTest::tearDown(){ +void PluginManagerTest::tearDown() +{ // Delete the plugin manager object - delete _pm; _pm=0; - if(plugin) - delete plugin; plugin = 0; - if(library) - delete library; library = 0; + delete _pm; + _pm=0; + + if (plugin) + delete plugin; + + plugin = 0; + + if (library) + delete library; + + library = 0; } diff --git a/sflphone-common/test/rtpTest.cpp b/sflphone-common/test/rtpTest.cpp index a33e1df141..c2aa396e1b 100644 --- a/sflphone-common/test/rtpTest.cpp +++ b/sflphone-common/test/rtpTest.cpp @@ -38,9 +38,10 @@ using std::cout; using std::endl; -void RtpTest::setUp(){ +void RtpTest::setUp() +{ - _debug("------ Set up rtp test------\n"); + _debug ("------ Set up rtp test------\n"); Manager::instance().initConfigFile(); Manager::instance().init(); @@ -49,25 +50,26 @@ void RtpTest::setUp(){ CallID cid = "123456"; - sipcall = new SIPCall(cid, Call::Incoming, _pool); - - sipcall->setLocalIp("127.0.0.1"); - sipcall->setLocalAudioPort(RANDOM_LOCAL_PORT); - sipcall->setLocalExternAudioPort(RANDOM_LOCAL_PORT); + sipcall = new SIPCall (cid, Call::Incoming, _pool); + + sipcall->setLocalIp ("127.0.0.1"); + sipcall->setLocalAudioPort (RANDOM_LOCAL_PORT); + sipcall->setLocalExternAudioPort (RANDOM_LOCAL_PORT); + - } -bool RtpTest::pjsipInit(){ +bool RtpTest::pjsipInit() +{ // Create memory cache for pool - pj_caching_pool_init(&_cp, &pj_pool_factory_default_policy, 0); + pj_caching_pool_init (&_cp, &pj_pool_factory_default_policy, 0); - // Create memory pool for application. - _pool = pj_pool_create(&_cp.factory, "rtpTest", 4000, 4000, NULL); + // Create memory pool for application. + _pool = pj_pool_create (&_cp.factory, "rtpTest", 4000, 4000, NULL); if (!_pool) { - _debug("----- RtpTest: Could not initialize pjsip memory pool ------\n"); + _debug ("----- RtpTest: Could not initialize pjsip memory pool ------\n"); return PJ_ENOMEM; } @@ -79,41 +81,44 @@ void RtpTest::testRtpInitClose() audiortp = new AudioRtp(); - _debug("------ void RtpTest::testRtpInit() ------\n"); + _debug ("------ void RtpTest::testRtpInit() ------\n"); + try { - _debug("-------- Open Rtp Session ----------\n"); - audiortp->createNewSession(sipcall); + _debug ("-------- Open Rtp Session ----------\n"); + audiortp->createNewSession (sipcall); + + } catch (...) { + + _debug ("!!! Exception occured while Oppenning Rtp !!!\n"); - } catch(...) { - - _debug("!!! Exception occured while Oppenning Rtp !!!\n"); - } - CPPUNIT_ASSERT(audiortp != NULL); + CPPUNIT_ASSERT (audiortp != NULL); - audiortp->_RTXThread->computeCodecFrameSize(320,8000); + audiortp->_RTXThread->computeCodecFrameSize (320,8000); - // computeNbByteAudioLayer - - _debug("------ Finilize Rtp Initialization ------ \n"); + // computeNbByteAudioLayer + _debug ("------ Finilize Rtp Initialization ------ \n"); - _debug("------ RtpTest::testRtpClose() ------\n"); + + _debug ("------ RtpTest::testRtpClose() ------\n"); try { - _debug("------ Close Rtp Session -------\n"); - CPPUNIT_ASSERT(audiortp->closeRtpSession()); + _debug ("------ Close Rtp Session -------\n"); + CPPUNIT_ASSERT (audiortp->closeRtpSession()); - } catch(...) { + } catch (...) { - _debug("!!! Exception occured while closing Rtp !!!\n"); + _debug ("!!! Exception occured while closing Rtp !!!\n"); } - delete audiortp; audiortp = NULL; + delete audiortp; + + audiortp = NULL; } @@ -122,38 +127,42 @@ void RtpTest::testRtpThread() audiortp = new AudioRtp(); - _debug("-------- Open Rtp Session ----------\n"); + _debug ("-------- Open Rtp Session ----------\n"); + try { - audiortp->createNewSession(sipcall); + audiortp->createNewSession (sipcall); + + } catch (...) { + + _debug ("!!! Exception occured while Oppenning Rtp !!!\n"); - } catch(...) { - - _debug("!!! Exception occured while Oppenning Rtp !!!\n"); - } - _debug("------ void RtpTest::testRtpThread ------\n"); + _debug ("------ void RtpTest::testRtpThread ------\n"); - CPPUNIT_ASSERT(audiortp->_RTXThread->computeCodecFrameSize(160,8000) == 20.0f); - CPPUNIT_ASSERT(audiortp->_RTXThread->computeCodecFrameSize(320,16000) == 20.0f); - CPPUNIT_ASSERT(audiortp->_RTXThread->computeCodecFrameSize(882,44100) == 20.0f); + CPPUNIT_ASSERT (audiortp->_RTXThread->computeCodecFrameSize (160,8000) == 20.0f); + CPPUNIT_ASSERT (audiortp->_RTXThread->computeCodecFrameSize (320,16000) == 20.0f); + CPPUNIT_ASSERT (audiortp->_RTXThread->computeCodecFrameSize (882,44100) == 20.0f); // 20 ms at 44.1 khz corespond to 882 samples (1764 byte) - CPPUNIT_ASSERT(audiortp->_RTXThread->computeNbByteAudioLayer(20.f) == 1764); - - _debug("------ Close Rtp Session -------\n"); + CPPUNIT_ASSERT (audiortp->_RTXThread->computeNbByteAudioLayer (20.f) == 1764); + + _debug ("------ Close Rtp Session -------\n"); + try { - CPPUNIT_ASSERT(audiortp->closeRtpSession()); + CPPUNIT_ASSERT (audiortp->closeRtpSession()); - } catch(...) { + } catch (...) { - _debug("!!! Exception occured while closing Rtp !!!\n"); + _debug ("!!! Exception occured while closing Rtp !!!\n"); } - delete audiortp; audiortp = NULL; + delete audiortp; + + audiortp = NULL; } @@ -173,48 +182,56 @@ void RtpTest::testRtpResampling() audiortp = new AudioRtp(); - _debug("-------- Open Rtp Session ----------\n"); + _debug ("-------- Open Rtp Session ----------\n"); + try { - audiortp->createNewSession(sipcall); + audiortp->createNewSession (sipcall); + + } catch (...) { + + _debug ("!!! Exception occured while Oppenning Rtp !!!\n"); - } catch(...) { - - _debug("!!! Exception occured while Oppenning Rtp !!!\n"); - } - _debug("------ void RtpTest::testRtpResampling ------\n"); + _debug ("------ void RtpTest::testRtpResampling ------\n"); + + CPPUNIT_ASSERT (0 == 0); + rsmpl_nbSample = audiortp->_RTXThread->reSampleData (data, rsmpl_data, 8000, nbSample, UP_SAMPLING); + _debug ("ORIGINAL DATA SET\n"); - CPPUNIT_ASSERT(0 == 0); - rsmpl_nbSample = audiortp->_RTXThread->reSampleData(data, rsmpl_data, 8000, nbSample, UP_SAMPLING); - _debug("ORIGINAL DATA SET\n"); for (int i = 0; i < nbSample; i++) - printf(" %i=>%i ", i, data[i]); - - _debug("RESAMPLED DATA SET\n"); - for (int i = 0; i < rsmpl_nbSample; i++ ) - printf(" %i=>%i ", i, rsmpl_data[i]); - - printf("\n"); - - - _debug("------ Close Rtp Session -------\n"); + printf (" %i=>%i ", i, data[i]); + + _debug ("RESAMPLED DATA SET\n"); + + for (int i = 0; i < rsmpl_nbSample; i++) + printf (" %i=>%i ", i, rsmpl_data[i]); + + printf ("\n"); + + + _debug ("------ Close Rtp Session -------\n"); + try { - CPPUNIT_ASSERT(audiortp->closeRtpSession()); + CPPUNIT_ASSERT (audiortp->closeRtpSession()); - } catch(...) { + } catch (...) { - _debug("!!! Exception occured while closing Rtp !!!\n"); + _debug ("!!! Exception occured while closing Rtp !!!\n"); } - delete audiortp; audiortp = NULL; + delete audiortp; + + audiortp = NULL; } -void RtpTest::tearDown(){ +void RtpTest::tearDown() +{ - delete sipcall; sipcall = NULL; + delete sipcall; + sipcall = NULL; } -- GitLab