array: fix up types in vlc_array_*()
[vlc.git] / modules / misc / fingerprinter.c
1 /*****************************************************************************
2  * fingerprinter.c: Audio fingerprinter module
3  *****************************************************************************
4  * Copyright (C) 2012 VLC authors and VideoLAN
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU Lesser General Public License as published by
8  * the Free Software Foundation; either version 2.1 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
19  *****************************************************************************/
20 #ifdef HAVE_CONFIG_H
21 # include "config.h"
22 #endif
23
24 #include <assert.h>
25
26 #include <vlc_common.h>
27 #include <vlc_plugin.h>
28 #include <vlc_stream.h>
29 #include <vlc_modules.h>
30 #include <vlc_meta.h>
31 #include <vlc_url.h>
32
33 #include <vlc/vlc.h>
34 #include <vlc_input.h>
35 #include <vlc_fingerprinter.h>
36 #include "webservices/acoustid.h"
37 #include "../stream_out/chromaprint_data.h"
38
39 /*****************************************************************************
40  * Local prototypes
41  *****************************************************************************/
42
43 struct fingerprinter_sys_t
44 {
45     vlc_thread_t thread;
46
47     struct
48     {
49         vlc_array_t         *queue;
50         vlc_mutex_t         lock;
51     } incoming, results;
52
53     struct
54     {
55         vlc_array_t         *queue;
56         vlc_mutex_t         lock;
57         vlc_cond_t          cond;
58         bool                b_working;
59     } processing;
60 };
61
62 static int  Open            (vlc_object_t *);
63 static void Close           (vlc_object_t *);
64 static void CleanSys        (fingerprinter_sys_t *);
65 static void *Run(void *);
66
67 /*****************************************************************************
68  * Module descriptor
69  ****************************************************************************/
70 vlc_module_begin ()
71     set_category(CAT_ADVANCED)
72     set_subcategory(SUBCAT_ADVANCED_MISC)
73     set_shortname(N_("acoustid"))
74     set_description(N_("Track fingerprinter (based on Acoustid)"))
75     set_capability("fingerprinter", 10)
76     set_callbacks(Open, Close)
77 vlc_module_end ()
78
79 /*****************************************************************************
80  * Requests lifecycle
81  *****************************************************************************/
82
83 static void EnqueueRequest( fingerprinter_thread_t *f, fingerprint_request_t *r )
84 {
85     fingerprinter_sys_t *p_sys = f->p_sys;
86     vlc_mutex_lock( &p_sys->incoming.lock );
87     vlc_array_append( p_sys->incoming.queue, r );
88     vlc_mutex_unlock( &p_sys->incoming.lock );
89 }
90
91 static void QueueIncomingRequests( fingerprinter_sys_t *p_sys )
92 {
93     vlc_mutex_lock( &p_sys->incoming.lock );
94     size_t i = vlc_array_count( p_sys->incoming.queue );
95     if ( i == 0 ) goto end;
96     while( i )
97         vlc_array_append( p_sys->processing.queue,
98                           vlc_array_item_at_index( p_sys->incoming.queue, --i ) );
99     vlc_array_clear( p_sys->incoming.queue );
100 end:
101     vlc_mutex_unlock(&p_sys->incoming.lock);
102 }
103
104 static fingerprint_request_t * GetResult( fingerprinter_thread_t *f )
105 {
106     fingerprint_request_t *r = NULL;
107     fingerprinter_sys_t *p_sys = f->p_sys;
108     vlc_mutex_lock( &p_sys->results.lock );
109     if ( vlc_array_count( p_sys->results.queue ) )
110     {
111         r = vlc_array_item_at_index( p_sys->results.queue, 0 );
112         vlc_array_remove( p_sys->results.queue, 0 );
113     }
114     vlc_mutex_unlock( &p_sys->results.lock );
115     return r;
116 }
117
118 static void ApplyResult( fingerprint_request_t *p_r, int i_resultid )
119 {
120     if ( i_resultid >= vlc_array_count( & p_r->results.metas_array ) ) return;
121
122     vlc_meta_t *p_meta = (vlc_meta_t *)
123             vlc_array_item_at_index( & p_r->results.metas_array, i_resultid );
124     input_item_t *p_item = p_r->p_item;
125     vlc_mutex_lock( &p_item->lock );
126     vlc_meta_Merge( p_item->p_meta, p_meta );
127     vlc_mutex_unlock( &p_item->lock );
128 }
129
130 static int InputEventHandler( vlc_object_t *p_this, char const *psz_cmd,
131                               vlc_value_t oldval, vlc_value_t newval,
132                               void *p_data )
133 {
134     VLC_UNUSED( psz_cmd );
135     VLC_UNUSED( oldval );
136     input_thread_t *p_input = (input_thread_t *) p_this;
137     fingerprinter_sys_t *p_sys = (fingerprinter_sys_t *) p_data;
138     if( newval.i_int == INPUT_EVENT_STATE )
139     {
140         if( var_GetInteger( p_input, "state" ) >= PAUSE_S )
141         {
142             vlc_mutex_lock( &p_sys->processing.lock );
143             p_sys->processing.b_working = false;
144             vlc_cond_signal( &p_sys->processing.cond );
145             vlc_mutex_unlock( &p_sys->processing.lock );
146         }
147     }
148     return VLC_SUCCESS;
149 }
150
151 static void DoFingerprint( fingerprinter_thread_t *p_fingerprinter,
152                            acoustid_fingerprint_t *fp,
153                            const char *psz_uri )
154 {
155     input_item_t *p_item = input_item_New( NULL, NULL );
156     if ( unlikely(p_item == NULL) )
157          return;
158
159     char *psz_sout_option;
160     /* Note: need at -max- 2 channels, but we can't guess it before playing */
161     /* the stereo upmix could make the mono tracks fingerprint to differ :/ */
162     if ( asprintf( &psz_sout_option,
163                    "sout=#transcode{acodec=%s,channels=2}:chromaprint",
164                    ( VLC_CODEC_S16L == VLC_CODEC_S16N ) ? "s16l" : "s16b" )
165          == -1 )
166     {
167         input_item_Release( p_item );
168         return;
169     }
170
171     input_item_AddOption( p_item, psz_sout_option, VLC_INPUT_OPTION_TRUSTED );
172     free( psz_sout_option );
173     input_item_AddOption( p_item, "vout=dummy", VLC_INPUT_OPTION_TRUSTED );
174     input_item_AddOption( p_item, "aout=dummy", VLC_INPUT_OPTION_TRUSTED );
175     if ( fp->i_duration )
176     {
177         if ( asprintf( &psz_sout_option, "stop-time=%u", fp->i_duration ) == -1 )
178         {
179             input_item_Release( p_item );
180             return;
181         }
182         input_item_AddOption( p_item, psz_sout_option, VLC_INPUT_OPTION_TRUSTED );
183         free( psz_sout_option );
184     }
185     input_item_SetURI( p_item, psz_uri ) ;
186
187     input_thread_t *p_input = input_Create( p_fingerprinter, p_item, "fingerprinter", NULL );
188     input_item_Release( p_item );
189
190     if( p_input == NULL )
191         return;
192
193     chromaprint_fingerprint_t chroma_fingerprint;
194
195     chroma_fingerprint.psz_fingerprint = NULL;
196     chroma_fingerprint.i_duration = fp->i_duration;
197
198     var_Create( p_input, "fingerprint-data", VLC_VAR_ADDRESS );
199     var_SetAddress( p_input, "fingerprint-data", &chroma_fingerprint );
200
201     var_AddCallback( p_input, "intf-event", InputEventHandler, p_fingerprinter->p_sys );
202
203     if( input_Start( p_input ) != VLC_SUCCESS )
204     {
205         var_DelCallback( p_input, "intf-event", InputEventHandler, p_fingerprinter->p_sys );
206         input_Close( p_input );
207     }
208     else
209     {
210         p_fingerprinter->p_sys->processing.b_working = true;
211         while( p_fingerprinter->p_sys->processing.b_working )
212         {
213             vlc_cond_wait( &p_fingerprinter->p_sys->processing.cond,
214                            &p_fingerprinter->p_sys->processing.lock );
215         }
216         var_DelCallback( p_input, "intf-event", InputEventHandler, p_fingerprinter->p_sys );
217         input_Stop( p_input );
218         input_Close( p_input );
219
220         fp->psz_fingerprint = chroma_fingerprint.psz_fingerprint;
221         if( !fp->i_duration ) /* had not given hint */
222             fp->i_duration = chroma_fingerprint.i_duration;
223     }
224 }
225
226 /*****************************************************************************
227  * Open:
228  *****************************************************************************/
229 static int Open(vlc_object_t *p_this)
230 {
231     fingerprinter_thread_t *p_fingerprinter = (fingerprinter_thread_t*) p_this;
232     fingerprinter_sys_t *p_sys = calloc(1, sizeof(fingerprinter_sys_t));
233
234     if ( !p_sys )
235         return VLC_ENOMEM;
236
237     p_fingerprinter->p_sys = p_sys;
238
239     p_sys->incoming.queue = vlc_array_new();
240     vlc_mutex_init( &p_sys->incoming.lock );
241
242     p_sys->processing.queue = vlc_array_new();
243     vlc_mutex_init( &p_sys->processing.lock );
244     vlc_cond_init( &p_sys->processing.cond );
245
246     p_sys->results.queue = vlc_array_new();
247     vlc_mutex_init( &p_sys->results.lock );
248
249     p_fingerprinter->pf_enqueue = EnqueueRequest;
250     p_fingerprinter->pf_getresults = GetResult;
251     p_fingerprinter->pf_apply = ApplyResult;
252
253     var_Create( p_fingerprinter, "results-available", VLC_VAR_BOOL );
254     if( vlc_clone( &p_sys->thread, Run, p_fingerprinter,
255                    VLC_THREAD_PRIORITY_LOW ) )
256     {
257         msg_Err( p_fingerprinter, "cannot spawn fingerprinter thread" );
258         goto error;
259     }
260
261     return VLC_SUCCESS;
262
263 error:
264     CleanSys( p_sys );
265     free( p_sys );
266     return VLC_EGENERIC;
267 }
268
269 /*****************************************************************************
270  * Close:
271  *****************************************************************************/
272 static void Close(vlc_object_t *p_this)
273 {
274     fingerprinter_thread_t   *p_fingerprinter = (fingerprinter_thread_t*) p_this;
275     fingerprinter_sys_t *p_sys = p_fingerprinter->p_sys;
276
277     vlc_cancel( p_sys->thread );
278     vlc_join( p_sys->thread, NULL );
279
280     CleanSys( p_sys );
281     free( p_sys );
282 }
283
284 static void CleanSys( fingerprinter_sys_t *p_sys )
285 {
286     for ( int i = 0; i < vlc_array_count( p_sys->incoming.queue ); i++ )
287         fingerprint_request_Delete( vlc_array_item_at_index( p_sys->incoming.queue, i ) );
288     vlc_array_destroy( p_sys->incoming.queue );
289     vlc_mutex_destroy( &p_sys->incoming.lock );
290
291     for ( int i = 0; i < vlc_array_count( p_sys->processing.queue ); i++ )
292         fingerprint_request_Delete( vlc_array_item_at_index( p_sys->processing.queue, i ) );
293     vlc_array_destroy( p_sys->processing.queue );
294     vlc_mutex_destroy( &p_sys->processing.lock );
295     vlc_cond_destroy( &p_sys->processing.cond );
296
297     for ( int i = 0; i < vlc_array_count( p_sys->results.queue ); i++ )
298         fingerprint_request_Delete( vlc_array_item_at_index( p_sys->results.queue, i ) );
299     vlc_array_destroy( p_sys->results.queue );
300     vlc_mutex_destroy( &p_sys->results.lock );
301 }
302
303 static void fill_metas_with_results( fingerprint_request_t *p_r, acoustid_fingerprint_t *p_f )
304 {
305     for( unsigned int i=0 ; i < p_f->results.count; i++ )
306     {
307         acoustid_result_t *p_result = & p_f->results.p_results[ i ];
308         for ( unsigned int j=0 ; j < p_result->recordings.count; j++ )
309         {
310             musicbrainz_recording_t *p_record = & p_result->recordings.p_recordings[ j ];
311             vlc_meta_t *p_meta = vlc_meta_New();
312             if ( p_meta )
313             {
314                 vlc_meta_Set( p_meta, vlc_meta_Title, p_record->psz_title );
315                 vlc_meta_Set( p_meta, vlc_meta_Artist, p_record->psz_artist );
316                 vlc_meta_AddExtra( p_meta, "musicbrainz-id", p_record->s_musicbrainz_id );
317                 vlc_array_append( & p_r->results.metas_array, p_meta );
318             }
319         }
320     }
321 }
322
323 /*****************************************************************************
324  * Run :
325  *****************************************************************************/
326 static void *Run( void *opaque )
327 {
328     fingerprinter_thread_t *p_fingerprinter = opaque;
329     fingerprinter_sys_t *p_sys = p_fingerprinter->p_sys;
330
331     vlc_mutex_lock( &p_sys->processing.lock );
332     mutex_cleanup_push( &p_sys->processing.lock );
333
334     /* main loop */
335     for (;;)
336     {
337         msleep( CLOCK_FREQ );
338
339         QueueIncomingRequests( p_sys );
340
341         vlc_testcancel();
342
343         for ( int i = 0 ; i < vlc_array_count( p_sys->processing.queue ); i++ )
344         {
345             int canc = vlc_savecancel();
346             fingerprint_request_t *p_data = vlc_array_item_at_index( p_sys->processing.queue, i );
347
348             char *psz_uri = input_item_GetURI( p_data->p_item );
349             if ( psz_uri != NULL )
350             {
351                  acoustid_fingerprint_t acoustid_print;
352
353                  memset( &acoustid_print , 0, sizeof (acoustid_print) );
354                 /* overwrite with hint, as in this case, fingerprint's session will be truncated */
355                 if ( p_data->i_duration )
356                      acoustid_print.i_duration = p_data->i_duration;
357
358                 DoFingerprint( p_fingerprinter, &acoustid_print, psz_uri );
359                 free( psz_uri );
360
361                 DoAcoustIdWebRequest( VLC_OBJECT(p_fingerprinter), &acoustid_print );
362                 fill_metas_with_results( p_data, &acoustid_print );
363
364                 for( unsigned j = 0; j < acoustid_print.results.count; j++ )
365                      free_acoustid_result_t( &acoustid_print.results.p_results[j] );
366                 if( acoustid_print.results.count )
367                     free( acoustid_print.results.p_results );
368                 free( acoustid_print.psz_fingerprint );
369             }
370             vlc_restorecancel(canc);
371
372             /* copy results */
373             vlc_mutex_lock( &p_sys->results.lock );
374             vlc_array_append( p_sys->results.queue, p_data );
375             vlc_mutex_unlock( &p_sys->results.lock );
376
377             vlc_testcancel();
378         }
379
380         if ( vlc_array_count( p_sys->processing.queue ) )
381         {
382             var_TriggerCallback( p_fingerprinter, "results-available" );
383             vlc_array_clear( p_sys->processing.queue );
384         }
385     }
386
387     vlc_cleanup_pop();
388     vlc_assert_unreachable();
389 }