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