diff --git a/sflphone-common/libs/dbus-c++/src/connection.cpp b/sflphone-common/libs/dbus-c++/src/connection.cpp index b7b6729726731f238347799ca5846b371b722fbb..0cc10df95143b90287770be421a87e8372ac3351 100644 --- a/sflphone-common/libs/dbus-c++/src/connection.cpp +++ b/sflphone-common/libs/dbus-c++/src/connection.cpp @@ -42,13 +42,11 @@ using namespace DBus; Connection::Private::Private (DBusConnection *c, Server::Private *s) - : conn (c) , dispatcher (0), server (s) -{ + : conn (c) , dispatcher (0), server (s) { init(); } -Connection::Private::Private (DBusBusType type) -{ +Connection::Private::Private (DBusBusType type) { InternalError e; conn = dbus_bus_get_private (type, e); @@ -58,8 +56,7 @@ Connection::Private::Private (DBusBusType type) init(); } -Connection::Private::~Private() -{ +Connection::Private::~Private() { debug_log ("terminating connection 0x%08x", conn); detach_server(); @@ -79,8 +76,7 @@ Connection::Private::~Private() dbus_connection_unref (conn); } -void Connection::Private::init() -{ +void Connection::Private::init() { dbus_connection_ref (conn); dbus_connection_ref (conn); //todo: the library has to own another reference @@ -94,8 +90,7 @@ void Connection::Private::init() dbus_connection_set_exit_on_disconnect (conn, false); //why was this set to true?? } -void Connection::Private::detach_server() -{ +void Connection::Private::detach_server() { /* Server::Private *tmp = server; server = NULL; @@ -115,8 +110,7 @@ void Connection::Private::detach_server() }*/ } -bool Connection::Private::do_dispatch() -{ +bool Connection::Private::do_dispatch() { debug_log ("dispatching on %p", conn); if (!dbus_connection_get_is_connected (conn)) { @@ -130,8 +124,7 @@ bool Connection::Private::do_dispatch() 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); switch (status) { @@ -151,8 +144,7 @@ void Connection::Private::dispatch_status_stub (DBusConnection *dc, DBusDispatch } } -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); Message msg = Message (new Message::Private (dmsg)); @@ -162,8 +154,7 @@ DBusHandlerResult Connection::Private::message_filter_stub (DBusConnection *conn : 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); @@ -174,34 +165,28 @@ bool Connection::Private::disconn_filter_function (const Message &msg) return false; } -DBusDispatchStatus Connection::Private::dispatch_status() -{ +DBusDispatchStatus Connection::Private::dispatch_status() { return dbus_connection_get_dispatch_status (conn); } -bool Connection::Private::has_something_to_dispatch() -{ +bool Connection::Private::has_something_to_dispatch() { return dispatch_status() == DBUS_DISPATCH_DATA_REMAINS; } -Connection Connection::SystemBus() -{ +Connection Connection::SystemBus() { return Connection (new Private (DBUS_BUS_SYSTEM)); } -Connection Connection::SessionBus() -{ +Connection Connection::SessionBus() { return Connection (new Private (DBUS_BUS_SESSION)); } -Connection Connection::ActivationBus() -{ +Connection Connection::ActivationBus() { 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) @@ -217,24 +202,20 @@ Connection::Connection (const char *address, bool priv) } Connection::Connection (Connection::Private *p) - : _pvt (p) -{ + : _pvt (p) { setup (default_dispatcher); } Connection::Connection (const Connection &c) - : _pvt (c._pvt) -{ + : _pvt (c._pvt) { dbus_connection_ref (_pvt->conn); } -Connection::~Connection() -{ +Connection::~Connection() { dbus_connection_unref (_pvt->conn); } -Dispatcher *Connection::setup (Dispatcher *dispatcher) -{ +Dispatcher *Connection::setup (Dispatcher *dispatcher) { debug_log ("registering stubs for connection %p", _pvt->conn); if (!dispatcher) dispatcher = default_dispatcher; @@ -268,13 +249,11 @@ Dispatcher *Connection::setup (Dispatcher *dispatcher) return prev; } -bool Connection::operator == (const Connection &c) const -{ +bool Connection::operator == (const Connection &c) const { return _pvt->conn == c._pvt->conn; } -bool Connection::register_bus() -{ +bool Connection::register_bus() { InternalError e; bool r = dbus_bus_register (_pvt->conn, e); @@ -284,39 +263,32 @@ bool Connection::register_bus() return r; } -bool Connection::connected() const -{ +bool Connection::connected() const { return dbus_connection_get_is_connected (_pvt->conn); } -void Connection::disconnect() -{ +void Connection::disconnect() { // dbus_connection_disconnect(_pvt->conn); // disappeared in 0.9x 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); } -bool Connection::unique_name (const char *n) -{ +bool Connection::unique_name (const char *n) { return dbus_bus_set_unique_name (_pvt->conn, n); } -const char *Connection::unique_name() const -{ +const char *Connection::unique_name() const { return dbus_bus_get_unique_name (_pvt->conn); } -void Connection::flush() -{ +void Connection::flush() { dbus_connection_flush (_pvt->conn); } -void Connection::add_match (const char *rule) -{ +void Connection::add_match (const char *rule) { InternalError e; dbus_bus_add_match (_pvt->conn, rule, e); @@ -326,8 +298,7 @@ void Connection::add_match (const char *rule) 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); @@ -337,25 +308,21 @@ void Connection::remove_match (const char *rule) 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); } -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); } -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); } -Message Connection::send_blocking (Message &msg, int timeout) -{ +Message Connection::send_blocking (Message &msg, int timeout) { DBusMessage *reply; InternalError e; @@ -366,8 +333,7 @@ Message Connection::send_blocking (Message &msg, int timeout) 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; if (!dbus_connection_send_with_reply (_pvt->conn, msg._pvt->msg, &pending, timeout)) { @@ -377,8 +343,7 @@ PendingCall Connection::send_async (Message &msg, int timeout) 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; debug_log ("%s: registering bus name %s", unique_name(), name); @@ -396,8 +361,7 @@ void Connection::request_name (const char *name, int flags) } } -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); @@ -407,8 +371,7 @@ unsigned long Connection::sender_unix_uid (const char *sender) return ul; } -bool Connection::has_name (const char *name) -{ +bool Connection::has_name (const char *name) { InternalError e; bool b = dbus_bus_name_has_owner (_pvt->conn, name, e); @@ -418,13 +381,11 @@ bool Connection::has_name (const char *name) return b; } -const std::vector<std::string>& Connection::names() -{ +const std::vector<std::string>& Connection::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; bool b = dbus_bus_start_service_by_name (_pvt->conn, name, flags, NULL, e); diff --git a/sflphone-common/libs/dbus-c++/src/debug.cpp b/sflphone-common/libs/dbus-c++/src/debug.cpp index 213a784d05a4a7672a86fc0825e8e0c83a4bdaf4..6ee5176ec5a2a77890980ee1023b4500744b6bfc 100644 --- a/sflphone-common/libs/dbus-c++/src/debug.cpp +++ b/sflphone-common/libs/dbus-c++/src/debug.cpp @@ -31,8 +31,7 @@ #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; diff --git a/sflphone-common/libs/dbus-c++/src/dispatcher.cpp b/sflphone-common/libs/dbus-c++/src/dispatcher.cpp index e71bae99fd48a0309d9f6f1c30e57bd3da8ee90e..b333f43a6f3c3cdff290e90c4109dd729c2f794a 100644 --- a/sflphone-common/libs/dbus-c++/src/dispatcher.cpp +++ b/sflphone-common/libs/dbus-c++/src/dispatcher.cpp @@ -38,23 +38,19 @@ DBus::Dispatcher *DBus::default_dispatcher = NULL; using namespace DBus; Timeout::Timeout (Timeout::Internal *i) - : _int (i) -{ + : _int (i) { dbus_timeout_set_data ( (DBusTimeout *) i, this, NULL); } -int Timeout::interval() const -{ +int Timeout::interval() const { return dbus_timeout_get_interval ( (DBusTimeout *) _int); } -bool Timeout::enabled() const -{ +bool Timeout::enabled() const { return dbus_timeout_get_enabled ( (DBusTimeout *) _int); } -bool Timeout::handle() -{ +bool Timeout::handle() { return dbus_timeout_handle ( (DBusTimeout *) _int); } @@ -62,13 +58,11 @@ bool Timeout::handle() */ Watch::Watch (Watch::Internal *i) - : _int (i) -{ + : _int (i) { dbus_watch_set_data ( (DBusWatch *) i, this, NULL); } -int Watch::descriptor() const -{ +int Watch::descriptor() const { #if HAVE_WIN32 return dbus_watch_get_socket ( (DBusWatch*) _int); #else @@ -76,26 +70,22 @@ int Watch::descriptor() const #endif } -int Watch::flags() const -{ +int Watch::flags() const { return dbus_watch_get_flags ( (DBusWatch *) _int); } -bool Watch::enabled() const -{ +bool Watch::enabled() const { return dbus_watch_get_enabled ( (DBusWatch *) _int); } -bool Watch::handle (int flags) -{ +bool Watch::handle (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); Watch::Internal *w = reinterpret_cast<Watch::Internal *> (watch); @@ -105,8 +95,7 @@ dbus_bool_t Dispatcher::Private::on_add_watch (DBusWatch *watch, void *data) 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); Watch *w = static_cast<Watch *> (dbus_watch_get_data (watch)); @@ -114,15 +103,13 @@ void Dispatcher::Private::on_rem_watch (DBusWatch *watch, void *data) 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)); 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); Timeout::Internal *t = reinterpret_cast<Timeout::Internal *> (timeout); @@ -132,8 +119,7 @@ dbus_bool_t Dispatcher::Private::on_add_timeout (DBusTimeout *timeout, void *dat 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); Timeout *t = static_cast<Timeout *> (dbus_timeout_get_data (timeout)); @@ -141,23 +127,20 @@ void Dispatcher::Private::on_rem_timeout (DBusTimeout *timeout, void *data) 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)); 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(); } -bool Dispatcher::has_something_to_dispatch() -{ +bool Dispatcher::has_something_to_dispatch() { _mutex_p.lock(); bool has_something = false; @@ -173,8 +156,7 @@ bool Dispatcher::has_something_to_dispatch() } -void Dispatcher::dispatch_pending() -{ +void Dispatcher::dispatch_pending() { _mutex_p.lock(); // SEEME: dbus-glib is dispatching only one message at a time to not starve the loop/other things... @@ -199,8 +181,7 @@ void Dispatcher::dispatch_pending() _mutex_p.unlock(); } -void DBus::_init_threading() -{ +void DBus::_init_threading() { #ifdef DBUS_HAS_THREADS_INIT_DEFAULT dbus_threads_init_default(); #else @@ -219,8 +200,7 @@ void DBus::_init_threading ( CondVarWaitTimeoutFn c4, CondVarWakeOneFn c5, CondVarWakeAllFn c6 -) -{ +) { #ifndef DBUS_HAS_RECURSIVE_MUTEX DBusThreadFunctions functions = { DBUS_THREAD_FUNCTIONS_MUTEX_NEW_MASK | diff --git a/sflphone-common/libs/dbus-c++/src/ecore-integration.cpp b/sflphone-common/libs/dbus-c++/src/ecore-integration.cpp index d18d4b1136cc2b43de1f4eaa22841cb4fb4c8f80..d18192f279c12879883cf0b38bc53da646480d6b 100644 --- a/sflphone-common/libs/dbus-c++/src/ecore-integration.cpp +++ b/sflphone-common/libs/dbus-c++/src/ecore-integration.cpp @@ -32,26 +32,22 @@ using namespace DBus; Ecore::BusTimeout::BusTimeout (Timeout::Internal* ti) - : Timeout (ti) -{ + : Timeout (ti) { _enable(); } -Ecore::BusTimeout::~BusTimeout() -{ +Ecore::BusTimeout::~BusTimeout() { _disable(); } -void Ecore::BusTimeout::toggle() -{ +void Ecore::BusTimeout::toggle() { debug_log ("ecore: timeout %p toggled (%s)", this, Timeout::enabled() ? "on":"off"); 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); debug_log ("Ecore::BusTimeout::timeout_handler( void *data )"); @@ -61,37 +57,32 @@ int Ecore::BusTimeout::timeout_handler (void *data) return 1; // 1 -> reshedule in ecore for next timer interval } -void Ecore::BusTimeout::_enable() -{ +void Ecore::BusTimeout::_enable() { debug_log ("Ecore::BusTimeout::_enable()"); _etimer = ecore_timer_add ( ( (double) Timeout::interval()) /1000, timeout_handler, this); } -void Ecore::BusTimeout::_disable() -{ +void Ecore::BusTimeout::_disable() { debug_log ("Ecore::BusTimeout::_disable()"); ecore_timer_del (_etimer); } -static bool watch_prepare (int *timeout) -{ +static bool watch_prepare (int *timeout) { debug_log ("ecore: watch_prepare"); *timeout = -1; return false; } -static bool watch_check() -{ +static bool watch_check() { debug_log ("ecore: watch_check"); return true; } -static bool watch_dispatch (void *data) -{ +static bool watch_dispatch (void *data) { debug_log ("ecore: watch_dispatch"); bool cb = true; @@ -100,26 +91,22 @@ static bool watch_dispatch (void *data) } Ecore::BusWatch::BusWatch (Watch::Internal* wi) - : Watch (wi) -{ + : Watch (wi) { _enable(); } -Ecore::BusWatch::~BusWatch() -{ +Ecore::BusWatch::~BusWatch() { _disable(); } -void Ecore::BusWatch::toggle() -{ +void Ecore::BusWatch::toggle() { debug_log ("ecore: watch %p toggled (%s)", this, Watch::enabled() ? "on":"off"); 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); debug_log ("ecore: watch_handler_read"); @@ -133,8 +120,7 @@ int Ecore::BusWatch::watch_handler_read (void *data, Ecore_Fd_Handler *fdh) 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); debug_log ("ecore: watch_handler_error"); @@ -146,8 +132,7 @@ int Ecore::BusWatch::watch_handler_error (void *data, Ecore_Fd_Handler *fdh) return 1; } -void Ecore::BusWatch::_enable() -{ +void Ecore::BusWatch::_enable() { debug_log ("Ecore::BusWatch::_enable()"); int flags = Watch::flags(); @@ -169,18 +154,15 @@ void Ecore::BusWatch::_enable() ecore_main_fd_handler_active_set (fd_handler_error, ECORE_FD_ERROR); } -void Ecore::BusWatch::_disable() -{ +void Ecore::BusWatch::_disable() { 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); debug_log ("ecore: added timeout %p (%s)", t, t->enabled() ? "on":"off"); @@ -188,15 +170,13 @@ Timeout* Ecore::BusDispatcher::add_timeout (Timeout::Internal* wi) return t; } -void Ecore::BusDispatcher::rem_timeout (Timeout* t) -{ +void Ecore::BusDispatcher::rem_timeout (Timeout* t) { debug_log ("ecore: removed timeout %p", 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); debug_log ("ecore: added watch %p (%s) fd=%d flags=%d", @@ -205,8 +185,7 @@ Watch* Ecore::BusDispatcher::add_watch (Watch::Internal* wi) return w; } -void Ecore::BusDispatcher::rem_watch (Watch* w) -{ +void Ecore::BusDispatcher::rem_watch (Watch* w) { debug_log ("ecore: removed watch %p", w); delete w; diff --git a/sflphone-common/libs/dbus-c++/src/error.cpp b/sflphone-common/libs/dbus-c++/src/error.cpp index 89d91d1f39d2d604f6de6313788530b2e5176ca7..ccb3da960fec2d0ace11c4e860d07cc69a15c3af 100644 --- a/sflphone-common/libs/dbus-c++/src/error.cpp +++ b/sflphone-common/libs/dbus-c++/src/error.cpp @@ -39,51 +39,41 @@ using namespace DBus; */ Error::Error() - : _int (new InternalError) -{} + : _int (new InternalError) {} Error::Error (InternalError &i) - : _int (new InternalError (i)) -{} + : _int (new InternalError (i)) {} Error::Error (const char *name, const char *message) - : _int (new InternalError) -{ + : _int (new InternalError) { set (name, message); } Error::Error (Message &m) - : _int (new InternalError) -{ + : _int (new InternalError) { dbus_set_error_from_message (& (_int->error), m._pvt->msg); } -Error::~Error() throw() -{ +Error::~Error() throw() { } -const char *Error::name() const -{ +const char *Error::name() const { return _int->error.name; } -const char *Error::message() const -{ +const char *Error::message() const { return _int->error.message; } -bool Error::is_set() const -{ +bool Error::is_set() const { 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); } -const char *Error::what() const throw() -{ +const char *Error::what() const throw() { 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 6947f28130fa5d27e4b83038246626c0a1b1ba9a..f367623e5f5b9fb887d5ff86fb0885fe295e062e 100644 --- a/sflphone-common/libs/dbus-c++/src/eventloop-integration.cpp +++ b/sflphone-common/libs/dbus-c++/src/eventloop-integration.cpp @@ -35,21 +35,18 @@ using namespace DBus; BusTimeout::BusTimeout (Timeout::Internal *ti, BusDispatcher *bd) - : Timeout (ti), DefaultTimeout (Timeout::interval(), true, bd) -{ + : Timeout (ti), DefaultTimeout (Timeout::interval(), true, bd) { DefaultTimeout::enabled (Timeout::enabled()); } -void BusTimeout::toggle() -{ +void BusTimeout::toggle() { debug_log ("timeout %p toggled (%s)", this, Timeout::enabled() ? "on":"off"); DefaultTimeout::enabled (Timeout::enabled()); } BusWatch::BusWatch (Watch::Internal *wi, BusDispatcher *bd) - : Watch (wi), DefaultWatch (Watch::descriptor(), 0, bd) -{ + : Watch (wi), DefaultWatch (Watch::descriptor(), 0, bd) { int flags = POLLHUP | POLLERR; if (Watch::flags() & DBUS_WATCH_READABLE) @@ -63,15 +60,13 @@ BusWatch::BusWatch (Watch::Internal *wi, BusDispatcher *bd) DefaultWatch::enabled (Watch::enabled()); } -void BusWatch::toggle() -{ +void BusWatch::toggle() { debug_log ("watch %p toggled (%s)", this, Watch::enabled() ? "on":"off"); DefaultWatch::enabled (Watch::enabled()); } -void BusDispatcher::enter() -{ +void BusDispatcher::enter() { debug_log ("entering dispatcher %p", this); _running = true; @@ -83,20 +78,17 @@ void BusDispatcher::enter() debug_log ("leaving dispatcher %p", this); } -void BusDispatcher::leave() -{ +void BusDispatcher::leave() { _running = false; terminate(); } -void BusDispatcher::do_iteration() -{ +void BusDispatcher::do_iteration() { dispatch_pending(); dispatch(); } -Timeout *BusDispatcher::add_timeout (Timeout::Internal *ti) -{ +Timeout *BusDispatcher::add_timeout (Timeout::Internal *ti) { BusTimeout *bt = new BusTimeout (ti, this); bt->expired = new Callback<BusDispatcher, void, DefaultTimeout &> (this, &BusDispatcher::timeout_expired); @@ -108,15 +100,13 @@ Timeout *BusDispatcher::add_timeout (Timeout::Internal *ti) return bt; } -void BusDispatcher::rem_timeout (Timeout *t) -{ +void BusDispatcher::rem_timeout (Timeout *t) { debug_log ("removed timeout %p", t); delete t; } -Watch *BusDispatcher::add_watch (Watch::Internal *wi) -{ +Watch *BusDispatcher::add_watch (Watch::Internal *wi) { BusWatch *bw = new BusWatch (wi, this); bw->ready = new Callback<BusDispatcher, void, DefaultWatch &> (this, &BusDispatcher::watch_ready); @@ -128,15 +118,13 @@ Watch *BusDispatcher::add_watch (Watch::Internal *wi) return bw; } -void BusDispatcher::rem_watch (Watch *w) -{ +void BusDispatcher::rem_watch (Watch *w) { debug_log ("removed watch %p", w); delete w; } -void BusDispatcher::timeout_expired (DefaultTimeout &et) -{ +void BusDispatcher::timeout_expired (DefaultTimeout &et) { debug_log ("timeout %p expired", &et); BusTimeout *timeout = reinterpret_cast<BusTimeout *> (et.data()); @@ -144,8 +132,7 @@ void BusDispatcher::timeout_expired (DefaultTimeout &et) timeout->handle(); } -void BusDispatcher::watch_ready (DefaultWatch &ew) -{ +void BusDispatcher::watch_ready (DefaultWatch &ew) { BusWatch *watch = reinterpret_cast<BusWatch *> (ew.data()); debug_log ("watch %p ready, flags=%d state=%d", diff --git a/sflphone-common/libs/dbus-c++/src/eventloop.cpp b/sflphone-common/libs/dbus-c++/src/eventloop.cpp index f74cafeaa6385fb66bf45d96f64315c25f3ec0a8..94bf59b389069754f9d6a016a717d6abac8b0e1d 100644 --- a/sflphone-common/libs/dbus-c++/src/eventloop.cpp +++ b/sflphone-common/libs/dbus-c++/src/eventloop.cpp @@ -36,14 +36,12 @@ using namespace DBus; -static double millis (timeval tv) -{ +static double millis (timeval tv) { 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) -{ + : _enabled (true), _interval (interval), _repeat (repeat), _expiration (0), _data (0), _disp (ed) { timeval now; gettimeofday (&now, NULL); @@ -54,57 +52,48 @@ DefaultTimeout::DefaultTimeout (int interval, bool repeat, DefaultMainLoop *ed) _disp->_mutex_t.unlock(); } -DefaultTimeout::~DefaultTimeout() -{ +DefaultTimeout::~DefaultTimeout() { _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) -{ + : _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(); } -DefaultWatch::~DefaultWatch() -{ +DefaultWatch::~DefaultWatch() { _disp->_mutex_w.lock(); _disp->_watches.remove (this); _disp->_mutex_w.unlock(); } -DefaultMutex::DefaultMutex() -{ +DefaultMutex::DefaultMutex() { pthread_mutex_init (&_mutex, NULL); } -DefaultMutex::~DefaultMutex() -{ +DefaultMutex::~DefaultMutex() { pthread_mutex_destroy (&_mutex); } -void DefaultMutex::lock() -{ +void DefaultMutex::lock() { pthread_mutex_lock (&_mutex); } -void DefaultMutex::unlock() -{ +void DefaultMutex::unlock() { pthread_mutex_unlock (&_mutex); } -DefaultMainLoop::DefaultMainLoop() -{ +DefaultMainLoop::DefaultMainLoop() { if (pipe (_terminateFd) < 0) { throw ErrorFailed ("unable to create unamed pipe"); } } -DefaultMainLoop::~DefaultMainLoop() -{ +DefaultMainLoop::~DefaultMainLoop() { _mutex_w.lock(); DefaultWatches::iterator wi = _watches.begin(); @@ -140,13 +129,11 @@ DefaultMainLoop::~DefaultMainLoop() _mutex_t.unlock(); } -void DefaultMainLoop::terminate() -{ +void DefaultMainLoop::terminate() { write (_terminateFd[1], " ", 1); } -void DefaultMainLoop::dispatch() -{ +void DefaultMainLoop::dispatch() { _mutex_w.lock(); int nfd = _watches.size() + 1; diff --git a/sflphone-common/libs/dbus-c++/src/glib-integration.cpp b/sflphone-common/libs/dbus-c++/src/glib-integration.cpp index 1739670bfc49bb7eaa79ed55b8113caf5a161d39..8785608fa7f15b5c507d9fb576492ab4b00a56c3 100644 --- a/sflphone-common/libs/dbus-c++/src/glib-integration.cpp +++ b/sflphone-common/libs/dbus-c++/src/glib-integration.cpp @@ -31,27 +31,23 @@ using namespace DBus; Glib::BusTimeout::BusTimeout (Timeout::Internal *ti, GMainContext *ctx, int priority) - : Timeout (ti), _ctx (ctx), _priority (priority), _source (NULL) -{ + : Timeout (ti), _ctx (ctx), _priority (priority), _source (NULL) { if (Timeout::enabled()) _enable(); } -Glib::BusTimeout::~BusTimeout() -{ +Glib::BusTimeout::~BusTimeout() { _disable(); } -void Glib::BusTimeout::toggle() -{ +void Glib::BusTimeout::toggle() { debug_log ("glib: timeout %p toggled (%s)", this, Timeout::enabled() ? "on":"off"); 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); t->handle(); @@ -59,8 +55,7 @@ gboolean Glib::BusTimeout::timeout_handler (gpointer data) return TRUE; } -void Glib::BusTimeout::_enable() -{ +void Glib::BusTimeout::_enable() { if (_source) _disable(); // be sane @@ -73,8 +68,7 @@ void Glib::BusTimeout::_enable() g_source_attach (_source, _ctx); } -void Glib::BusTimeout::_disable() -{ +void Glib::BusTimeout::_disable() { if (_source) { g_source_destroy (_source); _source = NULL; @@ -86,24 +80,21 @@ struct BusSource { GPollFD poll; }; -static gboolean watch_prepare (GSource *source, gint *timeout) -{ +static gboolean watch_prepare (GSource *source, gint *timeout) { //debug_log("glib: watch_prepare"); *timeout = -1; return FALSE; } -static gboolean watch_check (GSource *source) -{ +static gboolean watch_check (GSource *source) { //debug_log("glib: watch_check"); 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"); gboolean cb = callback (data); @@ -118,27 +109,23 @@ static GSourceFuncs watch_funcs = { }; Glib::BusWatch::BusWatch (Watch::Internal *wi, GMainContext *ctx, int priority) - : Watch (wi), _ctx (ctx), _priority (priority), _source (NULL) -{ + : Watch (wi), _ctx (ctx), _priority (priority), _source (NULL) { if (Watch::enabled()) _enable(); } -Glib::BusWatch::~BusWatch() -{ +Glib::BusWatch::~BusWatch() { _disable(); } -void Glib::BusWatch::toggle() -{ +void Glib::BusWatch::toggle() { debug_log ("glib: watch %p toggled (%s)", this, Watch::enabled() ? "on":"off"); 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); BusSource *io = (BusSource *) (w->_source); @@ -162,8 +149,7 @@ gboolean Glib::BusWatch::watch_handler (gpointer data) return TRUE; } -void Glib::BusWatch::_enable() -{ +void Glib::BusWatch::_enable() { if (_source) _disable(); // be sane @@ -202,8 +188,7 @@ void Glib::BusWatch::_enable() g_source_attach (_source, _ctx); } -void Glib::BusWatch::_disable() -{ +void Glib::BusWatch::_disable() { if (!_source) return; @@ -228,8 +213,7 @@ struct DispatcherSource { }; -static gboolean dispatcher_prepare (GSource *source, gint *timeout) -{ +static gboolean dispatcher_prepare (GSource *source, gint *timeout) { Dispatcher *dispatcher = ( (DispatcherSource*) source)->dispatcher; *timeout = -1; @@ -237,16 +221,14 @@ static gboolean dispatcher_prepare (GSource *source, gint *timeout) return dispatcher->has_something_to_dispatch() ? TRUE:FALSE; } -static gboolean dispatcher_check (GSource *source) -{ +static gboolean dispatcher_check (GSource *source) { return FALSE; } static gboolean dispatcher_dispatch (GSource *source, GSourceFunc callback, - gpointer user_data) -{ + gpointer user_data) { Dispatcher *dispatcher = ( (DispatcherSource*) source)->dispatcher; dispatcher->dispatch_pending(); @@ -261,12 +243,10 @@ static const GSourceFuncs dispatcher_funcs = { }; Glib::BusDispatcher::BusDispatcher() - : _ctx (NULL), _priority (G_PRIORITY_DEFAULT), _source (NULL) -{ + : _ctx (NULL), _priority (G_PRIORITY_DEFAULT), _source (NULL) { } -Glib::BusDispatcher::~BusDispatcher() -{ +Glib::BusDispatcher::~BusDispatcher() { if (_source) { GSource *temp = _source; _source = NULL; @@ -279,8 +259,7 @@ Glib::BusDispatcher::~BusDispatcher() 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 _ctx = ctx ? ctx : g_main_context_default(); @@ -294,8 +273,7 @@ void Glib::BusDispatcher::attach (GMainContext *ctx) 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); debug_log ("glib: added timeout %p (%s)", t, t->enabled() ? "on":"off"); @@ -303,15 +281,13 @@ Timeout *Glib::BusDispatcher::add_timeout (Timeout::Internal *wi) return t; } -void Glib::BusDispatcher::rem_timeout (Timeout *t) -{ +void Glib::BusDispatcher::rem_timeout (Timeout *t) { debug_log ("glib: removed timeout %p", 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); debug_log ("glib: added watch %p (%s) fd=%d flags=%d", @@ -320,14 +296,12 @@ Watch *Glib::BusDispatcher::add_watch (Watch::Internal *wi) return w; } -void Glib::BusDispatcher::rem_watch (Watch *w) -{ +void Glib::BusDispatcher::rem_watch (Watch *w) { debug_log ("glib: removed watch %p", w); delete w; } -void Glib::BusDispatcher::set_priority (int priority) -{ +void Glib::BusDispatcher::set_priority (int priority) { _priority = priority; } diff --git a/sflphone-common/libs/dbus-c++/src/interface.cpp b/sflphone-common/libs/dbus-c++/src/interface.cpp index aefcd1dea91bde9fe54765990b219d4e1cde01cd..95c11efdc41ff5f0e739c00307f7a2c13e7a759c 100644 --- a/sflphone-common/libs/dbus-c++/src/interface.cpp +++ b/sflphone-common/libs/dbus-c++/src/interface.cpp @@ -33,29 +33,24 @@ using namespace DBus; Interface::Interface (const std::string &name) - : _name (name) -{} + : _name (name) {} -Interface::~Interface() -{} +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); return ii != _interfaces.end() ? ii->second : NULL; } InterfaceAdaptor::InterfaceAdaptor (const std::string &name) - : Interface (name) -{ + : Interface (name) { debug_log ("adding interface %s", name.c_str()); _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); @@ -67,8 +62,7 @@ Message InterfaceAdaptor::dispatch_method (const CallMessage &msg) } } -void InterfaceAdaptor::emit_signal (const SignalMessage &sig) -{ +void InterfaceAdaptor::emit_signal (const SignalMessage &sig) { SignalMessage &sig2 = const_cast<SignalMessage &> (sig); if (sig2.interface() == NULL) @@ -77,8 +71,7 @@ void InterfaceAdaptor::emit_signal (const SignalMessage &sig) _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); if (pti != _properties.end()) { @@ -91,8 +84,7 @@ Variant *InterfaceAdaptor::get_property (const std::string &name) 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); if (pti != _properties.end()) { @@ -112,23 +104,20 @@ void InterfaceAdaptor::set_property (const std::string &name, Variant &value) 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); return ii != _interfaces.end() ? ii->second : NULL; } InterfaceProxy::InterfaceProxy (const std::string &name) - : Interface (name) -{ + : Interface (name) { debug_log ("adding interface %s", name.c_str()); _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); @@ -145,8 +134,7 @@ bool InterfaceProxy::dispatch_signal (const SignalMessage &msg) } } -Message InterfaceProxy::invoke_method (const CallMessage &call) -{ +Message InterfaceProxy::invoke_method (const CallMessage &call) { CallMessage &call2 = const_cast<CallMessage &> (call); if (call.interface() == NULL) @@ -155,8 +143,7 @@ Message InterfaceProxy::invoke_method (const CallMessage &call) 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); if (call.interface() == NULL) diff --git a/sflphone-common/libs/dbus-c++/src/introspection.cpp b/sflphone-common/libs/dbus-c++/src/introspection.cpp index 41f6439f4aad8eae013e776a3909c96ad95b1c37..15eb5fcc0df143c64b8bc287d0e8163e36b575a3 100644 --- a/sflphone-common/libs/dbus-c++/src/introspection.cpp +++ b/sflphone-common/libs/dbus-c++/src/introspection.cpp @@ -38,13 +38,11 @@ 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); } -Message IntrospectableAdaptor::Introspect (const CallMessage &call) -{ +Message IntrospectableAdaptor::Introspect (const CallMessage &call) { debug_log ("requested introspection data"); std::ostringstream xml; @@ -143,8 +141,7 @@ Message IntrospectableAdaptor::Introspect (const CallMessage &call) return reply; } -IntrospectedInterface *const IntrospectableAdaptor::introspect() const -{ +IntrospectedInterface *const IntrospectableAdaptor::introspect() const { static IntrospectedArgument Introspect_args[] = { { "data", "s", false }, { 0, 0, 0 } @@ -169,11 +166,9 @@ IntrospectedInterface *const IntrospectableAdaptor::introspect() const } IntrospectableProxy::IntrospectableProxy() - : InterfaceProxy (introspectable_name) -{} + : InterfaceProxy (introspectable_name) {} -std::string IntrospectableProxy::Introspect() -{ +std::string IntrospectableProxy::Introspect() { DBus::CallMessage call; call.member ("Introspect"); diff --git a/sflphone-common/libs/dbus-c++/src/message.cpp b/sflphone-common/libs/dbus-c++/src/message.cpp index 4f3425e08dc23c67edac9d849f717d5a2d29ef11..0daa307b15db81efeaea3a720c5a5afbe5fe4c72 100644 --- a/sflphone-common/libs/dbus-c++/src/message.cpp +++ b/sflphone-common/libs/dbus-c++/src/message.cpp @@ -38,233 +38,194 @@ using namespace DBus; /* */ -int MessageIter::type() -{ +int MessageIter::type() { return dbus_message_iter_get_arg_type ( (DBusMessageIter *) &_iter); } -bool MessageIter::at_end() -{ +bool MessageIter::at_end() { return type() == DBUS_TYPE_INVALID; } -bool MessageIter::has_next() -{ +bool MessageIter::has_next() { return dbus_message_iter_has_next ( (DBusMessageIter *) &_iter); } -MessageIter &MessageIter::operator ++() -{ +MessageIter &MessageIter::operator ++() { dbus_message_iter_next ( (DBusMessageIter *) &_iter); return (*this); } -MessageIter MessageIter::operator ++ (int) -{ +MessageIter MessageIter::operator ++ (int) { 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); } -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"); 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); } -unsigned char MessageIter::get_byte() -{ +unsigned char MessageIter::get_byte() { 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); } -bool MessageIter::get_bool() -{ +bool MessageIter::get_bool() { 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); } -signed short MessageIter::get_int16() -{ +signed short MessageIter::get_int16() { 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); } -unsigned short MessageIter::get_uint16() -{ +unsigned short MessageIter::get_uint16() { 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); } -signed int MessageIter::get_int32() -{ +signed int MessageIter::get_int32() { 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); } -unsigned int MessageIter::get_uint32() -{ +unsigned int MessageIter::get_uint32() { unsigned int u; get_basic (DBUS_TYPE_UINT32, &u); return u; } -signed long long MessageIter::get_int64() -{ +signed long long MessageIter::get_int64() { 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); } -unsigned long long MessageIter::get_uint64() -{ +unsigned long long MessageIter::get_uint64() { 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); } -double MessageIter::get_double() -{ +double MessageIter::get_double() { 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); } -bool MessageIter::append_string (const char *chars) -{ +bool MessageIter::append_string (const char *chars) { return append_basic (DBUS_TYPE_STRING, &chars); } -const char *MessageIter::get_string() -{ +const char *MessageIter::get_string() { 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); } -const char *MessageIter::get_path() -{ +const char *MessageIter::get_path() { 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); } -const char *MessageIter::get_signature() -{ +const char *MessageIter::get_signature() { 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; } -char *MessageIter::signature() const -{ +char *MessageIter::signature() const { 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); } -int MessageIter::array_type() -{ +int MessageIter::array_type() { 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; } -bool MessageIter::is_array() -{ +bool MessageIter::is_array() { return dbus_message_iter_get_arg_type ( (DBusMessageIter *) &_iter) == DBUS_TYPE_ARRAY; } -bool MessageIter::is_dict() -{ +bool MessageIter::is_dict() { 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) @@ -272,8 +233,7 @@ MessageIter MessageIter::new_array (const char *sig) 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) @@ -281,8 +241,7 @@ MessageIter MessageIter::new_variant (const char *sig) return var; } -MessageIter MessageIter::new_struct() -{ +MessageIter MessageIter::new_struct() { MessageIter stu (msg()); dbus_message_iter_open_container ( (DBusMessageIter *) _iter, DBUS_TYPE_STRUCT, NULL, (DBusMessageIter *) & (stu._iter) @@ -290,8 +249,7 @@ MessageIter MessageIter::new_struct() return stu; } -MessageIter MessageIter::new_dict_entry() -{ +MessageIter MessageIter::new_dict_entry() { MessageIter ent (msg()); dbus_message_iter_open_container ( (DBusMessageIter *) _iter, DBUS_TYPE_DICT_ENTRY, NULL, (DBusMessageIter *) & (ent._iter) @@ -299,13 +257,11 @@ MessageIter MessageIter::new_dict_entry() return ent; } -void MessageIter::close_container (MessageIter &container) -{ +void MessageIter::close_container (MessageIter &container) { dbus_message_iter_close_container ( (DBusMessageIter *) &_iter, (DBusMessageIter *) & (container._iter)); } -static bool is_basic_type (int typecode) -{ +static bool is_basic_type (int typecode) { switch (typecode) { case 'y': @@ -338,8 +294,7 @@ static bool is_basic_type (int typecode) } } -void MessageIter::copy_data (MessageIter &to) -{ +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()); @@ -373,29 +328,24 @@ void MessageIter::copy_data (MessageIter &to) */ Message::Message() - : _pvt (new Private) -{ + : _pvt (new Private) { } Message::Message (Message::Private *p, bool incref) - : _pvt (p) -{ + : _pvt (p) { if (_pvt->msg && incref) dbus_message_ref (_pvt->msg); } Message::Message (const Message &m) - : _pvt (m._pvt) -{ + : _pvt (m._pvt) { dbus_message_ref (_pvt->msg); } -Message::~Message() -{ +Message::~Message() { dbus_message_unref (_pvt->msg); } -Message &Message::operator = (const Message &m) -{ +Message &Message::operator = (const Message &m) { if (&m != this) { dbus_message_unref (_pvt->msg); _pvt = m._pvt; @@ -405,14 +355,12 @@ Message &Message::operator = (const Message &m) return *this; } -Message Message::copy() -{ +Message Message::copy() { 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); @@ -422,70 +370,57 @@ bool Message::append (int first_type, ...) return b; } -void Message::terminate() -{ +void Message::terminate() { dbus_message_append_args (_pvt->msg, DBUS_TYPE_INVALID); } -int Message::type() const -{ +int Message::type() const { return dbus_message_get_type (_pvt->msg); } -int Message::serial() const -{ +int Message::serial() const { return dbus_message_get_serial (_pvt->msg); } -int Message::reply_serial() const -{ +int Message::reply_serial() const { 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); } -const char *Message::sender() const -{ +const char *Message::sender() const { 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); } -const char *Message::destination() const -{ +const char *Message::destination() const { 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); } -bool Message::is_error() const -{ +bool Message::is_error() const { 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); } -MessageIter Message::writer() -{ +MessageIter Message::writer() { MessageIter iter (*this); dbus_message_iter_init_append (_pvt->msg, (DBusMessageIter *) & (iter._iter)); return iter; } -MessageIter Message::reader() const -{ +MessageIter Message::reader() const { MessageIter iter (const_cast<Message &> (*this)); dbus_message_iter_init (_pvt->msg, (DBusMessageIter *) & (iter._iter)); return iter; @@ -494,153 +429,129 @@ MessageIter Message::reader() const /* */ -ErrorMessage::ErrorMessage() -{ +ErrorMessage::ErrorMessage() { _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); } -bool ErrorMessage::operator == (const ErrorMessage &m) const -{ +bool ErrorMessage::operator == (const ErrorMessage &m) const { return dbus_message_is_error (_pvt->msg, m.name()); } -const char *ErrorMessage::name() const -{ +const char *ErrorMessage::name() const { 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); } /* */ -SignalMessage::SignalMessage (const char *name) -{ +SignalMessage::SignalMessage (const char *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); } -bool SignalMessage::operator == (const SignalMessage &m) const -{ +bool SignalMessage::operator == (const SignalMessage &m) const { return dbus_message_is_signal (_pvt->msg, m.interface(), m.member()); } const char *SignalMessage::interface() const { - return dbus_message_get_interface (_pvt->msg); - } + return dbus_message_get_interface (_pvt->msg); +} bool SignalMessage::interface (const char *i) { return dbus_message_set_interface (_pvt->msg, i); } -const char *SignalMessage::member() const -{ +const char *SignalMessage::member() const { 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); } -const char *SignalMessage::path() const -{ +const char *SignalMessage::path() const { return dbus_message_get_path (_pvt->msg); } -char ** SignalMessage::path_split() const -{ +char ** SignalMessage::path_split() const { 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); } /* */ -CallMessage::CallMessage() -{ +CallMessage::CallMessage() { _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); } -bool CallMessage::operator == (const CallMessage &m) const -{ +bool CallMessage::operator == (const CallMessage &m) const { return dbus_message_is_method_call (_pvt->msg, m.interface(), m.member()); } const char *CallMessage::interface() const { - return dbus_message_get_interface (_pvt->msg); - } + return dbus_message_get_interface (_pvt->msg); +} bool CallMessage::interface (const char *i) { return dbus_message_set_interface (_pvt->msg, i); } -const char *CallMessage::member() const -{ +const char *CallMessage::member() const { 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); } -const char *CallMessage::path() const -{ +const char *CallMessage::path() const { return dbus_message_get_path (_pvt->msg); } -char ** CallMessage::path_split() const -{ +char ** CallMessage::path_split() const { 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); } -const char *CallMessage::signature() const -{ +const char *CallMessage::signature() const { 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)); } -const char *ReturnMessage::signature() const -{ +const char *ReturnMessage::signature() const { 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 4fa8cd15d11a099afae8a3ccbf52cbe2d0f1da90..a54122fdc8d27ec10cd4a277467bb9ee94688751 100644 --- a/sflphone-common/libs/dbus-c++/src/object.cpp +++ b/sflphone-common/libs/dbus-c++/src/object.cpp @@ -40,12 +40,10 @@ using namespace DBus; Object::Object (Connection &conn, const Path &path, const char *service) - : _conn (conn), _path (path), _service (service ? service : "") -{ + : _conn (conn), _path (path), _service (service ? service : "") { } -Object::~Object() -{ +Object::~Object() { } struct ObjectAdaptor::Private { @@ -59,13 +57,11 @@ static DBusObjectPathVTable _vtable = { 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 ? } -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) { @@ -89,8 +85,7 @@ DBusHandlerResult ObjectAdaptor::Private::message_function_stub (DBusConnection 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); if (ati != _adaptor_table.end()) @@ -99,8 +94,7 @@ ObjectAdaptor *ObjectAdaptor::from_path (const Path &path) return NULL; } -ObjectAdaptorPList ObjectAdaptor::from_path_prefix (const std::string &prefix) -{ +ObjectAdaptorPList ObjectAdaptor::from_path_prefix (const std::string &prefix) { ObjectAdaptorPList ali; ObjectAdaptorTable::iterator ati = _adaptor_table.begin(); @@ -117,8 +111,7 @@ ObjectAdaptorPList ObjectAdaptor::from_path_prefix (const std::string &prefix) return ali; } -ObjectPathList ObjectAdaptor::child_nodes_from_prefix (const std::string &prefix) -{ +ObjectPathList ObjectAdaptor::child_nodes_from_prefix (const std::string &prefix) { ObjectPathList ali; ObjectAdaptorTable::iterator ati = _adaptor_table.begin(); @@ -143,18 +136,15 @@ ObjectPathList ObjectAdaptor::child_nodes_from_prefix (const std::string &prefix } ObjectAdaptor::ObjectAdaptor (Connection &conn, const Path &path) - : Object (conn, path, conn.unique_name()) -{ + : Object (conn, path, conn.unique_name()) { register_obj(); } -ObjectAdaptor::~ObjectAdaptor() -{ +ObjectAdaptor::~ObjectAdaptor() { unregister_obj(); } -void ObjectAdaptor::register_obj() -{ +void ObjectAdaptor::register_obj() { debug_log ("registering local object %s", path().c_str()); if (!dbus_connection_register_object_path (conn()._pvt->conn, path().c_str(), &_vtable, this)) { @@ -164,8 +154,7 @@ void ObjectAdaptor::register_obj() _adaptor_table[path() ] = this; } -void ObjectAdaptor::unregister_obj() -{ +void ObjectAdaptor::unregister_obj() { _adaptor_table.erase (path()); debug_log ("unregistering local object %s", path().c_str()); @@ -173,8 +162,7 @@ void ObjectAdaptor::unregister_obj() 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()); conn().send (sig); @@ -184,8 +172,7 @@ 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: { @@ -221,14 +208,12 @@ bool ObjectAdaptor::handle_message (const Message &msg) } } -void ObjectAdaptor::return_later (const Tag *tag) -{ +void ObjectAdaptor::return_later (const Tag *tag) { ReturnLaterError rle = { tag }; throw rle; } -void ObjectAdaptor::return_now (Continuation *ret) -{ +void ObjectAdaptor::return_now (Continuation *ret) { ret->_conn.send (ret->_return); ContinuationMap::iterator di = _continuations.find (ret->_tag); @@ -238,8 +223,7 @@ void ObjectAdaptor::return_now (Continuation *ret) _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())); ContinuationMap::iterator di = _continuations.find (ret->_tag); @@ -249,16 +233,14 @@ void ObjectAdaptor::return_error (Continuation *ret, const Error error) _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); 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) -{ + : _conn (conn), _call (call), _return (_call), _tag (tag) { _writer = _return.writer(); //todo: verify } @@ -266,18 +248,15 @@ ObjectAdaptor::Continuation::Continuation (Connection &conn, const CallMessage & */ ObjectProxy::ObjectProxy (Connection &conn, const Path &path, const char *service) - : Object (conn, path, service) -{ + : Object (conn, path, service) { register_obj(); } -ObjectProxy::~ObjectProxy() -{ +ObjectProxy::~ObjectProxy() { unregister_obj(); } -void ObjectProxy::register_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); @@ -293,8 +272,7 @@ void ObjectProxy::register_obj() } } -void ObjectProxy::unregister_obj() -{ +void ObjectProxy::unregister_obj() { debug_log ("unregistering remote object %s", path().c_str()); InterfaceProxyTable::const_iterator ii = _interfaces.begin(); @@ -308,8 +286,7 @@ void ObjectProxy::unregister_obj() 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()); @@ -319,8 +296,7 @@ Message ObjectProxy::_invoke_method (CallMessage &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()); @@ -330,8 +306,7 @@ bool ObjectProxy::_invoke_method_noreply (CallMessage &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: { diff --git a/sflphone-common/libs/dbus-c++/src/pendingcall.cpp b/sflphone-common/libs/dbus-c++/src/pendingcall.cpp index 775561c21c3a733e99b1f2c0c17c7a7558245936..172e3e6d3932bc50c7a708446bebbb5ee8a1c866 100644 --- a/sflphone-common/libs/dbus-c++/src/pendingcall.cpp +++ b/sflphone-common/libs/dbus-c++/src/pendingcall.cpp @@ -36,22 +36,19 @@ using namespace DBus; PendingCall::Private::Private (DBusPendingCall *dpc) - : call (dpc), dataslot (-1) -{ + : call (dpc), dataslot (-1) { if (!dbus_pending_call_allocate_data_slot (&dataslot)) { throw ErrorNoMemory ("Unable to allocate data slot"); } } -PendingCall::Private::~Private() -{ +PendingCall::Private::~Private() { 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 pc (pvt); @@ -59,26 +56,22 @@ void PendingCall::Private::notify_stub (DBusPendingCall *dpc, void *data) } PendingCall::PendingCall (PendingCall::Private *p) - : _pvt (p) -{ + : _pvt (p) { 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) -{ + : _pvt (c._pvt) { dbus_pending_call_ref (_pvt->call); } -PendingCall::~PendingCall() -{ +PendingCall::~PendingCall() { dbus_pending_call_unref (_pvt->call); } -PendingCall &PendingCall::operator = (const PendingCall &c) -{ +PendingCall &PendingCall::operator = (const PendingCall &c) { if (&c != this) { dbus_pending_call_unref (_pvt->call); _pvt = c._pvt; @@ -88,40 +81,33 @@ PendingCall &PendingCall::operator = (const PendingCall &c) return *this; } -bool PendingCall::completed() -{ +bool PendingCall::completed() { return dbus_pending_call_get_completed (_pvt->call); } -void PendingCall::cancel() -{ +void PendingCall::cancel() { dbus_pending_call_cancel (_pvt->call); } -void PendingCall::block() -{ +void PendingCall::block() { 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"); } } -void *PendingCall::data() -{ +void *PendingCall::data() { return dbus_pending_call_get_data (_pvt->call, _pvt->dataslot); } -Slot<void, PendingCall &>& PendingCall::slot() -{ +Slot<void, PendingCall &>& PendingCall::slot() { return _pvt->slot; } -Message PendingCall::steal_reply() -{ +Message PendingCall::steal_reply() { DBusMessage *dmsg = dbus_pending_call_steal_reply (_pvt->call); if (!dmsg) { diff --git a/sflphone-common/libs/dbus-c++/src/property.cpp b/sflphone-common/libs/dbus-c++/src/property.cpp index e8b02fdaded719b0b8d9e763e0dc42e7e9f8b42c..0afccd9b4cc7e9e3c311ae35f803e98eda540fe0 100644 --- a/sflphone-common/libs/dbus-c++/src/property.cpp +++ b/sflphone-common/libs/dbus-c++/src/property.cpp @@ -35,14 +35,12 @@ 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); } -Message PropertiesAdaptor::Get (const CallMessage &call) -{ +Message PropertiesAdaptor::Get (const CallMessage &call) { MessageIter ri = call.reader(); std::string iface_name; @@ -73,8 +71,7 @@ Message PropertiesAdaptor::Get (const CallMessage &call) return reply; } -Message PropertiesAdaptor::Set (const CallMessage &call) -{ +Message PropertiesAdaptor::Set (const CallMessage &call) { MessageIter ri = call.reader(); std::string iface_name; @@ -97,8 +94,7 @@ Message PropertiesAdaptor::Set (const CallMessage &call) return reply; } -IntrospectedInterface *const PropertiesAdaptor::introspect() const -{ +IntrospectedInterface *const PropertiesAdaptor::introspect() const { static IntrospectedArgument Get_args[] = { { "interface_name", "s", true }, { "property_name", "s", true }, @@ -132,19 +128,16 @@ IntrospectedInterface *const PropertiesAdaptor::introspect() const } 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; } -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 b3dbfe267b96254e70a3bc9dee77f48bb66dc97d..f2bc5d293870c4e092ed7073fb21ce7954307b44 100644 --- a/sflphone-common/libs/dbus-c++/src/server.cpp +++ b/sflphone-common/libs/dbus-c++/src/server.cpp @@ -36,16 +36,13 @@ using namespace DBus; Server::Private::Private (DBusServer *s) - : server (s) -{ + : server (s) { } -Server::Private::~Private() -{ +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); Connection nc (new Connection::Private (conn, s->_pvt.get())); @@ -57,8 +54,7 @@ void Server::Private::on_new_conn_cb (DBusServer *server, DBusConnection *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); @@ -80,13 +76,11 @@ Server::Server(const Server &s) dbus_server_ref(_pvt->server); } */ -Server::~Server() -{ +Server::~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; @@ -114,18 +108,15 @@ Dispatcher *Server::setup (Dispatcher *dispatcher) return prev; } -bool Server::operator == (const Server &s) const -{ +bool Server::operator == (const Server &s) const { return _pvt->server == s._pvt->server; } -bool Server::listening() const -{ +bool Server::listening() const { return dbus_server_get_is_connected (_pvt->server); } -void Server::disconnect() -{ +void Server::disconnect() { 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 d8100258e69f5251b46f9df4164ff7aaa248f038..9e16bde4bd4c07c2bb3ee05ac9e332241b9fd2ce 100644 --- a/sflphone-common/libs/dbus-c++/src/types.cpp +++ b/sflphone-common/libs/dbus-c++/src/types.cpp @@ -37,20 +37,17 @@ 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()) -{ + : _msg (CallMessage()) { MessageIter vi = it.recurse(); MessageIter mi = _msg.writer(); vi.copy_data (mi); } -Variant &Variant::operator = (const Variant &v) -{ +Variant &Variant::operator = (const Variant &v) { if (&v != this) { _msg = v._msg; } @@ -58,14 +55,12 @@ Variant &Variant::operator = (const Variant &v) return *this; } -void Variant::clear() -{ +void Variant::clear() { CallMessage empty; _msg = empty; } -const Signature Variant::signature() const -{ +const Signature Variant::signature() const { char *sigbuf = reader().signature(); Signature signature = sigbuf; @@ -75,8 +70,7 @@ const Signature Variant::signature() const return signature; } -MessageIter &operator << (MessageIter &iter, const Variant &val) -{ +MessageIter &operator << (MessageIter &iter, const Variant &val) { const Signature sig = val.signature(); MessageIter rit = val.reader(); @@ -89,8 +83,7 @@ MessageIter &operator << (MessageIter &iter, const Variant &val) return iter; } -MessageIter &operator >> (MessageIter &iter, Variant &val) -{ +MessageIter &operator >> (MessageIter &iter, Variant &val) { if (iter.type() != DBUS_TYPE_VARIANT) throw ErrorInvalidArgs ("variant type expected"); diff --git a/sflphone-common/libs/dbus-c++/tools/generate_adaptor.cpp b/sflphone-common/libs/dbus-c++/tools/generate_adaptor.cpp index c8f0cd6abb4d08c3951e6ff8da50c80a005c4e70..98721703facb188a635bac1ddadea8e415a0e74a 100644 --- a/sflphone-common/libs/dbus-c++/tools/generate_adaptor.cpp +++ b/sflphone-common/libs/dbus-c++/tools/generate_adaptor.cpp @@ -39,8 +39,7 @@ 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; diff --git a/sflphone-common/libs/dbus-c++/tools/generate_proxy.cpp b/sflphone-common/libs/dbus-c++/tools/generate_proxy.cpp index 288dfa4845ec403439fced710c63a3a56747dbca..95987f45c7a308d682cf43ef5fba2ae263b53bc3 100644 --- a/sflphone-common/libs/dbus-c++/tools/generate_proxy.cpp +++ b/sflphone-common/libs/dbus-c++/tools/generate_proxy.cpp @@ -39,8 +39,7 @@ 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; diff --git a/sflphone-common/libs/dbus-c++/tools/generator_utils.cpp b/sflphone-common/libs/dbus-c++/tools/generator_utils.cpp index 9b5a364966a7631eeea48a7c2b421bd7737082e9..3549632ece299ee4f496d1a4bc53bb3b0c8d4cf3 100644 --- a/sflphone-common/libs/dbus-c++/tools/generator_utils.cpp +++ b/sflphone-common/libs/dbus-c++/tools/generator_utils.cpp @@ -42,22 +42,19 @@ const char *dbus_includes = "\n\ #include <cassert>\n\ "; - void underscorize (string &str) - { + 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) - { + string stub_name (string name) { underscorize (name); return "_" + name + "_stub"; } - const char *atomic_type_to_string (char t) - { + const char *atomic_type_to_string (char t) { static struct { char type; @@ -88,8 +85,7 @@ const char *dbus_includes = "\n\ return atos[i].name; } - void _parse_signature (const string &signature, string &type, unsigned int &i) - { + void _parse_signature (const string &signature, string &type, unsigned int &i) { for (; i < signature.length(); ++i) { switch (signature[i]) { @@ -164,8 +160,7 @@ const char *dbus_includes = "\n\ } } - string signature_to_type (const string &signature) - { + string signature_to_type (const string &signature) { string type; unsigned int i = 0; _parse_signature (signature, type, i); diff --git a/sflphone-common/libs/dbus-c++/tools/introspect.cpp b/sflphone-common/libs/dbus-c++/tools/introspect.cpp index 88a767396139d976588c1d26464cceaa9153c6bb..7459007d548c921cf8c84d5c1374634d5645e115 100644 --- a/sflphone-common/libs/dbus-c++/tools/introspect.cpp +++ b/sflphone-common/libs/dbus-c++/tools/introspect.cpp @@ -32,8 +32,7 @@ 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(); IntrospectedObject io (conn, path, service); @@ -43,8 +42,7 @@ void niam (int sig) dispatcher.leave(); } -int main (int argc, char ** argv) -{ +int main (int argc, char ** argv) { signal (SIGTERM, niam); signal (SIGINT, niam); signal (SIGALRM, niam); diff --git a/sflphone-common/libs/dbus-c++/tools/xml.cpp b/sflphone-common/libs/dbus-c++/tools/xml.cpp index 2ba8635a3c9508d2f73e5cdeda87f84d7ed0b76c..0393f587ca85d0cf41bdf25071ba4c646172a636 100644 --- a/sflphone-common/libs/dbus-c++/tools/xml.cpp +++ b/sflphone-common/libs/dbus-c++/tools/xml.cpp @@ -28,8 +28,7 @@ #include <expat.h> -std::istream &operator >> (std::istream &in, DBus::Xml::Document &doc) -{ +std::istream &operator >> (std::istream &in, DBus::Xml::Document &doc) { std::stringbuf xmlbuf; in.get (xmlbuf, '\0'); doc.from_xml (xmlbuf.str()); @@ -37,8 +36,7 @@ std::istream &operator >> (std::istream &in, DBus::Xml::Document &doc) return in; } -std::ostream &operator << (std::ostream &out, const DBus::Xml::Document &doc) -{ +std::ostream &operator << (std::ostream &out, const DBus::Xml::Document &doc) { return out << doc.to_xml(); } @@ -46,8 +44,7 @@ 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; estream << "line " << line << ", column " << column << ": " << error; @@ -56,8 +53,7 @@ Error::Error (const char *error, int line, int column) } Node::Node (const char *n, const char ** a) - : name (n) -{ + : name (n) { if (a) for (int i = 0; a[i]; i += 2) { _attrs[a[i]] = a[i+1]; @@ -66,8 +62,7 @@ Node::Node (const char *n, const char ** a) } } -Nodes Nodes::operator[] (const std::string &key) -{ +Nodes Nodes::operator[] (const std::string &key) { Nodes result; for (iterator i = begin(); i != end(); ++i) { @@ -79,8 +74,7 @@ Nodes Nodes::operator[] (const std::string &key) 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) { @@ -91,8 +85,7 @@ Nodes Nodes::select (const std::string &attr, const std::string &value) return result; } -Nodes Node::operator[] (const std::string &key) -{ +Nodes Node::operator[] (const std::string &key) { Nodes result; if (key.length() == 0) return result; @@ -105,24 +98,21 @@ Nodes Node::operator[] (const std::string &key) 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 ""; } -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); } -std::string Node::to_xml() const -{ +std::string Node::to_xml() const { std::string xml; int depth = 0; @@ -131,8 +121,7 @@ std::string Node::to_xml() const 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); @@ -167,18 +156,15 @@ void Node::_raw_xml (std::string &xml, int &depth) const } Document::Document() - : root (0), _depth (0) -{ + : root (0), _depth (0) { } Document::Document (const std::string &xml) - : root (0), _depth (0) -{ + : root (0), _depth (0) { from_xml (xml); } -Document::~Document() -{ +Document::~Document() { delete root; } @@ -192,8 +178,7 @@ struct Document::Expat { 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; @@ -234,23 +219,19 @@ void Document::from_xml (const std::string &xml) } } -std::string Document::to_xml() const -{ +std::string Document::to_xml() const { 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::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); @@ -272,8 +253,7 @@ void Document::Expat::start_element_handler (void *data, const XML_Char *name, c 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; Node *nod = doc->root; @@ -294,8 +274,7 @@ void Document::Expat::character_data_handler (void *data, const XML_Char *chars, 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; //debug_log("xml:%d <- %s", doc->_depth, name); diff --git a/sflphone-common/libs/dbus-c++/tools/xml2cpp.cpp b/sflphone-common/libs/dbus-c++/tools/xml2cpp.cpp index 3284d766753fdeb3baa39de951c56df43a88cea4..300a21d6cdc17e0ed1bec4467256d8c831abc198 100644 --- a/sflphone-common/libs/dbus-c++/tools/xml2cpp.cpp +++ b/sflphone-common/libs/dbus-c++/tools/xml2cpp.cpp @@ -42,8 +42,7 @@ 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); @@ -62,8 +61,7 @@ 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]); } @@ -82,11 +80,10 @@ int main (int argc, char ** argv) 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; - } + } else if (!strncmp (argv[a], "--adaptor=", 10)) { + adaptor_mode = true; + adaptor = argv[a] +10; + } } if (!proxy_mode && !adaptor_mode) usage (argv[0]); diff --git a/sflphone-common/libs/utilspp/singleton/LifetimeLibrary.cpp b/sflphone-common/libs/utilspp/singleton/LifetimeLibrary.cpp index 7f7afac3b23beb5eeeba4ee3c951a1dca5d81c48..6e71baddaad90bc1922457fcae4791c3b53cea3d 100644 --- a/sflphone-common/libs/utilspp/singleton/LifetimeLibrary.cpp +++ b/sflphone-common/libs/utilspp/singleton/LifetimeLibrary.cpp @@ -4,17 +4,14 @@ utilspp::LifetimeLibraryImpl::LifetimeLibraryImpl() : mTrackerArray (NULL), - mNbElements (0) -{} + mNbElements (0) {} -utilspp::LifetimeLibraryImpl::~LifetimeLibraryImpl() -{ +utilspp::LifetimeLibraryImpl::~LifetimeLibraryImpl() { 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)); @@ -39,8 +36,7 @@ utilspp::LifetimeLibraryImpl::add (utilspp::PrivateMembers::LifetimeTracker *tra }; void -utilspp::LifetimeLibraryImpl::terminate() -{ +utilspp::LifetimeLibraryImpl::terminate() { //The number of elements MUST always be equal or over zero. assert (mNbElements >= 0); @@ -64,8 +60,7 @@ utilspp::LifetimeLibraryImpl::terminate() } unsigned int -utilspp::getLongevity (utilspp::LifetimeLibraryImpl *) -{ +utilspp::getLongevity (utilspp::LifetimeLibraryImpl *) { return 0; } diff --git a/sflphone-common/libs/utilspp/singleton/PrivateMembers.cpp b/sflphone-common/libs/utilspp/singleton/PrivateMembers.cpp index 194fbda664470c36a6f0d4264c8058726d82139d..a033e0c54c6255fca5144b7963c50ea2ace9ab07 100644 --- a/sflphone-common/libs/utilspp/singleton/PrivateMembers.cpp +++ b/sflphone-common/libs/utilspp/singleton/PrivateMembers.cpp @@ -10,24 +10,20 @@ int utilspp::PrivateMembers::mNbElements = 0; utilspp::PrivateMembers::LifetimeTracker::LifetimeTracker (unsigned int longevity) : - mLongevity (longevity) -{} + mLongevity (longevity) {} -utilspp::PrivateMembers::LifetimeTracker::~LifetimeTracker() -{} +utilspp::PrivateMembers::LifetimeTracker::~LifetimeTracker() {} bool utilspp::PrivateMembers::LifetimeTracker::compare ( const LifetimeTracker *l, const LifetimeTracker *r -) -{ +) { return l->mLongevity < r->mLongevity; } void -utilspp::PrivateMembers::atExitFunc() -{ +utilspp::PrivateMembers::atExitFunc() { assert ( (mTrackerArray != NULL) && (mNbElements > 0)); diff --git a/sflphone-common/src/account.cpp b/sflphone-common/src/account.cpp index 66f78f4786547b35207a70e04b7861a4e61c8835..9150f65908e33218e889ccc4fcec990d78ff6295 100644 --- a/sflphone-common/src/account.cpp +++ b/sflphone-common/src/account.cpp @@ -34,81 +34,81 @@ #include "manager.h" Account::Account (const AccountID& accountID, std::string type) : - _accountID (accountID) - , _link (NULL) - , _enabled (true) - , _type (type) - , _codecOrder () - , _codecStr("") - , _ringtonePath("/usr/share/sflphone/ringtones/konga.ul") - , _ringtoneEnabled(true) - , _displayName("") - , _useragent("SFLphone") -{ - setRegistrationState (Unregistered); + _accountID (accountID) + , _link (NULL) + , _enabled (true) + , _type (type) + , _codecOrder () + , _codecStr ("") + , _ringtonePath ("/usr/share/sflphone/ringtones/konga.ul") + , _ringtoneEnabled (true) + , _displayName ("") + , _useragent ("SFLphone") { + setRegistrationState (Unregistered); } -Account::~Account() -{ +Account::~Account() { } void Account::loadConfig() { - // If IAX is not supported, do not register this account + // If IAX is not supported, do not register this account #ifndef USE_IAX - if (_type == "IAX") - _enabled = false; + + if (_type == "IAX") + _enabled = false; + #endif - loadAudioCodecs (); + loadAudioCodecs (); } void Account::setRegistrationState (RegistrationState state) { - if (state != _registrationState) { - _debug ("Account: set registration state"); - _registrationState = state; + if (state != _registrationState) { + _debug ("Account: set registration state"); + _registrationState = state; - // Notify the client - Manager::instance().connectionStatusNotification(); - } + // Notify the client + Manager::instance().connectionStatusNotification(); + } } void Account::loadAudioCodecs (void) { - // if the user never set the codec list, use the default configuration for this account - if(_codecStr == "") { - _info ("Account: use the default order"); - Manager::instance ().getCodecDescriptorMap ().setDefaultOrder(); - } - // else retrieve the one set in the user config file - else { - std::vector<std::string> active_list = Manager::instance ().retrieveActiveCodecs(); - // This property is now set per account basis - // std::string s = Manager::instance ().getConfigString (_accountID, "ActiveCodecs"); - setActiveCodecs (Manager::instance ().unserialize (_codecStr)); - } + // if the user never set the codec list, use the default configuration for this account + if (_codecStr == "") { + _info ("Account: use the default order"); + Manager::instance ().getCodecDescriptorMap ().setDefaultOrder(); + } + // else retrieve the one set in the user config file + else { + std::vector<std::string> active_list = Manager::instance ().retrieveActiveCodecs(); + // This property is now set per account basis + // std::string s = Manager::instance ().getConfigString (_accountID, "ActiveCodecs"); + setActiveCodecs (Manager::instance ().unserialize (_codecStr)); + } } void Account::setActiveCodecs (const std::vector <std::string> &list) { - _codecOrder.clear(); - // list contains the ordered payload of active codecs picked by the user for this account - // 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()); - _info ("Account: Adding codec with RTP payload=%i", payload); - //if (Manager::instance ().getCodecDescriptorMap ().isCodecLoaded (payload)) { - _codecOrder.push_back ( (AudioCodecType) payload); - //} - i++; - } - - // setConfig - _codecStr = Manager::instance ().serialize (list); + _codecOrder.clear(); + // list contains the ordered payload of active codecs picked by the user for this account + // 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()); + _info ("Account: Adding codec with RTP payload=%i", payload); + //if (Manager::instance ().getCodecDescriptorMap ().isCodecLoaded (payload)) { + _codecOrder.push_back ( (AudioCodecType) payload); + //} + i++; + } + + // setConfig + _codecStr = Manager::instance ().serialize (list); } diff --git a/sflphone-common/src/accountcreator.cpp b/sflphone-common/src/accountcreator.cpp index 8bf74f3cb3e51bf70624834bd95fe7a43af36b14..607ce4fef36b0429d7512f75afcb6a63657e6aa0 100644 --- a/sflphone-common/src/accountcreator.cpp +++ b/sflphone-common/src/accountcreator.cpp @@ -36,40 +36,37 @@ #include "iax/iaxaccount.h" #endif -AccountCreator::AccountCreator() -{ +AccountCreator::AccountCreator() { } -AccountCreator::~AccountCreator() -{ +AccountCreator::~AccountCreator() { } Account* -AccountCreator::createAccount (AccountType type, AccountID accountID) -{ +AccountCreator::createAccount (AccountType type, AccountID accountID) { switch (type) { - case SIP_ACCOUNT: { - _debug("AccountCreator: create account %s", accountID.c_str()); - return new SIPAccount (accountID); - break; - } - case SIP_DIRECT_IP_ACCOUNT: { - _debug("AccountCreator: create account IP2IP_PROFILE"); - return new SIPAccount (IP2IP_PROFILE); - break; - } + case SIP_ACCOUNT: { + _debug ("AccountCreator: create account %s", accountID.c_str()); + return new SIPAccount (accountID); + break; + } + case SIP_DIRECT_IP_ACCOUNT: { + _debug ("AccountCreator: create account IP2IP_PROFILE"); + return new SIPAccount (IP2IP_PROFILE); + break; + } #ifdef USE_IAX - case IAX_ACCOUNT: { - _debug("AccountCreator: create account %s", accountID.c_str()); - return new IAXAccount (accountID); - break; - } + case IAX_ACCOUNT: { + _debug ("AccountCreator: create account %s", accountID.c_str()); + return new IAXAccount (accountID); + break; + } #endif - default: - _error("AccountCreator: Error: unknown account type"); + default: + _error ("AccountCreator: Error: unknown account type"); } return 0; diff --git a/sflphone-common/src/audio/alsa/alsalayer.cpp b/sflphone-common/src/audio/alsa/alsalayer.cpp index 5c19f3da8cce792c8b86742700bcfe1aceffd651..75321e25db809662b56882a8da5b2b135d9d6c23 100644 --- a/sflphone-common/src/audio/alsa/alsalayer.cpp +++ b/sflphone-common/src/audio/alsa/alsalayer.cpp @@ -39,7 +39,7 @@ int framesPerBufferAlsa = 2048; AlsaLayer::AlsaLayer (ManagerImpl* manager) : AudioLayer (manager , ALSA) , _PlaybackHandle (NULL) - , _RingtoneHandle (NULL) + , _RingtoneHandle (NULL) , _CaptureHandle (NULL) , _periodSize() , _audioPlugin() @@ -59,14 +59,13 @@ AlsaLayer::AlsaLayer (ManagerImpl* manager) // _audioThread = new AudioThread (this); // _audioThread = NULL; _urgentRingBuffer.createReadPointer(); - + AudioLayer::_echocancelstate = true; AudioLayer::_noisesuppressstate = true; } // Destructor -AlsaLayer::~AlsaLayer (void) -{ +AlsaLayer::~AlsaLayer (void) { _debug ("Audio: Destroy of ALSA layer"); closeLayer(); @@ -77,8 +76,7 @@ AlsaLayer::~AlsaLayer (void) } bool -AlsaLayer::closeLayer() -{ +AlsaLayer::closeLayer() { _debugAlsa ("Audio: Close ALSA streams"); try { @@ -105,15 +103,14 @@ AlsaLayer::closeLayer() } bool -AlsaLayer::openDevice (int indexIn, int indexOut, int indexRing, int sampleRate, int frameSize, int stream , std::string plugin) -{ +AlsaLayer::openDevice (int indexIn, int indexOut, int indexRing, 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) { 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; @@ -136,50 +133,48 @@ AlsaLayer::openDevice (int indexIn, int indexOut, int indexRing, int sampleRate, _converter = new SamplerateConverter (_audioSampleRate, 1000); AudioLayer::_echoCancel = new EchoCancel(); - AudioLayer::_echoCanceller = new AudioProcessing(static_cast<Algorithm *>(_echoCancel)); + AudioLayer::_echoCanceller = new AudioProcessing (static_cast<Algorithm *> (_echoCancel)); - AudioLayer::_echoCancel->setEchoCancelState(AudioLayer::_echocancelstate); - AudioLayer::_echoCancel->setNoiseSuppressState(AudioLayer::_noisesuppressstate); + AudioLayer::_echoCancel->setEchoCancelState (AudioLayer::_echocancelstate); + AudioLayer::_echoCancel->setNoiseSuppressState (AudioLayer::_noisesuppressstate); AudioLayer::_dcblocker = new DcBlocker(); - AudioLayer::_audiofilter = new AudioProcessing(static_cast<Algorithm *>(_dcblocker)); + AudioLayer::_audiofilter = new AudioProcessing (static_cast<Algorithm *> (_dcblocker)); - return true; + return true; } void -AlsaLayer::startStream (void) -{ +AlsaLayer::startStream (void) { _debug ("Audio: Start stream"); - if(_audiofilter) - _audiofilter->resetAlgorithm(); + if (_audiofilter) + _audiofilter->resetAlgorithm(); - if(_echoCanceller) - _echoCanceller->resetAlgorithm(); + if (_echoCanceller) + _echoCanceller->resetAlgorithm(); - if(is_playback_running() && is_capture_running() ) + if (is_playback_running() && is_capture_running()) return; std::string pcmp; std::string pcmr; std::string pcmc; - if(_audioPlugin == PCM_DMIX_DSNOOP) { - pcmp = buildDeviceTopo (PCM_DMIX, _indexOut, 0); - pcmr = buildDeviceTopo (PCM_DMIX, _indexRing, 0); - pcmc = buildDeviceTopo(PCM_DSNOOP, _indexIn, 0); - } - else { - pcmp = buildDeviceTopo (_audioPlugin, _indexOut, 0); - pcmr = buildDeviceTopo (_audioPlugin, _indexRing, 0); - pcmc = buildDeviceTopo(_audioPlugin, _indexIn, 0); + if (_audioPlugin == PCM_DMIX_DSNOOP) { + pcmp = buildDeviceTopo (PCM_DMIX, _indexOut, 0); + pcmr = buildDeviceTopo (PCM_DMIX, _indexRing, 0); + pcmc = buildDeviceTopo (PCM_DSNOOP, _indexIn, 0); + } else { + pcmp = buildDeviceTopo (_audioPlugin, _indexOut, 0); + pcmr = buildDeviceTopo (_audioPlugin, _indexRing, 0); + pcmc = buildDeviceTopo (_audioPlugin, _indexIn, 0); } - _debug("pcmp: %s, index %d", pcmp.c_str(), _indexOut); - _debug("pcmr: %s, index %d", pcmr.c_str(), _indexRing); - _debug("pcmc: %s, index %d", pcmc.c_str(), _indexIn); + _debug ("pcmp: %s, index %d", pcmp.c_str(), _indexOut); + _debug ("pcmr: %s, index %d", pcmr.c_str(), _indexRing); + _debug ("pcmc: %s, index %d", pcmc.c_str(), _indexIn); if (!is_playback_open()) { open_device (pcmp, pcmc, pcmr, SFL_PCM_PLAYBACK); @@ -214,8 +209,7 @@ AlsaLayer::startStream (void) } void -AlsaLayer::stopStream (void) -{ +AlsaLayer::stopStream (void) { _debug ("Audio: Stop stream"); try { @@ -244,8 +238,7 @@ AlsaLayer::stopStream (void) } -bool AlsaLayer::isCaptureActive (void) -{ +bool AlsaLayer::isCaptureActive (void) { ost::MutexLock guard (_mutex); if (_CaptureHandle) @@ -255,22 +248,20 @@ bool AlsaLayer::isCaptureActive (void) } -void AlsaLayer::setEchoCancelState(bool state) -{ - // if a stream already running - if(AudioLayer::_echoCancel) - _echoCancel->setEchoCancelState(state); +void AlsaLayer::setEchoCancelState (bool state) { + // if a stream already running + if (AudioLayer::_echoCancel) + _echoCancel->setEchoCancelState (state); - AudioLayer::_echocancelstate = state; + AudioLayer::_echocancelstate = state; } -void AlsaLayer::setNoiseSuppressState(bool state) -{ - // if a stream already opened - if(AudioLayer::_echoCancel) - _echoCancel->setNoiseSuppressState(state); +void AlsaLayer::setNoiseSuppressState (bool state) { + // if a stream already opened + if (AudioLayer::_echoCancel) + _echoCancel->setNoiseSuppressState (state); - AudioLayer::_noisesuppressstate = state; + AudioLayer::_noisesuppressstate = state; } @@ -279,8 +270,7 @@ void AlsaLayer::setNoiseSuppressState(bool state) ///////////////// ALSA PRIVATE FUNCTIONS //////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////// -void AlsaLayer::stopCaptureStream (void) -{ +void AlsaLayer::stopCaptureStream (void) { int err; if (_CaptureHandle) { @@ -294,8 +284,7 @@ void AlsaLayer::stopCaptureStream (void) } } -void AlsaLayer::closeCaptureStream (void) -{ +void AlsaLayer::closeCaptureStream (void) { int err; if (is_capture_prepared() == true && is_capture_running() == true) @@ -311,8 +300,7 @@ void AlsaLayer::closeCaptureStream (void) } } -void AlsaLayer::startCaptureStream (void) -{ +void AlsaLayer::startCaptureStream (void) { int err; if (_CaptureHandle && !is_capture_running()) { @@ -325,8 +313,7 @@ void AlsaLayer::startCaptureStream (void) } } -void AlsaLayer::prepareCaptureStream (void) -{ +void AlsaLayer::prepareCaptureStream (void) { int err; if (is_capture_open() && !is_capture_prepared()) { @@ -339,16 +326,15 @@ void AlsaLayer::prepareCaptureStream (void) } } -void AlsaLayer::stopPlaybackStream (void) -{ +void AlsaLayer::stopPlaybackStream (void) { int err; - if(_RingtoneHandle && is_playback_running()) { - _debug("Audio: Stop ALSA ringtone"); + if (_RingtoneHandle && is_playback_running()) { + _debug ("Audio: Stop ALSA ringtone"); - if( (err = snd_pcm_drop(_RingtoneHandle)) < 0) { - _debug("Audio: Error: Stop ALSA ringtone: %s", snd_strerror(err)); - } + if ( (err = snd_pcm_drop (_RingtoneHandle)) < 0) { + _debug ("Audio: Error: Stop ALSA ringtone: %s", snd_strerror (err)); + } } if (_PlaybackHandle && is_playback_running()) { @@ -362,8 +348,7 @@ void AlsaLayer::stopPlaybackStream (void) } -void AlsaLayer::closePlaybackStream (void) -{ +void AlsaLayer::closePlaybackStream (void) { int err; if (is_playback_prepared() == true && is_playback_running() == true) @@ -372,24 +357,23 @@ void AlsaLayer::closePlaybackStream (void) if (is_playback_open()) { - _debug("Audio: Close ALSA playback"); + _debug ("Audio: Close ALSA playback"); - if(_RingtoneHandle) { - if((err = snd_pcm_close(_RingtoneHandle)) < 0) { - _warn("Audio: Error: Closing ALSA ringtone: %s", snd_strerror(err)); - } + if (_RingtoneHandle) { + if ( (err = snd_pcm_close (_RingtoneHandle)) < 0) { + _warn ("Audio: Error: Closing ALSA ringtone: %s", snd_strerror (err)); + } } if ( (err = snd_pcm_close (_PlaybackHandle)) < 0) - _warn("Audio: Error: Closing ALSA playback: %s", snd_strerror (err)); + _warn ("Audio: Error: Closing ALSA playback: %s", snd_strerror (err)); else close_playback (); } } -void AlsaLayer::startPlaybackStream (void) -{ +void AlsaLayer::startPlaybackStream (void) { int err; if (_PlaybackHandle && !is_playback_running()) { @@ -402,8 +386,7 @@ void AlsaLayer::startPlaybackStream (void) } } -void AlsaLayer::preparePlaybackStream (void) -{ +void AlsaLayer::preparePlaybackStream (void) { int err; if (is_playback_open() && !is_playback_prepared()) { @@ -445,8 +428,7 @@ void AlsaLayer::recoverPlaybackStream(int error) */ -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; @@ -493,9 +475,8 @@ bool AlsaLayer::alsa_set_params (snd_pcm_t *pcm_handle, int type, int rate) if ( (err = snd_pcm_hw_params_set_rate_near (pcm_handle, hwparams, &exact_ivalue, &dir) < 0)) { _debugAlsa ("Audio: Error: Cannot set sample rate (%s)", snd_strerror (err)); return false; - } - else - _debug("Audio: Set audio rate to %d", rate); + } else + _debug ("Audio: Set audio rate to %d", rate); if (dir!= 0) { _debugAlsa ("Audio: Error: (%i) The choosen rate %d Hz is not supported by your hardware.Using %d Hz instead. ",type ,rate, exact_ivalue); @@ -572,8 +553,7 @@ bool AlsaLayer::alsa_set_params (snd_pcm_t *pcm_handle, int type, int rate) bool -AlsaLayer::open_device (std::string pcm_p, std::string pcm_c, std::string pcm_r, int flag) -{ +AlsaLayer::open_device (std::string pcm_p, std::string pcm_c, std::string pcm_r, int flag) { int err; @@ -581,8 +561,8 @@ AlsaLayer::open_device (std::string pcm_p, std::string pcm_c, std::string pcm_r, _debug ("Audio: Open playback device (and ringtone)"); - if ((err = snd_pcm_open(&_PlaybackHandle, pcm_p.c_str(), SND_PCM_STREAM_PLAYBACK, 0)) < 0) { - _warn("Audio: Error while opening playback device %s", pcm_p.c_str()); + if ( (err = snd_pcm_open (&_PlaybackHandle, pcm_p.c_str(), SND_PCM_STREAM_PLAYBACK, 0)) < 0) { + _warn ("Audio: Error while opening playback device %s", pcm_p.c_str()); setErrorMessage (ALSA_PLAYBACK_DEVICE); close_playback (); return false; @@ -595,19 +575,19 @@ AlsaLayer::open_device (std::string pcm_p, std::string pcm_c, std::string pcm_r, return false; } - if (getIndexOut() != getIndexRing()) { + if (getIndexOut() != getIndexRing()) { - if((err = snd_pcm_open(&_RingtoneHandle, pcm_r.c_str(), SND_PCM_STREAM_PLAYBACK, 0)) < 0) { - _warn("Audio: Error: Opening ringtone device %s", pcm_r.c_str()); - // setErrorMessage(ALSA_RINGTONE_DEVICE); - } + if ( (err = snd_pcm_open (&_RingtoneHandle, pcm_r.c_str(), SND_PCM_STREAM_PLAYBACK, 0)) < 0) { + _warn ("Audio: Error: Opening ringtone device %s", pcm_r.c_str()); + // setErrorMessage(ALSA_RINGTONE_DEVICE); + } - if(!alsa_set_params(_RingtoneHandle, 1, getSampleRate())) { - _warn("Audio: Error: Ringtone failed"); - snd_pcm_close(_RingtoneHandle); - - } - } + if (!alsa_set_params (_RingtoneHandle, 1, getSampleRate())) { + _warn ("Audio: Error: Ringtone failed"); + snd_pcm_close (_RingtoneHandle); + + } + } open_playback (); } @@ -616,8 +596,8 @@ AlsaLayer::open_device (std::string pcm_p, std::string pcm_c, std::string pcm_r, _debug ("Audio: Open capture device"); - if ((err = snd_pcm_open(&_CaptureHandle, pcm_c.c_str(), SND_PCM_STREAM_CAPTURE, 0)) < 0){ - _warn("Audio: Error: Opening capture device %s", pcm_c.c_str()); + if ( (err = snd_pcm_open (&_CaptureHandle, pcm_c.c_str(), SND_PCM_STREAM_CAPTURE, 0)) < 0) { + _warn ("Audio: Error: Opening capture device %s", pcm_c.c_str()); setErrorMessage (ALSA_CAPTURE_DEVICE); close_capture (); @@ -625,7 +605,7 @@ AlsaLayer::open_device (std::string pcm_p, std::string pcm_c, std::string pcm_r, } if (!alsa_set_params (_CaptureHandle, 0, 8000)) { - _warn("Audio: Error: Capture failed"); + _warn ("Audio: Error: Capture failed"); snd_pcm_close (_CaptureHandle); close_capture (); return false; @@ -636,15 +616,14 @@ AlsaLayer::open_device (std::string pcm_p, std::string pcm_c, std::string pcm_r, // prepare_capture (); } - + 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, snd_pcm_t * handle) -{ +AlsaLayer::write (void* buffer, int length, snd_pcm_t * handle) { if (_trigger_request == true) { _trigger_request = false; startPlaybackStream (); @@ -663,7 +642,7 @@ AlsaLayer::write (void* buffer, int length, snd_pcm_t * handle) case -EIO: //_debugAlsa(" XRUN playback ignored (%s)", snd_strerror(err)); - handle_xrun_playback(handle); + handle_xrun_playback (handle); if (snd_pcm_writei (handle, buffer , frames) <0) _debugAlsa ("Audio: XRUN handling failed"); @@ -685,8 +664,7 @@ AlsaLayer::write (void* buffer, int length, snd_pcm_t * handle) } int -AlsaLayer::read (void* buffer, int toCopy) -{ +AlsaLayer::read (void* buffer, int toCopy) { //ost::MutexLock lock( _mutex ); int samples; @@ -731,8 +709,7 @@ AlsaLayer::read (void* buffer, int toCopy) } void -AlsaLayer::handle_xrun_capture (void) -{ +AlsaLayer::handle_xrun_capture (void) { _debugAlsa ("Audio: Handle xrun capture"); snd_pcm_status_t* status; @@ -751,21 +728,20 @@ AlsaLayer::handle_xrun_capture (void) } void -AlsaLayer::handle_xrun_playback (snd_pcm_t *handle) -{ +AlsaLayer::handle_xrun_playback (snd_pcm_t *handle) { _debugAlsa ("Audio: Handle xrun playback"); int state; snd_pcm_status_t* status; snd_pcm_status_alloca (&status); - if ( (state = snd_pcm_status (handle, status)) < 0) - _debugAlsa ("Audio: Error: Cannot get playback handle status (%s)" , snd_strerror (state)); + if ( (state = snd_pcm_status (handle, status)) < 0) + _debugAlsa ("Audio: Error: Cannot get playback handle status (%s)" , snd_strerror (state)); else { state = snd_pcm_status_get_state (status); if (state == SND_PCM_STATE_XRUN) { - _debug("Audio: audio device in state SND_PCM_STATE_XRUN, restart device"); + _debug ("Audio: audio device in state SND_PCM_STATE_XRUN, restart device"); stopPlaybackStream (); preparePlaybackStream (); @@ -776,8 +752,7 @@ AlsaLayer::handle_xrun_playback (snd_pcm_t *handle) } std::string -AlsaLayer::buildDeviceTopo (std::string plugin, int card, int subdevice) -{ +AlsaLayer::buildDeviceTopo (std::string plugin, int card, int subdevice) { std::stringstream ss,ss1; std::string pcm = plugin; @@ -796,18 +771,17 @@ AlsaLayer::buildDeviceTopo (std::string plugin, int card, int subdevice) pcm.append (ss1.str()); } - _debug("Audio: Device topo: %s", pcm.c_str()); + _debug ("Audio: Device topo: %s", pcm.c_str()); return pcm; } std::vector<std::string> -AlsaLayer::getSoundCardsInfo (int stream) -{ +AlsaLayer::getSoundCardsInfo (int stream) { std::vector<std::string> cards_id; HwIDPair p; - _debug("Audio: Get sound cards info: "); + _debug ("Audio: Get sound cards info: "); snd_ctl_t* handle; snd_ctl_card_info_t *info; @@ -863,8 +837,7 @@ AlsaLayer::getSoundCardsInfo (int stream) bool -AlsaLayer::soundCardIndexExist (int card , int stream) -{ +AlsaLayer::soundCardIndexExist (int card , int stream) { snd_ctl_t* handle; snd_pcm_info_t *pcminfo; snd_pcm_info_alloca (&pcminfo); @@ -884,8 +857,7 @@ AlsaLayer::soundCardIndexExist (int card , int stream) } int -AlsaLayer::soundCardGetIndex (std::string description) -{ +AlsaLayer::soundCardGetIndex (std::string description) { unsigned int i; for (i = 0 ; i < IDSoundCards.size() ; i++) { @@ -899,8 +871,7 @@ AlsaLayer::soundCardGetIndex (std::string description) return 0; } -void AlsaLayer::audioCallback(void) -{ +void AlsaLayer::audioCallback (void) { int toGet, urgentAvailBytes, normalAvailBytes, maxBytes; unsigned short spkrVolume, micVolume; @@ -920,13 +891,13 @@ void AlsaLayer::audioCallback(void) // framePerBuffer are the number of data for one channel (left) urgentAvailBytes = _urgentRingBuffer.AvailForGet(); - if(!_PlaybackHandle || !_CaptureHandle) - return; + if (!_PlaybackHandle || !_CaptureHandle) + return; - snd_pcm_wait(_PlaybackHandle, 20); + snd_pcm_wait (_PlaybackHandle, 20); - int playbackAvailSmpl = snd_pcm_avail_update(_PlaybackHandle); - int playbackAvailBytes = playbackAvailSmpl*sizeof(SFLDataFormat); + int playbackAvailSmpl = snd_pcm_avail_update (_PlaybackHandle); + int playbackAvailBytes = playbackAvailSmpl*sizeof (SFLDataFormat); // _debug("PLAYBACK: %d", playbackAvailSmpl); if (urgentAvailBytes > 0) { @@ -957,18 +928,17 @@ void AlsaLayer::audioCallback(void) free (out); out = 0; - - } - else if (file_tone && !_RingtoneHandle && (normalAvailBytes <= 0)) { - out = (SFLDataFormat *) malloc (playbackAvailBytes); - file_tone->getNext (out, playbackAvailSmpl, spkrVolume); - write (out, playbackAvailBytes, _PlaybackHandle); + } else if (file_tone && !_RingtoneHandle && (normalAvailBytes <= 0)) { - free (out); - out = NULL; + out = (SFLDataFormat *) malloc (playbackAvailBytes); + file_tone->getNext (out, playbackAvailSmpl, spkrVolume); + write (out, playbackAvailBytes, _PlaybackHandle); - } else { + free (out); + out = NULL; + + } else { // If nothing urgent, play the regular sound samples @@ -983,9 +953,9 @@ void AlsaLayer::audioCallback(void) double upsampleFactor = (double) _audioSampleRate / _mainBufferSampleRate; maxNbSamplesToGet = (int) ( (double) playbackAvailSmpl / upsampleFactor); - maxNbBytesToGet = maxNbSamplesToGet * sizeof (SFLDataFormat); + maxNbBytesToGet = maxNbSamplesToGet * sizeof (SFLDataFormat); - } + } toGet = (normalAvailBytes < (int) maxNbBytesToGet) ? normalAvailBytes : maxNbBytesToGet; @@ -995,9 +965,9 @@ void AlsaLayer::audioCallback(void) getMainBuffer()->getData (out, toGet, spkrVolume); - // TODO: Audio processing should be performed inside mainbuffer - // to avoid such problem - AudioLayer::_echoCancel->setSamplingRate(_mainBufferSampleRate); + // TODO: Audio processing should be performed inside mainbuffer + // to avoid such problem + AudioLayer::_echoCancel->setSamplingRate (_mainBufferSampleRate); if (_mainBufferSampleRate && ( (int) _audioSampleRate != _mainBufferSampleRate)) { @@ -1018,18 +988,18 @@ void AlsaLayer::audioCallback(void) } else { - write (out, toGet, _PlaybackHandle); + write (out, toGet, _PlaybackHandle); } - // Copy far-end signal in echo canceller to adapt filter coefficient - AudioLayer::_echoCanceller->putData(out, toGet); + // Copy far-end signal in echo canceller to adapt filter coefficient + AudioLayer::_echoCanceller->putData (out, toGet); } else { - if (!tone && !file_tone) { + if (!tone && !file_tone) { - SFLDataFormat *zeros = (SFLDataFormat*)malloc(playbackAvailBytes); + SFLDataFormat *zeros = (SFLDataFormat*) malloc (playbackAvailBytes); bzero (zeros, playbackAvailBytes); write (zeros, playbackAvailBytes, _PlaybackHandle); @@ -1049,29 +1019,29 @@ void AlsaLayer::audioCallback(void) if (file_tone && _RingtoneHandle) { - int ringtoneAvailSmpl = snd_pcm_avail_update(_RingtoneHandle); - int ringtoneAvailBytes = ringtoneAvailSmpl*sizeof(SFLDataFormat); + int ringtoneAvailSmpl = snd_pcm_avail_update (_RingtoneHandle); + int ringtoneAvailBytes = ringtoneAvailSmpl*sizeof (SFLDataFormat); - // _debug("RINGTONE: %d", ringtoneAvailSmpl); + // _debug("RINGTONE: %d", ringtoneAvailSmpl); - out = (SFLDataFormat *) malloc(ringtoneAvailBytes); - file_tone->getNext (out, ringtoneAvailSmpl, spkrVolume); - write (out, ringtoneAvailBytes, _RingtoneHandle); + out = (SFLDataFormat *) malloc (ringtoneAvailBytes); + file_tone->getNext (out, ringtoneAvailSmpl, spkrVolume); + write (out, ringtoneAvailBytes, _RingtoneHandle); - free (out); - out = NULL; + free (out); + out = NULL; } else if (_RingtoneHandle) { - int ringtoneAvailSmpl = snd_pcm_avail_update(_RingtoneHandle); - int ringtoneAvailBytes = ringtoneAvailSmpl*sizeof(SFLDataFormat); + int ringtoneAvailSmpl = snd_pcm_avail_update (_RingtoneHandle); + int ringtoneAvailBytes = ringtoneAvailSmpl*sizeof (SFLDataFormat); - out = (SFLDataFormat *) malloc(ringtoneAvailBytes); - memset(out, 0, ringtoneAvailBytes); - write(out, ringtoneAvailBytes, _RingtoneHandle); + out = (SFLDataFormat *) malloc (ringtoneAvailBytes); + memset (out, 0, ringtoneAvailBytes); + write (out, ringtoneAvailBytes, _RingtoneHandle); - free(out); - out = NULL; + free (out); + out = NULL; } // Additionally handle the mic's audio stream @@ -1081,7 +1051,7 @@ void AlsaLayer::audioCallback(void) SFLDataFormat* in; SFLDataFormat echoCancelledMic[5000]; - memset(echoCancelledMic, 0, 5000); + memset (echoCancelledMic, 0, 5000); // snd_pcm_sframes_t micAvailAlsa; in = 0; @@ -1112,28 +1082,28 @@ void AlsaLayer::audioCallback(void) // _debug("nb_sample_up %i", nb_sample_up); nbSample = _converter->downsampleData ( (SFLDataFormat*) in, rsmpl_out, _mainBufferSampleRate, _audioSampleRate, nb_sample_up); - _audiofilter->processAudio (rsmpl_out, nbSample*sizeof(SFLDataFormat)); + _audiofilter->processAudio (rsmpl_out, nbSample*sizeof (SFLDataFormat)); - // echo cancellation processing - int sampleready = AudioLayer::_echoCanceller->processAudio(rsmpl_out, echoCancelledMic, nbSample*sizeof(SFLDataFormat)); + // echo cancellation processing + int sampleready = AudioLayer::_echoCanceller->processAudio (rsmpl_out, echoCancelledMic, nbSample*sizeof (SFLDataFormat)); // getMainBuffer()->putData (rsmpl_out, nbSample * sizeof (SFLDataFormat), 100); - getMainBuffer()->putData ( echoCancelledMic, sampleready*sizeof (SFLDataFormat), 100); + getMainBuffer()->putData (echoCancelledMic, sampleready*sizeof (SFLDataFormat), 100); free (rsmpl_out); rsmpl_out = 0; } else { - - SFLDataFormat* filter_out = (SFLDataFormat*) malloc (framesPerBufferAlsa * sizeof (SFLDataFormat)); - _audiofilter->processAudio (in, filter_out, toPut); - - int sampleready = AudioLayer::_echoCanceller->processAudio(filter_out, echoCancelledMic, toPut); + SFLDataFormat* filter_out = (SFLDataFormat*) malloc (framesPerBufferAlsa * sizeof (SFLDataFormat)); + + _audiofilter->processAudio (in, filter_out, toPut); - getMainBuffer()->putData (echoCancelledMic, sampleready*sizeof(SFLDataFormat), 100); - free(rsmpl_out); + int sampleready = AudioLayer::_echoCanceller->processAudio (filter_out, echoCancelledMic, toPut); + + getMainBuffer()->putData (echoCancelledMic, sampleready*sizeof (SFLDataFormat), 100); + free (rsmpl_out); } } @@ -1147,8 +1117,7 @@ void AlsaLayer::audioCallback(void) } } -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; diff --git a/sflphone-common/src/audio/audiodevice.cpp b/sflphone-common/src/audio/audiodevice.cpp index 1fd9744690f66faefc1b42d8b6267b78bc888d30..7e85e3cc9306ffe526a0fb59533fab7eb2988ba8 100644 --- a/sflphone-common/src/audio/audiodevice.cpp +++ b/sflphone-common/src/audio/audiodevice.cpp @@ -34,12 +34,10 @@ const double AudioDevice::DEFAULT_RATE = 8000.0; AudioDevice::AudioDevice (int id, const std::string& name) : - _id (id), _name (name), _rate (DEFAULT_RATE) -{ + _id (id), _name (name), _rate (DEFAULT_RATE) { _rate = DEFAULT_RATE; } -AudioDevice::~AudioDevice() -{ +AudioDevice::~AudioDevice() { } diff --git a/sflphone-common/src/audio/audiolayer.cpp b/sflphone-common/src/audio/audiolayer.cpp index 45d23a7bd613515cf1c80513736b4b47289f4bfa..f9e9d301293694903b6a3ada6ad5d48a6a6c3a66 100644 --- a/sflphone-common/src/audio/audiolayer.cpp +++ b/sflphone-common/src/audio/audiolayer.cpp @@ -30,8 +30,7 @@ #include "audiolayer.h" -void AudioLayer::flushMain (void) -{ +void AudioLayer::flushMain (void) { ost::MutexLock guard (_mutex); // should pass call id @@ -42,15 +41,13 @@ void AudioLayer::flushMain (void) } -void AudioLayer::flushUrgent (void) -{ +void AudioLayer::flushUrgent (void) { ost::MutexLock guard (_mutex); _urgentRingBuffer.flushAll(); } -int AudioLayer::putUrgent (void* buffer, int toCopy) -{ +int AudioLayer::putUrgent (void* buffer, int toCopy) { int a; ost::MutexLock guard (_mutex); @@ -65,8 +62,7 @@ int AudioLayer::putUrgent (void* buffer, int toCopy) return 0; } -int AudioLayer::putMain (void *buffer, int toCopy, CallID call_id) -{ +int AudioLayer::putMain (void *buffer, int toCopy, CallID call_id) { int a; ost::MutexLock guard (_mutex); diff --git a/sflphone-common/src/audio/audioloop.cpp b/sflphone-common/src/audio/audioloop.cpp index 67626daa59f7936922d914efcb4b25fa5f7d9c2f..228bd8c967dbb4ce8e9ad35500cf6a45cb08e23c 100644 --- a/sflphone-common/src/audio/audioloop.cpp +++ b/sflphone-common/src/audio/audioloop.cpp @@ -36,19 +36,16 @@ #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() -{ +AudioLoop::~AudioLoop() { 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; @@ -64,7 +61,7 @@ AudioLoop::getNext (SFLDataFormat* output, int nb, short volume) bcopy (_buffer+pos, output, block*sizeof (SFLDataFormat)); // short>char conversion if (volume!=100) { - for (int i=0;i<block;i++) { + for (int i=0; i<block; i++) { *output = (*output * volume) /100; output++; } diff --git a/sflphone-common/src/audio/audioprocessing.cpp b/sflphone-common/src/audio/audioprocessing.cpp index 264bbef498d8ab4b054bf1fa5e134507d30d8f6f..577cc87fcbb350327bbc162cb258873c7039c665 100644 --- a/sflphone-common/src/audio/audioprocessing.cpp +++ b/sflphone-common/src/audio/audioprocessing.cpp @@ -33,47 +33,42 @@ -AudioProcessing::AudioProcessing(Algorithm *_algo) : _algorithm(_algo) {} +AudioProcessing::AudioProcessing (Algorithm *_algo) : _algorithm (_algo) {} -AudioProcessing::~AudioProcessing(void){} +AudioProcessing::~AudioProcessing (void) {} -void AudioProcessing::resetAlgorithm(void) -{ - if(_algorithm) - _algorithm->reset(); +void AudioProcessing::resetAlgorithm (void) { + if (_algorithm) + _algorithm->reset(); } -int AudioProcessing::getData(SFLDataFormat *outputData) -{ - if(_algorithm) - return _algorithm->getData(outputData); - else - return 0; +int AudioProcessing::getData (SFLDataFormat *outputData) { + if (_algorithm) + return _algorithm->getData (outputData); + else + return 0; } -void AudioProcessing::putData(SFLDataFormat *inputData, int nbBytes) -{ - if(_algorithm) - _algorithm->putData(inputData, nbBytes); +void AudioProcessing::putData (SFLDataFormat *inputData, int nbBytes) { + if (_algorithm) + _algorithm->putData (inputData, nbBytes); } -void AudioProcessing::processAudio(SFLDataFormat *inputData, int nbBytes) -{ - if(_algorithm) - _algorithm->process(inputData, nbBytes); +void AudioProcessing::processAudio (SFLDataFormat *inputData, int nbBytes) { + if (_algorithm) + _algorithm->process (inputData, nbBytes); } -int AudioProcessing::processAudio(SFLDataFormat *inputData, SFLDataFormat *outputData, int nbBytes) -{ - if(_algorithm) - return _algorithm->process(inputData, outputData, nbBytes); - else - return 0; +int AudioProcessing::processAudio (SFLDataFormat *inputData, SFLDataFormat *outputData, int nbBytes) { + if (_algorithm) + return _algorithm->process (inputData, outputData, nbBytes); + else + return 0; } -void AudioProcessing::processAudio(SFLDataFormat *micData, SFLDataFormat *spkrData, SFLDataFormat *outputData, int nbBytes) { - if(_algorithm) - _algorithm->process(micData, spkrData, outputData, nbBytes); +void AudioProcessing::processAudio (SFLDataFormat *micData, SFLDataFormat *spkrData, SFLDataFormat *outputData, int nbBytes) { + if (_algorithm) + _algorithm->process (micData, spkrData, outputData, nbBytes); } diff --git a/sflphone-common/src/audio/audiorecord.cpp b/sflphone-common/src/audio/audiorecord.cpp index 06d97d0b30d0ee58919e957e3f243245a880ae1e..a063e8fac7b1adf76059ca7e6622ee252f5ad8ae 100644 --- a/sflphone-common/src/audio/audiorecord.cpp +++ b/sflphone-common/src/audio/audiorecord.cpp @@ -49,8 +49,7 @@ struct wavhdr { }; -AudioRecord::AudioRecord() -{ +AudioRecord::AudioRecord() { sndSmplRate_ = 8000; channels_ = 1; @@ -66,21 +65,18 @@ AudioRecord::AudioRecord() spkBuffer_ = new SFLDataFormat[nbSamplesMax_]; } -AudioRecord::~AudioRecord() -{ +AudioRecord::~AudioRecord() { delete [] mixBuffer_; delete [] micBuffer_; delete [] spkBuffer_; } -void AudioRecord::setSndSamplingRate (int smplRate) -{ +void AudioRecord::setSndSamplingRate (int smplRate) { sndSmplRate_ = smplRate; } -void AudioRecord::setRecordingOption (FILE_TYPE type, SOUND_FORMAT format, int sndSmplRate, std::string path) -{ +void AudioRecord::setRecordingOption (FILE_TYPE type, SOUND_FORMAT format, int sndSmplRate, std::string path) { fileType_ = type; @@ -94,8 +90,7 @@ void AudioRecord::setRecordingOption (FILE_TYPE type, SOUND_FORMAT format, int s -void AudioRecord::initFileName (std::string peerNumber) -{ +void AudioRecord::initFileName (std::string peerNumber) { std::string fName; @@ -104,12 +99,12 @@ void AudioRecord::initFileName (std::string peerNumber) if (fileType_ == FILE_RAW) { if (strstr (fileName_, ".raw") == NULL) { - _debug("AudioRecord: concatenate .raw file extension: name : %s", fileName_); + _debug ("AudioRecord: concatenate .raw file extension: name : %s", fileName_); fName.append (".raw"); } } else if (fileType_ == FILE_WAV) { if (strstr (fileName_, ".wav") == NULL) { - _debug("AudioRecord: concatenate .wav file extension: name : %s", fileName_); + _debug ("AudioRecord: concatenate .wav file extension: name : %s", fileName_); fName.append (".wav"); } } @@ -117,8 +112,7 @@ void AudioRecord::initFileName (std::string peerNumber) savePath_.append (fName); } -void AudioRecord::openFile() -{ +void AudioRecord::openFile() { bool result = false; @@ -145,8 +139,7 @@ void AudioRecord::openFile() } -void AudioRecord::closeFile() -{ +void AudioRecord::closeFile() { if (fp == 0) return; @@ -160,8 +153,7 @@ void AudioRecord::closeFile() } -bool AudioRecord::isOpenFile() -{ +bool AudioRecord::isOpenFile() { if (fp) { return true; @@ -171,8 +163,7 @@ bool AudioRecord::isOpenFile() } -bool AudioRecord::isFileExist() -{ +bool AudioRecord::isFileExist() { _info ("AudioRecord: Try to open name : %s ", fileName_); if (fopen (fileName_,"rb") ==0) { @@ -182,8 +173,7 @@ bool AudioRecord::isFileExist() return false; } -bool AudioRecord::isRecording() -{ +bool AudioRecord::isRecording() { if (recordingEnabled_) return true; @@ -192,22 +182,19 @@ bool AudioRecord::isRecording() } -bool AudioRecord::setRecording() -{ +bool AudioRecord::setRecording() { if (isOpenFile()) { - if (!recordingEnabled_) { - _info ("AudioRecording: Start recording"); - recordingEnabled_ = true; - } - else { - recordingEnabled_ = false; - _info ("AudioRecording: Stop recording"); - } - } - else { + if (!recordingEnabled_) { + _info ("AudioRecording: Start recording"); + recordingEnabled_ = true; + } else { + recordingEnabled_ = false; + _info ("AudioRecording: Stop recording"); + } + } else { openFile(); - + recordingEnabled_ = true; // once opend file, start recording } @@ -216,8 +203,7 @@ bool AudioRecord::setRecording() } -void AudioRecord::stopRecording() -{ +void AudioRecord::stopRecording() { _info ("AudioRecording: Stop recording"); if (recordingEnabled_) @@ -225,8 +211,7 @@ void AudioRecord::stopRecording() } -void AudioRecord::createFilename() -{ +void AudioRecord::createFilename() { time_t rawtime; @@ -275,11 +260,10 @@ void AudioRecord::createFilename() // fileName_ = out.str(); strncpy (fileName_, out.str().c_str(), 8192); - _info("AudioRecord: create filename for this call %s ", fileName_); + _info ("AudioRecord: create filename for this call %s ", fileName_); } -bool AudioRecord::setRawFile() -{ +bool AudioRecord::setRawFile() { fp = fopen (savePath_.c_str(), "wb"); @@ -299,13 +283,12 @@ bool AudioRecord::setRawFile() } -bool AudioRecord::setWavFile() -{ +bool AudioRecord::setWavFile() { fp = fopen (savePath_.c_str(), "wb"); if (!fp) { - _warn("AudioRecord: Error: could not create WAV file."); + _warn ("AudioRecord: Error: could not create WAV file."); return false; } @@ -333,7 +316,7 @@ bool AudioRecord::setWavFile() if (fwrite (&hdr, 4, 11, fp) != 11) { - _warn("AudioRecord: Error: could not write WAV header for file. "); + _warn ("AudioRecord: Error: could not write WAV header for file. "); return false; } @@ -343,8 +326,7 @@ bool AudioRecord::setWavFile() } -bool AudioRecord::openExistingRawFile() -{ +bool AudioRecord::openExistingRawFile() { fp = fopen (fileName_, "ab+"); if (!fp) { @@ -356,14 +338,13 @@ bool AudioRecord::openExistingRawFile() } -bool AudioRecord::openExistingWavFile() -{ +bool AudioRecord::openExistingWavFile() { _info ("AudioRecord: Open existing wave file"); fp = fopen (fileName_, "rb+"); if (!fp) { - _warn("AudioRecord: Error: could not open WAV file!"); + _warn ("AudioRecord: Error: could not open WAV file!"); return false; } @@ -373,7 +354,7 @@ bool AudioRecord::openExistingWavFile() _warn ("AudioRecord: Error: Couldn't seek offset 40 in the file "); if (fread (&byteCounter_, 4, 1, fp)) - _warn("AudioRecord: Error: bytecounter Read successfully "); + _warn ("AudioRecord: Error: bytecounter Read successfully "); if (fseek (fp, 0 , SEEK_END) != 0) _warn ("AudioRecord: Error: Couldn't seek at the en of the file "); @@ -399,36 +380,39 @@ bool AudioRecord::openExistingWavFile() } -void AudioRecord::closeWavFile() -{ +void AudioRecord::closeWavFile() { if (fp == 0) { _debug ("AudioRecord: Can't closeWavFile, a file has not yet been opened!"); return; } - _debug("AudioRecord: Close wave file"); + _debug ("AudioRecord: Close wave file"); SINT32 bytes = byteCounter_ * channels_; fseek (fp, 40, SEEK_SET); // jump to data length - if (ferror (fp)) + + if (ferror (fp)) _warn ("AudioRecord: Error: can't reach offset 40 while closing"); fwrite (&bytes, sizeof (SINT32), 1, fp); - if (ferror (fp)) + + if (ferror (fp)) _warn ("AudioRecord: Error: can't write bytes for data length "); bytes = byteCounter_ * channels_ + 44; // + 44 for the wave header fseek (fp, 4, SEEK_SET); // jump to file size - if (ferror (fp)) + + if (ferror (fp)) _warn ("AudioRecord: Error: can't reach offset 4"); fwrite (&bytes, 4, 1, fp); - if (ferror (fp)) - _warn("AudioRecord: Error: can't reach offset 4"); + + if (ferror (fp)) + _warn ("AudioRecord: Error: can't reach offset 4"); if (fclose (fp) != 0) @@ -437,8 +421,7 @@ void AudioRecord::closeWavFile() } -void AudioRecord::recSpkrData (SFLDataFormat* buffer, int nSamples) -{ +void AudioRecord::recSpkrData (SFLDataFormat* buffer, int nSamples) { if (recordingEnabled_) { @@ -452,8 +435,7 @@ void AudioRecord::recSpkrData (SFLDataFormat* buffer, int nSamples) } -void AudioRecord::recMicData (SFLDataFormat* buffer, int nSamples) -{ +void AudioRecord::recMicData (SFLDataFormat* buffer, int nSamples) { if (recordingEnabled_) { @@ -468,10 +450,9 @@ void AudioRecord::recMicData (SFLDataFormat* buffer, int nSamples) } -void AudioRecord::recData (SFLDataFormat* buffer, int nSamples) -{ +void AudioRecord::recData (SFLDataFormat* buffer, int nSamples) { - if (recordingEnabled_) { + if (recordingEnabled_) { if (fp == 0) { _debug ("AudioRecord: Can't record data, a file has not yet been opened!"); @@ -494,12 +475,11 @@ void AudioRecord::recData (SFLDataFormat* buffer, int nSamples) } -void AudioRecord::recData (SFLDataFormat* buffer_1, SFLDataFormat* buffer_2, int nSamples_1, int nSamples_2) -{ +void AudioRecord::recData (SFLDataFormat* buffer_1, SFLDataFormat* buffer_2, int nSamples_1, int nSamples_2) { if (recordingEnabled_) { - _debug("Recording enabled"); + _debug ("Recording enabled"); if (fp == 0) { _debug ("AudioRecord: Can't record data, a file has not yet been opened!"); diff --git a/sflphone-common/src/audio/audiorecorder.cpp b/sflphone-common/src/audio/audiorecorder.cpp index bb846e022b3a728c3bca022514583d0e84e30663..4353368f535756c88225181bdfe92dc7d9e69749 100644 --- a/sflphone-common/src/audio/audiorecorder.cpp +++ b/sflphone-common/src/audio/audiorecorder.cpp @@ -33,13 +33,12 @@ int AudioRecorder::count = 0; -AudioRecorder::AudioRecorder (AudioRecord *arec, MainBuffer *mb) : Thread() -{ +AudioRecorder::AudioRecorder (AudioRecord *arec, MainBuffer *mb) : Thread() { setCancel (cancelDeferred); ++count; - std::string id("processid_"); + std::string id ("processid_"); // convert count into string std::string s; @@ -47,37 +46,36 @@ AudioRecorder::AudioRecorder (AudioRecord *arec, MainBuffer *mb) : Thread() out << count; s = out.str(); - recorderId = id.append(s); + recorderId = id.append (s); arecord = arec; - mbuffer = mb; + mbuffer = mb; } /** * Reimplementation of run() */ -void AudioRecorder::run (void) -{ +void AudioRecorder::run (void) { SFLDataFormat buffer[10000]; - while(true) { + while (true) { - if(!mbuffer) - _warn("AudioRecorder: Error: No instance of ringbuffer"); + if (!mbuffer) + _warn ("AudioRecorder: Error: No instance of ringbuffer"); - int availBytes = mbuffer->availForGet(recorderId); + int availBytes = mbuffer->availForGet (recorderId); - if(availBytes > 0) { + if (availBytes > 0) { - int got = mbuffer->getData(buffer, availBytes, 100, recorderId); + int got = mbuffer->getData (buffer, availBytes, 100, recorderId); - int availBytesAfter = mbuffer->availForGet(recorderId); + int availBytesAfter = mbuffer->availForGet (recorderId); - arecord->recData(buffer, availBytes/sizeof(SFLDataFormat)); - } + arecord->recData (buffer, availBytes/sizeof (SFLDataFormat)); + } - sleep(20); + sleep (20); } diff --git a/sflphone-common/src/audio/audiortp/AudioRtpFactory.cpp b/sflphone-common/src/audio/audiortp/AudioRtpFactory.cpp index 85f53cf09e5e31ca623104932c608b8d3e56283b..cffccb23d64f8315a2ca4e927bd7fc54018b3b2d 100644 --- a/sflphone-common/src/audio/audiortp/AudioRtpFactory.cpp +++ b/sflphone-common/src/audio/audiortp/AudioRtpFactory.cpp @@ -40,16 +40,13 @@ #include <assert.h> -namespace sfl -{ +namespace sfl { -AudioRtpFactory::AudioRtpFactory() : _rtpSession (NULL) -{ +AudioRtpFactory::AudioRtpFactory() : _rtpSession (NULL) { } -AudioRtpFactory::AudioRtpFactory (SIPCall *ca) : _rtpSession (NULL) -{ +AudioRtpFactory::AudioRtpFactory (SIPCall *ca) : _rtpSession (NULL) { assert (ca); try { @@ -59,13 +56,11 @@ AudioRtpFactory::AudioRtpFactory (SIPCall *ca) : _rtpSession (NULL) } } -AudioRtpFactory::~AudioRtpFactory() -{ +AudioRtpFactory::~AudioRtpFactory() { stop(); } -void AudioRtpFactory::initAudioRtpConfig(SIPCall *ca) -{ +void AudioRtpFactory::initAudioRtpConfig (SIPCall *ca) { assert (ca); if (_rtpSession != NULL) { @@ -90,11 +85,11 @@ void AudioRtpFactory::initAudioRtpConfig(SIPCall *ca) } } -void AudioRtpFactory::initAudioRtpSession (SIPCall * ca) -{ +void AudioRtpFactory::initAudioRtpSession (SIPCall * ca) { ost::MutexLock m (_audioRtpThreadMutex); _debug ("Srtp enable: %d ", _srtpEnabled); + if (_srtpEnabled) { std::string zidFilename (Manager::instance().getConfigString (SIGNALISATION, ZRTP_ZIDFILE)); @@ -115,14 +110,14 @@ void AudioRtpFactory::initAudioRtpSession (SIPCall * ca) case Sdes: - _rtpSession = new AudioSrtpSession (&Manager::instance(), ca); + _rtpSession = new AudioSrtpSession (&Manager::instance(), ca); _rtpSessionType = Sdes; - ca->getLocalSDP()->set_srtp_crypto(static_cast<AudioSrtpSession *> (_rtpSession)->getLocalCryptoInfo()); - break; + ca->getLocalSDP()->set_srtp_crypto (static_cast<AudioSrtpSession *> (_rtpSession)->getLocalCryptoInfo()); + break; default: - _debug("Unsupported Rtp Session Exception Type!"); + _debug ("Unsupported Rtp Session Exception Type!"); throw UnsupportedRtpSessionType(); } } else { @@ -132,8 +127,7 @@ void AudioRtpFactory::initAudioRtpSession (SIPCall * ca) } } -void AudioRtpFactory::start (AudioCodec* audiocodec) -{ +void AudioRtpFactory::start (AudioCodec* audiocodec) { if (_rtpSession == NULL) { throw AudioRtpFactoryException ("RTP: Error: _rtpSession was null when trying to start audio thread"); } @@ -141,15 +135,17 @@ void AudioRtpFactory::start (AudioCodec* audiocodec) switch (_rtpSessionType) { case Sdes: - if (static_cast<AudioSrtpSession *> (_rtpSession)->startRtpThread(audiocodec) != 0) { + + if (static_cast<AudioSrtpSession *> (_rtpSession)->startRtpThread (audiocodec) != 0) { throw AudioRtpFactoryException ("RTP: Error: Failed to start AudioSRtpSession thread"); } - break; + + break; case Symmetric: _debug ("Starting symmetric rtp thread"); - if (static_cast<AudioSymmetricRtpSession *> (_rtpSession)->startRtpThread(audiocodec) != 0) { + if (static_cast<AudioSymmetricRtpSession *> (_rtpSession)->startRtpThread (audiocodec) != 0) { throw AudioRtpFactoryException ("RTP: Error: Failed to start AudioSymmetricRtpSession thread"); } @@ -157,17 +153,17 @@ void AudioRtpFactory::start (AudioCodec* audiocodec) case Zrtp: - if (static_cast<AudioZrtpSession *> (_rtpSession)->startRtpThread(audiocodec) != 0) { + if (static_cast<AudioZrtpSession *> (_rtpSession)->startRtpThread (audiocodec) != 0) { throw AudioRtpFactoryException ("RTP: Error: Failed to start AudioZrtpSession thread"); } + break; } } -void AudioRtpFactory::stop (void) -{ +void AudioRtpFactory::stop (void) { ost::MutexLock mutex (_audioRtpThreadMutex); - _info("RTP: Stopping audio rtp session"); + _info ("RTP: Stopping audio rtp session"); if (_rtpSession == NULL) { _debugException ("RTP: Error: _rtpSession is null when trying to stop. Returning."); @@ -178,8 +174,8 @@ void AudioRtpFactory::stop (void) switch (_rtpSessionType) { case Sdes: - delete static_cast<AudioSrtpSession *> (_rtpSession); - break; + delete static_cast<AudioSrtpSession *> (_rtpSession); + break; case Symmetric: delete static_cast<AudioSymmetricRtpSession *> (_rtpSession); @@ -193,13 +189,13 @@ void AudioRtpFactory::stop (void) _rtpSession = NULL; } catch (...) { _debugException ("RTP: Error: Exception caught when stopping the audio rtp session"); - throw AudioRtpFactoryException("RTP: Error: caught exception in AudioRtpFactory::stop"); + throw AudioRtpFactoryException ("RTP: Error: caught exception in AudioRtpFactory::stop"); } } -void AudioRtpFactory::updateDestinationIpAddress (void) -{ +void AudioRtpFactory::updateDestinationIpAddress (void) { _info ("RTP: Updating IP address"); + if (_rtpSession == NULL) { throw AudioRtpFactoryException ("RTP: Error: _rtpSession was null when trying to update IP address"); } @@ -207,62 +203,58 @@ void AudioRtpFactory::updateDestinationIpAddress (void) switch (_rtpSessionType) { case Sdes: - static_cast<AudioSrtpSession *> (_rtpSession)->updateDestinationIpAddress(); - break; + static_cast<AudioSrtpSession *> (_rtpSession)->updateDestinationIpAddress(); + break; case Symmetric: static_cast<AudioSymmetricRtpSession *> (_rtpSession)->updateDestinationIpAddress(); break; case Zrtp: - static_cast<AudioZrtpSession *> (_rtpSession)->updateDestinationIpAddress(); + static_cast<AudioZrtpSession *> (_rtpSession)->updateDestinationIpAddress(); break; } } -sfl::AudioSymmetricRtpSession * AudioRtpFactory::getAudioSymetricRtpSession() -{ - if ( (_rtpSessionType == Symmetric) && (_rtpSessionType != NULL)) { - return static_cast<AudioSymmetricRtpSession *> (_rtpSession); - } else { - throw AudioRtpFactoryException("RTP: Error: _rtpSession is NULL in getAudioSymetricRtpSession"); - } +sfl::AudioSymmetricRtpSession * AudioRtpFactory::getAudioSymetricRtpSession() { + if ( (_rtpSessionType == Symmetric) && (_rtpSessionType != NULL)) { + return static_cast<AudioSymmetricRtpSession *> (_rtpSession); + } else { + throw AudioRtpFactoryException ("RTP: Error: _rtpSession is NULL in getAudioSymetricRtpSession"); + } } -sfl::AudioZrtpSession * AudioRtpFactory::getAudioZrtpSession() -{ +sfl::AudioZrtpSession * AudioRtpFactory::getAudioZrtpSession() { if ( (_rtpSessionType == Zrtp) && (_rtpSessionType != NULL)) { return static_cast<AudioZrtpSession *> (_rtpSession); } else { - throw AudioRtpFactoryException("RTP: Error: _rtpSession is NULL in getAudioZrtpSession"); + throw AudioRtpFactoryException ("RTP: Error: _rtpSession is NULL in getAudioZrtpSession"); } } -void AudioRtpFactory::setRemoteCryptoInfo(sfl::SdesNegotiator& nego) -{ - if ( _rtpSession && _rtpSessionType && (_rtpSessionType == Sdes)) { - static_cast<AudioSrtpSession *> (_rtpSession)->setRemoteCryptoInfo(nego); - } - else { - throw AudioRtpFactoryException("RTP: Error: _rtpSession is NULL in setRemoteCryptoInfo"); +void AudioRtpFactory::setRemoteCryptoInfo (sfl::SdesNegotiator& nego) { + if (_rtpSession && _rtpSessionType && (_rtpSessionType == Sdes)) { + static_cast<AudioSrtpSession *> (_rtpSession)->setRemoteCryptoInfo (nego); + } else { + throw AudioRtpFactoryException ("RTP: Error: _rtpSession is NULL in setRemoteCryptoInfo"); } } -void AudioRtpFactory::sendDtmfDigit(int digit) { - switch(_rtpSessionType) { +void AudioRtpFactory::sendDtmfDigit (int digit) { + switch (_rtpSessionType) { - case Sdes: - static_cast<AudioSrtpSession *> (_rtpSession)->putDtmfEvent(digit); - break; + case Sdes: + static_cast<AudioSrtpSession *> (_rtpSession)->putDtmfEvent (digit); + break; - case Symmetric: - static_cast<AudioSymmetricRtpSession *> (_rtpSession)->putDtmfEvent(digit); - break; + case Symmetric: + static_cast<AudioSymmetricRtpSession *> (_rtpSession)->putDtmfEvent (digit); + break; - case Zrtp: - static_cast<AudioZrtpSession *> (_rtpSession)->putDtmfEvent(digit); - break; - } + case Zrtp: + static_cast<AudioZrtpSession *> (_rtpSession)->putDtmfEvent (digit); + break; + } } } diff --git a/sflphone-common/src/audio/audiortp/AudioSrtpSession.cpp b/sflphone-common/src/audio/audiortp/AudioSrtpSession.cpp index a5608d997a234a9583890eb42bc557dfe2350f8d..90e7b8716560fb5d373d06c4756a364725728a9f 100644 --- a/sflphone-common/src/audio/audiortp/AudioSrtpSession.cpp +++ b/sflphone-common/src/audio/audiortp/AudioSrtpSession.cpp @@ -45,18 +45,17 @@ #include <cerrno> -namespace sfl -{ +namespace sfl { AudioSrtpSession::AudioSrtpSession (ManagerImpl * manager, SIPCall * sipcall) : ost::SymmetricRTPSession (ost::InetHostAddress (sipcall->getLocalIp().c_str()), sipcall->getLocalAudioPort()), AudioRtpSession<AudioSrtpSession> (manager, sipcall), - _localCryptoSuite(0), - _remoteCryptoSuite(0), - _localMasterKeyLength(0), - _localMasterSaltLength(0), - _remoteMasterKeyLength(0), - _remoteMasterSaltLength(0) + _localCryptoSuite (0), + _remoteCryptoSuite (0), + _localMasterKeyLength (0), + _localMasterSaltLength (0), + _remoteMasterKeyLength (0), + _remoteMasterSaltLength (0) { @@ -66,19 +65,19 @@ AudioSrtpSession::AudioSrtpSession (ManagerImpl * manager, SIPCall * sipcall) : initializeLocalCryptoContext(); // Set local crypto context in ccrtp - _localCryptoCtx->deriveSrtpKeys(0); + _localCryptoCtx->deriveSrtpKeys (0); - setOutQueueCryptoContext(_localCryptoCtx); + setOutQueueCryptoContext (_localCryptoCtx); } - + std::vector<std::string> AudioSrtpSession::getLocalCryptoInfo() { - _debug("Get Cryptographic info from this rtp session"); + _debug ("Get Cryptographic info from this rtp session"); std::vector<std::string> crypto_vector; - // @TODO we should return a vector containing supported + // @TODO we should return a vector containing supported // cryptographic context tagged 1, 2, 3... std::string tag = "1"; @@ -92,33 +91,32 @@ std::vector<std::string> AudioSrtpSession::getLocalCryptoInfo() { // srtp_keys.append("|2^20|1:32"); // generate crypto attribute - std::string crypto_attr = tag.append(" "); - crypto_attr += crypto_suite.append(" "); + std::string crypto_attr = tag.append (" "); + crypto_attr += crypto_suite.append (" "); crypto_attr += srtp_keys; - _debug("%s", crypto_attr.c_str()); + _debug ("%s", crypto_attr.c_str()); - crypto_vector.push_back(crypto_attr); + crypto_vector.push_back (crypto_attr); return crypto_vector; } -void AudioSrtpSession::setRemoteCryptoInfo(sfl::SdesNegotiator& nego) { +void AudioSrtpSession::setRemoteCryptoInfo (sfl::SdesNegotiator& nego) { - _debug("Set remote Cryptographic info for Srtp"); + _debug ("Set remote Cryptographic info for Srtp"); // decode keys - unBase64ConcatenatedKeys(nego.getKeyInfo()); + unBase64ConcatenatedKeys (nego.getKeyInfo()); // init crypto content int Srtp session initializeRemoteCryptoContext(); - setInQueueCryptoContext(_remoteCryptoCtx); + setInQueueCryptoContext (_remoteCryptoCtx); } -void AudioSrtpSession::initializeLocalMasterKey(void) -{ +void AudioSrtpSession::initializeLocalMasterKey (void) { // @TODO key may have different length depending on cipher suite _localMasterKeyLength = sfl::CryptoSuites[_localCryptoSuite].masterKeyLength / 8; @@ -128,10 +126,11 @@ void AudioSrtpSession::initializeLocalMasterKey(void) // Generate ryptographically strong pseudo-random bytes int err; - if((err = RAND_bytes(random_key, _localMasterKeyLength)) != 1) - _debug("Error occured while generating cryptographically strong pseudo-random key"); - memcpy(_localMasterKey, random_key, _localMasterKeyLength); + if ( (err = RAND_bytes (random_key, _localMasterKeyLength)) != 1) + _debug ("Error occured while generating cryptographically strong pseudo-random key"); + + memcpy (_localMasterKey, random_key, _localMasterKeyLength); /* printf("Local Master: "); @@ -144,29 +143,28 @@ void AudioSrtpSession::initializeLocalMasterKey(void) } -void AudioSrtpSession::initializeLocalMasterSalt(void) -{ +void AudioSrtpSession::initializeLocalMasterSalt (void) { - // @TODO key may have different length depending on cipher suite - _localMasterSaltLength = sfl::CryptoSuites[_localCryptoSuite].masterSaltLength / 8; + // @TODO key may have different length depending on cipher suite + _localMasterSaltLength = sfl::CryptoSuites[_localCryptoSuite].masterSaltLength / 8; // Allocate memory for key unsigned char *random_key = new unsigned char[_localMasterSaltLength]; // Generate ryptographically strong pseudo-random bytes int err; - if((err = RAND_bytes(random_key, _localMasterSaltLength)) != 1) - _debug("Error occured while generating cryptographically strong pseudo-random key"); - memcpy(_localMasterSalt, random_key, _localMasterSaltLength); + if ( (err = RAND_bytes (random_key, _localMasterSaltLength)) != 1) + _debug ("Error occured while generating cryptographically strong pseudo-random key"); + + memcpy (_localMasterSalt, random_key, _localMasterSaltLength); return; } -std::string AudioSrtpSession::getBase64ConcatenatedKeys() -{ +std::string AudioSrtpSession::getBase64ConcatenatedKeys() { // compute concatenated master and salt length int concatLength = _localMasterKeyLength + _localMasterSaltLength; @@ -174,23 +172,22 @@ std::string AudioSrtpSession::getBase64ConcatenatedKeys() uint8 concatKeys[concatLength]; // concatenate keys - memcpy((void*)concatKeys, (void*)_localMasterKey, _localMasterKeyLength); - memcpy((void*)(concatKeys + _localMasterKeyLength), (void*)_localMasterSalt, _localMasterSaltLength); + memcpy ( (void*) concatKeys, (void*) _localMasterKey, _localMasterKeyLength); + memcpy ( (void*) (concatKeys + _localMasterKeyLength), (void*) _localMasterSalt, _localMasterSaltLength); // encode concatenated keys in base64 - char *output = encodeBase64((unsigned char*)concatKeys, concatLength); + char *output = encodeBase64 ( (unsigned char*) concatKeys, concatLength); // init string containing encoded data - std::string keys(output); + std::string keys (output); - free(output); + free (output); return keys; } -void AudioSrtpSession::unBase64ConcatenatedKeys(std::string base64keys) -{ +void AudioSrtpSession::unBase64ConcatenatedKeys (std::string base64keys) { _remoteMasterKeyLength = sfl::CryptoSuites[1].masterKeyLength / 8; _remoteMasterSaltLength = sfl::CryptoSuites[1].masterSaltLength / 8; @@ -199,112 +196,108 @@ void AudioSrtpSession::unBase64ConcatenatedKeys(std::string base64keys) int length; // pointer to binary data - char *dataptr = (char*)base64keys.data(); + char *dataptr = (char*) base64keys.data(); // decode concatenated binary keys - char *output = decodeBase64((unsigned char*)dataptr, strlen(dataptr), &length); + char *output = decodeBase64 ( (unsigned char*) dataptr, strlen (dataptr), &length); // copy master and slt respectively - memcpy((void*)_remoteMasterKey, (void*)output, _remoteMasterKeyLength); - memcpy((void*)_remoteMasterSalt, (void*)(output + _remoteMasterKeyLength), _remoteMasterSaltLength); + memcpy ( (void*) _remoteMasterKey, (void*) output, _remoteMasterKeyLength); + memcpy ( (void*) _remoteMasterSalt, (void*) (output + _remoteMasterKeyLength), _remoteMasterSaltLength); - free(output); + free (output); } -void AudioSrtpSession::initializeRemoteCryptoContext(void) -{ +void AudioSrtpSession::initializeRemoteCryptoContext (void) { CryptoSuiteDefinition crypto = sfl::CryptoSuites[_localCryptoSuite]; - _remoteCryptoCtx = new ost::CryptoContext(0x0, - 0, // roc, - 0L, // keydr, - SrtpEncryptionAESCM, // encryption algo - SrtpAuthenticationSha1Hmac, // authtication algo - _remoteMasterKey, - _remoteMasterKeyLength, - _remoteMasterSalt, - _remoteMasterSaltLength, - crypto.encryptionKeyLength / 8, - crypto.srtpAuthKeyLength / 8, - 112 / 8, // session salt len - crypto.srtpAuthTagLength / 8); - + _remoteCryptoCtx = new ost::CryptoContext (0x0, + 0, // roc, + 0L, // keydr, + SrtpEncryptionAESCM, // encryption algo + SrtpAuthenticationSha1Hmac, // authtication algo + _remoteMasterKey, + _remoteMasterKeyLength, + _remoteMasterSalt, + _remoteMasterSaltLength, + crypto.encryptionKeyLength / 8, + crypto.srtpAuthKeyLength / 8, + 112 / 8, // session salt len + crypto.srtpAuthTagLength / 8); + } -void AudioSrtpSession::initializeLocalCryptoContext(void) -{ +void AudioSrtpSession::initializeLocalCryptoContext (void) { CryptoSuiteDefinition crypto = sfl::CryptoSuites[_localCryptoSuite]; - _localCryptoCtx = new ost::CryptoContext(OutgoingDataQueue::getLocalSSRC(), - 0, // roc, - 0L, // keydr, - SrtpEncryptionAESCM, // encryption algo - SrtpAuthenticationSha1Hmac, // authtication algo - _localMasterKey, - _localMasterKeyLength, - _localMasterSalt, - _localMasterSaltLength, - crypto.encryptionKeyLength / 8, - crypto.srtpAuthKeyLength / 8, - 112 / 8, // session salt len - crypto.srtpAuthTagLength / 8); + _localCryptoCtx = new ost::CryptoContext (OutgoingDataQueue::getLocalSSRC(), + 0, // roc, + 0L, // keydr, + SrtpEncryptionAESCM, // encryption algo + SrtpAuthenticationSha1Hmac, // authtication algo + _localMasterKey, + _localMasterKeyLength, + _localMasterSalt, + _localMasterSaltLength, + crypto.encryptionKeyLength / 8, + crypto.srtpAuthKeyLength / 8, + 112 / 8, // session salt len + crypto.srtpAuthTagLength / 8); } -char* AudioSrtpSession::encodeBase64(unsigned char *input, int length) -{ +char* AudioSrtpSession::encodeBase64 (unsigned char *input, int length) { BIO *b64, *bmem; BUF_MEM *bptr ; - char *buffer = (char *)malloc(2*length); - memset(buffer, 0, 2*length); + char *buffer = (char *) malloc (2*length); + memset (buffer, 0, 2*length); // init decoder - b64 = BIO_new(BIO_f_base64()); - BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); + b64 = BIO_new (BIO_f_base64()); + BIO_set_flags (b64, BIO_FLAGS_BASE64_NO_NL); // init internal buffer - bmem = BIO_new(BIO_s_mem()); + bmem = BIO_new (BIO_s_mem()); // create decoder chain - b64 = BIO_push(b64, bmem); + b64 = BIO_push (b64, bmem); - BIO_write(b64, input, length); - BIO_flush(b64); + BIO_write (b64, input, length); + BIO_flush (b64); // get pointer to data - BIO_get_mem_ptr(b64, &bptr); + BIO_get_mem_ptr (b64, &bptr); // copy result in output buffer (-1 since we do not want the EOF character) - strncpy(buffer, (char*)(bptr->data), bptr->length); + strncpy (buffer, (char*) (bptr->data), bptr->length); - BIO_free_all(bmem); + BIO_free_all (bmem); - return buffer; + return buffer; } -char* AudioSrtpSession::decodeBase64(unsigned char *input, int length, int *length_out) -{ +char* AudioSrtpSession::decodeBase64 (unsigned char *input, int length, int *length_out) { BIO *b64, *bmem; - char *buffer = (char *)malloc(length); - memset(buffer, 0, length); + char *buffer = (char *) malloc (length); + memset (buffer, 0, length); // init decoder and read-only BIO buffer - b64 = BIO_new(BIO_f_base64()); - BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); + b64 = BIO_new (BIO_f_base64()); + BIO_set_flags (b64, BIO_FLAGS_BASE64_NO_NL); // init internal buffer - bmem = BIO_new_mem_buf(input, length); + bmem = BIO_new_mem_buf (input, length); // create encoder chain - bmem = BIO_push(b64, bmem); + bmem = BIO_push (b64, bmem); - *length_out = BIO_read(bmem, buffer, length); + *length_out = BIO_read (bmem, buffer, length); - BIO_free_all(bmem); + BIO_free_all (bmem); return buffer; diff --git a/sflphone-common/src/audio/audiortp/AudioZrtpSession.cpp b/sflphone-common/src/audio/audiortp/AudioZrtpSession.cpp index 6632bc2a61c63f87223b32b8447e13c6f5e4febe..8a2c4168b296316725e5a5dbf4ddd847c99f3d71 100644 --- a/sflphone-common/src/audio/audiortp/AudioZrtpSession.cpp +++ b/sflphone-common/src/audio/audiortp/AudioZrtpSession.cpp @@ -39,20 +39,17 @@ #include <cstring> #include <cerrno> -namespace sfl -{ +namespace sfl { AudioZrtpSession::AudioZrtpSession (ManagerImpl * manager, SIPCall * sipcall, const std::string& zidFilename) : ost::SymmetricZRTPSession (ost::InetHostAddress (sipcall->getLocalIp().c_str()), sipcall->getLocalAudioPort()), AudioRtpSession<AudioZrtpSession> (manager, sipcall), - _zidFilename (zidFilename) -{ + _zidFilename (zidFilename) { _debug ("AudioZrtpSession initialized"); initializeZid(); } -void AudioZrtpSession::initializeZid (void) -{ +void AudioZrtpSession::initializeZid (void) { if (_zidFilename.empty()) { throw ZrtpZidException(); diff --git a/sflphone-common/src/audio/audiortp/ZrtpSessionCallback.cpp b/sflphone-common/src/audio/audiortp/ZrtpSessionCallback.cpp index b0be6b719eb86162e593d510d69191bb757df665..dc66b46f277f69472bb120a53010bfa9edfa91ca 100644 --- a/sflphone-common/src/audio/audiortp/ZrtpSessionCallback.cpp +++ b/sflphone-common/src/audio/audiortp/ZrtpSessionCallback.cpp @@ -44,18 +44,16 @@ using namespace ost; using namespace std; -namespace sfl -{ +namespace sfl { ZrtpSessionCallback::ZrtpSessionCallback (SIPCall *sipcall) : - _sipcall (sipcall) -{ + _sipcall (sipcall) { if (_mapInitialized) { return; } - _info("Zrtp: Initialize callbacks"); + _info ("Zrtp: Initialize callbacks"); /** * Information Map @@ -123,38 +121,33 @@ ZrtpSessionCallback::ZrtpSessionCallback (SIPCall *sipcall) : } void -ZrtpSessionCallback::secureOn (std::string cipher) -{ +ZrtpSessionCallback::secureOn (std::string cipher) { _debug ("Zrtp: Secure mode is on with cipher %s", cipher.c_str()); DBusManager::instance().getCallManager()->secureZrtpOn (_sipcall->getCallId(), cipher); } void -ZrtpSessionCallback::secureOff (void) -{ +ZrtpSessionCallback::secureOff (void) { _debug ("Zrtp: Secure mode is off"); DBusManager::instance().getCallManager()->secureZrtpOff (_sipcall->getCallId()); } void -ZrtpSessionCallback::showSAS (std::string sas, bool verified) -{ +ZrtpSessionCallback::showSAS (std::string sas, bool verified) { _debug ("Zrtp: SAS is: %s", sas.c_str()); DBusManager::instance().getCallManager()->showSAS (_sipcall->getCallId(), sas, verified); } void -ZrtpSessionCallback::zrtpNotSuppOther() -{ +ZrtpSessionCallback::zrtpNotSuppOther() { _debug ("Zrtp: Callee does not support ZRTP"); DBusManager::instance().getCallManager()->zrtpNotSuppOther (_sipcall->getCallId()); } void -ZrtpSessionCallback::showMessage (GnuZrtpCodes::MessageSeverity sev, int32_t subCode) -{ +ZrtpSessionCallback::showMessage (GnuZrtpCodes::MessageSeverity sev, int32_t subCode) { string* msg; if (sev == Info) { @@ -197,8 +190,7 @@ ZrtpSessionCallback::showMessage (GnuZrtpCodes::MessageSeverity sev, int32_t sub } void -ZrtpSessionCallback::zrtpNegotiationFailed (MessageSeverity severity, int subCode) -{ +ZrtpSessionCallback::zrtpNegotiationFailed (MessageSeverity severity, int subCode) { string* msg; if (severity == ZrtpError) { @@ -223,8 +215,7 @@ ZrtpSessionCallback::zrtpNegotiationFailed (MessageSeverity severity, int subCod } void -ZrtpSessionCallback::confirmGoClear() -{ +ZrtpSessionCallback::confirmGoClear() { _debug ("Zrtp: Received go clear message. Until confirmation, ZRTP won't send any data"); DBusManager::instance().getCallManager()->zrtpNotSuppOther (_sipcall->getCallId()); } diff --git a/sflphone-common/src/audio/codecs/alaw.cpp b/sflphone-common/src/audio/codecs/alaw.cpp index 4c083abce20d08f48c12e359770d2c4947fc371f..eb2c20b9a7a7c584a94187584e8f3b2333490627 100644 --- a/sflphone-common/src/audio/codecs/alaw.cpp +++ b/sflphone-common/src/audio/codecs/alaw.cpp @@ -32,8 +32,7 @@ #include "../common.h" #include "audiocodec.h" -class Alaw : public AudioCodec -{ +class Alaw : public AudioCodec { public: // 8 PCMA A 8000 1 [RFC3551] @@ -134,13 +133,11 @@ class Alaw : public AudioCodec }; // the class factories -extern "C" AudioCodec* create() -{ +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 b3e31012bcf6bc1d16aaf1ddc4ef2ad04309c008..fd1606d14bf1d28e404edbe39e33157409e213a5 100644 --- a/sflphone-common/src/audio/codecs/celtcodec.cpp +++ b/sflphone-common/src/audio/codecs/celtcodec.cpp @@ -33,8 +33,7 @@ #include <celt/celt.h> -class Celt : public AudioCodec -{ +class Celt : public AudioCodec { public: Celt (int payload=0) : AudioCodec (payload, "celt") { @@ -58,32 +57,32 @@ class Celt : public AudioCodec _mode = celt_mode_create (_clockRate, _frameSize, &error); - if(error != CELT_OK) { - switch(error) { - case CELT_BAD_ARG: - printf("Celt: Error: An (or more) invalid argument (e.g. out of range)\n"); - break; - case CELT_INVALID_MODE: - printf("Celt: Error: The mode struct passed is invalid\n"); - break; - case CELT_INTERNAL_ERROR: - printf("Celt: Error: An internal error was detected\n"); - break; - case CELT_CORRUPTED_DATA: - printf("Celt: Error: The data passed (e.g. compressed data to decoder) is corrupted\n"); - break; - case CELT_UNIMPLEMENTED: - printf("Celt: Error: Invalid/unsupported request numbe\n"); - break; - case CELT_INVALID_STATE: - printf("Celt: Error: An encoder or decoder structure is invalid or already freed\n"); - break; - case CELT_ALLOC_FAIL: - printf("Celt: Error: Memory allocation has failed\n"); - break; - default: - printf("Celt: Error"); - } + if (error != CELT_OK) { + switch (error) { + case CELT_BAD_ARG: + printf ("Celt: Error: An (or more) invalid argument (e.g. out of range)\n"); + break; + case CELT_INVALID_MODE: + printf ("Celt: Error: The mode struct passed is invalid\n"); + break; + case CELT_INTERNAL_ERROR: + printf ("Celt: Error: An internal error was detected\n"); + break; + case CELT_CORRUPTED_DATA: + printf ("Celt: Error: The data passed (e.g. compressed data to decoder) is corrupted\n"); + break; + case CELT_UNIMPLEMENTED: + printf ("Celt: Error: Invalid/unsupported request numbe\n"); + break; + case CELT_INVALID_STATE: + printf ("Celt: Error: An encoder or decoder structure is invalid or already freed\n"); + break; + case CELT_ALLOC_FAIL: + printf ("Celt: Error: Memory allocation has failed\n"); + break; + default: + printf ("Celt: Error"); + } } @@ -105,10 +104,10 @@ class Celt : public AudioCodec _dec = celt_decoder_create (_mode, _channel, &error); celt_encoder_ctl (_enc, CELT_SET_COMPLEXITY (2)); - celt_decoder_ctl(_dec, CELT_SET_COMPLEXITY (2)); + celt_decoder_ctl (_dec, CELT_SET_COMPLEXITY (2)); - celt_encoder_ctl (_enc, CELT_SET_PREDICTION(2)); - celt_decoder_ctl(_dec, CELT_SET_PREDICTION(2)); + celt_encoder_ctl (_enc, CELT_SET_PREDICTION (2)); + celt_decoder_ctl (_dec, CELT_SET_PREDICTION (2)); } @@ -121,7 +120,7 @@ class Celt : public AudioCodec celt_encoder_destroy (_enc); celt_decoder_destroy (_dec); - celt_mode_destroy(_mode); + celt_mode_destroy (_mode); } virtual int codecDecode (short *dst, unsigned char *src, unsigned int size) { @@ -150,12 +149,10 @@ class Celt : public AudioCodec }; // the class factories -extern "C" AudioCodec* create() -{ +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/codecDescriptor.cpp b/sflphone-common/src/audio/codecs/codecDescriptor.cpp index 268a6010d780dac542d7e3ceaa63e78759b6d994..3bd4b715a534a1fb4a35898d4894e8646a15f676 100644 --- a/sflphone-common/src/audio/codecs/codecDescriptor.cpp +++ b/sflphone-common/src/audio/codecs/codecDescriptor.cpp @@ -36,19 +36,16 @@ #include "codecDescriptor.h" -CodecDescriptor::CodecDescriptor() : _CodecsMap(), _defaultCodecOrder(), _Cache(), _nbCodecs(), _CodecInMemory() -{ +CodecDescriptor::CodecDescriptor() : _CodecsMap(), _defaultCodecOrder(), _Cache(), _nbCodecs(), _CodecInMemory() { } -CodecDescriptor::~CodecDescriptor() -{ +CodecDescriptor::~CodecDescriptor() { } void -CodecDescriptor::deleteHandlePointer (void) -{ - _debug("CodecDesccriptor: Delete codec handle pointers"); +CodecDescriptor::deleteHandlePointer (void) { + _debug ("CodecDesccriptor: Delete codec handle pointers"); for (int i = 0 ; (unsigned int) i < _CodecInMemory.size() ; i++) { unloadCodec (_CodecInMemory[i]); @@ -58,8 +55,7 @@ CodecDescriptor::deleteHandlePointer (void) } void -CodecDescriptor::init() -{ +CodecDescriptor::init() { std::vector<AudioCodec*> CodecDynamicList = scanCodecDirectory(); _nbCodecs = CodecDynamicList.size(); @@ -88,8 +84,7 @@ void CodecDescriptor::setDefaultOrder() { } std::string -CodecDescriptor::getCodecName (AudioCodecType payload) -{ +CodecDescriptor::getCodecName (AudioCodecType payload) { std::string resNull = ""; CodecsMap::iterator iter = _CodecsMap.find (payload); @@ -101,8 +96,7 @@ CodecDescriptor::getCodecName (AudioCodecType payload) } AudioCodec* -CodecDescriptor::getCodec (AudioCodecType payload) -{ +CodecDescriptor::getCodec (AudioCodecType payload) { CodecsMap::iterator iter = _CodecsMap.find (payload); if (iter!=_CodecsMap.end()) { @@ -262,6 +256,7 @@ AudioCodec* CodecDescriptor::instantiateCodec (AudioCodecType payload) { return a; } + iter++; } @@ -302,6 +297,7 @@ bool CodecDescriptor::seemsValid (std::string lib) { #ifdef HAVE_SPEEX_CODEC // Nothing special #else + if (lib.substr (begin.length() , lib.length() - begin.length() - end.length()) == SPEEX_STRING_DESCRIPTION) return false; @@ -310,6 +306,7 @@ bool CodecDescriptor::seemsValid (std::string lib) { #ifdef HAVE_GSM_CODEC // Nothing special #else + if (lib.substr (begin.length() , lib.length() - begin.length() - end.length()) == GSM_STRING_DESCRIPTION) return false; @@ -318,6 +315,7 @@ bool CodecDescriptor::seemsValid (std::string lib) { #ifdef BUILD_ILBC // Nothing special #else + if (lib.substr (begin.length() , lib.length() - begin.length() - end.length()) == ILBC_STRING_DESCRIPTION) return false; @@ -333,8 +331,7 @@ bool CodecDescriptor::seemsValid (std::string lib) { } bool -CodecDescriptor::alreadyInCache (std::string lib) -{ +CodecDescriptor::alreadyInCache (std::string lib) { int i; for (i = 0 ; (unsigned int) i < _Cache.size() ; i++) { @@ -362,30 +359,30 @@ bool CodecDescriptor::isCodecLoaded (int payload) { std::vector <std::string> CodecDescriptor::getCodecSpecifications (const int32_t& payload) { - _debug ("CodecDescriptor: Gathering codec specifications for payload %i", payload); + _debug ("CodecDescriptor: Gathering codec specifications for payload %i", payload); - std::vector<std::string> v; + std::vector<std::string> v; std::stringstream ss; - // Add the name of the codec + // Add the name of the codec v.push_back (getCodecName ( (AudioCodecType) payload)); - // Add the sample rate + // Add the sample rate ss << getSampleRate ( (AudioCodecType) payload); v.push_back ( (ss.str()).data()); ss.str (""); - // Add the bit rate + // Add the bit rate ss << getBitRate ( (AudioCodecType) payload); v.push_back ( (ss.str()).data()); ss.str (""); - // Add the bandwidth information + // Add the bandwidth information ss << getBandwidthPerCall ( (AudioCodecType) payload); v.push_back ( (ss.str()).data()); ss.str (""); - return v; + return v; } diff --git a/sflphone-common/src/audio/codecs/g722.cpp b/sflphone-common/src/audio/codecs/g722.cpp index bde8cabae927a90f65d8949ece847930e73ec0b0..3fe5e786bba9a883cfe7657fceed7dd7ec36e9af 100644 --- a/sflphone-common/src/audio/codecs/g722.cpp +++ b/sflphone-common/src/audio/codecs/g722.cpp @@ -43,8 +43,7 @@ #define FALSE 0 -class G722 : public AudioCodec -{ +class G722 : public AudioCodec { public: @@ -799,13 +798,11 @@ class G722 : public AudioCodec }; // the class factories -extern "C" AudioCodec* create() -{ +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 fef1d7a2c42943fbee8115ef0624ca9b609bae21..8afbc648ee90b7b686594c84c71a8d90de94a94b 100644 --- a/sflphone-common/src/audio/codecs/gsmcodec.cpp +++ b/sflphone-common/src/audio/codecs/gsmcodec.cpp @@ -31,8 +31,7 @@ #include "audiocodec.h" -extern "C" -{ +extern "C" { #include <gsm/gsm.h> } @@ -40,8 +39,7 @@ extern "C" * GSM audio codec C++ class (over gsm/gsm.h) */ -class Gsm : public AudioCodec -{ +class Gsm : public AudioCodec { public: // _payload should be 3 @@ -91,12 +89,10 @@ class Gsm : public AudioCodec gsm _encode_gsmhandle; }; -extern "C" AudioCodec* create() -{ +extern "C" AudioCodec* create() { return new Gsm (3); } -extern "C" void destroy (AudioCodec* 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 fdad5f29dc9facfc789d0c67b97967b220a90d4d..5af0cbef598788f740329f3659673030a2d2b1a4 100644 --- a/sflphone-common/src/audio/codecs/speexcodec_nb.cpp +++ b/sflphone-common/src/audio/codecs/speexcodec_nb.cpp @@ -34,8 +34,7 @@ #include <speex/speex.h> #include <speex/speex_preprocess.h> -class Speex : public AudioCodec -{ +class Speex : public AudioCodec { public: Speex (int payload=0) @@ -45,7 +44,7 @@ class Speex : public AudioCodec _speex_enc_bits(), _speex_dec_state(), _speex_enc_state(), - _speex_frame_size() { + _speex_frame_size() { _clockRate = 8000; _frameSize = 160; // samples, 20 ms at 8kHz _channel = 1; @@ -123,13 +122,11 @@ class Speex : public AudioCodec }; // the class factories -extern "C" AudioCodec* create() -{ +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 47494fb99c79c9427052e1f9bd86b6bf06bf18a9..28e988e3faea5a09cdfd7de9ebb1ffa6f72c2eba 100644 --- a/sflphone-common/src/audio/codecs/speexcodec_ub.cpp +++ b/sflphone-common/src/audio/codecs/speexcodec_ub.cpp @@ -33,8 +33,7 @@ #include <cstdio> #include <speex/speex.h> -class Speex : public AudioCodec -{ +class Speex : public AudioCodec { public: Speex (int payload=0) @@ -44,7 +43,7 @@ class Speex : public AudioCodec _speex_enc_bits(), _speex_dec_state(), _speex_enc_state(), - _speex_frame_size() { + _speex_frame_size() { _clockRate = 32000; _frameSize = 640; // 20 ms at 32 kHz _channel = 1; @@ -125,13 +124,11 @@ class Speex : public AudioCodec }; // the class factories -extern "C" AudioCodec* create() -{ +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 d9fda3e3af502b0dfcdc6d24c864b46942b1e64b..6086777c7258f7d7f273d2b9c024e6f9d578a019 100644 --- a/sflphone-common/src/audio/codecs/speexcodec_wb.cpp +++ b/sflphone-common/src/audio/codecs/speexcodec_wb.cpp @@ -33,8 +33,7 @@ #include <cstdio> #include <speex/speex.h> -class Speex : public AudioCodec -{ +class Speex : public AudioCodec { public: Speex (int payload=0) @@ -44,7 +43,7 @@ class Speex : public AudioCodec _speex_enc_bits(), _speex_dec_state(), _speex_enc_state(), - _speex_frame_size() { + _speex_frame_size() { _clockRate = 16000; _frameSize = 320; // 20 ms at 16 kHz _channel = 1; @@ -125,13 +124,11 @@ class Speex : public AudioCodec }; // the class factories -extern "C" AudioCodec* create() -{ +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 37d5fd2df8b88f06089937e546fae2a4b9418ac0..fe0c6f2e7febe1b420621195ca15fc6459cafd07 100644 --- a/sflphone-common/src/audio/codecs/ulaw.cpp +++ b/sflphone-common/src/audio/codecs/ulaw.cpp @@ -34,8 +34,7 @@ #include "../common.h" #include "audiocodec.h" -class Ulaw : public AudioCodec -{ +class Ulaw : public AudioCodec { public: // 0 PCMU A 8000 1 [RFC3551] @@ -127,12 +126,10 @@ class Ulaw : public AudioCodec }; // the class factories -extern "C" AudioCodec* create() -{ +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/dcblocker.cpp b/sflphone-common/src/audio/dcblocker.cpp index b1a18eb1a2e6ddcf97568825cd057df55a8b42fc..a32f2467e3354fee3a3bd08af05dd14ef1dcf07e 100644 --- a/sflphone-common/src/audio/dcblocker.cpp +++ b/sflphone-common/src/audio/dcblocker.cpp @@ -30,27 +30,28 @@ #include "dcblocker.h" -DcBlocker::DcBlocker() : _y(0), _x(0), _xm1(0), _ym1(0) {} +DcBlocker::DcBlocker() : _y (0), _x (0), _xm1 (0), _ym1 (0) {} DcBlocker::~DcBlocker() {} -void DcBlocker::reset() -{ - _y = 0; - _x = 0; - _xm1 = 0; - _ym1 = 0; +void DcBlocker::reset() { + _y = 0; + _x = 0; + _xm1 = 0; + _ym1 = 0; } -void DcBlocker::putData(SFLDataFormat *inputData, int nbBytes) {} +void DcBlocker::putData (SFLDataFormat *inputData, int nbBytes) {} -int DcBlocker::getData(SFLDataFormat *outputData) { return 0; } +int DcBlocker::getData (SFLDataFormat *outputData) { + return 0; +} -void DcBlocker::process (SFLDataFormat *data, int nbBytes) -{ +void DcBlocker::process (SFLDataFormat *data, int nbBytes) { // y(n) = x(n) - x(n-1) + R y(n-1) , R = 0.9999 - int nbSamples = nbBytes / sizeof(SFLDataFormat); + int nbSamples = nbBytes / sizeof (SFLDataFormat); + for (int i = 0; i < nbSamples; i++) { _x = data[i]; @@ -63,9 +64,10 @@ void DcBlocker::process (SFLDataFormat *data, int nbBytes) } } -int DcBlocker::process(SFLDataFormat *inputData, SFLDataFormat *outputData, int nbBytes) { +int DcBlocker::process (SFLDataFormat *inputData, SFLDataFormat *outputData, int nbBytes) { + + int nbSamples = nbBytes / sizeof (SFLDataFormat); - int nbSamples = nbBytes / sizeof(SFLDataFormat); for (int i = 0; i < nbSamples; i++) { _x = inputData[i]; @@ -77,8 +79,8 @@ int DcBlocker::process(SFLDataFormat *inputData, SFLDataFormat *outputData, int outputData[i] = _y; } - return 0; + return 0; } -void DcBlocker::process(SFLDataFormat *micData, SFLDataFormat *spkrData, SFLDataFormat *outputData, int nbBytes) {} +void DcBlocker::process (SFLDataFormat *micData, SFLDataFormat *spkrData, SFLDataFormat *outputData, int nbBytes) {} diff --git a/sflphone-common/src/audio/delaydetection.cpp b/sflphone-common/src/audio/delaydetection.cpp index 5c6ab4d742644ed469eb6ab426030680173ab82b..a5f9dd264c86ef283c9b473d2854cbbc22fabae9 100644 --- a/sflphone-common/src/audio/delaydetection.cpp +++ b/sflphone-common/src/audio/delaydetection.cpp @@ -38,349 +38,356 @@ // decimation filter coefficient float decimationCoefs[] = {-0.09870257, 0.07473655, 0.05616626, 0.04448337, 0.03630817, 0.02944626, - 0.02244098, 0.01463477, 0.00610982, -0.00266367, -0.01120109, -0.01873722, - -0.02373243, -0.02602213, -0.02437806, -0.01869834, -0.00875287, 0.00500204, - 0.02183252, 0.04065763, 0.06015944, 0.0788299, 0.09518543, 0.10799179, - 0.1160644, 0.12889288, 0.1160644, 0.10799179, 0.09518543, 0.0788299, - 0.06015944, 0.04065763, 0.02183252, 0.00500204, -0.00875287, -0.01869834, - -0.02437806, -0.02602213, -0.02373243, -0.01873722, -0.01120109, -0.00266367, - 0.00610982, 0.01463477, 0.02244098, 0.02944626, 0.03630817, 0.04448337, - 0.05616626, 0.07473655, -0.09870257}; -std::vector<double> ird(decimationCoefs, decimationCoefs + sizeof(decimationCoefs)/sizeof(float)); + 0.02244098, 0.01463477, 0.00610982, -0.00266367, -0.01120109, -0.01873722, + -0.02373243, -0.02602213, -0.02437806, -0.01869834, -0.00875287, 0.00500204, + 0.02183252, 0.04065763, 0.06015944, 0.0788299, 0.09518543, 0.10799179, + 0.1160644, 0.12889288, 0.1160644, 0.10799179, 0.09518543, 0.0788299, + 0.06015944, 0.04065763, 0.02183252, 0.00500204, -0.00875287, -0.01869834, + -0.02437806, -0.02602213, -0.02373243, -0.01873722, -0.01120109, -0.00266367, + 0.00610982, 0.01463477, 0.02244098, 0.02944626, 0.03630817, 0.04448337, + 0.05616626, 0.07473655, -0.09870257 + }; +std::vector<double> ird (decimationCoefs, decimationCoefs + sizeof (decimationCoefs) /sizeof (float)); // decimation filter coefficient float bandpassCoefs[] = {0.06278034, -0.0758545, -0.02274943, -0.0084497, 0.0702427, 0.05986113, - 0.06436469, -0.02412049, -0.03433526, -0.07568665, -0.03214543, -0.07236507, - -0.06979052, -0.12446371, -0.05530828, 0.00947243, 0.15294699, 0.17735563, - 0.15294699, 0.00947243, -0.05530828, -0.12446371, -0.06979052, -0.07236507, - -0.03214543, -0.07568665, -0.03433526, -0.02412049, 0.06436469, 0.05986113, - 0.0702427, -0.0084497, -0.02274943, -0.0758545, 0.06278034}; -std::vector<double> irb(bandpassCoefs, bandpassCoefs + sizeof(bandpassCoefs)/sizeof(float)); - - -FirFilter::FirFilter(std::vector<double> ir) : _length(ir.size()), - _impulseResponse(ir), - _count(0) -{ - memset(_taps, 0, sizeof(double)*MAXFILTERSIZE); + 0.06436469, -0.02412049, -0.03433526, -0.07568665, -0.03214543, -0.07236507, + -0.06979052, -0.12446371, -0.05530828, 0.00947243, 0.15294699, 0.17735563, + 0.15294699, 0.00947243, -0.05530828, -0.12446371, -0.06979052, -0.07236507, + -0.03214543, -0.07568665, -0.03433526, -0.02412049, 0.06436469, 0.05986113, + 0.0702427, -0.0084497, -0.02274943, -0.0758545, 0.06278034 + }; +std::vector<double> irb (bandpassCoefs, bandpassCoefs + sizeof (bandpassCoefs) /sizeof (float)); + + +FirFilter::FirFilter (std::vector<double> ir) : _length (ir.size()), + _impulseResponse (ir), + _count (0) { + memset (_taps, 0, sizeof (double) *MAXFILTERSIZE); } FirFilter::~FirFilter() {} -float FirFilter::getOutputSample(float inputSample) -{ - _taps[_count] = inputSample; - double result = 0.0; - int index = _count; - for(int i = 0; i < _length; i++) { - result = result + _impulseResponse[i] * _taps[index--]; - if(index < 0) - index = _length-1; - } - _count++; - if(_count >= _length) - _count = 0; - - return result; +float FirFilter::getOutputSample (float inputSample) { + _taps[_count] = inputSample; + double result = 0.0; + int index = _count; + + for (int i = 0; i < _length; i++) { + result = result + _impulseResponse[i] * _taps[index--]; + + if (index < 0) + index = _length-1; + } + + _count++; + + if (_count >= _length) + _count = 0; + + return result; } -void FirFilter::reset(void) -{ - for(int i = 0; i < _length; i++) { - _impulseResponse[i] = 0.0; - } +void FirFilter::reset (void) { + for (int i = 0; i < _length; i++) { + _impulseResponse[i] = 0.0; + } } -DelayDetection::DelayDetection() : _internalState(WaitForSpeaker), _decimationFilter(ird), _bandpassFilter(irb), _segmentSize(DELAY_BUFF_SIZE), _downsamplingFactor(8) -{ +DelayDetection::DelayDetection() : _internalState (WaitForSpeaker), _decimationFilter (ird), _bandpassFilter (irb), _segmentSize (DELAY_BUFF_SIZE), _downsamplingFactor (8) { _micDownSize = WINDOW_SIZE / _downsamplingFactor; _spkrDownSize = DELAY_BUFF_SIZE / _downsamplingFactor; - memset(_spkrReference, 0, sizeof(float)*WINDOW_SIZE*2); - memset(_capturedData, 0, sizeof(float)*DELAY_BUFF_SIZE*2); - memset(_spkrReferenceDown, 0, sizeof(float)*WINDOW_SIZE*2); - memset(_captureDataDown, 0, sizeof(float)*DELAY_BUFF_SIZE*2); - memset(_spkrReferenceFilter, 0, sizeof(float)*WINDOW_SIZE*2); - memset(_captureDataFilter, 0, sizeof(float)*DELAY_BUFF_SIZE*2); - memset(_correlationResult, 0, sizeof(float)*DELAY_BUFF_SIZE*2); + memset (_spkrReference, 0, sizeof (float) *WINDOW_SIZE*2); + memset (_capturedData, 0, sizeof (float) *DELAY_BUFF_SIZE*2); + memset (_spkrReferenceDown, 0, sizeof (float) *WINDOW_SIZE*2); + memset (_captureDataDown, 0, sizeof (float) *DELAY_BUFF_SIZE*2); + memset (_spkrReferenceFilter, 0, sizeof (float) *WINDOW_SIZE*2); + memset (_captureDataFilter, 0, sizeof (float) *DELAY_BUFF_SIZE*2); + memset (_correlationResult, 0, sizeof (float) *DELAY_BUFF_SIZE*2); } -DelayDetection::~DelayDetection(){} +DelayDetection::~DelayDetection() {} -void DelayDetection::reset() -{ +void DelayDetection::reset() { _nbMicSampleStored = 0; _nbSpkrSampleStored = 0; _decimationFilter.reset(); _bandpassFilter.reset(); - memset(_spkrReference, 0, sizeof(float)*WINDOW_SIZE*2); - memset(_capturedData, 0, sizeof(float)*DELAY_BUFF_SIZE*2); - memset(_spkrReferenceDown, 0, sizeof(float)*WINDOW_SIZE*2); - memset(_captureDataDown, 0, sizeof(float)*DELAY_BUFF_SIZE*2); - memset(_spkrReferenceFilter, 0, sizeof(float)*WINDOW_SIZE*2); - memset(_captureDataFilter, 0, sizeof(float)*DELAY_BUFF_SIZE*2); - memset(_correlationResult, 0, sizeof(float)*DELAY_BUFF_SIZE*2); - + memset (_spkrReference, 0, sizeof (float) *WINDOW_SIZE*2); + memset (_capturedData, 0, sizeof (float) *DELAY_BUFF_SIZE*2); + memset (_spkrReferenceDown, 0, sizeof (float) *WINDOW_SIZE*2); + memset (_captureDataDown, 0, sizeof (float) *DELAY_BUFF_SIZE*2); + memset (_spkrReferenceFilter, 0, sizeof (float) *WINDOW_SIZE*2); + memset (_captureDataFilter, 0, sizeof (float) *DELAY_BUFF_SIZE*2); + memset (_correlationResult, 0, sizeof (float) *DELAY_BUFF_SIZE*2); + _internalState = WaitForSpeaker; } -void DelayDetection::putData(SFLDataFormat *inputData, int nbBytes) -{ +void DelayDetection::putData (SFLDataFormat *inputData, int nbBytes) { - // Machine may already got a spkr and is waiting for mic or computing correlation - if(_nbSpkrSampleStored == WINDOW_SIZE) - return; + // Machine may already got a spkr and is waiting for mic or computing correlation + if (_nbSpkrSampleStored == WINDOW_SIZE) + return; - int nbSamples = nbBytes/sizeof(SFLDataFormat); + int nbSamples = nbBytes/sizeof (SFLDataFormat); - if((_nbSpkrSampleStored + nbSamples) > WINDOW_SIZE) - nbSamples = WINDOW_SIZE - _nbSpkrSampleStored; - + if ( (_nbSpkrSampleStored + nbSamples) > WINDOW_SIZE) + nbSamples = WINDOW_SIZE - _nbSpkrSampleStored; - if (nbSamples) { - float tmp[nbSamples]; - float down[nbSamples]; + if (nbSamples) { + + float tmp[nbSamples]; + float down[nbSamples]; - convertInt16ToFloat32(inputData, tmp, nbSamples); - memcpy(_spkrReference+_nbSpkrSampleStored, tmp, nbSamples*sizeof(float)); + convertInt16ToFloat32 (inputData, tmp, nbSamples); + memcpy (_spkrReference+_nbSpkrSampleStored, tmp, nbSamples*sizeof (float)); - downsampleData(tmp, down, nbSamples, _downsamplingFactor); - bandpassFilter(down, nbSamples/_downsamplingFactor); - memcpy(_spkrReferenceDown+(_nbSpkrSampleStored/_downsamplingFactor), down, (nbSamples/_downsamplingFactor)*sizeof(float)); - - _nbSpkrSampleStored += nbSamples; + downsampleData (tmp, down, nbSamples, _downsamplingFactor); + bandpassFilter (down, nbSamples/_downsamplingFactor); + memcpy (_spkrReferenceDown+ (_nbSpkrSampleStored/_downsamplingFactor), down, (nbSamples/_downsamplingFactor) *sizeof (float)); - } + _nbSpkrSampleStored += nbSamples; + + } - // Update the state - _internalState = WaitForMic; + // Update the state + _internalState = WaitForMic; } -int DelayDetection::getData(SFLDataFormat *outputData) { return 0; } +int DelayDetection::getData (SFLDataFormat *outputData) { + return 0; +} -void DelayDetection::process(SFLDataFormat *inputData, int nbBytes) { +void DelayDetection::process (SFLDataFormat *inputData, int nbBytes) { - if(_internalState != WaitForMic) - return; + if (_internalState != WaitForMic) + return; - int nbSamples = nbBytes/sizeof(SFLDataFormat); + int nbSamples = nbBytes/sizeof (SFLDataFormat); - if((_nbMicSampleStored + nbSamples) > DELAY_BUFF_SIZE) - nbSamples = DELAY_BUFF_SIZE - _nbMicSampleStored; + if ( (_nbMicSampleStored + nbSamples) > DELAY_BUFF_SIZE) + nbSamples = DELAY_BUFF_SIZE - _nbMicSampleStored; - if(nbSamples) { - float tmp[nbSamples]; - float down[nbSamples]; + if (nbSamples) { + float tmp[nbSamples]; + float down[nbSamples]; - convertInt16ToFloat32(inputData, tmp, nbSamples); - memcpy(_capturedData+_nbMicSampleStored, tmp, nbSamples); + convertInt16ToFloat32 (inputData, tmp, nbSamples); + memcpy (_capturedData+_nbMicSampleStored, tmp, nbSamples); - downsampleData(tmp, down, nbSamples, _downsamplingFactor); + downsampleData (tmp, down, nbSamples, _downsamplingFactor); - /* - for(int i = 0; i < 10; i++) - _debug("up: %.10f", tmp[i]); + /* + for(int i = 0; i < 10; i++) + _debug("up: %.10f", tmp[i]); - for(int i = 0; i < 10; i++) - _debug("down: %.10f", down[i]); + for(int i = 0; i < 10; i++) + _debug("down: %.10f", down[i]); - bandpassFilter(down, nbSamples/_downsamplingFactor); + bandpassFilter(down, nbSamples/_downsamplingFactor); - for(int i = 0; i < 10; i++) - _debug("band: %.10f", down[i]); - */ + for(int i = 0; i < 10; i++) + _debug("band: %.10f", down[i]); + */ - memcpy(_captureDataDown+(_nbMicSampleStored/_downsamplingFactor), down, (nbSamples/_downsamplingFactor)*sizeof(float)); + memcpy (_captureDataDown+ (_nbMicSampleStored/_downsamplingFactor), down, (nbSamples/_downsamplingFactor) *sizeof (float)); - _nbMicSampleStored += nbSamples; + _nbMicSampleStored += nbSamples; - } + } - if(_nbMicSampleStored == DELAY_BUFF_SIZE) - _internalState = ComputeCorrelation; - else - return; + if (_nbMicSampleStored == DELAY_BUFF_SIZE) + _internalState = ComputeCorrelation; + else + return; - /* - for(int i = 0; i < 10; i++) - _debug("spkrRef: %.10f", _spkrReferenceDown[i]); + /* + for(int i = 0; i < 10; i++) + _debug("spkrRef: %.10f", _spkrReferenceDown[i]); - for(int i = 0; i < 10; i++) - _debug("micSeg: %.10f", _captureDataDown[i]); - */ + for(int i = 0; i < 10; i++) + _debug("micSeg: %.10f", _captureDataDown[i]); + */ - _debug("_spkrDownSize: %d, _micDownSize: %d", _spkrDownSize, _micDownSize); - crossCorrelate(_spkrReferenceDown, _captureDataDown, _correlationResult, _micDownSize, _spkrDownSize); + _debug ("_spkrDownSize: %d, _micDownSize: %d", _spkrDownSize, _micDownSize); + crossCorrelate (_spkrReferenceDown, _captureDataDown, _correlationResult, _micDownSize, _spkrDownSize); - int maxIndex = getMaxIndex(_correlationResult, _spkrDownSize); + int maxIndex = getMaxIndex (_correlationResult, _spkrDownSize); - _debug("MaxIndex: %d", maxIndex); + _debug ("MaxIndex: %d", maxIndex); - // reset(); + // reset(); } -int DelayDetection::process(SFLDataFormat *intputData, SFLDataFormat *outputData, int nbBytes) { return 0; } +int DelayDetection::process (SFLDataFormat *intputData, SFLDataFormat *outputData, int nbBytes) { + return 0; +} -void DelayDetection::process(SFLDataFormat *micData, SFLDataFormat *spkrData, SFLDataFormat *outputData, int nbBytes) {} +void DelayDetection::process (SFLDataFormat *micData, SFLDataFormat *spkrData, SFLDataFormat *outputData, int nbBytes) {} -void DelayDetection::crossCorrelate(float *ref, float *seg, float *res, int refSize, int segSize) { +void DelayDetection::crossCorrelate (float *ref, float *seg, float *res, int refSize, int segSize) { - _debug("CrossCorrelate"); + _debug ("CrossCorrelate"); - int counter = 0; + int counter = 0; - // Output has same size as the - int rsize = refSize; - int ssize = segSize; - int tmpsize = segSize-refSize+1; + // Output has same size as the + int rsize = refSize; + int ssize = segSize; + int tmpsize = segSize-refSize+1; - /* - for(int i = 0; i < 32; i++) - _debug("ref: %.10f", ref[i]); + /* + for(int i = 0; i < 32; i++) + _debug("ref: %.10f", ref[i]); - for(int i = 0; i < 150; i++) - _debug("seg: %.10f", seg[i]); - */ + for(int i = 0; i < 150; i++) + _debug("seg: %.10f", seg[i]); + */ - // perform autocorrelation on reference signal - float acref = correlate(ref, ref, rsize); - // _debug("acref: %f", acref); - - // perform crossrelation on signal - float acseg = 0.0; - float r; - while(--tmpsize) { - --ssize; - acseg = correlate(seg+tmpsize, seg+tmpsize, rsize); - // _debug("acseg: %f", acseg); - res[ssize] = correlate(ref, seg+tmpsize, rsize); - r = sqrt(acref*acseg); + // perform autocorrelation on reference signal + float acref = correlate (ref, ref, rsize); + // _debug("acref: %f", acref); + + // perform crossrelation on signal + float acseg = 0.0; + float r; + + while (--tmpsize) { + --ssize; + acseg = correlate (seg+tmpsize, seg+tmpsize, rsize); + // _debug("acseg: %f", acseg); + res[ssize] = correlate (ref, seg+tmpsize, rsize); + r = sqrt (acref*acseg); + + if (r < 0.0000001) + res[ssize] = 0.0; + else + res[ssize] = res[ssize] / r; + } - if(r < 0.0000001) - res[ssize] = 0.0; - else - res[ssize] = res[ssize] / r; - } - - // perform crosscorrelation on zerro padded region - int i = 0; - while(rsize) { - acseg = correlate(seg, seg, rsize); - // _debug("acseg: %f", acseg); - res[ssize-1] = correlate(ref+i, seg, rsize); - r = sqrt(acref*acseg); - - if(r < 0.0001) - res[ssize-1] = 0.0; - else - res[ssize-1] = res[ssize-1] / r; - - --rsize; - --ssize; - ++i; - } + // perform crosscorrelation on zerro padded region + int i = 0; + + while (rsize) { + acseg = correlate (seg, seg, rsize); + // _debug("acseg: %f", acseg); + res[ssize-1] = correlate (ref+i, seg, rsize); + r = sqrt (acref*acseg); + + if (r < 0.0001) + res[ssize-1] = 0.0; + else + res[ssize-1] = res[ssize-1] / r; + + --rsize; + --ssize; + ++i; + } } -double DelayDetection::correlate(float *sig1, float *sig2, short size) { +double DelayDetection::correlate (float *sig1, float *sig2, short size) { + + short s = size; - short s = size; + double ac = 0.0; - double ac = 0.0; - while(s--) - ac += sig1[s]*sig2[s]; + while (s--) + ac += sig1[s]*sig2[s]; - return ac; + return ac; } -void DelayDetection::convertInt16ToFloat32(SFLDataFormat *input, float *output, int nbSamples) { +void DelayDetection::convertInt16ToFloat32 (SFLDataFormat *input, float *output, int nbSamples) { // factor is 1/(2^15), used to rescale the short int range to the // [-1.0 - 1.0] float range. #define S2F_FACTOR .000030517578125f; - int len = nbSamples; + int len = nbSamples; - while(len) { - len--; - output[len] = (float)input[len] * S2F_FACTOR; - } + while (len) { + len--; + output[len] = (float) input[len] * S2F_FACTOR; + } } -void DelayDetection::downsampleData(float *input, float *output, int nbSamples, int factor) { - - /* - float tmp[nbSamples]; - - for(int i = 0; i < nbSamples; i++) { - tmp[i] = _decimationFilter.getOutputSample(input[i]); - } - - int j; - for(j=_remainingIndex; j<nbSamples; j+=factor) { - output[j] = tmp[j]; - } - _remainingIndex = j - nbSamples; - */ - - /* - double downsampleFactor = (double) samplerate1 / samplerate2; - - int nbSamplesMax = (int) (samplerate1 * getFramesize() / 1000); - */ - - int _src_err; - - SRC_STATE *_src_state = src_new (SRC_LINEAR, 1, &_src_err); - - double downfactor = 1.0 / (double)factor; - - if (downfactor != 1.0) { - SRC_DATA src_data; - src_data.data_in = input; - src_data.data_out = output; - src_data.input_frames = nbSamples; - src_data.output_frames = nbSamples / factor; - src_data.src_ratio = downfactor; - src_data.end_of_input = 0; // More data will come - - //src_short_to_float_array (dataIn, _floatBufferUpMic, nbSamples); - //_debug("downsample %d %f %d" , src_data.output_frames, src_data.src_ratio , nbSamples); - src_process (_src_state, &src_data); - //_debug("downsample %d %f %d" , 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" , src_data.output_frames, src_data.src_ratio , nbSamples); - // src_float_to_short_array (_floatBufferDownMic , dataOut , nbSamples); - } +void DelayDetection::downsampleData (float *input, float *output, int nbSamples, int factor) { + + /* + float tmp[nbSamples]; + + for(int i = 0; i < nbSamples; i++) { + tmp[i] = _decimationFilter.getOutputSample(input[i]); + } + + int j; + for(j=_remainingIndex; j<nbSamples; j+=factor) { + output[j] = tmp[j]; + } + _remainingIndex = j - nbSamples; + */ + + /* + double downsampleFactor = (double) samplerate1 / samplerate2; + + int nbSamplesMax = (int) (samplerate1 * getFramesize() / 1000); + */ + + int _src_err; + + SRC_STATE *_src_state = src_new (SRC_LINEAR, 1, &_src_err); + + double downfactor = 1.0 / (double) factor; + + if (downfactor != 1.0) { + SRC_DATA src_data; + src_data.data_in = input; + src_data.data_out = output; + src_data.input_frames = nbSamples; + src_data.output_frames = nbSamples / factor; + src_data.src_ratio = downfactor; + src_data.end_of_input = 0; // More data will come + + //src_short_to_float_array (dataIn, _floatBufferUpMic, nbSamples); + //_debug("downsample %d %f %d" , src_data.output_frames, src_data.src_ratio , nbSamples); + src_process (_src_state, &src_data); + //_debug("downsample %d %f %d" , 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" , src_data.output_frames, src_data.src_ratio , nbSamples); + // src_float_to_short_array (_floatBufferDownMic , dataOut , nbSamples); + } } -void DelayDetection::bandpassFilter(float *input, int nbSamples) { +void DelayDetection::bandpassFilter (float *input, int nbSamples) { - for(int i = 0; i < nbSamples; i++) { - input[i] = _bandpassFilter.getOutputSample(input[i]); + for (int i = 0; i < nbSamples; i++) { + input[i] = _bandpassFilter.getOutputSample (input[i]); } } -int DelayDetection::getMaxIndex(float *data, int size) { +int DelayDetection::getMaxIndex (float *data, int size) { - float max = 0.0; - int k; + float max = 0.0; + int k; - for(int i = 0; i < size; i++) { - if(data[i] >= max) { - max = data[i]; - k = i; + for (int i = 0; i < size; i++) { + if (data[i] >= max) { + max = data[i]; + k = i; + } } - } - return k; + return k; } diff --git a/sflphone-common/src/audio/echocancel.cpp b/sflphone-common/src/audio/echocancel.cpp index aab1e8f9989fc18c7c79315ef6dd64c76de12018..8a436c33a2e97e880aba96297006db71df3462b6 100644 --- a/sflphone-common/src/audio/echocancel.cpp +++ b/sflphone-common/src/audio/echocancel.cpp @@ -32,574 +32,571 @@ // #include <fstream> -EchoCancel::EchoCancel(int smplRate, int frameLength) : _samplingRate(smplRate), - _frameLength(frameLength), - _smplPerFrame(0), - _smplPerSeg(0), - _nbSegmentPerFrame(0), - _micHistoryLength(0), - _spkrHistoryLength(0), - _alpha(0.01), - _spkrLevelMem(0), - _micLevelMem(0), - _spkrLevel(0), - _micLevel(0), - _spkrHistCnt(0), - _micHistCnt(0), - _amplFactor(0.0), - _lastAmplFactor(0.0), - _amplDelayIndexIn(0), - _amplDelayIndexOut(0), - _adaptDone(false), - _adaptStarted(false), - _adaptCnt(0), - _spkrAdaptCnt(0), - _micAdaptCnt(0), - _spkrAdaptSize(SPKR_ADAPT_SIZE), - _micAdaptSize(MIC_ADAPT_SIZE), - _correlationSize(0), - _processedByte(0), - _echoActive(true), - _noiseActive(true) -{ - _debug("EchoCancel: Instantiate echo canceller"); - - - // micFile = new ofstream("micData", ofstream::binary); - // echoFile = new ofstream("echoData", ofstream::binary); - // spkrFile = new ofstream("spkrData", ofstream::binary); - - micLevelData = new ofstream("micLevelData", ofstream::binary); - spkrLevelData = new ofstream("spkrLevelData", ofstream::binary); - - - _micData = new RingBuffer(50000); - _spkrData = new RingBuffer(50000); - _spkrDataOut = new RingBuffer(50000); - - _micData->createReadPointer(); - _spkrData->createReadPointer(); - _spkrDataOut->createReadPointer(); - - // variable used to sync mic and spkr - _spkrStoped = true; - - _smplPerFrame = (_samplingRate * _frameLength) / MS_PER_SEC; - _smplPerSeg = (_samplingRate * SEGMENT_LENGTH) / MS_PER_SEC; - _micHistoryLength = MIC_LENGTH / SEGMENT_LENGTH; - _spkrHistoryLength = SPKR_LENGTH / SEGMENT_LENGTH; - _nbSegmentPerFrame = _frameLength / SEGMENT_LENGTH; - - _noiseState = speex_preprocess_state_init(_smplPerFrame, _samplingRate); - int i=1; - speex_preprocess_ctl(_noiseState, SPEEX_PREPROCESS_SET_DENOISE, &i); - i=-20; - speex_preprocess_ctl(_noiseState, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &i); - i=0; - speex_preprocess_ctl(_noiseState, SPEEX_PREPROCESS_SET_AGC, &i); - i=8000; - speex_preprocess_ctl(_noiseState, SPEEX_PREPROCESS_SET_AGC_TARGET, &i); - i=16000; - speex_preprocess_ctl(_noiseState, SPEEX_PREPROCESS_SET_AGC_LEVEL, &i); - i=0; - speex_preprocess_ctl(_noiseState, SPEEX_PREPROCESS_SET_DEREVERB, &i); - float f=0.0; - speex_preprocess_ctl(_noiseState, SPEEX_PREPROCESS_SET_DEREVERB_DECAY, &f); - f=0.0; - speex_preprocess_ctl(_noiseState, SPEEX_PREPROCESS_SET_DEREVERB_LEVEL, &f); - i = 0; - speex_preprocess_ctl(_noiseState, SPEEX_PREPROCESS_SET_VAD, &i); - - - memset(_avgSpkrLevelHist, 0, BUFF_SIZE*sizeof(int)); - memset(_avgMicLevelHist, 0, BUFF_SIZE*sizeof(int)); - - memset(_delayLineAmplify, 0, MAX_DELAY_LINE_AMPL*sizeof(float)); - - _amplDelayIndexIn = 0; - _amplDelayIndexOut = 0; - - _correlationSize = _spkrAdaptSize; - +EchoCancel::EchoCancel (int smplRate, int frameLength) : _samplingRate (smplRate), + _frameLength (frameLength), + _smplPerFrame (0), + _smplPerSeg (0), + _nbSegmentPerFrame (0), + _micHistoryLength (0), + _spkrHistoryLength (0), + _alpha (0.01), + _spkrLevelMem (0), + _micLevelMem (0), + _spkrLevel (0), + _micLevel (0), + _spkrHistCnt (0), + _micHistCnt (0), + _amplFactor (0.0), + _lastAmplFactor (0.0), + _amplDelayIndexIn (0), + _amplDelayIndexOut (0), + _adaptDone (false), + _adaptStarted (false), + _adaptCnt (0), + _spkrAdaptCnt (0), + _micAdaptCnt (0), + _spkrAdaptSize (SPKR_ADAPT_SIZE), + _micAdaptSize (MIC_ADAPT_SIZE), + _correlationSize (0), + _processedByte (0), + _echoActive (true), + _noiseActive (true) { + _debug ("EchoCancel: Instantiate echo canceller"); + + + // micFile = new ofstream("micData", ofstream::binary); + // echoFile = new ofstream("echoData", ofstream::binary); + // spkrFile = new ofstream("spkrData", ofstream::binary); + + micLevelData = new ofstream ("micLevelData", ofstream::binary); + spkrLevelData = new ofstream ("spkrLevelData", ofstream::binary); + + + _micData = new RingBuffer (50000); + _spkrData = new RingBuffer (50000); + _spkrDataOut = new RingBuffer (50000); + + _micData->createReadPointer(); + _spkrData->createReadPointer(); + _spkrDataOut->createReadPointer(); + + // variable used to sync mic and spkr + _spkrStoped = true; + + _smplPerFrame = (_samplingRate * _frameLength) / MS_PER_SEC; + _smplPerSeg = (_samplingRate * SEGMENT_LENGTH) / MS_PER_SEC; + _micHistoryLength = MIC_LENGTH / SEGMENT_LENGTH; + _spkrHistoryLength = SPKR_LENGTH / SEGMENT_LENGTH; + _nbSegmentPerFrame = _frameLength / SEGMENT_LENGTH; + + _noiseState = speex_preprocess_state_init (_smplPerFrame, _samplingRate); + int i=1; + speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_DENOISE, &i); + i=-20; + speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &i); + i=0; + speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_AGC, &i); + i=8000; + speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_AGC_TARGET, &i); + i=16000; + speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_AGC_LEVEL, &i); + i=0; + speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_DEREVERB, &i); + float f=0.0; + speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_DEREVERB_DECAY, &f); + f=0.0; + speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_DEREVERB_LEVEL, &f); + i = 0; + speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_VAD, &i); + + + memset (_avgSpkrLevelHist, 0, BUFF_SIZE*sizeof (int)); + memset (_avgMicLevelHist, 0, BUFF_SIZE*sizeof (int)); + + memset (_delayLineAmplify, 0, MAX_DELAY_LINE_AMPL*sizeof (float)); + + _amplDelayIndexIn = 0; + _amplDelayIndexOut = 0; + + _correlationSize = _spkrAdaptSize; + } -EchoCancel::~EchoCancel() -{ - _debug("EchoCancel: Delete echo canceller"); +EchoCancel::~EchoCancel() { + _debug ("EchoCancel: Delete echo canceller"); + + delete _micData; + _micData = NULL; - delete _micData; - _micData = NULL; + delete _spkrData; + _spkrData = NULL; - delete _spkrData; - _spkrData = NULL; + speex_preprocess_state_destroy (_noiseState); - speex_preprocess_state_destroy(_noiseState); - - // micFile->close(); - // spkrFile->close(); - // echoFile->close(); + // micFile->close(); + // spkrFile->close(); + // echoFile->close(); - // delete micFile; - // delete spkrFile; - // delete echoFile; + // delete micFile; + // delete spkrFile; + // delete echoFile; - micLevelData->close(); - spkrLevelData->close(); - delete micLevelData; - delete spkrLevelData; + micLevelData->close(); + spkrLevelData->close(); + delete micLevelData; + delete spkrLevelData; } -void EchoCancel::reset() -{ - _debug("EchoCancel: Reset internal state, Sampling rate %d, Frame size %d", _samplingRate, _smplPerFrame); - - memset(_avgSpkrLevelHist, 0, BUFF_SIZE*sizeof(int)); - memset(_avgMicLevelHist, 0, BUFF_SIZE*sizeof(int)); - - _spkrLevel = 0; - _micLevel = 0; - _spkrHistCnt = 0; - _micHistCnt = 0; - _amplFactor = 0.0; - _lastAmplFactor = 0.0; - - _smplPerFrame = (_samplingRate * _frameLength) / MS_PER_SEC; - _smplPerSeg = (_samplingRate * SEGMENT_LENGTH) / MS_PER_SEC; - _micHistoryLength = MIC_LENGTH / SEGMENT_LENGTH; - _spkrHistoryLength = SPKR_LENGTH / SEGMENT_LENGTH; - _nbSegmentPerFrame = _frameLength / SEGMENT_LENGTH; - - memset(_delayLineAmplify, 0, MAX_DELAY_LINE_AMPL*sizeof(float)); - - _amplDelayIndexIn = 0; - _amplDelayIndexOut = ECHO_LENGTH / SEGMENT_LENGTH; - - _adaptDone = false; - _adaptStarted = false; - _adaptCnt = 0; - _spkrAdaptCnt = 0; - _micAdaptCnt = 0; - - _micData->flushAll(); - _spkrData->flushAll(); - _spkrDataOut->flushAll(); - - speex_preprocess_state_destroy(_noiseState); - - _noiseState = speex_preprocess_state_init(_smplPerFrame, _samplingRate); - int i=1; - speex_preprocess_ctl(_noiseState, SPEEX_PREPROCESS_SET_DENOISE, &i); - i=-10; - speex_preprocess_ctl(_noiseState, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &i); - i=0; - speex_preprocess_ctl(_noiseState, SPEEX_PREPROCESS_SET_AGC, &i); - i=8000; - speex_preprocess_ctl(_noiseState, SPEEX_PREPROCESS_SET_AGC_TARGET, &i); - i=16000; - speex_preprocess_ctl(_noiseState, SPEEX_PREPROCESS_SET_AGC_LEVEL, &i); - i=0; - speex_preprocess_ctl(_noiseState, SPEEX_PREPROCESS_SET_DEREVERB, &i); - float f=0.0; - speex_preprocess_ctl(_noiseState, SPEEX_PREPROCESS_SET_DEREVERB_DECAY, &f); - f=0.0; - speex_preprocess_ctl(_noiseState, SPEEX_PREPROCESS_SET_DEREVERB_LEVEL, &f); - - _spkrStoped = true; - - _processedByte = 0; +void EchoCancel::reset() { + _debug ("EchoCancel: Reset internal state, Sampling rate %d, Frame size %d", _samplingRate, _smplPerFrame); + + memset (_avgSpkrLevelHist, 0, BUFF_SIZE*sizeof (int)); + memset (_avgMicLevelHist, 0, BUFF_SIZE*sizeof (int)); + + _spkrLevel = 0; + _micLevel = 0; + _spkrHistCnt = 0; + _micHistCnt = 0; + _amplFactor = 0.0; + _lastAmplFactor = 0.0; + + _smplPerFrame = (_samplingRate * _frameLength) / MS_PER_SEC; + _smplPerSeg = (_samplingRate * SEGMENT_LENGTH) / MS_PER_SEC; + _micHistoryLength = MIC_LENGTH / SEGMENT_LENGTH; + _spkrHistoryLength = SPKR_LENGTH / SEGMENT_LENGTH; + _nbSegmentPerFrame = _frameLength / SEGMENT_LENGTH; + + memset (_delayLineAmplify, 0, MAX_DELAY_LINE_AMPL*sizeof (float)); + + _amplDelayIndexIn = 0; + _amplDelayIndexOut = ECHO_LENGTH / SEGMENT_LENGTH; + + _adaptDone = false; + _adaptStarted = false; + _adaptCnt = 0; + _spkrAdaptCnt = 0; + _micAdaptCnt = 0; + + _micData->flushAll(); + _spkrData->flushAll(); + _spkrDataOut->flushAll(); + + speex_preprocess_state_destroy (_noiseState); + + _noiseState = speex_preprocess_state_init (_smplPerFrame, _samplingRate); + int i=1; + speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_DENOISE, &i); + i=-10; + speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &i); + i=0; + speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_AGC, &i); + i=8000; + speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_AGC_TARGET, &i); + i=16000; + speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_AGC_LEVEL, &i); + i=0; + speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_DEREVERB, &i); + float f=0.0; + speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_DEREVERB_DECAY, &f); + f=0.0; + speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_DEREVERB_LEVEL, &f); + + _spkrStoped = true; + + _processedByte = 0; } -void EchoCancel::putData(SFLDataFormat *inputData, int nbBytes) -{ +void EchoCancel::putData (SFLDataFormat *inputData, int nbBytes) { - _delayDetector.putData(inputData, nbBytes); + _delayDetector.putData (inputData, nbBytes); - if(_spkrStoped) { - _debug("EchoCancel: Flush data"); - _micData->flushAll(); - _spkrData->flushAll(); - _spkrStoped = false; - } + if (_spkrStoped) { + _debug ("EchoCancel: Flush data"); + _micData->flushAll(); + _spkrData->flushAll(); + _spkrStoped = false; + } - // Put data in speaker ring buffer - _spkrData->Put(inputData, nbBytes); + // Put data in speaker ring buffer + _spkrData->Put (inputData, nbBytes); } -int EchoCancel::getData(SFLDataFormat *outputData) -{ +int EchoCancel::getData (SFLDataFormat *outputData) { - int copied = 0; + int copied = 0; - if(_processedByte > 0) { - copied = _spkrDataOut->Get(outputData, _processedByte); - _processedByte = 0; - } + if (_processedByte > 0) { + copied = _spkrDataOut->Get (outputData, _processedByte); + _processedByte = 0; + } - return copied; + return copied; } -void EchoCancel::process(SFLDataFormat *data, int nbBytes) {} +void EchoCancel::process (SFLDataFormat *data, int nbBytes) {} -int EchoCancel::process(SFLDataFormat *inputData, SFLDataFormat *outputData, int nbBytes) -{ +int EchoCancel::process (SFLDataFormat *inputData, SFLDataFormat *outputData, int nbBytes) { - _delayDetector.process(inputData, nbBytes); + _delayDetector.process (inputData, nbBytes); - if(_spkrStoped) { - bcopy(inputData, outputData, nbBytes); - return nbBytes; - } + if (_spkrStoped) { + bcopy (inputData, outputData, nbBytes); + return nbBytes; + } - int byteSize = _smplPerFrame*sizeof(SFLDataFormat); + int byteSize = _smplPerFrame*sizeof (SFLDataFormat); - // init temporary buffers - memset(_tmpSpkr, 0, BUFF_SIZE*sizeof(SFLDataFormat)); - memset(_tmpMic, 0, BUFF_SIZE*sizeof(SFLDataFormat)); - memset(_tmpOut, 0, BUFF_SIZE*sizeof(SFLDataFormat)); + // init temporary buffers + memset (_tmpSpkr, 0, BUFF_SIZE*sizeof (SFLDataFormat)); + memset (_tmpMic, 0, BUFF_SIZE*sizeof (SFLDataFormat)); + memset (_tmpOut, 0, BUFF_SIZE*sizeof (SFLDataFormat)); - // Put mic data in ringbuffer - _micData->Put(inputData, nbBytes); + // Put mic data in ringbuffer + _micData->Put (inputData, nbBytes); - // Store data for synchronization - int spkrAvail = _spkrData->AvailForGet(); - int micAvail = _micData->AvailForGet(); + // Store data for synchronization + int spkrAvail = _spkrData->AvailForGet(); + int micAvail = _micData->AvailForGet(); - // Init number of frame processed - int nbFrame = 0; + // Init number of frame processed + int nbFrame = 0; - // Get data from mic and speaker internal buffer - // while((spkrAvail >= byteSize) && (micAvail >= byteSize)) { - while(micAvail >= byteSize) { + // Get data from mic and speaker internal buffer + // while((spkrAvail >= byteSize) && (micAvail >= byteSize)) { + while (micAvail >= byteSize) { - if(spkrAvail >= byteSize) { + if (spkrAvail >= byteSize) { - // get synchronized data - _spkrData->Get(_tmpSpkr, byteSize); - _micData->Get(_tmpMic, byteSize); - - // micFile->write((const char *)_tmpMic, byteSize); - // spkrFile->write((const char *)_tmpSpkr, byteSize); + // get synchronized data + _spkrData->Get (_tmpSpkr, byteSize); + _micData->Get (_tmpMic, byteSize); + + // micFile->write((const char *)_tmpMic, byteSize); + // spkrFile->write((const char *)_tmpSpkr, byteSize); #ifdef HAVE_LIBSPEEX_DSP - _debug("OK"); + _debug ("OK"); + + // Remove noise + if (_noiseActive) + speex_preprocess_run (_noiseState, _tmpMic); - // Remove noise - if(_noiseActive) - speex_preprocess_run(_noiseState, _tmpMic); #endif - // Processed echo cancellation - performEchoCancel(_tmpMic, _tmpSpkr, _tmpOut); + // Processed echo cancellation + performEchoCancel (_tmpMic, _tmpSpkr, _tmpOut); - // echoFile->write((const char *)_tmpOut, byteSize); + // echoFile->write((const char *)_tmpOut, byteSize); - bcopy(_tmpOut, outputData+(nbFrame*_smplPerFrame), byteSize); + bcopy (_tmpOut, outputData+ (nbFrame*_smplPerFrame), byteSize); - // used to sync with speaker - _processedByte += byteSize; + // used to sync with speaker + _processedByte += byteSize; - spkrAvail = _spkrData->AvailForGet(); - micAvail = _micData->AvailForGet(); + spkrAvail = _spkrData->AvailForGet(); + micAvail = _micData->AvailForGet(); - // increment nb of frame processed - ++nbFrame; - } - else { - _micData->Get(_tmpMic, byteSize); + // increment nb of frame processed + ++nbFrame; + } else { + _micData->Get (_tmpMic, byteSize); - performEchoCancelNoSpkr(_tmpMic, _tmpOut); + performEchoCancelNoSpkr (_tmpMic, _tmpOut); - bcopy(_tmpOut, outputData+(nbFrame*_smplPerFrame), byteSize); - ++nbFrame; - } + bcopy (_tmpOut, outputData+ (nbFrame*_smplPerFrame), byteSize); + ++nbFrame; + } - spkrAvail = _spkrData->AvailForGet(); - micAvail = _micData->AvailForGet(); - } + spkrAvail = _spkrData->AvailForGet(); + micAvail = _micData->AvailForGet(); + } - // if spkrAvail is twice the size of a frame discard it, this data is late and won't be used - if(spkrAvail > (2*byteSize)) { - _spkrData->Discard(spkrAvail-(2*byteSize)); - } + // if spkrAvail is twice the size of a frame discard it, this data is late and won't be used + if (spkrAvail > (2*byteSize)) { + _spkrData->Discard (spkrAvail- (2*byteSize)); + } - return nbFrame * _smplPerFrame; + return nbFrame * _smplPerFrame; } -void EchoCancel::process(SFLDataFormat *micData, SFLDataFormat *spkrData, SFLDataFormat *outputData, int nbBytes){ +void EchoCancel::process (SFLDataFormat *micData, SFLDataFormat *spkrData, SFLDataFormat *outputData, int nbBytes) { } -void EchoCancel::setSamplingRate(int smplRate) { - - if (smplRate != _samplingRate) { - _samplingRate = smplRate; +void EchoCancel::setSamplingRate (int smplRate) { + + if (smplRate != _samplingRate) { + _samplingRate = smplRate; - reset(); - } + reset(); + } } -void EchoCancel::performEchoCancel(SFLDataFormat *micData, SFLDataFormat *spkrData, SFLDataFormat *outputData) { +void EchoCancel::performEchoCancel (SFLDataFormat *micData, SFLDataFormat *spkrData, SFLDataFormat *outputData) { - for(int k = 0; k < _nbSegmentPerFrame; k++) { + for (int k = 0; k < _nbSegmentPerFrame; k++) { - updateEchoCancel(micData+(k*_smplPerSeg), spkrData+(k*_smplPerSeg)); + updateEchoCancel (micData+ (k*_smplPerSeg), spkrData+ (k*_smplPerSeg)); - _spkrLevel = getMaxAmplitude(_avgSpkrLevelHist, _spkrHistoryLength); - _micLevel = getMaxAmplitude(_avgMicLevelHist, _micHistoryLength)/6; + _spkrLevel = getMaxAmplitude (_avgSpkrLevelHist, _spkrHistoryLength); + _micLevel = getMaxAmplitude (_avgMicLevelHist, _micHistoryLength) /6; - if(_spkrLevel >= MIN_SIG_LEVEL) { - if(_micLevel > _spkrLevel) { - increaseFactor(0.2); - } - else { - _amplFactor = 0.0; - } - } - else { - increaseFactor(0.01); - } + if (_spkrLevel >= MIN_SIG_LEVEL) { + if (_micLevel > _spkrLevel) { + increaseFactor (0.2); + } else { + _amplFactor = 0.0; + } + } else { + increaseFactor (0.01); + } - // lowpass filtering - float amplify = (_lastAmplFactor + _amplFactor) / 2; - _lastAmplFactor = _amplFactor; + // lowpass filtering + float amplify = (_lastAmplFactor + _amplFactor) / 2; + _lastAmplFactor = _amplFactor; - if(!_echoActive) - amplify = 1.0; + if (!_echoActive) + amplify = 1.0; - amplifySignal(micData+(k*_smplPerSeg), outputData+(k*_smplPerSeg), amplify); - - } + amplifySignal (micData+ (k*_smplPerSeg), outputData+ (k*_smplPerSeg), amplify); + + } } -void EchoCancel::performEchoCancelNoSpkr(SFLDataFormat *micData, SFLDataFormat *outputData) { +void EchoCancel::performEchoCancelNoSpkr (SFLDataFormat *micData, SFLDataFormat *outputData) { - for(int k = 0; k < _nbSegmentPerFrame; k++) { + for (int k = 0; k < _nbSegmentPerFrame; k++) { - updateMicLevel(micData); + updateMicLevel (micData); - _micLevel = getMaxAmplitude(_avgMicLevelHist, _micHistoryLength)/6; - if(_micLevel > MIN_SIG_LEVEL) { - increaseFactor(0.2); - } + _micLevel = getMaxAmplitude (_avgMicLevelHist, _micHistoryLength) /6; - // lowpass filtering - float amplify = (_lastAmplFactor + _amplFactor) / 2; - _lastAmplFactor = _amplFactor; + if (_micLevel > MIN_SIG_LEVEL) { + increaseFactor (0.2); + } - if(!_echoActive) - amplify = 1.0; + // lowpass filtering + float amplify = (_lastAmplFactor + _amplFactor) / 2; + _lastAmplFactor = _amplFactor; - amplifySignal(micData+(k*_smplPerSeg), outputData+(k*_smplPerSeg), amplify); - } + if (!_echoActive) + amplify = 1.0; + + amplifySignal (micData+ (k*_smplPerSeg), outputData+ (k*_smplPerSeg), amplify); + } } -void EchoCancel::updateMicLevel(SFLDataFormat *micData) { +void EchoCancel::updateMicLevel (SFLDataFormat *micData) { - int micLvl = computeAmplitudeLevel(micData, _smplPerSeg); + int micLvl = computeAmplitudeLevel (micData, _smplPerSeg); - SFLDataFormat tempMicLevel[_smplPerSeg]; + SFLDataFormat tempMicLevel[_smplPerSeg]; - _micLevelMem = estimatePower(micData, tempMicLevel, _smplPerSeg, _micLevelMem); + _micLevelMem = estimatePower (micData, tempMicLevel, _smplPerSeg, _micLevelMem); - _avgMicLevelHist[_micHistCnt++] = micLvl+1; + _avgMicLevelHist[_micHistCnt++] = micLvl+1; - if(_micHistCnt >= _micHistoryLength) - _micHistCnt = 0; + if (_micHistCnt >= _micHistoryLength) + _micHistCnt = 0; - micLevelData->write((const char*)tempMicLevel, sizeof(SFLDataFormat)*_smplPerSeg); + micLevelData->write ( (const char*) tempMicLevel, sizeof (SFLDataFormat) *_smplPerSeg); } -void EchoCancel::updateSpkrLevel(SFLDataFormat *spkrData) { +void EchoCancel::updateSpkrLevel (SFLDataFormat *spkrData) { - int spkrLvl = computeAmplitudeLevel(spkrData, _smplPerSeg); + int spkrLvl = computeAmplitudeLevel (spkrData, _smplPerSeg); - SFLDataFormat tempSpkrLevel[_smplPerSeg]; + SFLDataFormat tempSpkrLevel[_smplPerSeg]; - _spkrLevelMem = estimatePower(spkrData, tempSpkrLevel, _smplPerSeg, _spkrLevelMem); + _spkrLevelMem = estimatePower (spkrData, tempSpkrLevel, _smplPerSeg, _spkrLevelMem); - _avgSpkrLevelHist[_spkrHistCnt++] = spkrLvl+1; + _avgSpkrLevelHist[_spkrHistCnt++] = spkrLvl+1; - if(_spkrHistCnt >= _spkrHistoryLength) - _spkrHistCnt = 0; + if (_spkrHistCnt >= _spkrHistoryLength) + _spkrHistCnt = 0; - spkrLevelData->write((const char*)tempSpkrLevel, sizeof(SFLDataFormat)*_smplPerSeg); + spkrLevelData->write ( (const char*) tempSpkrLevel, sizeof (SFLDataFormat) *_smplPerSeg); } -void EchoCancel::updateEchoCancel(SFLDataFormat *micData, SFLDataFormat *spkrData) { +void EchoCancel::updateEchoCancel (SFLDataFormat *micData, SFLDataFormat *spkrData) { - // Add 1 to make sure we are not dividing by 0 - updateMicLevel(micData); - updateSpkrLevel(spkrData); + // Add 1 to make sure we are not dividing by 0 + updateMicLevel (micData); + updateSpkrLevel (spkrData); - /* - // if adaptation done, stop here - // if(_adaptDone) - if(true) - return; - - // start learning only if there is data played through speaker - if(!_adaptStarted) { - if(spkrLvl > MIN_SIG_LEVEL) - _adaptStarted = true; - else + /* + // if adaptation done, stop here + // if(_adaptDone) + if(true) return; - } - if(_spkrAdaptCnt < _spkrAdaptSize) - _spkrAdaptArray[_spkrAdaptCnt++] = spkrLvl; + // start learning only if there is data played through speaker + if(!_adaptStarted) { + if(spkrLvl > MIN_SIG_LEVEL) + _adaptStarted = true; + else + return; + } + + if(_spkrAdaptCnt < _spkrAdaptSize) + _spkrAdaptArray[_spkrAdaptCnt++] = spkrLvl; - if(_micAdaptCnt < _micAdaptSize) - _micAdaptArray[_micAdaptCnt++] = micLvl; + if(_micAdaptCnt < _micAdaptSize) + _micAdaptArray[_micAdaptCnt++] = micLvl; - // perform correlation if spkr size is reached - if(_adaptCnt > _spkrAdaptSize) { - int k = _adaptCnt - _spkrAdaptSize; - _correlationArray[k] = performCorrelation(_spkrAdaptArray, _micAdaptArray+k, _correlationSize); - } + // perform correlation if spkr size is reached + if(_adaptCnt > _spkrAdaptSize) { + int k = _adaptCnt - _spkrAdaptSize; + _correlationArray[k] = performCorrelation(_spkrAdaptArray, _micAdaptArray+k, _correlationSize); + } - _adaptCnt++; + _adaptCnt++; - // if we captured a full echo - if(_adaptCnt == _micAdaptSize) { - _adaptDone = true; - _amplDelayIndexOut = 0;// getMaximumIndex(_correlationArray, _correlationSize); - } - */ + // if we captured a full echo + if(_adaptCnt == _micAdaptSize) { + _adaptDone = true; + _amplDelayIndexOut = 0;// getMaximumIndex(_correlationArray, _correlationSize); + } + */ } -int EchoCancel::computeAmplitudeLevel(SFLDataFormat *data, int size) { +int EchoCancel::computeAmplitudeLevel (SFLDataFormat *data, int size) { + + int level = 0; - int level = 0; + for (int i = 0; i < size; i++) { + if (data[i] >= 0.0) + level += (int) data[i]; + else + level -= (int) data[i]; + } - for(int i = 0; i < size; i++) { - if(data[i] >= 0.0) - level += (int)data[i]; - else - level -= (int)data[i]; - } + level = level / _smplPerSeg; - level = level / _smplPerSeg; + return level; - return level; - } -SFLDataFormat EchoCancel::estimatePower(SFLDataFormat *data, SFLDataFormat *ampl, int size, SFLDataFormat mem) { +SFLDataFormat EchoCancel::estimatePower (SFLDataFormat *data, SFLDataFormat *ampl, int size, SFLDataFormat mem) { - float memFactor = 1.0 - _alpha; + float memFactor = 1.0 - _alpha; - for (int i = 0; i < size; i++) { - mem = (SFLDataFormat)(memFactor*(float)mem + abs(_alpha*(float)data[i])); - ampl[i] = mem; - } + for (int i = 0; i < size; i++) { + mem = (SFLDataFormat) (memFactor* (float) mem + abs (_alpha* (float) data[i])); + ampl[i] = mem; + } - return mem; + return mem; } -int EchoCancel::getMaxAmplitude(int *data, int size) { +int EchoCancel::getMaxAmplitude (int *data, int size) { - SFLDataFormat level = 0.0; + SFLDataFormat level = 0.0; - for(int i = 0; i < size; i++) { - if(data[i] >= level) - level = data[i]; - } + for (int i = 0; i < size; i++) { + if (data[i] >= level) + level = data[i]; + } - return (int)level; + return (int) level; } -void EchoCancel::amplifySignal(SFLDataFormat *micData, SFLDataFormat *outputData, float amplify) { +void EchoCancel::amplifySignal (SFLDataFormat *micData, SFLDataFormat *outputData, float amplify) { - // for(int i = 0; i < _smplPerSeg; i++) - // outputData[i] = micData[i]; + // for(int i = 0; i < _smplPerSeg; i++) + // outputData[i] = micData[i]; - // Use delayed amplification factor due to sound card latency - // do not increment amplitude array if adaptation is not done - // if (_adaptDone) { - if (true) { - for(int i = 0; i < _smplPerSeg; i++) { - outputData[i] = (SFLDataFormat)(((float)micData[i])*_delayLineAmplify[_amplDelayIndexOut]); - } - _amplDelayIndexOut++; - _delayLineAmplify[_amplDelayIndexIn++] = amplify; - } - else { - for(int i = 0; i < _smplPerSeg; i++) { - outputData[i] = micData[i]; + // Use delayed amplification factor due to sound card latency + // do not increment amplitude array if adaptation is not done + // if (_adaptDone) { + if (true) { + for (int i = 0; i < _smplPerSeg; i++) { + outputData[i] = (SFLDataFormat) ( ( (float) micData[i]) *_delayLineAmplify[_amplDelayIndexOut]); + } + + _amplDelayIndexOut++; + _delayLineAmplify[_amplDelayIndexIn++] = amplify; + } else { + for (int i = 0; i < _smplPerSeg; i++) { + outputData[i] = micData[i]; + } + + return; } - return; - } - if(_amplDelayIndexOut >= MAX_DELAY_LINE_AMPL) - _amplDelayIndexOut = 0; + if (_amplDelayIndexOut >= MAX_DELAY_LINE_AMPL) + _amplDelayIndexOut = 0; - if(_amplDelayIndexIn >= MAX_DELAY_LINE_AMPL) - _amplDelayIndexIn = 0; + if (_amplDelayIndexIn >= MAX_DELAY_LINE_AMPL) + _amplDelayIndexIn = 0; } -void EchoCancel::increaseFactor(float factor) { +void EchoCancel::increaseFactor (float factor) { - // Get 200 ms to get back to full amplitude - _amplFactor += factor; + // Get 200 ms to get back to full amplitude + _amplFactor += factor; - if(_amplFactor > 1.0) - _amplFactor = 1.0; + if (_amplFactor > 1.0) + _amplFactor = 1.0; } void EchoCancel::decreaseFactor() { - // Takes about 50 ms to react - _amplFactor -= 0.2; + // Takes about 50 ms to react + _amplFactor -= 0.2; - if(_amplFactor < 0.0) - _amplFactor = 0.0; + if (_amplFactor < 0.0) + _amplFactor = 0.0; } -int EchoCancel::performCorrelation(int *data1, int *data2, int size) { +int EchoCancel::performCorrelation (int *data1, int *data2, int size) { + + int correlation = 0; + + while (size) { + size--; + correlation += data1[size] * data2[size]; + } - int correlation = 0; - while(size) { - size--; - correlation += data1[size] * data2[size]; - } - return correlation; + return correlation; } -int EchoCancel::getMaximumIndex(int *data, int size) { +int EchoCancel::getMaximumIndex (int *data, int size) { + + int index = size; + int max = data[size-1]; + + while (size) { + size--; - int index = size; - int max = data[size-1]; - - while(size) { - size--; - if(data[size] > max) { - index = size; - max = data[size]; + if (data[size] > max) { + index = size; + max = data[size]; + } } - } - return index; + return index; } diff --git a/sflphone-common/src/audio/jitterbuf.cpp b/sflphone-common/src/audio/jitterbuf.cpp old mode 100755 new mode 100644 index c72a6387f9769ae91feefd23e332030a74a0d328..6f752e992819ff0a0c46f315bd1af1c27f240cd5 --- a/sflphone-common/src/audio/jitterbuf.cpp +++ b/sflphone-common/src/audio/jitterbuf.cpp @@ -51,831 +51,830 @@ static jb_output_function_t warnf, errf, dbgf; -void jb_setoutput(jb_output_function_t err, jb_output_function_t warn, jb_output_function_t dbg) -{ - errf = err; - warnf = warn; - dbgf = dbg; +void jb_setoutput (jb_output_function_t err, jb_output_function_t warn, jb_output_function_t dbg) { + errf = err; + warnf = warn; + dbgf = dbg; } -static void increment_losspct(jitterbuf *jb) -{ - jb->info.losspct = (100000 + 499 * jb->info.losspct)/500; +static void increment_losspct (jitterbuf *jb) { + jb->info.losspct = (100000 + 499 * jb->info.losspct) /500; } -static void decrement_losspct(jitterbuf *jb) -{ - jb->info.losspct = (499 * jb->info.losspct)/500; +static void decrement_losspct (jitterbuf *jb) { + jb->info.losspct = (499 * jb->info.losspct) /500; } -void jb_reset(jitterbuf *jb) -{ - /* only save settings */ - jb_conf s = jb->info.conf; - memset(jb, 0, sizeof(*jb)); - jb->info.conf = s; +void jb_reset (jitterbuf *jb) { + /* only save settings */ + jb_conf s = jb->info.conf; + memset (jb, 0, sizeof (*jb)); + jb->info.conf = s; - /* initialize length, using the default value */ - jb->info.current = jb->info.target = jb->info.conf.target_extra = JB_TARGET_EXTRA; - jb->info.silence_begin_ts = -1; + /* initialize length, using the default value */ + jb->info.current = jb->info.target = jb->info.conf.target_extra = JB_TARGET_EXTRA; + jb->info.silence_begin_ts = -1; } -jitterbuf * jb_new() -{ - jitterbuf *jb; +jitterbuf * jb_new() { + jitterbuf *jb; - if (!(jb = (jitterbuf *)malloc(sizeof(*jb)))) - return NULL; + if (! (jb = (jitterbuf *) malloc (sizeof (*jb)))) + return NULL; - jb_reset(jb); + jb_reset (jb); - jb_dbg2("jb_new() = %x\n", jb); - return jb; + jb_dbg2 ("jb_new() = %x\n", jb); + return jb; } -void jb_destroy(jitterbuf *jb) -{ - jb_frame *frame; - jb_dbg2("jb_destroy(%x)\n", jb); - - /* free all the frames on the "free list" */ - frame = jb->free; - while (frame != NULL) { - jb_frame *next = frame->next; - free(frame); - frame = next; - } - - /* free ourselves! */ - free(jb); +void jb_destroy (jitterbuf *jb) { + jb_frame *frame; + jb_dbg2 ("jb_destroy(%x)\n", jb); + + /* free all the frames on the "free list" */ + frame = jb->free; + + while (frame != NULL) { + jb_frame *next = frame->next; + free (frame); + frame = next; + } + + /* free ourselves! */ + free (jb); } #if 0 -static int longcmp(const void *a, const void *b) -{ - return *(long *)a - *(long *)b; +static int longcmp (const void *a, const void *b) { + return * (long *) a - * (long *) b; } #endif -/*! \brief simple history manipulation +/*! \brief simple history manipulation \note maybe later we can make the history buckets variable size, or something? */ /* drop parameter determines whether we will drop outliers to minimize * delay */ -static int history_put(jitterbuf *jb, long ts, long now, long ms) -{ - long delay = now - (ts - jb->info.resync_offset); - long threshold = 2 * jb->info.jitter + jb->info.conf.resync_threshold; - long kicked; - - /* don't add special/negative times to history */ - if (ts <= 0) - return 0; - - /* check for drastic change in delay */ - if (jb->info.conf.resync_threshold != -1) { - if (abs(delay - jb->info.last_delay) > threshold) { - jb->info.cnt_delay_discont++; - if (jb->info.cnt_delay_discont > 3) { - /* resync the jitterbuffer */ - jb->info.cnt_delay_discont = 0; - jb->hist_ptr = 0; - jb->hist_maxbuf_valid = 0; - - jb_warn("Resyncing the jb. last_delay %ld, this delay %ld, threshold %ld, new offset %ld\n", jb->info.last_delay, delay, threshold, ts - now); - jb->info.resync_offset = ts - now; - jb->info.last_delay = delay = 0; /* after resync, frame is right on time */ - } else { - return -1; - } - } else { - jb->info.last_delay = delay; - jb->info.cnt_delay_discont = 0; - } - } - - kicked = jb->history[jb->hist_ptr % JB_HISTORY_SZ]; - - jb->history[(jb->hist_ptr++) % JB_HISTORY_SZ] = delay; - - /* optimization; the max/min buffers don't need to be recalculated, if this packet's - * entry doesn't change them. This happens if this packet is not involved, _and_ any packet - * that got kicked out of the history is also not involved - * We do a number of comparisons, but it's probably still worthwhile, because it will usually - * succeed, and should be a lot faster than going through all 500 packets in history */ - if (!jb->hist_maxbuf_valid) - return 0; - - /* don't do this until we've filled history - * (reduces some edge cases below) */ - if (jb->hist_ptr < JB_HISTORY_SZ) - goto invalidate; - - /* if the new delay would go into min */ - if (delay < jb->hist_minbuf[JB_HISTORY_MAXBUF_SZ-1]) - goto invalidate; - - /* or max.. */ - if (delay > jb->hist_maxbuf[JB_HISTORY_MAXBUF_SZ-1]) - goto invalidate; - - /* or the kicked delay would be in min */ - if (kicked <= jb->hist_minbuf[JB_HISTORY_MAXBUF_SZ-1]) - goto invalidate; - - if (kicked >= jb->hist_maxbuf[JB_HISTORY_MAXBUF_SZ-1]) - goto invalidate; - - /* if we got here, we don't need to invalidate, 'cause this delay didn't - * affect things */ - return 0; - /* end optimization */ +static int history_put (jitterbuf *jb, long ts, long now, long ms) { + long delay = now - (ts - jb->info.resync_offset); + long threshold = 2 * jb->info.jitter + jb->info.conf.resync_threshold; + long kicked; + + /* don't add special/negative times to history */ + if (ts <= 0) + return 0; + + /* check for drastic change in delay */ + if (jb->info.conf.resync_threshold != -1) { + if (abs (delay - jb->info.last_delay) > threshold) { + jb->info.cnt_delay_discont++; + + if (jb->info.cnt_delay_discont > 3) { + /* resync the jitterbuffer */ + jb->info.cnt_delay_discont = 0; + jb->hist_ptr = 0; + jb->hist_maxbuf_valid = 0; + + jb_warn ("Resyncing the jb. last_delay %ld, this delay %ld, threshold %ld, new offset %ld\n", jb->info.last_delay, delay, threshold, ts - now); + jb->info.resync_offset = ts - now; + jb->info.last_delay = delay = 0; /* after resync, frame is right on time */ + } else { + return -1; + } + } else { + jb->info.last_delay = delay; + jb->info.cnt_delay_discont = 0; + } + } + + kicked = jb->history[jb->hist_ptr % JB_HISTORY_SZ]; + + jb->history[ (jb->hist_ptr++) % JB_HISTORY_SZ] = delay; + + /* optimization; the max/min buffers don't need to be recalculated, if this packet's + * entry doesn't change them. This happens if this packet is not involved, _and_ any packet + * that got kicked out of the history is also not involved + * We do a number of comparisons, but it's probably still worthwhile, because it will usually + * succeed, and should be a lot faster than going through all 500 packets in history */ + if (!jb->hist_maxbuf_valid) + return 0; + + /* don't do this until we've filled history + * (reduces some edge cases below) */ + if (jb->hist_ptr < JB_HISTORY_SZ) + goto invalidate; + + /* if the new delay would go into min */ + if (delay < jb->hist_minbuf[JB_HISTORY_MAXBUF_SZ-1]) + goto invalidate; + + /* or max.. */ + if (delay > jb->hist_maxbuf[JB_HISTORY_MAXBUF_SZ-1]) + goto invalidate; + + /* or the kicked delay would be in min */ + if (kicked <= jb->hist_minbuf[JB_HISTORY_MAXBUF_SZ-1]) + goto invalidate; + + if (kicked >= jb->hist_maxbuf[JB_HISTORY_MAXBUF_SZ-1]) + goto invalidate; + + /* if we got here, we don't need to invalidate, 'cause this delay didn't + * affect things */ + return 0; + /* end optimization */ invalidate: - jb->hist_maxbuf_valid = 0; - return 0; + jb->hist_maxbuf_valid = 0; + return 0; } -static void history_calc_maxbuf(jitterbuf *jb) -{ - int i,j; +static void history_calc_maxbuf (jitterbuf *jb) { + int i,j; - if (jb->hist_ptr == 0) - return; + if (jb->hist_ptr == 0) + return; - /* initialize maxbuf/minbuf to the latest value */ - for (i=0;i<JB_HISTORY_MAXBUF_SZ;i++) { -/* - * jb->hist_maxbuf[i] = jb->history[(jb->hist_ptr-1) % JB_HISTORY_SZ]; - * jb->hist_minbuf[i] = jb->history[(jb->hist_ptr-1) % JB_HISTORY_SZ]; - */ - jb->hist_maxbuf[i] = JB_LONGMIN; - jb->hist_minbuf[i] = JB_LONGMAX; - } - - /* use insertion sort to populate maxbuf */ - /* we want it to be the top "n" values, in order */ - - /* start at the beginning, or JB_HISTORY_SZ frames ago */ - i = (jb->hist_ptr > JB_HISTORY_SZ) ? (jb->hist_ptr - JB_HISTORY_SZ) : 0; - - for (;i<jb->hist_ptr;i++) { - long toins = jb->history[i % JB_HISTORY_SZ]; - - /* if the maxbuf should get this */ - if (toins > jb->hist_maxbuf[JB_HISTORY_MAXBUF_SZ-1]) { - - /* insertion-sort it into the maxbuf */ - for (j=0;j<JB_HISTORY_MAXBUF_SZ;j++) { - /* found where it fits */ - if (toins > jb->hist_maxbuf[j]) { - /* move over */ - memmove(jb->hist_maxbuf + j + 1, jb->hist_maxbuf + j, (JB_HISTORY_MAXBUF_SZ - (j + 1)) * sizeof(jb->hist_maxbuf[0])); - /* insert */ - jb->hist_maxbuf[j] = toins; - - break; - } - } - } - - /* if the minbuf should get this */ - if (toins < jb->hist_minbuf[JB_HISTORY_MAXBUF_SZ-1]) { - - /* insertion-sort it into the maxbuf */ - for (j=0;j<JB_HISTORY_MAXBUF_SZ;j++) { - /* found where it fits */ - if (toins < jb->hist_minbuf[j]) { - /* move over */ - memmove(jb->hist_minbuf + j + 1, jb->hist_minbuf + j, (JB_HISTORY_MAXBUF_SZ - (j + 1)) * sizeof(jb->hist_minbuf[0])); - /* insert */ - jb->hist_minbuf[j] = toins; - - break; - } - } - } - - if (0) { - int k; - _debug("toins = %ld\n", toins); - _debug("maxbuf ="); - for (k=0;k<JB_HISTORY_MAXBUF_SZ;k++) - _debug("%ld ", jb->hist_maxbuf[k]); - _debug("\nminbuf ="); - for (k=0;k<JB_HISTORY_MAXBUF_SZ;k++) - _debug("%ld ", jb->hist_minbuf[k]); - _debug("\n"); - } - } - - jb->hist_maxbuf_valid = 1; + /* initialize maxbuf/minbuf to the latest value */ + for (i=0; i<JB_HISTORY_MAXBUF_SZ; i++) { + /* + * jb->hist_maxbuf[i] = jb->history[(jb->hist_ptr-1) % JB_HISTORY_SZ]; + * jb->hist_minbuf[i] = jb->history[(jb->hist_ptr-1) % JB_HISTORY_SZ]; + */ + jb->hist_maxbuf[i] = JB_LONGMIN; + jb->hist_minbuf[i] = JB_LONGMAX; + } + + /* use insertion sort to populate maxbuf */ + /* we want it to be the top "n" values, in order */ + + /* start at the beginning, or JB_HISTORY_SZ frames ago */ + i = (jb->hist_ptr > JB_HISTORY_SZ) ? (jb->hist_ptr - JB_HISTORY_SZ) : 0; + + for (; i<jb->hist_ptr; i++) { + long toins = jb->history[i % JB_HISTORY_SZ]; + + /* if the maxbuf should get this */ + if (toins > jb->hist_maxbuf[JB_HISTORY_MAXBUF_SZ-1]) { + + /* insertion-sort it into the maxbuf */ + for (j=0; j<JB_HISTORY_MAXBUF_SZ; j++) { + /* found where it fits */ + if (toins > jb->hist_maxbuf[j]) { + /* move over */ + memmove (jb->hist_maxbuf + j + 1, jb->hist_maxbuf + j, (JB_HISTORY_MAXBUF_SZ - (j + 1)) * sizeof (jb->hist_maxbuf[0])); + /* insert */ + jb->hist_maxbuf[j] = toins; + + break; + } + } + } + + /* if the minbuf should get this */ + if (toins < jb->hist_minbuf[JB_HISTORY_MAXBUF_SZ-1]) { + + /* insertion-sort it into the maxbuf */ + for (j=0; j<JB_HISTORY_MAXBUF_SZ; j++) { + /* found where it fits */ + if (toins < jb->hist_minbuf[j]) { + /* move over */ + memmove (jb->hist_minbuf + j + 1, jb->hist_minbuf + j, (JB_HISTORY_MAXBUF_SZ - (j + 1)) * sizeof (jb->hist_minbuf[0])); + /* insert */ + jb->hist_minbuf[j] = toins; + + break; + } + } + } + + if (0) { + int k; + _debug ("toins = %ld\n", toins); + _debug ("maxbuf ="); + + for (k=0; k<JB_HISTORY_MAXBUF_SZ; k++) + _debug ("%ld ", jb->hist_maxbuf[k]); + + _debug ("\nminbuf ="); + + for (k=0; k<JB_HISTORY_MAXBUF_SZ; k++) + _debug ("%ld ", jb->hist_minbuf[k]); + + _debug ("\n"); + } + } + + jb->hist_maxbuf_valid = 1; } -static void history_get(jitterbuf *jb) -{ - long max, min, jitter; - int idx; - int count; +static void history_get (jitterbuf *jb) { + long max, min, jitter; + int idx; + int count; - if (!jb->hist_maxbuf_valid) - history_calc_maxbuf(jb); + if (!jb->hist_maxbuf_valid) + history_calc_maxbuf (jb); - /* count is how many items in history we're examining */ - count = (jb->hist_ptr < JB_HISTORY_SZ) ? jb->hist_ptr : JB_HISTORY_SZ; + /* count is how many items in history we're examining */ + count = (jb->hist_ptr < JB_HISTORY_SZ) ? jb->hist_ptr : JB_HISTORY_SZ; - /* idx is the "n"ths highest/lowest that we'll look for */ - idx = count * JB_HISTORY_DROPPCT / 100; + /* idx is the "n"ths highest/lowest that we'll look for */ + idx = count * JB_HISTORY_DROPPCT / 100; - /* sanity checks for idx */ - if (idx > (JB_HISTORY_MAXBUF_SZ - 1)) - idx = JB_HISTORY_MAXBUF_SZ - 1; + /* sanity checks for idx */ + if (idx > (JB_HISTORY_MAXBUF_SZ - 1)) + idx = JB_HISTORY_MAXBUF_SZ - 1; - if (idx < 0) { - jb->info.min = 0; - jb->info.jitter = 0; - return; - } + if (idx < 0) { + jb->info.min = 0; + jb->info.jitter = 0; + return; + } - max = jb->hist_maxbuf[idx]; - min = jb->hist_minbuf[idx]; + max = jb->hist_maxbuf[idx]; + min = jb->hist_minbuf[idx]; - jitter = max - min; + jitter = max - min; - /* these debug stmts compare the difference between looking at the absolute jitter, and the - * values we get by throwing away the outliers */ - // printf("[%ld] min=%ld, max=%ld, jitter=%ld\n", index, min, max, jitter); - // printf("[%ld] min=%ld, max=%ld, jitter=%ld\n", 0, jb->hist_minbuf[0], jb->hist_maxbuf[0], jb->hist_maxbuf[0]-jb->hist_minbuf[0]); + /* these debug stmts compare the difference between looking at the absolute jitter, and the + * values we get by throwing away the outliers */ + // printf("[%ld] min=%ld, max=%ld, jitter=%ld\n", index, min, max, jitter); + // printf("[%ld] min=%ld, max=%ld, jitter=%ld\n", 0, jb->hist_minbuf[0], jb->hist_maxbuf[0], jb->hist_maxbuf[0]-jb->hist_minbuf[0]); - jb->info.min = min; - jb->info.jitter = jitter; + jb->info.min = min; + jb->info.jitter = jitter; } /* returns 1 if frame was inserted into head of queue, 0 otherwise */ -static int queue_put(jitterbuf *jb, void *data, const enum jb_frame_type type, long ms, long ts) -{ - jb_frame *frame; - jb_frame *p; - int head = 0; - long resync_ts = ts - jb->info.resync_offset; - - if ((frame = jb->free)) { - jb->free = frame->next; - } else if (!(frame = (jb_frame *)malloc(sizeof(*frame)))) { - jb_err("cannot allocate frame\n"); - return 0; - } - - jb->info.frames_cur++; - - frame->data = data; - frame->ts = resync_ts; - frame->ms = ms; - frame->type = type; - - /* - * frames are a circular list, jb-frames points to to the lowest ts, - * jb->frames->prev points to the highest ts - */ - - if (!jb->frames) { /* queue is empty */ - jb->frames = frame; - frame->next = frame; - frame->prev = frame; - head = 1; - } else if (resync_ts < jb->frames->ts) { - frame->next = jb->frames; - frame->prev = jb->frames->prev; - - frame->next->prev = frame; - frame->prev->next = frame; - - /* frame is out of order */ - jb->info.frames_ooo++; - - jb->frames = frame; - head = 1; - } else { - p = jb->frames; - - /* frame is out of order */ - if (resync_ts < p->prev->ts) jb->info.frames_ooo++; - - while (resync_ts < p->prev->ts && p->prev != jb->frames) - p = p->prev; - - frame->next = p; - frame->prev = p->prev; - - frame->next->prev = frame; - frame->prev->next = frame; - } - return head; +static int queue_put (jitterbuf *jb, void *data, const enum jb_frame_type type, long ms, long ts) { + jb_frame *frame; + jb_frame *p; + int head = 0; + long resync_ts = ts - jb->info.resync_offset; + + if ( (frame = jb->free)) { + jb->free = frame->next; + } else if (! (frame = (jb_frame *) malloc (sizeof (*frame)))) { + jb_err ("cannot allocate frame\n"); + return 0; + } + + jb->info.frames_cur++; + + frame->data = data; + frame->ts = resync_ts; + frame->ms = ms; + frame->type = type; + + /* + * frames are a circular list, jb-frames points to to the lowest ts, + * jb->frames->prev points to the highest ts + */ + + if (!jb->frames) { /* queue is empty */ + jb->frames = frame; + frame->next = frame; + frame->prev = frame; + head = 1; + } else if (resync_ts < jb->frames->ts) { + frame->next = jb->frames; + frame->prev = jb->frames->prev; + + frame->next->prev = frame; + frame->prev->next = frame; + + /* frame is out of order */ + jb->info.frames_ooo++; + + jb->frames = frame; + head = 1; + } else { + p = jb->frames; + + /* frame is out of order */ + if (resync_ts < p->prev->ts) jb->info.frames_ooo++; + + while (resync_ts < p->prev->ts && p->prev != jb->frames) + p = p->prev; + + frame->next = p; + frame->prev = p->prev; + + frame->next->prev = frame; + frame->prev->next = frame; + } + + return head; } -static long queue_next(jitterbuf *jb) -{ - if (jb->frames) - return jb->frames->ts; - else - return -1; +static long queue_next (jitterbuf *jb) { + if (jb->frames) + return jb->frames->ts; + else + return -1; } -static long queue_last(jitterbuf *jb) -{ - if (jb->frames) - return jb->frames->prev->ts; - else - return -1; +static long queue_last (jitterbuf *jb) { + if (jb->frames) + return jb->frames->prev->ts; + else + return -1; } -static jb_frame *_queue_get(jitterbuf *jb, long ts, int all) -{ - jb_frame *frame; - frame = jb->frames; +static jb_frame *_queue_get (jitterbuf *jb, long ts, int all) { + jb_frame *frame; + frame = jb->frames; - if (!frame) - return NULL; + if (!frame) + return NULL; - _debug("queue_get: ASK %ld FIRST %ld\n", ts, frame->ts); + _debug ("queue_get: ASK %ld FIRST %ld\n", ts, frame->ts); - if (all || ts >= frame->ts) { - /* remove this frame */ - frame->prev->next = frame->next; - frame->next->prev = frame->prev; + if (all || ts >= frame->ts) { + /* remove this frame */ + frame->prev->next = frame->next; + frame->next->prev = frame->prev; - if (frame->next == frame) - jb->frames = NULL; - else - jb->frames = frame->next; + if (frame->next == frame) + jb->frames = NULL; + else + jb->frames = frame->next; - /* insert onto "free" single-linked list */ - frame->next = jb->free; - jb->free = frame; + /* insert onto "free" single-linked list */ + frame->next = jb->free; + jb->free = frame; - jb->info.frames_cur--; + jb->info.frames_cur--; - /* we return the frame pointer, even though it's on free list, - * but caller must copy data */ - return frame; - } + /* we return the frame pointer, even though it's on free list, + * but caller must copy data */ + return frame; + } - return NULL; + return NULL; } -static jb_frame *queue_get(jitterbuf *jb, long ts) -{ - return _queue_get(jb,ts,0); +static jb_frame *queue_get (jitterbuf *jb, long ts) { + return _queue_get (jb,ts,0); } -static jb_frame *queue_getall(jitterbuf *jb) -{ - return _queue_get(jb,0,1); +static jb_frame *queue_getall (jitterbuf *jb) { + return _queue_get (jb,0,1); } /* some diagnostics */ -void jb_dbginfo(jitterbuf *jb) -{ - - _debug("\njb info: fin=%ld fout=%ld flate=%ld flost=%ld fdrop=%ld fcur=%ld\n", - jb->info.frames_in, jb->info.frames_out, jb->info.frames_late, jb->info.frames_lost, jb->info.frames_dropped, jb->info.frames_cur); - - _debug("jitter=%ld current=%ld target=%ld min=%ld sil=%ld len=%ld len/fcur=%ld\n", - jb->info.jitter, jb->info.current, jb->info.target, jb->info.min, jb->info.silence_begin_ts, jb->info.current - jb->info.min, - jb->info.frames_cur ? (jb->info.current - jb->info.min)/jb->info.frames_cur : -8); - if (jb->info.frames_in > 0) - _debug("jb info: Loss PCT = %ld%%, Late PCT = %ld%%\n", - jb->info.frames_lost * 100/(jb->info.frames_in + jb->info.frames_lost), - jb->info.frames_late * 100/jb->info.frames_in); - _debug("jb info: queue %ld -> %ld. last_ts %ld (queue len: %ld) last_ms %ld\n\n", - queue_next(jb), - queue_last(jb), - jb->info.next_voice_ts, - queue_last(jb) - queue_next(jb), - jb->info.last_voice_ms); +void jb_dbginfo (jitterbuf *jb) { + + _debug ("\njb info: fin=%ld fout=%ld flate=%ld flost=%ld fdrop=%ld fcur=%ld\n", + jb->info.frames_in, jb->info.frames_out, jb->info.frames_late, jb->info.frames_lost, jb->info.frames_dropped, jb->info.frames_cur); + + _debug ("jitter=%ld current=%ld target=%ld min=%ld sil=%ld len=%ld len/fcur=%ld\n", + jb->info.jitter, jb->info.current, jb->info.target, jb->info.min, jb->info.silence_begin_ts, jb->info.current - jb->info.min, + jb->info.frames_cur ? (jb->info.current - jb->info.min) /jb->info.frames_cur : -8); + + if (jb->info.frames_in > 0) + _debug ("jb info: Loss PCT = %ld%%, Late PCT = %ld%%\n", + jb->info.frames_lost * 100/ (jb->info.frames_in + jb->info.frames_lost), + jb->info.frames_late * 100/jb->info.frames_in); + + _debug ("jb info: queue %ld -> %ld. last_ts %ld (queue len: %ld) last_ms %ld\n\n", + queue_next (jb), + queue_last (jb), + jb->info.next_voice_ts, + queue_last (jb) - queue_next (jb), + jb->info.last_voice_ms); } #ifdef DEEP_DEBUG -static void jb_chkqueue(jitterbuf *jb) -{ - int i=0; - jb_frame *p = jb->frames; - - if (!p) { - return; - } - - do { - if (p->next == NULL) { - jb_err("Queue is BROKEN at item [%d]", i); - } - i++; - p=p->next; - } while (p->next != jb->frames); +static void jb_chkqueue (jitterbuf *jb) { + int i=0; + jb_frame *p = jb->frames; + + if (!p) { + return; + } + + do { + if (p->next == NULL) { + jb_err ("Queue is BROKEN at item [%d]", i); + } + + i++; + p=p->next; + } while (p->next != jb->frames); } -static void jb_dbgqueue(jitterbuf *jb) -{ - int i=0; - jb_frame *p = jb->frames; +static void jb_dbgqueue (jitterbuf *jb) { + int i=0; + jb_frame *p = jb->frames; - jb_dbg("queue: "); + jb_dbg ("queue: "); - if (!p) { - jb_dbg("EMPTY\n"); - return; - } + if (!p) { + jb_dbg ("EMPTY\n"); + return; + } - do { - jb_dbg("[%d]=%ld ", i++, p->ts); - p=p->next; - } while (p->next != jb->frames); + do { + jb_dbg ("[%d]=%ld ", i++, p->ts); + p=p->next; + } while (p->next != jb->frames); - jb_dbg("\n"); + jb_dbg ("\n"); } #endif -jb_return_code jb_put(jitterbuf *jb, void *data, const enum jb_frame_type type, long ms, long ts, long now) -{ - long numts; - - _debug("jb_put(%p,%p,%ld,%ld,%ld)\n", jb, data, ms, ts, now); - - numts = 0; - if (jb->frames) - numts = jb->frames->prev->ts - jb->frames->ts; - - _debug("numts %ld\n", numts); - - if (numts >= jb->info.conf.max_jitterbuf) { - if (!jb->dropem) { - _debug("Attempting to exceed Jitterbuf max %ld timeslots\n", - jb->info.conf.max_jitterbuf); - jb->dropem = 1; - } - jb->info.frames_dropped++; - return JB_DROP; - } else { - jb->dropem = 0; - } - - if (type == JB_TYPE_VOICE) { - /* presently, I'm only adding VOICE frames to history and drift calculations; mostly because with the - * IAX integrations, I'm sending retransmitted control frames with their awkward timestamps through */ - if (history_put(jb,ts,now,ms)) { - jb->info.frames_dropped++; - return JB_DROP; - } - } - - jb->info.frames_in++; - - /* if put into head of queue, caller needs to reschedule */ - if (queue_put(jb,data,type,ms,ts)) { - return JB_SCHED; - } - return JB_OK; +jb_return_code jb_put (jitterbuf *jb, void *data, const enum jb_frame_type type, long ms, long ts, long now) { + long numts; + + _debug ("jb_put(%p,%p,%ld,%ld,%ld)\n", jb, data, ms, ts, now); + + numts = 0; + + if (jb->frames) + numts = jb->frames->prev->ts - jb->frames->ts; + + _debug ("numts %ld\n", numts); + + if (numts >= jb->info.conf.max_jitterbuf) { + if (!jb->dropem) { + _debug ("Attempting to exceed Jitterbuf max %ld timeslots\n", + jb->info.conf.max_jitterbuf); + jb->dropem = 1; + } + + jb->info.frames_dropped++; + return JB_DROP; + } else { + jb->dropem = 0; + } + + if (type == JB_TYPE_VOICE) { + /* presently, I'm only adding VOICE frames to history and drift calculations; mostly because with the + * IAX integrations, I'm sending retransmitted control frames with their awkward timestamps through */ + if (history_put (jb,ts,now,ms)) { + jb->info.frames_dropped++; + return JB_DROP; + } + } + + jb->info.frames_in++; + + /* if put into head of queue, caller needs to reschedule */ + if (queue_put (jb,data,type,ms,ts)) { + return JB_SCHED; + } + + return JB_OK; } -static enum jb_return_code _jb_get(jitterbuf *jb, jb_frame *frameout, long now, long interpl) -{ - jb_frame *frame; - long diff; - static int dbg_cnt = 0; - - _debug("_jb_get\n"); - - /*if ((now - jb_next(jb)) > 2 * jb->info.last_voice_ms) jb_warn("SCHED: %ld", (now - jb_next(jb))); */ - /* get jitter info */ - history_get(jb); - - if (dbg_cnt && dbg_cnt % 50 == 0) { - jb_dbg("\n"); - } - dbg_cnt++; - - /* target */ - jb->info.target = jb->info.jitter + jb->info.min + jb->info.conf.target_extra; - - /* if a hard clamp was requested, use it */ - if ((jb->info.conf.max_jitterbuf) && ((jb->info.target - jb->info.min) > jb->info.conf.max_jitterbuf)) { - _debug("clamping target from %ld to %ld\n", (jb->info.target - jb->info.min), jb->info.conf.max_jitterbuf); - jb->info.target = jb->info.min + jb->info.conf.max_jitterbuf; - } - - diff = jb->info.target - jb->info.current; - - _debug("diff = %ld lms=%ld last = %ld now = %ld, djust delay = %ld\n", diff, - jb->info.last_voice_ms, jb->info.last_adjustment, now); - - /* let's work on non-silent case first */ - if (!jb->info.silence_begin_ts) { - - /* - if(diff > 0) - printf("diff > 0\n"); - - if((jb->info.last_adjustment + JB_ADJUST_DELAY) < now) - printf("(jb->info.last_adjustment + JB_ADJUST_DELAY) < now\n"); - - if((diff > queue_last(jb) - queue_next(jb))) - printf("diff > queue_last(jb) - queue_next(jb)\n"); - */ - _debug("** Non-silent case update timing info **\n"); - _debug("diff %ld\n", diff); - _debug("jb->info.last_adjustment %ld\n", jb->info.last_adjustment); - _debug("JB_ADJUST_DELAY %ld\n", JB_ADJUST_DELAY); - _debug("now %ld\n", now); - - /* we want to grow */ - if ((diff > 0) && - /* we haven't grown in the delay length */ - (((jb->info.last_adjustment + JB_ADJUST_DELAY) < now) || - /* we need to grow more than the "length" we have left */ - (diff > queue_last(jb) - queue_next(jb)) ) ) { - - - - - /* grow by interp frame length */ - jb->info.current += interpl; - jb->info.next_voice_ts += interpl; - jb->info.last_voice_ms = interpl; - jb->info.last_adjustment = now; - jb->info.cnt_contig_interp++; - if (jb->info.conf.max_contig_interp && jb->info.cnt_contig_interp >= jb->info.conf.max_contig_interp) { - jb->info.silence_begin_ts = jb->info.next_voice_ts - jb->info.current; - } - - _debug("Non silent case\n"); - return JB_INTERP; - } - - _debug("queue get\n"); - - frame = queue_get(jb, jb->info.next_voice_ts - jb->info.current); - - if(!frame) - _debug("frame not valid\n"); - - /* not a voice frame; just return it. */ - if (frame && frame->type != JB_TYPE_VOICE) { - if (frame->type == JB_TYPE_SILENCE) { - jb->info.silence_begin_ts = frame->ts; - jb->info.cnt_contig_interp = 0; - } - - *frameout = *frame; - jb->info.frames_out++; - _debug("Not a voice packet\n"); - return JB_OK; - } - - - /* voice frame is later than expected */ - if (frame && frame->ts + jb->info.current < jb->info.next_voice_ts) { - if (frame->ts + jb->info.current > jb->info.next_voice_ts - jb->info.last_voice_ms) { - /* either we interpolated past this frame in the last jb_get */ - /* or the frame is still in order, but came a little too quick */ - *frameout = *frame; - /* reset expectation for next frame */ - jb->info.next_voice_ts = frame->ts + jb->info.current + frame->ms; - jb->info.frames_out++; - decrement_losspct(jb); - jb->info.cnt_contig_interp = 0; - _debug("Either we interpolated past this frame in the last jb_get" \ - "or the frame is still in order, but came a little too quick\n"); - return JB_OK; - } else { - /* voice frame is late */ - *frameout = *frame; - jb->info.frames_out++; - decrement_losspct(jb); - jb->info.frames_late++; - jb->info.frames_lost--; - _debug("Voice frame is late\n"); - _debug("late: wanted=%ld, this=%ld, next=%ld\n", jb->info.next_voice_ts - jb->info.current, frame->ts, queue_next(jb)); - return JB_DROP; - } - } - - /* keep track of frame sizes, to allow for variable sized-frames */ - if (frame && frame->ms > 0) { - jb->info.last_voice_ms = frame->ms; - } - - /* we want to shrink; shrink at 1 frame / 500ms */ - /* unless we don't have a frame, then shrink 1 frame */ - /* every 80ms (though perhaps we can shrink even faster */ - /* in this case) */ - if (diff < -jb->info.conf.target_extra && - ((!frame && jb->info.last_adjustment + 80 < now) || - (jb->info.last_adjustment + 500 < now))) { - - jb->info.last_adjustment = now; - jb->info.cnt_contig_interp = 0; - - if (frame) { - *frameout = *frame; - /* shrink by frame size we're throwing out */ - jb->info.current -= frame->ms; - jb->info.frames_out++; - decrement_losspct(jb); - jb->info.frames_dropped++; - _debug("Shrink by frame size we're throwing out"); - return JB_DROP; - } else { - /* shrink by last_voice_ms */ - jb->info.current -= jb->info.last_voice_ms; - jb->info.frames_lost++; - increment_losspct(jb); - jb_dbg("S"); - _debug("No frames, shrink by last_voice_ms"); - return JB_NOFRAME; - } - } - - /* lost frame */ - if (!frame) { - /* this is a bit of a hack for now, but if we're close to - * target, and we find a missing frame, it makes sense to - * grow, because the frame might just be a bit late; - * otherwise, we presently get into a pattern where we return - * INTERP for the lost frame, then it shows up next, and we - * throw it away because it's late */ - /* I've recently only been able to replicate this using - * iaxclient talking to app_echo on asterisk. In this case, - * my outgoing packets go through asterisk's (old) - * jitterbuffer, and then might get an unusual increasing delay - * there if it decides to grow?? */ - /* Update: that might have been a different bug, that has been fixed.. - * But, this still seemed like a good idea, except that it ended up making a single actual - * lost frame get interpolated two or more times, when there was "room" to grow, so it might - * be a bit of a bad idea overall */ - /*if (diff > -1 * jb->info.last_voice_ms) { - jb->info.current += jb->info.last_voice_ms; - jb->info.last_adjustment = now; - jb_warn("g"); - return JB_INTERP; - } */ - jb->info.frames_lost++; - increment_losspct(jb); - jb->info.next_voice_ts += interpl; - jb->info.last_voice_ms = interpl; - jb->info.cnt_contig_interp++; - if (jb->info.conf.max_contig_interp && jb->info.cnt_contig_interp >= jb->info.conf.max_contig_interp) { - jb->info.silence_begin_ts = jb->info.next_voice_ts - jb->info.current; - } - - return JB_INTERP; - } - - /* normal case; return the frame, increment stuff */ - *frameout = *frame; - jb->info.next_voice_ts += frame->ms; - jb->info.frames_out++; - jb->info.cnt_contig_interp = 0; - decrement_losspct(jb); - jb_dbg("v"); - return JB_OK; - } else { - - _debug("Silence???\n"); - /* TODO: after we get the non-silent case down, we'll make the - * silent case -- basically, we'll just grow and shrink faster - * here, plus handle next_voice_ts a bit differently */ - - /* to disable silent special case altogether, just uncomment this: */ - /* jb->info.silence_begin_ts = 0; */ - - /* shrink interpl len every 10ms during silence */ - if (diff < -jb->info.conf.target_extra && - jb->info.last_adjustment + 10 <= now) { - jb->info.current -= interpl; - jb->info.last_adjustment = now; - } - - frame = queue_get(jb, now - jb->info.current); - if (!frame) { - return JB_NOFRAME; - } else if (frame->type != JB_TYPE_VOICE) { - /* normal case; in silent mode, got a non-voice frame */ - *frameout = *frame; - jb->info.frames_out++; - return JB_OK; - } - if (frame->ts < jb->info.silence_begin_ts) { - /* voice frame is late */ - *frameout = *frame; - jb->info.frames_out++; - decrement_losspct(jb); - jb->info.frames_late++; - jb->info.frames_lost--; - jb_dbg("l"); - /*jb_warn("\nlate: wanted=%ld, this=%ld, next=%ld\n", jb->info.next_voice_ts - jb->info.current, frame->ts, queue_next(jb)); - jb_warninfo(jb); */ - return JB_DROP; - } else { - /* voice frame */ - /* try setting current to target right away here */ - jb->info.current = jb->info.target; - jb->info.silence_begin_ts = 0; - jb->info.next_voice_ts = frame->ts + jb->info.current + frame->ms; - jb->info.last_voice_ms = frame->ms; - jb->info.frames_out++; - decrement_losspct(jb); - *frameout = *frame; - jb_dbg("V"); - return JB_OK; - } - } +static enum jb_return_code _jb_get (jitterbuf *jb, jb_frame *frameout, long now, long interpl) { + jb_frame *frame; + long diff; + static int dbg_cnt = 0; + + _debug ("_jb_get\n"); + + /*if ((now - jb_next(jb)) > 2 * jb->info.last_voice_ms) jb_warn("SCHED: %ld", (now - jb_next(jb))); */ + /* get jitter info */ + history_get (jb); + + if (dbg_cnt && dbg_cnt % 50 == 0) { + jb_dbg ("\n"); + } + + dbg_cnt++; + + /* target */ + jb->info.target = jb->info.jitter + jb->info.min + jb->info.conf.target_extra; + + /* if a hard clamp was requested, use it */ + if ( (jb->info.conf.max_jitterbuf) && ( (jb->info.target - jb->info.min) > jb->info.conf.max_jitterbuf)) { + _debug ("clamping target from %ld to %ld\n", (jb->info.target - jb->info.min), jb->info.conf.max_jitterbuf); + jb->info.target = jb->info.min + jb->info.conf.max_jitterbuf; + } + + diff = jb->info.target - jb->info.current; + + _debug ("diff = %ld lms=%ld last = %ld now = %ld, djust delay = %ld\n", diff, + jb->info.last_voice_ms, jb->info.last_adjustment, now); + + /* let's work on non-silent case first */ + if (!jb->info.silence_begin_ts) { + + /* + if(diff > 0) + printf("diff > 0\n"); + + if((jb->info.last_adjustment + JB_ADJUST_DELAY) < now) + printf("(jb->info.last_adjustment + JB_ADJUST_DELAY) < now\n"); + + if((diff > queue_last(jb) - queue_next(jb))) + printf("diff > queue_last(jb) - queue_next(jb)\n"); + */ + _debug ("** Non-silent case update timing info **\n"); + _debug ("diff %ld\n", diff); + _debug ("jb->info.last_adjustment %ld\n", jb->info.last_adjustment); + _debug ("JB_ADJUST_DELAY %ld\n", JB_ADJUST_DELAY); + _debug ("now %ld\n", now); + + /* we want to grow */ + if ( (diff > 0) && + /* we haven't grown in the delay length */ + ( ( (jb->info.last_adjustment + JB_ADJUST_DELAY) < now) || + /* we need to grow more than the "length" we have left */ + (diff > queue_last (jb) - queue_next (jb)))) { + + + + + /* grow by interp frame length */ + jb->info.current += interpl; + jb->info.next_voice_ts += interpl; + jb->info.last_voice_ms = interpl; + jb->info.last_adjustment = now; + jb->info.cnt_contig_interp++; + + if (jb->info.conf.max_contig_interp && jb->info.cnt_contig_interp >= jb->info.conf.max_contig_interp) { + jb->info.silence_begin_ts = jb->info.next_voice_ts - jb->info.current; + } + + _debug ("Non silent case\n"); + return JB_INTERP; + } + + _debug ("queue get\n"); + + frame = queue_get (jb, jb->info.next_voice_ts - jb->info.current); + + if (!frame) + _debug ("frame not valid\n"); + + /* not a voice frame; just return it. */ + if (frame && frame->type != JB_TYPE_VOICE) { + if (frame->type == JB_TYPE_SILENCE) { + jb->info.silence_begin_ts = frame->ts; + jb->info.cnt_contig_interp = 0; + } + + *frameout = *frame; + jb->info.frames_out++; + _debug ("Not a voice packet\n"); + return JB_OK; + } + + + /* voice frame is later than expected */ + if (frame && frame->ts + jb->info.current < jb->info.next_voice_ts) { + if (frame->ts + jb->info.current > jb->info.next_voice_ts - jb->info.last_voice_ms) { + /* either we interpolated past this frame in the last jb_get */ + /* or the frame is still in order, but came a little too quick */ + *frameout = *frame; + /* reset expectation for next frame */ + jb->info.next_voice_ts = frame->ts + jb->info.current + frame->ms; + jb->info.frames_out++; + decrement_losspct (jb); + jb->info.cnt_contig_interp = 0; + _debug ("Either we interpolated past this frame in the last jb_get" \ + "or the frame is still in order, but came a little too quick\n"); + return JB_OK; + } else { + /* voice frame is late */ + *frameout = *frame; + jb->info.frames_out++; + decrement_losspct (jb); + jb->info.frames_late++; + jb->info.frames_lost--; + _debug ("Voice frame is late\n"); + _debug ("late: wanted=%ld, this=%ld, next=%ld\n", jb->info.next_voice_ts - jb->info.current, frame->ts, queue_next (jb)); + return JB_DROP; + } + } + + /* keep track of frame sizes, to allow for variable sized-frames */ + if (frame && frame->ms > 0) { + jb->info.last_voice_ms = frame->ms; + } + + /* we want to shrink; shrink at 1 frame / 500ms */ + + /* unless we don't have a frame, then shrink 1 frame */ + + /* every 80ms (though perhaps we can shrink even faster */ + + /* in this case) */ + if (diff < -jb->info.conf.target_extra && + ( (!frame && jb->info.last_adjustment + 80 < now) || + (jb->info.last_adjustment + 500 < now))) { + + jb->info.last_adjustment = now; + jb->info.cnt_contig_interp = 0; + + if (frame) { + *frameout = *frame; + /* shrink by frame size we're throwing out */ + jb->info.current -= frame->ms; + jb->info.frames_out++; + decrement_losspct (jb); + jb->info.frames_dropped++; + _debug ("Shrink by frame size we're throwing out"); + return JB_DROP; + } else { + /* shrink by last_voice_ms */ + jb->info.current -= jb->info.last_voice_ms; + jb->info.frames_lost++; + increment_losspct (jb); + jb_dbg ("S"); + _debug ("No frames, shrink by last_voice_ms"); + return JB_NOFRAME; + } + } + + /* lost frame */ + if (!frame) { + /* this is a bit of a hack for now, but if we're close to + * target, and we find a missing frame, it makes sense to + * grow, because the frame might just be a bit late; + * otherwise, we presently get into a pattern where we return + * INTERP for the lost frame, then it shows up next, and we + * throw it away because it's late */ + /* I've recently only been able to replicate this using + * iaxclient talking to app_echo on asterisk. In this case, + * my outgoing packets go through asterisk's (old) + * jitterbuffer, and then might get an unusual increasing delay + * there if it decides to grow?? */ + /* Update: that might have been a different bug, that has been fixed.. + * But, this still seemed like a good idea, except that it ended up making a single actual + * lost frame get interpolated two or more times, when there was "room" to grow, so it might + * be a bit of a bad idea overall */ + /*if (diff > -1 * jb->info.last_voice_ms) { + jb->info.current += jb->info.last_voice_ms; + jb->info.last_adjustment = now; + jb_warn("g"); + return JB_INTERP; + } */ + jb->info.frames_lost++; + increment_losspct (jb); + jb->info.next_voice_ts += interpl; + jb->info.last_voice_ms = interpl; + jb->info.cnt_contig_interp++; + + if (jb->info.conf.max_contig_interp && jb->info.cnt_contig_interp >= jb->info.conf.max_contig_interp) { + jb->info.silence_begin_ts = jb->info.next_voice_ts - jb->info.current; + } + + return JB_INTERP; + } + + /* normal case; return the frame, increment stuff */ + *frameout = *frame; + jb->info.next_voice_ts += frame->ms; + jb->info.frames_out++; + jb->info.cnt_contig_interp = 0; + decrement_losspct (jb); + jb_dbg ("v"); + return JB_OK; + } else { + + _debug ("Silence???\n"); + /* TODO: after we get the non-silent case down, we'll make the + * silent case -- basically, we'll just grow and shrink faster + * here, plus handle next_voice_ts a bit differently */ + + /* to disable silent special case altogether, just uncomment this: */ + /* jb->info.silence_begin_ts = 0; */ + + /* shrink interpl len every 10ms during silence */ + if (diff < -jb->info.conf.target_extra && + jb->info.last_adjustment + 10 <= now) { + jb->info.current -= interpl; + jb->info.last_adjustment = now; + } + + frame = queue_get (jb, now - jb->info.current); + + if (!frame) { + return JB_NOFRAME; + } else if (frame->type != JB_TYPE_VOICE) { + /* normal case; in silent mode, got a non-voice frame */ + *frameout = *frame; + jb->info.frames_out++; + return JB_OK; + } + + if (frame->ts < jb->info.silence_begin_ts) { + /* voice frame is late */ + *frameout = *frame; + jb->info.frames_out++; + decrement_losspct (jb); + jb->info.frames_late++; + jb->info.frames_lost--; + jb_dbg ("l"); + /*jb_warn("\nlate: wanted=%ld, this=%ld, next=%ld\n", jb->info.next_voice_ts - jb->info.current, frame->ts, queue_next(jb)); + jb_warninfo(jb); */ + return JB_DROP; + } else { + /* voice frame */ + /* try setting current to target right away here */ + jb->info.current = jb->info.target; + jb->info.silence_begin_ts = 0; + jb->info.next_voice_ts = frame->ts + jb->info.current + frame->ms; + jb->info.last_voice_ms = frame->ms; + jb->info.frames_out++; + decrement_losspct (jb); + *frameout = *frame; + jb_dbg ("V"); + return JB_OK; + } + } } -long jb_next(jitterbuf *jb) -{ - if (jb->info.silence_begin_ts) { - if (jb->frames) { - long next = queue_next(jb); - history_get(jb); - /* shrink during silence */ - if (jb->info.target - jb->info.current < -jb->info.conf.target_extra) - return jb->info.last_adjustment + 10; - return next + jb->info.target; - } - else - return JB_LONGMAX; - } else { - return jb->info.next_voice_ts; - } +long jb_next (jitterbuf *jb) { + if (jb->info.silence_begin_ts) { + if (jb->frames) { + long next = queue_next (jb); + history_get (jb); + + /* shrink during silence */ + if (jb->info.target - jb->info.current < -jb->info.conf.target_extra) + return jb->info.last_adjustment + 10; + + return next + jb->info.target; + } else + return JB_LONGMAX; + } else { + return jb->info.next_voice_ts; + } } -enum jb_return_code jb_get(jitterbuf *jb, jb_frame *frameout, long now, long interpl) -{ - _debug("\n***** JB_GET *****\n\n"); +enum jb_return_code jb_get (jitterbuf *jb, jb_frame *frameout, long now, long interpl) { + _debug ("\n***** JB_GET *****\n\n"); - enum jb_return_code ret = _jb_get(jb, frameout, now, interpl); + enum jb_return_code ret = _jb_get (jb, frameout, now, interpl); #if 0 - static int lastts=0; - int thists = ((ret == JB_OK) || (ret == JB_DROP)) ? frameout->ts : 0; - jb_warn("jb_get(%x,%x,%ld) = %d (%d)\n", jb, frameout, now, ret, thists); - if (thists && thists < lastts) jb_warn("XXXX timestamp roll-back!!!\n"); - lastts = thists; + static int lastts=0; + int thists = ( (ret == JB_OK) || (ret == JB_DROP)) ? frameout->ts : 0; + jb_warn ("jb_get(%x,%x,%ld) = %d (%d)\n", jb, frameout, now, ret, thists); + + if (thists && thists < lastts) jb_warn ("XXXX timestamp roll-back!!!\n"); + + lastts = thists; #endif - if (ret == JB_INTERP) - frameout->ms = jb->info.last_voice_ms; - - return ret; + + if (ret == JB_INTERP) + frameout->ms = jb->info.last_voice_ms; + + return ret; } -enum jb_return_code jb_getall(jitterbuf *jb, jb_frame *frameout) -{ - jb_frame *frame; - frame = queue_getall(jb); +enum jb_return_code jb_getall (jitterbuf *jb, jb_frame *frameout) { + jb_frame *frame; + frame = queue_getall (jb); - if (!frame) { - return JB_NOFRAME; - } + if (!frame) { + return JB_NOFRAME; + } - *frameout = *frame; - return JB_OK; + *frameout = *frame; + return JB_OK; } -enum jb_return_code jb_getinfo(jitterbuf *jb, jb_info *stats) -{ +enum jb_return_code jb_getinfo (jitterbuf *jb, jb_info *stats) { - history_get(jb); + history_get (jb); - *stats = jb->info; + *stats = jb->info; - return JB_OK; + return JB_OK; } -enum jb_return_code jb_setconf(jitterbuf *jb, jb_conf *conf) -{ - /* take selected settings from the struct */ - - jb->info.conf.max_jitterbuf = conf->max_jitterbuf; - jb->info.conf.resync_threshold = conf->resync_threshold; - jb->info.conf.max_contig_interp = conf->max_contig_interp; - - /* -1 indicates use of the default JB_TARGET_EXTRA value */ - jb->info.conf.target_extra = ( conf->target_extra == -1 ) - ? JB_TARGET_EXTRA - : conf->target_extra - ; - - /* update these to match new target_extra setting */ - jb->info.current = jb->info.conf.target_extra; - jb->info.target = jb->info.conf.target_extra; - - return JB_OK; +enum jb_return_code jb_setconf (jitterbuf *jb, jb_conf *conf) { + /* take selected settings from the struct */ + + jb->info.conf.max_jitterbuf = conf->max_jitterbuf; + jb->info.conf.resync_threshold = conf->resync_threshold; + jb->info.conf.max_contig_interp = conf->max_contig_interp; + + /* -1 indicates use of the default JB_TARGET_EXTRA value */ + jb->info.conf.target_extra = (conf->target_extra == -1) + ? JB_TARGET_EXTRA + : conf->target_extra + ; + + /* update these to match new target_extra setting */ + jb->info.current = jb->info.conf.target_extra; + jb->info.target = jb->info.conf.target_extra; + + return JB_OK; } diff --git a/sflphone-common/src/audio/mainbuffer.cpp b/sflphone-common/src/audio/mainbuffer.cpp index 4c15008b0d5d0ee2264bebc2b77052b25b87354d..4f0af63d71c1ad5c1de1ed4ad337010b3da796f8 100644 --- a/sflphone-common/src/audio/mainbuffer.cpp +++ b/sflphone-common/src/audio/mainbuffer.cpp @@ -33,22 +33,20 @@ #include "manager.h" -MainBuffer::MainBuffer() : _internalSamplingRate (8000) -{ +MainBuffer::MainBuffer() : _internalSamplingRate (8000) { mixBuffer = new SFLDataFormat[STATIC_BUFSIZE]; } -MainBuffer::~MainBuffer() -{ +MainBuffer::~MainBuffer() { - delete [] mixBuffer; mixBuffer = NULL; + delete [] mixBuffer; + mixBuffer = NULL; } -void MainBuffer::setInternalSamplingRate (int sr) -{ - // ost::MutexLock guard (_mutex); +void MainBuffer::setInternalSamplingRate (int sr) { + // ost::MutexLock guard (_mutex); if (sr != _internalSamplingRate) { @@ -56,13 +54,12 @@ void MainBuffer::setInternalSamplingRate (int sr) flushAllBuffers(); - Manager::instance().audioSamplingRateChanged(); + Manager::instance().audioSamplingRateChanged(); } } -CallIDSet* MainBuffer::getCallIDSet (CallID call_id) -{ +CallIDSet* MainBuffer::getCallIDSet (CallID call_id) { CallIDMap::iterator iter = _callIDMap.find (call_id); @@ -73,8 +70,7 @@ CallIDSet* MainBuffer::getCallIDSet (CallID call_id) } -bool MainBuffer::createCallIDSet (CallID set_id) -{ +bool MainBuffer::createCallIDSet (CallID set_id) { CallIDSet* newCallIDSet = new CallIDSet; @@ -84,15 +80,15 @@ bool MainBuffer::createCallIDSet (CallID set_id) } -bool MainBuffer::removeCallIDSet (CallID set_id) -{ +bool MainBuffer::removeCallIDSet (CallID set_id) { CallIDSet* callid_set = getCallIDSet (set_id); if (callid_set != NULL) { if (_callIDMap.erase (set_id) != 0) { - delete callid_set; callid_set = NULL; + delete callid_set; + callid_set = NULL; return true; } else { _debug ("removeCallIDSet error while removing callid set %s!", set_id.c_str()); @@ -105,16 +101,14 @@ bool MainBuffer::removeCallIDSet (CallID set_id) } -void MainBuffer::addCallIDtoSet (CallID set_id, CallID call_id) -{ +void MainBuffer::addCallIDtoSet (CallID set_id, CallID call_id) { CallIDSet* callid_set = getCallIDSet (set_id); callid_set->insert (call_id); } -void MainBuffer::removeCallIDfromSet (CallID set_id, CallID call_id) -{ +void MainBuffer::removeCallIDfromSet (CallID set_id, CallID call_id) { CallIDSet* callid_set = getCallIDSet (set_id); @@ -129,8 +123,7 @@ void MainBuffer::removeCallIDfromSet (CallID set_id, CallID call_id) } -RingBuffer* MainBuffer::getRingBuffer (CallID call_id) -{ +RingBuffer* MainBuffer::getRingBuffer (CallID call_id) { RingBufferMap::iterator iter = _ringBufferMap.find (call_id); @@ -142,8 +135,7 @@ RingBuffer* MainBuffer::getRingBuffer (CallID call_id) } -RingBuffer* MainBuffer::createRingBuffer (CallID call_id) -{ +RingBuffer* MainBuffer::createRingBuffer (CallID call_id) { RingBuffer* newRingBuffer = new RingBuffer (SIZEBUF, call_id); @@ -153,14 +145,13 @@ RingBuffer* MainBuffer::createRingBuffer (CallID call_id) } -bool MainBuffer::removeRingBuffer (CallID call_id) -{ +bool MainBuffer::removeRingBuffer (CallID call_id) { RingBuffer* ring_buffer = getRingBuffer (call_id); if (ring_buffer != NULL) { if (_ringBufferMap.erase (call_id) != 0) { - delete ring_buffer; + delete ring_buffer; return true; } else { _error ("BufferManager: Error: Fail to delete ringbuffer %s!", call_id.c_str()); @@ -173,10 +164,9 @@ bool MainBuffer::removeRingBuffer (CallID call_id) } -void MainBuffer::bindCallID (CallID call_id1, CallID call_id2) -{ +void MainBuffer::bindCallID (CallID call_id1, CallID call_id2) { - // ost::MutexLock guard (_mutex); + // ost::MutexLock guard (_mutex); RingBuffer* ring_buffer; CallIDSet* callid_set; @@ -203,27 +193,25 @@ void MainBuffer::bindCallID (CallID call_id1, CallID call_id2) } -void MainBuffer::bindHalfDuplexOut(CallID process_id, CallID call_id) -{ +void MainBuffer::bindHalfDuplexOut (CallID process_id, CallID call_id) { + + // This method is used only for active calls, if this call does not exist, do nothing + if (!getRingBuffer (call_id)) + return; - // This method is used only for active calls, if this call does not exist, do nothing - if(!getRingBuffer(call_id)) - return; - - if(!getCallIDSet(process_id)) - createCallIDSet(process_id); + if (!getCallIDSet (process_id)) + createCallIDSet (process_id); - getRingBuffer(call_id)->createReadPointer(process_id); + getRingBuffer (call_id)->createReadPointer (process_id); - addCallIDtoSet(process_id, call_id); + addCallIDtoSet (process_id, call_id); } -void MainBuffer::unBindCallID (CallID call_id1, CallID call_id2) -{ +void MainBuffer::unBindCallID (CallID call_id1, CallID call_id2) { - // ost::MutexLock guard (_mutex); + // ost::MutexLock guard (_mutex); removeCallIDfromSet (call_id1, call_id2); removeCallIDfromSet (call_id2, call_id1); @@ -246,47 +234,45 @@ void MainBuffer::unBindCallID (CallID call_id1, CallID call_id2) ringbuffer = getRingBuffer (call_id1); if (ringbuffer) { - ringbuffer->removeReadPointer (call_id2); - - if (ringbuffer->getNbReadPointer() == 0) { - removeCallIDSet (call_id1); - removeRingBuffer (call_id1); - } + ringbuffer->removeReadPointer (call_id2); + + if (ringbuffer->getNbReadPointer() == 0) { + removeCallIDSet (call_id1); + removeRingBuffer (call_id1); + } } } -void MainBuffer::unBindHalfDuplexOut(CallID process_id, CallID call_id) -{ +void MainBuffer::unBindHalfDuplexOut (CallID process_id, CallID call_id) { - removeCallIDfromSet(process_id, call_id); + removeCallIDfromSet (process_id, call_id); + + RingBuffer* ringbuffer = getRingBuffer (call_id); + + if (ringbuffer) { + ringbuffer->removeReadPointer (process_id); + + if (ringbuffer->getNbReadPointer() == 0) { + removeCallIDSet (call_id); + removeRingBuffer (call_id); + } + } else { + _debug ("Error: did not found ringbuffer %s", process_id.c_str()); + removeCallIDSet (process_id); + } - RingBuffer* ringbuffer = getRingBuffer(call_id); - if(ringbuffer) { - ringbuffer->removeReadPointer(process_id); + CallIDSet* callid_set = getCallIDSet (process_id); - if(ringbuffer->getNbReadPointer() == 0) { - removeCallIDSet(call_id); - removeRingBuffer(call_id); + if (callid_set) { + if (callid_set->empty()) + removeCallIDSet (process_id); } - } - else { - _debug("Error: did not found ringbuffer %s", process_id.c_str()); - removeCallIDSet(process_id); - } - - - CallIDSet* callid_set = getCallIDSet(process_id); - if(callid_set) { - if(callid_set->empty()) - removeCallIDSet(process_id); - } } -void MainBuffer::unBindAll (CallID call_id) -{ +void MainBuffer::unBindAll (CallID call_id) { // ost::MutexLock guard (_mutex); @@ -312,32 +298,30 @@ void MainBuffer::unBindAll (CallID call_id) } -void MainBuffer::unBindAllHalfDuplexOut(CallID process_id) -{ +void MainBuffer::unBindAllHalfDuplexOut (CallID process_id) { - CallIDSet* callid_set = getCallIDSet(process_id); + CallIDSet* callid_set = getCallIDSet (process_id); - if(!callid_set) - return; + if (!callid_set) + return; - if(callid_set->empty()) - return; + if (callid_set->empty()) + return; - CallIDSet temp_set = *callid_set; + CallIDSet temp_set = *callid_set; - CallIDSet::iterator iter_set = temp_set.begin(); + CallIDSet::iterator iter_set = temp_set.begin(); - while(iter_set != temp_set.end()) { - CallID call_id_in_set = *iter_set; - unBindCallID(process_id, call_id_in_set); + while (iter_set != temp_set.end()) { + CallID call_id_in_set = *iter_set; + unBindCallID (process_id, call_id_in_set); - iter_set++; - } + iter_set++; + } } -int MainBuffer::putData (void *buffer, int toCopy, unsigned short volume, CallID call_id) -{ +int MainBuffer::putData (void *buffer, int toCopy, unsigned short volume, CallID call_id) { RingBuffer* ring_buffer = getRingBuffer (call_id); @@ -360,8 +344,7 @@ int MainBuffer::putData (void *buffer, int toCopy, unsigned short volume, CallID } -int MainBuffer::availForPut (CallID call_id) -{ +int MainBuffer::availForPut (CallID call_id) { RingBuffer* ringbuffer = getRingBuffer (call_id); @@ -373,8 +356,7 @@ int MainBuffer::availForPut (CallID call_id) } -int MainBuffer::getData (void *buffer, int toCopy, unsigned short volume, CallID call_id) -{ +int MainBuffer::getData (void *buffer, int toCopy, unsigned short volume, CallID call_id) { CallIDSet* callid_set = getCallIDSet (call_id); @@ -397,7 +379,7 @@ int MainBuffer::getData (void *buffer, int toCopy, unsigned short volume, CallID return 0; } else { - memset(buffer, 0, nbSmplToCopy*sizeof(SFLDataFormat)); + memset (buffer, 0, nbSmplToCopy*sizeof (SFLDataFormat)); int size = 0; @@ -405,9 +387,9 @@ int MainBuffer::getData (void *buffer, int toCopy, unsigned short volume, CallID while (iter_id != callid_set->end()) { - memset(mixBuffer, 0, toCopy); + memset (mixBuffer, 0, toCopy); - size = getDataByID(mixBuffer, toCopy, volume, (CallID) (*iter_id), call_id); + size = getDataByID (mixBuffer, toCopy, volume, (CallID) (*iter_id), call_id); if (size > 0) { for (int k = 0; k < nbSmplToCopy; k++) { @@ -423,8 +405,7 @@ int MainBuffer::getData (void *buffer, int toCopy, unsigned short volume, CallID } -int MainBuffer::getDataByID (void *buffer, int toCopy, unsigned short volume, CallID call_id, CallID reader_id) -{ +int MainBuffer::getDataByID (void *buffer, int toCopy, unsigned short volume, CallID call_id, CallID reader_id) { RingBuffer* ring_buffer = getRingBuffer (call_id); @@ -436,8 +417,7 @@ int MainBuffer::getDataByID (void *buffer, int toCopy, unsigned short volume, Ca } -int MainBuffer::availForGet (CallID call_id) -{ +int MainBuffer::availForGet (CallID call_id) { CallIDSet* callid_set = getCallIDSet (call_id); @@ -464,7 +444,7 @@ int MainBuffer::availForGet (CallID call_id) int nb_bytes; CallIDSet::iterator iter_id = callid_set->begin(); - syncBuffers(call_id); + syncBuffers (call_id); for (iter_id = callid_set->begin(); iter_id != callid_set->end(); iter_id++) { nb_bytes = availForGetByID (*iter_id, call_id); @@ -479,17 +459,16 @@ int MainBuffer::availForGet (CallID call_id) } -int MainBuffer::availForGetByID (CallID call_id, CallID reader_id) -{ +int MainBuffer::availForGetByID (CallID call_id, CallID reader_id) { if ( (call_id != default_id) && (reader_id == call_id)) { - _error("MainBuffer: Error: RingBuffer has a readpointer on tiself"); + _error ("MainBuffer: Error: RingBuffer has a readpointer on tiself"); } RingBuffer* ringbuffer = getRingBuffer (call_id); if (ringbuffer == NULL) { - _error("MainBuffer: Error: RingBuffer does not exist"); + _error ("MainBuffer: Error: RingBuffer does not exist"); return 0; } else return ringbuffer->AvailForGet (reader_id); @@ -497,8 +476,7 @@ int MainBuffer::availForGetByID (CallID call_id, CallID reader_id) } -int MainBuffer::discard (int toDiscard, CallID call_id) -{ +int MainBuffer::discard (int toDiscard, CallID call_id) { CallIDSet* callid_set = getCallIDSet (call_id); @@ -529,8 +507,7 @@ int MainBuffer::discard (int toDiscard, CallID call_id) } -int MainBuffer::discardByID (int toDiscard, CallID call_id, CallID reader_id) -{ +int MainBuffer::discardByID (int toDiscard, CallID call_id, CallID reader_id) { RingBuffer* ringbuffer = getRingBuffer (call_id); @@ -543,9 +520,8 @@ int MainBuffer::discardByID (int toDiscard, CallID call_id, CallID reader_id) -void MainBuffer::flush (CallID call_id) -{ - // ost::MutexLock guard (_mutex); +void MainBuffer::flush (CallID call_id) { + // ost::MutexLock guard (_mutex); CallIDSet* callid_set = getCallIDSet (call_id); @@ -570,17 +546,15 @@ void MainBuffer::flush (CallID call_id) } -void MainBuffer::flushDefault() -{ - // ost::MutexLock guard (_mutex); +void MainBuffer::flushDefault() { + // ost::MutexLock guard (_mutex); flushByID (default_id, default_id); } -void MainBuffer::flushByID (CallID call_id, CallID reader_id) -{ +void MainBuffer::flushByID (CallID call_id, CallID reader_id) { RingBuffer* ringbuffer = getRingBuffer (call_id); @@ -589,8 +563,7 @@ void MainBuffer::flushByID (CallID call_id, CallID reader_id) } -void MainBuffer::flushAllBuffers() -{ +void MainBuffer::flushAllBuffers() { RingBufferMap::iterator iter_buffer = _ringBufferMap.begin(); @@ -602,10 +575,9 @@ void MainBuffer::flushAllBuffers() } } -void MainBuffer:: syncBuffers(CallID call_id) -{ - - CallIDSet* callid_set = getCallIDSet(call_id); +void MainBuffer:: syncBuffers (CallID call_id) { + + CallIDSet* callid_set = getCallIDSet (call_id); if (callid_set == NULL) return; @@ -629,21 +601,21 @@ void MainBuffer:: syncBuffers(CallID call_id) // compute mean nb byte in buffers for (iter_id = callid_set->begin(); iter_id != callid_set->end(); iter_id++) { nbBuffers++; - mean_nbBytes += availForGetByID (*iter_id, call_id); + mean_nbBytes += availForGetByID (*iter_id, call_id); } + mean_nbBytes = mean_nbBytes / (float) nbBuffers; - + // resync buffers in this conference according to the computed mean for (iter_id = callid_set->begin(); iter_id != callid_set->end(); iter_id++) { - if(availForGetByID (*iter_id, call_id) > (mean_nbBytes + 640)) - discardByID (640, *iter_id, call_id); + if (availForGetByID (*iter_id, call_id) > (mean_nbBytes + 640)) + discardByID (640, *iter_id, call_id); } } -void MainBuffer::stateInfo() -{ +void MainBuffer::stateInfo() { _debug ("MainBuffer: State info"); CallIDMap::iterator iter_call = _callIDMap.begin(); diff --git a/sflphone-common/src/audio/pulseaudio/audiostream.cpp b/sflphone-common/src/audio/pulseaudio/audiostream.cpp index 41acf4c26362dcce9fa509f7d2e49ba257069009..6388eff122d303e8cf94f935e2842542c9d0ecc8 100644 --- a/sflphone-common/src/audio/pulseaudio/audiostream.cpp +++ b/sflphone-common/src/audio/pulseaudio/audiostream.cpp @@ -43,8 +43,7 @@ AudioStream::AudioStream (PulseLayerType * driver, int smplrate) _volume(), _flag (PA_STREAM_AUTO_TIMING_UPDATE), _sample_spec(), - _mainloop (driver->mainloop) -{ + _mainloop (driver->mainloop) { _sample_spec.format = PA_SAMPLE_S16LE; // PA_SAMPLE_FLOAT32LE; _sample_spec.rate = smplrate; _sample_spec.channels = 1; @@ -52,24 +51,21 @@ AudioStream::AudioStream (PulseLayerType * driver, int smplrate) pa_cvolume_set (&_volume , 1 , PA_VOLUME_NORM) ; // * vol / 100 ; } -AudioStream::~AudioStream() -{ +AudioStream::~AudioStream() { disconnectStream(); } bool -AudioStream::connectStream(std::string* deviceName) -{ +AudioStream::connectStream (std::string* deviceName) { ost::MutexLock guard (_mutex); if (!_audiostream) - _audiostream = createStream (_context, deviceName); + _audiostream = createStream (_context, deviceName); return true; } -static void success_cb (pa_stream *s, int success, void *userdata) -{ +static void success_cb (pa_stream *s, int success, void *userdata) { assert (s); @@ -80,10 +76,9 @@ static void success_cb (pa_stream *s, int success, void *userdata) bool -AudioStream::drainStream (void) -{ +AudioStream::drainStream (void) { if (_audiostream) { - _info("Audio: Draining stream"); + _info ("Audio: Draining stream"); pa_operation * operation; pa_threaded_mainloop_lock (_mainloop); @@ -91,7 +86,7 @@ AudioStream::drainStream (void) if ( (operation = pa_stream_drain (_audiostream, success_cb, _mainloop))) { while (pa_operation_get_state (operation) != PA_OPERATION_DONE) { if (!_context || pa_context_get_state (_context) != PA_CONTEXT_READY || !_audiostream || pa_stream_get_state (_audiostream) != PA_STREAM_READY) { - _warn("Audio: Connection died: %s", _context ? pa_strerror (pa_context_errno (_context)) : "NULL"); + _warn ("Audio: Connection died: %s", _context ? pa_strerror (pa_context_errno (_context)) : "NULL"); pa_operation_unref (operation); break; } else { @@ -107,9 +102,8 @@ AudioStream::drainStream (void) } bool -AudioStream::disconnectStream (void) -{ - _info("Audio: Destroy audio streams"); +AudioStream::disconnectStream (void) { + _info ("Audio: Destroy audio streams"); pa_threaded_mainloop_lock (_mainloop); @@ -134,11 +128,10 @@ AudioStream::disconnectStream (void) void -AudioStream::stream_state_callback (pa_stream* s, void* user_data) -{ +AudioStream::stream_state_callback (pa_stream* s, void* user_data) { pa_threaded_mainloop *m; - _info("Audio: The state of the stream changed"); + _info ("Audio: The state of the stream changed"); assert (s); char str[PA_SAMPLE_SPEC_SNPRINT_MAX]; @@ -149,7 +142,7 @@ AudioStream::stream_state_callback (pa_stream* s, void* user_data) switch (pa_stream_get_state (s)) { case PA_STREAM_CREATING: - _info("Audio: Stream is creating..."); + _info ("Audio: Stream is creating..."); break; case PA_STREAM_TERMINATED: @@ -158,14 +151,14 @@ AudioStream::stream_state_callback (pa_stream* s, void* user_data) case PA_STREAM_READY: _info ("Audio: Stream successfully created, connected to %s", pa_stream_get_device_name (s)); - // pa_buffer_attr *buffattr = (pa_buffer_attr *)pa_xmalloc (sizeof(pa_buffer_attr)); - _debug("Audio: maxlength %u", pa_stream_get_buffer_attr(s)->maxlength); - _debug("Audio: tlength %u", pa_stream_get_buffer_attr(s)->tlength); - _debug("Audio: prebug %u", pa_stream_get_buffer_attr(s)->prebuf); - _debug("Audio: minreq %u", pa_stream_get_buffer_attr(s)->minreq); - _debug("Audio: fragsize %u", pa_stream_get_buffer_attr(s)->fragsize); - _debug("Audio: samplespec %s", pa_sample_spec_snprint(str, sizeof(str), pa_stream_get_sample_spec(s))); - // pa_xfree (buffattr); + // pa_buffer_attr *buffattr = (pa_buffer_attr *)pa_xmalloc (sizeof(pa_buffer_attr)); + _debug ("Audio: maxlength %u", pa_stream_get_buffer_attr (s)->maxlength); + _debug ("Audio: tlength %u", pa_stream_get_buffer_attr (s)->tlength); + _debug ("Audio: prebug %u", pa_stream_get_buffer_attr (s)->prebuf); + _debug ("Audio: minreq %u", pa_stream_get_buffer_attr (s)->minreq); + _debug ("Audio: fragsize %u", pa_stream_get_buffer_attr (s)->fragsize); + _debug ("Audio: samplespec %s", pa_sample_spec_snprint (str, sizeof (str), pa_stream_get_sample_spec (s))); + // pa_xfree (buffattr); break; case PA_STREAM_UNCONNECTED: @@ -175,15 +168,14 @@ AudioStream::stream_state_callback (pa_stream* s, void* user_data) case PA_STREAM_FAILED: default: - _warn("Audio: Error - Sink/Source doesn't exists: %s" , pa_strerror (pa_context_errno (pa_stream_get_context (s)))); + _warn ("Audio: Error - Sink/Source doesn't exists: %s" , pa_strerror (pa_context_errno (pa_stream_get_context (s)))); exit (0); break; } } pa_stream_state_t -AudioStream::getStreamState (void) -{ +AudioStream::getStreamState (void) { ost::MutexLock guard (_mutex); return pa_stream_get_state (_audiostream); @@ -192,8 +184,7 @@ AudioStream::getStreamState (void) pa_stream* -AudioStream::createStream (pa_context* c, std::string *deviceName) -{ +AudioStream::createStream (pa_context* c, std::string *deviceName) { ost::MutexLock guard (_mutex); pa_stream* s; @@ -201,7 +192,7 @@ AudioStream::createStream (pa_context* c, std::string *deviceName) assert (pa_sample_spec_valid (&_sample_spec)); assert (pa_channel_map_valid (&channel_map)); - _info("Audio: Create pulseaudio stream"); + _info ("Audio: Create pulseaudio stream"); pa_buffer_attr* attributes = (pa_buffer_attr*) malloc (sizeof (pa_buffer_attr)); @@ -216,52 +207,53 @@ AudioStream::createStream (pa_context* c, std::string *deviceName) attributes->maxlength = pa_usec_to_bytes (80 * PA_USEC_PER_MSEC, &_sample_spec); // -1; attributes->tlength = pa_usec_to_bytes (40 * PA_USEC_PER_MSEC, &_sample_spec); attributes->prebuf = 0; - attributes->fragsize = pa_usec_to_bytes (20 * PA_USEC_PER_MSEC, &_sample_spec); + attributes->fragsize = pa_usec_to_bytes (20 * PA_USEC_PER_MSEC, &_sample_spec); attributes->minreq = (uint32_t) -1; - - pa_threaded_mainloop_lock(_mainloop); - if(deviceName) - pa_stream_connect_playback (s , deviceName->c_str(), attributes, (pa_stream_flags_t)(PA_STREAM_ADJUST_LATENCY|PA_STREAM_AUTO_TIMING_UPDATE), NULL, NULL); - else - pa_stream_connect_playback (s , NULL, attributes, (pa_stream_flags_t)(PA_STREAM_ADJUST_LATENCY|PA_STREAM_AUTO_TIMING_UPDATE), NULL, NULL); + pa_threaded_mainloop_lock (_mainloop); + + if (deviceName) + pa_stream_connect_playback (s , deviceName->c_str(), attributes, (pa_stream_flags_t) (PA_STREAM_ADJUST_LATENCY|PA_STREAM_AUTO_TIMING_UPDATE), NULL, NULL); + else + pa_stream_connect_playback (s , NULL, attributes, (pa_stream_flags_t) (PA_STREAM_ADJUST_LATENCY|PA_STREAM_AUTO_TIMING_UPDATE), NULL, NULL); - pa_threaded_mainloop_unlock(_mainloop); + pa_threaded_mainloop_unlock (_mainloop); } else if (_streamType == CAPTURE_STREAM) { - attributes->maxlength = pa_usec_to_bytes (80 * PA_USEC_PER_MSEC, &_sample_spec);// (uint32_t) -1; - attributes->tlength = pa_usec_to_bytes (40 * PA_USEC_PER_MSEC, &_sample_spec);// pa_usec_to_bytes (20 * PA_USEC_PER_MSEC, &_sample_spec); - attributes->prebuf = 0; + attributes->maxlength = pa_usec_to_bytes (80 * PA_USEC_PER_MSEC, &_sample_spec);// (uint32_t) -1; + attributes->tlength = pa_usec_to_bytes (40 * PA_USEC_PER_MSEC, &_sample_spec);// pa_usec_to_bytes (20 * PA_USEC_PER_MSEC, &_sample_spec); + attributes->prebuf = 0; attributes->fragsize = pa_usec_to_bytes (20 * PA_USEC_PER_MSEC, &_sample_spec); // pa_usec_to_bytes (20 * PA_USEC_PER_MSEC, &_sample_spec); - attributes->minreq = (uint32_t) -1; + attributes->minreq = (uint32_t) -1; + + pa_threaded_mainloop_lock (_mainloop); - pa_threaded_mainloop_lock(_mainloop); + if (deviceName) + pa_stream_connect_record (s, deviceName->c_str(), attributes, (pa_stream_flags_t) (PA_STREAM_ADJUST_LATENCY|PA_STREAM_AUTO_TIMING_UPDATE)); + else + pa_stream_connect_record (s, NULL, attributes, (pa_stream_flags_t) (PA_STREAM_ADJUST_LATENCY|PA_STREAM_AUTO_TIMING_UPDATE)); - if(deviceName) - pa_stream_connect_record (s, deviceName->c_str(), attributes, (pa_stream_flags_t) (PA_STREAM_ADJUST_LATENCY|PA_STREAM_AUTO_TIMING_UPDATE)); - else - pa_stream_connect_record (s, NULL, attributes, (pa_stream_flags_t) (PA_STREAM_ADJUST_LATENCY|PA_STREAM_AUTO_TIMING_UPDATE)); + pa_threaded_mainloop_unlock (_mainloop); - pa_threaded_mainloop_unlock(_mainloop); - } else if (_streamType == RINGTONE_STREAM) { - attributes->maxlength = pa_usec_to_bytes (80 * PA_USEC_PER_MSEC, &_sample_spec);; - attributes->tlength = pa_usec_to_bytes(40 * PA_USEC_PER_MSEC, &_sample_spec); - attributes->prebuf = 0; - attributes->fragsize = pa_usec_to_bytes(20 * PA_USEC_PER_MSEC, &_sample_spec); - attributes->minreq = (uint32_t) -1; + attributes->maxlength = pa_usec_to_bytes (80 * PA_USEC_PER_MSEC, &_sample_spec);; + attributes->tlength = pa_usec_to_bytes (40 * PA_USEC_PER_MSEC, &_sample_spec); + attributes->prebuf = 0; + attributes->fragsize = pa_usec_to_bytes (20 * PA_USEC_PER_MSEC, &_sample_spec); + attributes->minreq = (uint32_t) -1; - pa_threaded_mainloop_lock(_mainloop); - if(deviceName) - pa_stream_connect_playback(s, deviceName->c_str(), attributes, (pa_stream_flags_t) (PA_STREAM_ADJUST_LATENCY|PA_STREAM_AUTO_TIMING_UPDATE), NULL, NULL); - else - pa_stream_connect_playback(s, NULL, attributes, (pa_stream_flags_t) (PA_STREAM_ADJUST_LATENCY), NULL, NULL); + pa_threaded_mainloop_lock (_mainloop); + + if (deviceName) + pa_stream_connect_playback (s, deviceName->c_str(), attributes, (pa_stream_flags_t) (PA_STREAM_ADJUST_LATENCY|PA_STREAM_AUTO_TIMING_UPDATE), NULL, NULL); + else + pa_stream_connect_playback (s, NULL, attributes, (pa_stream_flags_t) (PA_STREAM_ADJUST_LATENCY), NULL, NULL); - pa_threaded_mainloop_unlock(_mainloop); + pa_threaded_mainloop_unlock (_mainloop); } else if (_streamType == UPLOAD_STREAM) { pa_stream_connect_upload (s , 1024); diff --git a/sflphone-common/src/audio/pulseaudio/pulselayer.cpp b/sflphone-common/src/audio/pulseaudio/pulselayer.cpp old mode 100755 new mode 100644 index 667f0cf2728e4910298733b49692da4df4f6788f..068ac26b4849b4ab8fe72d10692eb1a531338e1a --- a/sflphone-common/src/audio/pulseaudio/pulselayer.cpp +++ b/sflphone-common/src/audio/pulseaudio/pulselayer.cpp @@ -49,178 +49,177 @@ static void capture_callback (pa_stream* s, size_t bytes, void* userdata) { assert (s && bytes); assert (bytes > 0); static_cast<PulseLayer*> (userdata)->processCaptureData(); - + } static void ringtone_callback (pa_stream* s, size_t bytes, void* userdata) { - assert(s && bytes); - assert(bytes > 0); + assert (s && bytes); + assert (bytes > 0); static_cast<PulseLayer*> (userdata)->processRingtoneData(); } -static void stream_moved_callback(pa_stream *s, void *userdata) { +static void stream_moved_callback (pa_stream *s, void *userdata) { - int streamIndex = pa_stream_get_index(s); - int deviceIndex = pa_stream_get_device_index(s); + int streamIndex = pa_stream_get_index (s); + int deviceIndex = pa_stream_get_device_index (s); - _debug("stream_moved_callback: stream %d to %d", pa_stream_get_index(s), pa_stream_get_device_index(s)); + _debug ("stream_moved_callback: stream %d to %d", pa_stream_get_index (s), pa_stream_get_device_index (s)); } -static void pa_success_callback(pa_context *c, int success, void *userdata) { +static void pa_success_callback (pa_context *c, int success, void *userdata) { - _debug("Audio: Success callback"); + _debug ("Audio: Success callback"); } -static void latency_update_callback(pa_stream *p, void *userdata) { +static void latency_update_callback (pa_stream *p, void *userdata) { pa_usec_t r_usec; - pa_stream_get_latency (p, &r_usec, NULL); + pa_stream_get_latency (p, &r_usec, NULL); + + _debug ("Audio: Stream letency update %0.0f ms for device %s", (float) r_usec/1000, pa_stream_get_device_name (p)); + _debug ("Audio: maxlength %u", pa_stream_get_buffer_attr (p)->maxlength); + _debug ("Audio: tlength %u", pa_stream_get_buffer_attr (p)->tlength); + _debug ("Audio: prebuf %u", pa_stream_get_buffer_attr (p)->prebuf); + _debug ("Audio: minreq %u", pa_stream_get_buffer_attr (p)->minreq); + _debug ("Audio: fragsize %u", pa_stream_get_buffer_attr (p)->fragsize); - _debug("Audio: Stream letency update %0.0f ms for device %s", (float)r_usec/1000, pa_stream_get_device_name(p)); - _debug("Audio: maxlength %u", pa_stream_get_buffer_attr(p)->maxlength); - _debug("Audio: tlength %u", pa_stream_get_buffer_attr(p)->tlength); - _debug("Audio: prebuf %u", pa_stream_get_buffer_attr(p)->prebuf); - _debug("Audio: minreq %u", pa_stream_get_buffer_attr(p)->minreq); - _debug("Audio: fragsize %u", pa_stream_get_buffer_attr(p)->fragsize); - } -static void sink_input_info_callback(pa_context *c, const pa_sink_info *i, int eol, void *userdata) { - char s[PA_SAMPLE_SPEC_SNPRINT_MAX], cv[PA_CVOLUME_SNPRINT_MAX], cm[PA_CHANNEL_MAP_SNPRINT_MAX]; - - if(!eol) { - - printf("Sink %u\n" - " Name: %s\n" - " Driver: %s\n" - " Description: %s\n" - " Sample Specification: %s\n" - " Channel Map: %s\n" - " Owner Module: %u\n" - " Volume: %s\n" - " Monitor Source: %u\n" - " Latency: %0.0f usec\n" - " Flags: %s%s%s\n", - i->index, - i->name, - i->driver, - i->description, - pa_sample_spec_snprint(s, sizeof(s), &i->sample_spec), - pa_channel_map_snprint(cm, sizeof(cm), &i->channel_map), - i->owner_module, - i->mute ? "muted" : pa_cvolume_snprint(cv, sizeof(cv), &i->volume), - i->monitor_source, - (double) i->latency, - i->flags & PA_SINK_HW_VOLUME_CTRL ? "HW_VOLUME_CTRL " : "", - i->flags & PA_SINK_LATENCY ? "LATENCY " : "", - i->flags & PA_SINK_HARDWARE ? "HARDWARE" : ""); - - std::string deviceName(i->name); - ((PulseLayer *)userdata)->getSinkList()->push_back(deviceName); - - } +static void sink_input_info_callback (pa_context *c, const pa_sink_info *i, int eol, void *userdata) { + char s[PA_SAMPLE_SPEC_SNPRINT_MAX], cv[PA_CVOLUME_SNPRINT_MAX], cm[PA_CHANNEL_MAP_SNPRINT_MAX]; + + if (!eol) { + + printf ("Sink %u\n" + " Name: %s\n" + " Driver: %s\n" + " Description: %s\n" + " Sample Specification: %s\n" + " Channel Map: %s\n" + " Owner Module: %u\n" + " Volume: %s\n" + " Monitor Source: %u\n" + " Latency: %0.0f usec\n" + " Flags: %s%s%s\n", + i->index, + i->name, + i->driver, + i->description, + pa_sample_spec_snprint (s, sizeof (s), &i->sample_spec), + pa_channel_map_snprint (cm, sizeof (cm), &i->channel_map), + i->owner_module, + i->mute ? "muted" : pa_cvolume_snprint (cv, sizeof (cv), &i->volume), + i->monitor_source, + (double) i->latency, + i->flags & PA_SINK_HW_VOLUME_CTRL ? "HW_VOLUME_CTRL " : "", + i->flags & PA_SINK_LATENCY ? "LATENCY " : "", + i->flags & PA_SINK_HARDWARE ? "HARDWARE" : ""); + + std::string deviceName (i->name); + ( (PulseLayer *) userdata)->getSinkList()->push_back (deviceName); + + } } -static void source_input_info_callback(pa_context *c, const pa_source_info *i, int eol, void *userdata) { +static void source_input_info_callback (pa_context *c, const pa_source_info *i, int eol, void *userdata) { char s[PA_SAMPLE_SPEC_SNPRINT_MAX], cv[PA_CVOLUME_SNPRINT_MAX], cm[PA_CHANNEL_MAP_SNPRINT_MAX]; - if(!eol) { - - printf("Sink %u\n" - " Name: %s\n" - " Driver: %s\n" - " Description: %s\n" - " Sample Specification: %s\n" - " Channel Map: %s\n" - " Owner Module: %u\n" - " Volume: %s\n" - " Monitor if Sink: %u\n" - " Latency: %0.0f usec\n" - " Flags: %s%s%s\n", - i->index, - i->name, - i->driver, - i->description, - pa_sample_spec_snprint(s, sizeof(s), &i->sample_spec), - pa_channel_map_snprint(cm, sizeof(cm), &i->channel_map), - i->owner_module, - i->mute ? "muted" : pa_cvolume_snprint(cv, sizeof(cv), &i->volume), - i->monitor_of_sink, - (double) i->latency, - i->flags & PA_SOURCE_HW_VOLUME_CTRL ? "HW_VOLUME_CTRL " : "", - i->flags & PA_SOURCE_LATENCY ? "LATENCY " : "", - i->flags & PA_SOURCE_HARDWARE ? "HARDWARE" : ""); - - std::string deviceName(i->name); - ((PulseLayer *)userdata)->getSourceList()->push_back(deviceName); - - } + if (!eol) { + + printf ("Sink %u\n" + " Name: %s\n" + " Driver: %s\n" + " Description: %s\n" + " Sample Specification: %s\n" + " Channel Map: %s\n" + " Owner Module: %u\n" + " Volume: %s\n" + " Monitor if Sink: %u\n" + " Latency: %0.0f usec\n" + " Flags: %s%s%s\n", + i->index, + i->name, + i->driver, + i->description, + pa_sample_spec_snprint (s, sizeof (s), &i->sample_spec), + pa_channel_map_snprint (cm, sizeof (cm), &i->channel_map), + i->owner_module, + i->mute ? "muted" : pa_cvolume_snprint (cv, sizeof (cv), &i->volume), + i->monitor_of_sink, + (double) i->latency, + i->flags & PA_SOURCE_HW_VOLUME_CTRL ? "HW_VOLUME_CTRL " : "", + i->flags & PA_SOURCE_LATENCY ? "LATENCY " : "", + i->flags & PA_SOURCE_HARDWARE ? "HARDWARE" : ""); + + std::string deviceName (i->name); + ( (PulseLayer *) userdata)->getSourceList()->push_back (deviceName); + + } } -static void context_changed_callback(pa_context* c, pa_subscription_event_type_t t, uint32_t idx, void* userdata) -{ +static void context_changed_callback (pa_context* c, pa_subscription_event_type_t t, uint32_t idx, void* userdata) { + + switch (t) { + + case PA_SUBSCRIPTION_EVENT_SINK: + _debug ("Audio: PA_SUBSCRIPTION_EVENT_SINK"); + ( (PulseLayer *) userdata)->getSinkList()->clear(); + pa_context_get_sink_info_list (c, sink_input_info_callback, userdata); + break; + case PA_SUBSCRIPTION_EVENT_SOURCE: + _debug ("Audio: PA_SUBSCRIPTION_EVENT_SOURCE"); + ( (PulseLayer *) userdata)->getSourceList()->clear(); + pa_context_get_source_info_list (c, source_input_info_callback, userdata); + break; + case PA_SUBSCRIPTION_EVENT_SINK_INPUT: + _debug ("Audio: PA_SUBSCRIPTION_EVENT_SINK_INPUT"); + break; + case PA_SUBSCRIPTION_EVENT_SOURCE_OUTPUT: + _debug ("Audio: PA_SUBSCRIPTION_EVENT_SOURCE_OUTPUT"); + break; + case PA_SUBSCRIPTION_EVENT_MODULE: + _debug ("Audio: PA_SUBSCRIPTION_EVENT_MODULE"); + break; + case PA_SUBSCRIPTION_EVENT_CLIENT: + _debug ("Audio: PA_SUBSCRIPTION_EVENT_CLIENT"); + break; + case PA_SUBSCRIPTION_EVENT_SAMPLE_CACHE: + _debug ("Audio: PA_SUBSCRIPTION_EVENT_SAMPLE_CACHE"); + break; + case PA_SUBSCRIPTION_EVENT_SERVER: + _debug ("Audio: PA_SUBSCRIPTION_EVENT_SERVER"); + break; + case PA_SUBSCRIPTION_EVENT_CARD: + _debug ("Audio: PA_SUBSCRIPTION_EVENT_CARD"); + break; + case PA_SUBSCRIPTION_EVENT_FACILITY_MASK: + _debug ("Audio: PA_SUBSCRIPTION_EVENT_FACILITY_MASK"); + break; + case PA_SUBSCRIPTION_EVENT_CHANGE: + _debug ("Audio: PA_SUBSCRIPTION_EVENT_CHANGE"); + break; + case PA_SUBSCRIPTION_EVENT_REMOVE: + _debug ("Audio: PA_SUBSCRIPTION_EVENT_REMOVE"); + ( (PulseLayer *) userdata)->getSinkList()->clear(); + ( (PulseLayer *) userdata)->getSourceList()->clear(); + pa_context_get_sink_info_list (c, sink_input_info_callback, userdata); + pa_context_get_source_info_list (c, source_input_info_callback, userdata); + break; + case PA_SUBSCRIPTION_EVENT_TYPE_MASK: + _debug ("Audio: PA_SUBSCRIPTION_EVENT_TYPE_MASK"); + break; + default: + _debug ("Audio: Unknown event type"); + + } - switch(t) { - - case PA_SUBSCRIPTION_EVENT_SINK: - _debug("Audio: PA_SUBSCRIPTION_EVENT_SINK"); - ((PulseLayer *)userdata)->getSinkList()->clear(); - pa_context_get_sink_info_list(c, sink_input_info_callback, userdata); - break; - case PA_SUBSCRIPTION_EVENT_SOURCE: - _debug("Audio: PA_SUBSCRIPTION_EVENT_SOURCE"); - ((PulseLayer *)userdata)->getSourceList()->clear(); - pa_context_get_source_info_list(c, source_input_info_callback, userdata); - break; - case PA_SUBSCRIPTION_EVENT_SINK_INPUT: - _debug("Audio: PA_SUBSCRIPTION_EVENT_SINK_INPUT"); - break; - case PA_SUBSCRIPTION_EVENT_SOURCE_OUTPUT: - _debug("Audio: PA_SUBSCRIPTION_EVENT_SOURCE_OUTPUT"); - break; - case PA_SUBSCRIPTION_EVENT_MODULE: - _debug("Audio: PA_SUBSCRIPTION_EVENT_MODULE"); - break; - case PA_SUBSCRIPTION_EVENT_CLIENT: - _debug("Audio: PA_SUBSCRIPTION_EVENT_CLIENT"); - break; - case PA_SUBSCRIPTION_EVENT_SAMPLE_CACHE: - _debug("Audio: PA_SUBSCRIPTION_EVENT_SAMPLE_CACHE"); - break; - case PA_SUBSCRIPTION_EVENT_SERVER: - _debug("Audio: PA_SUBSCRIPTION_EVENT_SERVER"); - break; - case PA_SUBSCRIPTION_EVENT_CARD: - _debug("Audio: PA_SUBSCRIPTION_EVENT_CARD"); - break; - case PA_SUBSCRIPTION_EVENT_FACILITY_MASK: - _debug("Audio: PA_SUBSCRIPTION_EVENT_FACILITY_MASK"); - break; - case PA_SUBSCRIPTION_EVENT_CHANGE: - _debug("Audio: PA_SUBSCRIPTION_EVENT_CHANGE"); - break; - case PA_SUBSCRIPTION_EVENT_REMOVE: - _debug("Audio: PA_SUBSCRIPTION_EVENT_REMOVE"); - ((PulseLayer *)userdata)->getSinkList()->clear(); - ((PulseLayer *)userdata)->getSourceList()->clear(); - pa_context_get_sink_info_list(c, sink_input_info_callback, userdata); - pa_context_get_source_info_list(c, source_input_info_callback, userdata); - break; - case PA_SUBSCRIPTION_EVENT_TYPE_MASK: - _debug("Audio: PA_SUBSCRIPTION_EVENT_TYPE_MASK"); - break; - default: - _debug("Audio: Unknown event type"); - - } - } /* @@ -231,15 +230,13 @@ static void stream_suspended_callback (pa_stream *s UNUSED, void *userdata UNUSE */ -static void playback_underflow_callback (pa_stream* s, void* userdata UNUSED) -{ +static void playback_underflow_callback (pa_stream* s, void* userdata UNUSED) { // _debug ("Audio: Buffer Underflow"); // pa_stream_trigger (s, NULL, NULL); } -static void playback_overflow_callback (pa_stream* s UNUSED, void* userdata UNUSED) -{ +static void playback_overflow_callback (pa_stream* s UNUSED, void* userdata UNUSED) { // _debug ("Audio: Buffer OverFlow"); } @@ -249,12 +246,11 @@ PulseLayer::PulseLayer (ManagerImpl* manager) : AudioLayer (manager , PULSEAUDIO) , context (NULL) , m (NULL) - , playback(NULL) - , record(NULL) - , ringtone(NULL) -{ + , playback (NULL) + , record (NULL) + , ringtone (NULL) { _urgentRingBuffer.createReadPointer(); - + is_started = false; AudioLayer::_echocancelstate = true; @@ -271,8 +267,7 @@ PulseLayer::PulseLayer (ManagerImpl* manager) } // Destructor -PulseLayer::~PulseLayer (void) -{ +PulseLayer::~PulseLayer (void) { closeLayer (); if (_converter) { @@ -282,7 +277,7 @@ PulseLayer::~PulseLayer (void) delete AudioLayer::_echoCancel; AudioLayer::_echoCancel = NULL; - + delete AudioLayer::_echoCanceller; AudioLayer::_echoCanceller = NULL; @@ -304,27 +299,25 @@ PulseLayer::~PulseLayer (void) } void -PulseLayer::openLayer (void) -{ +PulseLayer::openLayer (void) { if (!is_started) { - _info("Audio: Open Pulseaudio layer"); + _info ("Audio: Open Pulseaudio layer"); - connectPulseAudioServer(); + connectPulseAudioServer(); - is_started = true; + is_started = true; } } bool -PulseLayer::closeLayer (void) -{ - _info("Audio: Close Pulseaudio layer"); +PulseLayer::closeLayer (void) { + _info ("Audio: Close Pulseaudio layer"); disconnectAudioStream(); - + if (m) { pa_threaded_mainloop_stop (m); } @@ -345,64 +338,64 @@ PulseLayer::closeLayer (void) } void -PulseLayer::connectPulseAudioServer (void) -{ - _info("Audio: Connect to Pulseaudio server"); +PulseLayer::connectPulseAudioServer (void) { + _info ("Audio: Connect to Pulseaudio server"); setenv ("PULSE_PROP_media.role", "phone", 1); pa_context_flags_t flag = PA_CONTEXT_NOAUTOSPAWN ; if (!m) { - - // Instantiate a mainloop - _info("Audio: Creating PulseAudio mainloop"); - if (!(m = pa_threaded_mainloop_new())) - _warn ("Audio: Error: while creating pulseaudio mainloop"); - - assert(m); + + // Instantiate a mainloop + _info ("Audio: Creating PulseAudio mainloop"); + + if (! (m = pa_threaded_mainloop_new())) + _warn ("Audio: Error: while creating pulseaudio mainloop"); + + assert (m); } - if(!context) { + if (!context) { // Instantiate a context if (! (context = pa_context_new (pa_threaded_mainloop_get_api (m) , "SFLphone"))) - _warn ("Audio: Error: while creating pulseaudio context"); + _warn ("Audio: Error: while creating pulseaudio context"); - assert(context); + assert (context); } // set context state callback before starting the mainloop pa_context_set_state_callback (context, context_state_callback, this); - _info("Audio: Connect the context to the server"); + _info ("Audio: Connect the context to the server"); + if (pa_context_connect (context, NULL , flag , NULL) < 0) { - _warn("Audio: Error: Could not connect context to the server"); + _warn ("Audio: Error: Could not connect context to the server"); } // Lock the loop before starting it pa_threaded_mainloop_lock (m); if (pa_threaded_mainloop_start (m) < 0) - _warn("Audio: Error: Failed to start pulseaudio mainloop"); + _warn ("Audio: Error: Failed to start pulseaudio mainloop"); + + pa_threaded_mainloop_wait (m); + - pa_threaded_mainloop_wait(m); - - // Run the main loop if (pa_context_get_state (context) != PA_CONTEXT_READY) { - _warn("Audio: Error: connecting to pulse audio server"); + _warn ("Audio: Error: connecting to pulse audio server"); } pa_threaded_mainloop_unlock (m); - _info("Audio: Context creation done"); + _info ("Audio: Context creation done"); } -void PulseLayer::context_state_callback (pa_context* c, void* user_data) -{ - _info("Audio: The state of the context changed"); +void PulseLayer::context_state_callback (pa_context* c, void* user_data) { + _info ("Audio: The state of the context changed"); PulseLayer* pulse = (PulseLayer*) user_data; assert (c && pulse->m); @@ -418,11 +411,11 @@ void PulseLayer::context_state_callback (pa_context* c, void* user_data) case PA_CONTEXT_READY: _debug ("Audio: Connection to PulseAudio server established"); - pa_threaded_mainloop_signal(pulse->m, 0); - pa_context_subscribe (c, (pa_subscription_mask_t)(PA_SUBSCRIPTION_MASK_SINK| - PA_SUBSCRIPTION_MASK_SOURCE), NULL, pulse); - pa_context_set_subscribe_callback (c, context_changed_callback, pulse); - pulse->updateSinkList(); + pa_threaded_mainloop_signal (pulse->m, 0); + pa_context_subscribe (c, (pa_subscription_mask_t) (PA_SUBSCRIPTION_MASK_SINK| + PA_SUBSCRIPTION_MASK_SOURCE), NULL, pulse); + pa_context_set_subscribe_callback (c, context_changed_callback, pulse); + pulse->updateSinkList(); break; case PA_CONTEXT_TERMINATED: @@ -432,15 +425,14 @@ void PulseLayer::context_state_callback (pa_context* c, void* user_data) case PA_CONTEXT_FAILED: default: - _warn("Audio: Error : %s" , pa_strerror (pa_context_errno (c))); + _warn ("Audio: Error : %s" , pa_strerror (pa_context_errno (c))); pulse->disconnectAudioStream(); exit (0); break; } } -bool PulseLayer::openDevice (int indexIn UNUSED, int indexOut UNUSED, int indexRing UNUSED, int sampleRate, int frameSize , int stream UNUSED, std::string plugin UNUSED) -{ +bool PulseLayer::openDevice (int indexIn UNUSED, int indexOut UNUSED, int indexRing UNUSED, int sampleRate, int frameSize , int stream UNUSED, std::string plugin UNUSED) { _audioSampleRate = sampleRate; _frameSize = frameSize; @@ -450,74 +442,73 @@ bool PulseLayer::openDevice (int indexIn UNUSED, int indexOut UNUSED, int indexR _converter = new SamplerateConverter (_audioSampleRate, 1000); // Instantiate the algorithm - AudioLayer::_echoCancel = new EchoCancel(_audioSampleRate, _frameSize); - AudioLayer::_echoCanceller = new AudioProcessing(static_cast<Algorithm *>(_echoCancel)); + AudioLayer::_echoCancel = new EchoCancel (_audioSampleRate, _frameSize); + AudioLayer::_echoCanceller = new AudioProcessing (static_cast<Algorithm *> (_echoCancel)); AudioLayer::_dcblocker = new DcBlocker(); - AudioLayer::_audiofilter = new AudioProcessing(static_cast<Algorithm *>(_dcblocker)); + AudioLayer::_audiofilter = new AudioProcessing (static_cast<Algorithm *> (_dcblocker)); return true; } -void PulseLayer::updateSinkList(void) { +void PulseLayer::updateSinkList (void) { - _debug("Audio: Update sink list"); + _debug ("Audio: Update sink list"); - getSinkList()->clear(); + getSinkList()->clear(); - pa_context_get_sink_info_list(context, sink_input_info_callback, this); + pa_context_get_sink_info_list (context, sink_input_info_callback, this); } -void PulseLayer::updateSourceList(void) { - _debug("Audio: Update source list"); +void PulseLayer::updateSourceList (void) { + _debug ("Audio: Update source list"); - getSourceList()->clear(); + getSourceList()->clear(); - pa_context_get_source_info_list(context, source_input_info_callback, this); + pa_context_get_source_info_list (context, source_input_info_callback, this); } -bool PulseLayer::inSinkList(std::string deviceName) { - // _debug("Audio: in device list %s", deviceName.c_str()); +bool PulseLayer::inSinkList (std::string deviceName) { + // _debug("Audio: in device list %s", deviceName.c_str()); - DeviceList::iterator iter = _sinkList.begin(); + DeviceList::iterator iter = _sinkList.begin(); - // _debug("_deviceList.size() %d", _sinkList.size()); + // _debug("_deviceList.size() %d", _sinkList.size()); - while(iter != _sinkList.end()) { - if (*iter == deviceName) { - // _debug("device name in list: %s", (*iter).c_str()); - return true; - } + while (iter != _sinkList.end()) { + if (*iter == deviceName) { + // _debug("device name in list: %s", (*iter).c_str()); + return true; + } - iter++; - } + iter++; + } - return false; + return false; } -bool PulseLayer::inSourceList(std::string deviceName) { - - DeviceList::iterator iter = _sourceList.begin(); +bool PulseLayer::inSourceList (std::string deviceName) { - while(iter != _sourceList.end()) { + DeviceList::iterator iter = _sourceList.begin(); - if(*iter == deviceName) { - return true; - } + while (iter != _sourceList.end()) { - iter++; - } + if (*iter == deviceName) { + return true; + } - return false; + iter++; + } + + return false; } -bool PulseLayer::createStreams (pa_context* c) -{ - _info("Audio: Create streams"); +bool PulseLayer::createStreams (pa_context* c) { + _info ("Audio: Create streams"); // _debug("Device list size %d", getDevicelist()->size()); @@ -525,9 +516,9 @@ bool PulseLayer::createStreams (pa_context* c) std::string recordDevice = _manager->audioPreference.getDeviceRecord(); std::string ringtoneDevice = _manager->audioPreference.getDeviceRingtone(); - _debug("Audio: Device stored in config for playback: %s", playbackDevice.c_str()); - _debug("Audio: Device stored in config for ringtone: %s", recordDevice.c_str()); - _debug("Audio: Device stored in config for record: %s", ringtoneDevice.c_str()); + _debug ("Audio: Device stored in config for playback: %s", playbackDevice.c_str()); + _debug ("Audio: Device stored in config for ringtone: %s", recordDevice.c_str()); + _debug ("Audio: Device stored in config for record: %s", ringtoneDevice.c_str()); PulseLayerType * playbackParam = new PulseLayerType(); playbackParam->context = c; @@ -535,20 +526,21 @@ bool PulseLayer::createStreams (pa_context* c) playbackParam->description = PLAYBACK_STREAM_NAME; playbackParam->volume = _manager->getSpkrVolume(); playbackParam->mainloop = m; - - playback = new AudioStream(playbackParam, _audioSampleRate); - if(inSinkList(playbackDevice)) { - playback->connectStream(&playbackDevice); - } - else { - playback->connectStream(NULL); + + playback = new AudioStream (playbackParam, _audioSampleRate); + + if (inSinkList (playbackDevice)) { + playback->connectStream (&playbackDevice); + } else { + playback->connectStream (NULL); } + pa_stream_set_write_callback (playback->pulseStream(), playback_callback, this); pa_stream_set_overflow_callback (playback->pulseStream(), playback_overflow_callback, this); pa_stream_set_underflow_callback (playback->pulseStream(), playback_underflow_callback, this); // pa_stream_set_suspended_callback(playback->pulseStream(), stream_suspended_callback, this); - pa_stream_set_moved_callback(playback->pulseStream(), stream_moved_callback, this); - pa_stream_set_latency_update_callback(playback->pulseStream(), latency_update_callback, this); + pa_stream_set_moved_callback (playback->pulseStream(), stream_moved_callback, this); + pa_stream_set_latency_update_callback (playback->pulseStream(), latency_update_callback, this); delete playbackParam; PulseLayerType * recordParam = new PulseLayerType(); @@ -559,18 +551,19 @@ bool PulseLayer::createStreams (pa_context* c) recordParam->mainloop = m; record = new AudioStream (recordParam, _audioSampleRate); - if(inSourceList(recordDevice)) { - record->connectStream(&recordDevice); + + if (inSourceList (recordDevice)) { + record->connectStream (&recordDevice); + } else { + record->connectStream (NULL); } - else { - record->connectStream(NULL); - } + pa_stream_set_read_callback (record->pulseStream() , capture_callback, this); // pa_stream_set_suspended_callback(record->pulseStream(), stream_suspended_callback, this); - pa_stream_set_moved_callback(record->pulseStream(), stream_moved_callback, this); - pa_stream_set_latency_update_callback(record->pulseStream(), latency_update_callback, this); + pa_stream_set_moved_callback (record->pulseStream(), stream_moved_callback, this); + pa_stream_set_latency_update_callback (record->pulseStream(), latency_update_callback, this); delete recordParam; - + PulseLayerType * ringtoneParam = new PulseLayerType(); ringtoneParam->context = c; ringtoneParam->type = RINGTONE_STREAM; @@ -579,14 +572,15 @@ bool PulseLayer::createStreams (pa_context* c) ringtoneParam->mainloop = m; ringtone = new AudioStream (ringtoneParam, _audioSampleRate); - if(inSourceList(ringtoneDevice)) { - ringtone->connectStream(&ringtoneDevice); - } - else { - ringtone->connectStream(NULL); + + if (inSourceList (ringtoneDevice)) { + ringtone->connectStream (&ringtoneDevice); + } else { + ringtone->connectStream (NULL); } - pa_stream_set_write_callback(ringtone->pulseStream(), ringtone_callback, this); - pa_stream_set_moved_callback(ringtone->pulseStream(), stream_moved_callback, this); + + pa_stream_set_write_callback (ringtone->pulseStream(), ringtone_callback, this); + pa_stream_set_moved_callback (ringtone->pulseStream(), stream_moved_callback, this); delete ringtoneParam; pa_threaded_mainloop_signal (m , 0); @@ -598,9 +592,8 @@ bool PulseLayer::createStreams (pa_context* c) } -bool PulseLayer::disconnectAudioStream (void) -{ - _info("Audio: Disconnect audio stream"); +bool PulseLayer::disconnectAudioStream (void) { + _info ("Audio: Disconnect audio stream"); closePlaybackStream(); closeCaptureStream(); @@ -612,41 +605,38 @@ bool PulseLayer::disconnectAudioStream (void) } -void PulseLayer::closeCaptureStream (void) -{ +void PulseLayer::closeCaptureStream (void) { if (record) { - std::string deviceName(pa_stream_get_device_name(record->pulseStream())); - _debug("Audio: record device to be stored in config: %s", deviceName.c_str()); - _manager->audioPreference.setDeviceRecord(deviceName); + std::string deviceName (pa_stream_get_device_name (record->pulseStream())); + _debug ("Audio: record device to be stored in config: %s", deviceName.c_str()); + _manager->audioPreference.setDeviceRecord (deviceName); delete record; record=NULL; } } -void PulseLayer::closePlaybackStream (void) -{ +void PulseLayer::closePlaybackStream (void) { if (playback) { - std::string deviceName(pa_stream_get_device_name(playback->pulseStream())); - _debug("Audio: playback device to be stored in config: %s", deviceName.c_str()); - _manager->audioPreference.setDevicePlayback(deviceName); + std::string deviceName (pa_stream_get_device_name (playback->pulseStream())); + _debug ("Audio: playback device to be stored in config: %s", deviceName.c_str()); + _manager->audioPreference.setDevicePlayback (deviceName); delete playback; playback=NULL; } - if(ringtone) { - std::string deviceName(pa_stream_get_device_name(ringtone->pulseStream())); - _debug("Audio: ringtone device to be stored in config: %s", deviceName.c_str()); - _manager->audioPreference.setDeviceRingtone(deviceName); + if (ringtone) { + std::string deviceName (pa_stream_get_device_name (ringtone->pulseStream())); + _debug ("Audio: ringtone device to be stored in config: %s", deviceName.c_str()); + _manager->audioPreference.setDeviceRingtone (deviceName); delete ringtone; - ringtone = NULL; + ringtone = NULL; } } -int PulseLayer::canGetMic() -{ +int PulseLayer::canGetMic() { if (record) return 0; else @@ -654,8 +644,7 @@ int PulseLayer::canGetMic() } -int PulseLayer::getMic (void *buffer, int toCopy) -{ +int PulseLayer::getMic (void *buffer, int toCopy) { if (record) { return 0; } else @@ -663,17 +652,16 @@ int PulseLayer::getMic (void *buffer, int toCopy) } -void PulseLayer::startStream (void) -{ - if(_audiofilter) - _audiofilter->resetAlgorithm(); +void PulseLayer::startStream (void) { + if (_audiofilter) + _audiofilter->resetAlgorithm(); - if(_echoCanceller) - _echoCanceller->resetAlgorithm(); + if (_echoCanceller) + _echoCanceller->resetAlgorithm(); // Create Streams - if(!playback || !record) - createStreams(context); + if (!playback || !record) + createStreams (context); // Flush outside the if statement: every time start stream is @@ -686,28 +674,26 @@ void PulseLayer::startStream (void) void -PulseLayer::stopStream (void) -{ +PulseLayer::stopStream (void) { - _info("Audio: Stop audio stream"); + _info ("Audio: Stop audio stream"); - pa_threaded_mainloop_lock (m); + pa_threaded_mainloop_lock (m); - if(playback) - pa_stream_flush (playback->pulseStream(), NULL, NULL); + if (playback) + pa_stream_flush (playback->pulseStream(), NULL, NULL); - if(record) - pa_stream_flush (record->pulseStream(), NULL, NULL); + if (record) + pa_stream_flush (record->pulseStream(), NULL, NULL); - pa_threaded_mainloop_unlock (m); + pa_threaded_mainloop_unlock (m); - disconnectAudioStream(); + disconnectAudioStream(); } -void PulseLayer::processPlaybackData (void) -{ +void PulseLayer::processPlaybackData (void) { // Handle the data for the speakers if (playback && (playback->pulseStream()) && (pa_stream_get_state (playback->pulseStream()) == PA_STREAM_READY)) { @@ -721,8 +707,7 @@ void PulseLayer::processPlaybackData (void) } -void PulseLayer::processCaptureData (void) -{ +void PulseLayer::processCaptureData (void) { // Handle the mic // We check if the stream is ready @@ -731,22 +716,20 @@ void PulseLayer::processCaptureData (void) } -void PulseLayer::processRingtoneData (void) -{ +void PulseLayer::processRingtoneData (void) { // handle ringtone playback - if(ringtone && (ringtone)->pulseStream() && (pa_stream_get_state(ringtone->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(ringtone->pulseStream()) == 0) - return; - - ringtoneToSpeaker(); - } + if (ringtone && (ringtone)->pulseStream() && (pa_stream_get_state (ringtone->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 (ringtone->pulseStream()) == 0) + return; + + ringtoneToSpeaker(); + } } -void PulseLayer::processData (void) -{ +void PulseLayer::processData (void) { // Handle the data for the speakers if (playback && (playback->pulseStream()) && (pa_stream_get_state (playback->pulseStream()) == PA_STREAM_READY)) { @@ -765,28 +748,25 @@ void PulseLayer::processData (void) } -void PulseLayer::setEchoCancelState(bool state) -{ - // if a stream already running - if(AudioLayer::_echoCancel) - _echoCancel->setEchoCancelState(state); +void PulseLayer::setEchoCancelState (bool state) { + // if a stream already running + if (AudioLayer::_echoCancel) + _echoCancel->setEchoCancelState (state); - AudioLayer::_echocancelstate = state; + AudioLayer::_echocancelstate = state; } -void PulseLayer::setNoiseSuppressState(bool state) -{ - // if a stream already opened - if(AudioLayer::_echoCancel) - _echoCancel->setNoiseSuppressState(state); +void PulseLayer::setNoiseSuppressState (bool state) { + // if a stream already opened + if (AudioLayer::_echoCancel) + _echoCancel->setNoiseSuppressState (state); - AudioLayer::_noisesuppressstate = state; + AudioLayer::_noisesuppressstate = state; } -void PulseLayer::writeToSpeaker (void) -{ +void PulseLayer::writeToSpeaker (void) { /** Bytes available in the urgent ringbuffer ( reserved for DTMF ) */ int urgentAvailBytes; /** Bytes available in the regular ringbuffer ( reserved for voice ) */ @@ -823,19 +803,19 @@ void PulseLayer::writeToSpeaker (void) // Get ringtone AudioLoop* tone = _manager->getTelephoneTone(); - // We must test if data have been received from network in case of early media - normalAvailBytes = getMainBuffer()->availForGet(); + // We must test if data have been received from network in case of early media + normalAvailBytes = getMainBuffer()->availForGet(); // flush remaining samples in _urgentRingBuffer flushUrgent(); - if ((tone != 0) && (normalAvailBytes <= 0)) { + if ( (tone != 0) && (normalAvailBytes <= 0)) { if (playback->getStreamState() == PA_STREAM_READY) { out = (SFLDataFormat*) pa_xmalloc (writeableSize); int copied = tone->getNext (out, writeableSize / sizeof (SFLDataFormat), 100); - + pa_stream_write (playback->pulseStream(), out, copied * sizeof (SFLDataFormat), NULL, 0, PA_SEEK_RELATIVE); pa_xfree (out); @@ -876,9 +856,9 @@ void PulseLayer::writeToSpeaker (void) getMainBuffer()->getData (out, byteToGet, 100); - // TODO: Audio processing should be performed inside mainbuffer - // to avoid such problem - AudioLayer::_echoCancel->setSamplingRate(_mainBufferSampleRate); + // TODO: Audio processing should be performed inside mainbuffer + // to avoid such problem + AudioLayer::_echoCancel->setSamplingRate (_mainBufferSampleRate); // test if resampling is required if (_mainBufferSampleRate && ( (int) _audioSampleRate != _mainBufferSampleRate)) { @@ -891,7 +871,7 @@ void PulseLayer::writeToSpeaker (void) int nbSample = _converter->upsampleData ( (SFLDataFormat*) out, rsmpl_out, _mainBufferSampleRate, _audioSampleRate, nb_sample_down); if ( (nbSample*sizeof (SFLDataFormat)) > (unsigned int) writeableSize) - _warn("Audio: Error: nbsbyte exceed buffer length"); + _warn ("Audio: Error: nbsbyte exceed buffer length"); pa_stream_write (playback->pulseStream(), rsmpl_out, nbSample*sizeof (SFLDataFormat), NULL, 0, PA_SEEK_RELATIVE); @@ -903,9 +883,9 @@ void PulseLayer::writeToSpeaker (void) } - - // Copy far-end signal in echo canceller to adapt filter coefficient - // AudioLayer::_echoCanceller->putData(out, byteToGet); + + // Copy far-end signal in echo canceller to adapt filter coefficient + // AudioLayer::_echoCanceller->putData(out, byteToGet); pa_xfree (out); @@ -933,19 +913,18 @@ void PulseLayer::writeToSpeaker (void) } -void PulseLayer::readFromMic (void) -{ +void PulseLayer::readFromMic (void) { const char* data = NULL; size_t r; SFLDataFormat echoCancelledMic[10000]; - memset(echoCancelledMic, 0, 10000*sizeof(SFLDataFormat)); + memset (echoCancelledMic, 0, 10000*sizeof (SFLDataFormat)); int readableSize = pa_stream_readable_size (record->pulseStream()); if (pa_stream_peek (record->pulseStream() , (const void**) &data , &r) < 0 || !data) { - _warn("Audio: Error capture stream peek failed: %s" , pa_strerror (pa_context_errno (context))); + _warn ("Audio: Error capture stream peek failed: %s" , pa_strerror (pa_context_errno (context))); } if (data != 0) { @@ -961,42 +940,42 @@ void PulseLayer::readFromMic (void) int nb_sample_up = nbSample; - // captureFile->write ((const char *)data, nbSample*sizeof(SFLDataFormat)); + // captureFile->write ((const char *)data, nbSample*sizeof(SFLDataFormat)); nbSample = _converter->downsampleData ( (SFLDataFormat *) data, rsmpl_out, _mainBufferSampleRate, _audioSampleRate, nb_sample_up); - // captureRsmplFile->write ((const char *)rsmpl_out, nbSample*sizeof(SFLDataFormat)); + // captureRsmplFile->write ((const char *)rsmpl_out, nbSample*sizeof(SFLDataFormat)); // remove dc offset - _audiofilter->processAudio(rsmpl_out, nbSample*sizeof(SFLDataFormat)); + _audiofilter->processAudio (rsmpl_out, nbSample*sizeof (SFLDataFormat)); - // captureFilterFile->write ((const char *)rsmpl_out, nbSample*sizeof(SFLDataFormat)); + // captureFilterFile->write ((const char *)rsmpl_out, nbSample*sizeof(SFLDataFormat)); - // echo cancellation processing - // int sampleready = _echoCanceller->processAudio(rsmpl_out, echoCancelledMic, nbSample*sizeof(SFLDataFormat)); + // echo cancellation processing + // int sampleready = _echoCanceller->processAudio(rsmpl_out, echoCancelledMic, nbSample*sizeof(SFLDataFormat)); // getMainBuffer()->putData ( (void*) rsmpl_out, nbSample*sizeof (SFLDataFormat), 100); - // if(sampleready) - // getMainBuffer()->putData ( echoCancelledMic, sampleready*sizeof (SFLDataFormat), 100); - getMainBuffer()->putData ( rsmpl_out, nbSample*sizeof (SFLDataFormat), 100); + // if(sampleready) + // getMainBuffer()->putData ( echoCancelledMic, sampleready*sizeof (SFLDataFormat), 100); + getMainBuffer()->putData (rsmpl_out, nbSample*sizeof (SFLDataFormat), 100); pa_xfree (rsmpl_out); } else { - SFLDataFormat* filter_out = (SFLDataFormat*) pa_xmalloc (r); + SFLDataFormat* filter_out = (SFLDataFormat*) pa_xmalloc (r); - // remove dc offset - _audiofilter->processAudio((SFLDataFormat *)data, filter_out, r); + // remove dc offset + _audiofilter->processAudio ( (SFLDataFormat *) data, filter_out, r); - // echo cancellation processing - // int sampleready = _echoCanceller->processAudio((SFLDataFormat *)filter_out, echoCancelledMic, r); + // echo cancellation processing + // int sampleready = _echoCanceller->processAudio((SFLDataFormat *)filter_out, echoCancelledMic, r); // no resampling required // getMainBuffer()->putData (echoCancelledMic, sampleready*sizeof (SFLDataFormat), 100); - getMainBuffer()->putData (filter_out, r, 100); + getMainBuffer()->putData (filter_out, r, 100); - pa_xfree(filter_out); + pa_xfree (filter_out); } @@ -1004,58 +983,54 @@ void PulseLayer::readFromMic (void) } if (pa_stream_drop (record->pulseStream()) < 0) { - _warn("Audio: Error: capture stream drop failed: %s" , pa_strerror( pa_context_errno( context) )); + _warn ("Audio: Error: capture stream drop failed: %s" , pa_strerror (pa_context_errno (context))); } } -void PulseLayer::ringtoneToSpeaker(void) -{ - int availBytes; +void PulseLayer::ringtoneToSpeaker (void) { + int availBytes; - AudioLoop* file_tone = _manager->getTelephoneFile(); + AudioLoop* file_tone = _manager->getTelephoneFile(); - SFLDataFormat* out; + SFLDataFormat* out; - int writableSize = pa_stream_writable_size(ringtone->pulseStream()); + int writableSize = pa_stream_writable_size (ringtone->pulseStream()); - if (file_tone) { + if (file_tone) { - if(ringtone->getStreamState() == PA_STREAM_READY) { - - out = (SFLDataFormat *)pa_xmalloc(writableSize); - int copied = file_tone->getNext(out, writableSize/sizeof(SFLDataFormat), 100); - pa_stream_write(ringtone->pulseStream(), out, copied*sizeof(SFLDataFormat), NULL, 0, PA_SEEK_RELATIVE); + if (ringtone->getStreamState() == PA_STREAM_READY) { - pa_xfree(out); - } - } - else { + out = (SFLDataFormat *) pa_xmalloc (writableSize); + int copied = file_tone->getNext (out, writableSize/sizeof (SFLDataFormat), 100); + pa_stream_write (ringtone->pulseStream(), out, copied*sizeof (SFLDataFormat), NULL, 0, PA_SEEK_RELATIVE); + + pa_xfree (out); + } + } else { + + if (ringtone->getStreamState() == PA_STREAM_READY) { - if(ringtone->getStreamState() == PA_STREAM_READY) { + out = (SFLDataFormat*) pa_xmalloc (writableSize); + memset (out, 0, writableSize); + pa_stream_write (ringtone->pulseStream(), out, writableSize, NULL, 0, PA_SEEK_RELATIVE); - out = (SFLDataFormat*)pa_xmalloc(writableSize); - memset(out, 0, writableSize); - pa_stream_write(ringtone->pulseStream(), out, writableSize, NULL, 0, PA_SEEK_RELATIVE); - - pa_xfree(out); + pa_xfree (out); + } } - } - + } -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" , i->user_name); _debug ("\t\tServer name : %s - Server version = %s" , i->server_name, i->server_version); _debug ("\t\tDefault sink name : %s" , i->default_sink_name); _debug ("\t\tDefault source name : %s" , 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) { @@ -1068,8 +1043,7 @@ static void reduce_sink_list_cb (pa_context *c UNUSED, const pa_sink_input_info } } -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) { @@ -1083,8 +1057,7 @@ static void restore_sink_list_cb (pa_context *c UNUSED, const pa_sink_input_info } } -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; @@ -1097,8 +1070,7 @@ static void set_playback_volume_cb (pa_context *c UNUSED, const pa_sink_input_in } } -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; @@ -1112,26 +1084,22 @@ static void set_capture_volume_cb (pa_context *c UNUSED, const pa_source_output_ } void -PulseLayer::reducePulseAppsVolume (void) -{ +PulseLayer::reducePulseAppsVolume (void) { pa_context_get_sink_input_info_list (context , reduce_sink_list_cb , this); } void -PulseLayer::restorePulseAppsVolume (void) -{ +PulseLayer::restorePulseAppsVolume (void) { pa_context_get_sink_input_info_list (context , restore_sink_list_cb , this); } void -PulseLayer::serverinfo (void) -{ +PulseLayer::serverinfo (void) { 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) ; @@ -1142,8 +1110,7 @@ void PulseLayer::setSinkVolume (int index, int channels, int volume) } -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) ; @@ -1155,14 +1122,12 @@ void PulseLayer::setSourceVolume (int index, int channels, int volume) } -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); } -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); } diff --git a/sflphone-common/src/audio/recordable.cpp b/sflphone-common/src/audio/recordable.cpp index 8371bf7ec8b52a82763e3b4ea90a51944eafd48b..8ae776a1d95d7eaba79e856540be1b31af96028e 100644 --- a/sflphone-common/src/audio/recordable.cpp +++ b/sflphone-common/src/audio/recordable.cpp @@ -30,8 +30,7 @@ #include "recordable.h" #include "manager.h" -Recordable::Recordable() : recorder(&recAudio, Manager::instance().getMainBuffer()) -{ +Recordable::Recordable() : recorder (&recAudio, Manager::instance().getMainBuffer()) { FILE_TYPE fileType = FILE_WAV; SOUND_FORMAT soundFormat = INT16; @@ -40,23 +39,20 @@ Recordable::Recordable() : recorder(&recAudio, Manager::instance().getMainBuffer } -Recordable::~Recordable() -{ +Recordable::~Recordable() { if (recAudio.isOpenFile()) { recAudio.closeFile(); } } -void Recordable::initRecFileName() -{ +void Recordable::initRecFileName() { recAudio.initFileName (getRecFileId()); } -void Recordable::setRecordingSmplRate (int smplRate) -{ +void Recordable::setRecordingSmplRate (int smplRate) { recAudio.setSndSamplingRate (smplRate); diff --git a/sflphone-common/src/audio/ringbuffer.cpp b/sflphone-common/src/audio/ringbuffer.cpp index c38b4c2212018afe37a8b2aa54fac577a2de4e88..6a09d91de7682468407c40857d6fae29f861f464 100644 --- a/sflphone-common/src/audio/ringbuffer.cpp +++ b/sflphone-common/src/audio/ringbuffer.cpp @@ -47,8 +47,7 @@ int RingBuffer::count_rb = 0; RingBuffer::RingBuffer (int size, CallID call_id) : mEnd (0) , mBufferSize (size > MIN_BUFFER_SIZE ? size : MIN_BUFFER_SIZE) , mBuffer (NULL) - , buffer_id (call_id) -{ + , buffer_id (call_id) { mBuffer = new unsigned char[mBufferSize]; assert (mBuffer != NULL); @@ -56,23 +55,20 @@ RingBuffer::RingBuffer (int size, CallID call_id) : mEnd (0) } // Free memory on object deletion -RingBuffer::~RingBuffer() -{ +RingBuffer::~RingBuffer() { delete[] mBuffer; mBuffer = NULL; } void -RingBuffer::flush (CallID call_id) -{ +RingBuffer::flush (CallID call_id) { storeReadPointer (mEnd, call_id); } void -RingBuffer::flushAll () -{ +RingBuffer::flushAll () { ReadPointer::iterator iter_pointer = _readpointer.begin(); @@ -86,8 +82,7 @@ RingBuffer::flushAll () } int -RingBuffer::putLen() -{ +RingBuffer::putLen() { int mStart; if (_readpointer.size() >= 1) { @@ -102,30 +97,27 @@ RingBuffer::putLen() } int -RingBuffer::getLen (CallID call_id) -{ +RingBuffer::getLen (CallID call_id) { int mStart = getReadPointer (call_id); int length = (mEnd + mBufferSize - mStart) % mBufferSize; - + // _debug(" *RingBuffer::getLen: buffer_id %s, call_id %s, mStart %i, mEnd %i, length %i, buffersie %i", buffer_id.c_str(), call_id.c_str(), mStart, mEnd, length, mBufferSize); return length; } void -RingBuffer::debug() -{ +RingBuffer::debug() { int mStart = getSmallestReadPointer(); _debug ("Start=%d; End=%d; BufferSize=%d", mStart, mEnd, mBufferSize); } int -RingBuffer::getReadPointer (CallID call_id) -{ +RingBuffer::getReadPointer (CallID call_id) { if (getNbReadPointer() == 0) return 0; @@ -141,8 +133,7 @@ RingBuffer::getReadPointer (CallID call_id) } int -RingBuffer::getSmallestReadPointer() -{ +RingBuffer::getSmallestReadPointer() { if (getNbReadPointer() == 0) return 0; @@ -161,8 +152,7 @@ RingBuffer::getSmallestReadPointer() } void -RingBuffer::storeReadPointer (int pointer_value, CallID call_id) -{ +RingBuffer::storeReadPointer (int pointer_value, CallID call_id) { ReadPointer::iterator iter = _readpointer.find (call_id); @@ -176,8 +166,7 @@ RingBuffer::storeReadPointer (int pointer_value, CallID call_id) void -RingBuffer::createReadPointer (CallID call_id) -{ +RingBuffer::createReadPointer (CallID call_id) { _readpointer.insert (pair<CallID, int> (call_id, mEnd)); @@ -185,8 +174,7 @@ RingBuffer::createReadPointer (CallID call_id) void -RingBuffer::removeReadPointer (CallID call_id) -{ +RingBuffer::removeReadPointer (CallID call_id) { _readpointer.erase (call_id); @@ -196,8 +184,7 @@ RingBuffer::removeReadPointer (CallID call_id) bool -RingBuffer::hasThisReadPointer (CallID call_id) -{ +RingBuffer::hasThisReadPointer (CallID call_id) { ReadPointer::iterator iter = _readpointer.find (call_id); if (iter == _readpointer.end()) { @@ -209,8 +196,7 @@ RingBuffer::hasThisReadPointer (CallID call_id) int -RingBuffer::getNbReadPointer() -{ +RingBuffer::getNbReadPointer() { return _readpointer.size(); } @@ -218,8 +204,7 @@ RingBuffer::getNbReadPointer() // For the writer only: // int -RingBuffer::AvailForPut() -{ +RingBuffer::AvailForPut() { // Always keep 4 bytes safe (?) return mBufferSize - putLen(); @@ -228,8 +213,7 @@ RingBuffer::AvailForPut() // 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) -{ +RingBuffer::Put (void* buffer, int toCopy, unsigned short volume) { samplePtr src; int block; int copied; @@ -271,7 +255,7 @@ RingBuffer::Put (void* buffer, int toCopy, unsigned short volume) //fprintf(stderr, "has %d put %d\t", len, block); bcopy (src, mBuffer + pos, block); - src += block; + src += block; pos = (pos + block) % mBufferSize; @@ -291,17 +275,15 @@ RingBuffer::Put (void* buffer, int toCopy, unsigned short volume) // int -RingBuffer::AvailForGet (CallID call_id) -{ +RingBuffer::AvailForGet (CallID call_id) { // Used space - return getLen(call_id); + return getLen (call_id); } // Get will move 'toCopy' bytes from the internal FIFO to 'buffer' int -RingBuffer::Get (void *buffer, int toCopy, unsigned short volume, CallID call_id) -{ +RingBuffer::Get (void *buffer, int toCopy, unsigned short volume, CallID call_id) { if (getNbReadPointer() == 0) return 0; @@ -363,8 +345,7 @@ RingBuffer::Get (void *buffer, int toCopy, unsigned short volume, CallID call_id // Used to discard some bytes. int -RingBuffer::Discard (int toDiscard, CallID call_id) -{ +RingBuffer::Discard (int toDiscard, CallID call_id) { int len = getLen (call_id); diff --git a/sflphone-common/src/audio/samplerateconverter.cpp b/sflphone-common/src/audio/samplerateconverter.cpp index 320d70b5cd1396dc331267993d66230de828e45f..aa3b1d734c4357c936a11203b68c58e2bced1fd3 100644 --- a/sflphone-common/src/audio/samplerateconverter.cpp +++ b/sflphone-common/src/audio/samplerateconverter.cpp @@ -39,8 +39,7 @@ SamplerateConverter::SamplerateConverter (void) , _floatBufferDownSpkr (NULL) , _floatBufferUpSpkr (NULL) , _src_state_spkr (NULL) - , _src_err (0) -{ + , _src_err (0) { init(); } @@ -53,13 +52,11 @@ SamplerateConverter::SamplerateConverter (int freq , int fs) , _floatBufferDownSpkr (NULL) , _floatBufferUpSpkr (NULL) , _src_state_spkr (NULL) - , _src_err (0) -{ + , _src_err (0) { init(); } -SamplerateConverter::~SamplerateConverter (void) -{ +SamplerateConverter::~SamplerateConverter (void) { delete [] _floatBufferUpMic; _floatBufferUpMic = NULL; @@ -76,8 +73,7 @@ SamplerateConverter::~SamplerateConverter (void) _src_state_spkr = src_delete (_src_state_spkr); } -void SamplerateConverter::init (void) -{ +void SamplerateConverter::init (void) { // libSamplerateConverter-related // Set the converter type for the upsampling and the downsampling @@ -96,8 +92,7 @@ void SamplerateConverter::init (void) } void -SamplerateConverter::Short2FloatArray (const short *in, float *out, int len) -{ +SamplerateConverter::Short2FloatArray (const short *in, float *out, int len) { // factor is 1/(2^15), used to rescale the short int range to the // [-1.0 - 1.0] float range. #define S2F_FACTOR .000030517578125f; @@ -110,8 +105,7 @@ SamplerateConverter::Short2FloatArray (const short *in, float *out, int len) //TODO Add ifdef for int16 or float32 type -int SamplerateConverter::upsampleData (SFLDataFormat* dataIn , SFLDataFormat* dataOut, int samplerate1 , int samplerate2 , int nbSamples) -{ +int SamplerateConverter::upsampleData (SFLDataFormat* dataIn , SFLDataFormat* dataOut, int samplerate1 , int samplerate2 , int nbSamples) { double upsampleFactor = (double) samplerate2 / samplerate1 ; @@ -141,8 +135,7 @@ int SamplerateConverter::upsampleData (SFLDataFormat* dataIn , SFLDataFormat* da } //TODO Add ifdef for int16 or float32 type -int SamplerateConverter::downsampleData (SFLDataFormat* dataIn , SFLDataFormat* dataOut , int samplerate1 , int samplerate2 , int nbSamples) -{ +int SamplerateConverter::downsampleData (SFLDataFormat* dataIn , SFLDataFormat* dataOut , int samplerate1 , int samplerate2 , int nbSamples) { double downsampleFactor = (double) samplerate1 / samplerate2; diff --git a/sflphone-common/src/audio/sound/audiofile.cpp b/sflphone-common/src/audio/sound/audiofile.cpp index 9bde16aea379a854e4fcc092b920a4bb01e6a3c9..d447ad1d0d1f84b4a0536d4ade389ba0fc7bf234 100644 --- a/sflphone-common/src/audio/sound/audiofile.cpp +++ b/sflphone-common/src/audio/sound/audiofile.cpp @@ -47,14 +47,12 @@ AudioFile::AudioFile() { } -AudioFile::~AudioFile() -{ +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; // if the filename was already load, with the same samplerate @@ -186,113 +184,111 @@ WavFile::WavFile() { } -WavFile::~WavFile() -{ +WavFile::~WavFile() { } -bool WavFile::isFileExist(const std::string& filename) -{ +bool WavFile::isFileExist (const std::string& filename) { - std::fstream fs(filename.c_str(), std::ios_base::in); - if(!fs) { - _debug("WavFile: File \"%s\" doesn't exist", filename.c_str()); - return false; - } + std::fstream fs (filename.c_str(), std::ios_base::in); - return true; + if (!fs) { + _debug ("WavFile: File \"%s\" doesn't exist", filename.c_str()); + return false; + } + + return true; } -bool WavFile::loadFile (const std::string& filename, AudioCodec* codec , unsigned int sampleRate) -{ - if(!isFileExist(filename)) - return false; - +bool WavFile::loadFile (const std::string& filename, AudioCodec* codec , unsigned int sampleRate) { + if (!isFileExist (filename)) + return false; + std::fstream file; - printf("WavFile: Open %s", filename.c_str()); + printf ("WavFile: Open %s", filename.c_str()); - file.open(filename.c_str(), std::ios::in | std::ios::binary); + file.open (filename.c_str(), std::ios::in | std::ios::binary); char riff[4] = {}; - file.read(riff, 4); + file.read (riff, 4); - if ( strncmp("RIFF", riff, 4) != 0 ) { - _error("WavFile: File is not of RIFF format"); + if (strncmp ("RIFF", riff, 4) != 0) { + _error ("WavFile: File is not of RIFF format"); return false; } // Find the "fmt " chunk - char fmt[4] = {}; + char fmt[4] = {}; - while ( strncmp("fmt ", fmt, 4) != 0 ) { - file.read(fmt, 4); - _debug("WavFile: Searching... %s", fmt); + while (strncmp ("fmt ", fmt, 4) != 0) { + file.read (fmt, 4); + _debug ("WavFile: Searching... %s", fmt); } SINT32 chunkSize; // fmt chunk size unsigned short formatTag; // data compression tag - file.read((char*)&chunkSize, 4); // Read fmt chunk size. - file.read((char*)&formatTag, 2); + file.read ( (char*) &chunkSize, 4); // Read fmt chunk size. + file.read ( (char*) &formatTag, 2); - _debug("Chunk size: %d\n", chunkSize); - _debug("Format tag: %d\n", formatTag); + _debug ("Chunk size: %d\n", chunkSize); + _debug ("Format tag: %d\n", formatTag); - if (formatTag != 1 ) { // PCM = 1, FLOAT = 3 { - _error("WaveFile: File contains an unsupported data format type"); + if (formatTag != 1) { // PCM = 1, FLOAT = 3 { + _error ("WaveFile: File contains an unsupported data format type"); return false; } // Get number of channels from the header. SINT16 chan; - file.read((char*)&chan, 2); + file.read ( (char*) &chan, 2); _channels = chan; - _debug("WavFile: channel %d", _channels); + _debug ("WavFile: channel %d", _channels); // Get file sample rate from the header. SINT32 srate; - file.read((char*)&srate, 4); + file.read ( (char*) &srate, 4); + + _fileRate = (double) srate; - _fileRate = (double)srate; + printf ("WavFile: srate %d", srate); - printf("WavFile: srate %d", srate); - SINT32 avgb; - file.read((char*)&avgb, 4); + file.read ( (char*) &avgb, 4); - _debug("WavFile: Average byte %i\n", avgb); + _debug ("WavFile: Average byte %i\n", avgb); SINT16 blockal; - file.read((char*)&blockal, 2); + file.read ( (char*) &blockal, 2); - _debug("WaveFile: block alignment %d", blockal); + _debug ("WaveFile: block alignment %d", blockal); // Determine the data type _dataType = 0; SINT16 dt; - file.read((char*)&dt, 2); + file.read ( (char*) &dt, 2); - _debug("WaveFile: dt %d", dt); + _debug ("WaveFile: dt %d", dt); - if ( formatTag == 1 ) { - if (dt == 8) - _dataType = 1; // SINT8; - else if (dt == 16) - _dataType = 2; // SINT16; - else if (dt == 32) - _dataType = 3; // SINT32; + if (formatTag == 1) { + if (dt == 8) + _dataType = 1; // SINT8; + else if (dt == 16) + _dataType = 2; // SINT16; + else if (dt == 32) + _dataType = 3; // SINT32; } /* - else if ( formatTag == 3 ) + else if ( formatTag == 3 ) { if (temp == 32) dataType_ = FLOAT32; @@ -301,29 +297,29 @@ bool WavFile::loadFile (const std::string& filename, AudioCodec* codec , unsigne } */ else { - _debug("WavFile: File's bits per sample is not supported"); - return false; + _debug ("WavFile: File's bits per sample is not supported"); + return false; } - // Find the "data" chunk + // Find the "data" chunk char data[4] = {}; - while ( strncmp("data", data, 4) ) { - file.read(data, 4); - _debug("WavFile: Searching data"); + while (strncmp ("data", data, 4)) { + file.read (data, 4); + _debug ("WavFile: Searching data"); } // Get length of data from the header. SINT32 bytes; - file.read((char*)&bytes, 4); + file.read ( (char*) &bytes, 4); - _debug("WavFile: Data size in byte %ld", bytes); + _debug ("WavFile: Data size in byte %ld", bytes); _fileSize = 8 * bytes / dt / _channels; // sample frames - _debug("WavFile: Data size in frames %ld", _fileSize); + _debug ("WavFile: Data size in frames %ld", _fileSize); - _debug("WavFile: File successfully opened"); + _debug ("WavFile: File successfully opened"); return true; diff --git a/sflphone-common/src/audio/sound/dtmf.cpp b/sflphone-common/src/audio/sound/dtmf.cpp index c833fbc9711dd68c66a841d0362beb6fe011571d..423a9cd02d191faa443a8fa3b39001ffe675a0df 100644 --- a/sflphone-common/src/audio/sound/dtmf.cpp +++ b/sflphone-common/src/audio/sound/dtmf.cpp @@ -35,23 +35,19 @@ #include "dtmf.h" DTMF::DTMF (unsigned int sampleRate) - : currentTone (0), newTone (0), dtmfgenerator (sampleRate) -{ + : currentTone (0), newTone (0), dtmfgenerator (sampleRate) { } -DTMF::~DTMF (void) -{ +DTMF::~DTMF (void) { } void -DTMF::startTone (char code) -{ +DTMF::startTone (char code) { newTone = code; } bool -DTMF::generateDTMF (SFLDataFormat* buffer, size_t n) -{ +DTMF::generateDTMF (SFLDataFormat* buffer, size_t n) { if (!buffer) return false; try { diff --git a/sflphone-common/src/audio/sound/dtmfgenerator.cpp b/sflphone-common/src/audio/sound/dtmfgenerator.cpp index f149d6b445e5f034ba293eb90e179caa1d0e00e4..51fa882c7a6385ccb186e6ebb650cfc21d543a73 100644 --- a/sflphone-common/src/audio/sound/dtmfgenerator.cpp +++ b/sflphone-common/src/audio/sound/dtmfgenerator.cpp @@ -62,17 +62,14 @@ const DTMFGenerator::DTMFTone DTMFGenerator::tones[NUM_TONES] = { }; -DTMFException::DTMFException (const char* _reason) throw() : reason (_reason) -{ +DTMFException::DTMFException (const char* _reason) throw() : reason (_reason) { } -DTMFException::~DTMFException() throw() -{ +DTMFException::~DTMFException() throw() { } -const char* DTMFException::what() const throw() -{ +const char* DTMFException::what() const throw() { return reason; } @@ -81,8 +78,7 @@ 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; @@ -92,8 +88,7 @@ DTMFGenerator::DTMFGenerator (unsigned int sampleRate) : state(), _sampleRate (s } -DTMFGenerator::~DTMFGenerator() -{ +DTMFGenerator::~DTMFGenerator() { for (int i = 0; i < NUM_TONES; i++) { delete[] samples[i]; samples[i] = NULL; @@ -103,8 +98,7 @@ DTMFGenerator::~DTMFGenerator() /* * Get n samples of the signal of code code */ -void DTMFGenerator::getSamples (SFLDataFormat* buffer, size_t n, unsigned char code) throw (DTMFException) -{ +void DTMFGenerator::getSamples (SFLDataFormat* buffer, size_t n, unsigned char code) throw (DTMFException) { size_t i; if (!buffer) { @@ -203,8 +197,7 @@ void DTMFGenerator::getSamples (SFLDataFormat* buffer, size_t n, unsigned char c * 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; if (!buffer) { @@ -226,8 +219,7 @@ void DTMFGenerator::getNextSamples (SFLDataFormat* buffer, size_t n) throw (DTMF /* * Generate a tone sample */ -SFLDataFormat* DTMFGenerator::generateSample (unsigned char code) throw (DTMFException) -{ +SFLDataFormat* DTMFGenerator::generateSample (unsigned char code) throw (DTMFException) { SFLDataFormat* ptr; try { diff --git a/sflphone-common/src/audio/sound/tone.cpp b/sflphone-common/src/audio/sound/tone.cpp index aaff9fa4f411278d18fb42144585b4132df63d0e..62460633c3e3701c81b414cf704060c6f2e8ff7e 100644 --- a/sflphone-common/src/audio/sound/tone.cpp +++ b/sflphone-common/src/audio/sound/tone.cpp @@ -42,19 +42,16 @@ #define TABLE_LENGTH 4096 double TWOPI = 2 * M_PI; -Tone::Tone (const std::string& definition, unsigned int sampleRate) : AudioLoop(), _sampleRate (sampleRate), _xhigher(0.0), _xlower(0.0) -{ - fillWavetable(); +Tone::Tone (const std::string& definition, unsigned int sampleRate) : AudioLoop(), _sampleRate (sampleRate), _xhigher (0.0), _xlower (0.0) { + fillWavetable(); genBuffer (definition); // allocate memory with definition parameter } -Tone::~Tone() -{ +Tone::~Tone() { } void -Tone::genBuffer (const std::string& definition) -{ +Tone::genBuffer (const std::string& definition) { if (definition.empty()) { return; } @@ -116,7 +113,7 @@ Tone::genBuffer (const std::string& definition) } // Generate SAMPLING_RATE samples of sinus, buffer is the result - _debug("genSin(%d, %d)", freq1, freq2); + _debug ("genSin(%d, %d)", freq1, freq2); genSin (bufferPos, freq1, freq2, count); // To concatenate the different buffers for each section. @@ -141,69 +138,66 @@ Tone::genBuffer (const std::string& definition) } void -Tone::fillWavetable() -{ - double tableSize = (double)TABLE_LENGTH; +Tone::fillWavetable() { + double tableSize = (double) TABLE_LENGTH; - for(int i = 0; i < TABLE_LENGTH; i++) { - _wavetable[i] = sin( ((double)i / (tableSize - 1.0)) * TWOPI ); - } + for (int i = 0; i < TABLE_LENGTH; i++) { + _wavetable[i] = sin ( ( (double) i / (tableSize - 1.0)) * TWOPI); + } } double -Tone::interpolate(double x) -{ - int xi_0, xi_1; - double yi_0, yi_1, A, B; +Tone::interpolate (double x) { + int xi_0, xi_1; + double yi_0, yi_1, A, B; - xi_0 = (int)x; - xi_1 = xi_0+1; + xi_0 = (int) x; + xi_1 = xi_0+1; - yi_0 =_wavetable[xi_0]; - yi_1 = _wavetable[xi_1]; + yi_0 =_wavetable[xi_0]; + yi_1 = _wavetable[xi_1]; - A = (x - xi_0); - B = 1.0 - A; + A = (x - xi_0); + B = 1.0 - A; - return A*yi_0 + B*yi_1; + return A*yi_0 + B*yi_1; } void -Tone::genSin (SFLDataFormat* buffer, int frequency1, int frequency2, int nb) -{ - _xhigher = 0.0; - _xlower = 0.0; +Tone::genSin (SFLDataFormat* buffer, int frequency1, int frequency2, int nb) { + _xhigher = 0.0; + _xlower = 0.0; - double sr = (double)_sampleRate; - double tableSize = (double)TABLE_LENGTH; + double sr = (double) _sampleRate; + double tableSize = (double) TABLE_LENGTH; - double N_h = sr / (double) (frequency1); - double N_l = sr / (double) (frequency2); + double N_h = sr / (double) (frequency1); + double N_l = sr / (double) (frequency2); - double dx_h = tableSize / N_h; - double dx_l = tableSize / N_l; + double dx_h = tableSize / N_h; + double dx_l = tableSize / N_l; - double x_h = _xhigher; - double x_l = _xlower; + double x_h = _xhigher; + double x_l = _xlower; - double amp = (double)SFLDataAmplitude; + double amp = (double) SFLDataAmplitude; - for (int t = 0; t < nb; t ++) { - buffer[t] = (int16)(amp*(interpolate(x_h) + interpolate(x_l))); - x_h += dx_h; - x_l += dx_l; + for (int t = 0; t < nb; t ++) { + buffer[t] = (int16) (amp* (interpolate (x_h) + interpolate (x_l))); + x_h += dx_h; + x_l += dx_l; - if(x_h > tableSize) { - x_h -= tableSize; - } + if (x_h > tableSize) { + x_h -= tableSize; + } - if(x_l > tableSize) { - x_l -= tableSize; - } - } + if (x_l > tableSize) { + x_l -= tableSize; + } + } - _xhigher = x_h; - _xlower = x_l; + _xhigher = x_h; + _xlower = x_l; } diff --git a/sflphone-common/src/audio/sound/tonelist.cpp b/sflphone-common/src/audio/sound/tonelist.cpp index 0bac7f0113dffb925793c1ed36ddb5b42f562cef..3b94628fb2ded0ba777352c7f127fc78030f464c 100644 --- a/sflphone-common/src/audio/sound/tonelist.cpp +++ b/sflphone-common/src/audio/sound/tonelist.cpp @@ -34,18 +34,15 @@ ToneList::ToneList() : _nbTone (TONE_NBTONE) , _nbCountry (TONE_NBCOUNTRY), - _defaultCountryId (ZID_NORTH_AMERICA) -{ + _defaultCountryId (ZID_NORTH_AMERICA) { initToneDefinition(); } -ToneList::~ToneList() -{ +ToneList::~ToneList() { } void -ToneList::initToneDefinition() -{ +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"; @@ -87,8 +84,7 @@ ToneList::initToneDefinition() } std::string -ToneList::getDefinition (COUNTRYID countryId, Tone::TONEID toneId) -{ +ToneList::getDefinition (COUNTRYID countryId, Tone::TONEID toneId) { if (toneId == Tone::TONE_NULL) { return ""; } @@ -97,8 +93,7 @@ ToneList::getDefinition (COUNTRYID countryId, Tone::TONEID toneId) } ToneList::COUNTRYID -ToneList::getCountryId (const std::string& countryName) -{ +ToneList::getCountryId (const std::string& countryName) { if (countryName.compare ("North America") == 0) { return ZID_NORTH_AMERICA; } else if (countryName.compare ("France") == 0) { @@ -120,8 +115,7 @@ ToneList::getCountryId (const std::string& countryName) TelephoneTone::TelephoneTone (const std::string& countryName, unsigned int sampleRate) : _currentTone (Tone::TONE_NULL), - _toneList() -{ + _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); @@ -130,8 +124,7 @@ TelephoneTone::TelephoneTone (const std::string& countryName, unsigned int sampl } -TelephoneTone::~TelephoneTone() -{ +TelephoneTone::~TelephoneTone() { for (int i=0; i<_toneList.getNbTone(); i++) { delete _tone[i]; _tone[i] = 0; @@ -139,8 +132,7 @@ TelephoneTone::~TelephoneTone() } void -TelephoneTone::setCurrentTone (Tone::TONEID toneId) -{ +TelephoneTone::setCurrentTone (Tone::TONEID toneId) { if (toneId != Tone::TONE_NULL && _currentTone != toneId) { _tone[toneId]->reset(); } @@ -149,8 +141,7 @@ TelephoneTone::setCurrentTone (Tone::TONEID toneId) } Tone* -TelephoneTone::getCurrentTone() -{ +TelephoneTone::getCurrentTone() { if (_currentTone == Tone::TONE_NULL) { return 0; } @@ -159,8 +150,7 @@ TelephoneTone::getCurrentTone() } bool -TelephoneTone::shouldPlay() -{ +TelephoneTone::shouldPlay() { return ( (_currentTone != Tone::TONE_NULL) ? true : false); } diff --git a/sflphone-common/src/audio/speexechocancel.cpp b/sflphone-common/src/audio/speexechocancel.cpp index fa5f1045ddfd0566d8ed36e018a9fcbf58f9df28..760df627fffef7593622e7ea8cc9e2ff1bd750b4 100644 --- a/sflphone-common/src/audio/speexechocancel.cpp +++ b/sflphone-common/src/audio/speexechocancel.cpp @@ -27,140 +27,135 @@ #define FILTER_LENGTH 800 -SpeexEchoCancel::SpeexEchoCancel() -{ - _debug("EchoCancel: Instantiate echo canceller"); +SpeexEchoCancel::SpeexEchoCancel() { + _debug ("EchoCancel: Instantiate echo canceller"); - int samplingRate = 8000; + int samplingRate = 8000; - _echoState = speex_echo_state_init(FRAME_SIZE, FILTER_LENGTH); - _preState = speex_preprocess_state_init(FRAME_SIZE, samplingRate); + _echoState = speex_echo_state_init (FRAME_SIZE, FILTER_LENGTH); + _preState = speex_preprocess_state_init (FRAME_SIZE, samplingRate); - speex_echo_ctl(_echoState, SPEEX_ECHO_SET_SAMPLING_RATE, &samplingRate); - speex_preprocess_ctl(_preState, SPEEX_PREPROCESS_SET_ECHO_STATE, _echoState); + speex_echo_ctl (_echoState, SPEEX_ECHO_SET_SAMPLING_RATE, &samplingRate); + speex_preprocess_ctl (_preState, SPEEX_PREPROCESS_SET_ECHO_STATE, _echoState); - micFile = new ofstream("micData", ofstream::binary); - echoFile = new ofstream("echoData", ofstream::binary); - spkrFile = new ofstream("spkrData", ofstream::binary); + micFile = new ofstream ("micData", ofstream::binary); + echoFile = new ofstream ("echoData", ofstream::binary); + spkrFile = new ofstream ("spkrData", ofstream::binary); - _micData = new RingBuffer(10000); - _spkrData = new RingBuffer(10000); + _micData = new RingBuffer (10000); + _spkrData = new RingBuffer (10000); - _micData->createReadPointer(); - _spkrData->createReadPointer(); + _micData->createReadPointer(); + _spkrData->createReadPointer(); - _spkrStoped = true; + _spkrStoped = true; } -SpeexEchoCancel::~SpeexEchoCancel() -{ - _debug("EchoCancel: Delete echo canceller"); +SpeexEchoCancel::~SpeexEchoCancel() { + _debug ("EchoCancel: Delete echo canceller"); - speex_echo_state_destroy(_echoState); - _echoState = NULL; + speex_echo_state_destroy (_echoState); + _echoState = NULL; - speex_preprocess_state_destroy(_preState); - _preState = NULL; + speex_preprocess_state_destroy (_preState); + _preState = NULL; - delete _micData; - _micData = NULL; + delete _micData; + _micData = NULL; - delete _spkrData; - _spkrData = NULL; + delete _spkrData; + _spkrData = NULL; - micFile->close(); - spkrFile->close(); - echoFile->close(); + micFile->close(); + spkrFile->close(); + echoFile->close(); - delete micFile; - delete spkrFile; - delete echoFile; + delete micFile; + delete spkrFile; + delete echoFile; } -void SpeexEchoCancel::reset() -{ +void SpeexEchoCancel::reset() { } -void SpeexEchoCancel::putData(SFLDataFormat *inputData, int nbBytes) -{ - // std::cout << "putData nbBytes: " << nbBytes << std::endl; +void SpeexEchoCancel::putData (SFLDataFormat *inputData, int nbBytes) { + // std::cout << "putData nbBytes: " << nbBytes << std::endl; - if(_spkrStoped) { - _micData->flushAll(); - _spkrData->flushAll(); - _spkrStoped = false; - } + if (_spkrStoped) { + _micData->flushAll(); + _spkrData->flushAll(); + _spkrStoped = false; + } - // Put data in speaker ring buffer - _spkrData->Put(inputData, nbBytes); + // Put data in speaker ring buffer + _spkrData->Put (inputData, nbBytes); - // In case we use libspeex internal buffer - // (require capture and playback stream to be synchronized) - // speex_echo_playback(_echoState, inputData); + // In case we use libspeex internal buffer + // (require capture and playback stream to be synchronized) + // speex_echo_playback(_echoState, inputData); } -void SpeexEchoCancel::process(SFLDataFormat *data, int nbBytes) {} +void SpeexEchoCancel::process (SFLDataFormat *data, int nbBytes) {} -int SpeexEchoCancel::process(SFLDataFormat *inputData, SFLDataFormat *outputData, int nbBytes) -{ +int SpeexEchoCancel::process (SFLDataFormat *inputData, SFLDataFormat *outputData, int nbBytes) { - if(_spkrStoped) { - return 0; - } + if (_spkrStoped) { + return 0; + } - int byteSize = FRAME_SIZE*2; + int byteSize = FRAME_SIZE*2; - // init temporary buffers - memset(_tmpSpkr, 0, 5000); - memset(_tmpMic, 0, 5000); - memset(_tmpOut, 0, 5000); + // init temporary buffers + memset (_tmpSpkr, 0, 5000); + memset (_tmpMic, 0, 5000); + memset (_tmpOut, 0, 5000); - // Put mic data in ringbuffer - _micData->Put(inputData, nbBytes); + // Put mic data in ringbuffer + _micData->Put (inputData, nbBytes); - // Store data for synchronization - int spkrAvail = _spkrData->AvailForGet(); - int micAvail = _micData->AvailForGet(); + // Store data for synchronization + int spkrAvail = _spkrData->AvailForGet(); + int micAvail = _micData->AvailForGet(); - // Init number of frame processed - int nbFrame = 0; + // Init number of frame processed + int nbFrame = 0; - // Get data from mic and speaker - while((spkrAvail > byteSize) && (micAvail > byteSize)) { + // Get data from mic and speaker + while ( (spkrAvail > byteSize) && (micAvail > byteSize)) { - // get synchronized data - _spkrData->Get(_tmpSpkr, byteSize); - _micData->Get(_tmpMic, byteSize); + // get synchronized data + _spkrData->Get (_tmpSpkr, byteSize); + _micData->Get (_tmpMic, byteSize); - speex_preprocess_run(_preState, _tmpMic); + speex_preprocess_run (_preState, _tmpMic); - micFile->write ((const char *)_tmpMic, byteSize); - spkrFile->write ((const char *)_tmpSpkr, byteSize); + micFile->write ( (const char *) _tmpMic, byteSize); + spkrFile->write ( (const char *) _tmpSpkr, byteSize); - // Processed echo cancellation - speex_echo_cancellation(_echoState, _tmpMic, _tmpSpkr, _tmpOut); + // Processed echo cancellation + speex_echo_cancellation (_echoState, _tmpMic, _tmpSpkr, _tmpOut); - // speex_preprocess_run(_preState, _tmpOut); + // speex_preprocess_run(_preState, _tmpOut); - bcopy(_tmpOut, outputData+(nbFrame*FRAME_SIZE), byteSize); + bcopy (_tmpOut, outputData+ (nbFrame*FRAME_SIZE), byteSize); - echoFile->write ((const char *)_tmpOut, byteSize); + echoFile->write ( (const char *) _tmpOut, byteSize); - spkrAvail = _spkrData->AvailForGet(); - micAvail = _micData->AvailForGet(); + spkrAvail = _spkrData->AvailForGet(); + micAvail = _micData->AvailForGet(); - // increment nb of frame processed - ++nbFrame; - } + // increment nb of frame processed + ++nbFrame; + } - return nbFrame * FRAME_SIZE; + return nbFrame * FRAME_SIZE; } -void SpeexEchoCancel::process(SFLDataFormat *micData, SFLDataFormat *spkrData, SFLDataFormat *outputData, int nbBytes){ +void SpeexEchoCancel::process (SFLDataFormat *micData, SFLDataFormat *spkrData, SFLDataFormat *outputData, int nbBytes) { - - // speex_echo_cancellation(_echoState, micData, spkrData, outputData); + + // speex_echo_cancellation(_echoState, micData, spkrData, outputData); } diff --git a/sflphone-common/src/call.cpp b/sflphone-common/src/call.cpp index c640ad77b80d9e49f999cf2d142a21e8aadb9433..65e896930c778182ace15798ad4514b9186e8c7a 100644 --- a/sflphone-common/src/call.cpp +++ b/sflphone-common/src/call.cpp @@ -45,48 +45,41 @@ Call::Call (const CallID& id, Call::CallType type) , _callState (Call::Inactive) , _callConfig (Call::Classic) , _peerName() - , _peerNumber() -{ + , _peerNumber() { } -Call::~Call() -{ +Call::~Call() { } void -Call::setConnectionState (ConnectionState state) -{ +Call::setConnectionState (ConnectionState state) { ost::MutexLock m (_callMutex); _connectionState = state; } Call::ConnectionState -Call::getConnectionState() -{ +Call::getConnectionState() { ost::MutexLock m (_callMutex); return _connectionState; } void -Call::setState (CallState state) -{ +Call::setState (CallState state) { ost::MutexLock m (_callMutex); _callState = state; } Call::CallState -Call::getState() -{ +Call::getState() { ost::MutexLock m (_callMutex); return _callState; } std::string -Call::getStateStr () -{ +Call::getStateStr () { CallState state = getState(); ConnectionState connection = getConnectionState (); CallType type = _type; @@ -158,65 +151,60 @@ Call::getStateStr () const std::string& -Call::getLocalIp() -{ +Call::getLocalIp() { ost::MutexLock m (_callMutex); return _localIPAddress; } unsigned int -Call::getLocalAudioPort() -{ +Call::getLocalAudioPort() { ost::MutexLock m (_callMutex); return _localAudioPort; } void -Call::setAudioStart (bool start) -{ +Call::setAudioStart (bool start) { ost::MutexLock m (_callMutex); _audioStarted = start; } bool -Call::isAudioStarted() -{ +Call::isAudioStarted() { ost::MutexLock m (_callMutex); return _audioStarted; } bool -Call::setRecording() -{ +Call::setRecording() { bool recordStatus = Recordable::recAudio.isRecording(); Recordable::recAudio.setRecording(); // Start recording - if(!recordStatus) { + if (!recordStatus) { - MainBuffer *mbuffer = Manager::instance().getMainBuffer(); - CallID process_id = Recordable::recorder.getRecorderID(); + MainBuffer *mbuffer = Manager::instance().getMainBuffer(); + CallID process_id = Recordable::recorder.getRecorderID(); - mbuffer->bindHalfDuplexOut(process_id, _id); - mbuffer->bindHalfDuplexOut(process_id); + mbuffer->bindHalfDuplexOut (process_id, _id); + mbuffer->bindHalfDuplexOut (process_id); } // Stop recording else { - MainBuffer *mbuffer = Manager::instance().getMainBuffer(); - CallID process_id = Recordable::recorder.getRecorderID(); + MainBuffer *mbuffer = Manager::instance().getMainBuffer(); + CallID process_id = Recordable::recorder.getRecorderID(); - mbuffer->unBindHalfDuplexOut(process_id, _id); - mbuffer->unBindHalfDuplexOut(process_id); + mbuffer->unBindHalfDuplexOut (process_id, _id); + mbuffer->unBindHalfDuplexOut (process_id); } Manager::instance().getMainBuffer()->stateInfo(); Recordable::recorder.start(); - + return recordStatus; } diff --git a/sflphone-common/src/conference.cpp b/sflphone-common/src/conference.cpp index 8ac1ce32820676f198dae5854c27001cc2cfa5eb..2adf50dae605ffbbc2a15635f24644750d09640f 100644 --- a/sflphone-common/src/conference.cpp +++ b/sflphone-common/src/conference.cpp @@ -38,8 +38,7 @@ int Conference::count = 0; -Conference::Conference() -{ +Conference::Conference() { _nbParticipant = 0; ++count; @@ -60,28 +59,24 @@ Conference::Conference() } -Conference::~Conference() -{ +Conference::~Conference() { } -int Conference::getState() -{ +int Conference::getState() { return _confState; } -void Conference::setState (ConferenceState state) -{ +void Conference::setState (ConferenceState state) { _confState = state; } -void Conference::add (CallID participant_id) -{ +void Conference::add (CallID participant_id) { _debug ("Conference:: add participant %s", participant_id.c_str()); @@ -91,8 +86,7 @@ void Conference::add (CallID participant_id) } -void Conference::remove (CallID participant_id) -{ +void Conference::remove (CallID participant_id) { _debug ("Conference::remove participant %s", participant_id.c_str()); @@ -103,8 +97,7 @@ void Conference::remove (CallID participant_id) } -void Conference::bindParticipant (CallID participant_id) -{ +void Conference::bindParticipant (CallID participant_id) { if (_nbParticipant >= 1) { ParticipantSet::iterator iter = _participants.begin(); @@ -126,8 +119,7 @@ void Conference::bindParticipant (CallID participant_id) } -std::string Conference::getStateStr() -{ +std::string Conference::getStateStr() { std::string state_str; @@ -153,8 +145,7 @@ std::string Conference::getStateStr() } -ParticipantSet Conference::getParticipantList() -{ +ParticipantSet Conference::getParticipantList() { return _participants; } @@ -162,49 +153,49 @@ ParticipantSet Conference::getParticipantList() bool Conference::setRecording() { - bool recordStatus = Recordable::recAudio.isRecording(); + bool recordStatus = Recordable::recAudio.isRecording(); - Recordable::recAudio.setRecording(); + Recordable::recAudio.setRecording(); - // start recording - if(!recordStatus){ + // start recording + if (!recordStatus) { - MainBuffer *mbuffer = Manager::instance().getMainBuffer(); + MainBuffer *mbuffer = Manager::instance().getMainBuffer(); - ParticipantSet::iterator iter = _participants.begin(); + ParticipantSet::iterator iter = _participants.begin(); - CallID process_id = Recordable::recorder.getRecorderID(); + CallID process_id = Recordable::recorder.getRecorderID(); - while(iter != _participants.end()) { - mbuffer->bindHalfDuplexOut(process_id, *iter); - iter++; - } + while (iter != _participants.end()) { + mbuffer->bindHalfDuplexOut (process_id, *iter); + iter++; + } - mbuffer->bindHalfDuplexOut(process_id); + mbuffer->bindHalfDuplexOut (process_id); - Recordable::recorder.start(); + Recordable::recorder.start(); - } - // stop recording - else { + } + // stop recording + else { - MainBuffer *mbuffer = Manager::instance().getMainBuffer(); + MainBuffer *mbuffer = Manager::instance().getMainBuffer(); - ParticipantSet::iterator iter = _participants.begin(); + ParticipantSet::iterator iter = _participants.begin(); - CallID process_id = Recordable::recorder.getRecorderID(); + CallID process_id = Recordable::recorder.getRecorderID(); - while(iter != _participants.end()) { - mbuffer->unBindHalfDuplexOut(process_id, *iter); - iter++; - } + while (iter != _participants.end()) { + mbuffer->unBindHalfDuplexOut (process_id, *iter); + iter++; + } - mbuffer->unBindHalfDuplexOut(process_id); + mbuffer->unBindHalfDuplexOut (process_id); - // Recordable::recorder.start(); + // Recordable::recorder.start(); - } + } - return recordStatus; + return recordStatus; } diff --git a/sflphone-common/src/config/config.cpp b/sflphone-common/src/config/config.cpp old mode 100755 new mode 100644 index 9f735964de9e45de8aa005817d8b7b714f6d13ac..ab76bd1adc201a7ac41ea60a95b758aec90af954 --- a/sflphone-common/src/config/config.cpp +++ b/sflphone-common/src/config/config.cpp @@ -40,17 +40,14 @@ #include <string.h> #include "yamlparser.h" -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(); @@ -62,8 +59,7 @@ ConfigTree::~ConfigTree() } } -void ConfigTree::addDefaultValue (const std::pair<std::string, std::string>& token, std::string section) -{ +void ConfigTree::addDefaultValue (const std::pair<std::string, std::string>& token, std::string section) { _defaultValueMap.insert (token); if (section.empty() == false) { @@ -71,8 +67,7 @@ void ConfigTree::addDefaultValue (const std::pair<std::string, std::string>& tok } } -std::string ConfigTree::getDefaultValue (const std::string& key) -{ +std::string ConfigTree::getDefaultValue (const std::string& key) { std::map<std::string, std::string>::iterator it; it = _defaultValueMap.find (key); @@ -87,8 +82,7 @@ std::string ConfigTree::getDefaultValue (const std::string& key) * Create the section only if it doesn't exists */ void -ConfigTree::createSection (const std::string& section) -{ +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; @@ -99,8 +93,7 @@ ConfigTree::createSection (const std::string& section) * Remove the section only if it exists */ void -ConfigTree::removeSection (const std::string& section) -{ +ConfigTree::removeSection (const std::string& section) { // if we doesn't find the item, create it SectionMap::iterator iter = _sections.find (section); @@ -111,8 +104,7 @@ ConfigTree::removeSection (const std::string& section) /** Retrieve the sections as an array */ TokenList -ConfigTree::getSections() -{ +ConfigTree::getSections() { TokenList sections; SectionMap::iterator iter = _sections.begin(); @@ -131,8 +123,7 @@ ConfigTree::getSections() * If the section doesn't exists, create it */ void -ConfigTree::addConfigTreeItem (const std::string& section, const ConfigTreeItem item) -{ +ConfigTree::addConfigTreeItem (const std::string& section, const ConfigTreeItem item) { // if we doesn't find the item, create it SectionMap::iterator iter = _sections.find (section); @@ -152,8 +143,7 @@ ConfigTree::addConfigTreeItem (const std::string& section, const ConfigTreeItem } std::string -ConfigTree::getConfigTreeItemValue (const std::string& section, const std::string& itemName) -{ +ConfigTree::getConfigTreeItemValue (const std::string& section, const std::string& itemName) { ConfigTreeItem* item = getConfigTreeItem (section, itemName); if (item != NULL) { @@ -165,8 +155,7 @@ ConfigTree::getConfigTreeItemValue (const std::string& section, const std::strin // throw a ConfigTreeItemException if not found int -ConfigTree::getConfigTreeItemIntValue (const std::string& section, const std::string& itemName) -{ +ConfigTree::getConfigTreeItemIntValue (const std::string& section, const std::string& itemName) { std::string configItem = getConfigTreeItemValue (section, itemName); int retval = atoi (configItem.data()); @@ -174,8 +163,7 @@ ConfigTree::getConfigTreeItemIntValue (const std::string& section, const std::st } bool -ConfigTree::getConfigTreeItemBoolValue (const std::string& section, const std::string& itemName) -{ +ConfigTree::getConfigTreeItemBoolValue (const std::string& section, const std::string& itemName) { std::string configItem = getConfigTreeItemValue (section, itemName); if (configItem == "true") { @@ -186,8 +174,7 @@ ConfigTree::getConfigTreeItemBoolValue (const std::string& section, const std::s } bool -ConfigTree::getConfigTreeItemToken (const std::string& section, const std::string& itemName, TokenList& arg) -{ +ConfigTree::getConfigTreeItemToken (const std::string& section, const std::string& itemName, TokenList& arg) { ConfigTreeItem *item = getConfigTreeItem (section, itemName); if (item) { @@ -207,19 +194,18 @@ ConfigTree::getConfigTreeItemToken (const std::string& section, const std::strin * Return a ConfigTreeItem or NULL if not found */ ConfigTreeItem* -ConfigTree::getConfigTreeItem (const std::string& section, const std::string& itemName) -{ +ConfigTree::getConfigTreeItem (const std::string& section, const std::string& itemName) { SectionMap::iterator iter = _sections.find (section); if (iter == _sections.end()) { - // _error("ConfigTree: Error: Did not found section %s in config tree", section.c_str()); + // _error("ConfigTree: Error: Did not found section %s in config tree", section.c_str()); return NULL; } ItemMap::iterator iterItem = iter->second->find (itemName); if (iterItem == iter->second->end()) { - // _error("ConfigTree: Error: Did not found item %s in config tree", itemName.c_str()); + // _error("ConfigTree: Error: Did not found item %s in config tree", itemName.c_str()); return NULL; } @@ -235,8 +221,7 @@ ConfigTree::getConfigTreeItem (const std::string& section, const std::string& it bool ConfigTree::setConfigTreeItem (const std::string& section, const std::string& itemName, - const std::string& value) -{ + const std::string& value) { SectionMap::iterator iter = _sections.find (section); @@ -271,8 +256,7 @@ ConfigTree::setConfigTreeItem (const std::string& section, // return false if empty, no config, or enable to open // return true if everything is ok bool -ConfigTree::saveConfigTree (const std::string& fileName) -{ +ConfigTree::saveConfigTree (const std::string& fileName) { if (fileName.empty() && _sections.begin() == _sections.end()) { return false; } @@ -282,7 +266,7 @@ ConfigTree::saveConfigTree (const std::string& fileName) file.open (fileName.data(), std::fstream::out); if (!file.is_open()) { - _error("ConfigTree: Error: Could not open %s configuration file", fileName.c_str()); + _error ("ConfigTree: Error: Could not open %s configuration file", fileName.c_str()); return false; } @@ -306,7 +290,7 @@ ConfigTree::saveConfigTree (const std::string& fileName) file.close(); if (chmod (fileName.c_str(), S_IRUSR | S_IWUSR)) { - _error("ConfigTree: Error: Failed to set permission on configuration: %s",strerror (errno)); + _error ("ConfigTree: Error: Failed to set permission on configuration: %s",strerror (errno)); } return true; @@ -317,8 +301,7 @@ ConfigTree::saveConfigTree (const std::string& fileName) // 1 = OK // 2 = unable to open int -ConfigTree::populateFromFile (const std::string& fileName) -{ +ConfigTree::populateFromFile (const std::string& fileName) { bool out = false; if (fileName.empty()) { @@ -380,15 +363,16 @@ ConfigTree::populateFromFile (const std::string& fileName) if (key.length() > 0 && val.length() > 0) { setConfigTreeItem (section, key, val); } - /* - if (key.length() > 0) { - if(val.length() > 0) - setConfigTreeItem (section, key, val); - else - setConfigTreeItem (section, key, ""); - } - */ + /* + if (key.length() > 0) { + + if(val.length() > 0) + setConfigTreeItem (section, key, val); + else + setConfigTreeItem (section, key, ""); + } + */ } } } @@ -403,8 +387,7 @@ ConfigTree::populateFromFile (const std::string& fileName) } TokenList -ConfigTreeIterator::begin() -{ +ConfigTreeIterator::begin() { TokenList tk; _iter = _tree->_sections.begin(); @@ -424,8 +407,7 @@ ConfigTreeIterator::begin() } TokenList -ConfigTreeIterator::next() -{ +ConfigTreeIterator::next() { TokenList tk; // we return tk empty if we are at the end of the list... diff --git a/sflphone-common/src/config/config.h b/sflphone-common/src/config/config.h old mode 100755 new mode 100644 index c304045f60d37ec5378eede250e68d59eb866dae..3c5e8a772bb42e3df2f0e0f0cff0a950b070317a --- a/sflphone-common/src/config/config.h +++ b/sflphone-common/src/config/config.h @@ -41,16 +41,14 @@ * @brief Configuration namespace for ConfigTree object (like .ini files) */ -namespace Conf -{ +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: /** @@ -66,8 +64,7 @@ class ConfigTreeItemException class ConfigTree; -class ConfigTreeIterator -{ +class ConfigTreeIterator { public: /** @@ -104,8 +101,7 @@ class ConfigTreeIterator ItemMap::iterator _iterItem; }; -class ConfigTree -{ +class ConfigTree { public: ConfigTree(); @@ -193,8 +189,7 @@ class ConfigTree } }; -class ConfigTreeItem -{ +class ConfigTreeItem { public: ConfigTreeItem() : _name (""), _value (""), _defaultValue (""), _type ("string") {} diff --git a/sflphone-common/src/config/yamlemitter.cpp b/sflphone-common/src/config/yamlemitter.cpp old mode 100755 new mode 100644 index 1eb51e2cfb6d68880ef576d799e3de5ddfe1168d..37c881bf07726de81ff0c9f80602758f0bda35c7 --- a/sflphone-common/src/config/yamlemitter.cpp +++ b/sflphone-common/src/config/yamlemitter.cpp @@ -34,335 +34,319 @@ namespace Conf { -YamlEmitter::YamlEmitter(const char *file) : filename(file), isFirstAccount(true) -{ - open(); +YamlEmitter::YamlEmitter (const char *file) : filename (file), isFirstAccount (true) { + open(); } -YamlEmitter::~YamlEmitter() -{ - close(); +YamlEmitter::~YamlEmitter() { + close(); } -void YamlEmitter::open() -{ - fd = fopen(filename.c_str(), "wb"); +void YamlEmitter::open() { + fd = fopen (filename.c_str(), "wb"); - if(!fd) - throw YamlEmitterException("Could not open file descriptor"); + if (!fd) + throw YamlEmitterException ("Could not open file descriptor"); - if(!yaml_emitter_initialize(&emitter)) - throw YamlEmitterException("Could not initialize emitter"); + if (!yaml_emitter_initialize (&emitter)) + throw YamlEmitterException ("Could not initialize emitter"); - // Use unicode format - yaml_emitter_set_unicode(&emitter, 1); + // Use unicode format + yaml_emitter_set_unicode (&emitter, 1); - yaml_emitter_set_output_file(&emitter, fd); + yaml_emitter_set_output_file (&emitter, fd); - yaml_document_initialize(&document, NULL, NULL, NULL, 0, 0); + yaml_document_initialize (&document, NULL, NULL, NULL, 0, 0); - // Init the main configuration mapping - if((topLevelMapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) - throw YamlEmitterException("Could not create top level mapping"); + // Init the main configuration mapping + if ( (topLevelMapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) + throw YamlEmitterException ("Could not create top level mapping"); } -void YamlEmitter::close() -{ - // yaml_emitter_delete(&emitter); +void YamlEmitter::close() { + // yaml_emitter_delete(&emitter); - if(!fd) - throw YamlEmitterException("File descriptor not valid"); - - fclose(fd); - /* - if(!fclose(fd)) - throw YamlEmitterException("Error closing file descriptor"); - */ + if (!fd) + throw YamlEmitterException ("File descriptor not valid"); - yaml_document_delete(&document); + fclose (fd); + /* + if(!fclose(fd)) + throw YamlEmitterException("Error closing file descriptor"); + */ + + yaml_document_delete (&document); } void YamlEmitter::read() {} -void YamlEmitter::write() -{ +void YamlEmitter::write() { } -void YamlEmitter::serializeData() -{ - yaml_emitter_dump(&emitter, &document); +void YamlEmitter::serializeData() { + yaml_emitter_dump (&emitter, &document); } -void YamlEmitter::serializeAccount(MappingNode *map) -{ +void YamlEmitter::serializeAccount (MappingNode *map) { + + std::string accountstr ("accounts"); - std::string accountstr("accounts"); - - int accountid, accountmapping; + int accountid, accountmapping; - _debug("YamlEmitter: Serialize account"); + _debug ("YamlEmitter: Serialize account"); - if(map->getType() != MAPPING) - throw YamlEmitterException("Node type is not a mapping while writing account"); + if (map->getType() != MAPPING) + throw YamlEmitterException ("Node type is not a mapping while writing account"); - if(isFirstAccount) { - // accountSequence need to be static outside this scope since reused each time an account is written - if((accountid = yaml_document_add_scalar(&document, NULL, (yaml_char_t *)accountstr.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) - throw YamlEmitterException("Could not add preference scalar to document"); + if (isFirstAccount) { + // accountSequence need to be static outside this scope since reused each time an account is written + if ( (accountid = yaml_document_add_scalar (&document, NULL, (yaml_char_t *) accountstr.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) + throw YamlEmitterException ("Could not add preference scalar to document"); - if((accountSequence = yaml_document_add_sequence (&document, NULL, YAML_BLOCK_SEQUENCE_STYLE)) == 0) - throw YamlEmitterException("Could not add sequence to document"); + if ( (accountSequence = yaml_document_add_sequence (&document, NULL, YAML_BLOCK_SEQUENCE_STYLE)) == 0) + throw YamlEmitterException ("Could not add sequence to document"); - if(!yaml_document_append_mapping_pair (&document, topLevelMapping, accountid, accountSequence)) - throw YamlEmitterException("Could not add mapping pair to top level mapping"); - - isFirstAccount = false; - } + if (!yaml_document_append_mapping_pair (&document, topLevelMapping, accountid, accountSequence)) + throw YamlEmitterException ("Could not add mapping pair to top level mapping"); + + isFirstAccount = false; + } - if((accountmapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) - throw YamlEmitterException("Could not add account mapping to document"); + if ( (accountmapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) + throw YamlEmitterException ("Could not add account mapping to document"); - if(!yaml_document_append_sequence_item (&document, accountSequence, accountmapping)) - throw YamlEmitterException("Could not append account mapping to sequence"); + if (!yaml_document_append_sequence_item (&document, accountSequence, accountmapping)) + throw YamlEmitterException ("Could not append account mapping to sequence"); - Mapping *internalmap = map->getMapping(); - Mapping::iterator iter = internalmap->begin(); + Mapping *internalmap = map->getMapping(); + Mapping::iterator iter = internalmap->begin(); - while(iter != internalmap->end()) { - addMappingItem(accountmapping, iter->first, iter->second); - iter++; - } + while (iter != internalmap->end()) { + addMappingItem (accountmapping, iter->first, iter->second); + iter++; + } } -void YamlEmitter::serializePreference(MappingNode *map) -{ - std::string preferencestr("preferences"); +void YamlEmitter::serializePreference (MappingNode *map) { + std::string preferencestr ("preferences"); - int preferenceid, preferencemapping; + int preferenceid, preferencemapping; - _debug("YamlEmitter: Serialize preference"); + _debug ("YamlEmitter: Serialize preference"); - if(map->getType() != MAPPING) - throw YamlEmitterException("Node type is not a mapping while writing preferences"); + if (map->getType() != MAPPING) + throw YamlEmitterException ("Node type is not a mapping while writing preferences"); - if((preferenceid = yaml_document_add_scalar(&document, NULL, (yaml_char_t *)preferencestr.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) - throw YamlEmitterException("Could not add scalar to document"); + if ( (preferenceid = yaml_document_add_scalar (&document, NULL, (yaml_char_t *) preferencestr.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) + throw YamlEmitterException ("Could not add scalar to document"); - if((preferencemapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) - throw YamlEmitterException("Could not add mapping to document"); + if ( (preferencemapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) + throw YamlEmitterException ("Could not add mapping to document"); - if(!yaml_document_append_mapping_pair (&document, topLevelMapping, preferenceid, preferencemapping)) - throw YamlEmitterException("Could not add mapping pair to top leve mapping"); + if (!yaml_document_append_mapping_pair (&document, topLevelMapping, preferenceid, preferencemapping)) + throw YamlEmitterException ("Could not add mapping pair to top leve mapping"); - Mapping *internalmap = map->getMapping(); - Mapping::iterator iter = internalmap->begin(); + Mapping *internalmap = map->getMapping(); + Mapping::iterator iter = internalmap->begin(); - while(iter != internalmap->end()) { - addMappingItem(preferencemapping, iter->first, iter->second); - iter++; - } + while (iter != internalmap->end()) { + addMappingItem (preferencemapping, iter->first, iter->second); + iter++; + } } -void YamlEmitter::serializeVoipPreference(MappingNode *map) -{ - std::string preferencestr("voipPreferences"); +void YamlEmitter::serializeVoipPreference (MappingNode *map) { + std::string preferencestr ("voipPreferences"); - int preferenceid, preferencemapping; + int preferenceid, preferencemapping; - _debug("YamlEmitter: Serialize voip preference"); + _debug ("YamlEmitter: Serialize voip preference"); - if(map->getType() != MAPPING) - throw YamlEmitterException("Node type is not a mapping while writing preferences"); + if (map->getType() != MAPPING) + throw YamlEmitterException ("Node type is not a mapping while writing preferences"); - if((preferenceid = yaml_document_add_scalar(&document, NULL, (yaml_char_t *)preferencestr.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) - throw YamlEmitterException("Could not add scalar to document"); + if ( (preferenceid = yaml_document_add_scalar (&document, NULL, (yaml_char_t *) preferencestr.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) + throw YamlEmitterException ("Could not add scalar to document"); - if((preferencemapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) - throw YamlEmitterException("Could not add mapping to document"); + if ( (preferencemapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) + throw YamlEmitterException ("Could not add mapping to document"); - if(!yaml_document_append_mapping_pair (&document, topLevelMapping, preferenceid, preferencemapping)) - throw YamlEmitterException("Could not add mapping pair to top leve mapping"); + if (!yaml_document_append_mapping_pair (&document, topLevelMapping, preferenceid, preferencemapping)) + throw YamlEmitterException ("Could not add mapping pair to top leve mapping"); - Mapping *internalmap = map->getMapping(); - Mapping::iterator iter = internalmap->begin(); + Mapping *internalmap = map->getMapping(); + Mapping::iterator iter = internalmap->begin(); - while(iter != internalmap->end()) { - addMappingItem(preferencemapping, iter->first, iter->second); - iter++; - } + while (iter != internalmap->end()) { + addMappingItem (preferencemapping, iter->first, iter->second); + iter++; + } } -void YamlEmitter::serializeAddressbookPreference(MappingNode *map) -{ - std::string preferencestr("addressbook"); +void YamlEmitter::serializeAddressbookPreference (MappingNode *map) { + std::string preferencestr ("addressbook"); - int preferenceid, preferencemapping; + int preferenceid, preferencemapping; - _debug("YamlEmitter: Serialize addressbook preferences"); + _debug ("YamlEmitter: Serialize addressbook preferences"); - if(map->getType() != MAPPING) - throw YamlEmitterException("Node type is not a mapping while writing preferences"); + if (map->getType() != MAPPING) + throw YamlEmitterException ("Node type is not a mapping while writing preferences"); - if((preferenceid = yaml_document_add_scalar(&document, NULL, (yaml_char_t *)preferencestr.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) - throw YamlEmitterException("Could not add scalar to document"); + if ( (preferenceid = yaml_document_add_scalar (&document, NULL, (yaml_char_t *) preferencestr.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) + throw YamlEmitterException ("Could not add scalar to document"); - if((preferencemapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) - throw YamlEmitterException("Could not add mapping to document"); + if ( (preferencemapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) + throw YamlEmitterException ("Could not add mapping to document"); - if(!yaml_document_append_mapping_pair (&document, topLevelMapping, preferenceid, preferencemapping)) - throw YamlEmitterException("Could not add mapping pair to top leve mapping"); + if (!yaml_document_append_mapping_pair (&document, topLevelMapping, preferenceid, preferencemapping)) + throw YamlEmitterException ("Could not add mapping pair to top leve mapping"); - Mapping *internalmap = map->getMapping(); - Mapping::iterator iter = internalmap->begin(); + Mapping *internalmap = map->getMapping(); + Mapping::iterator iter = internalmap->begin(); - while(iter != internalmap->end()) { - addMappingItem(preferencemapping, iter->first, iter->second); - iter++; - } + while (iter != internalmap->end()) { + addMappingItem (preferencemapping, iter->first, iter->second); + iter++; + } } -void YamlEmitter::serializeHooksPreference(MappingNode *map) -{ - std::string preferencestr("hooks"); +void YamlEmitter::serializeHooksPreference (MappingNode *map) { + std::string preferencestr ("hooks"); - int preferenceid, preferencemapping; + int preferenceid, preferencemapping; - _debug("YamlEmitter: Serialize hooks preferences"); + _debug ("YamlEmitter: Serialize hooks preferences"); - if(map->getType() != MAPPING) - throw YamlEmitterException("Node type is not a mapping while writing preferences"); + if (map->getType() != MAPPING) + throw YamlEmitterException ("Node type is not a mapping while writing preferences"); - if((preferenceid = yaml_document_add_scalar(&document, NULL, (yaml_char_t *)preferencestr.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) - throw YamlEmitterException("Could not add scalar to document"); + if ( (preferenceid = yaml_document_add_scalar (&document, NULL, (yaml_char_t *) preferencestr.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) + throw YamlEmitterException ("Could not add scalar to document"); - if((preferencemapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) - throw YamlEmitterException("Could not add mapping to document"); + if ( (preferencemapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) + throw YamlEmitterException ("Could not add mapping to document"); - if(!yaml_document_append_mapping_pair (&document, topLevelMapping, preferenceid, preferencemapping)) - throw YamlEmitterException("Could not add mapping pair to top leve mapping"); + if (!yaml_document_append_mapping_pair (&document, topLevelMapping, preferenceid, preferencemapping)) + throw YamlEmitterException ("Could not add mapping pair to top leve mapping"); - Mapping *internalmap = map->getMapping(); - Mapping::iterator iter = internalmap->begin(); + Mapping *internalmap = map->getMapping(); + Mapping::iterator iter = internalmap->begin(); - while(iter != internalmap->end()) { - addMappingItem(preferencemapping, iter->first, iter->second); - iter++; - } + while (iter != internalmap->end()) { + addMappingItem (preferencemapping, iter->first, iter->second); + iter++; + } } -void YamlEmitter::serializeAudioPreference(MappingNode *map) -{ - std::string preferencestr("audio"); +void YamlEmitter::serializeAudioPreference (MappingNode *map) { + std::string preferencestr ("audio"); - int preferenceid, preferencemapping; + int preferenceid, preferencemapping; - _debug("YamlEmitter: Serialize hooks preferences"); + _debug ("YamlEmitter: Serialize hooks preferences"); - if(map->getType() != MAPPING) - throw YamlEmitterException("Node type is not a mapping while writing preferences"); + if (map->getType() != MAPPING) + throw YamlEmitterException ("Node type is not a mapping while writing preferences"); - if((preferenceid = yaml_document_add_scalar(&document, NULL, (yaml_char_t *)preferencestr.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) - throw YamlEmitterException("Could not add scalar to document"); + if ( (preferenceid = yaml_document_add_scalar (&document, NULL, (yaml_char_t *) preferencestr.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) + throw YamlEmitterException ("Could not add scalar to document"); - if((preferencemapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) - throw YamlEmitterException("Could not add mapping to document"); + if ( (preferencemapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) + throw YamlEmitterException ("Could not add mapping to document"); - if(!yaml_document_append_mapping_pair (&document, topLevelMapping, preferenceid, preferencemapping)) - throw YamlEmitterException("Could not add mapping pair to top leve mapping"); + if (!yaml_document_append_mapping_pair (&document, topLevelMapping, preferenceid, preferencemapping)) + throw YamlEmitterException ("Could not add mapping pair to top leve mapping"); - Mapping *internalmap = map->getMapping(); - Mapping::iterator iter = internalmap->begin(); + Mapping *internalmap = map->getMapping(); + Mapping::iterator iter = internalmap->begin(); - while(iter != internalmap->end()) { - addMappingItem(preferencemapping, iter->first, iter->second); - iter++; - } + while (iter != internalmap->end()) { + addMappingItem (preferencemapping, iter->first, iter->second); + iter++; + } } -void YamlEmitter::serializeShortcutPreference(MappingNode *map) -{ - std::string preferencestr("shortcuts"); +void YamlEmitter::serializeShortcutPreference (MappingNode *map) { + std::string preferencestr ("shortcuts"); - int preferenceid, preferencemapping; + int preferenceid, preferencemapping; - _debug("YamlEmitter: Serialize shortcuts preferences"); + _debug ("YamlEmitter: Serialize shortcuts preferences"); - if(map->getType() != MAPPING) - throw YamlEmitterException("Node type is not a mapping while writing preferences"); + if (map->getType() != MAPPING) + throw YamlEmitterException ("Node type is not a mapping while writing preferences"); - if((preferenceid = yaml_document_add_scalar(&document, NULL, (yaml_char_t *)preferencestr.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) - throw YamlEmitterException("Could not add scalar to document"); + if ( (preferenceid = yaml_document_add_scalar (&document, NULL, (yaml_char_t *) preferencestr.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) + throw YamlEmitterException ("Could not add scalar to document"); - if((preferencemapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) - throw YamlEmitterException("Could not add mapping to document"); + if ( (preferencemapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) + throw YamlEmitterException ("Could not add mapping to document"); - if(!yaml_document_append_mapping_pair (&document, topLevelMapping, preferenceid, preferencemapping)) - throw YamlEmitterException("Could not add mapping pair to top leve mapping"); + if (!yaml_document_append_mapping_pair (&document, topLevelMapping, preferenceid, preferencemapping)) + throw YamlEmitterException ("Could not add mapping pair to top leve mapping"); - Mapping *internalmap = map->getMapping(); - Mapping::iterator iter = internalmap->begin(); + Mapping *internalmap = map->getMapping(); + Mapping::iterator iter = internalmap->begin(); - while(iter != internalmap->end()) { - addMappingItem(preferencemapping, iter->first, iter->second); - iter++; - } + while (iter != internalmap->end()) { + addMappingItem (preferencemapping, iter->first, iter->second); + iter++; + } } -void YamlEmitter::addMappingItem(int mappingid, Key key, YamlNode *node) -{ +void YamlEmitter::addMappingItem (int mappingid, Key key, YamlNode *node) { - if(node->getType() == SCALAR) { + if (node->getType() == SCALAR) { - int temp1, temp2; + int temp1, temp2; - ScalarNode *sclr = (ScalarNode *)node; + ScalarNode *sclr = (ScalarNode *) node; - if((temp1 = yaml_document_add_scalar(&document, NULL, (yaml_char_t *)key.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) - throw YamlEmitterException("Could not add scalar to document"); + if ( (temp1 = yaml_document_add_scalar (&document, NULL, (yaml_char_t *) key.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) + throw YamlEmitterException ("Could not add scalar to document"); - if((temp2 = yaml_document_add_scalar(&document, NULL, (yaml_char_t *)sclr->getValue().c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) - throw YamlEmitterException("Could not add scalar to document"); + if ( (temp2 = yaml_document_add_scalar (&document, NULL, (yaml_char_t *) sclr->getValue().c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) + throw YamlEmitterException ("Could not add scalar to document"); - if(!yaml_document_append_mapping_pair (&document, mappingid, temp1, temp2)) - throw YamlEmitterException("Could not append mapping pair to mapping"); + if (!yaml_document_append_mapping_pair (&document, mappingid, temp1, temp2)) + throw YamlEmitterException ("Could not append mapping pair to mapping"); - } - else if(node->getType() == MAPPING){ + } else if (node->getType() == MAPPING) { - int temp1, temp2; + int temp1, temp2; - if((temp1 = yaml_document_add_scalar(&document, NULL, (yaml_char_t *)key.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) - throw YamlEmitterException("Could not add scalar to document"); + if ( (temp1 = yaml_document_add_scalar (&document, NULL, (yaml_char_t *) key.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) + throw YamlEmitterException ("Could not add scalar to document"); - if((temp2 = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) - throw YamlEmitterException("Could not add scalar to document"); + if ( (temp2 = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) + throw YamlEmitterException ("Could not add scalar to document"); - if(!yaml_document_append_mapping_pair (&document, mappingid, temp1, temp2)) - throw YamlEmitterException("Could not add mapping pair to mapping"); + if (!yaml_document_append_mapping_pair (&document, mappingid, temp1, temp2)) + throw YamlEmitterException ("Could not add mapping pair to mapping"); - MappingNode *map = (MappingNode *)node; - Mapping *internalmap = map->getMapping(); - Mapping::iterator iter = internalmap->begin(); - - while(iter != internalmap->end()) { - addMappingItem(temp2, iter->first, iter->second); - iter++; - } - } - else - throw YamlEmitterException("Unknown node type while adding mapping node"); + MappingNode *map = (MappingNode *) node; + Mapping *internalmap = map->getMapping(); + Mapping::iterator iter = internalmap->begin(); + + while (iter != internalmap->end()) { + addMappingItem (temp2, iter->first, iter->second); + iter++; + } + } else + throw YamlEmitterException ("Unknown node type while adding mapping node"); } diff --git a/sflphone-common/src/config/yamlengine.cpp b/sflphone-common/src/config/yamlengine.cpp old mode 100755 new mode 100644 index 30a2545bfdea02643916d02cbbef5565196335fa..8ae05bb3ef1f73cb00ec782788db7bf35e64f54d --- a/sflphone-common/src/config/yamlengine.cpp +++ b/sflphone-common/src/config/yamlengine.cpp @@ -38,44 +38,38 @@ YamlEngine::YamlEngine() {} YamlEngine::~YamlEngine() {} -void YamlEngine::openConfigFile() -{ - - Conf::YamlParser *parser; - - try { - parser = new Conf::YamlParser("sequence.yml"); - } - catch (Conf::YamlParserException &e) { - _error("ConfigTree: %s", e.what()); - } - - try { - parser->serializeEvents(); - } - catch(Conf::YamlParserException &e) { - _error("ConfigTree: %s", e.what()); - } - - try { - document = parser->composeEvents(); - } - catch(Conf::YamlParserException &e) { - _error("ConfigTree: %s", e.what()); - } - - try { - delete parser; - parser = NULL; - } - catch (Conf::YamlParserException &e) { - _error("ConfigTree: %s", e.what()); - } +void YamlEngine::openConfigFile() { + + Conf::YamlParser *parser; + + try { + parser = new Conf::YamlParser ("sequence.yml"); + } catch (Conf::YamlParserException &e) { + _error ("ConfigTree: %s", e.what()); + } + + try { + parser->serializeEvents(); + } catch (Conf::YamlParserException &e) { + _error ("ConfigTree: %s", e.what()); + } + + try { + document = parser->composeEvents(); + } catch (Conf::YamlParserException &e) { + _error ("ConfigTree: %s", e.what()); + } + + try { + delete parser; + parser = NULL; + } catch (Conf::YamlParserException &e) { + _error ("ConfigTree: %s", e.what()); + } } -void YamlEngine::closeConfigFile() -{ - +void YamlEngine::closeConfigFile() { + } void YamlEngine::read() {} diff --git a/sflphone-common/src/config/yamlnode.cpp b/sflphone-common/src/config/yamlnode.cpp old mode 100755 new mode 100644 index 7a28a6cfa66bfd2545f7cb97b4d1e5cdf5eca1bc..1c9e26b8475d295342e10ae16ccf7823c157eaad --- a/sflphone-common/src/config/yamlnode.cpp +++ b/sflphone-common/src/config/yamlnode.cpp @@ -34,61 +34,53 @@ namespace Conf { -void YamlDocument::addNode(YamlNode *node) -{ - Sequence::iterator it = doc.end(); - doc.insert(it, node); +void YamlDocument::addNode (YamlNode *node) { + Sequence::iterator it = doc.end(); + doc.insert (it, node); } -YamlNode *YamlDocument::popNode() -{ - Sequence::iterator it = doc.begin(); - YamlNode *node = doc.front(); +YamlNode *YamlDocument::popNode() { + Sequence::iterator it = doc.begin(); + YamlNode *node = doc.front(); - //removed element's destructor is called - doc.pop_front(); + //removed element's destructor is called + doc.pop_front(); - return node; + return node; } -void MappingNode::addNode(YamlNode *node) -{ - Mapping::iterator it = map.end(); - map.insert(it, std::pair<Key, YamlNode *>(tmpKey, node)); +void MappingNode::addNode (YamlNode *node) { + Mapping::iterator it = map.end(); + map.insert (it, std::pair<Key, YamlNode *> (tmpKey, node)); } -void MappingNode::setKeyValue(Key key, YamlNode *value) -{ - Mapping::iterator it = map.end(); - map.insert(it, std::pair<Key, YamlNode *>(key, value)); +void MappingNode::setKeyValue (Key key, YamlNode *value) { + Mapping::iterator it = map.end(); + map.insert (it, std::pair<Key, YamlNode *> (key, value)); } -void MappingNode::removeKeyValue(Key key) -{ +void MappingNode::removeKeyValue (Key key) { -Mapping::iterator it = map.find(key); - map.erase(it); + Mapping::iterator it = map.find (key); + map.erase (it); } -YamlNode *MappingNode::getValue(Key key) -{ - Mapping::iterator it = map.find(key); +YamlNode *MappingNode::getValue (Key key) { + Mapping::iterator it = map.find (key); - if(it != map.end()) { - return it->second; - } - else { - _debug("MappingNode: Could not find %s", key.c_str()); - return NULL; - } + if (it != map.end()) { + return it->second; + } else { + _debug ("MappingNode: Could not find %s", key.c_str()); + return NULL; + } } -void SequenceNode::addNode(YamlNode *node) -{ - Sequence::iterator it = seq.end(); - seq.insert(it, node); +void SequenceNode::addNode (YamlNode *node) { + Sequence::iterator it = seq.end(); + seq.insert (it, node); } } diff --git a/sflphone-common/src/config/yamlparser.cpp b/sflphone-common/src/config/yamlparser.cpp index 08a436ad281719bae74cc6f2caf02f531531ab2a..d593ba033700f7de1f310c676cc7da756a6587bf 100644 --- a/sflphone-common/src/config/yamlparser.cpp +++ b/sflphone-common/src/config/yamlparser.cpp @@ -37,446 +37,432 @@ namespace Conf { -YamlParser::YamlParser(const char *file) : filename(file) - , accountSequence(NULL) - , preferenceSequence(NULL) - , addressbookSequence(NULL) - , audioSequence(NULL) - , hooksSequence(NULL) - , voiplinkSequence(NULL) - , shortcutSequence(NULL) -{ - memset(buffer, 0, PARSER_BUFFERSIZE); - - open(); +YamlParser::YamlParser (const char *file) : filename (file) + , accountSequence (NULL) + , preferenceSequence (NULL) + , addressbookSequence (NULL) + , audioSequence (NULL) + , hooksSequence (NULL) + , voiplinkSequence (NULL) + , shortcutSequence (NULL) { + memset (buffer, 0, PARSER_BUFFERSIZE); + + open(); } -YamlParser::~YamlParser() -{ - close(); +YamlParser::~YamlParser() { + close(); } -void YamlParser::open() -{ +void YamlParser::open() { - fd = fopen(filename.c_str(), "rb"); + fd = fopen (filename.c_str(), "rb"); - if(!fd) - throw YamlParserException("Could not open file descriptor"); + if (!fd) + throw YamlParserException ("Could not open file descriptor"); - if(!yaml_parser_initialize(&parser)) - throw YamlParserException("Could not open file descriptor"); + if (!yaml_parser_initialize (&parser)) + throw YamlParserException ("Could not open file descriptor"); - yaml_parser_set_input_file(&parser, fd); + yaml_parser_set_input_file (&parser, fd); } -void YamlParser::close() -{ +void YamlParser::close() { - yaml_parser_delete(&parser); + yaml_parser_delete (&parser); - if(!fd) - throw YamlParserException("File descriptor not valid"); + if (!fd) + throw YamlParserException ("File descriptor not valid"); - fclose(fd); - // if(!fclose(fd)) + fclose (fd); + // if(!fclose(fd)) // throw YamlParserException("Error closing file descriptor"); - + } -void YamlParser::serializeEvents() -{ - bool done = false; - yaml_event_t event; +void YamlParser::serializeEvents() { + bool done = false; + yaml_event_t event; + + while (!done) { - while(!done) { + if (!yaml_parser_parse (&parser, &event)) + throw YamlParserException ("Error while parsing"); - if(!yaml_parser_parse(&parser, &event)) - throw YamlParserException("Error while parsing"); + done = (event.type == YAML_STREAM_END_EVENT); - done = (event.type == YAML_STREAM_END_EVENT); - - if(eventNumber > PARSER_MAXEVENT) - throw YamlParserException("Reached maximum of event"); + if (eventNumber > PARSER_MAXEVENT) + throw YamlParserException ("Reached maximum of event"); - if(!copyEvent(&(events[eventNumber++]), &event)) - throw YamlParserException("Error copying event"); + if (!copyEvent (& (events[eventNumber++]), &event)) + throw YamlParserException ("Error copying event"); - } + } } -int YamlParser::copyEvent(yaml_event_t *event_to, yaml_event_t *event_from) -{ - - switch (event_from->type) { - case YAML_STREAM_START_EVENT: { - // _debug("YAML_STREAM_START_EVENT"); - return yaml_stream_start_event_initialize(event_to, - event_from->data.stream_start.encoding); - } - - case YAML_STREAM_END_EVENT: { - //_debug("YAML_STREAM_END_EVENT"); - return yaml_stream_end_event_initialize(event_to); - } - - case YAML_DOCUMENT_START_EVENT: { - // _debug("YAML_DOCUMENT_START_EVENT"); - return yaml_document_start_event_initialize(event_to, - event_from->data.document_start.version_directive, - event_from->data.document_start.tag_directives.start, - event_from->data.document_start.tag_directives.end, - event_from->data.document_start.implicit); - } - - case YAML_DOCUMENT_END_EVENT: { - // _debug("YAML_DOCUMENT_END_EVENT"); - return yaml_document_end_event_initialize(event_to, - event_from->data.document_end.implicit); - } - case YAML_ALIAS_EVENT:{ - // _debug("YAML_ALIAS_EVENT"); - return yaml_alias_event_initialize(event_to, - event_from->data.alias.anchor); - } - case YAML_SCALAR_EVENT: { - // _debug("YAML_SCALAR_EVENT"); - return yaml_scalar_event_initialize(event_to, - event_from->data.scalar.anchor, - event_from->data.scalar.tag, - event_from->data.scalar.value, - event_from->data.scalar.length, - event_from->data.scalar.plain_implicit, - event_from->data.scalar.quoted_implicit, - event_from->data.scalar.style); - } - case YAML_SEQUENCE_START_EVENT: { - // _debug("YAML_SEQUENCE_START_EVENT"); - return yaml_sequence_start_event_initialize(event_to, - event_from->data.sequence_start.anchor, - event_from->data.sequence_start.tag, - event_from->data.sequence_start.implicit, - event_from->data.sequence_start.style); - } - case YAML_SEQUENCE_END_EVENT: { - // _debug("YAML_SEQUENCE_END_EVENT"); - return yaml_sequence_end_event_initialize(event_to); - } - case YAML_MAPPING_START_EVENT: { - // _debug("YAML_MAPPING_START_EVENT"); - return yaml_mapping_start_event_initialize(event_to, - event_from->data.mapping_start.anchor, - event_from->data.mapping_start.tag, - event_from->data.mapping_start.implicit, - event_from->data.mapping_start.style); - } - case YAML_MAPPING_END_EVENT: { - // _debug("YAML_MAPPING_END_EVENT"); - return yaml_mapping_end_event_initialize(event_to); - - } - default: - assert(1); - - } - - return 0; +int YamlParser::copyEvent (yaml_event_t *event_to, yaml_event_t *event_from) { + + switch (event_from->type) { + case YAML_STREAM_START_EVENT: { + // _debug("YAML_STREAM_START_EVENT"); + return yaml_stream_start_event_initialize (event_to, + event_from->data.stream_start.encoding); + } + + case YAML_STREAM_END_EVENT: { + //_debug("YAML_STREAM_END_EVENT"); + return yaml_stream_end_event_initialize (event_to); + } + + case YAML_DOCUMENT_START_EVENT: { + // _debug("YAML_DOCUMENT_START_EVENT"); + return yaml_document_start_event_initialize (event_to, + event_from->data.document_start.version_directive, + event_from->data.document_start.tag_directives.start, + event_from->data.document_start.tag_directives.end, + event_from->data.document_start.implicit); + } + + case YAML_DOCUMENT_END_EVENT: { + // _debug("YAML_DOCUMENT_END_EVENT"); + return yaml_document_end_event_initialize (event_to, + event_from->data.document_end.implicit); + } + case YAML_ALIAS_EVENT: { + // _debug("YAML_ALIAS_EVENT"); + return yaml_alias_event_initialize (event_to, + event_from->data.alias.anchor); + } + case YAML_SCALAR_EVENT: { + // _debug("YAML_SCALAR_EVENT"); + return yaml_scalar_event_initialize (event_to, + event_from->data.scalar.anchor, + event_from->data.scalar.tag, + event_from->data.scalar.value, + event_from->data.scalar.length, + event_from->data.scalar.plain_implicit, + event_from->data.scalar.quoted_implicit, + event_from->data.scalar.style); + } + case YAML_SEQUENCE_START_EVENT: { + // _debug("YAML_SEQUENCE_START_EVENT"); + return yaml_sequence_start_event_initialize (event_to, + event_from->data.sequence_start.anchor, + event_from->data.sequence_start.tag, + event_from->data.sequence_start.implicit, + event_from->data.sequence_start.style); + } + case YAML_SEQUENCE_END_EVENT: { + // _debug("YAML_SEQUENCE_END_EVENT"); + return yaml_sequence_end_event_initialize (event_to); + } + case YAML_MAPPING_START_EVENT: { + // _debug("YAML_MAPPING_START_EVENT"); + return yaml_mapping_start_event_initialize (event_to, + event_from->data.mapping_start.anchor, + event_from->data.mapping_start.tag, + event_from->data.mapping_start.implicit, + event_from->data.mapping_start.style); + } + case YAML_MAPPING_END_EVENT: { + // _debug("YAML_MAPPING_END_EVENT"); + return yaml_mapping_end_event_initialize (event_to); + + } + default: + assert (1); + + } + + return 0; } YamlDocument *YamlParser::composeEvents() { - // _debug("YamlParser: Compose Events"); + // _debug("YamlParser: Compose Events"); - if(eventNumber == 0) - throw YamlParserException("No event available"); + if (eventNumber == 0) + throw YamlParserException ("No event available"); - if(events[0].type != YAML_STREAM_START_EVENT) - throw YamlParserException("Parsing does not start with stream start"); + if (events[0].type != YAML_STREAM_START_EVENT) + throw YamlParserException ("Parsing does not start with stream start"); - eventIndex = 0; + eventIndex = 0; - processStream(); + processStream(); - return doc; + return doc; } void YamlParser::processStream () { - // _debug("YamlParser: process stream"); + // _debug("YamlParser: process stream"); - while((eventIndex < eventNumber) && (events[eventIndex].type != YAML_STREAM_END_EVENT)) { + while ( (eventIndex < eventNumber) && (events[eventIndex].type != YAML_STREAM_END_EVENT)) { - if(events[eventIndex].type == YAML_DOCUMENT_START_EVENT) - processDocument(); + if (events[eventIndex].type == YAML_DOCUMENT_START_EVENT) + processDocument(); - eventIndex++; - } + eventIndex++; + } - if(events[eventIndex].type != YAML_STREAM_END_EVENT) - throw YamlParserException("Did not found end of stream"); + if (events[eventIndex].type != YAML_STREAM_END_EVENT) + throw YamlParserException ("Did not found end of stream"); } -void YamlParser::processDocument() -{ - // _debug("YamlParser: process document"); +void YamlParser::processDocument() { + // _debug("YamlParser: process document"); + + doc = new YamlDocument(); - doc = new YamlDocument(); + if (!doc) + throw YamlParserException ("Not able to create new document"); - if(!doc) - throw YamlParserException("Not able to create new document"); + while ( (eventIndex < eventNumber) && (events[eventIndex].type != YAML_DOCUMENT_END_EVENT)) { - while((eventIndex < eventNumber) && (events[eventIndex].type != YAML_DOCUMENT_END_EVENT)) { + switch (events[eventIndex].type) { + case YAML_SCALAR_EVENT: + processScalar ( (YamlNode *) doc); + break; + case YAML_SEQUENCE_START_EVENT: + processSequence ( (YamlNode *) doc); + break; + case YAML_MAPPING_START_EVENT: + processMapping ( (YamlNode *) doc); + break; + default: + break; + } - switch(events[eventIndex].type){ - case YAML_SCALAR_EVENT: - processScalar((YamlNode *)doc); - break; - case YAML_SEQUENCE_START_EVENT: - processSequence((YamlNode *)doc); - break; - case YAML_MAPPING_START_EVENT: - processMapping((YamlNode *)doc); - break; - default: - break; + eventIndex++; } - eventIndex++; - } + if (events[eventIndex].type != YAML_DOCUMENT_END_EVENT) + throw YamlParserException ("Did not found end of document"); - if(events[eventIndex].type != YAML_DOCUMENT_END_EVENT) - throw YamlParserException("Did not found end of document"); - } -void YamlParser::processScalar(YamlNode *topNode) -{ +void YamlParser::processScalar (YamlNode *topNode) { - // _debug("YamlParser: process scalar"); + // _debug("YamlParser: process scalar"); - if(!topNode) - throw YamlParserException("No container for scalar"); + if (!topNode) + throw YamlParserException ("No container for scalar"); - char buffer[1000]; - snprintf(buffer, 1000, "%s", events[eventIndex].data.scalar.value); - // _debug("and the scalar is: %s", buffer); + char buffer[1000]; + snprintf (buffer, 1000, "%s", events[eventIndex].data.scalar.value); + // _debug("and the scalar is: %s", buffer); + + ScalarNode *sclr = new ScalarNode (buffer, topNode); + + switch (topNode->getType()) { + case DOCUMENT: + ( (YamlDocument *) (topNode))->addNode (sclr); + break; + case SEQUENCE: + ( (SequenceNode *) (topNode))->addNode (sclr); + break; + case MAPPING: + ( (MappingNode *) (topNode))->addNode (sclr); + case SCALAR: + default: + break; + } +} - ScalarNode *sclr = new ScalarNode(buffer, topNode); - switch(topNode->getType()) { - case DOCUMENT: - ((YamlDocument *)(topNode))->addNode(sclr); - break; - case SEQUENCE: - ((SequenceNode *)(topNode))->addNode(sclr); - break; - case MAPPING: - ((MappingNode *)(topNode))->addNode(sclr); - case SCALAR: - default: - break; - } -} +void YamlParser::processSequence (YamlNode *topNode) { + _debug ("YamlParser: process sequence"); + if (!topNode) + throw YamlParserException ("No container for sequence"); -void YamlParser::processSequence(YamlNode *topNode) -{ - _debug("YamlParser: process sequence"); - - if(!topNode) - throw YamlParserException("No container for sequence"); - - SequenceNode *seq = new SequenceNode(topNode); - - switch(topNode->getType()) { - case DOCUMENT: - ((YamlDocument *)(topNode))->addNode(seq); - break; - case SEQUENCE: - ((SequenceNode *)(topNode))->addNode(seq); - break; - case MAPPING: - ((MappingNode *)(topNode))->addNode(seq); - case SCALAR: - default: - break; - } - - eventIndex++; - - while((eventIndex < eventNumber) && (events[eventIndex].type != YAML_SEQUENCE_END_EVENT)) { - - switch(events[eventIndex].type){ - case YAML_SCALAR_EVENT: - processScalar(seq); - break; - case YAML_SEQUENCE_START_EVENT: - processSequence(seq); - break; - case YAML_MAPPING_START_EVENT: - processMapping(seq); - break; - default: - break; + SequenceNode *seq = new SequenceNode (topNode); + + switch (topNode->getType()) { + case DOCUMENT: + ( (YamlDocument *) (topNode))->addNode (seq); + break; + case SEQUENCE: + ( (SequenceNode *) (topNode))->addNode (seq); + break; + case MAPPING: + ( (MappingNode *) (topNode))->addNode (seq); + case SCALAR: + default: + break; } eventIndex++; - } - - if(events[eventIndex].type != YAML_SEQUENCE_END_EVENT) - throw YamlParserException("Did not found end of sequence"); -} + while ( (eventIndex < eventNumber) && (events[eventIndex].type != YAML_SEQUENCE_END_EVENT)) { + + switch (events[eventIndex].type) { + case YAML_SCALAR_EVENT: + processScalar (seq); + break; + case YAML_SEQUENCE_START_EVENT: + processSequence (seq); + break; + case YAML_MAPPING_START_EVENT: + processMapping (seq); + break; + default: + break; + } + + eventIndex++; + } -void YamlParser::processMapping(YamlNode *topNode) -{ - // _debug("YamlParser: process mapping"); + if (events[eventIndex].type != YAML_SEQUENCE_END_EVENT) + throw YamlParserException ("Did not found end of sequence"); +} - if(!topNode) - throw YamlParserException("No container for mapping"); - MappingNode *map = new MappingNode(topNode); +void YamlParser::processMapping (YamlNode *topNode) { + // _debug("YamlParser: process mapping"); - switch(topNode->getType()) { - case DOCUMENT: - ((YamlDocument *)(topNode))->addNode(map); - break; - case SEQUENCE: - ((SequenceNode *)(topNode))->addNode(map); - break; - case MAPPING: - ((MappingNode *)(topNode))->addNode(map); - case SCALAR: - default: - break; - } + if (!topNode) + throw YamlParserException ("No container for mapping"); - eventIndex++; + MappingNode *map = new MappingNode (topNode); - while((eventIndex < eventNumber) && (events[eventIndex].type != YAML_MAPPING_END_EVENT)) { + switch (topNode->getType()) { + case DOCUMENT: + ( (YamlDocument *) (topNode))->addNode (map); + break; + case SEQUENCE: + ( (SequenceNode *) (topNode))->addNode (map); + break; + case MAPPING: + ( (MappingNode *) (topNode))->addNode (map); + case SCALAR: + default: + break; + } - if(events[eventIndex].type != YAML_SCALAR_EVENT) - throw YamlParserException("Mapping not followed by a key"); - - char buffer[1000]; - snprintf(buffer, 1000, "%s", events[eventIndex].data.scalar.value); - map->setTmpKey(Key(buffer)); - // _debug("KEY %s", buffer); - eventIndex++; - switch(events[eventIndex].type){ - case YAML_SCALAR_EVENT: - processScalar(map); - break; - case YAML_SEQUENCE_START_EVENT: - processSequence(map); - break; - case YAML_MAPPING_START_EVENT: - processMapping(map); - break; - default: - break; + while ( (eventIndex < eventNumber) && (events[eventIndex].type != YAML_MAPPING_END_EVENT)) { + + if (events[eventIndex].type != YAML_SCALAR_EVENT) + throw YamlParserException ("Mapping not followed by a key"); + + char buffer[1000]; + snprintf (buffer, 1000, "%s", events[eventIndex].data.scalar.value); + map->setTmpKey (Key (buffer)); + // _debug("KEY %s", buffer); + + eventIndex++; + + switch (events[eventIndex].type) { + case YAML_SCALAR_EVENT: + processScalar (map); + break; + case YAML_SEQUENCE_START_EVENT: + processSequence (map); + break; + case YAML_MAPPING_START_EVENT: + processMapping (map); + break; + default: + break; + } + + eventIndex++; } - eventIndex++; - } - - if(events[eventIndex].type != YAML_MAPPING_END_EVENT) - throw YamlParserException("Did not found end of mapping"); + if (events[eventIndex].type != YAML_MAPPING_END_EVENT) + throw YamlParserException ("Did not found end of mapping"); } void YamlParser::constructNativeData() { - - Sequence *seq; - - seq = doc->getSequence(); - - Sequence::iterator iter = seq->begin(); - - while(iter != seq->end()) { - - switch((*iter)->getType()){ - case SCALAR: - // _debug("construct scalar"); - throw YamlParserException("No scalar allowed at document level, expect a mapping"); - break; - case SEQUENCE: - // _debug("construct sequence"); - throw YamlParserException("No sequence allowed at document level, expect a mapping"); - break; - case MAPPING: { - // _debug("construct mapping"); - MappingNode *map = (MappingNode *)(*iter); - mainNativeDataMapping(map); - break; - } - default: - throw YamlParserException("Unknown type in configuration file, expect a mapping"); - break; - } - iter++; - } - -} + Sequence *seq; + seq = doc->getSequence(); -void YamlParser::mainNativeDataMapping(MappingNode *map) { + Sequence::iterator iter = seq->begin(); - - Mapping::iterator iter = map->getMapping()->begin(); + while (iter != seq->end()) { - Key accounts("accounts"); - Key addressbook("addressbook"); - Key audio("audio"); - Key hooks("hooks"); - Key preferences("preferences"); - Key voiplink("voipPreferences"); - Key shortcuts("shortcuts"); + switch ( (*iter)->getType()) { + case SCALAR: + // _debug("construct scalar"); + throw YamlParserException ("No scalar allowed at document level, expect a mapping"); + break; + case SEQUENCE: + // _debug("construct sequence"); + throw YamlParserException ("No sequence allowed at document level, expect a mapping"); + break; + case MAPPING: { + // _debug("construct mapping"); + MappingNode *map = (MappingNode *) (*iter); + mainNativeDataMapping (map); + break; + } + default: + throw YamlParserException ("Unknown type in configuration file, expect a mapping"); + break; + } - while(iter != map->getMapping()->end()) { + iter++; - _debug("Iterating: %s", iter->first.c_str()); - if(accounts.compare(iter->first) == 0) { - _debug("YamlParser: Adding voip account preferences"); - accountSequence = (SequenceNode *)(iter->second); - } - else if(addressbook.compare(iter->first) == 0) { - _debug("YamlParser: Adding addressbook preference"); - addressbookSequence = (SequenceNode *)(iter->second); } - else if(audio.compare(iter->first) == 0) { - _debug("YamlParser: Adding audio preference"); - audioSequence = (SequenceNode *)(iter->second); - } - else if(hooks.compare(iter->first) == 0) { - _debug("YamlParser: Adding hooks preference"); - hooksSequence = (SequenceNode *)(iter->second); - } - else if(preferences.compare(iter->first) == 0) { - _debug("YamlParser: Adding preference preference"); - preferenceSequence = (SequenceNode *)(iter->second); - } - else if(voiplink.compare(iter->first) == 0) { - _debug("YamlParser: Adding voip preference"); - voiplinkSequence = (SequenceNode *)(iter->second); - } - else if(shortcuts.compare(iter->first) == 0) { - _debug("YamlParser: Adding shortcut preference"); - shortcutSequence = (SequenceNode *)(iter->second); + +} + + +void YamlParser::mainNativeDataMapping (MappingNode *map) { + + + Mapping::iterator iter = map->getMapping()->begin(); + + Key accounts ("accounts"); + Key addressbook ("addressbook"); + Key audio ("audio"); + Key hooks ("hooks"); + Key preferences ("preferences"); + Key voiplink ("voipPreferences"); + Key shortcuts ("shortcuts"); + + while (iter != map->getMapping()->end()) { + + _debug ("Iterating: %s", iter->first.c_str()); + + if (accounts.compare (iter->first) == 0) { + _debug ("YamlParser: Adding voip account preferences"); + accountSequence = (SequenceNode *) (iter->second); + } else if (addressbook.compare (iter->first) == 0) { + _debug ("YamlParser: Adding addressbook preference"); + addressbookSequence = (SequenceNode *) (iter->second); + } else if (audio.compare (iter->first) == 0) { + _debug ("YamlParser: Adding audio preference"); + audioSequence = (SequenceNode *) (iter->second); + } else if (hooks.compare (iter->first) == 0) { + _debug ("YamlParser: Adding hooks preference"); + hooksSequence = (SequenceNode *) (iter->second); + } else if (preferences.compare (iter->first) == 0) { + _debug ("YamlParser: Adding preference preference"); + preferenceSequence = (SequenceNode *) (iter->second); + } else if (voiplink.compare (iter->first) == 0) { + _debug ("YamlParser: Adding voip preference"); + voiplinkSequence = (SequenceNode *) (iter->second); + } else if (shortcuts.compare (iter->first) == 0) { + _debug ("YamlParser: Adding shortcut preference"); + shortcutSequence = (SequenceNode *) (iter->second); + } else + throw YamlParserException ("Unknow map key in configuration"); + + iter++; } - else - throw YamlParserException("Unknow map key in configuration"); - iter++; - } - // _debug("Done"); + // _debug("Done"); } } diff --git a/sflphone-common/src/dbus/callmanager.cpp b/sflphone-common/src/dbus/callmanager.cpp index 5662b4640408d9c59180242f98385f3b938c1a6c..b784f010d9bd839494645ebb60b9cc1f19bc05f1 100644 --- a/sflphone-common/src/dbus/callmanager.cpp +++ b/sflphone-common/src/dbus/callmanager.cpp @@ -42,15 +42,13 @@ const char* CallManager::SERVER_PATH = "/org/sflphone/SFLphone/CallManager"; CallManager::CallManager (DBus::Connection& connection) - : DBus::ObjectAdaptor (connection, SERVER_PATH) -{ + : DBus::ObjectAdaptor (connection, SERVER_PATH) { } void CallManager::placeCall (const std::string& accountID, const std::string& callID, - const std::string& to) -{ // Check if a destination number is available + const std::string& to) { // Check if a destination number is available if (to == "") _debug ("No number entered - Call stopped"); else Manager::instance().outgoingCall (accountID, callID, to); @@ -58,12 +56,11 @@ CallManager::placeCall (const std::string& accountID, void CallManager::placeCallFirstAccount (const std::string& callID, - const std::string& to) -{ + const std::string& to) { if (to == "") { - _warn("CallManager: Warning: No number entered, call stopped"); - return; + _warn ("CallManager: Warning: No number entered, call stopped"); + return; } std::vector< std::string > accountOrder = Manager::instance().loadAccountOrder(); @@ -71,74 +68,73 @@ CallManager::placeCallFirstAccount (const std::string& callID, Account *account; - _debug("AccountOrder size: %d", accountOrder.size()); + _debug ("AccountOrder size: %d", accountOrder.size()); - if(accountOrder.size() > 0) { + if (accountOrder.size() > 0) { - iter = accountOrder.begin(); + iter = accountOrder.begin(); - while(iter != accountOrder.end()) { - account = Manager::instance().getAccount(*iter); - if((*iter != IP2IP_PROFILE) && account->isEnabled()) { - Manager::instance().outgoingCall (*iter, callID, to); - return; - } + while (iter != accountOrder.end()) { + account = Manager::instance().getAccount (*iter); - iter++; - } - } - else { - _error("AccountOrder is empty"); - // If accountOrder is empty fallback on accountList (which has no preference order) - std::vector< std::string > accountList = Manager::instance().getAccountList(); - iter = accountList.begin(); - - - _error("AccountList size: %d", accountList.size()); - if(accountList.size() > 0) { - while(iter != accountList.end()) { - _error("iter"); - account = Manager::instance().getAccount(*iter); - if((*iter != IP2IP_PROFILE) && account->isEnabled()) { - _error("makecall"); - Manager::instance().outgoingCall(*iter, callID, to); - return; - } - iter++; - } - - } + if ( (*iter != IP2IP_PROFILE) && account->isEnabled()) { + Manager::instance().outgoingCall (*iter, callID, to); + return; + } + + iter++; + } + } else { + _error ("AccountOrder is empty"); + // If accountOrder is empty fallback on accountList (which has no preference order) + std::vector< std::string > accountList = Manager::instance().getAccountList(); + iter = accountList.begin(); + + + _error ("AccountList size: %d", accountList.size()); + + if (accountList.size() > 0) { + while (iter != accountList.end()) { + _error ("iter"); + account = Manager::instance().getAccount (*iter); + + if ( (*iter != IP2IP_PROFILE) && account->isEnabled()) { + _error ("makecall"); + Manager::instance().outgoingCall (*iter, callID, to); + return; + } + + iter++; + } + + } } - - _warn("CallManager: Warning: No enabled account found, call stopped"); - + + _warn ("CallManager: Warning: No enabled account found, call stopped"); + } void -CallManager::refuse (const std::string& callID) -{ +CallManager::refuse (const std::string& callID) { _debug ("CallManager: Refuse %s", callID.c_str()); Manager::instance().refuseCall (callID); } void -CallManager::accept (const std::string& callID) -{ +CallManager::accept (const std::string& callID) { _debug ("CallManager: Accept received"); Manager::instance().answerCall (callID); } void -CallManager::hangUp (const std::string& callID) -{ +CallManager::hangUp (const std::string& callID) { _debug ("CallManager: HangUp received %s", callID.c_str()); Manager::instance().hangupCall (callID); } void -CallManager::hangUpConference (const std::string& confID) -{ +CallManager::hangUpConference (const std::string& confID) { _debug ("CallManager::hangUpConference received %s", confID.c_str()); Manager::instance().hangupConference (confID); @@ -146,23 +142,20 @@ CallManager::hangUpConference (const std::string& confID) void -CallManager::hold (const std::string& callID) -{ +CallManager::hold (const std::string& callID) { _debug ("CallManager::hold received %s", callID.c_str()); Manager::instance().onHoldCall (callID); } void -CallManager::unhold (const std::string& callID) -{ +CallManager::unhold (const std::string& callID) { _debug ("CallManager::unhold received %s", callID.c_str()); 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"); Manager::instance().transferCall (callID, to); } @@ -170,8 +163,7 @@ CallManager::transfert (const std::string& callID, const std::string& to) void -CallManager::setVolume (const std::string& device, const double& value) -{ +CallManager::setVolume (const std::string& device, const double& value) { if (device == "speaker") { Manager::instance().setSpkrVolume ( (int) (value*100.0)); @@ -183,8 +175,7 @@ CallManager::setVolume (const std::string& device, const double& value) } double -CallManager::getVolume (const std::string& device) -{ +CallManager::getVolume (const std::string& device) { if (device == "speaker") { _debug ("Current speaker = %d", Manager::instance().getSpkrVolume()); @@ -198,120 +189,102 @@ CallManager::getVolume (const std::string& device) } void -CallManager::joinParticipant (const std::string& sel_callID, const std::string& drag_callID) -{ +CallManager::joinParticipant (const std::string& sel_callID, const std::string& drag_callID) { _debug ("CallManager::joinParticipant received %s, %s", sel_callID.c_str(), drag_callID.c_str()); Manager::instance().joinParticipant (sel_callID, drag_callID); } void -CallManager::addParticipant (const std::string& callID, const std::string& confID) -{ +CallManager::addParticipant (const std::string& callID, const std::string& confID) { _debug ("CallManager::addParticipant received %s, %s", callID.c_str(), confID.c_str()); Manager::instance().addParticipant (callID, confID); } void -CallManager::addMainParticipant (const std::string& confID) -{ +CallManager::addMainParticipant (const std::string& confID) { _debug ("CallManager::addMainParticipant received %s", confID.c_str()); Manager::instance().addMainParticipant (confID); } void -CallManager::detachParticipant (const std::string& callID) -{ +CallManager::detachParticipant (const std::string& callID) { _debug ("CallManager::detachParticipant received %s", callID.c_str()); Manager::instance().detachParticipant (callID, ""); } void -CallManager::joinConference (const std::string& sel_confID, const std::string& drag_confID) -{ +CallManager::joinConference (const std::string& sel_confID, const std::string& drag_confID) { _debug ("CallManager::joinConference received %s, %s", sel_confID.c_str(), drag_confID.c_str()); Manager::instance().joinConference (sel_confID, drag_confID); } void -CallManager::holdConference (const std::string& confID) -{ +CallManager::holdConference (const std::string& confID) { _debug ("CallManager::holdConference received %s", confID.c_str()); Manager::instance().holdConference (confID); } void -CallManager::unholdConference (const std::string& confID) -{ +CallManager::unholdConference (const std::string& confID) { _debug ("CallManager: Unhold Conference %s", confID.c_str()); Manager::instance().unHoldConference (confID); } std::map< std::string, std::string > -CallManager::getConferenceDetails (const std::string& callID) -{ +CallManager::getConferenceDetails (const std::string& callID) { return Manager::instance().getConferenceDetails (callID); } std::vector< std::string > -CallManager::getConferenceList (void) -{ +CallManager::getConferenceList (void) { return Manager::instance().getConferenceList(); } std::vector< std::string > -CallManager::getParticipantList (const std::string& confID) -{ - _debug("CallManager: Get Participant list for conference %s", confID.c_str()); +CallManager::getParticipantList (const std::string& confID) { + _debug ("CallManager: Get Participant list for conference %s", confID.c_str()); return Manager::instance().getParticipantList (confID); } void -CallManager::setRecording (const std::string& callID) -{ +CallManager::setRecording (const std::string& callID) { Manager::instance().setRecordingCall (callID); } bool -CallManager::getIsRecording (const std::string& callID) -{ +CallManager::getIsRecording (const std::string& callID) { return Manager::instance().isRecording (callID); } std::string -CallManager::getCurrentCodecName (const std::string& callID) -{ +CallManager::getCurrentCodecName (const std::string& callID) { return Manager::instance().getCurrentCodecName (callID).c_str(); } std::map< std::string, std::string > -CallManager::getCallDetails (const std::string& callID) -{ +CallManager::getCallDetails (const std::string& callID) { return Manager::instance().getCallDetails (callID); } std::vector< std::string > -CallManager::getCallList (void) -{ +CallManager::getCallList (void) { return Manager::instance().getCallList(); } std::string -CallManager::getCurrentCallID() -{ +CallManager::getCurrentCallID() { return Manager::instance().getCurrentCallId(); } void -CallManager::playDTMF (const std::string& key) -{ +CallManager::playDTMF (const std::string& key) { Manager::instance().sendDtmf (Manager::instance().getCurrentCallId(), key.c_str() [0]); } void -CallManager::startTone (const int32_t& start , const int32_t& type) -{ +CallManager::startTone (const int32_t& start , const int32_t& type) { if (start == true) { if (type == 0) Manager::instance().playTone(); @@ -325,8 +298,7 @@ CallManager::startTone (const int32_t& start , const int32_t& type) // for conferencing in order to get // the right pointer for the given // callID. -sfl::AudioZrtpSession * CallManager::getAudioZrtpSession (const std::string& callID) -{ +sfl::AudioZrtpSession * CallManager::getAudioZrtpSession (const std::string& callID) { SIPVoIPLink * link = NULL; link = dynamic_cast<SIPVoIPLink *> (Manager::instance().getAccountLink (AccountNULL)); @@ -358,8 +330,7 @@ sfl::AudioZrtpSession * CallManager::getAudioZrtpSession (const std::string& cal } void -CallManager::setSASVerified (const std::string& callID) -{ +CallManager::setSASVerified (const std::string& callID) { try { sfl::AudioZrtpSession * zSession; @@ -372,8 +343,7 @@ CallManager::setSASVerified (const std::string& callID) } void -CallManager::resetSASVerified (const std::string& callID) -{ +CallManager::resetSASVerified (const std::string& callID) { try { sfl::AudioZrtpSession * zSession; @@ -386,8 +356,7 @@ CallManager::resetSASVerified (const std::string& callID) } void -CallManager::setConfirmGoClear (const std::string& callID) -{ +CallManager::setConfirmGoClear (const std::string& callID) { _debug ("CallManager::setConfirmGoClear received for account %s", callID.c_str()); try { @@ -401,8 +370,7 @@ CallManager::setConfirmGoClear (const std::string& callID) } void -CallManager::requestGoClear (const std::string& callID) -{ +CallManager::requestGoClear (const std::string& callID) { _debug ("CallManager::requestGoClear received for account %s", callID.c_str()); try { @@ -416,8 +384,7 @@ CallManager::requestGoClear (const std::string& callID) } void -CallManager::acceptEnrollment (const std::string& callID, const bool& accepted) -{ +CallManager::acceptEnrollment (const std::string& callID, const bool& accepted) { _debug ("CallManager::acceptEnrollment received for account %s", callID.c_str()); @@ -432,8 +399,7 @@ CallManager::acceptEnrollment (const std::string& callID, const bool& accepted) } void -CallManager::setPBXEnrollment (const std::string& callID, const bool& yesNo) -{ +CallManager::setPBXEnrollment (const std::string& callID, const bool& yesNo) { _debug ("CallManager::setPBXEnrollment received for account %s", callID.c_str()); diff --git a/sflphone-common/src/dbus/configurationmanager.cpp b/sflphone-common/src/dbus/configurationmanager.cpp old mode 100755 new mode 100644 index e64a4edff402ad31966ae67eec913ed39d978615..3daa6b6ebf06875bb7ae41afa12e932a189dd7a2 --- a/sflphone-common/src/dbus/configurationmanager.cpp +++ b/sflphone-common/src/dbus/configurationmanager.cpp @@ -38,531 +38,557 @@ #include "sip/sipaccount.h" const char* ConfigurationManager::SERVER_PATH = - "/org/sflphone/SFLphone/ConfigurationManager"; - -ConfigurationManager::ConfigurationManager(DBus::Connection& connection) : - DBus::ObjectAdaptor(connection, SERVER_PATH) { - shortcutsKeys.push_back("pick_up"); - shortcutsKeys.push_back("hang_up"); - shortcutsKeys.push_back("popup_window"); - shortcutsKeys.push_back("toggle_pick_up_hang_up"); - shortcutsKeys.push_back("toggle_hold"); + "/org/sflphone/SFLphone/ConfigurationManager"; + +ConfigurationManager::ConfigurationManager (DBus::Connection& connection) : + DBus::ObjectAdaptor (connection, SERVER_PATH) { + shortcutsKeys.push_back ("pick_up"); + shortcutsKeys.push_back ("hang_up"); + shortcutsKeys.push_back ("popup_window"); + shortcutsKeys.push_back ("toggle_pick_up_hang_up"); + shortcutsKeys.push_back ("toggle_hold"); } -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: get account details %s", accountID.c_str()); - return Manager::instance().getAccountDetails(accountID); + _debug ("ConfigurationManager: get account details %s", accountID.c_str()); + return Manager::instance().getAccountDetails (accountID); } -std::map<std::string, std::string> ConfigurationManager::getTlsSettingsDefault( - void) { +std::map<std::string, std::string> ConfigurationManager::getTlsSettingsDefault ( + void) { - std::map<std::string, std::string> tlsSettingsDefault; + std::map<std::string, std::string> tlsSettingsDefault; - tlsSettingsDefault.insert(std::pair<std::string, std::string>( - TLS_LISTENER_PORT, DEFAULT_SIP_TLS_PORT)); - tlsSettingsDefault.insert(std::pair<std::string, std::string>( - TLS_CA_LIST_FILE, "")); - tlsSettingsDefault.insert(std::pair<std::string, std::string>( - TLS_CERTIFICATE_FILE, "")); - tlsSettingsDefault.insert(std::pair<std::string, std::string>( - TLS_PRIVATE_KEY_FILE, "")); - tlsSettingsDefault.insert(std::pair<std::string, std::string>(TLS_PASSWORD, - "")); - tlsSettingsDefault.insert(std::pair<std::string, std::string>(TLS_METHOD, - "TLSv1")); - tlsSettingsDefault.insert(std::pair<std::string, std::string>(TLS_CIPHERS, - "")); - tlsSettingsDefault.insert(std::pair<std::string, std::string>( - TLS_SERVER_NAME, "")); - tlsSettingsDefault.insert(std::pair<std::string, std::string>( - TLS_VERIFY_SERVER, "true")); - tlsSettingsDefault.insert(std::pair<std::string, std::string>( - TLS_VERIFY_CLIENT, "true")); - tlsSettingsDefault.insert(std::pair<std::string, std::string>( - TLS_REQUIRE_CLIENT_CERTIFICATE, "true")); - tlsSettingsDefault.insert(std::pair<std::string, std::string>( - TLS_NEGOTIATION_TIMEOUT_SEC, "2")); - tlsSettingsDefault.insert(std::pair<std::string, std::string>( - TLS_NEGOTIATION_TIMEOUT_MSEC, "0")); + tlsSettingsDefault.insert (std::pair<std::string, std::string> ( + TLS_LISTENER_PORT, DEFAULT_SIP_TLS_PORT)); + tlsSettingsDefault.insert (std::pair<std::string, std::string> ( + TLS_CA_LIST_FILE, "")); + tlsSettingsDefault.insert (std::pair<std::string, std::string> ( + TLS_CERTIFICATE_FILE, "")); + tlsSettingsDefault.insert (std::pair<std::string, std::string> ( + TLS_PRIVATE_KEY_FILE, "")); + tlsSettingsDefault.insert (std::pair<std::string, std::string> (TLS_PASSWORD, + "")); + tlsSettingsDefault.insert (std::pair<std::string, std::string> (TLS_METHOD, + "TLSv1")); + tlsSettingsDefault.insert (std::pair<std::string, std::string> (TLS_CIPHERS, + "")); + tlsSettingsDefault.insert (std::pair<std::string, std::string> ( + TLS_SERVER_NAME, "")); + tlsSettingsDefault.insert (std::pair<std::string, std::string> ( + TLS_VERIFY_SERVER, "true")); + tlsSettingsDefault.insert (std::pair<std::string, std::string> ( + TLS_VERIFY_CLIENT, "true")); + tlsSettingsDefault.insert (std::pair<std::string, std::string> ( + TLS_REQUIRE_CLIENT_CERTIFICATE, "true")); + tlsSettingsDefault.insert (std::pair<std::string, std::string> ( + TLS_NEGOTIATION_TIMEOUT_SEC, "2")); + tlsSettingsDefault.insert (std::pair<std::string, std::string> ( + TLS_NEGOTIATION_TIMEOUT_MSEC, "0")); - return tlsSettingsDefault; + return tlsSettingsDefault; } -std::map<std::string, std::string> ConfigurationManager::getIp2IpDetails(void) { +std::map<std::string, std::string> ConfigurationManager::getIp2IpDetails (void) { - std::map<std::string, std::string> ip2ipAccountDetails; + std::map<std::string, std::string> ip2ipAccountDetails; - SIPAccount *sipaccount = (SIPAccount *)Manager::instance().getAccount(IP2IP_PROFILE); + SIPAccount *sipaccount = (SIPAccount *) Manager::instance().getAccount (IP2IP_PROFILE); - if(!sipaccount) { - _error("ConfigurationManager: could not find account"); - return ip2ipAccountDetails; - } + if (!sipaccount) { + _error ("ConfigurationManager: could not find account"); + return ip2ipAccountDetails; + } - ip2ipAccountDetails.insert(std::pair<std::string, std::string>(ACCOUNT_ID, IP2IP_PROFILE)); - ip2ipAccountDetails.insert(std::pair<std::string, std::string>(SRTP_KEY_EXCHANGE, sipaccount->getSrtpKeyExchange())); - ip2ipAccountDetails.insert(std::pair<std::string, std::string>(SRTP_ENABLE, sipaccount->getSrtpEnable() ? "true" : "false")); - ip2ipAccountDetails.insert(std::pair<std::string, std::string>(SRTP_RTP_FALLBACK, sipaccount->getSrtpFallback() ? "true" : "false")); - ip2ipAccountDetails.insert(std::pair<std::string, std::string>(ZRTP_DISPLAY_SAS, sipaccount->getZrtpDisplaySas() ? "true" : "false")); - ip2ipAccountDetails.insert(std::pair<std::string, std::string>(ZRTP_HELLO_HASH, sipaccount->getZrtpHelloHash() ? "true" : "false")); - ip2ipAccountDetails.insert(std::pair<std::string, std::string>(ZRTP_NOT_SUPP_WARNING, sipaccount->getZrtpNotSuppWarning() ? "true" : "false")); - ip2ipAccountDetails.insert(std::pair<std::string, std::string>(ZRTP_DISPLAY_SAS_ONCE, sipaccount->getZrtpDiaplaySasOnce() ? "true" : "false")); - ip2ipAccountDetails.insert(std::pair<std::string, std::string>(LOCAL_INTERFACE, sipaccount->getLocalInterface())); - std::stringstream portstr; portstr << sipaccount->getLocalPort(); - ip2ipAccountDetails.insert(std::pair<std::string, std::string>(LOCAL_PORT, portstr.str())); + ip2ipAccountDetails.insert (std::pair<std::string, std::string> (ACCOUNT_ID, IP2IP_PROFILE)); + ip2ipAccountDetails.insert (std::pair<std::string, std::string> (SRTP_KEY_EXCHANGE, sipaccount->getSrtpKeyExchange())); + ip2ipAccountDetails.insert (std::pair<std::string, std::string> (SRTP_ENABLE, sipaccount->getSrtpEnable() ? "true" : "false")); + ip2ipAccountDetails.insert (std::pair<std::string, std::string> (SRTP_RTP_FALLBACK, sipaccount->getSrtpFallback() ? "true" : "false")); + ip2ipAccountDetails.insert (std::pair<std::string, std::string> (ZRTP_DISPLAY_SAS, sipaccount->getZrtpDisplaySas() ? "true" : "false")); + ip2ipAccountDetails.insert (std::pair<std::string, std::string> (ZRTP_HELLO_HASH, sipaccount->getZrtpHelloHash() ? "true" : "false")); + ip2ipAccountDetails.insert (std::pair<std::string, std::string> (ZRTP_NOT_SUPP_WARNING, sipaccount->getZrtpNotSuppWarning() ? "true" : "false")); + ip2ipAccountDetails.insert (std::pair<std::string, std::string> (ZRTP_DISPLAY_SAS_ONCE, sipaccount->getZrtpDiaplaySasOnce() ? "true" : "false")); + ip2ipAccountDetails.insert (std::pair<std::string, std::string> (LOCAL_INTERFACE, sipaccount->getLocalInterface())); + std::stringstream portstr; + portstr << sipaccount->getLocalPort(); + ip2ipAccountDetails.insert (std::pair<std::string, std::string> (LOCAL_PORT, portstr.str())); - std::map<std::string, std::string> tlsSettings; - tlsSettings = getTlsSettings(IP2IP_PROFILE); - std::copy(tlsSettings.begin(), tlsSettings.end(), std::inserter( - ip2ipAccountDetails, ip2ipAccountDetails.end())); + std::map<std::string, std::string> tlsSettings; + tlsSettings = getTlsSettings (IP2IP_PROFILE); + std::copy (tlsSettings.begin(), tlsSettings.end(), std::inserter ( + ip2ipAccountDetails, ip2ipAccountDetails.end())); - return ip2ipAccountDetails; + return ip2ipAccountDetails; } -void ConfigurationManager::setIp2IpDetails(const std::map<std::string, - std::string>& details) { - std::map<std::string, std::string> map_cpy = details; - std::map<std::string, std::string>::iterator it; +void ConfigurationManager::setIp2IpDetails (const std::map<std::string, + std::string>& details) { + std::map<std::string, std::string> map_cpy = details; + std::map<std::string, std::string>::iterator it; + + SIPAccount *sipaccount = (SIPAccount *) Manager::instance().getAccount (IP2IP_PROFILE); + + if (!sipaccount) { + _error ("ConfigurationManager: could not find account"); + } + + + it = map_cpy.find (LOCAL_INTERFACE); + + if (it != details.end()) sipaccount->setLocalInterface (it->second); + + it = map_cpy.find (LOCAL_PORT); + + if (it != details.end()) sipaccount->setLocalPort (atoi (it->second.data())); - SIPAccount *sipaccount = (SIPAccount *)Manager::instance().getAccount(IP2IP_PROFILE); + it = map_cpy.find (SRTP_ENABLE); - if(!sipaccount) { - _error("ConfigurationManager: could not find account"); - } - + if (it != details.end()) sipaccount->setSrtpEnable ( (it->second == "true")); - it = map_cpy.find(LOCAL_INTERFACE); - if (it != details.end()) sipaccount->setLocalInterface(it->second); + it = map_cpy.find (SRTP_RTP_FALLBACK); - it = map_cpy.find(LOCAL_PORT); - if (it != details.end()) sipaccount->setLocalPort(atoi(it->second.data())); + if (it != details.end()) sipaccount->setSrtpFallback ( (it->second == "true")); - it = map_cpy.find(SRTP_ENABLE); - if (it != details.end()) sipaccount->setSrtpEnable((it->second == "true")); + it = map_cpy.find (SRTP_KEY_EXCHANGE); - it = map_cpy.find(SRTP_RTP_FALLBACK); - if (it != details.end()) sipaccount->setSrtpFallback((it->second == "true")); + if (it != details.end()) sipaccount->setSrtpKeyExchange (it->second); - it = map_cpy.find(SRTP_KEY_EXCHANGE); - if (it != details.end()) sipaccount->setSrtpKeyExchange(it->second); + it = map_cpy.find (ZRTP_DISPLAY_SAS); - it = map_cpy.find(ZRTP_DISPLAY_SAS); - if (it != details.end()) sipaccount->setZrtpDisplaySas((it->second == "true")); + if (it != details.end()) sipaccount->setZrtpDisplaySas ( (it->second == "true")); - it = map_cpy.find(ZRTP_NOT_SUPP_WARNING); - if (it != details.end()) sipaccount->setZrtpNotSuppWarning((it->second == "true")); + it = map_cpy.find (ZRTP_NOT_SUPP_WARNING); - it = map_cpy.find(ZRTP_HELLO_HASH); - if (it != details.end()) sipaccount->setZrtpHelloHash((it->second == "true")); + if (it != details.end()) sipaccount->setZrtpNotSuppWarning ( (it->second == "true")); - it = map_cpy.find(ZRTP_DISPLAY_SAS_ONCE); - if (it != details.end()) sipaccount->setZrtpDiaplaySasOnce((it->second == "true")); + it = map_cpy.find (ZRTP_HELLO_HASH); - setTlsSettings(IP2IP_PROFILE, details); + if (it != details.end()) sipaccount->setZrtpHelloHash ( (it->second == "true")); - Manager::instance().saveConfig(); + it = map_cpy.find (ZRTP_DISPLAY_SAS_ONCE); - // Update account details to the client side - accountsChanged(); + if (it != details.end()) sipaccount->setZrtpDiaplaySasOnce ( (it->second == "true")); - // Reload account settings from config - Manager::instance().getAccount(IP2IP_PROFILE)->loadConfig(); + setTlsSettings (IP2IP_PROFILE, details); + + Manager::instance().saveConfig(); + + // Update account details to the client side + accountsChanged(); + + // Reload account settings from config + Manager::instance().getAccount (IP2IP_PROFILE)->loadConfig(); } -std::map<std::string, std::string> ConfigurationManager::getTlsSettings( - const std::string& section) { +std::map<std::string, std::string> ConfigurationManager::getTlsSettings ( + const std::string& section) { - std::map<std::string, std::string> tlsSettings; + std::map<std::string, std::string> tlsSettings; - SIPAccount *sipaccount = (SIPAccount *)Manager::instance().getAccount(IP2IP_PROFILE); + SIPAccount *sipaccount = (SIPAccount *) Manager::instance().getAccount (IP2IP_PROFILE); - if(!sipaccount) - return tlsSettings; + if (!sipaccount) + return tlsSettings; - std::stringstream portstr; portstr << sipaccount->getTlsListenerPort(); - tlsSettings.insert(std::pair<std::string, std::string>(TLS_LISTENER_PORT, portstr.str())); - tlsSettings.insert(std::pair<std::string, std::string>(TLS_ENABLE, sipaccount->getTlsEnable())); - tlsSettings.insert(std::pair<std::string, std::string>(TLS_CA_LIST_FILE, sipaccount->getTlsCaListFile())); - tlsSettings.insert(std::pair<std::string, std::string>(TLS_CERTIFICATE_FILE, sipaccount->getTlsCertificateFile())); - tlsSettings.insert(std::pair<std::string, std::string>(TLS_PRIVATE_KEY_FILE, sipaccount->getTlsPrivateKeyFile())); - tlsSettings.insert(std::pair<std::string, std::string>(TLS_PASSWORD, sipaccount->getTlsPassword())); - tlsSettings.insert(std::pair<std::string, std::string>(TLS_METHOD, sipaccount->getTlsMethod())); - tlsSettings.insert(std::pair<std::string, std::string>(TLS_CIPHERS, sipaccount->getTlsCiphers())); - tlsSettings.insert(std::pair<std::string, std::string>(TLS_SERVER_NAME, sipaccount->getTlsServerName())); - tlsSettings.insert(std::pair<std::string, std::string>(TLS_VERIFY_SERVER, sipaccount->getTlsVerifyServer() ? "true" : "false")); - tlsSettings.insert(std::pair<std::string, std::string>(TLS_VERIFY_CLIENT, sipaccount->getTlsVerifyClient() ? "true" : "false")); - tlsSettings.insert(std::pair<std::string, std::string>(TLS_REQUIRE_CLIENT_CERTIFICATE, sipaccount->getTlsRequireClientCertificate() ? "true" : "false")); - tlsSettings.insert(std::pair<std::string, std::string>(TLS_NEGOTIATION_TIMEOUT_SEC, sipaccount->getTlsNegotiationTimeoutSec())); - tlsSettings.insert(std::pair<std::string, std::string>(TLS_NEGOTIATION_TIMEOUT_MSEC, sipaccount->getTlsNegotiationTimeoutMsec())); + std::stringstream portstr; + portstr << sipaccount->getTlsListenerPort(); + tlsSettings.insert (std::pair<std::string, std::string> (TLS_LISTENER_PORT, portstr.str())); + tlsSettings.insert (std::pair<std::string, std::string> (TLS_ENABLE, sipaccount->getTlsEnable())); + tlsSettings.insert (std::pair<std::string, std::string> (TLS_CA_LIST_FILE, sipaccount->getTlsCaListFile())); + tlsSettings.insert (std::pair<std::string, std::string> (TLS_CERTIFICATE_FILE, sipaccount->getTlsCertificateFile())); + tlsSettings.insert (std::pair<std::string, std::string> (TLS_PRIVATE_KEY_FILE, sipaccount->getTlsPrivateKeyFile())); + tlsSettings.insert (std::pair<std::string, std::string> (TLS_PASSWORD, sipaccount->getTlsPassword())); + tlsSettings.insert (std::pair<std::string, std::string> (TLS_METHOD, sipaccount->getTlsMethod())); + tlsSettings.insert (std::pair<std::string, std::string> (TLS_CIPHERS, sipaccount->getTlsCiphers())); + tlsSettings.insert (std::pair<std::string, std::string> (TLS_SERVER_NAME, sipaccount->getTlsServerName())); + tlsSettings.insert (std::pair<std::string, std::string> (TLS_VERIFY_SERVER, sipaccount->getTlsVerifyServer() ? "true" : "false")); + tlsSettings.insert (std::pair<std::string, std::string> (TLS_VERIFY_CLIENT, sipaccount->getTlsVerifyClient() ? "true" : "false")); + tlsSettings.insert (std::pair<std::string, std::string> (TLS_REQUIRE_CLIENT_CERTIFICATE, sipaccount->getTlsRequireClientCertificate() ? "true" : "false")); + tlsSettings.insert (std::pair<std::string, std::string> (TLS_NEGOTIATION_TIMEOUT_SEC, sipaccount->getTlsNegotiationTimeoutSec())); + tlsSettings.insert (std::pair<std::string, std::string> (TLS_NEGOTIATION_TIMEOUT_MSEC, sipaccount->getTlsNegotiationTimeoutMsec())); - return tlsSettings; + return tlsSettings; } -void ConfigurationManager::setTlsSettings(const std::string& section, - const std::map<std::string, std::string>& details) { +void ConfigurationManager::setTlsSettings (const std::string& section, + const std::map<std::string, std::string>& details) { + + std::map<std::string, std::string> map_cpy = details; + std::map<std::string, std::string>::iterator it; + + SIPAccount * sipaccount = (SIPAccount *) Manager::instance().getAccount (IP2IP_PROFILE); + + if (!sipaccount) { + _debug ("ConfigurationManager: Error: No valid account in set TLS settings"); + return; + } + + it = map_cpy.find (TLS_LISTENER_PORT); - std::map<std::string, std::string> map_cpy = details; - std::map<std::string, std::string>::iterator it; + if (it != details.end()) sipaccount->setTlsListenerPort (atoi (it->second.data())); - SIPAccount * sipaccount = (SIPAccount *)Manager::instance().getAccount(IP2IP_PROFILE); + it = map_cpy.find (TLS_ENABLE); - if(!sipaccount) { - _debug("ConfigurationManager: Error: No valid account in set TLS settings"); - return; - } + if (it != details.end()) sipaccount->setTlsEnable (it->second); - it = map_cpy.find(TLS_LISTENER_PORT); - if (it != details.end()) sipaccount->setTlsListenerPort(atoi(it->second.data())); + it = map_cpy.find (TLS_CA_LIST_FILE); - it = map_cpy.find(TLS_ENABLE); - if (it != details.end()) sipaccount->setTlsEnable(it->second); + if (it != map_cpy.end()) sipaccount->setTlsCaListFile (it->second); - it = map_cpy.find(TLS_CA_LIST_FILE); - if (it != map_cpy.end()) sipaccount->setTlsCaListFile(it->second); + it = map_cpy.find (TLS_CERTIFICATE_FILE); - it = map_cpy.find(TLS_CERTIFICATE_FILE); - if (it != map_cpy.end()) sipaccount->setTlsCertificateFile(it->second); + if (it != map_cpy.end()) sipaccount->setTlsCertificateFile (it->second); - it = map_cpy.find(TLS_PRIVATE_KEY_FILE); - if (it != map_cpy.end()) sipaccount->setTlsPrivateKeyFile(it->second); + it = map_cpy.find (TLS_PRIVATE_KEY_FILE); - it = map_cpy.find(TLS_PASSWORD); - if (it != map_cpy.end()) sipaccount->setTlsPassword(it->second); + if (it != map_cpy.end()) sipaccount->setTlsPrivateKeyFile (it->second); - it = map_cpy.find(TLS_METHOD); - if (it != map_cpy.end()) sipaccount->setTlsMethod(it->second); + it = map_cpy.find (TLS_PASSWORD); - it = map_cpy.find(TLS_CIPHERS); - if (it != map_cpy.end()) sipaccount->setTlsCiphers(it->second); + if (it != map_cpy.end()) sipaccount->setTlsPassword (it->second); - it = map_cpy.find(TLS_SERVER_NAME); - if (it != map_cpy.end()) sipaccount->setTlsServerName(it->second); + it = map_cpy.find (TLS_METHOD); - it = map_cpy.find(TLS_VERIFY_CLIENT); - if (it != map_cpy.end()) sipaccount->setTlsVerifyClient((it->second == "true") ? true : false); + if (it != map_cpy.end()) sipaccount->setTlsMethod (it->second); - it = map_cpy.find(TLS_REQUIRE_CLIENT_CERTIFICATE); - if (it != map_cpy.end()) sipaccount->setTlsRequireClientCertificate((it->second == "true") ? true : false); + it = map_cpy.find (TLS_CIPHERS); - it = map_cpy.find(TLS_NEGOTIATION_TIMEOUT_SEC); - if (it != map_cpy.end()) sipaccount->setTlsNegotiationTimeoutSec(it->second); + if (it != map_cpy.end()) sipaccount->setTlsCiphers (it->second); - it = map_cpy.find(TLS_NEGOTIATION_TIMEOUT_MSEC); - if (it != map_cpy.end()) sipaccount->setTlsNegotiationTimeoutMsec(it->second); + it = map_cpy.find (TLS_SERVER_NAME); - Manager::instance().saveConfig(); + if (it != map_cpy.end()) sipaccount->setTlsServerName (it->second); - // Update account details to the client side - accountsChanged(); + it = map_cpy.find (TLS_VERIFY_CLIENT); + + if (it != map_cpy.end()) sipaccount->setTlsVerifyClient ( (it->second == "true") ? true : false); + + it = map_cpy.find (TLS_REQUIRE_CLIENT_CERTIFICATE); + + if (it != map_cpy.end()) sipaccount->setTlsRequireClientCertificate ( (it->second == "true") ? true : false); + + it = map_cpy.find (TLS_NEGOTIATION_TIMEOUT_SEC); + + if (it != map_cpy.end()) sipaccount->setTlsNegotiationTimeoutSec (it->second); + + it = map_cpy.find (TLS_NEGOTIATION_TIMEOUT_MSEC); + + if (it != map_cpy.end()) sipaccount->setTlsNegotiationTimeoutMsec (it->second); + + Manager::instance().saveConfig(); + + // Update account details to the client side + accountsChanged(); } -std::map<std::string, std::string> ConfigurationManager::getCredential( - const std::string& accountID, const int32_t& index) { +std::map<std::string, std::string> ConfigurationManager::getCredential ( + const std::string& accountID, const int32_t& index) { + + Account *account = Manager::instance().getAccount (accountID); - Account *account = Manager::instance().getAccount(accountID); + std::map<std::string, std::string> credentialInformation; - std::map<std::string, std::string> credentialInformation; + if (account->getType() != "SIP") + return credentialInformation; - if(account->getType() != "SIP") - return credentialInformation; + SIPAccount *sipaccount = (SIPAccount *) account; - SIPAccount *sipaccount = (SIPAccount *)account; - - if(index == 0) { - std::string username = sipaccount->getUsername(); - std::string password = sipaccount->getPassword(); + if (index == 0) { + std::string username = sipaccount->getUsername(); + std::string password = sipaccount->getPassword(); std::string realm = sipaccount->getRealm(); - credentialInformation.insert(std::pair<std::string, std::string>(USERNAME, username)); - credentialInformation.insert(std::pair<std::string, std::string>(PASSWORD, password)); - credentialInformation.insert(std::pair<std::string, std::string>(REALM, realm)); - } - else { + credentialInformation.insert (std::pair<std::string, std::string> (USERNAME, username)); + credentialInformation.insert (std::pair<std::string, std::string> (PASSWORD, password)); + credentialInformation.insert (std::pair<std::string, std::string> (REALM, realm)); + } else { - // TODO: implement for extra credentials - std::string username = sipaccount->getUsername(); - std::string password = sipaccount->getPassword(); - std::string realm = sipaccount->getRealm(); + // TODO: implement for extra credentials + std::string username = sipaccount->getUsername(); + std::string password = sipaccount->getPassword(); + std::string realm = sipaccount->getRealm(); - credentialInformation.insert(std::pair<std::string, std::string>(USERNAME, username)); - credentialInformation.insert(std::pair<std::string, std::string>(PASSWORD, password)); - credentialInformation.insert(std::pair<std::string, std::string>(REALM, realm)); - } + credentialInformation.insert (std::pair<std::string, std::string> (USERNAME, username)); + credentialInformation.insert (std::pair<std::string, std::string> (PASSWORD, password)); + credentialInformation.insert (std::pair<std::string, std::string> (REALM, realm)); + } - return credentialInformation; + return credentialInformation; } -int32_t ConfigurationManager::getNumberOfCredential( - const std::string& accountID) { +int32_t ConfigurationManager::getNumberOfCredential ( + const std::string& accountID) { - SIPAccount *sipaccount = (SIPAccount *)Manager::instance().getAccount(accountID); - return sipaccount->getCredentialCount(); + SIPAccount *sipaccount = (SIPAccount *) Manager::instance().getAccount (accountID); + return sipaccount->getCredentialCount(); } -void ConfigurationManager::setNumberOfCredential(const std::string& accountID, - const int32_t& number) { - /* - if (accountID != AccountNULL || !accountID.empty()) { - SIPAccount *sipaccount = (SIPAccount *)Manager::instance().getAccount(accountID); - sipaccount->setCredentialCount(number); - } - */ +void ConfigurationManager::setNumberOfCredential (const std::string& accountID, + const int32_t& number) { + /* + if (accountID != AccountNULL || !accountID.empty()) { + SIPAccount *sipaccount = (SIPAccount *)Manager::instance().getAccount(accountID); + sipaccount->setCredentialCount(number); + } + */ } -void ConfigurationManager::setCredential(const std::string& accountID, - const int32_t& index, const std::map<std::string, std::string>& details) { - Manager::instance().setCredential(accountID, index, details); +void ConfigurationManager::setCredential (const std::string& accountID, + const int32_t& index, const std::map<std::string, std::string>& details) { + Manager::instance().setCredential (accountID, index, details); } -void ConfigurationManager::deleteAllCredential(const std::string& accountID) { - Manager::instance().deleteAllCredential(accountID); +void ConfigurationManager::deleteAllCredential (const std::string& accountID) { + Manager::instance().deleteAllCredential (accountID); } -void ConfigurationManager::setAccountDetails(const std::string& accountID, - const std::map<std::string, std::string>& details) { - Manager::instance().setAccountDetails(accountID, details); +void ConfigurationManager::setAccountDetails (const std::string& accountID, + const std::map<std::string, std::string>& details) { + Manager::instance().setAccountDetails (accountID, details); } -void ConfigurationManager::sendRegister(const std::string& accountID, - const int32_t& expire) { - Manager::instance().sendRegister(accountID, expire); +void ConfigurationManager::sendRegister (const std::string& accountID, + const int32_t& expire) { + Manager::instance().sendRegister (accountID, expire); } -std::string ConfigurationManager::addAccount(const std::map<std::string, - std::string>& details) { - return Manager::instance().addAccount(details); +std::string ConfigurationManager::addAccount (const std::map<std::string, + std::string>& details) { + return Manager::instance().addAccount (details); } -void ConfigurationManager::removeAccount(const std::string& accoundID) { - return Manager::instance().removeAccount(accoundID); +void ConfigurationManager::removeAccount (const std::string& accoundID) { + return Manager::instance().removeAccount (accoundID); } std::vector<std::string> ConfigurationManager::getAccountList() { - return Manager::instance().getAccountList(); + return Manager::instance().getAccountList(); } //TODO std::vector<std::string> ConfigurationManager::getToneLocaleList() { - std::vector<std::string> ret; - return ret; + std::vector<std::string> ret; + return ret; } //TODO std::string ConfigurationManager::getVersion() { - std::string ret(""); - return ret; + std::string ret (""); + return ret; } //TODO std::vector<std::string> ConfigurationManager::getRingtoneList() { - std::vector<std::string> ret; - return ret; + std::vector<std::string> ret; + return ret; } /** * Send the list of all codecs loaded to the client through DBus. * Can stay global, as only the active codecs will be set per accounts */ -std::vector<std::string> ConfigurationManager::getCodecList(void) { +std::vector<std::string> ConfigurationManager::getCodecList (void) { - std::vector<std::string> list; + std::vector<std::string> list; - CodecsMap codecs = Manager::instance().getCodecDescriptorMap().getCodecsMap(); - CodecsMap::iterator iter = codecs.begin(); + CodecsMap codecs = Manager::instance().getCodecDescriptorMap().getCodecsMap(); + CodecsMap::iterator iter = codecs.begin(); - while (iter != codecs.end()) { - std::stringstream ss; + while (iter != codecs.end()) { + std::stringstream ss; - if (iter->second != NULL) { - ss << iter->first; - list.push_back((ss.str()).data()); - } + if (iter->second != NULL) { + ss << iter->first; + list.push_back ( (ss.str()).data()); + } - iter++; - } + iter++; + } - return list; + return list; } -std::vector<std::string> ConfigurationManager::getSupportedTlsMethod(void) { - std::vector<std::string> method; - method.push_back("Default"); - method.push_back("TLSv1"); - method.push_back("SSLv2"); - method.push_back("SSLv3"); - method.push_back("SSLv23"); - return method; +std::vector<std::string> ConfigurationManager::getSupportedTlsMethod (void) { + std::vector<std::string> method; + method.push_back ("Default"); + method.push_back ("TLSv1"); + method.push_back ("SSLv2"); + method.push_back ("SSLv3"); + method.push_back ("SSLv23"); + return method; } -std::vector<std::string> ConfigurationManager::getCodecDetails( - const int32_t& payload) { +std::vector<std::string> ConfigurationManager::getCodecDetails ( + const int32_t& payload) { - return Manager::instance().getCodecDescriptorMap().getCodecSpecifications( - payload); + return Manager::instance().getCodecDescriptorMap().getCodecSpecifications ( + payload); } -std::vector<std::string> ConfigurationManager::getActiveCodecList( - const std::string& accountID) { +std::vector<std::string> ConfigurationManager::getActiveCodecList ( + const std::string& accountID) { + + _debug ("Send active codec list for account %s", accountID.c_str ()); - _debug("Send active codec list for account %s", accountID.c_str ()); + std::vector<std::string> v; + Account *acc; + CodecOrder active; + unsigned int i = 0; + size_t size; - std::vector<std::string> v; - Account *acc; - CodecOrder active; - unsigned int i = 0; - size_t size; + acc = Manager::instance().getAccount (accountID); - acc = Manager::instance().getAccount(accountID); - if (acc != NULL) { - active = acc->getActiveCodecs(); - size = active.size(); - while (i < size) { - std::stringstream ss; - ss << active[i]; - v.push_back((ss.str()).data()); - i++; - } - } + if (acc != NULL) { + active = acc->getActiveCodecs(); + size = active.size(); - return v; + while (i < size) { + std::stringstream ss; + ss << active[i]; + v.push_back ( (ss.str()).data()); + i++; + } + } + + return v; } -void ConfigurationManager::setActiveCodecList( - const std::vector<std::string>& list, const std::string& accountID) { +void ConfigurationManager::setActiveCodecList ( + const std::vector<std::string>& list, const std::string& accountID) { + + _debug ("ConfigurationManager: Active codec list received"); - _debug ("ConfigurationManager: Active codec list received"); + Account *acc; - Account *acc; + // Save the codecs list per account + acc = Manager::instance().getAccount (accountID); - // Save the codecs list per account - acc = Manager::instance().getAccount(accountID); - if (acc != NULL) { - acc->setActiveCodecs(list); - } + if (acc != NULL) { + acc->setActiveCodecs (list); + } } std::vector<std::string> ConfigurationManager::getAudioPluginList() { - std::vector<std::string> v; + std::vector<std::string> v; - v.push_back(PCM_DEFAULT); - // v.push_back(PCM_DMIX); - v.push_back(PCM_DMIX_DSNOOP); + v.push_back (PCM_DEFAULT); + // v.push_back(PCM_DMIX); + v.push_back (PCM_DMIX_DSNOOP); - return v; + return v; } -void ConfigurationManager::setInputAudioPlugin(const std::string& audioPlugin) { - return Manager::instance().setInputAudioPlugin(audioPlugin); +void ConfigurationManager::setInputAudioPlugin (const std::string& audioPlugin) { + return Manager::instance().setInputAudioPlugin (audioPlugin); } -void ConfigurationManager::setOutputAudioPlugin(const std::string& audioPlugin) { - return Manager::instance().setOutputAudioPlugin(audioPlugin); +void ConfigurationManager::setOutputAudioPlugin (const std::string& audioPlugin) { + return Manager::instance().setOutputAudioPlugin (audioPlugin); } std::vector<std::string> ConfigurationManager::getAudioOutputDeviceList() { - return Manager::instance().getAudioOutputDeviceList(); + return Manager::instance().getAudioOutputDeviceList(); } std::vector<std::string> ConfigurationManager::getAudioInputDeviceList() { - return Manager::instance().getAudioInputDeviceList(); + return Manager::instance().getAudioInputDeviceList(); } -void ConfigurationManager::setAudioOutputDevice(const int32_t& index) { - return Manager::instance().setAudioDevice(index, SFL_PCM_PLAYBACK); +void ConfigurationManager::setAudioOutputDevice (const int32_t& index) { + return Manager::instance().setAudioDevice (index, SFL_PCM_PLAYBACK); } -void ConfigurationManager::setAudioInputDevice(const int32_t& index) { - return Manager::instance().setAudioDevice(index, SFL_PCM_CAPTURE); +void ConfigurationManager::setAudioInputDevice (const int32_t& index) { + return Manager::instance().setAudioDevice (index, SFL_PCM_CAPTURE); } -void ConfigurationManager::setAudioRingtoneDevice(const int32_t& index) { - return Manager::instance().setAudioDevice(index, SFL_PCM_RINGTONE); +void ConfigurationManager::setAudioRingtoneDevice (const int32_t& index) { + return Manager::instance().setAudioDevice (index, SFL_PCM_RINGTONE); } std::vector<std::string> ConfigurationManager::getCurrentAudioDevicesIndex() { - return Manager::instance().getCurrentAudioDevicesIndex(); + return Manager::instance().getCurrentAudioDevicesIndex(); } -int32_t ConfigurationManager::getAudioDeviceIndex(const std::string& name) { - return Manager::instance().getAudioDeviceIndex(name); +int32_t ConfigurationManager::getAudioDeviceIndex (const std::string& name) { + return Manager::instance().getAudioDeviceIndex (name); } -std::string ConfigurationManager::getCurrentAudioOutputPlugin(void) { - return Manager::instance().getCurrentAudioOutputPlugin(); +std::string ConfigurationManager::getCurrentAudioOutputPlugin (void) { + return Manager::instance().getCurrentAudioOutputPlugin(); } -std::string ConfigurationManager::getEchoCancelState(void) { - return Manager::instance().getEchoCancelState(); +std::string ConfigurationManager::getEchoCancelState (void) { + return Manager::instance().getEchoCancelState(); } -void ConfigurationManager::setEchoCancelState(const std::string& state) { - Manager::instance().setEchoCancelState(state); +void ConfigurationManager::setEchoCancelState (const std::string& state) { + Manager::instance().setEchoCancelState (state); } -std::string ConfigurationManager::getNoiseSuppressState(void) { - return Manager::instance().getNoiseSuppressState(); +std::string ConfigurationManager::getNoiseSuppressState (void) { + return Manager::instance().getNoiseSuppressState(); } -void ConfigurationManager::setNoiseSuppressState(const std::string& state) { - Manager::instance().setNoiseSuppressState(state); +void ConfigurationManager::setNoiseSuppressState (const std::string& state) { + Manager::instance().setNoiseSuppressState (state); } std::vector<std::string> ConfigurationManager::getPlaybackDeviceList() { - std::vector<std::string> ret; - return ret; + std::vector<std::string> ret; + return ret; } std::vector<std::string> ConfigurationManager::getRecordDeviceList() { - std::vector<std::string> ret; - return ret; + std::vector<std::string> ret; + return ret; } -bool ConfigurationManager::isMd5CredentialHashing(void) { - return Manager::instance().preferences.getMd5Hash(); +bool ConfigurationManager::isMd5CredentialHashing (void) { + return Manager::instance().preferences.getMd5Hash(); } -void ConfigurationManager::setMd5CredentialHashing(const bool& enabled) { - Manager::instance().preferences.setMd5Hash(enabled); +void ConfigurationManager::setMd5CredentialHashing (const bool& enabled) { + Manager::instance().preferences.setMd5Hash (enabled); } -int32_t ConfigurationManager::isIax2Enabled(void) { - return Manager::instance().isIax2Enabled(); +int32_t ConfigurationManager::isIax2Enabled (void) { + return Manager::instance().isIax2Enabled(); } -void ConfigurationManager::ringtoneEnabled(const std::string& accountID) { - Manager::instance().ringtoneEnabled(accountID); +void ConfigurationManager::ringtoneEnabled (const std::string& accountID) { + Manager::instance().ringtoneEnabled (accountID); } -int32_t ConfigurationManager::isRingtoneEnabled(const std::string& accountID) { - return Manager::instance().isRingtoneEnabled(accountID); +int32_t ConfigurationManager::isRingtoneEnabled (const std::string& accountID) { + return Manager::instance().isRingtoneEnabled (accountID); } -std::string ConfigurationManager::getRingtoneChoice(const std::string& accountID) { - return Manager::instance().getRingtoneChoice(accountID); +std::string ConfigurationManager::getRingtoneChoice (const std::string& accountID) { + return Manager::instance().getRingtoneChoice (accountID); } -void ConfigurationManager::setRingtoneChoice(const std::string& accountID, const std::string& tone) { - Manager::instance().setRingtoneChoice(accountID, tone); +void ConfigurationManager::setRingtoneChoice (const std::string& accountID, const std::string& tone) { + Manager::instance().setRingtoneChoice (accountID, tone); } -std::string ConfigurationManager::getRecordPath(void) { - return Manager::instance().getRecordPath(); +std::string ConfigurationManager::getRecordPath (void) { + return Manager::instance().getRecordPath(); } -void ConfigurationManager::setRecordPath(const std::string& recPath) { - Manager::instance().setRecordPath(recPath); +void ConfigurationManager::setRecordPath (const std::string& recPath) { + Manager::instance().setRecordPath (recPath); } /* @@ -591,12 +617,12 @@ void ConfigurationManager::setVolumeControls(const bool& display) { } */ -int32_t ConfigurationManager::getHistoryLimit(void) { - return Manager::instance().getHistoryLimit(); +int32_t ConfigurationManager::getHistoryLimit (void) { + return Manager::instance().getHistoryLimit(); } -void ConfigurationManager::setHistoryLimit(const int32_t& days) { - Manager::instance().setHistoryLimit(days); +void ConfigurationManager::setHistoryLimit (const int32_t& days) { + Manager::instance().setHistoryLimit (days); } /* @@ -633,122 +659,122 @@ int32_t ConfigurationManager::getNotify(void) { } */ -void ConfigurationManager::setAudioManager(const int32_t& api) { - Manager::instance().setAudioManager(api); +void ConfigurationManager::setAudioManager (const int32_t& api) { + Manager::instance().setAudioManager (api); } -int32_t ConfigurationManager::getAudioManager(void) { - return Manager::instance().getAudioManager(); +int32_t ConfigurationManager::getAudioManager (void) { + return Manager::instance().getAudioManager(); } -void ConfigurationManager::setMailNotify(void) { - Manager::instance().setMailNotify(); +void ConfigurationManager::setMailNotify (void) { + Manager::instance().setMailNotify(); } -int32_t ConfigurationManager::getMailNotify(void) { - return Manager::instance().getMailNotify(); +int32_t ConfigurationManager::getMailNotify (void) { + return Manager::instance().getMailNotify(); } -std::map<std::string, int32_t> ConfigurationManager::getAddressbookSettings( - void) { - return Manager::instance().getAddressbookSettings(); +std::map<std::string, int32_t> ConfigurationManager::getAddressbookSettings ( + void) { + return Manager::instance().getAddressbookSettings(); } -void ConfigurationManager::setAddressbookSettings(const std::map<std::string, - int32_t>& settings) { - Manager::instance().setAddressbookSettings(settings); +void ConfigurationManager::setAddressbookSettings (const std::map<std::string, + int32_t>& settings) { + Manager::instance().setAddressbookSettings (settings); } -std::vector<std::string> ConfigurationManager::getAddressbookList(void) { - return Manager::instance().getAddressbookList(); +std::vector<std::string> ConfigurationManager::getAddressbookList (void) { + return Manager::instance().getAddressbookList(); } -void ConfigurationManager::setAddressbookList( - const std::vector<std::string>& list) { - Manager::instance().setAddressbookList(list); +void ConfigurationManager::setAddressbookList ( + const std::vector<std::string>& list) { + Manager::instance().setAddressbookList (list); } -std::map<std::string, std::string> ConfigurationManager::getHookSettings(void) { - return Manager::instance().getHookSettings(); +std::map<std::string, std::string> ConfigurationManager::getHookSettings (void) { + return Manager::instance().getHookSettings(); } -void ConfigurationManager::setHookSettings(const std::map<std::string, - std::string>& settings) { - Manager::instance().setHookSettings(settings); +void ConfigurationManager::setHookSettings (const std::map<std::string, + std::string>& settings) { + Manager::instance().setHookSettings (settings); } -void ConfigurationManager::setAccountsOrder(const std::string& order) { - Manager::instance().setAccountsOrder(order); +void ConfigurationManager::setAccountsOrder (const std::string& order) { + Manager::instance().setAccountsOrder (order); } -std::map<std::string, std::string> ConfigurationManager::getHistory(void) { - return Manager::instance().send_history_to_client(); +std::map<std::string, std::string> ConfigurationManager::getHistory (void) { + return Manager::instance().send_history_to_client(); } -void ConfigurationManager::setHistory( - const std::map<std::string, std::string>& entries) { - Manager::instance().receive_history_from_client(entries); +void ConfigurationManager::setHistory ( + const std::map<std::string, std::string>& entries) { + Manager::instance().receive_history_from_client (entries); } -std::string ConfigurationManager::getAddrFromInterfaceName( - const std::string& interface) { +std::string ConfigurationManager::getAddrFromInterfaceName ( + const std::string& interface) { - std::string address = SIPVoIPLink::instance("")->getInterfaceAddrFromName( - interface); + std::string address = SIPVoIPLink::instance ("")->getInterfaceAddrFromName ( + interface); - return address; + return address; } -std::vector<std::string> ConfigurationManager::getAllIpInterface(void) { +std::vector<std::string> ConfigurationManager::getAllIpInterface (void) { - std::vector<std::string> vector; - SIPVoIPLink * sipLink = NULL; - sipLink = SIPVoIPLink::instance(""); + std::vector<std::string> vector; + SIPVoIPLink * sipLink = NULL; + sipLink = SIPVoIPLink::instance (""); - if (sipLink != NULL) { - vector = sipLink->getAllIpInterface(); - } + if (sipLink != NULL) { + vector = sipLink->getAllIpInterface(); + } - return vector; + return vector; } -std::vector<std::string> ConfigurationManager::getAllIpInterfaceByName(void) { - std::vector<std::string> vector; - SIPVoIPLink * sipLink = NULL; - sipLink = SIPVoIPLink::instance(""); +std::vector<std::string> ConfigurationManager::getAllIpInterfaceByName (void) { + std::vector<std::string> vector; + SIPVoIPLink * sipLink = NULL; + sipLink = SIPVoIPLink::instance (""); - if (sipLink != NULL) { - vector = sipLink->getAllIpInterfaceByName(); - } + if (sipLink != NULL) { + vector = sipLink->getAllIpInterfaceByName(); + } - return vector; + return vector; } std::map<std::string, std::string> ConfigurationManager::getShortcuts() { - return Manager::instance().shortcutPreferences.getShortcuts(); + return Manager::instance().shortcutPreferences.getShortcuts(); } -void ConfigurationManager::setShortcuts( - const std::map<std::string, std::string>& shortcutsMap) { +void ConfigurationManager::setShortcuts ( + const std::map<std::string, std::string>& shortcutsMap) { + + std::map<std::string, std::string> map_cpy = shortcutsMap; + /* + std::map<std::string, std::string> map_cpy = shortcutsMap; + std::map<std::string, std::string>::iterator it; - std::map<std::string, std::string> map_cpy = shortcutsMap; - /* - std::map<std::string, std::string> map_cpy = shortcutsMap; - std::map<std::string, std::string>::iterator it; + for (int i = 0; i < (int)shortcutsKeys.size(); i++) { + std::string key = shortcutsKeys.at(i); + it = map_cpy.find(key); + if (it != shortcutsMap.end()) { - for (int i = 0; i < (int)shortcutsKeys.size(); i++) { - std::string key = shortcutsKeys.at(i); - it = map_cpy.find(key); - if (it != shortcutsMap.end()) { - - Manager::instance().setConfig("Shortcuts", key, it->second); - } - } - */ - Manager::instance().shortcutPreferences.setShortcuts(map_cpy); + Manager::instance().setConfig("Shortcuts", key, it->second); + } + } + */ + Manager::instance().shortcutPreferences.setShortcuts (map_cpy); - Manager::instance().saveConfig(); + Manager::instance().saveConfig(); } diff --git a/sflphone-common/src/dbus/contactmanager.cpp b/sflphone-common/src/dbus/contactmanager.cpp index 8474f6eac89acdef801631749cef3f4eb343e00d..cc4813ca2b752b8552ef361246c9783f8dd17612 100644 --- a/sflphone-common/src/dbus/contactmanager.cpp +++ b/sflphone-common/src/dbus/contactmanager.cpp @@ -34,27 +34,23 @@ 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 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 } 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 } 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 } diff --git a/sflphone-common/src/dbus/dbusmanagerimpl.cpp b/sflphone-common/src/dbus/dbusmanagerimpl.cpp index 1c70b42df81d09bb5d7bfd4820d57ebfcdb22e9c..62a5f4de9abcb0a3cec36d32d08937fc060073c9 100644 --- a/sflphone-common/src/dbus/dbusmanagerimpl.cpp +++ b/sflphone-common/src/dbus/dbusmanagerimpl.cpp @@ -39,8 +39,7 @@ const char* DBusManagerImpl::SERVER_NAME = "org.sflphone.SFLphone"; int -DBusManagerImpl::exec() -{ +DBusManagerImpl::exec() { DBus::default_dispatcher = &_dispatcher; @@ -53,7 +52,7 @@ DBusManagerImpl::exec() _instanceManager = new Instance (sessionConnection); #ifdef USE_NETWORKMANAGER - _networkManager = new NetworkManager(systemConnection, "/org/freedesktop/NetworkManager", ""); + _networkManager = new NetworkManager (systemConnection, "/org/freedesktop/NetworkManager", ""); #endif // Register accounts @@ -66,8 +65,7 @@ DBusManagerImpl::exec() } void -DBusManagerImpl::exit() -{ +DBusManagerImpl::exit() { _dispatcher.leave(); diff --git a/sflphone-common/src/dbus/instance.cpp b/sflphone-common/src/dbus/instance.cpp index 5813332ffbe071d06d9ccc95c1ccd3423b048cc9..00b4b7c80f607396be355346df1102e5081214b9 100644 --- a/sflphone-common/src/dbus/instance.cpp +++ b/sflphone-common/src/dbus/instance.cpp @@ -34,23 +34,20 @@ const char* Instance::SERVER_PATH = "/org/sflphone/SFLphone/Instance"; Instance::Instance (DBus::Connection& connection) - : DBus::ObjectAdaptor (connection, SERVER_PATH) -{ + : DBus::ObjectAdaptor (connection, SERVER_PATH) { count = 0; } void Instance::Register (const int32_t& pid UNUSED, - const std::string& name UNUSED) -{ + const std::string& name UNUSED) { _debug ("Instance::register received"); count++; } void -Instance::Unregister (const int32_t& pid UNUSED) -{ +Instance::Unregister (const int32_t& pid UNUSED) { _debug ("Instance::unregister received"); count --; @@ -65,8 +62,7 @@ Instance::Unregister (const int32_t& pid UNUSED) } int32_t -Instance::getRegistrationCount (void) -{ +Instance::getRegistrationCount (void) { return count; diff --git a/sflphone-common/src/dbus/networkmanager.cpp b/sflphone-common/src/dbus/networkmanager.cpp index 2e106167591b267648886a046fa168819d471d4a..0bece0f4afee490d74c7a96304defa25db53001a 100644 --- a/sflphone-common/src/dbus/networkmanager.cpp +++ b/sflphone-common/src/dbus/networkmanager.cpp @@ -40,52 +40,48 @@ using namespace std; const string NetworkManager::statesString[5] = {"unknown", "asleep", "connecting", "connected", "disconnected"}; -string NetworkManager::stateAsString(const uint32_t& state) -{ - return statesString[state]; +string NetworkManager::stateAsString (const uint32_t& state) { + return statesString[state]; } -void NetworkManager::StateChanged(const uint32_t& state) -{ - _warn("Network state changed: %s", stateAsString(state).c_str()); +void NetworkManager::StateChanged (const uint32_t& state) { + _warn ("Network state changed: %s", stateAsString (state).c_str()); } -void NetworkManager::PropertiesChanged(const std::map< std::string, ::DBus::Variant >& argin0) -{ - const map< string, ::DBus::Variant >::const_iterator iter = argin0.begin(); +void NetworkManager::PropertiesChanged (const std::map< std::string, ::DBus::Variant >& argin0) { + const map< string, ::DBus::Variant >::const_iterator iter = argin0.begin(); - string message = iter->first; + string message = iter->first; - _warn("Properties changed: %s", iter->first.c_str()); -/* - DBus::Variant variant = iter->second; - DBus::MessageIter i = variant.reader(); - cout << i.type() << endl;// 97 - cout << (char )i.type() << endl; - cout << (char)i.array_type() << endl; + _warn ("Properties changed: %s", iter->first.c_str()); + /* + DBus::Variant variant = iter->second; + DBus::MessageIter i = variant.reader(); + cout << i.type() << endl;// 97 + cout << (char )i.type() << endl; + cout << (char)i.array_type() << endl; - cout << i.is_array() << endl;// 1 - cout << i.is_dict() << endl;// 0 - cout << i.array_type() << endl;// 111 + cout << i.is_array() << endl;// 1 + cout << i.is_dict() << endl;// 0 + cout << i.array_type() << endl;// 111 - int size; - ::DBus::Path* value = new ::DBus::Path[10]; - size = i.get_array(value); - cout << "length: " << size << endl; + int size; + ::DBus::Path* value = new ::DBus::Path[10]; + size = i.get_array(value); + cout << "length: " << size << endl; - while (!i.at_end()) - { - char **array = new char*[2]; - size_t length = i.get_array(&array); - cout << "length: " << length << endl; - i = i.recurse(); - } -*/ - Manager::instance().registerAccounts(); + while (!i.at_end()) + { + char **array = new char*[2]; + size_t length = i.get_array(&array); + cout << "length: " << length << endl; + i = i.recurse(); + } + */ + Manager::instance().registerAccounts(); } -NetworkManager::NetworkManager(DBus::Connection& connection, const DBus::Path& path, const char* destination): DBus::ObjectProxy (connection, path, destination) -{ +NetworkManager::NetworkManager (DBus::Connection& connection, const DBus::Path& path, const char* destination) : DBus::ObjectProxy (connection, path, destination) { } #endif diff --git a/sflphone-common/src/eventthread.cpp b/sflphone-common/src/eventthread.cpp index cc16b5e77f45e448e13455b5ed99853c9b17fcda..24c5279b1c0bdd8249e93a6ab8f5f0721e502a13 100644 --- a/sflphone-common/src/eventthread.cpp +++ b/sflphone-common/src/eventthread.cpp @@ -34,8 +34,7 @@ /********************************** Voiplink thread *************************************/ EventThread::EventThread (VoIPLink *link) - : Thread(), _linkthread (link) -{ + : Thread(), _linkthread (link) { setCancel (cancelDeferred); } @@ -43,8 +42,7 @@ EventThread::EventThread (VoIPLink *link) /** * Reimplementation of run() */ -void EventThread::run (void) -{ +void EventThread::run (void) { while (!testCancel()) { _linkthread->getEvent(); } @@ -53,16 +51,14 @@ void EventThread::run (void) /********************************************************************************************/ AudioThread::AudioThread (AlsaLayer *alsa) - : Thread(), _alsa (alsa) -{ + : Thread(), _alsa (alsa) { setCancel (cancelDeferred); } /** * Reimplementation of run() */ -void AudioThread::run (void) -{ +void AudioThread::run (void) { while (!testCancel()) { _alsa->audioCallback(); Thread::sleep (20); diff --git a/sflphone-common/src/history/historyitem.cpp b/sflphone-common/src/history/historyitem.cpp index 11f47ceb2c2e9cc663eb51a6764b85e6876e6f87..0149b404030866da59120506f00d9e5a8eebcfcb 100644 --- a/sflphone-common/src/history/historyitem.cpp +++ b/sflphone-common/src/history/historyitem.cpp @@ -43,14 +43,12 @@ HistoryItem::HistoryItem (std::string timestamp_start, CallType call_type, std:: _call_type (call_type), _name (name), _number (number), - _account_id (account_id) -{ + _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; @@ -98,13 +96,11 @@ HistoryItem::HistoryItem (std::string timestamp, std::string serialized_form) (serialized_form == EMPTY_STRING) ? _account_id = "" : _account_id=serialized_form ; } -HistoryItem::~HistoryItem () -{ +HistoryItem::~HistoryItem () { // TODO } -bool HistoryItem::save (Conf::ConfigTree **history) -{ +bool HistoryItem::save (Conf::ConfigTree **history) { std::string section, timestamp; std::stringstream call_type; @@ -123,8 +119,7 @@ bool HistoryItem::save (Conf::ConfigTree **history) return res; } -std::string HistoryItem::serialize (void) -{ +std::string HistoryItem::serialize (void) { std::stringstream res; std::string separator = ITEM_SEPARATOR; std::string name, accountID; @@ -142,7 +137,6 @@ std::string HistoryItem::serialize (void) } -bool HistoryItem::non_valid_account (std::string id) -{ +bool HistoryItem::non_valid_account (std::string id) { return !Manager::instance().accountExists (id); } diff --git a/sflphone-common/src/history/historymanager.cpp b/sflphone-common/src/history/historymanager.cpp index 54fa6d1eb614b40a17f35f645f5b5e02b53f6ac4..ad2c13d1240c4b2a209344b4f2c994ca996f8d97 100644 --- a/sflphone-common/src/history/historymanager.cpp +++ b/sflphone-common/src/history/historymanager.cpp @@ -36,29 +36,27 @@ HistoryManager::HistoryManager () : _history_loaded (false), - _history_path ("") -{ + _history_path ("") { } -HistoryManager::~HistoryManager () -{ - HistoryItemMap::iterator iter = _history_items.begin(); +HistoryManager::~HistoryManager () { + HistoryItemMap::iterator iter = _history_items.begin(); - HistoryItem * item; - while(iter != _history_items.end()){ - item = iter->second; - delete item; - iter++; - } + HistoryItem * item; + + while (iter != _history_items.end()) { + item = iter->second; + delete item; + iter++; + } // Clear the history map _history_items.clear (); } -int HistoryManager::load_history (int limit, std::string path) -{ +int HistoryManager::load_history (int limit, std::string path) { Conf::ConfigTree history_list; create_history_path (path); @@ -66,16 +64,14 @@ int HistoryManager::load_history (int limit, std::string path) return load_history_items_map (&history_list, limit); } -bool HistoryManager::save_history (void) -{ +bool HistoryManager::save_history (void) { Conf::ConfigTree history_list; save_history_items_map (&history_list); return save_history_to_file (&history_list); } -bool HistoryManager::load_history_from_file (Conf::ConfigTree *history_list) -{ +bool HistoryManager::load_history_from_file (Conf::ConfigTree *history_list) { bool exist; exist = history_list->populateFromFile (_history_path); @@ -84,8 +80,7 @@ bool HistoryManager::load_history_from_file (Conf::ConfigTree *history_list) return exist; } -int HistoryManager::load_history_items_map (Conf::ConfigTree *history_list, int limit) -{ +int HistoryManager::load_history_items_map (Conf::ConfigTree *history_list, int limit) { short nb_items = 0; Conf::TokenList sections; @@ -128,15 +123,13 @@ int HistoryManager::load_history_items_map (Conf::ConfigTree *history_list, int } -bool HistoryManager::save_history_to_file (Conf::ConfigTree *history_list) -{ +bool HistoryManager::save_history_to_file (Conf::ConfigTree *history_list) { _debug ("Saving history in XDG directory: %s", _history_path.data()); return history_list->saveConfigTree (_history_path.data()); } -int HistoryManager::save_history_items_map (Conf::ConfigTree *history_list) -{ +int HistoryManager::save_history_items_map (Conf::ConfigTree *history_list) { HistoryItemMap::iterator iter; HistoryItem *item; int items_saved = 0; @@ -159,14 +152,12 @@ int HistoryManager::save_history_items_map (Conf::ConfigTree *history_list) return items_saved; } -void HistoryManager::add_new_history_entry (HistoryItem *new_item) -{ +void HistoryManager::add_new_history_entry (HistoryItem *new_item) { // Add it in the map _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 userdata, xdg_env, xdg_data; @@ -202,8 +193,7 @@ int HistoryManager::create_history_path (std::string path) // throw an Conf::ConfigTreeItemException if not found int -HistoryManager::getConfigInt (const std::string& section, const std::string& name, Conf::ConfigTree *history_list) -{ +HistoryManager::getConfigInt (const std::string& section, const std::string& name, Conf::ConfigTree *history_list) { try { return history_list->getConfigTreeItemIntValue (section, name); } catch (Conf::ConfigTreeItemException& e) { @@ -214,8 +204,7 @@ HistoryManager::getConfigInt (const std::string& section, const std::string& nam } std::string -HistoryManager::getConfigString (const std::string& section, const std::string& name, Conf::ConfigTree *history_list) -{ +HistoryManager::getConfigString (const std::string& section, const std::string& name, Conf::ConfigTree *history_list) { try { return history_list->getConfigTreeItemValue (section, name); } catch (Conf::ConfigTreeItemException& e) { @@ -225,8 +214,7 @@ HistoryManager::getConfigString (const std::string& section, const std::string& return ""; } -std::map <std::string, std::string> HistoryManager::get_history_serialized (void) -{ +std::map <std::string, std::string> HistoryManager::get_history_serialized (void) { std::map <std::string, std::string> serialized; HistoryItemMap::iterator iter; HistoryItem *current; @@ -250,8 +238,7 @@ std::map <std::string, std::string> HistoryManager::get_history_serialized (void } -int HistoryManager::set_serialized_history (std::map <std::string, std::string> history, int limit) -{ +int HistoryManager::set_serialized_history (std::map <std::string, std::string> history, int limit) { std::map <std::string, std::string>::iterator iter; HistoryItem *new_item; int items_added = 0; diff --git a/sflphone-common/src/hooks/urlhook.cpp b/sflphone-common/src/hooks/urlhook.cpp index f74aa00ef0794c41f15e84bb96d2040b5e476f40..c0b1dfb3edd326c79cb5f9a0f98d7ea2f1a18cd8 100644 --- a/sflphone-common/src/hooks/urlhook.cpp +++ b/sflphone-common/src/hooks/urlhook.cpp @@ -36,36 +36,36 @@ 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; - std::string temp; - std::vector <std::string> args; - size_t pos; - unsigned int i; + std::string temp; + std::vector <std::string> args; + size_t pos; + unsigned int i; - /* Escape the '&' char to not discard $_GET parameters in the URL - #2659 */ - while ( (pos = field_value.find ("&", 0)) != std::string::npos) { + /* Escape the '&' char to not discard $_GET parameters in the URL - #2659 */ + while ( (pos = field_value.find ("&", 0)) != std::string::npos) { temp = field_value.substr (0, pos); field_value.erase (0, pos + 1); - args.push_back (temp); - std::cout << temp << " " << std::endl; - } + args.push_back (temp); + std::cout << temp << " " << std::endl; + } command_bg = command + " "; - pos = args.size (); - for (i=0; i<pos; i++) { - // Escape the "&" - command_bg += args[i] + "\\&"; - } + pos = args.size (); - // Retrieve the last argument - command_bg += field_value; + for (i=0; i<pos; i++) { + // Escape the "&" + command_bg += args[i] + "\\&"; + } + + // Retrieve the last argument + command_bg += field_value; /* Execute the command in the background to not block the application */ - command_bg += "&"; + command_bg += "&"; /* Execute a system call */ return RUN_COMMAND (command_bg.c_str()); diff --git a/sflphone-common/src/iax/iaxaccount.cpp b/sflphone-common/src/iax/iaxaccount.cpp index b0af8857985bf151b953dbaa3b45900b2b2bf06f..cb120f92d41a39af5ec345b941f28ddf7e553d03 100644 --- a/sflphone-common/src/iax/iaxaccount.cpp +++ b/sflphone-common/src/iax/iaxaccount.cpp @@ -35,170 +35,206 @@ #include "manager.h" IAXAccount::IAXAccount (const AccountID& accountID) - : Account (accountID, "iax2") -{ + : Account (accountID, "iax2") { _link = new IAXVoIPLink (accountID); } -IAXAccount::~IAXAccount() -{ +IAXAccount::~IAXAccount() { delete _link; _link = NULL; } -void IAXAccount::serialize(Conf::YamlEmitter *emitter) -{ - _debug("IaxAccount: serialize %s", _accountID.c_str()); - - Conf::MappingNode accountmap(NULL); - - Conf::ScalarNode id(Account::_accountID); - Conf::ScalarNode username(Account::_username); - Conf::ScalarNode password(Account::_password); - Conf::ScalarNode alias(Account::_alias); - Conf::ScalarNode hostname(Account::_hostname); - Conf::ScalarNode enable(_enabled ? "true" : "false"); - Conf::ScalarNode type(Account::_type); - Conf::ScalarNode mailbox("97"); - - Conf::ScalarNode codecs(_codecStr); - Conf::ScalarNode displayName(_displayName); - - accountmap.setKeyValue(aliasKey, &alias); - accountmap.setKeyValue(typeKey, &type); - accountmap.setKeyValue(idKey, &id); - accountmap.setKeyValue(usernameKey, &username); - accountmap.setKeyValue(passwordKey, &password); - accountmap.setKeyValue(hostnameKey, &hostname); - accountmap.setKeyValue(accountEnableKey, &enable); - accountmap.setKeyValue(mailboxKey, &mailbox); - - accountmap.setKeyValue(displayNameKey, &displayName); - accountmap.setKeyValue(codecsKey, &codecs); - - try{ - emitter->serializeAccount(&accountmap); - } - catch (Conf::YamlEmitterException &e) { - _error("ConfigTree: %s", e.what()); - } +void IAXAccount::serialize (Conf::YamlEmitter *emitter) { + _debug ("IaxAccount: serialize %s", _accountID.c_str()); + + Conf::MappingNode accountmap (NULL); + + Conf::ScalarNode id (Account::_accountID); + Conf::ScalarNode username (Account::_username); + Conf::ScalarNode password (Account::_password); + Conf::ScalarNode alias (Account::_alias); + Conf::ScalarNode hostname (Account::_hostname); + Conf::ScalarNode enable (_enabled ? "true" : "false"); + Conf::ScalarNode type (Account::_type); + Conf::ScalarNode mailbox ("97"); + + Conf::ScalarNode codecs (_codecStr); + Conf::ScalarNode displayName (_displayName); + + accountmap.setKeyValue (aliasKey, &alias); + accountmap.setKeyValue (typeKey, &type); + accountmap.setKeyValue (idKey, &id); + accountmap.setKeyValue (usernameKey, &username); + accountmap.setKeyValue (passwordKey, &password); + accountmap.setKeyValue (hostnameKey, &hostname); + accountmap.setKeyValue (accountEnableKey, &enable); + accountmap.setKeyValue (mailboxKey, &mailbox); + + accountmap.setKeyValue (displayNameKey, &displayName); + accountmap.setKeyValue (codecsKey, &codecs); + + try { + emitter->serializeAccount (&accountmap); + } catch (Conf::YamlEmitterException &e) { + _error ("ConfigTree: %s", e.what()); + } } -void IAXAccount::unserialize(Conf::MappingNode *map) -{ - Conf::ScalarNode *val; - - _debug("IaxAccount: Unserialize"); - - val = (Conf::ScalarNode *)(map->getValue(aliasKey)); - if(val) { _alias = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(typeKey)); - if(val) { _type = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(idKey)); - if(val) { _accountID = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(usernameKey)); - if(val) { _username = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(passwordKey)); - if(val) { _password = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(hostnameKey)); - if(val) { _hostname = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(accountEnableKey)); - if(val) { _enabled = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - // val = (Conf::ScalarNode *)(map->getValue(mailboxKey)); - - val = (Conf::ScalarNode *)(map->getValue(codecsKey)); - if(val) { _codecStr = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(displayNameKey)); - if(val) { _displayName = val->getValue(); val = NULL; } +void IAXAccount::unserialize (Conf::MappingNode *map) { + Conf::ScalarNode *val; + + _debug ("IaxAccount: Unserialize"); + + val = (Conf::ScalarNode *) (map->getValue (aliasKey)); + + if (val) { + _alias = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (typeKey)); + + if (val) { + _type = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (idKey)); + + if (val) { + _accountID = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (usernameKey)); + + if (val) { + _username = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (passwordKey)); + + if (val) { + _password = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (hostnameKey)); + + if (val) { + _hostname = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (accountEnableKey)); + + if (val) { + _enabled = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + // val = (Conf::ScalarNode *)(map->getValue(mailboxKey)); + + val = (Conf::ScalarNode *) (map->getValue (codecsKey)); + + if (val) { + _codecStr = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (displayNameKey)); + + if (val) { + _displayName = val->getValue(); + val = NULL; + } } -void IAXAccount::setAccountDetails(const std::map<std::string, std::string>& details) -{ - std::map<std::string, std::string> map_cpy; - std::map<std::string, std::string>::iterator iter; - - _debug("IaxAccount: Set account details: %s", _accountID.c_str()); - - // Work on a copy - map_cpy = details; - - std::string alias; - std::string type; - std::string hostname; - std::string username; - std::string password; - std::string mailbox; - std::string accountEnable; - - std::string ua_name; - - // Account setting common to SIP and IAX - find_in_map(CONFIG_ACCOUNT_ALIAS, alias) - find_in_map(CONFIG_ACCOUNT_TYPE, type) - find_in_map(HOSTNAME, hostname) - find_in_map(USERNAME, username) - find_in_map(PASSWORD, password) - find_in_map(CONFIG_ACCOUNT_MAILBOX, mailbox); - find_in_map(CONFIG_ACCOUNT_ENABLE, accountEnable); - - setAlias(alias); - setType(type); - setUsername(username); - setHostname(hostname); - setPassword(password); - setEnabled((accountEnable.compare("true") == 0) ? true : false); - - std::string displayName; - find_in_map(DISPLAY_NAME, displayName) - setDisplayName(displayName); - - find_in_map(USERAGENT, ua_name) - setUseragent(ua_name); +void IAXAccount::setAccountDetails (const std::map<std::string, std::string>& details) { + std::map<std::string, std::string> map_cpy; + std::map<std::string, std::string>::iterator iter; + + _debug ("IaxAccount: Set account details: %s", _accountID.c_str()); + + // Work on a copy + map_cpy = details; + + std::string alias; + std::string type; + std::string hostname; + std::string username; + std::string password; + std::string mailbox; + std::string accountEnable; + + std::string ua_name; + + // Account setting common to SIP and IAX + find_in_map (CONFIG_ACCOUNT_ALIAS, alias) + find_in_map (CONFIG_ACCOUNT_TYPE, type) + find_in_map (HOSTNAME, hostname) + find_in_map (USERNAME, username) + find_in_map (PASSWORD, password) + find_in_map (CONFIG_ACCOUNT_MAILBOX, mailbox); + find_in_map (CONFIG_ACCOUNT_ENABLE, accountEnable); + + setAlias (alias); + setType (type); + setUsername (username); + setHostname (hostname); + setPassword (password); + setEnabled ( (accountEnable.compare ("true") == 0) ? true : false); + + std::string displayName; + find_in_map (DISPLAY_NAME, displayName) + setDisplayName (displayName); + + find_in_map (USERAGENT, ua_name) + setUseragent (ua_name); } -std::map<std::string, std::string> IAXAccount::getAccountDetails() -{ - std::map<std::string, std::string> a; +std::map<std::string, std::string> IAXAccount::getAccountDetails() { + std::map<std::string, std::string> a; - _debug("IaxAccount: get account details %s", _accountID.c_str()); + _debug ("IaxAccount: get account details %s", _accountID.c_str()); - a.insert(std::pair<std::string, std::string>(ACCOUNT_ID, _accountID)); - a.insert(std::pair<std::string, std::string>(CONFIG_ACCOUNT_ALIAS, getAlias())); - a.insert(std::pair<std::string, std::string>(CONFIG_ACCOUNT_ENABLE, isEnabled() ? "true" : "false")); - a.insert(std::pair<std::string, std::string>(CONFIG_ACCOUNT_TYPE, getType())); - a.insert(std::pair<std::string, std::string>(HOSTNAME, getHostname())); - a.insert(std::pair<std::string, std::string>(USERNAME, getUsername())); - a.insert(std::pair<std::string, std::string>(PASSWORD, getPassword())); + a.insert (std::pair<std::string, std::string> (ACCOUNT_ID, _accountID)); + a.insert (std::pair<std::string, std::string> (CONFIG_ACCOUNT_ALIAS, getAlias())); + a.insert (std::pair<std::string, std::string> (CONFIG_ACCOUNT_ENABLE, isEnabled() ? "true" : "false")); + a.insert (std::pair<std::string, std::string> (CONFIG_ACCOUNT_TYPE, getType())); + a.insert (std::pair<std::string, std::string> (HOSTNAME, getHostname())); + a.insert (std::pair<std::string, std::string> (USERNAME, getUsername())); + a.insert (std::pair<std::string, std::string> (PASSWORD, getPassword())); - RegistrationState state = Unregistered; - std::string registrationStateCode; - std::string registrationStateDescription; + RegistrationState state = Unregistered; + std::string registrationStateCode; + std::string registrationStateDescription; - state = getRegistrationState(); - int code = getRegistrationStateDetailed().first; - std::stringstream out; out << code; - registrationStateCode = out.str(); - registrationStateDescription = getRegistrationStateDetailed().second; + state = getRegistrationState(); + int code = getRegistrationStateDetailed().first; + std::stringstream out; + out << code; + registrationStateCode = out.str(); + registrationStateDescription = getRegistrationStateDetailed().second; - a.insert(std::pair<std::string, std::string>(REGISTRATION_STATUS, Manager::instance().mapStateNumberToString(state))); - a.insert(std::pair<std::string, std::string>(REGISTRATION_STATE_CODE, registrationStateCode)); - a.insert(std::pair<std::string, std::string>(REGISTRATION_STATE_DESCRIPTION, registrationStateDescription)); - a.insert(std::pair<std::string, std::string>(USERAGENT, getUseragent())); + a.insert (std::pair<std::string, std::string> (REGISTRATION_STATUS, Manager::instance().mapStateNumberToString (state))); + a.insert (std::pair<std::string, std::string> (REGISTRATION_STATE_CODE, registrationStateCode)); + a.insert (std::pair<std::string, std::string> (REGISTRATION_STATE_DESCRIPTION, registrationStateDescription)); + a.insert (std::pair<std::string, std::string> (USERAGENT, getUseragent())); - return a; + return a; } -void IAXAccount::setVoIPLink() -{ +void IAXAccount::setVoIPLink() { } -int IAXAccount::registerVoIPLink() -{ +int IAXAccount::registerVoIPLink() { _link->init(); // Stuff needed for IAX registration @@ -212,8 +248,7 @@ int IAXAccount::registerVoIPLink() } int -IAXAccount::unregisterVoIPLink() -{ +IAXAccount::unregisterVoIPLink() { _link->sendUnregister (_accountID); _link->terminate(); @@ -221,8 +256,7 @@ IAXAccount::unregisterVoIPLink() } void -IAXAccount::loadConfig() -{ +IAXAccount::loadConfig() { // Account generic Account::loadConfig(); } diff --git a/sflphone-common/src/iax/iaxcall.cpp b/sflphone-common/src/iax/iaxcall.cpp index 7964df857fdf82434c65277334068f0b97d34bf1..1f7e0f54f876783bcf035c73486c31d739966a3a 100644 --- a/sflphone-common/src/iax/iaxcall.cpp +++ b/sflphone-common/src/iax/iaxcall.cpp @@ -33,178 +33,172 @@ #include "manager.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() -{ - _session = NULL; // just to be sure to don't have unknown pointer, do not delete it! +IAXCall::~IAXCall() { + _session = NULL; // just to be sure to don't have unknown pointer, do not delete it! } - void -IAXCall::setFormat (int format) -{ - _format = format; - - _info ("IAX set supported format: "); - - switch (format) { - - case AST_FORMAT_ULAW: - _info("PCMU"); - setAudioCodec (PAYLOAD_CODEC_ULAW); - break; - - case AST_FORMAT_GSM: - _info ("GSM"); - setAudioCodec (PAYLOAD_CODEC_GSM); - break; - - case AST_FORMAT_ALAW: - _info ("ALAW"); - setAudioCodec (PAYLOAD_CODEC_ALAW); - break; - - case AST_FORMAT_ILBC: - _info ("ILBC"); - setAudioCodec (PAYLOAD_CODEC_ILBC_20); - break; - - case AST_FORMAT_SPEEX: - _info ("SPEEX"); - setAudioCodec (PAYLOAD_CODEC_SPEEX_8000); - break; - - default: - _info ("Error audio codec type %i not supported!", format); - setAudioCodec ( (AudioCodecType) -1); - break; - } +void +IAXCall::setFormat (int format) { + _format = format; + + _info ("IAX set supported format: "); + + switch (format) { + + case AST_FORMAT_ULAW: + _info ("PCMU"); + setAudioCodec (PAYLOAD_CODEC_ULAW); + break; + + case AST_FORMAT_GSM: + _info ("GSM"); + setAudioCodec (PAYLOAD_CODEC_GSM); + break; + + case AST_FORMAT_ALAW: + _info ("ALAW"); + setAudioCodec (PAYLOAD_CODEC_ALAW); + break; + + case AST_FORMAT_ILBC: + _info ("ILBC"); + setAudioCodec (PAYLOAD_CODEC_ILBC_20); + break; + + case AST_FORMAT_SPEEX: + _info ("SPEEX"); + setAudioCodec (PAYLOAD_CODEC_SPEEX_8000); + break; + + default: + _info ("Error audio codec type %i not supported!", format); + setAudioCodec ( (AudioCodecType) -1); + break; + } } - int -IAXCall::getSupportedFormat (std::string accountID) -{ - CodecOrder map; - int format = 0; - unsigned int iter; - Account *account; +int +IAXCall::getSupportedFormat (std::string accountID) { + CodecOrder map; + int format = 0; + unsigned int iter; + Account *account; - _info ("IAX get supported format: "); + _info ("IAX get supported format: "); - account = Manager::instance().getAccount (accountID); - if (account != NULL) { - map = account->getActiveCodecs(); - } - else { - _error ("No IAx account could be found"); - } + account = Manager::instance().getAccount (accountID); - for (iter=0 ; iter < map.size() ; iter++) { - switch (map[iter]) { + if (account != NULL) { + map = account->getActiveCodecs(); + } else { + _error ("No IAx account could be found"); + } - case PAYLOAD_CODEC_ULAW: - _info ("PCMU "); - format |= AST_FORMAT_ULAW; - break; + for (iter=0 ; iter < map.size() ; iter++) { + switch (map[iter]) { - case PAYLOAD_CODEC_GSM: - _info ("GSM "); - format |= AST_FORMAT_GSM; - break; + case PAYLOAD_CODEC_ULAW: + _info ("PCMU "); + format |= AST_FORMAT_ULAW; + break; - case PAYLOAD_CODEC_ALAW: - _info ("PCMA "); - format |= AST_FORMAT_ALAW; - break; + case PAYLOAD_CODEC_GSM: + _info ("GSM "); + format |= AST_FORMAT_GSM; + break; - case PAYLOAD_CODEC_ILBC_20: - _info ("ILBC "); - format |= AST_FORMAT_ILBC; - break; + case PAYLOAD_CODEC_ALAW: + _info ("PCMA "); + format |= AST_FORMAT_ALAW; + break; - case PAYLOAD_CODEC_SPEEX_8000: - _info ("SPEEX "); - format |= AST_FORMAT_SPEEX; - break; + case PAYLOAD_CODEC_ILBC_20: + _info ("ILBC "); + format |= AST_FORMAT_ILBC; + break; - default: - break; - } - } + case PAYLOAD_CODEC_SPEEX_8000: + _info ("SPEEX "); + format |= AST_FORMAT_SPEEX; + break; - return format; + default: + break; + } + } + + return format; } int IAXCall::getFirstMatchingFormat (int needles, std::string accountID) { - Account *account; - CodecOrder map; - int format = 0; - unsigned int iter; + Account *account; + CodecOrder map; + int format = 0; + unsigned int iter; + + _debug ("IAX get first matching codec: "); - _debug ("IAX get first matching codec: "); + account = Manager::instance().getAccount (accountID); - account = Manager::instance().getAccount (accountID); - if (account != NULL) { - map = account->getActiveCodecs(); - } - else { - _error ("No IAx account could be found"); - } + if (account != NULL) { + map = account->getActiveCodecs(); + } else { + _error ("No IAx account could be found"); + } - for (iter=0 ; iter < map.size() ; iter++) { - switch (map[iter]) { + for (iter=0 ; iter < map.size() ; iter++) { + switch (map[iter]) { - case PAYLOAD_CODEC_ULAW: - _debug ("PCMU"); - format = AST_FORMAT_ULAW; - break; + case PAYLOAD_CODEC_ULAW: + _debug ("PCMU"); + format = AST_FORMAT_ULAW; + break; - case PAYLOAD_CODEC_GSM: - _debug ("GSM"); - format = AST_FORMAT_GSM; - break; + case PAYLOAD_CODEC_GSM: + _debug ("GSM"); + format = AST_FORMAT_GSM; + break; - case PAYLOAD_CODEC_ALAW: - _debug ("PCMA"); - format = AST_FORMAT_ALAW; - break; + case PAYLOAD_CODEC_ALAW: + _debug ("PCMA"); + format = AST_FORMAT_ALAW; + break; - case PAYLOAD_CODEC_ILBC_20: - _debug ("ILBC"); - format = AST_FORMAT_ILBC; - break; + case PAYLOAD_CODEC_ILBC_20: + _debug ("ILBC"); + format = AST_FORMAT_ILBC; + break; - case PAYLOAD_CODEC_SPEEX_8000: - _debug ("SPEEX"); - format = AST_FORMAT_SPEEX; - break; + case PAYLOAD_CODEC_SPEEX_8000: + _debug ("SPEEX"); + format = AST_FORMAT_SPEEX; + break; - default: - 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; +CodecDescriptor& IAXCall::getCodecMap() { + return _codecMap; } -AudioCodecType IAXCall::getAudioCodec() -{ - return _audioCodec; +AudioCodecType IAXCall::getAudioCodec() { + return _audioCodec; } diff --git a/sflphone-common/src/iax/iaxvoiplink.cpp b/sflphone-common/src/iax/iaxvoiplink.cpp index 415bda1f6eb01bdeafeb5a5a6a925ca2c51b1baa..91c9dbb7e87c6c489c02a7636c9150a508be75e8 100644 --- a/sflphone-common/src/iax/iaxvoiplink.cpp +++ b/sflphone-common/src/iax/iaxvoiplink.cpp @@ -52,8 +52,7 @@ return false; } IAXVoIPLink::IAXVoIPLink (const AccountID& accountID) - : VoIPLink (accountID) -{ + : VoIPLink (accountID) { // _debug("IAXVoIPLink::IAXVoIPLink : creating eventhread "); _evThread = new EventThread (this); _regSession = NULL; @@ -80,8 +79,7 @@ IAXVoIPLink::IAXVoIPLink (const AccountID& accountID) } -IAXVoIPLink::~IAXVoIPLink() -{ +IAXVoIPLink::~IAXVoIPLink() { delete _evThread; _evThread = NULL; _regSession = NULL; // shall not delete it @@ -105,8 +103,7 @@ IAXVoIPLink::~IAXVoIPLink() } bool -IAXVoIPLink::init() -{ +IAXVoIPLink::init() { // If it was done, don't do it again, until we call terminate() if (initDone()) return false; @@ -161,8 +158,7 @@ IAXVoIPLink::init() } void -IAXVoIPLink::terminate() -{ +IAXVoIPLink::terminate() { // If it was done, don't do it again, until we call init() if (!initDone()) return; @@ -176,8 +172,7 @@ IAXVoIPLink::terminate() } void -IAXVoIPLink::terminateIAXCall() -{ +IAXVoIPLink::terminateIAXCall() { std::string reason = "Dumped Call"; ost::MutexLock m (_callMapMutex); CallMap::iterator iter = _callMap.begin(); @@ -201,8 +196,7 @@ IAXVoIPLink::terminateIAXCall() _callMap.clear(); } -void IAXVoIPLink::terminateOneCall (const CallID& id) -{ +void IAXVoIPLink::terminateOneCall (const CallID& id) { IAXCall* call = getIAXCall (id); if (call) { @@ -215,8 +209,7 @@ void IAXVoIPLink::terminateOneCall (const CallID& id) void -IAXVoIPLink::getEvent() -{ +IAXVoIPLink::getEvent() { IAXCall* call = NULL; // lock iax_ stuff.. @@ -291,8 +284,7 @@ IAXVoIPLink::getEvent() } void -IAXVoIPLink::sendAudioFromMic (void) -{ +IAXVoIPLink::sendAudioFromMic (void) { int maxBytesToGet, availBytesFromMic, bytesAvail, compSize; AudioCodec *ac; @@ -395,8 +387,7 @@ IAXVoIPLink::sendAudioFromMic (void) IAXCall* -IAXVoIPLink::getIAXCall (const CallID& id) -{ +IAXVoIPLink::getIAXCall (const CallID& id) { Call* call = getCall (id); if (call) { @@ -408,23 +399,22 @@ IAXVoIPLink::getIAXCall (const CallID& id) int -IAXVoIPLink::sendRegister (AccountID id) -{ +IAXVoIPLink::sendRegister (AccountID id) { IAXAccount *account; bool result; - _debug("IAX: Sending registration"); + _debug ("IAX: Sending registration"); result = false; account = dynamic_cast<IAXAccount *> (getAccountPtr()); if (account->getHostname().empty()) { - _error("IAX: Error: Account hostname is empty"); + _error ("IAX: Error: Account hostname is empty"); return false; } if (account->getUsername().empty()) { - _error("IAX: Error: Account username is empty"); + _error ("IAX: Error: Account username is empty"); return false; } @@ -459,8 +449,7 @@ IAXVoIPLink::sendRegister (AccountID id) } int -IAXVoIPLink::sendUnregister (AccountID id) -{ +IAXVoIPLink::sendUnregister (AccountID id) { IAXAccount *account; account = dynamic_cast<IAXAccount*> (getAccountPtr()); @@ -488,8 +477,7 @@ IAXVoIPLink::sendUnregister (AccountID id) } Call* -IAXVoIPLink::newOutgoingCall (const CallID& id, const std::string& toUrl) -{ +IAXVoIPLink::newOutgoingCall (const CallID& id, const std::string& toUrl) { IAXCall* call = new IAXCall (id, Call::Outgoing); call->setCodecMap (Manager::instance().getCodecDescriptorMap()); @@ -512,8 +500,7 @@ IAXVoIPLink::newOutgoingCall (const CallID& id, const std::string& toUrl) bool -IAXVoIPLink::answer (const CallID& id) -{ +IAXVoIPLink::answer (const CallID& id) { IAXCall* call = getIAXCall (id); call->setCodecMap (Manager::instance().getCodecDescriptorMap()); @@ -535,8 +522,7 @@ IAXVoIPLink::answer (const CallID& id) } bool -IAXVoIPLink::hangup (const CallID& id) -{ +IAXVoIPLink::hangup (const CallID& id) { _debug ("IAXVoIPLink::hangup() : function called once hangup "); IAXCall* call = getIAXCall (id); std::string reason = "Dumped Call"; @@ -563,8 +549,7 @@ IAXVoIPLink::hangup (const CallID& id) bool -IAXVoIPLink::peerHungup (const CallID& id) -{ +IAXVoIPLink::peerHungup (const CallID& id) { _debug ("IAXVoIPLink::peerHangup() : function called once hangup "); IAXCall* call = getIAXCall (id); std::string reason = "Dumped Call"; @@ -591,8 +576,7 @@ IAXVoIPLink::peerHungup (const CallID& id) bool -IAXVoIPLink::onhold (const CallID& id) -{ +IAXVoIPLink::onhold (const CallID& id) { IAXCall* call = getIAXCall (id); CHK_VALID_CALL; @@ -610,8 +594,7 @@ IAXVoIPLink::onhold (const CallID& id) } bool -IAXVoIPLink::offhold (const CallID& id) -{ +IAXVoIPLink::offhold (const CallID& id) { IAXCall* call = getIAXCall (id); CHK_VALID_CALL; @@ -628,8 +611,7 @@ IAXVoIPLink::offhold (const CallID& id) } bool -IAXVoIPLink::transfer (const CallID& id, const std::string& to) -{ +IAXVoIPLink::transfer (const CallID& id, const std::string& to) { IAXCall* call = getIAXCall (id); CHK_VALID_CALL; @@ -648,8 +630,7 @@ IAXVoIPLink::transfer (const CallID& id, const std::string& to) } bool -IAXVoIPLink::refuse (const CallID& id) -{ +IAXVoIPLink::refuse (const CallID& id) { IAXCall* call = getIAXCall (id); std::string reason = "Call rejected manually."; @@ -668,8 +649,7 @@ IAXVoIPLink::refuse (const CallID& id) bool -IAXVoIPLink::carryingDTMFdigits (const CallID& id, char code) -{ +IAXVoIPLink::carryingDTMFdigits (const CallID& id, char code) { IAXCall* call = getIAXCall (id); CHK_VALID_CALL; @@ -683,8 +663,7 @@ IAXVoIPLink::carryingDTMFdigits (const CallID& id, char code) std::string -IAXVoIPLink::getCurrentCodecName() -{ +IAXVoIPLink::getCurrentCodecName() { IAXCall *call = NULL; AudioCodec *ac = NULL; std::string name = ""; @@ -702,8 +681,7 @@ IAXVoIPLink::getCurrentCodecName() bool -IAXVoIPLink::iaxOutgoingInvite (IAXCall* call) -{ +IAXVoIPLink::iaxOutgoingInvite (IAXCall* call) { struct iax_session *newsession; ost::MutexLock m (_mutexIAX); @@ -738,8 +716,7 @@ IAXVoIPLink::iaxOutgoingInvite (IAXCall* call) IAXCall* -IAXVoIPLink::iaxFindCallBySession (struct iax_session* session) -{ +IAXVoIPLink::iaxFindCallBySession (struct iax_session* session) { // access to callMap shoud use that // the code below is like findSIPCallWithCid() ost::MutexLock m (_callMapMutex); @@ -760,8 +737,7 @@ IAXVoIPLink::iaxFindCallBySession (struct iax_session* session) } void -IAXVoIPLink::iaxHandleCallEvent (iax_event* event, IAXCall* call) -{ +IAXVoIPLink::iaxHandleCallEvent (iax_event* event, IAXCall* call) { // call should not be 0 // note activity? // @@ -909,8 +885,7 @@ IAXVoIPLink::iaxHandleCallEvent (iax_event* event, IAXCall* call) /* Handle audio event, VOICE packet received */ void -IAXVoIPLink::iaxHandleVoiceEvent (iax_event* event, IAXCall* call) -{ +IAXVoIPLink::iaxHandleVoiceEvent (iax_event* event, IAXCall* call) { unsigned char *data; unsigned int size, max, nbInt16; @@ -1002,8 +977,7 @@ IAXVoIPLink::iaxHandleVoiceEvent (iax_event* event, IAXCall* call) * Handle the registration process */ void -IAXVoIPLink::iaxHandleRegReply (iax_event* event) -{ +IAXVoIPLink::iaxHandleRegReply (iax_event* event) { std::string account_id; IAXAccount *account; @@ -1044,8 +1018,7 @@ IAXVoIPLink::iaxHandleRegReply (iax_event* event) } } -int IAXVoIPLink::processIAXMsgCount (int msgcount) -{ +int IAXVoIPLink::processIAXMsgCount (int msgcount) { // IAX sends the message count under a specific format: // 1 @@ -1067,8 +1040,7 @@ int IAXVoIPLink::processIAXMsgCount (int msgcount) void -IAXVoIPLink::iaxHandlePrecallEvent (iax_event* event) -{ +IAXVoIPLink::iaxHandlePrecallEvent (iax_event* event) { IAXCall* call = NULL; CallID id; std::string reason = "Error ringing user."; @@ -1175,8 +1147,7 @@ IAXVoIPLink::iaxHandlePrecallEvent (iax_event* event) } -void IAXVoIPLink::updateAudiolayer (void) -{ +void IAXVoIPLink::updateAudiolayer (void) { _mutexIAX.enterMutex(); audiolayer = NULL; audiolayer = Manager::instance().getAudioDriver(); diff --git a/sflphone-common/src/logger.cpp b/sflphone-common/src/logger.cpp index 9269553817df1e55b73465fba9445a6cb1b64fd3..54437fe8b25f199831e09d0af24610623ee64ab3 100644 --- a/sflphone-common/src/logger.cpp +++ b/sflphone-common/src/logger.cpp @@ -35,75 +35,65 @@ using namespace std; -namespace Logger -{ +namespace Logger { bool consoleLog = false; bool debugMode = false; -void log(const int level, const char* format, ...) -{ - if(!debugMode && level == LOG_DEBUG) - return; +void log (const int level, const char* format, ...) { + if (!debugMode && level == LOG_DEBUG) + return; - va_list ap; - string prefix = "<> "; - char buffer[4096]; - string message = ""; - string color_prefix = ""; + va_list ap; + string prefix = "<> "; + char buffer[4096]; + string message = ""; + string color_prefix = ""; - switch(level) - { - case LOG_ERR: - { - prefix = "<error> "; - color_prefix = RED; - break; - } - case LOG_WARNING: - { - prefix = "<warning> "; - color_prefix = LIGHT_RED; - break; - } - case LOG_INFO: - { - prefix = "<info> "; - color_prefix = ""; - break; - } - case LOG_DEBUG: - { - prefix = "<debug> "; - color_prefix = ""; - break; - } - } - - va_start(ap, format); - vsprintf(buffer, format, ap); - va_end(ap); + switch (level) { + case LOG_ERR: { + prefix = "<error> "; + color_prefix = RED; + break; + } + case LOG_WARNING: { + prefix = "<warning> "; + color_prefix = LIGHT_RED; + break; + } + case LOG_INFO: { + prefix = "<info> "; + color_prefix = ""; + break; + } + case LOG_DEBUG: { + prefix = "<debug> "; + color_prefix = ""; + break; + } + } - message = buffer; - message = prefix + message; + va_start (ap, format); + vsprintf (buffer, format, ap); + va_end (ap); - syslog(level, message.c_str()); + message = buffer; + message = prefix + message; - if(consoleLog) - { - message = color_prefix + message + END_COLOR + "\n"; - fprintf(stderr, message.c_str()); - } + syslog (level, message.c_str()); + + if (consoleLog) { + message = color_prefix + message + END_COLOR + "\n"; + fprintf (stderr, message.c_str()); + } } -void setConsoleLog(bool c) -{ - Logger::consoleLog = c; +void setConsoleLog (bool c) { + Logger::consoleLog = c; } -void setDebugMode(bool d) -{ - Logger::debugMode = d; +void setDebugMode (bool d) { + Logger::debugMode = d; } } diff --git a/sflphone-common/src/main.cpp b/sflphone-common/src/main.cpp index aca2e1f1547ccfcf0770eddbd476ccf90b87253b..b7fd7ebdc146db7beaab4ce11a2633eb2fde1424 100644 --- a/sflphone-common/src/main.cpp +++ b/sflphone-common/src/main.cpp @@ -48,170 +48,167 @@ using namespace std; using namespace ost; -CommandOptionArg level( - "log-level", "l", "Log level (not yet implemented)" +CommandOptionArg level ( + "log-level", "l", "Log level (not yet implemented)" ); -CommandOptionNoArg console( - "console", "c", "Log in console (instead of syslog)" +CommandOptionNoArg console ( + "console", "c", "Log in console (instead of syslog)" ); -CommandOptionNoArg debug( - "debug", "d", "Debug mode (more verbose)" +CommandOptionNoArg debug ( + "debug", "d", "Debug mode (more verbose)" ); -CommandOptionNoArg help( - "help", "h", "Print help" +CommandOptionNoArg help ( + "help", "h", "Print help" ); int -main (int argc, char **argv) -{ - int exit_code = 0; +main (int argc, char **argv) { + int exit_code = 0; - Logger::setConsoleLog(false); - Logger::setDebugMode(false); + Logger::setConsoleLog (false); + Logger::setDebugMode (false); - CommandOptionParse * args = makeCommandOptionParse(argc, argv, ""); + CommandOptionParse * args = makeCommandOptionParse (argc, argv, ""); - printf ("SFLphone Daemon %s, by Savoir-Faire Linux 2004-2009\n", VERSION); - printf ("http://www.sflphone.org/\n"); + printf ("SFLphone Daemon %s, by Savoir-Faire Linux 2004-2009\n", VERSION); + printf ("http://www.sflphone.org/\n"); - if ( help.numSet ) { - cerr << args->printUsage(); - ::exit(0); - } + if (help.numSet) { + cerr << args->printUsage(); + ::exit (0); + } - if ( args->argsHaveError() ) { - cerr << args->printErrors(); - cerr << args->printUsage(); - ::exit(1); - } + if (args->argsHaveError()) { + cerr << args->printErrors(); + cerr << args->printUsage(); + ::exit (1); + } - if( console.numSet ) - { - _info("Console logging activated"); - Logger::setConsoleLog(true); - } + if (console.numSet) { + _info ("Console logging activated"); + Logger::setConsoleLog (true); + } - if( debug.numSet ) - { - _info("Debug mode activated"); - Logger::setDebugMode(true); - } + if (debug.numSet) { + _info ("Debug mode activated"); + Logger::setDebugMode (true); + } - delete args; + delete args; - FILE *fp; - char homepid[128]; - char sfldir[128]; + FILE *fp; + char homepid[128]; + char sfldir[128]; - unsigned int iPid = getpid(); - char cPid[64], cOldPid[64]; - sprintf (cPid,"%d", iPid); - std::string xdg_cache, xdg_env, path; + unsigned int iPid = getpid(); + char cPid[64], cOldPid[64]; + sprintf (cPid,"%d", iPid); + std::string xdg_cache, xdg_env, path; - xdg_cache = std::string (HOMEDIR) + DIR_SEPARATOR_STR + ".cache/"; + xdg_cache = std::string (HOMEDIR) + DIR_SEPARATOR_STR + ".cache/"; - if (XDG_CACHE_HOME != NULL) { - xdg_env = std::string (XDG_CACHE_HOME); - (xdg_env.length() > 0) ? path = xdg_env - : path = xdg_cache; - } else - path = xdg_cache; + if (XDG_CACHE_HOME != NULL) { + xdg_env = std::string (XDG_CACHE_HOME); + (xdg_env.length() > 0) ? path = xdg_env + : path = xdg_cache; + } else + path = xdg_cache; - sprintf (sfldir, "%s", path.c_str ()); + sprintf (sfldir, "%s", path.c_str ()); - path = path + "sflphone"; + path = path + "sflphone"; - sprintf (homepid, "%s/%s", path.c_str (), PIDFILE); + sprintf (homepid, "%s/%s", path.c_str (), PIDFILE); - if ( (fp = fopen (homepid,"r")) == NULL) { - // Check if $XDG_CACHE_HOME directory exists or not. - DIR *dir; + if ( (fp = fopen (homepid,"r")) == NULL) { + // Check if $XDG_CACHE_HOME 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.", sfldir); - exit (-1); - } + if ( (dir = opendir (sfldir)) == NULL) { + //Create it + if (mkdir (sfldir, 0755) != 0) { + fprintf (stderr, "Creating directory %s failed. Exited.", sfldir); + exit (-1); } + } - // Then create the sflphone directory inside the $XDG_CACHE_HOME dir - sprintf (sfldir, "%s", path.c_str ()); - - if ( (dir = opendir (sfldir)) == NULL) { - //Create it - if (mkdir (sfldir, 0755) != 0) { - fprintf (stderr, "Creating directory %s failed. Exited.", sfldir); - exit (-1); - } - } + // Then create the sflphone directory inside the $XDG_CACHE_HOME dir + sprintf (sfldir, "%s", path.c_str ()); - // 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.", homepid); + if ( (dir = opendir (sfldir)) == NULL) { + //Create it + if (mkdir (sfldir, 0755) != 0) { + fprintf (stderr, "Creating directory %s failed. Exited.", sfldir); exit (-1); - } else { - fputs (cPid , fp); - fclose (fp); } + } + + // 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.", homepid); + exit (-1); } else { - // PID file exists. Check the former process still alive or not. If alive, give user a hint. - char *res; - res = fgets (cOldPid, 64, fp); + fputs (cPid , fp); + fclose (fp); + } + } else { + // PID file exists. Check the former process still alive or not. If alive, give user a hint. + char *res; + res = fgets (cOldPid, 64, fp); - if (res == NULL) perror ("Error getting string from stream"); + if (res == NULL) perror ("Error getting string from stream"); - else { - fclose (fp); + else { + fclose (fp); - if (kill (atoi (cOldPid), 0) == SUCCESS) { - fprintf (stderr, "There is already a sflphoned daemon running in the system. Starting Failed."); + if (kill (atoi (cOldPid), 0) == SUCCESS) { + fprintf (stderr, "There is already a sflphoned daemon running in the system. Starting Failed."); + exit (-1); + } else { + if ( (fp = fopen (homepid,"w")) == NULL) { + fprintf (stderr, "Writing to PID file %s failed. Exited.", homepid); exit (-1); } else { - if ( (fp = fopen (homepid,"w")) == NULL) { - fprintf (stderr, "Writing to PID file %s failed. Exited.", homepid); - exit (-1); - } else { - fputs (cPid , fp); - fclose (fp); - } - + 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 { - // TODO Use $XDG_CONFIG_HOME to save the config file (which default to $HOME/.config) - 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."); - exit_code = -1; - } + int sessionPort = 0; + + if (argc == 2) { + char* ptrPort = strstr (argv[1], "--port="); - if (initOK) { - Manager::instance().setDBusManager (&DBusManager::instance()); - exit_code = DBusManager::instance().exec(); // UI Loop + if (ptrPort != 0) { + sessionPort = atoi (ptrPort+7); } + } + + bool initOK = false; + + try { + // TODO Use $XDG_CONFIG_HOME to save the config file (which default to $HOME/.config) + 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."); + exit_code = -1; + } + + if (initOK) { + Manager::instance().setDBusManager (&DBusManager::instance()); + exit_code = DBusManager::instance().exec(); // UI Loop + } return exit_code; } diff --git a/sflphone-common/src/managerimpl.cpp b/sflphone-common/src/managerimpl.cpp old mode 100755 new mode 100644 index 8652d731c291214d45b0ba62d9ee5b837b22b2e4..00bb176297422e3da1f30ab47a67e46d4ae0219b --- a/sflphone-common/src/managerimpl.cpp +++ b/sflphone-common/src/managerimpl.cpp @@ -73,131 +73,136 @@ #define MD5_APPEND(pms,buf,len) pj_md5_update(pms, (const pj_uint8_t*)buf, len) // Default account used to get default parametersa if requested by client (to build ne account) -SIPAccount defaultAccount("default"); +SIPAccount defaultAccount ("default"); ManagerImpl::ManagerImpl (void) : - _hasTriedToRegister(false), _config(), _currentCallId2(), - _currentCallMutex(), _codecBuilder(NULL), _audiodriver(NULL), - _dtmfKey(NULL), _codecDescriptorMap(), _toneMutex(), - _telephoneTone(NULL), _audiofile(), _spkr_volume(0), - _mic_volume(0), _mutex(), _dbus(NULL), _waitingCall(), - _waitingCallMutex(), _nbIncomingWaitingCall(0), _path(""), - _exist(0), _setupLoaded(false), _callAccountMap(), - _callAccountMapMutex(), _callConfigMap(), _accountMap(), - _directIpAccount(NULL), _cleaner(NULL), _history(NULL) { - - // initialize random generator for call id - srand(time(NULL)); - - _cleaner = new NumberCleaner(); - _history = new HistoryManager(); + _hasTriedToRegister (false), _config(), _currentCallId2(), + _currentCallMutex(), _codecBuilder (NULL), _audiodriver (NULL), + _dtmfKey (NULL), _codecDescriptorMap(), _toneMutex(), + _telephoneTone (NULL), _audiofile(), _spkr_volume (0), + _mic_volume (0), _mutex(), _dbus (NULL), _waitingCall(), + _waitingCallMutex(), _nbIncomingWaitingCall (0), _path (""), + _exist (0), _setupLoaded (false), _callAccountMap(), + _callAccountMapMutex(), _callConfigMap(), _accountMap(), + _directIpAccount (NULL), _cleaner (NULL), _history (NULL) { + + // initialize random generator for call id + 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 = NULL; - delete _history; _history = NULL; + // terminate(); + delete _cleaner; + _cleaner = NULL; + delete _history; + _history = NULL; - _debug ("Manager: %s stop correctly.", PROGNAME); + _debug ("Manager: %s stop correctly.", PROGNAME); } void ManagerImpl::init () { - _debug("Manager: Init"); + _debug ("Manager: Init"); - // Load accounts, init map - buildConfiguration(); + // Load accounts, init map + buildConfiguration(); - _debug("Manager: account map loaded"); + _debug ("Manager: account map loaded"); - initVolume(); + initVolume(); - if (_exist == 0) { - _warn ("Manager: Cannot create config file in your home directory"); - } + if (_exist == 0) { + _warn ("Manager: Cannot create config file in your home directory"); + } - initAudioDriver(); + initAudioDriver(); - selectAudioDriver(); + selectAudioDriver(); - // Initialize the list of supported audio codecs - initAudioCodec(); + // Initialize the list of supported audio codecs + initAudioCodec(); - AudioLayer *audiolayer = getAudioDriver(); + AudioLayer *audiolayer = getAudioDriver(); - if (audiolayer) { - unsigned int sampleRate = audiolayer->getSampleRate(); + if (audiolayer) { + unsigned int sampleRate = audiolayer->getSampleRate(); - _debugInit ("Manager: Load telephone tone"); - std::string country = preferences.getZoneToneChoice(); - _telephoneTone = new TelephoneTone(country, sampleRate); + _debugInit ("Manager: Load telephone tone"); + std::string country = preferences.getZoneToneChoice(); + _telephoneTone = new TelephoneTone (country, sampleRate); - _debugInit ("Manager: Loading DTMF key"); - _dtmfKey = new DTMF(sampleRate); - } + _debugInit ("Manager: Loading DTMF key"); + _dtmfKey = new DTMF (sampleRate); + } - // Load the history - _history->load_history(preferences.getHistoryLimit()); + // Load the history + _history->load_history (preferences.getHistoryLimit()); } void ManagerImpl::terminate () { - _debug ("Manager: Terminate "); - saveConfig(); + _debug ("Manager: Terminate "); + saveConfig(); - unloadAccountMap(); + unloadAccountMap(); - _debug ("Manager: Unload DTMF key"); - delete _dtmfKey; + _debug ("Manager: Unload DTMF key"); + delete _dtmfKey; - _debug("Manager: Unload telephone tone"); - delete _telephoneTone; _telephoneTone = NULL; + _debug ("Manager: Unload telephone tone"); + delete _telephoneTone; + _telephoneTone = NULL; - _debug ("Manager: Unload audio driver"); - delete _audiodriver; _audiodriver = NULL; + _debug ("Manager: Unload audio driver"); + delete _audiodriver; + _audiodriver = NULL; - _debug ("Manager: Unload telephone tone"); - delete _telephoneTone; _telephoneTone = NULL; + _debug ("Manager: Unload telephone tone"); + delete _telephoneTone; + _telephoneTone = NULL; - _debug ("Manager: Unload audio codecs "); - _codecDescriptorMap.deleteHandlePointer(); + _debug ("Manager: Unload audio codecs "); + _codecDescriptorMap.deleteHandlePointer(); } bool ManagerImpl::isCurrentCall (const CallID& callId) { - return (_currentCallId2 == callId ? true : false); + return (_currentCallId2 == callId ? true : false); } bool ManagerImpl::hasCurrentCall () { - // _debug ("ManagerImpl::hasCurrentCall current call ID = %s", _currentCallId2.c_str()); + // _debug ("ManagerImpl::hasCurrentCall current call ID = %s", _currentCallId2.c_str()); - if (_currentCallId2 != "") { - return true; - } + if (_currentCallId2 != "") { + return true; + } - return false; + return false; } const CallID& ManagerImpl::getCurrentCallId () { - return _currentCallId2; + return _currentCallId2; } void ManagerImpl::switchCall (const CallID& id) { - ost::MutexLock m(_currentCallMutex); - _debug ("----- Switch current call id to %s -----", id.c_str()); - _currentCallId2 = id; + ost::MutexLock m (_currentCallMutex); + _debug ("----- Switch current call id to %s -----", id.c_str()); + _currentCallId2 = id; } /////////////////////////////////////////////////////////////////////////////// @@ -206,1373 +211,1373 @@ void ManagerImpl::switchCall (const CallID& id) { /* Main Thread */ bool ManagerImpl::outgoingCall (const std::string& account_id, - const CallID& call_id, const std::string& to) { + const CallID& call_id, const std::string& to) { - std::string pattern, to_cleaned; - Call::CallConfiguration callConfig; - SIPVoIPLink *siplink; + std::string pattern, to_cleaned; + Call::CallConfiguration callConfig; + SIPVoIPLink *siplink; - _debug ("Manager: New outgoing call %s to %s", call_id.c_str(), to.c_str()); + _debug ("Manager: New outgoing call %s to %s", call_id.c_str(), to.c_str()); - CallID current_call_id = getCurrentCallId(); + CallID current_call_id = getCurrentCallId(); + + if (hookPreference.getNumberEnabled()) + _cleaner->set_phone_number_prefix (hookPreference.getNumberAddPrefix()); + else + _cleaner->set_phone_number_prefix (""); - if(hookPreference.getNumberEnabled()) - _cleaner->set_phone_number_prefix(hookPreference.getNumberAddPrefix()); - else - _cleaner->set_phone_number_prefix(""); + to_cleaned = _cleaner->clean (to); - to_cleaned = _cleaner->clean(to); + /* Check what kind of call we are dealing with */ + check_call_configuration (call_id, to_cleaned, &callConfig); - /* Check what kind of call we are dealing with */ - check_call_configuration(call_id, to_cleaned, &callConfig); + // in any cases we have to detach from current communication + if (hasCurrentCall()) { - // in any cases we have to detach from current communication - if (hasCurrentCall()) { + _debug ("Manager: Has current call (%s) put it onhold", current_call_id.c_str()); - _debug ("Manager: Has current call (%s) put it onhold", current_call_id.c_str()); - // if this is not a conferenceand this and is not a conference participant - if (!isConference(current_call_id) && !participToConference(current_call_id)) { - onHoldCall(current_call_id); - } else if (isConference(current_call_id) && !participToConference(call_id)) { - detachParticipant(default_id, current_call_id); - } - } + // if this is not a conferenceand this and is not a conference participant + if (!isConference (current_call_id) && !participToConference (current_call_id)) { + onHoldCall (current_call_id); + } else if (isConference (current_call_id) && !participToConference (call_id)) { + detachParticipant (default_id, current_call_id); + } + } - if (callConfig == Call::IPtoIP) { - _debug ("Manager: Start IP2IP call"); - /* We need to retrieve the sip voiplink instance */ - siplink = SIPVoIPLink::instance(""); + if (callConfig == Call::IPtoIP) { + _debug ("Manager: Start IP2IP call"); + /* We need to retrieve the sip voiplink instance */ + siplink = SIPVoIPLink::instance (""); - if (siplink->new_ip_to_ip_call(call_id, to_cleaned)) { - switchCall(call_id); - return true; - } else { - callFailure(call_id); - } + if (siplink->new_ip_to_ip_call (call_id, to_cleaned)) { + switchCall (call_id); + return true; + } else { + callFailure (call_id); + } - return false; - } + return false; + } - _debug("Manager: Selecting account %s", account_id.c_str()); - if (!accountExists(account_id)) { - _error ("Manager: Error: Account doesn't exist in new outgoing call"); - return false; - } + _debug ("Manager: Selecting account %s", account_id.c_str()); - if (getAccountFromCall(call_id) != AccountNULL) { - _error ("Manager: Error: Call id already exists in outgoing call"); - return false; - } + if (!accountExists (account_id)) { + _error ("Manager: Error: Account doesn't exist in new outgoing call"); + return false; + } - _debug ("Manager: Adding Outgoing Call %s on account %s", call_id.data(), account_id.data()); - associateCallToAccount(call_id, account_id); + if (getAccountFromCall (call_id) != AccountNULL) { + _error ("Manager: Error: Call id already exists in outgoing call"); + return false; + } - if (getAccountLink(account_id)->newOutgoingCall(call_id, to_cleaned)) { - switchCall(call_id); - return true; - } else { - callFailure(call_id); - _debug ("Manager: Error: An error occur, the call was not created"); - } + _debug ("Manager: Adding Outgoing Call %s on account %s", call_id.data(), account_id.data()); + associateCallToAccount (call_id, account_id); - return false; + if (getAccountLink (account_id)->newOutgoingCall (call_id, to_cleaned)) { + switchCall (call_id); + return true; + } else { + callFailure (call_id); + _debug ("Manager: Error: An error occur, the call was not created"); + } + + return false; } //THREAD=Main : for outgoing Call bool ManagerImpl::answerCall (const CallID& call_id) { - _debug ("ManagerImpl: Answer call %s", call_id.c_str()); + _debug ("ManagerImpl: Answer call %s", call_id.c_str()); - stopTone(); + stopTone(); - // store the current call id - CallID current_call_id = getCurrentCallId(); + // store the current call id + CallID current_call_id = getCurrentCallId(); - AccountID account_id = getAccountFromCall(call_id); + AccountID account_id = getAccountFromCall (call_id); - if (account_id == AccountNULL) { - _debug (" answerCall: AccountId is null"); - } + if (account_id == AccountNULL) { + _debug (" answerCall: AccountId is null"); + } - Call* call = NULL; + Call* call = NULL; - call = getAccountLink(account_id)->getCall(call_id); + call = getAccountLink (account_id)->getCall (call_id); - if (call == NULL) { - _debug (" answerCall: Call is null"); - } + if (call == NULL) { + _debug (" answerCall: Call is null"); + } - // in any cases we have to detach from current communication - if (hasCurrentCall()) { + // in any cases we have to detach from current communication + if (hasCurrentCall()) { - _debug (" answerCall: Currently conversing with %s", current_call_id.c_str()); - // if it is not a conference and is not a conference participant + _debug (" answerCall: Currently conversing with %s", current_call_id.c_str()); + // if it is not a conference and is not a conference participant - if (!isConference(current_call_id) && !participToConference( - current_call_id)) { - _debug (" answerCall: Put the current call (%s) on hold", current_call_id.c_str()); - onHoldCall(current_call_id); - } + if (!isConference (current_call_id) && !participToConference ( + current_call_id)) { + _debug (" answerCall: Put the current call (%s) on hold", current_call_id.c_str()); + onHoldCall (current_call_id); + } - // if we are talking to a conference and we are answering an incoming call - else if (isConference(current_call_id) - && !participToConference(call_id)) { - _debug (" answerCall: Detach main participant from conference"); - detachParticipant(default_id, current_call_id); - } + // if we are talking to a conference and we are answering an incoming call + else if (isConference (current_call_id) + && !participToConference (call_id)) { + _debug (" answerCall: Detach main participant from conference"); + detachParticipant (default_id, current_call_id); + } - } + } - if (!getAccountLink(account_id)->answer(call_id)) { - // error when receiving... - removeCallAccount(call_id); - return false; - } + if (!getAccountLink (account_id)->answer (call_id)) { + // error when receiving... + removeCallAccount (call_id); + return false; + } - // if it was waiting, it's waiting no more - if (_dbus) - _dbus->getCallManager()->callStateChanged(call_id, "CURRENT"); + // if it was waiting, it's waiting no more + if (_dbus) + _dbus->getCallManager()->callStateChanged (call_id, "CURRENT"); - // std::string codecName = Manager::instance().getCurrentCodecName (call_id); - // if (_dbus) _dbus->getCallManager()->currentSelectedCodec (call_id, codecName.c_str()); + // std::string codecName = Manager::instance().getCurrentCodecName (call_id); + // if (_dbus) _dbus->getCallManager()->currentSelectedCodec (call_id, codecName.c_str()); - removeWaitingCall(call_id); + removeWaitingCall (call_id); - // if we dragged this call into a conference already - if (participToConference(call_id)) { + // if we dragged this call into a conference already + if (participToConference (call_id)) { - // AccountID currentAccountId; - // Call* call = NULL; + // AccountID currentAccountId; + // Call* call = NULL; - // currentAccountId = getAccountFromCall (call_id); - // call = getAccountLink (currentAccountId)->getCall (call_id); + // currentAccountId = getAccountFromCall (call_id); + // call = getAccountLink (currentAccountId)->getCall (call_id); - switchCall(call->getConfId()); - } else { - switchCall(call_id); - } + switchCall (call->getConfId()); + } else { + switchCall (call_id); + } - return true; + return true; } //THREAD=Main bool ManagerImpl::hangupCall (const CallID& call_id) { - _info("Manager: Hangup call %s", call_id.c_str()); - - PulseLayer *pulselayer; - AccountID account_id; - bool returnValue = true; + _info ("Manager: Hangup call %s", call_id.c_str()); - // store the current call id - CallID current_call_id = getCurrentCallId(); + PulseLayer *pulselayer; + AccountID account_id; + bool returnValue = true; - stopTone(); + // store the current call id + CallID current_call_id = getCurrentCallId(); - /* Broadcast a signal over DBus */ - _debug ("Manager: Send DBUS call state change (HUNGUP) for id %s", call_id.c_str()); + stopTone(); - if (_dbus) - _dbus->getCallManager()->callStateChanged(call_id, "HUNGUP"); + /* Broadcast a signal over DBus */ + _debug ("Manager: Send DBUS call state change (HUNGUP) for id %s", call_id.c_str()); - if (participToConference(call_id)) { + if (_dbus) + _dbus->getCallManager()->callStateChanged (call_id, "HUNGUP"); - Conference *conf = getConferenceFromCallID(call_id); + if (participToConference (call_id)) { - if (conf != NULL) { - // remove this participant - removeParticipant(call_id); + Conference *conf = getConferenceFromCallID (call_id); - processRemainingParticipant(current_call_id, conf); - } + if (conf != NULL) { + // remove this participant + removeParticipant (call_id); - } else { - // we are not participating to a conference, current call switched to "" - if (!isConference(current_call_id)) - switchCall(""); - } + processRemainingParticipant (current_call_id, conf); + } - /* Direct IP to IP call */ - if (getConfigFromCall(call_id) == Call::IPtoIP) { - returnValue = SIPVoIPLink::instance(AccountNULL)->hangup(call_id); - } - /* Classic call, attached to an account */ - else { - account_id = getAccountFromCall(call_id); + } else { + // we are not participating to a conference, current call switched to "" + if (!isConference (current_call_id)) + switchCall (""); + } - // Account may be NULL if call have not been sent yet - if (account_id == AccountNULL) { - _error ("Manager: Error: account id is NULL in hangup"); - returnValue = false; - } else { - returnValue = getAccountLink(account_id)->hangup(call_id); - removeCallAccount(call_id); - } - } + /* Direct IP to IP call */ + if (getConfigFromCall (call_id) == Call::IPtoIP) { + returnValue = SIPVoIPLink::instance (AccountNULL)->hangup (call_id); + } + /* Classic call, attached to an account */ + else { + account_id = getAccountFromCall (call_id); + + // Account may be NULL if call have not been sent yet + if (account_id == AccountNULL) { + _error ("Manager: Error: account id is NULL in hangup"); + returnValue = false; + } else { + returnValue = getAccountLink (account_id)->hangup (call_id); + removeCallAccount (call_id); + } + } - int nbCalls = getCallList().size(); + int nbCalls = getCallList().size(); - AudioLayer *audiolayer = getAudioDriver(); + AudioLayer *audiolayer = getAudioDriver(); - // stop streams - if (audiolayer && (nbCalls <= 0)) { - _debug ("Manager: stop audio stream, ther is only %i call(s) remaining", nbCalls); - audiolayer->stopStream(); - } + // stop streams + if (audiolayer && (nbCalls <= 0)) { + _debug ("Manager: stop audio stream, ther is only %i call(s) remaining", nbCalls); + audiolayer->stopStream(); + } - if (_audiodriver->getLayerType() == PULSEAUDIO) { - pulselayer = dynamic_cast<PulseLayer *> (getAudioDriver()); - } + if (_audiodriver->getLayerType() == PULSEAUDIO) { + pulselayer = dynamic_cast<PulseLayer *> (getAudioDriver()); + } - return returnValue; + return returnValue; } bool ManagerImpl::hangupConference (const ConfID& id) { - _debug ("Manager: Hangup conference %s", id.c_str()); + _debug ("Manager: Hangup conference %s", id.c_str()); - Conference *conf; - ConferenceMap::iterator iter_conf = _conferencemap.find(id); + Conference *conf; + ConferenceMap::iterator iter_conf = _conferencemap.find (id); - AccountID currentAccountId; + AccountID currentAccountId; - // Call* call = NULL; + // Call* call = NULL; - if (iter_conf != _conferencemap.end()) { - conf = iter_conf->second; + if (iter_conf != _conferencemap.end()) { + conf = iter_conf->second; - ParticipantSet participants = conf->getParticipantList(); - ParticipantSet::iterator iter_participant = participants.begin(); + ParticipantSet participants = conf->getParticipantList(); + ParticipantSet::iterator iter_participant = participants.begin(); - while (iter_participant != participants.end()) { - _debug ("Manager: Hangup onference participant %s", (*iter_participant).c_str()); + while (iter_participant != participants.end()) { + _debug ("Manager: Hangup onference participant %s", (*iter_participant).c_str()); - hangupCall(*iter_participant); + hangupCall (*iter_participant); - iter_participant++; + iter_participant++; - } + } - } + } - switchCall(""); + switchCall (""); - return true; + return true; } //THREAD=Main bool ManagerImpl::cancelCall (const CallID& id) { - AccountID accountid; - bool returnValue; + AccountID accountid; + bool returnValue; - _debug("Manager: Cancel call"); + _debug ("Manager: Cancel call"); - stopTone(); + stopTone(); - /* Direct IP to IP call */ + /* Direct IP to IP call */ - if (getConfigFromCall(id) == Call::IPtoIP) { - returnValue = SIPVoIPLink::instance(AccountNULL)->cancel(id); - } + if (getConfigFromCall (id) == Call::IPtoIP) { + returnValue = SIPVoIPLink::instance (AccountNULL)->cancel (id); + } - /* Classic call, attached to an account */ - else { - accountid = getAccountFromCall(id); + /* Classic call, attached to an account */ + else { + accountid = getAccountFromCall (id); - if (accountid == AccountNULL) { - _debug ("! Manager Cancel Call: Call doesn't exists"); - return false; - } + if (accountid == AccountNULL) { + _debug ("! Manager Cancel Call: Call doesn't exists"); + return false; + } - returnValue = getAccountLink(accountid)->cancel(id); + returnValue = getAccountLink (accountid)->cancel (id); - removeCallAccount(id); - } + removeCallAccount (id); + } - // it could be a waiting call? - removeWaitingCall(id); + // it could be a waiting call? + removeWaitingCall (id); - switchCall(""); + switchCall (""); - return returnValue; + return returnValue; } //THREAD=Main bool ManagerImpl::onHoldCall (const CallID& call_id) { - AccountID account_id; - bool returnValue; + AccountID account_id; + bool returnValue; - _debug ("Manager: Put call %s on hold", call_id.c_str()); + _debug ("Manager: Put call %s on hold", call_id.c_str()); - stopTone(); + stopTone(); - CallID current_call_id = getCurrentCallId(); + CallID current_call_id = getCurrentCallId(); - /* Direct IP to IP call */ + /* Direct IP to IP call */ - if (getConfigFromCall(call_id) == Call::IPtoIP) { - returnValue = SIPVoIPLink::instance(AccountNULL)-> onhold(call_id); - } + if (getConfigFromCall (call_id) == Call::IPtoIP) { + returnValue = SIPVoIPLink::instance (AccountNULL)-> onhold (call_id); + } - /* Classic call, attached to an account */ - else { - account_id = getAccountFromCall(call_id); + /* Classic call, attached to an account */ + else { + account_id = getAccountFromCall (call_id); - if (account_id == AccountNULL) { - _debug ("Manager: Account ID %s or callid %s doesn't exists in call onHold", account_id.c_str(), call_id.c_str()); - return false; - } + if (account_id == AccountNULL) { + _debug ("Manager: Account ID %s or callid %s doesn't exists in call onHold", account_id.c_str(), call_id.c_str()); + return false; + } - returnValue = getAccountLink(account_id)->onhold(call_id); - } + returnValue = getAccountLink (account_id)->onhold (call_id); + } - removeWaitingCall(call_id); + removeWaitingCall (call_id); - // keeps current call id if the action is not holding this call or a new outgoing call + // keeps current call id if the action is not holding this call or a new outgoing call - if (current_call_id == call_id) { + if (current_call_id == call_id) { - switchCall(""); - } + switchCall (""); + } - if (_dbus) - _dbus->getCallManager()->callStateChanged(call_id, "HOLD"); + if (_dbus) + _dbus->getCallManager()->callStateChanged (call_id, "HOLD"); - return returnValue; + return returnValue; } //THREAD=Main bool ManagerImpl::offHoldCall (const CallID& call_id) { - AccountID account_id; - bool returnValue, is_rec; - std::string codecName; + AccountID account_id; + bool returnValue, is_rec; + std::string codecName; - is_rec = false; + is_rec = false; - _debug ("Manager: Put call %s off hold", call_id.c_str()); + _debug ("Manager: Put call %s off hold", call_id.c_str()); - stopTone(); + stopTone(); - CallID current_call_id = getCurrentCallId(); + CallID current_call_id = getCurrentCallId(); - //Place current call on hold if it isn't + //Place current call on hold if it isn't - if (hasCurrentCall()) { - // if this is not a conferenceand this and is not a conference participant - if (!isConference(current_call_id) && !participToConference( - current_call_id)) { - onHoldCall(current_call_id); - } else if (isConference(current_call_id) && !participToConference( - call_id)) { - detachParticipant(default_id, current_call_id); - } - } + if (hasCurrentCall()) { + // if this is not a conferenceand this and is not a conference participant + if (!isConference (current_call_id) && !participToConference ( + current_call_id)) { + onHoldCall (current_call_id); + } else if (isConference (current_call_id) && !participToConference ( + call_id)) { + detachParticipant (default_id, current_call_id); + } + } - // switch current call id to id since sipvoip link need it to amke a call - // switchCall(id); + // switch current call id to id since sipvoip link need it to amke a call + // switchCall(id); - /* Direct IP to IP call */ - if (getConfigFromCall(call_id) == Call::IPtoIP) { - // is_rec = SIPVoIPLink::instance (AccountNULL)-> isRecording (call_id); - returnValue = SIPVoIPLink::instance(AccountNULL)-> offhold(call_id); - } + /* Direct IP to IP call */ + if (getConfigFromCall (call_id) == Call::IPtoIP) { + // is_rec = SIPVoIPLink::instance (AccountNULL)-> isRecording (call_id); + returnValue = SIPVoIPLink::instance (AccountNULL)-> offhold (call_id); + } - /* Classic call, attached to an account */ - else { - account_id = getAccountFromCall(call_id); + /* Classic call, attached to an account */ + else { + account_id = getAccountFromCall (call_id); - if (account_id == AccountNULL) { - _warn ("Manager: Error: Call doesn't exists in off hold"); - return false; - } + if (account_id == AccountNULL) { + _warn ("Manager: Error: Call doesn't exists in off hold"); + return false; + } - _debug ("Manager: Setting offhold, Account %s, callid %s", account_id.c_str(), call_id.c_str()); + _debug ("Manager: Setting offhold, Account %s, callid %s", account_id.c_str(), call_id.c_str()); - is_rec = getAccountLink(account_id)->getCall(call_id)->isRecording(); - returnValue = getAccountLink(account_id)->offhold(call_id); - } + is_rec = getAccountLink (account_id)->getCall (call_id)->isRecording(); + returnValue = getAccountLink (account_id)->offhold (call_id); + } - if (_dbus) { - if (is_rec) - _dbus->getCallManager()->callStateChanged(call_id, "UNHOLD_RECORD"); - else - _dbus->getCallManager()->callStateChanged(call_id, "UNHOLD_CURRENT"); + if (_dbus) { + if (is_rec) + _dbus->getCallManager()->callStateChanged (call_id, "UNHOLD_RECORD"); + else + _dbus->getCallManager()->callStateChanged (call_id, "UNHOLD_CURRENT"); - } + } - if (participToConference(call_id)) { + if (participToConference (call_id)) { - AccountID currentAccountId; - Call* call = NULL; + AccountID currentAccountId; + Call* call = NULL; - currentAccountId = getAccountFromCall(call_id); - call = getAccountLink(currentAccountId)->getCall(call_id); + currentAccountId = getAccountFromCall (call_id); + call = getAccountLink (currentAccountId)->getCall (call_id); - switchCall(call->getConfId()); + switchCall (call->getConfId()); - } else { - switchCall(call_id); - _audiodriver->flushMain(); - } + } else { + switchCall (call_id); + _audiodriver->flushMain(); + } - return returnValue; + return returnValue; } //THREAD=Main bool ManagerImpl::transferCall (const CallID& call_id, const std::string& to) { - AccountID accountid; - bool returnValue; + AccountID accountid; + bool returnValue; - _info("Manager: Transfer call %s", call_id.c_str()); + _info ("Manager: Transfer call %s", call_id.c_str()); - CallID current_call_id = getCurrentCallId(); + CallID current_call_id = getCurrentCallId(); - // Direct IP to IP call - if (getConfigFromCall(call_id) == Call::IPtoIP) { - returnValue = SIPVoIPLink::instance(AccountNULL)-> transfer(call_id, to); - } - // Classic call, attached to an account - else { + // Direct IP to IP call + if (getConfigFromCall (call_id) == Call::IPtoIP) { + returnValue = SIPVoIPLink::instance (AccountNULL)-> transfer (call_id, to); + } + // Classic call, attached to an account + else { - accountid = getAccountFromCall(call_id); + accountid = getAccountFromCall (call_id); - if (accountid == AccountNULL) { - _warn ("Manager: Call doesn't exists"); - return false; - } + if (accountid == AccountNULL) { + _warn ("Manager: Call doesn't exists"); + return false; + } - returnValue = getAccountLink(accountid)->transfer(call_id, to); + returnValue = getAccountLink (accountid)->transfer (call_id, to); - } + } - // remove waiting call in case we make transfer without even answer - removeWaitingCall(call_id); + // remove waiting call in case we make transfer without even answer + removeWaitingCall (call_id); - return returnValue; + return returnValue; } void ManagerImpl::transferFailed () { - _debug("UserAgent: Transfer failed"); + _debug ("UserAgent: Transfer failed"); - if (_dbus) - _dbus->getCallManager()->transferFailed(); + if (_dbus) + _dbus->getCallManager()->transferFailed(); } void ManagerImpl::transferSucceded () { - _debug("UserAgent: Transfer succeded"); + _debug ("UserAgent: Transfer succeded"); - if (_dbus) - _dbus->getCallManager()->transferSucceded(); + if (_dbus) + _dbus->getCallManager()->transferSucceded(); } //THREAD=Main : Call:Incoming bool ManagerImpl::refuseCall (const CallID& id) { - AccountID accountid; - bool returnValue; + AccountID accountid; + bool returnValue; - _debug("Manager: Refuse call %s", id.c_str()); + _debug ("Manager: Refuse call %s", id.c_str()); - CallID current_call_id = getCurrentCallId(); + CallID current_call_id = getCurrentCallId(); - stopTone(); + stopTone(); - int nbCalls = getCallList().size(); + int nbCalls = getCallList().size(); - // AudioLayer* audiolayer = getAudioDriver(); + // AudioLayer* audiolayer = getAudioDriver(); - if (nbCalls <= 1) { - _debug (" refuseCall: stop audio stream, there is only %i call(s) remaining", nbCalls); + if (nbCalls <= 1) { + _debug (" refuseCall: stop audio stream, there is only %i call(s) remaining", nbCalls); - AudioLayer* audiolayer = getAudioDriver(); - audiolayer->stopStream(); - } + AudioLayer* audiolayer = getAudioDriver(); + audiolayer->stopStream(); + } - /* Direct IP to IP call */ + /* Direct IP to IP call */ - if (getConfigFromCall(id) == Call::IPtoIP) { - returnValue = SIPVoIPLink::instance(AccountNULL)-> refuse(id); - } + if (getConfigFromCall (id) == Call::IPtoIP) { + returnValue = SIPVoIPLink::instance (AccountNULL)-> refuse (id); + } - /* Classic call, attached to an account */ - else { - accountid = getAccountFromCall(id); + /* Classic call, attached to an account */ + else { + accountid = getAccountFromCall (id); - if (accountid == AccountNULL) { - _warn ("Manager: Call doesn't exists"); - return false; - } + if (accountid == AccountNULL) { + _warn ("Manager: Call doesn't exists"); + return false; + } - returnValue = getAccountLink(accountid)->refuse(id); + returnValue = getAccountLink (accountid)->refuse (id); - removeCallAccount(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 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"); - } + if (_dbus) + _dbus->getCallManager()->callStateChanged (id, "HUNGUP"); + } - return returnValue; + return returnValue; } Conference* ManagerImpl::createConference (const CallID& id1, const CallID& id2) { - _debug ("Manager: Create conference with call %s and %s", id1.c_str(), id2.c_str()); + _debug ("Manager: Create conference with call %s and %s", id1.c_str(), id2.c_str()); - Conference* conf = new Conference(); + Conference* conf = new Conference(); - conf->add(id1); - conf->add(id2); + conf->add (id1); + conf->add (id2); - // Add conference to map - _conferencemap.insert( std::pair<CallID, Conference*>(conf->getConfID(), conf)); + // Add conference to map + _conferencemap.insert (std::pair<CallID, Conference*> (conf->getConfID(), conf)); - // broadcast a signal over dbus - _dbus->getCallManager()->conferenceCreated(conf->getConfID()); + // broadcast a signal over dbus + _dbus->getCallManager()->conferenceCreated (conf->getConfID()); - return conf; + return conf; } void ManagerImpl::removeConference (const ConfID& conference_id) { - _debug ("Manager: Remove conference %s", conference_id.c_str()); + _debug ("Manager: Remove conference %s", conference_id.c_str()); - Conference* conf = NULL; + Conference* conf = NULL; - _debug ("Manager: number of participant: %d", (int) _conferencemap.size()); - ConferenceMap::iterator iter = _conferencemap.find(conference_id); + _debug ("Manager: number of participant: %d", (int) _conferencemap.size()); + ConferenceMap::iterator iter = _conferencemap.find (conference_id); - if (iter != _conferencemap.end()) { - conf = iter->second; - } + if (iter != _conferencemap.end()) { + conf = iter->second; + } - if (conf == NULL) { - _error ("Manager: Error: Conference not found"); - return; - } + if (conf == NULL) { + _error ("Manager: Error: Conference not found"); + return; + } - // We now need to bind the audio to the remain participant + // We now need to bind the audio to the remain participant - // Unbind main participant audio from conference - _audiodriver->getMainBuffer()->unBindAll(default_id); + // Unbind main participant audio from conference + _audiodriver->getMainBuffer()->unBindAll (default_id); - ParticipantSet participants = conf->getParticipantList(); + ParticipantSet participants = conf->getParticipantList(); - // bind main participant audio to remaining conference call - ParticipantSet::iterator iter_p = participants.begin(); + // bind main participant audio to remaining conference call + ParticipantSet::iterator iter_p = participants.begin(); - if (iter_p != participants.end()) { + if (iter_p != participants.end()) { - _audiodriver->getMainBuffer()->bindCallID(*iter_p, default_id); - } + _audiodriver->getMainBuffer()->bindCallID (*iter_p, default_id); + } - // Then remove the conference from the conference map - if (_conferencemap.erase(conference_id) == 1) - _debug ("Manager: Conference %s removed successfully", conference_id.c_str()); - else - _error ("Manager: Error: Cannot remove conference: %s", conference_id.c_str()); + // Then remove the conference from the conference map + if (_conferencemap.erase (conference_id) == 1) + _debug ("Manager: Conference %s removed successfully", conference_id.c_str()); + else + _error ("Manager: Error: Cannot remove conference: %s", conference_id.c_str()); - // broadcast a signal over dbus - _dbus->getCallManager()->conferenceRemoved(conference_id); + // broadcast a signal over dbus + _dbus->getCallManager()->conferenceRemoved (conference_id); } Conference* ManagerImpl::getConferenceFromCallID (const CallID& call_id) { - AccountID account_id; - Call* call = NULL; + AccountID account_id; + Call* call = NULL; - account_id = getAccountFromCall(call_id); - call = getAccountLink(account_id)->getCall(call_id); + account_id = getAccountFromCall (call_id); + call = getAccountLink (account_id)->getCall (call_id); - ConferenceMap::iterator iter = _conferencemap.find(call->getConfId()); + ConferenceMap::iterator iter = _conferencemap.find (call->getConfId()); - if (iter != _conferencemap.end()) { - return iter->second; - } else { - return NULL; - } + if (iter != _conferencemap.end()) { + return iter->second; + } else { + return NULL; + } } void ManagerImpl::holdConference (const CallID& id) { - _debug ("Manager: Hold conference()"); + _debug ("Manager: Hold conference()"); - Conference *conf; - ConferenceMap::iterator iter_conf = _conferencemap.find(id); + Conference *conf; + ConferenceMap::iterator iter_conf = _conferencemap.find (id); - AccountID currentAccountId; + AccountID currentAccountId; - Call* call = NULL; + Call* call = NULL; - if (iter_conf != _conferencemap.end()) { - conf = iter_conf->second; + if (iter_conf != _conferencemap.end()) { + conf = iter_conf->second; - ParticipantSet participants = conf->getParticipantList(); - ParticipantSet::iterator iter_participant = participants.begin(); + ParticipantSet participants = conf->getParticipantList(); + ParticipantSet::iterator iter_participant = participants.begin(); - while (iter_participant != participants.end()) { - _debug (" holdConference: participant %s", (*iter_participant).c_str()); - currentAccountId = getAccountFromCall(*iter_participant); - call = getAccountLink(currentAccountId)->getCall(*iter_participant); + while (iter_participant != participants.end()) { + _debug (" holdConference: participant %s", (*iter_participant).c_str()); + currentAccountId = getAccountFromCall (*iter_participant); + call = getAccountLink (currentAccountId)->getCall (*iter_participant); - switchCall(*iter_participant); - onHoldCall(*iter_participant); + switchCall (*iter_participant); + onHoldCall (*iter_participant); - iter_participant++; + iter_participant++; - } + } - conf->setState(Conference::Hold); + conf->setState (Conference::Hold); - _dbus->getCallManager()->conferenceChanged(conf->getConfID(), - conf->getStateStr()); + _dbus->getCallManager()->conferenceChanged (conf->getConfID(), + conf->getStateStr()); - } + } } void ManagerImpl::unHoldConference (const CallID& id) { - _debug ("Manager: Unhold conference()"); + _debug ("Manager: Unhold conference()"); - Conference *conf; - ConferenceMap::iterator iter_conf = _conferencemap.find(id); + Conference *conf; + ConferenceMap::iterator iter_conf = _conferencemap.find (id); - AccountID currentAccountId; + AccountID currentAccountId; - Call* call = NULL; + Call* call = NULL; - if (iter_conf != _conferencemap.end()) { - conf = iter_conf->second; + if (iter_conf != _conferencemap.end()) { + conf = iter_conf->second; - ParticipantSet participants = conf->getParticipantList(); - ParticipantSet::iterator iter_participant = participants.begin(); + ParticipantSet participants = conf->getParticipantList(); + ParticipantSet::iterator iter_participant = participants.begin(); - while (iter_participant != participants.end()) { - _debug (" unholdConference: participant %s", (*iter_participant).c_str()); - currentAccountId = getAccountFromCall(*iter_participant); - call = getAccountLink(currentAccountId)->getCall(*iter_participant); + while (iter_participant != participants.end()) { + _debug (" unholdConference: participant %s", (*iter_participant).c_str()); + currentAccountId = getAccountFromCall (*iter_participant); + call = getAccountLink (currentAccountId)->getCall (*iter_participant); - offHoldCall(*iter_participant); + offHoldCall (*iter_participant); - iter_participant++; + iter_participant++; - } + } - conf->setState(Conference::Active_Atached); + conf->setState (Conference::Active_Atached); - _dbus->getCallManager()->conferenceChanged(conf->getConfID(), - conf->getStateStr()); + _dbus->getCallManager()->conferenceChanged (conf->getConfID(), + conf->getStateStr()); - } + } } bool ManagerImpl::isConference (const CallID& id) { - ConferenceMap::iterator iter = _conferencemap.find(id); + ConferenceMap::iterator iter = _conferencemap.find (id); - if (iter == _conferencemap.end()) { - return false; - } else { - return true; - } + if (iter == _conferencemap.end()) { + return false; + } else { + return true; + } } bool ManagerImpl::participToConference (const CallID& call_id) { - AccountID accountId; + AccountID accountId; - Call* call = NULL; + Call* call = NULL; - accountId = getAccountFromCall(call_id); - call = getAccountLink(accountId)->getCall(call_id); + accountId = getAccountFromCall (call_id); + call = getAccountLink (accountId)->getCall (call_id); - if (call == NULL) { - return false; + if (call == NULL) { + return false; - } + } - if (call->getConfId() == "") { - return false; - } else { + if (call->getConfId() == "") { + return false; + } else { - return true; - } + return true; + } } void ManagerImpl::addParticipant (const CallID& call_id, const CallID& conference_id) { - _debug ("ManagerImpl: Add participant %s to %s", call_id.c_str(), conference_id.c_str()); + _debug ("ManagerImpl: Add participant %s to %s", call_id.c_str(), conference_id.c_str()); - std::map<std::string, std::string> call_details = getCallDetails(call_id); + std::map<std::string, std::string> call_details = getCallDetails (call_id); - ConferenceMap::iterator iter = _conferencemap.find(conference_id); - std::map<std::string, std::string>::iterator iter_details; + ConferenceMap::iterator iter = _conferencemap.find (conference_id); + std::map<std::string, std::string>::iterator iter_details; - // store the current call id (it will change in offHoldCall or in answerCall) - CallID current_call_id = getCurrentCallId(); + // store the current call id (it will change in offHoldCall or in answerCall) + CallID current_call_id = getCurrentCallId(); - // detach from the conference and switch to this conference + // detach from the conference and switch to this conference - if (current_call_id != call_id) { - if (isConference(current_call_id)) { - detachParticipant(default_id, current_call_id); - } else - onHoldCall(current_call_id); - } + if (current_call_id != call_id) { + if (isConference (current_call_id)) { + detachParticipant (default_id, current_call_id); + } else + onHoldCall (current_call_id); + } - // TODO: remove this ugly hack => There should be different calls when double clicking - // a conference to add main participant to it, or (in this case) adding a participant - // toconference - switchCall(""); + // TODO: remove this ugly hack => There should be different calls when double clicking + // a conference to add main participant to it, or (in this case) adding a participant + // toconference + switchCall (""); - addMainParticipant(conference_id); + addMainParticipant (conference_id); - _debug (" addParticipant: enter main process"); + _debug (" addParticipant: enter main process"); - if (iter != _conferencemap.end()) { + if (iter != _conferencemap.end()) { - Conference* conf = iter->second; - switchCall(conf->getConfID()); + Conference* conf = iter->second; + switchCall (conf->getConfID()); - AccountID currentAccountId; - Call* call = NULL; + AccountID currentAccountId; + Call* call = NULL; - currentAccountId = getAccountFromCall(call_id); - call = getAccountLink(currentAccountId)->getCall(call_id); - call->setConfId(conf->getConfID()); + currentAccountId = getAccountFromCall (call_id); + call = getAccountLink (currentAccountId)->getCall (call_id); + call->setConfId (conf->getConfID()); - conf->add(call_id); + conf->add (call_id); - iter_details = call_details.find("CALL_STATE"); + iter_details = call_details.find ("CALL_STATE"); - _debug (" addParticipant: call state: %s", iter_details->second.c_str()); + _debug (" addParticipant: call state: %s", iter_details->second.c_str()); - if (iter_details->second == "HOLD") { - _debug (" OFFHOLD %s", call_id.c_str()); + if (iter_details->second == "HOLD") { + _debug (" OFFHOLD %s", call_id.c_str()); - // offHoldCall create a new rtp session which use addStream to bind participant - offHoldCall(call_id); - } else if (iter_details->second == "INCOMING") { - _debug (" ANSWER %s", call_id.c_str()); - // answerCall create a new rtp session which use addStream to bind participant - answerCall(call_id); - } else if (iter_details->second == "CURRENT") { - // Already a curent call, so we beed to reset audio stream bindings manually - _audiodriver->getMainBuffer()->unBindAll(call_id); - conf->bindParticipant(call_id); - } + // offHoldCall create a new rtp session which use addStream to bind participant + offHoldCall (call_id); + } else if (iter_details->second == "INCOMING") { + _debug (" ANSWER %s", call_id.c_str()); + // answerCall create a new rtp session which use addStream to bind participant + answerCall (call_id); + } else if (iter_details->second == "CURRENT") { + // Already a curent call, so we beed to reset audio stream bindings manually + _audiodriver->getMainBuffer()->unBindAll (call_id); + conf->bindParticipant (call_id); + } - // _dbus->getCallManager()->conferenceChanged(conference_id, conf->getStateStr()); + // _dbus->getCallManager()->conferenceChanged(conference_id, conf->getStateStr()); - ParticipantSet participants = conf->getParticipantList(); + ParticipantSet participants = conf->getParticipantList(); - // reset ring buffer for all conference participant - ParticipantSet::iterator iter_p = participants.begin(); + // reset ring buffer for all conference participant + ParticipantSet::iterator iter_p = participants.begin(); - while (iter_p != participants.end()) { + while (iter_p != participants.end()) { - // flush conference participants only - _audiodriver->getMainBuffer()->flush(*iter_p); + // flush conference participants only + _audiodriver->getMainBuffer()->flush (*iter_p); - iter_p++; - } + iter_p++; + } - _audiodriver->getMainBuffer()->flush(default_id); - } else { - _debug (" addParticipant: Error, conference %s conference_id not found!", conference_id.c_str()); - } + _audiodriver->getMainBuffer()->flush (default_id); + } else { + _debug (" addParticipant: Error, conference %s conference_id not found!", conference_id.c_str()); + } } void ManagerImpl::addMainParticipant (const CallID& conference_id) { - if (hasCurrentCall()) { - CallID current_call_id = getCurrentCallId(); - - if (isConference(current_call_id)) { - detachParticipant(default_id, current_call_id); - } else { - onHoldCall(current_call_id); - } - } + if (hasCurrentCall()) { + CallID current_call_id = getCurrentCallId(); + + if (isConference (current_call_id)) { + detachParticipant (default_id, current_call_id); + } else { + onHoldCall (current_call_id); + } + } - ConferenceMap::iterator iter = _conferencemap.find(conference_id); + ConferenceMap::iterator iter = _conferencemap.find (conference_id); - Conference *conf = NULL; + Conference *conf = NULL; - if (iter != _conferencemap.end()) { - conf = iter->second; + if (iter != _conferencemap.end()) { + conf = iter->second; - ParticipantSet participants = conf->getParticipantList(); + ParticipantSet participants = conf->getParticipantList(); - ParticipantSet::iterator iter_participant = participants.begin(); + ParticipantSet::iterator iter_participant = participants.begin(); - while (iter_participant != participants.end()) { - _audiodriver->getMainBuffer()->bindCallID(*iter_participant, - default_id); + while (iter_participant != participants.end()) { + _audiodriver->getMainBuffer()->bindCallID (*iter_participant, + default_id); - iter_participant++; - } + iter_participant++; + } - // Reset ringbuffer's readpointers - iter_participant = participants.begin(); + // Reset ringbuffer's readpointers + iter_participant = participants.begin(); - while (iter_participant != participants.end()) { - _audiodriver->getMainBuffer()->flush(*iter_participant); + while (iter_participant != participants.end()) { + _audiodriver->getMainBuffer()->flush (*iter_participant); - iter_participant++; - } + iter_participant++; + } - _audiodriver->getMainBuffer()->flush(default_id); + _audiodriver->getMainBuffer()->flush (default_id); - conf->setState(Conference::Active_Atached); + conf->setState (Conference::Active_Atached); - _dbus->getCallManager()->conferenceChanged(conference_id, - conf->getStateStr()); + _dbus->getCallManager()->conferenceChanged (conference_id, + conf->getStateStr()); - } + } - switchCall(conference_id); + switchCall (conference_id); } void ManagerImpl::joinParticipant (const CallID& call_id1, const CallID& call_id2) { - _debug ("Manager: Join participants %s, %s", call_id1.c_str(), call_id2.c_str()); - - std::map<std::string, std::string> call1_details = getCallDetails(call_id1); - std::map<std::string, std::string> call2_details = getCallDetails(call_id2); + _debug ("Manager: Join participants %s, %s", call_id1.c_str(), call_id2.c_str()); - std::map<std::string, std::string>::iterator iter_details; + std::map<std::string, std::string> call1_details = getCallDetails (call_id1); + std::map<std::string, std::string> call2_details = getCallDetails (call_id2); - // Test if we have valid call ids - iter_details = call1_details.find("PEER_NUMBER"); - if(iter_details->second == "Unknown") { - _error("Manager: Error: Id %s is not a valid call", call_id1.c_str()); - return; - } + std::map<std::string, std::string>::iterator iter_details; - iter_details = call2_details.find("PEER_NUMBER"); - if(iter_details->second == "Unknown") { - _error("Manager: Error: Id %s is not a valid call", call_id2.c_str()); - return; - } + // Test if we have valid call ids + iter_details = call1_details.find ("PEER_NUMBER"); - AccountID currentAccountId; - Call* call = NULL; - - CallID current_call_id = getCurrentCallId(); - _debug ("Manager: current_call_id %s", current_call_id.c_str()); - - // detach from the conference and switch to this conference - if ((current_call_id != call_id1) && (current_call_id != call_id2)) { - - // If currently in a conference - if (isConference(current_call_id)) - detachParticipant(default_id, current_call_id); - // If currently in a call - else - onHoldCall(current_call_id); - } - - _debug ("Manager: Create a conference"); + if (iter_details->second == "Unknown") { + _error ("Manager: Error: Id %s is not a valid call", call_id1.c_str()); + return; + } - Conference *conf = createConference(call_id1, call_id2); - switchCall(conf->getConfID()); + iter_details = call2_details.find ("PEER_NUMBER"); - currentAccountId = getAccountFromCall(call_id1); - call = getAccountLink(currentAccountId)->getCall(call_id1); - call->setConfId(conf->getConfID()); + if (iter_details->second == "Unknown") { + _error ("Manager: Error: Id %s is not a valid call", call_id2.c_str()); + return; + } - iter_details = call1_details.find("CALL_STATE"); - _debug ("Manager: Process call %s state: %s", call_id1.c_str(), iter_details->second.c_str()); + AccountID currentAccountId; + Call* call = NULL; - if (iter_details->second == "HOLD") { - offHoldCall(call_id1); - } else if (iter_details->second == "INCOMING") { - answerCall(call_id1); - } else if (iter_details->second == "CURRENT") { - _audiodriver->getMainBuffer()->unBindAll(call_id1); - conf->bindParticipant(call_id1); - } else if (iter_details->second == "INACTIVE") { - answerCall(call_id1); - } else { - _warn ("Manager: Call state not recognized"); - } + CallID current_call_id = getCurrentCallId(); + _debug ("Manager: current_call_id %s", current_call_id.c_str()); - currentAccountId = getAccountFromCall(call_id2); + // detach from the conference and switch to this conference + if ( (current_call_id != call_id1) && (current_call_id != call_id2)) { - call = getAccountLink(currentAccountId)->getCall(call_id2); - call->setConfId(conf->getConfID()); + // If currently in a conference + if (isConference (current_call_id)) + detachParticipant (default_id, current_call_id); + // If currently in a call + else + onHoldCall (current_call_id); + } - iter_details = call2_details.find("CALL_STATE"); - _debug ("Manager: Process call %s state: %s", call_id2.c_str(), iter_details->second.c_str()); + _debug ("Manager: Create a conference"); + + Conference *conf = createConference (call_id1, call_id2); + switchCall (conf->getConfID()); + + currentAccountId = getAccountFromCall (call_id1); + call = getAccountLink (currentAccountId)->getCall (call_id1); + call->setConfId (conf->getConfID()); + + iter_details = call1_details.find ("CALL_STATE"); + _debug ("Manager: Process call %s state: %s", call_id1.c_str(), iter_details->second.c_str()); + + if (iter_details->second == "HOLD") { + offHoldCall (call_id1); + } else if (iter_details->second == "INCOMING") { + answerCall (call_id1); + } else if (iter_details->second == "CURRENT") { + _audiodriver->getMainBuffer()->unBindAll (call_id1); + conf->bindParticipant (call_id1); + } else if (iter_details->second == "INACTIVE") { + answerCall (call_id1); + } else { + _warn ("Manager: Call state not recognized"); + } - if (iter_details->second == "HOLD") { - offHoldCall(call_id2); - } else if (iter_details->second == "INCOMING") { - answerCall(call_id2); - } else if (iter_details->second == "CURRENT") { - _audiodriver->getMainBuffer()->unBindAll(call_id2); - conf->bindParticipant(call_id2); - } else if (iter_details->second == "INACTIVE") { - answerCall(call_id2); - } else { - _warn ("Manager: Call state not recognized"); - } + currentAccountId = getAccountFromCall (call_id2); + + call = getAccountLink (currentAccountId)->getCall (call_id2); + call->setConfId (conf->getConfID()); + + iter_details = call2_details.find ("CALL_STATE"); + _debug ("Manager: Process call %s state: %s", call_id2.c_str(), iter_details->second.c_str()); + + if (iter_details->second == "HOLD") { + offHoldCall (call_id2); + } else if (iter_details->second == "INCOMING") { + answerCall (call_id2); + } else if (iter_details->second == "CURRENT") { + _audiodriver->getMainBuffer()->unBindAll (call_id2); + conf->bindParticipant (call_id2); + } else if (iter_details->second == "INACTIVE") { + answerCall (call_id2); + } else { + _warn ("Manager: Call state not recognized"); + } - if (_audiodriver) - _audiodriver->getMainBuffer()->stateInfo(); + if (_audiodriver) + _audiodriver->getMainBuffer()->stateInfo(); } void ManagerImpl::detachParticipant (const CallID& call_id, - const CallID& current_id) { + const CallID& current_id) { - _debug ("Manager: Detach participant %s from conference", call_id.c_str()); + _debug ("Manager: Detach participant %s from conference", call_id.c_str()); - CallID current_call_id = current_id; + CallID current_call_id = current_id; - current_call_id = getCurrentCallId(); + current_call_id = getCurrentCallId(); - if (call_id != default_id) { - AccountID currentAccountId; - Call* call = NULL; + if (call_id != default_id) { + AccountID currentAccountId; + Call* call = NULL; - currentAccountId = getAccountFromCall(call_id); - call = getAccountLink(currentAccountId)->getCall(call_id); + currentAccountId = getAccountFromCall (call_id); + call = getAccountLink (currentAccountId)->getCall (call_id); - // TODO: add conference_id as a second parameter - ConferenceMap::iterator iter = _conferencemap.find(call->getConfId()); + // TODO: add conference_id as a second parameter + ConferenceMap::iterator iter = _conferencemap.find (call->getConfId()); - Conference *conf = getConferenceFromCallID(call_id); + Conference *conf = getConferenceFromCallID (call_id); - if (conf != NULL) { + if (conf != NULL) { - _debug ("Manager: Detaching participant %s", call_id.c_str()); - std::map<std::string, std::string> call_details = getCallDetails( - call_id); - std::map<std::string, std::string>::iterator iter_details; + _debug ("Manager: Detaching participant %s", call_id.c_str()); + std::map<std::string, std::string> call_details = getCallDetails ( + call_id); + std::map<std::string, std::string>::iterator iter_details; - iter_details = call_details.find("CALL_STATE"); + iter_details = call_details.find ("CALL_STATE"); - if (iter_details->second == "RINGING") { + if (iter_details->second == "RINGING") { - removeParticipant(call_id); - } - else { - onHoldCall(call_id); - removeParticipant(call_id); - processRemainingParticipant(current_call_id, conf); + removeParticipant (call_id); + } else { + onHoldCall (call_id); + removeParticipant (call_id); + processRemainingParticipant (current_call_id, conf); - _dbus->getCallManager()->conferenceChanged(conf->getConfID(), - conf->getStateStr()); - } - } - else { + _dbus->getCallManager()->conferenceChanged (conf->getConfID(), + conf->getStateStr()); + } + } else { - _debug ("Manager: Call is not conferencing, cannot detach"); + _debug ("Manager: Call is not conferencing, cannot detach"); - } - } - else { - _debug ("Manager: Unbind main participant from all"); - _audiodriver->getMainBuffer()->unBindAll(default_id); + } + } else { + _debug ("Manager: Unbind main participant from all"); + _audiodriver->getMainBuffer()->unBindAll (default_id); - if (isConference(current_call_id)) { + if (isConference (current_call_id)) { - ConferenceMap::iterator iter = _conferencemap.find(current_call_id); - Conference *conf = iter->second; + ConferenceMap::iterator iter = _conferencemap.find (current_call_id); + Conference *conf = iter->second; - conf->setState(Conference::Active_Detached); + conf->setState (Conference::Active_Detached); - _dbus->getCallManager()->conferenceChanged(conf->getConfID(), - conf->getStateStr()); - } + _dbus->getCallManager()->conferenceChanged (conf->getConfID(), + conf->getStateStr()); + } - switchCall(""); + switchCall (""); - } + } } void ManagerImpl::removeParticipant (const CallID& call_id) { - _debug ("Manager: Remove participant %s", call_id.c_str()); + _debug ("Manager: Remove participant %s", call_id.c_str()); - // TODO: add conference_id as a second parameter - Conference* conf; + // TODO: add conference_id as a second parameter + Conference* conf; - AccountID currentAccountId; - Call* call = NULL; + AccountID currentAccountId; + Call* call = NULL; - // this call is no more a conference participant - currentAccountId = getAccountFromCall(call_id); - call = getAccountLink(currentAccountId)->getCall(call_id); + // this call is no more a conference participant + currentAccountId = getAccountFromCall (call_id); + call = getAccountLink (currentAccountId)->getCall (call_id); - ConferenceMap conf_map = _conferencemap; - ConferenceMap::iterator iter = conf_map.find(call->getConfId()); + ConferenceMap conf_map = _conferencemap; + ConferenceMap::iterator iter = conf_map.find (call->getConfId()); - if (iter == conf_map.end()) { - _debug ("Manager: Error: No conference created, cannot remove participant"); - } else { + if (iter == conf_map.end()) { + _debug ("Manager: Error: No conference created, cannot remove participant"); + } else { - conf = iter->second; + conf = iter->second; - _debug ("Manager: Remove participant %s", call_id.c_str()); - conf->remove(call_id); - call->setConfId(""); + _debug ("Manager: Remove participant %s", call_id.c_str()); + conf->remove (call_id); + call->setConfId (""); - } + } - if (_audiodriver) - _audiodriver->getMainBuffer()->stateInfo(); + if (_audiodriver) + _audiodriver->getMainBuffer()->stateInfo(); } void ManagerImpl::processRemainingParticipant (CallID current_call_id, - Conference *conf) { + Conference *conf) { - _debug ("Manager: Process remaining %d participant(s) from conference %s", - conf->getNbParticipants(), conf->getConfID().c_str()); + _debug ("Manager: Process remaining %d participant(s) from conference %s", + conf->getNbParticipants(), conf->getConfID().c_str()); - if (conf->getNbParticipants() > 1) { + if (conf->getNbParticipants() > 1) { - ParticipantSet participants = conf->getParticipantList(); - ParticipantSet::iterator iter_participant = participants.begin(); + ParticipantSet participants = conf->getParticipantList(); + ParticipantSet::iterator iter_participant = participants.begin(); - // Reset ringbuffer's readpointers - iter_participant = participants.begin(); + // Reset ringbuffer's readpointers + iter_participant = participants.begin(); - while (iter_participant != participants.end()) { - _audiodriver->getMainBuffer()->flush(*iter_participant); + while (iter_participant != participants.end()) { + _audiodriver->getMainBuffer()->flush (*iter_participant); - iter_participant++; - } + iter_participant++; + } - _audiodriver->getMainBuffer()->flush(default_id); + _audiodriver->getMainBuffer()->flush (default_id); - } else if (conf->getNbParticipants() == 1) { + } else if (conf->getNbParticipants() == 1) { - _debug ("Manager: Only one remaining participant"); + _debug ("Manager: Only one remaining participant"); - AccountID currentAccountId; - Call* call = NULL; + AccountID currentAccountId; + Call* call = NULL; - ParticipantSet participants = conf->getParticipantList(); - ParticipantSet::iterator iter_participant = participants.begin(); + ParticipantSet participants = conf->getParticipantList(); + ParticipantSet::iterator iter_participant = participants.begin(); - // bind main participant to remaining conference call - if (iter_participant != participants.end()) { + // bind main participant to remaining conference call + if (iter_participant != participants.end()) { - // this call is no more a conference participant - currentAccountId = getAccountFromCall(*iter_participant); - call = getAccountLink(currentAccountId)->getCall(*iter_participant); - call->setConfId(""); + // this call is no more a conference participant + currentAccountId = getAccountFromCall (*iter_participant); + call = getAccountLink (currentAccountId)->getCall (*iter_participant); + call->setConfId (""); - // if we are not listening to this conference + // if we are not listening to this conference - if (current_call_id != conf->getConfID()) { - onHoldCall(call->getCallId()); - } else { - switchCall(*iter_participant); - } - } + if (current_call_id != conf->getConfID()) { + onHoldCall (call->getCallId()); + } else { + switchCall (*iter_participant); + } + } - removeConference(conf->getConfID()); + removeConference (conf->getConfID()); - } else { + } else { - _debug ("Manager: No remaining participant, remove conference"); + _debug ("Manager: No remaining participant, remove conference"); - removeConference(conf->getConfID()); + removeConference (conf->getConfID()); - switchCall(""); - } + switchCall (""); + } } void ManagerImpl::joinConference (const CallID& conf_id1, - const CallID& conf_id2) { - _debug ("Manager: Join conference %s, %s", conf_id1.c_str(), conf_id2.c_str()); + const CallID& conf_id2) { + _debug ("Manager: Join conference %s, %s", conf_id1.c_str(), conf_id2.c_str()); - ConferenceMap::iterator iter; + ConferenceMap::iterator iter; - Conference *conf1 = NULL; - Conference *conf2 = NULL; + Conference *conf1 = NULL; + Conference *conf2 = NULL; - iter = _conferencemap.find(conf_id1); + iter = _conferencemap.find (conf_id1); - if (iter != _conferencemap.end()) { - conf1 = iter->second; - } - else { - _error("Manager: Error: Not a valid conference ID"); - return; - } + if (iter != _conferencemap.end()) { + conf1 = iter->second; + } else { + _error ("Manager: Error: Not a valid conference ID"); + return; + } - iter = _conferencemap.find(conf_id2); + iter = _conferencemap.find (conf_id2); - if (iter != _conferencemap.end()) { - conf2 = iter->second; - } - else { - _error("Manager: Error: Not a valid conference ID"); - return; - } + if (iter != _conferencemap.end()) { + conf2 = iter->second; + } else { + _error ("Manager: Error: Not a valid conference ID"); + return; + } - ParticipantSet participants = conf1->getParticipantList(); + ParticipantSet participants = conf1->getParticipantList(); - ParticipantSet::iterator iter_participant = participants.begin(); + ParticipantSet::iterator iter_participant = participants.begin(); - while (iter_participant != participants.end()) { - detachParticipant(*iter_participant, ""); - addParticipant(*iter_participant, conf_id2); + while (iter_participant != participants.end()) { + detachParticipant (*iter_participant, ""); + addParticipant (*iter_participant, conf_id2); - iter_participant++; - } + iter_participant++; + } - // detachParticipant(default_id, ""); + // detachParticipant(default_id, ""); } void ManagerImpl::addStream (const CallID& call_id) { - _debug ("Manager: Add audio stream %s", call_id.c_str()); + _debug ("Manager: Add audio stream %s", call_id.c_str()); + + AccountID currentAccountId; + Call* call = NULL; - AccountID currentAccountId; - Call* call = NULL; + currentAccountId = getAccountFromCall (call_id); + call = getAccountLink (currentAccountId)->getCall (call_id); - currentAccountId = getAccountFromCall(call_id); - call = getAccountLink(currentAccountId)->getCall(call_id); + if (participToConference (call_id)) { - if (participToConference(call_id)) { + _debug ("Manager: Add stream to conference"); - _debug("Manager: Add stream to conference"); + // bind to conference participant + ConferenceMap::iterator iter = _conferencemap.find (call->getConfId()); - // bind to conference participant - ConferenceMap::iterator iter = _conferencemap.find(call->getConfId()); + if (iter != _conferencemap.end()) { + Conference* conf = iter->second; - if (iter != _conferencemap.end()) { - Conference* conf = iter->second; + conf->bindParticipant (call_id); - conf->bindParticipant(call_id); + ParticipantSet participants = conf->getParticipantList(); + // reset ring buffer for all conference participant + ParticipantSet::iterator iter_p = participants.begin(); - ParticipantSet participants = conf->getParticipantList(); - // reset ring buffer for all conference participant - ParticipantSet::iterator iter_p = participants.begin(); + while (iter_p != participants.end()) { - while (iter_p != participants.end()) { + // to avoid puting onhold the call + // switchCall(""); + _audiodriver->getMainBuffer()->flush (*iter_p); - // to avoid puting onhold the call - // switchCall(""); - _audiodriver->getMainBuffer()->flush(*iter_p); - - iter_p++; - } + iter_p++; + } - _audiodriver->getMainBuffer()->flush(default_id); - } + _audiodriver->getMainBuffer()->flush (default_id); + } - } else { + } else { - _debug("Manager: Add stream to call"); + _debug ("Manager: Add stream to call"); - // bind to main - getAudioDriver()->getMainBuffer()->bindCallID(call_id); - - // _audiodriver->getMainBuffer()->flush(default_id); - _audiodriver->flushUrgent(); - _audiodriver->flushMain(); + // bind to main + getAudioDriver()->getMainBuffer()->bindCallID (call_id); - } + // _audiodriver->getMainBuffer()->flush(default_id); + _audiodriver->flushUrgent(); + _audiodriver->flushMain(); + + } - if (_audiodriver) - _audiodriver->getMainBuffer()->stateInfo(); + if (_audiodriver) + _audiodriver->getMainBuffer()->stateInfo(); } void ManagerImpl::removeStream (const CallID& call_id) { - _debug ("Manager: Remove audio stream %s", call_id.c_str()); + _debug ("Manager: Remove audio stream %s", call_id.c_str()); - getAudioDriver()->getMainBuffer()->unBindAll(call_id); + getAudioDriver()->getMainBuffer()->unBindAll (call_id); - if (participToConference(call_id)) { - removeParticipant(call_id); - } + if (participToConference (call_id)) { + removeParticipant (call_id); + } - if (_audiodriver) - _audiodriver->getMainBuffer()->stateInfo(); + if (_audiodriver) + _audiodriver->getMainBuffer()->stateInfo(); } //THREAD=Main bool ManagerImpl::saveConfig (void) { - _debug ("Manager: Saving Configuration to XDG directory %s ... ", _path.c_str()); - audioPreference.setVolumemic(getMicVolume()); - audioPreference.setVolumespkr(getSpkrVolume()); + _debug ("Manager: Saving Configuration to XDG directory %s ... ", _path.c_str()); + audioPreference.setVolumemic (getMicVolume()); + audioPreference.setVolumespkr (getSpkrVolume()); + + AccountMap::iterator iter = _accountMap.begin(); - AccountMap::iterator iter = _accountMap.begin(); + try { + // emitter = new Conf::YamlEmitter("sequenceEmitter.yml"); + emitter = new Conf::YamlEmitter (_path.c_str()); - try{ - // emitter = new Conf::YamlEmitter("sequenceEmitter.yml"); - emitter = new Conf::YamlEmitter(_path.c_str()); + while (iter != _accountMap.end()) { + _debug ("Manager: Saving account: %s", iter->first.c_str()); - while(iter != _accountMap.end()) { - _debug("Manager: Saving account: %s", iter->first.c_str()); - if(iter->first == "") { - iter++; - continue; - } - iter->second->serialize(emitter); - iter++; - } + if (iter->first == "") { + iter++; + continue; + } - preferences.serialize(emitter); - voipPreferences.serialize(emitter); - addressbookPreference.serialize(emitter); - hookPreference.serialize(emitter); - audioPreference.serialize(emitter); - shortcutPreferences.serialize(emitter); + iter->second->serialize (emitter); + iter++; + } - emitter->serializeData(); + preferences.serialize (emitter); + voipPreferences.serialize (emitter); + addressbookPreference.serialize (emitter); + hookPreference.serialize (emitter); + audioPreference.serialize (emitter); + shortcutPreferences.serialize (emitter); - delete emitter; - } - catch (Conf::YamlEmitterException &e) { - _error("ConfigTree: %s", e.what()); - } + emitter->serializeData(); - // _setupLoaded = _config.saveConfigTree(_path.data()); - return _setupLoaded; + delete emitter; + } catch (Conf::YamlEmitterException &e) { + _error ("ConfigTree: %s", e.what()); + } + + // _setupLoaded = _config.saveConfigTree(_path.data()); + return _setupLoaded; } //THREAD=Main bool ManagerImpl::sendDtmf (const CallID& id, char code) { - AccountID accountid = getAccountFromCall(id); + AccountID accountid = getAccountFromCall (id); - bool returnValue = false; + bool returnValue = false; - playDtmf(code); + playDtmf (code); - CallAccountMap::iterator iter = _callAccountMap.find(id); + CallAccountMap::iterator iter = _callAccountMap.find (id); - // Make sure the call exist before sending DTMF, ths could be simply call dialing - if(iter != _callAccountMap.end()) - returnValue = getAccountLink(accountid)->carryingDTMFdigits(id, code); + // Make sure the call exist before sending DTMF, ths could be simply call dialing + if (iter != _callAccountMap.end()) + returnValue = getAccountLink (accountid)->carryingDTMFdigits (id, code); - return returnValue; + return returnValue; } //THREAD=Main | VoIPLink bool ManagerImpl::playDtmf (char code) { - int pulselen, layer, size; - bool ret = false; - AudioLayer *audiolayer; - SFLDataFormat *buf; - - stopTone(); + int pulselen, layer, size; + bool ret = false; + AudioLayer *audiolayer; + SFLDataFormat *buf; - bool hasToPlayTone = voipPreferences.getPlayDtmf(); + stopTone(); - if (!hasToPlayTone) { - _debug ("Manager: playDtmf: Do not have to play a tone..."); - return false; - } + bool hasToPlayTone = voipPreferences.getPlayDtmf(); - // length in milliseconds - pulselen = voipPreferences.getPulseLength(); - - if (!pulselen) { - _debug ("Manager: playDtmf: Pulse length is not set..."); - return false; - } - - // numbers of int = length in milliseconds / 1000 (number of seconds) - // = number of seconds * SAMPLING_RATE by SECONDS - audiolayer = getAudioDriver(); + if (!hasToPlayTone) { + _debug ("Manager: playDtmf: Do not have to play a tone..."); + return false; + } - layer = audiolayer->getLayerType(); + // length in milliseconds + pulselen = voipPreferences.getPulseLength(); - // fast return, no sound, so no dtmf - if (audiolayer == 0 || _dtmfKey == 0) { - _debug ("Manager: playDtmf: Error no audio layer..."); - return false; - } + if (!pulselen) { + _debug ("Manager: playDtmf: Pulse length is not set..."); + return false; + } - // number of data sampling in one pulselen depends on samplerate - // size (n sampling) = time_ms * sampling/s - // --------------------- - // ms/s - size = (int) ((pulselen * (float) audiolayer->getSampleRate()) / 1000); + // numbers of int = length in milliseconds / 1000 (number of seconds) + // = number of seconds * SAMPLING_RATE by SECONDS + audiolayer = getAudioDriver(); - // this buffer is for mono - // TODO <-- this should be global and hide if same size - buf = new SFLDataFormat[size]; + layer = audiolayer->getLayerType(); - // Handle dtmf - _dtmfKey->startTone(code); + // fast return, no sound, so no dtmf + if (audiolayer == 0 || _dtmfKey == 0) { + _debug ("Manager: playDtmf: Error no audio layer..."); + return false; + } - // copy the sound - 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->flushUrgent(); - audiolayer->startStream(); - audiolayer->putUrgent(buf, size * sizeof(SFLDataFormat)); - } + // number of data sampling in one pulselen depends on samplerate + // size (n sampling) = time_ms * sampling/s + // --------------------- + // ms/s + 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); + + // copy the sound + 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->flushUrgent(); + audiolayer->startStream(); + audiolayer->putUrgent (buf, size * sizeof (SFLDataFormat)); + } - ret = true; + ret = true; - // TODO Cache the DTMF + // TODO Cache the DTMF - delete[] buf; - buf = 0; + delete[] buf; + buf = 0; - return ret; + return ret; } // Multi-thread bool ManagerImpl::incomingCallWaiting () { - return (_nbIncomingWaitingCall > 0) ? true : false; + return (_nbIncomingWaitingCall > 0) ? true : false; } void ManagerImpl::addWaitingCall (const CallID& id) { - _info("Manager: Add waiting call %s (%d calls)", id.c_str(), _nbIncomingWaitingCall); + _info ("Manager: Add waiting call %s (%d calls)", id.c_str(), _nbIncomingWaitingCall); - ost::MutexLock m(_waitingCallMutex); - _waitingCall.insert(id); - _nbIncomingWaitingCall++; + ost::MutexLock m (_waitingCallMutex); + _waitingCall.insert (id); + _nbIncomingWaitingCall++; } void ManagerImpl::removeWaitingCall (const CallID& id) { - _info("Manager: Remove waiting call %s (%d calls)", id.c_str(), _nbIncomingWaitingCall); + _info ("Manager: Remove waiting call %s (%d calls)", id.c_str(), _nbIncomingWaitingCall); - ost::MutexLock m(_waitingCallMutex); - // should return more than 1 if it erase a call + ost::MutexLock m (_waitingCallMutex); + // should return more than 1 if it erase a call - if (_waitingCall.erase(id)) { - _nbIncomingWaitingCall--; - } + if (_waitingCall.erase (id)) { + _nbIncomingWaitingCall--; + } } bool ManagerImpl::isWaitingCall (const CallID& id) { - CallIDSet::iterator iter = _waitingCall.find(id); + CallIDSet::iterator iter = _waitingCall.find (id); - if (iter != _waitingCall.end()) { - return false; - } + if (iter != _waitingCall.end()) { + return false; + } - return true; + return true; } /////////////////////////////////////////////////////////////////////////////// @@ -1581,243 +1586,241 @@ bool ManagerImpl::isWaitingCall (const CallID& id) { // SipEvent Thread bool ManagerImpl::incomingCall (Call* call, const AccountID& accountId) { - std::string from, number, display_name, display; + std::string from, number, display_name, display; - if(!call) - _error("Manager: Error: no call at this point"); + if (!call) + _error ("Manager: Error: no call at this point"); - stopTone(); + stopTone(); - _debug ("Manager: Incoming call %s for account %s", call->getCallId().data(), accountId.c_str()); + _debug ("Manager: Incoming call %s for account %s", call->getCallId().data(), accountId.c_str()); - associateCallToAccount(call->getCallId(), accountId); + associateCallToAccount (call->getCallId(), accountId); - // If account is null it is an ip to ip call - if (accountId == AccountNULL) { - associateConfigToCall(call->getCallId(), Call::IPtoIP); - } - else { - // strip sip: which is not required and bring confusion with ip to ip calls - // when placing new call from history (if call is IAX, do nothing) - std::string peerNumber = call->getPeerNumber(); + // If account is null it is an ip to ip call + if (accountId == AccountNULL) { + associateConfigToCall (call->getCallId(), Call::IPtoIP); + } else { + // strip sip: which is not required and bring confusion with ip to ip calls + // when placing new call from history (if call is IAX, do nothing) + std::string peerNumber = call->getPeerNumber(); - int startIndex = peerNumber.find("sip:"); + int startIndex = peerNumber.find ("sip:"); - if (startIndex != (int) string::npos) { - std::string strippedPeerNumber = peerNumber.substr(startIndex + 4); - call->setPeerNumber(strippedPeerNumber); - } + if (startIndex != (int) string::npos) { + std::string strippedPeerNumber = peerNumber.substr (startIndex + 4); + call->setPeerNumber (strippedPeerNumber); + } - } + } - if (!hasCurrentCall()) { - _debug ("Manager: Has no current call"); + if (!hasCurrentCall()) { + _debug ("Manager: Has no current call"); - call->setConnectionState(Call::Ringing); - ringtone(accountId); + call->setConnectionState (Call::Ringing); + ringtone (accountId); - } - else { - _debug ("Manager: has current call"); - } + } else { + _debug ("Manager: has current call"); + } - addWaitingCall(call->getCallId()); + addWaitingCall (call->getCallId()); - from = call->getPeerName(); - number = call->getPeerNumber(); - display_name = call->getDisplayName(); + from = call->getPeerName(); + number = call->getPeerNumber(); + display_name = call->getDisplayName(); - if (from != "" && number != "") { - from.append(" <"); - from.append(number); - from.append(">"); - } else if (from.empty()) { - from.append("<"); - from.append(number); - from.append(">"); - } + if (from != "" && number != "") { + from.append (" <"); + from.append (number); + from.append (">"); + } else if (from.empty()) { + from.append ("<"); + from.append (number); + from.append (">"); + } - /* Broadcast a signal over DBus */ - _debug ("Manager: From: %s, Number: %s, Display Name: %s", from.c_str(), number.c_str(), display_name.c_str()); + /* Broadcast a signal over DBus */ + _debug ("Manager: From: %s, Number: %s, Display Name: %s", from.c_str(), number.c_str(), display_name.c_str()); - display = display_name; - display.append(" "); - display.append(from); + display = display_name; + display.append (" "); + display.append (from); - if (_dbus) - _dbus->getCallManager()->incomingCall(accountId, call->getCallId(), display.c_str()); + if (_dbus) + _dbus->getCallManager()->incomingCall (accountId, call->getCallId(), display.c_str()); - return true; + return true; } //THREAD=VoIP void ManagerImpl::incomingMessage (const AccountID& accountId, - const std::string& message) { - if (_dbus) { - _dbus->getCallManager()->incomingMessage(accountId, message); - } + const std::string& message) { + if (_dbus) { + _dbus->getCallManager()->incomingMessage (accountId, message); + } } //THREAD=VoIP CALL=Outgoing void ManagerImpl::peerAnsweredCall (const CallID& id) { - _debug ("Manager: Peer answered call %s", id.c_str()); + _debug ("Manager: Peer answered call %s", id.c_str()); - // The if statement is usefull only if we sent two calls at the same time. - if (isCurrentCall(id)) { - stopTone(); - } + // The if statement is usefull only if we sent two calls at the same time. + if (isCurrentCall (id)) { + stopTone(); + } - if (_dbus) - _dbus->getCallManager()->callStateChanged(id, "CURRENT"); + if (_dbus) + _dbus->getCallManager()->callStateChanged (id, "CURRENT"); - _audiodriver->flushMain(); + _audiodriver->flushMain(); - _audiodriver->flushUrgent(); + _audiodriver->flushUrgent(); } //THREAD=VoIP Call=Outgoing void ManagerImpl::peerRingingCall (const CallID& id) { - _debug ("Manager: Peer call %s ringing", id.c_str()); + _debug ("Manager: Peer call %s ringing", id.c_str()); - if (isCurrentCall(id)) { - ringback(); - } + if (isCurrentCall (id)) { + ringback(); + } - if (_dbus) - _dbus->getCallManager()->callStateChanged(id, "RINGING"); + if (_dbus) + _dbus->getCallManager()->callStateChanged (id, "RINGING"); } //THREAD=VoIP Call=Outgoing/Ingoing void ManagerImpl::peerHungupCall (const CallID& call_id) { - PulseLayer *pulselayer; - AccountID account_id; - bool returnValue; + PulseLayer *pulselayer; + AccountID account_id; + bool returnValue; - _debug ("Manager: Peer hungup call %s", call_id.c_str()); + _debug ("Manager: Peer hungup call %s", call_id.c_str()); - // store the current call id - CallID current_call_id = getCurrentCallId(); + // store the current call id + CallID current_call_id = getCurrentCallId(); - if (participToConference(call_id)) { + if (participToConference (call_id)) { - Conference *conf = getConferenceFromCallID(call_id); + Conference *conf = getConferenceFromCallID (call_id); - if (conf != NULL) { + if (conf != NULL) { - removeParticipant(call_id); - processRemainingParticipant(current_call_id, conf); + removeParticipant (call_id); + processRemainingParticipant (current_call_id, conf); - } - } else { - if (isCurrentCall(call_id)) { - stopTone(); + } + } else { + if (isCurrentCall (call_id)) { + stopTone(); - switchCall(""); - } - } + switchCall (""); + } + } - /* Direct IP to IP call */ - if (getConfigFromCall(call_id) == Call::IPtoIP) { - SIPVoIPLink::instance(AccountNULL)->hangup(call_id); - } + /* Direct IP to IP call */ + if (getConfigFromCall (call_id) == Call::IPtoIP) { + SIPVoIPLink::instance (AccountNULL)->hangup (call_id); + } - else { + else { - account_id = getAccountFromCall(call_id); + account_id = getAccountFromCall (call_id); - returnValue = getAccountLink(account_id)->peerHungup(call_id); - } + returnValue = getAccountLink (account_id)->peerHungup (call_id); + } - /* Broadcast a signal over DBus */ - if (_dbus) - _dbus->getCallManager()->callStateChanged(call_id, "HUNGUP"); + /* Broadcast a signal over DBus */ + if (_dbus) + _dbus->getCallManager()->callStateChanged (call_id, "HUNGUP"); - removeWaitingCall(call_id); + removeWaitingCall (call_id); - removeCallAccount(call_id); + removeCallAccount (call_id); - int nbCalls = getCallList().size(); + int nbCalls = getCallList().size(); - // stop streams + // stop streams - if (nbCalls <= 0) { - _debug ("Manager: Stop audio stream, ther is only %i call(s) remaining", nbCalls); + if (nbCalls <= 0) { + _debug ("Manager: Stop audio stream, ther is only %i call(s) remaining", nbCalls); - AudioLayer* audiolayer = getAudioDriver(); - audiolayer->stopStream(); - } + AudioLayer* audiolayer = getAudioDriver(); + audiolayer->stopStream(); + } - if (_audiodriver->getLayerType() == PULSEAUDIO) { - pulselayer = dynamic_cast<PulseLayer *> (getAudioDriver()); - } + if (_audiodriver->getLayerType() == PULSEAUDIO) { + pulselayer = dynamic_cast<PulseLayer *> (getAudioDriver()); + } } //THREAD=VoIP void ManagerImpl::callBusy (const CallID& id) { - _debug ("Manager: Call %s busy", id.c_str()); + _debug ("Manager: Call %s busy", id.c_str()); - if (_dbus) - _dbus->getCallManager()->callStateChanged(id, "BUSY"); + if (_dbus) + _dbus->getCallManager()->callStateChanged (id, "BUSY"); - if (isCurrentCall(id)) { - playATone(Tone::TONE_BUSY); - switchCall(""); - } + if (isCurrentCall (id)) { + playATone (Tone::TONE_BUSY); + switchCall (""); + } - removeCallAccount(id); + removeCallAccount (id); - removeWaitingCall(id); + removeWaitingCall (id); } //THREAD=VoIP void ManagerImpl::callFailure (const CallID& call_id) { - if (_dbus) - _dbus->getCallManager()->callStateChanged(call_id, "FAILURE"); + if (_dbus) + _dbus->getCallManager()->callStateChanged (call_id, "FAILURE"); - if (isCurrentCall(call_id)) { - playATone(Tone::TONE_BUSY); - switchCall(""); - } + if (isCurrentCall (call_id)) { + playATone (Tone::TONE_BUSY); + switchCall (""); + } - CallID current_call_id = getCurrentCallId(); + CallID current_call_id = getCurrentCallId(); - if (participToConference(call_id)) { + if (participToConference (call_id)) { - _debug ("Manager: Call %s participating to a conference failed", call_id.c_str()); + _debug ("Manager: Call %s participating to a conference failed", call_id.c_str()); - Conference *conf = getConferenceFromCallID(call_id); + Conference *conf = getConferenceFromCallID (call_id); - if (conf != NULL) { - // remove this participant - removeParticipant(call_id); + if (conf != NULL) { + // remove this participant + removeParticipant (call_id); - processRemainingParticipant(current_call_id, conf); - } + processRemainingParticipant (current_call_id, conf); + } - } + } - removeCallAccount(call_id); + removeCallAccount (call_id); - removeWaitingCall(call_id); + removeWaitingCall (call_id); } //THREAD=VoIP void ManagerImpl::startVoiceMessageNotification (const AccountID& accountId, - int nb_msg) { - if (_dbus) - _dbus->getCallManager()->voiceMailNotify(accountId, nb_msg); + int nb_msg) { + if (_dbus) + _dbus->getCallManager()->voiceMailNotify (accountId, nb_msg); } void ManagerImpl::connectionStatusNotification () { - - _debug("Manager: connectionStatusNotification"); - if (_dbus != NULL) { - _dbus->getConfigurationManager()->accountsChanged(); - } + _debug ("Manager: connectionStatusNotification"); + + if (_dbus != NULL) { + _dbus->getConfigurationManager()->accountsChanged(); + } } /** @@ -1825,198 +1828,198 @@ void ManagerImpl::connectionStatusNotification () { */ bool ManagerImpl::playATone (Tone::TONEID toneId) { - bool hasToPlayTone; - AudioLayer *audiolayer; + bool hasToPlayTone; + AudioLayer *audiolayer; - // _debug ("Manager: Play tone %d", toneId); + // _debug ("Manager: Play tone %d", toneId); - hasToPlayTone = voipPreferences.getPlayTones(); + hasToPlayTone = voipPreferences.getPlayTones(); - if (!hasToPlayTone) - return false; + if (!hasToPlayTone) + return false; - audiolayer = getAudioDriver(); + audiolayer = getAudioDriver(); - if (audiolayer) { + if (audiolayer) { - audiolayer->flushUrgent(); - audiolayer->startStream(); - } + audiolayer->flushUrgent(); + audiolayer->startStream(); + } - if (_telephoneTone != 0) { - _toneMutex.enterMutex(); - _telephoneTone->setCurrentTone(toneId); - _toneMutex.leaveMutex(); - } + if (_telephoneTone != 0) { + _toneMutex.enterMutex(); + _telephoneTone->setCurrentTone (toneId); + _toneMutex.leaveMutex(); + } - return true; + return true; } /** * Multi Thread */ void ManagerImpl::stopTone () { - bool hasToPlayTone; + bool hasToPlayTone; - hasToPlayTone = voipPreferences.getPlayTones(); + hasToPlayTone = voipPreferences.getPlayTones(); - if (!hasToPlayTone) - return; + if (!hasToPlayTone) + return; - _toneMutex.enterMutex(); + _toneMutex.enterMutex(); - if (_telephoneTone != 0) { - _telephoneTone->setCurrentTone(Tone::TONE_NULL); - } + if (_telephoneTone != 0) { + _telephoneTone->setCurrentTone (Tone::TONE_NULL); + } - _audiofile.stop(); - _toneMutex.leaveMutex(); + _audiofile.stop(); + _toneMutex.leaveMutex(); } /** * Multi Thread */ bool ManagerImpl::playTone () { - playATone(Tone::TONE_DIALTONE); - return true; + playATone (Tone::TONE_DIALTONE); + return true; } /** * Multi Thread */ bool ManagerImpl::playToneWithMessage () { - playATone(Tone::TONE_CONGESTION); - return true; + playATone (Tone::TONE_CONGESTION); + return true; } /** * Multi Thread */ void ManagerImpl::congestion () { - playATone(Tone::TONE_CONGESTION); + playATone (Tone::TONE_CONGESTION); } /** * Multi Thread */ void ManagerImpl::ringback () { - playATone(Tone::TONE_RINGTONE); + playATone (Tone::TONE_RINGTONE); } /** * Multi Thread */ void ManagerImpl::ringtone (const AccountID& accountID) { - std::string ringchoice; - AudioLayer *audiolayer; - AudioCodec *codecForTone; - int layer, samplerate; - bool loadFile; + std::string ringchoice; + AudioLayer *audiolayer; + AudioCodec *codecForTone; + int layer, samplerate; + bool loadFile; - _debug("Manager: Ringtone"); + _debug ("Manager: Ringtone"); - Account *account = getAccount(accountID); + Account *account = getAccount (accountID); - if(!account) { - _warn("Manager: Warning: invalid account in ringtone"); - return; - } + if (!account) { + _warn ("Manager: Warning: invalid account in ringtone"); + return; + } - if (account->getRingtoneEnabled()) { + if (account->getRingtoneEnabled()) { - _debug ("Manager: Tone is enabled"); - //TODO Comment this because it makes the daemon crashes since the main thread - //synchronizes the ringtone thread. + _debug ("Manager: Tone is enabled"); + //TODO Comment this because it makes the daemon crashes since the main thread + //synchronizes the ringtone thread. - ringchoice = account->getRingtonePath(); - //if there is no / inside the path + ringchoice = account->getRingtonePath(); + //if there is no / inside the path - 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; - } + 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; + } - audiolayer = getAudioDriver(); + audiolayer = getAudioDriver(); - if (!audiolayer) { - _error("Manager: Error: no audio layer in ringtone"); - return; - } + if (!audiolayer) { + _error ("Manager: Error: no audio layer in ringtone"); + return; + } - layer = audiolayer->getLayerType(); + layer = audiolayer->getLayerType(); - samplerate = audiolayer->getSampleRate(); + samplerate = audiolayer->getSampleRate(); - codecForTone = _codecDescriptorMap.getFirstCodecAvailable(); + codecForTone = _codecDescriptorMap.getFirstCodecAvailable(); - _toneMutex.enterMutex(); + _toneMutex.enterMutex(); - loadFile = _audiofile.loadFile(ringchoice, codecForTone, samplerate); + loadFile = _audiofile.loadFile (ringchoice, codecForTone, samplerate); - _toneMutex.leaveMutex(); + _toneMutex.leaveMutex(); - if (loadFile) { + if (loadFile) { - _toneMutex.enterMutex(); - _audiofile.start(); - _toneMutex.leaveMutex(); + _toneMutex.enterMutex(); + _audiofile.start(); + _toneMutex.leaveMutex(); - // start audio if not started AND flush all buffers (main and urgent) - audiolayer->startStream(); + // start audio if not started AND flush all buffers (main and urgent) + audiolayer->startStream(); - } else { - ringback(); - } + } else { + ringback(); + } - } else { - ringback(); - } + } else { + ringback(); + } } AudioLoop* ManagerImpl::getTelephoneTone () { - // _debug("ManagerImpl::getTelephoneTone()"); - if (_telephoneTone != 0) { - ost::MutexLock m(_toneMutex); - return _telephoneTone->getCurrentTone(); - } else { - return 0; - } + // _debug("ManagerImpl::getTelephoneTone()"); + if (_telephoneTone != 0) { + ost::MutexLock m (_toneMutex); + return _telephoneTone->getCurrentTone(); + } else { + return 0; + } } AudioLoop* ManagerImpl::getTelephoneFile () { - // _debug("ManagerImpl::getTelephoneFile()"); - ost::MutexLock m(_toneMutex); + // _debug("ManagerImpl::getTelephoneFile()"); + ost::MutexLock m (_toneMutex); - if (_audiofile.isStarted()) { - return &_audiofile; - } else { - return 0; - } + if (_audiofile.isStarted()) { + return &_audiofile; + } else { + return 0; + } } void ManagerImpl::notificationIncomingCall (void) { - AudioLayer *audiolayer; - std::ostringstream frequency; - unsigned int samplerate, nbSampling; - - audiolayer = getAudioDriver(); - - _debug ("ManagerImpl::notificationIncomingCall"); - - if (audiolayer != 0) { - samplerate = audiolayer->getSampleRate(); - frequency << "440/" << 160; - Tone tone(frequency.str(), samplerate); - nbSampling = tone.getSize(); - SFLDataFormat buf[nbSampling]; - tone.getNext(buf, tone.getSize()); - /* Put the data in the urgent ring buffer */ - audiolayer->flushUrgent(); - audiolayer->putUrgent(buf, sizeof(SFLDataFormat) * nbSampling); - } + AudioLayer *audiolayer; + std::ostringstream frequency; + unsigned int samplerate, nbSampling; + + audiolayer = getAudioDriver(); + + _debug ("ManagerImpl::notificationIncomingCall"); + + if (audiolayer != 0) { + samplerate = audiolayer->getSampleRate(); + frequency << "440/" << 160; + Tone tone (frequency.str(), samplerate); + nbSampling = tone.getSize(); + SFLDataFormat buf[nbSampling]; + tone.getNext (buf, tone.getSize()); + /* Put the data in the urgent ring buffer */ + audiolayer->flushUrgent(); + audiolayer->putUrgent (buf, sizeof (SFLDataFormat) * nbSampling); + } } /////////////////////////////////////////////////////////////////////////////// @@ -2029,31 +2032,31 @@ void ManagerImpl::notificationIncomingCall (void) { */ int ManagerImpl::createSettingsPath (void) { - std::string xdg_config, xdg_env; + std::string xdg_config, xdg_env; - _debug ("XDG_CONFIG_HOME: %s", XDG_CONFIG_HOME); + _debug ("XDG_CONFIG_HOME: %s", XDG_CONFIG_HOME); - xdg_config = std::string(HOMEDIR) + DIR_SEPARATOR_STR + ".config" - + DIR_SEPARATOR_STR + PROGDIR; + xdg_config = std::string (HOMEDIR) + DIR_SEPARATOR_STR + ".config" + + DIR_SEPARATOR_STR + PROGDIR; - if (XDG_CONFIG_HOME != NULL) { - xdg_env = std::string(XDG_CONFIG_HOME); - (xdg_env.length() > 0) ? _path = xdg_env : _path = xdg_config; - } else - _path = xdg_config; + if (XDG_CONFIG_HOME != NULL) { + xdg_env = std::string (XDG_CONFIG_HOME); + (xdg_env.length() > 0) ? _path = xdg_env : _path = xdg_config; + } else + _path = xdg_config; - if (mkdir(_path.data(), 0700) != 0) { - // If directory creation failed - if (errno != EEXIST) { - _debug ("Cannot create directory: %s", strerror (errno)); - return -1; - } - } + if (mkdir (_path.data(), 0700) != 0) { + // If directory creation failed + if (errno != EEXIST) { + _debug ("Cannot create directory: %s", strerror (errno)); + return -1; + } + } - // Load user's configuration - _path = _path + DIR_SEPARATOR_STR + PROGNAME + ".yml"; + // Load user's configuration + _path = _path + DIR_SEPARATOR_STR + PROGNAME + ".yml"; - return 1; + return 1; } /** @@ -2061,99 +2064,99 @@ int ManagerImpl::createSettingsPath (void) { */ void ManagerImpl::initConfigFile (bool load_user_value, std::string alternate) { - _debug ("Manager: Init config file"); + _debug ("Manager: Init config file"); - // Init display name to the username under which - // this sflphone instance is running. - uid_t uid = getuid(); + // Init display name to the username under which + // this sflphone instance is running. + uid_t uid = getuid(); - struct passwd * user_info = NULL; - user_info = getpwuid(uid); + struct passwd * user_info = NULL; + user_info = getpwuid (uid); - std::string path; - // Loads config from ~/.sflphone/sflphoned.yml or so.. + std::string path; + // Loads config from ~/.sflphone/sflphoned.yml or so.. - if (createSettingsPath() == 1 && load_user_value) { + if (createSettingsPath() == 1 && load_user_value) { - (alternate == "") ? path = _path : path = alternate; - std::cout << path << std::endl; - _exist = _config.populateFromFile(path); - } - _debug("Manager: configuration file path: %s", path.c_str()); - + (alternate == "") ? path = _path : path = alternate; + std::cout << path << std::endl; + _exist = _config.populateFromFile (path); + } - bool fileExist = true; - bool out = false; - - if (path.empty()) { - _error("Manager: Error: XDG config file path is empty!"); - fileExist = false; - } + _debug ("Manager: configuration file path: %s", path.c_str()); + + + bool fileExist = true; + bool out = false; + + if (path.empty()) { + _error ("Manager: Error: XDG config file path is empty!"); + fileExist = false; + } - std::fstream file; + std::fstream file; - file.open (path.data(), std::fstream::in); + file.open (path.data(), std::fstream::in); - if (!file.is_open()) { + if (!file.is_open()) { - _debug("Manager: File %s not opened, create new one", path.c_str()); - file.open (path.data(), std::fstream::out); - out = true; + _debug ("Manager: File %s not opened, create new one", path.c_str()); + file.open (path.data(), std::fstream::out); + out = true; - if (!file.is_open()) { - _error("Manager: Error: could not create empty configurationfile!"); + if (!file.is_open()) { + _error ("Manager: Error: could not create empty configurationfile!"); fileExist = false; - } - - file.close(); - - fileExist = false; - } - - // get length of file: - file.seekg (0, std::ios::end); - int length = file.tellg(); - - file.seekg (0, std::ios::beg); - - if (length <= 0) { - _debug("Manager: Configuration file length is empty", length); - file.close(); - fileExist = false; // should load config - } - - if(fileExist) { - try { - - // parser = new Conf::YamlParser("sequenceParser.yml"); - parser = new Conf::YamlParser(_path.c_str()); - - parser->serializeEvents(); - - parser->composeEvents(); - - parser->constructNativeData(); - - _setupLoaded = true; - - _debug("Manager: Configuration file parsed successfully"); - } - catch (Conf::YamlParserException &e) { - _error("Manager: %s", e.what()); - } - } + } + + file.close(); + + fileExist = false; + } + + // get length of file: + file.seekg (0, std::ios::end); + int length = file.tellg(); + + file.seekg (0, std::ios::beg); + + if (length <= 0) { + _debug ("Manager: Configuration file length is empty", length); + file.close(); + fileExist = false; // should load config + } + + if (fileExist) { + try { + + // parser = new Conf::YamlParser("sequenceParser.yml"); + parser = new Conf::YamlParser (_path.c_str()); + + parser->serializeEvents(); + + parser->composeEvents(); + + parser->constructNativeData(); + + _setupLoaded = true; + + _debug ("Manager: Configuration file parsed successfully"); + } catch (Conf::YamlParserException &e) { + _error ("Manager: %s", e.what()); + } + } } /** * Initialization: Main Thread */ void ManagerImpl::initAudioCodec (void) { - _info("Manager: Init audio codecs"); + _info ("Manager: Init audio codecs"); - /* Init list of all supported codecs by the application. - * This is a global list. Every account will inherit it. - */ - _codecDescriptorMap.init(); + /* Init list of all supported codecs by the application. + * This is a global list. Every account will inherit it. + */ + _codecDescriptorMap.init(); } /* @@ -2161,71 +2164,71 @@ void ManagerImpl::initAudioCodec (void) { */ std::vector<std::string> ManagerImpl::retrieveActiveCodecs () { - // This property is now set per account basis so we should remove it... - std::string s = ""; - _info("Manager: Retrieve active codecs: %s", s.c_str ()); - return unserialize(s); + // This property is now set per account basis so we should remove it... + std::string s = ""; + _info ("Manager: Retrieve active codecs: %s", s.c_str ()); + return unserialize (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) { - unsigned int i; - std::string res; + unsigned int i; + std::string res; - for (i = 0; i < v.size(); i++) { - res += v[i] + "/"; - } + for (i = 0; i < v.size(); i++) { + res += v[i] + "/"; + } - return res; + return res; } std::string ManagerImpl::getCurrentCodecName (const CallID& id) { - AccountID accountid = getAccountFromCall(id); - VoIPLink* link = getAccountLink(accountid); - Call* call = link->getCall(id); + AccountID accountid = getAccountFromCall (id); + VoIPLink* link = getAccountLink (accountid); + Call* call = link->getCall (id); - if (!call) - return ""; + if (!call) + return ""; - if (call->getState() != Call::Active) - return ""; - else - return link->getCurrentCodecName(); + if (call->getState() != Call::Active) + return ""; + else + return link->getCurrentCodecName(); } /** * 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"); - _audiodriver -> setErrorMessage(-1); - _audiodriver -> openDevice(_audiodriver->getIndexIn(), _audiodriver->getIndexOut(), - _audiodriver->getIndexRing(), _audiodriver -> getSampleRate(), - _audiodriver -> getFrameSize(), SFL_PCM_CAPTURE, audioPlugin); - - if (_audiodriver -> getErrorMessage() != -1) - notifyErrClient(_audiodriver -> getErrorMessage()); - } else { - } + int layer = _audiodriver -> getLayerType(); + + if (CHECK_INTERFACE (layer , ALSA)) { + _debug ("Set input audio plugin"); + _audiodriver -> setErrorMessage (-1); + _audiodriver -> openDevice (_audiodriver->getIndexIn(), _audiodriver->getIndexOut(), + _audiodriver->getIndexRing(), _audiodriver -> getSampleRate(), + _audiodriver -> getFrameSize(), SFL_PCM_CAPTURE, audioPlugin); + + if (_audiodriver -> getErrorMessage() != -1) + notifyErrClient (_audiodriver -> getErrorMessage()); + } else { + } } @@ -2234,88 +2237,89 @@ void ManagerImpl::setInputAudioPlugin (const std::string& audioPlugin) { */ void ManagerImpl::setOutputAudioPlugin (const std::string& audioPlugin) { - int res; + int res; - _debug ("Manager: Set output audio plugin"); - _audiodriver -> setErrorMessage(-1); - res = _audiodriver -> openDevice(_audiodriver->getIndexIn(), _audiodriver->getIndexOut(), - _audiodriver->getIndexRing(), _audiodriver -> getSampleRate(), - _audiodriver -> getFrameSize(), SFL_PCM_BOTH, audioPlugin); + _debug ("Manager: Set output audio plugin"); + _audiodriver -> setErrorMessage (-1); + res = _audiodriver -> openDevice (_audiodriver->getIndexIn(), _audiodriver->getIndexOut(), + _audiodriver->getIndexRing(), _audiodriver -> getSampleRate(), + _audiodriver -> getFrameSize(), SFL_PCM_BOTH, audioPlugin); + + if (_audiodriver -> getErrorMessage() != -1) + notifyErrClient (_audiodriver -> getErrorMessage()); - if (_audiodriver -> getErrorMessage() != -1) - notifyErrClient(_audiodriver -> getErrorMessage()); + // set config + if (res) + audioPreference.setPlugin (audioPlugin); - // set config - if (res) - audioPreference.setPlugin(audioPlugin); - //setConig(AUDIO, ALSA_PLUGIN, audioPlugin); + //setConig(AUDIO, ALSA_PLUGIN, audioPlugin); } /** * Get list of supported audio output device */ std::vector<std::string> ManagerImpl::getAudioOutputDeviceList (void) { - _debug ("Manager: Get audio output device list"); - AlsaLayer *layer; - std::vector<std::string> devices; + _debug ("Manager: Get audio output device list"); + AlsaLayer *layer; + std::vector<std::string> devices; - layer = dynamic_cast<AlsaLayer*> (getAudioDriver()); + layer = dynamic_cast<AlsaLayer*> (getAudioDriver()); - if (layer) - devices = layer -> getSoundCardsInfo(SFL_PCM_PLAYBACK); + if (layer) + devices = layer -> getSoundCardsInfo (SFL_PCM_PLAYBACK); - return devices; + return devices; } /** * Set audio output device */ void ManagerImpl::setAudioDevice (const int index, int streamType) { - + AlsaLayer *alsalayer = NULL; std::string alsaplugin; _debug ("Manager: Set audio device: %i", index); - _audiodriver -> setErrorMessage(-1); + _audiodriver -> setErrorMessage (-1); - if(!(alsalayer = dynamic_cast<AlsaLayer*> (getAudioDriver()))) { - _warn("Manager: Error: No audio driver"); - return; + if (! (alsalayer = dynamic_cast<AlsaLayer*> (getAudioDriver()))) { + _warn ("Manager: Error: No audio driver"); + return; } - + alsaplugin = alsalayer->getAudioPlugin(); _debug ("Manager: Set ALSA plugin: %s", alsaplugin.c_str()); - switch(streamType) { - case SFL_PCM_PLAYBACK: - _debug("Manager: Set output device"); - _audiodriver->openDevice(_audiodriver->getIndexIn(), index, _audiodriver->getIndexRing(), - _audiodriver->getSampleRate(), _audiodriver->getFrameSize(), - SFL_PCM_PLAYBACK, alsaplugin); - audioPreference.setCardout(index); - break; - case SFL_PCM_CAPTURE: - _debug("Manager: Set input device"); - _audiodriver->openDevice(index, _audiodriver->getIndexOut(), _audiodriver->getIndexRing(), - _audiodriver->getSampleRate(), _audiodriver->getFrameSize(), - SFL_PCM_CAPTURE, alsaplugin); - audioPreference.setCardin(index); - break; - case SFL_PCM_RINGTONE: - _debug("Manager: Set ringtone device"); - _audiodriver->openDevice(_audiodriver->getIndexOut(), _audiodriver->getIndexOut(), index, - _audiodriver->getSampleRate(), _audiodriver->getFrameSize(), - SFL_PCM_RINGTONE, alsaplugin); - audioPreference.setCardring(index); - break; - default: - _warn("Unknown stream type"); + switch (streamType) { + case SFL_PCM_PLAYBACK: + _debug ("Manager: Set output device"); + _audiodriver->openDevice (_audiodriver->getIndexIn(), index, _audiodriver->getIndexRing(), + _audiodriver->getSampleRate(), _audiodriver->getFrameSize(), + SFL_PCM_PLAYBACK, alsaplugin); + audioPreference.setCardout (index); + break; + case SFL_PCM_CAPTURE: + _debug ("Manager: Set input device"); + _audiodriver->openDevice (index, _audiodriver->getIndexOut(), _audiodriver->getIndexRing(), + _audiodriver->getSampleRate(), _audiodriver->getFrameSize(), + SFL_PCM_CAPTURE, alsaplugin); + audioPreference.setCardin (index); + break; + case SFL_PCM_RINGTONE: + _debug ("Manager: Set ringtone device"); + _audiodriver->openDevice (_audiodriver->getIndexOut(), _audiodriver->getIndexOut(), index, + _audiodriver->getSampleRate(), _audiodriver->getFrameSize(), + SFL_PCM_RINGTONE, alsaplugin); + audioPreference.setCardring (index); + break; + default: + _warn ("Unknown stream type"); } if (_audiodriver -> getErrorMessage() != -1) - notifyErrClient(_audiodriver -> getErrorMessage()); + notifyErrClient (_audiodriver -> getErrorMessage()); } @@ -2323,273 +2327,275 @@ void ManagerImpl::setAudioDevice (const int index, int streamType) { * Get list of supported audio input device */ std::vector<std::string> ManagerImpl::getAudioInputDeviceList (void) { - AlsaLayer *audiolayer; - std::vector<std::string> devices; + AlsaLayer *audiolayer; + std::vector<std::string> devices; - audiolayer = dynamic_cast<AlsaLayer *> (getAudioDriver()); + audiolayer = dynamic_cast<AlsaLayer *> (getAudioDriver()); - if (audiolayer) - devices = audiolayer->getSoundCardsInfo(SFL_PCM_CAPTURE); + if (audiolayer) + devices = audiolayer->getSoundCardsInfo (SFL_PCM_CAPTURE); - return devices; + return devices; } /** * Get string array representing integer indexes of output and input device */ std::vector<std::string> ManagerImpl::getCurrentAudioDevicesIndex () { - _debug ("Get current audio devices index"); - std::vector<std::string> v; - std::stringstream ssi, sso, ssr; - sso << _audiodriver->getIndexOut(); - v.push_back(sso.str()); - ssi << _audiodriver->getIndexIn(); - v.push_back(ssi.str()); - ssr << _audiodriver->getIndexRing(); - v.push_back(ssr.str()); - return v; + _debug ("Get current audio devices index"); + std::vector<std::string> v; + std::stringstream ssi, sso, ssr; + sso << _audiodriver->getIndexOut(); + v.push_back (sso.str()); + ssi << _audiodriver->getIndexIn(); + v.push_back (ssi.str()); + ssr << _audiodriver->getIndexRing(); + v.push_back (ssr.str()); + return v; } int ManagerImpl::isIax2Enabled (void) { #ifdef USE_IAX - return true; + return true; #else - return false; + return false; #endif } int ManagerImpl::isRingtoneEnabled (const AccountID& id) { - Account *account = getAccount(id); + Account *account = getAccount (id); - if(!account) { - _warn("Manager: Warning: invalid account in ringtone enabled"); - return 0; - } + if (!account) { + _warn ("Manager: Warning: invalid account in ringtone enabled"); + return 0; + } - return account->getRingtoneEnabled() ? 1 : 0; + return account->getRingtoneEnabled() ? 1 : 0; } void ManagerImpl::ringtoneEnabled (const AccountID& id) { - Account *account = getAccount(id); + Account *account = getAccount (id); - if(!account) { - _warn("Manager: Warning: invalid account in ringtone enabled"); - return; - } + if (!account) { + _warn ("Manager: Warning: invalid account in ringtone enabled"); + return; + } + + account->getRingtoneEnabled() ? account->setRingtoneEnabled (false) : account->setRingtoneEnabled (true); - account->getRingtoneEnabled() ? account->setRingtoneEnabled(false) : account->setRingtoneEnabled(true); - } std::string ManagerImpl::getRingtoneChoice (const AccountID& id) { - - // retreive specified account id - Account *account = getAccount(id); - if(!account) { - _warn("Manager: Warning: Not a valid account ID for ringone choice"); - return std::string(""); - } + // retreive specified account id + Account *account = getAccount (id); - // we need the absolute path - std::string tone_name = account->getRingtonePath(); - std::string tone_path; + if (!account) { + _warn ("Manager: Warning: Not a valid account ID for ringone choice"); + return std::string (""); + } - 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; - } + // we need the absolute path + std::string tone_name = account->getRingtonePath(); + 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 ("Manager: get ringtone path %s", tone_path.c_str()); + _debug ("Manager: get ringtone path %s", tone_path.c_str()); - return tone_path; + return tone_path; } void ManagerImpl::setRingtoneChoice (const std::string& tone, const AccountID& id) { - _debug("Manager: Set ringtone path %s to account", tone.c_str()); + _debug ("Manager: Set ringtone path %s to account", tone.c_str()); - // retreive specified account id - Account *account = getAccount(id); + // retreive specified account id + Account *account = getAccount (id); - if(!account) { - _warn("Manager: Warning: Not a valid account ID for ringtone choice"); - return; - } + if (!account) { + _warn ("Manager: Warning: Not a valid account ID for ringtone choice"); + return; + } - // we save the absolute path - account->setRingtonePath(tone); + // we save the absolute path + account->setRingtonePath (tone); } std::string ManagerImpl::getRecordPath (void) { - return audioPreference.getRecordpath(); + return audioPreference.getRecordpath(); } void ManagerImpl::setRecordPath (const std::string& recPath) { - _debug ("Manager: Set record path %s", recPath.c_str()); - audioPreference.setRecordpath(recPath); + _debug ("Manager: Set record path %s", recPath.c_str()); + audioPreference.setRecordpath (recPath); } bool ManagerImpl::getMd5CredentialHashing (void) { - return preferences.getMd5Hash(); + return preferences.getMd5Hash(); } void ManagerImpl::setRecordingCall (const CallID& id) { - Recordable* rec; - if(!isConference(id)) { - AccountID accountid = getAccountFromCall(id); - rec = (Recordable *) getAccountLink(accountid)->getCall(id); - } - else { - ConferenceMap::iterator it = _conferencemap.find(id); - rec = (Recordable *)it->second; - } + Recordable* rec; + + if (!isConference (id)) { + AccountID accountid = getAccountFromCall (id); + rec = (Recordable *) getAccountLink (accountid)->getCall (id); + } else { + ConferenceMap::iterator it = _conferencemap.find (id); + rec = (Recordable *) it->second; + } - rec->setRecording(); + rec->setRecording(); } bool ManagerImpl::isRecording (const CallID& id) { - AccountID accountid = getAccountFromCall(id); - Recordable* rec = (Recordable*) getAccountLink(accountid)->getCall(id); + AccountID accountid = getAccountFromCall (id); + Recordable* rec = (Recordable*) getAccountLink (accountid)->getCall (id); - return rec->isRecording(); + return rec->isRecording(); } void ManagerImpl::setHistoryLimit (const int& days) { - preferences.setHistoryLimit(days); + preferences.setHistoryLimit (days); } int ManagerImpl::getHistoryLimit (void) { - return preferences.getHistoryLimit(); + return preferences.getHistoryLimit(); } int32_t ManagerImpl::getMailNotify (void) { - return preferences.getNotifyMails(); + return preferences.getNotifyMails(); } void ManagerImpl::setMailNotify (void) { - preferences.getNotifyMails() ? preferences.setNotifyMails(true) : preferences.setNotifyMails(false); + preferences.getNotifyMails() ? preferences.setNotifyMails (true) : preferences.setNotifyMails (false); } void ManagerImpl::setAudioManager (const int32_t& api) { - int type; - std::string alsaPlugin; + int type; + std::string alsaPlugin; - _debug ("Setting audio manager "); + _debug ("Setting audio manager "); - if (!_audiodriver) - return; + if (!_audiodriver) + return; - type = _audiodriver->getLayerType(); + type = _audiodriver->getLayerType(); - if (type == api) { - _debug ("Audio manager chosen already in use. No changes made. "); - return; - } + if (type == api) { + _debug ("Audio manager chosen already in use. No changes made. "); + return; + } - preferences.setAudioApi(api); + preferences.setAudioApi (api); - switchAudioManager(); - return; + switchAudioManager(); + return; } int32_t ManagerImpl::getAudioManager (void) { - return preferences.getAudioApi(); + return preferences.getAudioApi(); } void ManagerImpl::notifyErrClient (const int32_t& errCode) { - if (_dbus) { - _debug ("NOTIFY ERR NUMBER %i" , errCode); - _dbus -> getConfigurationManager() -> errorAlert(errCode); - } + if (_dbus) { + _debug ("NOTIFY ERR NUMBER %i" , errCode); + _dbus -> getConfigurationManager() -> errorAlert (errCode); + } } int ManagerImpl::getAudioDeviceIndex (const std::string name) { - AlsaLayer *alsalayer; + AlsaLayer *alsalayer; - _debug ("Get audio device index"); + _debug ("Get audio device index"); - alsalayer = dynamic_cast<AlsaLayer *> (getAudioDriver()); + alsalayer = dynamic_cast<AlsaLayer *> (getAudioDriver()); - if (alsalayer) - return alsalayer -> soundCardGetIndex(name); - else - return 0; + if (alsalayer) + return alsalayer -> soundCardGetIndex (name); + else + return 0; } std::string ManagerImpl::getCurrentAudioOutputPlugin (void) { - AlsaLayer *alsalayer; + AlsaLayer *alsalayer; - _debug ("Get alsa plugin"); + _debug ("Get alsa plugin"); - alsalayer = dynamic_cast<AlsaLayer *> (getAudioDriver()); + alsalayer = dynamic_cast<AlsaLayer *> (getAudioDriver()); - if (alsalayer) - return alsalayer -> getAudioPlugin(); - else - return audioPreference.getPlugin(); + if (alsalayer) + return alsalayer -> getAudioPlugin(); + else + return audioPreference.getPlugin(); } -std::string ManagerImpl::getEchoCancelState(void) { +std::string ManagerImpl::getEchoCancelState (void) { // echo canceller is disabled by default bool isEnabled = false; - if(_audiodriver) { + if (_audiodriver) { isEnabled = _audiodriver->getEchoCancelState(); } - std::string state(""); - if(isEnabled) - state = "enabled"; + std::string state (""); + + if (isEnabled) + state = "enabled"; else - state = "disabled"; + state = "disabled"; return state; } -void ManagerImpl::setEchoCancelState(std::string state) { - _debug("Manager: Set echo suppress state: %s", state.c_str()); +void ManagerImpl::setEchoCancelState (std::string state) { + _debug ("Manager: Set echo suppress state: %s", state.c_str()); bool isEnabled = false; - if(state.compare("enabled") == 0) + if (state.compare ("enabled") == 0) isEnabled = true; else isEnabled = false; - if(_audiodriver) { - _audiodriver->setEchoCancelState(isEnabled); + if (_audiodriver) { + _audiodriver->setEchoCancelState (isEnabled); } } -std::string ManagerImpl::getNoiseSuppressState(void) { - +std::string ManagerImpl::getNoiseSuppressState (void) { + // noise suppress disabled by default bool isEnabled = false; - if(_audiodriver) { + if (_audiodriver) { isEnabled = _audiodriver->getNoiseSuppressState(); } - std::string state(""); - if(isEnabled) + std::string state (""); + + if (isEnabled) state = "enabled"; else state = "disabled"; @@ -2597,26 +2603,26 @@ std::string ManagerImpl::getNoiseSuppressState(void) { return state; } -void ManagerImpl::setNoiseSuppressState(std::string state) { - _debug("Manager: Set noise suppress state: %s", state.c_str()); +void ManagerImpl::setNoiseSuppressState (std::string state) { + _debug ("Manager: Set noise suppress state: %s", state.c_str()); bool isEnabled = false; - if(state.compare("enabled") == 0) - isEnabled = true; + if (state.compare ("enabled") == 0) + isEnabled = true; else - isEnabled = false; + isEnabled = false; - if(_audiodriver) { - _audiodriver->setNoiseSuppressState(isEnabled); + if (_audiodriver) { + _audiodriver->setNoiseSuppressState (isEnabled); } } int ManagerImpl::app_is_running (std::string process) { - std::ostringstream cmd; + std::ostringstream cmd; - cmd << "ps -C " << process; - return system(cmd.str().c_str()); + cmd << "ps -C " << process; + return system (cmd.str().c_str()); } /** @@ -2624,39 +2630,38 @@ int ManagerImpl::app_is_running (std::string process) { */ bool ManagerImpl::initAudioDriver (void) { - int error; - - _debugInit ("AudioLayer Creation"); - - if (preferences.getAudioApi() == ALSA) { - _audiodriver = new AlsaLayer(this); - _audiodriver->setMainBuffer(&_mainBuffer); - } - else if(preferences.getAudioApi() == PULSEAUDIO) { - if (app_is_running("pulseaudio") == 0) { - _audiodriver = new PulseLayer(this); - _audiodriver->setMainBuffer(&_mainBuffer); - } else { - _audiodriver = new AlsaLayer(this); - preferences.setAudioApi(ALSA); - _audiodriver->setMainBuffer(&_mainBuffer); - } - } else - _debug ("Error - Audio API unknown"); - - if (_audiodriver == 0) { - _debug ("Init audio driver error"); - return false; - } else { - error = getAudioDriver()->getErrorMessage(); - - if (error == -1) { - _debug ("Init audio driver: %i", error); - return false; - } - } + int error; + + _debugInit ("AudioLayer Creation"); + + if (preferences.getAudioApi() == ALSA) { + _audiodriver = new AlsaLayer (this); + _audiodriver->setMainBuffer (&_mainBuffer); + } else if (preferences.getAudioApi() == PULSEAUDIO) { + if (app_is_running ("pulseaudio") == 0) { + _audiodriver = new PulseLayer (this); + _audiodriver->setMainBuffer (&_mainBuffer); + } else { + _audiodriver = new AlsaLayer (this); + preferences.setAudioApi (ALSA); + _audiodriver->setMainBuffer (&_mainBuffer); + } + } else + _debug ("Error - Audio API unknown"); + + if (_audiodriver == 0) { + _debug ("Init audio driver error"); + return false; + } else { + error = getAudioDriver()->getErrorMessage(); + + if (error == -1) { + _debug ("Init audio driver: %i", error); + return false; + } + } - return true; + return true; } @@ -2664,226 +2669,226 @@ bool ManagerImpl::initAudioDriver (void) { * Initialization: Main Thread and gui */ void ManagerImpl::selectAudioDriver (void) { - int layer, numCardIn, numCardOut, numCardRing, sampleRate, frameSize; - std::string alsaPlugin; - AlsaLayer *alsalayer; - - layer = _audiodriver->getLayerType(); - _debug ("Audio layer type: %i" , layer); - - /* Retrieve the global devices info from the user config */ - alsaPlugin = audioPreference.getPlugin(); - numCardIn = audioPreference.getCardin(); - numCardOut = audioPreference.getCardout(); - numCardRing = audioPreference.getCardring(); - - sampleRate = _mainBuffer.getInternalSamplingRate(); - frameSize = audioPreference.getFramesize(); - - /* Only for the ALSA layer, we check the sound card information */ - - 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.", numCardIn); - numCardIn = ALSA_DFT_CARD_ID; - audioPreference.setCardin(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.", numCardOut); - numCardOut = ALSA_DFT_CARD_ID; - audioPreference.setCardout(ALSA_DFT_CARD_ID); - } - - if (!alsalayer->soundCardIndexExist(numCardRing, SFL_PCM_RINGTONE)) { - _debug(" Card with index %i doesn't exist or cannot ringtone. Switch to 0.", numCardRing); - numCardRing = ALSA_DFT_CARD_ID; - audioPreference.setCardring(ALSA_DFT_CARD_ID); - } - } + int layer, numCardIn, numCardOut, numCardRing, sampleRate, frameSize; + std::string alsaPlugin; + AlsaLayer *alsalayer; + + layer = _audiodriver->getLayerType(); + _debug ("Audio layer type: %i" , layer); + + /* Retrieve the global devices info from the user config */ + alsaPlugin = audioPreference.getPlugin(); + numCardIn = audioPreference.getCardin(); + numCardOut = audioPreference.getCardout(); + numCardRing = audioPreference.getCardring(); + + sampleRate = _mainBuffer.getInternalSamplingRate(); + frameSize = audioPreference.getFramesize(); + + /* Only for the ALSA layer, we check the sound card information */ + + 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.", numCardIn); + numCardIn = ALSA_DFT_CARD_ID; + audioPreference.setCardin (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.", numCardOut); + numCardOut = ALSA_DFT_CARD_ID; + audioPreference.setCardout (ALSA_DFT_CARD_ID); + } + + if (!alsalayer->soundCardIndexExist (numCardRing, SFL_PCM_RINGTONE)) { + _debug (" Card with index %i doesn't exist or cannot ringtone. Switch to 0.", numCardRing); + numCardRing = ALSA_DFT_CARD_ID; + audioPreference.setCardring (ALSA_DFT_CARD_ID); + } + } - _audiodriver->setErrorMessage(-1); + _audiodriver->setErrorMessage (-1); - /* Open the audio devices */ - _audiodriver->openDevice(numCardIn, numCardOut, numCardRing, sampleRate, frameSize, - SFL_PCM_BOTH, alsaPlugin); + /* Open the audio devices */ + _audiodriver->openDevice (numCardIn, numCardOut, numCardRing, sampleRate, frameSize, + SFL_PCM_BOTH, alsaPlugin); - /* Notify the error if there is one */ + /* Notify the error if there is one */ - if (_audiodriver -> getErrorMessage() != -1) - notifyErrClient(_audiodriver -> getErrorMessage()); + if (_audiodriver -> getErrorMessage() != -1) + notifyErrClient (_audiodriver -> getErrorMessage()); } void ManagerImpl::switchAudioManager (void) { - int type, samplerate, framesize, numCardIn, numCardOut, numCardRing; - std::string alsaPlugin; + int type, samplerate, framesize, numCardIn, numCardOut, numCardRing; + std::string alsaPlugin; - _debug ("Manager: Switching audio manager "); + _debug ("Manager: Switching audio manager "); - if (!_audiodriver) - return; + if (!_audiodriver) + return; - type = _audiodriver->getLayerType(); + type = _audiodriver->getLayerType(); - samplerate = _mainBuffer.getInternalSamplingRate(); - framesize = audioPreference.getFramesize(); + samplerate = _mainBuffer.getInternalSamplingRate(); + framesize = audioPreference.getFramesize(); - _debug ("Manager: samplerate: %i, framesize %i", samplerate, framesize); + _debug ("Manager: samplerate: %i, framesize %i", samplerate, framesize); - alsaPlugin = audioPreference.getPlugin(); + alsaPlugin = audioPreference.getPlugin(); - numCardIn = audioPreference.getCardin(); - numCardOut = audioPreference.getCardout(); - numCardRing = audioPreference.getCardring(); + numCardIn = audioPreference.getCardin(); + numCardOut = audioPreference.getCardout(); + numCardRing = audioPreference.getCardring(); - _debug ("Manager: Deleting current layer... "); + _debug ("Manager: Deleting current layer... "); - // ost::MutexLock lock (*getAudioLayerMutex()); - getAudioLayerMutex()->enter(); + // ost::MutexLock lock (*getAudioLayerMutex()); + getAudioLayerMutex()->enter(); - // _audiodriver->closeLayer(); - delete _audiodriver; + // _audiodriver->closeLayer(); + delete _audiodriver; - _audiodriver = NULL; + _audiodriver = NULL; - switch (type) { + switch (type) { - case ALSA: - _debug ("Manager: Creating Pulseaudio layer..."); - _audiodriver = new PulseLayer(this); - _audiodriver->setMainBuffer(&_mainBuffer); - break; + case ALSA: + _debug ("Manager: Creating Pulseaudio layer..."); + _audiodriver = new PulseLayer (this); + _audiodriver->setMainBuffer (&_mainBuffer); + break; - case PULSEAUDIO: - _debug ("Manager: Creating ALSA layer..."); - _audiodriver = new AlsaLayer(this); - _audiodriver->setMainBuffer(&_mainBuffer); - break; + case PULSEAUDIO: + _debug ("Manager: Creating ALSA layer..."); + _audiodriver = new AlsaLayer (this); + _audiodriver->setMainBuffer (&_mainBuffer); + break; - default: - _warn("Manager: Error: audio layer unknown"); - break; - } + default: + _warn ("Manager: Error: audio layer unknown"); + break; + } - _audiodriver->setErrorMessage(-1); + _audiodriver->setErrorMessage (-1); - _audiodriver->openDevice(numCardIn, numCardOut, numCardRing, samplerate, framesize, - SFL_PCM_BOTH, alsaPlugin); + _audiodriver->openDevice (numCardIn, numCardOut, numCardRing, samplerate, framesize, + SFL_PCM_BOTH, alsaPlugin); - if (_audiodriver -> getErrorMessage() != -1) - notifyErrClient(_audiodriver -> getErrorMessage()); + if (_audiodriver -> getErrorMessage() != -1) + notifyErrClient (_audiodriver -> getErrorMessage()); - _debug ("Manager: Current device: %i ", type); - _debug ("Manager: Has current call: %i ", hasCurrentCall()); + _debug ("Manager: Current device: %i ", type); + _debug ("Manager: Has current call: %i ", hasCurrentCall()); - if (hasCurrentCall()) - _audiodriver->startStream(); + if (hasCurrentCall()) + _audiodriver->startStream(); - // ost::MutexLock unlock (*getAudioLayerMutex()); - getAudioLayerMutex()->leave(); + // ost::MutexLock unlock (*getAudioLayerMutex()); + getAudioLayerMutex()->leave(); - // need to stop audio streams if there is currently no call - // if ( (type != PULSEAUDIO) && (!hasCurrentCall())) { - // _debug("There is currently a call!!"); - // _audiodriver->stopStream(); + // need to stop audio streams if there is currently no call + // if ( (type != PULSEAUDIO) && (!hasCurrentCall())) { + // _debug("There is currently a call!!"); + // _audiodriver->stopStream(); - // } + // } } void ManagerImpl::audioSamplingRateChanged (void) { - int type, samplerate, framesize, numCardIn, numCardOut, numCardRing; - std::string alsaPlugin; + int type, samplerate, framesize, numCardIn, numCardOut, numCardRing; + std::string alsaPlugin; - _debug ("Manager: Audio Sampling Rate"); + _debug ("Manager: Audio Sampling Rate"); - if (!_audiodriver) - return; + if (!_audiodriver) + return; - type = _audiodriver->getLayerType(); + type = _audiodriver->getLayerType(); - samplerate = _mainBuffer.getInternalSamplingRate(); - framesize = audioPreference.getFramesize(); + samplerate = _mainBuffer.getInternalSamplingRate(); + framesize = audioPreference.getFramesize(); - _debug ("Mnager: samplerate: %i, framesize %i", samplerate, framesize); + _debug ("Mnager: samplerate: %i, framesize %i", samplerate, framesize); - alsaPlugin = audioPreference.getPlugin(); + alsaPlugin = audioPreference.getPlugin(); - numCardIn = audioPreference.getCardin(); - numCardOut = audioPreference.getCardout(); - numCardRing = audioPreference.getCardring(); + numCardIn = audioPreference.getCardin(); + numCardOut = audioPreference.getCardout(); + numCardRing = audioPreference.getCardring(); - _debug ("Manager: Deleting current layer... "); + _debug ("Manager: Deleting current layer... "); - // ost::MutexLock lock (*getAudioLayerMutex()); - getAudioLayerMutex()->enter(); + // ost::MutexLock lock (*getAudioLayerMutex()); + getAudioLayerMutex()->enter(); - // _audiodriver->closeLayer(); - delete _audiodriver; + // _audiodriver->closeLayer(); + delete _audiodriver; - _audiodriver = NULL; + _audiodriver = NULL; - switch (type) { + switch (type) { - case PULSEAUDIO: - _debug ("Manager: Creating Pulseaudio layer..."); - _audiodriver = new PulseLayer(this); - _audiodriver->setMainBuffer(&_mainBuffer); - break; + case PULSEAUDIO: + _debug ("Manager: Creating Pulseaudio layer..."); + _audiodriver = new PulseLayer (this); + _audiodriver->setMainBuffer (&_mainBuffer); + break; - case ALSA: - _debug ("Manager: Creating ALSA layer..."); - _audiodriver = new AlsaLayer(this); - _audiodriver->setMainBuffer(&_mainBuffer); - break; + case ALSA: + _debug ("Manager: Creating ALSA layer..."); + _audiodriver = new AlsaLayer (this); + _audiodriver->setMainBuffer (&_mainBuffer); + break; - default: - _warn("Manager: Error: audio layer unknown"); - break; - } + default: + _warn ("Manager: Error: audio layer unknown"); + break; + } - _audiodriver->setErrorMessage(-1); + _audiodriver->setErrorMessage (-1); - _audiodriver->openDevice(numCardIn, numCardOut, numCardRing, samplerate, framesize, - SFL_PCM_BOTH, alsaPlugin); + _audiodriver->openDevice (numCardIn, numCardOut, numCardRing, samplerate, framesize, + SFL_PCM_BOTH, alsaPlugin); - if (_audiodriver -> getErrorMessage() != -1) - notifyErrClient(_audiodriver -> getErrorMessage()); + if (_audiodriver -> getErrorMessage() != -1) + notifyErrClient (_audiodriver -> getErrorMessage()); - _debug ("Manager: Current device: %i ", type); - _debug ("Manager: Has current call: %i ", hasCurrentCall()); + _debug ("Manager: Current device: %i ", type); + _debug ("Manager: Has current call: %i ", hasCurrentCall()); - if (_audiodriver) { - unsigned int sampleRate = _audiodriver->getSampleRate(); + if (_audiodriver) { + unsigned int sampleRate = _audiodriver->getSampleRate(); - delete _telephoneTone; + delete _telephoneTone; - _debugInit ("Manager: Load telephone tone"); - std::string country = preferences.getZoneToneChoice(); - _telephoneTone = new TelephoneTone(country, sampleRate); + _debugInit ("Manager: Load telephone tone"); + std::string country = preferences.getZoneToneChoice(); + _telephoneTone = new TelephoneTone (country, sampleRate); - delete _dtmfKey; + delete _dtmfKey; - _debugInit ("Manager: Loading DTMF key"); - _dtmfKey = new DTMF(sampleRate); - } + _debugInit ("Manager: Loading DTMF key"); + _dtmfKey = new DTMF (sampleRate); + } - if (hasCurrentCall()) - _audiodriver->startStream(); + if (hasCurrentCall()) + _audiodriver->startStream(); - // ost::MutexLock unlock (*getAudioLayerMutex()); - getAudioLayerMutex()->leave(); + // ost::MutexLock unlock (*getAudioLayerMutex()); + getAudioLayerMutex()->leave(); - // need to stop audio streams if there is currently no call - // if ( (type != PULSEAUDIO) && (!hasCurrentCall())) { - // _debug("There is currently a call!!"); - // _audiodriver->stopStream(); + // need to stop audio streams if there is currently no call + // if ( (type != PULSEAUDIO) && (!hasCurrentCall())) { + // _debug("There is currently a call!!"); + // _audiodriver->stopStream(); - // } + // } } /** @@ -2891,35 +2896,35 @@ void ManagerImpl::audioSamplingRateChanged (void) { * Initialization: Main Thread */ void ManagerImpl::initVolume () { - _debugInit ("Initiate Volume"); - setSpkrVolume(audioPreference.getVolumespkr()); - setMicVolume(audioPreference.getVolumemic()); + _debugInit ("Initiate Volume"); + setSpkrVolume (audioPreference.getVolumespkr()); + setMicVolume (audioPreference.getVolumemic()); } void ManagerImpl::setSpkrVolume (unsigned short spkr_vol) { - PulseLayer *pulselayer = NULL; + PulseLayer *pulselayer = NULL; - /* Set the manager sound volume */ - _spkr_volume = spkr_vol; + /* Set the manager sound volume */ + _spkr_volume = spkr_vol; - /* Only for PulseAudio */ - pulselayer = dynamic_cast<PulseLayer*> (getAudioDriver()); + /* 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) { - _mic_volume = mic_vol; + _mic_volume = mic_vol; } int ManagerImpl::getLocalIp2IpPort (void) { - // The SIP port used for default account (IP to IP) calls= - return preferences.getPortNum(); + // The SIP port used for default account (IP to IP) calls= + return preferences.getPortNum(); } @@ -2928,253 +2933,254 @@ int ManagerImpl::getLocalIp2IpPort (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: - - case Call::Conferencing: - 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; + 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: + + case Call::Conferencing: + 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) { - return _config.getConfigTreeItemToken(section, name, arg); + const std::string& name, TokenList& 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) { - try { - return _config.getConfigTreeItemIntValue(section, name); - } catch (Conf::ConfigTreeItemException& e) { - throw e; - } + const std::string& name) { + try { + return _config.getConfigTreeItemIntValue (section, name); + } catch (Conf::ConfigTreeItemException& e) { + throw e; + } - return 0; + return 0; } bool ManagerImpl::getConfigBool (const std::string& section, - const std::string& name) { - try { - return (_config.getConfigTreeItemValue(section, name) == TRUE_STR) ? true - : false; - } catch (Conf::ConfigTreeItemException& e) { - throw e; - } + const std::string& name) { + try { + return (_config.getConfigTreeItemValue (section, name) == TRUE_STR) ? true + : false; + } catch (Conf::ConfigTreeItemException& e) { + throw e; + } - return false; + return false; } //THREAD=Main std::string ManagerImpl::getConfigString (const std::string& section, - const std::string& name) { - try { - return _config.getConfigTreeItemValue(section, name); - } catch (Conf::ConfigTreeItemException& e) { - throw e; - } + const std::string& name) { + try { + return _config.getConfigTreeItemValue (section, name); + } catch (Conf::ConfigTreeItemException& e) { + throw e; + } - return ""; + return ""; } //THREAD=Main bool ManagerImpl::setConfig (const std::string& section, - const std::string& name, const std::string& value) { + 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) { - std::ostringstream valueStream; - valueStream << value; - return _config.setConfigTreeItem(section, name, valueStream.str()); + const std::string& name, int value) { + std::ostringstream valueStream; + valueStream << value; + return _config.setConfigTreeItem (section, name, valueStream.str()); } void ManagerImpl::setAccountsOrder (const std::string& order) { - _debug ("Manager: Set accounts order : %s", order.c_str()); - // Set the new config + _debug ("Manager: Set accounts order : %s", order.c_str()); + // Set the new config - preferences.setAccountOrder(order); + preferences.setAccountOrder (order); } std::vector<std::string> ManagerImpl::getAccountList () { - std::vector<std::string> v; - std::vector<std::string> account_order; - unsigned int i; - - _debug("Manager: Get account list"); - - account_order = loadAccountOrder(); - AccountMap::iterator iter; - - // The IP2IP profile is always available, and first in the list - iter = _accountMap.find(IP2IP_PROFILE); - if (iter->second != NULL) { - // _debug("PUSHING BACK %s", iter->first.c_str()); - // v.push_back(iter->first.data()); - v.push_back(iter->second->getAccountID()); - } - else { - _error("Manager: could not find IP2IP profile in getAccount list"); - } - - // If no order has been set, load the default one - // ie according to the creation date. - - if (account_order.size() == 0) { - _debug("Manager: account order is empty"); - iter = _accountMap.begin(); - - while (iter != _accountMap.end()) { - - if (iter->second != NULL && iter->first != IP2IP_PROFILE) { - _debug("PUSHING BACK %s", iter->first.c_str()); - // v.push_back(iter->first.data()); - v.push_back(iter->second->getAccountID()); - } - - iter++; - } - } - - // Otherelse, load the custom one - // ie according to the saved order - else { - _debug("Manager: Load account list according to preferences"); - 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 the account is valid - if (iter->second != NULL && iter->first != IP2IP_PROFILE) { - //_debug("PUSHING BACK %s", iter->first.c_str()); - // v.push_back(iter->first.data()); - v.push_back(iter->second->getAccountID()); - } - } - } - } - - return v; + std::vector<std::string> v; + std::vector<std::string> account_order; + unsigned int i; + + _debug ("Manager: Get account list"); + + account_order = loadAccountOrder(); + AccountMap::iterator iter; + + // The IP2IP profile is always available, and first in the list + iter = _accountMap.find (IP2IP_PROFILE); + + if (iter->second != NULL) { + // _debug("PUSHING BACK %s", iter->first.c_str()); + // v.push_back(iter->first.data()); + v.push_back (iter->second->getAccountID()); + } else { + _error ("Manager: could not find IP2IP profile in getAccount list"); + } + + // If no order has been set, load the default one + // ie according to the creation date. + + if (account_order.size() == 0) { + _debug ("Manager: account order is empty"); + iter = _accountMap.begin(); + + while (iter != _accountMap.end()) { + + if (iter->second != NULL && iter->first != IP2IP_PROFILE) { + _debug ("PUSHING BACK %s", iter->first.c_str()); + // v.push_back(iter->first.data()); + v.push_back (iter->second->getAccountID()); + } + + iter++; + } + } + + // Otherelse, load the custom one + // ie according to the saved order + else { + _debug ("Manager: Load account list according to preferences"); + + 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 the account is valid + if (iter->second != NULL && iter->first != IP2IP_PROFILE) { + //_debug("PUSHING BACK %s", iter->first.c_str()); + // v.push_back(iter->first.data()); + v.push_back (iter->second->getAccountID()); + } + } + } + } + + return v; } std::map<std::string, std::string> ManagerImpl::getAccountDetails ( - const AccountID& accountID) { + const AccountID& accountID) { + + _debug ("Manager: get account details %s", accountID.c_str()); + + Account * account; + + if (! (account = _accountMap[accountID])) { + _debug ("Manager: Get account details on a non-existing accountID %s. Returning default", accountID.c_str()); + // return a default map + return defaultAccount.getAccountDetails(); + } else + return account->getAccountDetails(); - _debug("Manager: get account details %s", accountID.c_str()); - - Account * account; - if(!(account = _accountMap[accountID])) { - _debug("Manager: Get account details on a non-existing accountID %s. Returning default", accountID.c_str()); - // return a default map - return defaultAccount.getAccountDetails(); - } - else - return account->getAccountDetails(); - } /* Transform digest to string. @@ -3186,815 +3192,812 @@ std::map<std::string, std::string> ManagerImpl::getAccountDetails ( */ void ManagerImpl::digest2str (const unsigned char digest[], char *output) { - int i; + int i; - for (i = 0; i < 16; ++i) { - pj_val_to_hex_digit(digest[i], output); - output += 2; - } + for (i = 0; i < 16; ++i) { + pj_val_to_hex_digit (digest[i], output); + output += 2; + } } std::string ManagerImpl::computeMd5HashFromCredential ( - const std::string& username, const std::string& password, - const std::string& realm) { - pj_md5_context pms; - unsigned char digest[16]; - char ha1[PJSIP_MD5STRLEN]; + const std::string& username, const std::string& password, + const std::string& realm) { + pj_md5_context pms; + unsigned char digest[16]; + char ha1[PJSIP_MD5STRLEN]; - pj_str_t usernamePjFormat = pj_str(strdup(username.c_str())); - pj_str_t passwordPjFormat = pj_str(strdup(password.c_str())); - pj_str_t realmPjFormat = pj_str(strdup(realm.c_str())); + pj_str_t usernamePjFormat = pj_str (strdup (username.c_str())); + pj_str_t passwordPjFormat = pj_str (strdup (password.c_str())); + pj_str_t realmPjFormat = pj_str (strdup (realm.c_str())); - /* Compute md5 hash = MD5(username ":" realm ":" password) */ - pj_md5_init(&pms); - MD5_APPEND (&pms, usernamePjFormat.ptr, usernamePjFormat.slen); - MD5_APPEND (&pms, ":", 1); - MD5_APPEND (&pms, realmPjFormat.ptr, realmPjFormat.slen); - MD5_APPEND (&pms, ":", 1); - MD5_APPEND (&pms, passwordPjFormat.ptr, passwordPjFormat.slen); - pj_md5_final(&pms, digest); + /* Compute md5 hash = MD5(username ":" realm ":" password) */ + pj_md5_init (&pms); + MD5_APPEND (&pms, usernamePjFormat.ptr, usernamePjFormat.slen); + MD5_APPEND (&pms, ":", 1); + MD5_APPEND (&pms, realmPjFormat.ptr, realmPjFormat.slen); + MD5_APPEND (&pms, ":", 1); + MD5_APPEND (&pms, passwordPjFormat.ptr, passwordPjFormat.slen); + pj_md5_final (&pms, digest); - digest2str(digest, ha1); + digest2str (digest, ha1); - char ha1_null_terminated[PJSIP_MD5STRLEN + 1]; - memcpy(ha1_null_terminated, ha1, sizeof(char) * PJSIP_MD5STRLEN); - ha1_null_terminated[PJSIP_MD5STRLEN] = '\0'; + char ha1_null_terminated[PJSIP_MD5STRLEN + 1]; + memcpy (ha1_null_terminated, ha1, sizeof (char) * PJSIP_MD5STRLEN); + ha1_null_terminated[PJSIP_MD5STRLEN] = '\0'; - std::string hashedDigest = ha1_null_terminated; - return hashedDigest; + std::string hashedDigest = ha1_null_terminated; + return hashedDigest; } void ManagerImpl::setCredential (const std::string& accountID, - const int32_t& index, const std::map<std::string, std::string>& details) { - - _debug("Manager: set credential"); - /* - std::map<std::string, std::string>::iterator it; - std::map<std::string, std::string> credentialInformation = details; + const int32_t& index, const std::map<std::string, std::string>& details) { - std::string credentialIndex; - std::stringstream streamOut; - streamOut << index; - credentialIndex = streamOut.str(); + _debug ("Manager: set credential"); + /* + std::map<std::string, std::string>::iterator it; + std::map<std::string, std::string> credentialInformation = details; - std::string section = "Credential" + std::string(":") + accountID - + std::string(":") + credentialIndex; + std::string credentialIndex; + std::stringstream streamOut; + streamOut << index; + credentialIndex = streamOut.str(); - _debug ("Setting credential in section %s", section.c_str()); + std::string section = "Credential" + std::string(":") + accountID + + std::string(":") + credentialIndex; - it = credentialInformation.find(USERNAME); - std::string username; + _debug ("Setting credential in section %s", section.c_str()); - if (it == credentialInformation.end()) { - username = EMPTY_FIELD; - } else { - username = it->second; - } + it = credentialInformation.find(USERNAME); + std::string username; - Manager::instance().setConfig(section, USERNAME, username); + if (it == credentialInformation.end()) { + username = EMPTY_FIELD; + } else { + username = it->second; + } - it = credentialInformation.find(REALM); - std::string realm; + Manager::instance().setConfig(section, USERNAME, username); - if (it == credentialInformation.end()) { - realm = EMPTY_FIELD; - } else { - realm = it->second; - } + it = credentialInformation.find(REALM); + std::string realm; - Manager::instance().setConfig(section, REALM, realm); + if (it == credentialInformation.end()) { + realm = EMPTY_FIELD; + } else { + realm = it->second; + } - it = credentialInformation.find(PASSWORD); - std::string password; + Manager::instance().setConfig(section, REALM, realm); - if (it == credentialInformation.end()) { - password = EMPTY_FIELD; - } else { - password = it->second; - } + it = credentialInformation.find(PASSWORD); + std::string password; - if (getMd5CredentialHashing()) { - // TODO: Fix this. - // This is an extremly weak test in order to check - // if the password is a hashed value. This is done - // because deleteCredential() is called before this - // method. Therefore, we cannot check if the value - // is different from the one previously stored in - // the configuration file. This is to avoid to - // re-hash a hashed password. + if (it == credentialInformation.end()) { + password = EMPTY_FIELD; + } else { + password = it->second; + } - if (password.length() != 32) { - password = computeMd5HashFromCredential(username, password, realm); - } - } + if (getMd5CredentialHashing()) { + // TODO: Fix this. + // This is an extremly weak test in order to check + // if the password is a hashed value. This is done + // because deleteCredential() is called before this + // method. Therefore, we cannot check if the value + // is different from the one previously stored in + // the configuration file. This is to avoid to + // re-hash a hashed password. + + if (password.length() != 32) { + password = computeMd5HashFromCredential(username, password, realm); + } + } - Manager::instance().setConfig(section, PASSWORD, password); - */ + Manager::instance().setConfig(section, PASSWORD, password); + */ } // method to reduce the if/else mess. // Even better, switch to XML ! void ManagerImpl::setAccountDetails (const std::string& accountID, - const std::map<std::string, std::string>& details) { - - _debug("Manager: Set account details %s", accountID.c_str()); - - Account* account; - if(!(account = getAccount(accountID))) { - _warn("Manager: Cannot setAccountDetails on a non-existing accountID %s.", accountID.c_str()); - return; - } + const std::map<std::string, std::string>& details) { - account->setAccountDetails(details); + _debug ("Manager: Set account details %s", accountID.c_str()); - saveConfig(); + Account* account; - if (account->isEnabled()) - account->registerVoIPLink(); - else - account->unregisterVoIPLink(); - - // Update account details to the client side - if (_dbus) - _dbus->getConfigurationManager()->accountsChanged(); - -} - -std::string ManagerImpl::addAccount ( - const std::map<std::string, std::string>& details) { + if (! (account = getAccount (accountID))) { + _warn ("Manager: Cannot setAccountDetails on a non-existing accountID %s.", accountID.c_str()); + return; + } - /** @todo Deal with both the _accountMap and the Configuration */ - std::string accountType, account_list; - Account* newAccount; - std::stringstream accountID; - AccountID newAccountID; + account->setAccountDetails (details); - accountID << "Account:" << time(NULL); - newAccountID = accountID.str(); + saveConfig(); - // Get the type - accountType = (*details.find(CONFIG_ACCOUNT_TYPE)).second; + if (account->isEnabled()) + account->registerVoIPLink(); + else + account->unregisterVoIPLink(); - _debug ("Manager: Adding account %s", newAccountID.c_str()); + // Update account details to the client side + if (_dbus) + _dbus->getConfigurationManager()->accountsChanged(); - /** @todo Verify the uniqueness, in case a program adds accounts, two in a row. */ +} - if (accountType == "SIP") { - newAccount = AccountCreator::createAccount(AccountCreator::SIP_ACCOUNT, - newAccountID); - newAccount->setVoIPLink(); - } else if (accountType == "IAX") { - newAccount = AccountCreator::createAccount(AccountCreator::IAX_ACCOUNT, - newAccountID); - } else { - _error("Unknown %s param when calling addAccount(): %s", CONFIG_ACCOUNT_TYPE, accountType.c_str()); - return ""; - } +std::string ManagerImpl::addAccount ( + const std::map<std::string, std::string>& details) { + + /** @todo Deal with both the _accountMap and the Configuration */ + std::string accountType, account_list; + Account* newAccount; + std::stringstream accountID; + AccountID newAccountID; + + accountID << "Account:" << time (NULL); + newAccountID = accountID.str(); + + // Get the type + accountType = (*details.find (CONFIG_ACCOUNT_TYPE)).second; + + _debug ("Manager: Adding account %s", newAccountID.c_str()); + + /** @todo Verify the uniqueness, in case a program adds accounts, two in a row. */ + + if (accountType == "SIP") { + newAccount = AccountCreator::createAccount (AccountCreator::SIP_ACCOUNT, + newAccountID); + newAccount->setVoIPLink(); + } else if (accountType == "IAX") { + newAccount = AccountCreator::createAccount (AccountCreator::IAX_ACCOUNT, + newAccountID); + } else { + _error ("Unknown %s param when calling addAccount(): %s", CONFIG_ACCOUNT_TYPE, accountType.c_str()); + return ""; + } - _accountMap[newAccountID] = newAccount; + _accountMap[newAccountID] = newAccount; - newAccount->setAccountDetails(details); + newAccount->setAccountDetails (details); - // Add the newly created account in the account order list - account_list = preferences.getAccountOrder(); + // Add the newly created account in the account order list + account_list = preferences.getAccountOrder(); - if (account_list != "") { - newAccountID += "/"; - // Prepend the new account - account_list.insert(0, newAccountID); + if (account_list != "") { + newAccountID += "/"; + // Prepend the new account + account_list.insert (0, newAccountID); - preferences.setAccountOrder(account_list); - } - else { - newAccountID += "/"; - account_list = newAccountID; - preferences.setAccountOrder(account_list); - } + preferences.setAccountOrder (account_list); + } else { + newAccountID += "/"; + account_list = newAccountID; + preferences.setAccountOrder (account_list); + } - _debug("AccountMap: %s", account_list.c_str()); + _debug ("AccountMap: %s", account_list.c_str()); - newAccount->setVoIPLink(); + newAccount->setVoIPLink(); - newAccount->registerVoIPLink(); + newAccount->registerVoIPLink(); - saveConfig(); + saveConfig(); - if (_dbus) - _dbus->getConfigurationManager()->accountsChanged(); + if (_dbus) + _dbus->getConfigurationManager()->accountsChanged(); - return accountID.str(); + return accountID.str(); } void ManagerImpl::deleteAllCredential (const AccountID& accountID) { - - _debug("Manager: delete all credential"); - Account *account = getAccount(accountID); + _debug ("Manager: delete all credential"); - if(!account) - return; - - if(account->getType() != "SIP") - return; + Account *account = getAccount (accountID); - SIPAccount *sipaccount = (SIPAccount *)account; + if (!account) + return; - if (accountID.empty() == false) { - sipaccount->setCredentialCount(0); - } + if (account->getType() != "SIP") + return; + + SIPAccount *sipaccount = (SIPAccount *) account; + + if (accountID.empty() == false) { + sipaccount->setCredentialCount (0); + } } void ManagerImpl::removeAccount (const AccountID& accountID) { - // Get it down and dying - Account* remAccount = NULL; - remAccount = getAccount(accountID); - - if (remAccount != NULL) { - remAccount->unregisterVoIPLink(); - _accountMap.erase(accountID); - // http://projects.savoirfairelinux.net/issues/show/2355 - // delete remAccount; - } + // Get it down and dying + Account* remAccount = NULL; + remAccount = getAccount (accountID); + + if (remAccount != NULL) { + remAccount->unregisterVoIPLink(); + _accountMap.erase (accountID); + // http://projects.savoirfairelinux.net/issues/show/2355 + // delete remAccount; + } - _config.removeSection(accountID); + _config.removeSection (accountID); - saveConfig(); + saveConfig(); - _debug ("REMOVE ACCOUNT"); + _debug ("REMOVE ACCOUNT"); - 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", callID.data(), accountID.data()); - return true; - } else { - return false; - } - } else { - return false; - } + 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", callID.data(), accountID.data()); + return true; + } else { + return false; + } + } else { + return false; + } } AccountID ManagerImpl::getAccountFromCall (const CallID& callID) { - ost::MutexLock m(_callAccountMapMutex); - CallAccountMap::iterator iter = _callAccountMap.find(callID); + ost::MutexLock m (_callAccountMapMutex); + CallAccountMap::iterator iter = _callAccountMap.find (callID); - if (iter == _callAccountMap.end()) { - return AccountNULL; - } else { - return iter->second; - } + if (iter == _callAccountMap.end()) { + return AccountNULL; + } else { + return iter->second; + } } bool ManagerImpl::removeCallAccount (const CallID& callID) { - ost::MutexLock m(_callAccountMapMutex); + ost::MutexLock m (_callAccountMapMutex); + + if (_callAccountMap.erase (callID)) { + return true; + } - if (_callAccountMap.erase(callID)) { - return true; - } - return false; + return false; } 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(); - } + while (getAccountFromCall (random_id.str()) != AccountNULL) { + random_id.clear(); + random_id << "s"; + random_id << (unsigned) rand(); + } - return random_id.str(); + return random_id.str(); } std::vector<std::string> ManagerImpl::loadAccountOrder (void) { - std::string account_list; - std::vector<std::string> account_vect; + std::string account_list; + std::vector<std::string> account_vect; - account_list = preferences.getAccountOrder(); + account_list = preferences.getAccountOrder(); - _debug("Manager: Load sccount order %s", account_list.c_str()); + _debug ("Manager: Load sccount order %s", account_list.c_str()); - return unserialize(account_list); + return unserialize (account_list); } short ManagerImpl::buildConfiguration () { - _debug ("Manager: Loading account map"); + _debug ("Manager: Loading account map"); - loadIptoipProfile(); + loadIptoipProfile(); - int nbAccount = loadAccountMap(); + int nbAccount = loadAccountMap(); - return nbAccount; + return nbAccount; } void ManagerImpl::loadIptoipProfile() { - _debug ("Manager: Create default \"account\" (used as default UDP transport)"); + _debug ("Manager: Create default \"account\" (used as default UDP transport)"); - // build a default IP2IP account with default parameters - _directIpAccount = AccountCreator::createAccount(AccountCreator::SIP_DIRECT_IP_ACCOUNT, ""); - _accountMap[IP2IP_PROFILE] = _directIpAccount; + // build a default IP2IP account with default parameters + _directIpAccount = AccountCreator::createAccount (AccountCreator::SIP_DIRECT_IP_ACCOUNT, ""); + _accountMap[IP2IP_PROFILE] = _directIpAccount; - if (_directIpAccount == NULL) { - _error("Manager: Failed to create default \"account\""); - return; - } + if (_directIpAccount == NULL) { + _error ("Manager: Failed to create default \"account\""); + return; + } - // If configuration file parsed, load saved preferences - if (_setupLoaded) { + // If configuration file parsed, load saved preferences + if (_setupLoaded) { - _debug("Manager: Loading IP2IP profile preferences from config"); + _debug ("Manager: Loading IP2IP profile preferences from config"); - Conf::SequenceNode *seq = parser->getAccountSequence(); + Conf::SequenceNode *seq = parser->getAccountSequence(); - Conf::Sequence::iterator iterIP2IP = seq->getSequence()->begin(); - Conf::Key accID("id"); - - // Iterate over every account maps - while(iterIP2IP != seq->getSequence()->end()) { - - Conf::MappingNode *map = (Conf::MappingNode *)(*iterIP2IP); - - // Get the account id - Conf::ScalarNode * val = (Conf::ScalarNode *)(map->getValue(accID)); - Conf::Value accountid = val->getValue(); - - // if ID is IP2IP, unserialize - if(accountid == "IP2IP") { - - try { - _directIpAccount->unserialize(map); - } - catch(SipAccountException &e) { - _error("Manager: %s", e.what()); - } - break; - } + Conf::Sequence::iterator iterIP2IP = seq->getSequence()->begin(); + Conf::Key accID ("id"); + + // Iterate over every account maps + while (iterIP2IP != seq->getSequence()->end()) { + + Conf::MappingNode *map = (Conf::MappingNode *) (*iterIP2IP); + + // Get the account id + Conf::ScalarNode * val = (Conf::ScalarNode *) (map->getValue (accID)); + Conf::Value accountid = val->getValue(); + + // if ID is IP2IP, unserialize + if (accountid == "IP2IP") { - iterIP2IP++; + try { + _directIpAccount->unserialize (map); + } catch (SipAccountException &e) { + _error ("Manager: %s", e.what()); + } + + break; + } + + iterIP2IP++; + } } - } - // Force IP2IP settings to be loaded to be loaded - // No registration in the sense of the REGISTER method is performed. - _directIpAccount->registerVoIPLink(); - - // SIPVoIPlink is used as a singleton, it is the first call to instance here - // The SIP library initialization is done in the SIPVoIPLink constructor - // We need the IP2IP settings to be loaded at this time as they are used - // for default sip transport - - // _directIpAccount->setVoIPLink(SIPVoIPLink::instance ("")); - _directIpAccount->setVoIPLink(); + // Force IP2IP settings to be loaded to be loaded + // No registration in the sense of the REGISTER method is performed. + _directIpAccount->registerVoIPLink(); + + // SIPVoIPlink is used as a singleton, it is the first call to instance here + // The SIP library initialization is done in the SIPVoIPLink constructor + // We need the IP2IP settings to be loaded at this time as they are used + // for default sip transport + + // _directIpAccount->setVoIPLink(SIPVoIPLink::instance ("")); + _directIpAccount->setVoIPLink(); } short ManagerImpl::loadAccountMap() { - _debug("Manager: Load account map"); + _debug ("Manager: Load account map"); - // Conf::YamlParser *parser; - int nbAccount = 0; + // Conf::YamlParser *parser; + int nbAccount = 0; - if(!_setupLoaded) - return 0; + if (!_setupLoaded) + return 0; - // build preferences - preferences.unserialize((Conf::MappingNode *)(parser->getPreferenceSequence())); - voipPreferences.unserialize((Conf::MappingNode *)(parser->getVoipPreferenceSequence())); - addressbookPreference.unserialize((Conf::MappingNode *)(parser->getAddressbookSequence())); - hookPreference.unserialize((Conf::MappingNode *)(parser->getHookSequence())); - audioPreference.unserialize((Conf::MappingNode *)(parser->getAudioSequence())); - shortcutPreferences.unserialize((Conf::MappingNode *)(parser->getShortcutSequence())); + // build preferences + preferences.unserialize ( (Conf::MappingNode *) (parser->getPreferenceSequence())); + voipPreferences.unserialize ( (Conf::MappingNode *) (parser->getVoipPreferenceSequence())); + addressbookPreference.unserialize ( (Conf::MappingNode *) (parser->getAddressbookSequence())); + hookPreference.unserialize ( (Conf::MappingNode *) (parser->getHookSequence())); + audioPreference.unserialize ( (Conf::MappingNode *) (parser->getAudioSequence())); + shortcutPreferences.unserialize ( (Conf::MappingNode *) (parser->getShortcutSequence())); - Conf::SequenceNode *seq = parser->getAccountSequence(); + Conf::SequenceNode *seq = parser->getAccountSequence(); - // Each element in sequence is a new account to create - Conf::Sequence::iterator iterSeq = seq->getSequence()->begin(); - - Conf::Key accTypeKey("type"); - Conf::Key accID("id"); + // Each element in sequence is a new account to create + Conf::Sequence::iterator iterSeq = seq->getSequence()->begin(); - while(iterSeq != seq->getSequence()->end()) { + Conf::Key accTypeKey ("type"); + Conf::Key accID ("id"); - Account *tmpAccount = NULL; - Conf::MappingNode *map = (Conf::MappingNode *)(*iterSeq); - - Conf::ScalarNode * val = (Conf::ScalarNode *)(map->getValue(accTypeKey)); - Conf::Value accountType = val->getValue(); - - val = (Conf::ScalarNode *)(map->getValue(accID)); - Conf::Value accountid = val->getValue(); + while (iterSeq != seq->getSequence()->end()) { - if (accountType == "SIP" && accountid != "IP2IP") { - _debug("Manager: Create SIP account: %s", accountid.c_str()); - tmpAccount = AccountCreator::createAccount(AccountCreator::SIP_ACCOUNT, accountid); - } - else if (accountType == "IAX" && accountid != "IP2IP") { - _debug("Manager: Create IAX account: %s", accountid.c_str()); - tmpAccount = AccountCreator::createAccount(AccountCreator::IAX_ACCOUNT, accountid); - } + Account *tmpAccount = NULL; + Conf::MappingNode *map = (Conf::MappingNode *) (*iterSeq); + Conf::ScalarNode * val = (Conf::ScalarNode *) (map->getValue (accTypeKey)); + Conf::Value accountType = val->getValue(); - if (tmpAccount != NULL) { - - try { - tmpAccount->unserialize(map); - } - catch(SipAccountException &e) { - _error("Manager: %s", e.what()); - } - - _accountMap[accountid] = tmpAccount; - _debug ("Manager: Loading account %s (size %d)", accountid.c_str(), _accountMap.size()); + val = (Conf::ScalarNode *) (map->getValue (accID)); + Conf::Value accountid = val->getValue(); + + if (accountType == "SIP" && accountid != "IP2IP") { + _debug ("Manager: Create SIP account: %s", accountid.c_str()); + tmpAccount = AccountCreator::createAccount (AccountCreator::SIP_ACCOUNT, accountid); + } else if (accountType == "IAX" && accountid != "IP2IP") { + _debug ("Manager: Create IAX account: %s", accountid.c_str()); + tmpAccount = AccountCreator::createAccount (AccountCreator::IAX_ACCOUNT, accountid); + } + + + if (tmpAccount != NULL) { + + try { + tmpAccount->unserialize (map); + } catch (SipAccountException &e) { + _error ("Manager: %s", e.what()); + } - tmpAccount->setVoIPLink(); - nbAccount++; + _accountMap[accountid] = tmpAccount; + _debug ("Manager: Loading account %s (size %d)", accountid.c_str(), _accountMap.size()); + + tmpAccount->setVoIPLink(); + nbAccount++; + } + + iterSeq++; } - - iterSeq++; - } - try { - delete parser; - } - catch (Conf::YamlParserException &e) { - _error("Manager: %s", e.what()); - } + try { + delete parser; + } catch (Conf::YamlParserException &e) { + _error ("Manager: %s", e.what()); + } - parser = NULL; + parser = NULL; - return nbAccount; + return nbAccount; } void ManagerImpl::unloadAccountMap () { - AccountMap::iterator iter = _accountMap.begin(); + AccountMap::iterator iter = _accountMap.begin(); + + while (iter != _accountMap.end()) { - while (iter != _accountMap.end()) { + _debug ("Unloading account %s", iter->first.c_str()); - _debug ("Unloading account %s", iter->first.c_str()); + delete iter->second; + iter->second = NULL; - delete iter->second; - iter->second = NULL; + iter++; + } - iter++; - } + _debug ("Manager: Clear account map"); + _accountMap.clear(); + _debug ("Manager: Unload account map"); - _debug("Manager: Clear account map"); - _accountMap.clear(); - _debug("Manager: Unload account map"); - } bool ManagerImpl::accountExists (const AccountID& accountID) { - AccountMap::iterator iter = _accountMap.find(accountID); + AccountMap::iterator iter = _accountMap.find (accountID); - if (iter == _accountMap.end()) { - return false; - } + if (iter == _accountMap.end()) { + return false; + } - return true; + return true; } Account* ManagerImpl::getAccount (const AccountID& accountID) { - // In our definition, - // this is the "direct ip calls account" - if (accountID == AccountNULL) { - _debug ("Returns the direct IP account"); - return _directIpAccount; - } + // In our definition, + // this is the "direct ip calls account" + if (accountID == AccountNULL) { + _debug ("Returns the direct IP account"); + return _directIpAccount; + } - AccountMap::iterator iter = _accountMap.find(accountID); + AccountMap::iterator iter = _accountMap.find (accountID); - if (iter == _accountMap.end()) { - return NULL; - } + if (iter == _accountMap.end()) { + return NULL; + } - return iter->second; + return iter->second; } AccountID ManagerImpl::getAccountIdFromNameAndServer ( - const std::string& userName, const std::string& server) { + const std::string& userName, const std::string& server) { - AccountMap::iterator iter; - SIPAccount *account; + AccountMap::iterator iter; + SIPAccount *account; - _info ("Manager : username = %s , server = %s", userName.c_str(), server.c_str()); - // Try to find the account id from username and server name by full match + _info ("Manager : username = %s , server = %s", 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) { - account = dynamic_cast<SIPAccount *> (iter->second); + for (iter = _accountMap.begin(); iter != _accountMap.end(); ++iter) { + account = dynamic_cast<SIPAccount *> (iter->second); - if (account != NULL) { - if (account->fullMatch(userName, server)) { - _debug ("Manager: Matching account id in request is a fullmatch %s@%s", userName.c_str(), server.c_str()); - return iter->first; - } - } - } + if (account != NULL) { + if (account->fullMatch (userName, server)) { + _debug ("Manager: Matching account id in request is a fullmatch %s@%s", userName.c_str(), server.c_str()); + return iter->first; + } + } + } - // We failed! Then only match the hostname - for (iter = _accountMap.begin(); iter != _accountMap.end(); ++iter) { - account = dynamic_cast<SIPAccount *> (iter->second); + // 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 ("Manager: Matching account id in request with hostname %s", server.c_str()); - return iter->first; - } - } - } + if (account != NULL) { + if (account->hostnameMatch (server)) { + _debug ("Manager: Matching account id in request with hostname %s", server.c_str()); + return iter->first; + } + } + } - // We failed! Then only match the username - for (iter = _accountMap.begin(); iter != _accountMap.end(); ++iter) { - account = dynamic_cast<SIPAccount *> (iter->second); + // 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 ("Manager: Matching account id in request with username %s", userName.c_str()); - return iter->first; - } - } - } + if (account != NULL) { + if (account->userMatch (userName)) { + _debug ("Manager: Matching account id in request with username %s", userName.c_str()); + return iter->first; + } + } + } - _debug ("Manager: Username %s or server %s doesn't match any account, using IP2IP", userName.c_str(), server.c_str()); + _debug ("Manager: Username %s or server %s doesn't match any account, using IP2IP", userName.c_str(), server.c_str()); - // Failed again! return AccountNULL - return AccountNULL; + // Failed again! return AccountNULL + return AccountNULL; } std::map<std::string, int32_t> ManagerImpl::getAddressbookSettings () { - std::map<std::string, int32_t> settings; + std::map<std::string, int32_t> settings; - settings.insert(std::pair<std::string, int32_t>("ADDRESSBOOK_ENABLE", addressbookPreference.getEnabled() ? 1 : 0)); - settings.insert(std::pair<std::string, int32_t>("ADDRESSBOOK_MAX_RESULTS", addressbookPreference.getMaxResults())); - settings.insert(std::pair<std::string, int32_t>("ADDRESSBOOK_DISPLAY_CONTACT_PHOTO", addressbookPreference.getPhoto() ? 1 : 0)); - settings.insert(std::pair<std::string, int32_t>("ADDRESSBOOK_DISPLAY_PHONE_BUSINESS", addressbookPreference.getBusiness() ? 1 : 0)); - settings.insert(std::pair<std::string, int32_t>("ADDRESSBOOK_DISPLAY_PHONE_HOME", addressbookPreference.getHome() ? 1 : 0)); - settings.insert(std::pair<std::string, int32_t>("ADDRESSBOOK_DISPLAY_PHONE_MOBILE", addressbookPreference.getMobile() ? 1 : 0)); + settings.insert (std::pair<std::string, int32_t> ("ADDRESSBOOK_ENABLE", addressbookPreference.getEnabled() ? 1 : 0)); + settings.insert (std::pair<std::string, int32_t> ("ADDRESSBOOK_MAX_RESULTS", addressbookPreference.getMaxResults())); + settings.insert (std::pair<std::string, int32_t> ("ADDRESSBOOK_DISPLAY_CONTACT_PHOTO", addressbookPreference.getPhoto() ? 1 : 0)); + settings.insert (std::pair<std::string, int32_t> ("ADDRESSBOOK_DISPLAY_PHONE_BUSINESS", addressbookPreference.getBusiness() ? 1 : 0)); + settings.insert (std::pair<std::string, int32_t> ("ADDRESSBOOK_DISPLAY_PHONE_HOME", addressbookPreference.getHome() ? 1 : 0)); + settings.insert (std::pair<std::string, int32_t> ("ADDRESSBOOK_DISPLAY_PHONE_MOBILE", addressbookPreference.getMobile() ? 1 : 0)); - return settings; + return settings; } void ManagerImpl::setAddressbookSettings ( - const std::map<std::string, int32_t>& settings) { + const std::map<std::string, int32_t>& settings) { - addressbookPreference.setEnabled((settings.find("ADDRESSBOOK_ENABLE")->second == 1) ? true : false); - addressbookPreference.setMaxResults(settings.find("ADDRESSBOOK_MAX_RESULTS")->second); - addressbookPreference.setPhoto((settings.find("ADDRESSBOOK_DISPLAY_CONTACT_PHOTO")->second == 1) ? true : false); - addressbookPreference.setBusiness((settings.find("ADDRESSBOOK_DISPLAY_PHONE_BUSINESS")->second == 1) ? true : false); - addressbookPreference.setHone((settings.find("ADDRESSBOOK_DISPLAY_PHONE_HOME")->second == 1) ? true : false); - addressbookPreference.setMobile((settings.find("ADDRESSBOOK_DISPLAY_PHONE_MOBILE")->second == 1) ? true : false); + addressbookPreference.setEnabled ( (settings.find ("ADDRESSBOOK_ENABLE")->second == 1) ? true : false); + addressbookPreference.setMaxResults (settings.find ("ADDRESSBOOK_MAX_RESULTS")->second); + addressbookPreference.setPhoto ( (settings.find ("ADDRESSBOOK_DISPLAY_CONTACT_PHOTO")->second == 1) ? true : false); + addressbookPreference.setBusiness ( (settings.find ("ADDRESSBOOK_DISPLAY_PHONE_BUSINESS")->second == 1) ? true : false); + addressbookPreference.setHone ( (settings.find ("ADDRESSBOOK_DISPLAY_PHONE_HOME")->second == 1) ? true : false); + addressbookPreference.setMobile ( (settings.find ("ADDRESSBOOK_DISPLAY_PHONE_MOBILE")->second == 1) ? true : false); - // Write it to the configuration file - saveConfig(); + // Write it to the configuration file + saveConfig(); } void ManagerImpl::setAddressbookList (const std::vector<std::string>& list) { - std::string s = serialize(list); - addressbookPreference.setList(s); + std::string s = serialize (list); + addressbookPreference.setList (s); } std::vector<std::string> ManagerImpl::getAddressbookList (void) { - std::string s = addressbookPreference.getList(); - return unserialize(s); + std::string s = addressbookPreference.getList(); + return unserialize (s); } std::map<std::string, std::string> ManagerImpl::getHookSettings () { - std::map<std::string, std::string> settings; + std::map<std::string, std::string> settings; - - settings.insert(std::pair<std::string, std::string>("URLHOOK_IAX2_ENABLED", hookPreference.getIax2Enabled() ? "true" : "false")); - settings.insert(std::pair<std::string, std::string>("PHONE_NUMBER_HOOK_ADD_PREFIX", hookPreference.getNumberAddPrefix())); - settings.insert(std::pair<std::string, std::string>("PHONE_NUMBER_HOOK_ENABLED", hookPreference.getNumberEnabled() ? "true" : "false")); - settings.insert(std::pair<std::string, std::string>("URLHOOK_SIP_ENABLED", hookPreference.getSipEnabled() ? "true" : "false")); - settings.insert(std::pair<std::string, std::string>("URLHOOK_COMMAND", hookPreference.getUrlCommand())); - settings.insert(std::pair<std::string, std::string>("URLHOOK_SIP_FIELD", hookPreference.getUrlSipField())); - return settings; + settings.insert (std::pair<std::string, std::string> ("URLHOOK_IAX2_ENABLED", hookPreference.getIax2Enabled() ? "true" : "false")); + settings.insert (std::pair<std::string, std::string> ("PHONE_NUMBER_HOOK_ADD_PREFIX", hookPreference.getNumberAddPrefix())); + settings.insert (std::pair<std::string, std::string> ("PHONE_NUMBER_HOOK_ENABLED", hookPreference.getNumberEnabled() ? "true" : "false")); + settings.insert (std::pair<std::string, std::string> ("URLHOOK_SIP_ENABLED", hookPreference.getSipEnabled() ? "true" : "false")); + settings.insert (std::pair<std::string, std::string> ("URLHOOK_COMMAND", hookPreference.getUrlCommand())); + settings.insert (std::pair<std::string, std::string> ("URLHOOK_SIP_FIELD", hookPreference.getUrlSipField())); + + return settings; } void ManagerImpl::setHookSettings (const std::map<std::string, std::string>& settings) { - hookPreference.setIax2Enabled((settings.find("URLHOOK_IAX2_ENABLED")->second == "true") ? true : false); - hookPreference.setNumberAddPrefix(settings.find("PHONE_NUMBER_HOOK_ADD_PREFIX")->second); - hookPreference.setNumberEnabled((settings.find("PHONE_NUMBER_HOOK_ENABLED")->second == "true") ? true : false); - hookPreference.setSipEnabled((settings.find("URLHOOK_SIP_ENABLED")->second == "true") ? true : false); - hookPreference.setUrlCommand(settings.find("URLHOOK_COMMAND")->second); - hookPreference.setUrlSipField(settings.find("URLHOOK_SIP_FIELD")->second); + hookPreference.setIax2Enabled ( (settings.find ("URLHOOK_IAX2_ENABLED")->second == "true") ? true : false); + hookPreference.setNumberAddPrefix (settings.find ("PHONE_NUMBER_HOOK_ADD_PREFIX")->second); + hookPreference.setNumberEnabled ( (settings.find ("PHONE_NUMBER_HOOK_ENABLED")->second == "true") ? true : false); + hookPreference.setSipEnabled ( (settings.find ("URLHOOK_SIP_ENABLED")->second == "true") ? true : false); + hookPreference.setUrlCommand (settings.find ("URLHOOK_COMMAND")->second); + hookPreference.setUrlSipField (settings.find ("URLHOOK_SIP_FIELD")->second); - // Write it to the configuration file - saveConfig(); + // Write it to the configuration file + saveConfig(); } void ManagerImpl::check_call_configuration (const CallID& id, - const std::string &to, Call::CallConfiguration *callConfig) { - Call::CallConfiguration config; - - if (to.find(SIP_SCHEME) == 0 || to.find(SIPS_SCHEME) == 0) { - _debug ("Manager: Sip scheme detected (sip: or sips:), sending IP2IP Call"); - config = Call::IPtoIP; - } else { - config = Call::Classic; - } + const std::string &to, Call::CallConfiguration *callConfig) { + Call::CallConfiguration config; + + if (to.find (SIP_SCHEME) == 0 || to.find (SIPS_SCHEME) == 0) { + _debug ("Manager: Sip scheme detected (sip: or sips:), sending IP2IP Call"); + config = Call::IPtoIP; + } else { + config = Call::Classic; + } - associateConfigToCall(id, config); + associateConfigToCall (id, config); - *callConfig = config; + *callConfig = config; } bool ManagerImpl::associateConfigToCall (const CallID& callID, - Call::CallConfiguration config) { - - if (getConfigFromCall(callID) == CallConfigNULL) { // nothing with the same ID - _callConfigMap[callID] = config; - _debug ("Manager: Associate call %s with config %i", callID.c_str(), config); - return true; - } else { - return false; - } + Call::CallConfiguration config) { + + if (getConfigFromCall (callID) == CallConfigNULL) { // nothing with the same ID + _callConfigMap[callID] = config; + _debug ("Manager: Associate call %s with config %i", callID.c_str(), config); + return true; + } else { + return false; + } } 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; - } else { - return iter->second; - } + if (iter == _callConfigMap.end()) { + return (Call::CallConfiguration) CallConfigNULL; + } else { + return iter->second; + } } bool ManagerImpl::removeCallConfig (const CallID& callID) { - if (_callConfigMap.erase(callID)) { - return true; - } + if (_callConfigMap.erase (callID)) { + return true; + } - return false; + return false; } std::map<std::string, std::string> ManagerImpl::getCallDetails (const CallID& callID) { - std::map<std::string, std::string> call_details; - AccountID accountid; - Account *account; - VoIPLink *link; - Call *call = NULL; - std::stringstream type; - - // We need here to retrieve the call information attached to the call ID - // To achieve that, we need to get the voip link attached to the call - // But to achieve that, we need to get the account the call was made with - - // So first we fetch the account - accountid = getAccountFromCall(callID); - - // 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) { - 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>("DISPLAY_NAME", call->getDisplayName())); - 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 { - _error ("Manager: Error: getCallDetails()"); - call_details.insert(std::pair<std::string, std::string>("ACCOUNTID", AccountNULL)); - call_details.insert(std::pair<std::string, std::string>("PEER_NUMBER", "Unknown")); - call_details.insert(std::pair<std::string, std::string>("PEER_NAME", "Unknown")); - 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; + std::map<std::string, std::string> call_details; + AccountID accountid; + Account *account; + VoIPLink *link; + Call *call = NULL; + std::stringstream type; + + // We need here to retrieve the call information attached to the call ID + // To achieve that, we need to get the voip link attached to the call + // But to achieve that, we need to get the account the call was made with + + // So first we fetch the account + accountid = getAccountFromCall (callID); + + // 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) { + 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> ("DISPLAY_NAME", call->getDisplayName())); + 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 { + _error ("Manager: Error: getCallDetails()"); + call_details.insert (std::pair<std::string, std::string> ("ACCOUNTID", AccountNULL)); + call_details.insert (std::pair<std::string, std::string> ("PEER_NUMBER", "Unknown")); + call_details.insert (std::pair<std::string, std::string> ("PEER_NAME", "Unknown")); + 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; } std::map<std::string, std::string> ManagerImpl::send_history_to_client (void) { - return _history->get_history_serialized(); + return _history->get_history_serialized(); } void ManagerImpl::receive_history_from_client (std::map<std::string, - std::string> history) { + std::string> history) { - _history->set_serialized_history(history, preferences.getHistoryLimit());; - _history->save_history(); + _history->set_serialized_history (history, preferences.getHistoryLimit());; + _history->save_history(); } std::vector<std::string> ManagerImpl::getCallList (void) { - std::vector<std::string> v; + std::vector<std::string> v; - CallAccountMap::iterator iter = _callAccountMap.begin(); + CallAccountMap::iterator iter = _callAccountMap.begin(); - while (iter != _callAccountMap.end()) { - v.push_back(iter->first.data()); - iter++; - } + while (iter != _callAccountMap.end()) { + v.push_back (iter->first.data()); + iter++; + } - return v; + return v; } std::map<std::string, std::string> ManagerImpl::getConferenceDetails ( - const ConfID& confID) { + const ConfID& confID) { - std::map<std::string, std::string> conf_details; - ConferenceMap::iterator iter_conf; + std::map<std::string, std::string> conf_details; + ConferenceMap::iterator iter_conf; - iter_conf = _conferencemap.find(confID); + iter_conf = _conferencemap.find (confID); - Conference* conf = NULL; + Conference* conf = NULL; - if (iter_conf != _conferencemap.end()) { + if (iter_conf != _conferencemap.end()) { - conf = iter_conf->second; - conf_details.insert(std::pair<std::string, std::string>("CONFID", - confID)); - conf_details.insert(std::pair<std::string, std::string>("CONF_STATE", - conf->getStateStr())); - } + conf = iter_conf->second; + conf_details.insert (std::pair<std::string, std::string> ("CONFID", + confID)); + conf_details.insert (std::pair<std::string, std::string> ("CONF_STATE", + conf->getStateStr())); + } - return conf_details; + return conf_details; } std::vector<std::string> ManagerImpl::getConferenceList (void) { - _debug ("ManagerImpl::getConferenceList"); - std::vector<std::string> v; + _debug ("ManagerImpl::getConferenceList"); + std::vector<std::string> v; - ConferenceMap::iterator iter = _conferencemap.begin(); + ConferenceMap::iterator iter = _conferencemap.begin(); - while (iter != _conferencemap.end()) { - v.push_back(iter->first); - iter++; - } + while (iter != _conferencemap.end()) { + v.push_back (iter->first); + iter++; + } - return v; + return v; } std::vector<std::string> ManagerImpl::getParticipantList ( - const std::string& confID) { + const std::string& confID) { - _debug ("ManagerImpl: Get participant list %s", confID.c_str()); - std::vector<std::string> v; + _debug ("ManagerImpl: Get participant list %s", confID.c_str()); + std::vector<std::string> v; - ConferenceMap::iterator iter_conf = _conferencemap.find(confID); - Conference *conf = NULL; + ConferenceMap::iterator iter_conf = _conferencemap.find (confID); + Conference *conf = NULL; - if (iter_conf != _conferencemap.end()) - conf = iter_conf->second; + if (iter_conf != _conferencemap.end()) + conf = iter_conf->second; - if (conf != NULL) { - ParticipantSet participants = conf->getParticipantList(); - ParticipantSet::iterator iter_participant = participants.begin(); + if (conf != NULL) { + ParticipantSet participants = conf->getParticipantList(); + ParticipantSet::iterator iter_participant = participants.begin(); - while (iter_participant != participants.end()) { + while (iter_participant != participants.end()) { - v.push_back(*iter_participant); + v.push_back (*iter_participant); - iter_participant++; - } - } - else { - _warn("Manager: Warning: Did not found conference %s", confID.c_str()); - } + iter_participant++; + } + } else { + _warn ("Manager: Warning: Did not found conference %s", confID.c_str()); + } - return v; + return v; } - + diff --git a/sflphone-common/src/managerimpl_registration.cpp b/sflphone-common/src/managerimpl_registration.cpp old mode 100755 new mode 100644 index 1329aaa68bce3104d60de4bdacf9b26655739c7b..b0f4076523f24b4d3cd605feff1c1ea756249984 --- a/sflphone-common/src/managerimpl_registration.cpp +++ b/sflphone-common/src/managerimpl_registration.cpp @@ -52,8 +52,7 @@ #include <cstdlib> int -ManagerImpl::registerAccounts() -{ +ManagerImpl::registerAccounts() { int status; bool flag = true; AccountMap::iterator iter; @@ -68,8 +67,8 @@ ManagerImpl::registerAccounts() if (iter->second->isEnabled()) { - _debug("Register account %s", iter->first.c_str()); - + _debug ("Register account %s", iter->first.c_str()); + status = iter->second->registerVoIPLink(); if (status != SUCCESS) { @@ -92,8 +91,7 @@ ManagerImpl::registerAccounts() //THREAD=Main int -ManagerImpl::initRegisterAccounts() -{ +ManagerImpl::initRegisterAccounts() { int status; bool flag = true; AccountMap::iterator iter; @@ -129,8 +127,7 @@ ManagerImpl::initRegisterAccounts() return SUCCESS; } -void ManagerImpl::restartPJSIP (void) -{ +void ManagerImpl::restartPJSIP (void) { _debug ("ManagerImpl::restartPJSIP\n"); VoIPLink *link = getSIPAccountLink(); SIPVoIPLink *siplink = NULL; @@ -158,8 +155,7 @@ void ManagerImpl::restartPJSIP (void) this->registerCurSIPAccounts (); } -VoIPLink* ManagerImpl::getAccountLink (const AccountID& accountID) -{ +VoIPLink* ManagerImpl::getAccountLink (const AccountID& accountID) { if (accountID!=AccountNULL) { Account* acc = getAccount (accountID); @@ -172,8 +168,7 @@ VoIPLink* ManagerImpl::getAccountLink (const AccountID& accountID) return SIPVoIPLink::instance (""); } -VoIPLink* ManagerImpl::getSIPAccountLink() -{ +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 = _accountMap.begin(); @@ -192,8 +187,7 @@ VoIPLink* ManagerImpl::getSIPAccountLink() return NULL; } -pjsip_regc *getSipRegcFromID (const AccountID& id UNUSED) -{ +pjsip_regc *getSipRegcFromID (const AccountID& id UNUSED) { /*SIPAccount *tmp = dynamic_cast<SIPAccount *>getAccount(id); if(tmp != NULL) return tmp->getSipRegc(); @@ -201,8 +195,7 @@ pjsip_regc *getSipRegcFromID (const AccountID& id UNUSED) return NULL; } -void ManagerImpl::unregisterCurSIPAccounts() -{ +void ManagerImpl::unregisterCurSIPAccounts() { Account *current; AccountMap::iterator iter = _accountMap.begin(); @@ -220,8 +213,7 @@ void ManagerImpl::unregisterCurSIPAccounts() } } -void ManagerImpl::registerCurSIPAccounts (void) -{ +void ManagerImpl::registerCurSIPAccounts (void) { Account *current; @@ -244,16 +236,15 @@ void ManagerImpl::registerCurSIPAccounts (void) } void -ManagerImpl::sendRegister (const std::string& accountID , const int32_t& enable) -{ +ManagerImpl::sendRegister (const std::string& accountID , const int32_t& enable) { // Update the active field Account* acc = getAccount (accountID); - if(enable == 1) - acc->setEnabled(true); + if (enable == 1) + acc->setEnabled (true); else - acc->setEnabled(false); + acc->setEnabled (false); acc->loadConfig(); diff --git a/sflphone-common/src/numbercleaner.cpp b/sflphone-common/src/numbercleaner.cpp index cc84b754df4d864e4996c50a31ee67e8f76449fd..50953e917b77234ba32d1a9a5db1004d969be11e 100644 --- a/sflphone-common/src/numbercleaner.cpp +++ b/sflphone-common/src/numbercleaner.cpp @@ -33,16 +33,13 @@ #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); @@ -52,8 +49,7 @@ 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; diff --git a/sflphone-common/src/observer.cpp b/sflphone-common/src/observer.cpp index d1cb8912fb2d235319a9097d9f16d38ed9eadc2e..56f8a2bd7cfd53d5386106e1c8e9762284cd3bd7 100644 --- a/sflphone-common/src/observer.cpp +++ b/sflphone-common/src/observer.cpp @@ -31,20 +31,17 @@ #include "observer.h" #include <algorithm> -namespace Pattern -{ +namespace Pattern { void -Subject::attach (Observer& observer) -{ +Subject::attach (Observer& observer) { if (std::find (_observers.begin(), _observers.end(), &observer) == _observers.end()) { _observers.push_back (&observer); } } void -Subject::detach (Observer& observer) -{ +Subject::detach (Observer& observer) { std::list<Observer*>::iterator iter = std::find (_observers.begin(), _observers.end(), &observer); if (iter != _observers.end()) { @@ -53,8 +50,7 @@ Subject::detach (Observer& observer) } void -Subject::notify() -{ +Subject::notify() { std::list<Observer*>::iterator iter = _observers.begin(); while (iter != _observers.end()) { diff --git a/sflphone-common/src/plug-in/librarymanager.cpp b/sflphone-common/src/plug-in/librarymanager.cpp index b63df59bd31dfc9b7d075fff8e86b1ae81fe8720..28a1a014ab5636cebd902a2a92ed683e28f2c961 100644 --- a/sflphone-common/src/plug-in/librarymanager.cpp +++ b/sflphone-common/src/plug-in/librarymanager.cpp @@ -32,18 +32,15 @@ #include "librarymanager.h" LibraryManager::LibraryManager (const std::string &filename) - : _filename (filename), _handlePtr (NULL) -{ + : _filename (filename), _handlePtr (NULL) { _handlePtr = loadLibrary (filename); } -LibraryManager::~LibraryManager (void) -{ +LibraryManager::~LibraryManager (void) { unloadLibrary (); } -LibraryManager::LibraryHandle LibraryManager::loadLibrary (const std::string &filename) -{ +LibraryManager::LibraryHandle LibraryManager::loadLibrary (const std::string &filename) { LibraryHandle pluginHandlePtr = NULL; const char *error; @@ -63,8 +60,7 @@ LibraryManager::LibraryHandle LibraryManager::loadLibrary (const std::string &fi return pluginHandlePtr; } -int LibraryManager::unloadLibrary () -{ +int LibraryManager::unloadLibrary () { if (_handlePtr == NULL) return 1; @@ -80,8 +76,7 @@ int LibraryManager::unloadLibrary () return 0; } -int LibraryManager::resolveSymbol (const std::string &symbol, SymbolHandle *symbolPtr) -{ +int LibraryManager::resolveSymbol (const std::string &symbol, SymbolHandle *symbolPtr) { SymbolHandle sy = 0; if (_handlePtr) { @@ -112,7 +107,6 @@ LibraryManagerException::LibraryManagerException (const std::string &libraryName _details = "Error when resolving symbol " + details + " in " + libraryName; } -const char* LibraryManagerException::what () const throw() -{ +const char* LibraryManagerException::what () const throw() { return _details.c_str(); } diff --git a/sflphone-common/src/plug-in/pluginmanager.cpp b/sflphone-common/src/plug-in/pluginmanager.cpp index 5584ba2a1212483e99a344dc3ea22c2290d7ec88..749ad97d12d5000cdcd4611cd4a6ee0a386d2f4b 100644 --- a/sflphone-common/src/plug-in/pluginmanager.cpp +++ b/sflphone-common/src/plug-in/pluginmanager.cpp @@ -36,8 +36,7 @@ PluginManager* PluginManager::_instance = 0; PluginManager* -PluginManager::instance() -{ +PluginManager::instance() { if (!_instance) { return new PluginManager(); } @@ -46,19 +45,16 @@ PluginManager::instance() } PluginManager::PluginManager() - :_loadedPlugins() -{ + :_loadedPlugins() { _instance = this; } -PluginManager::~PluginManager() -{ +PluginManager::~PluginManager() { _instance = 0; } int -PluginManager::loadPlugins (const std::string &path) -{ +PluginManager::loadPlugins (const std::string &path) { std::string pluginDir, current; DIR *dir; dirent *dirStruct; @@ -111,8 +107,7 @@ PluginManager::loadPlugins (const std::string &path) } int -PluginManager::unloadPlugins (void) -{ +PluginManager::unloadPlugins (void) { PluginInfo *info; if (_loadedPlugins.empty()) return 0; @@ -144,8 +139,7 @@ PluginManager::unloadPlugins (void) } bool -PluginManager::isPluginLoaded (const std::string &name) -{ +PluginManager::isPluginLoaded (const std::string &name) { if (_loadedPlugins.empty()) return false; /* Use an iterator on the loaded plugins map */ @@ -163,23 +157,20 @@ PluginManager::isPluginLoaded (const std::string &name) LibraryManager* -PluginManager::loadDynamicLibrary (const std::string& filename) -{ +PluginManager::loadDynamicLibrary (const std::string& filename) { /* Load the library through the library manager */ return new LibraryManager (filename); } int -PluginManager::unloadDynamicLibrary (LibraryManager *libraryPtr) -{ +PluginManager::unloadDynamicLibrary (LibraryManager *libraryPtr) { _debug ("Unloading dynamic library ..."); /* Close it */ return libraryPtr->unloadLibrary (); } int -PluginManager::instanciatePlugin (LibraryManager *libraryPtr, Plugin **plugin) -{ +PluginManager::instanciatePlugin (LibraryManager *libraryPtr, Plugin **plugin) { createFunc *createPlugin; LibraryManager::SymbolHandle symbol; @@ -194,8 +185,7 @@ PluginManager::instanciatePlugin (LibraryManager *libraryPtr, Plugin **plugin) } int -PluginManager::deletePlugin (PluginInfo *plugin) -{ +PluginManager::deletePlugin (PluginInfo *plugin) { destroyFunc *destroyPlugin; LibraryManager::SymbolHandle symbol; @@ -211,8 +201,7 @@ PluginManager::deletePlugin (PluginInfo *plugin) } int -PluginManager::registerPlugin (Plugin *plugin, LibraryManager *library) -{ +PluginManager::registerPlugin (Plugin *plugin, LibraryManager *library) { std::string key; PluginInfo *p_info; @@ -236,8 +225,7 @@ PluginManager::registerPlugin (Plugin *plugin, LibraryManager *library) } int -PluginManager::unregisterPlugin (PluginInfo *plugin) -{ +PluginManager::unregisterPlugin (PluginInfo *plugin) { pluginMap::iterator iter; std::string key; diff --git a/sflphone-common/src/plug-in/test/pluginTest.cpp b/sflphone-common/src/plug-in/test/pluginTest.cpp index a1c80a40fdd82b5b5dcc9b043d25e830f855fe43..9dda3ab41f69d2776726de5cd10701483e70ebe4 100644 --- a/sflphone-common/src/plug-in/test/pluginTest.cpp +++ b/sflphone-common/src/plug-in/test/pluginTest.cpp @@ -33,8 +33,7 @@ #define MAJOR_VERSION 1 #define MINOR_VERSION 0 -class PluginTest : public Plugin -{ +class PluginTest : public Plugin { public: PluginTest (const std::string &name) @@ -52,12 +51,10 @@ class PluginTest : public Plugin } }; -extern "C" Plugin* createPlugin (void) -{ +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/preferences.cpp b/sflphone-common/src/preferences.cpp index 23566f24d2ef5a6b125898645d89a7acbcd7c5b2..53795787bd76eef09d8f8748157283790b57864a 100644 --- a/sflphone-common/src/preferences.cpp +++ b/sflphone-common/src/preferences.cpp @@ -33,512 +33,735 @@ #include "global.h" #include "user_cfg.h" -Preferences::Preferences() : _accountOrder("") - , _audioApi(0) - , _historyLimit(30) - , _historyMaxCalls(20) - , _notifyMails(false) - , _zoneToneChoice(DFT_ZONE) // DFT_ZONE - , _registrationExpire(180) - , _portNum(5060) - , _searchBarDisplay(true) - , _zeroConfenable(false) - , _md5Hash(false) -{ +Preferences::Preferences() : _accountOrder ("") + , _audioApi (0) + , _historyLimit (30) + , _historyMaxCalls (20) + , _notifyMails (false) + , _zoneToneChoice (DFT_ZONE) // DFT_ZONE + , _registrationExpire (180) + , _portNum (5060) + , _searchBarDisplay (true) + , _zeroConfenable (false) + , _md5Hash (false) { } Preferences::~Preferences() {} -void Preferences::serialize(Conf::YamlEmitter *emiter) -{ - - _debug("Preference: Serialize configuration"); - - Conf::MappingNode preferencemap(NULL); - - Conf::ScalarNode order(_accountOrder); - std::stringstream audiostr; audiostr << _audioApi; - Conf::ScalarNode audioapi(audiostr.str()); - std::stringstream histlimitstr; histlimitstr << _historyLimit; - Conf::ScalarNode historyLimit(histlimitstr.str()); - std::stringstream histmaxstr; histmaxstr << _historyMaxCalls; - Conf::ScalarNode historyMaxCalls(histmaxstr.str()); - Conf::ScalarNode notifyMails(_notifyMails ? "true" : "false"); - Conf::ScalarNode zoneToneChoice(_zoneToneChoice); - std::stringstream expirestr; expirestr << _registrationExpire; - Conf::ScalarNode registrationExpire(expirestr.str()); - std::stringstream portstr; portstr << _portNum; - Conf::ScalarNode portNum(portstr.str()); - Conf::ScalarNode searchBarDisplay(_searchBarDisplay ? "true" : "false"); - Conf::ScalarNode zeroConfenable(_zeroConfenable ? "true" : "false"); - Conf::ScalarNode md5Hash(_md5Hash ? "true" : "false"); - - preferencemap.setKeyValue(orderKey, &order); - preferencemap.setKeyValue(audioApiKey, &audioapi); - preferencemap.setKeyValue(historyLimitKey, &historyLimit); - preferencemap.setKeyValue(historyMaxCallsKey, &historyMaxCalls); - preferencemap.setKeyValue(notifyMailsKey, ¬ifyMails); - preferencemap.setKeyValue(zoneToneChoiceKey, &zoneToneChoice); - preferencemap.setKeyValue(registrationExpireKey, ®istrationExpire); - preferencemap.setKeyValue(portNumKey, &portNum); - preferencemap.setKeyValue(searchBarDisplayKey, &searchBarDisplay); - preferencemap.setKeyValue(zeroConfenableKey, &zeroConfenable); - preferencemap.setKeyValue(md5HashKey, &md5Hash); - - emiter->serializePreference(&preferencemap); +void Preferences::serialize (Conf::YamlEmitter *emiter) { + + _debug ("Preference: Serialize configuration"); + + Conf::MappingNode preferencemap (NULL); + + Conf::ScalarNode order (_accountOrder); + std::stringstream audiostr; + audiostr << _audioApi; + Conf::ScalarNode audioapi (audiostr.str()); + std::stringstream histlimitstr; + histlimitstr << _historyLimit; + Conf::ScalarNode historyLimit (histlimitstr.str()); + std::stringstream histmaxstr; + histmaxstr << _historyMaxCalls; + Conf::ScalarNode historyMaxCalls (histmaxstr.str()); + Conf::ScalarNode notifyMails (_notifyMails ? "true" : "false"); + Conf::ScalarNode zoneToneChoice (_zoneToneChoice); + std::stringstream expirestr; + expirestr << _registrationExpire; + Conf::ScalarNode registrationExpire (expirestr.str()); + std::stringstream portstr; + portstr << _portNum; + Conf::ScalarNode portNum (portstr.str()); + Conf::ScalarNode searchBarDisplay (_searchBarDisplay ? "true" : "false"); + Conf::ScalarNode zeroConfenable (_zeroConfenable ? "true" : "false"); + Conf::ScalarNode md5Hash (_md5Hash ? "true" : "false"); + + preferencemap.setKeyValue (orderKey, &order); + preferencemap.setKeyValue (audioApiKey, &audioapi); + preferencemap.setKeyValue (historyLimitKey, &historyLimit); + preferencemap.setKeyValue (historyMaxCallsKey, &historyMaxCalls); + preferencemap.setKeyValue (notifyMailsKey, ¬ifyMails); + preferencemap.setKeyValue (zoneToneChoiceKey, &zoneToneChoice); + preferencemap.setKeyValue (registrationExpireKey, ®istrationExpire); + preferencemap.setKeyValue (portNumKey, &portNum); + preferencemap.setKeyValue (searchBarDisplayKey, &searchBarDisplay); + preferencemap.setKeyValue (zeroConfenableKey, &zeroConfenable); + preferencemap.setKeyValue (md5HashKey, &md5Hash); + + emiter->serializePreference (&preferencemap); } -void Preferences::unserialize(Conf::MappingNode *map) -{ - - _debug("Preference: Unserialize configuration"); - - Conf::ScalarNode *val; - - if(!map) - return; - - val = (Conf::ScalarNode *)(map->getValue(orderKey)); - if(val) { _accountOrder = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(audioApiKey)); - if(val) { _audioApi = atoi(val->getValue().data()); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(historyLimitKey)); - if(val) { _historyLimit = atoi(val->getValue().data()); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(historyMaxCallsKey)); - if(val) { _historyMaxCalls = atoi(val->getValue().data()); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(notifyMailsKey)); - if(val) { _notifyMails = atoi(val->getValue().data()); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(zoneToneChoiceKey)); - if(val) { _zoneToneChoice = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(registrationExpireKey)); - if(val) { _registrationExpire = atoi(val->getValue().data()); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(portNumKey)); - if(val) { _portNum = atoi(val->getValue().data()); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(searchBarDisplayKey)); - if(val && !val->getValue().empty()) { _searchBarDisplay = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(zeroConfenableKey)); - if(val && !val->getValue().empty()) { _zeroConfenable = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(md5HashKey)); - if(val && !val->getValue().empty()) { _md5Hash = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - - - +void Preferences::unserialize (Conf::MappingNode *map) { + + _debug ("Preference: Unserialize configuration"); + + Conf::ScalarNode *val; + + if (!map) + return; + + val = (Conf::ScalarNode *) (map->getValue (orderKey)); + + if (val) { + _accountOrder = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (audioApiKey)); + + if (val) { + _audioApi = atoi (val->getValue().data()); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (historyLimitKey)); + + if (val) { + _historyLimit = atoi (val->getValue().data()); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (historyMaxCallsKey)); + + if (val) { + _historyMaxCalls = atoi (val->getValue().data()); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (notifyMailsKey)); + + if (val) { + _notifyMails = atoi (val->getValue().data()); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (zoneToneChoiceKey)); + + if (val) { + _zoneToneChoice = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (registrationExpireKey)); + + if (val) { + _registrationExpire = atoi (val->getValue().data()); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (portNumKey)); + + if (val) { + _portNum = atoi (val->getValue().data()); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (searchBarDisplayKey)); + + if (val && !val->getValue().empty()) { + _searchBarDisplay = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (zeroConfenableKey)); + + if (val && !val->getValue().empty()) { + _zeroConfenable = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (md5HashKey)); + + if (val && !val->getValue().empty()) { + _md5Hash = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + + } -VoipPreference::VoipPreference() : _playDtmf(true) - , _playTones(true) - , _pulseLength(atoi(DFT_PULSE_LENGTH_STR))// DFT_PULSE_LENGTH_STR - , _sendDtmfAs(0) - , _symmetricRtp(true) - , _zidFile(ZRTP_ZIDFILE)// ZRTP_ZID_FILENAME -{ +VoipPreference::VoipPreference() : _playDtmf (true) + , _playTones (true) + , _pulseLength (atoi (DFT_PULSE_LENGTH_STR)) // DFT_PULSE_LENGTH_STR + , _sendDtmfAs (0) + , _symmetricRtp (true) + , _zidFile (ZRTP_ZIDFILE) { // ZRTP_ZID_FILENAME } VoipPreference::~VoipPreference() {} -void VoipPreference::serialize(Conf::YamlEmitter *emitter) -{ - _debug("VoipPreference: Serialize configuration"); +void VoipPreference::serialize (Conf::YamlEmitter *emitter) { + _debug ("VoipPreference: Serialize configuration"); - Conf::MappingNode preferencemap(NULL); + Conf::MappingNode preferencemap (NULL); - Conf::ScalarNode playDtmf(_playDtmf ? "true" : "false"); - Conf::ScalarNode playTones(_playTones ? "true" : "false"); - std::stringstream pulselengthstr; pulselengthstr << _pulseLength; - Conf::ScalarNode pulseLength(pulselengthstr.str()); - std::stringstream senddtmfstr; senddtmfstr << _sendDtmfAs; - Conf::ScalarNode sendDtmfAs(senddtmfstr.str()); - Conf::ScalarNode symmetricRtp(_symmetricRtp ? "true" : "false"); - Conf::ScalarNode zidFile(_zidFile.c_str()); + Conf::ScalarNode playDtmf (_playDtmf ? "true" : "false"); + Conf::ScalarNode playTones (_playTones ? "true" : "false"); + std::stringstream pulselengthstr; + pulselengthstr << _pulseLength; + Conf::ScalarNode pulseLength (pulselengthstr.str()); + std::stringstream senddtmfstr; + senddtmfstr << _sendDtmfAs; + Conf::ScalarNode sendDtmfAs (senddtmfstr.str()); + Conf::ScalarNode symmetricRtp (_symmetricRtp ? "true" : "false"); + Conf::ScalarNode zidFile (_zidFile.c_str()); - preferencemap.setKeyValue(playDtmfKey, &playDtmf); - preferencemap.setKeyValue(playTonesKey, &playTones); - preferencemap.setKeyValue(pulseLengthKey, &pulseLength); - preferencemap.setKeyValue(sendDtmfAsKey, &sendDtmfAs); - preferencemap.setKeyValue(symmetricRtpKey, &symmetricRtp); - preferencemap.setKeyValue(zidFileKey, &zidFile); + preferencemap.setKeyValue (playDtmfKey, &playDtmf); + preferencemap.setKeyValue (playTonesKey, &playTones); + preferencemap.setKeyValue (pulseLengthKey, &pulseLength); + preferencemap.setKeyValue (sendDtmfAsKey, &sendDtmfAs); + preferencemap.setKeyValue (symmetricRtpKey, &symmetricRtp); + preferencemap.setKeyValue (zidFileKey, &zidFile); - emitter->serializeVoipPreference(&preferencemap); + emitter->serializeVoipPreference (&preferencemap); } -void VoipPreference::unserialize(Conf::MappingNode *map) -{ - - _debug("VoipPreference: Unserialize configuration"); - - Conf::ScalarNode *val = NULL; - - if(!map) - return; - - val = (Conf::ScalarNode *)(map->getValue(playDtmfKey)); - if(val && !val->getValue().empty()) { _playDtmf = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(playTonesKey)); - if(val && !val->getValue().empty()) { _playTones = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(pulseLengthKey)); - if(val) { _pulseLength = atoi(val->getValue().data()); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(sendDtmfAsKey)); - if(val) { _sendDtmfAs = atoi(val->getValue().data()); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(symmetricRtpKey)); - if(val && !val->getValue().empty()) { _symmetricRtp = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(zidFileKey)); - if(val) { _zidFile = val->getValue().c_str(); val = NULL; } - +void VoipPreference::unserialize (Conf::MappingNode *map) { + + _debug ("VoipPreference: Unserialize configuration"); + + Conf::ScalarNode *val = NULL; + + if (!map) + return; + + val = (Conf::ScalarNode *) (map->getValue (playDtmfKey)); + + if (val && !val->getValue().empty()) { + _playDtmf = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (playTonesKey)); + + if (val && !val->getValue().empty()) { + _playTones = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (pulseLengthKey)); + + if (val) { + _pulseLength = atoi (val->getValue().data()); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (sendDtmfAsKey)); + + if (val) { + _sendDtmfAs = atoi (val->getValue().data()); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (symmetricRtpKey)); + + if (val && !val->getValue().empty()) { + _symmetricRtp = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (zidFileKey)); + + if (val) { + _zidFile = val->getValue().c_str(); + val = NULL; + } + } -AddressbookPreference::AddressbookPreference() : _photo(true) - , _enabled(true) - , _list("") - , _maxResults(25) - , _business(true) - , _home(true) - , _mobile(true) -{ +AddressbookPreference::AddressbookPreference() : _photo (true) + , _enabled (true) + , _list ("") + , _maxResults (25) + , _business (true) + , _home (true) + , _mobile (true) { } AddressbookPreference::~AddressbookPreference() {} -void AddressbookPreference::serialize(Conf::YamlEmitter *emitter) -{ - _debug("Addressbook: Serialize configuration"); - - Conf::MappingNode preferencemap(NULL); - - Conf::ScalarNode photo(_photo ? "true" : "false"); - Conf::ScalarNode enabled(_enabled ? "true" : "false"); - Conf::ScalarNode list(_list); - std::stringstream maxresultstr; maxresultstr << _maxResults; - Conf::ScalarNode maxResults(maxresultstr.str()); - Conf::ScalarNode business(_business ? "true" : "false"); - Conf::ScalarNode home(_home ? "true" : "false"); - Conf::ScalarNode mobile(_mobile ? "true" : "false"); - - preferencemap.setKeyValue(photoKey, &photo); - preferencemap.setKeyValue(enabledKey, &enabled); - preferencemap.setKeyValue(listKey, &list); - preferencemap.setKeyValue(maxResultsKey, &maxResults); - preferencemap.setKeyValue(businessKey, &business); - preferencemap.setKeyValue(homeKey, &home); - preferencemap.setKeyValue(mobileKey, &mobile); - - emitter->serializeAddressbookPreference(&preferencemap); +void AddressbookPreference::serialize (Conf::YamlEmitter *emitter) { + _debug ("Addressbook: Serialize configuration"); + + Conf::MappingNode preferencemap (NULL); + + Conf::ScalarNode photo (_photo ? "true" : "false"); + Conf::ScalarNode enabled (_enabled ? "true" : "false"); + Conf::ScalarNode list (_list); + std::stringstream maxresultstr; + maxresultstr << _maxResults; + Conf::ScalarNode maxResults (maxresultstr.str()); + Conf::ScalarNode business (_business ? "true" : "false"); + Conf::ScalarNode home (_home ? "true" : "false"); + Conf::ScalarNode mobile (_mobile ? "true" : "false"); + + preferencemap.setKeyValue (photoKey, &photo); + preferencemap.setKeyValue (enabledKey, &enabled); + preferencemap.setKeyValue (listKey, &list); + preferencemap.setKeyValue (maxResultsKey, &maxResults); + preferencemap.setKeyValue (businessKey, &business); + preferencemap.setKeyValue (homeKey, &home); + preferencemap.setKeyValue (mobileKey, &mobile); + + emitter->serializeAddressbookPreference (&preferencemap); } -void AddressbookPreference::unserialize(Conf::MappingNode *map) -{ - _debug("Addressbook: Unserialize configuration"); - - Conf::ScalarNode *val = NULL; - - if(!map) - return; - - val = (Conf::ScalarNode *)(map->getValue(photoKey)); - if(val && !(val->getValue().empty())) { _photo = (val->getValue() == "true") ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(enabledKey)); - if(val && !val->getValue().empty()) { _enabled = (val->getValue() == "true") ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(listKey)); - if(val) { _list = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(maxResultsKey)); - if(val) { _maxResults = atoi(val->getValue().data()); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(businessKey)); - if(val && !val->getValue().empty()) { _business = (val->getValue() == "true") ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(homeKey)); - if(val && !val->getValue().empty()) { _home = (val->getValue() == "true") ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(mobileKey)); - if(val && !val->getValue().empty()) { _mobile = (val->getValue() == "true") ? true : false; val = NULL; } - +void AddressbookPreference::unserialize (Conf::MappingNode *map) { + _debug ("Addressbook: Unserialize configuration"); + + Conf::ScalarNode *val = NULL; + + if (!map) + return; + + val = (Conf::ScalarNode *) (map->getValue (photoKey)); + + if (val && ! (val->getValue().empty())) { + _photo = (val->getValue() == "true") ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (enabledKey)); + + if (val && !val->getValue().empty()) { + _enabled = (val->getValue() == "true") ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (listKey)); + + if (val) { + _list = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (maxResultsKey)); + + if (val) { + _maxResults = atoi (val->getValue().data()); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (businessKey)); + + if (val && !val->getValue().empty()) { + _business = (val->getValue() == "true") ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (homeKey)); + + if (val && !val->getValue().empty()) { + _home = (val->getValue() == "true") ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (mobileKey)); + + if (val && !val->getValue().empty()) { + _mobile = (val->getValue() == "true") ? true : false; + val = NULL; + } + } -HookPreference::HookPreference() : _iax2Enabled(false) - , _numberAddPrefix("") - , _numberEnabled(false) - , _sipEnabled(false) - , _urlCommand("x-www-browser") - , _urlSipField("X-sflphone-url") -{ +HookPreference::HookPreference() : _iax2Enabled (false) + , _numberAddPrefix ("") + , _numberEnabled (false) + , _sipEnabled (false) + , _urlCommand ("x-www-browser") + , _urlSipField ("X-sflphone-url") { } HookPreference::~HookPreference() {} -void HookPreference::serialize(Conf::YamlEmitter *emitter) -{ - _debug("Hook: Serialize configuration"); +void HookPreference::serialize (Conf::YamlEmitter *emitter) { + _debug ("Hook: Serialize configuration"); - Conf::MappingNode preferencemap(NULL); + Conf::MappingNode preferencemap (NULL); - Conf::ScalarNode iax2Enabled(_iax2Enabled ? "true" : "false"); - Conf::ScalarNode numberAddPrefix(_numberAddPrefix); - Conf::ScalarNode numberEnabled(_numberEnabled ? "true" : "false"); - Conf::ScalarNode sipEnabled(_sipEnabled ? "true" : "false"); - Conf::ScalarNode urlCommand(_urlCommand); - Conf::ScalarNode urlSipField(_urlSipField); + Conf::ScalarNode iax2Enabled (_iax2Enabled ? "true" : "false"); + Conf::ScalarNode numberAddPrefix (_numberAddPrefix); + Conf::ScalarNode numberEnabled (_numberEnabled ? "true" : "false"); + Conf::ScalarNode sipEnabled (_sipEnabled ? "true" : "false"); + Conf::ScalarNode urlCommand (_urlCommand); + Conf::ScalarNode urlSipField (_urlSipField); - preferencemap.setKeyValue(iax2EnabledKey, &iax2Enabled); - preferencemap.setKeyValue(numberAddPrefixKey, &numberAddPrefix); - preferencemap.setKeyValue(numberEnabledKey, &numberEnabled); - preferencemap.setKeyValue(sipEnabledKey, &sipEnabled); - preferencemap.setKeyValue(urlCommandKey, &urlCommand); - preferencemap.setKeyValue(urlSipFieldKey, &urlSipField); + preferencemap.setKeyValue (iax2EnabledKey, &iax2Enabled); + preferencemap.setKeyValue (numberAddPrefixKey, &numberAddPrefix); + preferencemap.setKeyValue (numberEnabledKey, &numberEnabled); + preferencemap.setKeyValue (sipEnabledKey, &sipEnabled); + preferencemap.setKeyValue (urlCommandKey, &urlCommand); + preferencemap.setKeyValue (urlSipFieldKey, &urlSipField); - emitter->serializeHooksPreference(&preferencemap); + emitter->serializeHooksPreference (&preferencemap); } -void HookPreference::unserialize(Conf::MappingNode *map) -{ - Conf::ScalarNode *val = NULL; - - _debug("Hook: Unserialize preference"); - - if(!map) - return; - - val = (Conf::ScalarNode *)(map->getValue(iax2EnabledKey)); - if(val) { _iax2Enabled = (val->getValue() == "true") ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(numberAddPrefixKey)); - if(val) { _numberAddPrefix = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(numberEnabledKey)); - if(val) { _numberEnabled = (val->getValue() == "true") ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(sipEnabledKey)); - if(val) { _sipEnabled = (val->getValue() == "true") ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(urlCommandKey)); - if(val) { _urlCommand = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(urlSipFieldKey)); - if(val) { _urlSipField = val->getValue(); val = NULL; } - +void HookPreference::unserialize (Conf::MappingNode *map) { + Conf::ScalarNode *val = NULL; + + _debug ("Hook: Unserialize preference"); + + if (!map) + return; + + val = (Conf::ScalarNode *) (map->getValue (iax2EnabledKey)); + + if (val) { + _iax2Enabled = (val->getValue() == "true") ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (numberAddPrefixKey)); + + if (val) { + _numberAddPrefix = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (numberEnabledKey)); + + if (val) { + _numberEnabled = (val->getValue() == "true") ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (sipEnabledKey)); + + if (val) { + _sipEnabled = (val->getValue() == "true") ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (urlCommandKey)); + + if (val) { + _urlCommand = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (urlSipFieldKey)); + + if (val) { + _urlSipField = val->getValue(); + val = NULL; + } + } -AudioPreference::AudioPreference() : _cardin(atoi(ALSA_DFT_CARD)) // ALSA_DFT_CARD - , _cardout(atoi(ALSA_DFT_CARD)) // ALSA_DFT_CARD - , _cardring(atoi(ALSA_DFT_CARD)) // ALSA_DFT_CARD - , _framesize(atoi(DFT_FRAME_SIZE)) // DFT_FRAME_SIZE - , _plugin("default") // PCM_DEFAULT - , _smplrate(44100) // DFT_SAMPLE_RATE - , _devicePlayback("") - , _deviceRecord("") - , _deviceRingtone("") - , _recordpath("") // DFT_RECORD_PATH - , _volumemic(atoi(DFT_VOL_SPKR_STR)) // DFT_VOL_SPKR_STR - , _volumespkr(atoi(DFT_VOL_MICRO_STR)) // DFT_VOL_MICRO_STR -{ +AudioPreference::AudioPreference() : _cardin (atoi (ALSA_DFT_CARD)) // ALSA_DFT_CARD + , _cardout (atoi (ALSA_DFT_CARD)) // ALSA_DFT_CARD + , _cardring (atoi (ALSA_DFT_CARD)) // ALSA_DFT_CARD + , _framesize (atoi (DFT_FRAME_SIZE)) // DFT_FRAME_SIZE + , _plugin ("default") // PCM_DEFAULT + , _smplrate (44100) // DFT_SAMPLE_RATE + , _devicePlayback ("") + , _deviceRecord ("") + , _deviceRingtone ("") + , _recordpath ("") // DFT_RECORD_PATH + , _volumemic (atoi (DFT_VOL_SPKR_STR)) // DFT_VOL_SPKR_STR + , _volumespkr (atoi (DFT_VOL_MICRO_STR)) { // DFT_VOL_MICRO_STR } AudioPreference::~AudioPreference() {} -void AudioPreference::serialize(Conf::YamlEmitter *emitter) -{ - _debug("AudioPreference: Serialize configuration"); +void AudioPreference::serialize (Conf::YamlEmitter *emitter) { + _debug ("AudioPreference: Serialize configuration"); - Conf::MappingNode preferencemap(NULL); - Conf::MappingNode alsapreferencemap(NULL); - Conf::MappingNode pulsepreferencemap(NULL); + Conf::MappingNode preferencemap (NULL); + Conf::MappingNode alsapreferencemap (NULL); + Conf::MappingNode pulsepreferencemap (NULL); // alsa preference - std::stringstream instr; instr << _cardin; - Conf::ScalarNode cardin(instr.str()); // 0 - std::stringstream outstr; outstr << _cardout; - Conf::ScalarNode cardout(outstr.str()); // 0 - std::stringstream ringstr; ringstr << _cardring; - Conf::ScalarNode cardring(ringstr.str());// 0 - std::stringstream framestr; framestr << _framesize; - Conf::ScalarNode framesize(framestr.str()); // 20 - Conf::ScalarNode plugin(_plugin); // default - std::stringstream ratestr; ratestr << _smplrate; - Conf::ScalarNode smplrate(ratestr.str());// 44100 - - //pulseaudio preference - Conf::ScalarNode devicePlayback(_devicePlayback);//: - Conf::ScalarNode deviceRecord(_deviceRecord); //: - Conf::ScalarNode deviceRingtone(_deviceRingtone); //: - - // general preference - Conf::ScalarNode recordpath(_recordpath); //: /home/msavard/Bureau - std::stringstream micstr; micstr << _volumemic; - Conf::ScalarNode volumemic(micstr.str()); //: 100 - std::stringstream spkrstr; spkrstr << _volumespkr; - Conf::ScalarNode volumespkr(spkrstr.str()); //: 100 - - preferencemap.setKeyValue(recordpathKey, &recordpath); - preferencemap.setKeyValue(volumemicKey, &volumemic); - preferencemap.setKeyValue(volumespkrKey, &volumespkr); - - preferencemap.setKeyValue(alsamapKey, &alsapreferencemap); - alsapreferencemap.setKeyValue(cardinKey, &cardin); - alsapreferencemap.setKeyValue(cardoutKey, &cardout); - alsapreferencemap.setKeyValue(cardringKey, &cardring); - alsapreferencemap.setKeyValue(framesizeKey, &framesize); - alsapreferencemap.setKeyValue(pluginKey, &plugin); - alsapreferencemap.setKeyValue(smplrateKey, &smplrate); - - preferencemap.setKeyValue(pulsemapKey, &pulsepreferencemap); - pulsepreferencemap.setKeyValue(devicePlaybackKey, &devicePlayback); - pulsepreferencemap.setKeyValue(deviceRecordKey, &deviceRecord); - pulsepreferencemap.setKeyValue(deviceRingtoneKey, &deviceRingtone); - - emitter->serializeAudioPreference(&preferencemap); - + std::stringstream instr; + instr << _cardin; + Conf::ScalarNode cardin (instr.str()); // 0 + std::stringstream outstr; + outstr << _cardout; + Conf::ScalarNode cardout (outstr.str()); // 0 + std::stringstream ringstr; + ringstr << _cardring; + Conf::ScalarNode cardring (ringstr.str());// 0 + std::stringstream framestr; + framestr << _framesize; + Conf::ScalarNode framesize (framestr.str()); // 20 + Conf::ScalarNode plugin (_plugin); // default + std::stringstream ratestr; + ratestr << _smplrate; + Conf::ScalarNode smplrate (ratestr.str());// 44100 + + //pulseaudio preference + Conf::ScalarNode devicePlayback (_devicePlayback);//: + Conf::ScalarNode deviceRecord (_deviceRecord); //: + Conf::ScalarNode deviceRingtone (_deviceRingtone); //: + + // general preference + Conf::ScalarNode recordpath (_recordpath); //: /home/msavard/Bureau + std::stringstream micstr; + micstr << _volumemic; + Conf::ScalarNode volumemic (micstr.str()); //: 100 + std::stringstream spkrstr; + spkrstr << _volumespkr; + Conf::ScalarNode volumespkr (spkrstr.str()); //: 100 + + preferencemap.setKeyValue (recordpathKey, &recordpath); + preferencemap.setKeyValue (volumemicKey, &volumemic); + preferencemap.setKeyValue (volumespkrKey, &volumespkr); + + preferencemap.setKeyValue (alsamapKey, &alsapreferencemap); + alsapreferencemap.setKeyValue (cardinKey, &cardin); + alsapreferencemap.setKeyValue (cardoutKey, &cardout); + alsapreferencemap.setKeyValue (cardringKey, &cardring); + alsapreferencemap.setKeyValue (framesizeKey, &framesize); + alsapreferencemap.setKeyValue (pluginKey, &plugin); + alsapreferencemap.setKeyValue (smplrateKey, &smplrate); + + preferencemap.setKeyValue (pulsemapKey, &pulsepreferencemap); + pulsepreferencemap.setKeyValue (devicePlaybackKey, &devicePlayback); + pulsepreferencemap.setKeyValue (deviceRecordKey, &deviceRecord); + pulsepreferencemap.setKeyValue (deviceRingtoneKey, &deviceRingtone); + + emitter->serializeAudioPreference (&preferencemap); + } -void AudioPreference::unserialize(Conf::MappingNode *map) -{ - _debug("AudioPreference: Unserialize configuration"); - - if(!map) - return; - - Conf::ScalarNode *val = NULL; - - val = (Conf::ScalarNode *)(map->getValue(cardinKey)); - if(val) { _cardin = atoi(val->getValue().data()); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(cardoutKey)); - if(val) { _cardout = atoi(val->getValue().data()); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(cardringKey)); - if(val) { _cardring = atoi(val->getValue().data()); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(framesizeKey)); - if(val) { _framesize = atoi(val->getValue().data()); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(smplrateKey)); - if(val) { _smplrate = atoi(val->getValue().data()); val = NULL; } - - val = (Conf::ScalarNode *)(map->getValue(devicePlaybackKey)); - if(val) { _devicePlayback = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(deviceRecordKey)); - if(val) { _deviceRecord = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(deviceRingtoneKey)); - if(val) { _deviceRingtone = val->getValue(); val = NULL; } - - val = (Conf::ScalarNode *)(map->getValue(recordpathKey)); - if(val) { _recordpath = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(volumemicKey)); - if(val) { _volumemic = atoi(val->getValue().data()); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(volumespkrKey)); - if(val) { _volumespkr = atoi(val->getValue().data()); val = NULL; } +void AudioPreference::unserialize (Conf::MappingNode *map) { + _debug ("AudioPreference: Unserialize configuration"); + + if (!map) + return; + + Conf::ScalarNode *val = NULL; + + val = (Conf::ScalarNode *) (map->getValue (cardinKey)); + + if (val) { + _cardin = atoi (val->getValue().data()); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (cardoutKey)); + + if (val) { + _cardout = atoi (val->getValue().data()); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (cardringKey)); + + if (val) { + _cardring = atoi (val->getValue().data()); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (framesizeKey)); + + if (val) { + _framesize = atoi (val->getValue().data()); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (smplrateKey)); + + if (val) { + _smplrate = atoi (val->getValue().data()); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (devicePlaybackKey)); + + if (val) { + _devicePlayback = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (deviceRecordKey)); + + if (val) { + _deviceRecord = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (deviceRingtoneKey)); + + if (val) { + _deviceRingtone = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (recordpathKey)); + + if (val) { + _recordpath = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (volumemicKey)); + + if (val) { + _volumemic = atoi (val->getValue().data()); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (volumespkrKey)); + + if (val) { + _volumespkr = atoi (val->getValue().data()); + val = NULL; + } } -ShortcutPreferences::ShortcutPreferences() : _hangup("") - , _pickup("") - , _popup("") - , _toggleHold("") - , _togglePickupHangup("") -{ +ShortcutPreferences::ShortcutPreferences() : _hangup ("") + , _pickup ("") + , _popup ("") + , _toggleHold ("") + , _togglePickupHangup ("") { } ShortcutPreferences::~ShortcutPreferences() {} -std::map<std::string, std::string> ShortcutPreferences::getShortcuts() -{ +std::map<std::string, std::string> ShortcutPreferences::getShortcuts() { - std::map<std::string, std::string> shortcutsMap; + std::map<std::string, std::string> shortcutsMap; - shortcutsMap.insert(std::pair<std::string, std::string>(hangupShortKey, _hangup)); - shortcutsMap.insert(std::pair<std::string, std::string>(pickupShortKey, _pickup)); - shortcutsMap.insert(std::pair<std::string, std::string>(popupShortKey, _popup)); - shortcutsMap.insert(std::pair<std::string, std::string>(toggleHoldShortKey, _toggleHold)); - shortcutsMap.insert(std::pair<std::string, std::string>(togglePickupHangupShortKey, _togglePickupHangup)); + shortcutsMap.insert (std::pair<std::string, std::string> (hangupShortKey, _hangup)); + shortcutsMap.insert (std::pair<std::string, std::string> (pickupShortKey, _pickup)); + shortcutsMap.insert (std::pair<std::string, std::string> (popupShortKey, _popup)); + shortcutsMap.insert (std::pair<std::string, std::string> (toggleHoldShortKey, _toggleHold)); + shortcutsMap.insert (std::pair<std::string, std::string> (togglePickupHangupShortKey, _togglePickupHangup)); - return shortcutsMap; + return shortcutsMap; } -void ShortcutPreferences::setShortcuts(std::map<std::string, std::string> map_cpy) -{ - // std::map<std::string, int> map_cpy = shortcut; - std::map<std::string, std::string>::iterator it; - - it = map_cpy.find(hangupShortKey); - if (it != map_cpy.end()) { - _hangup = it->second; - } - - it = map_cpy.find(pickupShortKey); - if (it != map_cpy.end()) { - _pickup = it->second; - } - - it = map_cpy.find(popupShortKey); - if (it != map_cpy.end()) { - _popup = it->second; - } - - it = map_cpy.find(toggleHoldShortKey); - if(it != map_cpy.end()) { - _toggleHold = it->second; - } - - it = map_cpy.find(togglePickupHangupShortKey); - if(it != map_cpy.end()) { - _togglePickupHangup = it->second; - } - /* - for (int i = 0; i < (int)shortcutsKeys.size(); i++) { - std::string key = shortcutsKeys.at(i); - it = map_cpy.find(key); - if (it != shortcutsMap.end()) { - Manager::instance().setConfig("Shortcuts", key, it->second); - } - } - */ +void ShortcutPreferences::setShortcuts (std::map<std::string, std::string> map_cpy) { + // std::map<std::string, int> map_cpy = shortcut; + std::map<std::string, std::string>::iterator it; + + it = map_cpy.find (hangupShortKey); + + if (it != map_cpy.end()) { + _hangup = it->second; + } + + it = map_cpy.find (pickupShortKey); + + if (it != map_cpy.end()) { + _pickup = it->second; + } + + it = map_cpy.find (popupShortKey); + + if (it != map_cpy.end()) { + _popup = it->second; + } + + it = map_cpy.find (toggleHoldShortKey); + + if (it != map_cpy.end()) { + _toggleHold = it->second; + } + + it = map_cpy.find (togglePickupHangupShortKey); + + if (it != map_cpy.end()) { + _togglePickupHangup = it->second; + } + + /* + for (int i = 0; i < (int)shortcutsKeys.size(); i++) { + std::string key = shortcutsKeys.at(i); + it = map_cpy.find(key); + if (it != shortcutsMap.end()) { + Manager::instance().setConfig("Shortcuts", key, it->second); + } + } + */ } -void ShortcutPreferences::serialize(Conf::YamlEmitter *emitter) -{ +void ShortcutPreferences::serialize (Conf::YamlEmitter *emitter) { - _debug("ShortcutPreference: Serialize configuration"); + _debug ("ShortcutPreference: Serialize configuration"); - Conf::MappingNode preferencemap(NULL); + Conf::MappingNode preferencemap (NULL); - Conf::ScalarNode hangup(_hangup); - Conf::ScalarNode pickup(_pickup); - Conf::ScalarNode popup(_popup); - Conf::ScalarNode toggleHold(_toggleHold); - Conf::ScalarNode togglePickupHangup(_togglePickupHangup); - - preferencemap.setKeyValue(hangupShortKey, &hangup); - preferencemap.setKeyValue(pickupShortKey, &pickup); - preferencemap.setKeyValue(popupShortKey, &popup); - preferencemap.setKeyValue(toggleHoldShortKey, &toggleHold); - preferencemap.setKeyValue(togglePickupHangupShortKey, &togglePickupHangup); - - emitter->serializeShortcutPreference(&preferencemap); + Conf::ScalarNode hangup (_hangup); + Conf::ScalarNode pickup (_pickup); + Conf::ScalarNode popup (_popup); + Conf::ScalarNode toggleHold (_toggleHold); + Conf::ScalarNode togglePickupHangup (_togglePickupHangup); + + preferencemap.setKeyValue (hangupShortKey, &hangup); + preferencemap.setKeyValue (pickupShortKey, &pickup); + preferencemap.setKeyValue (popupShortKey, &popup); + preferencemap.setKeyValue (toggleHoldShortKey, &toggleHold); + preferencemap.setKeyValue (togglePickupHangupShortKey, &togglePickupHangup); + + emitter->serializeShortcutPreference (&preferencemap); } -void ShortcutPreferences::unserialize(Conf::MappingNode *map) -{ - _debug("ShortcutPreference: Unserialize configuration"); - - if(!map) - return; - - Conf::ScalarNode *val = NULL; - - val = (Conf::ScalarNode *)(map->getValue(hangupShortKey)); - if(val) { _hangup = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(pickupShortKey)); - if(val) { _pickup = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(popupShortKey)); - if(val) { _popup = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(toggleHoldShortKey)); - if(val) { _toggleHold = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(togglePickupHangupShortKey)); - if(val) { _togglePickupHangup = val->getValue(); val = NULL; } +void ShortcutPreferences::unserialize (Conf::MappingNode *map) { + _debug ("ShortcutPreference: Unserialize configuration"); + + if (!map) + return; + + Conf::ScalarNode *val = NULL; + + val = (Conf::ScalarNode *) (map->getValue (hangupShortKey)); + + if (val) { + _hangup = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (pickupShortKey)); + + if (val) { + _pickup = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (popupShortKey)); + + if (val) { + _popup = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (toggleHoldShortKey)); + + if (val) { + _toggleHold = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (togglePickupHangupShortKey)); + + if (val) { + _togglePickupHangup = val->getValue(); + val = NULL; + } } diff --git a/sflphone-common/src/sip/Pattern.cpp b/sflphone-common/src/sip/Pattern.cpp index 89e3efb48a884e740383ff294370797ef6a2502a..975f95d361f34505ff9372a6b71e7b2926fd9fa5 100644 --- a/sflphone-common/src/sip/Pattern.cpp +++ b/sflphone-common/src/sip/Pattern.cpp @@ -31,17 +31,15 @@ #include <sstream> #include <cstdio> -namespace sfl -{ +namespace sfl { Pattern::Pattern (const std::string& pattern, const std::string& options) : _pattern (pattern), - _re (NULL), + _re (NULL), _ovector (NULL), _ovectorSize (0), _count (0), - _options (0) -{ + _options (0) { // printf("Pattern constructor called for %s!\n", pattern.c_str()); // Set offsets @@ -75,8 +73,7 @@ Pattern::Pattern (const std::string& pattern, const std::string& options) : compile(); } -Pattern::~Pattern() -{ +Pattern::~Pattern() { if (_re != NULL) { pcre_free (_re); } @@ -84,8 +81,7 @@ Pattern::~Pattern() delete[] _ovector; } -void Pattern::compile (void) -{ +void Pattern::compile (void) { // Compile the pattern int offset; const char * error; @@ -116,15 +112,13 @@ void Pattern::compile (void) _ovectorSize = (captureCount + 1) * 3; } -unsigned int Pattern::getCaptureGroupCount (void) -{ +unsigned int Pattern::getCaptureGroupCount (void) { int captureCount; pcre_fullinfo (_re, NULL, PCRE_INFO_CAPTURECOUNT, &captureCount); return captureCount; } -std::vector<std::string> Pattern::groups (void) -{ +std::vector<std::string> Pattern::groups (void) { const char ** stringList; pcre_get_substring_list (_subject.c_str(), @@ -146,8 +140,7 @@ std::vector<std::string> Pattern::groups (void) return matchedSubstrings; } -std::string Pattern::group (int groupNumber) -{ +std::string Pattern::group (int groupNumber) { const char * stringPtr; int rc = pcre_get_substring ( @@ -178,8 +171,7 @@ std::string Pattern::group (int groupNumber) return matchedStr; } -std::string Pattern::group (const std::string& groupName) -{ +std::string Pattern::group (const std::string& groupName) { const char * stringPtr = NULL; int rc = pcre_get_named_substring ( @@ -194,8 +186,8 @@ std::string Pattern::group (const std::string& groupName) switch (rc) { case PCRE_ERROR_NOSUBSTRING: - - break; + + break; case PCRE_ERROR_NOMEMORY: throw match_error ("Memory exhausted."); @@ -207,67 +199,58 @@ std::string Pattern::group (const std::string& groupName) std::string matchedStr; - if(stringPtr) { + if (stringPtr) { - matchedStr = stringPtr; - pcre_free_substring (stringPtr); - } - else { + matchedStr = stringPtr; + pcre_free_substring (stringPtr); + } else { - matchedStr = ""; + matchedStr = ""; } return matchedStr; } -void Pattern::start (const std::string& groupName) const -{ +void Pattern::start (const std::string& groupName) const { int index = pcre_get_stringnumber (_re, groupName.c_str()); start (index); } -size_t Pattern::start (unsigned int groupNumber) const -{ - if (groupNumber <= (unsigned int)_count) { +size_t Pattern::start (unsigned int groupNumber) const { + if (groupNumber <= (unsigned int) _count) { return _ovector[ (groupNumber + 1) * 2]; } else { throw std::out_of_range ("Invalid group reference."); } } -size_t Pattern::start (void) const -{ +size_t Pattern::start (void) const { return _ovector[0] + _offset[0]; } -void Pattern::end (const std::string& groupName) const -{ +void Pattern::end (const std::string& groupName) const { int index = pcre_get_stringnumber (_re, groupName.c_str()); end (index); } -size_t Pattern::end (unsigned int groupNumber) const -{ - if (groupNumber <= (unsigned int)_count) { +size_t Pattern::end (unsigned int groupNumber) const { + if (groupNumber <= (unsigned int) _count) { return _ovector[ ( (groupNumber + 1) * 2) + 1 ] - 1; } else { throw std::out_of_range ("Invalid group reference."); } } -size_t Pattern::end (void) const -{ +size_t Pattern::end (void) const { return (_ovector[1] - 1) + _offset[0]; } -bool Pattern::matches (void) throw (match_error) -{ +bool Pattern::matches (void) throw (match_error) { return matches (_subject); } -bool Pattern::matches (const std::string& subject) throw (match_error) -{ +bool Pattern::matches (const std::string& subject) throw (match_error) { // Try to find a match for this pattern int rc = pcre_exec ( @@ -280,7 +263,7 @@ bool Pattern::matches (const std::string& subject) throw (match_error) _ovector, _ovectorSize); - + // Matching failed. if (rc < 0) { @@ -304,13 +287,12 @@ bool Pattern::matches (const std::string& subject) throw (match_error) // Matching succeeded. Keep the number of substrings for // subsequent calls to group(). - _count = rc; + _count = rc; return true; } -std::vector<std::string> Pattern::split (void) -{ +std::vector<std::string> Pattern::split (void) { size_t tokenEnd = -1; size_t tokenStart = 0; @@ -320,8 +302,8 @@ std::vector<std::string> Pattern::split (void) tokenStart = start(); substringSplitted.push_back (_subject.substr (tokenEnd + 1, tokenStart - tokenEnd - 1)); - // printf("split: %s\n", _subject.substr (tokenEnd + 1, - // tokenStart - tokenEnd - 1).c_str()); + // printf("split: %s\n", _subject.substr (tokenEnd + 1, + // tokenStart - tokenEnd - 1).c_str()); tokenEnd = end(); } diff --git a/sflphone-common/src/sip/SdesNegotiator.cpp b/sflphone-common/src/sip/SdesNegotiator.cpp index 5396755b6be1b948629e6cf6e63111f9756c828e..2c223ffc74e15238f7c8188ec57cdc348762da3e 100644 --- a/sflphone-common/src/sip/SdesNegotiator.cpp +++ b/sflphone-common/src/sip/SdesNegotiator.cpp @@ -43,13 +43,11 @@ using namespace sfl; SdesNegotiator::SdesNegotiator (const std::vector<CryptoSuiteDefinition>& localCapabilites, const std::vector<std::string>& remoteAttribute) : _remoteAttribute (remoteAttribute), - _localCapabilities (localCapabilites) -{ + _localCapabilities (localCapabilites) { } -std::vector<CryptoAttribute *> SdesNegotiator::parse (void) -{ +std::vector<CryptoAttribute *> SdesNegotiator::parse (void) { // The patterns below try to follow // the ABNF grammar rules described in // RFC4568 section 9.2 with the general @@ -65,7 +63,7 @@ std::vector<CryptoAttribute *> SdesNegotiator::parse (void) try { - // used to match white space (which are used as separator) + // used to match white space (which are used as separator) generalSyntaxPattern = new Pattern ("[\x20\x09]+", "g"); tagPattern = new Pattern ("^a=crypto:(?P<tag>[0-9]{1,9})"); @@ -76,12 +74,12 @@ std::vector<CryptoAttribute *> SdesNegotiator::parse (void) "F8_128_HMAC_SHA1_80|" \ "[A-Za-z0-9_]+)"); // srtp-crypto-suite-ext - keyParamsPattern = new Pattern ( - "(?P<srtpKeyMethod>inline|[A-Za-z0-9_]+)\\:" \ - "(?P<srtpKeyInfo>[A-Za-z0-9\x2B\x2F\x3D]+)" \ - "(\\|2\\^(?P<lifetime>[0-9]+)\\|" \ - "(?P<mkiValue>[0-9]+)\\:" \ - "(?P<mkiLength>[0-9]{1,3})\\;?)?", "g"); + keyParamsPattern = new Pattern ( + "(?P<srtpKeyMethod>inline|[A-Za-z0-9_]+)\\:" \ + "(?P<srtpKeyInfo>[A-Za-z0-9\x2B\x2F\x3D]+)" \ + "(\\|2\\^(?P<lifetime>[0-9]+)\\|" \ + "(?P<mkiValue>[0-9]+)\\:" \ + "(?P<mkiLength>[0-9]{1,3})\\;?)?", "g"); sessionParamPattern = new Pattern ( "(?P<sessionParam>(kdr\\=[0-9]{1,2}|" \ @@ -96,23 +94,23 @@ std::vector<CryptoAttribute *> SdesNegotiator::parse (void) } catch (compile_error& exception) { throw parse_error ("A compile exception occured on a pattern."); } - + // Take each line from the vector // and parse its content - + std::vector<std::string>::iterator iter; std::vector<CryptoAttribute *> cryptoAttributeVector; - + for (iter = _remoteAttribute.begin(); iter != _remoteAttribute.end(); iter++) { // Split the line into its component // that we will analyze further down. std::vector<std::string> sdesLine; - - *generalSyntaxPattern << (*iter); - + + *generalSyntaxPattern << (*iter); + try { sdesLine = generalSyntaxPattern->split(); @@ -122,54 +120,55 @@ std::vector<CryptoAttribute *> SdesNegotiator::parse (void) } catch (match_error& exception) { throw parse_error ("Error while analyzing the SDES line."); } - + // Check if the attribute starts with a=crypto // and get the tag for this line *tagPattern << sdesLine.at (0); - - std::string tag; - if (tagPattern->matches()) { - try { - // std::cout << "Parsing the tag field"; - tag = tagPattern->group ("tag"); - // std::cout << ": " << tag << std::endl; - } catch (match_error& exception) { - throw parse_error ("Error while parsing the tag field"); - } - } else { - return cryptoAttributeVector; - } + + std::string tag; + + if (tagPattern->matches()) { + try { + // std::cout << "Parsing the tag field"; + tag = tagPattern->group ("tag"); + // std::cout << ": " << tag << std::endl; + } catch (match_error& exception) { + throw parse_error ("Error while parsing the tag field"); + } + } else { + return cryptoAttributeVector; + } // Check if the crypto suite is valid and retreive // its value. *cryptoSuitePattern << sdesLine.at (1); - std::string cryptoSuite; - - if (cryptoSuitePattern->matches()) { - try { - // std::cout << "Parsing the crypto suite field"; - cryptoSuite = cryptoSuitePattern->group ("cryptoSuite"); - // std::cout << ": " << cryptoSuite << std::endl; - } catch (match_error& exception) { - throw parse_error ("Error while parsing the crypto-suite field"); - } - } else { - return cryptoAttributeVector; - } - + std::string cryptoSuite; + + if (cryptoSuitePattern->matches()) { + try { + // std::cout << "Parsing the crypto suite field"; + cryptoSuite = cryptoSuitePattern->group ("cryptoSuite"); + // std::cout << ": " << cryptoSuite << std::endl; + } catch (match_error& exception) { + throw parse_error ("Error while parsing the crypto-suite field"); + } + } else { + return cryptoAttributeVector; + } + // Parse one or more key-params field. *keyParamsPattern << sdesLine.at (2); - std::string srtpKeyInfo; - std::string srtpKeyMethod; - std::string lifetime; - std::string mkiLength; - std::string mkiValue; - + std::string srtpKeyInfo; + std::string srtpKeyMethod; + std::string lifetime; + std::string mkiLength; + std::string mkiValue; + try { - while(keyParamsPattern->matches()) { + while (keyParamsPattern->matches()) { srtpKeyMethod = keyParamsPattern->group ("srtpKeyMethod"); srtpKeyInfo = keyParamsPattern->group ("srtpKeyInfo"); lifetime = keyParamsPattern->group ("lifetime"); @@ -197,18 +196,17 @@ std::vector<CryptoAttribute *> SdesNegotiator::parse (void) } } } */ - - // Add the new CryptoAttribute to the vector - - CryptoAttribute * cryptoAttribute = new CryptoAttribute(tag, cryptoSuite, srtpKeyMethod, srtpKeyInfo, lifetime, mkiValue, mkiLength); - cryptoAttributeVector.push_back(cryptoAttribute); + + // Add the new CryptoAttribute to the vector + + CryptoAttribute * cryptoAttribute = new CryptoAttribute (tag, cryptoSuite, srtpKeyMethod, srtpKeyInfo, lifetime, mkiValue, mkiLength); + cryptoAttributeVector.push_back (cryptoAttribute); } return cryptoAttributeVector; } -bool SdesNegotiator::negotiate (void) -{ +bool SdesNegotiator::negotiate (void) { std::vector<CryptoAttribute *> cryptoAttributeVector = parse(); std::vector<CryptoAttribute *>::iterator iter_offer = cryptoAttributeVector.begin(); @@ -218,48 +216,48 @@ bool SdesNegotiator::negotiate (void) bool negotiationSuccess = false; try { - + while (!negotiationSuccess && (iter_offer != cryptoAttributeVector.end())) { - /* - std::cout << "Negotiate tag: " + (*iter_offer)->getTag() << std::endl; - std::cout << "Crypto Suite: " + (*iter_offer)->getCryptoSuite() << std::endl; - std::cout << "SRTP Key Method: " + (*iter_offer)->getSrtpKeyMethod() << std::endl; - std::cout << "SRTP Key Info: " + (*iter_offer)->getSrtpKeyInfo() << std::endl; - std::cout << "Lifetime: " + (*iter_offer)->getLifetime() << std::endl; - std::cout << "MKI Value: " + (*iter_offer)->getMkiValue() << std::endl; - std::cout << "MKI Length: " + (*iter_offer)->getMkiLength() << std::endl; - */ + /* + std::cout << "Negotiate tag: " + (*iter_offer)->getTag() << std::endl; + std::cout << "Crypto Suite: " + (*iter_offer)->getCryptoSuite() << std::endl; + std::cout << "SRTP Key Method: " + (*iter_offer)->getSrtpKeyMethod() << std::endl; + std::cout << "SRTP Key Info: " + (*iter_offer)->getSrtpKeyInfo() << std::endl; + std::cout << "Lifetime: " + (*iter_offer)->getLifetime() << std::endl; + std::cout << "MKI Value: " + (*iter_offer)->getMkiValue() << std::endl; + std::cout << "MKI Length: " + (*iter_offer)->getMkiLength() << std::endl; + */ - iter_local = _localCapabilities.begin(); + iter_local = _localCapabilities.begin(); - while(!negotiationSuccess && (iter_local != _localCapabilities.end())) { + while (!negotiationSuccess && (iter_local != _localCapabilities.end())) { - if((*iter_offer)->getCryptoSuite().compare((*iter_local).name)){ + if ( (*iter_offer)->getCryptoSuite().compare ( (*iter_local).name)) { - negotiationSuccess = true; + negotiationSuccess = true; - _cryptoSuite = (*iter_offer)->getCryptoSuite(); - _srtpKeyMethod = (*iter_offer)->getSrtpKeyMethod(); - _srtpKeyInfo = (*iter_offer)->getSrtpKeyInfo(); - _lifetime = (*iter_offer)->getLifetime(); - _mkiValue = (*iter_offer)->getMkiValue(); - _mkiLength = (*iter_offer)->getMkiLength(); - } + _cryptoSuite = (*iter_offer)->getCryptoSuite(); + _srtpKeyMethod = (*iter_offer)->getSrtpKeyMethod(); + _srtpKeyInfo = (*iter_offer)->getSrtpKeyInfo(); + _lifetime = (*iter_offer)->getLifetime(); + _mkiValue = (*iter_offer)->getMkiValue(); + _mkiLength = (*iter_offer)->getMkiLength(); + } - iter_local++; - } + iter_local++; + } + + delete (*iter_offer); + + iter_offer++; + } - delete (*iter_offer); - - iter_offer++; - } - } catch (parse_error& exception) { return false; } catch (match_error& exception) { return false; } - + return negotiationSuccess; } diff --git a/sflphone-common/src/sip/sdp.cpp b/sflphone-common/src/sip/sdp.cpp index d98386916c9f50af296138a35eb7b8d7e0b150a7..b578d87c8062f9701e011fbf28fbdb38bdae9a05 100644 --- a/sflphone-common/src/sip/sdp.cpp +++ b/sflphone-common/src/sip/sdp.cpp @@ -56,15 +56,13 @@ Sdp::Sdp (pj_pool_t *pool) , _local_offer (NULL) , _negociated_offer (NULL) , _pool (NULL) - , _local_extern_audio_port (0) -{ + , _local_extern_audio_port (0) { _pool = pool; } -Sdp::~Sdp() -{ - // clean_session_media(); - // clean_local_media_capabilities(); +Sdp::~Sdp() { + // clean_session_media(); + // clean_local_media_capabilities(); } void Sdp::set_media_descriptor_line (sdpMedia *media, pjmedia_sdp_media** p_med) { @@ -85,11 +83,10 @@ void Sdp::set_media_descriptor_line (sdpMedia *media, pjmedia_sdp_media** p_med) med->desc.port = media->get_port(); // in case of sdes, media are tagged as "RTP/SAVP", RTP/AVP elsewhere - if(_srtp_crypto.empty()) { - + if (_srtp_crypto.empty()) { + pj_strdup (_pool, &med->desc.transport, &STR_RTP_AVP); - } - else { + } else { pj_strdup (_pool, &med->desc.transport, &STR_RTP_SAVP); } @@ -114,11 +111,10 @@ void Sdp::set_media_descriptor_line (sdpMedia *media, pjmedia_sdp_media** p_med) rtpmap.enc_name = pj_str ( (char*) codec->getCodecName().c_str()); // G722 require G722/8000 media description even if it is 16000 codec - if(codec->getPayload () == 9) { - rtpmap.clock_rate = 8000; - } - else { - rtpmap.clock_rate = codec->getClockRate(); + if (codec->getPayload () == 9) { + rtpmap.clock_rate = 8000; + } else { + rtpmap.clock_rate = codec->getClockRate(); } // Add the channel number only if different from 1 @@ -156,7 +152,7 @@ int Sdp::create_local_offer (CodecOrder selectedCodecs) { pj_status_t status; - _info("SDP: Create local offer"); + _info ("SDP: Create local offer"); // Build local media capabilities set_local_media_capabilities (selectedCodecs); @@ -175,8 +171,8 @@ int Sdp::create_local_offer (CodecOrder selectedCodecs) { sdp_add_timing(); sdp_add_media_description(); - if(!_srtp_crypto.empty()) { - sdp_add_sdes_attribute(_srtp_crypto); + if (!_srtp_crypto.empty()) { + sdp_add_sdes_attribute (_srtp_crypto); } //toString (); @@ -195,7 +191,7 @@ int Sdp::create_initial_offer (CodecOrder selectedCodecs) { pj_status_t status; pjmedia_sdp_neg_state state; - _info("SDP: Create initial offer"); + _info ("SDP: Create initial offer"); // Build the SDP session descriptor status = create_local_offer (selectedCodecs); @@ -226,9 +222,9 @@ int Sdp::receiving_initial_offer (pjmedia_sdp_session* remote, CodecOrder select pj_status_t status; - if (!remote) { - return !PJ_SUCCESS; - } + if (!remote) { + return !PJ_SUCCESS; + } // 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 ) @@ -237,7 +233,7 @@ int Sdp::receiving_initial_offer (pjmedia_sdp_session* remote, CodecOrder select status = create_local_offer (selectedCodecs); if (status != PJ_SUCCESS) { - _error ("SDP: Error: Failed to create initial offer"); + _error ("SDP: Error: Failed to create initial offer"); return status; } @@ -245,7 +241,7 @@ int Sdp::receiving_initial_offer (pjmedia_sdp_session* remote, CodecOrder select this->set_media_transport_info_from_remote_sdp (remote); status = pjmedia_sdp_neg_create_w_remote_offer (_pool, - get_local_sdp_session(), remote, &_negociator); + get_local_sdp_session(), remote, &_negociator); PJ_ASSERT_RETURN (status == PJ_SUCCESS, 1); @@ -369,8 +365,7 @@ void Sdp::sdp_add_attributes() { } -void Sdp::sdp_add_media_description() -{ +void Sdp::sdp_add_media_description() { pjmedia_sdp_media* med; int nb_media, i; @@ -384,51 +379,49 @@ void Sdp::sdp_add_media_description() } } -void Sdp::sdp_add_sdes_attribute (std::vector<std::string>& crypto) -{ +void Sdp::sdp_add_sdes_attribute (std::vector<std::string>& crypto) { // temporary buffer used to store crypto attribute char tempbuf[256]; std::vector<std::string>::iterator iter = crypto.begin(); - while(iter != crypto.end()) { + while (iter != crypto.end()) { // the attribute to add to sdp - pjmedia_sdp_attr *attribute = (pjmedia_sdp_attr*) pj_pool_zalloc(_pool, sizeof(pjmedia_sdp_attr)); + pjmedia_sdp_attr *attribute = (pjmedia_sdp_attr*) pj_pool_zalloc (_pool, sizeof (pjmedia_sdp_attr)); - attribute->name = pj_strdup3(_pool, "crypto"); + attribute->name = pj_strdup3 (_pool, "crypto"); - // _debug("crypto from sdp: %s", crypto.c_str()); + // _debug("crypto from sdp: %s", crypto.c_str()); - - int len = pj_ansi_snprintf(tempbuf, sizeof(tempbuf), - "%.*s",(int)(*iter).size(), (*iter).c_str()); - - attribute->value.slen = len; - attribute->value.ptr = (char*) pj_pool_alloc (_pool, attribute->value.slen+1); - pj_memcpy (attribute->value.ptr, tempbuf, attribute->value.slen+1); - // get number of media for this SDP - int media_count = _local_offer->media_count; + int len = pj_ansi_snprintf (tempbuf, sizeof (tempbuf), + "%.*s", (int) (*iter).size(), (*iter).c_str()); - // add crypto attribute to media - for(int i = 0; i < media_count; i++) { + attribute->value.slen = len; + attribute->value.ptr = (char*) pj_pool_alloc (_pool, attribute->value.slen+1); + pj_memcpy (attribute->value.ptr, tempbuf, attribute->value.slen+1); - if(pjmedia_sdp_media_add_attr(_local_offer->media[i], attribute) != PJ_SUCCESS) { - // if(pjmedia_sdp_attr_add(&(_local_offer->attr_count), _local_offer->attr, attribute) != PJ_SUCCESS){ - throw sdpException(); - } - } + // get number of media for this SDP + int media_count = _local_offer->media_count; + // add crypto attribute to media + for (int i = 0; i < media_count; i++) { - iter++; + if (pjmedia_sdp_media_add_attr (_local_offer->media[i], attribute) != PJ_SUCCESS) { + // if(pjmedia_sdp_attr_add(&(_local_offer->attr_count), _local_offer->attr, attribute) != PJ_SUCCESS){ + throw sdpException(); + } + } + + + iter++; } } -void Sdp::sdp_add_zrtp_attribute (pjmedia_sdp_media* media, std::string hash) -{ +void Sdp::sdp_add_zrtp_attribute (pjmedia_sdp_media* media, std::string hash) { pjmedia_sdp_attr *attribute; char tempbuf[256]; int len; @@ -454,8 +447,7 @@ void Sdp::sdp_add_zrtp_attribute (pjmedia_sdp_media* media, std::string hash) } } -std::string Sdp::media_to_string (void) -{ +std::string Sdp::media_to_string (void) { int size, i; std::ostringstream res; @@ -470,45 +462,44 @@ std::string Sdp::media_to_string (void) return res.str(); } -void Sdp::clean_session_media() -{ - _info("SDP: Clean session media"); +void Sdp::clean_session_media() { + _info ("SDP: Clean session media"); - if(_session_media.size() > 0) { + if (_session_media.size() > 0) { - std::vector<sdpMedia *>::iterator iter = _session_media.begin(); - sdpMedia *media; + std::vector<sdpMedia *>::iterator iter = _session_media.begin(); + sdpMedia *media; - while(iter != _session_media.end()) { - media = *iter; - delete media; - iter++; - } - _session_media.clear(); - } + while (iter != _session_media.end()) { + media = *iter; + delete media; + iter++; + } + + _session_media.clear(); + } } -void Sdp::clean_local_media_capabilities() -{ - _info("SDP: Clean local media capabilities"); +void Sdp::clean_local_media_capabilities() { + _info ("SDP: Clean local media capabilities"); - if(_local_media_cap.size() > 0) { + if (_local_media_cap.size() > 0) { - std::vector<sdpMedia *>::iterator iter = _local_media_cap.begin(); - sdpMedia *media; + std::vector<sdpMedia *>::iterator iter = _local_media_cap.begin(); + sdpMedia *media; - while(iter != _local_media_cap.end()) { - media = *iter; - delete media; - iter++; - } - _local_media_cap.clear(); - } + while (iter != _local_media_cap.end()) { + media = *iter; + delete media; + iter++; + } + + _local_media_cap.clear(); + } } -void Sdp::set_negotiated_sdp (const pjmedia_sdp_session *sdp) -{ +void Sdp::set_negotiated_sdp (const pjmedia_sdp_session *sdp) { int nb_media, nb_codecs; int i,j, port; @@ -557,8 +548,7 @@ void Sdp::set_negotiated_sdp (const pjmedia_sdp_session *sdp) } } -AudioCodec* Sdp::get_session_media (void) -{ +AudioCodec* Sdp::get_session_media (void) { int nb_media; int nb_codec; @@ -582,22 +572,19 @@ AudioCodec* Sdp::get_session_media (void) } -pj_status_t Sdp::start_negociation() -{ - pj_status_t status; +pj_status_t Sdp::start_negociation() { + pj_status_t status; - if (_negociator) { - status = pjmedia_sdp_neg_negotiate(_pool, _negociator, 0); - } - else { - status = !PJ_SUCCESS; - } + if (_negociator) { + status = pjmedia_sdp_neg_negotiate (_pool, _negociator, 0); + } else { + status = !PJ_SUCCESS; + } - return status; + return status; } -void Sdp::toString (void) -{ +void Sdp::toString (void) { std::ostringstream sdp; int count, i; @@ -657,17 +644,15 @@ void Sdp::set_local_media_capabilities (CodecOrder selectedCodecs) { if (iter!=codecs_list.end()) { audio->add_codec (iter->second); + } else { + _warn ("SDP: Couldn't find audio codec"); } - else { - _warn ("SDP: Couldn't find audio codec"); - } - } + } _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; @@ -682,23 +667,20 @@ void Sdp::attribute_port_to_all_media (int 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::set_remote_ip_from_sdp (const pjmedia_sdp_session *r_sdp) -{ +void Sdp::set_remote_ip_from_sdp (const pjmedia_sdp_session *r_sdp) { std::string remote_ip (r_sdp->conn->addr.ptr, r_sdp->conn->addr.slen); _info ("SDP: Remote IP from fetching SDP: %s", remote_ip.c_str()); this->set_remote_ip (remote_ip); } -void Sdp::set_remote_audio_port_from_sdp (pjmedia_sdp_media *r_media) -{ +void Sdp::set_remote_audio_port_from_sdp (pjmedia_sdp_media *r_media) { int remote_port; @@ -707,13 +689,12 @@ void Sdp::set_remote_audio_port_from_sdp (pjmedia_sdp_media *r_media) this->set_remote_audio_port (remote_port); } -void Sdp::set_media_transport_info_from_remote_sdp (const pjmedia_sdp_session *remote_sdp) -{ +void Sdp::set_media_transport_info_from_remote_sdp (const pjmedia_sdp_session *remote_sdp) { _info ("SDP: Fetching media from sdp"); - if(!remote_sdp) - return; + if (!remote_sdp) + return; pjmedia_sdp_media *r_media; @@ -730,12 +711,11 @@ void Sdp::set_media_transport_info_from_remote_sdp (const pjmedia_sdp_session *r } -void Sdp::get_remote_sdp_media_from_offer (const pjmedia_sdp_session* remote_sdp, pjmedia_sdp_media** r_media) -{ +void Sdp::get_remote_sdp_media_from_offer (const pjmedia_sdp_session* remote_sdp, pjmedia_sdp_media** r_media) { int count, i; - if(!remote_sdp) - return; + if (!remote_sdp) + return; count = remote_sdp->media_count; *r_media = NULL; @@ -748,8 +728,7 @@ void Sdp::get_remote_sdp_media_from_offer (const pjmedia_sdp_session* remote_sdp } } -void Sdp::get_remote_sdp_crypto_from_offer (const pjmedia_sdp_session* remote_sdp, CryptoOffer& crypto_offer) -{ +void Sdp::get_remote_sdp_crypto_from_offer (const pjmedia_sdp_session* remote_sdp, CryptoOffer& crypto_offer) { int i, j; int attr_count, media_count; @@ -764,31 +743,31 @@ void Sdp::get_remote_sdp_crypto_from_offer (const pjmedia_sdp_session* remote_sd // iterate over all media for (i = 0; i < media_count; ++i) { - // get media - media = remote_sdp->media[i]; + // get media + media = remote_sdp->media[i]; - // get number of attribute for this memdia - attr_count = media->attr_count; + // get number of attribute for this memdia + attr_count = media->attr_count; - // iterate over all attribute for this media - for(j = 0; j < attr_count; j++) { + // iterate over all attribute for this media + for (j = 0; j < attr_count; j++) { - attribute = media->attr[j]; + attribute = media->attr[j]; - // test if this attribute is a crypto - if (pj_stricmp2 (&attribute->name, "crypto") == 0) { + // test if this attribute is a crypto + if (pj_stricmp2 (&attribute->name, "crypto") == 0) { - std::string attr(attribute->value.ptr, attribute->value.slen); + std::string attr (attribute->value.ptr, attribute->value.slen); - // @TODO our parser require the "a=crypto:" to be present - std::string full_attr = "a=crypto:"; - full_attr += attr; + // @TODO our parser require the "a=crypto:" to be present + std::string full_attr = "a=crypto:"; + full_attr += attr; - crypto_offer.push_back(full_attr); - } + crypto_offer.push_back (full_attr); + } - } + } } - + } diff --git a/sflphone-common/src/sip/sdpmedia.cpp b/sflphone-common/src/sip/sdpmedia.cpp index 95955a51db652bc9ebd92c553589e7d82a563a77..3ac118d8ebc3f41b1bf1ae201d6af66391176734 100644 --- a/sflphone-common/src/sip/sdpmedia.cpp +++ b/sflphone-common/src/sip/sdpmedia.cpp @@ -55,8 +55,7 @@ sdpMedia::sdpMedia (int type) sdpMedia::sdpMedia (std::string type, int port, std::string dir) : _media_type ( (mediaType)-1), _codec_list (0), _port (port), - _stream_type ( (streamDirection)-1) -{ + _stream_type ( (streamDirection)-1) { unsigned int i; const char* tmp; @@ -83,14 +82,12 @@ sdpMedia::sdpMedia (std::string type, int port, std::string dir) } -sdpMedia::~sdpMedia() -{ - clear_codec_list(); +sdpMedia::~sdpMedia() { + clear_codec_list(); } -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 @@ -104,13 +101,11 @@ std::string sdpMedia::get_media_type_str (void) } -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; int size; @@ -133,15 +128,13 @@ void sdpMedia::remove_codec (std::string codecName) } -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 @@ -155,8 +148,7 @@ std::string sdpMedia::get_stream_direction_str (void) } -std::string sdpMedia::to_string (void) -{ +std::string sdpMedia::to_string (void) { std::ostringstream display; int size, i; diff --git a/sflphone-common/src/sip/sipaccount.cpp b/sflphone-common/src/sip/sipaccount.cpp old mode 100755 new mode 100644 index 4a9bfb8b88a53b67b73de87cbd4024ba7e133263..63d63f54531cb667b0200a771d190e66985f160b --- a/sflphone-common/src/sip/sipaccount.cpp +++ b/sflphone-common/src/sip/sipaccount.cpp @@ -40,57 +40,57 @@ // CredentialItem::~CredentialItem() {} -Credentials::Credentials() : credentialCount(0) {} +Credentials::Credentials() : credentialCount (0) {} Credentials::~Credentials() {} -void Credentials::setNewCredential(std::string username, std::string password, std::string realm) -{ - credentialArray[credentialCount].username = username; - credentialArray[credentialCount].password = password; - credentialArray[credentialCount].realm = realm; +void Credentials::setNewCredential (std::string username, std::string password, std::string realm) { + credentialArray[credentialCount].username = username; + credentialArray[credentialCount].password = password; + credentialArray[credentialCount].realm = realm; } -CredentialItem *Credentials::getCredential(int index) -{ - if((index >= 0) && (index < credentialCount)) - return &(credentialArray[index]); - else - return NULL; +CredentialItem *Credentials::getCredential (int index) { + if ( (index >= 0) && (index < credentialCount)) + return & (credentialArray[index]); + else + return NULL; } -void Credentials::serialize(Conf::YamlEmitter *emitter) -{ - +void Credentials::serialize (Conf::YamlEmitter *emitter) { + } -void Credentials::unserialize(Conf::MappingNode *map) -{ +void Credentials::unserialize (Conf::MappingNode *map) { + + Conf::ScalarNode *val = NULL; - Conf::ScalarNode *val = NULL; + _debug ("SipAccount: Unserialize"); - _debug("SipAccount: Unserialize"); + val = (Conf::ScalarNode *) (map->getValue (credentialCountKey)); - val = (Conf::ScalarNode *)(map->getValue(credentialCountKey)); - if(val) { credentialCount = atoi(val->getValue().data()); val = NULL; } + if (val) { + credentialCount = atoi (val->getValue().data()); + val = NULL; + } } SIPAccount::SIPAccount (const AccountID& accountID) : Account (accountID, "SIP") - , _routeSet("") + , _routeSet ("") , _regc (NULL) , _bRegister (false) , _registrationExpire ("") - , _interface("default") + , _interface ("default") , _publishedSameasLocal (true) , _publishedIpAddress ("") , _localPort (atoi (DEFAULT_SIP_PORT)) , _publishedPort (atoi (DEFAULT_SIP_PORT)) - , _serviceRoute("") - , _tlsListenerPort (atoi (DEFAULT_SIP_TLS_PORT)) + , _serviceRoute ("") + , _tlsListenerPort (atoi (DEFAULT_SIP_TLS_PORT)) , _transportType (PJSIP_TRANSPORT_UNSPECIFIED) , _transport (NULL) , _resolveOnce (false) @@ -98,40 +98,39 @@ SIPAccount::SIPAccount (const AccountID& accountID) , _realm (DEFAULT_REALM) , _authenticationUsername ("") , _tlsSetting (NULL) - , _dtmfType(OVERRTP) - , _tlsEnable("") - , _tlsPortStr(DEFAULT_SIP_TLS_PORT) - , _tlsCaListFile("") - , _tlsCertificateFile("") - , _tlsPrivateKeyFile("") - , _tlsPassword("") - , _tlsMethod("TLSv1") - , _tlsCiphers("") - , _tlsServerName("") - , _tlsVerifyServer(true) - , _tlsVerifyClient(true) - , _tlsRequireClientCertificate(true) - , _tlsNegotiationTimeoutSec("2") - , _tlsNegotiationTimeoutMsec("0") - , _stunServer(DFT_STUN_SERVER) - , _tlsEnabled(false) - , _stunEnabled(false) - , _srtpEnabled(false) - , _srtpKeyExchange("sdes") - , _srtpFallback(false) - , _zrtpDisplaySas(true) - , _zrtpDisplaySasOnce(false) - , _zrtpHelloHash(true) - , _zrtpNotSuppWarning(true) -{ - - _debug("Sip account constructor called"); - + , _dtmfType (OVERRTP) + , _tlsEnable ("") + , _tlsPortStr (DEFAULT_SIP_TLS_PORT) + , _tlsCaListFile ("") + , _tlsCertificateFile ("") + , _tlsPrivateKeyFile ("") + , _tlsPassword ("") + , _tlsMethod ("TLSv1") + , _tlsCiphers ("") + , _tlsServerName ("") + , _tlsVerifyServer (true) + , _tlsVerifyClient (true) + , _tlsRequireClientCertificate (true) + , _tlsNegotiationTimeoutSec ("2") + , _tlsNegotiationTimeoutMsec ("0") + , _stunServer (DFT_STUN_SERVER) + , _tlsEnabled (false) + , _stunEnabled (false) + , _srtpEnabled (false) + , _srtpKeyExchange ("sdes") + , _srtpFallback (false) + , _zrtpDisplaySas (true) + , _zrtpDisplaySasOnce (false) + , _zrtpHelloHash (true) + , _zrtpNotSuppWarning (true) { + + _debug ("Sip account constructor called"); + _stunServerName.ptr = NULL; _stunServerName.slen = 0; _stunPort = 0; - // IP2IP settings must be loaded before singleton instanciation, cannot call it here... + // IP2IP settings must be loaded before singleton instanciation, cannot call it here... // _link = SIPVoIPLink::instance (""); @@ -140,11 +139,10 @@ SIPAccount::SIPAccount (const AccountID& accountID) } -SIPAccount::~SIPAccount() -{ +SIPAccount::~SIPAccount() { /* One SIP account less connected to the sip voiplink */ - if(_accountID != "default") - dynamic_cast<SIPVoIPLink*> (_link)->decrementClients(); + if (_accountID != "default") + dynamic_cast<SIPVoIPLink*> (_link)->decrementClients(); /* Delete accounts-related information */ _regc = NULL; @@ -152,552 +150,762 @@ SIPAccount::~SIPAccount() free (_tlsSetting); } -void SIPAccount::serialize(Conf::YamlEmitter *emitter) { - - _debug("SipAccount: serialize %s", _accountID.c_str()); - - - Conf::MappingNode accountmap(NULL); - Conf::MappingNode credentialmap(NULL); - Conf::MappingNode srtpmap(NULL); - Conf::MappingNode zrtpmap(NULL); - Conf::MappingNode tlsmap(NULL); - - Conf::ScalarNode id(Account::_accountID); - Conf::ScalarNode username(Account::_username); - Conf::ScalarNode password(Account::_password); - Conf::ScalarNode alias(Account::_alias); - Conf::ScalarNode hostname(Account::_hostname); - Conf::ScalarNode enable(_enabled ? "true" : "false"); - Conf::ScalarNode type(Account::_type); - Conf::ScalarNode expire(_registrationExpire); - Conf::ScalarNode interface(_interface); - std::stringstream portstr; portstr << _localPort; - Conf::ScalarNode port(portstr.str()); - Conf::ScalarNode serviceRoute(_serviceRoute); - - Conf::ScalarNode mailbox("97"); - Conf::ScalarNode publishAddr(_publishedIpAddress); - std::stringstream publicportstr; publicportstr << _publishedPort; - Conf::ScalarNode publishPort(publicportstr.str()); - Conf::ScalarNode sameasLocal(_publishedSameasLocal ? "true" : "false"); - Conf::ScalarNode resolveOnce(_resolveOnce ? "true" : "false"); - Conf::ScalarNode codecs(_codecStr); - Conf::ScalarNode ringtonePath(_ringtonePath); - Conf::ScalarNode ringtoneEnabled(_ringtoneEnabled ? "true" : "false"); - Conf::ScalarNode stunServer(_stunServer); - Conf::ScalarNode stunEnabled(_stunEnabled ? "true" : "false"); - Conf::ScalarNode displayName(_displayName); - Conf::ScalarNode dtmfType(_dtmfType==0 ? "overrtp" : "sipinfo"); - - std::stringstream countstr; countstr << 0; - Conf::ScalarNode count(countstr.str()); - - Conf::ScalarNode srtpenabled(_srtpEnabled ? "true" : "false"); - Conf::ScalarNode keyExchange(_srtpKeyExchange); - Conf::ScalarNode rtpFallback(_srtpFallback ? "true" : "false"); - - Conf::ScalarNode displaySas(_zrtpDisplaySas ? "true" : "false"); - Conf::ScalarNode displaySasOnce(_zrtpDisplaySasOnce ? "true" : "false"); - Conf::ScalarNode helloHashEnabled(_zrtpHelloHash ? "true" : "false"); - Conf::ScalarNode notSuppWarning(_zrtpNotSuppWarning ? "true" : "false"); - - Conf::ScalarNode tlsport(_tlsPortStr); - Conf::ScalarNode certificate(_tlsCertificateFile); - Conf::ScalarNode calist(_tlsCaListFile); - Conf::ScalarNode ciphers(_tlsCiphers); - Conf::ScalarNode tlsenabled(_tlsEnable); - Conf::ScalarNode tlsmethod(_tlsMethod); - Conf::ScalarNode timeout(_tlsNegotiationTimeoutSec); - Conf::ScalarNode tlspassword(_tlsPassword); - Conf::ScalarNode privatekey(_tlsPrivateKeyFile); - Conf::ScalarNode requirecertif(_tlsRequireClientCertificate ? "true" : "false"); - Conf::ScalarNode server(_tlsServerName); - Conf::ScalarNode verifyclient(_tlsVerifyServer ? "true" : "false"); - Conf::ScalarNode verifyserver(_tlsVerifyClient ? "true" : "false"); - - accountmap.setKeyValue(aliasKey, &alias); - accountmap.setKeyValue(typeKey, &type); - accountmap.setKeyValue(idKey, &id); - accountmap.setKeyValue(usernameKey, &username); - accountmap.setKeyValue(passwordKey, &password); - accountmap.setKeyValue(hostnameKey, &hostname); - accountmap.setKeyValue(accountEnableKey, &enable); - accountmap.setKeyValue(mailboxKey, &mailbox); - accountmap.setKeyValue(expireKey, &expire); - accountmap.setKeyValue(interfaceKey, &interface); - accountmap.setKeyValue(portKey, &port); - accountmap.setKeyValue(stunServerKey, &stunServer); - accountmap.setKeyValue(stunEnabledKey, &stunEnabled); - accountmap.setKeyValue(publishAddrKey, &publishAddr); - accountmap.setKeyValue(publishPortKey, &publishPort); - accountmap.setKeyValue(sameasLocalKey, &sameasLocal); - accountmap.setKeyValue(resolveOnceKey, &resolveOnce); - accountmap.setKeyValue(serviceRouteKey, &serviceRoute); - accountmap.setKeyValue(dtmfTypeKey, &dtmfType); - accountmap.setKeyValue(displayNameKey, &displayName); - accountmap.setKeyValue(codecsKey, &codecs); - accountmap.setKeyValue(ringtonePathKey, &ringtonePath); - accountmap.setKeyValue(ringtoneEnabledKey, &ringtoneEnabled); - - accountmap.setKeyValue(srtpKey, &srtpmap); - srtpmap.setKeyValue(srtpEnableKey, &srtpenabled); - srtpmap.setKeyValue(keyExchangeKey, &keyExchange); - srtpmap.setKeyValue(rtpFallbackKey, &rtpFallback); - - accountmap.setKeyValue(zrtpKey, &zrtpmap); - zrtpmap.setKeyValue(displaySasKey, &displaySas); - zrtpmap.setKeyValue(displaySasOnceKey, &displaySasOnce); - zrtpmap.setKeyValue(helloHashEnabledKey, &helloHashEnabled); - zrtpmap.setKeyValue(notSuppWarningKey, ¬SuppWarning); - - accountmap.setKeyValue(credKey, &credentialmap); - credentialmap.setKeyValue(credentialCountKey, &count); - - accountmap.setKeyValue(tlsKey, &tlsmap); - tlsmap.setKeyValue(tlsPortKey, &tlsport); - tlsmap.setKeyValue(certificateKey, &certificate); - tlsmap.setKeyValue(calistKey, &calist); - tlsmap.setKeyValue(ciphersKey, &ciphers); - tlsmap.setKeyValue(tlsEnableKey, &tlsenabled); - tlsmap.setKeyValue(methodKey, &tlsmethod); - tlsmap.setKeyValue(timeoutKey, &timeout); - tlsmap.setKeyValue(tlsPasswordKey, &tlspassword); - tlsmap.setKeyValue(privateKeyKey, &privatekey); - tlsmap.setKeyValue(requireCertifKey, &requirecertif); - tlsmap.setKeyValue(serverKey, &server); - tlsmap.setKeyValue(verifyClientKey, &verifyclient); - tlsmap.setKeyValue(verifyServerKey, &verifyserver); - - try{ - emitter->serializeAccount(&accountmap); - } - catch (Conf::YamlEmitterException &e) { - _error("ConfigTree: %s", e.what()); - } +void SIPAccount::serialize (Conf::YamlEmitter *emitter) { + + _debug ("SipAccount: serialize %s", _accountID.c_str()); + + + Conf::MappingNode accountmap (NULL); + Conf::MappingNode credentialmap (NULL); + Conf::MappingNode srtpmap (NULL); + Conf::MappingNode zrtpmap (NULL); + Conf::MappingNode tlsmap (NULL); + + Conf::ScalarNode id (Account::_accountID); + Conf::ScalarNode username (Account::_username); + Conf::ScalarNode password (Account::_password); + Conf::ScalarNode alias (Account::_alias); + Conf::ScalarNode hostname (Account::_hostname); + Conf::ScalarNode enable (_enabled ? "true" : "false"); + Conf::ScalarNode type (Account::_type); + Conf::ScalarNode expire (_registrationExpire); + Conf::ScalarNode interface (_interface); + std::stringstream portstr; + portstr << _localPort; + Conf::ScalarNode port (portstr.str()); + Conf::ScalarNode serviceRoute (_serviceRoute); + + Conf::ScalarNode mailbox ("97"); + Conf::ScalarNode publishAddr (_publishedIpAddress); + std::stringstream publicportstr; + publicportstr << _publishedPort; + Conf::ScalarNode publishPort (publicportstr.str()); + Conf::ScalarNode sameasLocal (_publishedSameasLocal ? "true" : "false"); + Conf::ScalarNode resolveOnce (_resolveOnce ? "true" : "false"); + Conf::ScalarNode codecs (_codecStr); + Conf::ScalarNode ringtonePath (_ringtonePath); + Conf::ScalarNode ringtoneEnabled (_ringtoneEnabled ? "true" : "false"); + Conf::ScalarNode stunServer (_stunServer); + Conf::ScalarNode stunEnabled (_stunEnabled ? "true" : "false"); + Conf::ScalarNode displayName (_displayName); + Conf::ScalarNode dtmfType (_dtmfType==0 ? "overrtp" : "sipinfo"); + + std::stringstream countstr; + countstr << 0; + Conf::ScalarNode count (countstr.str()); + + Conf::ScalarNode srtpenabled (_srtpEnabled ? "true" : "false"); + Conf::ScalarNode keyExchange (_srtpKeyExchange); + Conf::ScalarNode rtpFallback (_srtpFallback ? "true" : "false"); + + Conf::ScalarNode displaySas (_zrtpDisplaySas ? "true" : "false"); + Conf::ScalarNode displaySasOnce (_zrtpDisplaySasOnce ? "true" : "false"); + Conf::ScalarNode helloHashEnabled (_zrtpHelloHash ? "true" : "false"); + Conf::ScalarNode notSuppWarning (_zrtpNotSuppWarning ? "true" : "false"); + + Conf::ScalarNode tlsport (_tlsPortStr); + Conf::ScalarNode certificate (_tlsCertificateFile); + Conf::ScalarNode calist (_tlsCaListFile); + Conf::ScalarNode ciphers (_tlsCiphers); + Conf::ScalarNode tlsenabled (_tlsEnable); + Conf::ScalarNode tlsmethod (_tlsMethod); + Conf::ScalarNode timeout (_tlsNegotiationTimeoutSec); + Conf::ScalarNode tlspassword (_tlsPassword); + Conf::ScalarNode privatekey (_tlsPrivateKeyFile); + Conf::ScalarNode requirecertif (_tlsRequireClientCertificate ? "true" : "false"); + Conf::ScalarNode server (_tlsServerName); + Conf::ScalarNode verifyclient (_tlsVerifyServer ? "true" : "false"); + Conf::ScalarNode verifyserver (_tlsVerifyClient ? "true" : "false"); + + accountmap.setKeyValue (aliasKey, &alias); + accountmap.setKeyValue (typeKey, &type); + accountmap.setKeyValue (idKey, &id); + accountmap.setKeyValue (usernameKey, &username); + accountmap.setKeyValue (passwordKey, &password); + accountmap.setKeyValue (hostnameKey, &hostname); + accountmap.setKeyValue (accountEnableKey, &enable); + accountmap.setKeyValue (mailboxKey, &mailbox); + accountmap.setKeyValue (expireKey, &expire); + accountmap.setKeyValue (interfaceKey, &interface); + accountmap.setKeyValue (portKey, &port); + accountmap.setKeyValue (stunServerKey, &stunServer); + accountmap.setKeyValue (stunEnabledKey, &stunEnabled); + accountmap.setKeyValue (publishAddrKey, &publishAddr); + accountmap.setKeyValue (publishPortKey, &publishPort); + accountmap.setKeyValue (sameasLocalKey, &sameasLocal); + accountmap.setKeyValue (resolveOnceKey, &resolveOnce); + accountmap.setKeyValue (serviceRouteKey, &serviceRoute); + accountmap.setKeyValue (dtmfTypeKey, &dtmfType); + accountmap.setKeyValue (displayNameKey, &displayName); + accountmap.setKeyValue (codecsKey, &codecs); + accountmap.setKeyValue (ringtonePathKey, &ringtonePath); + accountmap.setKeyValue (ringtoneEnabledKey, &ringtoneEnabled); + + accountmap.setKeyValue (srtpKey, &srtpmap); + srtpmap.setKeyValue (srtpEnableKey, &srtpenabled); + srtpmap.setKeyValue (keyExchangeKey, &keyExchange); + srtpmap.setKeyValue (rtpFallbackKey, &rtpFallback); + + accountmap.setKeyValue (zrtpKey, &zrtpmap); + zrtpmap.setKeyValue (displaySasKey, &displaySas); + zrtpmap.setKeyValue (displaySasOnceKey, &displaySasOnce); + zrtpmap.setKeyValue (helloHashEnabledKey, &helloHashEnabled); + zrtpmap.setKeyValue (notSuppWarningKey, ¬SuppWarning); + + accountmap.setKeyValue (credKey, &credentialmap); + credentialmap.setKeyValue (credentialCountKey, &count); + + accountmap.setKeyValue (tlsKey, &tlsmap); + tlsmap.setKeyValue (tlsPortKey, &tlsport); + tlsmap.setKeyValue (certificateKey, &certificate); + tlsmap.setKeyValue (calistKey, &calist); + tlsmap.setKeyValue (ciphersKey, &ciphers); + tlsmap.setKeyValue (tlsEnableKey, &tlsenabled); + tlsmap.setKeyValue (methodKey, &tlsmethod); + tlsmap.setKeyValue (timeoutKey, &timeout); + tlsmap.setKeyValue (tlsPasswordKey, &tlspassword); + tlsmap.setKeyValue (privateKeyKey, &privatekey); + tlsmap.setKeyValue (requireCertifKey, &requirecertif); + tlsmap.setKeyValue (serverKey, &server); + tlsmap.setKeyValue (verifyClientKey, &verifyclient); + tlsmap.setKeyValue (verifyServerKey, &verifyserver); + + try { + emitter->serializeAccount (&accountmap); + } catch (Conf::YamlEmitterException &e) { + _error ("ConfigTree: %s", e.what()); + } +} + + +void SIPAccount::unserialize (Conf::MappingNode *map) { + Conf::ScalarNode *val; + Conf::MappingNode *srtpMap; + Conf::MappingNode *tlsMap; + Conf::MappingNode *zrtpMap; + Conf::MappingNode *credMap; + + _debug ("SipAccount: Unserialize %s", _accountID.c_str()); + + val = (Conf::ScalarNode *) (map->getValue (aliasKey)); + + if (val) { + _alias = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (typeKey)); + + if (val) { + _type = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (idKey)); + + if (val) { + _accountID = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (usernameKey)); + + if (val) { + _username = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (passwordKey)); + + if (val) { + _password = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (hostnameKey)); + + if (val) { + _hostname = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (accountEnableKey)); + + if (val) { + _enabled = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + // val = (Conf::ScalarNode *)(map->getValue(mailboxKey)); + + val = (Conf::ScalarNode *) (map->getValue (codecsKey)); + + if (val) { + _codecStr = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (ringtonePathKey)); + + if (val) { + _ringtonePath = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (ringtoneEnabledKey)); + + if (val) { + _ringtoneEnabled = (val->getValue() == "true") ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (expireKey)); + + if (val) { + _registrationExpire = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (interfaceKey)); + + if (val) { + _interface = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (portKey)); + + if (val) { + _localPort = atoi (val->getValue().data()); + val = NULL; + } + + // val = (Conf::ScalarNode *)(map->getValue(mailboxKey)); + val = (Conf::ScalarNode *) (map->getValue (publishAddrKey)); + + if (val) { + _publishedIpAddress = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (publishPortKey)); + + if (val) { + _publishedPort = atoi (val->getValue().data()); + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (sameasLocalKey)); + + if (val) { + _publishedSameasLocal = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (resolveOnceKey)); + + if (val) { + _resolveOnce = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (dtmfTypeKey)); + + if (val) { + val = NULL; + } + + // _dtmfType = atoi(val->getValue(); + val = (Conf::ScalarNode *) (map->getValue (serviceRouteKey)); + + if (val) { + _serviceRoute = val->getValue(); + } + + // stun enabled + val = (Conf::ScalarNode *) (map->getValue (stunEnabledKey)); + + if (val) { + _stunEnabled = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (map->getValue (stunServerKey)); + + if (val) { + _stunServer = val->getValue(); + val = NULL; + } + + _stunServerName = pj_str ( (char*) _stunServer.data()); + + credMap = (Conf::MappingNode *) (map->getValue (credKey)); + credentials.unserialize (credMap); + + val = (Conf::ScalarNode *) (map->getValue (displayNameKey)); + + if (val) { + _displayName = val->getValue(); + val = NULL; + } + + // get srtp submap + srtpMap = (Conf::MappingNode *) (map->getValue (srtpKey)); + + if (!srtpMap) + throw SipAccountException (" did not found srtp map"); + + val = (Conf::ScalarNode *) (srtpMap->getValue (srtpEnableKey)); + + if (val) { + _srtpEnabled = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (srtpMap->getValue (keyExchangeKey)); + + if (val) { + _srtpKeyExchange = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (srtpMap->getValue (rtpFallbackKey)); + + if (val) { + _srtpFallback = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + // get zrtp submap + zrtpMap = (Conf::MappingNode *) (map->getValue (zrtpKey)); + + if (!zrtpMap) + throw SipAccountException (" did not found zrtp map"); + + val = (Conf::ScalarNode *) (zrtpMap->getValue (displaySasKey)); + + if (val) { + _zrtpDisplaySas = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (zrtpMap->getValue (displaySasOnceKey)); + + if (val) { + _zrtpDisplaySasOnce = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (zrtpMap->getValue (helloHashEnabledKey)); + + if (val) { + _zrtpHelloHash = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (zrtpMap->getValue (notSuppWarningKey)); + + if (val) { + _zrtpNotSuppWarning = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + // get tls submap + tlsMap = (Conf::MappingNode *) (map->getValue (tlsKey)); + + if (!tlsMap) + throw SipAccountException (" did not found tls map"); + + val = (Conf::ScalarNode *) (tlsMap->getValue (tlsEnableKey)); + + if (val) { + _tlsEnable = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (tlsMap->getValue (tlsPortKey)); + + if (val) { + _tlsPortStr = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (tlsMap->getValue (certificateKey)); + + if (val) { + _tlsCertificateFile = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (tlsMap->getValue (calistKey)); + + if (val) { + _tlsCaListFile = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (tlsMap->getValue (ciphersKey)); + + if (val) { + _tlsCiphers = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (tlsMap->getValue (methodKey)); + + if (val) { + _tlsMethod = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (tlsMap->getValue (timeoutKey)); + + if (val) _tlsNegotiationTimeoutSec = val->getValue(); + + if (val) { + _tlsNegotiationTimeoutMsec = val->getValue(); + val=NULL; + } + + val = (Conf::ScalarNode *) (tlsMap->getValue (tlsPasswordKey)); + + if (val) { + _tlsPassword = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (tlsMap->getValue (privateKeyKey)); + + if (val) { + _tlsPrivateKeyFile = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (tlsMap->getValue (requireCertifKey)); + + if (val) { + _tlsRequireClientCertificate = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (tlsMap->getValue (serverKey)); + + if (val) { + _tlsServerName = val->getValue(); + val = NULL; + } + + val = (Conf::ScalarNode *) (tlsMap->getValue (verifyClientKey)); + + if (val) { + _tlsVerifyServer = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + + val = (Conf::ScalarNode *) (tlsMap->getValue (verifyServerKey)); + + if (val) { + _tlsVerifyClient = (val->getValue().compare ("true") == 0) ? true : false; + val = NULL; + } + } -void SIPAccount::unserialize(Conf::MappingNode *map) -{ - Conf::ScalarNode *val; - Conf::MappingNode *srtpMap; - Conf::MappingNode *tlsMap; - Conf::MappingNode *zrtpMap; - Conf::MappingNode *credMap; - - _debug("SipAccount: Unserialize %s", _accountID.c_str()); - - val = (Conf::ScalarNode *)(map->getValue(aliasKey)); - if(val) { _alias = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(typeKey)); - if(val) { _type = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(idKey)); - if(val) { _accountID = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(usernameKey)); - if(val) { _username = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(passwordKey)); - if(val) { _password = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(hostnameKey)); - if(val) { _hostname = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(accountEnableKey)); - if(val) { _enabled = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - // val = (Conf::ScalarNode *)(map->getValue(mailboxKey)); - - val = (Conf::ScalarNode *)(map->getValue(codecsKey)); - if(val) { _codecStr = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(ringtonePathKey)); - if(val) { _ringtonePath = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(ringtoneEnabledKey)); - if(val) { _ringtoneEnabled = (val->getValue() == "true") ? true : false; val = NULL; } - - val = (Conf::ScalarNode *)(map->getValue(expireKey)); - if(val) { _registrationExpire = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(interfaceKey)); - if(val) { _interface = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(portKey)); - if(val) { _localPort = atoi(val->getValue().data()); val = NULL; } - // val = (Conf::ScalarNode *)(map->getValue(mailboxKey)); - val = (Conf::ScalarNode *)(map->getValue(publishAddrKey)); - if(val) { _publishedIpAddress = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(publishPortKey)); - if(val) { _publishedPort = atoi(val->getValue().data()); val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(sameasLocalKey)); - if(val) { _publishedSameasLocal = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(resolveOnceKey)); - if(val) { _resolveOnce = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(dtmfTypeKey)); - if(val) { val = NULL; } - // _dtmfType = atoi(val->getValue(); - val = (Conf::ScalarNode *)(map->getValue(serviceRouteKey)); - if(val) { _serviceRoute = val->getValue(); } - - // stun enabled - val = (Conf::ScalarNode *)(map->getValue(stunEnabledKey)); - if(val) { _stunEnabled = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(map->getValue(stunServerKey)); - if(val) { _stunServer = val->getValue(); val = NULL; } - _stunServerName = pj_str ( (char*) _stunServer.data()); - - credMap = (Conf::MappingNode *)(map->getValue(credKey)); - credentials.unserialize(credMap); - - val = (Conf::ScalarNode *)(map->getValue(displayNameKey)); - if(val) { _displayName = val->getValue(); val = NULL; } - - // get srtp submap - srtpMap = (Conf::MappingNode *)(map->getValue(srtpKey)); - if(!srtpMap) - throw SipAccountException(" did not found srtp map"); - - val = (Conf::ScalarNode *)(srtpMap->getValue(srtpEnableKey)); - if(val) { _srtpEnabled = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(srtpMap->getValue(keyExchangeKey)); - if(val) { _srtpKeyExchange = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(srtpMap->getValue(rtpFallbackKey)); - if(val) { _srtpFallback = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - - // get zrtp submap - zrtpMap = (Conf::MappingNode *)(map->getValue(zrtpKey)); - if(!zrtpMap) - throw SipAccountException(" did not found zrtp map"); - - val = (Conf::ScalarNode *)(zrtpMap->getValue(displaySasKey)); - if(val) { _zrtpDisplaySas = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(zrtpMap->getValue(displaySasOnceKey)); - if(val) { _zrtpDisplaySasOnce = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(zrtpMap->getValue(helloHashEnabledKey)); - if(val) { _zrtpHelloHash = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(zrtpMap->getValue(notSuppWarningKey)); - if(val) { _zrtpNotSuppWarning = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - - // get tls submap - tlsMap = (Conf::MappingNode *)(map->getValue(tlsKey)); - if(!tlsMap) - throw SipAccountException(" did not found tls map"); - - val = (Conf::ScalarNode *)(tlsMap->getValue(tlsEnableKey)); - if(val) { _tlsEnable = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(tlsMap->getValue(tlsPortKey)); - if(val) { _tlsPortStr = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(tlsMap->getValue(certificateKey)); - if(val) { _tlsCertificateFile = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(tlsMap->getValue(calistKey)); - if(val) { _tlsCaListFile = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(tlsMap->getValue(ciphersKey)); - if(val) { _tlsCiphers = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(tlsMap->getValue(methodKey)); - if(val) { _tlsMethod = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(tlsMap->getValue(timeoutKey)); - if(val) _tlsNegotiationTimeoutSec = val->getValue(); - if(val) { _tlsNegotiationTimeoutMsec = val->getValue(); val=NULL; } - val = (Conf::ScalarNode *)(tlsMap->getValue(tlsPasswordKey)); - if(val) { _tlsPassword = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(tlsMap->getValue(privateKeyKey)); - if(val) { _tlsPrivateKeyFile = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(tlsMap->getValue(requireCertifKey)); - if(val) { _tlsRequireClientCertificate = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(tlsMap->getValue(serverKey)); - if(val) { _tlsServerName = val->getValue(); val = NULL; } - val = (Conf::ScalarNode *)(tlsMap->getValue(verifyClientKey)); - if(val) { _tlsVerifyServer = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } - val = (Conf::ScalarNode *)(tlsMap->getValue(verifyServerKey)); - if(val) { _tlsVerifyClient = (val->getValue().compare("true") == 0) ? true : false; val = NULL; } +void SIPAccount::setAccountDetails (const std::map<std::string, std::string>& details) { + + std::map<std::string, std::string> map_cpy; + std::map<std::string, std::string>::iterator iter; + + _debug ("SipAccount: set account details %s", _accountID.c_str()); + + // Work on a copy + map_cpy = details; + + std::string alias; + std::string type; + std::string hostname; + std::string username; + std::string password; + std::string mailbox; + std::string accountEnable; + std::string ringtonePath; + std::string ringtoneEnabled; + + // Account setting common to SIP and IAX + find_in_map (CONFIG_ACCOUNT_ALIAS, alias) + find_in_map (CONFIG_ACCOUNT_TYPE, type) + find_in_map (HOSTNAME, hostname) + find_in_map (USERNAME, username) + find_in_map (PASSWORD, password) + find_in_map (CONFIG_ACCOUNT_MAILBOX, mailbox); + find_in_map (CONFIG_ACCOUNT_ENABLE, accountEnable); + find_in_map (CONFIG_RINGTONE_PATH, ringtonePath); + find_in_map (CONFIG_RINGTONE_ENABLED, ringtoneEnabled); + + setAlias (alias); + setType (type); + setUsername (username); + setHostname (hostname); + setPassword (password); + setEnabled ( (accountEnable == "true")); + setRingtonePath (ringtonePath); + setRingtoneEnabled ( (ringtoneEnabled == "true")); + + // SIP specific account settings + if (getType() == "SIP") { + + std::string ua_name; + std::string realm; + std::string routeset; + std::string authenticationName; + + std::string resolveOnce; + std::string registrationExpire; + + std::string displayName; + std::string localInterface; + std::string publishedSameasLocal; + std::string localAddress; + std::string publishedAddress; + std::string localPort; + std::string publishedPort; + std::string stunEnable; + std::string stunServer; + std::string dtmfType; + std::string srtpEnable; + std::string srtpRtpFallback; + std::string zrtpDisplaySas; + std::string zrtpDisplaySasOnce; + std::string zrtpNotSuppWarning; + std::string zrtpHelloHash; + std::string srtpKeyExchange; + + std::string tlsListenerPort; + std::string tlsEnable; + std::string tlsCaListFile; + std::string tlsCertificateFile; + std::string tlsPrivateKeyFile; + std::string tlsPassword; + std::string tlsMethod; + std::string tlsCiphers; + std::string tlsServerName; + std::string tlsVerifyServer; + std::string tlsVerifyClient; + std::string tlsRequireClientCertificate; + std::string tlsNegotiationTimeoutSec; + std::string tlsNegotiationTimeoutMsec; + + // general sip settings + find_in_map (DISPLAY_NAME, displayName) + find_in_map (ROUTESET, routeset) + find_in_map (LOCAL_INTERFACE, localInterface) + find_in_map (PUBLISHED_SAMEAS_LOCAL, publishedSameasLocal) + find_in_map (PUBLISHED_ADDRESS, publishedAddress) + find_in_map (LOCAL_PORT, localPort) + find_in_map (PUBLISHED_PORT, publishedPort) + find_in_map (STUN_ENABLE, stunEnable) + find_in_map (STUN_SERVER, stunServer) + find_in_map (ACCOUNT_DTMF_TYPE, dtmfType) + find_in_map (CONFIG_ACCOUNT_RESOLVE_ONCE, resolveOnce) + find_in_map (CONFIG_ACCOUNT_REGISTRATION_EXPIRE, registrationExpire) + + setDisplayName (displayName); + setServiceRoute (routeset); + setLocalInterface (localInterface); + setPublishedSameasLocal ( (publishedSameasLocal.compare ("true") == 0) ? true : false); + setPublishedAddress (publishedAddress); + setLocalPort (atoi (localPort.data())); + setPublishedPort (atoi (publishedPort.data())); + setStunServer (stunServer); + setStunEnabled ( (stunEnable == "true")); + setResolveOnce ( (resolveOnce.compare ("true") ==0) ? true : false); + setRegistrationExpire (registrationExpire); + + // sip credential + find_in_map (REALM, realm) + find_in_map (AUTHENTICATION_USERNAME, authenticationName) + find_in_map (USERAGENT, ua_name) + + setUseragent (ua_name); + + // srtp settings + find_in_map (SRTP_ENABLE, srtpEnable) + find_in_map (SRTP_RTP_FALLBACK, srtpRtpFallback) + find_in_map (ZRTP_DISPLAY_SAS, zrtpDisplaySas) + find_in_map (ZRTP_DISPLAY_SAS_ONCE, zrtpDisplaySasOnce) + find_in_map (ZRTP_NOT_SUPP_WARNING, zrtpNotSuppWarning) + find_in_map (ZRTP_HELLO_HASH, zrtpHelloHash) + find_in_map (SRTP_KEY_EXCHANGE, srtpKeyExchange) + + setSrtpEnable ( (srtpEnable.compare ("true") == 0) ? true : false); + setSrtpFallback ( (srtpRtpFallback.compare ("true") == 0) ? true : false); + setZrtpDisplaySas ( (zrtpDisplaySas.compare ("true") == 0) ? true : false); + setZrtpDiaplaySasOnce ( (zrtpDisplaySasOnce.compare ("true") == 0) ? true : false); + setZrtpNotSuppWarning ( (zrtpNotSuppWarning.compare ("true") == 0) ? true : false); + setZrtpHelloHash ( (zrtpHelloHash.compare ("true") == 0) ? true : false); + // sipaccount->setSrtpKeyExchange((srtpKeyExchange.compare("true") == 0) ? true : false); + setSrtpKeyExchange (srtpKeyExchange); + + // TLS settings + // The TLS listener is unique and globally defined through IP2IP_PROFILE + if (_accountID == IP2IP_PROFILE) { + find_in_map (TLS_LISTENER_PORT, tlsListenerPort) + } + + find_in_map (TLS_ENABLE, tlsEnable) + find_in_map (TLS_CA_LIST_FILE, tlsCaListFile) + find_in_map (TLS_CERTIFICATE_FILE, tlsCertificateFile) + find_in_map (TLS_PRIVATE_KEY_FILE, tlsPrivateKeyFile) + find_in_map (TLS_PASSWORD, tlsPassword) + find_in_map (TLS_METHOD, tlsMethod) + find_in_map (TLS_CIPHERS, tlsCiphers) + find_in_map (TLS_SERVER_NAME, tlsServerName) + find_in_map (TLS_VERIFY_SERVER, tlsVerifyServer) + find_in_map (TLS_VERIFY_CLIENT, tlsVerifyClient) + find_in_map (TLS_REQUIRE_CLIENT_CERTIFICATE, tlsRequireClientCertificate) + find_in_map (TLS_NEGOTIATION_TIMEOUT_SEC, tlsNegotiationTimeoutSec) + find_in_map (TLS_NEGOTIATION_TIMEOUT_MSEC, tlsNegotiationTimeoutMsec) + + if (_accountID == IP2IP_PROFILE) { + setTlsListenerPort (atoi (tlsListenerPort.data())); + } + setTlsEnable (tlsEnable); + setTlsCaListFile (tlsCaListFile); + setTlsCertificateFile (tlsCertificateFile); + setTlsPrivateKeyFile (tlsPrivateKeyFile); + setTlsPassword (tlsPassword); + setTlsMethod (tlsMethod); + setTlsCiphers (tlsCiphers); + setTlsServerName (tlsServerName); + setTlsVerifyServer (tlsVerifyServer.compare ("true") ? true : false); + setTlsVerifyClient (tlsVerifyServer.compare ("true") ? true : false); + setTlsRequireClientCertificate (tlsRequireClientCertificate.compare ("true") ? true : false); + setTlsNegotiationTimeoutSec (tlsNegotiationTimeoutSec); + setTlsNegotiationTimeoutMsec (tlsNegotiationTimeoutMsec); + + if (!Manager::instance().preferences.getMd5Hash()) { + setPassword (password); + } else { + // Make sure not to re-hash the password field if + // it is already saved as a MD5 Hash. + // TODO: This test is weak. Fix this. + if ( (password.compare (getPassword()) != 0)) { + _debug ("SipAccount: Password sent and password from config are different. Re-hashing"); + std::string hash; + + if (authenticationName.empty()) { + hash = Manager::instance().computeMd5HashFromCredential (username, password, realm); + } else { + hash = Manager::instance().computeMd5HashFromCredential (authenticationName, password, realm); + } + + setPassword (hash); + } + } + } } +std::map<std::string, std::string> SIPAccount::getAccountDetails() { + _debug ("SipAccount: get account details %s", _accountID.c_str()); + + std::map<std::string, std::string> a; + + a.insert (std::pair<std::string, std::string> (ACCOUNT_ID, _accountID)); + // The IP profile does not allow to set an alias + (_accountID == IP2IP_PROFILE) ? + a.insert (std::pair<std::string, std::string> (CONFIG_ACCOUNT_ALIAS, IP2IP_PROFILE)) : + a.insert (std::pair<std::string, std::string> (CONFIG_ACCOUNT_ALIAS, getAlias())); + + a.insert (std::pair<std::string, std::string> (CONFIG_ACCOUNT_ENABLE, isEnabled() ? "true" : "false")); + a.insert (std::pair<std::string, std::string> (CONFIG_ACCOUNT_TYPE, getType())); + a.insert (std::pair<std::string, std::string> (HOSTNAME, getHostname())); + a.insert (std::pair<std::string, std::string> (USERNAME, getUsername())); + a.insert (std::pair<std::string, std::string> (PASSWORD, getPassword())); -void SIPAccount::setAccountDetails(const std::map<std::string, std::string>& details) -{ - - std::map<std::string, std::string> map_cpy; - std::map<std::string, std::string>::iterator iter; - - _debug("SipAccount: set account details %s", _accountID.c_str()); - - // Work on a copy - map_cpy = details; - - std::string alias; - std::string type; - std::string hostname; - std::string username; - std::string password; - std::string mailbox; - std::string accountEnable; - std::string ringtonePath; - std::string ringtoneEnabled; - - // Account setting common to SIP and IAX - find_in_map(CONFIG_ACCOUNT_ALIAS, alias) - find_in_map(CONFIG_ACCOUNT_TYPE, type) - find_in_map(HOSTNAME, hostname) - find_in_map(USERNAME, username) - find_in_map(PASSWORD, password) - find_in_map(CONFIG_ACCOUNT_MAILBOX, mailbox); - find_in_map(CONFIG_ACCOUNT_ENABLE, accountEnable); - find_in_map(CONFIG_RINGTONE_PATH, ringtonePath); - find_in_map(CONFIG_RINGTONE_ENABLED, ringtoneEnabled); - - setAlias(alias); - setType(type); - setUsername(username); - setHostname(hostname); - setPassword(password); - setEnabled((accountEnable == "true")); - setRingtonePath(ringtonePath); - setRingtoneEnabled((ringtoneEnabled == "true")); - - // SIP specific account settings - if(getType() == "SIP") { - - std::string ua_name; - std::string realm; - std::string routeset; - std::string authenticationName; - - std::string resolveOnce; - std::string registrationExpire; - - std::string displayName; - std::string localInterface; - std::string publishedSameasLocal; - std::string localAddress; - std::string publishedAddress; - std::string localPort; - std::string publishedPort; - std::string stunEnable; - std::string stunServer; - std::string dtmfType; - std::string srtpEnable; - std::string srtpRtpFallback; - std::string zrtpDisplaySas; - std::string zrtpDisplaySasOnce; - std::string zrtpNotSuppWarning; - std::string zrtpHelloHash; - std::string srtpKeyExchange; - - std::string tlsListenerPort; - std::string tlsEnable; - std::string tlsCaListFile; - std::string tlsCertificateFile; - std::string tlsPrivateKeyFile; - std::string tlsPassword; - std::string tlsMethod; - std::string tlsCiphers; - std::string tlsServerName; - std::string tlsVerifyServer; - std::string tlsVerifyClient; - std::string tlsRequireClientCertificate; - std::string tlsNegotiationTimeoutSec; - std::string tlsNegotiationTimeoutMsec; - - // general sip settings - find_in_map(DISPLAY_NAME, displayName) - find_in_map(ROUTESET, routeset) - find_in_map(LOCAL_INTERFACE, localInterface) - find_in_map(PUBLISHED_SAMEAS_LOCAL, publishedSameasLocal) - find_in_map(PUBLISHED_ADDRESS, publishedAddress) - find_in_map(LOCAL_PORT, localPort) - find_in_map(PUBLISHED_PORT, publishedPort) - find_in_map(STUN_ENABLE, stunEnable) - find_in_map(STUN_SERVER, stunServer) - find_in_map(ACCOUNT_DTMF_TYPE, dtmfType) - find_in_map(CONFIG_ACCOUNT_RESOLVE_ONCE, resolveOnce) - find_in_map(CONFIG_ACCOUNT_REGISTRATION_EXPIRE, registrationExpire) - - setDisplayName(displayName); - setServiceRoute(routeset); - setLocalInterface(localInterface); - setPublishedSameasLocal((publishedSameasLocal.compare("true") == 0) ? true : false); - setPublishedAddress(publishedAddress); - setLocalPort(atoi(localPort.data())); - setPublishedPort(atoi(publishedPort.data())); - setStunServer(stunServer); - setStunEnabled((stunEnable == "true")); - setResolveOnce((resolveOnce.compare("true")==0) ? true : false); - setRegistrationExpire(registrationExpire); - - // sip credential - find_in_map(REALM, realm) - find_in_map(AUTHENTICATION_USERNAME, authenticationName) - find_in_map(USERAGENT, ua_name) - - setUseragent(ua_name); - - // srtp settings - find_in_map(SRTP_ENABLE, srtpEnable) - find_in_map(SRTP_RTP_FALLBACK, srtpRtpFallback) - find_in_map(ZRTP_DISPLAY_SAS, zrtpDisplaySas) - find_in_map(ZRTP_DISPLAY_SAS_ONCE, zrtpDisplaySasOnce) - find_in_map(ZRTP_NOT_SUPP_WARNING, zrtpNotSuppWarning) - find_in_map(ZRTP_HELLO_HASH, zrtpHelloHash) - find_in_map(SRTP_KEY_EXCHANGE, srtpKeyExchange) - - setSrtpEnable((srtpEnable.compare("true") == 0) ? true : false); - setSrtpFallback((srtpRtpFallback.compare("true") == 0) ? true : false); - setZrtpDisplaySas((zrtpDisplaySas.compare("true") == 0) ? true : false); - setZrtpDiaplaySasOnce((zrtpDisplaySasOnce.compare("true") == 0) ? true : false); - setZrtpNotSuppWarning((zrtpNotSuppWarning.compare("true") == 0) ? true : false); - setZrtpHelloHash((zrtpHelloHash.compare("true") == 0) ? true : false); - // sipaccount->setSrtpKeyExchange((srtpKeyExchange.compare("true") == 0) ? true : false); - setSrtpKeyExchange(srtpKeyExchange); - - // TLS settings - // The TLS listener is unique and globally defined through IP2IP_PROFILE - if(_accountID == IP2IP_PROFILE) { - find_in_map(TLS_LISTENER_PORT, tlsListenerPort) - } - find_in_map(TLS_ENABLE, tlsEnable) - find_in_map(TLS_CA_LIST_FILE, tlsCaListFile) - find_in_map(TLS_CERTIFICATE_FILE, tlsCertificateFile) - find_in_map(TLS_PRIVATE_KEY_FILE, tlsPrivateKeyFile) - find_in_map(TLS_PASSWORD, tlsPassword) - find_in_map(TLS_METHOD, tlsMethod) - find_in_map(TLS_CIPHERS, tlsCiphers) - find_in_map(TLS_SERVER_NAME, tlsServerName) - find_in_map(TLS_VERIFY_SERVER, tlsVerifyServer) - find_in_map(TLS_VERIFY_CLIENT, tlsVerifyClient) - find_in_map(TLS_REQUIRE_CLIENT_CERTIFICATE, tlsRequireClientCertificate) - find_in_map(TLS_NEGOTIATION_TIMEOUT_SEC, tlsNegotiationTimeoutSec) - find_in_map(TLS_NEGOTIATION_TIMEOUT_MSEC, tlsNegotiationTimeoutMsec) - - if (_accountID == IP2IP_PROFILE){ - setTlsListenerPort(atoi(tlsListenerPort.data())); - } - setTlsEnable(tlsEnable); - setTlsCaListFile(tlsCaListFile); - setTlsCertificateFile(tlsCertificateFile); - setTlsPrivateKeyFile(tlsPrivateKeyFile); - setTlsPassword(tlsPassword); - setTlsMethod(tlsMethod); - setTlsCiphers(tlsCiphers); - setTlsServerName(tlsServerName); - setTlsVerifyServer(tlsVerifyServer.compare("true") ? true : false); - setTlsVerifyClient(tlsVerifyServer.compare("true") ? true : false); - setTlsRequireClientCertificate(tlsRequireClientCertificate.compare("true") ? true : false); - setTlsNegotiationTimeoutSec(tlsNegotiationTimeoutSec); - setTlsNegotiationTimeoutMsec(tlsNegotiationTimeoutMsec); - - if (!Manager::instance().preferences.getMd5Hash()) { - setPassword(password); + a.insert (std::pair<std::string, std::string> (CONFIG_RINGTONE_PATH, getRingtonePath())); + a.insert (std::pair<std::string, std::string> (CONFIG_RINGTONE_ENABLED, getRingtoneEnabled() ? "true" : "false")); + + RegistrationState state = Unregistered; + std::string registrationStateCode; + std::string registrationStateDescription; + + + if (_accountID == IP2IP_PROFILE) { + registrationStateCode = EMPTY_FIELD; + registrationStateDescription = "Direct IP call"; } else { - // Make sure not to re-hash the password field if - // it is already saved as a MD5 Hash. - // TODO: This test is weak. Fix this. - if ((password.compare(getPassword()) != 0)) { - _debug ("SipAccount: Password sent and password from config are different. Re-hashing"); - std::string hash; - - if (authenticationName.empty()) { - hash = Manager::instance().computeMd5HashFromCredential(username, password, realm); - } else { - hash = Manager::instance().computeMd5HashFromCredential(authenticationName, password, realm); - } - - setPassword(hash); - } - } - } -} + state = getRegistrationState(); + int code = getRegistrationStateDetailed().first; + std::stringstream out; + out << code; + registrationStateCode = out.str(); + registrationStateDescription = getRegistrationStateDetailed().second; + } + + + (_accountID == IP2IP_PROFILE) ? + a.insert (std::pair<std::string, std::string> (REGISTRATION_STATUS, "READY")) : + a.insert (std::pair<std::string, std::string> (REGISTRATION_STATUS, Manager::instance().mapStateNumberToString (state))); + + a.insert (std::pair<std::string, std::string> (REGISTRATION_STATE_CODE, registrationStateCode)); + a.insert (std::pair<std::string, std::string> (REGISTRATION_STATE_DESCRIPTION, registrationStateDescription)); + + + // Add sip specific details + if (getType() == "SIP") { + + a.insert (std::pair<std::string, std::string> (ROUTESET, getServiceRoute())); + a.insert (std::pair<std::string, std::string> (CONFIG_ACCOUNT_RESOLVE_ONCE, isResolveOnce() ? "true" : "false")); + a.insert (std::pair<std::string, std::string> (REALM, _realm)); + a.insert (std::pair<std::string, std::string> (USERAGENT, getUseragent())); + + a.insert (std::pair<std::string, std::string> (CONFIG_ACCOUNT_REGISTRATION_EXPIRE, getRegistrationExpire())); + a.insert (std::pair<std::string, std::string> (LOCAL_INTERFACE, getLocalInterface())); + a.insert (std::pair<std::string, std::string> (PUBLISHED_SAMEAS_LOCAL, getPublishedSameasLocal() ? "true" : "false")); + a.insert (std::pair<std::string, std::string> (PUBLISHED_ADDRESS, getPublishedAddress())); + + std::stringstream localport; + localport << getLocalPort(); + a.insert (std::pair<std::string, std::string> (LOCAL_PORT, localport.str())); + std::stringstream publishedport; + publishedport << getPublishedPort(); + a.insert (std::pair<std::string, std::string> (PUBLISHED_PORT, publishedport.str())); + a.insert (std::pair<std::string, std::string> (STUN_ENABLE, isStunEnabled() ? "true" : "false")); + a.insert (std::pair<std::string, std::string> (STUN_SERVER, getStunServer())); + a.insert (std::pair<std::string, std::string> (ACCOUNT_DTMF_TYPE, (getDtmfType() == 0) ? "0" : "1")); + + a.insert (std::pair<std::string, std::string> (SRTP_KEY_EXCHANGE, getSrtpKeyExchange())); + a.insert (std::pair<std::string, std::string> (SRTP_ENABLE, getSrtpEnable() ? "true" : "false")); + a.insert (std::pair<std::string, std::string> (SRTP_RTP_FALLBACK, getSrtpFallback() ? "true" : "false")); + + a.insert (std::pair<std::string, std::string> (ZRTP_DISPLAY_SAS, getZrtpDisplaySas() ? "true" : "false")); + a.insert (std::pair<std::string, std::string> (ZRTP_DISPLAY_SAS_ONCE, getZrtpDiaplaySasOnce() ? "true" : "false")); + a.insert (std::pair<std::string, std::string> (ZRTP_HELLO_HASH, getZrtpHelloHash() ? "true" : "false")); + a.insert (std::pair<std::string, std::string> (ZRTP_NOT_SUPP_WARNING, getZrtpNotSuppWarning() ? "true" : "false")); + + // TLS listener is unique and parameters are modified through IP2IP_PROFILE + std::stringstream tlslistenerport; + tlslistenerport << getTlsListenerPort(); + a.insert (std::pair<std::string, std::string> (TLS_LISTENER_PORT, tlslistenerport.str())); + a.insert (std::pair<std::string, std::string> (TLS_ENABLE, getTlsEnable())); + a.insert (std::pair<std::string, std::string> (TLS_CA_LIST_FILE, getTlsCaListFile())); + a.insert (std::pair<std::string, std::string> (TLS_CERTIFICATE_FILE, getTlsCertificateFile())); + a.insert (std::pair<std::string, std::string> (TLS_PRIVATE_KEY_FILE, getTlsPrivateKeyFile())); + a.insert (std::pair<std::string, std::string> (TLS_PASSWORD, getTlsPassword())); + a.insert (std::pair<std::string, std::string> (TLS_METHOD, getTlsMethod())); + a.insert (std::pair<std::string, std::string> (TLS_CIPHERS, getTlsCiphers())); + a.insert (std::pair<std::string, std::string> (TLS_SERVER_NAME, getTlsServerName())); + a.insert (std::pair<std::string, std::string> (TLS_VERIFY_SERVER, getTlsVerifyServer() ? "true" : "false")); + a.insert (std::pair<std::string, std::string> (TLS_VERIFY_CLIENT, getTlsVerifyClient() ? "true" : "false")); + a.insert (std::pair<std::string, std::string> (TLS_REQUIRE_CLIENT_CERTIFICATE, getTlsRequireClientCertificate() ? "true" : "false")); + a.insert (std::pair<std::string, std::string> (TLS_NEGOTIATION_TIMEOUT_SEC, getTlsNegotiationTimeoutSec())); + a.insert (std::pair<std::string, std::string> (TLS_NEGOTIATION_TIMEOUT_MSEC, getTlsNegotiationTimeoutMsec())); -std::map<std::string, std::string> SIPAccount::getAccountDetails() -{ - _debug("SipAccount: get account details %s", _accountID.c_str()); - - std::map<std::string, std::string> a; - - a.insert(std::pair<std::string, std::string>(ACCOUNT_ID, _accountID)); - // The IP profile does not allow to set an alias - (_accountID == IP2IP_PROFILE) ? - a.insert(std::pair<std::string, std::string>(CONFIG_ACCOUNT_ALIAS, IP2IP_PROFILE)) : - a.insert(std::pair<std::string, std::string>(CONFIG_ACCOUNT_ALIAS, getAlias())); - - a.insert(std::pair<std::string, std::string>(CONFIG_ACCOUNT_ENABLE, isEnabled() ? "true" : "false")); - a.insert(std::pair<std::string, std::string>(CONFIG_ACCOUNT_TYPE, getType())); - a.insert(std::pair<std::string, std::string>(HOSTNAME, getHostname())); - a.insert(std::pair<std::string, std::string>(USERNAME, getUsername())); - a.insert(std::pair<std::string, std::string>(PASSWORD, getPassword())); - - a.insert(std::pair<std::string, std::string>(CONFIG_RINGTONE_PATH, getRingtonePath())); - a.insert(std::pair<std::string, std::string>(CONFIG_RINGTONE_ENABLED, getRingtoneEnabled() ? "true" : "false")); - - RegistrationState state = Unregistered; - std::string registrationStateCode; - std::string registrationStateDescription; - - - if (_accountID == IP2IP_PROFILE) { - registrationStateCode = EMPTY_FIELD; - registrationStateDescription = "Direct IP call"; - } else { - state = getRegistrationState(); - int code = getRegistrationStateDetailed().first; - std::stringstream out; out << code; - registrationStateCode = out.str(); - registrationStateDescription = getRegistrationStateDetailed().second; - } - - - (_accountID == IP2IP_PROFILE) ? - a.insert(std::pair<std::string, std::string>(REGISTRATION_STATUS, "READY")) : - a.insert(std::pair<std::string, std::string>(REGISTRATION_STATUS, Manager::instance().mapStateNumberToString(state))); - - a.insert(std::pair<std::string, std::string>(REGISTRATION_STATE_CODE, registrationStateCode)); - a.insert(std::pair<std::string, std::string>(REGISTRATION_STATE_DESCRIPTION, registrationStateDescription)); - - - // Add sip specific details - if(getType() == "SIP") { - - a.insert(std::pair<std::string, std::string>(ROUTESET, getServiceRoute())); - a.insert(std::pair<std::string, std::string>(CONFIG_ACCOUNT_RESOLVE_ONCE, isResolveOnce() ? "true" : "false")); - a.insert(std::pair<std::string, std::string>(REALM, _realm)); - a.insert(std::pair<std::string, std::string>(USERAGENT, getUseragent())); - - a.insert(std::pair<std::string, std::string>(CONFIG_ACCOUNT_REGISTRATION_EXPIRE, getRegistrationExpire())); - a.insert(std::pair<std::string, std::string>(LOCAL_INTERFACE, getLocalInterface())); - a.insert(std::pair<std::string, std::string>(PUBLISHED_SAMEAS_LOCAL, getPublishedSameasLocal() ? "true" : "false")); - a.insert(std::pair<std::string, std::string>(PUBLISHED_ADDRESS, getPublishedAddress())); - - std::stringstream localport; localport << getLocalPort(); - a.insert(std::pair<std::string, std::string>(LOCAL_PORT, localport.str())); - std::stringstream publishedport; publishedport << getPublishedPort(); - a.insert(std::pair<std::string, std::string>(PUBLISHED_PORT, publishedport.str())); - a.insert(std::pair<std::string, std::string>(STUN_ENABLE, isStunEnabled() ? "true" : "false")); - a.insert(std::pair<std::string, std::string>(STUN_SERVER, getStunServer())); - a.insert(std::pair<std::string, std::string>(ACCOUNT_DTMF_TYPE, (getDtmfType() == 0) ? "0" : "1")); - - a.insert(std::pair<std::string, std::string>(SRTP_KEY_EXCHANGE, getSrtpKeyExchange())); - a.insert(std::pair<std::string, std::string>(SRTP_ENABLE, getSrtpEnable() ? "true" : "false")); - a.insert(std::pair<std::string, std::string>(SRTP_RTP_FALLBACK, getSrtpFallback() ? "true" : "false")); - - a.insert(std::pair<std::string, std::string>(ZRTP_DISPLAY_SAS, getZrtpDisplaySas() ? "true" : "false")); - a.insert(std::pair<std::string, std::string>(ZRTP_DISPLAY_SAS_ONCE, getZrtpDiaplaySasOnce() ? "true" : "false")); - a.insert(std::pair<std::string, std::string>(ZRTP_HELLO_HASH, getZrtpHelloHash() ? "true" : "false")); - a.insert(std::pair<std::string, std::string>(ZRTP_NOT_SUPP_WARNING, getZrtpNotSuppWarning() ? "true" : "false")); - - // TLS listener is unique and parameters are modified through IP2IP_PROFILE - std::stringstream tlslistenerport; - tlslistenerport << getTlsListenerPort(); - a.insert(std::pair<std::string, std::string>(TLS_LISTENER_PORT, tlslistenerport.str())); - a.insert(std::pair<std::string, std::string>(TLS_ENABLE, getTlsEnable())); - a.insert(std::pair<std::string, std::string>(TLS_CA_LIST_FILE, getTlsCaListFile())); - a.insert(std::pair<std::string, std::string>(TLS_CERTIFICATE_FILE, getTlsCertificateFile())); - a.insert(std::pair<std::string, std::string>(TLS_PRIVATE_KEY_FILE, getTlsPrivateKeyFile())); - a.insert(std::pair<std::string, std::string>(TLS_PASSWORD, getTlsPassword())); - a.insert(std::pair<std::string, std::string>(TLS_METHOD, getTlsMethod())); - a.insert(std::pair<std::string, std::string>(TLS_CIPHERS, getTlsCiphers())); - a.insert(std::pair<std::string, std::string>(TLS_SERVER_NAME, getTlsServerName())); - a.insert(std::pair<std::string, std::string>(TLS_VERIFY_SERVER, getTlsVerifyServer() ? "true" : "false")); - a.insert(std::pair<std::string, std::string>(TLS_VERIFY_CLIENT, getTlsVerifyClient() ? "true" : "false")); - a.insert(std::pair<std::string, std::string>(TLS_REQUIRE_CLIENT_CERTIFICATE, getTlsRequireClientCertificate() ? "true" : "false")); - a.insert(std::pair<std::string, std::string>(TLS_NEGOTIATION_TIMEOUT_SEC, getTlsNegotiationTimeoutSec())); - a.insert(std::pair<std::string, std::string>(TLS_NEGOTIATION_TIMEOUT_MSEC, getTlsNegotiationTimeoutMsec())); - - } - - return a; + } + + return a; } @@ -711,9 +919,8 @@ void SIPAccount::setVoIPLink() { } -int SIPAccount::initCredential (void) -{ - _debug("SipAccount: Init credential"); +int SIPAccount::initCredential (void) { + _debug ("SipAccount: Init credential"); bool md5HashingEnabled = false; int dataType = 0; @@ -754,7 +961,7 @@ int SIPAccount::initCredential (void) // Set the datatype cred_info[0].data_type = dataType; - + // Set the secheme cred_info[0].scheme = pj_str ( (char*) "digest"); @@ -764,8 +971,8 @@ int SIPAccount::initCredential (void) for (i = 0; i < credentials.getCredentialCount(); i++) { std::string username = _username; - std::string password = _password; - std::string realm = _realm; + std::string password = _password; + std::string realm = _realm; cred_info[i].username = pj_str (strdup (username.c_str())); cred_info[i].data = pj_str (strdup (password.c_str())); @@ -795,8 +1002,7 @@ int SIPAccount::initCredential (void) } -int SIPAccount::registerVoIPLink() -{ +int SIPAccount::registerVoIPLink() { _debug ("Account: Register account %s", getAccountID().c_str()); // Init general settings @@ -820,9 +1026,8 @@ int SIPAccount::registerVoIPLink() if (_stunEnabled) { _transportType = PJSIP_TRANSPORT_START_OTHER; initStunConfiguration (); - } - else { - _stunServerName = pj_str ((char*) _stunServer.data()); + } else { + _stunServerName = pj_str ( (char*) _stunServer.data()); } // In our definition of the @@ -836,8 +1041,7 @@ int SIPAccount::registerVoIPLink() return SUCCESS; } -int SIPAccount::unregisterVoIPLink() -{ +int SIPAccount::unregisterVoIPLink() { _debug ("Unregister account %s" , getAccountID().c_str()); if (_accountID == IP2IP_PROFILE) { @@ -852,8 +1056,7 @@ int SIPAccount::unregisterVoIPLink() } -pjsip_ssl_method SIPAccount::sslMethodStringToPjEnum (const std::string& method) -{ +pjsip_ssl_method SIPAccount::sslMethodStringToPjEnum (const std::string& method) { if (method == "Default") { return PJSIP_SSL_UNSPECIFIED_METHOD; } @@ -877,8 +1080,7 @@ pjsip_ssl_method SIPAccount::sslMethodStringToPjEnum (const std::string& method) return PJSIP_SSL_UNSPECIFIED_METHOD; } -void SIPAccount::initTlsConfiguration (void) -{ +void SIPAccount::initTlsConfiguration (void) { /* * Initialize structure to zero */ @@ -888,10 +1090,10 @@ void SIPAccount::initTlsConfiguration (void) } // TLS listener is unique and should be only modified through IP2IP_PROFILE - + // setTlsListenerPort(atoi(tlsPortStr.c_str())); - setTlsListenerPort(atoi(_tlsPortStr.c_str())); - + setTlsListenerPort (atoi (_tlsPortStr.c_str())); + _tlsSetting = (pjsip_tls_setting *) malloc (sizeof (pjsip_tls_setting)); assert (_tlsSetting); @@ -915,12 +1117,11 @@ void SIPAccount::initTlsConfiguration (void) } -void SIPAccount::initStunConfiguration (void) -{ +void SIPAccount::initStunConfiguration (void) { size_t pos; std::string stunServer, serverName, serverPort; - stunServer = _stunServer; + stunServer = _stunServer; // Init STUN socket pos = stunServer.find (':'); @@ -937,8 +1138,7 @@ void SIPAccount::initStunConfiguration (void) } } -void SIPAccount::loadConfig() -{ +void SIPAccount::loadConfig() { if (_registrationExpire.empty()) _registrationExpire = DFT_EXPIRE_VALUE; @@ -953,13 +1153,11 @@ void SIPAccount::loadConfig() 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)); } -bool SIPAccount::userMatch (const std::string& username) -{ +bool SIPAccount::userMatch (const std::string& username) { if (username.empty()) { return false; } @@ -967,20 +1165,17 @@ bool SIPAccount::userMatch (const std::string& username) return (username == getUsername()); } -bool SIPAccount::hostnameMatch (const std::string& hostname) -{ +bool SIPAccount::hostnameMatch (const std::string& hostname) { return (hostname == getHostname()); } -std::string SIPAccount::getMachineName (void) -{ +std::string SIPAccount::getMachineName (void) { std::string hostname; hostname = std::string (pj_gethostname()->ptr, pj_gethostname()->slen); return hostname; } -std::string SIPAccount::getLoginName (void) -{ +std::string SIPAccount::getLoginName (void) { std::string username; uid_t uid = getuid(); @@ -995,9 +1190,8 @@ std::string SIPAccount::getLoginName (void) return username; } -std::string SIPAccount::getTransportMapKey(void) -{ - +std::string SIPAccount::getTransportMapKey (void) { + std::stringstream out; out << getLocalPort(); std::string localPort = out.str(); @@ -1006,8 +1200,7 @@ std::string SIPAccount::getTransportMapKey(void) } -std::string SIPAccount::getFromUri (void) -{ +std::string SIPAccount::getFromUri (void) { char uri[PJSIP_MAX_URL_SIZE]; std::string scheme; @@ -1033,7 +1226,7 @@ std::string SIPAccount::getFromUri (void) // Get machine hostname if not provided if (_hostname.empty()) { - hostname = getMachineName(); + hostname = getMachineName(); } @@ -1048,8 +1241,7 @@ std::string SIPAccount::getFromUri (void) return std::string (uri, len); } -std::string SIPAccount::getToUri (const std::string& username) -{ +std::string SIPAccount::getToUri (const std::string& username) { char uri[PJSIP_MAX_URL_SIZE]; std::string scheme; @@ -1074,7 +1266,7 @@ std::string SIPAccount::getToUri (const std::string& username) // Check if hostname is already specified if (username.find ("@") == std::string::npos) { // hostname not specified - hostname = _hostname; + hostname = _hostname; } int len = pj_ansi_snprintf (uri, PJSIP_MAX_URL_SIZE, @@ -1089,8 +1281,7 @@ std::string SIPAccount::getToUri (const std::string& username) return std::string (uri, len); } -std::string SIPAccount::getServerUri (void) -{ +std::string SIPAccount::getServerUri (void) { char uri[PJSIP_MAX_URL_SIZE]; std::string scheme; @@ -1116,8 +1307,7 @@ std::string SIPAccount::getServerUri (void) return std::string (uri, len); } -std::string SIPAccount::getContactHeader (const std::string& address, const std::string& port) -{ +std::string SIPAccount::getContactHeader (const std::string& address, const std::string& port) { char contact[PJSIP_MAX_URL_SIZE]; const char * beginquote, * endquote; diff --git a/sflphone-common/src/sip/sipcall.cpp b/sflphone-common/src/sip/sipcall.cpp index 78595928dfc0665feba6b6f4b06e8286e2b89910..f9d741d185a99810f5dd8b53470c7e41fc8195d4 100644 --- a/sflphone-common/src/sip/sipcall.cpp +++ b/sflphone-common/src/sip/sipcall.cpp @@ -42,16 +42,14 @@ SIPCall::SIPCall (const CallID& id, Call::CallType type, pj_pool_t *pool) : Call , _audiortp (new sfl::AudioRtpFactory()) , _xferSub (NULL) , _invSession (NULL) - , _local_sdp (0) -{ - _debug ("SIPCall: Create new call %s", id.c_str()); + , _local_sdp (0) { + _debug ("SIPCall: Create new call %s", id.c_str()); _local_sdp = new Sdp (pool); } -SIPCall::~SIPCall() -{ - _debug ("SIPCall: Delete call"); +SIPCall::~SIPCall() { + _debug ("SIPCall: Delete call"); delete _audiortp; _audiortp = 0; diff --git a/sflphone-common/src/sip/sipvoiplink.cpp b/sflphone-common/src/sip/sipvoiplink.cpp old mode 100755 new mode 100644 index 45f8a1437efec7765417139b049765498c9ef301..104dbb005f5adfae4c6560b7bb00c1cb1d2f5316 --- a/sflphone-common/src/sip/sipvoiplink.cpp +++ b/sflphone-common/src/sip/sipvoiplink.cpp @@ -215,7 +215,7 @@ void call_on_tsx_changed (pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_ void on_rx_offer (pjsip_inv_session *inv, const pjmedia_sdp_session *offer); -void on_create_offer(pjsip_inv_session *inv, pjmedia_sdp_session **p_offer); +void on_create_offer (pjsip_inv_session *inv, pjmedia_sdp_session **p_offer); /* * Registration callback @@ -245,7 +245,7 @@ pj_bool_t mod_on_rx_response (pjsip_rx_data *rdata UNUSED) ; * Send an ACK message inside a transaction. PJSIP send automatically, non-2xx ACK response. * ACK for a 2xx response must be send using this method. */ -static void sendAck(pjsip_dialog *dlg, pjsip_rx_data *rdata); +static void sendAck (pjsip_dialog *dlg, pjsip_rx_data *rdata); /* * Transfer callbacks @@ -264,10 +264,9 @@ SIPVoIPLink::SIPVoIPLink (const AccountID& accountID) : VoIPLink (accountID) , _nbTryListenAddr (2) // number of times to try to start SIP listener , _regPort (atoi (DEFAULT_SIP_PORT)) - , _clients (0) -{ + , _clients (0) { - _debug("SIPVOIPLINK"); + _debug ("SIPVOIPLINK"); // to get random number for RANDOM_PORT srand (time (NULL)); @@ -277,16 +276,14 @@ SIPVoIPLink::SIPVoIPLink (const AccountID& accountID) init(); } -SIPVoIPLink::~SIPVoIPLink() -{ - _debug("UserAgent: SIPVoIPLink destructor called"); +SIPVoIPLink::~SIPVoIPLink() { + _debug ("UserAgent: SIPVoIPLink destructor called"); terminate(); } -SIPVoIPLink* SIPVoIPLink::instance (const AccountID& id) -{ +SIPVoIPLink* SIPVoIPLink::instance (const AccountID& id) { if (!_instance) { _debug ("UserAgent: Create new SIPVoIPLink instance"); @@ -296,20 +293,18 @@ SIPVoIPLink* SIPVoIPLink::instance (const AccountID& id) return _instance; } -void SIPVoIPLink::decrementClients (void) -{ +void SIPVoIPLink::decrementClients (void) { _clients--; if (_clients == 0) { - _debug("UserAgent: No SIP account anymore, terminate SIPVoIPLink"); + _debug ("UserAgent: No SIP account anymore, terminate SIPVoIPLink"); // terminate(); delete SIPVoIPLink::_instance; } } -bool SIPVoIPLink::init() -{ +bool SIPVoIPLink::init() { if (initDone()) return false; @@ -329,13 +324,13 @@ bool SIPVoIPLink::init() } void -SIPVoIPLink::terminate() -{ +SIPVoIPLink::terminate() { _debug ("UserAgent: Terminating SIPVoIPLink"); if (_evThread) { _debug ("UserAgent: Deleting sip eventThread"); - delete _evThread; _evThread = NULL; + delete _evThread; + _evThread = NULL; } @@ -350,8 +345,7 @@ SIPVoIPLink::terminate() } void -SIPVoIPLink::terminateSIPCall() -{ +SIPVoIPLink::terminateSIPCall() { ost::MutexLock m (_callMapMutex); CallMap::iterator iter = _callMap.begin(); SIPCall *call; @@ -372,9 +366,8 @@ SIPVoIPLink::terminateSIPCall() } void -SIPVoIPLink::terminateOneCall (const CallID& id) -{ - _debug("UserAgent: Terminate call %s", id.c_str()); +SIPVoIPLink::terminateOneCall (const CallID& id) { + _debug ("UserAgent: Terminate call %s", id.c_str()); SIPCall *call = getSIPCall (id); @@ -385,8 +378,7 @@ SIPVoIPLink::terminateOneCall (const CallID& id) } } -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; @@ -409,7 +401,7 @@ void get_remote_sdp_from_offer (pjsip_rx_data *rdata, pjmedia_sdp_session** r_sd } -std::string SIPVoIPLink::getInterfaceAddrFromName(std::string ifaceName) { +std::string SIPVoIPLink::getInterfaceAddrFromName (std::string ifaceName) { struct ifreq ifr; int fd; @@ -418,49 +410,48 @@ std::string SIPVoIPLink::getInterfaceAddrFromName(std::string ifaceName) { struct sockaddr_in *saddr_in; struct in_addr *addr_in; - if((fd = socket (AF_INET, SOCK_DGRAM,0)) < 0) - _error("UserAgent: Error: could not open socket"); + if ( (fd = socket (AF_INET, SOCK_DGRAM,0)) < 0) + _error ("UserAgent: Error: could not open socket"); memset (&ifr, 0, sizeof (struct ifreq)); strcpy (ifr.ifr_name, ifaceName.c_str()); ifr.ifr_addr.sa_family = AF_INET; - if((err = ioctl(fd, SIOCGIFADDR, &ifr)) < 0) - _debug("UserAgent: Use default interface (0.0.0.0)"); - - saddr_in = (struct sockaddr_in *)&ifr.ifr_addr; - addr_in = &(saddr_in->sin_addr); + if ( (err = ioctl (fd, SIOCGIFADDR, &ifr)) < 0) + _debug ("UserAgent: Use default interface (0.0.0.0)"); - std::string addr(pj_inet_ntoa(*((pj_in_addr*)addr_in))); + saddr_in = (struct sockaddr_in *) &ifr.ifr_addr; + addr_in = & (saddr_in->sin_addr); - close(fd); + std::string addr (pj_inet_ntoa (* ( (pj_in_addr*) addr_in))); + + close (fd); return addr; } -std::string SIPVoIPLink::get_useragent_name (const AccountID& id) -{ - /* +std::string SIPVoIPLink::get_useragent_name (const AccountID& id) { + /* useragent << PROGNAME << "/" << SFLPHONED_VERSION; return useragent.str(); - */ + */ - SIPAccount *account = (SIPAccount *)Manager::instance().getAccount(id); + SIPAccount *account = (SIPAccount *) Manager::instance().getAccount (id); std::ostringstream useragent; useragent << account->getUseragent(); + if (useragent.str() == "sflphone" || useragent.str() == "") - useragent << "/" << SFLPHONED_VERSION; - + useragent << "/" << SFLPHONED_VERSION; + return useragent.str (); } void -SIPVoIPLink::getEvent() -{ +SIPVoIPLink::getEvent() { // We have to register the external thread so it could access the pjsip frameworks if (!pj_thread_is_registered()) pj_thread_register (NULL, desc, &thread); @@ -472,8 +463,7 @@ SIPVoIPLink::getEvent() } -int SIPVoIPLink::sendRegister (AccountID id) -{ +int SIPVoIPLink::sendRegister (AccountID id) { int expire_value; @@ -537,17 +527,17 @@ int SIPVoIPLink::sendRegister (AccountID id) } - // Create SIP transport or get existent SIP transport from internal map + // Create SIP transport or get existent SIP transport from internal map // according to account settings, if the transport could not be created but - // one is already set in account, use this one (most likely this is the - // transport we tried to create) - acquireTransport(account->getAccountID()); + // one is already set in account, use this one (most likely this is the + // transport we tried to create) + acquireTransport (account->getAccountID()); if (account->getAccountTransport()) { - _debug("Acquire transport in account registration: %s %s (refcnt=%d)", - account->getAccountTransport()->obj_name, - account->getAccountTransport()->info, - (int)pj_atomic_get(account->getAccountTransport()->ref_cnt)); + _debug ("Acquire transport in account registration: %s %s (refcnt=%d)", + account->getAccountTransport()->obj_name, + account->getAccountTransport()->info, + (int) pj_atomic_get (account->getAccountTransport()->ref_cnt)); } _mutexSIP.enterMutex(); @@ -611,19 +601,19 @@ int SIPVoIPLink::sendRegister (AccountID id) status = pjsip_regc_init (regc, &pjSrv, &pjFrom, &pjFrom, 1, &pjContact, expire_value); - if(!(account->getServiceRoute().empty())) { + if (! (account->getServiceRoute().empty())) { - _error("UserAgent: Set Service-Route with %s", account->getServiceRoute().c_str()); + _error ("UserAgent: Set Service-Route with %s", account->getServiceRoute().c_str()); - pjsip_route_hdr *route_set = pjsip_route_hdr_create(_pool); - pjsip_route_hdr *routing = pjsip_route_hdr_create(_pool); - pjsip_sip_uri *url = pjsip_sip_uri_create(_pool, 0); - routing->name_addr.uri = (pjsip_uri*)url; - pj_strdup2(_pool, &url->host, account->getServiceRoute().c_str()); + pjsip_route_hdr *route_set = pjsip_route_hdr_create (_pool); + pjsip_route_hdr *routing = pjsip_route_hdr_create (_pool); + pjsip_sip_uri *url = pjsip_sip_uri_create (_pool, 0); + routing->name_addr.uri = (pjsip_uri*) url; + pj_strdup2 (_pool, &url->host, account->getServiceRoute().c_str()); - pj_list_push_back(&route_set, pjsip_hdr_clone(_pool, routing)); + pj_list_push_back (&route_set, pjsip_hdr_clone (_pool, routing)); - pjsip_regc_set_route_set(regc, route_set); + pjsip_regc_set_route_set (regc, route_set); } if (status != PJ_SUCCESS) { @@ -649,7 +639,7 @@ int SIPVoIPLink::sendRegister (AccountID id) // pj_list_push_back (&hdr_list, (pjsip_hdr*) routing); pjsip_regc_add_headers (regc, &hdr_list); - + status = pjsip_regc_register (regc, PJ_TRUE, &tdata); if (status != PJ_SUCCESS) { @@ -660,20 +650,20 @@ int SIPVoIPLink::sendRegister (AccountID id) pjsip_tpselector *tp; - init_transport_selector (account->getAccountTransport (), &tp); - + init_transport_selector (account->getAccountTransport (), &tp); + // pjsip_regc_set_transport increments transport ref count by one status = pjsip_regc_set_transport (regc, tp); - if(account->getAccountTransport()) { - // decrease transport's ref count, counter icrementation is - // managed when acquiring transport - pjsip_transport_dec_ref(account->getAccountTransport ()); + if (account->getAccountTransport()) { + // decrease transport's ref count, counter icrementation is + // managed when acquiring transport + pjsip_transport_dec_ref (account->getAccountTransport ()); - _debug("UserAgent: After setting the transport in account registration using transport: %s %s (refcnt=%d)", - account->getAccountTransport()->obj_name, - account->getAccountTransport()->info, - (int)pj_atomic_get(account->getAccountTransport()->ref_cnt)); + _debug ("UserAgent: After setting the transport in account registration using transport: %s %s (refcnt=%d)", + account->getAccountTransport()->obj_name, + account->getAccountTransport()->info, + (int) pj_atomic_get (account->getAccountTransport()->ref_cnt)); } if (status != PJ_SUCCESS) { @@ -683,14 +673,14 @@ int SIPVoIPLink::sendRegister (AccountID id) } // Send registration request - // pjsip_regc_send increment the transport ref count by one, + // pjsip_regc_send increment the transport ref count by one, status = pjsip_regc_send (regc, tdata); - if(account->getAccountTransport()) { - // Decrease transport's ref count, since coresponding reference counter decrementation + if (account->getAccountTransport()) { + // Decrease transport's ref count, since coresponding reference counter decrementation // is performed in pjsip_regc_destroy. This function is never called in SFLphone as the // regc data structure is permanently associated to the account at first registration. - pjsip_transport_dec_ref(account->getAccountTransport ()); + pjsip_transport_dec_ref (account->getAccountTransport ()); } if (status != PJ_SUCCESS) { @@ -703,20 +693,19 @@ int SIPVoIPLink::sendRegister (AccountID id) account->setRegistrationInfo (regc); - if(account->getAccountTransport()) { + if (account->getAccountTransport()) { - _debug("Sent account registration using transport: %s %s (refcnt=%d)", - account->getAccountTransport()->obj_name, - account->getAccountTransport()->info, - (int)pj_atomic_get(account->getAccountTransport()->ref_cnt)); + _debug ("Sent account registration using transport: %s %s (refcnt=%d)", + account->getAccountTransport()->obj_name, + account->getAccountTransport()->info, + (int) pj_atomic_get (account->getAccountTransport()->ref_cnt)); } return true; } int -SIPVoIPLink::sendUnregister (AccountID id) -{ +SIPVoIPLink::sendUnregister (AccountID id) { pj_status_t status = 0; pjsip_tx_data *tdata = NULL; @@ -727,12 +716,12 @@ SIPVoIPLink::sendUnregister (AccountID id) regc = account->getRegistrationInfo(); // If an transport is attached to this account, detach it and decrease reference counter - if(account->getAccountTransport()) { + if (account->getAccountTransport()) { - _debug("Sent account unregistration using transport: %s %s (refcnt=%d)", - account->getAccountTransport()->obj_name, - account->getAccountTransport()->info, - (int)pj_atomic_get(account->getAccountTransport()->ref_cnt)); + _debug ("Sent account unregistration using transport: %s %s (refcnt=%d)", + account->getAccountTransport()->obj_name, + account->getAccountTransport()->info, + (int) pj_atomic_get (account->getAccountTransport()->ref_cnt)); } @@ -749,7 +738,7 @@ SIPVoIPLink::sendUnregister (AccountID id) _debug ("UserAgent: Unable to unregister regc."); return false; } - + status = pjsip_regc_send (regc, tdata); if (status != PJ_SUCCESS) { @@ -768,13 +757,12 @@ SIPVoIPLink::sendUnregister (AccountID id) } Call* -SIPVoIPLink::newOutgoingCall (const CallID& id, const std::string& toUrl) -{ +SIPVoIPLink::newOutgoingCall (const CallID& id, const std::string& toUrl) { SIPAccount * account = NULL; pj_status_t status; std::string localAddr, addrSdp; - _debug("UserAgent: New outgoing call %s to %s", id.c_str(), toUrl.c_str()); + _debug ("UserAgent: New outgoing call %s to %s", id.c_str(), toUrl.c_str()); SIPCall* call = new SIPCall (id, Call::Outgoing, _pool); @@ -794,9 +782,9 @@ SIPVoIPLink::newOutgoingCall (const CallID& id, const std::string& toUrl) call->setPeerNumber (toUri); - localAddr = getInterfaceAddrFromName(account->getLocalInterface ()); + localAddr = getInterfaceAddrFromName (account->getLocalInterface ()); - _debug("UserAgent: Local address for call: %s", localAddr.c_str()); + _debug ("UserAgent: Local address for call: %s", localAddr.c_str()); if (localAddr == "0.0.0.0") loadSIPLocalIP (&localAddr); @@ -804,7 +792,7 @@ SIPVoIPLink::newOutgoingCall (const CallID& id, const std::string& toUrl) setCallAudioLocal (call, localAddr); // May use the published address as well - account->isStunEnabled () ? addrSdp = account->getPublishedAddress () : addrSdp = getInterfaceAddrFromName(account->getLocalInterface ()); + account->isStunEnabled () ? addrSdp = account->getPublishedAddress () : addrSdp = getInterfaceAddrFromName (account->getLocalInterface ()); if (addrSdp == "0.0.0.0") loadSIPLocalIP (&addrSdp); @@ -845,8 +833,7 @@ SIPVoIPLink::newOutgoingCall (const CallID& id, const std::string& toUrl) } bool -SIPVoIPLink::answer (const CallID& id) -{ +SIPVoIPLink::answer (const CallID& id) { pj_status_t status; pjsip_tx_data *tdata; pjsip_inv_session *inv_session; @@ -903,8 +890,7 @@ SIPVoIPLink::answer (const CallID& id) } bool -SIPVoIPLink::hangup (const CallID& id) -{ +SIPVoIPLink::hangup (const CallID& id) { pj_status_t status; pjsip_tx_data *tdata = NULL; SIPCall* call; @@ -951,13 +937,12 @@ SIPVoIPLink::hangup (const CallID& id) } bool -SIPVoIPLink::peerHungup (const CallID& id) -{ +SIPVoIPLink::peerHungup (const CallID& id) { pj_status_t status; pjsip_tx_data *tdata = NULL; SIPCall* call; - _info("UserAgent: Peer hungup"); + _info ("UserAgent: Peer hungup"); call = getSIPCall (id); @@ -998,14 +983,13 @@ SIPVoIPLink::peerHungup (const CallID& id) } bool -SIPVoIPLink::cancel (const CallID& id) -{ - _info ("UserAgent: Cancel call %s", id.c_str()); +SIPVoIPLink::cancel (const CallID& id) { + _info ("UserAgent: Cancel call %s", id.c_str()); SIPCall* call = getSIPCall (id); if (!call) { - _warn("UserAgent: Error: Call doesn't exist"); + _warn ("UserAgent: Error: Call doesn't exist"); return false; } @@ -1016,8 +1000,7 @@ SIPVoIPLink::cancel (const CallID& id) } bool -SIPVoIPLink::onhold (const CallID& id) -{ +SIPVoIPLink::onhold (const CallID& id) { pj_status_t status; SIPCall* call; @@ -1048,8 +1031,7 @@ SIPVoIPLink::onhold (const CallID& id) return true; } -int SIPVoIPLink::inv_session_reinvite (SIPCall *call, std::string direction) -{ +int SIPVoIPLink::inv_session_reinvite (SIPCall *call, std::string direction) { pj_status_t status; pjsip_tx_data *tdata; @@ -1065,7 +1047,7 @@ int SIPVoIPLink::inv_session_reinvite (SIPCall *call, std::string direction) // Reinvite only if connected // Build the local SDP offer - // TODO Restore Re-Invite + // TODO Restore Re-Invite // status = call->getLocalSDP()->create_initial_offer(); // if (status != PJ_SUCCESS) @@ -1096,8 +1078,7 @@ int SIPVoIPLink::inv_session_reinvite (SIPCall *call, std::string direction) bool -SIPVoIPLink::offhold (const CallID& id) -{ +SIPVoIPLink::offhold (const CallID& id) { SIPCall *call; pj_status_t status; @@ -1127,8 +1108,7 @@ SIPVoIPLink::offhold (const CallID& id) } bool -SIPVoIPLink::transfer (const CallID& id, const std::string& to) -{ +SIPVoIPLink::transfer (const CallID& id, const std::string& to) { SIPCall *call; std::string tmp_to; @@ -1146,7 +1126,7 @@ SIPVoIPLink::transfer (const CallID& id, const std::string& to) account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (account_id)); if (!account) { - _error("UserAgent: Error: Transfer account is null. Returning."); + _error ("UserAgent: Error: Transfer account is null. Returning."); return false; } @@ -1195,9 +1175,9 @@ SIPVoIPLink::transfer (const CallID& id, const std::string& to) } // Put SIP call id in map in order to retrieve call during transfer callback - std::string callidtransfer(call->getInvSession()->dlg->call_id->id.ptr, call->getInvSession()->dlg->call_id->id.slen); - _debug("%s", callidtransfer.c_str()); - transferCallID.insert(std::pair<std::string, CallID>(callidtransfer, call->getCallId())); + std::string callidtransfer (call->getInvSession()->dlg->call_id->id.ptr, call->getInvSession()->dlg->call_id->id.slen); + _debug ("%s", callidtransfer.c_str()); + transferCallID.insert (std::pair<std::string, CallID> (callidtransfer, call->getCallId())); /* Send. */ @@ -1211,11 +1191,10 @@ SIPVoIPLink::transfer (const CallID& id, const std::string& to) return true; } -bool SIPVoIPLink::transferStep2 (SIPCall* call) -{ +bool SIPVoIPLink::transferStep2 (SIPCall* call) { - // TODO is this the best way to proceed? - Manager::instance().peerHungupCall(call->getCallId()); + // TODO is this the best way to proceed? + Manager::instance().peerHungupCall (call->getCallId()); @@ -1223,13 +1202,12 @@ bool SIPVoIPLink::transferStep2 (SIPCall* call) } bool -SIPVoIPLink::refuse (const CallID& id) -{ +SIPVoIPLink::refuse (const CallID& id) { SIPCall *call; pj_status_t status; pjsip_tx_data *tdata; - _debug("UserAgent: Refuse call %s", id.c_str()); + _debug ("UserAgent: Refuse call %s", id.c_str()); call = getSIPCall (id); @@ -1257,19 +1235,18 @@ SIPVoIPLink::refuse (const CallID& id) call->getInvSession()->mod_data[getModId() ] = NULL; - removeCall(id); + removeCall (id); terminateOneCall (id); - _debug("UserAgent: Refuse call completed"); + _debug ("UserAgent: Refuse call completed"); return true; } std::string -SIPVoIPLink::getCurrentCodecName() -{ +SIPVoIPLink::getCurrentCodecName() { SIPCall *call; AudioCodec *ac = NULL; @@ -1287,8 +1264,7 @@ SIPVoIPLink::getCurrentCodecName() } bool -SIPVoIPLink::carryingDTMFdigits (const CallID& id, char code) -{ +SIPVoIPLink::carryingDTMFdigits (const CallID& id, char code) { SIPCall *call = getSIPCall (id); if (!call) { @@ -1296,23 +1272,23 @@ SIPVoIPLink::carryingDTMFdigits (const CallID& id, char code) return false; } - AccountID accountID = Manager::instance().getAccountFromCall(id); - SIPAccount *account = static_cast<SIPAccount *>(Manager::instance().getAccount(accountID)); + AccountID accountID = Manager::instance().getAccountFromCall (id); + SIPAccount *account = static_cast<SIPAccount *> (Manager::instance().getAccount (accountID)); - if(!account) { - _error ("UserAgent: Error: Account not found while sending DTMF"); - return false; + if (!account) { + _error ("UserAgent: Error: Account not found while sending DTMF"); + return false; } DtmfType type = account->getDtmfType(); - if(type == OVERRTP) - dtmfOverRtp(call, code); - else if(type == SIPINFO) - dtmfSipInfo(call, code); + if (type == OVERRTP) + dtmfOverRtp (call, code); + else if (type == SIPINFO) + dtmfSipInfo (call, code); else { - _error("UserAgent: Error: Dtmf type does not exist"); - return false; + _error ("UserAgent: Error: Dtmf type does not exist"); + return false; } return true; @@ -1320,76 +1296,73 @@ SIPVoIPLink::carryingDTMFdigits (const CallID& id, char code) bool -SIPVoIPLink::dtmfSipInfo(SIPCall *call, char code) -{ +SIPVoIPLink::dtmfSipInfo (SIPCall *call, char code) { - 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; + 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; - duration = Manager::instance().voipPreferences.getPulseLength(); + duration = Manager::instance().voipPreferences.getPulseLength(); - dtmf_body = new char[body_len]; + dtmf_body = new char[body_len]; - snprintf (dtmf_body, body_len - 1, "Signal=%c\r\nDuration=%d\r\n", code, duration); + 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); + 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); + /* 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", status); - return false; - } + if (status != PJ_SUCCESS) { + _debug ("UserAgent: Unable to create INFO request -- %d", status); + return false; + } - /* Get MIME type */ - pj_strdup2 (_pool, &ctype.type, "application"); + /* Get MIME type */ + pj_strdup2 (_pool, &ctype.type, "application"); - pj_strdup2 (_pool, &ctype.subtype, "dtmf-relay"); + pj_strdup2 (_pool, &ctype.subtype, "dtmf-relay"); - /* Create "application/dtmf-relay" message body. */ - pj_strdup2 (_pool, &content, dtmf_body); + /* 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); + 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!"); - pjsip_tx_data_dec_ref (tdata); - return false; - } + if (tdata->msg->body == NULL) { + _debug ("UserAgent: Unable to create msg body!"); + pjsip_tx_data_dec_ref (tdata); + return false; + } - /* Send the request. */ - status = pjsip_dlg_send_request (call->getInvSession()->dlg, tdata, getModId(), NULL); + /* 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", status); - return false; - } + if (status != PJ_SUCCESS) { + _debug ("UserAgent: Unable to send MESSAGE request -- %d", status); + return false; + } - return true; + return true; } bool -SIPVoIPLink::dtmfOverRtp(SIPCall* call, char code) -{ - call->getAudioRtp()->sendDtmfDigit(atoi(&code)); +SIPVoIPLink::dtmfOverRtp (SIPCall* call, char code) { + call->getAudioRtp()->sendDtmfDigit (atoi (&code)); - return true; + return true; } bool -SIPVoIPLink::SIPOutgoingInvite (SIPCall* call) -{ +SIPVoIPLink::SIPOutgoingInvite (SIPCall* call) { // If no SIP proxy setting for direct call with only IP address if (!SIPStartCall (call, "")) { _debug ("! SIP Failure: call not started"); @@ -1400,8 +1373,7 @@ SIPVoIPLink::SIPOutgoingInvite (SIPCall* call) } bool -SIPVoIPLink::SIPStartCall (SIPCall* call, const std::string& subject UNUSED) -{ +SIPVoIPLink::SIPStartCall (SIPCall* call, const std::string& subject UNUSED) { pj_status_t status; pjsip_inv_session *inv; pjsip_dialog *dialog; @@ -1409,7 +1381,7 @@ SIPVoIPLink::SIPStartCall (SIPCall* call, const std::string& subject UNUSED) AccountID id; - _debug("UserAgent: Start sip call"); + _debug ("UserAgent: Start sip call"); if (call == NULL) return false; @@ -1474,19 +1446,19 @@ SIPVoIPLink::SIPStartCall (SIPCall* call, const std::string& subject UNUSED) status = pjsip_inv_create_uac (dialog, call->getLocalSDP()->get_local_sdp_session(), 0, &inv); - if(!(account->getServiceRoute().empty())) { + if (! (account->getServiceRoute().empty())) { - _error("UserAgent: Set Service-Route with %s", account->getServiceRoute().c_str()); + _error ("UserAgent: Set Service-Route with %s", account->getServiceRoute().c_str()); - pjsip_route_hdr *route_set = pjsip_route_hdr_create(_pool); - pjsip_route_hdr *routing = pjsip_route_hdr_create(_pool); - pjsip_sip_uri *url = pjsip_sip_uri_create(_pool, 0); - routing->name_addr.uri = (pjsip_uri*)url; - pj_strdup2(_pool, &url->host, account->getServiceRoute().c_str()); + pjsip_route_hdr *route_set = pjsip_route_hdr_create (_pool); + pjsip_route_hdr *routing = pjsip_route_hdr_create (_pool); + pjsip_sip_uri *url = pjsip_sip_uri_create (_pool, 0); + routing->name_addr.uri = (pjsip_uri*) url; + pj_strdup2 (_pool, &url->host, account->getServiceRoute().c_str()); - pj_list_push_back(&route_set, pjsip_hdr_clone(_pool, routing)); + pj_list_push_back (&route_set, pjsip_hdr_clone (_pool, routing)); - pjsip_dlg_set_route_set(dialog, route_set); + pjsip_dlg_set_route_set (dialog, route_set); } @@ -1515,7 +1487,7 @@ SIPVoIPLink::SIPStartCall (SIPCall* call, const std::string& subject UNUSED) // decrement transport's ref count // pjsip_transport_dec_ref(account->getAccountTransport()); - + status = pjsip_inv_send_msg (inv, tdata); if (status != PJ_SUCCESS) { @@ -1523,20 +1495,19 @@ SIPVoIPLink::SIPStartCall (SIPCall* call, const std::string& subject UNUSED) return false; } - if(account->getAccountTransport()) { + if (account->getAccountTransport()) { - _debug("UserAgent: Sent invite request using transport: %s %s (refcnt=%d)", - account->getAccountTransport()->obj_name, - account->getAccountTransport()->info, - (int)pj_atomic_get(account->getAccountTransport()->ref_cnt)); + _debug ("UserAgent: Sent invite request using transport: %s %s (refcnt=%d)", + account->getAccountTransport()->obj_name, + account->getAccountTransport()->info, + (int) pj_atomic_get (account->getAccountTransport()->ref_cnt)); } return true; } void -SIPVoIPLink::SIPCallServerFailure (SIPCall *call) -{ +SIPVoIPLink::SIPCallServerFailure (SIPCall *call) { if (call != 0) { _error ("UserAgent: Error: Server error!"); CallID id = call->getCallId(); @@ -1550,12 +1521,11 @@ SIPVoIPLink::SIPCallServerFailure (SIPCall *call) } void -SIPVoIPLink::SIPCallClosed (SIPCall *call) -{ - _info("UserAgent: Closing call"); +SIPVoIPLink::SIPCallClosed (SIPCall *call) { + _info ("UserAgent: Closing call"); if (!call) { - _warn("UserAgent: Error: CAll pointer is NULL\n"); + _warn ("UserAgent: Error: CAll pointer is NULL\n"); return; } @@ -1574,8 +1544,7 @@ SIPVoIPLink::SIPCallClosed (SIPCall *call) } void -SIPVoIPLink::SIPCallReleased (SIPCall *call) -{ +SIPVoIPLink::SIPCallReleased (SIPCall *call) { if (!call) { return; } @@ -1594,8 +1563,7 @@ SIPVoIPLink::SIPCallReleased (SIPCall *call) void -SIPVoIPLink::SIPCallAnswered (SIPCall *call, pjsip_rx_data *rdata) -{ +SIPVoIPLink::SIPCallAnswered (SIPCall *call, pjsip_rx_data *rdata) { _info ("UserAgent: SIP call answered"); @@ -1616,8 +1584,7 @@ SIPVoIPLink::SIPCallAnswered (SIPCall *call, pjsip_rx_data *rdata) SIPCall* -SIPVoIPLink::getSIPCall (const CallID& id) -{ +SIPVoIPLink::getSIPCall (const CallID& id) { Call* call = getCall (id); if (call) { @@ -1627,8 +1594,7 @@ SIPVoIPLink::getSIPCall (const CallID& id) return NULL; } -bool SIPVoIPLink::new_ip_to_ip_call (const CallID& id, const std::string& to) -{ +bool SIPVoIPLink::new_ip_to_ip_call (const CallID& id, const std::string& to) { SIPCall *call; pj_status_t status; pjsip_dialog *dialog; @@ -1636,7 +1602,7 @@ bool SIPVoIPLink::new_ip_to_ip_call (const CallID& id, const std::string& to) pjsip_tx_data *tdata; std::string localAddress, addrSdp; - _debug("UserAgent: New IP2IP call %s to %s", id.c_str(), to.c_str()); + _debug ("UserAgent: New IP2IP call %s to %s", id.c_str(), to.c_str()); /* Create the call */ call = new SIPCall (id, Call::Outgoing, _pool); @@ -1651,11 +1617,11 @@ bool SIPVoIPLink::new_ip_to_ip_call (const CallID& id, const std::string& to) if (account == NULL) { _error ("UserAgent: Error: Account %s is null. Returning", IP2IP_PROFILE); - return !PJ_SUCCESS; + return !PJ_SUCCESS; } // Set the local address - localAddress = getInterfaceAddrFromName(account->getLocalInterface ()); + localAddress = getInterfaceAddrFromName (account->getLocalInterface ()); // Set SDP parameters - Set to local addrSdp = localAddress; @@ -1664,14 +1630,14 @@ bool SIPVoIPLink::new_ip_to_ip_call (const CallID& id, const std::string& to) loadSIPLocalIP (&localAddress); } - _debug ("UserAgent: Local Address for IP2IP call: %s", localAddress.c_str()); + _debug ("UserAgent: Local Address for IP2IP call: %s", localAddress.c_str()); // Local address to appear in SDP if (addrSdp == "0.0.0.0") { - addrSdp = localAddress; + addrSdp = localAddress; } - _debug ("UserAgent: Media Address for IP2IP call: %s", localAddress.c_str()); + _debug ("UserAgent: Media Address for IP2IP call: %s", localAddress.c_str()); // Set local address for RTP media setCallAudioLocal (call, localAddress); @@ -1689,33 +1655,33 @@ bool SIPVoIPLink::new_ip_to_ip_call (const CallID& id, const std::string& to) // Audio Rtp Session must be initialized before creating initial offer in SDP session // since SDES require crypto attribute. try { - call->getAudioRtp()->initAudioRtpConfig (call); - call->getAudioRtp()->initAudioRtpSession (call); + call->getAudioRtp()->initAudioRtpConfig (call); + call->getAudioRtp()->initAudioRtpSession (call); } catch (...) { - _debug ("UserAgent: Unable to create RTP Session in new IP2IP call (%s:%d)", __FILE__, __LINE__); + _debug ("UserAgent: Unable to create RTP Session in new IP2IP call (%s:%d)", __FILE__, __LINE__); } // Init TLS transport if enabled - if(account->isTlsEnabled()) { + if (account->isTlsEnabled()) { - _debug("UserAgent: TLS enabled for IP2IP calls"); - int at = toUri.find("@"); - int trns = toUri.find(";transport"); - std::string remoteAddr = toUri.substr(at+1, trns-at-1); + _debug ("UserAgent: TLS enabled for IP2IP calls"); + int at = toUri.find ("@"); + int trns = toUri.find (";transport"); + std::string remoteAddr = toUri.substr (at+1, trns-at-1); - if(toUri.find("sips:") != 1) { - _debug("UserAgent: Error \"sips\" scheme required for TLS call"); - return false; - } + if (toUri.find ("sips:") != 1) { + _debug ("UserAgent: Error \"sips\" scheme required for TLS call"); + return false; + } - if(createTlsTransport(account->getAccountID(), remoteAddr) != PJ_SUCCESS) - return false; + if (createTlsTransport (account->getAccountID(), remoteAddr) != PJ_SUCCESS) + return false; } // If no transport already set, use the default one created at pjsip initialization if (account->getAccountTransport() == NULL) { - _debug ("UserAgent: No transport for this account, using the default one"); - account->setAccountTransport (_localUDPTransport); + _debug ("UserAgent: No transport for this account, using the default one"); + account->setAccountTransport (_localUDPTransport); } _debug ("UserAgent: Local port %i for IP2IP call", account->getLocalPort()); @@ -1729,94 +1695,94 @@ bool SIPVoIPLink::new_ip_to_ip_call (const CallID& id, const std::string& to) int port = findLocalPortFromUri (toUri, account->getAccountTransport()); std::stringstream ss; - std::string portStr; - ss << port; - ss >> portStr; - - std::string contactUri = account->getContactHeader (address, portStr); - - _debug ("UserAgent: FROM uri: %s, TO uri: %s, CONTACT uri: %s", - fromUri.c_str(), toUri.c_str(), contactUri.c_str()); - - pj_str_t pjFrom; - pj_cstr (&pjFrom, fromUri.c_str()); - - pj_str_t pjTo; - pj_cstr (&pjTo, toUri.c_str()); - - pj_str_t pjContact; - pj_cstr (&pjContact, contactUri.c_str()); - - // Create the dialog (UAC) - // (Parameters are "strduped" inside this function) - status = pjsip_dlg_create_uac (pjsip_ua_instance(), &pjFrom, &pjContact, &pjTo, NULL, &dialog); - 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); - - if(!(account->getServiceRoute().empty())) { - - _error("UserAgent: Set Service-Route with %s", account->getServiceRoute().c_str()); - - pjsip_route_hdr *route_set = pjsip_route_hdr_create(_pool); - pjsip_route_hdr *routing = pjsip_route_hdr_create(_pool); - pjsip_sip_uri *url = pjsip_sip_uri_create(_pool, 0); - routing->name_addr.uri = (pjsip_uri*)url; - pj_strdup2(_pool, &url->host, account->getServiceRoute().c_str()); - - pj_list_push_back(&route_set, pjsip_hdr_clone(_pool, routing)); - - pjsip_dlg_set_route_set(dialog, route_set); - } - - // Set the appropriate transport - pjsip_tpselector *tp; - - init_transport_selector (account->getAccountTransport(), &tp); - - if(!account->getAccountTransport()) { - _error("UserAgent: Error: Transport is NULL in IP2IP call"); - } - - // set_transport methods increment transport's ref_count - status = pjsip_dlg_set_transport (dialog, tp); - - // decrement transport's ref count - // pjsip_transport_dec_ref(account->getAccountTransport()); - - if (status != PJ_SUCCESS) { - _error ("UserAgent: Error: Failed to set the transport for an IP2IP call"); - return status; - } - - // 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) { - delete call; - call = 0; - return false; - } - - call->setConnectionState (Call::Progressing); - - call->setState (Call::Active); - addCall (call); - - return true; + std::string portStr; + ss << port; + ss >> portStr; + + std::string contactUri = account->getContactHeader (address, portStr); + + _debug ("UserAgent: FROM uri: %s, TO uri: %s, CONTACT uri: %s", + fromUri.c_str(), toUri.c_str(), contactUri.c_str()); + + pj_str_t pjFrom; + pj_cstr (&pjFrom, fromUri.c_str()); + + pj_str_t pjTo; + pj_cstr (&pjTo, toUri.c_str()); + + pj_str_t pjContact; + pj_cstr (&pjContact, contactUri.c_str()); + + // Create the dialog (UAC) + // (Parameters are "strduped" inside this function) + status = pjsip_dlg_create_uac (pjsip_ua_instance(), &pjFrom, &pjContact, &pjTo, NULL, &dialog); + 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); + + if (! (account->getServiceRoute().empty())) { + + _error ("UserAgent: Set Service-Route with %s", account->getServiceRoute().c_str()); + + pjsip_route_hdr *route_set = pjsip_route_hdr_create (_pool); + pjsip_route_hdr *routing = pjsip_route_hdr_create (_pool); + pjsip_sip_uri *url = pjsip_sip_uri_create (_pool, 0); + routing->name_addr.uri = (pjsip_uri*) url; + pj_strdup2 (_pool, &url->host, account->getServiceRoute().c_str()); + + pj_list_push_back (&route_set, pjsip_hdr_clone (_pool, routing)); + + pjsip_dlg_set_route_set (dialog, route_set); + } + + // Set the appropriate transport + pjsip_tpselector *tp; + + init_transport_selector (account->getAccountTransport(), &tp); + + if (!account->getAccountTransport()) { + _error ("UserAgent: Error: Transport is NULL in IP2IP call"); + } + + // set_transport methods increment transport's ref_count + status = pjsip_dlg_set_transport (dialog, tp); + + // decrement transport's ref count + // pjsip_transport_dec_ref(account->getAccountTransport()); + + if (status != PJ_SUCCESS) { + _error ("UserAgent: Error: Failed to set the transport for an IP2IP call"); + return status; + } + + // 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) { + delete call; + call = 0; + return false; + } + + call->setConnectionState (Call::Progressing); + + call->setState (Call::Active); + addCall (call); + + return true; } else - return false; + return false; } @@ -1825,8 +1791,7 @@ bool SIPVoIPLink::new_ip_to_ip_call (const CallID& id, const std::string& to) /////////////////////////////////////////////////////////////////////////////// -bool get_dns_server_addresses (std::vector<std::string> *servers) -{ +bool get_dns_server_addresses (std::vector<std::string> *servers) { int server_count, i; std::vector<std::string> nameservers; @@ -1853,18 +1818,18 @@ bool get_dns_server_addresses (std::vector<std::string> *servers) return true; } -pj_status_t SIPVoIPLink::enable_dns_srv_resolver (pjsip_endpoint *endpt, pj_dns_resolver **p_resv) -{ +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; int scount, i; - _debug("UserAgent: Enable DNS SRV resolver"); + _debug ("UserAgent: Enable DNS SRV resolver"); // Create the DNS resolver instance status = pjsip_endpt_create_resolver (endpt, &resv); + if (status != PJ_SUCCESS) { _error ("UserAgent: Error: Creating the DNS resolver instance"); return status; @@ -1882,13 +1847,15 @@ pj_status_t SIPVoIPLink::enable_dns_srv_resolver (pjsip_endpoint *endpt, pj_dns_ } pj_str_t nameservers[scount]; + for (i = 0; i<scount; i++) { - _debug("UserAgent: Server: %s", (char *)dns_servers[i].c_str()); + _debug ("UserAgent: Server: %s", (char *) dns_servers[i].c_str()); 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 ("UserAgent: Error updating the name servers for the DNS resolver"); return status; @@ -1896,6 +1863,7 @@ pj_status_t SIPVoIPLink::enable_dns_srv_resolver (pjsip_endpoint *endpt, pj_dns_ // Set the DNS resolver instance of the SIP resolver engine status = pjsip_endpt_set_resolver (endpt, resv); + if (status != PJ_SUCCESS) { _debug ("UserAgent: Error setting the DNS resolver instance of the SIP resolver engine"); return status; @@ -1907,8 +1875,7 @@ pj_status_t SIPVoIPLink::enable_dns_srv_resolver (pjsip_endpoint *endpt, pj_dns_ } -bool SIPVoIPLink::pjsip_init() -{ +bool SIPVoIPLink::pjsip_init() { pj_status_t status; pjsip_inv_callback inv_cb; pj_str_t accepted; @@ -1957,11 +1924,11 @@ bool SIPVoIPLink::pjsip_init() return false; } - // Initialize default UDP transport according to + // Initialize default UDP transport according to // IP to IP settings (most likely using port 5060) createDefaultSipUdpTransport(); - // Call this method to create TLS listener + // Call this method to create TLS listener createDefaultSipTlsListener(); // Initialize transaction layer @@ -2051,8 +2018,7 @@ bool SIPVoIPLink::pjsip_init() return PJ_SUCCESS; } -pj_status_t SIPVoIPLink::stunServerResolve (AccountID id) -{ +pj_status_t SIPVoIPLink::stunServerResolve (AccountID id) { pj_str_t stunServer; pj_uint16_t stunPort; pj_stun_sock_cb stun_sock_cb; @@ -2110,79 +2076,77 @@ pj_status_t SIPVoIPLink::stunServerResolve (AccountID id) -bool SIPVoIPLink::acquireTransport(const AccountID& accountID) { +bool SIPVoIPLink::acquireTransport (const AccountID& accountID) { SIPAccount* account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (accountID)); - if(!account) + if (!account) return false; - // If an account is already bound to this account, decrease its reference - // as it is going to change. If the same transport is selected, reference + // If an account is already bound to this account, decrease its reference + // as it is going to change. If the same transport is selected, reference // counter will be increased - if(account->getAccountTransport()) { + if (account->getAccountTransport()) { - _debug("pjsip_transport_dec_ref in acquireTransport"); - pjsip_transport_dec_ref(account->getAccountTransport()); + _debug ("pjsip_transport_dec_ref in acquireTransport"); + pjsip_transport_dec_ref (account->getAccountTransport()); } // Try to create a new transport in case the settings for this account // are different than one defined for already created ones // If TLS is enabled, TLS connection is automatically handled when sending account registration - // However, for any other sip transaction, we must create TLS connection - if(createSipTransport(accountID)) { + // However, for any other sip transaction, we must create TLS connection + if (createSipTransport (accountID)) { return true; } // A transport is already created on this port, use it else { - _debug("Could not create a new transport (%s)", account->getTransportMapKey().c_str()); - _debug("Searching transport (%s) in transport map", account->getTransportMapKey().c_str()); + _debug ("Could not create a new transport (%s)", account->getTransportMapKey().c_str()); + _debug ("Searching transport (%s) in transport map", account->getTransportMapKey().c_str()); // Could not create new transport, this transport may already exists SipTransportMap::iterator transport; - transport = _transportMap.find(account->getTransportMapKey()); + transport = _transportMap.find (account->getTransportMapKey()); - if(transport != _transportMap.end()) { + if (transport != _transportMap.end()) { - // Transport already exist, use it for this account - _debug("Found transport (%s) in transport map", account->getTransportMapKey().c_str()); + // Transport already exist, use it for this account + _debug ("Found transport (%s) in transport map", account->getTransportMapKey().c_str()); - pjsip_transport* tr = transport->second; + pjsip_transport* tr = transport->second; - // Set transport to be used for transaction involving this account - account->setAccountTransport(tr); + // Set transport to be used for transaction involving this account + account->setAccountTransport (tr); - // Increment newly associated transport reference counter - // If the account is shutdowning, time is automatically canceled - pjsip_transport_add_ref(tr); + // Increment newly associated transport reference counter + // If the account is shutdowning, time is automatically canceled + pjsip_transport_add_ref (tr); - return true; - } - else { + return true; + } else { - // Transport could not either be created, socket not available - _debug("Did not find transport (%s) in transport map", account->getTransportMapKey().c_str()); + // Transport could not either be created, socket not available + _debug ("Did not find transport (%s) in transport map", account->getTransportMapKey().c_str()); - account->setAccountTransport(_localUDPTransport); + account->setAccountTransport (_localUDPTransport); - std::string localHostName(_localUDPTransport->local_name.host.ptr, _localUDPTransport->local_name.host.slen); + std::string localHostName (_localUDPTransport->local_name.host.ptr, _localUDPTransport->local_name.host.slen); - _debug("Use default one instead (%s:%i)", localHostName.c_str(), _localUDPTransport->local_name.port); + _debug ("Use default one instead (%s:%i)", localHostName.c_str(), _localUDPTransport->local_name.port); - // account->setLocalAddress(localHostName); - account->setLocalPort(_localUDPTransport->local_name.port); + // account->setLocalAddress(localHostName); + account->setLocalPort (_localUDPTransport->local_name.port); - // Transport could not either be created or found in the map, socket not available - return false; - } + // Transport could not either be created or found in the map, socket not available + return false; + } } } -bool SIPVoIPLink::createDefaultSipUdpTransport() -{ +bool SIPVoIPLink::createDefaultSipUdpTransport() { int errPjsip = 0; @@ -2194,16 +2158,16 @@ bool SIPVoIPLink::createDefaultSipUdpTransport() // Create a UDP listener meant for all accounts for which TLS was not enabled // Cannot acquireTransport since default UDP transport must be created regardless of TLS - errPjsip = createUdpTransport(IP2IP_PROFILE); + errPjsip = createUdpTransport (IP2IP_PROFILE); - if(account && (errPjsip == PJ_SUCCESS)) { + if (account && (errPjsip == PJ_SUCCESS)) { // Store transport in transport map - addTransportToMap(account->getTransportMapKey(), account->getAccountTransport()); + addTransportToMap (account->getTransportMapKey(), account->getAccountTransport()); + + // if account is not NULL, use IP2IP trasport as default one + _localUDPTransport = account->getAccountTransport(); - // if account is not NULL, use IP2IP trasport as default one - _localUDPTransport = account->getAccountTransport(); - } // If the above UDP server // could not be created, then give it another try @@ -2213,12 +2177,12 @@ bool SIPVoIPLink::createDefaultSipUdpTransport() _regPort = RANDOM_SIP_PORT; _debug ("UserAgent: Trying to initialize SIP listener on port %d", _regPort); - // If no AccountID specified, pointer to transport is stored in _localUDPTransport + // If no AccountID specified, pointer to transport is stored in _localUDPTransport errPjsip = createUdpTransport(); if (errPjsip != PJ_SUCCESS) { _debug ("UserAgent: Fail to initialize SIP listener on port %d", _regPort); - return false; + return false; } } @@ -2227,20 +2191,18 @@ bool SIPVoIPLink::createDefaultSipUdpTransport() } -void SIPVoIPLink::createDefaultSipTlsListener() -{ +void SIPVoIPLink::createDefaultSipTlsListener() { SIPAccount * account = NULL; account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (IP2IP_PROFILE)); - if(account->isTlsEnabled()) { - createTlsListener(IP2IP_PROFILE); + if (account->isTlsEnabled()) { + createTlsListener (IP2IP_PROFILE); } } -void SIPVoIPLink::createTlsListener(const AccountID& accountID) -{ +void SIPVoIPLink::createTlsListener (const AccountID& accountID) { pjsip_tpfactory *tls; pj_sockaddr_in local_addr; @@ -2248,7 +2210,7 @@ void SIPVoIPLink::createTlsListener(const AccountID& accountID) pj_status_t status; pj_status_t success; - _debug("Create TLS listener"); + _debug ("Create TLS listener"); /* Grab the tls settings, populated * from configuration file. @@ -2266,7 +2228,7 @@ void SIPVoIPLink::createTlsListener(const AccountID& accountID) pj_sockaddr_in_init (&local_addr, 0, 0); pj_uint16_t localTlsPort = account->getTlsListenerPort(); local_addr.sin_port = pj_htons (localTlsPort); - + pj_str_t pjAddress; pj_cstr (&pjAddress, PJ_INADDR_ANY); success = pj_sockaddr_in_set_str_addr (&local_addr, &pjAddress); @@ -2274,7 +2236,7 @@ void SIPVoIPLink::createTlsListener(const AccountID& accountID) // Init published address for this listener (Local IP address on port 5061) std::string publishedAddress; - loadSIPLocalIP(&publishedAddress); + loadSIPLocalIP (&publishedAddress); pj_bzero (&a_name, sizeof (pjsip_host_port)); pj_cstr (&a_name.host, publishedAddress.c_str()); @@ -2283,29 +2245,27 @@ void SIPVoIPLink::createTlsListener(const AccountID& accountID) /* Get TLS settings. Expected to be filled */ pjsip_tls_setting * tls_setting = account->getTlsSetting(); - + _debug ("UserAgent: TLS transport to be initialized with published address %.*s," " published port %d,\n local address %.*s, local port %d", (int) a_name.host.slen, a_name.host.ptr, (int) a_name.port, pjAddress.slen, pjAddress.ptr, (int) localTlsPort); - + status = pjsip_tls_transport_start (_endpt, tls_setting, &local_addr, &a_name, 1, &tls); if (status != PJ_SUCCESS) { _debug ("UserAgent: Error creating SIP TLS listener (%d)", status); - } - else { + } else { _localTlsListener = tls; } - + // return PJ_SUCCESS; - + } -bool SIPVoIPLink::createSipTransport(AccountID id) -{ +bool SIPVoIPLink::createSipTransport (AccountID id) { SIPAccount* account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (id)); @@ -2316,23 +2276,22 @@ bool SIPVoIPLink::createSipTransport(AccountID id) if (account->isTlsEnabled()) { - if(_localTlsListener == NULL) - createTlsListener(id); + if (_localTlsListener == NULL) + createTlsListener (id); - // Parse remote address to establish connection + // Parse remote address to establish connection std::string remoteSipUri = account->getServerUri(); - int sips = remoteSipUri.find("<sips:") + 6; - int trns = remoteSipUri.find(";transport"); - std::string remoteAddr = remoteSipUri.substr(sips, trns-sips); + int sips = remoteSipUri.find ("<sips:") + 6; + int trns = remoteSipUri.find (";transport"); + std::string remoteAddr = remoteSipUri.substr (sips, trns-sips); // Nothing to do, TLS listener already created at pjsip's startup and TLS connection // is automatically handled in pjsip when sending registration messages. - if(createTlsTransport(id, remoteAddr) != PJ_SUCCESS) - return false; + if (createTlsTransport (id, remoteAddr) != PJ_SUCCESS) + return false; return true; - } - else { + } else { // Launch a new UDP listener/transport, using the published address if (account->isStunEnabled ()) { @@ -2341,53 +2300,50 @@ bool SIPVoIPLink::createSipTransport(AccountID id) if (status != PJ_SUCCESS) { _debug ("Failed to init UDP transport with STUN published address for account %s", id.c_str()); - return false; + return false; } } else { status = createUdpTransport (id); - if (status != PJ_SUCCESS) { + if (status != PJ_SUCCESS) { _debug ("Failed to initialize UDP transport for account %s", id.c_str()); - return false; - } - else { + return false; + } else { - // If transport successfully created, store it in the internal map. - // STUN aware transport are account specific and should not be stored in map. - // TLS transport is ephemeral and is managed by PJSIP, should not be stored either. - addTransportToMap(account->getTransportMapKey(), account->getAccountTransport()); - } - } + // If transport successfully created, store it in the internal map. + // STUN aware transport are account specific and should not be stored in map. + // TLS transport is ephemeral and is managed by PJSIP, should not be stored either. + addTransportToMap (account->getTransportMapKey(), account->getAccountTransport()); + } + } } - return true; + return true; } - -bool SIPVoIPLink::addTransportToMap(std::string key, pjsip_transport* transport) -{ + +bool SIPVoIPLink::addTransportToMap (std::string key, pjsip_transport* transport) { SipTransportMap::iterator iter_transport; - iter_transport = _transportMap.find(key); - + iter_transport = _transportMap.find (key); + // old transport in transport map, erase it - if(iter_transport != _transportMap.end()){ - _transportMap.erase(iter_transport); + if (iter_transport != _transportMap.end()) { + _transportMap.erase (iter_transport); } - _debug("UserAgent: Storing newly created transport in map using key %s", key.c_str()); - _transportMap.insert(pair<std::string, pjsip_transport*>(key, transport)); + _debug ("UserAgent: Storing newly created transport in map using key %s", key.c_str()); + _transportMap.insert (pair<std::string, pjsip_transport*> (key, transport)); return true; } -int SIPVoIPLink::createUdpTransport (AccountID id) -{ +int SIPVoIPLink::createUdpTransport (AccountID id) { pj_status_t status; pj_sockaddr_in bound_addr; @@ -2422,10 +2378,10 @@ int SIPVoIPLink::createUdpTransport (AccountID id) } else { // We are trying to initialize a UDP transport available for all local accounts and direct IP calls - _debug("UserAgent: found account %s in map", account->getAccountID().c_str()); + _debug ("UserAgent: found account %s in map", account->getAccountID().c_str()); if (account->getLocalInterface () != "default") { - listeningAddress = getInterfaceAddrFromName(account->getLocalInterface()); + listeningAddress = getInterfaceAddrFromName (account->getLocalInterface()); } listeningPort = account->getLocalPort (); @@ -2439,13 +2395,12 @@ int SIPVoIPLink::createUdpTransport (AccountID id) // Init bound address to ANY bound_addr.sin_addr.s_addr = pj_htonl (PJ_INADDR_ANY); - loadSIPLocalIP (&listeningAddress); - } - else { + loadSIPLocalIP (&listeningAddress); + } else { - // bind this account to a specific interface - pj_strdup2(_pool, &temporary_address, listeningAddress.c_str()); - bound_addr.sin_addr = pj_inet_addr(&temporary_address); + // bind this account to a specific interface + pj_strdup2 (_pool, &temporary_address, listeningAddress.c_str()); + bound_addr.sin_addr = pj_inet_addr (&temporary_address); } bound_addr.sin_port = pj_htons ( (pj_uint16_t) listeningPort); @@ -2467,13 +2422,14 @@ int SIPVoIPLink::createUdpTransport (AccountID id) // We must specify this here to avoid the IP2IP_PROFILE // to create a transport with name 0.0.0.0 to appear in the via header - if(id == IP2IP_PROFILE) - loadSIPLocalIP (&listeningAddress); + if (id == IP2IP_PROFILE) + loadSIPLocalIP (&listeningAddress); - if(listeningAddress == "" || listeningPort == 0) { - _error("UserAgent: Error invalid address for new udp transport"); - return !PJ_SUCCESS; + if (listeningAddress == "" || listeningPort == 0) { + _error ("UserAgent: Error invalid address for new udp transport"); + return !PJ_SUCCESS; } + //strcpy (tmpIP, listeningAddress.data()); /* Init published name */ pj_bzero (&a_name, sizeof (pjsip_host_port)); @@ -2500,21 +2456,19 @@ int SIPVoIPLink::createUdpTransport (AccountID id) if (account == NULL) { - _debug("UserAgent: Use transport as local UDP server"); + _debug ("UserAgent: Use transport as local UDP server"); _localUDPTransport = transport; - } - else { + } else { - _debug("UserAgent: bind transport to account %s", account->getAccountID().c_str()); - account->setAccountTransport (transport); - } + _debug ("UserAgent: bind transport to account %s", account->getAccountID().c_str()); + account->setAccountTransport (transport); + } } return PJ_SUCCESS; } -std::string SIPVoIPLink::findLocalAddressFromUri (const std::string& uri, pjsip_transport *transport) -{ +std::string SIPVoIPLink::findLocalAddressFromUri (const std::string& uri, pjsip_transport *transport) { pj_str_t localAddress; pjsip_transport_type_e transportType; pjsip_tpselector *tp_sel; @@ -2575,18 +2529,17 @@ std::string SIPVoIPLink::findLocalAddressFromUri (const std::string& uri, pjsip_ pj_status_t status; /* Init the transport selector */ + //_debug ("Transport ID: %s", transport->obj_name); if (transportType == PJSIP_TRANSPORT_UDP) { status = init_transport_selector (transport, &tp_sel); if (status == PJ_SUCCESS) { status = pjsip_tpmgr_find_local_addr (tpmgr, _pool, transportType, tp_sel, &localAddress, &port); + } else { + status = pjsip_tpmgr_find_local_addr (tpmgr, _pool, transportType, NULL, &localAddress, &port); } - else { - status = pjsip_tpmgr_find_local_addr (tpmgr, _pool, transportType, NULL, &localAddress, &port); - } - } - else { + } else { status = pjsip_tpmgr_find_local_addr (tpmgr, _pool, transportType, NULL, &localAddress, &port); } @@ -2595,20 +2548,19 @@ std::string SIPVoIPLink::findLocalAddressFromUri (const std::string& uri, pjsip_ return machineName; } - std::string localaddr(localAddress.ptr, localAddress.slen); + std::string localaddr (localAddress.ptr, localAddress.slen); - if(localaddr == "0.0.0.0") - loadSIPLocalIP (&localaddr); + if (localaddr == "0.0.0.0") + loadSIPLocalIP (&localaddr); - _debug ("SIP: Local address discovered from attached transport: %s", localaddr.c_str()); + _debug ("SIP: Local address discovered from attached transport: %s", localaddr.c_str()); return localaddr; } -pj_status_t SIPVoIPLink::init_transport_selector (pjsip_transport *transport, pjsip_tpselector **tp_sel) -{ +pj_status_t SIPVoIPLink::init_transport_selector (pjsip_transport *transport, pjsip_tpselector **tp_sel) { pjsip_tpselector *tp; if (transport != NULL) { @@ -2624,8 +2576,7 @@ pj_status_t SIPVoIPLink::init_transport_selector (pjsip_transport *transport, pj return !PJ_SUCCESS; } -int SIPVoIPLink::findLocalPortFromUri (const std::string& uri, pjsip_transport *transport) -{ +int SIPVoIPLink::findLocalPortFromUri (const std::string& uri, pjsip_transport *transport) { pj_str_t localAddress; pjsip_transport_type_e transportType; int port; @@ -2704,26 +2655,25 @@ int SIPVoIPLink::findLocalPortFromUri (const std::string& uri, pjsip_transport * } -pj_status_t SIPVoIPLink::createTlsTransport(const AccountID& accountID, std::string remoteAddr) -{ +pj_status_t SIPVoIPLink::createTlsTransport (const AccountID& accountID, std::string remoteAddr) { pj_status_t success; - _debug("Create TLS transport for account %s\n", accountID.c_str()); + _debug ("Create TLS transport for account %s\n", accountID.c_str()); // Retrieve the account information SIPAccount * account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (accountID)); - if(!account) { - _debug("UserAgent: Account is NULL when creating TLS connection, returning"); - return !PJ_SUCCESS; + if (!account) { + _debug ("UserAgent: Account is NULL when creating TLS connection, returning"); + return !PJ_SUCCESS; } pj_sockaddr_in rem_addr; pj_str_t remote; - pj_cstr(&remote, remoteAddr.c_str()); + pj_cstr (&remote, remoteAddr.c_str()); - pj_sockaddr_in_init(&rem_addr, &remote, (pj_uint16_t)5061); + pj_sockaddr_in_init (&rem_addr, &remote, (pj_uint16_t) 5061); // Update TLS settings for account registration using the default listeners // Pjsip does not allow to create multiple listener @@ -2732,18 +2682,17 @@ pj_status_t SIPVoIPLink::createTlsTransport(const AccountID& accountID, std::str // Create a new TLS connection from TLS listener pjsip_transport *tls; - success = pjsip_endpt_acquire_transport(_endpt, PJSIP_TRANSPORT_TLS, &rem_addr, sizeof(rem_addr), NULL, &tls); + success = pjsip_endpt_acquire_transport (_endpt, PJSIP_TRANSPORT_TLS, &rem_addr, sizeof (rem_addr), NULL, &tls); - if(success != PJ_SUCCESS) - _debug("UserAgent: Error could not create TLS transport"); - else - account->setAccountTransport(tls); + if (success != PJ_SUCCESS) + _debug ("UserAgent: Error could not create TLS transport"); + else + account->setAccountTransport (tls); return success; } -pj_status_t SIPVoIPLink::createAlternateUdpTransport (AccountID id) -{ +pj_status_t SIPVoIPLink::createAlternateUdpTransport (AccountID id) { pj_sockaddr_in boundAddr; pjsip_host_port a_name; pj_status_t status; @@ -2832,18 +2781,18 @@ pj_status_t SIPVoIPLink::createAlternateUdpTransport (AccountID id) account->setAccountTransport (transport); - if(transport) { + if (transport) { + + _debug ("UserAgent: Initial ref count: %s %s (refcnt=%i)", transport->obj_name, transport->info, + (int) pj_atomic_get (transport->ref_cnt)); + + pj_sockaddr *addr = (pj_sockaddr*) & (transport->key.rem_addr); - _debug("UserAgent: Initial ref count: %s %s (refcnt=%i)", transport->obj_name, transport->info, - (int)pj_atomic_get(transport->ref_cnt)); + static char str[PJ_INET6_ADDRSTRLEN]; + pj_inet_ntop ( ( (const pj_sockaddr*) addr)->addr.sa_family, pj_sockaddr_get_addr (addr), str, sizeof (str)); - pj_sockaddr *addr = (pj_sockaddr*)&(transport->key.rem_addr); - static char str[PJ_INET6_ADDRSTRLEN]; - pj_inet_ntop(((const pj_sockaddr*)addr)->addr.sa_family, pj_sockaddr_get_addr(addr), str, sizeof(str)); - - - _debug("UserAgent: KEY: %s:%d",str, pj_sockaddr_get_port((const pj_sockaddr*)&(transport->key.rem_addr))); + _debug ("UserAgent: KEY: %s:%d",str, pj_sockaddr_get_port ( (const pj_sockaddr*) & (transport->key.rem_addr))); } @@ -2855,28 +2804,27 @@ pj_status_t SIPVoIPLink::createAlternateUdpTransport (AccountID id) } -void SIPVoIPLink::shutdownSipTransport(const AccountID& accountID) -{ +void SIPVoIPLink::shutdownSipTransport (const AccountID& accountID) { - _debug("UserAgent: Shutdown Sip Transport"); + _debug ("UserAgent: Shutdown Sip Transport"); SIPAccount* account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (accountID)); - if(!account) + if (!account) return; - if(account->getAccountTransport()) { + if (account->getAccountTransport()) { - _debug("Transport bound to account, decrease ref count"); + _debug ("Transport bound to account, decrease ref count"); - // decrease reference count added by pjsip_regc_send - // PJSIP's IDLE timer is set if counter reach 0 + // decrease reference count added by pjsip_regc_send + // PJSIP's IDLE timer is set if counter reach 0 // there is still problems when account registration fails, so comment it for now - // status = pjsip_transport_dec_ref(account->getAccountTransport()); + // status = pjsip_transport_dec_ref(account->getAccountTransport()); - // detach transport from this account - account->setAccountTransport(NULL); + // detach transport from this account + account->setAccountTransport (NULL); } @@ -2884,8 +2832,7 @@ void SIPVoIPLink::shutdownSipTransport(const AccountID& accountID) -bool SIPVoIPLink::loadSIPLocalIP (std::string *addr) -{ +bool SIPVoIPLink::loadSIPLocalIP (std::string *addr) { bool returnValue = true; std::string localAddress = "127.0.0.1"; @@ -2905,8 +2852,7 @@ bool SIPVoIPLink::loadSIPLocalIP (std::string *addr) return returnValue; } -void SIPVoIPLink::busy_sleep (unsigned msec) -{ +void SIPVoIPLink::busy_sleep (unsigned msec) { #if defined(PJ_SYMBIAN) && PJ_SYMBIAN != 0 /* Ideally we shouldn't call pj_thread_sleep() and rather @@ -2933,8 +2879,7 @@ void SIPVoIPLink::busy_sleep (unsigned msec) #endif } -bool SIPVoIPLink::pjsip_shutdown (void) -{ +bool SIPVoIPLink::pjsip_shutdown (void) { if (_endpt) { _debug ("UserAgent: Shutting down..."); busy_sleep (1000); @@ -2968,13 +2913,11 @@ bool SIPVoIPLink::pjsip_shutdown (void) return true; } -int getModId() -{ +int getModId() { return _mod_ua.id; } -static void dns_cb (pj_status_t status, void *token, const struct pjsip_server_addresses *addr) -{ +static void dns_cb (pj_status_t status, void *token, const struct pjsip_server_addresses *addr) { struct result * result = (struct result*) token; @@ -2985,8 +2928,7 @@ static void dns_cb (pj_status_t status, void *token, const struct pjsip_server_a } } -void set_voicemail_info (AccountID account, pjsip_msg_body *body) -{ +void set_voicemail_info (AccountID account, pjsip_msg_body *body) { int voicemail = 0, pos_begin, pos_end; std::string voice_str = "Voice-Message: "; @@ -3021,32 +2963,30 @@ void set_voicemail_info (AccountID account, pjsip_msg_body *body) Manager::instance().startVoiceMessageNotification (account, voicemail); } -void SIPVoIPLink::handle_reinvite (SIPCall *call) -{ +void SIPVoIPLink::handle_reinvite (SIPCall *call) { _debug ("UserAgent: Handle reinvite"); /* // Close the previous RTP session call->getAudioRtp()->stop (); call->setAudioStart (false); - + _debug ("Create new rtp session from handle_reinvite : %s:%i", call->getLocalIp().c_str(), call->getLocalAudioPort()); _debug ("UserAgent: handle_reinvite"); - + try { call->getAudioRtp()->initAudioRtpSession (call); } catch (...) { _debug ("! SIP Failure: Unable to create RTP Session (%s:%d)", __FILE__, __LINE__); } - - + + _debug("Handle reINVITE"); */ } // This callback is called when the invite session state has changed -void call_on_state_changed (pjsip_inv_session *inv, pjsip_event *e) -{ +void call_on_state_changed (pjsip_inv_session *inv, pjsip_event *e) { _debug ("UserAgent: Call state changed to %s", invitationStateMap[inv->state]); pjsip_rx_data *rdata; @@ -3182,22 +3122,24 @@ void call_on_state_changed (pjsip_inv_session *inv, pjsip_event *e) accId = Manager::instance().getAccountFromCall (call->getCallId()); link = dynamic_cast<SIPVoIPLink *> (Manager::instance().getAccountLink (accId)); - // Make sure link is valid - assert(link); + // Make sure link is valid + assert (link); switch (inv->cause) { - // The call terminates normally - BYE / CANCEL + // The call terminates normally - BYE / CANCEL case PJSIP_SC_OK: case PJSIP_SC_REQUEST_TERMINATED: link->SIPCallClosed (call); break; case PJSIP_SC_DECLINE: - _debug("UserAgent: Call %s is declined", call->getCallId().c_str()); - if (inv->role == PJSIP_ROLE_UAC) - link->SIPCallServerFailure (call); - break; + _debug ("UserAgent: Call %s is declined", call->getCallId().c_str()); + + if (inv->role == PJSIP_ROLE_UAC) + link->SIPCallServerFailure (call); + + break; case PJSIP_SC_NOT_FOUND: /* peer not found */ case PJSIP_SC_REQUEST_TIMEOUT: /* request timeout */ @@ -3206,13 +3148,13 @@ void call_on_state_changed (pjsip_inv_session *inv, pjsip_event *e) case PJSIP_SC_UNSUPPORTED_MEDIA_TYPE: case PJSIP_SC_UNAUTHORIZED: case PJSIP_SC_FORBIDDEN: - case PJSIP_SC_REQUEST_PENDING: - case PJSIP_SC_ADDRESS_INCOMPLETE: + case PJSIP_SC_REQUEST_PENDING: + case PJSIP_SC_ADDRESS_INCOMPLETE: link->SIPCallServerFailure (call); break; default: - link->SIPCallServerFailure (call); + link->SIPCallServerFailure (call); _error ("UserAgent: Unhandled call state. This is probably a bug."); break; } @@ -3221,8 +3163,7 @@ void call_on_state_changed (pjsip_inv_session *inv, pjsip_event *e) } // This callback is called after SDP offer/answer session has completed. -void call_on_media_update (pjsip_inv_session *inv, pj_status_t status) -{ +void call_on_media_update (pjsip_inv_session *inv, pj_status_t status) { _debug ("UserAgent: Call media update"); const pjmedia_sdp_session *local_sdp; @@ -3274,105 +3215,105 @@ void call_on_media_update (pjsip_inv_session *inv, pj_status_t status) try { call->getAudioRtp()->updateDestinationIpAddress(); - } - catch(...) { - + } catch (...) { + } // Get the crypto attribute containing srtp's cryptographic context (keys, cipher) CryptoOffer crypto_offer; - call->getLocalSDP()->get_remote_sdp_crypto_from_offer(remote_sdp, crypto_offer); + call->getLocalSDP()->get_remote_sdp_crypto_from_offer (remote_sdp, crypto_offer); bool nego_success = false; - if(!crypto_offer.empty()) { - _debug("UserAgent: Crypto attribute in SDP, init SRTP session"); + if (!crypto_offer.empty()) { + + _debug ("UserAgent: Crypto attribute in SDP, init SRTP session"); + + // init local cryptografic capabilities for negotiation + std::vector<sfl::CryptoSuiteDefinition>localCapabilities; + + for (int i = 0; i < 3; i++) { + localCapabilities.push_back (sfl::CryptoSuites[i]); + } + + sfl::SdesNegotiator sdesnego (localCapabilities, crypto_offer); - // init local cryptografic capabilities for negotiation - std::vector<sfl::CryptoSuiteDefinition>localCapabilities; - for(int i = 0; i < 3; i++) { - localCapabilities.push_back(sfl::CryptoSuites[i]); - } + if (sdesnego.negotiate()) { + _debug ("UserAgent: SDES negociation successfull \n"); + nego_success = true; - sfl::SdesNegotiator sdesnego(localCapabilities, crypto_offer); - - if(sdesnego.negotiate()) { - _debug("UserAgent: SDES negociation successfull \n"); - nego_success = true; + _debug ("UserAgent: Set remote cryptographic context\n"); - _debug("UserAgent: Set remote cryptographic context\n"); try { - call->getAudioRtp()->setRemoteCryptoInfo(sdesnego); - } - catch(...) {} + call->getAudioRtp()->setRemoteCryptoInfo (sdesnego); + } catch (...) {} DBusManager::instance().getCallManager()->secureSdesOn (call->getCallId()); - } - else { - DBusManager::instance().getCallManager()->secureSdesOff (call->getCallId()); - } + } else { + DBusManager::instance().getCallManager()->secureSdesOff (call->getCallId()); + } } // We did not found any crypto context for this media - if(!nego_success && call->getAudioRtp()->getAudioRtpType() == sfl::Sdes) { - + if (!nego_success && call->getAudioRtp()->getAudioRtpType() == sfl::Sdes) { + // We did not found any crypto context for this media // @TODO if SRTPONLY, CallFail - _debug("UserAgent: Did not found any crypto or negociation failed but Sdes enabled"); + _debug ("UserAgent: Did not found any crypto or negociation failed but Sdes enabled"); call->getAudioRtp()->stop(); - call->getAudioRtp()->setSrtpEnabled(false); + call->getAudioRtp()->setSrtpEnabled (false); - // if RTPFALLBACK, change RTP session - AccountID accountID = Manager::instance().getAccountFromCall (call->getCallId()); - SIPAccount *account = (SIPAccount *)Manager::instance().getAccount(accountID); + // if RTPFALLBACK, change RTP session + AccountID accountID = Manager::instance().getAccountFromCall (call->getCallId()); + SIPAccount *account = (SIPAccount *) Manager::instance().getAccount (accountID); - if(account->getSrtpFallback()) - call->getAudioRtp()->initAudioRtpSession(call); + if (account->getSrtpFallback()) + call->getAudioRtp()->initAudioRtpSession (call); } - if(nego_success && call->getAudioRtp()->getAudioRtpType() != sfl::Sdes) { - - // We found a crypto context for this media but Sdes is not + if (nego_success && call->getAudioRtp()->getAudioRtpType() != sfl::Sdes) { + + // We found a crypto context for this media but Sdes is not // enabled for this call, make a try using RTP only... - _debug("UserAgent: SDES not initialized for this call\n"); + _debug ("UserAgent: SDES not initialized for this call\n"); } Sdp *sdpSession = call->getLocalSDP(); - if(!sdpSession) - return; + + if (!sdpSession) + return; AudioCodec *sessionMedia = sdpSession->get_session_media(); - if(!sessionMedia) - return; - AudioCodecType pl = (AudioCodecType)sessionMedia->getPayload(); - AudioCodec* audiocodec = Manager::instance().getCodecDescriptorMap().instantiateCodec(pl); + if (!sessionMedia) + return; + + AudioCodecType pl = (AudioCodecType) sessionMedia->getPayload(); + AudioCodec* audiocodec = Manager::instance().getCodecDescriptorMap().instantiateCodec (pl); - if (audiocodec == NULL) - _error ("UserAgent: No audiocodec found"); + if (audiocodec == NULL) + _error ("UserAgent: No audiocodec found"); try { call->setAudioStart (true); - call->getAudioRtp()->start(audiocodec); + call->getAudioRtp()->start (audiocodec); } catch (exception& rtpException) { _error ("UserAgent: Error: %s", rtpException.what()); } } -void call_on_forked (pjsip_inv_session *inv, pjsip_event *e) -{ +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) -{ - assert(tsx); +void call_on_tsx_changed (pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e) { + assert (tsx); - _debug("UserAgent: Transaction changed to state %s", transactionStateMap[tsx->state]); + _debug ("UserAgent: Transaction changed to state %s", transactionStateMap[tsx->state]); if (tsx->role==PJSIP_ROLE_UAS && tsx->state==PJSIP_TSX_STATE_TRYING && pjsip_method_cmp (&tsx->method, &pjsip_refer_method) ==0) { @@ -3383,26 +3324,26 @@ void call_on_tsx_changed (pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_ if (e && e->body.rx_msg.rdata) { - _debug("Event"); + _debug ("Event"); pjsip_tx_data* t_data; pjsip_rx_data* r_data = e->body.rx_msg.rdata; if (r_data && r_data->msg_info.msg->line.req.method.id == PJSIP_OTHER_METHOD) { - _debug("R_data"); + _debug ("R_data"); std::string method_info = "INFO"; std::string method_notify = "NOTIFY"; std::string request = pjsip_rx_data_get_info (r_data); - _debug("UserAgent: %s", request.c_str()); + _debug ("UserAgent: %s", request.c_str()); - if(request.find (method_notify) != (size_t)-1) { + if (request.find (method_notify) != (size_t)-1) { - } - // Must reply 200 OK on SIP INFO request - else if (request.find (method_info) != (size_t)-1) { + } + // Must reply 200 OK on SIP INFO request + else if (request.find (method_info) != (size_t)-1) { pjsip_dlg_create_response (inv->dlg, r_data, PJSIP_SC_OK, NULL, &t_data); @@ -3413,8 +3354,7 @@ void call_on_tsx_changed (pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_ } } -void regc_cb (struct pjsip_regc_cbparam *param) -{ +void regc_cb (struct pjsip_regc_cbparam *param) { SIPAccount * account = NULL; account = static_cast<SIPAccount *> (param->token); @@ -3434,10 +3374,10 @@ void regc_cb (struct pjsip_regc_cbparam *param) DBusManager::instance().getCallManager()->registrationStateChanged (account->getAccountID(), std::string (description->ptr, description->slen), param->code); std::pair<int, std::string> details (param->code, std::string (description->ptr, description->slen)); - - // there a race condition for this ressource when closing the application - if(account) - account->setRegistrationStateDetailed (details); + + // there a race condition for this ressource when closing the application + if (account) + account->setRegistrationStateDetailed (details); } if (param->status == PJ_SUCCESS) { @@ -3464,20 +3404,20 @@ void regc_cb (struct pjsip_regc_cbparam *param) account->setRegistrationState (ErrorAuth); break; - case 423: { // Expiration Interval Too Brief + case 423: { // Expiration Interval Too Brief - int expire_value; - std::istringstream stream (account->getRegistrationExpire()); - stream >> expire_value; + int expire_value; + std::istringstream stream (account->getRegistrationExpire()); + stream >> expire_value; - std::stringstream out; - out << (expire_value * 2); - std::string s = out.str(); + std::stringstream out; + out << (expire_value * 2); + std::string s = out.str(); - account->setRegistrationExpire(s); - account->registerVoIPLink(); - } - break; + account->setRegistrationExpire (s); + account->registerVoIPLink(); + } + break; default: account->setRegistrationState (Error); @@ -3486,11 +3426,11 @@ void regc_cb (struct pjsip_regc_cbparam *param) account->setRegister (false); - // shutdown this transport since useless - // if(account->getAccountTransport() != _localUDPTransport) { + // shutdown this transport since useless + // if(account->getAccountTransport() != _localUDPTransport) { - SIPVoIPLink::instance("")->shutdownSipTransport(account->getAccountID()); - //} + SIPVoIPLink::instance ("")->shutdownSipTransport (account->getAccountID()); + //} } else { // Registration/Unregistration is success @@ -3500,25 +3440,24 @@ void regc_cb (struct pjsip_regc_cbparam *param) account->setRegistrationState (Unregistered); account->setRegister (false); - SIPVoIPLink::instance("")->shutdownSipTransport(account->getAccountID()); + SIPVoIPLink::instance ("")->shutdownSipTransport (account->getAccountID()); - // pjsip_regc_destroy(param->regc); - // account->setRegistrationInfo(NULL); + // pjsip_regc_destroy(param->regc); + // account->setRegistrationInfo(NULL); } } } else { account->setRegistrationState (ErrorAuth); account->setRegister (false); - SIPVoIPLink::instance("")->shutdownSipTransport(account->getAccountID()); + SIPVoIPLink::instance ("")->shutdownSipTransport (account->getAccountID()); } } // Optional function to be called to process incoming request message. pj_bool_t -mod_on_rx_request (pjsip_rx_data *rdata) -{ +mod_on_rx_request (pjsip_rx_data *rdata) { pj_status_t status; pj_str_t reason; unsigned options = 0; @@ -3542,14 +3481,14 @@ mod_on_rx_request (pjsip_rx_data *rdata) std::string request; - _info("UserAgent: Transaction REQUEST received using transport: %s %s (refcnt=%d)", - rdata->tp_info.transport->obj_name, - rdata->tp_info.transport->info, - (int)pj_atomic_get(rdata->tp_info.transport->ref_cnt)); + _info ("UserAgent: Transaction REQUEST received using transport: %s %s (refcnt=%d)", + rdata->tp_info.transport->obj_name, + rdata->tp_info.transport->info, + (int) pj_atomic_get (rdata->tp_info.transport->ref_cnt)); // No need to go any further on incoming ACK - if (rdata->msg_info.msg->line.req.method.id == PJSIP_ACK_METHOD && pjsip_rdata_get_dlg(rdata) != NULL) { - _info("UserAgent: received an ACK"); + if (rdata->msg_info.msg->line.req.method.id == PJSIP_ACK_METHOD && pjsip_rdata_get_dlg (rdata) != NULL) { + _info ("UserAgent: received an ACK"); return true; } @@ -3576,24 +3515,26 @@ mod_on_rx_request (pjsip_rx_data *rdata) /* If we can't find any voIP link to handle the incoming call */ if (!link) { - _warn("UserAgent: Error: cannot retrieve the voiplink from the account ID..."); - pj_strdup2 (_pool, &reason, "ERROR: cannot retrieve the voip link from account"); - pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, - &reason, NULL, NULL); + _warn ("UserAgent: Error: cannot retrieve the voiplink from the account ID..."); + pj_strdup2 (_pool, &reason, "ERROR: cannot retrieve the voip link from account"); + pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, + &reason, NULL, NULL); return true; return false; } // Parse the display name from "From" header char* from_header = strstr (rdata->msg_info.msg_buf, "From: "); + if (from_header) { std::string temp (from_header); int begin_displayName = temp.find ("\"") + 1; int end_displayName = temp.rfind ("\""); displayName = temp.substr (begin_displayName, end_displayName - begin_displayName); - if(displayName.size() > 25) { - displayName = std::string (""); - } + + if (displayName.size() > 25) { + displayName = std::string (""); + } } else { displayName = std::string (""); } @@ -3614,15 +3555,17 @@ mod_on_rx_request (pjsip_rx_data *rdata) std::string peerNumber (tmp, length); //Remove sip: prefix - size_t found = peerNumber.find("sip:"); + size_t found = peerNumber.find ("sip:"); + if (found!=std::string::npos) - peerNumber.erase(found, found+4); + peerNumber.erase (found, found+4); + + found = peerNumber.find ("@"); - found = peerNumber.find("@"); if (found!=std::string::npos) - peerNumber.erase(found); + peerNumber.erase (found); - _debug("UserAgent: Peer number: %s", peerNumber.c_str()); + _debug ("UserAgent: Peer number: %s", peerNumber.c_str()); // Get the server voicemail notification // Catch the NOTIFY message @@ -3654,8 +3597,8 @@ mod_on_rx_request (pjsip_rx_data *rdata) 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); + pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_METHOD_NOT_ALLOWED, + &reason, NULL, NULL); return true; } } @@ -3663,20 +3606,22 @@ mod_on_rx_request (pjsip_rx_data *rdata) account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (account_id)); get_remote_sdp_from_offer (rdata, &r_sdp); - if(account->getActiveCodecs().empty()) { - _warn ("UserAgent: Error: No active codec"); - pj_strdup2 (_pool, &reason, "no active codec"); - pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_NOT_ACCEPTABLE_HERE , - &reason, NULL, NULL); + + if (account->getActiveCodecs().empty()) { + _warn ("UserAgent: Error: No active codec"); + pj_strdup2 (_pool, &reason, "no active codec"); + pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_NOT_ACCEPTABLE_HERE , + &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); + pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_METHOD_NOT_ALLOWED, + &reason, NULL, NULL); return true; } @@ -3684,12 +3629,12 @@ mod_on_rx_request (pjsip_rx_data *rdata) if (Manager::instance().hookPreference.getSipEnabled()) { - _debug("UserAgent: Set sip url hooks"); + _debug ("UserAgent: Set sip url hooks"); std::string header_value; - header_value = fetch_header_value (rdata->msg_info.msg, - Manager::instance().hookPreference.getUrlSipField()); + header_value = fetch_header_value (rdata->msg_info.msg, + Manager::instance().hookPreference.getUrlSipField()); if (header_value.size () < header_value.max_size()) { if (header_value!="") { @@ -3712,10 +3657,10 @@ mod_on_rx_request (pjsip_rx_data *rdata) // If an error occured at the call creation if (!call) { - _warn("UserAgent: Error: Unable to create an incoming call"); + _warn ("UserAgent: Error: Unable to create an incoming call"); pj_strdup2 (_pool, &reason, "unable to create an incoming call"); - pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, - &reason, NULL, NULL); + pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, + &reason, NULL, NULL); return false; } @@ -3727,17 +3672,17 @@ mod_on_rx_request (pjsip_rx_data *rdata) // May use the published address as well - addrToUse = SIPVoIPLink::instance("")->getInterfaceAddrFromName(account->getLocalInterface ()); + addrToUse = SIPVoIPLink::instance ("")->getInterfaceAddrFromName (account->getLocalInterface ()); account->isStunEnabled () ? addrSdp = account->getPublishedAddress () : addrSdp = addrToUse; // Set the appropriate transport to have the right VIA header link->init_transport_selector (account->getAccountTransport (), &tp); - if(account->getAccountTransport()) { + if (account->getAccountTransport()) { - _debug("UserAgent: SIP transport for this account: %s %s (refcnt=%i)", - account->getAccountTransport()->obj_name, - account->getAccountTransport()->info, - (int)pj_atomic_get(account->getAccountTransport()->ref_cnt)); + _debug ("UserAgent: SIP transport for this account: %s %s (refcnt=%i)", + account->getAccountTransport()->obj_name, + account->getAccountTransport()->info, + (int) pj_atomic_get (account->getAccountTransport()->ref_cnt)); } } @@ -3755,7 +3700,7 @@ mod_on_rx_request (pjsip_rx_data *rdata) call->setDisplayName (displayName); call->initRecFileName(); - _debug("UserAgent: DisplayName: %s", displayName.c_str()); + _debug ("UserAgent: DisplayName: %s", displayName.c_str()); // Have to do some stuff with the SDP @@ -3775,22 +3720,25 @@ mod_on_rx_request (pjsip_rx_data *rdata) status = call->getLocalSDP()->receiving_initial_offer (r_sdp, account->getActiveCodecs ()); if (status!=PJ_SUCCESS) { - delete call; call = NULL; - _warn("UserAgent: fail in receiving initial offer"); + delete call; + call = NULL; + _warn ("UserAgent: fail in receiving initial offer"); pj_strdup2 (_pool, &reason, "fail in receiving initial offer"); - pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, - &reason, NULL, NULL); + pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, + &reason, NULL, NULL); return false; } /* Create the local dialog (UAS) */ status = pjsip_dlg_create_uas (pjsip_ua_instance(), rdata, NULL, &dialog); + if (status != PJ_SUCCESS) { - delete call; call = NULL; - _warn("UserAgent: Error: Failed to create uas dialog"); + delete call; + call = NULL; + _warn ("UserAgent: Error: Failed to create uas dialog"); pj_strdup2 (_pool, &reason, "fail to create uas dialog"); - pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, - &reason, NULL, NULL); + pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, + &reason, NULL, NULL); return false; } @@ -3819,67 +3767,66 @@ mod_on_rx_request (pjsip_rx_data *rdata) call->setConnectionState (Call::Ringing); _debug ("UserAgent: Add call to account link"); + 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; - _warn ("UserAgent: Fail to notify UI!"); - pj_strdup2 (_pool, &reason, "fail to notify ui"); - pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, - &reason, NULL, NULL); - return false; - } + // Add this call to the callAccountMap in ManagerImpl + Manager::instance().getAccountLink (account_id)->addCall (call); + } else { + // Fail to notify UI + delete call; + call = NULL; + _warn ("UserAgent: Fail to notify UI!"); + pj_strdup2 (_pool, &reason, "fail to notify ui"); + pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, + &reason, NULL, NULL); + return false; + } /* Done */ return true; } -pj_bool_t mod_on_rx_response (pjsip_rx_data *rdata) -{ +pj_bool_t mod_on_rx_response (pjsip_rx_data *rdata) { _info ("UserAgent: Transaction response using transport: %s %s (refcnt=%d)", - rdata->tp_info.transport->obj_name, - rdata->tp_info.transport->info, - (int)pj_atomic_get(rdata->tp_info.transport->ref_cnt)); + rdata->tp_info.transport->obj_name, + rdata->tp_info.transport->info, + (int) pj_atomic_get (rdata->tp_info.transport->ref_cnt)); pjsip_dialog *dlg; - dlg = pjsip_rdata_get_dlg( rdata ); - - if(dlg != NULL) { - pjsip_transaction *tsx = pjsip_rdata_get_tsx( rdata ); - if ( tsx != NULL && tsx->method.id == PJSIP_INVITE_METHOD) { - if (tsx->status_code < 200) { - _info("UserAgent: Received provisional response"); - } - else if (tsx->status_code >= 300) { - _warn("UserAgent: Dialog failed"); - // pjsip_dlg_dec_session(dlg); - // ACK for non-2xx final response is sent by transaction. - } - else { - _info("UserAgent: Received 200 OK response"); - sendAck(dlg, rdata); - } - } - } + dlg = pjsip_rdata_get_dlg (rdata); + + if (dlg != NULL) { + pjsip_transaction *tsx = pjsip_rdata_get_tsx (rdata); + + if (tsx != NULL && tsx->method.id == PJSIP_INVITE_METHOD) { + if (tsx->status_code < 200) { + _info ("UserAgent: Received provisional response"); + } else if (tsx->status_code >= 300) { + _warn ("UserAgent: Dialog failed"); + // pjsip_dlg_dec_session(dlg); + // ACK for non-2xx final response is sent by transaction. + } else { + _info ("UserAgent: Received 200 OK response"); + sendAck (dlg, rdata); + } + } + } return PJ_SUCCESS; } -static void sendAck(pjsip_dialog *dlg, pjsip_rx_data *rdata) { +static void sendAck (pjsip_dialog *dlg, pjsip_rx_data *rdata) { - pjsip_tx_data *tdata; + pjsip_tx_data *tdata; - // Create ACK request - pjsip_dlg_create_request(dlg, &pjsip_ack_method, rdata->msg_info.cseq->cseq, &tdata); + // Create ACK request + pjsip_dlg_create_request (dlg, &pjsip_ack_method, rdata->msg_info.cseq->cseq, &tdata); - pjsip_dlg_send_request( dlg, tdata,-1, NULL); + pjsip_dlg_send_request (dlg, tdata,-1, NULL); } -void onCallTransfered (pjsip_inv_session *inv, pjsip_rx_data *rdata) -{ +void onCallTransfered (pjsip_inv_session *inv, pjsip_rx_data *rdata) { pj_status_t status; pjsip_tx_data *tdata; @@ -3924,7 +3871,7 @@ void onCallTransfered (pjsip_inv_session *inv, pjsip_rx_data *rdata) * request. */ ref_by_hdr = (pjsip_hdr*) - pjsip_msg_find_hdr_by_name (rdata->msg_info.msg, &str_ref_by, NULL); + pjsip_msg_find_hdr_by_name (rdata->msg_info.msg, &str_ref_by, NULL); /* Notify callback */ code = PJSIP_SC_ACCEPTED; @@ -4100,8 +4047,7 @@ void onCallTransfered (pjsip_inv_session *inv, pjsip_rx_data *rdata) -void xfer_func_cb (pjsip_evsub *sub, pjsip_event *event) -{ +void xfer_func_cb (pjsip_evsub *sub, pjsip_event *event) { PJ_UNUSED_ARG (event); @@ -4156,7 +4102,7 @@ void xfer_func_cb (pjsip_evsub *sub, pjsip_event *event) /* This better be a NOTIFY request */ if (r_data->msg_info.msg->line.req.method.id == PJSIP_OTHER_METHOD && - request.find(method_notify) != (size_t)-1) { + request.find (method_notify) != (size_t)-1) { /* Check if there's body */ msg = r_data->msg_info.msg; @@ -4189,8 +4135,8 @@ void xfer_func_cb (pjsip_evsub *sub, pjsip_event *event) } // Get call coresponding to this transaction - std::string transferID(r_data->msg_info.cid->id.ptr, r_data->msg_info.cid->id.slen); - std::map<std::string, CallID>::iterator it = transferCallID.find(transferID); + std::string transferID (r_data->msg_info.cid->id.ptr, r_data->msg_info.cid->id.slen); + std::map<std::string, CallID>::iterator it = transferCallID.find (transferID); CallID cid = it->second; SIPCall *call = dynamic_cast<SIPCall *> (link->getCall (cid)); @@ -4205,10 +4151,11 @@ void xfer_func_cb (pjsip_evsub *sub, pjsip_event *event) cont = !is_last; - _debug("UserAgent: Notification status line: %d", status_line.code); + _debug ("UserAgent: Notification status line: %d", status_line.code); + if (status_line.code/100 == 2) { - _debug ("UserAgent: Received 200 OK on call transfered, stop call!"); + _debug ("UserAgent: Received 200 OK on call transfered, stop call!"); pjsip_tx_data *tdata; status = pjsip_inv_end_session (call->getInvSession(), PJSIP_SC_GONE, NULL, &tdata); @@ -4236,8 +4183,7 @@ void xfer_func_cb (pjsip_evsub *sub, pjsip_event *event) } -void xfer_svr_cb (pjsip_evsub *sub, pjsip_event *event) -{ +void xfer_svr_cb (pjsip_evsub *sub, pjsip_event *event) { PJ_UNUSED_ARG (event); @@ -4263,9 +4209,8 @@ void xfer_svr_cb (pjsip_evsub *sub, pjsip_event *event) } } -void on_rx_offer (pjsip_inv_session *inv, const pjmedia_sdp_session *offer) -{ - _info("UserAgent: Received SDP offer"); +void on_rx_offer (pjsip_inv_session *inv, const pjmedia_sdp_session *offer) { + _info ("UserAgent: Received SDP offer"); #ifdef CAN_REINVITE @@ -4296,52 +4241,50 @@ void on_rx_offer (pjsip_inv_session *inv, const pjmedia_sdp_session *offer) } -void on_create_offer(pjsip_inv_session *inv, pjmedia_sdp_session **p_offer) -{ - _info("UserAgent: Create new SDP offer"); +void on_create_offer (pjsip_inv_session *inv, pjmedia_sdp_session **p_offer) { + _info ("UserAgent: Create new SDP offer"); - /* Retrieve the call information */ - SIPCall * call = NULL; - call = reinterpret_cast<SIPCall*> (inv->mod_data[_mod_ua.id]); + /* Retrieve the call information */ + SIPCall * call = NULL; + call = reinterpret_cast<SIPCall*> (inv->mod_data[_mod_ua.id]); - CallID callid = call->getCallId(); - AccountID accountid = Manager::instance().getAccountFromCall(callid); + CallID callid = call->getCallId(); + AccountID accountid = Manager::instance().getAccountFromCall (callid); - SIPAccount *account = dynamic_cast<SIPAccount *>(Manager::instance().getAccount(accountid)); + SIPAccount *account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (accountid)); SIPVoIPLink *link = dynamic_cast<SIPVoIPLink *> (Manager::instance().getAccountLink (accountid)); - // Set the local address - std::string localAddress = link->getInterfaceAddrFromName(account->getLocalInterface ()); - // Set SDP parameters - Set to local - std::string addrSdp = localAddress; + // Set the local address + std::string localAddress = link->getInterfaceAddrFromName (account->getLocalInterface ()); + // Set SDP parameters - Set to local + std::string addrSdp = localAddress; - _debug ("UserAgent: Local Address for IP2IP call: %s", localAddress.c_str()); + _debug ("UserAgent: Local Address for IP2IP call: %s", localAddress.c_str()); - // If local address bound to ANY, reslove it using PJSIP - if (localAddress == "0.0.0.0") { - link->loadSIPLocalIP (&localAddress); - } + // If local address bound to ANY, reslove it using PJSIP + if (localAddress == "0.0.0.0") { + link->loadSIPLocalIP (&localAddress); + } - // Local address to appear in SDP - if (addrSdp == "0.0.0.0") { - addrSdp = localAddress; - } + // Local address to appear in SDP + if (addrSdp == "0.0.0.0") { + addrSdp = localAddress; + } // Set local address for RTP media setCallAudioLocal (call, localAddress); // Building the local SDP offer call->getLocalSDP()->set_ip_address (addrSdp); - call->getLocalSDP()->create_initial_offer( account->getActiveCodecs() ); + call->getLocalSDP()->create_initial_offer (account->getActiveCodecs()); *p_offer = call->getLocalSDP()->get_local_sdp_session(); } -void handle_incoming_options (pjsip_rx_data *rdata) -{ +void handle_incoming_options (pjsip_rx_data *rdata) { pjsip_tx_data *tdata; @@ -4389,7 +4332,7 @@ void handle_incoming_options (pjsip_rx_data *rdata) status = pjsip_endpt_send_response (_endpt, &res_addr, tdata, NULL, NULL); - + if (status != PJ_SUCCESS) pjsip_tx_data_dec_ref (tdata); } @@ -4397,8 +4340,7 @@ void handle_incoming_options (pjsip_rx_data *rdata) /*****************************************************************************************************************/ -bool setCallAudioLocal (SIPCall* call, std::string localIP) -{ +bool setCallAudioLocal (SIPCall* call, std::string localIP) { SIPAccount *account = NULL; if (call) { @@ -4432,8 +4374,7 @@ bool setCallAudioLocal (SIPCall* call, std::string localIP) return false; } -std::string fetch_header_value (pjsip_msg *msg, std::string field) -{ +std::string fetch_header_value (pjsip_msg *msg, std::string field) { pj_str_t name; @@ -4463,8 +4404,7 @@ std::string fetch_header_value (pjsip_msg *msg, std::string field) return url; } -std::vector<std::string> SIPVoIPLink::getAllIpInterface (void) -{ +std::vector<std::string> SIPVoIPLink::getAllIpInterface (void) { pj_sockaddr addrList[16]; unsigned int addrCnt = PJ_ARRAY_SIZE (addrList); @@ -4492,70 +4432,66 @@ std::vector<std::string> SIPVoIPLink::getAllIpInterface (void) } -int get_iface_list(struct ifconf *ifconf) -{ - int sock, rval; +int get_iface_list (struct ifconf *ifconf) { + int sock, rval; - if((sock = socket(AF_INET,SOCK_STREAM,0)) < 0) - _debug("get_iface_list error could not open socket\n"); + if ( (sock = socket (AF_INET,SOCK_STREAM,0)) < 0) + _debug ("get_iface_list error could not open socket\n"); - if((rval = ioctl(sock, SIOCGIFCONF , (char*) ifconf )) < 0 ) - _debug("get_iface_list error ioctl(SIOGIFCONF)\n"); + if ( (rval = ioctl (sock, SIOCGIFCONF , (char*) ifconf)) < 0) + _debug ("get_iface_list error ioctl(SIOGIFCONF)\n"); - close(sock); + close (sock); - return rval; + return rval; } -std::vector<std::string> SIPVoIPLink::getAllIpInterfaceByName(void) -{ +std::vector<std::string> SIPVoIPLink::getAllIpInterfaceByName (void) { std::vector<std::string> ifaceList; static struct ifreq ifreqs[20]; struct ifconf ifconf; int nifaces; - // add the default - ifaceList.push_back(std::string("default")); + // add the default + ifaceList.push_back (std::string ("default")); - memset(&ifconf,0,sizeof(ifconf)); + memset (&ifconf,0,sizeof (ifconf)); ifconf.ifc_buf = (char*) (ifreqs); - ifconf.ifc_len = sizeof(ifreqs); + ifconf.ifc_len = sizeof (ifreqs); - if(get_iface_list(&ifconf) < 0) - _debug("getAllIpInterfaceByName error could not get interface list\n"); + if (get_iface_list (&ifconf) < 0) + _debug ("getAllIpInterfaceByName error could not get interface list\n"); - nifaces = ifconf.ifc_len/sizeof(struct ifreq); + nifaces = ifconf.ifc_len/sizeof (struct ifreq); - _debug("Interfaces (count = %d):\n", nifaces); - for(int i = 0; i < nifaces; i++) { - _debug(" %s ", ifreqs[i].ifr_name); - ifaceList.push_back(std::string (ifreqs[i].ifr_name)); - printf(" %s\n", getInterfaceAddrFromName(std::string (ifreqs[i].ifr_name)).c_str()); + _debug ("Interfaces (count = %d):\n", nifaces); + + for (int i = 0; i < nifaces; i++) { + _debug (" %s ", ifreqs[i].ifr_name); + ifaceList.push_back (std::string (ifreqs[i].ifr_name)); + printf (" %s\n", getInterfaceAddrFromName (std::string (ifreqs[i].ifr_name)).c_str()); } - return ifaceList; + return ifaceList; } -pj_bool_t stun_sock_on_status (pj_stun_sock *stun_sock, pj_stun_sock_op op, pj_status_t status) -{ +pj_bool_t stun_sock_on_status (pj_stun_sock *stun_sock, pj_stun_sock_op op, pj_status_t status) { if (status == PJ_SUCCESS) return PJ_TRUE; else return PJ_FALSE; } -pj_bool_t stun_sock_on_rx_data (pj_stun_sock *stun_sock, void *pkt, unsigned pkt_len, const pj_sockaddr_t *src_addr, unsigned addr_len) -{ +pj_bool_t stun_sock_on_rx_data (pj_stun_sock *stun_sock, void *pkt, unsigned pkt_len, const pj_sockaddr_t *src_addr, unsigned addr_len) { return PJ_TRUE; } -std::string getLocalAddressAssociatedToAccount (AccountID id) -{ +std::string getLocalAddressAssociatedToAccount (AccountID id) { SIPAccount *account = NULL; pj_sockaddr_in local_addr_ipv4; pjsip_transport *tspt; diff --git a/sflphone-common/src/voiplink.cpp b/sflphone-common/src/voiplink.cpp index 8d2dc014bc9ea56143205dbba9074139ac3a2063..1bc19316a72763da039627c7382562615d580327 100644 --- a/sflphone-common/src/voiplink.cpp +++ b/sflphone-common/src/voiplink.cpp @@ -35,17 +35,14 @@ #include "voiplink.h" #include "manager.h" -VoIPLink::VoIPLink (const AccountID& accountID) : _accountID (accountID), _localPort (0), _initDone (false) -{ +VoIPLink::VoIPLink (const AccountID& accountID) : _accountID (accountID), _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); @@ -56,8 +53,7 @@ bool VoIPLink::addCall (Call* call) return false; } -bool VoIPLink::removeCall (const CallID& id) -{ +bool VoIPLink::removeCall (const CallID& id) { ost::MutexLock m (_callMapMutex); if (_callMap.erase (id)) { @@ -67,8 +63,7 @@ bool VoIPLink::removeCall (const CallID& id) return false; } -Call* VoIPLink::getCall (const CallID& id) -{ +Call* VoIPLink::getCall (const CallID& id) { ost::MutexLock m (_callMapMutex); CallMap::iterator iter = _callMap.find (id); @@ -79,8 +74,7 @@ Call* VoIPLink::getCall (const CallID& id) return NULL; } -bool VoIPLink::clearCallMap() -{ +bool VoIPLink::clearCallMap() { ost::MutexLock m (_callMapMutex); CallMap::iterator iter = _callMap.begin(); @@ -96,8 +90,7 @@ bool VoIPLink::clearCallMap() return true; } -Account* VoIPLink::getAccountPtr (void) -{ +Account* VoIPLink::getAccountPtr (void) { AccountID id; id = getAccountID(); diff --git a/sflphone-common/test/accounttest.cpp b/sflphone-common/test/accounttest.cpp index dc905e9a8c040aac9bee05f3edca3a723159fa72..457596b98b672948c37b6ea327fa7e5d96b54e41 100644 --- a/sflphone-common/test/accounttest.cpp +++ b/sflphone-common/test/accounttest.cpp @@ -35,18 +35,18 @@ #include "logger.h" #include "validator.h" -void AccountTest::TestAddRemove(void) { - _debug ("-------------------- AccountTest::TestAddRemove --------------------\n"); +void AccountTest::TestAddRemove (void) { + _debug ("-------------------- AccountTest::TestAddRemove --------------------\n"); - std::map<std::string, std::string> details; - details[CONFIG_ACCOUNT_TYPE] = "SIP"; - details[CONFIG_ACCOUNT_ENABLE] = "false"; + std::map<std::string, std::string> details; + details[CONFIG_ACCOUNT_TYPE] = "SIP"; + details[CONFIG_ACCOUNT_ENABLE] = "false"; - std::string accountId = Manager::instance().addAccount(details); - CPPUNIT_ASSERT(Validator::isNotNull(accountId)); - CPPUNIT_ASSERT(Manager::instance().accountExists(accountId)); + std::string accountId = Manager::instance().addAccount (details); + CPPUNIT_ASSERT (Validator::isNotNull (accountId)); + CPPUNIT_ASSERT (Manager::instance().accountExists (accountId)); - Manager::instance().removeAccount(accountId); + Manager::instance().removeAccount (accountId); - CPPUNIT_ASSERT(!Manager::instance().accountExists(accountId)); + CPPUNIT_ASSERT (!Manager::instance().accountExists (accountId)); } diff --git a/sflphone-common/test/audiolayertest.cpp b/sflphone-common/test/audiolayertest.cpp index 7119cae3b1d2ab37629d3bf6b44a490c2b1cb025..4271ad5fa19bf81241ba894ba27697b442eac3c0 100644 --- a/sflphone-common/test/audiolayertest.cpp +++ b/sflphone-common/test/audiolayertest.cpp @@ -39,106 +39,106 @@ using std::cout; using std::endl; void AudioLayerTest::testAudioLayerConfig() { - _debug ("-------------------- AudioLayerTest::testAudioLayerConfig --------------------\n"); + _debug ("-------------------- AudioLayerTest::testAudioLayerConfig --------------------\n"); - // int sampling_rate = Manager::instance().audioPreference.getSmplrate(); - // int frame_size = Manager::instance().audioPreference.getFramesize(); + // int sampling_rate = Manager::instance().audioPreference.getSmplrate(); + // int frame_size = Manager::instance().audioPreference.getFramesize(); - // int layer = Manager::instance().getAudioDriver()->getLayerType(); + // int layer = Manager::instance().getAudioDriver()->getLayerType(); - // if (layer != ALSA) - // Manager::instance().switchAudioManager(); + // if (layer != ALSA) + // Manager::instance().switchAudioManager(); - // TODO: Fix tests - //CPPUNIT_ASSERT ( (int) Manager::instance().getAudioDriver()->getSampleRate() == sampling_rate); + // TODO: Fix tests + //CPPUNIT_ASSERT ( (int) Manager::instance().getAudioDriver()->getSampleRate() == sampling_rate); - //CPPPUNIT_ASSERT ( (int) Manager::instance().getAudioDriver()->getFrameSize() == frame_size); + //CPPPUNIT_ASSERT ( (int) Manager::instance().getAudioDriver()->getFrameSize() == frame_size); } void AudioLayerTest::testAudioLayerSwitch() { - _debug ("-------------------- AudioLayerTest::testAudioLayerSwitch --------------------\n"); + _debug ("-------------------- AudioLayerTest::testAudioLayerSwitch --------------------\n"); - int previous_layer = Manager::instance().getAudioDriver()->getLayerType(); + int previous_layer = Manager::instance().getAudioDriver()->getLayerType(); - for (int i = 0; i < 2; i++) { - _debug ("iter - %i",i); - Manager::instance().switchAudioManager(); + for (int i = 0; i < 2; i++) { + _debug ("iter - %i",i); + Manager::instance().switchAudioManager(); - if (previous_layer == ALSA) { - CPPUNIT_ASSERT (Manager::instance().getAudioDriver()->getLayerType() == PULSEAUDIO); - } else { - CPPUNIT_ASSERT (Manager::instance().getAudioDriver()->getLayerType() == ALSA); - } + 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(); + previous_layer = Manager::instance().getAudioDriver()->getLayerType(); - usleep(100000); - } + usleep (100000); + } } void AudioLayerTest::testPulseConnect() { - _debug ("-------------------- AudioLayerTest::testPulseConnect --------------------\n"); + _debug ("-------------------- AudioLayerTest::testPulseConnect --------------------\n"); - if (Manager::instance().getAudioDriver()->getLayerType() == ALSA) - return; + if (Manager::instance().getAudioDriver()->getLayerType() == ALSA) + return; - ManagerImpl* manager; - manager = &Manager::instance(); + ManagerImpl* manager; + manager = &Manager::instance(); - _pulselayer = (PulseLayer*) Manager::instance().getAudioDriver(); + _pulselayer = (PulseLayer*) Manager::instance().getAudioDriver(); - CPPUNIT_ASSERT (_pulselayer->getLayerType() == PULSEAUDIO); + CPPUNIT_ASSERT (_pulselayer->getLayerType() == PULSEAUDIO); - std::string alsaPlugin; - int numCardIn, numCardOut, numCardRing, sampleRate, frameSize; + std::string alsaPlugin; + int numCardIn, numCardOut, numCardRing, sampleRate, frameSize; - alsaPlugin = manager->audioPreference.getPlugin(); - numCardIn = manager->audioPreference.getCardin(); - numCardOut = manager->audioPreference.getCardout(); - numCardRing = manager->audioPreference.getCardring(); - sampleRate = manager->audioPreference.getSmplrate(); - frameSize = manager->audioPreference.getFramesize(); + alsaPlugin = manager->audioPreference.getPlugin(); + numCardIn = manager->audioPreference.getCardin(); + numCardOut = manager->audioPreference.getCardout(); + numCardRing = manager->audioPreference.getCardring(); + sampleRate = manager->audioPreference.getSmplrate(); + frameSize = manager->audioPreference.getFramesize(); - CPPUNIT_ASSERT (_pulselayer->getPlaybackStream() == NULL); - CPPUNIT_ASSERT (_pulselayer->getRecordStream() == NULL); + CPPUNIT_ASSERT (_pulselayer->getPlaybackStream() == NULL); + CPPUNIT_ASSERT (_pulselayer->getRecordStream() == NULL); - _pulselayer->setErrorMessage(-1); + _pulselayer->setErrorMessage (-1); - try { - CPPUNIT_ASSERT (_pulselayer->openDevice (numCardIn, numCardOut, numCardRing, sampleRate, frameSize, SFL_PCM_BOTH, alsaPlugin) == true); - } catch (...) { - _debug ("Exception occured wile opening device! "); - } + try { + CPPUNIT_ASSERT (_pulselayer->openDevice (numCardIn, numCardOut, numCardRing, sampleRate, frameSize, SFL_PCM_BOTH, alsaPlugin) == true); + } catch (...) { + _debug ("Exception occured wile opening device! "); + } - usleep(100000); + usleep (100000); - CPPUNIT_ASSERT (_pulselayer->getPlaybackStream() == NULL); - CPPUNIT_ASSERT (_pulselayer->getRecordStream() == NULL); + CPPUNIT_ASSERT (_pulselayer->getPlaybackStream() == NULL); + CPPUNIT_ASSERT (_pulselayer->getRecordStream() == NULL); - _debug ("-------------------------- \n"); - _pulselayer->startStream(); + _debug ("-------------------------- \n"); + _pulselayer->startStream(); - 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); - CPPUNIT_ASSERT (_pulselayer->getPlaybackStream()->connectStream(NULL) == true); - CPPUNIT_ASSERT (_pulselayer->getRecordStream()->connectStream(NULL) == true); + CPPUNIT_ASSERT (_pulselayer->getPlaybackStream()->connectStream (NULL) == true); + CPPUNIT_ASSERT (_pulselayer->getRecordStream()->connectStream (NULL) == 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(NULL) == true); - CPPUNIT_ASSERT (_pulselayer->getRecordStream()->connectStream(NULL) == true); + CPPUNIT_ASSERT (_pulselayer->getPlaybackStream()->connectStream (NULL) == true); + CPPUNIT_ASSERT (_pulselayer->getRecordStream()->connectStream (NULL) == 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->disconnectAudioStream() == true); + CPPUNIT_ASSERT (_pulselayer->disconnectAudioStream() == true); } diff --git a/sflphone-common/test/configurationtest.cpp b/sflphone-common/test/configurationtest.cpp old mode 100755 new mode 100644 index 57a5e27f2c71b357201dbafefe39fe83839e03d2..7519961f97e521dd6a4990cfc4dd8adea8bbc3ad --- a/sflphone-common/test/configurationtest.cpp +++ b/sflphone-common/test/configurationtest.cpp @@ -38,247 +38,244 @@ using std::cout; using std::endl; void ConfigurationTest::testDefaultValueAudio() { - _debug ("-------------------- ConfigurationTest::testDefaultValueAudio() --------------------\n"); - - CPPUNIT_ASSERT (Manager::instance().audioPreference.getCardin() == 0); // ALSA_DFT_CARD); - CPPUNIT_ASSERT (Manager::instance().audioPreference.getCardout() == 0); // ALSA_DFT_CARD); - CPPUNIT_ASSERT (Manager::instance().audioPreference.getSmplrate() == 44100); // DFT_SAMPLE_RATE); - CPPUNIT_ASSERT (Manager::instance().audioPreference.getFramesize() == 20); // DFT_FRAME_SIZE); - CPPUNIT_ASSERT (Manager::instance().audioPreference.getPlugin() == PCM_DEFAULT); - CPPUNIT_ASSERT (Manager::instance().audioPreference.getVolumespkr() == 100); - CPPUNIT_ASSERT (Manager::instance().audioPreference.getVolumemic() == 100); + _debug ("-------------------- ConfigurationTest::testDefaultValueAudio() --------------------\n"); + + CPPUNIT_ASSERT (Manager::instance().audioPreference.getCardin() == 0); // ALSA_DFT_CARD); + CPPUNIT_ASSERT (Manager::instance().audioPreference.getCardout() == 0); // ALSA_DFT_CARD); + CPPUNIT_ASSERT (Manager::instance().audioPreference.getSmplrate() == 44100); // DFT_SAMPLE_RATE); + CPPUNIT_ASSERT (Manager::instance().audioPreference.getFramesize() == 20); // DFT_FRAME_SIZE); + CPPUNIT_ASSERT (Manager::instance().audioPreference.getPlugin() == PCM_DEFAULT); + CPPUNIT_ASSERT (Manager::instance().audioPreference.getVolumespkr() == 100); + CPPUNIT_ASSERT (Manager::instance().audioPreference.getVolumemic() == 100); } void ConfigurationTest::testDefaultValuePreferences() { - _debug ("-------------------- ConfigurationTest::testDefaultValuePreferences --------------------\n"); + _debug ("-------------------- ConfigurationTest::testDefaultValuePreferences --------------------\n"); - CPPUNIT_ASSERT (Manager::instance().preferences.getZoneToneChoice() == DFT_ZONE); + CPPUNIT_ASSERT (Manager::instance().preferences.getZoneToneChoice() == DFT_ZONE); } void ConfigurationTest::testDefaultValueSignalisation() { - _debug ("-------------------- ConfigurationTest::testDefaultValueSignalisation --------------------\n"); + _debug ("-------------------- ConfigurationTest::testDefaultValueSignalisation --------------------\n"); - CPPUNIT_ASSERT (Manager::instance().voipPreferences.getSymmetricRtp() == true); - CPPUNIT_ASSERT (Manager::instance().voipPreferences.getPlayDtmf() == true); - CPPUNIT_ASSERT (Manager::instance().voipPreferences.getPlayTones() == true); - CPPUNIT_ASSERT (Manager::instance().voipPreferences.getPulseLength() == 250); - CPPUNIT_ASSERT (Manager::instance().voipPreferences.getSendDtmfAs() == 0); + CPPUNIT_ASSERT (Manager::instance().voipPreferences.getSymmetricRtp() == true); + CPPUNIT_ASSERT (Manager::instance().voipPreferences.getPlayDtmf() == true); + CPPUNIT_ASSERT (Manager::instance().voipPreferences.getPlayTones() == true); + CPPUNIT_ASSERT (Manager::instance().voipPreferences.getPulseLength() == 250); + CPPUNIT_ASSERT (Manager::instance().voipPreferences.getSendDtmfAs() == 0); } void ConfigurationTest::testLoadSIPAccount() { - _debug ("-------------------- ConfigurationTest::testLoadSIPAccount --------------------\n"); - - AccountMap accounts; - Account *current; - std::ostringstream ss; - int nb_account; // Must be 1 - - // Load the account from the user file - nb_account = Manager::instance().loadAccountMap(); - 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()) { - current = iter->second; - CPPUNIT_ASSERT (iter->first == current->getAccountID()); - CPPUNIT_ASSERT (0 == current->getVoIPLink()); - iter++; - } + _debug ("-------------------- ConfigurationTest::testLoadSIPAccount --------------------\n"); + + AccountMap accounts; + Account *current; + std::ostringstream ss; + int nb_account; // Must be 1 + + // Load the account from the user file + nb_account = Manager::instance().loadAccountMap(); + 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()) { + current = iter->second; + CPPUNIT_ASSERT (iter->first == current->getAccountID()); + CPPUNIT_ASSERT (0 == current->getVoIPLink()); + iter++; + } } void ConfigurationTest::testUnloadSIPAccount() { - _debug ("-------------------- ConfigurationTest::testUnloadSIPAccount --------------------\n"); + _debug ("-------------------- ConfigurationTest::testUnloadSIPAccount --------------------\n"); - AccountMap accounts; + AccountMap accounts; - // Load the accounts from the user file - Manager::instance().loadAccountMap(); - // Unload the accounts - Manager::instance().unloadAccountMap(); - // Save the account information - accounts = Manager::instance()._accountMap; + // Load the accounts from the user file + 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); + AccountMap::iterator iter = accounts.begin(); + CPPUNIT_ASSERT (Manager::instance().accountExists (iter->first) == false); - if (iter != accounts.end()) { - CPPUNIT_FAIL ("Unload account map failed\n"); - } + if (iter != accounts.end()) { + CPPUNIT_FAIL ("Unload account map failed\n"); + } } void ConfigurationTest::testInitVolume() { - _debug ("-------------------- ConfigurationTest::testInitVolume --------------------\n"); + _debug ("-------------------- ConfigurationTest::testInitVolume --------------------\n"); - Manager::instance().initVolume(); - - CPPUNIT_ASSERT (Manager::instance().audioPreference.getVolumespkr() == Manager::instance().getSpkrVolume()); - CPPUNIT_ASSERT (Manager::instance().audioPreference.getVolumemic() == Manager::instance().getMicVolume()); + Manager::instance().initVolume(); + + CPPUNIT_ASSERT (Manager::instance().audioPreference.getVolumespkr() == Manager::instance().getSpkrVolume()); + CPPUNIT_ASSERT (Manager::instance().audioPreference.getVolumemic() == Manager::instance().getMicVolume()); } void ConfigurationTest::testInitAudioDriver() { - _debug ("-------------------- ConfigurationTest::testInitAudioDriver --------------------\n"); + _debug ("-------------------- ConfigurationTest::testInitAudioDriver --------------------\n"); - // Load the audio driver - Manager::instance().initAudioDriver(); + // Load the audio driver + Manager::instance().initAudioDriver(); - // Check the creation + // 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().preferences.getAudioApi() == ALSA) - CPPUNIT_ASSERT_EQUAL (Manager::instance().getAudioDriver()->getLayerType(), ALSA); - else if (Manager::instance().preferences.getAudioApi() == PULSEAUDIO) - CPPUNIT_ASSERT_EQUAL (Manager::instance().getAudioDriver()->getLayerType(), PULSEAUDIO); - else - CPPUNIT_FAIL ("Wrong audio layer type"); + // Check if it has been created with the right type + if (Manager::instance().preferences.getAudioApi() == ALSA) + CPPUNIT_ASSERT_EQUAL (Manager::instance().getAudioDriver()->getLayerType(), ALSA); + else if (Manager::instance().preferences.getAudioApi() == PULSEAUDIO) + CPPUNIT_ASSERT_EQUAL (Manager::instance().getAudioDriver()->getLayerType(), PULSEAUDIO); + else + CPPUNIT_FAIL ("Wrong audio layer type"); } -void ConfigurationTest::testYamlParser() -{ +void ConfigurationTest::testYamlParser() { + + Conf::YamlParser *parser; + + try { + + parser = new Conf::YamlParser ("sequence2.yml"); + + parser->serializeEvents(); - Conf::YamlParser *parser; - try { + parser->composeEvents(); - parser = new Conf::YamlParser("sequence2.yml"); - - parser->serializeEvents(); + parser->constructNativeData(); - parser->composeEvents(); + delete parser; + parser = NULL; - parser->constructNativeData(); - - delete parser; - parser = NULL; + } catch (Conf::YamlParserException &e) { + _error ("ConfigTree: %s", e.what()); + } - } - catch (Conf::YamlParserException &e) { - _error("ConfigTree: %s", e.what()); - } - } -void ConfigurationTest::testYamlEmitter() -{ - Conf::YamlEmitter *emitter; - - Conf::MappingNode accountmap(NULL); - Conf::MappingNode credentialmap(NULL); - Conf::MappingNode srtpmap(NULL); - Conf::MappingNode zrtpmap(NULL); - Conf::MappingNode tlsmap(NULL); - - - Conf::ScalarNode id("Account:1278432417"); - Conf::ScalarNode username("181"); - Conf::ScalarNode password("pass181"); - Conf::ScalarNode alias("sfl-181"); - Conf::ScalarNode hostname("192.168.50.3"); - Conf::ScalarNode enable("true"); - Conf::ScalarNode type("SIP"); - Conf::ScalarNode expire("3600"); - Conf::ScalarNode interface("default"); - Conf::ScalarNode port("5060"); - Conf::ScalarNode mailbox("97"); - Conf::ScalarNode publishAddr("192.168.50.182"); - Conf::ScalarNode publishPort("5060"); - Conf::ScalarNode sameasLocal("true"); - Conf::ScalarNode resolveOnce("false"); - Conf::ScalarNode codecs("0/9/110/111/112/"); - Conf::ScalarNode stunServer("stun.sflphone.org"); - Conf::ScalarNode stunEnabled("false"); - Conf::ScalarNode displayName("Alexandre Savard"); - Conf::ScalarNode dtmfType("sipinfo"); - - Conf::ScalarNode count("0"); - - Conf::ScalarNode srtpenabled("false"); - Conf::ScalarNode keyExchange("sdes"); - Conf::ScalarNode rtpFallback("false"); - - Conf::ScalarNode displaySas("false"); - Conf::ScalarNode displaySasOnce("false"); - Conf::ScalarNode helloHashEnabled("false"); - Conf::ScalarNode notSuppWarning("false"); - - Conf::ScalarNode tlsport(""); - Conf::ScalarNode certificate(""); - Conf::ScalarNode calist(""); - Conf::ScalarNode ciphers(""); - Conf::ScalarNode tlsenabled("false"); - Conf::ScalarNode tlsmethod("TLSV1"); - Conf::ScalarNode timeout("0"); - Conf::ScalarNode tlspassword(""); - Conf::ScalarNode privatekey(""); - Conf::ScalarNode requirecertif("true"); - Conf::ScalarNode server(""); - Conf::ScalarNode verifyclient("true"); - Conf::ScalarNode verifyserver("true"); - - accountmap.setKeyValue(aliasKey, &alias); - accountmap.setKeyValue(typeKey, &type); - accountmap.setKeyValue(idKey, &id); - accountmap.setKeyValue(usernameKey, &username); - accountmap.setKeyValue(passwordKey, &password); - accountmap.setKeyValue(hostnameKey, &hostname); - accountmap.setKeyValue(accountEnableKey, &enable); - accountmap.setKeyValue(mailboxKey, &mailbox); - accountmap.setKeyValue(expireKey, &expire); - accountmap.setKeyValue(interfaceKey, &interface); - accountmap.setKeyValue(portKey, &port); - accountmap.setKeyValue(publishAddrKey, &publishAddr); - accountmap.setKeyValue(publishPortKey, &publishPort); - accountmap.setKeyValue(sameasLocalKey, &sameasLocal); - accountmap.setKeyValue(resolveOnceKey, &resolveOnce); - accountmap.setKeyValue(dtmfTypeKey, &dtmfType); - accountmap.setKeyValue(displayNameKey, &displayName); - - accountmap.setKeyValue(srtpKey, &srtpmap); - srtpmap.setKeyValue(srtpEnableKey, &srtpenabled); - srtpmap.setKeyValue(keyExchangeKey, &keyExchange); - srtpmap.setKeyValue(rtpFallbackKey, &rtpFallback); - - accountmap.setKeyValue(zrtpKey, &zrtpmap); - zrtpmap.setKeyValue(displaySasKey, &displaySas); - zrtpmap.setKeyValue(displaySasOnceKey, &displaySasOnce); - zrtpmap.setKeyValue(helloHashEnabledKey, &helloHashEnabled); - zrtpmap.setKeyValue(notSuppWarningKey, ¬SuppWarning); - - accountmap.setKeyValue(credKey, &credentialmap); - credentialmap.setKeyValue(credentialCountKey, &count); - - accountmap.setKeyValue(tlsKey, &tlsmap); - tlsmap.setKeyValue(tlsPortKey, &tlsport); - tlsmap.setKeyValue(certificateKey, &certificate); - tlsmap.setKeyValue(calistKey, &calist); - tlsmap.setKeyValue(ciphersKey, &ciphers); - tlsmap.setKeyValue(tlsEnableKey, &tlsenabled); - tlsmap.setKeyValue(methodKey, &tlsmethod); - tlsmap.setKeyValue(timeoutKey, &timeout); - tlsmap.setKeyValue(tlsPasswordKey, &tlspassword); - tlsmap.setKeyValue(privateKeyKey, &privatekey); - tlsmap.setKeyValue(requireCertifKey, &requirecertif); - tlsmap.setKeyValue(serverKey, &server); - tlsmap.setKeyValue(verifyClientKey, &verifyclient); - tlsmap.setKeyValue(verifyServerKey, &verifyserver); - - try{ - emitter = new Conf::YamlEmitter("/tmp/sequenceEmiter.txt"); - - emitter->serializeAccount(&accountmap); - emitter->serializeAccount(&accountmap); - emitter->serializeData(); - - delete emitter; - } - catch (Conf::YamlEmitterException &e) { - _error("ConfigTree: %s", e.what()); - } +void ConfigurationTest::testYamlEmitter() { + Conf::YamlEmitter *emitter; + + Conf::MappingNode accountmap (NULL); + Conf::MappingNode credentialmap (NULL); + Conf::MappingNode srtpmap (NULL); + Conf::MappingNode zrtpmap (NULL); + Conf::MappingNode tlsmap (NULL); + + + Conf::ScalarNode id ("Account:1278432417"); + Conf::ScalarNode username ("181"); + Conf::ScalarNode password ("pass181"); + Conf::ScalarNode alias ("sfl-181"); + Conf::ScalarNode hostname ("192.168.50.3"); + Conf::ScalarNode enable ("true"); + Conf::ScalarNode type ("SIP"); + Conf::ScalarNode expire ("3600"); + Conf::ScalarNode interface ("default"); + Conf::ScalarNode port ("5060"); + Conf::ScalarNode mailbox ("97"); + Conf::ScalarNode publishAddr ("192.168.50.182"); + Conf::ScalarNode publishPort ("5060"); + Conf::ScalarNode sameasLocal ("true"); + Conf::ScalarNode resolveOnce ("false"); + Conf::ScalarNode codecs ("0/9/110/111/112/"); + Conf::ScalarNode stunServer ("stun.sflphone.org"); + Conf::ScalarNode stunEnabled ("false"); + Conf::ScalarNode displayName ("Alexandre Savard"); + Conf::ScalarNode dtmfType ("sipinfo"); + + Conf::ScalarNode count ("0"); + + Conf::ScalarNode srtpenabled ("false"); + Conf::ScalarNode keyExchange ("sdes"); + Conf::ScalarNode rtpFallback ("false"); + + Conf::ScalarNode displaySas ("false"); + Conf::ScalarNode displaySasOnce ("false"); + Conf::ScalarNode helloHashEnabled ("false"); + Conf::ScalarNode notSuppWarning ("false"); + + Conf::ScalarNode tlsport (""); + Conf::ScalarNode certificate (""); + Conf::ScalarNode calist (""); + Conf::ScalarNode ciphers (""); + Conf::ScalarNode tlsenabled ("false"); + Conf::ScalarNode tlsmethod ("TLSV1"); + Conf::ScalarNode timeout ("0"); + Conf::ScalarNode tlspassword (""); + Conf::ScalarNode privatekey (""); + Conf::ScalarNode requirecertif ("true"); + Conf::ScalarNode server (""); + Conf::ScalarNode verifyclient ("true"); + Conf::ScalarNode verifyserver ("true"); + + accountmap.setKeyValue (aliasKey, &alias); + accountmap.setKeyValue (typeKey, &type); + accountmap.setKeyValue (idKey, &id); + accountmap.setKeyValue (usernameKey, &username); + accountmap.setKeyValue (passwordKey, &password); + accountmap.setKeyValue (hostnameKey, &hostname); + accountmap.setKeyValue (accountEnableKey, &enable); + accountmap.setKeyValue (mailboxKey, &mailbox); + accountmap.setKeyValue (expireKey, &expire); + accountmap.setKeyValue (interfaceKey, &interface); + accountmap.setKeyValue (portKey, &port); + accountmap.setKeyValue (publishAddrKey, &publishAddr); + accountmap.setKeyValue (publishPortKey, &publishPort); + accountmap.setKeyValue (sameasLocalKey, &sameasLocal); + accountmap.setKeyValue (resolveOnceKey, &resolveOnce); + accountmap.setKeyValue (dtmfTypeKey, &dtmfType); + accountmap.setKeyValue (displayNameKey, &displayName); + + accountmap.setKeyValue (srtpKey, &srtpmap); + srtpmap.setKeyValue (srtpEnableKey, &srtpenabled); + srtpmap.setKeyValue (keyExchangeKey, &keyExchange); + srtpmap.setKeyValue (rtpFallbackKey, &rtpFallback); + + accountmap.setKeyValue (zrtpKey, &zrtpmap); + zrtpmap.setKeyValue (displaySasKey, &displaySas); + zrtpmap.setKeyValue (displaySasOnceKey, &displaySasOnce); + zrtpmap.setKeyValue (helloHashEnabledKey, &helloHashEnabled); + zrtpmap.setKeyValue (notSuppWarningKey, ¬SuppWarning); + + accountmap.setKeyValue (credKey, &credentialmap); + credentialmap.setKeyValue (credentialCountKey, &count); + + accountmap.setKeyValue (tlsKey, &tlsmap); + tlsmap.setKeyValue (tlsPortKey, &tlsport); + tlsmap.setKeyValue (certificateKey, &certificate); + tlsmap.setKeyValue (calistKey, &calist); + tlsmap.setKeyValue (ciphersKey, &ciphers); + tlsmap.setKeyValue (tlsEnableKey, &tlsenabled); + tlsmap.setKeyValue (methodKey, &tlsmethod); + tlsmap.setKeyValue (timeoutKey, &timeout); + tlsmap.setKeyValue (tlsPasswordKey, &tlspassword); + tlsmap.setKeyValue (privateKeyKey, &privatekey); + tlsmap.setKeyValue (requireCertifKey, &requirecertif); + tlsmap.setKeyValue (serverKey, &server); + tlsmap.setKeyValue (verifyClientKey, &verifyclient); + tlsmap.setKeyValue (verifyServerKey, &verifyserver); + + try { + emitter = new Conf::YamlEmitter ("/tmp/sequenceEmiter.txt"); + + emitter->serializeAccount (&accountmap); + emitter->serializeAccount (&accountmap); + emitter->serializeData(); + + delete emitter; + } catch (Conf::YamlEmitterException &e) { + _error ("ConfigTree: %s", e.what()); + } } diff --git a/sflphone-common/test/delaydetectiontest.cpp b/sflphone-common/test/delaydetectiontest.cpp index a0bb79bbc8335c1f783e48caaf0e18cfb41c8cfd..5f11407aa3a5d90169958d66c501e1f507587035 100644 --- a/sflphone-common/test/delaydetectiontest.cpp +++ b/sflphone-common/test/delaydetectiontest.cpp @@ -39,173 +39,178 @@ void DelayDetectionTest::setUp() {} void DelayDetectionTest::tearDown() {} -void DelayDetectionTest::testCrossCorrelation() -{ +void DelayDetectionTest::testCrossCorrelation() { float signal[10] = {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0}; float ref[3] = {0.0, 1.0, 2.0}; float result[10]; float expected[10] = {0.0, 0.89442719, 1.0, 0.95618289, 0.91350028, 0.88543774, 0.86640023, 0.85280287, 0.8426548, 0.83480969}; - CPPUNIT_ASSERT(_delaydetect.correlate(ref, ref, 3) == 5.0); - CPPUNIT_ASSERT(_delaydetect.correlate(signal, signal, 10) == 285.0); - - _delaydetect.crossCorrelate(ref, signal, result, 3, 10); + CPPUNIT_ASSERT (_delaydetect.correlate (ref, ref, 3) == 5.0); + CPPUNIT_ASSERT (_delaydetect.correlate (signal, signal, 10) == 285.0); + + _delaydetect.crossCorrelate (ref, signal, result, 3, 10); float tmp; + for (int i = 0; i < 10; i++) { tmp = result[i]-expected[i]; - if(tmp < 0.0) - CPPUNIT_ASSERT (tmp > -0.001); - else - CPPUNIT_ASSERT(tmp < 0.001); + + if (tmp < 0.0) + CPPUNIT_ASSERT (tmp > -0.001); + else + CPPUNIT_ASSERT (tmp < 0.001); } } -void DelayDetectionTest::testCrossCorrelationDelay() -{ - float signal[10] = {0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0}; - float ref[3] = {0.0, 1.0, 0.0}; +void DelayDetectionTest::testCrossCorrelationDelay() { + float signal[10] = {0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0}; + float ref[3] = {0.0, 1.0, 0.0}; + + float result[10]; - float result[10]; + _delaydetect.crossCorrelate (ref, signal, result, 3, 10); - _delaydetect.crossCorrelate(ref, signal, result, 3, 10); + float expected[10] = {0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0}; - float expected[10] = {0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0}; - } -void DelayDetectionTest::testFirFilter() -{ +void DelayDetectionTest::testFirFilter() { float decimationCoefs[] = {-0.09870257, 0.07473655, 0.05616626, 0.04448337, 0.03630817, 0.02944626, - 0.02244098, 0.01463477, 0.00610982, -0.00266367, -0.01120109, -0.01873722, - -0.02373243, -0.02602213, -0.02437806, -0.01869834, -0.00875287, 0.00500204, - 0.02183252, 0.04065763, 0.06015944, 0.0788299, 0.09518543, 0.10799179, - 0.1160644, 0.12889288, 0.1160644, 0.10799179, 0.09518543, 0.0788299, - 0.06015944, 0.04065763, 0.02183252, 0.00500204, -0.00875287, -0.01869834, - -0.02437806, -0.02602213, -0.02373243, -0.01873722, -0.01120109, -0.00266367, - 0.00610982, 0.01463477, 0.02244098, 0.02944626, 0.03630817, 0.04448337, - 0.05616626, 0.07473655, -0.09870257}; - std::vector<double> ird(decimationCoefs, decimationCoefs + sizeof(decimationCoefs)/sizeof(float)); + 0.02244098, 0.01463477, 0.00610982, -0.00266367, -0.01120109, -0.01873722, + -0.02373243, -0.02602213, -0.02437806, -0.01869834, -0.00875287, 0.00500204, + 0.02183252, 0.04065763, 0.06015944, 0.0788299, 0.09518543, 0.10799179, + 0.1160644, 0.12889288, 0.1160644, 0.10799179, 0.09518543, 0.0788299, + 0.06015944, 0.04065763, 0.02183252, 0.00500204, -0.00875287, -0.01869834, + -0.02437806, -0.02602213, -0.02373243, -0.01873722, -0.01120109, -0.00266367, + 0.00610982, 0.01463477, 0.02244098, 0.02944626, 0.03630817, 0.04448337, + 0.05616626, 0.07473655, -0.09870257 + }; + std::vector<double> ird (decimationCoefs, decimationCoefs + sizeof (decimationCoefs) /sizeof (float)); float bandpassCoefs[] = {0.06278034, -0.0758545, -0.02274943, -0.0084497, 0.0702427, 0.05986113, - 0.06436469, -0.02412049, -0.03433526, -0.07568665, -0.03214543, -0.07236507, - -0.06979052, -0.12446371, -0.05530828, 0.00947243, 0.15294699, 0.17735563, - 0.15294699, 0.00947243, -0.05530828, -0.12446371, -0.06979052, -0.07236507, - -0.03214543, -0.07568665, -0.03433526, -0.02412049, 0.06436469, 0.05986113, - 0.0702427, -0.0084497, -0.02274943, -0.0758545, 0.06278034}; - std::vector<double> irb(bandpassCoefs, bandpassCoefs + sizeof(bandpassCoefs)/sizeof(float)); + 0.06436469, -0.02412049, -0.03433526, -0.07568665, -0.03214543, -0.07236507, + -0.06979052, -0.12446371, -0.05530828, 0.00947243, 0.15294699, 0.17735563, + 0.15294699, 0.00947243, -0.05530828, -0.12446371, -0.06979052, -0.07236507, + -0.03214543, -0.07568665, -0.03433526, -0.02412049, 0.06436469, 0.05986113, + 0.0702427, -0.0084497, -0.02274943, -0.0758545, 0.06278034 + }; + std::vector<double> irb (bandpassCoefs, bandpassCoefs + sizeof (bandpassCoefs) /sizeof (float)); float impulse[100]; - memset(impulse, 0, sizeof(float)*100); + memset (impulse, 0, sizeof (float) *100); impulse[0] = 1.0; - FirFilter _decimationFilter(ird); - FirFilter _bandpassFilter(irb); + FirFilter _decimationFilter (ird); + FirFilter _bandpassFilter (irb); float impulseresponse[100]; - memset(impulseresponse, 0, sizeof(float)*100); + memset (impulseresponse, 0, sizeof (float) *100); // compute impulse response - for(int i = 0; i < 100; i++) { - impulseresponse[i] = _decimationFilter.getOutputSample(impulse[i]); + for (int i = 0; i < 100; i++) { + impulseresponse[i] = _decimationFilter.getOutputSample (impulse[i]); } float tmp; - int size = sizeof(decimationCoefs)/sizeof(float); - for(int i = 0; i < size; i++) { - tmp = decimationCoefs[i] - impulseresponse[i]; - if(tmp < 0.0) - CPPUNIT_ASSERT (tmp > -0.000001); - else - CPPUNIT_ASSERT(tmp < 0.000001); + int size = sizeof (decimationCoefs) /sizeof (float); + + for (int i = 0; i < size; i++) { + tmp = decimationCoefs[i] - impulseresponse[i]; + + if (tmp < 0.0) + CPPUNIT_ASSERT (tmp > -0.000001); + else + CPPUNIT_ASSERT (tmp < 0.000001); } - for(int i = 0; i < 100; i++) { - impulseresponse[i] = _bandpassFilter.getOutputSample(impulse[i]); + for (int i = 0; i < 100; i++) { + impulseresponse[i] = _bandpassFilter.getOutputSample (impulse[i]); } - size = sizeof(bandpassCoefs)/sizeof(float); - for(int i = 0; i < size; i++) { - tmp = bandpassCoefs[i] - impulseresponse[i]; - if(tmp < 0.0) - CPPUNIT_ASSERT (tmp > -0.000001); - else - CPPUNIT_ASSERT(tmp < 0.000001); + size = sizeof (bandpassCoefs) /sizeof (float); + + for (int i = 0; i < size; i++) { + tmp = bandpassCoefs[i] - impulseresponse[i]; + + if (tmp < 0.0) + CPPUNIT_ASSERT (tmp > -0.000001); + else + CPPUNIT_ASSERT (tmp < 0.000001); } - + } void DelayDetectionTest::testIntToFloatConversion() { - SFLDataFormat data[32768*2]; - float converted[32768*2]; + SFLDataFormat data[32768*2]; + float converted[32768*2]; - for(int i = -32768; i < 32768; i++) - data[i+32768] = i; - - _delaydetect.convertInt16ToFloat32(data, converted, 32768*2); + for (int i = -32768; i < 32768; i++) + data[i+32768] = i; - for(int i = -32768; i < 0; i++) { - CPPUNIT_ASSERT(converted[i+32768] >= -1.0); - CPPUNIT_ASSERT(converted[i+32768] <= 0.0); - } + _delaydetect.convertInt16ToFloat32 (data, converted, 32768*2); + + for (int i = -32768; i < 0; i++) { + CPPUNIT_ASSERT (converted[i+32768] >= -1.0); + CPPUNIT_ASSERT (converted[i+32768] <= 0.0); + } - for(int i = 0; i < 32768; i++) { - CPPUNIT_ASSERT(converted[i+32768] >= 0.0); - CPPUNIT_ASSERT(converted[i+32768] <= 1.0); - } + for (int i = 0; i < 32768; i++) { + CPPUNIT_ASSERT (converted[i+32768] >= 0.0); + CPPUNIT_ASSERT (converted[i+32768] <= 1.0); + } } void DelayDetectionTest::testDownSamplingData() { - SFLDataFormat data[32768*2]; - float converted[32768*2]; - float resampled[32768*2]; + SFLDataFormat data[32768*2]; + float converted[32768*2]; + float resampled[32768*2]; + + for (int i = -32768; i < 32768; i++) + data[i+32768] = i; - for(int i = -32768; i < 32768; i++) - data[i+32768] = i; + _delaydetect.convertInt16ToFloat32 (data, converted, 32768*2); - _delaydetect.convertInt16ToFloat32(data, converted, 32768*2); + _delaydetect.downsampleData (converted, resampled, 32768*2, 8); - _delaydetect.downsampleData(converted, resampled, 32768*2, 8); + for (int i = 0; i < 32768/8; i++) { + CPPUNIT_ASSERT (resampled[i] >= -1.0); + CPPUNIT_ASSERT (resampled[i] <= 0.0); + } - for(int i = 0; i < 32768/8; i++) { - CPPUNIT_ASSERT(resampled[i] >= -1.0); - CPPUNIT_ASSERT(resampled[i] <= 0.0); - } + for (int i = 32768/8+1; i < 32768/4; i++) { + CPPUNIT_ASSERT (resampled[i] >= 0.0); + CPPUNIT_ASSERT (resampled[i] <= 1.0); + } - for(int i = 32768/8+1; i < 32768/4; i++) { - CPPUNIT_ASSERT(resampled[i] >= 0.0); - CPPUNIT_ASSERT(resampled[i] <= 1.0); - } - } void DelayDetectionTest::testDelayDetection() { - int delay = 100; - - SFLDataFormat spkr[WINDOW_SIZE]; - memset(spkr, 0, sizeof(SFLDataFormat)*WINDOW_SIZE); - spkr[0] = 32000; - spkr[1] = 32000; - spkr[2] = 32000; - spkr[3] = 32000; - spkr[4] = 32000; - - SFLDataFormat mic[DELAY_BUFF_SIZE]; - memset(mic, 0, sizeof(SFLDataFormat)*DELAY_BUFF_SIZE); - mic[delay] = 32000; - mic[delay+1] = 32000; - mic[delay+2] = 32000; - mic[delay+3] = 32000; - mic[delay+4] = 32000; - - _delaydetect.putData(spkr, WINDOW_SIZE*sizeof(SFLDataFormat)); - _delaydetect.process(mic, DELAY_BUFF_SIZE*sizeof(SFLDataFormat)); + int delay = 100; + + SFLDataFormat spkr[WINDOW_SIZE]; + memset (spkr, 0, sizeof (SFLDataFormat) *WINDOW_SIZE); + spkr[0] = 32000; + spkr[1] = 32000; + spkr[2] = 32000; + spkr[3] = 32000; + spkr[4] = 32000; + + SFLDataFormat mic[DELAY_BUFF_SIZE]; + memset (mic, 0, sizeof (SFLDataFormat) *DELAY_BUFF_SIZE); + mic[delay] = 32000; + mic[delay+1] = 32000; + mic[delay+2] = 32000; + mic[delay+3] = 32000; + mic[delay+4] = 32000; + + _delaydetect.putData (spkr, WINDOW_SIZE*sizeof (SFLDataFormat)); + _delaydetect.process (mic, DELAY_BUFF_SIZE*sizeof (SFLDataFormat)); } diff --git a/sflphone-common/test/historytest.cpp b/sflphone-common/test/historytest.cpp index 8f0853c6a142b7ece063c455b97fb0369473b74e..7e22efeb648b5c41450f4394a24486791974c8ec 100644 --- a/sflphone-common/test/historytest.cpp +++ b/sflphone-common/test/historytest.cpp @@ -40,187 +40,187 @@ using std::cout; using std::endl; void HistoryTest::setUp() { - // Instanciate the cleaner singleton - history = new HistoryManager(); + // Instanciate the cleaner singleton + history = new HistoryManager(); } void HistoryTest::test_create_history_path() { - _debug ("-------------------- HistoryTest::test_create_history_path --------------------\n"); + _debug ("-------------------- HistoryTest::test_create_history_path --------------------\n"); - int result; - char *cpath; - std::string path; + int result; + char *cpath; + std::string path; - cpath = getenv("XDG_DATA_HOME"); - (cpath != NULL) ? path = std::string(cpath) : path = std::string(HOMEDIR) - + "/.local/share/sflphone/history"; + cpath = getenv ("XDG_DATA_HOME"); + (cpath != NULL) ? path = std::string (cpath) : path = std::string (HOMEDIR) + + "/.local/share/sflphone/history"; - result = history->create_history_path(); - CPPUNIT_ASSERT (result == 0); - CPPUNIT_ASSERT (!history->is_loaded ()); - CPPUNIT_ASSERT (history->_history_path == path); + result = history->create_history_path(); + CPPUNIT_ASSERT (result == 0); + CPPUNIT_ASSERT (!history->is_loaded ()); + CPPUNIT_ASSERT (history->_history_path == path); } void HistoryTest::test_load_history_from_file() { - _debug ("-------------------- HistoryTest::test_load_history_from_file --------------------\n"); + _debug ("-------------------- HistoryTest::test_load_history_from_file --------------------\n"); - bool res; - Conf::ConfigTree history_list; + bool res; + Conf::ConfigTree history_list; - history->create_history_path(); - res = history->load_history_from_file(&history_list); + history->create_history_path(); + res = history->load_history_from_file (&history_list); - CPPUNIT_ASSERT (history->is_loaded ()); - CPPUNIT_ASSERT (res == true); + CPPUNIT_ASSERT (history->is_loaded ()); + CPPUNIT_ASSERT (res == true); } void HistoryTest::test_load_history_items_map() { - _debug ("-------------------- HistoryTest::test_load_history_items_map --------------------\n"); - - std::string path; - int nb_items; - Conf::ConfigTree history_list; - - history->set_history_path(HISTORY_SAMPLE); - history->load_history_from_file(&history_list); - nb_items = history->load_history_items_map(&history_list, - HUGE_HISTORY_LIMIT); - CPPUNIT_ASSERT (nb_items == HISTORY_SAMPLE_SIZE); - CPPUNIT_ASSERT (history->get_history_size () == HISTORY_SAMPLE_SIZE); + _debug ("-------------------- HistoryTest::test_load_history_items_map --------------------\n"); + + std::string path; + int nb_items; + Conf::ConfigTree history_list; + + history->set_history_path (HISTORY_SAMPLE); + history->load_history_from_file (&history_list); + nb_items = history->load_history_items_map (&history_list, + HUGE_HISTORY_LIMIT); + CPPUNIT_ASSERT (nb_items == HISTORY_SAMPLE_SIZE); + CPPUNIT_ASSERT (history->get_history_size () == HISTORY_SAMPLE_SIZE); } void HistoryTest::test_save_history_items_map() { - _debug ("-------------------- HistoryTest::test_save_history_items_map --------------------\n"); - - std::string path; - int nb_items_loaded, nb_items_saved; - Conf::ConfigTree history_list, history_list2; - - history->set_history_path(HISTORY_SAMPLE); - history->load_history_from_file(&history_list); - nb_items_loaded = history->load_history_items_map(&history_list, - HUGE_HISTORY_LIMIT); - nb_items_saved = history->save_history_items_map(&history_list2); - CPPUNIT_ASSERT (nb_items_loaded == nb_items_saved); + _debug ("-------------------- HistoryTest::test_save_history_items_map --------------------\n"); + + std::string path; + int nb_items_loaded, nb_items_saved; + Conf::ConfigTree history_list, history_list2; + + history->set_history_path (HISTORY_SAMPLE); + history->load_history_from_file (&history_list); + nb_items_loaded = history->load_history_items_map (&history_list, + HUGE_HISTORY_LIMIT); + nb_items_saved = history->save_history_items_map (&history_list2); + CPPUNIT_ASSERT (nb_items_loaded == nb_items_saved); } void HistoryTest::test_save_history_to_file() { - _debug ("-------------------- HistoryTest::test_save_history_to_file --------------------\n"); - - std::string path; - Conf::ConfigTree history_list, history_list2; - std::map<std::string, std::string> res; - std::map<std::string, std::string>::iterator iter; - - history->set_history_path(HISTORY_SAMPLE); - history->load_history_from_file(&history_list); - history->load_history_items_map(&history_list, HUGE_HISTORY_LIMIT); - history->save_history_items_map(&history_list2); - CPPUNIT_ASSERT (history->save_history_to_file (&history_list2)); + _debug ("-------------------- HistoryTest::test_save_history_to_file --------------------\n"); + + std::string path; + Conf::ConfigTree history_list, history_list2; + std::map<std::string, std::string> res; + std::map<std::string, std::string>::iterator iter; + + history->set_history_path (HISTORY_SAMPLE); + history->load_history_from_file (&history_list); + history->load_history_items_map (&history_list, HUGE_HISTORY_LIMIT); + history->save_history_items_map (&history_list2); + CPPUNIT_ASSERT (history->save_history_to_file (&history_list2)); } void HistoryTest::test_get_history_serialized() { - _debug ("-------------------- HistoryTest::test_get_history_serialized --------------------\n"); + _debug ("-------------------- HistoryTest::test_get_history_serialized --------------------\n"); - std::map<std::string, std::string> res; - std::map<std::string, std::string>::iterator iter; - std::string tmp; + std::map<std::string, std::string> res; + std::map<std::string, std::string>::iterator iter; + std::string tmp; - 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 (history->load_history (HUGE_HISTORY_LIMIT, HISTORY_SAMPLE) == HISTORY_SAMPLE_SIZE); + res = history->get_history_serialized(); + 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 + // 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 (Validator::isEqual(tmp, res ["144562436"])); + // Check the first + tmp = "0|514-276-5468|Savoir-faire Linux|144562458|empty"; + CPPUNIT_ASSERT (Validator::isEqual (tmp, res ["144562436"])); - tmp = "2|136|Emmanuel Milou|747638765|Account:1239059899"; - CPPUNIT_ASSERT (Validator::isEqual(tmp, res ["747638685"])); + tmp = "2|136|Emmanuel Milou|747638765|Account:1239059899"; + CPPUNIT_ASSERT (Validator::isEqual (tmp, res ["747638685"])); - // the account ID does not correspond to a loaded account - tmp = "1|5143848557|empty|775354987|empty"; - CPPUNIT_ASSERT (Validator::isEqual(tmp, res ["775354456"])); + // the account ID does not correspond to a loaded account + tmp = "1|5143848557|empty|775354987|empty"; + CPPUNIT_ASSERT (Validator::isEqual (tmp, res ["775354456"])); } void HistoryTest::test_set_serialized_history() { - _debug ("-------------------- HistoryTest::test_set_serialized_history --------------------\n"); + _debug ("-------------------- HistoryTest::test_set_serialized_history --------------------\n"); - // We build a map to have an efficient test - std::map<std::string, std::string> map_test; - std::string tmp; - Conf::ConfigTree history_list; + // We build a map to have an efficient test + std::map<std::string, std::string> map_test; + std::string tmp; + Conf::ConfigTree history_list; - map_test["144562436"] = "0|514-276-5468|Savoir-faire Linux|144562458|empty"; - map_test["747638685"] = "2|136|Emmanuel Milou|747638765|Account:1239059899"; - map_test["775354456"] = "1|5143848557|empty|775354987|Account:43789459478"; + map_test["144562436"] = "0|514-276-5468|Savoir-faire Linux|144562458|empty"; + map_test["747638685"] = "2|136|Emmanuel Milou|747638765|Account:1239059899"; + map_test["775354456"] = "1|5143848557|empty|775354987|Account:43789459478"; - CPPUNIT_ASSERT (history->load_history (HUGE_HISTORY_LIMIT, HISTORY_SAMPLE) == HISTORY_SAMPLE_SIZE); - // We use a large history limit to be able to interpret results - CPPUNIT_ASSERT (history->set_serialized_history (map_test, HUGE_HISTORY_LIMIT) == 3); - CPPUNIT_ASSERT (history->get_history_size () == 3); + CPPUNIT_ASSERT (history->load_history (HUGE_HISTORY_LIMIT, HISTORY_SAMPLE) == HISTORY_SAMPLE_SIZE); + // We use a large history limit to be able to interpret results + CPPUNIT_ASSERT (history->set_serialized_history (map_test, HUGE_HISTORY_LIMIT) == 3); + CPPUNIT_ASSERT (history->get_history_size () == 3); - map_test.clear(); - map_test = history->get_history_serialized(); - CPPUNIT_ASSERT (map_test.size() ==3); + map_test.clear(); + map_test = history->get_history_serialized(); + CPPUNIT_ASSERT (map_test.size() ==3); - // Check the first - tmp = "0|514-276-5468|Savoir-faire Linux|144562458|empty"; - CPPUNIT_ASSERT (Validator::isEqual(tmp, map_test ["144562436"])); + // Check the first + tmp = "0|514-276-5468|Savoir-faire Linux|144562458|empty"; + CPPUNIT_ASSERT (Validator::isEqual (tmp, map_test ["144562436"])); - tmp = "2|136|Emmanuel Milou|747638765|Account:1239059899"; - CPPUNIT_ASSERT (Validator::isEqual(tmp, map_test ["747638685"])); + tmp = "2|136|Emmanuel Milou|747638765|Account:1239059899"; + CPPUNIT_ASSERT (Validator::isEqual (tmp, map_test ["747638685"])); - // the account ID does not correspond to a loaded account - tmp = "1|5143848557|empty|775354987|empty"; - CPPUNIT_ASSERT (Validator::isEqual(tmp, map_test ["775354456"])); + // the account ID does not correspond to a loaded account + tmp = "1|5143848557|empty|775354987|empty"; + CPPUNIT_ASSERT (Validator::isEqual (tmp, map_test ["775354456"])); - history->save_history_items_map(&history_list); - CPPUNIT_ASSERT (history->save_history_to_file (&history_list)); + history->save_history_items_map (&history_list); + CPPUNIT_ASSERT (history->save_history_to_file (&history_list)); } void HistoryTest::test_set_serialized_history_with_limit() { - _debug ("-------------------- HistoryTest::test_set_serialized_history_with_limit --------------------\n"); - - // We build a map to have an efficient test - std::map<std::string, std::string> map_test; - std::string tmp; - Conf::ConfigTree history_list; - time_t current, day = 86400; // One day in unix timestamp - std::stringstream current_1, current_2, current_3; - - (void) time(¤t); - current_1 << (current - 2 * day) << std::endl; - 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"; - - 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); - - // 1 day - no entry should not be saved - CPPUNIT_ASSERT (history->set_serialized_history (map_test, 1) == 0); - CPPUNIT_ASSERT (history->get_history_size () == 0); + _debug ("-------------------- HistoryTest::test_set_serialized_history_with_limit --------------------\n"); + + // We build a map to have an efficient test + std::map<std::string, std::string> map_test; + std::string tmp; + Conf::ConfigTree history_list; + time_t current, day = 86400; // One day in unix timestamp + std::stringstream current_1, current_2, current_3; + + (void) time (¤t); + current_1 << (current - 2 * day) << std::endl; + 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"; + + 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); + + // 1 day - no entry should not be saved + CPPUNIT_ASSERT (history->set_serialized_history (map_test, 1) == 0); + CPPUNIT_ASSERT (history->get_history_size () == 0); } void HistoryTest::tearDown() { - // Delete the history object - delete history; - history = 0; + // Delete the history object + delete history; + history = 0; } diff --git a/sflphone-common/test/hookmanagertest.cpp b/sflphone-common/test/hookmanagertest.cpp index b0d68c936251e69f7200ce772f29af5f40e3d0a2..d66461e57d0dce68da90fde2aa3c736ed219080b 100644 --- a/sflphone-common/test/hookmanagertest.cpp +++ b/sflphone-common/test/hookmanagertest.cpp @@ -39,15 +39,13 @@ using std::cout; using std::endl; -void HookManagerTest::setUp() -{ +void HookManagerTest::setUp() { // Instanciate the hook manager singleton urlhook = new UrlHook (); } -void HookManagerTest::testAddAction () -{ - _debug ("-------------------- HookManagerTest::testAddAction --------------------\n"); +void HookManagerTest::testAddAction () { + _debug ("-------------------- HookManagerTest::testAddAction --------------------\n"); int status; @@ -55,16 +53,14 @@ void HookManagerTest::testAddAction () CPPUNIT_ASSERT (status == 0); } -void HookManagerTest::testLargeUrl () -{ - _debug ("-------------------- HookManagerTest::testLargeUrl --------------------\n"); +void HookManagerTest::testLargeUrl () { + _debug ("-------------------- HookManagerTest::testLargeUrl --------------------\n"); 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; diff --git a/sflphone-common/test/main.cpp b/sflphone-common/test/main.cpp index ada12320f8272f1247ae0f3c6e4b1743ed8da548..610e5065f8f2bcc8ab69c37905219205ed8cb14a 100644 --- a/sflphone-common/test/main.cpp +++ b/sflphone-common/test/main.cpp @@ -37,73 +37,73 @@ #include <cppunit/extensions/TestFactoryRegistry.h> #include <cppunit/ui/text/TextTestRunner.h> -int main(int argc, char* argv[]) { - - printf("\nSFLphone Daemon Test Suite, by Savoir-Faire Linux 2004-2010\n\n"); - Logger::setConsoleLog(true); - Logger::setDebugMode(true); - - int argvIndex = 1; - - if (argc > 1) { - if (strcmp("--help", argv[1]) == 0) { - argvIndex++; - - CPPUNIT_NS::Test* suite = CPPUNIT_NS::TestFactoryRegistry::getRegistry("All Tests").makeTest(); - - int testSuiteCount = suite->getChildTestCount(); - printf("Usage: test [OPTIONS] [TEST_SUITE]\n"); - printf("\nOptions:\n"); - printf(" --debug - Debug mode\n"); - printf(" --help - Print help\n"); - printf("\nAvailable test suites:\n"); - for (int i = 0; i < testSuiteCount; i++) { - printf(" - %s\n", suite->getChildTestAt(i)->getName().c_str()); - } - exit(0); - } - else if (strcmp("--debug", argv[1]) == 0) { - argvIndex++; - - Logger::setDebugMode(true); - _info("Debug mode activated"); - } - } - - // Default test suite : all tests - std::string testSuiteName = "All Tests"; - if(argvIndex < argc) - { - testSuiteName = argv[argvIndex]; - argvIndex++; - } - - printf("\n\n=== SFLphone initialization ===\n\n"); - Manager::instance().initConfigFile(true, CONFIG_SAMPLE); - Manager::instance().init(); - - // Get the top level suite from the registry - printf("\n\n=== Test Suite: %s ===\n\n", testSuiteName.c_str()); - CPPUNIT_NS::Test *suite = CPPUNIT_NS::TestFactoryRegistry::getRegistry(testSuiteName).makeTest(); - - if(suite->getChildTestCount() == 0) - { - _error("Invalid test suite name: %s", testSuiteName.c_str()); - exit(-1); - } - - // Adds the test to the list of test to run - CppUnit::TextTestRunner runner; - runner.addTest(suite); - - // Change the default outputter to a compiler error format outputter - runner.setOutputter(new CppUnit::CompilerOutputter(&runner.result(), std::cerr)); - - // Run the tests. - bool wasSucessful = runner.run(); - - Manager::instance().terminate(); - - // Return error code 1 if the one of test failed. - return wasSucessful ? 0 : 1; +int main (int argc, char* argv[]) { + + printf ("\nSFLphone Daemon Test Suite, by Savoir-Faire Linux 2004-2010\n\n"); + Logger::setConsoleLog (true); + Logger::setDebugMode (true); + + int argvIndex = 1; + + if (argc > 1) { + if (strcmp ("--help", argv[1]) == 0) { + argvIndex++; + + CPPUNIT_NS::Test* suite = CPPUNIT_NS::TestFactoryRegistry::getRegistry ("All Tests").makeTest(); + + int testSuiteCount = suite->getChildTestCount(); + printf ("Usage: test [OPTIONS] [TEST_SUITE]\n"); + printf ("\nOptions:\n"); + printf (" --debug - Debug mode\n"); + printf (" --help - Print help\n"); + printf ("\nAvailable test suites:\n"); + + for (int i = 0; i < testSuiteCount; i++) { + printf (" - %s\n", suite->getChildTestAt (i)->getName().c_str()); + } + + exit (0); + } else if (strcmp ("--debug", argv[1]) == 0) { + argvIndex++; + + Logger::setDebugMode (true); + _info ("Debug mode activated"); + } + } + + // Default test suite : all tests + std::string testSuiteName = "All Tests"; + + if (argvIndex < argc) { + testSuiteName = argv[argvIndex]; + argvIndex++; + } + + printf ("\n\n=== SFLphone initialization ===\n\n"); + Manager::instance().initConfigFile (true, CONFIG_SAMPLE); + Manager::instance().init(); + + // Get the top level suite from the registry + printf ("\n\n=== Test Suite: %s ===\n\n", testSuiteName.c_str()); + CPPUNIT_NS::Test *suite = CPPUNIT_NS::TestFactoryRegistry::getRegistry (testSuiteName).makeTest(); + + if (suite->getChildTestCount() == 0) { + _error ("Invalid test suite name: %s", testSuiteName.c_str()); + exit (-1); + } + + // Adds the test to the list of test to run + CppUnit::TextTestRunner runner; + runner.addTest (suite); + + // Change the default outputter to a compiler error format outputter + runner.setOutputter (new CppUnit::CompilerOutputter (&runner.result(), std::cerr)); + + // Run the tests. + bool wasSucessful = runner.run(); + + Manager::instance().terminate(); + + // Return error code 1 if the one of test failed. + return wasSucessful ? 0 : 1; } diff --git a/sflphone-common/test/mainbuffertest.cpp b/sflphone-common/test/mainbuffertest.cpp index 8b36a4b776dddfaddbb669ba15ce20815cacc973..1b339b1219cdd5421a4e63e347984cfcc912d547 100644 --- a/sflphone-common/test/mainbuffertest.cpp +++ b/sflphone-common/test/mainbuffertest.cpp @@ -49,22 +49,19 @@ using std::cout; using std::endl; -void MainBufferTest::setUp() -{ +void MainBufferTest::setUp() { } -void MainBufferTest::tearDown() -{ +void MainBufferTest::tearDown() { } -void MainBufferTest::testRingBufferCreation() -{ - _debug ("-------------------- MainBufferTest::testRingBufferCreation --------------------\n"); +void MainBufferTest::testRingBufferCreation() { + _debug ("-------------------- MainBufferTest::testRingBufferCreation --------------------\n"); CallID test_id = "1234"; CallID null_id = "null id"; @@ -109,9 +106,8 @@ void MainBufferTest::testRingBufferCreation() } -void MainBufferTest::testRingBufferReadPointer() -{ - _debug ("-------------------- MainBufferTest::testRingBufferReadPointer --------------------\n"); +void MainBufferTest::testRingBufferReadPointer() { + _debug ("-------------------- MainBufferTest::testRingBufferReadPointer --------------------\n"); CallID call_id = "call id"; CallID read_id = "read id"; @@ -156,9 +152,8 @@ void MainBufferTest::testRingBufferReadPointer() } -void MainBufferTest::testCallIDSet() -{ - _debug ("-------------------- MainBufferTest::testCallIDSet --------------------\n"); +void MainBufferTest::testCallIDSet() { + _debug ("-------------------- MainBufferTest::testCallIDSet --------------------\n"); CallID test_id = "set id"; CallID false_id = "false set id"; @@ -239,9 +234,8 @@ void MainBufferTest::testCallIDSet() } -void MainBufferTest::testRingBufferInt() -{ - _debug ("-------------------- MainBufferTest::testRingBufferInt --------------------\n"); +void MainBufferTest::testRingBufferInt() { + _debug ("-------------------- MainBufferTest::testRingBufferInt --------------------\n"); // CallID test_id = "test_int"; @@ -355,9 +349,8 @@ void MainBufferTest::testRingBufferInt() } -void MainBufferTest::testRingBufferNonDefaultID() -{ - _debug ("-------------------- MainBufferTest::testRingBufferNonDefaultID --------------------\n"); +void MainBufferTest::testRingBufferNonDefaultID() { + _debug ("-------------------- MainBufferTest::testRingBufferNonDefaultID --------------------\n"); CallID test_id = "test_int"; @@ -442,9 +435,8 @@ void MainBufferTest::testRingBufferNonDefaultID() } -void MainBufferTest::testRingBufferFloat() -{ - _debug ("-------------------- MainBufferTest::testRingBufferFloat --------------------\n"); +void MainBufferTest::testRingBufferFloat() { + _debug ("-------------------- MainBufferTest::testRingBufferFloat --------------------\n"); float testfloat1 = 12.5; float testfloat2 = 13.4; @@ -476,9 +468,8 @@ void MainBufferTest::testRingBufferFloat() } -void MainBufferTest::testTwoPointer() -{ - _debug ("-------------------- MainBufferTest::testTwoPointer --------------------\n"); +void MainBufferTest::testTwoPointer() { + _debug ("-------------------- MainBufferTest::testTwoPointer --------------------\n"); RingBuffer* input_buffer = _mainbuffer.createRingBuffer (default_id); input_buffer->createReadPointer (default_id); @@ -493,9 +484,8 @@ void MainBufferTest::testTwoPointer() } -void MainBufferTest::testBindUnbindBuffer() -{ - _debug ("-------------------- MainBufferTest::testBindUnbindBuffer --------------------\n"); +void MainBufferTest::testBindUnbindBuffer() { + _debug ("-------------------- MainBufferTest::testBindUnbindBuffer --------------------\n"); CallID test_id1 = "bind unbind 1"; CallID test_id2 = "bind unbind 2"; @@ -892,9 +882,8 @@ void MainBufferTest::testBindUnbindBuffer() } -void MainBufferTest::testGetPutDataByID() -{ - _debug ("-------------------- MainBufferTest::testGetPutDataByID --------------------\n"); +void MainBufferTest::testGetPutDataByID() { + _debug ("-------------------- MainBufferTest::testGetPutDataByID --------------------\n"); CallID test_id = "getData putData"; CallID false_id = "false id"; @@ -947,9 +936,8 @@ void MainBufferTest::testGetPutDataByID() -void MainBufferTest::testGetPutData() -{ - _debug ("-------------------- MainBufferTest::testGetPutData --------------------\n"); +void MainBufferTest::testGetPutData() { + _debug ("-------------------- MainBufferTest::testGetPutData --------------------\n"); CallID test_id = "incoming rtp session"; @@ -995,9 +983,8 @@ void MainBufferTest::testGetPutData() } -void MainBufferTest::testDiscardFlush() -{ - _debug ("-------------------- MainBufferTest::testDiscardFlush --------------------\n"); +void MainBufferTest::testDiscardFlush() { + _debug ("-------------------- MainBufferTest::testDiscardFlush --------------------\n"); CallID test_id = "flush discard"; // _mainbuffer.createRingBuffer(test_id); @@ -1037,9 +1024,8 @@ void MainBufferTest::testDiscardFlush() } -void MainBufferTest::testReadPointerInit() -{ - _debug ("-------------------- MainBufferTest::testReadPointerInit --------------------\n"); +void MainBufferTest::testReadPointerInit() { + _debug ("-------------------- MainBufferTest::testReadPointerInit --------------------\n"); CallID test_id = "test read pointer init"; // RingBuffer* test_ring_buffer = _mainbuffer.createRingBuffer(test_id); @@ -1065,9 +1051,8 @@ void MainBufferTest::testReadPointerInit() } -void MainBufferTest::testRingBufferSeveralPointers() -{ - _debug ("-------------------- MainBufferTest::testRingBufferSeveralPointers --------------------\n"); +void MainBufferTest::testRingBufferSeveralPointers() { + _debug ("-------------------- MainBufferTest::testRingBufferSeveralPointers --------------------\n"); CallID test_id = "test multiple read pointer"; RingBuffer* test_ring_buffer = _mainbuffer.createRingBuffer (test_id); @@ -1178,9 +1163,8 @@ void MainBufferTest::testRingBufferSeveralPointers() -void MainBufferTest::testConference() -{ - _debug ("-------------------- MainBufferTest::testConference --------------------\n"); +void MainBufferTest::testConference() { + _debug ("-------------------- MainBufferTest::testConference --------------------\n"); CallID test_id1 = "participant A"; CallID test_id2 = "participant B"; diff --git a/sflphone-common/test/numbercleanertest.cpp b/sflphone-common/test/numbercleanertest.cpp index c13573e3f9bd9d78d07add7d28ad98f176433ebc..a2898ff4dc9ba184bd17061503280647f077f250 100644 --- a/sflphone-common/test/numbercleanertest.cpp +++ b/sflphone-common/test/numbercleanertest.cpp @@ -55,95 +55,82 @@ 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) -{ - _debug ("-------------------- NumberCleanerTest::test_format_1 --------------------\n"); +void NumberCleanerTest::test_format_1 (void) { + _debug ("-------------------- NumberCleanerTest::test_format_1 --------------------\n"); CPPUNIT_ASSERT (cleaner->clean (NUMBER_TEST_1) == VALID_NUMBER); } -void NumberCleanerTest::test_format_2 (void) -{ - _debug ("-------------------- NumberCleanerTest::test_format_2 --------------------\n"); +void NumberCleanerTest::test_format_2 (void) { + _debug ("-------------------- NumberCleanerTest::test_format_2 --------------------\n"); CPPUNIT_ASSERT (cleaner->clean (NUMBER_TEST_2) == VALID_NUMBER); } -void NumberCleanerTest::test_format_3 (void) -{ - _debug ("-------------------- NumberCleanerTest::test_format_3 --------------------\n"); +void NumberCleanerTest::test_format_3 (void) { + _debug ("-------------------- NumberCleanerTest::test_format_3 --------------------\n"); CPPUNIT_ASSERT (cleaner->clean (NUMBER_TEST_3) == VALID_NUMBER); } -void NumberCleanerTest::test_format_4 (void) -{ - _debug ("-------------------- NumberCleanerTest::test_format_4 --------------------\n"); +void NumberCleanerTest::test_format_4 (void) { + _debug ("-------------------- NumberCleanerTest::test_format_4 --------------------\n"); CPPUNIT_ASSERT (cleaner->clean (NUMBER_TEST_4) == VALID_NUMBER); } -void NumberCleanerTest::test_format_5 (void) -{ - _debug ("-------------------- NumberCleanerTest::test_format_5 --------------------\n"); +void NumberCleanerTest::test_format_5 (void) { + _debug ("-------------------- NumberCleanerTest::test_format_5 --------------------\n"); CPPUNIT_ASSERT (cleaner->clean (NUMBER_TEST_5) == VALID_NUMBER); } -void NumberCleanerTest::test_format_6 (void) -{ - _debug ("-------------------- NumberCleanerTest::test_format_6 --------------------\n"); +void NumberCleanerTest::test_format_6 (void) { + _debug ("-------------------- NumberCleanerTest::test_format_6 --------------------\n"); CPPUNIT_ASSERT (cleaner->clean (NUMBER_TEST_6) == VALID_NUMBER); } -void NumberCleanerTest::test_format_7 (void) -{ - _debug ("-------------------- NumberCleanerTest::test_format_7 --------------------\n"); +void NumberCleanerTest::test_format_7 (void) { + _debug ("-------------------- NumberCleanerTest::test_format_7 --------------------\n"); CPPUNIT_ASSERT (cleaner->clean (NUMBER_TEST_7) == VALID_EXTENSION); } -void NumberCleanerTest::test_format_8 (void) -{ - _debug ("-------------------- NumberCleanerTest::test_format_8 --------------------\n"); +void NumberCleanerTest::test_format_8 (void) { + _debug ("-------------------- NumberCleanerTest::test_format_8 --------------------\n"); CPPUNIT_ASSERT (cleaner->clean (NUMBER_TEST_8) == VALID_NUMBER); } -void NumberCleanerTest::test_format_9 (void) -{ - _debug ("-------------------- NumberCleanerTest::test_format_9 --------------------\n"); +void NumberCleanerTest::test_format_9 (void) { + _debug ("-------------------- NumberCleanerTest::test_format_9 --------------------\n"); CPPUNIT_ASSERT (cleaner->clean (NUMBER_TEST_9) == VALID_NUMBER); } -void NumberCleanerTest::test_format_10 (void) -{ - _debug ("-------------------- NumberCleanerTest::test_format_10 --------------------\n"); +void NumberCleanerTest::test_format_10 (void) { + _debug ("-------------------- NumberCleanerTest::test_format_10 --------------------\n"); 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) -{ - _debug ("-------------------- NumberCleanerTest::test_format_11 --------------------\n"); +void NumberCleanerTest::test_format_11 (void) { + _debug ("-------------------- NumberCleanerTest::test_format_11 --------------------\n"); 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; diff --git a/sflphone-common/test/pluginmanagertest.cpp b/sflphone-common/test/pluginmanagertest.cpp index faa28f2b035931a9da340b16b3406397892efa48..4111a4b3a97f133837b629cd7062b4d15c25e4c7 100644 --- a/sflphone-common/test/pluginmanagertest.cpp +++ b/sflphone-common/test/pluginmanagertest.cpp @@ -42,33 +42,29 @@ 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() -{ - _debug ("-------------------- PluginManagerTest::testLoadDynamicLibrary --------------------\n"); +void PluginManagerTest::testLoadDynamicLibrary() { + _debug ("-------------------- PluginManagerTest::testLoadDynamicLibrary --------------------\n"); CPPUNIT_ASSERT (_pm->loadDynamicLibrary (PLUGIN_TEST_NAME) != NULL); } -void PluginManagerTest::testUnloadDynamicLibrary() -{ - _debug ("-------------------- PluginManagerTest::testUnloadDynamicLibrary --------------------\n"); +void PluginManagerTest::testUnloadDynamicLibrary() { + _debug ("-------------------- PluginManagerTest::testUnloadDynamicLibrary --------------------\n"); library = _pm->loadDynamicLibrary (PLUGIN_TEST_NAME); CPPUNIT_ASSERT (library != NULL); CPPUNIT_ASSERT (_pm->unloadDynamicLibrary (library) == 0); } -void PluginManagerTest::testInstanciatePlugin() -{ - _debug ("-------------------- PluginManagerTest::testInstanciatePlugin --------------------\n"); +void PluginManagerTest::testInstanciatePlugin() { + _debug ("-------------------- PluginManagerTest::testInstanciatePlugin --------------------\n"); library = _pm->loadDynamicLibrary (PLUGIN_TEST_NAME); CPPUNIT_ASSERT (library != NULL); @@ -76,9 +72,8 @@ void PluginManagerTest::testInstanciatePlugin() CPPUNIT_ASSERT (plugin!=NULL); } -void PluginManagerTest::testInitPlugin() -{ - _debug ("-------------------- PluginManagerTest::testInitPlugin --------------------\n"); +void PluginManagerTest::testInitPlugin() { + _debug ("-------------------- PluginManagerTest::testInitPlugin --------------------\n"); library = _pm->loadDynamicLibrary (PLUGIN_TEST_NAME); CPPUNIT_ASSERT (library != NULL); @@ -87,9 +82,8 @@ void PluginManagerTest::testInitPlugin() CPPUNIT_ASSERT (plugin->getPluginName() == PLUGIN_TEST_DESC); } -void PluginManagerTest::testRegisterPlugin() -{ - _debug ("-------------------- PluginManagerTest::testRegisterPlugin --------------------\n"); +void PluginManagerTest::testRegisterPlugin() { + _debug ("-------------------- PluginManagerTest::testRegisterPlugin --------------------\n"); library = _pm->loadDynamicLibrary (PLUGIN_TEST_NAME); CPPUNIT_ASSERT (library != NULL); @@ -99,17 +93,15 @@ void PluginManagerTest::testRegisterPlugin() CPPUNIT_ASSERT (_pm->isPluginLoaded (PLUGIN_TEST_DESC) == true); } -void PluginManagerTest::testLoadPlugins () -{ - _debug ("-------------------- PluginManagerTest::testLoadPlugins --------------------\n"); +void PluginManagerTest::testLoadPlugins () { + _debug ("-------------------- PluginManagerTest::testLoadPlugins --------------------\n"); CPPUNIT_ASSERT (_pm->loadPlugins (PLUGIN_TEST_DIR) == 0); CPPUNIT_ASSERT (_pm->isPluginLoaded (PLUGIN_TEST_DESC) == true); } -void PluginManagerTest::testUnloadPlugins () -{ - _debug ("-------------------- PluginManagerTest::testUnloadPlugins --------------------\n"); +void PluginManagerTest::testUnloadPlugins () { + _debug ("-------------------- PluginManagerTest::testUnloadPlugins --------------------\n"); CPPUNIT_ASSERT (_pm->loadPlugins (PLUGIN_TEST_DIR) == 0); CPPUNIT_ASSERT (_pm->isPluginLoaded (PLUGIN_TEST_DESC) == true); @@ -117,8 +109,7 @@ void PluginManagerTest::testUnloadPlugins () CPPUNIT_ASSERT (_pm->isPluginLoaded (PLUGIN_TEST_DESC) == false); } -void PluginManagerTest::tearDown() -{ +void PluginManagerTest::tearDown() { // Delete the plugin manager object delete _pm; _pm=0; diff --git a/sflphone-common/test/ringtonetest.cpp b/sflphone-common/test/ringtonetest.cpp index 49501d2f576747ba753b75e1035b5855fcb35796..68ae415f23cd4241f1e69e30e5bbdd9a984f01c2 100644 --- a/sflphone-common/test/ringtonetest.cpp +++ b/sflphone-common/test/ringtonetest.cpp @@ -30,18 +30,18 @@ #include "ringtonetest.h" -void RingtoneTest::testLoadWavefile() -{ - WavFile *wav = new WavFile(); +void RingtoneTest::testLoadWavefile() { + WavFile *wav = new WavFile(); - // Test initial values - CPPUNIT_ASSERT(wav->isStarted() == false); - CPPUNIT_ASSERT(wav->getSize() == 0); + // Test initial values + CPPUNIT_ASSERT (wav->isStarted() == false); + CPPUNIT_ASSERT (wav->getSize() == 0); - // Test protection against wrong file name - CPPUNIT_ASSERT(wav->loadFile(std::string("wrongfilename.wav"), NULL, 44100) == false); + // Test protection against wrong file name + CPPUNIT_ASSERT (wav->loadFile (std::string ("wrongfilename.wav"), NULL, 44100) == false); - - delete wav; wav = NULL; + + delete wav; + wav = NULL; } diff --git a/sflphone-common/test/rtptest.cpp b/sflphone-common/test/rtptest.cpp index 366fc1fe23619b18f695228d74db761dfeea64e3..ab7bea2200b901b23b84c1cdb6d454d4143767b8 100644 --- a/sflphone-common/test/rtptest.cpp +++ b/sflphone-common/test/rtptest.cpp @@ -48,74 +48,74 @@ void RtpTest::setUp() { - pjsipInit(); + pjsipInit(); - CallID cid = "123456"; + CallID cid = "123456"; - sipcall = new SIPCall(cid, Call::Incoming, _pool); + sipcall = new SIPCall (cid, Call::Incoming, _pool); - sipcall->setLocalIp("127.0.0.1"); - sipcall->setLocalAudioPort(RANDOM_LOCAL_PORT); - sipcall->setLocalExternAudioPort(RANDOM_LOCAL_PORT); + sipcall->setLocalIp ("127.0.0.1"); + sipcall->setLocalAudioPort (RANDOM_LOCAL_PORT); + sipcall->setLocalExternAudioPort (RANDOM_LOCAL_PORT); } bool RtpTest::pjsipInit() { - // Create memory cache for pool - pj_caching_pool_init(&_cp, &pj_pool_factory_default_policy, 0); + // Create memory cache for pool + 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 ------"); - return PJ_ENOMEM; - } + if (!_pool) { + _debug ("----- RtpTest: Could not initialize pjsip memory pool ------"); + return PJ_ENOMEM; + } - return true; + return true; } void RtpTest::testRtpInitClose() { - _debug ("-------------------- RtpTest::testRtpInitClose --------------------\n"); + _debug ("-------------------- RtpTest::testRtpInitClose --------------------\n"); - audiortp = new AudioRtpFactory(); + audiortp = new AudioRtpFactory(); - try { - _debug ("-------- Open Rtp Session ----------"); - audiortp->initAudioRtpConfig(sipcall); - audiortp->initAudioRtpSession(sipcall); - //AudioCodecType codecType = PAYLOAD_CODEC_ULAW; - //AudioCodec* audioCodec = Manager::instance().getCodecDescriptorMap().instantiateCodec(codecType); - //audiortp->start(audioCodec); + try { + _debug ("-------- Open Rtp Session ----------"); + audiortp->initAudioRtpConfig (sipcall); + audiortp->initAudioRtpSession (sipcall); + //AudioCodecType codecType = PAYLOAD_CODEC_ULAW; + //AudioCodec* audioCodec = Manager::instance().getCodecDescriptorMap().instantiateCodec(codecType); + //audiortp->start(audioCodec); - } catch (...) { - _debug ("!!! Exception occured while Oppenning Rtp !!!"); - CPPUNIT_ASSERT(false); + } catch (...) { + _debug ("!!! Exception occured while Oppenning Rtp !!!"); + CPPUNIT_ASSERT (false); - } + } - CPPUNIT_ASSERT (audiortp != NULL); + CPPUNIT_ASSERT (audiortp != NULL); - sleep(1); + sleep (1); - _debug ("------ RtpTest::testRtpClose() ------"); + _debug ("------ RtpTest::testRtpClose() ------"); - try { - _debug ("------ Close Rtp Session -------"); - audiortp->stop(); + try { + _debug ("------ Close Rtp Session -------"); + audiortp->stop(); - } catch (...) { + } catch (...) { - _debug ("!!! Exception occured while closing Rtp !!!"); - CPPUNIT_ASSERT(false); + _debug ("!!! Exception occured while closing Rtp !!!"); + CPPUNIT_ASSERT (false); - } + } - delete audiortp; + delete audiortp; - audiortp = NULL; + audiortp = NULL; } void RtpTest::tearDown() { - delete sipcall; - sipcall = NULL; + delete sipcall; + sipcall = NULL; } diff --git a/sflphone-common/test/sdesnegotiatortest.cpp b/sflphone-common/test/sdesnegotiatortest.cpp index 6a873613f29b59d4fdebf32b15e4c30c9c4724fe..e85b90559af973e31c3884d1befd4b6cd15a17e6 100644 --- a/sflphone-common/test/sdesnegotiatortest.cpp +++ b/sflphone-common/test/sdesnegotiatortest.cpp @@ -49,87 +49,83 @@ using std::cout; using std::endl; -void SdesNegotiatorTest::testTagPattern() -{ - _debug ("-------------------- SdesNegotiatorTest::testTagPattern --------------------\n"); +void SdesNegotiatorTest::testTagPattern() { + _debug ("-------------------- SdesNegotiatorTest::testTagPattern --------------------\n"); - std::string subject = "a=crypto:4"; + std::string subject = "a=crypto:4"; - pattern = new sfl::Pattern("^a=crypto:(?P<tag>[0-9]{1,9})"); + pattern = new sfl::Pattern ("^a=crypto:(?P<tag>[0-9]{1,9})"); *pattern << subject; - CPPUNIT_ASSERT(pattern->matches()); - CPPUNIT_ASSERT(pattern->group("tag").compare("4") == 0); + CPPUNIT_ASSERT (pattern->matches()); + CPPUNIT_ASSERT (pattern->group ("tag").compare ("4") == 0); delete pattern; pattern = NULL; } -void SdesNegotiatorTest::testCryptoSuitePattern() -{ - _debug ("-------------------- SdesNegotiatorTest::testCryptoSuitePattern --------------------\n"); +void SdesNegotiatorTest::testCryptoSuitePattern() { + _debug ("-------------------- SdesNegotiatorTest::testCryptoSuitePattern --------------------\n"); - std::string subject = "AES_CM_128_HMAC_SHA1_80"; + std::string subject = "AES_CM_128_HMAC_SHA1_80"; - pattern = new sfl::Pattern("(?P<cryptoSuite>AES_CM_128_HMAC_SHA1_80|" \ - "AES_CM_128_HMAC_SHA1_32|" \ - "F8_128_HMAC_SHA1_80|" \ - "[A-Za-z0-9_]+)"); + pattern = new sfl::Pattern ("(?P<cryptoSuite>AES_CM_128_HMAC_SHA1_80|" \ + "AES_CM_128_HMAC_SHA1_32|" \ + "F8_128_HMAC_SHA1_80|" \ + "[A-Za-z0-9_]+)"); *pattern << subject; - CPPUNIT_ASSERT(pattern->matches()); - CPPUNIT_ASSERT(pattern->group("cryptoSuite").compare("AES_CM_128_HMAC_SHA1_80") == 0); + CPPUNIT_ASSERT (pattern->matches()); + CPPUNIT_ASSERT (pattern->group ("cryptoSuite").compare ("AES_CM_128_HMAC_SHA1_80") == 0); delete pattern; pattern = NULL; } -void SdesNegotiatorTest::testKeyParamsPattern() -{ - _debug ("-------------------- SdesNegotiatorTest::testKeyParamsPattern --------------------\n"); +void SdesNegotiatorTest::testKeyParamsPattern() { + _debug ("-------------------- SdesNegotiatorTest::testKeyParamsPattern --------------------\n"); std::string subject = "inline:d0RmdmcmVCspeEc3QGZiNWpVLFJhQX1cfHAwJSoj|2^20|1:32"; - pattern = new sfl::Pattern("(?P<srtpKeyMethod>inline|[A-Za-z0-9_]+)\\:" \ - "(?P<srtpKeyInfo>[A-Za-z0-9\x2B\x2F\x3D]+)\\|" \ - "(2\\^(?P<lifetime>[0-9]+)\\|" \ - "(?P<mkiValue>[0-9]+)\\:" \ - "(?P<mkiLength>[0-9]{1,3})\\;?)?", "g"); + pattern = new sfl::Pattern ("(?P<srtpKeyMethod>inline|[A-Za-z0-9_]+)\\:" \ + "(?P<srtpKeyInfo>[A-Za-z0-9\x2B\x2F\x3D]+)\\|" \ + "(2\\^(?P<lifetime>[0-9]+)\\|" \ + "(?P<mkiValue>[0-9]+)\\:" \ + "(?P<mkiLength>[0-9]{1,3})\\;?)?", "g"); *pattern << subject; pattern->matches(); - CPPUNIT_ASSERT(pattern->group("srtpKeyMethod").compare("inline:")); - CPPUNIT_ASSERT(pattern->group("srtpKeyInfo").compare("d0RmdmcmVCspeEc3QGZiNWpVLFJhQX1cfHAwJSoj") -== 0); - CPPUNIT_ASSERT(pattern->group("lifetime").compare("20")== 0); - CPPUNIT_ASSERT(pattern->group("mkiValue").compare("1")== 0); - CPPUNIT_ASSERT(pattern->group("mkiLength").compare("32")== 0); + CPPUNIT_ASSERT (pattern->group ("srtpKeyMethod").compare ("inline:")); + CPPUNIT_ASSERT (pattern->group ("srtpKeyInfo").compare ("d0RmdmcmVCspeEc3QGZiNWpVLFJhQX1cfHAwJSoj") + == 0); + CPPUNIT_ASSERT (pattern->group ("lifetime").compare ("20") == 0); + CPPUNIT_ASSERT (pattern->group ("mkiValue").compare ("1") == 0); + CPPUNIT_ASSERT (pattern->group ("mkiLength").compare ("32") == 0); delete pattern; pattern = NULL; } -void SdesNegotiatorTest::testKeyParamsPatternWithoutMKI() -{ - _debug ("-------------------- SdesNegotiatorTest::testKeyParamsPatternWithoutMKI --------------------\n"); +void SdesNegotiatorTest::testKeyParamsPatternWithoutMKI() { + _debug ("-------------------- SdesNegotiatorTest::testKeyParamsPatternWithoutMKI --------------------\n"); std::string subject = "inline:d0RmdmcmVCspeEc3QGZiNWpVLFJhQX1cfHAwJSoj"; - pattern = new sfl::Pattern("(?P<srtpKeyMethod>inline|[A-Za-z0-9_]+)\\:" \ - "(?P<srtpKeyInfo>[A-Za-z0-9\x2B\x2F\x3D]+)" \ - "(\\|2\\^(?P<lifetime>[0-9]+)\\|" \ - "(?P<mkiValue>[0-9]+)\\:" \ - "(?P<mkiLength>[0-9]{1,3})\\;?)?", "g"); + pattern = new sfl::Pattern ("(?P<srtpKeyMethod>inline|[A-Za-z0-9_]+)\\:" \ + "(?P<srtpKeyInfo>[A-Za-z0-9\x2B\x2F\x3D]+)" \ + "(\\|2\\^(?P<lifetime>[0-9]+)\\|" \ + "(?P<mkiValue>[0-9]+)\\:" \ + "(?P<mkiLength>[0-9]{1,3})\\;?)?", "g"); *pattern << subject; pattern->matches(); - CPPUNIT_ASSERT(pattern->group("srtpKeyMethod").compare("inline:")); - CPPUNIT_ASSERT(pattern->group("srtpKeyInfo").compare("d0RmdmcmVCspeEc3QGZiNWpVLFJhQX1cfHAwJSoj") -== 0); + CPPUNIT_ASSERT (pattern->group ("srtpKeyMethod").compare ("inline:")); + CPPUNIT_ASSERT (pattern->group ("srtpKeyInfo").compare ("d0RmdmcmVCspeEc3QGZiNWpVLFJhQX1cfHAwJSoj") + == 0); delete pattern; pattern = NULL; @@ -138,26 +134,26 @@ void SdesNegotiatorTest::testKeyParamsPatternWithoutMKI() /** * Make sure that all the fields can be extracted - * properly from the syntax. + * properly from the syntax. */ -void SdesNegotiatorTest::testNegotiation() -{ - _debug ("-------------------- SdesNegotiatorTest::testNegotiation --------------------\n"); +void SdesNegotiatorTest::testNegotiation() { + _debug ("-------------------- SdesNegotiatorTest::testNegotiation --------------------\n"); - // Add a new SDES crypto line to be processed. + // Add a new SDES crypto line to be processed. remoteOffer = new std::vector<std::string>(); - remoteOffer->push_back(std::string("a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwd|2^20|1:32")); - remoteOffer->push_back(std::string("a=crypto:2 AES_CM_128_HMAC_SHA1_32 inline:NzB4d1BINUAvLEw6UzF3WSJ+PSdFcGdUJShpX1Zj|2^20|1:32")); - + remoteOffer->push_back (std::string ("a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwd|2^20|1:32")); + remoteOffer->push_back (std::string ("a=crypto:2 AES_CM_128_HMAC_SHA1_32 inline:NzB4d1BINUAvLEw6UzF3WSJ+PSdFcGdUJShpX1Zj|2^20|1:32")); + // Register the local capabilities. localCapabilities = new std::vector<sfl::CryptoSuiteDefinition>(); - for(int i = 0; i < 3; i++) { - localCapabilities->push_back(sfl::CryptoSuites[i]); + + for (int i = 0; i < 3; i++) { + localCapabilities->push_back (sfl::CryptoSuites[i]); } - sdesnego = new sfl::SdesNegotiator(*localCapabilities, *remoteOffer); + sdesnego = new sfl::SdesNegotiator (*localCapabilities, *remoteOffer); - CPPUNIT_ASSERT(sdesnego->negotiate()); + CPPUNIT_ASSERT (sdesnego->negotiate()); // CPPUNIT_ASSERT(sdesnego->getKeyInfo().compare("AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwd|2^20|1:32")==0); delete remoteOffer; @@ -173,26 +169,25 @@ void SdesNegotiatorTest::testNegotiation() /** * Make sure that unproperly formatted crypto lines are rejected. */ -void SdesNegotiatorTest::testComponent() -{ - _debug ("-------------------- SdesNegotiatorTest::testComponent --------------------\n"); +void SdesNegotiatorTest::testComponent() { + _debug ("-------------------- SdesNegotiatorTest::testComponent --------------------\n"); // Register the local capabilities. std::vector<sfl::CryptoSuiteDefinition> * capabilities = new std::vector<sfl::CryptoSuiteDefinition>(); - + //Support all the CryptoSuites - for(int i = 0; i < 3; i++) { - capabilities->push_back(sfl::CryptoSuites[i]); + for (int i = 0; i < 3; i++) { + capabilities->push_back (sfl::CryptoSuites[i]); } - + // Make sure that if a component is missing, negotiate will fail - std::string cryptoLine("a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:|2^20|1:32"); + std::string cryptoLine ("a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:|2^20|1:32"); std::vector<std::string> * cryptoOffer = new std::vector<std::string>(); - cryptoOffer->push_back(cryptoLine); + cryptoOffer->push_back (cryptoLine); - sfl::SdesNegotiator * negotiator = new sfl::SdesNegotiator(*capabilities, *cryptoOffer); + sfl::SdesNegotiator * negotiator = new sfl::SdesNegotiator (*capabilities, *cryptoOffer); - CPPUNIT_ASSERT(negotiator->negotiate() == false); + CPPUNIT_ASSERT (negotiator->negotiate() == false); } @@ -200,35 +195,37 @@ void SdesNegotiatorTest::testComponent() /** * Make sure that most simple case does not fail. */ -void SdesNegotiatorTest::testMostSimpleCase() -{ - _debug ("-------------------- SdesNegotiatorTest::testMostSimpleCase --------------------\n"); +void SdesNegotiatorTest::testMostSimpleCase() { + _debug ("-------------------- SdesNegotiatorTest::testMostSimpleCase --------------------\n"); // Register the local capabilities. std::vector<sfl::CryptoSuiteDefinition> * capabilities = new std::vector<sfl::CryptoSuiteDefinition>(); //Support all the CryptoSuites - for(int i = 0; i < 3; i++) { - capabilities->push_back(sfl::CryptoSuites[i]); + for (int i = 0; i < 3; i++) { + capabilities->push_back (sfl::CryptoSuites[i]); } // Make sure taht this case works (since it's default for most application) - std::string cryptoLine("a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwd"); + std::string cryptoLine ("a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwd"); std::vector<std::string> * cryptoOffer = new std::vector<std::string>(); - cryptoOffer->push_back(cryptoLine); + cryptoOffer->push_back (cryptoLine); - sfl::SdesNegotiator * negotiator = new sfl::SdesNegotiator(*capabilities, *cryptoOffer); + sfl::SdesNegotiator * negotiator = new sfl::SdesNegotiator (*capabilities, *cryptoOffer); - CPPUNIT_ASSERT(negotiator->negotiate() == true); + CPPUNIT_ASSERT (negotiator->negotiate() == true); - CPPUNIT_ASSERT(negotiator->getCryptoSuite().compare("AES_CM_128_HMAC_SHA1_80") == 0); - CPPUNIT_ASSERT(negotiator->getKeyMethod().compare("inline") == 0); - CPPUNIT_ASSERT(negotiator->getKeyInfo().compare("AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwd") == 0); - CPPUNIT_ASSERT(negotiator->getLifeTime().compare("")== 0); - CPPUNIT_ASSERT(negotiator->getMkiValue().compare("")== 0); - CPPUNIT_ASSERT(negotiator->getMkiLength().compare("")== 0); + CPPUNIT_ASSERT (negotiator->getCryptoSuite().compare ("AES_CM_128_HMAC_SHA1_80") == 0); + CPPUNIT_ASSERT (negotiator->getKeyMethod().compare ("inline") == 0); + CPPUNIT_ASSERT (negotiator->getKeyInfo().compare ("AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwd") == 0); + CPPUNIT_ASSERT (negotiator->getLifeTime().compare ("") == 0); + CPPUNIT_ASSERT (negotiator->getMkiValue().compare ("") == 0); + CPPUNIT_ASSERT (negotiator->getMkiLength().compare ("") == 0); - delete capabilities; capabilities = NULL; - delete cryptoOffer; cryptoOffer = NULL; - delete negotiator; negotiator = NULL; + delete capabilities; + capabilities = NULL; + delete cryptoOffer; + cryptoOffer = NULL; + delete negotiator; + negotiator = NULL; } diff --git a/sflphone-common/test/validator.cpp b/sflphone-common/test/validator.cpp index a12bad1714cebcbda861aa6261f13af8e1851e2f..bc4ee2038058705e65c2c2b025d4a35736749e5a 100644 --- a/sflphone-common/test/validator.cpp +++ b/sflphone-common/test/validator.cpp @@ -30,20 +30,22 @@ #include "validator.h" -bool Validator::isNumber(std::string str) { - unsigned int i = 0; - if (!str.empty() && (str[i] == '-' || str[i] == '+')) - i++; - return string::npos == str.find_first_not_of(".eE0123456789", i); +bool Validator::isNumber (std::string str) { + unsigned int i = 0; + + if (!str.empty() && (str[i] == '-' || str[i] == '+')) + i++; + + return string::npos == str.find_first_not_of (".eE0123456789", i); } -bool Validator::isNotNull(std::string str) { - if(!str.empty()) - return true; - else - return false; +bool Validator::isNotNull (std::string str) { + if (!str.empty()) + return true; + else + return false; } -bool Validator::isEqual(std::string str1, std::string str2) { - return str1.compare(str2) == 0; +bool Validator::isEqual (std::string str1, std::string str2) { + return str1.compare (str2) == 0; }