]> rtime.felk.cvut.cz Git - frescor/fwp.git/blob - wme_test/wclient.c
Merge branch 'master' of rtime:/var/git/frescor
[frescor/fwp.git] / wme_test / wclient.c
1 #include <errno.h>
2 #include <sys/types.h>
3 #include <sys/socket.h>
4 #include <netinet/in.h>
5 #include <arpa/inet.h>
6 #include <netdb.h>
7 #include <signal.h>
8 #include <sys/wait.h>
9 #include <stdio.h>
10 #include <unistd.h>
11 #include <fcntl.h>
12 #include <time.h>
13 #include <string.h>
14 #include <pthread.h>
15 #include <string.h>
16 #include <stdlib.h>
17 #include <stdbool.h>
18 #include "common.h"
19 #include <semaphore.h>
20
21 #define MAX_STREAMS  10 
22 #define MIN_GRANULARITY 100
23
24 unsigned opt_packet_size = 800;
25 int opt_send_buf_size = -1;
26 unsigned opt_period_usec = 10*MSEC_TO_USEC;
27 unsigned opt_jitter = 0;
28 char    *opt_output = "delay_stats";
29 unsigned opt_count_sec = 0;
30 unsigned opt_def_bandwidth = 200;
31 unsigned opt_def_period_msec = 0;
32 int opt_granularity_usec = MIN_GRANULARITY;
33 bool opt_wait_for_queue_is_full; /* Don't gather any statistics until any queue is full */
34
35 bool some_queue_is_full = false;
36 struct timespec reset_timestamp;
37
38 /* Locked when some queue is full to prevent multiple resets of
39    statstics. */
40 pthread_mutex_t queue_full_mutex = PTHREAD_MUTEX_INITIALIZER;
41
42 int ac_sockfd[AC_NUM];
43
44 struct receiver {
45         pthread_t thread;
46         unsigned received, last_received;
47 } receivers[AC_NUM];
48
49 FILE* logfd;
50 char* server_addr; 
51 char logfname[100];
52
53 /* maximal traffic delay in ms - 10 s*/
54 #define MAX_DELAY_US 10000000
55
56 struct delay_stat {
57         unsigned csc;           /* Client-server-client delay divided by 2 */
58         unsigned cs;            /* Client-server delay */
59         unsigned sc;            /* Server-client delay */
60 };
61
62 struct delay_stat delay_stats[AC_NUM][MAX_DELAY_US/MIN_GRANULARITY];
63 pthread_mutex_t delay_stats_mutex = PTHREAD_MUTEX_INITIALIZER;
64
65 /*struct ac_stats[AC_NUM] {
66    unsigned long int min_trans_time;
67    unsigned long int sum_trans_time;
68    struct timespec   recv_timestamp;
69    struct timespec   send_timestamp; 
70 };*/
71
72 struct stream {
73         /* Input parameters */
74         enum ac ac;             /*  */
75         int bandwidth_bps;      /* bits per second */
76         int jitter;             /* percent */
77         /* Mulualy exclusive input parameters */
78         int packet_size;
79         long period_usec;       /* all time units are in microseconds */
80         struct sockaddr_in rem_addr;
81
82         /* Statistics */
83         pthread_mutex_t mutex;
84         unsigned long long sent, really_sent, received;
85 };
86
87 /*
88 struct send_endpoint sepoint[] = {
89         { .ac = AC_VO, .period_usec=200*MSEC_TO_USEC, .bandwidth_bps = 34*Kbit },
90         { .ac = AC_VI, .period_usec=25*MSEC_TO_USEC, .bandwidth_bps =  480*Kbit },
91         { .ac = AC_BE, .period_usec=40*MSEC_TO_USEC, .bandwidth_bps =  300*Kbit },
92         { .ac = AC_BK, .period_usec=40*MSEC_TO_USEC, .bandwidth_bps =  300*Kbit },
93 //      { .ac = AC_VI, .period_usec=17*MSEC_TO_USEC, .bandwidth_bps =  675*Kbit },
94 };
95 */
96
97 struct stream streams[MAX_STREAMS];
98
99 unsigned int nr_streams = 0;
100
101 sem_t sem_thread_finished;
102
103 bool exit_flag = false;
104
105 void stopper()
106 {
107         int i;
108         exit_flag = true;
109
110         /* Interrupt all receivers */
111         for (i=0; i < AC_NUM; i++) {
112                 pthread_kill(receivers[i].thread, SIGUSR1);
113         }
114 }
115
116 void stream_to_text(char *stream_desc, size_t n, struct stream *stream, long long useconds)
117 {
118         char buf[3][12];
119         char real[100];
120
121         if (useconds) {
122                 snprintf(real, sizeof(real), "; real: %s sent %lld (%lld/s), received %lld (%lld/s)",
123                          bandwidth_to_text(buf[0], (long long)stream->really_sent*stream->packet_size*8*SEC_TO_USEC/useconds),
124                          stream->sent, stream->sent*SEC_TO_USEC/useconds,
125                          stream->received, stream->received*SEC_TO_USEC/useconds);
126         } else {
127                 real[0]=0;
128         }
129         
130         snprintf(stream_desc, n, "%d: %s %s (%d bytes per %s +-%s, %d packets/s)%s",
131                  stream-streams, ac_to_text[stream->ac], bandwidth_to_text(buf[0], stream->bandwidth_bps),
132                  stream->packet_size, usec_to_text(buf[1], stream->period_usec),
133                  usec_to_text(buf[2], stream->jitter*stream->period_usec/100),
134                  (int)(SEC_TO_USEC/stream->period_usec), real);
135 }
136
137 void save_results(int argc, char *argv[], int useconds)
138 {
139         int ac, i, maxi;
140         const int mini = 3000/opt_granularity_usec;
141         bool allzeros;
142         unsigned send_count[AC_NUM];
143
144         fprintf(stderr, "Writing data to %s... ", logfname);
145         fflush(stderr);
146
147         fprintf(logfd, "# Invoked as: ");
148         for (i=0; i<argc; i++) fprintf(logfd, "%s ", argv[i]);
149         fprintf(logfd, "\n");
150
151         if (useconds/SEC_TO_USEC != opt_count_sec) {
152                 char buf[20];
153                 usec_to_text(buf, useconds);
154                 fprintf(logfd, "# Data gathered for %s.\n", buf);
155         }
156                 
157         for (i = 0; i < nr_streams; i++) {
158                 char stream_desc[200];
159                 stream_to_text(stream_desc, sizeof(stream_desc), &streams[i], useconds);
160                 fprintf(logfd, "# Stream %s\n", stream_desc);
161         }
162
163         /* Find maximal delay */
164         allzeros = true;
165         for (maxi = MAX_DELAY_US/opt_granularity_usec - 1; maxi >= 0; maxi--) {
166                 for (ac = 0; ac < AC_NUM; ac++) {
167                         if ((delay_stats[ac][maxi].csc != 0) ||
168                             (delay_stats[ac][maxi].cs != 0) ||
169                             (delay_stats[ac][maxi].sc != 0))
170                                 allzeros = false;
171                 }
172                 if (!allzeros) break;
173         }
174         maxi++;
175         if (maxi < mini) maxi = mini;
176
177         /* Calculate total number of sent packets per AC */
178         memset(send_count, 0, sizeof(send_count));
179         for (i = 0; i < nr_streams; i++) {
180                 ac = streams[i].ac;
181                 send_count[ac] += streams[i].sent;
182         }
183
184 #if 0
185         /* Write pdf */
186         for ( i = 0 ; i < maxi; i++) {
187                 fprintf(logfd,"\n%f", i*opt_granularity_usec/1000.0);
188                 for (ac = 0; ac < AC_NUM; ac++) { 
189                         if (sum[ac])
190                                 val = (double)delay_stats[ac][i]*100.0 / sum[ac];
191                         else val = -1; /* Don't display this ac */
192                         fprintf(logfd," %lf", val);
193                 }
194         }
195         
196         fprintf(logfd,"\n\n");
197 #endif
198         
199         fprintf(logfd,"## Format: msec csc%% cs%% sc%%\n");
200
201         /* Write PDF */
202         for (ac = 0; ac < AC_NUM; ac++) {
203                 struct delay_stat integral = {0,0,0}, last = {-1,-1,-1};
204
205                 fprintf(logfd,"%f %f %f %f\n", 0.0, 0.0, 0.0, 0.0);
206
207                 if (send_count[ac] != 0) {
208                         i=0;
209                         while ((delay_stats[ac][i].csc == 0) &&
210                                (delay_stats[ac][i].cs == 0) &&
211                                (delay_stats[ac][i].sc == 0)) i++;
212                 
213                         for (i++; i < maxi+1; i++) {
214                                 if (memcmp(&last, &integral, sizeof(last))) {
215                                         fprintf(logfd,"%f %f %f %f\n", i*opt_granularity_usec/1000.0,
216                                                 (double)integral.csc*100.0 / send_count[ac],
217                                                 (double)integral.cs *100.0 / send_count[ac],
218                                                 (double)integral.sc *100.0 / send_count[ac]
219                                                 );
220                                         last = integral;
221                                 }
222                                 if (i>0) {
223                                         integral.csc += delay_stats[ac][i-1].csc;
224                                         integral.sc  += delay_stats[ac][i-1].sc;
225                                         integral.cs  += delay_stats[ac][i-1].cs;
226                                 }
227                         }
228                 }
229                 fprintf(logfd,"\n\n");
230         }
231         
232         fprintf(stderr, "finished.\n");
233         fclose(logfd);
234
235         exit(0);
236 }
237
238 static inline 
239 void timespec_add (struct timespec *sum, const struct timespec *left,
240               const struct timespec *right)
241 {
242         sum->tv_sec = left->tv_sec + right->tv_sec;
243         sum->tv_nsec = left->tv_nsec + right->tv_nsec;
244
245         if (sum->tv_nsec >= 1000000000){
246                 ++sum->tv_sec;
247                 sum->tv_nsec -= 1000000000;
248         }
249 }
250
251 static inline 
252 void timespec_sub (struct timespec *diff, const struct timespec *left,
253               const struct timespec *right)
254 {
255         diff->tv_sec = left->tv_sec - right->tv_sec;
256         diff->tv_nsec = left->tv_nsec - right->tv_nsec;
257
258         if (diff->tv_nsec < 0){
259                   --diff->tv_sec;
260                   diff->tv_nsec += 1000000000;
261         }
262 }
263
264 static inline long long timespec_sub_usec(const struct timespec *left,
265                                           const struct timespec *right)
266 {
267         struct timespec result;
268         timespec_sub(&result, left, right);
269         return (long long)result.tv_sec * SEC_TO_USEC +
270                 result.tv_nsec / USEC_TO_NSEC;
271 }
272
273 static inline long long timespec2usec(const struct timespec *ts)
274 {
275         return ts->tv_sec * SEC_TO_USEC + ts->tv_nsec / USEC_TO_NSEC;
276 }
277
278
279 int create_ac_socket(unsigned int ac) 
280 {
281         int sockfd;
282         unsigned int yes=1, tos;
283
284
285         if ((sockfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
286         {
287                 perror("Unable to open socket");
288                 return -1;
289         }
290         if (fcntl(sockfd, F_SETFL, O_NONBLOCK) != 0) {
291                 perror("set non-blocking socket");
292                 return -1;
293         }
294         if (setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1) {
295                 perror("Unable to set socket");
296                 return -1;
297         }
298
299         if (opt_send_buf_size >= 0) {
300                 if (setsockopt(sockfd,SOL_SOCKET,SO_SNDBUF,&opt_send_buf_size,sizeof(opt_send_buf_size)) == -1) {
301                         perror("Unable to set socket buffer size");
302                         return -1;
303                 }
304         }
305
306         
307         //tos = ((AC_NUM - ac) *2 - 1)*32;
308         tos = ac_to_tos[ac];
309         if (setsockopt(sockfd, SOL_IP, IP_TOS, &tos, sizeof(tos))) {
310                 perror("Unable to set TOS");
311                 close(sockfd);
312                 return -1;
313         }
314
315         return sockfd;
316 }
317
318 void empty_handler()
319 {
320 }
321
322 void reset_statistics()
323 {
324         int i;
325         for (i = 0; i < nr_streams; i++) {
326                 pthread_mutex_lock(&streams[i].mutex);
327                 streams[i].sent = 0;
328                 streams[i].really_sent = 0;
329                 streams[i].received = 0;
330                 pthread_mutex_unlock(&streams[i].mutex);
331         }
332         pthread_mutex_lock(&delay_stats_mutex);
333         clock_gettime(CLOCK_REALTIME, &reset_timestamp);
334         memset(delay_stats, 0, sizeof(delay_stats));
335         pthread_mutex_unlock(&delay_stats_mutex);
336 }
337
338 void* receiver(void* queue)
339 {
340         struct msg_t    msg;
341         struct  sockaddr_in rem_addr;
342         int     mlen, ret;
343         unsigned int ac, rem_addr_length; 
344         long long int trans_time_usec, client_to_server_usec, server_to_client_usec;
345         long long int min_trans_time;
346         struct timespec send_timestamp, server_timestamp, recv_timestamp;
347         fd_set fdset;
348         
349         min_trans_time = ~0;
350         
351         block_signals();
352         set_rt_prio(99);
353
354         ac = (int)queue;
355         rem_addr_length = sizeof(rem_addr);
356         FD_ZERO(&fdset);
357         while (!exit_flag) {
358                 FD_SET(ac_sockfd[ac], &fdset);
359                 ret = select(ac_sockfd[ac]+1, &fdset, NULL, NULL, NULL);
360                 if (ret < 0) {
361                         if (errno == EINTR) continue;
362                         perror("receiver select");
363                         goto out;
364                 }
365                 mlen = recvfrom(ac_sockfd[ac], &msg, sizeof(msg), 0,
366                                 (struct sockaddr*)&rem_addr, &rem_addr_length);
367                 if (mlen < 0) {
368                         perror("Chyba pri prijimani pozadavku");
369                         goto out;
370                 }       
371                 clock_gettime(CLOCK_REALTIME,&recv_timestamp);
372                 send_timestamp = msg.send_timestamp;
373                 server_timestamp = msg.sendback_timestamp;
374
375                 /* Check whether this message was sent after reset_statistics() */
376                 
377                 if ((ret = timespec_sub_usec(&send_timestamp, &reset_timestamp)) < 0) {
378                         continue; /* If so, don't count it */
379                 }
380
381                 trans_time_usec = timespec_sub_usec(&recv_timestamp ,&send_timestamp) / 2;
382                 client_to_server_usec = timespec_sub_usec(&server_timestamp, &send_timestamp);
383                 server_to_client_usec = timespec_sub_usec(&recv_timestamp, &server_timestamp);
384
385                 pthread_mutex_lock(&delay_stats_mutex);
386                 if (trans_time_usec < MAX_DELAY_US) {
387                         delay_stats[ac][trans_time_usec/opt_granularity_usec].csc++;
388                 }
389                 if (client_to_server_usec < MAX_DELAY_US && client_to_server_usec >= 0) {
390                         delay_stats[ac][client_to_server_usec/opt_granularity_usec].cs++;
391                 }
392                 if (server_to_client_usec < MAX_DELAY_US && server_to_client_usec >= 0) {
393                         delay_stats[ac][server_to_client_usec/opt_granularity_usec].sc++;
394                 }
395                 pthread_mutex_unlock(&delay_stats_mutex);
396                 
397                 receivers[ac].received++;
398                 
399                 pthread_mutex_lock(&streams[msg.stream].mutex);
400                 streams[msg.stream].received++;
401                 pthread_mutex_unlock(&streams[msg.stream].mutex);
402         
403                 /*if (trans_time_nsec < min_trans_time) 
404                         min_trans_time = trans_time_nsec;*/
405                 /*printf("seqn= %lu tos= %d start= %lu(s).%lu(ns)"\
406                          "stop= %lu(s).%lu(ns)\n trans_time = %lums\n",\
407                          msg.seqn, msg.tos, send_timestamp.tv_sec,\
408                          send_timestamp.tv_nsec,recv_timestamp.tv_sec,\
409                          recv_timestamp.tv_nsec, trans_time_msec); */
410         }
411 out:
412         sem_post(&sem_thread_finished);
413         return NULL;
414 }
415
416 /** 
417  * Send a packet.
418  * 
419  * @return -1 in case of error, 1 in case of sucessfull send and 0
420  *         when all buffers are full.
421  */
422 static inline int 
423 send_packet(struct stream* stream, union msg_buff* buff)
424 {
425         int ret = 1;
426         while (sendto(ac_sockfd[stream->ac], buff, stream->packet_size, 0,
427                       (struct sockaddr*)&stream->rem_addr, sizeof(stream->rem_addr)) < 0) {
428                 if (errno == EINTR) continue;
429                 if (errno == EAGAIN) {
430                         if (opt_wait_for_queue_is_full && 
431                             !some_queue_is_full && 
432                             /* We use mutex as atomic test and set */
433                             (pthread_mutex_trylock(&queue_full_mutex) != EBUSY)) {
434                                 some_queue_is_full = true;
435                                 reset_statistics();
436                         }
437                         ret = 0;
438                         break;
439                 } else {
440                         perror("Error while sending");
441                         ret = -1;
442                         break;
443                 }
444         }
445         return ret;
446 }
447
448 static inline void
449 wait_for_next_send(struct stream* stream, struct timespec *last_send_time)
450 {
451         struct timespec time_to_wait, current_time, period, interval;
452         unsigned period_usec = stream->period_usec;
453
454         /*           |~~~+~~~| jitter interval (width = 2*stream->jitter percentage from period)*/
455         /* |-------------|     nominal period*/
456         if (stream->jitter) {
457                 period.tv_nsec = USEC_TO_NSEC*(period_usec*(100-stream->jitter)/100
458                                                + rand() % (2*period_usec*stream->jitter/100));
459         } else {
460                 period.tv_nsec = USEC_TO_NSEC*(period_usec);
461         }
462         period.tv_sec = 0;
463         
464         timespec_add(&time_to_wait, last_send_time, &period);
465         clock_gettime(CLOCK_REALTIME,&current_time);
466         timespec_sub(&interval,&time_to_wait,&current_time);
467         nanosleep(&interval,NULL);
468 }
469
470
471 void* sender(void* arg)
472 {
473         union msg_buff buff;
474         unsigned long int seqn;
475         struct stream* stream = (struct stream*) arg;
476         char stream_desc[100];
477         int ret;
478
479         stream_to_text(stream_desc, sizeof(stream_desc), stream, 0);
480         printf("%s\n", stream_desc);
481
482         if (stream->bandwidth_bps == 0)
483                 goto out;
484
485         seqn = 0;
486         
487         block_signals();
488         set_rt_prio(90-stream->ac);
489
490         while (!exit_flag) {
491
492 /*              buff.msg.seqn = seqn++; */
493 /*              buff.msg.tos = ac_to_tos[stream->ac]; */
494                 buff.msg.stream = stream-streams;
495                 
496                 clock_gettime(CLOCK_REALTIME,&buff.msg.send_timestamp);
497
498                 ret = send_packet(stream, &buff);
499                 if (ret < 0) {
500                         goto out;
501                 }
502
503                 pthread_mutex_lock(&stream->mutex);
504                 stream->sent++;
505                 if (ret > 0)
506                         stream->really_sent++;
507                 pthread_mutex_unlock(&stream->mutex);
508
509 #ifdef DEBUG
510                 printf("%d", stream->ac);
511                 fflush(stdout);
512 #endif
513
514                 wait_for_next_send(stream, &buff.msg.send_timestamp);
515         }
516 out:
517         sem_post(&sem_thread_finished);
518         return NULL;
519 }
520
521 static inline void
522 calc_stream_params(struct stream *stream)
523 {
524         int packet_size;
525         unsigned period_usec;
526         int bandwidth;
527         struct hostent* ph;
528
529         bandwidth = stream->bandwidth_bps;
530
531         /* Avoid arithmetic exception. Server thread will exit if
532            stream->bandwidth_bps == 0. */
533         if (bandwidth == 0) bandwidth = 1;
534
535         if (stream->packet_size) {
536                 packet_size = stream->packet_size;
537                 period_usec = SEC_TO_USEC*packet_size*8/bandwidth;
538                 if (period_usec == 0) period_usec = 1;
539         } else if (stream->period_usec) {
540                 period_usec = stream->period_usec;
541                 packet_size = (long long)bandwidth/8 * period_usec/SEC_TO_USEC;
542         } else {
543                 char buf[200];
544                 stream_to_text(buf, sizeof(buf), stream, 0);
545                 fprintf(stderr, "Neither packet size nor period was specified for a stream %s\n", buf);
546                 exit(1);
547         }
548
549         if (packet_size < sizeof(struct msg_t)) {
550                 fprintf(stderr, "Packet size too small (min %d)\n", sizeof(struct msg_t));
551                 exit(1);
552         }
553
554         stream->packet_size = packet_size;
555         stream->period_usec = period_usec;
556         stream->jitter = opt_jitter;
557
558         memset(&stream->rem_addr,0, sizeof(stream->rem_addr));
559                 
560         stream->rem_addr.sin_family = AF_INET;
561         ph = gethostbyname(server_addr);
562         if (ph) 
563                 stream->rem_addr.sin_addr = *((struct in_addr *)ph->h_addr);
564         else {
565                 perror("Unknown server");
566                 exit(1);
567         }
568         stream->rem_addr.sin_port = htons(BASE_PORT + stream->ac);
569
570 }
571
572 /** 
573  * Parse -b parameter.
574  * 
575  * @param params String to parse
576  * 
577  * @return NULL in case of success, pointer to a problematic character
578  *         on error.
579  */
580 char* parse_bandwidths(char *params)
581 {
582         struct stream *sp = &streams[nr_streams];
583
584         while (*params && nr_streams < MAX_STREAMS) {
585                 char *ac_ids[AC_NUM] = { [AC_VO]="VO", [AC_VI]="VI", [AC_BE]="BE", [AC_BK]="BK" };
586                 int i;
587                 char *next_char;
588
589                 if (strlen(params) < 2)
590                         return params;
591                 for (i=0; i<AC_NUM; i++) {
592                         if (strncmp(params, ac_ids[i], 2) == 0) {
593                                 sp->ac = i;
594                                 params+=strlen(ac_ids[i]);
595                                 break;
596                         }
597                 }
598                 if (i==AC_NUM)
599                         return params;
600
601                 long bw;
602                 if (*params == ':') {
603                         params++;
604
605                         bw = strtol(params, &next_char, 10);
606                         if (next_char == params)
607                                 return params;
608                         params = next_char;
609                 } else
610                         bw = opt_def_bandwidth;
611                 
612                 sp->bandwidth_bps = bw*Kbit;
613
614                 long period = 0;
615                 long packet_size = 0;
616                 if (*params == '@') {
617                         params++;
618                         period = strtol(params, &next_char, 10);
619                         if (period == 0)
620                                 return params;
621                         params = next_char;
622                 }
623                 else {
624                         if (*params == '/') {
625                                 params++;
626                                 packet_size = strtol(params, &next_char, 10);
627                                 if (packet_size == 0)
628                                         return params;
629                                 params = next_char;
630                         } else {
631                                 packet_size = opt_packet_size;
632                                 period = opt_def_period_msec;
633                         }
634                 }
635                 sp->period_usec = period*MSEC_TO_USEC;
636                 sp->packet_size = packet_size;
637
638                 
639
640                 if (*params != '\0' && *params != ',')
641                         return params;
642                 nr_streams++;
643                 sp++;
644                 if (*params == ',')
645                         params++;
646         }
647         return NULL;
648 }
649
650 int main(int argc, char *argv[])
651 {
652         int ac, i, rc, seconds;
653         pthread_attr_t attr;
654         pthread_t thread;
655         char opt;
656
657
658         while ((opt = getopt(argc, argv, "B:b:c:g:j:o:qQ:s:T:")) != -1) {
659                 switch (opt) {
660                         case 'B':
661                                 opt_def_bandwidth = atoi(optarg);
662                                 break;
663                         case 'b': {
664                                 char *error;
665                                 error = parse_bandwidths(optarg);
666                                 if (error != NULL) {
667                                         if (*error == '\0')
668                                                 fprintf(stderr, "Bandwidth parse error - string to short\n");
669                                         else
670                                                 fprintf(stderr, "Bandwidth parse error at '%s'\n", error);
671                                         exit(1);
672                                 }
673                                 break;
674                         }
675                         case 'c':
676                                 opt_count_sec = atoi(optarg);
677                                 break;
678                         case 'g':
679                                 opt_granularity_usec = atoi(optarg);
680                                 if (opt_granularity_usec < MIN_GRANULARITY) {
681                                         fprintf(stderr, "Granulatiry too small (min %d)!\n", MIN_GRANULARITY);
682                                         exit(1);
683                                 }
684                                 break;
685                         case 'j':
686                                 opt_jitter = atoi(optarg);
687                                 break;
688                         case 'o':
689                                 opt_output = optarg;
690                                 break;
691                         case 'Q':
692                                 opt_send_buf_size = atoi(optarg);
693                                 break;
694                         case 'q':
695                                 opt_wait_for_queue_is_full = true;
696                                 break;
697                         case 's':
698                                 opt_packet_size = atoi(optarg);
699                                 break;
700                         case 'T':
701                                 opt_def_period_msec = atoi(optarg);
702                                 break;
703                         default:
704                                 fprintf(stderr, "Usage: %s [ options ] server_addr\n\n", argv[0]);
705                                 fprintf(stderr, "Options:\n");
706                                 fprintf(stderr, "    -B  default bandwidth for -b option [kbit]\n");
707                                 fprintf(stderr, "    -b  bandwidth of streams (VO|VI|BE|BK)[:<kbit>][@<msec> or /<bytes>][,...]\n");
708                                 fprintf(stderr, "    -c  count (number of seconds to run)\n");
709                                 fprintf(stderr, "    -g  histogram granularity [usec]\n");
710                                 fprintf(stderr, "    -j  send jitter (0-100) [%%]\n");
711                                 fprintf(stderr, "    -o  output filename (.dat will be appended)\n");
712                                 fprintf(stderr, "    -q  gather statistics only after some queue becomes full\n");
713                                 fprintf(stderr, "    -Q  <bytes> set size for socket send buffers\n");
714                                 fprintf(stderr, "    -s  size of data payload in packets [bytes] (default: %d)\n", opt_packet_size);
715                                 fprintf(stderr, "    -T  default period for -b option [msec]\n");
716                                 exit(1);
717                 }
718         }
719         if (opt_packet_size && opt_def_period_msec) {
720                 fprintf(stderr, "Error: Nonzero -T and -s can't be used together!.\n");
721                 exit(1);
722         }
723
724         if (optind < argc) {
725                 server_addr = argv[optind];
726         } else {
727                 fprintf(stderr, "Expected server address argument\n");
728                 exit(1);
729         }
730
731         if (nr_streams == 0)
732                 parse_bandwidths("BE");
733                 
734         pthread_attr_init(&attr);
735
736         snprintf(logfname, sizeof(logfname), "%s.dat", opt_output);
737
738         if ((logfd = fopen(logfname,"w+")) == NULL) {
739                 fprintf(stderr,"Can not open %s\n", logfname);
740                 exit(1);
741         }
742         if (signal(SIGTERM, stopper) == SIG_ERR) {
743                 perror("Error in signal registration");
744                 exit(1);
745         }
746                 
747         if (signal(SIGINT, stopper) == SIG_ERR) {
748                 perror("Signal handler registration error");
749                 exit(1);
750         }
751
752         struct sigaction sa;
753         sa.sa_handler = empty_handler;
754         sa.sa_flags = 0;        /* don't restart syscalls */
755
756         if (sigaction(SIGUSR1, &sa, NULL) < 0) {
757                 perror("sigaction error");
758                 exit(1);
759         }
760
761         sem_init(&sem_thread_finished, 0, 0);
762
763         reset_statistics();
764
765         /* create four receivers each per AC */
766         for (ac = AC_NUM - 1; ac >= 0; ac--) {
767                 ac_sockfd[ac] = create_ac_socket(ac);
768                 if (ac_sockfd[ac] < 0) {
769                         return 1;
770                 }
771                 rc = pthread_create(&receivers[ac].thread, &attr, receiver, (void*) ac);
772                 if (rc) {
773                         fprintf(stderr, "Error while creating receiver %d\n",rc);
774                         return 1;
775                 }
776         }               
777                         
778         /* create sendpoints */
779         for (i = 0; i < nr_streams; i++) {
780                 struct stream *s = &streams[i];
781                 pthread_mutex_init(&s->mutex, NULL);
782                 calc_stream_params(s);
783                 rc = pthread_create(&thread, &attr, sender, (void*) s);
784                 if (rc) {
785                         fprintf(stderr, "Error while creating sender %d\n",rc);
786                         return 1;
787                 }
788         }
789         
790         seconds = 0;
791         while (!exit_flag) {
792                 sleep(1);
793                 seconds++;
794                 fprintf(stderr, "\r%3ds", seconds);
795                 for (ac = 0; ac < AC_NUM; ac++) {
796                         int delta = receivers[ac].received - receivers[ac].last_received;
797                         receivers[ac].last_received = receivers[ac].received;
798                         fprintf(stderr, " %s %5d %4d/s", ac_to_text[ac], receivers[ac].received, delta);
799                 }
800                 fflush(stderr);
801                 if (seconds == opt_count_sec)
802                         stopper();
803         }
804
805         fprintf(stderr, "\nWaiting for threads to finish\n");
806         /* Wait for all threads to finish */
807         for (i=0; i < nr_streams + AC_NUM; i++) {
808                 sem_wait(&sem_thread_finished);
809         }
810         struct timespec end_timestamp, measure_length;
811         clock_gettime(CLOCK_REALTIME,&end_timestamp);
812         timespec_sub(&measure_length, &end_timestamp, &reset_timestamp);
813
814         save_results(argc, argv, timespec2usec(&measure_length));
815
816         return 0;
817 }