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