与普通的pj媒体应用程序不同,此程序将绕过pj媒体的流框架,利用自己的线程手工处理RTP包。活动图如下:
//用法
static constchar*USAGE =
" 作用: \n"
" 此程序创建SIP INVITE会话和媒体,并计算媒体质量(丢包、jitter、rtt等) \n"
" 与普通的pj媒体应用程序不同,此程序将绕过pj媒体的流框架 \n"
" 利用自己的线程手工处理RTP包 \n"
"\n"
" 用法:\n"
" siprtp [options] => 以服务模式启动\n"
" siprtp [options] URL => 以客户模式启动\n"
"\n"
" 程序选项:\n"
" --count=N, -c 设置要创建呼叫数目 (缺省:1) \n"
" --gap=N -g 设置呼叫间隙到N毫秒 (缺省:0)\n"
" --duration=SEC, -d 设置最大的呼叫持续时间 (缺省:不限制) \n"
" --auto-quit, -q 当呼叫完成时是否退出(缺省:否)\n"
" --call-report -R 显示呼叫终止报告否 (缺省:是)\n"
"\n"
" 地址和端口选项\n"
" --local-port=PORT,-p 设置本地SIP端口(缺省: 5060)\n"
" --rtp-port=PORT, -r 设置RTP的开始端口 (缺省: 4000)\n"
" --ip-addr=IP, -i Set local IP address to use (otherwise itwill\n"
" try to determinelocal IP address from hostname)\n"
"\n"
" 日志选项:\n"
" --log-level=N, -l 设置日志冗长级别 (缺省=5)\n"
" --app-log-level=N 设置应用日志冗长级别 (缺省=3)\n"
" --log-file=FILE 写日志到文件 FILE\n"
" --report-file=FILE 写报告到文件 FILE\n"
"\n"
/* Don't support this anymore, because codec isproperly examined in
pjmedia_session_info_from_sdp() function.
" Codec Options:\n"
" --a-pt=PT Set audiopayload type to PT (default=0)\n"
" --a-name=NAME Set audiocodec name to NAME (default=pcmu)\n"
" --a-clock=RATE Set audiocodec rate to RATE Hz (default=8000Hz)\n"
" --a-bitrate=BPS Set audiocodec bitrate to BPS (default=64000bps)\n"
" --a-ptime=MS Set audioframe time to MS msec (default=20ms)\n"
*/
;
//包括的头文件
#include <pjsip.h>
#include <pjmedia.h>
#include <pjmedia-codec.h>
#include <pjsip_ua.h>
#include <pjsip_simple.h>
#include <pjlib-util.h>
#include <pjlib.h>
#include <stdlib.h>
//如果禁用多线程,请解开以下注释
//注意:如果禁用多线程,则siprtp将不能传输RTP包
/*
#undef PJ_HAS_THREADS
#define PJ_HAS_THREADS 0
*/
#if PJ_HAS_HIGH_RES_TIMER==0
# error"High resolution timer is needed for this sample"
#endif
#define THIS_FILE "siprtp.c"
#define MAX_CALLS 1024
#define RTP_START_PORT 4000
// 编解码器描述:
struct codec
{
unsigned pt;
char* name;
unsigned clock_rate;
unsigned bit_rate;
unsigned ptime;
char* description;
};
//当呼叫可用时,创建双向媒体流
struct media_stream
{
//静态
unsigned call_index; //呼叫所有者
unsigned media_index; //呼叫中的媒体索引
pjmedia_transport *transport; //用于发送/接收RTP/RTCP
//是否活动
pj_bool_t active; //如果在呼叫中,则为非零值
//当前流信息
pjmedia_stream_info si; //当前流信息
//更多信息
unsigned clock_rate; //时钟速率
unsigned samples_per_frame; //每帧采样
unsigned bytes_per_frame; //帧大小
//RTP会话
pjmedia_rtp_session out_sess; //呼出 RTP 会话
pjmedia_rtp_session in_sess; //呼入 RTP 会话
//RTCP状态
pjmedia_rtcp_session rtcp; //呼入 RTCP会话
//线程
pj_bool_t thread_quit_flag; //停止媒体线程否
pj_thread_t *thread; //媒体线程
};
//当应用程序启动时,下面的呼叫结构被创建。当应用程序退出时,结构被销毁
struct call
{
unsigned index;
pjsip_inv_session *inv;
unsigned media_count;
structmedia_stream media[1];
pj_time_val start_time;
pj_time_val response_time;
pj_time_val connect_time;
pj_timer_entry d_timer; //断开定时
};
//应用程序用到的全局变量
static structapp
{
unsigned max_calls;
unsigned call_gap;
pj_bool_t call_report;
unsigned uac_calls;
unsigned duration;
pj_bool_t auto_quit;
unsigned thread_count;
int sip_port;
int rtp_start_port;
pj_str_t local_addr;
pj_str_t local_uri;
pj_str_t local_contact;
int app_log_level;
int log_level;
char *log_filename;
char *report_filename;
structcodec audio_codec;
pj_str_t uri_to_call;
pj_caching_pool cp;
pj_pool_t *pool;
pjsip_endpoint *sip_endpt;
pj_bool_t thread_quit;
pj_thread_t *sip_thread[1];
pjmedia_endpt *med_endpt;
structcall call[MAX_CALLS];
} app;
//原型声明:
//当呼叫中的SDP协商完成时,函数被回调
static void call_on_media_update( pjsip_inv_session *inv,
pj_status_t status);
//当INVITE会话状态变化时,函数被回调
static void call_on_state_changed( pjsip_inv_session *inv,
pjsip_event *e);
//当对话被复制后,函数被回调
static void call_on_forked(pjsip_inv_session *inv, pjsip_event *e);
//当在对话外收到呼入请求时,函数被回调
//* Callback to be called to handle incomingrequests outside dialogs: */
static pj_bool_t on_rx_request(pjsip_rx_data *rdata );
//工作线程原型
static int sip_worker_thread(void *arg);
//创建用于呼叫的SDP
static pj_status_t create_sdp(pj_pool_t *pool,
structcall *call,
pjmedia_sdp_session **p_sdp);
//挂断呼叫
static void hangup_call(unsigned index);
//销毁呼叫媒体
static void destroy_call_media(unsigned call_index);
//销毁媒体
static void destroy_media();
//当收到RTP包时,此函数被回调
static void on_rx_rtp(void *user_data, void*pkt, pj_ssize_t size);
//当收到RTCP包时,此函数被回调
static void on_rx_rtcp(void *user_data, void*pkt, pj_ssize_t size);
//显示错误
static void app_perror(const char*sender, const char*title,
pj_status_t status);
//打印呼叫信息
static void print_call(int call_index);
//应用程序使用下面的PJSIP注册模块,控制对话或事务外的呼入请求,
//此处的主要目的是为了控制呼入INVITE请求消息。
static pjsip_module mod_siprtp =
{
NULL, NULL, /* prev, next. */
{ "mod-siprtpapp", 13 }, /* Name. */
-1, /* Id */
PJSIP_MOD_PRIORITY_APPLICATION, /*Priority */
NULL, /* load() */
NULL, /* start() */
NULL, /* stop() */
NULL, /* unload() */
&on_rx_request, /*on_rx_request() */
NULL, /* on_rx_response() */
NULL, /* on_tx_request. */
NULL, /* on_tx_response() */
NULL, /* on_tsx_state() */
};
//编解码器列表
struct codec audio_codecs[] =
{
{ 0, "PCMU",8000, 64000, 20, "G.711 ULaw" },
{ 3, "GSM", 8000, 13200, 20, "GSM"},
{ 4, "G723",8000, 6400, 30, "G.723.1"},
{ 8, "PCMA",8000, 64000, 20, "G.711 ALaw" },
{ 18, "G729", 8000, 8000, 20, "G.729" },
};
//初始化SIP协议栈
static pj_status_t init_sip()
{
unsignedi;
pj_status_t status;
//初始化PJLIB-UTIL:
status =pjlib_util_init();
PJ_ASSERT_RETURN(status == PJ_SUCCESS, status);
//在分配内存之前,必须创建pool factory!
pj_caching_pool_init(&app.cp, &pj_pool_factory_default_policy,0);
//创建应用程序内存池
app.pool= pj_pool_create(&app.cp.factory, "app",1000, 1000, NULL);
//创建SIP终端
status =pjsip_endpt_create(&app.cp.factory, pj_gethostname()->ptr,
&app.sip_endpt);
PJ_ASSERT_RETURN(status == PJ_SUCCESS, status);
//添加UDP传输端口
{
pj_sockaddr_in addr;
pjsip_host_port addrname;
pjsip_transport *tp;
pj_bzero(&addr,sizeof(addr));
addr.sin_family= pj_AF_INET();
addr.sin_addr.s_addr= 0;
addr.sin_port= pj_htons((pj_uint16_t)app.sip_port);
if(app.local_addr.slen) {
addrname.host = app.local_addr;
addrname.port = app.sip_port;
status = pj_sockaddr_in_init(&addr,&app.local_addr,
(pj_uint16_t)app.sip_port);
if (status!= PJ_SUCCESS) {
app_perror(THIS_FILE, "Unable to resolve IPinterface", status);
returnstatus;
}
}
//启动UDP侦听
status =pjsip_udp_transport_start( app.sip_endpt, &addr,
(app.local_addr.slen ? &addrname:NULL),
1, &tp);
if(status != PJ_SUCCESS) {
app_perror(THIS_FILE,"Unable to start UDP transport",status);
return status;
}
PJ_LOG(3,(THIS_FILE, "SIP UDP listening on%.*s:%d",
(int)tp->local_name.host.slen,tp->local_name.host.ptr,
tp->local_name.port));
}
//初始化事务层
//将创建/初始化事务hash表。。。
status =pjsip_tsx_layer_init_module(app.sip_endpt);
PJ_ASSERT_RETURN(status == PJ_SUCCESS, status);
//初始化UA层
status =pjsip_ua_init_module( app.sip_endpt, NULL);
PJ_ASSERT_RETURN(status == PJ_SUCCESS, status);
//初始化100rel支持
status =pjsip_100rel_init_module(app.sip_endpt);
PJ_ASSERT_RETURN(status == PJ_SUCCESS, status);
//初始化INVITE会话模块
{
pjsip_inv_callback inv_cb;
//初始化INVITE会话回调
pj_bzero(&inv_cb,sizeof(inv_cb));
inv_cb.on_state_changed= &call_on_state_changed;
inv_cb.on_new_session= &call_on_forked;
inv_cb.on_media_update= &call_on_media_update;
//初始化INVITE会话模块
status =pjsip_inv_usage_init(app.sip_endpt, &inv_cb);
PJ_ASSERT_RETURN(status== PJ_SUCCESS, 1);
}
//注册模块用于收到呼入请求处理
status =pjsip_endpt_register_module( app.sip_endpt, &mod_siprtp);
PJ_ASSERT_RETURN(status == PJ_SUCCESS, status);
//初始化全部呼叫
for(i=0; i<app.max_calls; ++i)
app.call[i].index= i;
//完成
returnPJ_SUCCESS;
}
//销毁SIP
static void destroy_sip()
{
unsignedi;
app.thread_quit = 1;
for(i=0; i<app.thread_count; ++i) {
if(app.sip_thread[i]) {
pj_thread_join(app.sip_thread[i]);
pj_thread_destroy(app.sip_thread[i]);
app.sip_thread[i] = NULL;
}
}
if(app.sip_endpt) {
pjsip_endpt_destroy(app.sip_endpt);
app.sip_endpt= NULL;
}
}
//初始化媒体栈
static pj_status_t init_media()
{
unsigned i, count;
pj_uint16_t rtp_port;
pj_status_t status;
//初始化媒体终端
*Initialize media endpoint so that at least error subsystem is properly
*initialized.
*/
#if PJ_HAS_THREADS
status =pjmedia_endpt_create(&app.cp.factory, NULL, 1, &app.med_endpt);
#else
status =pjmedia_endpt_create(&app.cp.factory,
pjsip_endpt_get_ioqueue(app.sip_endpt),
0, &app.med_endpt);
#endif
PJ_ASSERT_RETURN(status == PJ_SUCCESS, status);
//必须注册支持的编解码器
#if defined(PJMEDIA_HAS_G711_CODEC)&& PJMEDIA_HAS_G711_CODEC!=0
pjmedia_codec_g711_init(app.med_endpt);
#endif
//RTP端口计数器
rtp_port= (pj_uint16_t)(app.rtp_start_port & 0xFFFE);
//为所为呼叫初始化媒体传输端口
for(i=0, count=0; i<app.max_calls; ++i, ++count) {
unsignedj;
//为呼叫中的每个媒体创建传输端口
for(j=0; j<PJ_ARRAY_SIZE(app.call[0].media); ++j) {
//当绑定当前端口号错误时,重复绑定下个媒体套接字端口
int retry;
app.call[i].media[j].call_index = i;
app.call[i].media[j].media_index = j;
status = -1;
for(retry=0; retry<100; ++retry,rtp_port+=2) {
structmedia_stream *m = &app.call[i].media[j];
status= pjmedia_transport_udp_create2(app.med_endpt,
"siprtp",
&app.local_addr,
rtp_port, 0,
&m->transport);
if(status == PJ_SUCCESS) {
rtp_port += 2;
break;
}
}
}
if(status != PJ_SUCCESS)
gotoon_error;
}
/*Done */
returnPJ_SUCCESS;
on_error:
destroy_media();
returnstatus;
}
//销毁媒体
static void destroy_media()
{
unsigned i;
for(i=0; i<app.max_calls; ++i) {
unsigned j;
for(j=0; j<PJ_ARRAY_SIZE(app.call[0].media); ++j) {
struct media_stream *m = &app.call[i].media[j];
if(m->transport) {
pjmedia_transport_close(m->transport);
m->transport= NULL;
}
}
}
if(app.med_endpt) {
pjmedia_endpt_destroy(app.med_endpt);
app.med_endpt= NULL;
}
}
//构造外出呼叫
static pj_status_t make_call(constpj_str_t *dst_uri)
{
unsigned i;
struct call *call;
pjsip_dialog *dlg;
pjmedia_sdp_session *sdp;
pjsip_tx_data *tdata;
pj_status_t status;
//找到未使用的呼叫槽
for(i=0; i<app.max_calls; ++i) {
if(app.call[i].inv == NULL)
break;
}
if(i == app.max_calls)
return PJ_ETOOMANY;
call =&app.call[i];
//创建UAC对话
status =pjsip_dlg_create_uac( pjsip_ua_instance(),
&app.local_uri, /* local URI */
&app.local_contact, /* local Contact */
dst_uri, /* remote URI */
dst_uri, /* remote target */
&dlg); /*dialog */
if(status != PJ_SUCCESS) {
++app.uac_calls;
return status;
}
//创建 SDP
create_sdp( dlg->pool, call, &sdp);
//创建INVITE会话
status =pjsip_inv_create_uac( dlg, sdp, 0, &call->inv);
if(status != PJ_SUCCESS) {
pjsip_dlg_terminate(dlg);
++app.uac_calls;
returnstatus;
}
//附加呼叫数据到INVITE会话
call->inv->mod_data[mod_siprtp.id] = call;
//标记呼叫启动状态
pj_gettimeofday(&call->start_time);
//创建INVITE请求
//此请求要提供完整的请求信息和SDP内容
status =pjsip_inv_invite(call->inv, &tdata);
PJ_ASSERT_RETURN(status == PJ_SUCCESS, status);
//发送INVITE请求
status =pjsip_inv_send_msg(call->inv, tdata);
PJ_ASSERT_RETURN(status == PJ_SUCCESS, status);
returnPJ_SUCCESS;
}
//收到呼入呼叫
static void process_incoming_call(pjsip_rx_data *rdata)
{
unsignedi, options;
structcall *call;
pjsip_dialog *dlg;
pjmedia_sdp_session *sdp;
pjsip_tx_data *tdata;
pj_status_t status;
//查找未用呼叫槽
for(i=0; i<app.max_calls; ++i) {
if(app.call[i].inv == NULL)
break;
}
if(i == app.max_calls) {
constpj_str_t reason = pj_str("Too many calls");
pjsip_endpt_respond_stateless(app.sip_endpt, rdata,
500, &reason,
NULL,NULL);
return;
}
call =&app.call[i];
//效验要处理的请求
options =0;
status =pjsip_inv_verify_request(rdata,&options, NULL, NULL,
app.sip_endpt, &tdata);
if(status != PJ_SUCCESS) {
//无法处理呼叫的INVITE请求
if(tdata) {
pjsip_response_addr res_addr;
pjsip_get_response_addr(tdata->pool, rdata,&res_addr);
pjsip_endpt_send_response(app.sip_endpt,&res_addr, tdata,
NULL, NULL);
} else{
//回应500(内部服务错误)
pjsip_endpt_respond_stateless(app.sip_endpt, rdata,500, NULL,
NULL, NULL);
}
return;
}
//创建UAS对话
status =pjsip_dlg_create_uas_and_inc_lock( pjsip_ua_instance(), rdata,
&app.local_contact,&dlg);
if(status != PJ_SUCCESS) {
const pj_str_t reason = pj_str("Unable to create dialog");
pjsip_endpt_respond_stateless(app.sip_endpt, rdata,
500, &reason,
NULL,NULL);
return;
}
//创建SDP
create_sdp( dlg->pool, call, &sdp);
//创建UAS会话
status =pjsip_inv_create_uas( dlg, rdata, sdp,0, &call->inv);
if(status != PJ_SUCCESS) {
pjsip_dlg_create_response(dlg,rdata,500, NULL, &tdata);
pjsip_dlg_send_response(dlg,pjsip_rdata_get_tsx(rdata), tdata);
pjsip_dlg_dec_lock(dlg);
return;
}
//INVITE会话已经建立,撤销锁定
pjsip_dlg_dec_lock(dlg);
//附加呼叫数据到INVITE会话
call->inv->mod_data[mod_siprtp.id] = call;
//标记呼叫启动状态
pj_gettimeofday(&call->start_time);
//创建200回应
status =pjsip_inv_initial_answer(call->inv, rdata,200,
NULL,NULL, &tdata);
if(status != PJ_SUCCESS) {
status =pjsip_inv_initial_answer(call->inv, rdata,
PJSIP_SC_NOT_ACCEPTABLE,
NULL,NULL, &tdata);
if(status == PJ_SUCCESS)
pjsip_inv_send_msg(call->inv, tdata);
else
pjsip_inv_terminate(call->inv, 500,PJ_FALSE);
return;
}
//发送200回应
status =pjsip_inv_send_msg(call->inv, tdata);
PJ_ASSERT_ON_FAIL(status == PJ_SUCCESS, return);
//完成
}
//当对话被复制后,函数被回调
static void call_on_forked(pjsip_inv_session *inv,pjsip_event *e)
{
PJ_UNUSED_ARG(inv);
PJ_UNUSED_ARG(e);
PJ_TODO(HANDLE_FORKING );
}
//当在对话外收到呼入请求时,函数被回调
static pj_bool_t on_rx_request(pjsip_rx_data *rdata )
{
//忽略标准ACK
if(rdata->msg_info.msg->line.req.method.id== PJSIP_ACK_METHOD)
returnPJ_FALSE;
//以500回应任意非INVITE请求
if(rdata->msg_info.msg->line.req.method.id!= PJSIP_INVITE_METHOD) {
pj_str_treason = pj_str("Unsupported Operation");
pjsip_endpt_respond_stateless(app.sip_endpt, rdata,
500, &reason,
NULL,NULL);
returnPJ_TRUE;
}
//控制呼入INVITE
process_incoming_call(rdata);
//完成
returnPJ_TRUE;
}
//当超时断开呼叫时,回调此函数
static void timer_disconnect_call( pj_timer_heap_t *timer_heap,
struct pj_timer_entry *entry)
{
structcall *call = entry->user_data;
PJ_UNUSED_ARG(timer_heap);
entry->id= 0;
hangup_call(call->index);
}
//当INVITE会话状态变更时,此函数被回调
static void call_on_state_changed( pjsip_inv_session *inv,
pjsip_event *e)
{
structcall *call = inv->mod_data[mod_siprtp.id];
PJ_UNUSED_ARG(e);
if(!call)
return;
if(inv->state== PJSIP_INV_STATE_DISCONNECTED) {
pj_time_valnull_time = {0, 0};
if(call->d_timer.id != 0) {
pjsip_endpt_cancel_timer(app.sip_endpt,&call->d_timer);
call->d_timer.id = 0;
}
PJ_LOG(3,(THIS_FILE, "Call #%d disconnected.Reason=%d (%.*s)",
call->index,
inv->cause,
(int)inv->cause_text.slen,
inv->cause_text.ptr));
if(app.call_report) {
PJ_LOG(3,(THIS_FILE,"Call #%d statistics:", call->index));
print_call(call->index);
}
call->inv= NULL;
inv->mod_data[mod_siprtp.id]= NULL;
destroy_call_media(call->index);
call->start_time= null_time;
call->response_time= null_time;
call->connect_time= null_time;
++app.uac_calls;
} elseif(inv->state== PJSIP_INV_STATE_CONFIRMED) {
pj_time_valt;
pj_gettimeofday(&call->connect_time);
if(call->response_time.sec == 0)
call->response_time =call->connect_time;
t =call->connect_time;
PJ_TIME_VAL_SUB(t,call->start_time);
PJ_LOG(3,(THIS_FILE, "Call #%d connected in %dms", call->index,
PJ_TIME_VAL_MSEC(t)));
if(app.duration != 0) {
call->d_timer.id = 1;
call->d_timer.user_data = call;
call->d_timer.cb =&timer_disconnect_call;
t.sec = app.duration;
t.msec = 0;
pjsip_endpt_schedule_timer(app.sip_endpt,&call->d_timer, &t);
}
} elseif( inv->state== PJSIP_INV_STATE_EARLY ||
inv->state== PJSIP_INV_STATE_CONNECTING) {
if(call->response_time.sec == 0)
pj_gettimeofday(&call->response_time);
}
}
//杂项
static void app_perror(const char*sender,constchar*title,
pj_status_t status)
{
char errmsg[PJ_ERR_MSG_SIZE];
pj_strerror(status, errmsg, sizeof(errmsg));
PJ_LOG(3,(sender, "%s:%s [status=%d]", title,errmsg, status));
}
//SIP工作线程
static int sip_worker_thread(void *arg)
{
PJ_UNUSED_ARG(arg);
while(!app.thread_quit) {
pj_time_valtimeout = {0, 10};
pjsip_endpt_handle_events(app.sip_endpt,&timeout);
}
return0;
}
//应用程序初始化选项
static pj_status_t init_options(intargc,char*argv[])
{
static char ip_addr[PJ_INET_ADDRSTRLEN];
static char local_uri[64];
enum{ OPT_START,
OPT_APP_LOG_LEVEL, OPT_LOG_FILE,
OPT_A_PT, OPT_A_NAME, OPT_A_CLOCK,OPT_A_BITRATE, OPT_A_PTIME,
OPT_REPORT_FILE };
struct pj_getopt_option long_options[] = {
{ "count", 1, 0, 'c'},
{ "gap", 1, 0, 'g' },
{ "call-report", 0, 0, 'R' },
{ "duration", 1, 0, 'd'},
{ "auto-quit", 0, 0, 'q'},
{ "local-port", 1, 0, 'p'},
{ "rtp-port", 1, 0, 'r'},
{ "ip-addr", 1, 0, 'i'},
{ "log-level", 1, 0, 'l'},
{ "app-log-level", 1, 0, OPT_APP_LOG_LEVEL },
{ "log-file", 1, 0, OPT_LOG_FILE },
{ "report-file", 1, 0, OPT_REPORT_FILE },
/*Don't support this anymore, see comments in USAGE above.
{"a-pt", 1, 0, OPT_A_PT },
{"a-name", 1, 0, OPT_A_NAME },
{"a-clock", 1, 0, OPT_A_CLOCK },
{"a-bitrate", 1, 0, OPT_A_BITRATE },
{"a-ptime", 1, 0, OPT_A_PTIME },
*/
{ NULL, 0, 0, 0 },
};
intc;
intoption_index;
//设置缺省IP地址为本地IP地址
{
const pj_str_t *hostname;
pj_sockaddr_in tmp_addr;
hostname =pj_gethostname();
pj_sockaddr_in_init(&tmp_addr,hostname, 0);
pj_inet_ntop(pj_AF_INET(),&tmp_addr.sin_addr, ip_addr,
sizeof(ip_addr));
}
//初始化缺省值
app.max_calls = 1;
app.thread_count = 1;
app.sip_port = 5060;
app.rtp_start_port = RTP_START_PORT;
app.local_addr = pj_str(ip_addr);
app.log_level = 5;
app.app_log_level = 3;
app.log_filename = NULL;
//缺省的编解码器
app.audio_codec = audio_codecs[0];
//解析参数选项
pj_optind= 0;
while((c=pj_getopt_long(argc,argv,"c:d:p:r:i:l:g:qR",
long_options, &option_index))!=-1)
{
switch(c) {
case'c':
app.max_calls = atoi(pj_optarg);
if(app.max_calls > MAX_CALLS) {
PJ_LOG(3,(THIS_FILE,"Invalid max calls value %s"
"(must be <=%d)", pj_optarg, MAX_CALLS));
return1;
}
break;
case'g':
app.call_gap = atoi(pj_optarg);
break;
case'R':
app.call_report = PJ_TRUE;
break;
case'd':
app.duration = atoi(pj_optarg);
break;
case'q':
app.auto_quit = 1;
break;
case'p':
app.sip_port = atoi(pj_optarg);
break;
case'r':
app.rtp_start_port = atoi(pj_optarg);
break;
case'i':
app.local_addr = pj_str(pj_optarg);
break;
case'l':
app.log_level = atoi(pj_optarg);
break;
caseOPT_APP_LOG_LEVEL:
app.app_log_level = atoi(pj_optarg);
break;
caseOPT_LOG_FILE:
app.log_filename = pj_optarg;
break;
caseOPT_A_PT:
app.audio_codec.pt = atoi(pj_optarg);
break;
caseOPT_A_NAME:
app.audio_codec.name = pj_optarg;
break;
caseOPT_A_CLOCK:
app.audio_codec.clock_rate =atoi(pj_optarg);
break;
caseOPT_A_BITRATE:
app.audio_codec.bit_rate = atoi(pj_optarg);
break;
caseOPT_A_PTIME:
app.audio_codec.ptime = atoi(pj_optarg);
break;
caseOPT_REPORT_FILE:
app.report_filename = pj_optarg;
break;
default:
puts(USAGE);
return 1;
}
}
//检测给定的URI
if(pj_optind < argc)
app.uri_to_call= pj_str(argv[pj_optind]);
//创建本地URI和联系人
pj_ansi_sprintf( local_uri, "sip:%s:%d",app.local_addr.ptr, app.sip_port);
app.local_uri = pj_str(local_uri);
app.local_contact = app.local_uri;
returnPJ_SUCCESS;
}
///
//媒体部分
//为某个呼叫创建SDP会话
static pj_status_t create_sdp(pj_pool_t *pool,
structcall *call,
pjmedia_sdp_session **p_sdp)
{
pj_time_val tv;
pjmedia_sdp_session *sdp;
pjmedia_sdp_media *m;
pjmedia_sdp_attr *attr;
pjmedia_transport_info tpinfo;
struct media_stream *audio = &call->media[0];
PJ_ASSERT_RETURN(pool&& p_sdp, PJ_EINVAL);
//取传输端口信息
pjmedia_transport_info_init(&tpinfo);
pjmedia_transport_get_info(audio->transport, &tpinfo);
//创建和初始化基础SDP会话
sdp =pj_pool_zalloc (pool, sizeof(pjmedia_sdp_session));
pj_gettimeofday(&tv);
sdp->origin.user = pj_str("pjsip-siprtp");
sdp->origin.version = sdp->origin.id = tv.sec + 2208988800UL;
sdp->origin.net_type = pj_str("IN");
sdp->origin.addr_type = pj_str("IP4");
sdp->origin.addr = *pj_gethostname();
sdp->name = pj_str("pjsip");
//因为我们当下只支持一个媒体流,故以下列方式提供SDP连接行
sdp->conn = pj_pool_zalloc (pool, sizeof(pjmedia_sdp_conn));
sdp->conn->net_type = pj_str("IN");
sdp->conn->addr_type = pj_str("IP4");
sdp->conn->addr = app.local_addr;
//SDP的time及属性
sdp->time.start = sdp->time.stop = 0;
sdp->attr_count = 0;
//创建媒体流0
sdp->media_count = 1;
m =pj_pool_zalloc (pool, sizeof(pjmedia_sdp_media));
sdp->media[0]= m;
//标准媒体信息
m->desc.media = pj_str("audio");
m->desc.port =pj_ntohs(tpinfo.sock_info.rtp_addr_name.ipv4.sin_port);
m->desc.port_count = 1;
m->desc.transport = pj_str("RTP/AVP");
//为每个编解码器添加rtpmap格式
m->desc.fmt_count= 1;
m->attr_count = 0;
{
pjmedia_sdp_rtpmap rtpmap;
char ptstr[10];
sprintf(ptstr,"%d", app.audio_codec.pt);
pj_strdup2(pool,&m->desc.fmt[0], ptstr);
rtpmap.pt= m->desc.fmt[0];
rtpmap.clock_rate= app.audio_codec.clock_rate;
rtpmap.enc_name= pj_str(app.audio_codec.name);
rtpmap.param.slen= 0;
pjmedia_sdp_rtpmap_to_attr(pool,&rtpmap, &attr);
m->attr[m->attr_count++]= attr;
}
//添加sendrecv属性
attr =pj_pool_zalloc(pool, sizeof(pjmedia_sdp_attr));
attr->name= pj_str("sendrecv");
m->attr[m->attr_count++] = attr;
#if 1
//添加对DTMF支持
m->desc.fmt[m->desc.fmt_count++] = pj_str("121");
/*Add rtpmap. */
attr =pj_pool_zalloc(pool, sizeof(pjmedia_sdp_attr));
attr->name = pj_str("rtpmap");
attr->value = pj_str("121 telephone-event/8000");
m->attr[m->attr_count++] = attr;
//添加 fmtp
attr =pj_pool_zalloc(pool, sizeof(pjmedia_sdp_attr));
attr->name = pj_str("fmtp");
attr->value = pj_str("121 0-15");
m->attr[m->attr_count++] = attr;
#endif
//完成
*p_sdp= sdp;
returnPJ_SUCCESS;
}
#if (defined(PJ_WIN32)&& PJ_WIN32 != 0) || (defined(PJ_WIN64)&& PJ_WIN64 != 0)
#include <windows.h>
static voidboost_priority(void)
{
SetPriorityClass( GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
}
#elif defined(PJ_LINUX)&& PJ_LINUX != 0
#include <pthread.h>
static voidboost_priority(void)
{
#define POLICY SCHED_FIFO
struct sched_param tp;
int max_prio;
int policy;
int rc;
if(sched_get_priority_min(POLICY) < sched_get_priority_max(POLICY))
max_prio =sched_get_priority_max(POLICY)-1;
else
max_prio =sched_get_priority_max(POLICY)+1;
//调整进程调度算法和优先级
rc = sched_getparam(0, &tp);
if(rc != 0) {
app_perror(THIS_FILE, "sched_getparam error",
PJ_RETURN_OS_ERROR(rc));
return;
}
tp.sched_priority = max_prio;
rc =sched_setscheduler(0, POLICY, &tp);
if(rc != 0) {
app_perror(THIS_FILE, "sched_setscheduler error",
PJ_RETURN_OS_ERROR(rc));
}
PJ_LOG(4,(THIS_FILE, "New process policy=%d, priority=%d",
policy, tp.sched_priority));
//调整线程调度算法和优先级
rc =pthread_getschedparam(pthread_self(), &policy, &tp);
if(rc != 0) {
app_perror(THIS_FILE, "pthread_getschedparam error",
PJ_RETURN_OS_ERROR(rc));
return;
}
PJ_LOG(4,(THIS_FILE, "Old thread policy=%d, priority=%d",
policy, tp.sched_priority));
policy =POLICY;
tp.sched_priority = max_prio;
rc =pthread_setschedparam(pthread_self(), policy, &tp);
if(rc != 0) {
app_perror(THIS_FILE, "pthread_setschedparam error",
PJ_RETURN_OS_ERROR(rc));
return;
}
PJ_LOG(4,(THIS_FILE, "New thread policy=%d, priority=%d",
policy, tp.sched_priority));
}
#else
# defineboost_priority()
#endif
//媒体传输端口收到RTP包时,此函数被回调
static void on_rx_rtp(void *user_data,void *pkt,pj_ssize_t size)
{
struct media_stream *strm;
pj_status_t status;
const pjmedia_rtp_hdr *hdr;
const void *payload;
unsigned payload_len;
strm = user_data;
//如果媒体无效,屏蔽此包
if(!strm->active)
return;
//检测错误
if(size< 0) {
app_perror(THIS_FILE, "RTP recv()错误",(pj_status_t)-size);
return;
}
//解码RTP包
status =pjmedia_rtp_decode_rtp(&strm->in_sess,
pkt, (int)size,
&hdr, &payload, &payload_len);
if(status != PJ_SUCCESS) {
app_perror(THIS_FILE, "RTP解码错误",status);
return;
}
//PJ_LOG(4,(THIS_FILE,"Rx seq=%d", pj_ntohs(hdr->seq)));
//更新RTCP会话
pjmedia_rtcp_rx_rtp(&strm->rtcp, pj_ntohs(hdr->seq),
pj_ntohl(hdr->ts),payload_len);
//更新RTP会话
pjmedia_rtp_session_update(&strm->in_sess, hdr, NULL);
}
//当媒体传输端口收到RTCP包时,此函数被回调
static void on_rx_rtcp(void *user_data,void *pkt,pj_ssize_t size)
{
struct media_stream *strm;
strm = user_data;
//如果媒体无效,屏蔽此包
if(!strm->active)
return;
//检测错误
if(size< 0) {
app_perror(THIS_FILE, "接收RTCP包错误",(pj_status_t)-size);
return;
}
//更新RTCP会话
pjmedia_rtcp_rx_rtcp(&strm->rtcp, pkt,size);
}
//媒体线程
//在线程中发送和接收RTP与RTCP包
static int media_thread(void *arg)
{
enum{ RTCP_INTERVAL = 5000, RTCP_RAND = 2000 };
struct media_stream *strm = arg;
char packet[1500];
unsigned msec_interval;
pj_timestamp freq, next_rtp, next_rtcp;
//如果需要提升线程级别
boost_priority();
/*Let things settle */
pj_thread_sleep(100);
msec_interval = strm->samples_per_frame * 1000 / strm->clock_rate;
pj_get_timestamp_freq(&freq);
pj_get_timestamp(&next_rtp);
next_rtp.u64 += (freq.u64 * msec_interval / 1000);
next_rtcp= next_rtp;
next_rtcp.u64 += (freq.u64 * (RTCP_INTERVAL+(pj_rand()%RTCP_RAND)) /1000);
while(!strm->thread_quit_flag) {
pj_timestampnow, lesser;
pj_time_valtimeout;
pj_bool_tsend_rtp, send_rtcp;
send_rtp =send_rtcp = PJ_FALSE;
//确定sleep时长
if(next_rtp.u64 < next_rtcp.u64) {
lesser = next_rtp;
send_rtp = PJ_TRUE;
} else{
lesser = next_rtcp;
send_rtcp = PJ_TRUE;
}
pj_get_timestamp(&now);
if(lesser.u64 <= now.u64) {
timeout.sec = timeout.msec = 0;
//printf("immediate"); fflush(stdout);
} else{
pj_uint64_t tick_delay;
tick_delay = lesser.u64 - now.u64;
timeout.sec = 0;
timeout.msec = (pj_uint32_t)(tick_delay *1000 / freq.u64);
pj_time_val_normalize(&timeout);
//printf("%d:%03d ",timeout.sec, timeout.msec); fflush(stdout);
}
//等待下个区间
//if(timeout.sec!=0 && timeout.msec!=0) {
pj_thread_sleep(PJ_TIME_VAL_MSEC(timeout));
if(strm->thread_quit_flag)
break;
//}
pj_get_timestamp(&now);
if(send_rtp || next_rtp.u64 <= now.u64) {
//定时发送RTP包
pj_status_t status;
const void *p_hdr;
const pjmedia_rtp_hdr *hdr;
pj_ssize_t size;
int hdrlen;
//格式RTP头
status = pjmedia_rtp_encode_rtp(&strm->out_sess, strm->si.tx_pt,
0, /*marker bit */
strm->bytes_per_frame,
strm->samples_per_frame,
&p_hdr, &hdrlen);
if (status== PJ_SUCCESS) {
//PJ_LOG(4,(THIS_FILE,"\t\tTx seq=%d", pj_ntohs(hdr->seq)));
hdr =(constpjmedia_rtp_hdr*) p_hdr;
//拷贝RTP头到包
pj_memcpy(packet,hdr, hdrlen);
//清空负载
pj_bzero(packet+hdrlen,strm->bytes_per_frame);
//发送RTP包
size =hdrlen + strm->bytes_per_frame;
status= pjmedia_transport_send_rtp(strm->transport,
packet, size);
if(status != PJ_SUCCESS)
app_perror(THIS_FILE,"发送RTP错误", status);
} else {
pj_assert(!"RTP编码()错误");
}
//更新RTCP SR
pjmedia_rtcp_tx_rtp( &strm->rtcp,(pj_uint16_t)strm->bytes_per_frame);
//规定下次发送
next_rtp.u64 += (msec_interval * freq.u64 /1000);
}
if(send_rtcp || next_rtcp.u64 <= now.u64) {
//定时发送RTCP包
void *rtcp_pkt;
int rtcp_len;
pj_ssize_t size;
pj_status_t status;
//创建RTCP包
pjmedia_rtcp_build_rtcp(&strm->rtcp,&rtcp_pkt, &rtcp_len);
//发送包
size = rtcp_len;
status =pjmedia_transport_send_rtcp(strm->transport,
rtcp_pkt, size);
if (status!= PJ_SUCCESS) {
app_perror(THIS_FILE, "发送RTCP包错误",status);
}
//规定下次发送
next_rtcp.u64 += (freq.u64 *(RTCP_INTERVAL+(pj_rand()%RTCP_RAND)) /
1000);
}
}
return0;
}
//当呼叫中的SDP协商完成时,函数被回调
static void call_on_media_update( pjsip_inv_session *inv,
pj_status_t status)
{
struct call *call;
struct media_stream *audio;
const pjmedia_sdp_session *local_sdp, *remote_sdp;
struct codec *codec_desc = NULL;
unsigned i;
call = inv->mod_data[mod_siprtp.id];
audio =&call->media[0];
//如果是呼叫中更新,则销毁已经存在的媒体
if(audio->thread != NULL)
destroy_call_media(call->index);
//如果媒体协商错误,则不做处理
if(status!= PJ_SUCCESS) {
app_perror(THIS_FILE, "SDP协商错误", status);
return;
}
//从SDP中提取流定义
pjmedia_sdp_neg_get_active_local(inv->neg,&local_sdp);
pjmedia_sdp_neg_get_active_remote(inv->neg,&remote_sdp);
status= pjmedia_stream_info_from_sdp(&audio->si, inv->pool,app.med_endpt,
local_sdp, remote_sdp, 0);
if(status!= PJ_SUCCESS) {
app_perror(THIS_FILE, "从SDP创建流信息错误", status);
return;
}
//从编解码器描述中取留存编解码器信息
if(audio->si.fmt.pt == app.audio_codec.pt)
codec_desc= &app.audio_codec;
else{
//从编解码器组中查找编解码器描述
for(i=0; i<PJ_ARRAY_SIZE(audio_codecs); ++i) {
if(audio_codecs[i].pt == audio->si.fmt.pt) {
codec_desc= &audio_codecs[i];
break;
}
}
if(codec_desc == NULL) {
PJ_LOG(3, (THIS_FILE,"错误:无效的负载类型"));
return;
}
}
audio->clock_rate = audio->si.fmt.clock_rate;
audio->samples_per_frame = audio->clock_rate *codec_desc->ptime / 1000;
audio->bytes_per_frame = codec_desc->bit_rate *codec_desc->ptime / 1000 / 8;
pjmedia_rtp_session_init(&audio->out_sess, audio->si.tx_pt,
pj_rand());
pjmedia_rtp_session_init(&audio->in_sess, audio->si.fmt.pt,0);
pjmedia_rtcp_init(&audio->rtcp, "rtcp",audio->clock_rate,
audio->samples_per_frame, 0);
//!!!附加媒体到传输端口
status= pjmedia_transport_attach(audio->transport, audio,
&audio->si.rem_addr,
&audio->si.rem_rtcp,
sizeof(pj_sockaddr_in),
&on_rx_rtp,
&on_rx_rtcp);
if(status!= PJ_SUCCESS) {
app_perror(THIS_FILE, "错误发生于pjmedia_transport_attach()",status);
return;
}
//启动媒体线程
audio->thread_quit_flag = 0;
#if PJ_HAS_THREADS
status =pj_thread_create( inv->pool, "media",&media_thread, audio,
0, 0, &audio->thread);
if(status != PJ_SUCCESS) {
app_perror(THIS_FILE,"创建媒体线程错误", status);
return;
}
#endif
//设置媒体状态可用
audio->active = PJ_TRUE;
}
//销毁所有媒体
static void destroy_call_media(unsigned call_index)
{
struct media_stream *audio = &app.call[call_index].media[0];
if(audio) {
audio->active= PJ_FALSE;
if(audio->thread) {
audio->thread_quit_flag = 1;
pj_thread_join(audio->thread);
pj_thread_destroy(audio->thread);
audio->thread = NULL;
audio->thread_quit_flag = 0;
}
pjmedia_transport_detach(audio->transport,audio);
}
}
///
//用户接口部分
static void call_get_duration(int call_index,pj_time_val *dur)
{
structcall *call = &app.call[call_index];
pjsip_inv_session *inv;
dur->sec= dur->msec = 0;
if(!call)
return;
inv =call->inv;
if(!inv)
return;
if(inv->state >= PJSIP_INV_STATE_CONFIRMED &&call->connect_time.sec) {
pj_gettimeofday(dur);
PJ_TIME_VAL_SUB((*dur),call->connect_time);
}
}
static const char *good_number(char *buf,pj_int32_t val)
{
if(val< 1000) {
pj_ansi_sprintf(buf,"%d", val);
} elseif(val< 1000000) {
pj_ansi_sprintf(buf,"%d.%02dK",
val/ 1000,
(val% 1000) / 100);
} else{
pj_ansi_sprintf(buf,"%d.%02dM",
val/ 1000000,
(val% 1000000) / 10000);
}
return buf;
}
static void print_avg_stat(void)
{
#define MIN_(var,val) if((int)val < (int)var)var = val
#define MAX_(var,val) if((int)val > (int)var)var = val
#define AVG_(var,val) var= ( ((var * count) + val) / (count+1) )
#define BIGVAL 0x7FFFFFFFL
struct stat_entry
{
int min, avg, max;
};
struct stat_entry call_dur, call_pdd;
pjmedia_rtcp_stat min_stat, avg_stat, max_stat;
char srx_min[16], srx_avg[16], srx_max[16];
char brx_min[16], brx_avg[16], brx_max[16];
char stx_min[16], stx_avg[16], stx_max[16];
char btx_min[16], btx_avg[16], btx_max[16];
unsigned i, count;
pj_bzero(&call_dur, sizeof(call_dur));
call_dur.min = BIGVAL;
pj_bzero(&call_pdd, sizeof(call_pdd));
call_pdd.min = BIGVAL;
pj_bzero(&min_stat, sizeof(min_stat));
min_stat.rx.pkt = min_stat.tx.pkt = BIGVAL;
min_stat.rx.bytes= min_stat.tx.bytes = BIGVAL;
min_stat.rx.loss = min_stat.tx.loss = BIGVAL;
min_stat.rx.dup = min_stat.tx.dup = BIGVAL;
min_stat.rx.reorder = min_stat.tx.reorder = BIGVAL;
min_stat.rx.jitter.min = min_stat.tx.jitter.min = BIGVAL;
min_stat.rtt.min = BIGVAL;
pj_bzero(&avg_stat, sizeof(avg_stat));
pj_bzero(&max_stat, sizeof(max_stat));
for(i=0, count=0; i<app.max_calls; ++i) {
struct call *call = &app.call[i];
struct media_stream *audio = &call->media[0];
pj_time_val dur;
unsigned msec_dur;
if(call->inv == NULL ||
call->inv->state <PJSIP_INV_STATE_CONFIRMED ||
call->connect_time.sec == 0)
{
continue;
}
//持续时间
call_get_duration(i,&dur);
msec_dur =PJ_TIME_VAL_MSEC(dur);
MIN_(call_dur.min,msec_dur);
MAX_(call_dur.max,msec_dur);
AVG_(call_dur.avg, msec_dur);
//连接延迟
if(call->connect_time.sec) {
pj_time_val t = call->connect_time;
PJ_TIME_VAL_SUB(t, call->start_time);
msec_dur = PJ_TIME_VAL_MSEC(t);
} else{
msec_dur = 10;
}
MIN_(call_pdd.min,msec_dur);
MAX_(call_pdd.max,msec_dur);
AVG_(call_pdd.avg, msec_dur);
//接收统计
//包数
MIN_(min_stat.rx.pkt, audio->rtcp.stat.rx.pkt);
MAX_(max_stat.rx.pkt, audio->rtcp.stat.rx.pkt);
AVG_(avg_stat.rx.pkt, audio->rtcp.stat.rx.pkt);
//字节数
MIN_(min_stat.rx.bytes, audio->rtcp.stat.rx.bytes);
MAX_(max_stat.rx.bytes, audio->rtcp.stat.rx.bytes);
AVG_(avg_stat.rx.bytes, audio->rtcp.stat.rx.bytes);
//丢包
MIN_(min_stat.rx.loss, audio->rtcp.stat.rx.loss);
MAX_(max_stat.rx.loss, audio->rtcp.stat.rx.loss);
AVG_(avg_stat.rx.loss, audio->rtcp.stat.rx.loss);
//复制包
MIN_(min_stat.rx.dup, audio->rtcp.stat.rx.dup);
MAX_(max_stat.rx.dup, audio->rtcp.stat.rx.dup);
AVG_(avg_stat.rx.dup, audio->rtcp.stat.rx.dup);
//重排序包
MIN_(min_stat.rx.reorder, audio->rtcp.stat.rx.reorder);
MAX_(max_stat.rx.reorder, audio->rtcp.stat.rx.reorder);
AVG_(avg_stat.rx.reorder, audio->rtcp.stat.rx.reorder);
//抖动
MIN_(min_stat.rx.jitter.min,audio->rtcp.stat.rx.jitter.min);
MAX_(max_stat.rx.jitter.max,audio->rtcp.stat.rx.jitter.max);
AVG_(avg_stat.rx.jitter.mean,audio->rtcp.stat.rx.jitter.mean);
//发送统计
//包数
MIN_(min_stat.tx.pkt, audio->rtcp.stat.tx.pkt);
MAX_(max_stat.tx.pkt, audio->rtcp.stat.tx.pkt);
AVG_(avg_stat.tx.pkt, audio->rtcp.stat.tx.pkt);
//字节数
MIN_(min_stat.tx.bytes, audio->rtcp.stat.tx.bytes);
MAX_(max_stat.tx.bytes, audio->rtcp.stat.tx.bytes);
AVG_(avg_stat.tx.bytes, audio->rtcp.stat.tx.bytes);
//丢包
MIN_(min_stat.tx.loss, audio->rtcp.stat.tx.loss);
MAX_(max_stat.tx.loss, audio->rtcp.stat.tx.loss);
AVG_(avg_stat.tx.loss, audio->rtcp.stat.tx.loss);
//复制包
MIN_(min_stat.tx.dup, audio->rtcp.stat.tx.dup);
MAX_(max_stat.tx.dup, audio->rtcp.stat.tx.dup);
AVG_(avg_stat.tx.dup, audio->rtcp.stat.tx.dup);
//重排序包
MIN_(min_stat.tx.reorder, audio->rtcp.stat.tx.reorder);
MAX_(max_stat.tx.reorder, audio->rtcp.stat.tx.reorder);
AVG_(avg_stat.tx.reorder, audio->rtcp.stat.tx.reorder);
//抖动
MIN_(min_stat.tx.jitter.min,audio->rtcp.stat.tx.jitter.min);
MAX_(max_stat.tx.jitter.max,audio->rtcp.stat.tx.jitter.max);
AVG_(avg_stat.tx.jitter.mean,audio->rtcp.stat.tx.jitter.mean);
//RTT
MIN_(min_stat.rtt.min,audio->rtcp.stat.rtt.min);
MAX_(max_stat.rtt.max,audio->rtcp.stat.rtt.max);
AVG_(avg_stat.rtt.mean, audio->rtcp.stat.rtt.mean);
++count;
}
if(count == 0) {
puts("无活动呼叫");
return;
}
printf("合计 %d 个活动呼叫.\n"
" 平均统计\n"
" 最小 平均 最大 \n"
" -----------------------\n"
" 呼叫持续时间: %7d %7d %7d %s\n"
" 连接 延迟: %7d %7d %7d %s\n"
" 接收统计:\n"
" 包: %7s %7s %7s %s\n"
" 负载: %7s %7s %7s %s\n"
" 丢失: %7d %7d %7d %s\n"
" 丢包百分比: %7.3f %7.3f %7.3f %s\n"
" 复制: %7d %7d %7d %s\n"
" 重新排序: %7d %7d %7d %s\n"
" 抖动: %7.3f %7.3f %7.3f %s\n"
" 发送统计:\n"
" 包: %7s %7s %7s %s\n"
" 负载: %7s %7s %7s %s\n"
" 丢失: %7d %7d %7d %s\n"
" 丢包百分比: %7.3f %7.3f %7.3f %s\n"
" 复制: %7d %7d %7d %s\n"
" 重新排序: %7d %7d %7d %s\n"
" 抖动: %7.3f %7.3f %7.3f %s\n"
" RTT : %7.3f %7.3f %7.3f %s\n"
,
count,
call_dur.min/1000, call_dur.avg/1000,call_dur.max/1000,
"秒",
call_pdd.min, call_pdd.avg, call_pdd.max,
"毫秒",
/* rx */
good_number(srx_min, min_stat.rx.pkt),
good_number(srx_avg, avg_stat.rx.pkt),
good_number(srx_max, max_stat.rx.pkt),
"packets",
good_number(brx_min, min_stat.rx.bytes),
good_number(brx_avg, avg_stat.rx.bytes),
good_number(brx_max, max_stat.rx.bytes),
"bytes",
min_stat.rx.loss, avg_stat.rx.loss,max_stat.rx.loss,
"packets",
min_stat.rx.loss*100.0/(min_stat.rx.pkt+min_stat.rx.loss),
avg_stat.rx.loss*100.0/(avg_stat.rx.pkt+avg_stat.rx.loss),
max_stat.rx.loss*100.0/(max_stat.rx.pkt+max_stat.rx.loss),
"%",
min_stat.rx.dup, avg_stat.rx.dup,max_stat.rx.dup,
"packets",
min_stat.rx.reorder, avg_stat.rx.reorder,max_stat.rx.reorder,
"packets",
min_stat.rx.jitter.min/1000.0,
avg_stat.rx.jitter.mean/1000.0,
max_stat.rx.jitter.max/1000.0,
"ms",
/* tx */
good_number(stx_min, min_stat.tx.pkt),
good_number(stx_avg, avg_stat.tx.pkt),
good_number(stx_max, max_stat.tx.pkt),
"packets",
good_number(btx_min, min_stat.tx.bytes),
good_number(btx_avg, avg_stat.tx.bytes),
good_number(btx_max, max_stat.tx.bytes),
"bytes",
min_stat.tx.loss, avg_stat.tx.loss,max_stat.tx.loss,
"packets",
min_stat.tx.loss*100.0/(min_stat.tx.pkt+min_stat.tx.loss),
avg_stat.tx.loss*100.0/(avg_stat.tx.pkt+avg_stat.tx.loss),
max_stat.tx.loss*100.0/(max_stat.tx.pkt+max_stat.tx.loss),
"%",
min_stat.tx.dup, avg_stat.tx.dup,max_stat.tx.dup,
"packets",
min_stat.tx.reorder, avg_stat.tx.reorder,max_stat.tx.reorder,
"packets",
min_stat.tx.jitter.min/1000.0,
avg_stat.tx.jitter.mean/1000.0,
max_stat.tx.jitter.max/1000.0,
"ms",
/* rtt */
min_stat.rtt.min/1000.0,
avg_stat.rtt.mean/1000.0,
max_stat.rtt.max/1000.0,
"ms"
);
}
#include "siprtp_report.c"
static void list_calls()
{
unsigned i;
puts("全部呼叫列表:");
for(i=0; i<app.max_calls; ++i) {
if(!app.call[i].inv)
continue;
print_call(i);
}
}
static void hangup_call(unsigned index)
{
pjsip_tx_data *tdata;
pj_status_t status;
if(app.call[index].inv == NULL)
return;
status =pjsip_inv_end_session(app.call[index].inv,603, NULL, &tdata);
if(status==PJ_SUCCESS && tdata!=NULL)
pjsip_inv_send_msg(app.call[index].inv,tdata);
}
static void hangup_all_calls()
{
unsignedi;
for(i=0; i<app.max_calls; ++i) {
if(!app.call[i].inv)
continue;
hangup_call(i);
pj_thread_sleep(app.call_gap);
}
//等待,直到所有呼叫被终止
for(i=0; i<app.max_calls; ++i) {
while(app.call[i].inv)
pj_thread_sleep(10);
}
}
static pj_bool_t simple_input(const char *title,char *buf,pj_size_t len)
{
char *p;
printf("%s (为空将取消): ", title);fflush(stdout);
if(fgets(buf, (int)len,stdin) == NULL)
return PJ_FALSE;
//删除换行符
for(p=buf; ; ++p) {
if(*p=='\r' || *p=='\n')*p='\0';
else if(!*p) break;
}
if(!*buf)
return PJ_FALSE;
return PJ_TRUE;
}
static const char *MENU =
"\n"
"Enter menu character:\n"
" s Summary\n"
" l List all calls\n"
" h Hangup a call\n"
" H Hangup all calls\n"
" q Quit\n"
"\n";
//主屏菜单
static void console_main()
{
char input1[10];
unsigned i;
printf("%s", MENU);
for(;;) {
printf(">>> "); fflush(stdout);
if(fgets(input1, sizeof(input1), stdin) == NULL) {
puts("键盘输入,读取EOF后退出..");
break;
}
switch(input1[0]) {
case's':
print_avg_stat();
break;
case'l':
list_calls();
break;
case'h':
if(!simple_input("要挂断的索引号", input1, sizeof(input1)))
break;
i = atoi(input1);
hangup_call(i);
break;
case'H':
hangup_all_calls();
break;
case'q':
gotoon_exit;
default:
puts("无效命令");
printf("%s",MENU);
break;
}
fflush(stdout);
}
on_exit:
hangup_all_calls();
}
///
//下面的简单模块用于记录全部呼入与呼出SIP消息日志
//呼入消息通知
static pj_bool_t logger_on_rx_msg(pjsip_rx_data *rdata)
{
PJ_LOG(4,(THIS_FILE, "收到 %d 字节 %s 从 %s:%d:\n"
"%s\n"
"—消息结束--",
rdata->msg_info.len,
pjsip_rx_data_get_info(rdata),
rdata->pkt_info.src_name,
rdata->pkt_info.src_port,
rdata->msg_info.msg_buf));
//必须返回假,否则其它消息将不被处理
returnPJ_FALSE;
}
//呼出消息通知
static pj_status_t logger_on_tx_msg(pjsip_tx_data *tdata)
{
//重要注意事项:
// 当外呼消息通过传输层后,tp_info域才有效。所以当模块的级别低于传输层时,不要试图存取tp_info。
PJ_LOG(4,(THIS_FILE, "发送 %d 字节 %s 到 %s:%d:\n"
"%s\n"
"—消息结束--",
(tdata->buf.cur- tdata->buf.start),
pjsip_tx_data_get_info(tdata),
tdata->tp_info.dst_name,
tdata->tp_info.dst_port,
tdata->buf.start));
//必须返回真,否则其它消息将不被发送
returnPJ_SUCCESS;
}
//模块实例
static pjsip_module msg_logger =
{
NULL, NULL, /* prev,next. */
{ "mod-siprtp-log", 14 }, /* Name. */
-1, /* Id */
PJSIP_MOD_PRIORITY_TRANSPORT_LAYER-1,/*Priority */
NULL, /*load() */
NULL, /*start() */
NULL, /*stop() */
NULL, /*unload() */
&logger_on_rx_msg, /*on_rx_request() */
&logger_on_rx_msg, /*on_rx_response() */
&logger_on_tx_msg, /*on_tx_request. */
&logger_on_tx_msg, /*on_tx_response() */
NULL, /*on_tsx_state() */
};
///
//订制应用程序控制台日志
static FILE *log_file;
static void app_log_writer(int level,const char *buffer,int len)
{
//同时写文件和标准输出
if(level<= app.app_log_level)
pj_log_write(level,buffer,len);
if(log_file) {
pj_size_t count = fwrite(buffer, len,1, log_file);
PJ_UNUSED_ARG(count);
fflush(log_file);
}
}
pj_status_t app_logging_init(void)
{
//重定向日志函数到我们的定制
pj_log_set_log_func( &app_log_writer );
//如果日志文件不存在,就创建它
if(app.log_filename) {
log_file =fopen(app.log_filename, "wt");
if(log_file == NULL) {
PJ_LOG(1,(THIS_FILE,"不能打开日志文件 %s",
app.log_filename));
return -1;
}
}
return PJ_SUCCESS;
}
void app_logging_shutdown(void)
{
//关闭日志文件
if(log_file) {
fclose(log_file);
log_file =NULL;
}
}
//主函数
int main(int argc,char *argv[])
{
unsigned i;
pj_status_t status;
//必须先初始化PJLIB
status =pj_init();
if(status != PJ_SUCCESS)
return1;
//取命令行参数
status =init_options(argc, argv);
if(status != PJ_SUCCESS)
return1;
//效验参数
//UAS模式不能用 Auto-quit
if(app.auto_quit && app.uri_to_call.slen == 0) {
printf("错误: --auto-quit 选项要应用于外呼模式"
"仅用于 (UAC) \n");
return1;
}
//初始化日志
status =app_logging_init();
if(status != PJ_SUCCESS)
return1;
//初始化SIP
status =init_sip();
if(status != PJ_SUCCESS) {
app_perror(THIS_FILE, "初始化错误",status);
destroy_sip();
return1;
}
//注册模块用于记录呼入/呼出消息日志
pjsip_endpt_register_module(app.sip_endpt, &msg_logger);
//初始化媒体
status =init_media();
if(status != PJ_SUCCESS) {
app_perror(THIS_FILE, "媒体初始化错误",status);
destroy_sip();
return1;
}
//启动工作线程
#if PJ_HAS_THREADS
for(i=0; i<app.thread_count; ++i) {
pj_thread_create(app.pool, "app", &sip_worker_thread, NULL,
0, 0, &app.sip_thread[i]);
}
#endif
//如果外呼URL存在,则立即创建呼叫
if(app.uri_to_call.slen) {
PJ_LOG(3,(THIS_FILE, "创建 %d 呼叫到 %s..",app.max_calls,
app.uri_to_call.ptr));
for(i=0; i<app.max_calls; ++i) {
status = make_call(&app.uri_to_call);
if (status!= PJ_SUCCESS) {
app_perror(THIS_FILE, "创建呼叫错误",status);
break;
}
pj_thread_sleep(app.call_gap);
}
if(app.auto_quit) {
//等待全部呼叫完成
while(app.uac_calls < app.max_calls)
pj_thread_sleep(100);
pj_thread_sleep(200);
} else{
#if PJ_HAS_THREADS
//启动用户界面循环
console_main();
#endif
}
} else{
PJ_LOG(3,(THIS_FILE, "已准备好,最多(max=%d)个呼叫",
app.max_calls));
#if PJ_HAS_THREADS
//启动用户界面循环
console_main();
#endif
}
#if !PJ_HAS_THREADS
PJ_LOG(3,(THIS_FILE, "按 Ctrl-C 退出"));
for(;;) {
pj_time_valt = {0, 10};
pjsip_endpt_handle_events(app.sip_endpt,&t);
}
#endif
//关闭
destroy_sip();
destroy_media();
if(app.pool) {
pj_pool_release(app.pool);
app.pool =NULL;
pj_caching_pool_destroy(&app.cp);
}
app_logging_shutdown();
//关闭PJLIB
pj_shutdown();
return0;
}