예제 #1
0
static pj_status_t init_stack()
{
    pj_sockaddr addr;
    pjsip_inv_callback inv_cb;
    pj_status_t status;

    pj_log_set_level(5);

    status = pj_init();
    CHECK_STATUS();

    pj_log_set_level(3);

    status = pjlib_util_init();
    CHECK_STATUS();

    pj_caching_pool_init(&app.cp, NULL, 0);
    app.pool = pj_pool_create( &app.cp.factory, "sipecho", 512, 512, 0);

    status = pjsip_endpt_create(&app.cp.factory, NULL, &app.sip_endpt);
    CHECK_STATUS();

    pj_log_set_level(4);
    pj_sockaddr_init(AF, &addr, NULL, (pj_uint16_t)SIP_PORT);
    if (AF == pj_AF_INET()) {
	status = pjsip_udp_transport_start( app.sip_endpt, &addr.ipv4, NULL,
					    1, NULL);
    } else if (AF == pj_AF_INET6()) {
	status = pjsip_udp_transport_start6(app.sip_endpt, &addr.ipv6, NULL,
					    1, NULL);
    } else {
	status = PJ_EAFNOTSUP;
    }

    pj_log_set_level(3);
    CHECK_STATUS();

    status = pjsip_tsx_layer_init_module(app.sip_endpt) ||
	     pjsip_ua_init_module( app.sip_endpt, NULL );
    CHECK_STATUS();

    pj_bzero(&inv_cb, sizeof(inv_cb));
    inv_cb.on_state_changed = &call_on_state_changed;
    inv_cb.on_new_session = &call_on_forked;
    inv_cb.on_media_update = &call_on_media_update;
    inv_cb.on_rx_offer = &call_on_rx_offer;

    status = pjsip_inv_usage_init(app.sip_endpt, &inv_cb) ||
	     pjsip_100rel_init_module(app.sip_endpt) ||
	     pjsip_endpt_register_module( app.sip_endpt, &mod_sipecho) ||
	     pjsip_endpt_register_module( app.sip_endpt, &msg_logger) ||
	     //pjmedia_endpt_create(&app.cp.factory,
		//		  pjsip_endpt_get_ioqueue(app.sip_endpt),
		//		  0, &app.med_endpt) ||
             pj_thread_create(app.pool, "sipecho", &worker_proc, NULL, 0, 0,
                              &app.worker_thread);
    CHECK_STATUS();

    return PJ_SUCCESS;
}
예제 #2
0
static int test_inner(void)
{
    pj_caching_pool caching_pool;
    int rc = 0;

    mem = &caching_pool.factory;

#if 1
    pj_log_set_level(3);
    pj_log_set_decor(param_log_decor);
    PJ_UNUSED_ARG(test_log_func);
#elif 1
    log_file = fopen("pjnath-test.log", "wt");
    pj_log_set_level(5);
    orig_log_func = pj_log_get_log_func();
    pj_log_set_log_func(&test_log_func);
#endif

    rc = pj_init();
    if (rc != 0) {
	app_perror("pj_init() error!!", rc);
	return rc;
    }

    pj_dump_config();
    pj_caching_pool_init( &caching_pool, &pj_pool_factory_default_policy, 0 );

    pjlib_util_init();
    pjnath_init();

#if INCLUDE_STUN_TEST
    DO_TEST(stun_test());
    DO_TEST(sess_auth_test());
#endif

#if INCLUDE_ICE_TEST
    DO_TEST(ice_test());
#endif

#if INCLUDE_STUN_SOCK_TEST
    DO_TEST(stun_sock_test());
#endif

#if INCLUDE_TURN_SOCK_TEST
    DO_TEST(turn_sock_test());
#endif

#if INCLUDE_CONCUR_TEST
    DO_TEST(concur_test());
#endif

on_return:
    if (log_file)
	fclose(log_file);
    return rc;
}
예제 #3
0
void proxy_init_all(void)
{
    pj_status_t status;

    global.port = 5060;
    global.record_route = 0;

    pj_log_set_level(5);

    status = init_stack();
    if (status != PJ_SUCCESS) {
        app_perror("Error initializing stack", status);
        return;
    }

    status = init_proxy();
    if (status != PJ_SUCCESS) {
        app_perror("Error initializing proxy", status);
        return;
    }

    status = init_stateful_proxy();
    if (status != PJ_SUCCESS) {
        app_perror("Error initializing stateful proxy", status);
        return;
    }

    return;
}
예제 #4
0
/*
 * main()
 */
int main(int argc, char *argv[])
{
    pj_caching_pool cp;
    pjmedia_endpt *med_ept;
    pjsip_endpoint *sip_ept;
    char errmsg[PJ_ERR_MSG_SIZE];
    pj_status_t code;

    if (argc != 2) {
	puts("Usage: strerror ERRNUM");
	return 1;
    }

    pj_log_set_level(3);

    pj_init();
    pj_caching_pool_init(&cp, NULL, 0);
    pjlib_util_init();
    pjnath_init();
    pjmedia_endpt_create(&cp.factory, NULL, 0, &med_ept);
    pjsip_endpt_create(&cp.factory, "localhost", &sip_ept);
    pjsip_evsub_init_module(sip_ept);

    code = atoi(argv[1]);
    pj_strerror(code, errmsg, sizeof(errmsg));

    printf("Status %d: %s\n", code, errmsg);

    pj_shutdown();
    return 0;
}
예제 #5
0
int main() {
    pj_sock_t sock;
    pj_sockaddr_in to_addr;
    char *s = "Cong hoa xa hoi chu nghia VietNam";

    char buffer[100];
    pj_ssize_t len;

    struct timeval tv_begin, tv_end, tv_diff;

    pj_log_set_level(3);
    CHECK(__FILE__, pj_init());
    pj_bzero(buffer, sizeof(buffer));
    CHECK_R( __FILE__, pj_sock_socket(PJ_AF_INET, PJ_SOCK_DGRAM, 0, &sock) );
    //udp_socket(12345, &sock);
    setup_addr_with_host_and_port(&to_addr, "127.0.0.1", 33333);

    len = strlen(s);
    gettimeofday(&tv_begin, NULL);
    pj_sock_sendto(sock, s, &len, 0, &to_addr, sizeof(to_addr));
    
    PJ_LOG(3, (__FILE__, "Sent: %s", s));
    len = 100;
    pj_sock_recv(sock, buffer, &len, 0);
    gettimeofday(&tv_end, NULL);
    int diff = timeval_subtract(&tv_diff, &tv_end, &tv_begin);
    PJ_LOG(3, (__FILE__, "Received: %s %0.2f msec", buffer, diff*1.0/1000));
    pj_shutdown();
    return 0;
}
예제 #6
0
/*
 * main()
 */
int main(int argc, char *argv[])
{
    pj_caching_pool cp;
    pj_status_t status;

    if (argc < 2 || argc > 3) {
	puts("Usage: httpdemo URL [output-filename]");
	return 1;
    }

    pj_log_set_level(5);

    pj_init();
    pj_caching_pool_init(&cp, NULL, 0);
    mem = &cp.factory;
    pjlib_util_init();

    if (argc > 2)
	f = fopen(argv[2], "wb");
    else
	f = stdout;

    status = getURL(argv[1]);
    if (status != PJ_SUCCESS) {
        PJ_PERROR(1, (THIS_FILE, status, "Error"));
    }

    if (f != stdout)
	fclose(f);

    pj_caching_pool_destroy(&cp);
    pj_shutdown();
    return 0;
}
예제 #7
0
파일: test.c 프로젝트: Jopie64/pjsip
int test_main(void)
{
    int rc = 0;
    pj_caching_pool caching_pool;

    pj_init();
    pj_caching_pool_init(&caching_pool, &pj_pool_factory_default_policy, 0);

    pj_log_set_decor(PJ_LOG_HAS_NEWLINE);
    pj_log_set_level(3);

    mem = &caching_pool.factory;

    DO_TEST(sdp_neg_test());
    //DO_TEST(sdp_test (&caching_pool.factory));
    //DO_TEST(rtp_test(&caching_pool.factory));
    //DO_TEST(session_test (&caching_pool.factory));
    DO_TEST(jbuf_main());
    DO_TEST(mips_test());
    DO_TEST(codec_test_vectors());

    PJ_LOG(3,(THIS_FILE," "));

on_return:
    if (rc != 0) {
	PJ_LOG(3,(THIS_FILE,"Test completed with error(s)!"));
    } else {
	PJ_LOG(3,(THIS_FILE,"Looks like everything is okay!"));
    }

    pj_caching_pool_destroy(&caching_pool);

    return rc;
}
예제 #8
0
int vid_codec_test(void)
{
    pj_pool_t *pool;
    int rc = 0;
    pj_status_t status;
    int orig_log_level;

    orig_log_level = pj_log_get_level();
    pj_log_set_level(3);

    PJ_LOG(3, (THIS_FILE, "Performing video codec tests.."));

    pool = pj_pool_create(mem, "Vid codec test", 256, 256, 0);

    status = pjmedia_vid_dev_subsys_init(mem);
    if (status != PJ_SUCCESS)
        return -10;

#if PJMEDIA_HAS_FFMPEG_VID_CODEC
    status = pjmedia_codec_ffmpeg_vid_init(NULL, mem);
    if (status != PJ_SUCCESS)
        return -20;
#endif

    rc = enum_codecs();
    if (rc != 0)
        goto on_return;

    rc = encode_decode_test(pool, "h263-1998", PJMEDIA_VID_PACKING_WHOLE);
    if (rc != 0)
        goto on_return;

    rc = encode_decode_test(pool, "h263-1998", PJMEDIA_VID_PACKING_PACKETS);
    if (rc != 0)
        goto on_return;

on_return:
#if PJMEDIA_HAS_FFMPEG_VID_CODEC
    pjmedia_codec_ffmpeg_vid_deinit();
#endif
    pjmedia_vid_dev_subsys_shutdown();
    pj_pool_release(pool);
    pj_log_set_level(orig_log_level);

    return rc;
}
예제 #9
0
파일: stack.cpp 프로젝트: gangbanlau/sprout
void init_pjsip_logging(int log_level,
                        pj_bool_t log_to_file,
                        const std::string& directory)
{
  pj_log_set_level(log_level);
  pj_log_set_decor(PJ_LOG_HAS_SENDER);
  pj_log_set_log_func(&pjsip_log_handler);
}
예제 #10
0
파일: test.c 프로젝트: avble/natClientEx
static int test_inner(void)
{
    pj_caching_pool caching_pool;
    int rc = 0;

    mem = &caching_pool.factory;

    pj_log_set_level(3);
    pj_log_set_decor(param_log_decor);

    rc = pj_init();
    if (rc != 0) {
	app_perror("pj_init() error!!", rc);
	return rc;
    }

    rc = pjlib_util_init();
    pj_assert(rc == 0);

    pj_dump_config();
    pj_caching_pool_init( &caching_pool, &pj_pool_factory_default_policy, 0 );

#if INCLUDE_XML_TEST
    DO_TEST(xml_test());
#endif

#if INCLUDE_JSON_TEST
    DO_TEST(json_test());
#endif

#if INCLUDE_ENCRYPTION_TEST
    DO_TEST(encryption_test());
    DO_TEST(encryption_benchmark());
#endif

#if INCLUDE_STUN_TEST
    DO_TEST(stun_test());
#endif

#if INCLUDE_RESOLVER_TEST
    DO_TEST(resolver_test());
#endif

#if INCLUDE_HTTP_CLIENT_TEST
    DO_TEST(http_client_test());
#endif

on_return:
    return rc;
}
예제 #11
0
파일: main.c 프로젝트: LuLei2013/pjproject
int main()
{
    pj_turn_srv *srv;
    pj_turn_listener *listener;
    pj_status_t status;

    status = pj_init();
    if (status != PJ_SUCCESS)
	return err("pj_init() error", status);

    pjlib_util_init();
    pjnath_init();

    pj_caching_pool_init(&g_cp, NULL, 0);

    pj_turn_auth_init(REALM);

    status = pj_turn_srv_create(&g_cp.factory, &srv);
    if (status != PJ_SUCCESS)
	return err("Error creating server", status);

    status = pj_turn_listener_create_udp(srv, pj_AF_INET(), NULL, 
					 TURN_PORT, 1, 0, &listener);
    if (status != PJ_SUCCESS)
	return err("Error creating UDP listener", status);

#if PJ_HAS_TCP
    status = pj_turn_listener_create_tcp(srv, pj_AF_INET(), NULL, 
					 TURN_PORT, 1, 0, &listener);
    if (status != PJ_SUCCESS)
	return err("Error creating listener", status);
#endif

    status = pj_turn_srv_add_listener(srv, listener);
    if (status != PJ_SUCCESS)
	return err("Error adding listener", status);

    puts("Server is running");

    pj_log_set_level(LOG_LEVEL);

    console_main(srv);

    pj_turn_srv_destroy(srv);
    pj_caching_pool_destroy(&g_cp);
    pj_shutdown();

    return 0;
}
예제 #12
0
static int test_inner(void)
{
    pj_caching_pool caching_pool;
    int rc = 0;

    mem = &caching_pool.factory;

#if 1
    pj_log_set_level(5);
    pj_log_set_decor(param_log_decor);
#endif

    rc = pj_init();
    if (rc != 0) {
	app_perror("pj_init() error!!", rc);
	return rc;
    }
    
    pj_dump_config();
    pj_caching_pool_init( &caching_pool, &pj_pool_factory_default_policy, 0 );

    pjlib_util_init();
    pjnath_init();

#if INCLUDE_STUN_TEST
    DO_TEST(stun_test());
    DO_TEST(sess_auth_test());
#endif

#if INCLUDE_ICE_TEST
    DO_TEST(ice_test());
#endif

#if INCLUDE_STUN_SOCK_TEST
    DO_TEST(stun_sock_test());
#endif

#if INCLUDE_TURN_SOCK_TEST
    DO_TEST(turn_sock_test());
#endif

on_return:
    return rc;
}
예제 #13
0
파일: main.c 프로젝트: mocidis/object-pool
int main() {
    pj_caching_pool cp;
    pj_pool_t *pool;
    int i;
    pj_thread_t *thread1;
    
    pj_log_set_level(3);
    CHECK(__FILE__, pj_init());
    pj_srand(123765);
    pj_caching_pool_init(&cp, NULL, 1024);

    pool = pj_pool_create(&cp.factory, "objpool", 128, 128, NULL);

    pj_thread_create(pool, "thread1", &do_test, pool, PJ_THREAD_DEFAULT_STACK_SIZE, 0, &thread1);
    pj_thread_sleep(500);
    do_test(pool);

    pj_thread_join(thread1);

    pj_pool_release(pool);
    pj_caching_pool_destroy(&cp);
    pj_shutdown();
    return 0;
}
예제 #14
0
pj_status_t latency_checker::start(latency_config_t &config)
{
	pj_status_t result = PJ_EINVAL;
	if(m_pool == NULL)
	{
		m_dstate = 0;
		m_start_tone_time.u64 = 0;
		m_latency = 0;
		m_quality = 0;
		m_config = config;
		m_status_string[0] = 0;
		m_gain = new snd_agc("",30,1,32000,32000);
		m_idle_freq1_det = new tone_detector(m_config.clock_rate,IDLE_FREQ1);
		m_idle_freq2_det = new tone_detector(m_config.clock_rate,IDLE_FREQ2);
		m_active_freq1_det = new tone_detector(m_config.clock_rate,ACTIVE_FREQ1);
		m_active_freq2_det = new tone_detector(m_config.clock_rate,ACTIVE_FREQ2);

		init_generate_dual_tone(&m_idle_tone,m_config.clock_rate,IDLE_FREQ1,IDLE_FREQ2,32767);
		init_generate_dual_tone(&m_active_tone,m_config.clock_rate,ACTIVE_FREQ1,ACTIVE_FREQ2,32767);
		pj_log_set_level(0);
		pj_log_set_decor(PJ_LOG_HAS_NEWLINE | PJ_LOG_HAS_SENDER | PJ_LOG_HAS_TIME | PJ_LOG_HAS_MICRO_SEC);
		if(pj_init()==PJ_SUCCESS)
		{
			m_caching_pool = (pj_caching_pool *)malloc(sizeof(pj_caching_pool));
			pj_caching_pool_init( m_caching_pool, NULL, 0 );
			m_pool_factory=&m_caching_pool->factory;
			m_pool = pj_pool_create(m_pool_factory, "LATENCY NATIVE", 4000, 4000, NULL);
			pj_log_set_level(m_config.logs.level);
			pj_logging_init(m_pool);
			pj_logging_setLogToConsole(1);

			pj_logging_setFilename(m_config.logs.file_name);
			pj_logging_setMaxLogFiles(m_config.logs.max_files);
			pj_logging_setMaxLogFileSize(m_config.logs.max_file_size*1024*1024);
			pj_logging_start();

			pj_get_timestamp(&m_last_get_frame_time);

			m_lock = new PPJ_SemaphoreLock(m_pool,NULL,1,1);

			pjmedia_aud_subsys_init(m_pool_factory);
#if PJMEDIA_AUDIO_DEV_HAS_ANDROID
#if PJ_ANDROID_DEVICE==1
			pjmedia_aud_register_factory(&pjmedia_android_factory);
#endif
#if PJ_ANDROID_DEVICE==2
			pjmedia_aud_register_factory(&pjmedia_opensl_factory);
#endif
#if PJ_ANDROID_DEVICE==3
			pjmedia_aud_register_factory(&pjmedia_alsa_factory);
#endif
#endif

			pjmedia_aud_param params;
			params.dir = PJMEDIA_DIR_CAPTURE_PLAYBACK;
			params.rec_id = 1;
			params.play_id = 6;
			params.clock_rate = m_config.clock_rate;
			params.channel_count = 1;
			params.samples_per_frame = m_config.min_frame_length*m_config.clock_rate/1000;
			params.bits_per_sample = 16;
			params.flags = PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY | PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY;
			params.input_latency_ms = m_config.min_frame_length;
			params.output_latency_ms = m_config.min_frame_length;
			result = pjmedia_aud_stream_create(&params,&rec_cb_s,&play_cb_s,this,&m_aud_stream);

			if(result==PJ_SUCCESS)
			{
				result = pjmedia_aud_stream_start(m_aud_stream);
				if(result==PJ_SUCCESS)
				{


				}

			}
		}
	}

	if(result!=PJ_SUCCESS)
		internal_clean();
	return result;
}
예제 #15
0
int jbuf_main(void)
{
    FILE *input;
    pj_bool_t data_eof = PJ_FALSE;
    int old_log_level;
    int rc = 0;
    const char* input_filename = "Jbtest.dat";
    const char* input_search_path[] = { 
	"../build",
	"pjmedia/build",
	"build"
    };

    /* Try to open test data file in the working directory */
    input = fopen(input_filename, "rt");

    /* If that fails, try to open test data file in specified search paths */
    if (input == NULL) {
	char input_path[PJ_MAXPATH];
	int i;

	for (i = 0; !input && i < PJ_ARRAY_SIZE(input_search_path); ++i) {
	    pj_ansi_snprintf(input_path, PJ_MAXPATH, "%s/%s",
			     input_search_path[i],
			     input_filename);
	    input = fopen(input_path, "rt");
	}
    }
    
    /* Failed to open test data file. */
    if (input == NULL) {
	printf("Failed to open test data file, Jbtest.dat\n");
	return -1;
    }

    old_log_level = pj_log_get_level();
    pj_log_set_level(5);

    while (rc == 0 && !data_eof) {
	pj_str_t jb_name = {"JBTEST", 6};
	pjmedia_jbuf *jb;
	pj_pool_t *pool;
	pjmedia_jb_state state;
	pj_uint16_t last_seq = 0;
	pj_uint16_t seq = 1;
	char line[1024], *p = NULL;

	test_param_t param;
	test_cond_t cond;

	param.adaptive = PJ_TRUE;
	param.init_prefetch = JB_INIT_PREFETCH;
	param.min_prefetch = JB_MIN_PREFETCH;
	param.max_prefetch = JB_MAX_PREFETCH;

	cond.burst = -1;
	cond.delay = -1;
	cond.discard = -1;
	cond.empty = -1;
	cond.lost = -1;

	printf("\n\n");

	/* Parse test session title, param, and conditions */
	do {
	    p = fgets(line, sizeof(line), input);
	} while (p && parse_test_headers(line, &param, &cond));

	/* EOF test data */
	if (p == NULL)
	    break;

	//printf("======================================================\n");

	/* Initialize test session */
	pool = pj_pool_create(mem, "JBPOOL", 256*16, 256*16, NULL);
	pjmedia_jbuf_create(pool, &jb_name, 1, JB_PTIME, JB_BUF_SIZE, &jb);
	pjmedia_jbuf_reset(jb);

	if (param.adaptive) {
	    pjmedia_jbuf_set_adaptive(jb, 
				      param.init_prefetch, 
				      param.min_prefetch,
				      param.max_prefetch);
	} else {
	    pjmedia_jbuf_set_fixed(jb, param.init_prefetch);
	}

#ifdef REPORT
	pjmedia_jbuf_get_state(jb, &state);
	printf("Initial\tsize=%d\tprefetch=%d\tmin.pftch=%d\tmax.pftch=%d\n", 
	       state.size, state.prefetch, state.min_prefetch, 
	       state.max_prefetch);
#endif


	/* Test session start */
	while (1) {
	    char c;
	    
	    /* Get next line of test data */
	    if (!p || *p == 0) {
		p = fgets(line, sizeof(line), input);
		if (p == NULL) {
		    data_eof = PJ_TRUE;
		    break;
		}
	    }

	    /* Get next char of test data */
	    c = *p++;

	    /* Skip spaces */
	    if (isspace(c))
		continue;

	    /* Print comment line */
	    if (c == '#') {
#ifdef PRINT_COMMENT
		while (*p && isspace(*p)) ++p;
		if (*p) printf("..%s", p);
#endif
		*p = 0;
		continue;
	    }

	    /* Process test data */
	    if (!process_test_data(c, jb, &seq, &last_seq))
		break;
	}

	/* Print JB states */
	pjmedia_jbuf_get_state(jb, &state);
	printf("------------------------------------------------------\n");
	printf("Summary:\n");
	printf("  size=%d prefetch=%d\n", state.size, state.prefetch);
	printf("  delay (min/max/avg/dev)=%d/%d/%d/%d ms\n",
	       state.min_delay, state.max_delay, state.avg_delay, 
	       state.dev_delay);
	printf("  lost=%d discard=%d empty=%d burst(avg)=%d\n", 
	       state.lost, state.discard, state.empty, state.avg_burst);

	/* Evaluate test session */
	if (cond.burst >= 0 && (int)state.avg_burst > cond.burst) {
	    printf("! 'Burst' should be %d, it is %d\n", 
		   cond.burst, state.avg_burst);
	    rc |= 1;
	}
	if (cond.delay >= 0 && (int)state.avg_delay/JB_PTIME > cond.delay) {
	    printf("! 'Delay' should be %d, it is %d\n", 
		   cond.delay, state.avg_delay/JB_PTIME);
	    rc |= 2;
	}
	if (cond.discard >= 0 && (int)state.discard > cond.discard) {
	    printf("! 'Discard' should be %d, it is %d\n",
		   cond.discard, state.discard);
	    rc |= 4;
	}
	if (cond.empty >= 0 && (int)state.empty > cond.empty) {
	    printf("! 'Empty' should be %d, it is %d\n", 
		   cond.empty, state.empty);
	    rc |= 8;
	}
	if (cond.lost >= 0 && (int)state.lost > cond.lost) {
	    printf("! 'Lost' should be %d, it is %d\n", 
		   cond.lost, state.lost);
	    rc |= 16;
	}

	pjmedia_jbuf_destroy(jb);
	pj_pool_release(pool);
    }

    fclose(input);
    pj_log_set_level(old_log_level);

    return rc;
}
예제 #16
0
/*
 * main()
 */
int main(int argc, char *argv[])
{
    pj_status_t status;

    global.port = 5060;
    pj_log_set_level(4);

    status = init_options(argc, argv);
    if (status != PJ_SUCCESS)
	return 1;

    status = init_stack();
    if (status != PJ_SUCCESS) {
	app_perror("Error initializing stack", status);
	return 1;
    }

    status = init_proxy();
    if (status != PJ_SUCCESS) {
	app_perror("Error initializing proxy", status);
	return 1;
    }

    status = init_stateless_proxy();
    if (status != PJ_SUCCESS) {
	app_perror("Error initializing stateless proxy", status);
	return 1;
    }

#if PJ_HAS_THREADS
    status = pj_thread_create(global.pool, "sproxy", &worker_thread, 
			      NULL, 0, 0, &global.thread);
    if (status != PJ_SUCCESS) {
	app_perror("Error creating thread", status);
	return 1;
    }

    while (!global.quit_flag) {
	char line[10];

	puts("\n"
	     "Menu:\n"
	     "  q    quit\n"
	     "  d    dump status\n"
	     "  dd   dump detailed status\n"
	     "");

	if (fgets(line, sizeof(line), stdin) == NULL) {
	    puts("EOF while reading stdin, will quit now..");
	    global.quit_flag = PJ_TRUE;
	    break;
	}

	if (line[0] == 'q') {
	    global.quit_flag = PJ_TRUE;
	} else if (line[0] == 'd') {
	    pj_bool_t detail = (line[1] == 'd');
	    pjsip_endpt_dump(global.endpt, detail);
#if STATEFUL
	    pjsip_tsx_layer_dump(detail);
#endif
	}
    }

    pj_thread_join(global.thread);

#else
    puts("\nPress Ctrl-C to quit\n");
    for (;;) {
	pj_time_val delay = {0, 0};
	pjsip_endpt_handle_events(global.endpt, &delay);
    }
#endif

    destroy_stack();

    return 0;
}
예제 #17
0
JNIEXPORT jint JNICALL Java_org_sipdroid_pjlib_codec_open
  (JNIEnv *env, jclass cls, jstring codec_id) {
    int rc = 0;
    unsigned count = 1;

    LOGE("Intializing PJLIB...");
    pj_init();
    pj_caching_pool_init(&caching_pool, &pj_pool_factory_default_policy, 0);

    pj_log_set_decor(PJ_LOG_HAS_NEWLINE);
    pj_log_set_level(3);

    mem = &caching_pool.factory;

    char* ctmp;
    jboolean iscopy;
    const char *codec_str = env->GetStringUTFChars(codec_id, &iscopy);
    ctmp = const_cast<char*>(codec_str);
    const pj_str_t pj_codec_str = pj_str(ctmp);

    unsigned clock_rate = 8000;

    LOGE("pj_pool_create");

    pool = pj_pool_create(mem, "pool", 1024, 1024, NULL);

    LOGE("PJ_POOL_ZALLOC_T");
    cp = PJ_POOL_ZALLOC_T(pool, struct codec_port);

    LOGE("pjmedia_endpt_create");
    status = pjmedia_endpt_create(mem, NULL, 0, &cp->endpt);
    if (status != PJ_SUCCESS)
	return NULL;

    cm = pjmedia_endpt_get_codec_mgr(cp->endpt);
#if PJMEDIA_HAS_G711_CODEC
    CHECK( pjmedia_codec_g711_init(cp->endpt) );
#endif
#if PJMEDIA_HAS_GSM_CODEC
    CHECK( pjmedia_codec_gsm_init(cp->endpt) );
#endif
#if PJMEDIA_HAS_ILBC_CODEC
    CHECK( pjmedia_codec_ilbc_init(cp->endpt, 30) );
#endif
#if PJMEDIA_HAS_SPEEX_CODEC
    CHECK( pjmedia_codec_speex_init(cp->endpt, 0, 5, 5) );
#endif
#if PJMEDIA_HAS_G722_CODEC
    CHECK( pjmedia_codec_g722_init(cp->endpt) );
#endif

     LOGE("pjmedia_codec_mgr_find_codecs_by_id: %s", codec_str);
     CHECK( status = pjmedia_codec_mgr_find_codecs_by_id(cm,
						 &pj_codec_str, &count, &ci, NULL) );
    if (status != PJ_SUCCESS) {
        LOGE("Cannot find codec");
	return NULL;
    }


    LOGE("pjmedia_codec_mgr_get_default_param");
    CHECK( status = pjmedia_codec_mgr_get_default_param(cm, ci, &param) );

    if (status != PJ_SUCCESS) {
        LOGE("pjmedia_codec_mgr_get_default_param failed");
	return NULL;
    }
    
    //param.setting.vad = 1;

    LOGE("pjmedia_codec_mgr_alloc_codec");
    CHECK( status = pjmedia_codec_mgr_alloc_codec(cm, ci, &cp->codec) );
    if (status != PJ_SUCCESS) {
        LOGE("Cannot allocate codec");
	return NULL;
    }


    LOGE("codec->op->init"); // channels=%d frm_ptime=%s", ci->channel_cnt, param.info.frm_ptime);
    status = (*cp->codec->op->init)(cp->codec, pool);
    if (status != PJ_SUCCESS)
	return NULL;

     LOGE("codec->op->open");
    status = cp->codec->op->open(cp->codec, &param);
    if (status != PJ_SUCCESS)
	return NULL;

    samples_per_frame = param.info.clock_rate * param.info.frm_ptime / 1000;

    LOGE("Finished initializing codec...");
    LOGE(" -> clock_rate=%d channel_count=%d samples_per_frame=%d pcm_bits_per_sample=%d", param.info.clock_rate, param.info.channel_cnt, \
									samples_per_frame, param.info.pcm_bits_per_sample);
    return (jint)PJ_SUCCESS;
}
예제 #18
0
int main()
{
    pj_caching_pool cp;
    pjmedia_endpt *med_endpt;
    pj_pool_t *pool;
    pjmedia_conf *conf;
    int i;
    pjmedia_port *sine_port[SINE_COUNT], *null_port, *conf_port;
    pjmedia_port *nulls[NULL_COUNT];
    unsigned null_slots[NULL_COUNT];
    pjmedia_master_port *master_port;
    pj_status_t status;


    pj_log_set_level(3);

    status = pj_init();
    PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);

    pj_caching_pool_init(&cp, &pj_pool_factory_default_policy, 0);
    pool = pj_pool_create( &cp.factory,	    /* pool factory	    */
			   "wav",	    /* pool name.	    */
			   4000,	    /* init size	    */
			   4000,	    /* increment size	    */
			   NULL		    /* callback on error    */
			   );

    status = pjmedia_endpt_create(&cp.factory, NULL, 1, &med_endpt);
    PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);



    status = pjmedia_conf_create( pool,
				  PORT_COUNT,
				  CLOCK_RATE,
				  1, SAMPLES_PER_FRAME, 16,
				  PJMEDIA_CONF_NO_DEVICE,
				  &conf);
    if (status != PJ_SUCCESS) {
	app_perror(THIS_FILE, "Unable to create conference bridge", status);
	return 1;
    }

    printf("Resampling is %s\n", (HAS_RESAMPLE?"active":"disabled"));

    /* Create Null ports */
    printf("Creating %d null ports..\n", NULL_COUNT);
    for (i=0; i<NULL_COUNT; ++i) {
	status = pjmedia_null_port_create(pool, CLOCK_RATE, 1, SAMPLES_PER_FRAME*2, 16, &nulls[i]);
	PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);

	status = pjmedia_conf_add_port(conf, pool, nulls[i], NULL, &null_slots[i]);
	PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);
    }

    /* Create sine ports. */
    printf("Creating %d sine generator ports..\n", SINE_COUNT);
    for (i=0; i<SINE_COUNT; ++i) {
	unsigned j, slot;

	/* Load the WAV file to file port. */
	status = create_sine_port(pool, SINE_CLOCK, 1, &sine_port[i]);
	PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);

	/* Add the file port to conference bridge */
	status = pjmedia_conf_add_port( conf,		/* The bridge	    */
					pool,		/* pool		    */
					sine_port[i],	/* port to connect  */
					NULL,		/* Use port's name  */
					&slot		/* ptr for slot #   */
					);
	if (status != PJ_SUCCESS) {
	    app_perror(THIS_FILE, "Unable to add conference port", status);
	    return 1;
	}

	status = pjmedia_conf_connect_port(conf, slot, 0, 0);
	PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);

	for (j=0; j<NULL_COUNT; ++j) {
	    status = pjmedia_conf_connect_port(conf, slot, null_slots[j], 0);
	    PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);
	}
    }

    /* Create idle ports */
    printf("Creating %d idle ports..\n", IDLE_COUNT);
    for (i=0; i<IDLE_COUNT; ++i) {
	pjmedia_port *dummy;
	status = pjmedia_null_port_create(pool, CLOCK_RATE, 1, SAMPLES_PER_FRAME, 16, &dummy);
	PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);
	status = pjmedia_conf_add_port(conf, pool, dummy, NULL, NULL);
	PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);
    }

    /* Create null port */
    status = pjmedia_null_port_create(pool, CLOCK_RATE, 1, SAMPLES_PER_FRAME, 16,
				      &null_port);
    PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);

    conf_port = pjmedia_conf_get_master_port(conf);

    /* Create master port */
    status = pjmedia_master_port_create(pool, null_port, conf_port, 0, &master_port);


    pjmedia_master_port_start(master_port);

    puts("Waiting to settle.."); fflush(stdout);
    pj_thread_sleep(5000);


    benchmark();


    /* Done. */
    return 0;
}
예제 #19
0
/*
 * main()
 */
int main(int argc, char *argv[])
{
    pj_caching_pool cp;
    pjmedia_endpt *med_endpt;
    pj_pool_t *pool;
    pjmedia_port *file_ori_port;
    pjmedia_port *file_deg_port;
    pj_status_t status;
    unsigned first_nsamples = 0;
    unsigned samples_compared = 0;

    char buf1[BYTES_PER_FRAME];
    char buf2[BYTES_PER_FRAME];

    double ref_mag = 0;
    double deg_mag = 0;
    double mix_mag = 0;

    int detail = 0;
    int res_deg, res_mix, res_overall;

    if (argc < 3) {
    	puts("Error: original & degraded filename required");
	puts(desc);
	return 1;
    }

    /* Set log level. */
    pj_log_set_level(3);

    /* Must init PJLIB first: */
    status = pj_init();
    PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);

    /* Must create a pool factory before we can allocate any memory. */
    pj_caching_pool_init(&cp, &pj_pool_factory_default_policy, 0);

    /* 
     * Initialize media endpoint.
     * This will implicitly initialize PJMEDIA too.
     */
    status = pjmedia_endpt_create(&cp.factory, NULL, 1, &med_endpt);
    PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);

    /* Create memory pool for our file player */
    pool = pj_pool_create( &cp.factory,	    /* pool factory	    */
			   "wav",	    /* pool name.	    */
			   4000,	    /* init size	    */
			   4000,	    /* increment size	    */
			   NULL		    /* callback on error    */
			   );

    /* Create file media port from the original WAV file */
    status = pjmedia_wav_player_port_create(  pool,	/* memory pool	    */
					      argv[1],	/* file to play	    */
					      40,	/* ptime.	    */
					      PJMEDIA_FILE_NO_LOOP,	/* flags	    */
					      0,	/* default buffer   */
					      &file_ori_port/* returned port    */
					      );
    if (status != PJ_SUCCESS) {
	app_perror(THIS_FILE, "Unable to use WAV file", status);
	return 1;
    }

    /* Create file media port from the degraded WAV file */
    status = pjmedia_wav_player_port_create(  pool,	/* memory pool	    */
					      argv[2],	/* file to play	    */
					      40,	/* ptime.	    */
					      PJMEDIA_FILE_NO_LOOP,	/* flags	    */
					      0,	/* default buffer   */
					      &file_deg_port/* returned port    */
					      );
    if (status != PJ_SUCCESS) {
	app_perror(THIS_FILE, "Unable to use WAV file", status);
	return 1;
    }

    if (file_ori_port->info.clock_rate != file_deg_port->info.clock_rate) {
	app_perror(THIS_FILE, "Clock rates must be same.", PJ_EINVAL);
	return 1;
    }

    if (argc > 3)
	first_nsamples = atoi(argv[3]) * file_ori_port->info.clock_rate / 1000;

    if (argc > 4)
	detail = atoi(argv[4]);

    while (1) {
	pjmedia_frame f1, f2;

	f1.buf = buf1;
	f1.size = BYTES_PER_FRAME;
	f2.buf = buf2;
	f2.size = BYTES_PER_FRAME;

	status = pjmedia_port_get_frame(file_ori_port, &f1);
	if (status == PJ_EEOF) {
	    break;
	} else if (status != PJ_SUCCESS) {
	    app_perror(THIS_FILE, "Error occured while reading file", status);
	    break;
	}
	status = pjmedia_port_get_frame(file_deg_port, &f2);
	if (status == PJ_EEOF) {
	    break;
	} else if (status != PJ_SUCCESS) {
	    app_perror(THIS_FILE, "Error occured while reading file", status);
	    break;
	}

	/* Calculate magnitudes */
	ref_mag += sum_mult_sig(f1.buf, f1.buf, BYTES_PER_FRAME >> 1);
	deg_mag += sum_mult_sig(f2.buf, f2.buf, BYTES_PER_FRAME >> 1);
	mix_mag += sum_mult_sig(f1.buf, f2.buf, BYTES_PER_FRAME >> 1);

	samples_compared += BYTES_PER_FRAME >> 1;
	if (first_nsamples && samples_compared >= first_nsamples)
	    break;
    }

    /* Degraded magnitude compared to reference magnitude 
     */
    res_deg = (int) (deg_mag / ref_mag * 100.0);
    if (res_deg < 0)
	res_deg = -1;
    else if (res_deg >= 81)
	res_deg = 9;
    else
	res_deg = pj_isqrt(res_deg);

    /* Mixed magnitude (don't know what this is actually :D) compared to 
     * reference magnitude 
     */
    res_mix = (int) (mix_mag / ref_mag * 100.0);
    if (res_mix < 0)
	res_mix = -1;
    else if (res_mix >= 81)
	res_mix = 9;
    else
	res_mix = pj_isqrt(res_mix);

    /* Overall score.
     * If mixed score is -1, then overall score should be -1 as well.
     * Apply no weighting (1:1) for now.
     */
    if (res_mix == -1)
	res_overall = -1;
    else
	res_overall = (res_mix*1 + res_deg*1) / 2;

    if (detail) {
	printf("Reference = %.0f\n", ref_mag);
	printf("Degraded  = %.0f\n", deg_mag);
	printf("Mixed     = %.0f\n", mix_mag);

	printf("\n");

	printf("Score 1   = %d\n", res_deg);
	printf("Score 2   = %d\n", res_mix);

	printf("\n");
    }

    printf("Overall   = %d\n", res_overall);

    /* Destroy file port */
    status = pjmedia_port_destroy( file_ori_port );
    PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);

    status = pjmedia_port_destroy( file_deg_port );
    PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);

    /* Release application pool */
    pj_pool_release( pool );

    /* Destroy media endpoint. */
    pjmedia_endpt_destroy( med_endpt );

    /* Destroy pool factory */
    pj_caching_pool_destroy( &cp );

    /* Shutdown PJLIB */
    pj_shutdown();


    /* Done. */
    return 0;
}
예제 #20
0
/*
 * main()
 *
 * If called with argument, treat argument as SIP URL to be called.
 * Otherwise wait for incoming calls.
 */
int main(int argc, char *argv[])
{
    pj_pool_t *pool = NULL;
    pj_status_t status;
    unsigned i;

    /* Must init PJLIB first: */
    status = pj_init();
    PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);

    pj_log_set_level(5);

    /* Then init PJLIB-UTIL: */
    status = pjlib_util_init();
    PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);


    /* Must create a pool factory before we can allocate any memory. */
    pj_caching_pool_init(&cp, &pj_pool_factory_default_policy, 0);


    /* Create global endpoint: */
    {
	const pj_str_t *hostname;
	const char *endpt_name;

	/* Endpoint MUST be assigned a globally unique name.
	 * The name will be used as the hostname in Warning header.
	 */

	/* For this implementation, we'll use hostname for simplicity */
	hostname = pj_gethostname();
	endpt_name = hostname->ptr;

	/* Create the endpoint: */

	status = pjsip_endpt_create(&cp.factory, endpt_name, 
				    &g_endpt);
	PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);
    }


    /* 
     * Add UDP transport, with hard-coded port 
     * Alternatively, application can use pjsip_udp_transport_attach() to
     * start UDP transport, if it already has an UDP socket (e.g. after it
     * resolves the address with STUN).
     */
    {
	pj_sockaddr addr;

	pj_sockaddr_init(AF, &addr, NULL, (pj_uint16_t)SIP_PORT);
	
	if (AF == pj_AF_INET()) {
	    status = pjsip_udp_transport_start( g_endpt, &addr.ipv4, NULL, 
						1, NULL);
	} else if (AF == pj_AF_INET6()) {
	    status = pjsip_udp_transport_start6(g_endpt, &addr.ipv6, NULL,
						1, NULL);
	} else {
	    status = PJ_EAFNOTSUP;
	}

	if (status != PJ_SUCCESS) {
	    app_perror(THIS_FILE, "Unable to start UDP transport", status);
	    return 1;
	}
    }


    /* 
     * Init transaction layer.
     * This will create/initialize transaction hash tables etc.
     */
    status = pjsip_tsx_layer_init_module(g_endpt);
    PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);


    /* 
     * Initialize UA layer module.
     * This will create/initialize dialog hash tables etc.
     */
    status = pjsip_ua_init_module( g_endpt, NULL );
    PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);


    /* 
     * Init invite session module.
     * The invite session module initialization takes additional argument,
     * i.e. a structure containing callbacks to be called on specific
     * occurence of events.
     *
     * The on_state_changed and on_new_session callbacks are mandatory.
     * Application must supply the callback function.
     *
     * We use on_media_update() callback in this application to start
     * media transmission.
     */
    {
	pjsip_inv_callback inv_cb;

	/* Init the callback for INVITE session: */
	pj_bzero(&inv_cb, sizeof(inv_cb));
	inv_cb.on_state_changed = &call_on_state_changed;
	inv_cb.on_new_session = &call_on_forked;
	inv_cb.on_media_update = &call_on_media_update;

	/* Initialize invite session module:  */
	status = pjsip_inv_usage_init(g_endpt, &inv_cb);
	PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);
    }

    /* Initialize 100rel support */
    status = pjsip_100rel_init_module(g_endpt);
    PJ_ASSERT_RETURN(status == PJ_SUCCESS, status);

    /*
     * Register our module to receive incoming requests.
     */
    status = pjsip_endpt_register_module( g_endpt, &mod_simpleua);
    PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);

    /*
     * Register message logger module.
     */
    status = pjsip_endpt_register_module( g_endpt, &msg_logger);
    PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);


    /* 
     * Initialize media endpoint.
     * This will implicitly initialize PJMEDIA too.
     */
#if PJ_HAS_THREADS
    status = pjmedia_endpt_create(&cp.factory, NULL, 1, &g_med_endpt);
#else
    status = pjmedia_endpt_create(&cp.factory, 
				  pjsip_endpt_get_ioqueue(g_endpt), 
				  0, &g_med_endpt);
#endif
    PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);

    /* 
     * Add PCMA/PCMU codec to the media endpoint. 
     */
#if defined(PJMEDIA_HAS_G711_CODEC) && PJMEDIA_HAS_G711_CODEC!=0
    status = pjmedia_codec_g711_init(g_med_endpt);
    PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);
#endif


#if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0)
    /* Init video subsystem */
    pool = pjmedia_endpt_create_pool(g_med_endpt, "Video subsystem", 512, 512);
    status = pjmedia_video_format_mgr_create(pool, 64, 0, NULL);
    PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);
    status = pjmedia_converter_mgr_create(pool, NULL);
    PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);
    status = pjmedia_vid_codec_mgr_create(pool, NULL);
    PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);
    status = pjmedia_vid_dev_subsys_init(&cp.factory);
    PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);

#  if defined(PJMEDIA_HAS_FFMPEG_VID_CODEC) && PJMEDIA_HAS_FFMPEG_VID_CODEC!=0
    /* Init ffmpeg video codecs */
    status = pjmedia_codec_ffmpeg_vid_init(NULL, &cp.factory);
    PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);
#  endif  /* PJMEDIA_HAS_FFMPEG_VID_CODEC */

#endif	/* PJMEDIA_HAS_VIDEO */
    
    /* 
     * Create media transport used to send/receive RTP/RTCP socket.
     * One media transport is needed for each call. Application may
     * opt to re-use the same media transport for subsequent calls.
     */
    for (i = 0; i < PJ_ARRAY_SIZE(g_med_transport); ++i) {
	status = pjmedia_transport_udp_create3(g_med_endpt, AF, NULL, NULL, 
					       RTP_PORT + i*2, 0, 
					       &g_med_transport[i]);
	if (status != PJ_SUCCESS) {
	    app_perror(THIS_FILE, "Unable to create media transport", status);
	    return 1;
	}

	/* 
	 * Get socket info (address, port) of the media transport. We will
	 * need this info to create SDP (i.e. the address and port info in
	 * the SDP).
	 */
	pjmedia_transport_info_init(&g_med_tpinfo[i]);
	pjmedia_transport_get_info(g_med_transport[i], &g_med_tpinfo[i]);

	pj_memcpy(&g_sock_info[i], &g_med_tpinfo[i].sock_info,
		  sizeof(pjmedia_sock_info));
    }

    /*
     * If URL is specified, then make call immediately.
     */
    if (argc > 1) {
	pj_sockaddr hostaddr;
	char hostip[PJ_INET6_ADDRSTRLEN+2];
	char temp[80];
	pj_str_t dst_uri = pj_str(argv[1]);
	pj_str_t local_uri;
	pjsip_dialog *dlg;
	pjmedia_sdp_session *local_sdp;
	pjsip_tx_data *tdata;

	if (pj_gethostip(AF, &hostaddr) != PJ_SUCCESS) {
	    app_perror(THIS_FILE, "Unable to retrieve local host IP", status);
	    return 1;
	}
	pj_sockaddr_print(&hostaddr, hostip, sizeof(hostip), 2);

	pj_ansi_sprintf(temp, "<sip:simpleuac@%s:%d>", 
			hostip, SIP_PORT);
	local_uri = pj_str(temp);

	/* Create UAC dialog */
	status = pjsip_dlg_create_uac( pjsip_ua_instance(), 
				       &local_uri,  /* local URI */
				       &local_uri,  /* local Contact */
				       &dst_uri,    /* remote URI */
				       &dst_uri,    /* remote target */
				       &dlg);	    /* dialog */
	if (status != PJ_SUCCESS) {
	    app_perror(THIS_FILE, "Unable to create UAC dialog", status);
	    return 1;
	}

	/* If we expect the outgoing INVITE to be challenged, then we should
	 * put the credentials in the dialog here, with something like this:
	 *
	    {
		pjsip_cred_info	cred[1];

		cred[0].realm	  = pj_str("sip.server.realm");
		cred[0].scheme    = pj_str("digest");
		cred[0].username  = pj_str("theuser");
		cred[0].data_type = PJSIP_CRED_DATA_PLAIN_PASSWD;
		cred[0].data      = pj_str("thepassword");

		pjsip_auth_clt_set_credentials( &dlg->auth_sess, 1, cred);
	    }
	 *
	 */


	/* Get the SDP body to be put in the outgoing INVITE, by asking
	 * media endpoint to create one for us.
	 */
	status = pjmedia_endpt_create_sdp( g_med_endpt,	    /* the media endpt	*/
					   dlg->pool,	    /* pool.		*/
					   MAX_MEDIA_CNT,   /* # of streams	*/
					   g_sock_info,     /* RTP sock info	*/
					   &local_sdp);	    /* the SDP result	*/
	PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);



	/* Create the INVITE session, and pass the SDP returned earlier
	 * as the session's initial capability.
	 */
	status = pjsip_inv_create_uac( dlg, local_sdp, 0, &g_inv);
	PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);

	/* If we want the initial INVITE to travel to specific SIP proxies,
	 * then we should put the initial dialog's route set here. The final
	 * route set will be updated once a dialog has been established.
	 * To set the dialog's initial route set, we do it with something
	 * like this:
	 *
	    {
		pjsip_route_hdr route_set;
		pjsip_route_hdr *route;
		const pj_str_t hname = { "Route", 5 };
		char *uri = "sip:proxy.server;lr";

		pj_list_init(&route_set);

		route = pjsip_parse_hdr( dlg->pool, &hname, 
					 uri, strlen(uri),
					 NULL);
		PJ_ASSERT_RETURN(route != NULL, 1);
		pj_list_push_back(&route_set, route);

		pjsip_dlg_set_route_set(dlg, &route_set);
	    }
	 *
	 * Note that Route URI SHOULD have an ";lr" parameter!
	 */

	/* Create initial INVITE request.
	 * This INVITE request will contain a perfectly good request and 
	 * an SDP body as well.
	 */
	status = pjsip_inv_invite(g_inv, &tdata);
	PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);



	/* Send initial INVITE request. 
	 * From now on, the invite session's state will be reported to us
	 * via the invite session callbacks.
	 */
	status = pjsip_inv_send_msg(g_inv, tdata);
	PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);


    } else {

	/* No URL to make call to */

	PJ_LOG(3,(THIS_FILE, "Ready to accept incoming calls..."));
    }


    /* Loop until one call is completed */
    for (;!g_complete;) {
	pj_time_val timeout = {0, 10};
	pjsip_endpt_handle_events(g_endpt, &timeout);
    }

    /* On exit, dump current memory usage: */
    dump_pool_usage(THIS_FILE, &cp);

    /* Destroy audio ports. Destroy the audio port first
     * before the stream since the audio port has threads
     * that get/put frames to the stream.
     */
    if (g_snd_port)
	pjmedia_snd_port_destroy(g_snd_port);

#if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0)
    /* Destroy video ports */
    if (g_vid_capturer)
	pjmedia_vid_port_destroy(g_vid_capturer);
    if (g_vid_renderer)
	pjmedia_vid_port_destroy(g_vid_renderer);
#endif

    /* Destroy streams */
    if (g_med_stream)
	pjmedia_stream_destroy(g_med_stream);
#if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0)
    if (g_med_vstream)
	pjmedia_vid_stream_destroy(g_med_vstream);

    /* Deinit ffmpeg codec */
#   if defined(PJMEDIA_HAS_FFMPEG_VID_CODEC) && PJMEDIA_HAS_FFMPEG_VID_CODEC!=0
    pjmedia_codec_ffmpeg_vid_deinit();
#   endif

#endif

    /* Destroy media transports */
    for (i = 0; i < MAX_MEDIA_CNT; ++i) {
	if (g_med_transport[i])
	    pjmedia_transport_close(g_med_transport[i]);
    }

    /* Deinit pjmedia endpoint */
    if (g_med_endpt)
	pjmedia_endpt_destroy(g_med_endpt);

    /* Deinit pjsip endpoint */
    if (g_endpt)
	pjsip_endpt_destroy(g_endpt);

    /* Release pool */
    if (pool)
	pj_pool_release(pool);

    return 0;
}
예제 #21
0
파일: test.c 프로젝트: Agostin/csipsimple
int test_main(void)
{
    pj_status_t rc;
    pj_caching_pool caching_pool;
    const char *filename;
    unsigned tsx_test_cnt=0;
    struct tsx_test_param tsx_test[10];
    pj_status_t status;
#if INCLUDE_TSX_TEST
    unsigned i;
    pjsip_transport *tp;
#if PJ_HAS_TCP
    pjsip_tpfactory *tpfactory;
#endif	/* PJ_HAS_TCP */
#endif	/* INCLUDE_TSX_TEST */
    int line;

    pj_log_set_level(log_level);
    pj_log_set_decor(param_log_decor);

    if ((rc=pj_init()) != PJ_SUCCESS) {
	app_perror("pj_init", rc);
	return rc;
    }

    if ((rc=pjlib_util_init()) != PJ_SUCCESS) {
	app_perror("pj_init", rc);
	return rc;
    }

    status = init_report();
    if (status != PJ_SUCCESS)
	return status;

    pj_dump_config();

    pj_caching_pool_init( &caching_pool, &pj_pool_factory_default_policy, 
			  PJSIP_TEST_MEM_SIZE );

    rc = pjsip_endpt_create(&caching_pool.factory, "endpt", &endpt);
    if (rc != PJ_SUCCESS) {
	app_perror("pjsip_endpt_create", rc);
	pj_caching_pool_destroy(&caching_pool);
	return rc;
    }

    PJ_LOG(3,(THIS_FILE,""));

    /* Init logger module. */
    init_msg_logger();
    msg_logger_set_enabled(1);

    /* Start transaction layer module. */
    rc = pjsip_tsx_layer_init_module(endpt);
    if (rc != PJ_SUCCESS) {
	app_perror("   Error initializing transaction module", rc);
	goto on_return;
    }

    /* Create loop transport. */
    rc = pjsip_loop_start(endpt, NULL);
    if (rc != PJ_SUCCESS) {
	app_perror("   error: unable to create datagram loop transport", 
		   rc);
	goto on_return;
    }
    tsx_test[tsx_test_cnt].port = 5060;
    tsx_test[tsx_test_cnt].tp_type = "loop-dgram";
    tsx_test[tsx_test_cnt].type = PJSIP_TRANSPORT_LOOP_DGRAM;
    ++tsx_test_cnt;


#if INCLUDE_URI_TEST
    DO_TEST(uri_test());
#endif

#if INCLUDE_MSG_TEST
    DO_TEST(msg_test());
    DO_TEST(msg_err_test());
#endif

#if INCLUDE_MULTIPART_TEST
    DO_TEST(multipart_test());
#endif

#if INCLUDE_TXDATA_TEST
    DO_TEST(txdata_test());
#endif

#if INCLUDE_TSX_BENCH
    DO_TEST(tsx_bench());
#endif

#if INCLUDE_UDP_TEST
    DO_TEST(transport_udp_test());
#endif

#if INCLUDE_LOOP_TEST
    DO_TEST(transport_loop_test());
#endif

#if INCLUDE_TCP_TEST
    DO_TEST(transport_tcp_test());
#endif

#if INCLUDE_RESOLVE_TEST
    DO_TEST(resolve_test());
#endif


#if INCLUDE_TSX_TEST
    status = pjsip_udp_transport_start(endpt, NULL, NULL, 1,  &tp);
    if (status == PJ_SUCCESS) {
	tsx_test[tsx_test_cnt].port = tp->local_name.port;
	tsx_test[tsx_test_cnt].tp_type = "udp";
	tsx_test[tsx_test_cnt].type = PJSIP_TRANSPORT_UDP;
	++tsx_test_cnt;
    }

#if PJ_HAS_TCP
    status = pjsip_tcp_transport_start(endpt, NULL, 1, &tpfactory);
    if (status == PJ_SUCCESS) {
	tsx_test[tsx_test_cnt].port = tpfactory->addr_name.port;
	tsx_test[tsx_test_cnt].tp_type = "tcp";
	tsx_test[tsx_test_cnt].type = PJSIP_TRANSPORT_TCP;
	++tsx_test_cnt;
    } else {
	app_perror("Unable to create TCP", status);
	rc = -4;
	goto on_return;
    }
#endif


    for (i=0; i<tsx_test_cnt; ++i) {
	DO_TSX_TEST(tsx_basic_test, &tsx_test[i]);
	DO_TSX_TEST(tsx_uac_test, &tsx_test[i]);
	DO_TSX_TEST(tsx_uas_test, &tsx_test[i]);
    }
#endif

#if INCLUDE_INV_OA_TEST
    DO_TEST(inv_offer_answer_test());
#endif

#if INCLUDE_REGC_TEST
    DO_TEST(regc_test());
#endif


on_return:
    flush_events(500);

    /* Dumping memory pool usage */
    PJ_LOG(3,(THIS_FILE, "Peak memory size=%u MB",
		         caching_pool.peak_used_size / 1000000));

    pjsip_endpt_destroy(endpt);
    pj_caching_pool_destroy(&caching_pool);

    PJ_LOG(3,(THIS_FILE, ""));
 
    pj_thread_get_stack_info(pj_thread_this(), &filename, &line);
    PJ_LOG(3,(THIS_FILE, "Stack max usage: %u, deepest: %s:%u", 
	              pj_thread_get_stack_max_usage(pj_thread_this()),
		      filename, line));
    if (rc == 0)
	PJ_LOG(3,(THIS_FILE, "Looks like everything is okay!.."));
    else
	PJ_LOG(3,(THIS_FILE, "Test completed with error(s)"));

    report_ival("test-status", rc, "", "Overall test status/result (0==success)");
    close_report();
    return rc;
}
예제 #22
0
/* Application init */
static pj_status_t app_init()
{
    unsigned i, count;
    pj_status_t status;

    /* Redirect log */
    pj_log_set_log_func((void (*)(int,const char*,int)) &log_writer);
    pj_log_set_decor(PJ_LOG_HAS_NEWLINE);
    pj_log_set_level(3);

    /* Init pjlib */
    status = pj_init();
    if (status != PJ_SUCCESS) {
    	app_perror("pj_init()", status);
    	return status;
    }

    pj_caching_pool_init(&cp, NULL, 0);

    /* Init sound subsystem */
    status = pjmedia_aud_subsys_init(&cp.factory);
    if (status != PJ_SUCCESS) {
    	app_perror("pjmedia_snd_init()", status);
        pj_caching_pool_destroy(&cp);
    	pj_shutdown();
    	return status;
    }

    count = pjmedia_aud_dev_count();
    PJ_LOG(3,(THIS_FILE, "Device count: %d", count));
    for (i=0; i<count; ++i) {
    	pjmedia_aud_dev_info info;
    	pj_status_t status;

    	status = pjmedia_aud_dev_get_info(i, &info);
    	pj_assert(status == PJ_SUCCESS);
    	PJ_LOG(3, (THIS_FILE, "%d: %s %d/%d %dHz",
    		   i, info.name, info.input_count, info.output_count,
    		   info.default_samples_per_sec));
    	
	unsigned j;

	/* Print extended formats supported by this audio device */
	PJ_LOG(3, (THIS_FILE, "   Extended formats supported:"));
	for (j = 0; j < info.ext_fmt_cnt; ++j) {
	    const char *fmt_name = NULL;
	    
	    switch (info.ext_fmt[j].id) {
	    case PJMEDIA_FORMAT_PCMA:
		fmt_name = "PCMA";
		break;
	    case PJMEDIA_FORMAT_PCMU:
		fmt_name = "PCMU";
		break;
	    case PJMEDIA_FORMAT_AMR:
		fmt_name = "AMR-NB";
		break;
	    case PJMEDIA_FORMAT_G729:
		fmt_name = "G729";
		break;
	    case PJMEDIA_FORMAT_ILBC:
		fmt_name = "ILBC";
		break;
	    case PJMEDIA_FORMAT_PCM:
		fmt_name = "PCM";
		break;
	    default:
		fmt_name = "Unknown";
		break;
	    }
	    PJ_LOG(3, (THIS_FILE, "   - %s", fmt_name));
	}
    }

    /* Create pool */
    pool = pj_pool_create(&cp.factory, THIS_FILE, 512, 512, NULL);
    if (pool == NULL) {
    	app_perror("pj_pool_create()", status);
        pj_caching_pool_destroy(&cp);
    	pj_shutdown();
    	return status;
    }

    /* Init delay buffer */
    status = pjmedia_delay_buf_create(pool, THIS_FILE, CLOCK_RATE,
				      SAMPLES_PER_FRAME, CHANNEL_COUNT,
				      0, 0, &delaybuf);
    if (status != PJ_SUCCESS) {
    	app_perror("pjmedia_delay_buf_create()", status);
        //pj_caching_pool_destroy(&cp);
    	//pj_shutdown();
    	//return status;
    }

    return PJ_SUCCESS;
}
예제 #23
0
파일: OIUC.cpp 프로젝트: mocidis/oiuc-v1
void OIUC::prepare() {

    /*---------------- ICS  -----------------*/
    ics_pool_init(&app_data.ics);
    ics_pjsua_init(&app_data.ics);
    ics_init(&app_data.ics);

    //qDebug() << "INIT DONE";
#if 1
    SET_LOG_LEVEL(4);
    pj_log_set_level(3);

    ics_set_default_callback(&on_reg_start_default);
    ics_set_reg_start_callback(&on_reg_start_impl);
    ics_set_reg_state_callback(&on_reg_state_impl);
    ics_set_incoming_call_callback(&on_incoming_call_impl);
    ics_set_call_state_callback(&on_call_state_impl);
    ics_set_call_transfer_callback(&on_call_transfer_impl);
    ics_set_call_media_state_callback(&on_call_media_state_impl);

    ics_start(&app_data.ics);
    config->getPortAsterisk(); // Don't need anymore, now set default bind to any port
    ics_connect(&app_data.ics, config->getPortAsterisk());

    qDebug() << "ICS STARTED";
#endif
    /*---------------- PTTC  -----------------*/
#if 0
    pttc_init(&app_data.serial, &app_data.pttc, on_pttc_ptt, app_data.ics.pool);
    pttc_start(&app_data.serial, config->getSerialFile().toLocal8Bit().data());
#endif
    /*---------------- NODE  -----------------*/
#if 1
    memset(&app_data.node, 0, sizeof(app_data.node));

    gm_cs = "udp:" + config->getArbiterIP() + ":" + QString::number(config->getPortSendToArbiter());
    gmc_cs = "udp:" + config->getOIUCIP() + ":" + QString::number(config->getPortOIUCListen());
    adv_cs = "udp:0.0.0.0:2015";

    init_adv_server(&app_data, adv_cs.toLocal8Bit().data(), &app_data.node, app_data.ics.pool);
    app_data.node.on_leaving_server_f = &on_leaving_server;
    node_init(&app_data.node,
              config->getOIUCName().toLocal8Bit().data(),
              config->getLocation().toLocal8Bit().data(),
              config->getOIUCDescription().toLocal8Bit().data(),
              -1,
              gm_cs.toLocal8Bit().data(),
              gmc_cs.toLocal8Bit().data(),
              app_data.ics.pool);
    node_add_adv_server(&app_data.node, &app_data.adv_server);

    qDebug() << "NODE INIT DONE";
#endif
    /*---------------- GB  -----------------*/
#if 1
    memset(&app_data.gr, 0, sizeof(app_data.gr));
    app_data.gr.on_online_report_f = &on_online_report;
    app_data.gr.on_tx_report_f = &on_tx_report;
    app_data.gr.on_rx_report_f = &on_rx_report;
    app_data.gr.on_sq_report_f = &on_sq_report;
    gb_receiver_init(&app_data.gr, (char *)GB_CS, app_data.ics.pool);

    qDebug() << "GB DONE";
#endif
    /*---------------- STREAM  -----------------*/
#if 1
    node_media_config(&app_data.node, &app_data.streamer, &app_data.receiver);
    app_data.node.streamer->pool = app_data.node.receiver->pool = app_data.ics.pool;
    app_data.node.streamer->ep = app_data.node.receiver->ep = pjsua_get_pjmedia_endpt();
    pjmedia_codec_g711_init(app_data.node.streamer->ep);
    pjmedia_codec_g711_init(app_data.node.receiver->ep);

    streamer_init(app_data.node.streamer, app_data.node.streamer->ep, app_data.node.streamer->pool);
    receiver_init(app_data.node.receiver, app_data.node.receiver->ep, app_data.node.receiver->pool, config->getNumberChannels());

    streamer_config_dev_source(app_data.node.streamer, config->getSoundStreamerIdx());
    receiver_config_dev_sink(app_data.node.receiver, config->getSoundReceiverIdx());
    //streamer_config_dev_source(app_data.node.streamer, 2);
    //receiver_config_dev_sink(app_data.node.receiver, 2);
    //qDebug() << "STREAM INIT...DONE\n";
#endif
}
예제 #24
0
/* main()
 *
 * If called with argument, treat argument as SIP URL to be called.
 * Otherwise wait for incoming calls.
 */
int main(int argc, char *argv[])
{
    struct pj_getopt_option long_options[] = {
        { "local-port",	1, 0, 'p' },
        { "tcp",	0, 0, 't' },
        { "ipv6",	0, 0, '6' },
        { "help", 	0, 0, 'h' }
    };
    int c, option_index;

    pj_log_set_level(5);

    pj_init();

    sip_af = pj_AF_INET();

    pj_optind = 0;
    while ((c = pj_getopt_long(argc, argv, "p:t6h", long_options,
                               &option_index)) != -1)
    {
	switch (c) {
	case 'p':
	    sip_port = atoi(pj_optarg);
	    break;
	case 't':
	    sip_tcp = PJ_TRUE;
	    break;
	case 'h':
	    usage();
	    return 0;
	case '6':
	    sip_af = pj_AF_INET6();
	    break;
	default:
	    PJ_LOG(1,(THIS_FILE,
		      "Argument \"%s\" is not valid. Use --help to see help",
		      argv[pj_optind-1]));
	    return -1;
	}
    }

    if (init_stack())
	goto on_error;

    /* If URL is specified, then make call immediately. */
    if (pj_optind != argc) {
	pj_sockaddr hostaddr;
	char hostip[PJ_INET6_ADDRSTRLEN+2];
	char temp[80];
	call_t *call;
	pj_str_t dst_uri = pj_str(argv[pj_optind]);
	pj_str_t local_uri;
	pjsip_dialog *dlg;
	pj_status_t status;
	pjsip_tx_data *tdata;

	if (pj_gethostip(sip_af, &hostaddr) != PJ_SUCCESS) {
	    PJ_LOG(1,(THIS_FILE, "Unable to retrieve local host IP"));
	    goto on_error;
	}
	pj_sockaddr_print(&hostaddr, hostip, sizeof(hostip), 2);

	pj_ansi_sprintf(temp, "<sip:sipecho@%s:%d>",
			hostip, sip_port);
	local_uri = pj_str(temp);

	call = &app.call[0];

	status = pjsip_dlg_create_uac( pjsip_ua_instance(),
				       &local_uri,  /* local URI */
				       &local_uri,  /* local Contact */
				       &dst_uri,    /* remote URI */
				       &dst_uri,    /* remote target */
				       &dlg);	    /* dialog */
	if (status != PJ_SUCCESS) {
	    app_perror(THIS_FILE, "Unable to create UAC dialog", status);
	    return 1;
	}

	status = pjsip_inv_create_uac( dlg, NULL, 0, &call->inv);
	if (status != PJ_SUCCESS) goto on_error;

	call->inv->mod_data[mod_sipecho.id] = call;

	status = pjsip_inv_invite(call->inv, &tdata);
	if (status != PJ_SUCCESS) goto on_error;

	status = pjsip_inv_send_msg(call->inv, tdata);
	if (status != PJ_SUCCESS) goto on_error;

	puts("Press ENTER to quit...");
    } else {
	puts("Ready for incoming calls. Press ENTER to quit...");
    }

    for (;;) {
	char s[10];

	printf("\nMenu:\n"
	       "  h    Hangup all calls\n"
	       "  l    %s message logging\n"
	       "  q    Quit\n",
	       (app.enable_msg_logging? "Disable" : "Enable"));

	if (fgets(s, sizeof(s), stdin) == NULL)
	    continue;

	if (s[0]=='q')
	    break;
	switch (s[0]) {
	case 'l':
	    app.enable_msg_logging = !app.enable_msg_logging;
	    break;
	case 'h':
	    hangup_all();
	    break;
	}
    }

    destroy_stack();

    puts("Bye bye..");
    return 0;

on_error:
    puts("An error has occurred. run a debugger..");
    return 1;
}
예제 #25
0
int main()
{
    pj_caching_pool cp;
    pj_bool_t done = PJ_FALSE;
    pj_status_t status;

    /* Init pjlib */
    status = pj_init();
    PJ_ASSERT_RETURN(status==PJ_SUCCESS, 1);
    
    pj_log_set_decor(PJ_LOG_HAS_NEWLINE);

    /* Must create a pool factory before we can allocate any memory. */
    pj_caching_pool_init(&cp, &pj_pool_factory_default_policy, 0);

    status = pjmedia_aud_subsys_init(&cp.factory);
    if (status != PJ_SUCCESS) {
	app_perror("pjmedia_aud_subsys_init()", status);
	pj_caching_pool_destroy(&cp);
	pj_shutdown();
	return 1;
    }

    list_devices();

    while (!done) {
	char line[80];

	print_menu();

	if (fgets(line, sizeof(line), stdin)==NULL)
	    break;

	switch (line[0]) {
	case 'l':
	    list_devices();
	    break;

	case 'R':
	    pjmedia_aud_dev_refresh();
	    puts("Audio device list refreshed.");
	    break;

	case 'i':
	    {
		unsigned dev_index;
		if (sscanf(line+2, "%u", &dev_index) != 1) {
		    puts("error: device ID required");
		    break;
		}
		show_dev_info(dev_index);
	    }
	    break;

	case 't':
	    {
		pjmedia_dir dir;
		int rec_id, play_id;
		unsigned clock_rate, ptime, chnum;
		int cnt;

		cnt = sscanf(line+2, "%d %d %u %u %u", &rec_id, &play_id, 
			     &clock_rate, &ptime, &chnum);
		if (cnt < 4) {
		    puts("error: not enough parameters");
		    break;
		}
		if (clock_rate < 8000 || clock_rate > 128000) {
		    puts("error: invalid clock rate");
		    break;
		}
		if (ptime < 10 || ptime > 500) {
		    puts("error: invalid ptime");
		    break;
		}
		if (cnt==5) {
		    if (chnum < 1 || chnum > 4) {
			puts("error: invalid number of channels");
			break;
		    }
		} else {
		    chnum = 1;
		}

		if (rec_id >= 0 && rec_id < (int)dev_count) {
		    if (play_id >= 0 && play_id < (int)dev_count)
			dir = PJMEDIA_DIR_CAPTURE_PLAYBACK;
		    else
			dir = PJMEDIA_DIR_CAPTURE;
		} else if (play_id >= 0 && play_id < (int)dev_count) {
		    dir = PJMEDIA_DIR_PLAYBACK;
		} else {
		    puts("error: at least one valid device index required");
		    break;
		}

		test_device(dir, rec_id, play_id, clock_rate, ptime, chnum);
		
	    }
	    break;

	case 'r':
	    /* record */
	    {
		int index;
		char filename[80];
		int count;

		count = sscanf(line+2, "%d %s", &index, filename);
		if (count==1)
		    record(index, NULL);
		else if (count==2)
		    record(index, filename);
		else
		    puts("error: invalid command syntax");
	    }
	    break;

	case 'p':
	    /* playback */
	    {
		int index;
		char filename[80];
		int count;

		count = sscanf(line+2, "%d %s", &index, filename);
		if (count==1)
		    play_file(index, NULL);
		else if (count==2)
		    play_file(index, filename);
		else
		    puts("error: invalid command syntax");
	    }
	    break;

	case 'd':
	    /* latencies */
	    {
		int rec_lat, play_lat;

		if (sscanf(line+2, "%d %d", &rec_lat, &play_lat) == 2) {
		    capture_lat = (unsigned) 
			 (rec_lat>=0? rec_lat:PJMEDIA_SND_DEFAULT_REC_LATENCY);
		    playback_lat = (unsigned)
			 (play_lat >= 0? play_lat : PJMEDIA_SND_DEFAULT_PLAY_LATENCY);
		    printf("Recording latency=%ums, playback latency=%ums",
			   capture_lat, playback_lat);
		} else {
		    printf("Current latencies: record=%ums, playback=%ums",
			   capture_lat, playback_lat);
		}
		puts("");
	    }
	    break;

	case 'v':
	    if (pj_log_get_level() <= 3) {
		pj_log_set_level(5);
		puts("Logging set to detail");
	    } else {
		pj_log_set_level(3);
		puts("Logging set to quiet");
	    }
	    break;

	case 'q':
	    done = PJ_TRUE;
	    break;
	}
    }

    pj_caching_pool_destroy(&cp);
    pj_shutdown();
    return 0;
}
예제 #26
0
bool Settings::load() {
  clear();

  std::ifstream in(m_filename.c_str());
  if (in.fail()) {
    Logger::warn("loading file %s failed", m_filename.c_str());
    return false;
  }

  std::stringstream buffer;
  buffer << in.rdbuf();
  std::string str = buffer.str();

  struct json_object* root = json_tokener_parse(str.c_str());

  std::string log_level;
  if (Helper::getObject(root, "log_level", true, m_filename, &log_level)) {
    Logger::setLogLevel(log_level);
  }

  Logger::debug("loading file %s", m_filename.c_str());

  int pjsip_log_level;
  if (Helper::getObject(root, "pjsip_log_level", false, m_filename, &pjsip_log_level)) {
    pj_log_set_level(pjsip_log_level);
  }

  // Phones
  struct json_object* phones;
  if (json_object_object_get_ex(root, "phones", &phones)) {
    for (int i = 0; i < json_object_array_length(phones); i++) {
      struct json_object* entry = json_object_array_get_idx(phones, i);
      bool enabled;
      if (!Helper::getObject(entry, "enabled", true, m_filename, &enabled) || !enabled) {
        continue;
      }

      if (json_object_object_get_ex(entry, "device", NULL)) {
        // Analog
        struct SettingAnalogPhone analog;
        if (!getBase(entry, &analog.base)) {
          continue;
        }
        if (!Helper::getObject(entry, "device", true, m_filename, &analog.device)) {
          continue;
        }
        m_analogPhones.push_back(analog);
      } else {
        // SIP
        struct SettingSipAccount sip;
        if (!getBase(entry, &sip.base)) {
          continue;
        }
        if (!Helper::getObject(entry, "from_domain", true, m_filename, &sip.fromDomain)) {
          continue;
        }
        if (!Helper::getObject(entry, "from_username", true, m_filename, &sip.fromUsername)) {
          continue;
        }
        if (!Helper::getObject(entry, "from_password", true, m_filename, &sip.fromPassword)) {
          continue;
        }
        m_sipAccounts.push_back(sip);
      }
    }
  } else {
    Logger::warn("no <phones> section found in settings file %s", m_filename.c_str());
  }

  // credentials
  struct json_object* onlineCredentials;
  if (json_object_object_get_ex(root, "online_credentials", &onlineCredentials)) {
    for (int i = 0; i < json_object_array_length(onlineCredentials); i++) {
      struct json_object* entry = json_object_array_get_idx(onlineCredentials, i);

      struct SettingOnlineCredential cred;
      if (!Helper::getObject(entry, "name", true, m_filename, &cred.name)) {
        continue;
      }
      json_object_object_foreach(entry, key, value) {
        (void)value; // not used here
        if (strcmp("name", key) == 0) continue;
        std::string value_str;
        if (!Helper::getObject(entry, key, true, m_filename, &value_str)) {
          continue;
        }
        cred.data[key] = value_str;
      }
      m_onlineCredentials.push_back(cred);
    }
  } else {
예제 #27
0
/*
 * main()
 */
int main(int argc, char *argv[])
{
    enum { NSAMPLES = 160, COUNT=100 };
    pj_caching_pool cp;
    pj_pool_t *pool;
    pjmedia_port *wav;
    pj_status_t status;


    /* Verify cmd line arguments. */
    if (argc != 2) {
	puts("Error: missing argument(s)");
	puts("Usage: latency REV.WAV");
	return 1;
    }

    pj_log_set_level(0);

    status = pj_init();
    PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);

    pj_caching_pool_init(&cp, &pj_pool_factory_default_policy, 0);

    pool = pj_pool_create( &cp.factory,	    /* pool factory	    */
			   "wav",	    /* pool name.	    */
			   4000,	    /* init size	    */
			   4000,	    /* increment size	    */
			   NULL		    /* callback on error    */
			   );

    status = pj_register_strerror(PJMEDIA_ERRNO_START, PJ_ERRNO_SPACE_SIZE, 
				  &pjmedia_strerror);
    pj_assert(status == PJ_SUCCESS);

    /* Wav */
    status = pjmedia_wav_player_port_create(  pool,	/* memory pool	    */
					      argv[1],	/* file to play	    */
					      0,	/* use default ptime*/
					      0,	/* flags	    */
					      0,	/* default buffer   */
					      &wav	/* returned port    */
					      );
    if (status != PJ_SUCCESS) {
	app_perror(THIS_FILE, argv[1], status);
	return 1;
    }

    status = calculate_latency(pool, wav);
    if (status != PJ_SUCCESS)
	return 1;

    status = pjmedia_port_destroy( wav );
    PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);

    pj_pool_release( pool );
    pj_caching_pool_destroy( &cp );
    pj_shutdown();

    /* Done. */
    return 0;
}
예제 #28
0
파일: test.c 프로젝트: Agostin/csipsimple
int test_inner(void)
{
    pj_caching_pool caching_pool;
    const char *filename;
    int line;
    int rc = 0;

    mem = &caching_pool.factory;

    pj_log_set_level(3);
    pj_log_set_decor(param_log_decor);

    rc = pj_init();
    if (rc != 0) {
	app_perror("pj_init() error!!", rc);
	return rc;
    }
    
    //pj_dump_config();
    pj_caching_pool_init( &caching_pool, NULL, 0 );

#if INCLUDE_ERRNO_TEST
    DO_TEST( errno_test() );
#endif

#if INCLUDE_EXCEPTION_TEST
    DO_TEST( exception_test() );
#endif

#if INCLUDE_OS_TEST
    DO_TEST( os_test() );
#endif

#if INCLUDE_RAND_TEST
    DO_TEST( rand_test() );
#endif

#if INCLUDE_LIST_TEST
    DO_TEST( list_test() );
#endif

#if INCLUDE_POOL_TEST
    DO_TEST( pool_test() );
#endif

#if INCLUDE_POOL_PERF_TEST
    DO_TEST( pool_perf_test() );
#endif

#if INCLUDE_STRING_TEST
    DO_TEST( string_test() );
#endif
    
#if INCLUDE_FIFOBUF_TEST
    DO_TEST( fifobuf_test() );
#endif

#if INCLUDE_RBTREE_TEST
    DO_TEST( rbtree_test() );
#endif

#if INCLUDE_HASH_TEST
    DO_TEST( hash_test() );
#endif

#if INCLUDE_TIMESTAMP_TEST
    DO_TEST( timestamp_test() );
#endif

#if INCLUDE_ATOMIC_TEST
    DO_TEST( atomic_test() );
#endif

#if INCLUDE_MUTEX_TEST
    DO_TEST( mutex_test() );
#endif

#if INCLUDE_TIMER_TEST
    DO_TEST( timer_test() );
#endif

#if INCLUDE_SLEEP_TEST
    DO_TEST( sleep_test() );
#endif

#if INCLUDE_THREAD_TEST
    DO_TEST( thread_test() );
#endif

#if INCLUDE_SOCK_TEST
    DO_TEST( sock_test() );
#endif

#if INCLUDE_SOCK_PERF_TEST
    DO_TEST( sock_perf_test() );
#endif

#if INCLUDE_SELECT_TEST
    DO_TEST( select_test() );
#endif

#if INCLUDE_UDP_IOQUEUE_TEST
    DO_TEST( udp_ioqueue_test() );
#endif

#if PJ_HAS_TCP && INCLUDE_TCP_IOQUEUE_TEST
    DO_TEST( tcp_ioqueue_test() );
#endif

#if INCLUDE_IOQUEUE_PERF_TEST
    DO_TEST( ioqueue_perf_test() );
#endif

#if INCLUDE_IOQUEUE_UNREG_TEST
    DO_TEST( udp_ioqueue_unreg_test() );
#endif

#if INCLUDE_ACTIVESOCK_TEST
    DO_TEST( activesock_test() );
#endif

#if INCLUDE_FILE_TEST
    DO_TEST( file_test() );
#endif

#if INCLUDE_SSLSOCK_TEST
    DO_TEST( ssl_sock_test() );
#endif

#if INCLUDE_ECHO_SERVER
    //echo_server();
    //echo_srv_sync();
    udp_echo_srv_ioqueue();

#elif INCLUDE_ECHO_CLIENT
    if (param_echo_sock_type == 0)
        param_echo_sock_type = pj_SOCK_DGRAM();

    echo_client( param_echo_sock_type, 
                 param_echo_server, 
                 param_echo_port);
#endif

    goto on_return;

on_return:

    pj_caching_pool_destroy( &caching_pool );

    PJ_LOG(3,("test", ""));
 
    pj_thread_get_stack_info(pj_thread_this(), &filename, &line);
    PJ_LOG(3,("test", "Stack max usage: %u, deepest: %s:%u", 
	              pj_thread_get_stack_max_usage(pj_thread_this()),
		      filename, line));
    if (rc == 0)
	PJ_LOG(3,("test", "Looks like everything is okay!.."));
    else
	PJ_LOG(3,("test", "Test completed with error(s)"));
    
    pj_shutdown();
    
    return 0;
}
예제 #29
0
파일: misc.c 프로젝트: svn2github/pjproject
/*
 * Parse program arguments
 */
static int parse_args(pj_pool_t *pool, int argc, char *argv[])
{
    int c;
    int option_index;
    enum { OPT_CONFIG_FILE, OPT_LOG_FILE, OPT_LOG_LEVEL, OPT_APP_LOG_LEVEL, 
	   OPT_HELP, OPT_VERSION, OPT_NULL_AUDIO,
	   OPT_LOCAL_PORT, OPT_PROXY, OPT_OUTBOUND_PROXY, OPT_REGISTRAR,
	   OPT_REG_TIMEOUT, OPT_ID, OPT_CONTACT, 
	   OPT_REALM, OPT_USERNAME, OPT_PASSWORD,
	   OPT_USE_STUN1, OPT_USE_STUN2, 
	   OPT_ADD_BUDDY, OPT_OFFER_X_MS_MSG, OPT_NO_PRESENCE,
	   OPT_AUTO_ANSWER, OPT_AUTO_HANGUP};
    struct option long_options[] = {
	{ "config-file",1, 0, OPT_CONFIG_FILE},
	{ "log-file",	1, 0, OPT_LOG_FILE},
	{ "log-level",	1, 0, OPT_LOG_LEVEL},
	{ "app-log-level",1,0,OPT_APP_LOG_LEVEL},
	{ "help",	0, 0, OPT_HELP},
	{ "version",	0, 0, OPT_VERSION},
	{ "null-audio", 0, 0, OPT_NULL_AUDIO},
	{ "local-port", 1, 0, OPT_LOCAL_PORT},
	{ "proxy",	1, 0, OPT_PROXY},
	{ "outbound",	1, 0, OPT_OUTBOUND_PROXY},
	{ "registrar",	1, 0, OPT_REGISTRAR},
	{ "reg-timeout",1, 0, OPT_REG_TIMEOUT},
	{ "id",		1, 0, OPT_ID},
	{ "contact",	1, 0, OPT_CONTACT},
	{ "realm",	1, 0, OPT_REALM},
	{ "username",	1, 0, OPT_USERNAME},
	{ "password",	1, 0, OPT_PASSWORD},
	{ "use-stun1",  1, 0, OPT_USE_STUN1},
	{ "use-stun2",  1, 0, OPT_USE_STUN2},
	{ "add-buddy",  1, 0, OPT_ADD_BUDDY},
	{ "offer-x-ms-msg",0,0,OPT_OFFER_X_MS_MSG},
	{ "no-presence", 0, 0, OPT_NO_PRESENCE},
	{ "auto-answer",1, 0, OPT_AUTO_ANSWER},
	{ "auto-hangup",1, 0, OPT_AUTO_HANGUP},
	{ NULL, 0, 0, 0}
    };
    char *config_file = NULL;

    /* Run getopt once to see if user specifies config file to read. */
    while ((c=getopt_long(argc, argv, "", long_options, &option_index)) != -1) {
	switch (c) {
	case 0:
	    config_file = optarg;
	    break;
	}
	if (config_file)
	    break;
    }

    if (config_file) {
	if (read_config_file(pool, config_file, &argc, &argv) != 0)
	    return -1;
    }

    /* Reinitialize and re-run getopt again, possibly with new arguments
     * read from config file.
     */
    optind = 0;
    while ((c=getopt_long(argc, argv, "", long_options, &option_index)) != -1) {
	char *err, *p;

	switch (c) {
	case OPT_LOG_FILE:
	    global.log_filename = optarg;
	    break;
	case OPT_LOG_LEVEL:
	    c = strtoul(optarg, &err, 10);
	    if (*err) {
		printf("Error: expecting integer value 0-6 for --log-level\n");
		return -1;
	    }
	    pj_log_set_level( c );
	    break;
	case OPT_APP_LOG_LEVEL:
	    global.app_log_level = strtoul(optarg, &err, 10);
	    if (*err) {
		printf("Error: expecting integer value 0-6 for --app-log-level\n");
		return -1;
	    }
	    break;
	case OPT_HELP:
	    usage();
	    return -1;
	case OPT_VERSION:   /* version */
	    pj_dump_config();
	    return -1;
	case OPT_NULL_AUDIO:
	    global.null_audio = 1;
	    break;
	case OPT_LOCAL_PORT:   /* local-port */
	    global.sip_port = strtoul(optarg, &err, 10);
	    if (*err) {
		printf("Error: expecting integer value for --local-port\n");
		return -1;
	    }
	    break;
	case OPT_PROXY:   /* proxy */
	    if (verify_sip_url(optarg) != 0) {
		printf("Error: invalid SIP URL '%s' in proxy argument\n", optarg);
		return -1;
	    }
	    global.proxy = pj_str(optarg);
	    break;
	case OPT_OUTBOUND_PROXY:   /* outbound proxy */
	    if (verify_sip_url(optarg) != 0) {
		printf("Error: invalid SIP URL '%s' in outbound proxy argument\n", optarg);
		return -1;
	    }
	    global.outbound_proxy = pj_str(optarg);
	    break;
	case OPT_REGISTRAR:   /* registrar */
	    if (verify_sip_url(optarg) != 0) {
		printf("Error: invalid SIP URL '%s' in registrar argument\n", optarg);
		return -1;
	    }
	    global.registrar_uri = pj_str(optarg);
	    break;
	case OPT_REG_TIMEOUT:   /* reg-timeout */
	    global.reg_timeout = strtoul(optarg, &err, 10);
	    if (*err) {
		printf("Error: expecting integer value for --reg-timeout\n");
		return -1;
	    }
	    break;
	case OPT_ID:   /* id */
	    if (verify_sip_url(optarg) != 0) {
		printf("Error: invalid SIP URL '%s' in local id argument\n", optarg);
		return -1;
	    }
	    global.local_uri = pj_str(optarg);
	    break;
	case OPT_CONTACT:   /* contact */
	    if (verify_sip_url(optarg) != 0) {
		printf("Error: invalid SIP URL '%s' in contact argument\n", optarg);
		return -1;
	    }
	    global.contact = pj_str(optarg);
	    break;
	case OPT_USERNAME:   /* Default authentication user */
	    if (!global.cred_count) global.cred_count = 1;
	    global.cred_info[0].username = pj_str(optarg);
	    break;
	case OPT_REALM:	    /* Default authentication realm. */
	    if (!global.cred_count) global.cred_count = 1;
	    global.cred_info[0].realm = pj_str(optarg);
	    break;
	case OPT_PASSWORD:   /* authentication password */
	    if (!global.cred_count) global.cred_count = 1;
	    global.cred_info[0].data_type = 0;
	    global.cred_info[0].data = pj_str(optarg);
	    break;
	case OPT_USE_STUN1:   /* STUN server 1 */
	    p = strchr(optarg, ':');
	    if (p) {
		*p = '\0';
		global.stun_srv1 = pj_str(optarg);
		global.stun_port1 = strtoul(p+1, &err, 10);
		if (*err || global.stun_port1==0) {
		    printf("Error: expecting port number with option --use-stun1\n");
		    return -1;
		}
	    } else {
		global.stun_port1 = 3478;
		global.stun_srv1 = pj_str(optarg);
	    }
	    break;
	case OPT_USE_STUN2:   /* STUN server 2 */
	    p = strchr(optarg, ':');
	    if (p) {
		*p = '\0';
		global.stun_srv2 = pj_str(optarg);
		global.stun_port2 = strtoul(p+1, &err, 10);
		if (*err || global.stun_port2==0) {
		    printf("Error: expecting port number with option --use-stun2\n");
		    return -1;
		}
	    } else {
		global.stun_port2 = 3478;
		global.stun_srv2 = pj_str(optarg);
	    }
	    break;
	case OPT_ADD_BUDDY: /* Add to buddy list. */
	    if (verify_sip_url(optarg) != 0) {
		printf("Error: invalid URL '%s' in --add-buddy option\n", optarg);
		return -1;
	    }
	    if (global.buddy_cnt == MAX_BUDDIES) {
		printf("Error: too many buddies in buddy list.\n");
		return -1;
	    }
	    global.buddy[global.buddy_cnt++] = pj_str(optarg);
	    break;
	case OPT_OFFER_X_MS_MSG:
	    global.offer_x_ms_msg = 1;
	    break;
	case OPT_NO_PRESENCE:
	    global.no_presence = 1;
	    break;
	case OPT_AUTO_ANSWER:
	    global.auto_answer = strtoul(optarg, &err, 10);
	    if (*err) {
		printf("Error: expecting integer value for --auto-answer option\n");
		return -1;
	    }
	    break;
	case OPT_AUTO_HANGUP:
	    global.auto_hangup = strtoul(optarg, &err, 10);
	    if (*err) {
		printf("Error: expecting integer value for --auto-hangup option\n");
		return -1;
	    }
	    break;
	}
    }

    if (optind != argc) {
	printf("Error: unknown options %s\n", argv[optind]);
	return -1;
    }

    if (global.reg_timeout == 0)
	global.reg_timeout = 3600;

    return 0;
}
예제 #30
0
int main(int argc, char *argv[]) {
    char temp[10];
    pj_caching_pool cp;
    pj_pool_t *pool;
    pjmedia_endpt *ep;
    pjmedia_stream *stream;
    pjmedia_codec_info *ci;

    int rport = 5321;
    char *rhost = "239.1.0.2";
    //char *rhost = "192.168.2.50";

    if (argc < 3) {
        usage(argv[0]);
    }

#if 1
    int lport;

    lport = atoi(argv[1]);
    char *file = argv[2];
#endif

#if 0
    int lport = 2345;
#endif
  
    pj_init();

    pj_log_set_level(5);
    pj_caching_pool_init(&cp, NULL, 1024);
    streamer.pool = pj_pool_create(&cp.factory, "pool1", 1024, 1024, NULL);
    pjmedia_endpt_create(&cp.factory, NULL, 1, &streamer.ep);
    pjmedia_codec_g711_init(streamer.ep);

    streamer_init(&streamer, streamer.ep, streamer.pool);
    streamer_config_stream(&streamer, lport, rhost, rport);
    streamer_config_file_source(&streamer, file);
    //streamer_config_dev_source(&streamer, 2);
    streamer_start(&streamer);
    fprintf(stdout, "Local port: %d, File: %s\n", lport, file);
    
   
    while(1) {
        fprintf(stdout, "s=Stop - r=Resume: ");
        fflush(stdout);
        if (fgets(temp, sizeof(temp), stdin) == NULL)
            exit(-1);
        fprintf(stdout, "%s\n",temp);
        switch(temp[0]) {
        case 's':
        case 'S':
            streamer_stop(&streamer);
            break;
        case 'r':
        case 'R':
            streamer_start(&streamer);
            break;
        case '+':
            rport++;
            streamer_stop(&streamer);
            streamer_config_stream(&streamer, lport, rhost, rport);
            streamer_start(&streamer);
            break;
        case '-':
            rport--;
            streamer_stop(&streamer);
            streamer_config_stream(&streamer, lport, rhost, rport);
            streamer_start(&streamer);
            break;
        case 'v':
            streamer_update_stats(&streamer);
            fprintf(stdout, "rtt:%d - delay:%d - pkt:%d - lost: %d - discard:%d\n",
                            streamer.streams[0].delay.mean_rtt_us, streamer.streams[0].delay.mean_delay_ms,
                            streamer.streams[0].drop.pkt, streamer.streams[0].drop.lost, streamer.streams[0].drop.discard);
            break;
        }
        pj_thread_sleep(5*100);
    }

    return 0;
}