]> git.sesse.net Git - vlc/blob - src/misc/messages.c
30cb00455a526f714a1bf4338a0afb8bf9ac94e5
[vlc] / src / misc / messages.c
1 /*****************************************************************************
2  * messages.c: messages interface
3  * This library provides an interface to the message queue to be used by other
4  * modules, especially intf modules. See vlc_config.h for output configuration.
5  *****************************************************************************
6  * Copyright (C) 1998-2005 the VideoLAN team
7  * $Id$
8  *
9  * Authors: Vincent Seguin <seguin@via.ecp.fr>
10  *          Samuel Hocevar <sam@zoy.org>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25  *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30
31 #ifdef HAVE_CONFIG_H
32 # include "config.h"
33 #endif
34
35 #include <vlc_common.h>
36
37 #include <stdarg.h>                                       /* va_list for BSD */
38
39 #include <errno.h>                                                  /* errno */
40
41 #ifdef WIN32
42 #   include <vlc_network.h>          /* 'net_strerror' and 'WSAGetLastError' */
43 #endif
44
45 #ifdef HAVE_UNISTD_H
46 #   include <unistd.h>                                   /* close(), write() */
47 #endif
48
49 #include <assert.h>
50
51 #include <vlc_charset.h>
52 #include "../libvlc.h"
53
54 typedef struct
55 {
56     int i_code;
57     char * psz_message;
58 } msg_context_t;
59
60 static void cleanup_msg_context (void *data)
61 {
62     msg_context_t *ctx = data;
63     free (ctx->psz_message);
64     free (ctx);
65 }
66
67 static vlc_threadvar_t msg_context;
68 static uintptr_t banks = 0;
69
70 /*****************************************************************************
71  * Local macros
72  *****************************************************************************/
73 #if defined(HAVE_VA_COPY)
74 #   define vlc_va_copy(dest,src) va_copy(dest,src)
75 #elif defined(HAVE___VA_COPY)
76 #   define vlc_va_copy(dest,src) __va_copy(dest,src)
77 #else
78 #   define vlc_va_copy(dest,src) (dest)=(src)
79 #endif
80
81 #define QUEUE priv->msg_bank
82 static inline msg_bank_t *libvlc_bank (libvlc_int_t *inst)
83 {
84     return &(libvlc_priv (inst))->msg_bank;
85 }
86
87 /*****************************************************************************
88  * Local prototypes
89  *****************************************************************************/
90 static void QueueMsg ( vlc_object_t *, int, const char *,
91                        const char *, va_list );
92 static void PrintMsg ( vlc_object_t *, msg_item_t * );
93
94 static vlc_mutex_t msg_stack_lock = VLC_STATIC_MUTEX;
95
96 /**
97  * Initialize messages queues
98  * This function initializes all message queues
99  */
100 void msg_Create (libvlc_int_t *p_libvlc)
101 {
102     libvlc_priv_t *priv = libvlc_priv (p_libvlc);
103     msg_bank_t *bank = libvlc_bank (p_libvlc);
104
105     vlc_rwlock_init (&bank->lock);
106     vlc_dictionary_init( &priv->msg_enabled_objects, 0 );
107     priv->msg_all_objects_enabled = true;
108
109     QUEUE.i_sub = 0;
110     QUEUE.pp_sub = NULL;
111
112 #ifdef UNDER_CE
113     QUEUE.logfile =
114         CreateFile( L"vlc-log.txt", GENERIC_WRITE,
115                     FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
116                     CREATE_ALWAYS, 0, NULL );
117     SetFilePointer( QUEUE.logfile, 0, NULL, FILE_END );
118 #endif
119
120     vlc_mutex_lock( &msg_stack_lock );
121     if( banks++ == 0 )
122         vlc_threadvar_create( &msg_context, cleanup_msg_context );
123     vlc_mutex_unlock( &msg_stack_lock );
124 }
125
126 /**
127  * Object Printing selection
128  */
129 static void const * kObjectPrintingEnabled = &kObjectPrintingEnabled;
130 static void const * kObjectPrintingDisabled = &kObjectPrintingDisabled;
131
132 void __msg_EnableObjectPrinting (vlc_object_t *p_this, const char * psz_object)
133 {
134     libvlc_priv_t *priv = libvlc_priv (p_this->p_libvlc);
135     vlc_rwlock_wrlock( &QUEUE.lock );
136     if( !strcmp(psz_object, "all") )
137         priv->msg_all_objects_enabled = true;
138     else
139         vlc_dictionary_insert( &priv->msg_enabled_objects, psz_object, (void *)kObjectPrintingEnabled );
140     vlc_rwlock_unlock( &QUEUE.lock );
141 }
142
143 void __msg_DisableObjectPrinting (vlc_object_t *p_this, const char * psz_object)
144 {
145     libvlc_priv_t *priv = libvlc_priv (p_this->p_libvlc);
146     vlc_rwlock_wrlock( &QUEUE.lock );
147     if( !strcmp(psz_object, "all") )
148         priv->msg_all_objects_enabled = false;
149     else
150         vlc_dictionary_insert( &priv->msg_enabled_objects, psz_object, (void *)kObjectPrintingDisabled );
151     vlc_rwlock_unlock( &QUEUE.lock );
152 }
153
154 /**
155  * Destroy the message queues
156  *
157  * This functions prints all messages remaining in the queues,
158  * then frees all the allocated resources
159  * No other messages interface functions should be called after this one.
160  */
161 void msg_Destroy (libvlc_int_t *p_libvlc)
162 {
163     libvlc_priv_t *priv = libvlc_priv (p_libvlc);
164     msg_bank_t *bank = libvlc_bank (p_libvlc);
165
166     if( QUEUE.i_sub )
167         msg_Err( p_libvlc, "stale interface subscribers (VLC might crash)" );
168
169     vlc_mutex_lock( &msg_stack_lock );
170     assert(banks > 0);
171     if( --banks == 0 )
172         vlc_threadvar_delete( &msg_context );
173     vlc_mutex_unlock( &msg_stack_lock );
174
175 #ifdef UNDER_CE
176     CloseHandle( QUEUE.logfile );
177 #endif
178
179     vlc_dictionary_clear( &priv->msg_enabled_objects, NULL, NULL );
180
181     vlc_rwlock_destroy (&bank->lock);
182 }
183
184 struct msg_subscription_t
185 {
186     libvlc_int_t   *instance;
187     msg_callback_t  func;
188     msg_cb_data_t  *opaque;
189 };
190
191 /**
192  * Subscribe to the message queue.
193  * Whenever a message is emitted, a callback will be called.
194  * Callback invocation are serialized within a subscription.
195  *
196  * @param instance LibVLC instance to get messages from
197  * @param cb callback function
198  * @param opaque data for the callback function
199  * @return a subscription pointer, or NULL in case of failure
200  */
201 msg_subscription_t *msg_Subscribe (libvlc_int_t *instance, msg_callback_t cb,
202                                    msg_cb_data_t *opaque)
203 {
204     msg_subscription_t *sub = malloc (sizeof (*sub));
205     if (sub == NULL)
206         return NULL;
207
208     sub->instance = instance;
209     sub->func = cb;
210     sub->opaque = opaque;
211
212     msg_bank_t *bank = libvlc_bank (instance);
213     vlc_rwlock_wrlock (&bank->lock);
214     TAB_APPEND (bank->i_sub, bank->pp_sub, sub);
215     vlc_rwlock_unlock (&bank->lock);
216
217     return sub;
218 }
219
220 /**
221  * Unsubscribe from the message queue.
222  * This function waits for the message callback to return if needed.
223  */
224 void msg_Unsubscribe (msg_subscription_t *sub)
225 {
226     msg_bank_t *bank = libvlc_bank (sub->instance);
227
228     vlc_rwlock_wrlock (&bank->lock);
229     TAB_REMOVE (bank->i_sub, bank->pp_sub, sub);
230     vlc_rwlock_unlock (&bank->lock);
231     free (sub);
232 }
233
234 /*****************************************************************************
235  * __msg_*: print a message
236  *****************************************************************************
237  * These functions queue a message for later printing.
238  *****************************************************************************/
239 void __msg_Generic( vlc_object_t *p_this, int i_type, const char *psz_module,
240                     const char *psz_format, ... )
241 {
242     va_list args;
243
244     va_start( args, psz_format );
245     QueueMsg( p_this, i_type, psz_module, psz_format, args );
246     va_end( args );
247 }
248
249 void __msg_GenericVa( vlc_object_t *p_this, int i_type, const char *psz_module,
250                       const char *psz_format, va_list args )
251 {
252     QueueMsg( p_this, i_type, psz_module, psz_format, args );
253 }
254
255 /**
256  * Destroys a message.
257  */
258 static void msg_Free (gc_object_t *gc)
259 {
260     msg_item_t *msg = vlc_priv (gc, msg_item_t);
261
262     free (msg->psz_module);
263     free (msg->psz_msg);
264     free (msg->psz_header);
265     free (msg);
266 }
267
268 /**
269  * Add a message to a queue
270  *
271  * This function provides basic functionnalities to other msg_* functions.
272  * It adds a message to a queue (after having printed all stored messages if it
273  * is full). If the message can't be converted to string in memory, it issues
274  * a warning.
275  */
276 static void QueueMsg( vlc_object_t *p_this, int i_type, const char *psz_module,
277                       const char *psz_format, va_list _args )
278 {
279     assert (p_this);
280     libvlc_priv_t *priv = libvlc_priv (p_this->p_libvlc);
281     int         i_header_size;             /* Size of the additionnal header */
282     vlc_object_t *p_obj;
283     char *       psz_str = NULL;                 /* formatted message string */
284     char *       psz_header = NULL;
285     va_list      args;
286
287     if( p_this->i_flags & OBJECT_FLAGS_QUIET ||
288         (p_this->i_flags & OBJECT_FLAGS_NODBG && i_type == VLC_MSG_DBG) )
289         return;
290
291 #ifndef __GLIBC__
292     /* Expand %m to strerror(errno) - only once */
293     char buf[strlen( psz_format ) + 2001], *ptr;
294     strcpy( buf, psz_format );
295     ptr = (char*)buf;
296     psz_format = (const char*) buf;
297
298     for( ;; )
299     {
300         ptr = strchr( ptr, '%' );
301         if( ptr == NULL )
302             break;
303
304         if( ptr[1] == 'm' )
305         {
306             char errbuf[2001];
307             size_t errlen;
308
309 #ifndef WIN32
310             strerror_r( errno, errbuf, 1001 );
311 #else
312             int sockerr = WSAGetLastError( );
313             if( sockerr )
314             {
315                 strncpy( errbuf, net_strerror( sockerr ), 1001 );
316                 WSASetLastError( sockerr );
317             }
318             if ((sockerr == 0)
319              || (strcmp ("Unknown network stack error", errbuf) == 0))
320                 strncpy( errbuf, strerror( errno ), 1001 );
321 #endif
322             errbuf[1000] = 0;
323
324             /* Escape '%' from the error string */
325             for( char *percent = strchr( errbuf, '%' );
326                  percent != NULL;
327                  percent = strchr( percent + 2, '%' ) )
328             {
329                 memmove( percent + 1, percent, strlen( percent ) + 1 );
330             }
331
332             errlen = strlen( errbuf );
333             memmove( ptr + errlen, ptr + 2, strlen( ptr + 2 ) + 1 );
334             memcpy( ptr, errbuf, errlen );
335             break; /* Only once, so we don't overflow */
336         }
337
338         /* Looks for conversion specifier... */
339         do
340             ptr++;
341         while( *ptr && ( strchr( "diouxXeEfFgGaAcspn%", *ptr ) == NULL ) );
342         if( *ptr )
343             ptr++; /* ...and skip it */
344     }
345 #endif
346
347     /* Convert message to string  */
348     vlc_va_copy( args, _args );
349     if( vasprintf( &psz_str, psz_format, args ) == -1 )
350         psz_str = NULL;
351     va_end( args );
352
353     if( psz_str == NULL )
354     {
355         int canc = vlc_savecancel (); /* Do not print half of a message... */
356 #ifdef __GLIBC__
357         fprintf( stderr, "main warning: can't store message (%m): " );
358 #else
359         char psz_err[1001];
360 #ifndef WIN32
361         /* we're not using GLIBC, so we are sure that the error description
362          * will be stored in the buffer we provide to strerror_r() */
363         strerror_r( errno, psz_err, 1001 );
364 #else
365         strncpy( psz_err, strerror( errno ), 1001 );
366 #endif
367         psz_err[1000] = '\0';
368         fprintf( stderr, "main warning: can't store message (%s): ", psz_err );
369 #endif
370         vlc_va_copy( args, _args );
371         /* We should use utf8_vfprintf - but it calls malloc()... */
372         vfprintf( stderr, psz_format, args );
373         va_end( args );
374         fputs( "\n", stderr );
375         vlc_restorecancel (canc);
376         return;
377     }
378
379     msg_item_t * p_item = malloc (sizeof (*p_item));
380     if (p_item == NULL)
381         return; /* Uho! */
382
383     vlc_gc_init (p_item, msg_Free);
384     p_item->psz_module = p_item->psz_msg = p_item->psz_header = NULL;
385
386
387
388     i_header_size = 0;
389     p_obj = p_this;
390     while( p_obj != NULL )
391     {
392         char *psz_old = NULL;
393         if( p_obj->psz_header )
394         {
395             i_header_size += strlen( p_obj->psz_header ) + 4;
396             if( psz_header )
397             {
398                 psz_old = strdup( psz_header );
399                 psz_header = xrealloc( psz_header, i_header_size );
400                 snprintf( psz_header, i_header_size , "[%s] %s",
401                           p_obj->psz_header, psz_old );
402             }
403             else
404             {
405                 psz_header = xmalloc( i_header_size );
406                 snprintf( psz_header, i_header_size, "[%s]",
407                           p_obj->psz_header );
408             }
409         }
410         free( psz_old );
411         p_obj = p_obj->p_parent;
412     }
413
414     /* Fill message information fields */
415     p_item->i_type =        i_type;
416     p_item->i_object_id =   (uintptr_t)p_this;
417     p_item->psz_object_type = p_this->psz_object_type;
418     p_item->psz_module =    strdup( psz_module );
419     p_item->psz_msg =       psz_str;
420     p_item->psz_header =    psz_header;
421
422     PrintMsg( p_this, p_item );
423
424     msg_bank_t *bank = &QUEUE;
425     vlc_rwlock_rdlock (&bank->lock);
426     for (int i = 0; i < bank->i_sub; i++)
427     {
428         msg_subscription_t *sub = bank->pp_sub[i];
429         sub->func (sub->opaque, p_item, 0);
430     }
431     vlc_rwlock_unlock (&bank->lock);
432     msg_Release (p_item);
433 }
434
435 /*****************************************************************************
436  * PrintMsg: output a standard message item to stderr
437  *****************************************************************************
438  * Print a message to stderr, with colour formatting if needed.
439  *****************************************************************************/
440 static void PrintMsg ( vlc_object_t * p_this, msg_item_t * p_item )
441 {
442 #   define COL(x)  "\033[" #x ";1m"
443 #   define RED     COL(31)
444 #   define GREEN   COL(32)
445 #   define YELLOW  COL(33)
446 #   define WHITE   COL(0)
447 #   define GRAY    "\033[0m"
448
449 #ifdef UNDER_CE
450     int i_dummy;
451 #endif
452     static const char ppsz_type[4][9] = { "", " error", " warning", " debug" };
453     static const char ppsz_color[4][8] = { WHITE, RED, YELLOW, GRAY };
454     const char *psz_object;
455     libvlc_priv_t *priv = libvlc_priv (p_this->p_libvlc);
456     int i_type = p_item->i_type;
457
458     switch( i_type )
459     {
460         case VLC_MSG_ERR:
461             if( priv->i_verbose < 0 ) return;
462             break;
463         case VLC_MSG_INFO:
464             if( priv->i_verbose < 0 ) return;
465             break;
466         case VLC_MSG_WARN:
467             if( priv->i_verbose < 1 ) return;
468             break;
469         case VLC_MSG_DBG:
470             if( priv->i_verbose < 2 ) return;
471             break;
472     }
473
474     psz_object = p_item->psz_object_type;
475     void * val = vlc_dictionary_value_for_key( &priv->msg_enabled_objects,
476                                                p_item->psz_module );
477     if( val == kObjectPrintingDisabled )
478         return;
479     if( val == kObjectPrintingEnabled )
480         /* Allowed */;
481     else
482     {
483         val = vlc_dictionary_value_for_key( &priv->msg_enabled_objects,
484                                             psz_object );
485         if( val == kObjectPrintingDisabled )
486             return;
487         if( val == kObjectPrintingEnabled )
488             /* Allowed */;
489         else if( !priv->msg_all_objects_enabled )
490             return;
491     }
492
493 #ifdef UNDER_CE
494 #   define CE_WRITE(str) WriteFile( QUEUE.logfile, \
495                                     str, strlen(str), &i_dummy, NULL );
496     CE_WRITE( p_item->psz_module );
497     CE_WRITE( " " );
498     CE_WRITE( psz_object );
499     CE_WRITE( ppsz_type[i_type] );
500     CE_WRITE( ": " );
501     CE_WRITE( p_item->psz_msg );
502     CE_WRITE( "\r\n" );
503     FlushFileBuffers( QUEUE.logfile );
504
505 #else
506     int canc = vlc_savecancel ();
507     /* Send the message to stderr */
508     utf8_fprintf( stderr, "[%s%p%s] %s%s%s %s%s: %s%s%s\n",
509                   priv->b_color ? GREEN : "",
510                   (void *)p_item->i_object_id,
511                   priv->b_color ? GRAY : "",
512                   p_item->psz_header ? p_item->psz_header : "",
513                   p_item->psz_header ? " " : "",
514                   p_item->psz_module, psz_object,
515                   ppsz_type[i_type],
516                   priv->b_color ? ppsz_color[i_type] : "",
517                   p_item->psz_msg,
518                   priv->b_color ? GRAY : "" );
519
520 #   if defined(WIN32)
521     fflush( stderr );
522 #   endif
523     vlc_restorecancel (canc);
524 #endif
525 }
526
527 static msg_context_t* GetContext(void)
528 {
529     msg_context_t *p_ctx = vlc_threadvar_get( msg_context );
530     if( p_ctx == NULL )
531     {
532         p_ctx = malloc( sizeof( msg_context_t ) );
533         if( !p_ctx )
534             return NULL;
535         p_ctx->psz_message = NULL;
536         vlc_threadvar_set( msg_context, p_ctx );
537     }
538     return p_ctx;
539 }
540
541 void msg_StackDestroy (void *data)
542 {
543     msg_context_t *p_ctx = data;
544
545     free (p_ctx->psz_message);
546     free (p_ctx);
547 }
548
549 void msg_StackSet( int i_code, const char *psz_message, ... )
550 {
551     va_list ap;
552     msg_context_t *p_ctx = GetContext();
553
554     if( p_ctx == NULL )
555         return;
556     free( p_ctx->psz_message );
557
558     va_start( ap, psz_message );
559     if( vasprintf( &p_ctx->psz_message, psz_message, ap ) == -1 )
560         p_ctx->psz_message = NULL;
561     va_end( ap );
562
563     p_ctx->i_code = i_code;
564 }
565
566 void msg_StackAdd( const char *psz_message, ... )
567 {
568     char *psz_tmp;
569     va_list ap;
570     msg_context_t *p_ctx = GetContext();
571
572     if( p_ctx == NULL )
573         return;
574
575     va_start( ap, psz_message );
576     if( vasprintf( &psz_tmp, psz_message, ap ) == -1 )
577         psz_tmp = NULL;
578     va_end( ap );
579
580     if( !p_ctx->psz_message )
581         p_ctx->psz_message = psz_tmp;
582     else
583     {
584         char *psz_new;
585         if( asprintf( &psz_new, "%s: %s", psz_tmp, p_ctx->psz_message ) == -1 )
586             psz_new = NULL;
587
588         free( p_ctx->psz_message );
589         p_ctx->psz_message = psz_new;
590         free( psz_tmp );
591     }
592 }
593
594 const char* msg_StackMsg( void )
595 {
596     msg_context_t *p_ctx = GetContext();
597     assert( p_ctx );
598     return p_ctx->psz_message;
599 }