Debian Codegraph @

Xpjproject/pjsip-apps/src/samples/jbsim.c

raw symbols SCIP
1 /*
2 * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */
18
19 /* jbsim:
20
21 This program emulates various system and network impairment
22 conditions as well as application parameters and apply it to
23 an input WAV file. The output is another WAV file as well as
24 a detailed log file (in CSV format) for troubleshooting.
25 */
26
27
28 /* Include PJMEDIA and PJLIB */
29 #include <pjmedia.h>
30 #include <pjmedia/event.h>
31 #include <pjmedia-codec.h>
32 #include <pjlib.h>
33 #include <pjlib-util.h>
34
35 #define THIS_FILE "jbsim.c"
36
37 /* Timer resolution in ms (must be NONZERO!) */
38 #define WALL_CLOCK_TICK 1
39
40 /* Defaults settings */
41 #define CODEC "PCMU"
42 #define LOG_FILE "jbsim.csv"
43 #define WAV_REF "../../tests/pjsua/wavs/input.8.wav"
44 #define WAV_OUT "jbsim.wav"
45 #define DURATION 60
46 #define DTX PJ_TRUE
47 #define PLC PJ_TRUE
48 #define MIN_LOST_BURST 0
49 #define MAX_LOST_BURST 20
50 #define LOSS_CORR 0
51 #define LOSS_EXTRA 2
52 #define SILENT 1
53
54 /*
55 Test setup:
56
57 Input WAV --> TX Stream --> Loop transport --> RX Stream --> Out WAV
58 */
59
60 /* Stream settings */
61 struct stream_cfg
62 {
63 const char *name; /* for logging purposes */
64 pjmedia_dir dir; /* stream direction */
65 pj_str_t codec; /* codec name */
66 unsigned ptime; /* zero for default */
67 pj_bool_t dtx; /* DTX enabled? */
68 pj_bool_t plc; /* PLC enabled? */
69 };
70
71 /* Stream instance. We will instantiate two streams, TX and RX */
72 struct stream
73 {
74 pj_pool_t *pool;
75 pjmedia_stream *strm;
76 pjmedia_port *port;
77
78 /*
79 * Running states:
80 */
81 union {
82 /* TX stream state */
83 struct {
84 pj_time_val next_schedule; /* Time to send next packet */
85 unsigned total_tx; /* # of TX packets so far */
86 int total_lost; /* # of dropped pkts so far */
87 unsigned cur_lost_burst; /* current # of lost bursts */
88 unsigned drop_prob; /* drop probability value */
89
90 } tx;
91
92 /* RX stream state */
93 struct {
94 pj_time_val next_schedule; /* Time to fetch next pkt */
95 } rx;
96 } state;
97 };
98
99 /*
100 * Logging
101 */
102
103 /* Events names */
104 #define EVENT_LOG ""
105 #define EVENT_TX "TX/PUT"
106 #define EVENT_TX_DROP "*** LOSS ***"
107 #define EVENT_GET_PRE "GET (pre)"
108 #define EVENT_GET_POST "GET (post)"
109
110
111 /* Logging entry */
112 struct log_entry
113 {
114 pj_time_val wall_clock; /* Wall clock time */
115 const char *event; /* Event name */
116 pjmedia_jb_state *jb_state; /* JB state, optional */
117 pjmedia_rtcp_stat *stat; /* Stream stat, optional */
118 const char *log; /* Log message, optional */
119 };
120
121 /* Test settings, taken from command line */
122 struct test_cfg
123 {
124 /* General options */
125 pj_bool_t silent; /* Write little to stdout */
126 const char *log_file; /* The output log file */
127
128 /* Test settings */
129 pj_str_t codec; /* Codec to be used */
130 unsigned duration_msec; /* Test duration */
131
132 /* Transmitter setting */
133 const char *tx_wav_in; /* Input/reference WAV */
134 unsigned tx_ptime; /* TX stream ptime */
135 unsigned tx_min_jitter; /* Minimum jitter in ms */
136 unsigned tx_max_jitter; /* Max jitter in ms */
137 unsigned tx_dtx; /* DTX enabled? */
138 unsigned tx_pct_avg_lost; /* Average loss in percent */
139 unsigned tx_min_lost_burst; /* Min lost burst in #pkt */
140 unsigned tx_max_lost_burst; /* Max lost burst in #pkt */
141 unsigned tx_pct_loss_corr; /* Loss correlation in pct */
142
143 /* Receiver setting */
144 const char *rx_wav_out; /* Output WAV file */
145 unsigned rx_ptime; /* RX stream ptime */
146 unsigned rx_snd_burst; /* RX sound burst */
147 pj_bool_t rx_plc; /* RX PLC enabled? */
148 int rx_jb_init; /* if > 0 will enable prefetch (ms) */
149 int rx_jb_min_pre; /* JB minimum prefetch (ms) */
150 int rx_jb_max_pre; /* JB maximum prefetch (ms) */
151 int rx_jb_max; /* JB maximum size (ms) */
152 };
153
154 /*
155 * Global var
156 */
157 struct global_app
158 {
159 pj_caching_pool cp;
160 pj_pool_t *pool;
161 pj_int16_t *framebuf;
162 pjmedia_endpt *endpt;
163 pjmedia_transport *loop;
164
165 pj_oshandle_t log_fd;
166
167 struct test_cfg cfg;
168
169 struct stream *tx;
170 pjmedia_port *tx_wav;
171
172 struct stream *rx;
173 pjmedia_port *rx_wav;
174
175 pj_time_val wall_clock;
176 };
177
178 static struct global_app g_app;
179
180
181 #ifndef MAX
182 # define MAX(a,b) (a<b ? b : a)
183 #endif
184
185 #ifndef MIN
186 # define MIN(a,b) (a<b ? a : b)
187 #endif
188
189 /*****************************************************************************
190 * Logging
191 */
192 static void write_log(struct log_entry *entry, pj_bool_t to_stdout)
193 {
194 /* Format (CSV): */
195 const char *format = "TIME;EVENT;#RX packets;#packets lost;#JB prefetch;#JB size;#JBDISCARD;#JBEMPTY;Log Message";
196 static char log[2000];
197 enum { D = 20 };
198 char s_jbprefetch[D],
199 s_jbsize[D],
200 s_rxpkt[D],
201 s_losspkt[D],
202 s_jbdiscard[D],
203 s_jbempty[D];
204 static pj_bool_t header_written;
205
206 if (!header_written) {
207 pj_ansi_snprintf(log, sizeof(log),
208 "%s\n", format);
209 if (g_app.log_fd != NULL) {
210 pj_ssize_t size = strlen(log);
211 pj_file_write(g_app.log_fd, log, &size);
212 }
213 if (to_stdout && !g_app.cfg.silent)
214 printf("%s", log);
215 header_written = PJ_TRUE;
216 }
217
218 if (entry->jb_state) {
219 pj_ansi_snprintf(s_jbprefetch, sizeof(s_jbprefetch),
220 "%d", entry->jb_state->prefetch);
221 pj_ansi_snprintf(s_jbsize, sizeof(s_jbsize),
222 "%d", entry->jb_state->size);
223 pj_ansi_snprintf(s_jbdiscard, sizeof(s_jbdiscard),
224 "%d", entry->jb_state->discard);
225 pj_ansi_snprintf(s_jbempty, sizeof(s_jbempty),
226 "%d", entry->jb_state->empty);
227 } else {
228 s_jbprefetch[0] = '\0';
229 s_jbsize[0] = '\0';
230 s_jbdiscard[0] = '\0';
231 s_jbempty[0] = '\0';
232 }
233
234 if (entry->stat) {
235 pj_ansi_snprintf(s_rxpkt, sizeof(s_rxpkt),
236 "%d", entry->stat->rx.pkt);
237 pj_ansi_snprintf(s_losspkt, sizeof(s_losspkt),
238 "%d", entry->stat->rx.loss);
239 } else {
240 s_rxpkt[0] = '\0';
241 s_losspkt[0] = '\0';
242 }
243
244 if (entry->log == NULL)
245 entry->log = "";
246
247 pj_ansi_snprintf(log, sizeof(log),
248 "'%d.%03d;" /* time */
249 "%s;" /* event */
250 "%s;" /* rxpkt */
251 "%s;" /* jb prefetch */
252 "%s;" /* jbsize */
253 "%s;" /* losspkt */
254 "%s;" /* jbdiscard */
255 "%s;" /* jbempty */
256 "%s\n" /* logmsg */,
257
258 (int)entry->wall_clock.sec, (int)entry->wall_clock.msec, /* time */
259 entry->event,
260 s_rxpkt,
261 s_losspkt,
262 s_jbprefetch,
263 s_jbsize,
264 s_jbdiscard,
265 s_jbempty,
266 entry->log
267 );
268 if (g_app.log_fd != NULL) {
269 pj_ssize_t size = strlen(log);
270 pj_file_write(g_app.log_fd, log, &size);
271 }
272
273 if (to_stdout && !g_app.cfg.silent)
274 printf("%s", log);
275 }
276
277 static void log_cb(int level, const char *data, int len)
278 {
279 struct log_entry entry;
280
281 /* Write to stdout */
282 pj_log_write(level, data, len);
283 puts("");
284
285 /* Also add to CSV file */
286 pj_bzero(&entry, sizeof(entry));
287 entry.event = EVENT_LOG;
288 entry.log = data;
289 entry.wall_clock = g_app.wall_clock;
290 write_log(&entry, PJ_FALSE);
291 }
292
293 static void jbsim_perror(const char *title, pj_status_t status)
294 {
295 char errmsg[PJ_ERR_MSG_SIZE];
296
297 pj_strerror(status, errmsg, sizeof(errmsg));
298 PJ_LOG(1,(THIS_FILE, "%s: %s", title, errmsg));
299 }
300
301 /*****************************************************************************
302 * stream
303 */
304
305 static void stream_destroy(struct stream *stream)
306 {
307 if (stream->strm)
308 pjmedia_stream_destroy(stream->strm);
309 if (stream->pool)
310 pj_pool_release(stream->pool);
311 }
312
313 static pj_status_t stream_init(const struct stream_cfg *cfg, struct stream **p_stream)
314 {
315 pj_pool_t *pool = NULL;
316 struct stream *stream = NULL;
317 pjmedia_codec_mgr *cm;
318 unsigned count;
319 const pjmedia_codec_info *ci;
320 pjmedia_stream_info si;
321 pj_status_t status;
322
323 /* Create instance */
324 pool = pj_pool_create(&g_app.cp.factory, cfg->name, 512, 512, NULL);
325 stream = PJ_POOL_ZALLOC_T(pool, struct stream);
326 stream->pool = pool;
327
328 /* Create stream info */
329 pj_bzero(&si, sizeof(si));
330 si.type = PJMEDIA_TYPE_AUDIO;
331 si.proto = PJMEDIA_TP_PROTO_RTP_AVP;
332 si.dir = cfg->dir;
333 pj_sockaddr_in_init(&si.rem_addr.ipv4, NULL, 4000); /* dummy */
334 pj_sockaddr_in_init(&si.rem_rtcp.ipv4, NULL, 4001); /* dummy */
335
336 /* Apply JB settings if this is RX direction */
337 if (cfg->dir == PJMEDIA_DIR_DECODING) {
338 si.jb_init = g_app.cfg.rx_jb_init;
339 si.jb_min_pre = g_app.cfg.rx_jb_min_pre;
340 si.jb_max_pre = g_app.cfg.rx_jb_max_pre;
341 si.jb_max = g_app.cfg.rx_jb_max;
342 si.jb_discard_algo = PJMEDIA_JB_DISCARD_PROGRESSIVE;
343 }
344
345 /* Get the codec info and param */
346 cm = pjmedia_endpt_get_codec_mgr(g_app.endpt);
347 count = 1;
348 status = pjmedia_codec_mgr_find_codecs_by_id(cm, &cfg->codec, &count, &ci, NULL);
349 if (status != PJ_SUCCESS) {
350 jbsim_perror("Unable to find codec", status);
351 goto on_error;
352 }
353
354 pj_memcpy(&si.fmt, ci, sizeof(*ci));
355
356 si.param = PJ_POOL_ALLOC_T(pool, struct pjmedia_codec_param);
357 status = pjmedia_codec_mgr_get_default_param(cm, &si.fmt, si.param);
358 if (status != PJ_SUCCESS) {
359 jbsim_perror("Unable to get codec defaults", status);
360 goto on_error;
361 }
362
363 si.tx_pt = si.fmt.pt;
364
365 /* Apply ptime setting */
366 if (cfg->ptime) {
367 si.param->setting.frm_per_pkt = (pj_uint8_t)
368 ((cfg->ptime + si.param->info.frm_ptime - 1) /
369 si.param->info.frm_ptime);
370 }
371 /* Apply DTX setting */
372 si.param->setting.vad = cfg->dtx;
373
374 /* Apply PLC setting */
375 si.param->setting.plc = cfg->plc;
376
377 /* Create stream */
378 status = pjmedia_stream_create(g_app.endpt, pool, &si, g_app.loop, NULL, &stream->strm);
379 if (status != PJ_SUCCESS) {
380 jbsim_perror("Error creating stream", status);
381 goto on_error;
382 }
383
384 status = pjmedia_stream_get_port(stream->strm, &stream->port);
385 if (status != PJ_SUCCESS) {
386 jbsim_perror("Error retrieving stream", status);
387 goto on_error;
388 }
389
390 /* Start stream */
391 status = pjmedia_stream_start(stream->strm);
392 if (status != PJ_SUCCESS) {
393 jbsim_perror("Error starting stream", status);
394 goto on_error;
395 }
396
397 /* Done */
398 *p_stream = stream;
399 return PJ_SUCCESS;
400
401 on_error:
402 if (stream) {
403 stream_destroy(stream);
404 } else {
405 if (pool)
406 pj_pool_release(pool);
407 }
408 return status;
409 }
410
411
412 /*****************************************************************************
413 * The test session
414 */
415 static void test_destroy(void)
416 {
417 if (g_app.tx)
418 stream_destroy(g_app.tx);
419 if (g_app.tx_wav)
420 pjmedia_port_destroy(g_app.tx_wav);
421 if (g_app.rx)
422 stream_destroy(g_app.rx);
423 if (g_app.rx_wav)
424 pjmedia_port_destroy(g_app.rx_wav);
425 if (g_app.loop)
426 pjmedia_transport_close(g_app.loop);
427 if (g_app.endpt)
428 pjmedia_endpt_destroy( g_app.endpt );
429 if (g_app.log_fd) {
430 pj_log_set_log_func(&pj_log_write);
431 pj_log_set_decor(pj_log_get_decor() | PJ_LOG_HAS_NEWLINE);
432 pj_file_close(g_app.log_fd);
433 g_app.log_fd = NULL;
434 }
435 if (g_app.pool)
436 pj_pool_release(g_app.pool);
437 pjmedia_event_mgr_destroy(NULL);
438 pj_caching_pool_destroy( &g_app.cp );
439 pj_shutdown();
440 }
441
442
443 static pj_status_t test_init(void)
444 {
445 struct stream_cfg strm_cfg;
446 pj_status_t status;
447
448 /* Must init PJLIB first: */
449 status = pj_init();
450 PJ_ASSERT_RETURN(status == PJ_SUCCESS, status);
451
452 /* Must create a pool factory before we can allocate any memory. */
453 pj_caching_pool_init(&g_app.cp, &pj_pool_factory_default_policy, 0);
454
455 /* Pool */
456 g_app.pool = pj_pool_create(&g_app.cp.factory, "g_app", 512, 512, NULL);
457
458 /* Log file */
459 if (g_app.cfg.log_file) {
460 status = pj_file_open(g_app.pool, g_app.cfg.log_file,
461 PJ_O_WRONLY,
462 &g_app.log_fd);
463 if (status != PJ_SUCCESS) {
464 jbsim_perror("Error writing output file", status);
465 goto on_error;
466 }
467
468 pj_log_set_decor(PJ_LOG_HAS_SENDER | PJ_LOG_HAS_COLOR | PJ_LOG_HAS_LEVEL_TEXT);
469 pj_log_set_log_func(&log_cb);
470 }
471
472 /*
473 * Initialize media endpoint.
474 * This will implicitly initialize PJMEDIA too.
475 */
476 status = pjmedia_endpt_create(&g_app.cp.factory, NULL, 0, &g_app.endpt);
477 if (status != PJ_SUCCESS) {
478 jbsim_perror("Error creating media endpoint", status);
479 goto on_error;
480 }
481
482 /* Register codecs */
483 pjmedia_codec_register_audio_codecs(g_app.endpt, NULL);
484
485 /* Create the loop transport */
486 status = pjmedia_transport_loop_create(g_app.endpt, &g_app.loop);
487 if (status != PJ_SUCCESS) {
488 jbsim_perror("Error creating loop transport", status);
489 goto on_error;
490 }
491
492 /* Create event manager */
493 status = pjmedia_event_mgr_create(g_app.pool, 0, NULL);
494 if (status != PJ_SUCCESS) {
495 jbsim_perror("Error creating event manager", status);
496 goto on_error;
497 }
498
499 /* Create transmitter stream */
500 pj_bzero(&strm_cfg, sizeof(strm_cfg));
501 strm_cfg.name = "tx";
502 strm_cfg.dir = PJMEDIA_DIR_ENCODING;
503 strm_cfg.codec = g_app.cfg.codec;
504 strm_cfg.ptime = g_app.cfg.tx_ptime;
505 strm_cfg.dtx = g_app.cfg.tx_dtx;
506 strm_cfg.plc = PJ_TRUE;
507 status = stream_init(&strm_cfg, &g_app.tx);
508 if (status != PJ_SUCCESS)
509 goto on_error;
510
511 /* Create transmitter WAV */
512 status = pjmedia_wav_player_port_create(g_app.pool,
513 g_app.cfg.tx_wav_in,
514 g_app.cfg.tx_ptime,
515 0,
516 0,
517 &g_app.tx_wav);
518 if (status != PJ_SUCCESS) {
519 jbsim_perror("Error reading input WAV file", status);
520 goto on_error;
521 }
522
523 /* Make sure stream and WAV parameters match */
524 if (PJMEDIA_PIA_SRATE(&g_app.tx_wav->info) != PJMEDIA_PIA_SRATE(&g_app.tx->port->info) ||
525 PJMEDIA_PIA_CCNT(&g_app.tx_wav->info) != PJMEDIA_PIA_CCNT(&g_app.tx->port->info))
526 {
527 jbsim_perror("Error: Input WAV file has different clock rate "
528 "or number of channels than the codec", PJ_SUCCESS);
529 goto on_error;
530 }
531
532
533 /* Create receiver */
534 pj_bzero(&strm_cfg, sizeof(strm_cfg));
535 strm_cfg.name = "rx";
536 strm_cfg.dir = PJMEDIA_DIR_DECODING;
537 strm_cfg.codec = g_app.cfg.codec;
538 strm_cfg.ptime = g_app.cfg.rx_ptime;
539 strm_cfg.dtx = PJ_TRUE;
540 strm_cfg.plc = g_app.cfg.rx_plc;
541 status = stream_init(&strm_cfg, &g_app.rx);
542 if (status != PJ_SUCCESS)
543 goto on_error;
544
545 /* Create receiver WAV */
546 status = pjmedia_wav_writer_port_create(g_app.pool,
547 g_app.cfg.rx_wav_out,
548 PJMEDIA_PIA_SRATE(&g_app.rx->port->info),
549 PJMEDIA_PIA_CCNT(&g_app.rx->port->info),
550 PJMEDIA_PIA_SPF(&g_app.rx->port->info),
551 PJMEDIA_PIA_BITS(&g_app.rx->port->info),
552 0,
553 0,
554 &g_app.rx_wav);
555 if (status != PJ_SUCCESS) {
556 jbsim_perror("Error creating output WAV file", status);
557 goto on_error;
558 }
559
560
561 /* Frame buffer */
562 g_app.framebuf = (pj_int16_t*)
563 pj_pool_alloc(g_app.pool,
564 MAX(PJMEDIA_PIA_SPF(&g_app.rx->port->info),
565 PJMEDIA_PIA_SPF(&g_app.tx->port->info)) * sizeof(pj_int16_t));
566
567
568 /* Set the receiver in the loop transport */
569 pjmedia_transport_loop_disable_rx(g_app.loop, g_app.tx->strm, PJ_TRUE);
570
571 /* Done */
572 return PJ_SUCCESS;
573
574 on_error:
575 test_destroy();
576 return status;
577 }
578
579 static void run_one_frame(pjmedia_port *src, pjmedia_port *dst,
580 pj_bool_t *has_frame)
581 {
582 pjmedia_frame frame;
583 pj_status_t status;
584
585 pj_bzero(&frame, sizeof(frame));
586 frame.type = PJMEDIA_FRAME_TYPE_AUDIO;
587 frame.buf = g_app.framebuf;
588 frame.size = PJMEDIA_PIA_SPF(&dst->info) * 2;
589
590 status = pjmedia_port_get_frame(src, &frame);
591 pj_assert(status == PJ_SUCCESS);
592
593 if (status!= PJ_SUCCESS || frame.type != PJMEDIA_FRAME_TYPE_AUDIO) {
594 frame.buf = g_app.framebuf;
595 pjmedia_zero_samples(g_app.framebuf, PJMEDIA_PIA_SPF(&src->info));
596 frame.size = PJMEDIA_PIA_SPF(&src->info) * 2;
597 if (has_frame)
598 *has_frame = PJ_FALSE;
599 } else {
600 if (has_frame)
601 *has_frame = PJ_TRUE;
602 }
603
604
605 status = pjmedia_port_put_frame(dst, &frame);
606 pj_assert(status == PJ_SUCCESS);
607 }
608
609
610 /* This is the transmission "tick".
611 * This function is called periodically every "tick" milliseconds, and
612 * it will determine whether to transmit packet(s) (or to drop it).
613 */
614 static void tx_tick(const pj_time_val *t)
615 {
616 struct stream *strm = g_app.tx;
617 static char log_msg[120];
618 pjmedia_port *port = g_app.tx->port;
619 long pkt_interval;
620
621 /* packet interval, without jitter */
622 pkt_interval = PJMEDIA_PIA_SPF(&port->info) * 1000 /
623 PJMEDIA_PIA_SRATE(&port->info);
624
625 while (PJ_TIME_VAL_GTE(*t, strm->state.tx.next_schedule)) {
626 struct log_entry entry;
627 pj_bool_t drop_this_pkt = PJ_FALSE;
628 int jitter;
629
630 /* Init log entry */
631 pj_bzero(&entry, sizeof(entry));
632 entry.wall_clock = *t;
633
634 /*
635 * Determine whether to drop this packet
636 */
637 if (strm->state.tx.cur_lost_burst) {
638 /* We are currently dropping packet */
639
640 /* Make it comply to minimum lost burst */
641 if (strm->state.tx.cur_lost_burst < g_app.cfg.tx_min_lost_burst) {
642 drop_this_pkt = PJ_TRUE;
643 }
644
645 /* Correlate the next packet loss */
646 if (!drop_this_pkt &&
647 strm->state.tx.cur_lost_burst < g_app.cfg.tx_max_lost_burst &&
648 MAX(strm->state.tx.total_lost-LOSS_EXTRA,0) * 100 / MAX(strm->state.tx.total_tx,1) < g_app.cfg.tx_pct_avg_lost
649 )
650 {
651 strm->state.tx.drop_prob = ((g_app.cfg.tx_pct_loss_corr * strm->state.tx.drop_prob) +
652 ((100-g_app.cfg.tx_pct_loss_corr) * (pj_rand()%100))
653 ) / 100;
654 if (strm->state.tx.drop_prob >= 100)
655 strm->state.tx.drop_prob = 99;
656
657 if (strm->state.tx.drop_prob >= 100 - g_app.cfg.tx_pct_avg_lost)
658 drop_this_pkt = PJ_TRUE;
659 }
660 }
661
662 /* If we're not dropping packet then use randomly distributed loss */
663 if (!drop_this_pkt &&
664 MAX(strm->state.tx.total_lost-LOSS_EXTRA,0) * 100 / MAX(strm->state.tx.total_tx,1) < g_app.cfg.tx_pct_avg_lost)
665 {
666 strm->state.tx.drop_prob = pj_rand() % 100;
667
668 if (strm->state.tx.drop_prob >= 100 - g_app.cfg.tx_pct_avg_lost)
669 drop_this_pkt = PJ_TRUE;
670 }
671
672 if (drop_this_pkt) {
673 /* Drop the frame */
674 pjmedia_transport_simulate_lost(g_app.loop, PJMEDIA_DIR_ENCODING, 100);
675 run_one_frame(g_app.tx_wav, g_app.tx->port, NULL);
676 pjmedia_transport_simulate_lost(g_app.loop, PJMEDIA_DIR_ENCODING, 0);
677
678 entry.event = EVENT_TX_DROP;
679 entry.log = "** This packet was lost **";
680
681 ++strm->state.tx.total_lost;
682 ++strm->state.tx.cur_lost_burst;
683
684 } else {
685 pjmedia_rtcp_stat stat;
686 pjmedia_jb_state jstate;
687 unsigned last_discard;
688
689 pjmedia_stream_get_stat_jbuf(g_app.rx->strm, &jstate);
690 last_discard = jstate.discard;
691
692 run_one_frame(g_app.tx_wav, g_app.tx->port, NULL);
693
694 pjmedia_stream_get_stat(g_app.rx->strm, &stat);
695 pjmedia_stream_get_stat_jbuf(g_app.rx->strm, &jstate);
696
697 entry.event = EVENT_TX;
698 entry.jb_state = &jstate;
699 entry.stat = &stat;
700 entry.log = log_msg;
701
702 if (jstate.discard > last_discard)
703 pj_ansi_strxcat(log_msg, "** Note: packet was discarded by jitter buffer **",
704 sizeof(log_msg));
705
706 strm->state.tx.cur_lost_burst = 0;
707 }
708
709 write_log(&entry, PJ_TRUE);
710
711 ++strm->state.tx.total_tx;
712
713 /* Calculate next schedule */
714 strm->state.tx.next_schedule.sec = 0;
715 strm->state.tx.next_schedule.msec = (strm->state.tx.total_tx + 1) * pkt_interval;
716
717 /* Apply jitter */
718 if (g_app.cfg.tx_max_jitter || g_app.cfg.tx_min_jitter) {
719
720 if (g_app.cfg.tx_max_jitter == g_app.cfg.tx_min_jitter) {
721 /* Fixed jitter */
722 switch (pj_rand() % 3) {
723 case 0:
724 jitter = 0 - g_app.cfg.tx_min_jitter;
725 break;
726 case 2:
727 jitter = g_app.cfg.tx_min_jitter;
728 break;
729 default:
730 jitter = 0;
731 break;
732 }
733 } else {
734 int jitter_range;
735 jitter_range = (g_app.cfg.tx_max_jitter-g_app.cfg.tx_min_jitter)*2;
736 jitter = pj_rand() % jitter_range;
737 if (jitter < jitter_range/2) {
738 jitter = 0 - g_app.cfg.tx_min_jitter - (jitter/2);
739 } else {
740 jitter = g_app.cfg.tx_min_jitter + (jitter/2);
741 }
742 }
743
744 } else {
745 jitter = 0;
746 }
747
748 pj_time_val_normalize(&strm->state.tx.next_schedule);
749
750 snprintf(log_msg, sizeof(log_msg),
751 "** Packet #%u tick is at %d.%03d, %d ms jitter applied **",
752 strm->state.tx.total_tx+1,
753 (int)strm->state.tx.next_schedule.sec, (int)strm->state.tx.next_schedule.msec,
754 jitter);
755
756 strm->state.tx.next_schedule.msec += jitter;
757 pj_time_val_normalize(&strm->state.tx.next_schedule);
758
759 } /* while */
760 }
761
762
763 /* This is the RX "tick".
764 * This function is called periodically every "tick" milliseconds, and
765 * it will determine whether to call get_frame() from the RX stream.
766 */
767 static void rx_tick(const pj_time_val *t)
768 {
769 struct stream *strm = g_app.rx;
770 pjmedia_port *port = g_app.rx->port;
771 long pkt_interval;
772
773 pkt_interval = PJMEDIA_PIA_SPF(&port->info) * 1000 /
774 PJMEDIA_PIA_SRATE(&port->info) *
775 (long)g_app.cfg.rx_snd_burst;
776
777 if (PJ_TIME_VAL_GTE(*t, strm->state.rx.next_schedule)) {
778 unsigned i;
779 for (i=0; i<g_app.cfg.rx_snd_burst; ++i) {
780 struct log_entry entry;
781 pjmedia_rtcp_stat stat;
782 pjmedia_jb_state jstate;
783 pj_bool_t has_frame;
784 char msg[120];
785 unsigned last_empty;
786
787 pjmedia_stream_get_stat(g_app.rx->strm, &stat);
788 pjmedia_stream_get_stat_jbuf(g_app.rx->strm, &jstate);
789 last_empty = jstate.empty;
790
791 /* Pre GET event */
792 pj_bzero(&entry, sizeof(entry));
793 entry.event = EVENT_GET_PRE;
794 entry.wall_clock = *t;
795 entry.stat = &stat;
796 entry.jb_state = &jstate;
797
798 write_log(&entry, PJ_TRUE);
799
800 /* GET */
801 run_one_frame(g_app.rx->port, g_app.rx_wav, &has_frame);
802
803 /* Post GET event */
804 pjmedia_stream_get_stat(g_app.rx->strm, &stat);
805 pjmedia_stream_get_stat_jbuf(g_app.rx->strm, &jstate);
806
807 pj_bzero(&entry, sizeof(entry));
808 entry.event = EVENT_GET_POST;
809 entry.wall_clock = *t;
810 entry.stat = &stat;
811 entry.jb_state = &jstate;
812
813 msg[0] = '\0';
814 entry.log = msg;
815
816 if (jstate.empty > last_empty)
817 pj_ansi_strxcat(msg, "** JBUF was empty **", sizeof(msg));
818 if (!has_frame)
819 pj_ansi_strxcat(msg, "** NULL frame was returned **",
820 sizeof(msg));
821
822 write_log(&entry, PJ_TRUE);
823
824 }
825
826
827 strm->state.rx.next_schedule.msec += pkt_interval;
828 pj_time_val_normalize(&strm->state.rx.next_schedule);
829 }
830
831 }
832
833 static void test_loop(long duration)
834 {
835 g_app.wall_clock.sec = 0;
836 g_app.wall_clock.msec = 0;
837
838 while (PJ_TIME_VAL_MSEC(g_app.wall_clock) <= duration) {
839
840 /* Run TX tick */
841 tx_tick(&g_app.wall_clock);
842
843 /* Run RX tick */
844 rx_tick(&g_app.wall_clock);
845
846 /* Increment tick */
847 g_app.wall_clock.msec += WALL_CLOCK_TICK;
848 pj_time_val_normalize(&g_app.wall_clock);
849 }
850 }
851
852
853 /*****************************************************************************
854 * usage()
855 */
856 enum {
857 OPT_CODEC = 'c',
858 OPT_INPUT = 'i',
859 OPT_OUTPUT = 'o',
860 OPT_DURATION = 'd',
861 OPT_LOG_FILE = 'l',
862 OPT_LOSS = 'x',
863 OPT_MIN_JITTER = 'j',
864 OPT_MAX_JITTER = 'J',
865 OPT_SND_BURST = 'b',
866 OPT_TX_PTIME = 't',
867 OPT_RX_PTIME = 'r',
868 OPT_NO_VAD = 'U',
869 OPT_NO_PLC = 'p',
870 OPT_JB_PREFETCH = 'P',
871 OPT_JB_MIN_PRE = 'm',
872 OPT_JB_MAX_PRE = 'M',
873 OPT_JB_MAX = 'X',
874 OPT_HELP = 'h',
875 OPT_MIN_LOST_BURST = 1,
876 OPT_MAX_LOST_BURST,
877 OPT_LOSS_CORR,
878 };
879
880
881 static void usage(void)
882 {
883 printf("jbsim - System and network impairments simulator\n");
884 printf("Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com)\n");
885 printf("\n");
886 printf("This program emulates various system and network impairment\n");
887 printf("conditions as well as application parameters and apply it to\n");
888 printf("an input WAV file. The output is another WAV file as well as\n");
889 printf("a detailed log file (in CSV format) for troubleshooting.\n");
890 printf("\n");
891 printf("Usage:\n");
892 printf(" jbsim [OPTIONS]\n");
893 printf("\n");
894 printf("General OPTIONS:\n");
895 printf(" --codec, -%c NAME Set the audio codec\n", OPT_CODEC);
896 printf(" Default: %s\n", CODEC);
897 printf(" --input, -%c FILE Set WAV reference file to FILE\n", OPT_INPUT);
898 printf(" Default: " WAV_REF "\n");
899 printf(" --output, -%c FILE Set WAV output file to FILE\n", OPT_OUTPUT);
900 printf(" Default: " WAV_OUT "\n");
901 printf(" --duration, -%c SEC Set test duration to SEC seconds\n", OPT_DURATION);
902 printf(" Default: %d\n", DURATION);
903 printf(" --log-file, -%c FILE Save simulation log file to FILE\n", OPT_LOG_FILE);
904 printf(" Note: FILE will be in CSV format with semicolon separator\n");
905 printf(" Default: %s\n", LOG_FILE);
906 printf(" --help, -h Display this screen\n");
907 printf("\n");
908 printf("Simulation OPTIONS:\n");
909 printf(" --loss, -%c PCT Set packet average loss to PCT percent\n", OPT_LOSS);
910 printf(" Default: 0\n");
911 printf(" --loss-corr PCT Set the loss correlation to PCT percent. Default: 0\n");
912 printf(" --min-lost-burst N Set minimum packet lost burst (default:%d)\n", MIN_LOST_BURST);
913 printf(" --max-lost-burst N Set maximum packet lost burst (default:%d)\n", MAX_LOST_BURST);
914 printf(" --min-jitter, -%c MSEC Set minimum network jitter to MSEC\n", OPT_MIN_JITTER);
915 printf(" Default: 0\n");
916 printf(" --max-jitter, -%c MSEC Set maximum network jitter to MSEC\n", OPT_MAX_JITTER);
917 printf(" Default: 0\n");
918 printf(" --snd-burst, -%c VAL Set RX sound burst value to VAL frames.\n", OPT_SND_BURST);
919 printf(" Default: 1\n");
920 printf(" --tx-ptime, -%c MSEC Set transmitter ptime to MSEC\n", OPT_TX_PTIME);
921 printf(" Default: 0 (not set, use default)\n");
922 printf(" --rx-ptime, -%c MSEC Set receiver ptime to MSEC\n", OPT_RX_PTIME);
923 printf(" Default: 0 (not set, use default)\n");
924 printf(" --no-vad, -%c Disable VAD/DTX in transmitter\n", OPT_NO_VAD);
925 printf(" --no-plc, -%c Disable PLC in receiver\n", OPT_NO_PLC);
926 printf(" --jb-prefetch, -%c Enable prefetch bufferring in jitter buffer\n", OPT_JB_PREFETCH);
927 printf(" --jb-min-pre, -%c MSEC Jitter buffer minimum prefetch delay in msec\n", OPT_JB_MIN_PRE);
928 printf(" --jb-max-pre, -%c MSEC Jitter buffer maximum prefetch delay in msec\n", OPT_JB_MAX_PRE);
929 printf(" --jb-max, -%c MSEC Set maximum delay that can be accomodated by the\n", OPT_JB_MAX);
930 printf(" jitter buffer msec.\n");
931 }
932
933
934 static int init_options(int argc, char *argv[])
935 {
936 struct pj_getopt_option long_options[] = {
937 { "codec", 1, 0, OPT_CODEC },
938 { "input", 1, 0, OPT_INPUT },
939 { "output", 1, 0, OPT_OUTPUT },
940 { "duration", 1, 0, OPT_DURATION },
941 { "log-file", 1, 0, OPT_LOG_FILE},
942 { "loss", 1, 0, OPT_LOSS },
943 { "min-lost-burst", 1, 0, OPT_MIN_LOST_BURST},
944 { "max-lost-burst", 1, 0, OPT_MAX_LOST_BURST},
945 { "loss-corr", 1, 0, OPT_LOSS_CORR},
946 { "min-jitter", 1, 0, OPT_MIN_JITTER },
947 { "max-jitter", 1, 0, OPT_MAX_JITTER },
948 { "snd-burst", 1, 0, OPT_SND_BURST },
949 { "tx-ptime", 1, 0, OPT_TX_PTIME },
950 { "rx-ptime", 1, 0, OPT_RX_PTIME },
951 { "no-vad", 0, 0, OPT_NO_VAD },
952 { "no-plc", 0, 0, OPT_NO_PLC },
953 { "jb-prefetch", 0, 0, OPT_JB_PREFETCH },
954 { "jb-min-pre", 1, 0, OPT_JB_MIN_PRE },
955 { "jb-max-pre", 1, 0, OPT_JB_MAX_PRE },
956 { "jb-max", 1, 0, OPT_JB_MAX },
957 { "help", 0, 0, OPT_HELP},
958 { NULL, 0, 0, 0 },
959 };
960 int c;
961 int option_index;
962 char format[128];
963
964 /* Init default config */
965 g_app.cfg.codec = pj_str(CODEC);
966 g_app.cfg.duration_msec = DURATION * 1000;
967 g_app.cfg.silent = SILENT;
968 g_app.cfg.log_file = LOG_FILE;
969 g_app.cfg.tx_wav_in = WAV_REF;
970 g_app.cfg.tx_ptime = 0;
971 g_app.cfg.tx_min_jitter = 0;
972 g_app.cfg.tx_max_jitter = 0;
973 g_app.cfg.tx_dtx = DTX;
974 g_app.cfg.tx_pct_avg_lost = 0;
975 g_app.cfg.tx_min_lost_burst = MIN_LOST_BURST;
976 g_app.cfg.tx_max_lost_burst = MAX_LOST_BURST;
977 g_app.cfg.tx_pct_loss_corr = LOSS_CORR;
978
979 g_app.cfg.rx_wav_out = WAV_OUT;
980 g_app.cfg.rx_ptime = 0;
981 g_app.cfg.rx_plc = PLC;
982 g_app.cfg.rx_snd_burst = 1;
983 g_app.cfg.rx_jb_init = -1;
984 g_app.cfg.rx_jb_min_pre = -1;
985 g_app.cfg.rx_jb_max_pre = -1;
986 g_app.cfg.rx_jb_max = -1;
987
988 /* Build format */
989 format[0] = '\0';
990 for (c=0; c<(int)PJ_ARRAY_SIZE(long_options)-1; ++c) {
991 if (long_options[c].has_arg) {
992 char cmd[10];
993 pj_ansi_snprintf(cmd, sizeof(cmd), "%c:", long_options[c].val);
994 pj_ansi_strxcat(format, cmd, sizeof(format));
995 }
996 }
997 for (c=0; c<(int)PJ_ARRAY_SIZE(long_options)-1; ++c) {
998 if (long_options[c].has_arg == 0) {
999 char cmd[10];
1000 pj_ansi_snprintf(cmd, sizeof(cmd), "%c", long_options[c].val);
1001 pj_ansi_strxcat(format, cmd, sizeof(format));
1002 }
1003 }
1004
1005 /* Parse options */
1006 pj_optind = 0;
1007 while((c=pj_getopt_long(argc,argv, format,
1008 long_options, &option_index))!=-1)
1009 {
1010 switch (c) {
1011 case OPT_CODEC:
1012 g_app.cfg.codec = pj_str(pj_optarg);
1013 break;
1014 case OPT_INPUT:
1015 g_app.cfg.tx_wav_in = pj_optarg;
1016 break;
1017 case OPT_OUTPUT:
1018 g_app.cfg.rx_wav_out = pj_optarg;
1019 break;
1020 case OPT_DURATION:
1021 g_app.cfg.duration_msec = atoi(pj_optarg) * 1000;
1022 break;
1023 case OPT_LOG_FILE:
1024 g_app.cfg.log_file = pj_optarg;
1025 break;
1026 case OPT_LOSS:
1027 g_app.cfg.tx_pct_avg_lost = atoi(pj_optarg);
1028 if (g_app.cfg.tx_pct_avg_lost > 100) {
1029 puts("Error: Invalid loss value?");
1030 return 1;
1031 }
1032 break;
1033 case OPT_MIN_LOST_BURST:
1034 g_app.cfg.tx_min_lost_burst = atoi(pj_optarg);
1035 break;
1036 case OPT_MAX_LOST_BURST:
1037 g_app.cfg.tx_max_lost_burst = atoi(pj_optarg);
1038 break;
1039 case OPT_LOSS_CORR:
1040 g_app.cfg.tx_pct_loss_corr = atoi(pj_optarg);
1041 if (g_app.cfg.tx_pct_avg_lost > 100) {
1042 puts("Error: Loss correlation is in percentage, value is not valid?");
1043 return 1;
1044 }
1045 break;
1046 case OPT_MIN_JITTER:
1047 g_app.cfg.tx_min_jitter = atoi(pj_optarg);
1048 break;
1049 case OPT_MAX_JITTER:
1050 g_app.cfg.tx_max_jitter = atoi(pj_optarg);
1051 break;
1052 case OPT_SND_BURST:
1053 g_app.cfg.rx_snd_burst = atoi(pj_optarg);
1054 break;
1055 case OPT_TX_PTIME:
1056 g_app.cfg.tx_ptime = atoi(pj_optarg);
1057 break;
1058 case OPT_RX_PTIME:
1059 g_app.cfg.rx_ptime = atoi(pj_optarg);
1060 break;
1061 case OPT_NO_VAD:
1062 g_app.cfg.tx_dtx = PJ_FALSE;
1063 break;
1064 case OPT_NO_PLC:
1065 g_app.cfg.rx_plc = PJ_FALSE;
1066 break;
1067 case OPT_JB_PREFETCH:
1068 g_app.cfg.rx_jb_init = 1;
1069 break;
1070 case OPT_JB_MIN_PRE:
1071 g_app.cfg.rx_jb_min_pre = atoi(pj_optarg);
1072 break;
1073 case OPT_JB_MAX_PRE:
1074 g_app.cfg.rx_jb_max_pre = atoi(pj_optarg);
1075 break;
1076 case OPT_JB_MAX:
1077 g_app.cfg.rx_jb_max = atoi(pj_optarg);
1078 break;
1079 case OPT_HELP:
1080 usage();
1081 return 1;
1082 default:
1083 usage();
1084 return 1;
1085 }
1086 }
1087
1088 /* Check for orphaned params */
1089 if (pj_optind < argc) {
1090 usage();
1091 return 1;
1092 }
1093
1094 /* Normalize options */
1095 if (g_app.cfg.rx_jb_init < g_app.cfg.rx_jb_min_pre)
1096 g_app.cfg.rx_jb_init = g_app.cfg.rx_jb_min_pre;
1097 else if (g_app.cfg.rx_jb_init > g_app.cfg.rx_jb_max_pre)
1098 g_app.cfg.rx_jb_init = g_app.cfg.rx_jb_max_pre;
1099
1100 if (g_app.cfg.tx_max_jitter < g_app.cfg.tx_min_jitter)
1101 g_app.cfg.tx_max_jitter = g_app.cfg.tx_min_jitter;
1102 return 0;
1103 }
1104
1105 /*****************************************************************************
1106 * main()
1107 */
1108 int main(int argc, char *argv[])
1109 {
1110 pj_status_t status;
1111
1112 if (init_options(argc, argv) != 0)
1113 return 1;
1114
1115
1116 /* Init */
1117 status = test_init();
1118 if (status != PJ_SUCCESS)
1119 return 1;
1120
1121 /* Print parameters */
1122 PJ_LOG(3,(THIS_FILE, "Starting simulation. Parameters: "));
1123 PJ_LOG(3,(THIS_FILE, " Codec=%.*s, tx_ptime=%d, rx_ptime=%d",
1124 (int)g_app.cfg.codec.slen,
1125 g_app.cfg.codec.ptr,
1126 g_app.cfg.tx_ptime,
1127 g_app.cfg.rx_ptime));
1128 PJ_LOG(3,(THIS_FILE, " Loss avg=%d%%, min_burst=%d, max_burst=%d",
1129 g_app.cfg.tx_pct_avg_lost,
1130 g_app.cfg.tx_min_lost_burst,
1131 g_app.cfg.tx_max_lost_burst));
1132 PJ_LOG(3,(THIS_FILE, " TX jitter min=%dms, max=%dms",
1133 g_app.cfg.tx_min_jitter,
1134 g_app.cfg.tx_max_jitter));
1135 PJ_LOG(3,(THIS_FILE, " RX jb init:%dms, min_pre=%dms, max_pre=%dms, max=%dms",
1136 g_app.cfg.rx_jb_init,
1137 g_app.cfg.rx_jb_min_pre,
1138 g_app.cfg.rx_jb_max_pre,
1139 g_app.cfg.rx_jb_max));
1140 PJ_LOG(3,(THIS_FILE, " RX sound burst:%d frames",
1141 g_app.cfg.rx_snd_burst));
1142 PJ_LOG(3,(THIS_FILE, " DTX=%d, PLC=%d",
1143 g_app.cfg.tx_dtx, g_app.cfg.rx_plc));
1144
1145 /* Run test loop */
1146 test_loop(g_app.cfg.duration_msec);
1147
1148 /* Print statistics */
1149 PJ_LOG(3,(THIS_FILE, "Simulation done"));
1150 PJ_LOG(3,(THIS_FILE, " TX packets=%u, dropped=%u/%5.1f%%",
1151 g_app.tx->state.tx.total_tx,
1152 g_app.tx->state.tx.total_lost,
1153 (float)(g_app.tx->state.tx.total_lost * 100.0 / g_app.tx->state.tx.total_tx)));
1154
1155 /* Done */
1156 test_destroy();
1157
1158 return 0;
1159 }