diff --git a/common/JackNetOneDriver.cpp b/common/JackNetOneDriver.cpp new file mode 100644 index 00000000..b9de94de --- /dev/null +++ b/common/JackNetOneDriver.cpp @@ -0,0 +1,1117 @@ +/* +Copyright (C) 2001 Paul Davis +Copyright (C) 2008 Romain Moret at Grame + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 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 General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. +*/ + +#define HAVE_CELT 1 + +#ifdef WIN32 +#include +#endif + +#include "JackNetOneDriver.h" +#include "JackEngineControl.h" +#include "JackGraphManager.h" +#include "JackWaitThreadedDriver.h" +#include "JackException.h" +#include "driver_interface.h" + +#include "netjack.h" +#include "netjack_packet.h" + +#if HAVE_SAMPLERATE +#include "samplerate.h" +#endif + +#if HAVE_CELT +#include "celt/celt.h" +#endif + +#define MIN(x,y) ((x)<(y) ? (x) : (y)) + +using namespace std; + +namespace Jack +{ + JackNetOneDriver::JackNetOneDriver ( const char* name, const char* alias, JackLockedEngine* engine, JackSynchro* table, + int port, int mtu, int capture_ports, int playback_ports, int midi_input_ports, int midi_output_ports, + int sample_rate, int period_size, int resample_factor, + char* net_name, uint transport_sync, int bitdepth, int use_autoconfig, + int latency, int redundancy, int dont_htonl_floats, int always_deadline ) + : JackAudioDriver ( name, alias, engine, table ) + { + jack_log ( "JackNetOneDriver::JackNetOneDriver port %d", port ); + +#ifdef WIN32 + WSADATA wsa; + int rc = WSAStartup(MAKEWORD(2,0),&wsa); +#endif + + netjack_init( & (this->netj), + NULL, // client + name, + capture_ports, + playback_ports, + midi_input_ports, + midi_output_ports, + sample_rate, + period_size, + port, + transport_sync, + resample_factor, + 0, + bitdepth, + use_autoconfig, + latency, + redundancy, + dont_htonl_floats, + always_deadline); + } + + JackNetOneDriver::~JackNetOneDriver() + { + // No destructor yet. + } + +//open, close, attach and detach------------------------------------------------------ + int JackNetOneDriver::Open ( jack_nframes_t buffer_size, jack_nframes_t samplerate, bool capturing, bool playing, + int inchannels, int outchannels, bool monitor, + const char* capture_driver_name, const char* playback_driver_name, + jack_nframes_t capture_latency, jack_nframes_t playback_latency ) + { + if ( JackAudioDriver::Open ( buffer_size, + samplerate, + capturing, + playing, + inchannels, + outchannels, + monitor, + capture_driver_name, + playback_driver_name, + capture_latency, + playback_latency ) == 0 ) + { + fEngineControl->fPeriod = 0; + fEngineControl->fComputation = 500 * 1000; + fEngineControl->fConstraint = 500 * 1000; + return 0; + } + else + { + jack_error( "open fail\n" ); + return -1; + } + } + + int JackNetOneDriver::Close() + { + FreePorts(); + netjack_release( &netj ); + return JackDriver::Close(); + } + + int JackNetOneDriver::Attach() + { + return 0; + } + + int JackNetOneDriver::Detach() + { + return 0; + } + + int JackNetOneDriver::AllocPorts() + { + jack_port_id_t port_id; + char buf[64]; + unsigned int chn; + int port_flags; + + + //if (netj.handle_transport_sync) + // jack_set_sync_callback(netj.client, (JackSyncCallback) net_driver_sync_cb, NULL); + + port_flags = JackPortIsOutput | JackPortIsPhysical | JackPortIsTerminal; + + for (chn = 0; chn < netj.capture_channels_audio; chn++) { + snprintf (buf, sizeof(buf) - 1, "system:capture_%u", chn + 1); + + if ( ( port_id = fGraphManager->AllocatePort ( fClientControl.fRefNum, buf, JACK_DEFAULT_AUDIO_TYPE, + static_cast ( port_flags ), fEngineControl->fBufferSize ) ) == NO_PORT ) + { + jack_error ( "driver: cannot register port for %s", buf ); + return -1; + } + //port = fGraphManager->GetPort ( port_id ); + + netj.capture_ports = + jack_slist_append (netj.capture_ports, (void *)(intptr_t)port_id); + + if( netj.bitdepth == 1000 ) { +#if HAVE_CELT + celt_int32_t lookahead; + // XXX: memory leak + CELTMode *celt_mode = celt_mode_create( netj.sample_rate, 1, netj.period_size, NULL ); + celt_mode_info( celt_mode, CELT_GET_LOOKAHEAD, &lookahead ); + netj.codec_latency = 2*lookahead; + + netj.capture_srcs = jack_slist_append(netj.capture_srcs, (void *)celt_decoder_create( celt_mode ) ); +#endif + } else { +#if HAVE_SAMPLERATE + netj.capture_srcs = jack_slist_append(netj.capture_srcs, (void *)src_new(SRC_LINEAR, 1, NULL)); +#endif + } + } + for (chn = netj.capture_channels_audio; chn < netj.capture_channels; chn++) { + snprintf (buf, sizeof(buf) - 1, "system:capture_%u", chn + 1); + + if ( ( port_id = fGraphManager->AllocatePort ( fClientControl.fRefNum, buf, JACK_DEFAULT_MIDI_TYPE, + static_cast ( port_flags ), fEngineControl->fBufferSize ) ) == NO_PORT ) + { + jack_error ( "driver: cannot register port for %s", buf ); + return -1; + } + //port = fGraphManager->GetPort ( port_id ); + + netj.capture_ports = + jack_slist_append (netj.capture_ports, (void *)(intptr_t)port_id); + } + + port_flags = JackPortIsInput | JackPortIsPhysical | JackPortIsTerminal; + + for (chn = 0; chn < netj.playback_channels_audio; chn++) { + snprintf (buf, sizeof(buf) - 1, "system:playback_%u", chn + 1); + + if ( ( port_id = fGraphManager->AllocatePort ( fClientControl.fRefNum, buf, JACK_DEFAULT_AUDIO_TYPE, + static_cast ( port_flags ), fEngineControl->fBufferSize ) ) == NO_PORT ) + { + jack_error ( "driver: cannot register port for %s", buf ); + return -1; + } + //port = fGraphManager->GetPort ( port_id ); + + netj.playback_ports = + jack_slist_append (netj.playback_ports, (void *)(intptr_t)port_id); + + if( netj.bitdepth == 1000 ) { +#if HAVE_CELT + // XXX: memory leak + CELTMode *celt_mode = celt_mode_create( netj.sample_rate, 1, netj.period_size, NULL ); + netj.playback_srcs = jack_slist_append(netj.playback_srcs, (void *)celt_encoder_create( celt_mode ) ); +#endif + } else { +#if HAVE_SAMPLERATE + netj.playback_srcs = jack_slist_append(netj.playback_srcs, (void *)src_new(SRC_LINEAR, 1, NULL)); +#endif + } + } + for (chn = netj.playback_channels_audio; chn < netj.playback_channels; chn++) { + snprintf (buf, sizeof(buf) - 1, "system:playback_%u", chn + 1); + + if ( ( port_id = fGraphManager->AllocatePort ( fClientControl.fRefNum, buf, JACK_DEFAULT_MIDI_TYPE, + static_cast ( port_flags ), fEngineControl->fBufferSize ) ) == NO_PORT ) + { + jack_error ( "driver: cannot register port for %s", buf ); + return -1; + } + //port = fGraphManager->GetPort ( port_id ); + + netj.playback_ports = + jack_slist_append (netj.playback_ports, (void *)(intptr_t)port_id); + } + return 0; + } + +//init and restart-------------------------------------------------------------------- + bool JackNetOneDriver::Initialize() + { + jack_log ( "JackNetOneDriver::Init()" ); + + if( global_packcache != NULL ) { + FreePorts(); + netjack_release( &netj ); + } + + //display some additional infos + jack_info ( "NetOne driver started" ); + if( netjack_startup( &netj ) ) { + return false; + } + + //register jack ports + if ( AllocPorts() != 0 ) + { + jack_error ( "Can't allocate ports." ); + return false; + } + + + //monitor + //driver parametering + JackAudioDriver::SetBufferSize ( netj.period_size ); + JackAudioDriver::SetSampleRate ( netj.sample_rate ); + + JackDriver::NotifyBufferSize ( netj.period_size ); + JackDriver::NotifySampleRate ( netj.sample_rate ); + + //transport engine parametering + fEngineControl->fTransport.SetNetworkSync ( true ); + return true; + } + + +//jack ports and buffers-------------------------------------------------------------- + +//driver processes-------------------------------------------------------------------- + int JackNetOneDriver::Read() + { + netjack_wait( &netj ); + + if( (netj.num_lost_packets * netj.period_size / netj.sample_rate) > 10 ) + throw JackNetException(); + + //netjack_read( &netj, netj.period_size ); + JackDriver::CycleTakeBeginTime(); + + jack_position_t local_trans_pos; + jack_transport_state_t local_trans_state; + + unsigned int *packet_buf, *packet_bufX; + + if( ! netj.packet_data_valid ) { + jack_log( "data not valid" ); + render_payload_to_jack_ports (netj.bitdepth, NULL, netj.net_period_down, netj.capture_ports, netj.capture_srcs, netj.period_size, netj.dont_htonl_floats ); + return 0; + } + packet_buf = netj.rx_buf; + + jacknet_packet_header *pkthdr = (jacknet_packet_header *)packet_buf; + + packet_bufX = packet_buf + sizeof(jacknet_packet_header) / sizeof(jack_default_audio_sample_t); + + netj.reply_port = pkthdr->reply_port; + netj.latency = pkthdr->latency; + + // Special handling for latency=0 + if( netj.latency == 0 ) + netj.resync_threshold = 0; + else + netj.resync_threshold = MIN( 15, pkthdr->latency-1 ); + + // check whether, we should handle the transport sync stuff, or leave trnasports untouched. + if (netj.handle_transport_sync) { +#if 1 + unsigned int compensated_tranport_pos = (pkthdr->transport_frame + (pkthdr->latency * netj.period_size) + netj.codec_latency); + + // read local transport info.... + //local_trans_state = jack_transport_query(netj.client, &local_trans_pos); + + local_trans_state = fEngineControl->fTransport.Query ( &local_trans_pos ); + + // Now check if we have to start or stop local transport to sync to remote... + switch (pkthdr->transport_state) { + case JackTransportStarting: + // the master transport is starting... so we set our reply to the sync_callback; + if (local_trans_state == JackTransportStopped) { + fEngineControl->fTransport.SetCommand ( TransportCommandStart ); + //jack_transport_start(netj.client); + //last_transport_state = JackTransportStopped; + netj.sync_state = 0; + jack_info("locally stopped... starting..."); + } + + if (local_trans_pos.frame != compensated_tranport_pos) + { + jack_position_t new_pos = local_trans_pos; + new_pos.frame = compensated_tranport_pos + 2*netj.period_size; + new_pos.valid = (jack_position_bits_t) 0; + + + fEngineControl->fTransport.RequestNewPos ( &new_pos ); + //jack_transport_locate(netj.client, compensated_tranport_pos); + //last_transport_state = JackTransportRolling; + netj.sync_state = 0; + jack_info("starting locate to %d", compensated_tranport_pos ); + } + break; + case JackTransportStopped: + netj.sync_state = 1; + if (local_trans_pos.frame != (pkthdr->transport_frame)) { + jack_position_t new_pos = local_trans_pos; + new_pos.frame = pkthdr->transport_frame; + new_pos.valid = (jack_position_bits_t)0; + fEngineControl->fTransport.RequestNewPos ( &new_pos ); + //jack_transport_locate(netj.client, (pkthdr->transport_frame)); + jack_info("transport is stopped locate to %d", pkthdr->transport_frame); + } + if (local_trans_state != JackTransportStopped) + //jack_transport_stop(netj.client); + fEngineControl->fTransport.SetCommand ( TransportCommandStop ); + break; + case JackTransportRolling: + netj.sync_state = 1; + // if(local_trans_pos.frame != (pkthdr->transport_frame + (pkthdr->latency) * netj.period_size)) { + // jack_transport_locate(netj.client, (pkthdr->transport_frame + (pkthdr->latency + 2) * netj.period_size)); + // jack_info("running locate to %d", pkthdr->transport_frame + (pkthdr->latency)*netj.period_size); + // } + if (local_trans_state != JackTransportRolling) + //jack_transport_start (netj.client); + fEngineControl->fTransport.SetState ( JackTransportRolling ); + + break; + + case JackTransportLooping: + break; + } +#endif + } + + render_payload_to_jack_ports (netj.bitdepth, packet_bufX, netj.net_period_down, netj.capture_ports, netj.capture_srcs, netj.period_size, netj.dont_htonl_floats ); + packet_cache_release_packet(global_packcache, netj.expected_framecnt ); + return 0; + } + + int JackNetOneDriver::Write() + { + int syncstate = netj.sync_state | ((fEngineControl->fTransport.GetState() == JackTransportNetStarting) ? 1 : 0 ); + //netjack_write( &netj, netj.period_size, 0 ); + uint32_t *packet_buf, *packet_bufX; + + int packet_size = get_sample_size(netj.bitdepth) * netj.playback_channels * netj.net_period_up + sizeof(jacknet_packet_header); + jacknet_packet_header *pkthdr; + + packet_buf = (uint32_t *) alloca(packet_size); + pkthdr = (jacknet_packet_header *)packet_buf; + + if( netj.running_free ) { + return 0; + } + + // offset packet_bufX by the packetheader. + packet_bufX = packet_buf + sizeof(jacknet_packet_header) / sizeof(jack_default_audio_sample_t); + + pkthdr->sync_state = syncstate;; + pkthdr->latency = netj.time_to_deadline; + //printf( "time to deadline = %d goodness=%d\n", (int)netj.time_to_deadline, netj.deadline_goodness ); + pkthdr->framecnt = netj.expected_framecnt; + + + render_jack_ports_to_payload(netj.bitdepth, netj.playback_ports, netj.playback_srcs, netj.period_size, packet_bufX, netj.net_period_up, netj.dont_htonl_floats ); + + packet_header_hton(pkthdr); + if (netj.srcaddress_valid) + { + unsigned int r; + +#ifdef __APPLE__ + static const int flag = 0; +#else + static const int flag = 0; +#endif + + if (netj.reply_port) + netj.syncsource_address.sin_port = htons(netj.reply_port); + + for( r=0; rdata; + node = jack_slist_remove_link( node, this_node ); + jack_slist_free_1( this_node ); + fGraphManager->ReleasePort( fClientControl.fRefNum, port_id ); + } + netj.capture_ports = NULL; + + node = netj.playback_ports; + while( node != NULL ) { + JSList *this_node = node; + jack_port_id_t port_id = (jack_port_id_t)(intptr_t) node->data; + node = jack_slist_remove_link( node, this_node ); + jack_slist_free_1( this_node ); + fGraphManager->ReleasePort( fClientControl.fRefNum, port_id ); + } + netj.playback_ports = NULL; + + if( netj.bitdepth == 1000 ) { +#if HAVE_CELT + node = netj.playback_srcs; + while( node != NULL ) { + JSList *this_node = node; + CELTEncoder *enc = (CELTEncoder *) node->data; + node = jack_slist_remove_link( node, this_node ); + jack_slist_free_1( this_node ); + celt_encoder_destroy( enc ); + } + netj.playback_srcs = NULL; + + node = netj.capture_srcs; + while( node != NULL ) { + JSList *this_node = node; + CELTDecoder *dec = (CELTDecoder *) node->data; + node = jack_slist_remove_link( node, this_node ); + jack_slist_free_1( this_node ); + celt_decoder_destroy( dec ); + } + netj.capture_srcs = NULL; +#endif + } else { +#if HAVE_SAMPLERATE + node = netj.playback_srcs; + while( node != NULL ) { + JSList *this_node = node; + SRC_STATE *state = (SRC_STATE *) node->data; + node = jack_slist_remove_link( node, this_node ); + jack_slist_free_1( this_node ); + src_delete( state ); + } + netj.playback_srcs = NULL; + + node = netj.capture_srcs; + while( node != NULL ) { + JSList *this_node = node; + SRC_STATE *state = (SRC_STATE *) node->data; + node = jack_slist_remove_link( node, this_node ); + jack_slist_free_1( this_node ); + src_delete( state ); + } + netj.capture_srcs = NULL; +#endif + } +} +//Render functions-------------------------------------------------------------------- + +// render functions for float +void +JackNetOneDriver::render_payload_to_jack_ports_float ( void *packet_payload, jack_nframes_t net_period_down, JSList *capture_ports, JSList *capture_srcs, jack_nframes_t nframes, int dont_htonl_floats) +{ + uint32_t chn = 0; + JSList *node = capture_ports; +#if HAVE_SAMPLERATE + JSList *src_node = capture_srcs; +#endif + + uint32_t *packet_bufX = (uint32_t *)packet_payload; + + if( !packet_payload ) + return; + + while (node != NULL) + { + unsigned int i; + int_float_t val; +#if HAVE_SAMPLERATE + SRC_DATA src; +#endif + + jack_port_id_t port_id = (jack_port_id_t)(intptr_t) node->data; + JackPort *port = fGraphManager->GetPort( port_id ); + + jack_default_audio_sample_t* buf = + (jack_default_audio_sample_t*)fGraphManager->GetBuffer(port_id, fEngineControl->fBufferSize); + + const char *porttype = port->GetType(); + + if (strncmp (porttype, JACK_DEFAULT_AUDIO_TYPE, jack_port_type_size()) == 0) + { +#if HAVE_SAMPLERATE + // audio port, resample if necessary + if (net_period_down != nframes) + { + SRC_STATE *src_state = (SRC_STATE *)src_node->data; + for (i = 0; i < net_period_down; i++) + { + packet_bufX[i] = ntohl (packet_bufX[i]); + } + + src.data_in = (float *) packet_bufX; + src.input_frames = net_period_down; + + src.data_out = buf; + src.output_frames = nframes; + + src.src_ratio = (float) nframes / (float) net_period_down; + src.end_of_input = 0; + + src_set_ratio (src_state, src.src_ratio); + src_process (src_state, &src); + src_node = jack_slist_next (src_node); + } + else +#endif + { + if( dont_htonl_floats ) + { + memcpy( buf, packet_bufX, net_period_down*sizeof(jack_default_audio_sample_t)); + } + else + { + for (i = 0; i < net_period_down; i++) + { + val.i = packet_bufX[i]; + val.i = ntohl (val.i); + buf[i] = val.f; + } + } + } + } + else if (strncmp (porttype, JACK_DEFAULT_MIDI_TYPE, jack_port_type_size()) == 0) + { + // midi port, decode midi events + // convert the data buffer to a standard format (uint32_t based) + unsigned int buffer_size_uint32 = net_period_down; + uint32_t * buffer_uint32 = (uint32_t*)packet_bufX; + decode_midi_buffer (buffer_uint32, buffer_size_uint32, buf); + } + packet_bufX = (packet_bufX + net_period_down); + node = jack_slist_next (node); + chn++; + } +} + +void +JackNetOneDriver::render_jack_ports_to_payload_float (JSList *playback_ports, JSList *playback_srcs, jack_nframes_t nframes, void *packet_payload, jack_nframes_t net_period_up, int dont_htonl_floats ) +{ + uint32_t chn = 0; + JSList *node = playback_ports; +#if HAVE_SAMPLERATE + JSList *src_node = playback_srcs; +#endif + + uint32_t *packet_bufX = (uint32_t *) packet_payload; + + while (node != NULL) + { +#if HAVE_SAMPLERATE + SRC_DATA src; +#endif + unsigned int i; + int_float_t val; + jack_port_id_t port_id = (jack_port_id_t)(intptr_t) node->data; + JackPort *port = fGraphManager->GetPort( port_id ); + + jack_default_audio_sample_t* buf = + (jack_default_audio_sample_t*)fGraphManager->GetBuffer(port_id, fEngineControl->fBufferSize); + + const char *porttype = port->GetType(); + + if (strncmp (porttype, JACK_DEFAULT_AUDIO_TYPE, jack_port_type_size()) == 0) + { + // audio port, resample if necessary + +#if HAVE_SAMPLERATE + if (net_period_up != nframes) { + SRC_STATE *src_state = (SRC_STATE *) src_node->data; + src.data_in = buf; + src.input_frames = nframes; + + src.data_out = (float *) packet_bufX; + src.output_frames = net_period_up; + + src.src_ratio = (float) net_period_up / (float) nframes; + src.end_of_input = 0; + + src_set_ratio (src_state, src.src_ratio); + src_process (src_state, &src); + + for (i = 0; i < net_period_up; i++) + { + packet_bufX[i] = htonl (packet_bufX[i]); + } + src_node = jack_slist_next (src_node); + } + else +#endif + { + if( dont_htonl_floats ) + { + memcpy( packet_bufX, buf, net_period_up*sizeof(jack_default_audio_sample_t) ); + } + else + { + for (i = 0; i < net_period_up; i++) + { + val.f = buf[i]; + val.i = htonl (val.i); + packet_bufX[i] = val.i; + } + } + } + } + else if (strncmp(porttype, JACK_DEFAULT_MIDI_TYPE, jack_port_type_size()) == 0) + { + // encode midi events from port to packet + // convert the data buffer to a standard format (uint32_t based) + unsigned int buffer_size_uint32 = net_period_up; + uint32_t * buffer_uint32 = (uint32_t*) packet_bufX; + encode_midi_buffer (buffer_uint32, buffer_size_uint32, buf); + } + packet_bufX = (packet_bufX + net_period_up); + node = jack_slist_next (node); + chn++; + } +} + +#if HAVE_CELT +// render functions for celt. +void +JackNetOneDriver::render_payload_to_jack_ports_celt (void *packet_payload, jack_nframes_t net_period_down, JSList *capture_ports, JSList *capture_srcs, jack_nframes_t nframes) +{ + uint32_t chn = 0; + JSList *node = capture_ports; + JSList *src_node = capture_srcs; + + unsigned char *packet_bufX = (unsigned char *)packet_payload; + + while (node != NULL) + { + jack_port_id_t port_id = (jack_port_id_t) (intptr_t)node->data; + JackPort *port = fGraphManager->GetPort( port_id ); + + jack_default_audio_sample_t* buf = + (jack_default_audio_sample_t*)fGraphManager->GetBuffer(port_id, fEngineControl->fBufferSize); + + const char *portname = port->GetType(); + + + if (strncmp(portname, JACK_DEFAULT_AUDIO_TYPE, jack_port_type_size()) == 0) + { + // audio port, decode celt data. + + CELTDecoder *decoder = (CELTDecoder *)src_node->data; + if( !packet_payload ) + celt_decode_float( decoder, NULL, net_period_down, buf ); + else + celt_decode_float( decoder, packet_bufX, net_period_down, buf ); + + src_node = jack_slist_next (src_node); + } + else if (strncmp(portname, JACK_DEFAULT_MIDI_TYPE, jack_port_type_size()) == 0) + { + // midi port, decode midi events + // convert the data buffer to a standard format (uint32_t based) + unsigned int buffer_size_uint32 = net_period_down / 2; + uint32_t * buffer_uint32 = (uint32_t*) packet_bufX; + if( packet_payload ) + decode_midi_buffer (buffer_uint32, buffer_size_uint32, buf); + } + packet_bufX = (packet_bufX + net_period_down); + node = jack_slist_next (node); + chn++; + } +} + +void +JackNetOneDriver::render_jack_ports_to_payload_celt (JSList *playback_ports, JSList *playback_srcs, jack_nframes_t nframes, void *packet_payload, jack_nframes_t net_period_up) +{ + uint32_t chn = 0; + JSList *node = playback_ports; + JSList *src_node = playback_srcs; + + unsigned char *packet_bufX = (unsigned char *)packet_payload; + + while (node != NULL) + { + jack_port_id_t port_id = (jack_port_id_t) (intptr_t) node->data; + JackPort *port = fGraphManager->GetPort( port_id ); + + jack_default_audio_sample_t* buf = + (jack_default_audio_sample_t*)fGraphManager->GetBuffer(port_id, fEngineControl->fBufferSize); + + const char *portname = port->GetType(); + + if (strncmp (portname, JACK_DEFAULT_AUDIO_TYPE, jack_port_type_size()) == 0) + { + // audio port, encode celt data. + + int encoded_bytes; + float *floatbuf = (float *)alloca (sizeof(float) * nframes ); + memcpy( floatbuf, buf, nframes*sizeof(float) ); + CELTEncoder *encoder = (CELTEncoder *)src_node->data; + encoded_bytes = celt_encode_float( encoder, floatbuf, NULL, packet_bufX, net_period_up ); + if( encoded_bytes != (int)net_period_up ) + jack_error( "something in celt changed. netjack needs to be changed to handle this.\n" ); + src_node = jack_slist_next( src_node ); + } + else if (strncmp(portname, JACK_DEFAULT_MIDI_TYPE, jack_port_type_size()) == 0) + { + // encode midi events from port to packet + // convert the data buffer to a standard format (uint32_t based) + unsigned int buffer_size_uint32 = net_period_up / 2; + uint32_t * buffer_uint32 = (uint32_t*) packet_bufX; + encode_midi_buffer (buffer_uint32, buffer_size_uint32, buf); + } + packet_bufX = (packet_bufX + net_period_up); + node = jack_slist_next (node); + chn++; + } +} + +#endif +/* Wrapper functions with bitdepth argument... */ +void +JackNetOneDriver::render_payload_to_jack_ports (int bitdepth, void *packet_payload, jack_nframes_t net_period_down, JSList *capture_ports, JSList *capture_srcs, jack_nframes_t nframes, int dont_htonl_floats) +{ +#if HAVE_CELT + if (bitdepth == 1000) + render_payload_to_jack_ports_celt (packet_payload, net_period_down, capture_ports, capture_srcs, nframes); + else +#endif + render_payload_to_jack_ports_float (packet_payload, net_period_down, capture_ports, capture_srcs, nframes, dont_htonl_floats); +} + +void +JackNetOneDriver::render_jack_ports_to_payload (int bitdepth, JSList *playback_ports, JSList *playback_srcs, jack_nframes_t nframes, void *packet_payload, jack_nframes_t net_period_up, int dont_htonl_floats) +{ +#if HAVE_CELT + if (bitdepth == 1000) + render_jack_ports_to_payload_celt (playback_ports, playback_srcs, nframes, packet_payload, net_period_up); + else +#endif + render_jack_ports_to_payload_float (playback_ports, playback_srcs, nframes, packet_payload, net_period_up, dont_htonl_floats); +} + + + +//driver loader----------------------------------------------------------------------- + +#ifdef __cplusplus + extern "C" + { +#endif + SERVER_EXPORT jack_driver_desc_t* driver_get_descriptor () + { + jack_driver_desc_t* desc = ( jack_driver_desc_t* ) calloc ( 1, sizeof ( jack_driver_desc_t ) ); + jack_driver_param_desc_t * params; + + strcpy ( desc->name, "netone" ); // size MUST be less then JACK_DRIVER_NAME_MAX + 1 + strcpy ( desc->desc, "netjack one slave backend component" ); // size MUST be less then JACK_DRIVER_PARAM_DESC + 1 + + desc->nparams = 17; + params = ( jack_driver_param_desc_t* ) calloc ( desc->nparams, sizeof ( jack_driver_param_desc_t ) ); + + int i = 0; + strcpy (params[i].name, "inchannels"); + params[i].character = 'i'; + params[i].type = JackDriverParamUInt; + params[i].value.ui = 2U; + strcpy (params[i].short_desc, "Number of capture channels (defaults to 2)"); + strcpy (params[i].long_desc, params[i].short_desc); + + i++; + strcpy (params[i].name, "outchannels"); + params[i].character = 'o'; + params[i].type = JackDriverParamUInt; + params[i].value.ui = 2U; + strcpy (params[i].short_desc, "Number of playback channels (defaults to 2)"); + strcpy (params[i].long_desc, params[i].short_desc); + + i++; + strcpy (params[i].name, "midi inchannels"); + params[i].character = 'I'; + params[i].type = JackDriverParamUInt; + params[i].value.ui = 1U; + strcpy (params[i].short_desc, "Number of midi capture channels (defaults to 1)"); + strcpy (params[i].long_desc, params[i].short_desc); + + i++; + strcpy (params[i].name, "midi outchannels"); + params[i].character = 'O'; + params[i].type = JackDriverParamUInt; + params[i].value.ui = 1U; + strcpy (params[i].short_desc, "Number of midi playback channels (defaults to 1)"); + strcpy (params[i].long_desc, params[i].short_desc); + + i++; + strcpy (params[i].name, "rate"); + params[i].character = 'r'; + params[i].type = JackDriverParamUInt; + params[i].value.ui = 48000U; + strcpy (params[i].short_desc, "Sample rate"); + strcpy (params[i].long_desc, params[i].short_desc); + + i++; + strcpy (params[i].name, "period"); + params[i].character = 'p'; + params[i].type = JackDriverParamUInt; + params[i].value.ui = 1024U; + strcpy (params[i].short_desc, "Frames per period"); + strcpy (params[i].long_desc, params[i].short_desc); + + i++; + strcpy (params[i].name, "listen-port"); + params[i].character = 'l'; + params[i].type = JackDriverParamUInt; + params[i].value.ui = 3000U; + strcpy (params[i].short_desc, + "The socket port we are listening on for sync packets"); + strcpy (params[i].long_desc, params[i].short_desc); + + i++; + strcpy (params[i].name, "factor"); + params[i].character = 'f'; + params[i].type = JackDriverParamUInt; + params[i].value.ui = 1U; + strcpy (params[i].short_desc, + "Factor for sample rate reduction"); + strcpy (params[i].long_desc, params[i].short_desc); + + i++; + strcpy (params[i].name, "upstream-factor"); + params[i].character = 'u'; + params[i].type = JackDriverParamUInt; + params[i].value.ui = 0U; + strcpy (params[i].short_desc, + "Factor for sample rate reduction on the upstream"); + strcpy (params[i].long_desc, params[i].short_desc); + + i++; + strcpy (params[i].name, "celt"); + params[i].character = 'c'; + params[i].type = JackDriverParamUInt; + params[i].value.ui = 0U; + strcpy (params[i].short_desc, + "sets celt encoding and number of bytes per channel"); + strcpy (params[i].long_desc, params[i].short_desc); + + i++; + strcpy (params[i].name, "bit-depth"); + params[i].character = 'b'; + params[i].type = JackDriverParamUInt; + params[i].value.ui = 0U; + strcpy (params[i].short_desc, + "Sample bit-depth (0 for float, 8 for 8bit and 16 for 16bit)"); + strcpy (params[i].long_desc, params[i].short_desc); + + i++; + strcpy (params[i].name, "transport-sync"); + params[i].character = 't'; + params[i].type = JackDriverParamBool; + params[i].value.ui = 1U; + strcpy (params[i].short_desc, + "Whether to slave the transport to the master transport"); + strcpy (params[i].long_desc, params[i].short_desc); + + i++; + strcpy (params[i].name, "autoconf"); + params[i].character = 'a'; + params[i].type = JackDriverParamBool; + params[i].value.ui = 1U; + strcpy (params[i].short_desc, + "Whether to use Autoconfig, or just start."); + strcpy (params[i].long_desc, params[i].short_desc); + + i++; + strcpy (params[i].name, "latency"); + params[i].character = 'L'; + params[i].type = JackDriverParamUInt; + params[i].value.ui = 5U; + strcpy (params[i].short_desc, + "Latency setting"); + strcpy (params[i].long_desc, params[i].short_desc); + + i++; + strcpy (params[i].name, "redundancy"); + params[i].character = 'R'; + params[i].type = JackDriverParamUInt; + params[i].value.ui = 1U; + strcpy (params[i].short_desc, + "Send packets N times"); + strcpy (params[i].long_desc, params[i].short_desc); + + i++; + strcpy (params[i].name, "no-htonl"); + params[i].character = 'H'; + params[i].type = JackDriverParamBool; + params[i].value.ui = 0U; + strcpy (params[i].short_desc, + "Dont convert samples to network byte order."); + strcpy (params[i].long_desc, params[i].short_desc); + + i++; + strcpy (params[i].name, "deadline"); + params[i].character = 'D'; + params[i].type = JackDriverParamBool; + params[i].value.ui = 0U; + strcpy (params[i].short_desc, + "always use deadline (recommended for internet connect)"); + strcpy (params[i].long_desc, params[i].short_desc); + + desc->params = params; + + return desc; + } + + SERVER_EXPORT Jack::JackDriverClientInterface* driver_initialize ( Jack::JackLockedEngine* engine, Jack::JackSynchro* table, const JSList* params ) + { + jack_nframes_t sample_rate = 48000; + jack_nframes_t resample_factor = 1; + jack_nframes_t period_size = 1024; + unsigned int capture_ports = 2; + unsigned int playback_ports = 2; + unsigned int capture_ports_midi = 1; + unsigned int playback_ports_midi = 1; + unsigned int listen_port = 3000; + unsigned int resample_factor_up = 0; + unsigned int bitdepth = 0; + unsigned int handle_transport_sync = 1; + unsigned int use_autoconfig = 1; + unsigned int latency = 5; + unsigned int redundancy = 1; + unsigned int mtu = 1400; + int dont_htonl_floats = 0; + int always_deadline = 0; + const JSList * node; + const jack_driver_param_t * param; + + + + for ( node = params; node; node = jack_slist_next ( node ) ) + { + param = ( const jack_driver_param_t* ) node->data; + switch ( param->character ) + { + case 'i': + capture_ports = param->value.ui; + break; + + case 'o': + playback_ports = param->value.ui; + break; + + case 'I': + capture_ports_midi = param->value.ui; + break; + + case 'O': + playback_ports_midi = param->value.ui; + break; + + case 'r': + sample_rate = param->value.ui; + break; + + case 'p': + period_size = param->value.ui; + break; + + case 'l': + listen_port = param->value.ui; + break; + + case 'f': +#if HAVE_SAMPLERATE + resample_factor = param->value.ui; +#else + jack_error( "not built with libsamplerate support\n" ); + exit(10); +#endif + break; + + case 'u': +#if HAVE_SAMPLERATE + resample_factor_up = param->value.ui; +#else + jack_error( "not built with libsamplerate support\n" ); + exit(10); +#endif + break; + + case 'b': + bitdepth = param->value.ui; + break; + + case 'c': +#if HAVE_CELT + bitdepth = 1000; + resample_factor = param->value.ui; +#else + jack_error( "not built with celt support\n" ); + exit(10); +#endif + break; + + case 't': + handle_transport_sync = param->value.ui; + break; + + case 'a': + use_autoconfig = param->value.ui; + break; + + case 'L': + latency = param->value.ui; + break; + + case 'R': + redundancy = param->value.ui; + break; + + case 'H': + dont_htonl_floats = param->value.ui; + break; + + case 'D': + always_deadline = param->value.ui; + break; + } + } + + try + { + + Jack::JackDriverClientInterface* driver = + new Jack::JackWaitThreadedDriver ( + new Jack::JackNetOneDriver ( "system", "net_pcm", engine, table, listen_port, mtu, + capture_ports_midi, playback_ports_midi, capture_ports, playback_ports, + sample_rate, period_size, resample_factor, + "net_pcm", handle_transport_sync, bitdepth, use_autoconfig, latency, redundancy, + dont_htonl_floats, always_deadline ) ); + + if ( driver->Open ( period_size, sample_rate, 1, 1, capture_ports, playback_ports, + 0, "from_master_", "to_master_", 0, 0 ) == 0 ) + { + return driver; + } + else + { + delete driver; + return NULL; + } + + } + catch ( ... ) + { + return NULL; + } + } + +#ifdef __cplusplus + } +#endif +} diff --git a/common/JackNetOneDriver.h b/common/JackNetOneDriver.h new file mode 100644 index 00000000..ce30e06e --- /dev/null +++ b/common/JackNetOneDriver.h @@ -0,0 +1,95 @@ +/* +Copyright (C) 2001 Paul Davis +Copyright (C) 2008 Romain Moret at Grame + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 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 General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + +*/ + +#ifndef __JackNetDriver__ +#define __JackNetDriver__ + +#include "JackAudioDriver.h" +#include "netjack.h" + +namespace Jack +{ + /** + \Brief This class describes the Net Backend + */ + + class JackNetOneDriver : public JackAudioDriver + { + private: + netjack_driver_state_t netj; + +void +render_payload_to_jack_ports_float ( void *packet_payload, jack_nframes_t net_period_down, JSList *capture_ports, JSList *capture_srcs, jack_nframes_t nframes, int dont_htonl_floats); +void +render_jack_ports_to_payload_float (JSList *playback_ports, JSList *playback_srcs, jack_nframes_t nframes, void *packet_payload, jack_nframes_t net_period_up, int dont_htonl_floats ); +#ifdef HAVE_CELT +void +render_payload_to_jack_ports_celt (void *packet_payload, jack_nframes_t net_period_down, JSList *capture_ports, JSList *capture_srcs, jack_nframes_t nframes); +void +render_jack_ports_to_payload_celt (JSList *playback_ports, JSList *playback_srcs, jack_nframes_t nframes, void *packet_payload, jack_nframes_t net_period_up); +#endif +void +render_payload_to_jack_ports (int bitdepth, void *packet_payload, jack_nframes_t net_period_down, JSList *capture_ports, JSList *capture_srcs, jack_nframes_t nframes, int dont_htonl_floats); +void +render_jack_ports_to_payload (int bitdepth, JSList *playback_ports, JSList *playback_srcs, jack_nframes_t nframes, void *packet_payload, jack_nframes_t net_period_up, int dont_htonl_floats); + + public: + JackNetOneDriver ( const char* name, const char* alias, JackLockedEngine* engine, JackSynchro* table, + int port, int mtu, int capture_ports, int playback_ports, int midi_input_ports, int midi_output_ports, + int sample_rate, int period_size, int resample_factor, + char* net_name, uint transport_sync, int bitdepth, int use_autoconfig, + int latency, int redundancy, int dont_htonl_floats, int always_deadline ); + ~JackNetOneDriver(); + + int Open ( jack_nframes_t frames_per_cycle, jack_nframes_t rate, bool capturing, bool playing, + int inchannels, int outchannels, bool monitor, const char* capture_driver_name, + const char* playback_driver_name, jack_nframes_t capture_latency, jack_nframes_t playback_latency ); + + int Close(); + int Attach(); + int Detach(); + + int Read(); + int Write(); + + bool Initialize(); + int AllocPorts(); + void FreePorts(); + + // BufferSize can't be changed + bool IsFixedBufferSize() + { + return true; + } + + int SetBufferSize ( jack_nframes_t buffer_size ) + { + return -1; + } + + int SetSampleRate ( jack_nframes_t sample_rate ) + { + return -1; + } + + }; +} + +#endif diff --git a/common/netjack.c b/common/netjack.c new file mode 100644 index 00000000..83436d7a --- /dev/null +++ b/common/netjack.c @@ -0,0 +1,687 @@ + +/* -*- mode: c; c-file-style: "linux"; -*- */ +/* +NetJack Abstraction. + +Copyright (C) 2008 Pieter Palmers +Copyright (C) 2006 Torben Hohn +Copyright (C) 2003 Robert Ham +Copyright (C) 2001 Paul Davis + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 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 General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + +$Id: net_driver.c,v 1.17 2006/04/16 20:16:10 torbenh Exp $ +*/ + +#define HAVE_CELT 1 + + +#include +#include +#include +#include +#include +#include +#include + +#include +#include "jack/jslist.h" + +#include + +#ifdef WIN32 +#include +#include +#else +#include +#include +#endif + +#include "netjack.h" + +//#include "config.h" +#if HAVE_SAMPLERATE +#include +#endif + +#if HAVE_CELT +#include +#endif + +#include "netjack.h" +#include "netjack_packet.h" + +// JACK2 +#include "jack/control.h" + +#define MIN(x,y) ((x)<(y) ? (x) : (y)) + +static int sync_state = 1; +static jack_transport_state_t last_transport_state; + +static int +net_driver_sync_cb(jack_transport_state_t state, jack_position_t *pos, void *data) +{ + int retval = sync_state; + + if (state == JackTransportStarting && last_transport_state != JackTransportStarting) { + retval = 0; + } +// if (state == JackTransportStarting) +// jack_info("Starting sync_state = %d", sync_state); + last_transport_state = state; + return retval; +} + +void netjack_wait( netjack_driver_state_t *netj ) +{ + int we_have_the_expected_frame = 0; + jack_nframes_t next_frame_avail; + jack_time_t packet_recv_time_stamp; + jacknet_packet_header *pkthdr; + + if( !netj->next_deadline_valid ) { + if( netj->latency == 0 ) + // for full sync mode... always wait for packet. + netj->next_deadline = jack_get_time() + 50*netj->period_usecs; + else if( netj->latency == 1 ) + // for normal 1 period latency mode, only 1 period for dealine. + netj->next_deadline = jack_get_time() + 110 * netj->period_usecs /100; + else + // looks like waiting 1 period always is correct. + // not 100% sure yet. with the improved resync, it might be better, + // to have more than one period headroom for high latency. + //netj->next_deadline = jack_get_time() + 5*netj->latency*netj->period_usecs/4; + netj->next_deadline = jack_get_time() + netj->period_usecs + 10*netj->latency*netj->period_usecs/100; + + netj->next_deadline_valid = 1; + } else { + netj->next_deadline += netj->period_usecs; + } + + // Increment expected frame here. + + netj->expected_framecnt += 1; + + //jack_log( "expect %d", netj->expected_framecnt ); + // Now check if required packet is already in the cache. + // then poll (have deadline calculated) + // then drain socket, rinse and repeat. + while(1) { + if( packet_cache_get_next_available_framecnt( global_packcache, netj->expected_framecnt, &next_frame_avail) ) { + if( next_frame_avail == netj->expected_framecnt ) { + we_have_the_expected_frame = 1; + if( !netj->always_deadline ) + break; + } + } + if( ! netjack_poll_deadline( netj->sockfd, netj->next_deadline ) ) { + break; + } + + packet_cache_drain_socket( global_packcache, netj->sockfd ); + } + + // check if we know who to send our packets too. + if (!netj->srcaddress_valid) + if( global_packcache->master_address_valid ) { + memcpy (&(netj->syncsource_address), &(global_packcache->master_address), sizeof( struct sockaddr_in ) ); + netj->srcaddress_valid = 1; + } + + // XXX: switching mode unconditionally is stupid. + // if we were running free perhaps we like to behave differently + // ie. fastforward one packet etc. + // well... this is the first packet we see. hmm.... dunno ;S + // it works... so... + netj->running_free = 0; + + if( !we_have_the_expected_frame ) + jack_log( "xrun... %d", netj->expected_framecnt ); + + if( we_have_the_expected_frame ) { + netj->time_to_deadline = netj->next_deadline - jack_get_time() - netj->period_usecs; + packet_cache_retreive_packet_pointer( global_packcache, netj->expected_framecnt, (char **) &(netj->rx_buf), netj->rx_bufsize , &packet_recv_time_stamp); + pkthdr = (jacknet_packet_header *) netj->rx_buf; + packet_header_ntoh(pkthdr); + netj->deadline_goodness = (int)pkthdr->sync_state; + netj->packet_data_valid = 1; + + // TODO: Queue state could be taken into account. + // But needs more processing, cause, when we are running as + // fast as we can, recv_time_offset can be zero, which is + // good. + // need to add (now-deadline) and check that. + /* + if( recv_time_offset < netj->period_usecs ) + //netj->next_deadline -= netj->period_usecs*netj->latency/100; + netj->next_deadline += netj->period_usecs/1000; + */ + + if( netj->deadline_goodness < (netj->period_usecs/4+10*(int)netj->period_usecs*netj->latency/100) ) { + netj->next_deadline += netj->period_usecs/100; + //jack_log( "goodness: %d, Adjust deadline: --- %d\n", netj->deadline_goodness, (int) netj->period_usecs*netj->latency/100 ); + } + if( netj->deadline_goodness > (netj->period_usecs/4+10*(int)netj->period_usecs*netj->latency/100) ) { + netj->next_deadline -= netj->period_usecs/100; + //jack_log( "goodness: %d, Adjust deadline: +++ %d\n", netj->deadline_goodness, (int) netj->period_usecs*netj->latency/100 ); + } + } else { + netj->time_to_deadline = 0; + // bah... the packet is not there. + // either + // - it got lost. + // - its late + // - sync source is not sending anymore. + + // lets check if we have the next packets, we will just run a cycle without data. + // in that case. + + if( packet_cache_get_next_available_framecnt( global_packcache, netj->expected_framecnt, &next_frame_avail) ) + { + jack_nframes_t offset = next_frame_avail - netj->expected_framecnt; + + //XXX: hmm... i need to remember why resync_threshold wasnt right. + //if( offset < netj->resync_threshold ) + if( offset < 10 ) { + // ok. dont do nothing. we will run without data. + // this seems to be one or 2 lost packets. + // + // this can also be reordered packet jitter. + // (maybe this is not happening in real live) + // but it happens in netem. + + netj->packet_data_valid = 0; + + // I also found this happening, when the packet queue, is too full. + // but wtf ? use a smaller latency. this link can handle that ;S + if( packet_cache_get_fill( global_packcache, netj->expected_framecnt ) > 80.0 ) + netj->next_deadline -= netj->period_usecs/2; + + + } else { + // the diff is too high. but we have a packet in the future. + // lets resync. + netj->expected_framecnt = next_frame_avail; + packet_cache_retreive_packet_pointer( global_packcache, netj->expected_framecnt, (char **) &(netj->rx_buf), netj->rx_bufsize, NULL ); + pkthdr = (jacknet_packet_header *) netj->rx_buf; + packet_header_ntoh(pkthdr); + //netj->deadline_goodness = 0; + netj->deadline_goodness = (int)pkthdr->sync_state - (int)netj->period_usecs * offset; + netj->next_deadline_valid = 0; + netj->packet_data_valid = 1; + } + + } else { + // no packets in buffer. + netj->packet_data_valid = 0; + + //printf( "frame %d No Packet in queue. num_lost_packets = %d \n", netj->expected_framecnt, netj->num_lost_packets ); + if( netj->num_lost_packets < 5 ) { + // ok. No Packet in queue. The packet was either lost, + // or we are running too fast. + // + // Adjusting the deadline unconditionally resulted in + // too many xruns on master. + // But we need to adjust for the case we are running too fast. + // So lets check if the last packet is there now. + // + // It would not be in the queue anymore, if it had been + // retrieved. This might break for redundancy, but + // i will make the packet cache drop redundant packets, + // that have already been retreived. + // + if( packet_cache_get_highest_available_framecnt( global_packcache, &next_frame_avail) ) { + if( next_frame_avail == (netj->expected_framecnt - 1) ) { + // Ok. the last packet is there now. + // and it had not been retrieved. + // + // TODO: We are still dropping 2 packets. + // perhaps we can adjust the deadline + // when (num_packets lost == 0) + + // This might still be too much. + netj->next_deadline += netj->period_usecs; + } + } + } else if( (netj->num_lost_packets <= 100) ) { + // lets try adjusting the deadline harder, for some packets, we might have just ran 2 fast. + netj->next_deadline += netj->period_usecs*netj->latency/8; + } else { + + // But now we can check for any new frame available. + // + if( packet_cache_get_highest_available_framecnt( global_packcache, &next_frame_avail) ) { + netj->expected_framecnt = next_frame_avail; + packet_cache_retreive_packet_pointer( global_packcache, netj->expected_framecnt, (char **) &(netj->rx_buf), netj->rx_bufsize, NULL ); + pkthdr = (jacknet_packet_header *) netj->rx_buf; + packet_header_ntoh(pkthdr); + netj->deadline_goodness = pkthdr->sync_state; + netj->next_deadline_valid = 0; + netj->packet_data_valid = 1; + netj->running_free = 0; + jack_info( "resync after freerun... %d\n", netj->expected_framecnt ); + } else { + // give up. lets run freely. + // XXX: hmm... + + netj->running_free = 1; + + // when we really dont see packets. + // reset source address. and open possibility for new master. + // maybe dsl reconnect. Also restart of netsource without fix + // reply address changes port. + if (netj->num_lost_packets > 200 ) { + netj->srcaddress_valid = 0; + packet_cache_reset_master_address( global_packcache ); + } + } + } + } + } + + if( !netj->packet_data_valid ) + netj->num_lost_packets += 1; + else { + netj->num_lost_packets = 0; + } +} + +void netjack_send_silence( netjack_driver_state_t *netj, int syncstate ) +{ + int tx_size = get_sample_size(netj->bitdepth) * netj->playback_channels * netj->net_period_up + sizeof(jacknet_packet_header); + unsigned int *packet_buf, *packet_bufX; + + packet_buf = alloca( tx_size); + jacknet_packet_header *tx_pkthdr = (jacknet_packet_header *)packet_buf; + jacknet_packet_header *rx_pkthdr = (jacknet_packet_header *)netj->rx_buf; + + //framecnt = rx_pkthdr->framecnt; + + netj->reply_port = rx_pkthdr->reply_port; + + // offset packet_bufX by the packetheader. + packet_bufX = packet_buf + sizeof(jacknet_packet_header) / sizeof(jack_default_audio_sample_t); + + tx_pkthdr->sync_state = syncstate; + tx_pkthdr->framecnt = netj->expected_framecnt; + + // memset 0 the payload. + int payload_size = get_sample_size(netj->bitdepth) * netj->playback_channels * netj->net_period_up; + memset(packet_bufX, 0, payload_size); + + packet_header_hton(tx_pkthdr); + if (netj->srcaddress_valid) + { + int r; + if (netj->reply_port) + netj->syncsource_address.sin_port = htons(netj->reply_port); + + for( r=0; rredundancy; r++ ) + netjack_sendto(netj->outsockfd, (char *)packet_buf, tx_size, + 0, (struct sockaddr*)&(netj->syncsource_address), sizeof(struct sockaddr_in), netj->mtu); + } +} + + +void netjack_attach( netjack_driver_state_t *netj ) +{ + //puts ("net_driver_attach"); + jack_port_t * port; + char buf[32]; + unsigned int chn; + int port_flags; + + + if (netj->handle_transport_sync) + jack_set_sync_callback(netj->client, (JackSyncCallback) net_driver_sync_cb, NULL); + + port_flags = JackPortIsOutput | JackPortIsPhysical | JackPortIsTerminal; + + for (chn = 0; chn < netj->capture_channels_audio; chn++) { + snprintf (buf, sizeof(buf) - 1, "capture_%u", chn + 1); + + port = jack_port_register (netj->client, buf, + JACK_DEFAULT_AUDIO_TYPE, + port_flags, 0); + if (!port) { + jack_error ("NET: cannot register port for %s", buf); + break; + } + + netj->capture_ports = + jack_slist_append (netj->capture_ports, port); + + if( netj->bitdepth == 1000 ) { +#if HAVE_CELT + celt_int32_t lookahead; + // XXX: memory leak + CELTMode *celt_mode = celt_mode_create( netj->sample_rate, 1, netj->period_size, NULL ); + celt_mode_info( celt_mode, CELT_GET_LOOKAHEAD, &lookahead ); + netj->codec_latency = 2*lookahead; + + netj->capture_srcs = jack_slist_append(netj->capture_srcs, celt_decoder_create( celt_mode ) ); +#endif + } else { +#if HAVE_SAMPLERATE + netj->capture_srcs = jack_slist_append(netj->capture_srcs, src_new(SRC_LINEAR, 1, NULL)); +#endif + } + } + for (chn = netj->capture_channels_audio; chn < netj->capture_channels; chn++) { + snprintf (buf, sizeof(buf) - 1, "capture_%u", chn + 1); + + port = jack_port_register (netj->client, buf, + JACK_DEFAULT_MIDI_TYPE, + port_flags, 0); + if (!port) { + jack_error ("NET: cannot register port for %s", buf); + break; + } + + netj->capture_ports = + jack_slist_append (netj->capture_ports, port); + } + + port_flags = JackPortIsInput | JackPortIsPhysical | JackPortIsTerminal; + + for (chn = 0; chn < netj->playback_channels_audio; chn++) { + snprintf (buf, sizeof(buf) - 1, "playback_%u", chn + 1); + + port = jack_port_register (netj->client, buf, + JACK_DEFAULT_AUDIO_TYPE, + port_flags, 0); + + if (!port) { + jack_error ("NET: cannot register port for %s", buf); + break; + } + + netj->playback_ports = + jack_slist_append (netj->playback_ports, port); + if( netj->bitdepth == 1000 ) { +#if HAVE_CELT + // XXX: memory leak + CELTMode *celt_mode = celt_mode_create( netj->sample_rate, 1, netj->period_size, NULL ); + netj->playback_srcs = jack_slist_append(netj->playback_srcs, celt_encoder_create( celt_mode ) ); +#endif + } else { +#if HAVE_SAMPLERATE + netj->playback_srcs = jack_slist_append(netj->playback_srcs, src_new(SRC_LINEAR, 1, NULL)); +#endif + } + } + for (chn = netj->playback_channels_audio; chn < netj->playback_channels; chn++) { + snprintf (buf, sizeof(buf) - 1, "playback_%u", chn + 1); + + port = jack_port_register (netj->client, buf, + JACK_DEFAULT_MIDI_TYPE, + port_flags, 0); + + if (!port) { + jack_error ("NET: cannot register port for %s", buf); + break; + } + + netj->playback_ports = + jack_slist_append (netj->playback_ports, port); + } + + jack_activate (netj->client); +} + + +void netjack_detach( netjack_driver_state_t *netj ) +{ + JSList * node; + + + for (node = netj->capture_ports; node; node = jack_slist_next (node)) + jack_port_unregister (netj->client, + ((jack_port_t *) node->data)); + + jack_slist_free (netj->capture_ports); + netj->capture_ports = NULL; + + for (node = netj->playback_ports; node; node = jack_slist_next (node)) + jack_port_unregister (netj->client, + ((jack_port_t *) node->data)); + + jack_slist_free (netj->playback_ports); + netj->playback_ports = NULL; +} + + +netjack_driver_state_t *netjack_init (netjack_driver_state_t *netj, + jack_client_t * client, + const char *name, + unsigned int capture_ports, + unsigned int playback_ports, + unsigned int capture_ports_midi, + unsigned int playback_ports_midi, + jack_nframes_t sample_rate, + jack_nframes_t period_size, + unsigned int listen_port, + unsigned int transport_sync, + unsigned int resample_factor, + unsigned int resample_factor_up, + unsigned int bitdepth, + unsigned int use_autoconfig, + unsigned int latency, + unsigned int redundancy, + int dont_htonl_floats, + int always_deadline) +{ + + // Fill in netj values. + // might be subject to autoconfig... + // so dont calculate anything with them... + + + netj->sample_rate = sample_rate; + netj->period_size = period_size; + netj->dont_htonl_floats = dont_htonl_floats; + + netj->listen_port = listen_port; + + netj->capture_channels = capture_ports + capture_ports_midi; + netj->capture_channels_audio = capture_ports; + netj->capture_channels_midi = capture_ports_midi; + netj->capture_ports = NULL; + netj->playback_channels = playback_ports + playback_ports_midi; + netj->playback_channels_audio = playback_ports; + netj->playback_channels_midi = playback_ports_midi; + netj->playback_ports = NULL; + netj->codec_latency = 0; + + netj->handle_transport_sync = transport_sync; + netj->mtu = 1400; + netj->latency = latency; + netj->redundancy = redundancy; + netj->use_autoconfig = use_autoconfig; + netj->always_deadline = always_deadline; + + + netj->client = client; + + + if ((bitdepth != 0) && (bitdepth != 8) && (bitdepth != 16) && (bitdepth != 1000)) + { + jack_info ("Invalid bitdepth: %d (8, 16 or 0 for float) !!!", bitdepth); + return NULL; + } + netj->bitdepth = bitdepth; + + + if (resample_factor_up == 0) + resample_factor_up = resample_factor; + + netj->resample_factor = resample_factor; + netj->resample_factor_up = resample_factor_up; + + + return netj; +} + +void netjack_release( netjack_driver_state_t *netj ) +{ + close( netj->sockfd ); + close( netj->outsockfd ); + + packet_cache_free( global_packcache ); + global_packcache = NULL; +} + +int +netjack_startup( netjack_driver_state_t *netj ) +{ + int first_pack_len; + struct sockaddr_in address; + // Now open the socket, and wait for the first packet to arrive... + netj->sockfd = socket (AF_INET, SOCK_DGRAM, 0); +#ifdef WIN32 + if (netj->sockfd == INVALID_SOCKET) +#else + if (netj->sockfd == -1) +#endif + { + jack_info ("socket error"); + return -1; + } + address.sin_family = AF_INET; + address.sin_port = htons(netj->listen_port); + address.sin_addr.s_addr = htonl(INADDR_ANY); + if (bind (netj->sockfd, (struct sockaddr *) &address, sizeof (address)) < 0) + { + jack_info("bind error"); + return -1; + } + + netj->outsockfd = socket (AF_INET, SOCK_DGRAM, 0); +#ifdef WIN32 + if (netj->outsockfd == INVALID_SOCKET) +#else + if (netj->outsockfd == -1) +#endif + { + jack_info ("socket error"); + return -1; + } + netj->srcaddress_valid = 0; + if (netj->use_autoconfig) + { + jacknet_packet_header *first_packet = alloca (sizeof (jacknet_packet_header)); +#ifdef WIN32 + int address_size = sizeof( struct sockaddr_in ); +#else + socklen_t address_size = sizeof (struct sockaddr_in); +#endif + //jack_info ("Waiting for an incoming packet !!!"); + //jack_info ("*** IMPORTANT *** Dont connect a client to jackd until the driver is attached to a clock source !!!"); + + while(1) { + first_pack_len = recvfrom (netj->sockfd, (char *)first_packet, sizeof (jacknet_packet_header), 0, (struct sockaddr*) & netj->syncsource_address, &address_size); +#ifdef WIN32 + if( first_pack_len == -1 ) { + first_pack_len = sizeof(jacknet_packet_header); + break; + } +#else + if (first_pack_len == sizeof (jacknet_packet_header)) + break; +#endif + } + netj->srcaddress_valid = 1; + + if (first_pack_len == sizeof (jacknet_packet_header)) + { + packet_header_ntoh (first_packet); + + jack_info ("AutoConfig Override !!!"); + if (netj->sample_rate != first_packet->sample_rate) + { + jack_info ("AutoConfig Override: Master JACK sample rate = %d", first_packet->sample_rate); + netj->sample_rate = first_packet->sample_rate; + } + + if (netj->period_size != first_packet->period_size) + { + jack_info ("AutoConfig Override: Master JACK period size is %d", first_packet->period_size); + netj->period_size = first_packet->period_size; + } + if (netj->capture_channels_audio != first_packet->capture_channels_audio) + { + jack_info ("AutoConfig Override: capture_channels_audio = %d", first_packet->capture_channels_audio); + netj->capture_channels_audio = first_packet->capture_channels_audio; + } + if (netj->capture_channels_midi != first_packet->capture_channels_midi) + { + jack_info ("AutoConfig Override: capture_channels_midi = %d", first_packet->capture_channels_midi); + netj->capture_channels_midi = first_packet->capture_channels_midi; + } + if (netj->playback_channels_audio != first_packet->playback_channels_audio) + { + jack_info ("AutoConfig Override: playback_channels_audio = %d", first_packet->playback_channels_audio); + netj->playback_channels_audio = first_packet->playback_channels_audio; + } + if (netj->playback_channels_midi != first_packet->playback_channels_midi) + { + jack_info ("AutoConfig Override: playback_channels_midi = %d", first_packet->playback_channels_midi); + netj->playback_channels_midi = first_packet->playback_channels_midi; + } + + netj->mtu = first_packet->mtu; + jack_info ("MTU is set to %d bytes", first_packet->mtu); + netj->latency = first_packet->latency; + } + } + netj->capture_channels = netj->capture_channels_audio + netj->capture_channels_midi; + netj->playback_channels = netj->playback_channels_audio + netj->playback_channels_midi; + + // After possible Autoconfig: do all calculations... + netj->period_usecs = + (jack_time_t) floor ((((float) netj->period_size) / (float)netj->sample_rate) + * 1000000.0f); + + if( netj->bitdepth == 1000 ) { + // celt mode. + // TODO: this is a hack. But i dont want to change the packet header. + netj->net_period_down = netj->resample_factor; + netj->net_period_up = netj->resample_factor_up; + } else { + netj->net_period_down = (float) netj->period_size / (float) netj->resample_factor; + netj->net_period_up = (float) netj->period_size / (float) netj->resample_factor_up; + } + + netj->rx_bufsize = sizeof (jacknet_packet_header) + netj->net_period_down * netj->capture_channels * get_sample_size (netj->bitdepth); + netj->pkt_buf = malloc (netj->rx_bufsize); + global_packcache = packet_cache_new (netj->latency + 50, netj->rx_bufsize, netj->mtu); + + netj->expected_framecnt_valid = 0; + netj->num_lost_packets = 0; + netj->next_deadline_valid = 0; + netj->deadline_goodness = 0; + netj->time_to_deadline = 0; + + // Special handling for latency=0 + if( netj->latency == 0 ) + netj->resync_threshold = 0; + else + netj->resync_threshold = MIN( 15, netj->latency-1 ); + + netj->running_free = 0; + + return 0; +} diff --git a/common/netjack.h b/common/netjack.h new file mode 100644 index 00000000..db30377a --- /dev/null +++ b/common/netjack.h @@ -0,0 +1,144 @@ + +/* + Copyright (C) 2003 Robert Ham + Copyright (C) 2005 Torben Hohn + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. +*/ + +#ifndef __NETJACK_H__ +#define __NETJACK_H__ + +#include + +#include +//#include +#include +#include + +#include "jack/jslist.h" + +//#include + +#ifdef __cplusplus +extern "C" +{ +#endif + +typedef struct _netjack_driver_state netjack_driver_state_t; + +struct _netjack_driver_state { + jack_nframes_t net_period_up; + jack_nframes_t net_period_down; + + jack_nframes_t sample_rate; + jack_nframes_t bitdepth; + jack_nframes_t period_size; + jack_time_t period_usecs; + int dont_htonl_floats; + int always_deadline; + + jack_nframes_t codec_latency; + + unsigned int listen_port; + + unsigned int capture_channels; + unsigned int playback_channels; + unsigned int capture_channels_audio; + unsigned int playback_channels_audio; + unsigned int capture_channels_midi; + unsigned int playback_channels_midi; + + JSList *capture_ports; + JSList *playback_ports; + JSList *playback_srcs; + JSList *capture_srcs; + + jack_client_t *client; + +#ifdef WIN32 + SOCKET sockfd; + SOCKET outsockfd; +#else + int sockfd; + int outsockfd; +#endif + + struct sockaddr_in syncsource_address; + + int reply_port; + int srcaddress_valid; + + int sync_state; + unsigned int handle_transport_sync; + + unsigned int *rx_buf; + unsigned int *pkt_buf; + unsigned int rx_bufsize; + //unsigned int tx_bufsize; + unsigned int mtu; + unsigned int latency; + unsigned int redundancy; + + jack_nframes_t expected_framecnt; + int expected_framecnt_valid; + unsigned int num_lost_packets; + jack_time_t next_deadline; + int next_deadline_valid; + int packet_data_valid; + int resync_threshold; + int running_free; + int deadline_goodness; + jack_time_t time_to_deadline; + unsigned int use_autoconfig; + unsigned int resample_factor; + unsigned int resample_factor_up; +}; + +void netjack_wait( netjack_driver_state_t *netj ); +void netjack_send_silence( netjack_driver_state_t *netj, int syncstate ); +void netjack_read( netjack_driver_state_t *netj, jack_nframes_t nframes ) ; +void netjack_write( netjack_driver_state_t *netj, jack_nframes_t nframes, int syncstate ); +void netjack_attach( netjack_driver_state_t *netj ); +void netjack_detach( netjack_driver_state_t *netj ); + +netjack_driver_state_t *netjack_init (netjack_driver_state_t *netj, + jack_client_t * client, + const char *name, + unsigned int capture_ports, + unsigned int playback_ports, + unsigned int capture_ports_midi, + unsigned int playback_ports_midi, + jack_nframes_t sample_rate, + jack_nframes_t period_size, + unsigned int listen_port, + unsigned int transport_sync, + unsigned int resample_factor, + unsigned int resample_factor_up, + unsigned int bitdepth, + unsigned int use_autoconfig, + unsigned int latency, + unsigned int redundancy, + int dont_htonl_floats, + int always_deadline); + +void netjack_release( netjack_driver_state_t *netj ); +int netjack_startup( netjack_driver_state_t *netj ); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/common/netjack_packet.c b/common/netjack_packet.c new file mode 100644 index 00000000..cd51dca9 --- /dev/null +++ b/common/netjack_packet.c @@ -0,0 +1,1527 @@ + +/* + * NetJack - Packet Handling functions + * + * used by the driver and the jacknet_client + * + * Copyright (C) 2008 Marc-Olivier Barre + * Copyright (C) 2008 Pieter Palmers + * Copyright (C) 2006 Torben Hohn + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + * + * $Id: net_driver.c,v 1.16 2006/03/20 19:41:37 torbenh Exp $ + * + */ + +//#include "config.h" + +#define HAVE_CELT 1 + +#define _XOPEN_SOURCE 600 +#define _BSD_SOURCE + +#ifdef __APPLE__ +#define _DARWIN_C_SOURCE +#endif + +#if HAVE_PPOLL +#define _GNU_SOURCE +#endif + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +//#include + +#include + +#ifdef WIN32 +#include +#include +#else +#include +#include +#include +#endif + +#include +#include + +#if HAVE_SAMPLERATE +#include +#endif + +#if HAVE_CELT +#include +#endif + +#include "netjack_packet.h" + +// JACK2 specific. +#include "jack/control.h" + +#ifdef NO_JACK_ERROR +#define jack_error printf +#endif + +int fraggo = 0; + +packet_cache *global_packcache = NULL; + +void +packet_header_hton (jacknet_packet_header *pkthdr) +{ + pkthdr->capture_channels_audio = htonl(pkthdr->capture_channels_audio); + pkthdr->playback_channels_audio = htonl(pkthdr->playback_channels_audio); + pkthdr->capture_channels_midi = htonl(pkthdr->capture_channels_midi); + pkthdr->playback_channels_midi = htonl(pkthdr->playback_channels_midi); + pkthdr->period_size = htonl(pkthdr->period_size); + pkthdr->sample_rate = htonl(pkthdr->sample_rate); + pkthdr->sync_state = htonl(pkthdr->sync_state); + pkthdr->transport_frame = htonl(pkthdr->transport_frame); + pkthdr->transport_state = htonl(pkthdr->transport_state); + pkthdr->framecnt = htonl(pkthdr->framecnt); + pkthdr->latency = htonl(pkthdr->latency); + pkthdr->reply_port = htonl(pkthdr->reply_port); + pkthdr->mtu = htonl(pkthdr->mtu); + pkthdr->fragment_nr = htonl(pkthdr->fragment_nr); +} + +void +packet_header_ntoh (jacknet_packet_header *pkthdr) +{ + pkthdr->capture_channels_audio = ntohl(pkthdr->capture_channels_audio); + pkthdr->playback_channels_audio = ntohl(pkthdr->playback_channels_audio); + pkthdr->capture_channels_midi = ntohl(pkthdr->capture_channels_midi); + pkthdr->playback_channels_midi = ntohl(pkthdr->playback_channels_midi); + pkthdr->period_size = ntohl(pkthdr->period_size); + pkthdr->sample_rate = ntohl(pkthdr->sample_rate); + pkthdr->sync_state = ntohl(pkthdr->sync_state); + pkthdr->transport_frame = ntohl(pkthdr->transport_frame); + pkthdr->transport_state = ntohl(pkthdr->transport_state); + pkthdr->framecnt = ntohl(pkthdr->framecnt); + pkthdr->latency = ntohl(pkthdr->latency); + pkthdr->reply_port = ntohl(pkthdr->reply_port); + pkthdr->mtu = ntohl(pkthdr->mtu); + pkthdr->fragment_nr = ntohl(pkthdr->fragment_nr); +} + +int get_sample_size (int bitdepth) +{ + if (bitdepth == 8) + return sizeof (int8_t); + if (bitdepth == 16) + return sizeof (int16_t); + if( bitdepth == 1000 ) + return sizeof( unsigned char ); + return sizeof (int32_t); +} + +// fragment management functions. + +packet_cache +*packet_cache_new (int num_packets, int pkt_size, int mtu) +{ + int fragment_payload_size = mtu - sizeof (jacknet_packet_header); + int i, fragment_number; + + if( pkt_size == sizeof(jacknet_packet_header) ) + fragment_number = 1; + else + fragment_number = (pkt_size - sizeof (jacknet_packet_header) - 1) / fragment_payload_size + 1; + + packet_cache *pcache = malloc (sizeof (packet_cache)); + if (pcache == NULL) + { + jack_error ("could not allocate packet cache (1)\n"); + return NULL; + } + + pcache->size = num_packets; + pcache->packets = malloc (sizeof (cache_packet) * num_packets); + pcache->master_address_valid = 0; + pcache->last_framecnt_retreived = 0; + pcache->last_framecnt_retreived_valid = 0; + + if (pcache->packets == NULL) + { + jack_error ("could not allocate packet cache (2)\n"); + return NULL; + } + + for (i = 0; i < num_packets; i++) + { + pcache->packets[i].valid = 0; + pcache->packets[i].num_fragments = fragment_number; + pcache->packets[i].packet_size = pkt_size; + pcache->packets[i].mtu = mtu; + pcache->packets[i].framecnt = 0; + pcache->packets[i].fragment_array = malloc (sizeof (char) * fragment_number); + pcache->packets[i].packet_buf = malloc (pkt_size); + if ((pcache->packets[i].fragment_array == NULL) || (pcache->packets[i].packet_buf == NULL)) + { + jack_error ("could not allocate packet cache (3)\n"); + return NULL; + } + } + pcache->mtu = mtu; + + return pcache; +} + +void +packet_cache_free (packet_cache *pcache) +{ + int i; + if( pcache == NULL ) + return; + + for (i = 0; i < pcache->size; i++) + { + free (pcache->packets[i].fragment_array); + free (pcache->packets[i].packet_buf); + } + + free (pcache->packets); + free (pcache); +} + +cache_packet +*packet_cache_get_packet (packet_cache *pcache, jack_nframes_t framecnt) +{ + int i; + cache_packet *retval; + + for (i = 0; i < pcache->size; i++) + { + if (pcache->packets[i].valid && (pcache->packets[i].framecnt == framecnt)) + return &(pcache->packets[i]); + } + + // The Packet is not in the packet cache. + // find a free packet. + + retval = packet_cache_get_free_packet (pcache); + if (retval != NULL) + { + cache_packet_set_framecnt (retval, framecnt); + return retval; + } + + // No Free Packet available + // Get The Oldest packet and reset it. + + retval = packet_cache_get_oldest_packet (pcache); + //printf( "Dropping %d from Cache :S\n", retval->framecnt ); + cache_packet_reset (retval); + cache_packet_set_framecnt (retval, framecnt); + + return retval; +} + +// TODO: fix wrapping case... need to pass +// current expected frame here. +// +// or just save framecount into packet_cache. + +cache_packet +*packet_cache_get_oldest_packet (packet_cache *pcache) +{ + jack_nframes_t minimal_frame = JACK_MAX_FRAMES; + cache_packet *retval = &(pcache->packets[0]); + int i; + + for (i = 0; i < pcache->size; i++) + { + if (pcache->packets[i].valid && (pcache->packets[i].framecnt < minimal_frame)) + { + minimal_frame = pcache->packets[i].framecnt; + retval = &(pcache->packets[i]); + } + } + + return retval; +} + +cache_packet +*packet_cache_get_free_packet (packet_cache *pcache) +{ + int i; + + for (i = 0; i < pcache->size; i++) + { + if (pcache->packets[i].valid == 0) + return &(pcache->packets[i]); + } + + return NULL; +} + +void +cache_packet_reset (cache_packet *pack) +{ + int i; + pack->valid = 0; + + // XXX: i dont think this is necessary here... + // fragement array is cleared in _set_framecnt() + + for (i = 0; i < pack->num_fragments; i++) + pack->fragment_array[i] = 0; +} + +void +cache_packet_set_framecnt (cache_packet *pack, jack_nframes_t framecnt) +{ + int i; + + pack->framecnt = framecnt; + + for (i = 0; i < pack->num_fragments; i++) + pack->fragment_array[i] = 0; + + pack->valid = 1; +} + +void +cache_packet_add_fragment (cache_packet *pack, char *packet_buf, int rcv_len) +{ + jacknet_packet_header *pkthdr = (jacknet_packet_header *) packet_buf; + int fragment_payload_size = pack->mtu - sizeof (jacknet_packet_header); + char *packet_bufX = pack->packet_buf + sizeof (jacknet_packet_header); + char *dataX = packet_buf + sizeof (jacknet_packet_header); + + jack_nframes_t fragment_nr = ntohl (pkthdr->fragment_nr); + jack_nframes_t framecnt = ntohl (pkthdr->framecnt); + + if (framecnt != pack->framecnt) + { + jack_error ("errror. framecnts dont match\n"); + return; + } + + + if (fragment_nr == 0) + { + memcpy (pack->packet_buf, packet_buf, rcv_len); + pack->fragment_array[0] = 1; + + return; + } + + if ((fragment_nr < pack->num_fragments) && (fragment_nr > 0)) + { + if ((fragment_nr * fragment_payload_size + rcv_len - sizeof (jacknet_packet_header)) <= (pack->packet_size - sizeof (jacknet_packet_header))) + { + memcpy (packet_bufX + fragment_nr * fragment_payload_size, dataX, rcv_len - sizeof (jacknet_packet_header)); + pack->fragment_array[fragment_nr] = 1; + } + else + jack_error ("too long packet received..."); + } +} + +int +cache_packet_is_complete (cache_packet *pack) +{ + int i; + for (i = 0; i < pack->num_fragments; i++) + if (pack->fragment_array[i] == 0) + return 0; + + return 1; +} + +#ifndef WIN32 +// new poll using nanoseconds resolution and +// not waiting forever. +int +netjack_poll_deadline (int sockfd, jack_time_t deadline) +{ + struct pollfd fds; + int i, poll_err = 0; + sigset_t sigmask; + struct sigaction action; +#if HAVE_PPOLL + struct timespec timeout_spec = { 0, 0 }; +#else + sigset_t rsigmask; + int timeout; +#endif + + + jack_time_t now = jack_get_time(); + if( now >= deadline ) + return 0; + +#if HAVE_PPOLL + timeout_spec.tv_nsec = (deadline - now) * 1000; +#else + timeout = lrintf( (float)(deadline - now) / 1000.0 ); +#endif + + sigemptyset(&sigmask); + sigaddset(&sigmask, SIGHUP); + sigaddset(&sigmask, SIGINT); + sigaddset(&sigmask, SIGQUIT); + sigaddset(&sigmask, SIGPIPE); + sigaddset(&sigmask, SIGTERM); + sigaddset(&sigmask, SIGUSR1); + sigaddset(&sigmask, SIGUSR2); + + action.sa_handler = SIG_DFL; + action.sa_mask = sigmask; + action.sa_flags = SA_RESTART; + + for (i = 1; i < NSIG; i++) + if (sigismember (&sigmask, i)) + sigaction (i, &action, 0); + + fds.fd = sockfd; + fds.events = POLLIN; + +#if HAVE_PPOLL + poll_err = ppoll (&fds, 1, &timeout_spec, &sigmask); +#else + sigprocmask (SIG_UNBLOCK, &sigmask, &rsigmask); + poll_err = poll (&fds, 1, timeout); + sigprocmask (SIG_SETMASK, &rsigmask, NULL); +#endif + + if (poll_err == -1) + { + switch (errno) + { + case EBADF: + jack_error ("Error %d: An invalid file descriptor was given in one of the sets", errno); + break; + case EFAULT: + jack_error ("Error %d: The array given as argument was not contained in the calling program's address space", errno); + break; + case EINTR: + jack_error ("Error %d: A signal occurred before any requested event", errno); + break; + case EINVAL: + jack_error ("Error %d: The nfds value exceeds the RLIMIT_NOFILE value", errno); + break; + case ENOMEM: + jack_error ("Error %d: There was no space to allocate file descriptor tables", errno); + break; + } + } + return poll_err; +} + +int +netjack_poll (int sockfd, int timeout) +{ + struct pollfd fds; + int i, poll_err = 0; + sigset_t sigmask, rsigmask; + struct sigaction action; + + sigemptyset(&sigmask); + sigaddset(&sigmask, SIGHUP); + sigaddset(&sigmask, SIGINT); + sigaddset(&sigmask, SIGQUIT); + sigaddset(&sigmask, SIGPIPE); + sigaddset(&sigmask, SIGTERM); + sigaddset(&sigmask, SIGUSR1); + sigaddset(&sigmask, SIGUSR2); + + action.sa_handler = SIG_DFL; + action.sa_mask = sigmask; + action.sa_flags = SA_RESTART; + + for (i = 1; i < NSIG; i++) + if (sigismember (&sigmask, i)) + sigaction (i, &action, 0); + + fds.fd = sockfd; + fds.events = POLLIN; + + sigprocmask(SIG_UNBLOCK, &sigmask, &rsigmask); + while (poll_err == 0) + { + poll_err = poll (&fds, 1, timeout); + } + sigprocmask(SIG_SETMASK, &rsigmask, NULL); + + if (poll_err == -1) + { + switch (errno) + { + case EBADF: + jack_error ("Error %d: An invalid file descriptor was given in one of the sets", errno); + break; + case EFAULT: + jack_error ("Error %d: The array given as argument was not contained in the calling program's address space", errno); + break; + case EINTR: + jack_error ("Error %d: A signal occurred before any requested event", errno); + break; + case EINVAL: + jack_error ("Error %d: The nfds value exceeds the RLIMIT_NOFILE value", errno); + break; + case ENOMEM: + jack_error ("Error %d: There was no space to allocate file descriptor tables", errno); + break; + } + return 0; + } + return 1; +} + +#else +int +netjack_poll (int sockfd, int timeout) +{ + jack_error( "netjack_poll not implemented\n" ); + return 0; +} +int +netjack_poll_deadline (int sockfd, jack_time_t deadline) +{ + fd_set fds; + FD_ZERO( &fds ); + FD_SET( sockfd, &fds ); + + struct timeval timeout; + while( 1 ) { + jack_time_t now = jack_get_time(); + if( now >= deadline ) + return 0; + + int timeout_usecs = (deadline - now); + //jack_error( "timeout = %d", timeout_usecs ); + timeout.tv_sec = 0; + timeout.tv_usec = (timeout_usecs < 500) ? 500 : timeout_usecs; + + int poll_err = select (0, &fds, NULL, NULL, &timeout); + if( poll_err != 0 ) + return poll_err; + } + + return 0; +} +#endif +// This now reads all a socket has into the cache. +// replacing netjack_recv functions. + +void +packet_cache_drain_socket( packet_cache *pcache, int sockfd ) +{ + char *rx_packet = alloca (pcache->mtu); + jacknet_packet_header *pkthdr = (jacknet_packet_header *) rx_packet; + int rcv_len; + jack_nframes_t framecnt; + cache_packet *cpack; + struct sockaddr_in sender_address; +#ifdef WIN32 + size_t senderlen = sizeof( struct sockaddr_in ); + u_long parm = 1; + ioctlsocket( sockfd, FIONBIO, &parm ); +#else + socklen_t senderlen = sizeof( struct sockaddr_in ); +#endif + while (1) + { +#ifdef WIN32 + rcv_len = recvfrom (sockfd, rx_packet, pcache->mtu, 0, + (struct sockaddr*) &sender_address, &senderlen); +#else + rcv_len = recvfrom (sockfd, rx_packet, pcache->mtu, MSG_DONTWAIT, + (struct sockaddr*) &sender_address, &senderlen); +#endif + if (rcv_len < 0) + return; + + if (pcache->master_address_valid) { + // Verify its from our master. + if (memcmp (&sender_address, &(pcache->master_address), senderlen) != 0) + continue; + } else { + // Setup this one as master + //printf( "setup master...\n" ); + memcpy ( &(pcache->master_address), &sender_address, senderlen ); + pcache->master_address_valid = 1; + } + + framecnt = ntohl (pkthdr->framecnt); + if( pcache->last_framecnt_retreived_valid && (framecnt <= pcache->last_framecnt_retreived )) + continue; + + cpack = packet_cache_get_packet (global_packcache, framecnt); + cache_packet_add_fragment (cpack, rx_packet, rcv_len); + cpack->recv_timestamp = jack_get_time(); + } +} + +void +packet_cache_reset_master_address( packet_cache *pcache ) +{ + pcache->master_address_valid = 0; + pcache->last_framecnt_retreived = 0; + pcache->last_framecnt_retreived_valid = 0; +} + +void +packet_cache_clear_old_packets (packet_cache *pcache, jack_nframes_t framecnt ) +{ + int i; + + for (i = 0; i < pcache->size; i++) + { + if (pcache->packets[i].valid && (pcache->packets[i].framecnt < framecnt)) + { + cache_packet_reset (&(pcache->packets[i])); + } + } +} + +int +packet_cache_retreive_packet_pointer( packet_cache *pcache, jack_nframes_t framecnt, char **packet_buf, int pkt_size, jack_time_t *timestamp ) +{ + int i; + cache_packet *cpack = NULL; + + + for (i = 0; i < pcache->size; i++) { + if (pcache->packets[i].valid && (pcache->packets[i].framecnt == framecnt)) { + cpack = &(pcache->packets[i]); + break; + } + } + + if( cpack == NULL ) { + //printf( "retreive packet: %d....not found\n", framecnt ); + return -1; + } + + if( !cache_packet_is_complete( cpack ) ) { + return -1; + } + + // ok. cpack is the one we want and its complete. + *packet_buf = cpack->packet_buf; + if( timestamp ) + *timestamp = cpack->recv_timestamp; + + pcache->last_framecnt_retreived_valid = 1; + pcache->last_framecnt_retreived = framecnt; + + return pkt_size; +} + +int +packet_cache_release_packet( packet_cache *pcache, jack_nframes_t framecnt ) +{ + int i; + cache_packet *cpack = NULL; + + + for (i = 0; i < pcache->size; i++) { + if (pcache->packets[i].valid && (pcache->packets[i].framecnt == framecnt)) { + cpack = &(pcache->packets[i]); + break; + } + } + + if( cpack == NULL ) { + //printf( "retreive packet: %d....not found\n", framecnt ); + return -1; + } + + if( !cache_packet_is_complete( cpack ) ) { + return -1; + } + + cache_packet_reset (cpack); + packet_cache_clear_old_packets( pcache, framecnt ); + + return 0; +} +float +packet_cache_get_fill( packet_cache *pcache, jack_nframes_t expected_framecnt ) +{ + int num_packets_before_us = 0; + int i; + + for (i = 0; i < pcache->size; i++) + { + cache_packet *cpack = &(pcache->packets[i]); + if (cpack->valid && cache_packet_is_complete( cpack )) + if( cpack->framecnt >= expected_framecnt ) + num_packets_before_us += 1; + } + + return 100.0 * (float)num_packets_before_us / (float)( pcache->size ) ; +} + +// Returns 0 when no valid packet is inside the cache. +int +packet_cache_get_next_available_framecnt( packet_cache *pcache, jack_nframes_t expected_framecnt, jack_nframes_t *framecnt ) +{ + int i; + jack_nframes_t best_offset = JACK_MAX_FRAMES/2-1; + int retval = 0; + + for (i = 0; i < pcache->size; i++) + { + cache_packet *cpack = &(pcache->packets[i]); + //printf( "p%d: valid=%d, frame %d\n", i, cpack->valid, cpack->framecnt ); + + if (!cpack->valid || !cache_packet_is_complete( cpack )) { + //printf( "invalid\n" ); + continue; + } + + if( (cpack->framecnt - expected_framecnt) > best_offset ) { + continue; + } + + best_offset = cpack->framecnt - expected_framecnt; + retval = 1; + + if( best_offset == 0 ) + break; + } + if( retval && framecnt ) + *framecnt = expected_framecnt + best_offset; + + return retval; +} + +int +packet_cache_get_highest_available_framecnt( packet_cache *pcache, jack_nframes_t *framecnt ) +{ + int i; + jack_nframes_t best_value = 0; + int retval = 0; + + for (i = 0; i < pcache->size; i++) + { + cache_packet *cpack = &(pcache->packets[i]); + //printf( "p%d: valid=%d, frame %d\n", i, cpack->valid, cpack->framecnt ); + + if (!cpack->valid || !cache_packet_is_complete( cpack )) { + //printf( "invalid\n" ); + continue; + } + + if (cpack->framecnt < best_value) { + continue; + } + + best_value = cpack->framecnt; + retval = 1; + + } + if( retval && framecnt ) + *framecnt = best_value; + + return retval; +} + +// Returns 0 when no valid packet is inside the cache. +int +packet_cache_find_latency( packet_cache *pcache, jack_nframes_t expected_framecnt, jack_nframes_t *framecnt ) +{ + int i; + jack_nframes_t best_offset = 0; + int retval = 0; + + for (i = 0; i < pcache->size; i++) + { + cache_packet *cpack = &(pcache->packets[i]); + //printf( "p%d: valid=%d, frame %d\n", i, cpack->valid, cpack->framecnt ); + + if (!cpack->valid || !cache_packet_is_complete( cpack )) { + //printf( "invalid\n" ); + continue; + } + + if( (cpack->framecnt - expected_framecnt) < best_offset ) { + continue; + } + + best_offset = cpack->framecnt - expected_framecnt; + retval = 1; + + if( best_offset == 0 ) + break; + } + if( retval && framecnt ) + *framecnt = JACK_MAX_FRAMES - best_offset; + + return retval; +} +// fragmented packet IO +int +netjack_recvfrom (int sockfd, char *packet_buf, int pkt_size, int flags, struct sockaddr *addr, size_t *addr_size, int mtu) +{ + int retval; + socklen_t from_len = *addr_size; + if (pkt_size <= mtu) { + retval = recvfrom (sockfd, packet_buf, pkt_size, flags, addr, &from_len); + *addr_size = from_len; + return retval; + } + + char *rx_packet = alloca (mtu); + jacknet_packet_header *pkthdr = (jacknet_packet_header *) rx_packet; + int rcv_len; + jack_nframes_t framecnt; + cache_packet *cpack; + do + { + rcv_len = recvfrom (sockfd, rx_packet, mtu, 0, addr, &from_len); + if (rcv_len < 0) + return rcv_len; + framecnt = ntohl (pkthdr->framecnt); + cpack = packet_cache_get_packet (global_packcache, framecnt); + cache_packet_add_fragment (cpack, rx_packet, rcv_len); + } while (!cache_packet_is_complete (cpack)); + memcpy (packet_buf, cpack->packet_buf, pkt_size); + cache_packet_reset (cpack); + *addr_size = from_len; + return pkt_size; +} + +int +netjack_recv (int sockfd, char *packet_buf, int pkt_size, int flags, int mtu) +{ + if (pkt_size <= mtu) + return recv (sockfd, packet_buf, pkt_size, flags); + char *rx_packet = alloca (mtu); + jacknet_packet_header *pkthdr = (jacknet_packet_header *) rx_packet; + int rcv_len; + jack_nframes_t framecnt; + cache_packet *cpack; + do + { + rcv_len = recv (sockfd, rx_packet, mtu, flags); + if (rcv_len < 0) + return rcv_len; + framecnt = ntohl (pkthdr->framecnt); + cpack = packet_cache_get_packet (global_packcache, framecnt); + cache_packet_add_fragment (cpack, rx_packet, rcv_len); + } while (!cache_packet_is_complete (cpack)); + memcpy (packet_buf, cpack->packet_buf, pkt_size); + cache_packet_reset (cpack); + return pkt_size; +} + +void +netjack_sendto (int sockfd, char *packet_buf, int pkt_size, int flags, struct sockaddr *addr, int addr_size, int mtu) +{ + int frag_cnt = 0; + char *tx_packet, *dataX; + jacknet_packet_header *pkthdr; + + tx_packet = alloca (mtu + 10); + dataX = tx_packet + sizeof (jacknet_packet_header); + pkthdr = (jacknet_packet_header *) tx_packet; + + int fragment_payload_size = mtu - sizeof (jacknet_packet_header); + + if (pkt_size <= mtu) { + int err; + pkthdr = (jacknet_packet_header *) packet_buf; + pkthdr->fragment_nr = htonl (0); + err = sendto(sockfd, packet_buf, pkt_size, flags, addr, addr_size); + if( err<0 ) { + //printf( "error in send\n" ); + perror( "send" ); + } + } + else + { + int err; + // Copy the packet header to the tx pack first. + memcpy(tx_packet, packet_buf, sizeof (jacknet_packet_header)); + + // Now loop and send all + char *packet_bufX = packet_buf + sizeof (jacknet_packet_header); + + while (packet_bufX < (packet_buf + pkt_size - fragment_payload_size)) + { + pkthdr->fragment_nr = htonl (frag_cnt++); + memcpy (dataX, packet_bufX, fragment_payload_size); + sendto (sockfd, tx_packet, mtu, flags, addr, addr_size); + packet_bufX += fragment_payload_size; + } + + int last_payload_size = packet_buf + pkt_size - packet_bufX; + memcpy (dataX, packet_bufX, last_payload_size); + pkthdr->fragment_nr = htonl (frag_cnt); + //jack_log("last fragment_count = %d, payload_size = %d\n", fragment_count, last_payload_size); + + // sendto(last_pack_size); + err = sendto(sockfd, tx_packet, last_payload_size + sizeof(jacknet_packet_header), flags, addr, addr_size); + if( err<0 ) { + //printf( "error in send\n" ); + perror( "send" ); + } + } +} + + +void +decode_midi_buffer (uint32_t *buffer_uint32, unsigned int buffer_size_uint32, jack_default_audio_sample_t* buf) +{ + int i; + jack_midi_clear_buffer (buf); + for (i = 0; i < buffer_size_uint32 - 3;) + { + uint32_t payload_size; + payload_size = buffer_uint32[i]; + payload_size = ntohl (payload_size); + if (payload_size) + { + jack_midi_event_t event; + event.time = ntohl (buffer_uint32[i+1]); + event.size = ntohl (buffer_uint32[i+2]); + event.buffer = (jack_midi_data_t*) (&(buffer_uint32[i+3])); + jack_midi_event_write (buf, event.time, event.buffer, event.size); + + // skip to the next event + unsigned int nb_data_quads = (((event.size-1) & ~0x3) >> 2)+1; + i += 3+nb_data_quads; + } + else + break; // no events can follow an empty event, we're done + } +} + +void +encode_midi_buffer (uint32_t *buffer_uint32, unsigned int buffer_size_uint32, jack_default_audio_sample_t* buf) +{ + int i; + unsigned int written = 0; + // midi port, encode midi events + unsigned int nevents = jack_midi_get_event_count (buf); + for (i = 0; i < nevents; ++i) + { + jack_midi_event_t event; + jack_midi_event_get (&event, buf, i); + unsigned int nb_data_quads = (((event.size - 1) & ~0x3) >> 2) + 1; + unsigned int payload_size = 3 + nb_data_quads; + // only write if we have sufficient space for the event + // otherwise drop it + if (written + payload_size < buffer_size_uint32 - 1) + { + // write header + buffer_uint32[written]=htonl (payload_size); + written++; + buffer_uint32[written]=htonl (event.time); + written++; + buffer_uint32[written]=htonl (event.size); + written++; + + // write data + jack_midi_data_t* tmpbuff = (jack_midi_data_t*)(&(buffer_uint32[written])); + memcpy (tmpbuff, event.buffer, event.size); + written += nb_data_quads; + } + else + { + // buffer overflow + jack_error ("midi buffer overflow"); + break; + } + } + // now put a netjack_midi 'no-payload' event, signaling EOF + buffer_uint32[written]=0; +} + +// render functions for float +void +render_payload_to_jack_ports_float ( void *packet_payload, jack_nframes_t net_period_down, JSList *capture_ports, JSList *capture_srcs, jack_nframes_t nframes, int dont_htonl_floats) +{ + int chn = 0; + JSList *node = capture_ports; +#if HAVE_SAMPLERATE + JSList *src_node = capture_srcs; +#endif + + uint32_t *packet_bufX = (uint32_t *)packet_payload; + + if( !packet_payload ) + return; + + while (node != NULL) + { + int i; + int_float_t val; +#if HAVE_SAMPLERATE + SRC_DATA src; +#endif + + jack_port_t *port = (jack_port_t *) node->data; + jack_default_audio_sample_t* buf = jack_port_get_buffer (port, nframes); + + const char *porttype = jack_port_type (port); + + if (strncmp (porttype, JACK_DEFAULT_AUDIO_TYPE, jack_port_type_size()) == 0) + { +#if HAVE_SAMPLERATE + // audio port, resample if necessary + if (net_period_down != nframes) + { + SRC_STATE *src_state = src_node->data; + for (i = 0; i < net_period_down; i++) + { + packet_bufX[i] = ntohl (packet_bufX[i]); + } + + src.data_in = (float *) packet_bufX; + src.input_frames = net_period_down; + + src.data_out = buf; + src.output_frames = nframes; + + src.src_ratio = (float) nframes / (float) net_period_down; + src.end_of_input = 0; + + src_set_ratio (src_state, src.src_ratio); + src_process (src_state, &src); + src_node = jack_slist_next (src_node); + } + else +#endif + { + if( dont_htonl_floats ) + { + memcpy( buf, packet_bufX, net_period_down*sizeof(jack_default_audio_sample_t)); + } + else + { + for (i = 0; i < net_period_down; i++) + { + val.i = packet_bufX[i]; + val.i = ntohl (val.i); + buf[i] = val.f; + } + } + } + } + else if (strncmp (porttype, JACK_DEFAULT_MIDI_TYPE, jack_port_type_size()) == 0) + { + // midi port, decode midi events + // convert the data buffer to a standard format (uint32_t based) + unsigned int buffer_size_uint32 = net_period_down; + uint32_t * buffer_uint32 = (uint32_t*)packet_bufX; + decode_midi_buffer (buffer_uint32, buffer_size_uint32, buf); + } + packet_bufX = (packet_bufX + net_period_down); + node = jack_slist_next (node); + chn++; + } +} + +void +render_jack_ports_to_payload_float (JSList *playback_ports, JSList *playback_srcs, jack_nframes_t nframes, void *packet_payload, jack_nframes_t net_period_up, int dont_htonl_floats ) +{ + int chn = 0; + JSList *node = playback_ports; +#if HAVE_SAMPLERATE + JSList *src_node = playback_srcs; +#endif + + uint32_t *packet_bufX = (uint32_t *) packet_payload; + + while (node != NULL) + { +#if HAVE_SAMPLERATE + SRC_DATA src; +#endif + int i; + int_float_t val; + jack_port_t *port = (jack_port_t *) node->data; + jack_default_audio_sample_t* buf = jack_port_get_buffer (port, nframes); + + const char *porttype = jack_port_type (port); + + if (strncmp (porttype, JACK_DEFAULT_AUDIO_TYPE, jack_port_type_size()) == 0) + { + // audio port, resample if necessary + +#if HAVE_SAMPLERATE + if (net_period_up != nframes) { + SRC_STATE *src_state = src_node->data; + src.data_in = buf; + src.input_frames = nframes; + + src.data_out = (float *) packet_bufX; + src.output_frames = net_period_up; + + src.src_ratio = (float) net_period_up / (float) nframes; + src.end_of_input = 0; + + src_set_ratio (src_state, src.src_ratio); + src_process (src_state, &src); + + for (i = 0; i < net_period_up; i++) + { + packet_bufX[i] = htonl (packet_bufX[i]); + } + src_node = jack_slist_next (src_node); + } + else +#endif + { + if( dont_htonl_floats ) + { + memcpy( packet_bufX, buf, net_period_up*sizeof(jack_default_audio_sample_t) ); + } + else + { + for (i = 0; i < net_period_up; i++) + { + val.f = buf[i]; + val.i = htonl (val.i); + packet_bufX[i] = val.i; + } + } + } + } + else if (strncmp(porttype, JACK_DEFAULT_MIDI_TYPE, jack_port_type_size()) == 0) + { + // encode midi events from port to packet + // convert the data buffer to a standard format (uint32_t based) + unsigned int buffer_size_uint32 = net_period_up; + uint32_t * buffer_uint32 = (uint32_t*) packet_bufX; + encode_midi_buffer (buffer_uint32, buffer_size_uint32, buf); + } + packet_bufX = (packet_bufX + net_period_up); + node = jack_slist_next (node); + chn++; + } +} + +// render functions for 16bit +void +render_payload_to_jack_ports_16bit (void *packet_payload, jack_nframes_t net_period_down, JSList *capture_ports, JSList *capture_srcs, jack_nframes_t nframes) +{ + int chn = 0; + JSList *node = capture_ports; +#if HAVE_SAMPLERATE + JSList *src_node = capture_srcs; +#endif + + uint16_t *packet_bufX = (uint16_t *)packet_payload; + + if( !packet_payload ) + return; + + while (node != NULL) + { + int i; + //uint32_t val; +#if HAVE_SAMPLERATE + SRC_DATA src; +#endif + + jack_port_t *port = (jack_port_t *) node->data; + jack_default_audio_sample_t* buf = jack_port_get_buffer (port, nframes); + +#if HAVE_SAMPLERATE + float *floatbuf = alloca (sizeof(float) * net_period_down); +#endif + const char *portname = jack_port_type (port); + + if (strncmp(portname, JACK_DEFAULT_AUDIO_TYPE, jack_port_type_size()) == 0) + { + // audio port, resample if necessary + +#if HAVE_SAMPLERATE + if (net_period_down != nframes) + { + SRC_STATE *src_state = src_node->data; + for (i = 0; i < net_period_down; i++) + { + floatbuf[i] = ((float) ntohs(packet_bufX[i])) / 32767.0 - 1.0; + } + + src.data_in = floatbuf; + src.input_frames = net_period_down; + + src.data_out = buf; + src.output_frames = nframes; + + src.src_ratio = (float) nframes / (float) net_period_down; + src.end_of_input = 0; + + src_set_ratio (src_state, src.src_ratio); + src_process (src_state, &src); + src_node = jack_slist_next (src_node); + } + else +#endif + for (i = 0; i < net_period_down; i++) + buf[i] = ((float) ntohs (packet_bufX[i])) / 32768.0 - 1.0; + } + else if (strncmp(portname, JACK_DEFAULT_MIDI_TYPE, jack_port_type_size()) == 0) + { + // midi port, decode midi events + // convert the data buffer to a standard format (uint32_t based) + unsigned int buffer_size_uint32 = net_period_down / 2; + uint32_t * buffer_uint32 = (uint32_t*) packet_bufX; + decode_midi_buffer (buffer_uint32, buffer_size_uint32, buf); + } + packet_bufX = (packet_bufX + net_period_down); + node = jack_slist_next (node); + chn++; + } +} + +void +render_jack_ports_to_payload_16bit (JSList *playback_ports, JSList *playback_srcs, jack_nframes_t nframes, void *packet_payload, jack_nframes_t net_period_up) +{ + int chn = 0; + JSList *node = playback_ports; +#if HAVE_SAMPLERATE + JSList *src_node = playback_srcs; +#endif + + uint16_t *packet_bufX = (uint16_t *)packet_payload; + + while (node != NULL) + { +#if HAVE_SAMPLERATE + SRC_DATA src; +#endif + int i; + jack_port_t *port = (jack_port_t *) node->data; + jack_default_audio_sample_t* buf = jack_port_get_buffer (port, nframes); + const char *portname = jack_port_type (port); + + if (strncmp (portname, JACK_DEFAULT_AUDIO_TYPE, jack_port_type_size()) == 0) + { + // audio port, resample if necessary + +#if HAVE_SAMPLERATE + if (net_period_up != nframes) + { + SRC_STATE *src_state = src_node->data; + + float *floatbuf = alloca (sizeof(float) * net_period_up); + + src.data_in = buf; + src.input_frames = nframes; + + src.data_out = floatbuf; + src.output_frames = net_period_up; + + src.src_ratio = (float) net_period_up / (float) nframes; + src.end_of_input = 0; + + src_set_ratio (src_state, src.src_ratio); + src_process (src_state, &src); + + for (i = 0; i < net_period_up; i++) + { + packet_bufX[i] = htons (((uint16_t)((floatbuf[i] + 1.0) * 32767.0))); + } + src_node = jack_slist_next (src_node); + } + else +#endif + for (i = 0; i < net_period_up; i++) + packet_bufX[i] = htons(((uint16_t)((buf[i] + 1.0) * 32767.0))); + } + else if (strncmp(portname, JACK_DEFAULT_MIDI_TYPE, jack_port_type_size()) == 0) + { + // encode midi events from port to packet + // convert the data buffer to a standard format (uint32_t based) + unsigned int buffer_size_uint32 = net_period_up / 2; + uint32_t * buffer_uint32 = (uint32_t*) packet_bufX; + encode_midi_buffer (buffer_uint32, buffer_size_uint32, buf); + } + packet_bufX = (packet_bufX + net_period_up); + node = jack_slist_next (node); + chn++; + } +} + +// render functions for 8bit +void +render_payload_to_jack_ports_8bit (void *packet_payload, jack_nframes_t net_period_down, JSList *capture_ports, JSList *capture_srcs, jack_nframes_t nframes) +{ + int chn = 0; + JSList *node = capture_ports; + +#if HAVE_SAMPLERATE + JSList *src_node = capture_srcs; +#endif + + int8_t *packet_bufX = (int8_t *)packet_payload; + + if( !packet_payload ) + return; + + while (node != NULL) + { + int i; + //uint32_t val; +#if HAVE_SAMPLERATE + SRC_DATA src; +#endif + + jack_port_t *port = (jack_port_t *) node->data; + jack_default_audio_sample_t* buf = jack_port_get_buffer (port, nframes); + +#if HAVE_SAMPLERATE + float *floatbuf = alloca (sizeof (float) * net_period_down); +#endif + const char *portname = jack_port_type (port); + + if (strncmp (portname, JACK_DEFAULT_AUDIO_TYPE, jack_port_type_size()) == 0) + { +#if HAVE_SAMPLERATE + // audio port, resample if necessary + if (net_period_down != nframes) + { + SRC_STATE *src_state = src_node->data; + for (i = 0; i < net_period_down; i++) + floatbuf[i] = ((float) packet_bufX[i]) / 127.0; + + src.data_in = floatbuf; + src.input_frames = net_period_down; + + src.data_out = buf; + src.output_frames = nframes; + + src.src_ratio = (float) nframes / (float) net_period_down; + src.end_of_input = 0; + + src_set_ratio (src_state, src.src_ratio); + src_process (src_state, &src); + src_node = jack_slist_next (src_node); + } + else +#endif + for (i = 0; i < net_period_down; i++) + buf[i] = ((float) packet_bufX[i]) / 127.0; + } + else if (strncmp(portname, JACK_DEFAULT_MIDI_TYPE, jack_port_type_size()) == 0) + { + // midi port, decode midi events + // convert the data buffer to a standard format (uint32_t based) + unsigned int buffer_size_uint32 = net_period_down / 2; + uint32_t * buffer_uint32 = (uint32_t*) packet_bufX; + decode_midi_buffer (buffer_uint32, buffer_size_uint32, buf); + } + packet_bufX = (packet_bufX + net_period_down); + node = jack_slist_next (node); + chn++; + } +} + +void +render_jack_ports_to_payload_8bit (JSList *playback_ports, JSList *playback_srcs, jack_nframes_t nframes, void *packet_payload, jack_nframes_t net_period_up) +{ + int chn = 0; + JSList *node = playback_ports; +#if HAVE_SAMPLERATE + JSList *src_node = playback_srcs; +#endif + + int8_t *packet_bufX = (int8_t *)packet_payload; + + while (node != NULL) + { +#if HAVE_SAMPLERATE + SRC_DATA src; +#endif + int i; + jack_port_t *port = (jack_port_t *) node->data; + + jack_default_audio_sample_t* buf = jack_port_get_buffer (port, nframes); + const char *portname = jack_port_type (port); + + if (strncmp (portname, JACK_DEFAULT_AUDIO_TYPE, jack_port_type_size()) == 0) + { +#if HAVE_SAMPLERATE + // audio port, resample if necessary + if (net_period_up != nframes) + { + + SRC_STATE *src_state = src_node->data; + + float *floatbuf = alloca (sizeof (float) * net_period_up); + + src.data_in = buf; + src.input_frames = nframes; + + src.data_out = floatbuf; + src.output_frames = net_period_up; + + src.src_ratio = (float) net_period_up / (float) nframes; + src.end_of_input = 0; + + src_set_ratio (src_state, src.src_ratio); + src_process (src_state, &src); + + for (i = 0; i < net_period_up; i++) + packet_bufX[i] = floatbuf[i] * 127.0; + src_node = jack_slist_next (src_node); + } + else +#endif + for (i = 0; i < net_period_up; i++) + packet_bufX[i] = buf[i] * 127.0; + } + else if (strncmp(portname, JACK_DEFAULT_MIDI_TYPE, jack_port_type_size()) == 0) + { + // encode midi events from port to packet + // convert the data buffer to a standard format (uint32_t based) + unsigned int buffer_size_uint32 = net_period_up / 4; + uint32_t * buffer_uint32 = (uint32_t*) packet_bufX; + encode_midi_buffer (buffer_uint32, buffer_size_uint32, buf); + } + packet_bufX = (packet_bufX + net_period_up); + node = jack_slist_next (node); + chn++; + } +} + +#if HAVE_CELT +// render functions for celt. +void +render_payload_to_jack_ports_celt (void *packet_payload, jack_nframes_t net_period_down, JSList *capture_ports, JSList *capture_srcs, jack_nframes_t nframes) +{ + int chn = 0; + JSList *node = capture_ports; + JSList *src_node = capture_srcs; + + unsigned char *packet_bufX = (unsigned char *)packet_payload; + + while (node != NULL) + { + jack_port_t *port = (jack_port_t *) node->data; + jack_default_audio_sample_t* buf = jack_port_get_buffer (port, nframes); + + const char *portname = jack_port_type (port); + + if (strncmp(portname, JACK_DEFAULT_AUDIO_TYPE, jack_port_type_size()) == 0) + { + // audio port, decode celt data. + + CELTDecoder *decoder = src_node->data; + if( !packet_payload ) + celt_decode_float( decoder, NULL, net_period_down, buf ); + else + celt_decode_float( decoder, packet_bufX, net_period_down, buf ); + + src_node = jack_slist_next (src_node); + } + else if (strncmp(portname, JACK_DEFAULT_MIDI_TYPE, jack_port_type_size()) == 0) + { + // midi port, decode midi events + // convert the data buffer to a standard format (uint32_t based) + unsigned int buffer_size_uint32 = net_period_down / 2; + uint32_t * buffer_uint32 = (uint32_t*) packet_bufX; + if( packet_payload ) + decode_midi_buffer (buffer_uint32, buffer_size_uint32, buf); + } + packet_bufX = (packet_bufX + net_period_down); + node = jack_slist_next (node); + chn++; + } +} + +void +render_jack_ports_to_payload_celt (JSList *playback_ports, JSList *playback_srcs, jack_nframes_t nframes, void *packet_payload, jack_nframes_t net_period_up) +{ + int chn = 0; + JSList *node = playback_ports; + JSList *src_node = playback_srcs; + + unsigned char *packet_bufX = (unsigned char *)packet_payload; + + while (node != NULL) + { + jack_port_t *port = (jack_port_t *) node->data; + jack_default_audio_sample_t* buf = jack_port_get_buffer (port, nframes); + const char *portname = jack_port_type (port); + + if (strncmp (portname, JACK_DEFAULT_AUDIO_TYPE, jack_port_type_size()) == 0) + { + // audio port, encode celt data. + + int encoded_bytes; + float *floatbuf = alloca (sizeof(float) * nframes ); + memcpy( floatbuf, buf, nframes*sizeof(float) ); + CELTEncoder *encoder = src_node->data; + encoded_bytes = celt_encode_float( encoder, floatbuf, NULL, packet_bufX, net_period_up ); + if( encoded_bytes != net_period_up ) + printf( "something in celt changed. netjack needs to be changed to handle this.\n" ); + src_node = jack_slist_next( src_node ); + } + else if (strncmp(portname, JACK_DEFAULT_MIDI_TYPE, jack_port_type_size()) == 0) + { + // encode midi events from port to packet + // convert the data buffer to a standard format (uint32_t based) + unsigned int buffer_size_uint32 = net_period_up / 2; + uint32_t * buffer_uint32 = (uint32_t*) packet_bufX; + encode_midi_buffer (buffer_uint32, buffer_size_uint32, buf); + } + packet_bufX = (packet_bufX + net_period_up); + node = jack_slist_next (node); + chn++; + } +} + +#endif +/* Wrapper functions with bitdepth argument... */ +void +render_payload_to_jack_ports (int bitdepth, void *packet_payload, jack_nframes_t net_period_down, JSList *capture_ports, JSList *capture_srcs, jack_nframes_t nframes, int dont_htonl_floats) +{ + if (bitdepth == 8) + render_payload_to_jack_ports_8bit (packet_payload, net_period_down, capture_ports, capture_srcs, nframes); + else if (bitdepth == 16) + render_payload_to_jack_ports_16bit (packet_payload, net_period_down, capture_ports, capture_srcs, nframes); +#if HAVE_CELT + else if (bitdepth == 1000) + render_payload_to_jack_ports_celt (packet_payload, net_period_down, capture_ports, capture_srcs, nframes); +#endif + else + render_payload_to_jack_ports_float (packet_payload, net_period_down, capture_ports, capture_srcs, nframes, dont_htonl_floats); +} + +void +render_jack_ports_to_payload (int bitdepth, JSList *playback_ports, JSList *playback_srcs, jack_nframes_t nframes, void *packet_payload, jack_nframes_t net_period_up, int dont_htonl_floats) +{ + if (bitdepth == 8) + render_jack_ports_to_payload_8bit (playback_ports, playback_srcs, nframes, packet_payload, net_period_up); + else if (bitdepth == 16) + render_jack_ports_to_payload_16bit (playback_ports, playback_srcs, nframes, packet_payload, net_period_up); +#if HAVE_CELT + else if (bitdepth == 1000) + render_jack_ports_to_payload_celt (playback_ports, playback_srcs, nframes, packet_payload, net_period_up); +#endif + else + render_jack_ports_to_payload_float (playback_ports, playback_srcs, nframes, packet_payload, net_period_up, dont_htonl_floats); +} diff --git a/common/netjack_packet.h b/common/netjack_packet.h new file mode 100644 index 00000000..7b21b0ee --- /dev/null +++ b/common/netjack_packet.h @@ -0,0 +1,162 @@ + +/* + * NetJack - Packet Handling functions + * + * used by the driver and the jacknet_client + * + * Copyright (C) 2006 Torben Hohn + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + * + * $Id: net_driver.c,v 1.16 2006/03/20 19:41:37 torbenh Exp $ + * + */ + +#ifndef __JACK_NET_PACKET_H__ +#define __JACK_NET_PACKET_H__ + +#ifdef __cplusplus + extern "C" + { +#endif + +#include +#include +//#include +#include + +#include + +//#include +// The Packet Header. + +typedef struct _jacknet_packet_header jacknet_packet_header; + +struct _jacknet_packet_header +{ + // General AutoConf Data + jack_nframes_t capture_channels_audio; + jack_nframes_t playback_channels_audio; + jack_nframes_t capture_channels_midi; + jack_nframes_t playback_channels_midi; + jack_nframes_t period_size; + jack_nframes_t sample_rate; + + // Transport Sync + jack_nframes_t sync_state; + jack_nframes_t transport_frame; + jack_nframes_t transport_state; + + // Packet loss Detection, and latency reduction + jack_nframes_t framecnt; + jack_nframes_t latency; + + jack_nframes_t reply_port; + jack_nframes_t mtu; + jack_nframes_t fragment_nr; +}; + +typedef union _int_float int_float_t; + +union _int_float +{ + uint32_t i; + float f; +}; + +// fragment reorder cache. +typedef struct _cache_packet cache_packet; + +struct _cache_packet +{ + int valid; + int num_fragments; + int packet_size; + int mtu; + jack_time_t recv_timestamp; + jack_nframes_t framecnt; + char * fragment_array; + char * packet_buf; +}; + +typedef struct _packet_cache packet_cache; + +struct _packet_cache +{ + int size; + cache_packet *packets; + int mtu; + struct sockaddr_in master_address; + int master_address_valid; + jack_nframes_t last_framecnt_retreived; + int last_framecnt_retreived_valid; +}; + +extern packet_cache *global_packcache; + +// fragment cache function prototypes +// XXX: Some of these are private. +packet_cache *packet_cache_new(int num_packets, int pkt_size, int mtu); +void packet_cache_free(packet_cache *pkt_cache); + +cache_packet *packet_cache_get_packet(packet_cache *pkt_cache, jack_nframes_t framecnt); +cache_packet *packet_cache_get_oldest_packet(packet_cache *pkt_cache); +cache_packet *packet_cache_get_free_packet(packet_cache *pkt_cache); + +void cache_packet_reset(cache_packet *pack); +void cache_packet_set_framecnt(cache_packet *pack, jack_nframes_t framecnt); +void cache_packet_add_fragment(cache_packet *pack, char *packet_buf, int rcv_len); +int cache_packet_is_complete(cache_packet *pack); + +void packet_cache_drain_socket( packet_cache *pcache, int sockfd ); +void packet_cache_reset_master_address( packet_cache *pcache ); +float packet_cache_get_fill( packet_cache *pcache, jack_nframes_t expected_framecnt ); +int packet_cache_retreive_packet_pointer( packet_cache *pcache, jack_nframes_t framecnt, char **packet_buf, int pkt_size, jack_time_t *timestamp ); +int packet_cache_release_packet( packet_cache *pcache, jack_nframes_t framecnt ); +int packet_cache_get_next_available_framecnt( packet_cache *pcache, jack_nframes_t expected_framecnt, jack_nframes_t *framecnt ); +int packet_cache_get_highest_available_framecnt( packet_cache *pcache, jack_nframes_t *framecnt ); +int packet_cache_find_latency( packet_cache *pcache, jack_nframes_t expected_framecnt, jack_nframes_t *framecnt ); +// Function Prototypes + +int netjack_poll_deadline (int sockfd, jack_time_t deadline); + +void netjack_sendto(int sockfd, char *packet_buf, int pkt_size, int flags, struct sockaddr *addr, int addr_size, int mtu); + + +int get_sample_size(int bitdepth); +void packet_header_hton(jacknet_packet_header *pkthdr); + +void packet_header_ntoh(jacknet_packet_header *pkthdr); + +void render_payload_to_jack_ports(int bitdepth, void *packet_payload, jack_nframes_t net_period_down, JSList *capture_ports, JSList *capture_srcs, jack_nframes_t nframes, int dont_htonl_floats ); + +void render_jack_ports_to_payload(int bitdepth, JSList *playback_ports, JSList *playback_srcs, jack_nframes_t nframes, void *packet_payload, jack_nframes_t net_period_up, int dont_htonl_floats ); + + +// XXX: This is sort of deprecated: +// This one waits forever. an is not using ppoll +int netjack_poll(int sockfd, int timeout); + +// TODO: these are deprecated. +//int netjack_recvfrom(int sockfd, char *packet_buf, int pkt_size, int flags, struct sockaddr *addr, socklen_t *addr_size, int mtu); +//int netjack_recv(int sockfd, char *packet_buf, int pkt_size, int flags, int mtu); + +void decode_midi_buffer (uint32_t *buffer_uint32, unsigned int buffer_size_uint32, jack_default_audio_sample_t* buf); +void encode_midi_buffer (uint32_t *buffer_uint32, unsigned int buffer_size_uint32, jack_default_audio_sample_t* buf); +#ifdef __cplusplus + } +#endif +#endif +