]> git.zerfleddert.de Git - record-dvb/blame - record-dvb.c
better reconnect-logic
[record-dvb] / record-dvb.c
CommitLineData
5c2e3e44 1#include <features.h>
2#include <stdio.h>
3#include <stdlib.h>
4#include <sys/time.h>
5#include <time.h>
6#include <sys/socket.h>
7#include <sys/types.h>
8#include <sys/stat.h>
9#include <fcntl.h>
10#include <unistd.h>
11#include <strings.h>
12
13#include "http.h"
14#include "mcast.h"
15
4710a9f8 16#define CHUNKSIZE 3000
6ac47f90 17#define GTOD_INTERVAL 100
5c2e3e44 18
19void record(int(*open_fn)(char *), char *url, char *outfile, int duration)
20{
21 struct timeval start, curr;
4710a9f8 22 int bytes, recvd, written, count = 0;
34d3d284 23 int error_sleep = 0;
5c2e3e44 24 char buffer[CHUNKSIZE];
5c2e3e44 25 int in, out;
26
4710a9f8 27 if ((in = (*open_fn)(url)) < 0) {
28 fprintf(stderr,"Can't open url %s!\n",url);
5c2e3e44 29 exit(EXIT_FAILURE);
30 }
31
4710a9f8 32 if ((out = open(outfile, O_CREAT|O_TRUNC|O_WRONLY|O_LARGEFILE, 00644)) < 0) {
33 perror("open");
5c2e3e44 34 exit(EXIT_FAILURE);
35 }
36
37 printf("Recording from %s for %d seconds...\n", url, duration);
38
39 gettimeofday(&start, NULL);
6ac47f90 40 curr = start;
5c2e3e44 41
42 do {
34d3d284 43 if (error_sleep) {
44 sleep(error_sleep);
45 printf("Reconnecting... ");
b973e875 46 if ((in = (*open_fn)(url)) < 0) {
34d3d284 47 if (error_sleep < 60)
48 error_sleep *= 2;
49
50 printf("failed\n");
b973e875 51 continue;
34d3d284 52 } else {
53 printf("succeeded\n");
54 error_sleep = 0;
b973e875 55 }
5c2e3e44 56 }
34d3d284 57
58 if ((recvd = recv(in, buffer, CHUNKSIZE, 0)) < 1) {
59 error_sleep = 1;
60 continue;
61 }
5c2e3e44 62 written = 0;
63 do {
4710a9f8 64 if ((bytes = write(out, buffer, recvd-written)) < 0) {
5c2e3e44 65 perror("write");
66 exit(EXIT_FAILURE);
67 }
4710a9f8 68 written += bytes;
69 } while(written < recvd);
6ac47f90 70
4710a9f8 71 if (!(++count % GTOD_INTERVAL))
6ac47f90 72 gettimeofday(&curr, NULL);
5c2e3e44 73 } while (curr.tv_sec < start.tv_sec+duration);
74
75 close(out);
76 close(in);
77 shutdown(in, SHUT_RDWR);
78}
79
80int main(int argc, char **argv)
81{
82 int duration;
83 char *url;
84 char *outfile;
85 int(*open_fn)(char *);
86
87 if (argc == 4) {
88 url = argv[1];
6a3dc096 89 duration = atoi(argv[2])*60;
5c2e3e44 90 outfile = argv[3];
91 } else {
460e6d22 92 fprintf(stderr,"Syntax: %s URL duration_in_minutes outfile\n", argv[0]);
5c2e3e44 93 exit(EXIT_FAILURE);
94 }
95
96 if (is_http(url)) {
97 open_fn = &open_http;
98 } else if (is_mcast(url)) {
99 open_fn = &open_mcast;
100 } else {
101 printf("URL %s not supported!\n", url);
102 exit(EXIT_FAILURE);
103 }
104
105 record(open_fn, url, outfile, duration);
106
107 return EXIT_SUCCESS;
108}
Impressum, Datenschutz