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