apps/conference/Conference.cpp
37abd537
 /*
  * Copyright (C) 2002-2003 Fhg Fokus
d46ba254
  * Copyright (C) 2007 Juha Heinanen (USE_MYSQL parts)
37abd537
  *
7dcb7e2a
  * This file is part of SEMS, a free SIP media server.
37abd537
  *
7dcb7e2a
  * SEMS is free software; you can redistribute it and/or modify
37abd537
  * it under the terms of the GNU General Public License as published by
  * the Free Software Foundation; either version 2 of the License, or
  * (at your option) any later version.
  *
  * For a license to use the sems software under conditions
  * other than those described here, or to purchase support for this
  * software, please contact iptel.org by e-mail at the following addresses:
  *    info@iptel.org
  *
7dcb7e2a
  * SEMS is distributed in the hope that it will be useful,
37abd537
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License 
  * along with this program; if not, write to the Free Software 
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  */
 
 #include "Conference.h"
 #include "AmUtils.h"
 #include "AmConfigReader.h"
 #include "AmConferenceStatus.h"
 #include "AmConfig.h"
 
9421bbe4
 #include "AmSessionContainer.h"
bbfe61da
 #include "AmMediaProcessor.h"
967dcefb
 #include "ampi/MonitoringAPI.h"
9421bbe4
 
37abd537
 #include "sems.h"
 #include "log.h"
 
c82fbdc5
 #ifdef USE_MYSQL
 #include <mysql++/mysql++.h>
 #include <stdio.h>
 #define DEFAULT_AUDIO_TABLE "default_audio"
 #define DOMAIN_AUDIO_TABLE "domain_audio"
 #define LONELY_USER_MSG "first_participant_msg"
3123aba1
 #define JOIN_SOUND "join_snd"
 #define DROP_SOUND "drop_snd"
c82fbdc5
 #endif
37abd537
 
c82fbdc5
 #define APP_NAME "conference"
 	
37abd537
 EXPORT_SESSION_FACTORY(ConferenceFactory,APP_NAME);
 
838f6357
 
 #ifdef WITH_SAS_TTS
 #define TTS_CACHE_PATH "/tmp/"
 extern "C" cst_voice *register_cmu_us_kal();
 #endif
 
37abd537
 ConferenceFactory::ConferenceFactory(const string& _app_name)
8d76c8bb
   : AmSessionFactory(_app_name)
37abd537
 {
 }
 
bb9f5a98
 string ConferenceFactory::AudioPath;
37abd537
 string ConferenceFactory::LonelyUserFile;
 string ConferenceFactory::JoinSound;
 string ConferenceFactory::DropSound;
9421bbe4
 string ConferenceFactory::DialoutSuffix;
f4d64a3d
 PlayoutType ConferenceFactory::m_PlayoutType = ADAPTIVE_PLAYOUT;
a3c88fe6
 unsigned int ConferenceFactory::MaxParticipants;
37abd537
 
cd701d1a
 bool ConferenceFactory::UseRFC4240Rooms;
a217168a
 AmConfigReader ConferenceFactory::cfg;
 AmSessionEventHandlerFactory* ConferenceFactory::session_timer_f = NULL;
cd701d1a
 
c82fbdc5
 #ifdef USE_MYSQL
 mysqlpp::Connection ConferenceFactory::Connection(mysqlpp::use_exceptions);
 
ec7e0030
 int get_audio_file(const string& message, const string& domain, const string& language,
27e3422d
 		   string& audio_file)
c82fbdc5
 {
8d76c8bb
   string query_string;
 
   if (language.empty()) {
     if (domain.empty()) {
27e3422d
       audio_file = string("/tmp/") + APP_NAME + "_" + message + ".wav";
8d76c8bb
       query_string = "select audio from " + string(DEFAULT_AUDIO_TABLE) + " where application='" + APP_NAME + "' and message='" + message + "' and language=''";
c82fbdc5
     } else {
27e3422d
       audio_file = "/tmp/" + domain + "_" + APP_NAME + "_" + 
8d76c8bb
 	message + ".wav";
       query_string = "select audio from " + string(DOMAIN_AUDIO_TABLE) + " where application='" + APP_NAME + "' and message='" + message + "' and domain='" + domain + "' and language=''";
     }
   } else {
     if (domain.empty()) {
27e3422d
       audio_file = "/tmp/" APP_NAME  "_" + message + "_" +
8d76c8bb
 	language + ".wav";
       query_string = "select audio from " + string(DEFAULT_AUDIO_TABLE) + " where application='" + APP_NAME + "' and message='" + message + "' and language='" + language + "'";
     } else {
27e3422d
       audio_file = "/tmp/" + domain + "_"  APP_NAME  "_" +
8d76c8bb
 	message + "_" +	language + ".wav";
       query_string = "select audio from " + string(DOMAIN_AUDIO_TABLE) + " where application='" + APP_NAME + "' and message='" + message + "' and domain='" + domain + "' and language='" + language + "'";
c82fbdc5
     }
8d76c8bb
   }
c82fbdc5
 
8d76c8bb
   try {
c82fbdc5
 
8d76c8bb
     mysqlpp::Query query = ConferenceFactory::Connection.query();
3123aba1
 	    
8d76c8bb
     DBG("Query string <%s>\n", query_string.c_str());
 
     query << query_string;
ffe99681
 
 #ifdef VERSION2
8d76c8bb
     mysqlpp::Result res = query.store();
ffe99681
 #else
     mysqlpp::StoreQueryResult res = query.store();
 #endif
8d76c8bb
 
     mysqlpp::Row row;
 
     if (res) {
       if ((res.num_rows() > 0) && (row = res.at(0))) {
 	FILE *file;
27e3422d
 	file = fopen(audio_file.c_str(), "wb");
ffe99681
 #ifdef VERSION2
 	unsigned long length = row.raw_string(0).size();
8d76c8bb
 	fwrite(row.at(0).data(), 1, length, file);
ffe99681
 #else
 	mysqlpp::String s = row[0];
 	fwrite(s.data(), 1, s.length(), file);
 #endif
8d76c8bb
 	fclose(file);
 	return 1;
       } else {
27e3422d
 	audio_file = "";
8d76c8bb
 	return 1;
       }
     } else {
       ERROR("Database query error\n");
27e3422d
       audio_file = "";
8d76c8bb
       return 0;
3123aba1
     }
8d76c8bb
   }
 
   catch (const mysqlpp::Exception& er) {
     // Catch-all for any MySQL++ exceptions
     ERROR("MySQL++ error: %s\n", er.what());
27e3422d
     audio_file = "";
8d76c8bb
     return 0;
   }
c82fbdc5
 }
 
3924478d
 #endif
 
37abd537
 int ConferenceFactory::onLoad()
 {
a393b55d
   if(cfg.loadFile(AmConfig::ModConfigPath + string(APP_NAME)+ ".conf")) {
     ERROR("Configuration file '%s' missing.\n",
 	  (AmConfig::ModConfigPath + string(APP_NAME)+ ".conf").c_str());
8d76c8bb
     return -1;
a393b55d
   }
37abd537
 
8d76c8bb
   // get application specific global parameters
   configureModule(cfg);
37abd537
 
c82fbdc5
 #ifdef USE_MYSQL
 
8d76c8bb
   /* Get default audio from MySQL */
c82fbdc5
 
8d76c8bb
   string mysql_server, mysql_user, mysql_passwd, mysql_db;
c82fbdc5
 
8d76c8bb
   mysql_server = cfg.getParameter("mysql_server");
   if (mysql_server.empty()) {
     mysql_server = "localhost";
   }
c82fbdc5
 
8d76c8bb
   mysql_user = cfg.getParameter("mysql_user");
   if (mysql_user.empty()) {
c30c0217
     ERROR("conference.conf parameter 'mysql_user' is missing.\n");
8d76c8bb
     return -1;
   }
c82fbdc5
 
8d76c8bb
   mysql_passwd = cfg.getParameter("mysql_passwd");
   if (mysql_passwd.empty()) {
c30c0217
     ERROR("conference.conf parameter 'mysql_passwd' is missing.\n");
8d76c8bb
     return -1;
   }
c82fbdc5
 
8d76c8bb
   mysql_db = cfg.getParameter("mysql_db");
   if (mysql_db.empty()) {
     mysql_db = "sems";
   }
c82fbdc5
 
8d76c8bb
   try {
c82fbdc5
 
ffe99681
 #ifdef VERSION2
18d97431
     Connection.set_option(Connection.opt_reconnect, true);
ffe99681
 #else
     Connection.set_option(new mysqlpp::ReconnectOption(true));
 #endif
8d76c8bb
     Connection.connect(mysql_db.c_str(), mysql_server.c_str(),
 		       mysql_user.c_str(), mysql_passwd.c_str());
     if (!Connection) {
       ERROR("Database connection failed: %s\n", Connection.error());
       return -1;
c82fbdc5
     }
8d76c8bb
   }
18d97431
 
   catch (const mysqlpp::BadOption& er) {
     ERROR("MySQL++ set_option error: %s\n", er.what());
     return -1;
   }
 
8d76c8bb
   catch (const mysqlpp::Exception& er) {
     // Catch-all for any MySQL++ exceptions
     ERROR("MySQL++ error: %s\n", er.what());
     return -1;
   }
 
27e3422d
   if (!get_audio_file(LONELY_USER_MSG, "", "", LonelyUserFile)) {
8d76c8bb
     return -1;
   }
 
   if (LonelyUserFile.empty()) {
     ERROR("default announce 'first_participant_msg'\n");
     ERROR("for module conference does not exist.\n");
     return -1;
   }
 
27e3422d
   if (!get_audio_file(JOIN_SOUND, "", "", JoinSound)) {
8d76c8bb
     return -1;
   }
 
27e3422d
   if (!get_audio_file(DROP_SOUND, "", "", DropSound)) {
8d76c8bb
     return -1;
   }
c82fbdc5
 
 #else 
 
8d76c8bb
   /* Get default audio from file system */
c82fbdc5
 
8d76c8bb
   AudioPath = cfg.getParameter("audio_path", ANNOUNCE_PATH);
bb9f5a98
 
8d76c8bb
   LonelyUserFile = cfg.getParameter("default_announce");
   if (LonelyUserFile.empty()) {
     LonelyUserFile = AudioPath + "/" ANNOUNCE_FILE;
   } else {
     if (LonelyUserFile[0] != '/') {
       LonelyUserFile = AudioPath + "/" + LonelyUserFile;
37abd537
     }
8d76c8bb
   }
   if(!file_exists(LonelyUserFile)){
     ERROR("default announce '%s' \n",LonelyUserFile.c_str());
     ERROR("for module conference does not exist.\n");
     return -1;
   }
37abd537
 
8d76c8bb
   JoinSound = cfg.getParameter("join_sound");
   if (!JoinSound.empty()) {
     if (JoinSound[0] != '/') {
       JoinSound = AudioPath + "/" + JoinSound;
bb9f5a98
     }
8d76c8bb
   }
bb9f5a98
 
8d76c8bb
   DropSound = cfg.getParameter("drop_sound");
   if (!DropSound.empty()) {
     if (DropSound[0] != '/') {
       DropSound = AudioPath + "/" + DropSound;
bb9f5a98
     }
8d76c8bb
   }
37abd537
 
c82fbdc5
 #endif
 	
8d76c8bb
   DialoutSuffix = cfg.getParameter("dialout_suffix");
   if(DialoutSuffix.empty()){
     WARN("No dialout_suffix has been configured in the conference plug-in:\n");
     WARN("\t -> dial out will not be available unless P-Dialout-Suffix\n");
     WARN("\t -> header parameter is passed to conference plug-in\n");
   }
a02bd125
     
8d76c8bb
   string playout_type = cfg.getParameter("playout_type");
   if (playout_type == "simple") {
     m_PlayoutType = SIMPLE_PLAYOUT;
     DBG("Using simple (fifo) buffer as playout technique.\n");
   } else 	if (playout_type == "adaptive_jb") {
     m_PlayoutType = JB_PLAYOUT;
     DBG("Using adaptive jitter buffer as playout technique.\n");
   } else {
     DBG("Using adaptive playout buffer as playout technique.\n");
   }
 
a3c88fe6
   MaxParticipants = 0;
   string max_participants = cfg.getParameter("max_participants");
   if (max_participants.length() && str2i(max_participants, MaxParticipants)) {
     ERROR("while parsing max_participants parameter\n"); 
   }
 
cd701d1a
   UseRFC4240Rooms = cfg.getParameter("use_rfc4240_rooms")=="yes";
   DBG("%ssing RFC4240 room naming.\n", UseRFC4240Rooms?"U":"Not u");
 
a217168a
   if(cfg.hasParameter("enable_session_timer") &&
      (cfg.getParameter("enable_session_timer") == string("yes")) ){
     DBG("enabling session timers\n");
     session_timer_f = AmPlugIn::instance()->getFactory4Seh("session_timer");
     if(session_timer_f == NULL){
       ERROR("Could not load the session_timer module: disabling session timers.\n");
     }
   }
 
8d76c8bb
   return 0;
37abd537
 }
 
81d73625
 AmSession* ConferenceFactory::onInvite(const AmSipRequest& req, const string& app_name,
 				       const map<string,string>& app_params)
37abd537
 {
a3c88fe6
   if ((ConferenceFactory::MaxParticipants > 0) &&
       (AmConferenceStatus::getConferenceSize(req.user) >=
       ConferenceFactory::MaxParticipants)) {
     DBG("Conference is full.\n");
     throw AmSession::Exception(486, "Busy Here");
   }
cd701d1a
 
   string conf_id=req.user;
 
   if (UseRFC4240Rooms) {
     // see RFC4240 5.  Conference Service
     if (req.user.length()<5)
       throw AmSession::Exception(404, "Not Found");
     
     if (req.user.substr(0,5)!="conf=")
       throw AmSession::Exception(404, "Not Found");
 
     conf_id = req.user.substr(5);
   }
 
a217168a
   ConferenceDialog* s = new ConferenceDialog(conf_id);
 
   setupSessionTimer(s);
 
   return s;
 }
 
 void ConferenceFactory::setupSessionTimer(AmSession* s) {
   if (NULL != session_timer_f) {
 
     AmSessionEventHandler* h = session_timer_f->getHandler(s);
     if (NULL == h)
       return;
 
     if(h->configure(cfg)){
       ERROR("Could not configure the session timer: disabling session timers.\n");
       delete h;
     } else {
       s->addHandler(h);
     }
   }
37abd537
 }
 
1f414020
 AmSession* ConferenceFactory::onRefer(const AmSipRequest& req, const string& app_name,
 				      const map<string,string>& app_params)
c75dd1ba
 {
8d76c8bb
   if(req.to_tag.empty())
     throw AmSession::Exception(488,"Not accepted here");
c75dd1ba
 
8d76c8bb
   AmSession* s = new ConferenceDialog(req.user);
fe76f843
   s->dlg->setLocalTag(req.from_tag);
a217168a
   
   setupSessionTimer(s);
c75dd1ba
 
fe76f843
   DBG("ConferenceFactory::onRefer: local_tag = %s\n",s->dlg->getLocalTag().c_str());
c75dd1ba
 
8d76c8bb
   return s;
c75dd1ba
 }
 
9421bbe4
 ConferenceDialog::ConferenceDialog(const string& conf_id,
 				   AmConferenceChannel* dialout_channel)
8d76c8bb
   : conf_id(conf_id), 
     channel(0),
     play_list(this),
     dialout_channel(dialout_channel),
     state(CS_normal),
     allow_dialout(false)
37abd537
 {
8d76c8bb
   dialedout = this->dialout_channel.get() != 0;
c6d9ae3b
   RTPStream()->setPlayoutType(ConferenceFactory::m_PlayoutType);
838f6357
 #ifdef WITH_SAS_TTS
   tts_voice = register_cmu_us_kal();
 #endif  
37abd537
 }
 
 ConferenceDialog::~ConferenceDialog()
 {
8d76c8bb
   DBG("ConferenceDialog::~ConferenceDialog()\n");
aee44c98
 
8d76c8bb
   // clean playlist items
4ac9c3f4
   play_list.flush();
838f6357
 
 #ifdef WITH_SAS_TTS
   // garbage collect tts files - TODO: delete files
   for (vector<AmAudioFile*>::iterator it =
 	 TTSFiles.begin();it!=TTSFiles.end();it++) {
     delete *it;
   }
 #endif
37abd537
 }
 
cd701d1a
 void ConferenceDialog::onStart() {
37abd537
 }
 
59307694
 void ConferenceDialog::onInvite(const AmSipRequest& req)
9421bbe4
 {
62fc8342
   if(dlg->getStatus() == AmSipDialog::Connected){
d3078a06
     AmSession::onInvite(req);  
59307694
     return;
d3078a06
   }
59307694
 
8d76c8bb
   int i, len;
   string lonely_user_file;
 
77853863
   string app_param_hdr = getHeader(req.hdrs, PARAM_HDR, true);
b72c4226
   string listen_only_str = "";
8d76c8bb
   if (app_param_hdr.length()) {
     from_header = get_header_keyvalue(app_param_hdr, "Dialout-From");
     extra_headers = get_header_keyvalue(app_param_hdr, "Dialout-Extra");
     dialout_suffix = get_header_keyvalue(app_param_hdr, "Dialout-Suffix");      
b72c4226
     language = get_header_keyvalue(app_param_hdr, "Language");
     listen_only_str = get_header_keyvalue(app_param_hdr, "Listen-Only");
8d76c8bb
   } else {
77853863
     from_header = getHeader(req.hdrs, "P-Dialout-From", true);
     extra_headers = getHeader(req.hdrs, "P-Dialout-Extra", true);
     dialout_suffix = getHeader(req.hdrs, "P-Dialout-Suffix", true);
8d76c8bb
     if (from_header.length() || extra_headers.length() 
 	|| dialout_suffix.length()) {
       DBG("Warning: P-Dialout- style headers are deprecated."
 	  " Please use P-App-Param header instead.\n");
     }
77853863
     language = getHeader(req.hdrs, "P-Language", true);
8d76c8bb
     if (language.length()) {
       DBG("Warning: P-Language header is deprecated."
 	  " Please use P-App-Param header instead.\n");
     }
   }
 
   len = extra_headers.length();
   for (i = 0; i < len; i++) {
     if (extra_headers[i] == '|') extra_headers[i] = '\n';
   }
d7c8b7f6
   if (extra_headers[len - 1] != '\n') {
       extra_headers += '\n';
   }
8d76c8bb
 
   if (dialout_suffix.length() == 0) {
     if (!ConferenceFactory::DialoutSuffix.empty()) {
       dialout_suffix = ConferenceFactory::DialoutSuffix;
a02bd125
     } else {
8d76c8bb
       dialout_suffix = "";
a02bd125
     }
8d76c8bb
   }
a02bd125
     
8d76c8bb
   allow_dialout = dialout_suffix.length() > 0;
bb9f5a98
 
b72c4226
   listen_only = listen_only_str.length() > 0;
 
8d76c8bb
   if (!language.empty()) {
c82fbdc5
 
 #ifdef USE_MYSQL
8d76c8bb
     /* Get domain/language specific lonely user file from MySQL */
     if (get_audio_file(LONELY_USER_MSG, req.domain, language,
27e3422d
 		       lonely_user_file) &&
8d76c8bb
 	!lonely_user_file.empty()) {
       ConferenceFactory::LonelyUserFile = lonely_user_file;
     } else {
       if (get_audio_file(LONELY_USER_MSG, "", language,
27e3422d
 			 lonely_user_file) &&
8d76c8bb
 	  !lonely_user_file.empty()) {
 	ConferenceFactory::LonelyUserFile = lonely_user_file;
       }
     }
c82fbdc5
 #else
8d76c8bb
     /* Get domain/language specific lonely user file from file system */
     lonely_user_file = ConferenceFactory::AudioPath + "/lonely_user_msg/" +
       req.domain + "/" + "default_" + language + ".wav";
     if(file_exists(lonely_user_file)) {
       ConferenceFactory::LonelyUserFile = lonely_user_file;
     } else {
       lonely_user_file = ConferenceFactory::AudioPath +
 	"/lonely_user_msg/default_" + language + ".wav";
       if(file_exists(lonely_user_file)) {
 	ConferenceFactory::LonelyUserFile = lonely_user_file;
       }
bb9f5a98
     }
8d76c8bb
 #endif
   }
c82fbdc5
 
8d76c8bb
   DBG("Using LonelyUserFile <%s>\n",
       ConferenceFactory::LonelyUserFile.c_str());
d5fcb56d
 
   AmSession::onInvite(req);  
9421bbe4
 }
 
59307694
 void ConferenceDialog::onSessionStart()
 {
   setupAudio();
d5fcb56d
 
   if(dialedout) {
     // send connect event
     AmSessionContainer::instance()
       ->postEvent(dialout_channel->getConfID(),
 		  new DialoutConfEvent(DoConfConnect,
 				       dialout_channel->getConfID()));
   }
 
26225816
   AmSession::onSessionStart();
59307694
 }
c75dd1ba
 
9421bbe4
 void ConferenceDialog::setupAudio()
37abd537
 {
8d76c8bb
   if(!ConferenceFactory::JoinSound.empty()) {
37abd537
 	
8d76c8bb
     JoinSound.reset(new AmAudioFile());
     if(JoinSound->open(ConferenceFactory::JoinSound,
 		       AmAudioFile::Read))
       JoinSound.reset(0);
   }
37abd537
 
8d76c8bb
   if(!ConferenceFactory::DropSound.empty()) {
37abd537
 	
8d76c8bb
     DropSound.reset(new AmAudioFile());
     if(DropSound->open(ConferenceFactory::DropSound,
 		       AmAudioFile::Read))
       DropSound.reset(0);
   }
37abd537
 
c75dd1ba
 
4ac9c3f4
   play_list.flush();
9421bbe4
 
8d76c8bb
   if(dialout_channel.get()){
9421bbe4
 
8d76c8bb
     DBG("adding dialout_channel to the playlist (dialedout = %i)\n",dialedout);
b72c4226
     if (listen_only)
 	play_list.addToPlaylist(new AmPlaylistItem(dialout_channel.get(),
 						   (AmAudio*)NULL));
     else
 	play_list.addToPlaylist(new AmPlaylistItem(dialout_channel.get(),
 						   dialout_channel.get()));
8d76c8bb
   }
   else {
9421bbe4
 
440323b8
     channel.reset(AmConferenceStatus::getChannel(conf_id,getLocalTag(),RTPStream()->getSampleRate()));
37abd537
 
b72c4226
     if (listen_only) {
 	play_list.addToPlaylist(new AmPlaylistItem(channel.get(),
 						   (AmAudio*)NULL));
     }
     else
 	play_list.addToPlaylist(new AmPlaylistItem(channel.get(),
 						   channel.get()));
8d76c8bb
   }
37abd537
 
8d76c8bb
   setInOut(&play_list,&play_list);
37abd537
     
8d76c8bb
   setCallgroup(conf_id);
967dcefb
   
7fb993dc
   MONITORING_LOG(getLocalTag().c_str(), "conf_id", conf_id.c_str());
05a10535
 	
8d76c8bb
   if(dialedout || !allow_dialout) {
     DBG("Dialout not enabled or dialout channel. Disabling DTMF detection.\n");
     setDtmfDetectionEnabled(false);
   }
37abd537
 }
 
 void ConferenceDialog::onBye(const AmSipRequest& req)
 {
8d76c8bb
   if(dialout_channel.get())
     disconnectDialout();
9421bbe4
 
8d76c8bb
   closeChannels();
   setStopped();
37abd537
 }
 
 void ConferenceDialog::process(AmEvent* ev)
 {
8d76c8bb
   ConferenceEvent* ce = dynamic_cast<ConferenceEvent*>(ev);
   if(ce && (conf_id == ce->conf_id)){
     switch(ce->event_id){
     case ConfNewParticipant:
37abd537
 
8d76c8bb
       DBG("########## new participant #########\n");
       if((ce->participants == 1) && 
 	 !ConferenceFactory::LonelyUserFile.empty() ){
37abd537
 
8d76c8bb
 	if(!LonelyUserFile.get()){
37abd537
 			
8d76c8bb
 	  LonelyUserFile.reset(new AmAudioFile());
 	  if(LonelyUserFile->open(ConferenceFactory::LonelyUserFile,
 				  AmAudioFile::Read))
 	    LonelyUserFile.reset(0);
 	}
37abd537
 		
8d76c8bb
 	if(LonelyUserFile.get())
 	  play_list.addToPlayListFront(
 				       new AmPlaylistItem( LonelyUserFile.get(), NULL ));
       }
       else {
37abd537
 		
8d76c8bb
 	if(JoinSound.get()){
 	  JoinSound->rewind();
 	  play_list.addToPlayListFront(
 				       new AmPlaylistItem( JoinSound.get(), NULL ));
37abd537
 	}
8d76c8bb
       }
 		
       break;
     case ConfParticipantLeft:
       DBG("########## participant left the room #########\n");
       if(DropSound.get()){
 	DropSound->rewind();
 	play_list.addToPlayListFront(
 				     new AmPlaylistItem( DropSound.get(), NULL ));
       }
       break;
     default:
       break;
37abd537
     }
8d76c8bb
     return;
   }
37abd537
 
8d76c8bb
   DialoutConfEvent* do_ev = dynamic_cast<DialoutConfEvent*>(ev);
   if(do_ev){
9421bbe4
 
8d76c8bb
     if(dialedout){
9421bbe4
 
8d76c8bb
       switch(do_ev->event_id){
9421bbe4
 
8d76c8bb
       case DoConfConnect:
9421bbe4
 
8d76c8bb
 	connectMainChannel();
 	break;
9421bbe4
 	
8d76c8bb
       case DoConfDisconnect:
9421bbe4
 		
62fc8342
 	dlg->bye();
8d76c8bb
 	closeChannels();
 	setStopped();
 	break;
 
       default:
 	break;
       }
     }
     else {
9421bbe4
 	    
8d76c8bb
       switch(do_ev->event_id){
9421bbe4
 
8d76c8bb
       case DoConfDisconnect:
9421bbe4
 
8d76c8bb
 	DBG("****** Caller received DoConfDisconnect *******\n");
 	connectMainChannel();
 	state = CS_normal;
 	break;
9421bbe4
 
8d76c8bb
       case DoConfConnect:
9421bbe4
 
8d76c8bb
 	state = CS_dialout_connected;
c75dd1ba
 
4ac9c3f4
 	play_list.flush();
8d76c8bb
 	play_list.addToPlaylist(new AmPlaylistItem(dialout_channel.get(),
 						   dialout_channel.get()));
 	break;
c75dd1ba
 
8d76c8bb
       case DoConfRinging:
c75dd1ba
 		
8d76c8bb
 	if(!RingTone.get())
 	  RingTone.reset(new AmRingTone(0,2000,4000,440,480)); // US
c75dd1ba
 
8d76c8bb
 	DBG("adding ring tone to the playlist (dialedout = %i)\n",dialedout);
4ac9c3f4
 	play_list.flush();
8d76c8bb
 	play_list.addToPlaylist(new AmPlaylistItem(RingTone.get(),NULL));
 	break;
c75dd1ba
 
8d76c8bb
       case DoConfError:
c75dd1ba
 		
8d76c8bb
 	DBG("****** Caller received DoConfError *******\n");
 	if(!ErrorTone.get())
 	  ErrorTone.reset(new AmRingTone(2000,250,250,440,480));
9421bbe4
 
8d76c8bb
 	DBG("adding error tone to the playlist (dialedout = %i)\n",dialedout);
 	play_list.addToPlayListFront(new AmPlaylistItem(ErrorTone.get(),NULL));
 	break;
 		
       }
9421bbe4
     }
 
8d76c8bb
     return;
   }
 
   AmSession::process(ev);
37abd537
 }
9421bbe4
 
 string dtmf2str(int event)
 {
8d76c8bb
   switch(event){
   case 0: case 1: case 2:
   case 3: case 4: case 5:
   case 6: case 7: case 8:
   case 9:
     return int2str(event);
9421bbe4
 	
8d76c8bb
   case 10: return "*";
   case 11: return "#";
   default: return "";
   }
9421bbe4
 }
 
c75dd1ba
 
9421bbe4
 void ConferenceDialog::onDtmf(int event, int duration)
 {
8d76c8bb
   DBG("ConferenceDialog::onDtmf\n");
a3c88fe6
   if (dialedout || !allow_dialout ||
       ((ConferenceFactory::MaxParticipants > 0) &&
fe76f843
        (AmConferenceStatus::getConferenceSize(dlg->getUser()) >= 
a3c88fe6
 	ConferenceFactory::MaxParticipants)))
8d76c8bb
     return;
9421bbe4
 
8d76c8bb
   switch(state){
9421bbe4
 	
8d76c8bb
   case CS_normal:
     DBG("CS_normal\n");
     dtmf_seq += dtmf2str(event);
 
     if(dtmf_seq.length() == 2){
838f6357
 
 #ifdef WITH_SAS_TTS
       if((dtmf_seq == "##") && !last_sas.empty()) {
 	sayTTS(last_sas);
 	dtmf_seq = "";
       }
 #endif
 
8d76c8bb
       if(dtmf_seq == "#*") {
 	state = CS_dialing_out;
 	dtmf_seq = "";
       } else {
 	// keep last digit
 	dtmf_seq = dtmf_seq[1]; 
       }
     }
     break;
 
   case CS_dialing_out:{
     DBG("CS_dialing_out\n");
     string digit = dtmf2str(event);
 
     if(digit == "*"){
9421bbe4
 	    
8d76c8bb
       if(!dtmf_seq.empty()){
 	createDialoutParticipant(dtmf_seq);
 	state = CS_dialed_out;
       }
       else {
 	DBG("state = CS_normal; ????????\n");
 	state = CS_normal;
       }
9421bbe4
 
8d76c8bb
       dtmf_seq = "";
     }
     else 
       dtmf_seq += digit;
9421bbe4
 
8d76c8bb
   } break;
9421bbe4
 
 
8d76c8bb
   case CS_dialout_connected:
     DBG("CS_dialout_connected\n");
     if(event == 10){ // '*'
9421bbe4
 
8d76c8bb
       AmSessionContainer::instance()
 	->postEvent(dialout_id,
 		    new DialoutConfEvent(DoConfConnect,
 					 getLocalTag()));
9421bbe4
 
8d76c8bb
       connectMainChannel();
       state = CS_normal;
9421bbe4
     }
8d76c8bb
 
   case CS_dialed_out:
     DBG("CS_dialed_out\n");
     if(event == 11){ // '#'
       disconnectDialout();
       state = CS_normal;
     }
     break;
 	
   }
9421bbe4
 }
 
c75dd1ba
 void ConferenceDialog::createDialoutParticipant(const string& uri_user)
9421bbe4
 {
8d76c8bb
   string uri;
a02bd125
 
8d76c8bb
   uri = "sip:" + uri_user + dialout_suffix;
c75dd1ba
 
440323b8
   dialout_channel.reset(AmConferenceStatus::getChannel(getLocalTag(),getLocalTag(),RTPStream()->getSampleRate()));
9421bbe4
 
8d76c8bb
   dialout_id = AmSession::getNewId();
9421bbe4
     
8d76c8bb
   ConferenceDialog* dialout_session = 
     new ConferenceDialog(conf_id,
 			 AmConferenceStatus::getChannel(getLocalTag(),
440323b8
 							dialout_id,RTPStream()->getSampleRate()));
9421bbe4
 
a217168a
   ConferenceFactory::setupSessionTimer(dialout_session);
 
62fc8342
   AmSipDialog* dialout_dlg = dialout_session->dlg;
9421bbe4
 
fe76f843
   dialout_dlg->setLocalTag(dialout_id);
   dialout_dlg->setCallid(AmSession::getNewId());
9421bbe4
 
8d76c8bb
   if (from_header.length() > 0) {
fe76f843
     dialout_dlg->setLocalParty(from_header);
8d76c8bb
   } else {
fe76f843
     dialout_dlg->setLocalParty(dlg->getLocalParty());
8d76c8bb
   }
fe76f843
   dialout_dlg->setRemoteParty(uri);
   dialout_dlg->setRemoteUri(uri);
9421bbe4
 
62fc8342
   dialout_dlg->sendRequest(SIP_METH_INVITE,NULL,
40db2c5a
 			  extra_headers);
9421bbe4
 
8d76c8bb
   dialout_session->start();
9421bbe4
 
8d76c8bb
   AmSessionContainer* sess_cont = AmSessionContainer::instance();
   sess_cont->addSession(dialout_id,dialout_session);
9421bbe4
 }
 
 void ConferenceDialog::disconnectDialout()
 {
8d76c8bb
   if(dialedout){
9421bbe4
 	
8d76c8bb
     if(dialout_channel.get()){
9421bbe4
 	    
8d76c8bb
       AmSessionContainer::instance()
 	->postEvent(dialout_channel->getConfID(),
 		    new DialoutConfEvent(DoConfDisconnect,
 					 dialout_channel->getConfID()));
     }
   }
   else {
 
     AmSessionContainer::instance()
       ->postEvent(dialout_id,
 		  new DialoutConfEvent(DoConfDisconnect,
 				       getLocalTag()));
c75dd1ba
     
8d76c8bb
     connectMainChannel();
   }
9421bbe4
 }
 
 void ConferenceDialog::connectMainChannel()
 {
8d76c8bb
   dialout_id = "";
   dialedout = false;
   dialout_channel.reset(NULL);
9421bbe4
     
4ac9c3f4
   play_list.flush();
9421bbe4
 
8d76c8bb
   if(!channel.get())
     channel.reset(AmConferenceStatus
 		  ::getChannel(conf_id,
440323b8
 			       getLocalTag(),RTPStream()->getSampleRate()));
9421bbe4
 
8d76c8bb
   play_list.addToPlaylist(new AmPlaylistItem(channel.get(),
 					     channel.get()));
9421bbe4
 }
 
 void ConferenceDialog::closeChannels()
 {
4ac9c3f4
   play_list.flush();
8d76c8bb
   setInOut(NULL,NULL);
   channel.reset(NULL);
   dialout_channel.reset(NULL);
9421bbe4
 }
 
c75dd1ba
 void ConferenceDialog::onSipRequest(const AmSipRequest& req)
 {
8d76c8bb
   AmSession::onSipRequest(req);
62fc8342
   if((dlg->getStatus() >= AmSipDialog::Connected) ||
8d76c8bb
      (req.method != "REFER"))
     return;
fa35cb1c
 
a9bc1d40
   string local_party(dlg->getLocalParty());
   dlg->setLocalParty(dlg->getRemoteParty());
   dlg->setRemoteParty(local_party);
   dlg->setRemoteTag("");
c75dd1ba
 
8d76c8bb
   // get route set and next hop
77853863
   string iptel_app_param = getHeader(req.hdrs, PARAM_HDR, true);
8d76c8bb
   if (iptel_app_param.length()) {
a9bc1d40
     dlg->setRouteSet(get_header_keyvalue(iptel_app_param,"Transfer-RR"));
8d76c8bb
   } else {
     INFO("Use of P-Transfer-RR/P-Transfer-NH is deprecated. "
 	 "Use '%s: Transfer-RR=<rr>;Transfer-NH=<nh>' instead.\n",PARAM_HDR);
c75dd1ba
 
a9bc1d40
     dlg->setRouteSet(getHeader(req.hdrs,"P-Transfer-RR", true));
8d76c8bb
   }
c75dd1ba
 
fe76f843
   DBG("ConferenceDialog::onSipRequest: local_party = %s\n",dlg->getLocalParty().c_str());
   DBG("ConferenceDialog::onSipRequest: local_tag = %s\n",dlg->getLocalTag().c_str());
   DBG("ConferenceDialog::onSipRequest: remote_party = %s\n",dlg->getRemoteParty().c_str());
   DBG("ConferenceDialog::onSipRequest: remote_tag = %s\n",dlg->getRemoteTag().c_str());
c75dd1ba
 
62fc8342
   dlg->sendRequest(SIP_METH_INVITE);
8d76c8bb
 
   transfer_req.reset(new AmSipRequest(req));
 
   return;
c75dd1ba
 }
 
6b4b3cc7
 void ConferenceDialog::onSipReply(const AmSipRequest& req,
 				  const AmSipReply& reply, 
 				  AmBasicSipDialog::Status old_dlg_status)
9421bbe4
 {
6b4b3cc7
   AmSession::onSipReply(req, reply, old_dlg_status);
c75dd1ba
 
8d76c8bb
   DBG("ConferenceDialog::onSipReply: code = %i, reason = %s\n, status = %i\n",
62fc8342
       reply.code,reply.reason.c_str(),dlg->getStatus());
9421bbe4
     
d5fcb56d
   if(!dialedout /*&& !transfer_req.get()*/)
8d76c8bb
     return;
c75dd1ba
 
d5fcb56d
   if((old_dlg_status < AmSipDialog::Connected) &&
      (reply.cseq_method == SIP_METH_INVITE)){
9421bbe4
 
62fc8342
     switch(dlg->getStatus()){
9421bbe4
 
d5fcb56d
     case AmSipDialog::Proceeding:
     case AmSipDialog::Early:
8d76c8bb
 
       switch(reply.code){
       case 180:
d5fcb56d
       case 183: break;//TODO: remote ring tone.
8d76c8bb
 
d5fcb56d
 	if(dialout_channel.get()){
 	  // send ringing event
 	  AmSessionContainer::instance()
 	    ->postEvent(dialout_channel->getConfID(),
 			new DialoutConfEvent(DoConfRinging,
 					     dialout_channel->getConfID()));
 	}
c75dd1ba
 		
8d76c8bb
 	break;
       default:  break;// continue waiting.
       }
       break;
c75dd1ba
 
8d76c8bb
     case AmSipDialog::Disconnected:
c75dd1ba
 
d5fcb56d
       // if(!transfer_req.get()){
       
       if(dialout_channel.get()){
8d76c8bb
 	disconnectDialout();
 	AmSessionContainer::instance()
 	  ->postEvent(dialout_channel->getConfID(),
 		      new DialoutConfEvent(DoConfError,
 					   dialout_channel->getConfID()));
       }
d5fcb56d
       setStopped();
 
       // }
       // else {
62fc8342
       // 	dlg->reply(*(transfer_req.get()),reply.code,reply.reason);
d5fcb56d
       // 	transfer_req.reset(0);
       // 	setStopped();
       // }
8d76c8bb
       break;
c75dd1ba
 
8d76c8bb
     default: break;
     }
   }
9421bbe4
 }
 
838f6357
 #ifdef WITH_SAS_TTS
 void ConferenceDialog::onZRTPEvent(zrtp_event_t event, zrtp_stream_ctx_t *stream_ctx) {
   DBG("ZrtpConferenceDialog::onZRTPEvent \n");
 
   switch (event) {
   case ZRTP_EVENT_IS_SECURE: {
     INFO("ZRTP_EVENT_IS_SECURE \n");
     //         info->is_verified  = ctx->_session_ctx->secrets.verifieds & ZRTP_BIT_RS0;
     
     zrtp_conn_ctx_t *session = stream_ctx->_session_ctx;
     
     string tts_sas = "My SAS is ";
     
     if (ZRTP_SAS_BASE32 == session->sas_values.rendering) {
       DBG("Got SAS value <<<%.4s>>>\n", session->sas_values.str1.buffer);
       tts_sas += session->sas_values.str1.buffer;
     } else {
       DBG("Got SAS values SAS1 '%s' and SAS2 '%s'\n", 
 	  session->sas_values.str1.buffer,
 	  session->sas_values.str2.buffer);
       tts_sas += session->sas_values.str1.buffer + string(" and ") + 
 	session->sas_values.str2.buffer + ".";
     }
     
     sayTTS(tts_sas);
     return;
   } break;
   default: break;
   } 
   AmSession::onZRTPEvent(event, stream_ctx);  
 }
 
 void ConferenceDialog::sayTTS(string text) {
 
   string filename = string(TTS_CACHE_PATH) + text /* AmSession::getNewId() */
     + string(".wav");
 
   last_sas = text;
   flite_text_to_speech(text.c_str(),tts_voice,filename.c_str());
   
   AmAudioFile* af = new AmAudioFile();
   if(!af->open(filename.c_str(), AmAudioFile::Read)) {
     play_list.addToPlayListFront(new AmPlaylistItem(af, NULL));
     TTSFiles.push_back(af);
   } else {
     ERROR("ERROR reading TTSed file %s\n", filename.c_str());
     delete af;
   }
 }
 
 #endif // WITH_SAS_TTS