]> git.sesse.net Git - vlc/blob - src/misc/messages.c
Hide message bank layout and cleanup a bit
[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 #include <locale.h>
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  * Store all data required by messages interfaces.
98  */
99 struct msg_bank_t
100 {
101     /** Message queue lock */
102     vlc_rwlock_t lock;
103
104     /* Subscribers */
105     int i_sub;
106     msg_subscription_t **pp_sub;
107
108     /* Logfile for WinCE */
109 #ifdef UNDER_CE
110     FILE *logfile;
111 #endif
112
113     locale_t locale; /**< C locale for error messages */
114     vlc_dictionary_t enabled_objects; ///< Enabled objects
115     bool all_objects_enabled; ///< Should we print all objects?
116 };
117
118 /**
119  * Initialize messages queues
120  * This function initializes all message queues
121  */
122 msg_bank_t *msg_Create (void)
123 {
124     msg_bank_t *bank = malloc (sizeof (*bank));
125
126     vlc_rwlock_init (&bank->lock);
127     vlc_dictionary_init (&bank->enabled_objects, 0);
128     bank->all_objects_enabled = true;
129
130     bank->i_sub = 0;
131     bank->pp_sub = NULL;
132
133     /* C locale to get error messages in English in the logs */
134     bank->locale = newlocale (LC_MESSAGES_MASK, "C", (locale_t)0);
135
136 #ifdef UNDER_CE
137     QUEUE.logfile =
138         CreateFile( L"vlc-log.txt", GENERIC_WRITE,
139                     FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
140                     CREATE_ALWAYS, 0, NULL );
141     SetFilePointer( QUEUE.logfile, 0, NULL, FILE_END );
142 #endif
143
144     vlc_mutex_lock( &msg_stack_lock );
145     if( banks++ == 0 )
146         vlc_threadvar_create( &msg_context, cleanup_msg_context );
147     vlc_mutex_unlock( &msg_stack_lock );
148     return bank;
149 }
150
151 /**
152  * Object Printing selection
153  */
154 static void const * kObjectPrintingEnabled = &kObjectPrintingEnabled;
155 static void const * kObjectPrintingDisabled = &kObjectPrintingDisabled;
156
157 #undef msg_EnableObjectPrinting
158 void msg_EnableObjectPrinting (vlc_object_t *obj, const char * psz_object)
159 {
160     msg_bank_t *bank = libvlc_bank (obj->p_libvlc);
161
162     vlc_rwlock_wrlock (&bank->lock);
163     if( !strcmp(psz_object, "all") )
164         bank->all_objects_enabled = true;
165     else
166         vlc_dictionary_insert (&bank->enabled_objects, psz_object,
167                                (void *)kObjectPrintingEnabled);
168     vlc_rwlock_unlock (&bank->lock);
169 }
170
171 #undef msg_DisableObjectPrinting
172 void msg_DisableObjectPrinting (vlc_object_t *obj, const char * psz_object)
173 {
174     msg_bank_t *bank = libvlc_bank (obj->p_libvlc);
175
176     vlc_rwlock_wrlock (&bank->lock);
177     if( !strcmp(psz_object, "all") )
178         bank->all_objects_enabled = false;
179     else
180         vlc_dictionary_insert (&bank->enabled_objects, psz_object,
181                                (void *)kObjectPrintingDisabled);
182     vlc_rwlock_unlock (&bank->lock);
183 }
184
185 /**
186  * Destroy the message queues
187  *
188  * This functions prints all messages remaining in the queues,
189  * then frees all the allocated resources
190  * No other messages interface functions should be called after this one.
191  */
192 void msg_Destroy (msg_bank_t *bank)
193 {
194     if (unlikely(bank->i_sub != 0))
195         fputs ("stale interface subscribers (LibVLC might crash)\n", stderr);
196
197     vlc_mutex_lock( &msg_stack_lock );
198     assert(banks > 0);
199     if( --banks == 0 )
200         vlc_threadvar_delete( &msg_context );
201     vlc_mutex_unlock( &msg_stack_lock );
202
203 #ifdef UNDER_CE
204     CloseHandle( QUEUE.logfile );
205 #endif
206     if (bank->locale != (locale_t)0)
207        freelocale (bank->locale);
208
209     vlc_dictionary_clear (&bank->enabled_objects, NULL, NULL);
210
211     vlc_rwlock_destroy (&bank->lock);
212     free (bank);
213 }
214
215 struct msg_subscription_t
216 {
217     libvlc_int_t   *instance;
218     msg_callback_t  func;
219     msg_cb_data_t  *opaque;
220 };
221
222 /**
223  * Subscribe to the message queue.
224  * Whenever a message is emitted, a callback will be called.
225  * Callback invocation are serialized within a subscription.
226  *
227  * @param instance LibVLC instance to get messages from
228  * @param cb callback function
229  * @param opaque data for the callback function
230  * @return a subscription pointer, or NULL in case of failure
231  */
232 msg_subscription_t *msg_Subscribe (libvlc_int_t *instance, msg_callback_t cb,
233                                    msg_cb_data_t *opaque)
234 {
235     msg_subscription_t *sub = malloc (sizeof (*sub));
236     if (sub == NULL)
237         return NULL;
238
239     sub->instance = instance;
240     sub->func = cb;
241     sub->opaque = opaque;
242
243     msg_bank_t *bank = libvlc_bank (instance);
244     vlc_rwlock_wrlock (&bank->lock);
245     TAB_APPEND (bank->i_sub, bank->pp_sub, sub);
246     vlc_rwlock_unlock (&bank->lock);
247
248     return sub;
249 }
250
251 /**
252  * Unsubscribe from the message queue.
253  * This function waits for the message callback to return if needed.
254  */
255 void msg_Unsubscribe (msg_subscription_t *sub)
256 {
257     msg_bank_t *bank = libvlc_bank (sub->instance);
258
259     vlc_rwlock_wrlock (&bank->lock);
260     TAB_REMOVE (bank->i_sub, bank->pp_sub, sub);
261     vlc_rwlock_unlock (&bank->lock);
262     free (sub);
263 }
264
265 /*****************************************************************************
266  * __msg_*: print a message
267  *****************************************************************************
268  * These functions queue a message for later printing.
269  *****************************************************************************/
270 void __msg_Generic( vlc_object_t *p_this, int i_type, const char *psz_module,
271                     const char *psz_format, ... )
272 {
273     va_list args;
274
275     va_start( args, psz_format );
276     QueueMsg( p_this, i_type, psz_module, psz_format, args );
277     va_end( args );
278 }
279
280 void __msg_GenericVa( vlc_object_t *p_this, int i_type, const char *psz_module,
281                       const char *psz_format, va_list args )
282 {
283     QueueMsg( p_this, i_type, psz_module, psz_format, args );
284 }
285
286 /**
287  * Destroys a message.
288  */
289 static void msg_Free (gc_object_t *gc)
290 {
291     msg_item_t *msg = vlc_priv (gc, msg_item_t);
292
293     free (msg->psz_module);
294     free (msg->psz_msg);
295     free (msg->psz_header);
296     free (msg);
297 }
298
299 /**
300  * Add a message to a queue
301  *
302  * This function provides basic functionnalities to other msg_* functions.
303  * It adds a message to a queue (after having printed all stored messages if it
304  * is full). If the message can't be converted to string in memory, it issues
305  * a warning.
306  */
307 static void QueueMsg( vlc_object_t *p_this, int i_type, const char *psz_module,
308                       const char *psz_format, va_list _args )
309 {
310     size_t      i_header_size;             /* Size of the additionnal header */
311     vlc_object_t *p_obj;
312     char *       psz_str = NULL;                 /* formatted message string */
313     char *       psz_header = NULL;
314     va_list      args;
315
316     assert (p_this);
317
318     if( p_this->i_flags & OBJECT_FLAGS_QUIET ||
319         (p_this->i_flags & OBJECT_FLAGS_NODBG && i_type == VLC_MSG_DBG) )
320         return;
321
322     msg_bank_t *bank = libvlc_bank (p_this->p_libvlc);
323     locale_t locale = uselocale (bank->locale);
324
325 #ifndef __GLIBC__
326     /* Expand %m to strerror(errno) - only once */
327     char buf[strlen( psz_format ) + 2001], *ptr;
328     strcpy( buf, psz_format );
329     ptr = (char*)buf;
330     psz_format = (const char*) buf;
331
332     for( ;; )
333     {
334         ptr = strchr( ptr, '%' );
335         if( ptr == NULL )
336             break;
337
338         if( ptr[1] == 'm' )
339         {
340             char errbuf[2001];
341             size_t errlen;
342
343 #ifndef WIN32
344             strerror_r( errno, errbuf, 1001 );
345 #else
346             int sockerr = WSAGetLastError( );
347             if( sockerr )
348             {
349                 strncpy( errbuf, net_strerror( sockerr ), 1001 );
350                 WSASetLastError( sockerr );
351             }
352             if ((sockerr == 0)
353              || (strcmp ("Unknown network stack error", errbuf) == 0))
354                 strncpy( errbuf, strerror( errno ), 1001 );
355 #endif
356             errbuf[1000] = 0;
357
358             /* Escape '%' from the error string */
359             for( char *percent = strchr( errbuf, '%' );
360                  percent != NULL;
361                  percent = strchr( percent + 2, '%' ) )
362             {
363                 memmove( percent + 1, percent, strlen( percent ) + 1 );
364             }
365
366             errlen = strlen( errbuf );
367             memmove( ptr + errlen, ptr + 2, strlen( ptr + 2 ) + 1 );
368             memcpy( ptr, errbuf, errlen );
369             break; /* Only once, so we don't overflow */
370         }
371
372         /* Looks for conversion specifier... */
373         do
374             ptr++;
375         while( *ptr && ( strchr( "diouxXeEfFgGaAcspn%", *ptr ) == NULL ) );
376         if( *ptr )
377             ptr++; /* ...and skip it */
378     }
379 #endif
380
381     /* Convert message to string  */
382     vlc_va_copy( args, _args );
383     if( vasprintf( &psz_str, psz_format, args ) == -1 )
384         psz_str = NULL;
385     va_end( args );
386
387     if( psz_str == NULL )
388     {
389         int canc = vlc_savecancel (); /* Do not print half of a message... */
390 #ifdef __GLIBC__
391         fprintf( stderr, "main warning: can't store message (%m): " );
392 #else
393         char psz_err[1001];
394 #ifndef WIN32
395         /* we're not using GLIBC, so we are sure that the error description
396          * will be stored in the buffer we provide to strerror_r() */
397         strerror_r( errno, psz_err, 1001 );
398 #else
399         strncpy( psz_err, strerror( errno ), 1001 );
400 #endif
401         psz_err[1000] = '\0';
402         fprintf( stderr, "main warning: can't store message (%s): ", psz_err );
403 #endif
404         vlc_va_copy( args, _args );
405         /* We should use utf8_vfprintf - but it calls malloc()... */
406         vfprintf( stderr, psz_format, args );
407         va_end( args );
408         fputs( "\n", stderr );
409         vlc_restorecancel (canc);
410         uselocale (locale);
411         return;
412     }
413     uselocale (locale);
414
415     msg_item_t * p_item = malloc (sizeof (*p_item));
416     if (p_item == NULL)
417         return; /* Uho! */
418
419     vlc_gc_init (p_item, msg_Free);
420     p_item->psz_module = p_item->psz_msg = p_item->psz_header = NULL;
421
422
423
424     i_header_size = 0;
425     p_obj = p_this;
426     while( p_obj != NULL )
427     {
428         char *psz_old = NULL;
429         if( p_obj->psz_header )
430         {
431             i_header_size += strlen( p_obj->psz_header ) + 4;
432             if( psz_header )
433             {
434                 psz_old = strdup( psz_header );
435                 psz_header = xrealloc( psz_header, i_header_size );
436                 snprintf( psz_header, i_header_size , "[%s] %s",
437                           p_obj->psz_header, psz_old );
438             }
439             else
440             {
441                 psz_header = xmalloc( i_header_size );
442                 snprintf( psz_header, i_header_size, "[%s]",
443                           p_obj->psz_header );
444             }
445         }
446         free( psz_old );
447         p_obj = p_obj->p_parent;
448     }
449
450     /* Fill message information fields */
451     p_item->i_type =        i_type;
452     p_item->i_object_id =   (uintptr_t)p_this;
453     p_item->psz_object_type = p_this->psz_object_type;
454     p_item->psz_module =    strdup( psz_module );
455     p_item->psz_msg =       psz_str;
456     p_item->psz_header =    psz_header;
457
458     PrintMsg( p_this, p_item );
459
460     vlc_rwlock_rdlock (&bank->lock);
461     for (int i = 0; i < bank->i_sub; i++)
462     {
463         msg_subscription_t *sub = bank->pp_sub[i];
464         sub->func (sub->opaque, p_item, 0);
465     }
466     vlc_rwlock_unlock (&bank->lock);
467     msg_Release (p_item);
468 }
469
470 /*****************************************************************************
471  * PrintMsg: output a standard message item to stderr
472  *****************************************************************************
473  * Print a message to stderr, with colour formatting if needed.
474  *****************************************************************************/
475 static void PrintMsg ( vlc_object_t * p_this, msg_item_t * p_item )
476 {
477 #   define COL(x)  "\033[" #x ";1m"
478 #   define RED     COL(31)
479 #   define GREEN   COL(32)
480 #   define YELLOW  COL(33)
481 #   define WHITE   COL(0)
482 #   define GRAY    "\033[0m"
483
484 #ifdef UNDER_CE
485     int i_dummy;
486 #endif
487     static const char ppsz_type[4][9] = { "", " error", " warning", " debug" };
488     static const char ppsz_color[4][8] = { WHITE, RED, YELLOW, GRAY };
489     const char *psz_object;
490     libvlc_priv_t *priv = libvlc_priv (p_this->p_libvlc);
491     msg_bank_t *bank = priv->msg_bank;
492     int i_type = p_item->i_type;
493
494     switch( i_type )
495     {
496         case VLC_MSG_ERR:
497             if( priv->i_verbose < 0 ) return;
498             break;
499         case VLC_MSG_INFO:
500             if( priv->i_verbose < 0 ) return;
501             break;
502         case VLC_MSG_WARN:
503             if( priv->i_verbose < 1 ) return;
504             break;
505         case VLC_MSG_DBG:
506             if( priv->i_verbose < 2 ) return;
507             break;
508     }
509
510     psz_object = p_item->psz_object_type;
511     void * val = vlc_dictionary_value_for_key (&bank->enabled_objects,
512                                                p_item->psz_module);
513     if( val == kObjectPrintingDisabled )
514         return;
515     if( val == kObjectPrintingEnabled )
516         /* Allowed */;
517     else
518     {
519         val = vlc_dictionary_value_for_key (&bank->enabled_objects,
520                                             psz_object);
521         if( val == kObjectPrintingDisabled )
522             return;
523         if( val == kObjectPrintingEnabled )
524             /* Allowed */;
525         else if( !bank->all_objects_enabled )
526             return;
527     }
528
529 #ifdef UNDER_CE
530 #   define CE_WRITE(str) WriteFile( QUEUE.logfile, \
531                                     str, strlen(str), &i_dummy, NULL );
532     CE_WRITE( p_item->psz_module );
533     CE_WRITE( " " );
534     CE_WRITE( psz_object );
535     CE_WRITE( ppsz_type[i_type] );
536     CE_WRITE( ": " );
537     CE_WRITE( p_item->psz_msg );
538     CE_WRITE( "\r\n" );
539     FlushFileBuffers( QUEUE.logfile );
540
541 #else
542     int canc = vlc_savecancel ();
543     /* Send the message to stderr */
544     utf8_fprintf( stderr, "[%s%p%s] %s%s%s %s%s: %s%s%s\n",
545                   priv->b_color ? GREEN : "",
546                   (void *)p_item->i_object_id,
547                   priv->b_color ? GRAY : "",
548                   p_item->psz_header ? p_item->psz_header : "",
549                   p_item->psz_header ? " " : "",
550                   p_item->psz_module, psz_object,
551                   ppsz_type[i_type],
552                   priv->b_color ? ppsz_color[i_type] : "",
553                   p_item->psz_msg,
554                   priv->b_color ? GRAY : "" );
555
556 #   if defined(WIN32)
557     fflush( stderr );
558 #   endif
559     vlc_restorecancel (canc);
560 #endif
561 }
562
563 static msg_context_t* GetContext(void)
564 {
565     msg_context_t *p_ctx = vlc_threadvar_get( msg_context );
566     if( p_ctx == NULL )
567     {
568         p_ctx = malloc( sizeof( msg_context_t ) );
569         if( !p_ctx )
570             return NULL;
571         p_ctx->psz_message = NULL;
572         vlc_threadvar_set( msg_context, p_ctx );
573     }
574     return p_ctx;
575 }
576
577 void msg_StackDestroy (void *data)
578 {
579     msg_context_t *p_ctx = data;
580
581     free (p_ctx->psz_message);
582     free (p_ctx);
583 }
584
585 void msg_StackSet( int i_code, const char *psz_message, ... )
586 {
587     va_list ap;
588     msg_context_t *p_ctx = GetContext();
589
590     if( p_ctx == NULL )
591         return;
592     free( p_ctx->psz_message );
593
594     va_start( ap, psz_message );
595     if( vasprintf( &p_ctx->psz_message, psz_message, ap ) == -1 )
596         p_ctx->psz_message = NULL;
597     va_end( ap );
598
599     p_ctx->i_code = i_code;
600 }
601
602 void msg_StackAdd( const char *psz_message, ... )
603 {
604     char *psz_tmp;
605     va_list ap;
606     msg_context_t *p_ctx = GetContext();
607
608     if( p_ctx == NULL )
609         return;
610
611     va_start( ap, psz_message );
612     if( vasprintf( &psz_tmp, psz_message, ap ) == -1 )
613         psz_tmp = NULL;
614     va_end( ap );
615
616     if( !p_ctx->psz_message )
617         p_ctx->psz_message = psz_tmp;
618     else
619     {
620         char *psz_new;
621         if( asprintf( &psz_new, "%s: %s", psz_tmp, p_ctx->psz_message ) == -1 )
622             psz_new = NULL;
623
624         free( p_ctx->psz_message );
625         p_ctx->psz_message = psz_new;
626         free( psz_tmp );
627     }
628 }
629
630 const char* msg_StackMsg( void )
631 {
632     msg_context_t *p_ctx = GetContext();
633     assert( p_ctx );
634     return p_ctx->psz_message;
635 }