1 /*****************************************************************************
2  * jack.c : JACK audio output module
3  *****************************************************************************
4  * Copyright (C) 2006 VLC authors and VideoLAN
5  * $Id: 5710fed72d0c4872b106961190e4ee35dfe1f7d2 $
6  *
7  * Authors: Cyril Deguet <asmax _at_ videolan.org>
8  *          Jon Griffiths <jon_p_griffiths _At_ yahoo _DOT_ com>
9  *
10  * This program is free software; you can redistribute it and/or modify it
11  * under the terms of the GNU Lesser General Public License as published by
12  * the Free Software Foundation; either version 2.1 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with this program; if not, write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24 /**
25  * \file modules/audio_output/jack.c
26  * \brief JACK audio output functions
27  */
28 /*****************************************************************************
29  * Preamble
30  *****************************************************************************/
31 
32 #ifdef HAVE_CONFIG_H
33 # include "config.h"
34 #endif
35 
36 #include <vlc_common.h>
37 #include <vlc_plugin.h>
38 #include <vlc_aout.h>
39 
40 #include <jack/jack.h>
41 #include <jack/ringbuffer.h>
42 
43 #include <stdio.h>
44 #include <unistd.h>                                      /* write(), close() */
45 
46 typedef jack_default_audio_sample_t jack_sample_t;
47 
48 /*****************************************************************************
49  * aout_sys_t: JACK audio output method descriptor
50  *****************************************************************************
51  * This structure is part of the audio output thread descriptor.
52  * It describes some JACK specific variables.
53  *****************************************************************************/
54 struct aout_sys_t
55 {
56     jack_ringbuffer_t *p_jack_ringbuffer;
57     jack_client_t  *p_jack_client;
58     jack_port_t   **p_jack_ports;
59     jack_sample_t **p_jack_buffers;
60     unsigned int    i_channels;
61     unsigned int    i_rate;
62     jack_nframes_t latency;
63     float soft_gain;
64     bool soft_mute;
65     mtime_t paused; /**< Time when (last) paused */
66 };
67 
68 /*****************************************************************************
69  * Local prototypes
70  *****************************************************************************/
71 static int  Open         ( vlc_object_t * );
72 static void Close        ( vlc_object_t * );
73 static void Play         ( audio_output_t * p_aout, block_t * p_block );
74 static void Pause        ( audio_output_t *aout, bool paused, mtime_t date );
75 static void Flush        ( audio_output_t *p_aout, bool wait );
76 static int  TimeGet      ( audio_output_t *, mtime_t * );
77 static int  Process      ( jack_nframes_t i_frames, void *p_arg );
78 static int  GraphChange  ( void *p_arg );
79 
80 #include "audio_output/volume.h"
81 
82 #define AUTO_CONNECT_OPTION "jack-auto-connect"
83 #define AUTO_CONNECT_TEXT N_("Automatically connect to writable clients")
84 #define AUTO_CONNECT_LONGTEXT N_( \
85     "If enabled, this option will automatically connect sound output to the " \
86     "first writable JACK clients found." )
87 
88 #define CONNECT_REGEX_OPTION "jack-connect-regex"
89 #define CONNECT_REGEX_TEXT N_("Connect to clients matching")
90 #define CONNECT_REGEX_LONGTEXT N_( \
91     "If automatic connection is enabled, only JACK clients whose names " \
92     "match this regular expression will be considered for connection." )
93 
94 #define JACK_NAME_TEXT N_( "JACK client name" )
95 
96 /*****************************************************************************
97  * Module descriptor
98  *****************************************************************************/
99 vlc_module_begin ()
100     set_shortname( "JACK" )
101     set_description( N_("JACK audio output") )
102     set_capability( "audio output", 100 )
set_category(CAT_AUDIO)103     set_category( CAT_AUDIO )
104     set_subcategory( SUBCAT_AUDIO_AOUT )
105     add_bool( AUTO_CONNECT_OPTION, true, AUTO_CONNECT_TEXT,
106               AUTO_CONNECT_LONGTEXT, false )
107     add_string( CONNECT_REGEX_OPTION, "system", CONNECT_REGEX_TEXT,
108                 CONNECT_REGEX_LONGTEXT, false )
109     add_string( "jack-name", "", JACK_NAME_TEXT, JACK_NAME_TEXT, false)
110 
111     add_sw_gain( )
112     set_callbacks( Open, Close )
113 vlc_module_end ()
114 
115 
116 static int Start( audio_output_t *p_aout, audio_sample_format_t *restrict fmt )
117 {
118     char *psz_name;
119     struct aout_sys_t *p_sys = p_aout->sys;
120     int status = VLC_SUCCESS;
121     unsigned int i;
122     int i_error;
123 
124     if( aout_FormatNbChannels( fmt ) == 0 )
125         return VLC_EGENERIC;
126 
127     p_sys->latency = 0;
128     p_sys->paused = VLC_TS_INVALID;
129 
130     /* Connect to the JACK server */
131     psz_name = var_InheritString( p_aout, "jack-name" );
132     if( !psz_name || !*psz_name )
133     {
134         free( psz_name );
135         if( asprintf( &psz_name, "vlc_%d", getpid()) == -1 )
136             return VLC_ENOMEM;
137     }
138 
139     p_sys->p_jack_client = jack_client_open( psz_name,
140                                              JackNullOption | JackNoStartServer,
141                                              NULL );
142     if( p_sys->p_jack_client == NULL )
143     {
144         msg_Err( p_aout, "failed to connect to JACK server" );
145         status = VLC_EGENERIC;
146         goto error_out;
147     }
148 
149     /* Set the process callback */
150     jack_set_process_callback( p_sys->p_jack_client, Process, p_aout );
151     jack_set_graph_order_callback ( p_sys->p_jack_client, GraphChange, p_aout );
152 
153     /* JACK only supports fl32 format */
154     fmt->i_format = VLC_CODEC_FL32;
155     // TODO add buffer size callback
156     p_sys->i_rate = fmt->i_rate = jack_get_sample_rate( p_sys->p_jack_client );
157 
158     p_aout->play = Play;
159     p_aout->pause = Pause;
160     p_aout->flush = Flush;
161     p_aout->time_get = TimeGet;
162     aout_SoftVolumeStart( p_aout );
163 
164     p_sys->i_channels = aout_FormatNbChannels( fmt );
165     aout_FormatPrepare(fmt);
166 
167     p_sys->p_jack_ports = malloc( p_sys->i_channels *
168                                   sizeof(jack_port_t *) );
169     if( p_sys->p_jack_ports == NULL )
170     {
171         status = VLC_ENOMEM;
172         goto error_out;
173     }
174 
175     p_sys->p_jack_buffers = malloc( p_sys->i_channels *
176                                     sizeof(jack_sample_t *) );
177     if( p_sys->p_jack_buffers == NULL )
178     {
179         status = VLC_ENOMEM;
180         goto error_out;
181     }
182 
183     const size_t buf_sz = AOUT_MAX_ADVANCE_TIME * fmt->i_rate *
184         fmt->i_bytes_per_frame / CLOCK_FREQ;
185     p_sys->p_jack_ringbuffer = jack_ringbuffer_create( buf_sz );
186 
187     if( p_sys->p_jack_ringbuffer == NULL )
188     {
189         status = VLC_ENOMEM;
190         goto error_out;
191     }
192 
193     if( jack_ringbuffer_mlock( p_sys->p_jack_ringbuffer ))
194     {
195         msg_Warn( p_aout, "failed to lock JACK ringbuffer in memory" );
196     }
197 
198     /* Create the output ports */
199     for( i = 0; i < p_sys->i_channels; i++ )
200     {
201         char *psz_name_output;
202         if( asprintf( &psz_name_output, "%s_out_%d", psz_name, i + 1) != -1 )
203         {
204             p_sys->p_jack_ports[i] = jack_port_register( p_sys->p_jack_client,
205                     psz_name_output, JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0 );
206             free( psz_name_output );
207         }
208 
209         if( p_sys->p_jack_ports[i] == NULL )
210         {
211             msg_Err( p_aout, "failed to register a JACK port" );
212             status = VLC_EGENERIC;
213             goto error_out;
214         }
215     }
216 
217     /* Tell the JACK server we are ready */
218     i_error = jack_activate( p_sys->p_jack_client );
219     if( i_error )
220     {
221         msg_Err( p_aout, "failed to activate JACK client (error %d)", i_error );
222         status = VLC_EGENERIC;
223         goto error_out;
224     }
225 
226     /* Auto connect ports if we were asked to */
227     if( var_InheritBool( p_aout, AUTO_CONNECT_OPTION ) )
228     {
229         unsigned int i_in_ports;
230         char *psz_regex = var_InheritString( p_aout, CONNECT_REGEX_OPTION );
231         const char **pp_in_ports = jack_get_ports( p_sys->p_jack_client,
232                                                    psz_regex, NULL,
233                                                    JackPortIsInput );
234         free( psz_regex );
235         /* Count the number of returned ports */
236         i_in_ports = 0;
237         while( pp_in_ports && pp_in_ports[i_in_ports] )
238         {
239             i_in_ports++;
240         }
241 
242         /* Tie the output ports to JACK input ports */
243         for( i = 0; i_in_ports > 0 && i < p_sys->i_channels; i++ )
244         {
245             const char* psz_in = pp_in_ports[i % i_in_ports];
246             const char* psz_out = jack_port_name( p_sys->p_jack_ports[i] );
247 
248             i_error = jack_connect( p_sys->p_jack_client, psz_out, psz_in );
249             if( i_error )
250             {
251                 msg_Err( p_aout, "failed to connect port %s to port %s (error %d)",
252                          psz_out, psz_in, i_error );
253             }
254             else
255             {
256                 msg_Dbg( p_aout, "connecting port %s to port %s",
257                          psz_out, psz_in );
258             }
259         }
260         free( pp_in_ports );
261     }
262 
263     msg_Dbg( p_aout, "JACK audio output initialized (%d channels, rate=%d)",
264              p_sys->i_channels, fmt->i_rate );
265     fmt->channel_type = AUDIO_CHANNEL_TYPE_BITMAP;
266 
267 error_out:
268     /* Clean up, if an error occurred */
269     if( status != VLC_SUCCESS )
270     {
271         if( p_sys->p_jack_client )
272         {
273             jack_deactivate( p_sys->p_jack_client );
274             jack_client_close( p_sys->p_jack_client );
275         }
276         if( p_sys->p_jack_ringbuffer )
277             jack_ringbuffer_free( p_sys->p_jack_ringbuffer );
278 
279         free( p_sys->p_jack_ports );
280         free( p_sys->p_jack_buffers );
281     }
282     free( psz_name );
283     return status;
284 }
285 
Play(audio_output_t * p_aout,block_t * p_block)286 static void Play (audio_output_t * p_aout, block_t * p_block)
287 {
288     struct aout_sys_t *p_sys = p_aout->sys;
289     jack_ringbuffer_t *rb = p_sys->p_jack_ringbuffer;
290     const size_t bytes_per_frame = p_sys->i_channels * sizeof(jack_sample_t);
291 
292     while (p_block->i_buffer > 0) {
293 
294         /* move data to buffer */
295         const size_t write_space = jack_ringbuffer_write_space(rb);
296         const size_t bytes = p_block->i_buffer < write_space ?
297             p_block->i_buffer : write_space;
298 
299         /* If our audio thread is not reading fast enough */
300         if( unlikely( bytes == 0 ) ) {
301             msg_Warn( p_aout, "%"PRIuPTR " frames of audio dropped",
302                     p_block->i_buffer /  bytes_per_frame );
303             break;
304         }
305 
306         jack_ringbuffer_write( rb, (const char *) p_block->p_buffer, bytes );
307 
308         p_block->p_buffer += bytes;
309         p_block->i_buffer -= bytes;
310     }
311 
312     block_Release(p_block);
313 }
314 
315 /**
316  * Pause or unpause playback
317  */
Pause(audio_output_t * aout,bool paused,mtime_t date)318 static void Pause(audio_output_t *aout, bool paused, mtime_t date)
319 {
320     aout_sys_t *sys = aout->sys;
321 
322     if( paused ) {
323         sys->paused = date;
324     } else {
325         date -= sys->paused;
326         msg_Dbg(aout, "resuming after %"PRId64" us", date);
327         sys->paused = VLC_TS_INVALID;
328     }
329 }
330 
Flush(audio_output_t * p_aout,bool wait)331 static void Flush(audio_output_t *p_aout, bool wait)
332 {
333     struct aout_sys_t * p_sys = p_aout->sys;
334     jack_ringbuffer_t *rb = p_sys->p_jack_ringbuffer;
335 
336     /* Sleep if wait was requested */
337     if( wait )
338     {
339         mtime_t delay;
340         if (!TimeGet(p_aout, &delay))
341             msleep(delay);
342     }
343 
344     /* reset ringbuffer read and write pointers */
345     jack_ringbuffer_reset(rb);
346 }
347 
TimeGet(audio_output_t * p_aout,mtime_t * delay)348 static int TimeGet(audio_output_t *p_aout, mtime_t *delay)
349 {
350     struct aout_sys_t * p_sys = p_aout->sys;
351     jack_ringbuffer_t *rb = p_sys->p_jack_ringbuffer;
352     const size_t bytes_per_frame = p_sys->i_channels * sizeof(jack_sample_t);
353 
354     *delay = (p_sys->latency +
355             (jack_ringbuffer_read_space(rb) / bytes_per_frame)) *
356         CLOCK_FREQ / p_sys->i_rate;
357 
358     return 0;
359 }
360 
361 /*****************************************************************************
362  * Process: callback for JACK
363  *****************************************************************************/
Process(jack_nframes_t i_frames,void * p_arg)364 int Process( jack_nframes_t i_frames, void *p_arg )
365 {
366     unsigned int i, j, frames_from_rb = 0;
367     size_t bytes_read = 0;
368     size_t frames_read;
369     audio_output_t *p_aout = (audio_output_t*) p_arg;
370     struct aout_sys_t *p_sys = p_aout->sys;
371 
372     /* Get the next audio data buffer unless paused */
373 
374     if( p_sys->paused == VLC_TS_INVALID )
375         frames_from_rb = i_frames;
376 
377     /* Get the JACK buffers to write to */
378     for( i = 0; i < p_sys->i_channels; i++ )
379     {
380         p_sys->p_jack_buffers[i] = jack_port_get_buffer( p_sys->p_jack_ports[i],
381                                                          i_frames );
382     }
383 
384     /* Copy in the audio data */
385     for( j = 0; j < frames_from_rb; j++ )
386     {
387         for( i = 0; i < p_sys->i_channels; i++ )
388         {
389             jack_sample_t *p_dst = p_sys->p_jack_buffers[i] + j;
390             bytes_read += jack_ringbuffer_read( p_sys->p_jack_ringbuffer,
391                     (char *) p_dst, sizeof(jack_sample_t) );
392         }
393     }
394 
395     /* Fill any remaining buffer with silence */
396     frames_read = (bytes_read / sizeof(jack_sample_t)) / p_sys->i_channels;
397     if( frames_read < i_frames )
398     {
399         for( i = 0; i < p_sys->i_channels; i++ )
400         {
401             memset( p_sys->p_jack_buffers[i] + frames_read, 0,
402                     sizeof( jack_sample_t ) * (i_frames - frames_read) );
403         }
404     }
405 
406     return 0;
407 }
408 
409 /*****************************************************************************
410  * GraphChange: callback when JACK reorders it's process graph.
411                 We update latency information.
412  *****************************************************************************/
413 
GraphChange(void * p_arg)414 static int GraphChange( void *p_arg )
415 {
416   audio_output_t *p_aout = (audio_output_t*) p_arg;
417   struct aout_sys_t *p_sys = p_aout->sys;
418   unsigned int i;
419   jack_latency_range_t port_latency;
420 
421   p_sys->latency = 0;
422 
423   for( i = 0; i < p_sys->i_channels; ++i )
424   {
425     jack_port_get_latency_range( p_sys->p_jack_ports[i], JackPlaybackLatency,
426                                  &port_latency );
427     p_sys->latency = __MAX( p_sys->latency, port_latency.max );
428   }
429 
430   msg_Dbg(p_aout, "JACK graph reordered. Our maximum latency=%d.",
431           p_sys->latency);
432 
433   return 0;
434 }
435 
436 /*****************************************************************************
437  * Close: close the JACK client
438  *****************************************************************************/
Stop(audio_output_t * p_aout)439 static void Stop( audio_output_t *p_aout )
440 {
441     int i_error;
442     struct aout_sys_t *p_sys = p_aout->sys;
443 
444     i_error = jack_deactivate( p_sys->p_jack_client );
445     if( i_error )
446     {
447         msg_Err( p_aout, "jack_deactivate failed (error %d)", i_error );
448     }
449 
450     i_error = jack_client_close( p_sys->p_jack_client );
451     if( i_error )
452     {
453         msg_Err( p_aout, "jack_client_close failed (error %d)", i_error );
454     }
455     free( p_sys->p_jack_ports );
456     free( p_sys->p_jack_buffers );
457     jack_ringbuffer_free( p_sys->p_jack_ringbuffer );
458 }
459 
Open(vlc_object_t * obj)460 static int Open(vlc_object_t *obj)
461 {
462     audio_output_t *aout = (audio_output_t *)obj;
463     aout_sys_t *sys = calloc(1, sizeof (*sys));
464 
465     if( unlikely( sys == NULL ) )
466         return VLC_ENOMEM;
467     aout->sys = sys;
468     aout->start = Start;
469     aout->stop = Stop;
470     aout_SoftVolumeInit(aout);
471     return VLC_SUCCESS;
472 }
473 
Close(vlc_object_t * obj)474 static void Close(vlc_object_t *obj)
475 {
476     audio_output_t *aout = (audio_output_t *)obj;
477     aout_sys_t *sys = aout->sys;
478 
479     free(sys);
480 }
481