Beispiel #1
0
int initSoundDecoder(int buf_len,int _time_print_stats) 
{
	sound_channels=SOUND_CHANNELS_STEREO;
	channels = sound_channels == SOUND_CHANNELS_MONO ? 1 : 2;
	time_print_stats=_time_print_stats;
	tprev=time(NULL); // for decoder statistics
    tprev_ppm=time(NULL); 
    buffer = (short *) hmalloc(channels*sizeof(short)*buf_len);
    rx_a = init_receiver('A', 2, 0);
    rx_b = init_receiver('B', 2, 1);
    return 1;
}
int main(int argc, char **argv) {
	char option;

	printf("RECEIVER alive: parsing options! (argc = %d\n",argc);

	while((option = getopt(argc, argv, option_string)) != -1) {
		switch(option) {
		case 'f':
			strncpy(ctrl2rcvr_fname, optarg, MAX_FILE_NAME_LEN);
			break;
		default:
			printf("invalid option %c\n",option);
			usage(argv);
			break;
		}
	}

	if(strlen(ctrl2rcvr_fname) == 0) {
		usage(argv);
	}

	printf("Receiver options ok... initializing\n");

	int sockedfd = init_receiver();

	receive_msgs(sockedfd);

	return 0;
}
Beispiel #3
0
bool proxy_instance::init(int addr_family, int version, int upstream_index, int upstream_vif, int downstream_index, int downstram_vif, bool single_instance){
    HC_LOG_TRACE("");

    m_is_single_instance = single_instance;
    m_addr_family =  addr_family;
    m_version = version;

    m_upstream = upstream_index;
    m_table_number = upstream_index;
    m_vif_map.insert(vif_pair(upstream_index,upstream_vif));

    m_state_table.insert(state_tabel_pair(downstream_index, g_state_map()));
    m_vif_map.insert(vif_pair(downstream_index, downstram_vif));

    if(!init_mrt_socket()) return false;

    m_check_source.init(m_addr_family, &m_mrt_sock);

    if(!init_receiver()) return false;

    if(!init_sender()) return false;

    m_routing.init(m_addr_family,m_version, &m_mrt_sock, m_is_single_instance, m_table_number);

    m_timing = timing::getInstance();

    return true;
}
/*!
 @brief Program entry point
 */
int main (void) {
	struct MagnetInit magnetInit;
	struct ServoInit boomServoInit, crowdServoInit, swingServoInit;
	struct RobotInit robotInit;
	
	magnetInit.periph = RCC_AHB1Periph_GPIOD;
	magnetInit.GPIOx = GPIOD;
	magnetInit.pin = GPIO_Pin_15;
	
	boomServoInit.CCR = 1;
	boomServoInit.maxPosition = BOOM_ANGLE_MAX;
	boomServoInit.minPosition = BOOM_ANGLE_MIN;
	
	crowdServoInit.CCR = 2;
	crowdServoInit.maxPosition = CROWD_ANGLE_MAX;
	crowdServoInit.minPosition = CROWD_ANGLE_MIN;
	
	swingServoInit.CCR = 3;
	swingServoInit.maxPosition = SWING_ANGLE_MAX;
	swingServoInit.minPosition = SWING_ANGLE_MIN;
	
	robotInit.boomServo = &boomServo;
	robotInit.crowdServo = &crowdServo;
	robotInit.swingServo = &swingServo;
	
	osThreadId tid_armThread;
	osThreadId tid_ledThread;

	init_TIM4(1 / SERVO_DUTY_CYCLE_STEP, SERVO_FREQUENCY);
	init_LEDS_PWM();
	init_LEDS();
	
	init_servo(&boomServo, &boomServoInit);
	init_servo(&crowdServo, &crowdServoInit);
	init_servo(&swingServo, &swingServoInit);
	init_robot(&robot, &robotInit);
	init_magnet(&magnet, &magnetInit);
	init_receiver(&receiver);
	
	tid_armThread = osThreadCreate(osThread(armThread), NULL);
	tid_ledThread = osThreadCreate(osThread(ledThread), NULL);
	
	osDelay(osWaitForever);
}
Beispiel #5
0
int main(int argc, const char * argv[]) {
    
    FILE *file;
    long file_size = -1;
    char *file_path, *file_name;
    struct stat file_stat;
    unsigned char required_acks = FSCP_DEFAULT_NUMBER_OF_ACKS;
    
    uchar_t  *packet;
    uint16_t recvfrom_addr;
    struct layer2 *l2;
    struct layer3 *l3;
    struct layer4_udp *l4;
    int i;
    char *dup, *token;
    uint8_t port;
    struct interface output_interface;
    
    size_t bandwidth = ~0;
    
    if (argc <= 1) {
        print_usage();
        exit(1);
    }
    
    // Increase the priority of the process (max priority is -20, min is 19)
    if (setpriority(PRIO_PROCESS, 0, -15) < 0) {
        fprintf(stderr, "** It is recommend to run as a superuser! **\n");
    }
    
    // Initializing packet and its header
    packet = (uchar_t *) malloc(MTU);
    memset(packet, 0, MTU);
    l2 = (struct layer2 *) packet;
    l3 = (struct layer3 *) (packet + sizeof(struct layer2));
    l4 = (struct layer4_udp *) (packet + sizeof(struct layer2) + sizeof(struct layer3));
    l3->type = TYPE_UDP;

    if (strcmp("-r", argv[1]) == 0) {
        
        //Begin receiving the file
        if (argc >= 11) {
            
            if (strcmp("-src", argv[2]) == 0) {
                l2->original_source_addr = htons((uint16_t) atoi(argv[3]));
            }
            else {
                print_usage();
                exit(1);
            }
            
            if (strcmp("-from", argv[4]) == 0) {
                recvfrom_addr = (uint16_t) atoi(argv[5]);
            }
            else {
                print_usage();
                exit(1);
            }
            
            if (strcmp("-path", argv[6]) == 0) {
                
                i = 0;
                dup = strdup(argv[7]);
                while ((token = strtok(dup, ",")) != NULL) {
                    
                    l3->source_routing[i] = atoi(token);
                    
                    i++;
                    dup = NULL;
                    
                    if (i > MAX_HOPS-1) break;
                }
                
                free(dup);
            }
            else {
                print_usage();
                exit(1);
            }
            
            if (strcmp("-port", argv[8]) == 0) {
                port = (uint8_t) atoi(argv[9]);
                l4->sport = port;
                l4->dport = port;
                l4->len = htons(FSCP_UDP_ID_BYTES);
            }
            else {
                print_usage();
                exit(1);
            }
            
            if (strcmp("-dev", argv[10]) == 0) {
                strcpy(output_interface.interface_name, argv[11]);
                fill_interface_info(&output_interface);
            }
            else {
                print_usage();
                exit(1);
            }
            
            if ((argc >= 13) && (strcmp("-f", argv[12]) == 0)) {
                if (argc >= 14) {
                    file_name = (char *) malloc(sizeof(char) * (strlen(argv[13]) + 1));
                    strcpy(file_name, argv[13]);
                }
                else {
                    print_usage();
                    exit(1);
                }
            }
            else {
                file_name = strdup("");
            }

            init_receiver(packet, recvfrom_addr, port, &output_interface, file_name);
            
        }
        else {
            print_usage();
            exit(1);
        }
        
    }
    else if (strcmp("-s", argv[1]) == 0) {
        if (argc >= 14) {

            if (strcmp("-src", argv[2]) == 0) {
                l2->original_source_addr = htons((uint16_t) atoi(argv[3]));
            }
            else {
                print_usage();
                exit(1);
            }
            
            if (strcmp("-dest", argv[4]) == 0) {
                recvfrom_addr = (uint16_t) atoi(argv[5]);
            }
            else {
                print_usage();
                exit(1);
            }

            if (strcmp("-path", argv[6]) == 0) {
                
                i = 0;
                dup = strdup(argv[7]);
                while ((token = strtok(dup, ",")) != NULL) {
                    
                    l3->source_routing[i] = atoi(token);
                    
                    i++;
                    dup = NULL;
                    
                    if (i > MAX_HOPS-1) break;
                }
                
                free(dup);
            }
            else {
                print_usage();
                exit(1);
            }
            
            if (strcmp("-port", argv[8]) == 0) {
                port = (uint8_t) atoi(argv[9]);
                l4->sport = port;
                l4->dport = port;
            }
            else {
                print_usage();
                exit(1);
            }
            
            if (strcmp("-dev", argv[10]) == 0) {
                strcpy(output_interface.interface_name, argv[11]);
                fill_interface_info(&output_interface);
            }
            else {
                print_usage();
                exit(1);
            }
            
            if (strcmp("-f", argv[12]) == 0) {
                file = fopen(argv[13], "r");
                if(!file) {
                    fprintf(stderr, "Error: cannot read the file %s\n", argv[13]);
                    exit(1);
                }
                
                stat(argv[13], &file_stat);
                file_size = file_stat.st_size;
                file_path = strdup(argv[13]);
                file_name = strdup(basename(file_path));
                
            }
            else {
                print_usage();
                exit(1);
            }
            
            if (argc >= 15) {
                if ((strcmp("-ack", argv[14]) == 0) && (argc >= 16)) {
                    required_acks = atoi(argv[15]);
                    if (required_acks == 0) {
                        required_acks = FSCP_DEFAULT_NUMBER_OF_ACKS;
                    }
                }
                #ifdef _THROTTLING_ENABLED
                else if ((strcmp("-bw", argv[14]) == 0) && (argc >= 16)) {
                    bandwidth = atoi(argv[15]);
                    bandwidth *= 125 * 1000;
                }
                #endif
                else {
                    print_usage();
                    exit(1);
                }
            }
            
            #ifdef _THROTTLING_ENABLED
            if (argc >= 17) {
                if ((strcmp("-bw", argv[16]) == 0) && (argc >= 18)) {
                    bandwidth = atoi(argv[17]);
                    bandwidth *= 125 * 1000;
                }
                else {
                    print_usage();
                    exit(1);
                }
            }
            #endif

            init_sender(packet, recvfrom_addr, port, port, &output_interface, file, file_size, file_name, required_acks, bandwidth);
            
        }
        else {
            print_usage();
            exit(1);
        }
        
    }
    else {
        print_usage();
        exit(1);
    }
    
    return 0;
}
Beispiel #6
0
int main(int argc, char *argv[])
{
	int err;
	done = 0;
	FILE *sound_in_fd = NULL;
	FILE *sound_out_fd = NULL;
	int channels;
	short *buffer = NULL;
	int buffer_l;
	int buffer_read;
	struct serial_state_t *serial = NULL;
	struct ipc_state_t *ipc = NULL;
	struct receiver *rx_a = NULL;
	struct receiver *rx_b = NULL;
	
	/* open syslog, write an initial log message and read configuration */
	open_log(logname, 0);
	hlog(LOG_NOTICE, "Starting up...");
	if (read_config()) {
		hlog(LOG_CRIT, "Initial configuration failed.");
		exit(1);
	}
	
	/* initialize position cache for timed JSON AIS transmission */
	if (uplink_config) {
		hlog(LOG_DEBUG, "Initializing cache...");
		if (cache_init())
			exit(1);
		hlog(LOG_DEBUG, "Initializing jsonout...");
		if (jsonout_init())
			exit(1);
	}
	
	/* initialize the AIS decoders */
	if (sound_channels != SOUND_CHANNELS_MONO) {
		hlog(LOG_DEBUG, "Initializing demodulator A");
		rx_a = init_receiver('A', 2, 0,ipc);
		hlog(LOG_DEBUG, "Initializing demodulator B");
		rx_b = init_receiver('B', 2, 1,ipc);
		channels = 2;
	} else {
		hlog(LOG_DEBUG, "Initializing demodulator A");
		rx_a = init_receiver('A', 1, 0,ipc);
		channels = 1;
	}


	printf("HEJ!");

		hlog(LOG_NOTICE, "Reading audio from blob.");
		buffer_l = 1024;
		int extra = buffer_l % 5;
		buffer_l -= extra;
		buffer = (short *) hmalloc(buffer_l * sizeof(short) * channels);
	
	hlog(LOG_NOTICE, "Started");
	
	int dataoffset = 0;

#define AAA 0

#if AAA
	sound_in_fd = fopen("xaa", "rb");
#endif

	while (!done) {
		printf(".");
#if AAA
		buffer_read = fread(buffer, channels * sizeof(short), buffer_l, sound_in_fd);
			if (buffer_read <= 0)
				done = 1;
#else
		memcpy(buffer, staticSoundData + dataoffset, buffer_l * channels * sizeof(short));
		dataoffset += buffer_l * channels;
		if (dataoffset >= sizeof(staticSoundData) / sizeof(short)) {
			done = 1;
		}
		buffer_read = buffer_l;

#endif

# if 0
		printf("buffer_read: %d\n", buffer_read);
		int xx;
		for (xx = 0; xx < buffer_l * channels; xx++)
			printf("%x ", buffer[xx]);
		
		done = 1;
#endif

		if (sound_channels == SOUND_CHANNELS_MONO) {
			receiver_run(rx_a, buffer, buffer_read);
		}
		if (sound_channels == SOUND_CHANNELS_BOTH
		    || sound_channels == SOUND_CHANNELS_RIGHT) {
			/* ch a/0/right */
			receiver_run(rx_a, buffer, buffer_read);
		}
		if (sound_channels == SOUND_CHANNELS_BOTH
		    || sound_channels == SOUND_CHANNELS_LEFT) {	
			/* ch b/1/left */
			receiver_run(rx_b, buffer, buffer_read);
		}
	}
	
	hlog(LOG_NOTICE, "Closing down...");
	if (sound_in_fd) {
		fclose(sound_in_fd);
	}
	
	hfree(buffer);

	if (uplink_config)
		jsonout_deinit();
	
	if (cache_positions)
		cache_deinit();
	
	if (rx_a) {
		struct demod_state_t *d = rx_a->decoder;
		hlog(LOG_INFO,
			"A: Received correctly: %d packets, wrong CRC: %d packets, wrong size: %d packets",
			d->receivedframes, d->lostframes,
			d->lostframes2);
	}
	
	if (rx_b) {
		struct demod_state_t *d = rx_b->decoder;
		hlog(LOG_INFO,
			"B: Received correctly: %d packets, wrong CRC: %d packets, wrong size: %d packets",
			d->receivedframes, d->lostframes,
			d->lostframes2);
	}
	
	free_receiver(rx_a);
	free_receiver(rx_b);
	
	free_config();
	close_log(0);
	
	return 0;
}
int main() {

    fprintf(stderr, "Starting audio_receiver test...\n");

    // Open files to write audio
    if ((F_audio1 = fopen(name_audio1, "wb")) == NULL) {
        perror(name_audio1);
        exit(errno);
    }
    if ((F_audio2 = fopen(name_audio2, "wb")) == NULL) {
        perror(name_audio2);
        exit(errno);
    }

    // General pourpouse variables.
    time_t start, stop;
    audio_frame2 *audio_frame;

    // Receiver configuration
    stream_list_t *video_stream_list = init_stream_list(); // Not used
    stream_list_t *audio_stream_list = init_stream_list();
    receiver_t *receiver = init_receiver(video_stream_list, audio_stream_list, 5004, 5006);

    // First stream and participant configuration
    participant_data_t *p1 = init_participant(1, INPUT, NULL, 0);
    stream_data_t *stream1 = init_stream(AUDIO, INPUT, rand(), I_AWAIT, 25.0, "Stream1");
    add_participant_stream(stream1, p1);
    add_stream(receiver->audio_stream_list, stream1);
    fprintf(stderr, " ·Stream1 configuration: 1 bps, 32000Hz, 1 channel, mulaw\n");
    ap_config(stream1->audio, 1, 32000, 1, AC_MULAW);
    ap_worker_start(stream1->audio);

    // Second stream and participant configuration
    participant_data_t *p2 = init_participant(2, INPUT, NULL, 0);
    stream_data_t *stream2 = init_stream(AUDIO, INPUT, rand(), I_AWAIT, 25.0, "Stream2");
    add_participant_stream(stream2, p2);
    add_stream(receiver->audio_stream_list, stream2);
    fprintf(stderr, " ·Stream2 configuration: 1 bps, 8000Hz, 1 channel, mulaw\n");
    ap_config(stream2->audio, 1, 8000, 1, AC_MULAW);
    ap_worker_start(stream2->audio);

    if (start_receiver(receiver)) {
        fprintf(stderr, " ·Receiver started!\n");

#ifdef STREAM1
        // STREAM1 recording block
        fprintf(stderr, "  ·Waiting for audio_frame2 data\n");
        while (stream1->audio->decoded_cq->level == CIRCULAR_QUEUE_EMPTY) {
#ifdef QUEUE_PRINT
            print_cq_status(stream1->audio->decoded_cq, "wait stream1");
#endif
        }
#ifdef QUEUE_PRINT
        print_cq_status(stream1->audio->decoded_cq, "continue stream1");
#endif

        fprintf(stderr, "   ·Copying to file... ");
        start = time(NULL);
        stop = start + RECORD_TIME;
        while (time(NULL) < stop) { // RECORD_TIME seconds loop
            audio_frame = cq_get_front(stream1->audio->decoded_cq);
            if (audio_frame != NULL) {
                fwrite(audio_frame->data[0], audio_frame->data_len[0], 1, F_audio1);
                cq_remove_bag(stream1->audio->decoded_cq);
            }
        }
        fprintf(stderr, "Done!\n");
#endif //STREAM1

#ifdef STREAM2
        // STREAM2 recording block
        fprintf(stderr, "  ·Waiting for audio_frame2 data\n");
        while (stream2->audio->decoded_cq->level == CIRCULAR_QUEUE_EMPTY) {
#ifdef QUEUE_PRINT
            print_cq_status(stream2->audio->decoded_cq, "wait stream2");
#endif
        }
#ifdef QUEUE_PRINT
        print_cq_status(stream2->audio->decoded_cq, "continue stream2");
#endif
        fprintf(stderr, "   ·Copying to file... ");
        start = time(NULL);
        stop = start + RECORD_TIME;
        while (time(NULL) < stop) { // RECORD_TIME seconds loop
            audio_frame = cq_get_front(stream2->audio->decoded_cq);
            if (audio_frame != NULL) {
                fwrite(audio_frame->data[0], audio_frame->data_len[0], 1, F_audio2);
                cq_remove_bag(stream2->audio->decoded_cq);
            }
        }
        fprintf(stderr, "Done!\n");
#endif //STREAM2

        // Finish and destroy objects
        stop_receiver(receiver);
        destroy_receiver(receiver);
        fprintf(stderr, " ·Receiver stopped\n");
        destroy_stream_list(video_stream_list);
        destroy_stream_list(audio_stream_list);
    }

    if (fclose(F_audio1) != 0) {
        perror(name_audio1);
        exit(-1);
    }
    if (fclose(F_audio2) != 0) {
        perror(name_audio2);
        exit(-1);
    }
    fprintf(stderr, "Finished\n");
}
int main()
{
    fprintf(stderr,
            "Starting audio_rec_trans test (max %i seconds)\n",
            LIVE_TIME);
    fprintf(stderr,
            "Issue kill -10 %i to dinamically add a couple of streams.\n",
            getpid()); 

    // Attach the handlers to the signals and prepare block stuff.
    signal(SIGINT, finish_handler);
    signal(SIGALRM, finish_handler);
    signal(SIGUSR1, action_handler);

    // Start live time alarm
    alarm(LIVE_TIME);

    // Receiver startup
    fprintf(stderr,
            " ·Configuring receiver (listen at %i)\n",
            RECEIVER_AUDIO_PORT);
    receiver = init_receiver(init_stream_list(),
            init_stream_list(),
            RECEIVER_VIDEO_PORT,
            RECEIVER_AUDIO_PORT);
    start_receiver(receiver);
    add_receiver_entity();

    // Transmitter startup
    fprintf(stderr, " ·Configuring transmitter\n");
    transmitter = init_transmitter(init_stream_list(),
            init_stream_list(),
            25.0);
    start_transmitter(transmitter);
    add_transmitter_entity(TRANSMITTER_IP_1, TRANSMITTER_PORT_1);

    // Temporal variables and initializations
    stream_data_t *in_stream_couple1,
                  *out_stream_couple1,
                  *in_stream_couple2,
                  *out_stream_couple2;
    bool cross = false;
    bool verbose = true;
    time_t lap_time = time(NULL) + SWITCH_TIME;

    // Main loop
    fprintf(stderr,
            " ·Forwarding audio and switching the streams every %i seconds...\n",
            SWITCH_TIME);
    while(!stop) {

        // Lap time control
        if (time(NULL) > lap_time) {
            lap_time = time(NULL) + SWITCH_TIME;
            cross = !cross;
            verbose = true;
            fprintf(stderr, "Done!\n");
        }

        // Cross sending control
        if (!cross) {
            in_stream_couple1 = receiver->audio_stream_list->first;
            out_stream_couple1 = transmitter->audio_stream_list->first;
            in_stream_couple2 = in_stream_couple1->next;
            out_stream_couple2 = out_stream_couple1->next;
        }
        else {
            in_stream_couple1 = receiver->audio_stream_list->first;
            out_stream_couple1 = transmitter->audio_stream_list->last;
            in_stream_couple2 = in_stream_couple1->next;
            out_stream_couple2 = out_stream_couple1->prev;
        }

        // Forward audio from receiver to transmitter
        if (in_stream_couple2 == NULL || out_stream_couple2 == NULL) {
            // One couple case (first to first).
            if (verbose) {
                sprintf(msg, "  ·Sending %s -> %s ",
                        in_stream_couple1->stream_name,
                        out_stream_couple1->stream_name);
            }
            audio_frame_forward(in_stream_couple1, out_stream_couple1);
        }
        else {
            // Two couples case (first to first, next to next).
            if (verbose) {
                sprintf(msg, "  ·Sending %s -> %s and %s -> %s ",
                        in_stream_couple1->stream_name,
                        out_stream_couple1->stream_name,
                        in_stream_couple2->stream_name,
                        out_stream_couple2->stream_name);
            }
            audio_frame_forward(in_stream_couple1, out_stream_couple1);
            audio_frame_forward(in_stream_couple2, out_stream_couple2);
        }

        // Print information message
        if (verbose) {
            fprintf(stderr, "%s", msg);
            verbose = false;
        }

        //Try to not send all the audio suddently.
        usleep(SEND_TIME);
    }
    fprintf(stderr, "Done!\n");

    // Finish and destroy receiver objects
    stop_receiver(receiver);
    destroy_stream_list(receiver->video_stream_list);
    destroy_stream_list(receiver->audio_stream_list);
    destroy_receiver(receiver);
    fprintf(stderr, " ·Receiver stopped\n");

    // Finish and destroy transmitter objects
    stop_transmitter(transmitter);
    destroy_stream_list(transmitter->video_stream_list);
    destroy_stream_list(transmitter->audio_stream_list);
    destroy_transmitter(transmitter);
    fprintf(stderr, " ·Transmitter stopped\n");

    fprintf(stderr, "Finished\n");
}
Beispiel #9
0
int main(int argc, char *argv[])
{
	int err;
	done = 0;
	snd_pcm_t *handle;
	FILE *sound_in_fd = NULL;
	FILE *sound_out_fd = NULL;
	int channels;
	short *buffer = NULL;
	int buffer_l;
	int buffer_read;
	struct serial_state_t *serial = NULL;
	struct ipc_state_t *ipc = NULL;
	struct receiver *rx_a = NULL;
	struct receiver *rx_b = NULL;
#ifdef HAVE_PULSEAUDIO
	pa_simple *pa_dev = NULL;
#endif
	
	/* command line */
	parse_cmdline(argc, argv);
	
	/* open syslog, write an initial log message and read configuration */
	open_log(logname, 0);
	hlog(LOG_NOTICE, "Starting up...");
	if (read_config()) {
		hlog(LOG_CRIT, "Initial configuration failed.");
		exit(1);
	}
	
	/* fork a daemon */
	if (fork_a_daemon) {
		int i = fork();
		if (i < 0) {
			hlog(LOG_CRIT, "Fork to background failed: %s", strerror(errno));
			fprintf(stderr, "Fork to background failed: %s\n", strerror(errno));
			exit(1);
		} else if (i == 0) {
			/* child */
			/* write pid file, now that we have our final pid... might fail, which is critical */
			hlog(LOG_DEBUG, "Writing pid...");
			if (!writepid(pidfile))
				exit(1);
		} else {
			/* parent, quitting */
			hlog(LOG_DEBUG, "Forked daemon process %d, parent quitting", i);
			exit(0);
		}
	}
	
	
	signal(SIGINT, closedown);
	signal(SIGPIPE, brokenconnection);
	
	/* initialize position cache for timed JSON AIS transmission */
	if (uplink_config) {
		hlog(LOG_DEBUG, "Initializing cache...");
		if (cache_init())
			exit(1);
		hlog(LOG_DEBUG, "Initializing jsonout...");
		if (jsonout_init())
			exit(1);
	}
	
	/* initialize serial port for NMEA output */
	if (serial_port)
		serial = serial_init();

	/* initialize Unix domain socket for communication with gnuaisgui */
	ipc = gnuais_ipc_init();
	if(ipc == 0){
		hlog(LOG_ERR, "Could not open Unix Domain Socket");
	}
	
	/* initialize the AIS decoders */
	if (sound_channels != SOUND_CHANNELS_MONO) {
		hlog(LOG_DEBUG, "Initializing demodulator A");
		rx_a = init_receiver('A', 2, 0,serial,ipc);
		hlog(LOG_DEBUG, "Initializing demodulator B");
		rx_b = init_receiver('B', 2, 1,serial,ipc);
		channels = 2;
	} else {
		hlog(LOG_DEBUG, "Initializing demodulator A");
		rx_a = init_receiver('A', 1, 0,serial,ipc);
		channels = 1;
	}
#ifdef HAVE_PULSEAUDIO
	if(sound_device != NULL && ((strcmp("pulse",sound_device) == 0) || (strcmp("pulseaudio",sound_device) == 0))){
		if((pa_dev = pulseaudio_initialize()) == NULL){
			hlog(LOG_CRIT, "Error opening pulseaudio device");
			return -1;
		}
		buffer_l = 1024;
		int extra = buffer_l % 5;
		buffer_l -= extra;
		buffer = (short *) hmalloc(buffer_l * sizeof(short) * channels);
	}
	else if (sound_device){
#else
	if (sound_device){
#endif

		if ((err = snd_pcm_open(&handle, sound_device, SND_PCM_STREAM_CAPTURE, 0)) < 0) {
			hlog(LOG_CRIT, "Error opening sound device (%s)", sound_device);
			return -1;
		}
		
		if (input_initialize(handle, &buffer, &buffer_l) < 0)
			return -1;
	} else if (sound_in_file) {
		if ((sound_in_fd = fopen(sound_in_file, "r")) == NULL) {
			hlog(LOG_CRIT, "Could not open sound file %s: %s", sound_in_file, strerror(errno));
			return -1;
		}
		hlog(LOG_NOTICE, "Reading audio from file: %s", sound_in_file);
		buffer_l = 1024;
		int extra = buffer_l % 5;
		buffer_l -= extra;
		buffer = (short *) hmalloc(buffer_l * sizeof(short) * channels);
	} else {
		hlog(LOG_CRIT, "Neither sound device or sound file configured.");
		return -1;
	}
	
	if (sound_out_file) {
		if ((sound_out_fd = fopen(sound_out_file, "w")) == NULL) {
			hlog(LOG_CRIT, "Could not open sound output file %s: %s", sound_out_file, strerror(errno));
			return -1;
		}
		hlog(LOG_NOTICE, "Recording audio to file: %s", sound_out_file);
	}
	
#ifdef HAVE_MYSQL
	if (mysql_db) {
		hlog(LOG_DEBUG, "Saving to MySQL database \"%s\"", mysql_db);
		if (!(my = myout_init()))
			return -1;
			
		if (mysql_keepsmall)
			hlog(LOG_DEBUG, "Updating database rows only.");
		else
			hlog(LOG_DEBUG, "Inserting data to database.");
			
		if (mysql_oldlimit)
			hlog(LOG_DEBUG, "Deleting data older than %d seconds", mysql_oldlimit);
	}
#endif
	
	hlog(LOG_NOTICE, "Started");
	
	while (!done) {
		if (sound_in_fd) {
			buffer_read = fread(buffer, channels * sizeof(short), buffer_l, sound_in_fd);
			if (buffer_read <= 0)
				done = 1;
		} 
#ifdef HAVE_PULSEAUDIO
		else if (pa_dev){
			buffer_read = pulseaudio_read(pa_dev, buffer, buffer_l);
		}
#endif
		else {
			buffer_read = input_read(handle, buffer, buffer_l);
			//printf("read %d\n", buffer_read);
		}
		if (buffer_read <= 0)
			continue;
		
		if (sound_out_fd) {
			fwrite(buffer, channels * sizeof(short), buffer_read, sound_out_fd);
		}
		
		if (sound_channels == SOUND_CHANNELS_MONO) {
			receiver_run(rx_a, buffer, buffer_read);
		}
		if (sound_channels == SOUND_CHANNELS_BOTH
		    || sound_channels == SOUND_CHANNELS_RIGHT) {
			/* ch a/0/right */
			receiver_run(rx_a, buffer, buffer_read);
		}
		if (sound_channels == SOUND_CHANNELS_BOTH
		    || sound_channels == SOUND_CHANNELS_LEFT) {	
			/* ch b/1/left */
			receiver_run(rx_b, buffer, buffer_read);
		}
	}
	
	hlog(LOG_NOTICE, "Closing down...");
	if (sound_in_fd) {
		fclose(sound_in_fd);
	}
#ifdef HAVE_PULSEAUDIO
	else if (pa_dev) {
		pulseaudio_cleanup(pa_dev);
	}
#endif
	else {
		input_cleanup(handle);
		handle = NULL;
	}

	
	if (sound_out_fd)
		fclose(sound_out_fd);
	
	hfree(buffer);

	gnuais_ipc_deinit(ipc);
	
	if (serial)
		serial_close(serial);
	
	if (uplink_config)
		jsonout_deinit();
	
	if (cache_positions)
		cache_deinit();
	
	if (rx_a) {
		struct demod_state_t *d = rx_a->decoder;
		hlog(LOG_INFO,
			"A: Received correctly: %d packets, wrong CRC: %d packets, wrong size: %d packets",
			d->receivedframes, d->lostframes,
			d->lostframes2);
	}
	
	if (rx_b) {
		struct demod_state_t *d = rx_b->decoder;
		hlog(LOG_INFO,
			"B: Received correctly: %d packets, wrong CRC: %d packets, wrong size: %d packets",
			d->receivedframes, d->lostframes,
			d->lostframes2);
	}
	
	free_receiver(rx_a);
	free_receiver(rx_b);
	
	free_config();
	close_log(0);
	
	return 0;
}