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