summaryrefslogtreecommitdiffstats
path: root/src/hdsync_cli.cpp
blob: 915ced3c266993a66a7de6532396e1f871df6037 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
/* HDSync
   
 (c) 2011-2012 Montevideo / Time Based Arts (aka NIMk.nl)
     2011-2012 Denis Roio <jaromil@dyne.org>

     This program is free software: you can redistribute it and/or modify
     it under the terms of the GNU Affero General Public License as
     published by the Free Software Foundation, either version 3 of the
     License, or (at your option) any later version.
     
     This program is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     GNU Affero General Public License for more details.
     
     You should have received a copy of the GNU Affero General Public License
     along with this program.  If not, see <http://www.gnu.org/licenses/>

*/

#include <config.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
//#include <netdb.h>

#include <errno.h>

#include <sys/types.h>
#include <ifaddrs.h>
#include <netinet/in.h> 
#include <arpa/inet.h>

#include <avremote.h>
#include <parsers.h>
#include <zmq.h>
#include <zmq_utils.h>

// our exit codes are shell style: 1 is error, 0 is success
#define ERR 1

// uncomment to debug
#define DEBUG 1

// network settings
#define ETHDEV "eth0"
#define PGMPORT "5555"


// commandline switches
char filename[512];
char server[512];
int port = 0;
int dryrun = 0;
int chanID = 0;
int chanTOT = 0;

// upnp reply parser
parser_f *parser = NULL;

// peers found
char **listeners = NULL;


// own IPv4 address
char IPv4[24];

// 0mq
void *zcontext;
void *sock_in = NULL;
void *sock_shout = NULL;
char pgmaddr[64];
zmq_msg_t request;

// we use only getopt, no _long
static const char *short_options = "-hvts:p:";

void cmdline(int argc, char **argv);


int get_address();


int shout(const char *message, int flags) {
  int res;
  //  zmq_connect(sock_out, pgmaddr);
  zmq_msg_init_size (&request, strlen(message));
  memcpy (zmq_msg_data (&request), message, strlen(message));
  printf ("Shouting \"%s\"\n", message);
  res = zmq_send (sock_shout, &request, flags);
  zmq_msg_close (&request);
  //  zmq_close(sock_out);
  return(res);
}

// extract a string from a message received:
// PREFIX;MESSAGE;
// message should be a char of 512 bytes 
int expect(const char *prefix, char *message, int flags) {
  zmq_msg_t reply;
  char res[512];
  char *p, *pp;
  int pfxlen = strlen(prefix);

  printf("Expecting prefix %s\n",prefix);

  // listen for answers
  zmq_msg_init (&reply);
  zmq_recv (sock_in, &reply, flags);
  // printf ("Received response\n");
  snprintf(res,511,"%s",zmq_msg_data(&reply));
  zmq_msg_close (&reply);
  
  // parse the response and if ACK insert it in uniq list
  if( strncmp(res,prefix,pfxlen) == 0) {
    // quick and secure string parsing
    p = res; while(*p != ';') p++; p++;
    pp = p; while(*pp != ';') pp++; *pp='\0';
    
    // *p has the ip string
    snprintf(message,511,"%s",p);
    printf("Expected prefix %s found: %s\n",prefix,message);
    return(0);
  }
  
  return(1);
}

int handshake() {
  int request_nbr;
  char message[256];
  int listindex = 0;
  int listmax = 0;
  char res[512];
  int c, i;
  
  if(chanID==1) { // first channel is the one to offer
    
    ////////
    // OFFER
    //////////////////////////////
    printf ("Offering on %s from address %s\n",pgmaddr, IPv4);
    
    listmax = chanTOT; // number of desired peers
    listmax--; // we count outrselves in
    printf("looking to connect %u peers\n",listmax);
    // allocate space for listener array
    listeners = (char**) calloc(listmax,sizeof(char*));
    for(i=0; i<listmax; i++) listeners[i] = (char*)calloc(16, sizeof(char));
    
    // offer subscribes to all broadcasts by default
    // somehow listening to ACK only doesn't works
    snprintf(message,255,"OFFER;%s;",IPv4);
    while(1) {
      
      shout(message, 0);

      if( expect("ACK",res, 0) == 0) {
	printf("Got ACK from %s\n",res);
	// parse the response and if ACK insert it in uniq list
	for(c=0; c<listindex; c++)
	  if(strncmp(listeners[c], res, 16) == 0)
	    break; // found a duplicate
	if(c==listindex) { // there was no duplicate
	  snprintf(listeners[c], 16, "%s", res);
	  printf("New listener: %s\n",listeners[c]);
	  listindex++;
	}
	
	if(listindex==listmax) { // goal reached
	  printf("Sending ready signals to listeners\n");
	  ///////////////////////////////////////////////
	  shout("READY", 0);
	  break; // break offer loop
	} // if listmax reached
	
      } // if ACK response

      zmq_sleep(1);

    }	// offer while loop
    
  } else { // all other channels listen

      /////////
      // LISTEN

      printf ("Listening on %s from address %s\n",pgmaddr, IPv4);

      snprintf(message,255,"ACK;%s;",IPv4);

      while (1) {
        //  Wait for offer
	while( expect("OFFER", res, 0) !=0); // blocking
	// reply with ACK
	shout(message, 0);
	
	while( expect("READY", res, 0) !=0); // blocking
	printf ("Received ready signal\n");
	break; // quit loop on ready signal
	
      }

  }
    
  return(1);
}

int main(int argc, char **argv) {
  upnp_t *upnp;
  int found;

  //////////
  ///// INIT

  cmdline(argc, argv);

  if(!filename[0]) {
    fprintf(stderr,"not enough args specified on commandline, see help.");
    exit(ERR);
  }

  fprintf(stderr,"HDSync starting for channel %u of %u\n",chanID, chanTOT);
  fprintf(stderr,"will sync and play video: %s\n", filename);

  upnp = create_upnp();
  
  // no server specified, force localhost
  if(!server[0]) sprintf(server,"localhost");

  // commandline or detection found explicit addresses
  snprintf(upnp->hostname, MAX_HOSTNAME_SIZE-1,"%s",server);
  upnp->port = port;

  if(!dryrun) {
    if ( connect_upnp (upnp) < 0 ) {
      fprintf(stderr,"can't connect to %s:%u: operation aborted.\n", server, port);
      free_upnp(upnp);
      exit(ERR);
    } else {
      fprintf(stderr,"UPNP connected to %s:%u\n",server, port);
      close(upnp->sockfd);
      upnp->sockfd = 0;
    }
  }

  if( ! get_address() )  {
    fprintf(stderr,"Error getting own address.\n");
    exit(ERR);
  }

  // initialize 0mq
  zcontext = zmq_init (1);

  // create broadcast socket
  sock_shout = zmq_socket (zcontext, ZMQ_PUB);
  zmq_connect(sock_shout, pgmaddr);

  // create input socket
  sock_in = zmq_socket (zcontext, ZMQ_SUB);
  zmq_bind (sock_in, pgmaddr);
  zmq_setsockopt(sock_in,ZMQ_SUBSCRIBE,"",0);


  /// END OF INIT
  ////////////////  


  ////////////////////
  if(! handshake()) {
    // no error return so far, just running endless untill contact is established
    fprintf(stderr,"error establishing contact with all desired channels, aborting.\n");
    exit(ERR);
  }

  printf("Handshake successful\n");

  //////////////////////
  if(dryrun) { // DRYRUN
    printf("Dry run\n");
    
    // testing sync with no real playback
    zmq_sleep(1);

    if(chanID==1) { // offer should send sync

      printf("Prepare to offer sync\n");
      
      zmq_sleep(3);

      shout("SYNC;GOGO;", 0);

    } else { // listener should prepare to receive sync

      printf("Prepare to receive sync\n");

      // TODO
      zmq_sleep(6);
    }
    
    //////////////////////

  } else { // RUN FOR REAL

    //////////////////////
  
    // load, play and pause in sequence
    // break and reopen connection in between
    

    if(chanID==1) { // offer should send sync
      zmq_sleep(1);
      // create output socket
      //      sock_out = zmq_socket (zcontext, ZMQ_PUB);
      //      zmq_connect(sock_out, pgmaddr);
      // prepare signal
      zmq_msg_init_size (&request, 4);
      memcpy (zmq_msg_data (&request), "SYNC", 4);

      // stop player
      connect_upnp(upnp);
      render_upnp(upnp,"Stop","");
      send_upnp(upnp);
      recv_upnp(upnp, 1000);
      close(upnp->sockfd);
      upnp->sockfd = 0;


      zmq_sleep(1);


      // prepare player in position
      render_uri_meta(upnp,filename);
      render_upnp(upnp,"SetAVTransportURI", upnp->meta);
      send_upnp(upnp);
      recv_upnp(upnp, 1000);
      close(upnp->sockfd);
      upnp->sockfd = 0;

      zmq_sleep(1);

      // play
      connect_upnp(upnp);
      render_upnp(upnp,"Play","<Speed>1</Speed>");
      send_upnp(upnp);
      recv_upnp(upnp, 1000);
      close(upnp->sockfd);
      upnp->sockfd = 0;
      // pause
      connect_upnp(upnp);
      render_upnp(upnp,"Pause","");
      send_upnp(upnp);
      recv_upnp(upnp, 1000);
      close(upnp->sockfd);
      upnp->sockfd = 0;

      zmq_sleep(1);
      
      // prepare upnp play message
      connect_upnp(upnp);
      render_upnp(upnp,"Play","<Speed>1</Speed>");

      // send sync signal
      //      zmq_send (sock_out, &request, 0);

      // start player
      send_upnp(upnp);
      recv_upnp(upnp, 1000);

    } else { // this is a listener

      // create input socket
      sock_in = zmq_socket (zcontext, ZMQ_SUB);
      zmq_bind (sock_in, pgmaddr);      


      // stop player
      connect_upnp(upnp);
      render_upnp(upnp,"Stop","");
      send_upnp(upnp);
      recv_upnp(upnp, 1000);
      close(upnp->sockfd);
      upnp->sockfd = 0;


      zmq_sleep(1);


      // prepare player in position
      render_uri_meta(upnp,filename);
      render_upnp(upnp,"SetAVTransportURI", upnp->meta);
      send_upnp(upnp);
      recv_upnp(upnp, 1000);
      close(upnp->sockfd);
      upnp->sockfd = 0;

      zmq_sleep(1);

      // play
      connect_upnp(upnp);
      render_upnp(upnp,"Play","<Speed>1</Speed>");
      send_upnp(upnp);
      recv_upnp(upnp, 1000);
      close(upnp->sockfd);
      upnp->sockfd = 0;
      // pause
      connect_upnp(upnp);
      render_upnp(upnp,"Pause","");
      send_upnp(upnp);
      recv_upnp(upnp, 1000);
      close(upnp->sockfd);
      upnp->sockfd = 0;

      zmq_sleep(1);
      
      // prepare upnp play message
      connect_upnp(upnp);
      render_upnp(upnp,"Play","<Speed>1</Speed>");
      
      //  Wait for next request from client
      zmq_msg_init (&request);
      zmq_recv (sock_in, &request, 0);
      if(strncmp((char*)zmq_msg_data(&request),"SYNC",4)==0) {
	// start player
	send_upnp(upnp);
	recv_upnp(upnp, 1000);
      }

    } // if(offer|listen)

    zmq_msg_close (&request);
    free_upnp(upnp);

  } // if(test|real)

  fprintf(stderr,"Software shutdown\n");

  // if(sock_out) {
  //  zmq_close (sock_out);
  //   sock_out = NULL;
  // }
  // if(sock_in) {
  //  zmq_close (sock_in);
  //   sock_in = NULL;
  // }

  // somehow offer blocks here
  zmq_term (zcontext);

  if(listeners) {
    for(int c; c<chanTOT; c++)
      free(listeners[c]);
    free(listeners);
  }
  
  fprintf(stderr,"Done.\n");
  exit(0);
}


void cmdline(int argc, char **argv) {
  filename[0] = 0;
  server[0] = 0;

  int res, optlen;
  do {
    res = getopt(argc, argv, short_options);
    switch(res) {
    case 'h':
      fprintf(stderr,
	      "%s %s - prepare and start synced playback of video across devices\n"
	      "\n"
	      " Copyright (C) 2011-2012 Jaromil @ Dyne.org , License GNU AGPL v3+\n"
	      " This is free software: you are free to change and redistribute it.\n"
	      " The latest HDSync sourcecode is published on <%s>\n"
	      "\n"
	      "Syntax: hdsync [options] channel_id channel_total filename\n"
	      "\n"
	      "Commands:\n"
	      "\n"
	      " prepare     prepare a file ready to sync\n"
	      " start       start the video that was prepared\n"
	      "\n"
	      "Options:\n"
	      "\n"
	      " -s          network address or hostname of the media server\n"
	      " -p          port on which the UPNP AVTransport daemon is listening\n"
	      " -t          dry run to test without a server (print out rendered xml)\n"
	      "\n"
	      " -h          print this help\n"
	      " -v          version information for this tool\n"
	      "\n"
	      "For more informations on HDSync see <http://syncstarter.org>\n"
	      "Please report bugs on <http://bugs.dyne.org>.\n",
	      PACKAGE, VERSION, PACKAGE_URL);
      exit(0);

    case 'v':
      fprintf(stderr,"%s - simple commandline tool to send AVTransport commands over UPNP\n"
	      "version %s distributed by Montevideo/NIMk\n"
	      "Copyright (C) 2011-2012 Jaromil @ Dyne.org, License GNU AGPL v3+\n"
	      "This is free software: you are free to change and redistribute it\n",
	      PACKAGE, VERSION);
      exit(0);
      
    case 's':
      snprintf(server,511,"%s",optarg);
      break;

    case 'p':
      sscanf (optarg, "%u", &port);
      break;

    case 't':
      dryrun = 1;
      break;

    case '?':
      fprintf(stderr,"unrecognized option: %s\n",optarg);
      break;
      
    case 1:
      if(!chanID) {
	sscanf(optarg,"%u",&chanID);
      } else if(!chanTOT) {
	sscanf(optarg,"%u",&chanTOT);
      } else if(!filename[0]) {
	snprintf(filename,511,"%s",optarg);
      }
      break;
    default:
      break;
    }

  } while(res != -1);
}

int get_address() {
    // discover own IP address
    struct ifaddrs * ifAddrStruct=NULL;
    struct ifaddrs * ifa=NULL;
    void * tmpAddrPtr=NULL;

    printf("Handshake on LAN\n");

    getifaddrs(&ifAddrStruct);

    pgmaddr[0] = NULL; // zero if iface not found

    for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) {
        if (ifa ->ifa_addr->sa_family==AF_INET) { // check it is IP4
            // is a valid IP4 Address
            tmpAddrPtr=&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
            char addressBuffer[INET_ADDRSTRLEN];
            inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
            // printf("%s IP Address %s\n", ifa->ifa_name, addressBuffer);
	    if( strcmp(ifa->ifa_name, ETHDEV) == 0) {
	      strncpy(IPv4, addressBuffer, 16);
	      snprintf(pgmaddr,63,"pgm://%s:%s",ifa->ifa_name, PGMPORT);
	    }
	}
    }
    if (ifAddrStruct!=NULL) freeifaddrs(ifAddrStruct);
    
    if(!pgmaddr[0]) {
      printf("Error: ethernet interface %s is not configured\n",ETHDEV);
      return(0);
    }
    return(1);
}