aboutsummaryrefslogtreecommitdiff
path: root/src/InputStream.cpp
blob: 8b6a331411e90d42da6b7bb32a19ec2527f62426 (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
#include "InputStream.h"
#include <iostream>		// cout, cerr
#include <string>		// strcpy, etc.

using namespace std;

int receive (int fd, unsigned char *rcvbuffer, int size) {
  fd_set set;
  struct timeval tv;
  int ret = -1;
  int selret = -1;
  tv.tv_sec = 1;
  tv.tv_usec = 500;
  FD_ZERO(&set);
  FD_SET(fd, &set);

  selret= select(fd +1, &set, NULL, NULL, &tv);
  if ( selret > 0 ) {
    // we can now be certain that ret will return something.
    ret = recv (fd, rcvbuffer, size, 0);
    if (ret < 0 ) {
      cerr << "InputStream:: receive error" << endl;
      return -1;
    }
    return ret;
  } else if ( selret == -1 ){
    cerr << "InputStream:: receive: select timed out, returned "<< selret << endl;
    return -1;
  }
  // return zero...means keep  on selecting
  return 0;
}

void * fill_infifo (void *zz) {
  int ret, wret, last_type, last_state;
  unsigned char tmp[SOCKET_READSIZE];
  InputStream *instream = (InputStream *) zz;
	
  pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &last_type);
  pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &last_state);
  
  pthread_mutex_lock (instream->get_mutex ());
  instream->set_threaded(true);
  pthread_cond_signal (instream->get_condition ());
  pthread_mutex_unlock (instream->get_mutex ());	
  //cout << "signalled parent thread" << endl;
  while ( 1 ) {
    while (instream->get_fifo()->FreeSpace() > SOCKET_READSIZE + 576) {
      // it's possible to hang here, watch this 
      if ( instream->get_quit() ) break;
      ret = receive (instream->get_fd() , tmp, SOCKET_READSIZE);
      if (ret > 0){
	wret = instream->get_fifo()->Write ((void *) tmp, ret * sizeof (unsigned char));
      } else if ( ret == -1){
	// got -1 on recieve. ...this means select failed and there is no data
	cerr << "InputStream:: fill_infifo: select failed, our socket must have died" << endl;
	if ( instream->get_recover() ) {
	  cout << "InputStream:: try to reconnect to server..." << endl;
	  if ( instream->socket_connect () < 0 ) {
	    cout << "InputStream:: tried to recover stream but socket connect failed" <<endl;
	    break;
	  }
	} else {
	  break;
	}
      } else {
	// got 0?? on recieve. ...select timed out, cause there wasn't any data
	//cerr << "InputStream: fill_infifo: select timed out, no data.  ret = " << ret << endl;
	// keep on truckin' until we get a select and recv that sticks
      }
    }
    if ( instream->get_quit() ) break;
    //cerr << "InputStream: fifo is full" << endl;
    pthread_mutex_lock (instream->get_mutex ());
    pthread_cond_wait (instream->get_condition (), instream->get_mutex ());
    pthread_mutex_unlock (instream->get_mutex ());	
    
  }
  instream->set_threaded(false);
  return NULL;
}

InputStream::InputStream () {
  fd = 0;
  format = -1;
  threaded = false;
  port = 0;
  infifo = new Fifo( STREAM_FIFOSIZE );
  quit = false;
  recover = false;
  verbosity = 1;
  pthread_mutex_init(&mut, 0);
  pthread_cond_init(&cond, 0);
}

InputStream::~InputStream () {
  quit = true;
  void *status;
  
  if (threaded ) 
    {
      //cout << "canceling thread" << endl;
      pthread_cond_signal ( &cond );
      //pthread_cancel( childthread );
      pthread_join( childthread, &status);
      threaded = -1;
      //cout << "thread canceled" << endl;
    }
  delete infifo;
}


// Open() returns the file type, either WAV, MP3, OGG, etc. see input.h
// this is a blocking call, in order to use the open command we need
// to figure out the format (ogg, mp3, etc).  this has to block.

int InputStream::Open (const char *pathname) {
  int rettype, thret;
  filename = pathname;
  if (verbosity > 1) 
    cout << "trying to open a socket connection" << endl;
  SetUrl (pathname);

  rettype = socket_connect( ); //hostname, mountpoint, port );
  if (rettype < 0) {  // couldn't connect or got a bad filetype
    cerr << "InputStream:: Couldn't connect or got a bad filetype" <<endl;
    return -1;
  }
  // start thread here to fill infifo
  //cout << "creating thread" << endl;
  thret = pthread_create(&childthread, NULL, fill_infifo, (void *)this);
  if ( thret!= 0 )
    return -1;
  //wait for thread to be created.
  pthread_mutex_lock( &mut );
  while ( !threaded )
    pthread_cond_wait( &cond, &mut );
  pthread_mutex_unlock( &mut );
  //cout << "threaded = " << threaded << "rettype = " << rettype << endl;
  
  while ( get_fifo()->UsedSpace () < (unsigned int)(STREAM_FIFOSIZE / 2) ) {
    usleep(100);  // we need to wait here for some of the input buffer to fill.
    //cout << "waiting for HTTP buffer to fill  " << get_fifo()->UsedSpace () <<endl;
  }
  /*  if ( rettype == FORMAT_HTTP_VORBIS) {
    cout << "---------->Lets try to flush fifo and fill again" <<endl;
    get_fifo()->Flush();
    pthread_cond_signal ( &cond );
    while ( get_fifo()->UsedSpace () < (unsigned int)(8500*2) ) {
      usleep(1000);  // we need to wait here for some of the input buffer to fill.
       cout << "waiting for HTTP buffer to fill  " << get_fifo()->UsedSpace () <<endl;
    }
    }*/
  return rettype;
}

int InputStream::Close () {
  // returns zero on success, or -1 if an error occurred
  return sys_closesocket (fd);
}

int InputStream::Read (void *buf, unsigned int count) {
  //if (quit) return -1;  	// return negative if the childthread exits
  //and sets quit true
  infifo->Read( buf ,  count);
  pthread_cond_signal ( &cond );
  return count;
}

long InputStream::SeekSet (long offset) {
  return -1;
}

long InputStream::SeekCur (long offset) {
  return -1;
}

long InputStream::SeekEnd (long offset) {
  return -1;
}

int InputStream::get_line( char * str, int sock, int maxget) {
  int i = 0;
  while(i < maxget - 1) {
    
  if ( recv(sock, str + i, 1, 0) <=  0 )  {
    cerr << "InputStream : could not read from socket" << endl;
    sys_closesocket(sock);
    return (-1);
  }
  if ( str[i] == '\n' )
    break;
  if( str[i] == 0x0A)  /* leave at end of line */
    break;
  if ( str[i] != '\r' )
    i++;
  }
  str[i] = '\0';
  return i;
}

// connect to shoutcast server 
int InputStream::socket_connect ( ) {
  struct sockaddr_in server;
  struct hostent *hp;
  int flags;
  // variables used for communication with server 
  string strtmp;		// tmp string for manipulating server strings
  string line, parsed;	        // string for parsing x-audicast vars
  char strret[STRBUF_SIZE];	// returned string from server
  
  fd_set fdset;
  struct timeval tv;
  int relocate = false;
  std::string::size_type ret;
  

  fd = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
  if (fd < 0) {
    if (verbosity > 0)
      cerr << "InputStream: internal error while attempting to open socket" << endl;
    return (-1);
  }

  //connect socket using hostname 
  server.sin_family = AF_INET;
  hp = gethostbyname (hostname.c_str ());
  
  if (hp == NULL) {
    if (verbosity > 0)
      cerr << "InputStream:: bad host?" << endl;
    sys_closesocket (fd);
    return (-1);
  }


  memcpy ((char *) &server.sin_addr, (char *) hp->h_addr, hp->h_length);
  // assign client port number 
  server.sin_port = htons ((unsigned short) port);
  

  flags = fcntl( fd, F_GETFL, 0);
  fcntl( fd, F_SETFL, FNDELAY);     // make this socket's calls non-blocking 
  //  fcntl( fd, F_SETFL, flags | O_NONBLOCK);

  if (connect( fd, (struct sockaddr *) &server, sizeof(server) ) == -1 && errno != EINPROGRESS) { 
    /*
     * If non-blocking connect() couldn't finish, it returns
     * EINPROGRESS.  That's OK, we'll take care of it a little
     * later, in the select().  But if some other error code was
     * returned there's a real problem...
     */
    sys_closesocket (fd);
    return(-1);
  
  } else {
    //cout << " error is EINPROGRESS " << endl;
    FD_ZERO (&fdset);
    FD_SET (fd, &fdset);
    tv.tv_sec = 1;		/* seconds */
    tv.tv_usec = 0;	/* microseconds */

    //  you want to do the select on the WRITEablity of the socket, HTTP expects a get
    // command, so make sure to pass args to both read and write fdset
    switch (select( fd+1 , &fdset, &fdset, NULL, &tv) ) {
      /*
       * select() will return when the socket is ready for action,
       * or when there is an error, or the when timeout specified
       * using tval is exceeded without anything becoming ready.
       */
      
    case 0:     // timeout 
      //do whatever you do when you couldn't connect
      cout << "InputStream:: connect timed out, bailing..." <<endl;
      sys_closesocket (fd);
      return (-1);
      break;
    case -1:    // error 
      cout << "InputStream:: connection error, bailing..." <<endl;
      sys_closesocket (fd);
      return (-1);
      break;
    default:    // your file descriptor is ready... 
      fcntl( fd, F_SETFL, flags);	
      break;
    }
  }


  // build up stuff we need to send to server 
  // should change it to send GET and then read the header until 
  // it recieves "\n\n", and then parse the header
  strtmp = "GET /" + mountpoint + " HTTP/1.0 \r\nHost: " + hostname +
    "\r\nUser-Agent: Readanysf~ 0.5\r\nAccept: */*\r\n\r\n";
  if (verbosity > 2)
    cout << "sending...." << strtmp << endl;
  if (send (fd, strtmp.c_str (), strtmp.length (), 0) < 0)
    {
      if (verbosity > 0)
	cerr << "InputStream:: could not contact server... " << endl;
      return (-1);
    }
  
  get_line( strret , fd , STRBUF_SIZE ) ;
  strtmp = strret;
  //cout << strtmp << endl;

  ret = strtmp.find ("HTTP", 0);
  if (ret != string::npos) {  /* seems to be IceCast server */
    ret = strtmp.find ("302", 0);
    if (ret != string::npos) {
      if (verbosity > 0)
	cerr << "InputStream::need to relocate...not implemented yet, bailing" << endl;
      relocate = true;
      return (-1);
    }
    ret = strtmp.find ("200", 0);
    if (ret == string::npos) {
      if (verbosity > 0)
	cerr <<  "InputStream : cannot connect to the (default) stream" << endl;
      sys_closesocket (fd);
      return (-1);
    }
    if (verbosity > 2)
      cerr << "everything seems to be fine, now lets parse the server strings" << endl;
    
    // go through header 10 times, line by line. this should be enough.
    // we only need the Content-Type for checking if it's mp3 or vorbis
    for (int i = 0; i < 10; i++)
      {
	get_line( strret , fd , STRBUF_SIZE ) ;
	line = strret;
	//cout << " Got line: " << line << endl; 
	// we could probable parse the Server flag for icecast 1
	// or 2 
	// server type, but that is more trouble than what its
	// worth
	parsed = ParseHttp (line, "Server");
	if (!parsed.empty ())
	  if (verbosity > 1)
	    cout << "server" << parsed << endl;
	parsed = ParseHttp (line, "Content-Type");
	if (!parsed.empty ()) {
	  std::string::size_type n;
	  if (verbosity > 1)  cout << "Content-Type " << parsed << endl;
	  n = parsed.find ("ogg");
	  if (n != string::npos) {
	    if (verbosity > 1)
	      cout << "we have an ogg vorbis stream" << endl;
	    format = FORMAT_HTTP_VORBIS;
	    break;	// found what we were looking for
	  }
	  n = parsed.find ("mpeg");
	  if (n != string::npos){
	    if (verbosity > 1)
	      cout << "we have an Mp3 stream" << endl;
	    format = FORMAT_HTTP_MP3;
	    break;	// found what we were looking for
	  }
	}
	
      }
    
  } else {
    //cout << "not HTTP, could be ICY for shoutcast" << endl;
    ret = strtmp.find ("ICY 200 OK", 0);
    if (ret != string::npos) {  /* seems to be IceCast server */
      // we are only interested in mp3 or ogg content type
      cout << "we have an ICY Mp3 stream" << endl;
      format = FORMAT_HTTP_MP3;

    } else {
      cout << "Neither a Shoutcast or Icecast stream, hafta bail." << endl;
      return -1;
    }
	
  }

  
  return (format);
}

// parses string "str" for the item "parse", if found return the part of 
// "str" after the ":" ex.

string InputStream::ParseHttp (string str, string parse) {
  std::string::size_type ret;
  
  ret = str.find (parse, 0);
  if (ret != string::npos) {
    return str.substr (parse.length () + 1, str.length () - parse.length ());
  }
  return "";
}



int InputStream::SetUrl (const char *url) {
  string strtmp = url;
  std::string::size_type p1, p2, tmp;
  
  tmp = strtmp.find ("http://");
  if (tmp < 0 || tmp > strtmp.length ())
    return 0;
  
  tmp = tmp + 7;
  strtmp = strtmp.substr (tmp, strtmp.length () - tmp);
  
  p2 = strtmp.find ("/", 0);
  if (p2 < 0 || p2 > strtmp.length ()) {
    p2 = strtmp.length();
    //cout << "didn't find the / in the url" <<endl;
    p1 = strtmp.find (":");
    if (p1 < 0 || p1 > strtmp.length ()) {
      port = 80;	// set port to default 80
      hostname = strtmp;
      mountpoint = " "; // send blank mntpoint
    } else {
      // found the ":", setting port number
      port = atoi (strtmp.substr (p1 + 1, p2 - p1 -1).c_str ());
      hostname = strtmp.substr (0, p1);
      mountpoint = " ";  // send blank mntpoint
    }
    return 1;	// didn't find the / in the URL
  }
  p1 = strtmp.find (":");
  if (p1 < 0 || p1 > strtmp.length ()) {
    // didn't find a ":", that 
    // 
    // means there's no port
    port = 80;	// set port to default 8000
    hostname = strtmp.substr (0, p2);
    mountpoint = strtmp.substr (p2 + 1, strtmp.length () - p2);
    if (verbosity > 1)
      cerr << "port is: default " << port << endl;
  } else {
    // found the ":", setting port number
    port = atoi (strtmp.substr (p1 + 1, p2 - p1 - 1).c_str ());
    hostname = strtmp.substr (0, p1);
    mountpoint = strtmp.substr (p2 + 1, strtmp.length () - p2);
  }
  
  if (verbosity > 2 ) {
    cout << "port: " << port << endl;
    cout << "hostname: " << hostname << endl;
    cout << "mount: " << mountpoint << endl;
  }
  return 1;
}

float InputStream::get_cachesize() {
  return (float)infifo->UsedSpace();
}
// ~ parsed = ParseHttp( line, "x-audiocast-location" ) ;
// ~ if ( !parsed.empty()) cout << parsed << endl;
// ~ parsed = ParseHttp( line, "x-audiocast-admin" ) ;
// ~ if ( !parsed.empty()) cout << parsed << endl;
// ~ parsed = ParseHttp( line, "x-audiocast-server-url" ) ;
// ~ if ( !parsed.empty()) cout << parsed << endl;
// ~ parsed = ParseHttp( line, "x-audiocast-mount" ) ;
// ~ if ( !parsed.empty()) cout << parsed << endl;
// ~ parsed = ParseHttp( line, "x-audiocast-name" ) ;
// ~ if ( !parsed.empty()) cout << parsed << endl;
// ~ parsed = ParseHttp( line, "x-audiocast-description" ) ;
// ~ if ( !parsed.empty()) cout << parsed << endl;
// ~ parsed = ParseHttp( line, "x-audiocast-url:http" ) ;
// ~ if ( !parsed.empty()) cout << parsed << endl;
// ~ parsed = ParseHttp( line, "x-audiocast-genre" ) ;
// ~ if ( !parsed.empty()) cout << parsed << endl;
// ~ parsed = ParseHttp( line, "x-audiocast-bitrate" ) ;
// ~ if ( !parsed.empty()) cout << parsed << endl;
// ~ parsed = ParseHttp( line, "x-audiocast-public" ) ;
// ~ if ( !parsed.empty()) cout << parsed << endl;