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