xref: /trunk/main/avmedia/source/framework/soundhandler.cxx (revision a3cdc23e488c57f3433f22cd4458e65c27aa499c)
1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 
23 
24 //_________________________________________________________________________________________________________________
25 //  my own includes
26 //_________________________________________________________________________________________________________________
27 
28 #ifndef __FRAMEWORK_DISPATCH_SOUNDHANDLER_HXX_
29 #include "soundhandler.hxx"
30 #endif
31 
32 #ifndef __COMPHELPER_MEDIADESCRIPTOR_HXX_
33 #include <comphelper/mediadescriptor.hxx>
34 #endif
35 
36 //_________________________________________________________________________________________________________________
37 //  interface includes
38 //_________________________________________________________________________________________________________________
39 #include <com/sun/star/io/XInputStream.hpp>
40 #include <com/sun/star/frame/DispatchResultState.hpp>
41 
42 //_________________________________________________________________________________________________________________
43 //  includes of other projects
44 //_________________________________________________________________________________________________________________
45 #include <comphelper/sequenceashashmap.hxx>
46 #include <rtl/ustrbuf.hxx>
47 
48 #include <cppuhelper/typeprovider.hxx>
49 #include <cppuhelper/factory.hxx>
50 #include <cppuhelper/implementationentry.hxx>
51 
52 //_________________________________________________________________________________________________________________
53 //  namespace
54 //_________________________________________________________________________________________________________________
55 
56 namespace avmedia{
57 
58 //_________________________________________________________________________________________________________________
59 //  non exported const
60 //_________________________________________________________________________________________________________________
61 
62 //_________________________________________________________________________________________________________________
63 //  non exported definitions
64 //_________________________________________________________________________________________________________________
65 
66 //_________________________________________________________________________________________________________________
67 //  declarations
68 //_________________________________________________________________________________________________________________
69 
70 //*****************************************************************************************************************
71 //  XInterface, XTypeProvider, XServiceInfo
72 //*****************************************************************************************************************
73 
74 void SAL_CALL SoundHandler::acquire() throw()
75 {
76        /* Don't use mutex in methods of XInterface! */
77        OWeakObject::acquire();
78 }
79 
80 void SAL_CALL SoundHandler::release() throw()
81 {
82        /* Don't use mutex in methods of XInterface! */
83        OWeakObject::release();
84 }
85 
86 css::uno::Any SAL_CALL SoundHandler::queryInterface( const css::uno::Type& aType ) throw( css::uno::RuntimeException )
87 {
88        /* Attention: Don't use mutex or guard in this method!!! It's a method of XInterface. */
89         /* Ask for my own supported interfaces ...*/
90        css::uno::Any aReturn( ::cppu::queryInterface( aType,
91                static_cast< css::lang::XTypeProvider* >(this),
92                static_cast< css::lang::XServiceInfo* >(this),
93                static_cast< css::frame::XNotifyingDispatch* >(this),
94                static_cast< css::frame::XDispatch* >(this),
95                static_cast< css::document::XExtendedFilterDetection* >(this)));
96        /* If searched interface not supported by this class ... */
97        if ( aReturn.hasValue() == sal_False )
98        {
99                /* ... ask baseclass for interfaces! */
100                aReturn = OWeakObject::queryInterface( aType );
101        }
102         /* Return result of this search. */
103        return aReturn;
104 }
105 
106 css::uno::Sequence< sal_Int8 > SAL_CALL SoundHandler::getImplementationId() throw( css::uno::RuntimeException )
107 {
108     /* Create one Id for all instances of this class.                                               */
109     /* Use ethernet address to do this! (sal_True)                                                  */
110     /* Optimize this method                                                                         */
111     /* We initialize a static variable only one time. And we don't must use a mutex at every call!  */
112     /* For the first call; pID is NULL - for the second call pID is different from NULL!            */
113     static ::cppu::OImplementationId* pID = NULL ;
114     if ( pID == NULL )
115     {
116         /* Ready for multithreading; get global mutex for first call of this method only! see before */
117         ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
118         /* Control these pointer again ... it can be, that another instance will be faster than these! */
119         if ( pID == NULL )
120         {
121             /* Create a new static ID ... */
122             static ::cppu::OImplementationId aID( sal_False );
123             /* ... and set his address to static pointer! */
124             pID = &aID ;
125         }
126     }
127     return pID->getImplementationId();
128 }
129 
130 css::uno::Sequence< css::uno::Type > SAL_CALL SoundHandler::getTypes() throw( css::uno::RuntimeException )
131 {
132     /* Optimize this method !                                       */
133     /* We initialize a static variable only one time.               */
134     /* And we don't must use a mutex at every call!                 */
135     /* For the first call; pTypeCollection is NULL -                */
136     /* for the second call pTypeCollection is different from NULL!  */
137     static ::cppu::OTypeCollection* pTypeCollection = NULL ;
138     if ( pTypeCollection == NULL )
139     {
140         /* Ready for multithreading; get global mutex for first call of this method only! see before */
141         ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
142         /* Control these pointer again ... it can be, that another instance will be faster than these! */
143         if ( pTypeCollection == NULL )
144         {
145             /* Create a static typecollection ... */
146             static ::cppu::OTypeCollection aTypeCollection
147                 (
148                     ::getCppuType(( const ::com::sun::star::uno::Reference< css::lang::XTypeProvider >*)NULL ),
149                     ::getCppuType(( const ::com::sun::star::uno::Reference< css::lang::XServiceInfo >*)NULL ),
150                     ::getCppuType(( const ::com::sun::star::uno::Reference< css::frame::XNotifyingDispatch >*)NULL ),
151                     ::getCppuType(( const ::com::sun::star::uno::Reference< css::frame::XDispatch >*)NULL ),
152                     ::getCppuType(( const ::com::sun::star::uno::Reference< css::document::XExtendedFilterDetection >*)NULL )
153                 );
154             /* ... and set his address to static pointer! */
155             pTypeCollection = &aTypeCollection ;
156         }
157     }
158     return pTypeCollection->getTypes();
159 }
160 
161 #define DECLARE_ASCII( SASCIIVALUE ) \
162         ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( SASCIIVALUE ) )
163 
164 #define IMPLEMENTATIONNAME_SOUNDHANDLER DECLARE_ASCII("com.sun.star.comp.framework.SoundHandler")
165 #define SERVICENAME_CONTENTHANDLER DECLARE_ASCII("com.sun.star.frame.ContentHandler")
166 
167 /*===========================================================================================================*/
168 /* XServiceInfo */
169 /*===========================================================================================================*/
170 ::rtl::OUString SAL_CALL SoundHandler::getImplementationName() throw( css::uno::RuntimeException )
171 {
172     return impl_getStaticImplementationName();
173 }
174 
175 /*===========================================================================================================*/
176 /* XServiceInfo */
177 /*===========================================================================================================*/
178 sal_Bool SAL_CALL SoundHandler::supportsService( const ::rtl::OUString& sServiceName ) throw( css::uno::RuntimeException )
179 {
180     /* Set default return value. */
181     sal_Bool bReturn = sal_False ;
182     /* Get names of all supported servicenames. */
183     css::uno::Sequence< ::rtl::OUString >  seqServiceNames =   getSupportedServiceNames();
184     const ::rtl::OUString*                 pArray          =   seqServiceNames.getConstArray();
185     sal_Int32                              nCounter        =   0;
186     sal_Int32                              nLength         =   seqServiceNames.getLength();
187     /* Search for right name in list. */
188     while   (
189               ( nCounter      <       nLength         )       &&
190               ( bReturn       ==      sal_False       )
191             )
192     {
193         /* If name was found, say "YES, SERVICE IS SUPPORTED." and break loop. */
194         if ( pArray[nCounter] == sServiceName )
195         {
196             bReturn = sal_True ;
197         }
198         /* Else step to next element in list. */
199         ++nCounter;
200     }
201     /* Return state of search. */
202     return bReturn;
203 }
204 
205 /*===========================================================================================================*/
206 /* XServiceInfo */
207 /*===========================================================================================================*/
208 css::uno::Sequence< ::rtl::OUString > SAL_CALL SoundHandler::getSupportedServiceNames() throw( css::uno::RuntimeException )
209 {
210     return impl_getStaticSupportedServiceNames();
211 }
212 
213 /*===========================================================================================================*/
214 /* Helper for XServiceInfo                                                                                   */
215 /*===========================================================================================================*/
216 css::uno::Sequence< ::rtl::OUString > SoundHandler::impl_getStaticSupportedServiceNames()
217 {
218     css::uno::Sequence< ::rtl::OUString > seqServiceNames( 1 );
219     seqServiceNames.getArray() [0] = SERVICENAME_CONTENTHANDLER;
220     return seqServiceNames;
221 }
222 
223 /*===========================================================================================================*/
224 /* Helper for XServiceInfo */
225 /*===========================================================================================================*/
226 ::rtl::OUString SoundHandler::impl_getStaticImplementationName()
227 {
228     return IMPLEMENTATIONNAME_SOUNDHANDLER;
229 }
230 
231 css::uno::Reference< css::uno::XInterface > SAL_CALL SoundHandler::impl_createInstance( const css::uno::Reference< css::uno::XComponentContext >& xContext ) throw( css::uno::Exception )
232 {
233     /* create new instance of service */
234     SoundHandler* pClass = new SoundHandler( xContext );
235     /* hold it alive by increasing his ref count!!! */
236     css::uno::Reference< css::uno::XInterface > xService( static_cast< ::cppu::OWeakObject* >(pClass), css::uno::UNO_QUERY );
237     /* initialize new service instance ... he can use his own refcount ... we hold it! */
238     pClass->impl_initService();
239     /* return new created service as reference */
240     return xService;
241 }
242 
243 static struct ::cppu::ImplementationEntry g_component_entries[] =
244 {
245     {
246         SoundHandler::impl_createInstance,
247         SoundHandler::impl_getStaticImplementationName,
248         SoundHandler::impl_getStaticSupportedServiceNames,
249         ::cppu::createSingleComponentFactory,
250         0,
251         0
252     },
253     { 0, 0, 0, 0, 0, 0 }
254 };
255 
256 void SAL_CALL SoundHandler::impl_initService()
257 {
258 }
259 
260 
261 /*-************************************************************************************************************//**
262     @short      standard ctor
263     @descr      These initialize a new instance of this class with needed informations for work.
264 
265     @seealso    using at owner
266 
267     @param      "xContext", reference to component context for creation of new services
268     @return     -
269 
270     @onerror    Show an assertion and do nothing else.
271     @threadsafe yes
272 *//*-*************************************************************************************************************/
273 SoundHandler::SoundHandler( const css::uno::Reference< css::uno::XComponentContext >& xContext )
274         //  Init baseclasses first
275         :   ThreadHelpBase      (          )
276         ,   ::cppu::OWeakObject (          )
277         // Init member
278     ,   m_bError        ( false    )
279         ,   m_xContext          ( xContext )
280 {
281     m_aUpdateTimer.SetTimeoutHdl(LINK(this, SoundHandler, implts_PlayerNotify));
282 }
283 
284 /*-************************************************************************************************************//**
285     @short      standard dtor
286     @descr      -
287 
288     @seealso    -
289 
290     @param      -
291     @return     -
292 
293     @onerror    -
294     @threadsafe -
295 *//*-*************************************************************************************************************/
296 SoundHandler::~SoundHandler()
297 {
298     if (m_xListener.is())
299     {
300         css::frame::DispatchResultEvent aEvent;
301         aEvent.State = css::frame::DispatchResultState::FAILURE;
302         m_xListener->dispatchFinished(aEvent);
303         m_xListener = css::uno::Reference< css::frame::XDispatchResultListener >();
304     }
305 }
306 
307 /*-************************************************************************************************************//**
308     @interface  ::com::sun::star::frame::XDispatch
309 
310     @short      try to load audio file
311     @descr      This method try to load given audio file by URL and play it. We use vcl/Sound class to do that.
312                 Playing of sound is asynchron every time.
313 
314     @attention  We must hold us alive by ourself ... because we use async. vcl sound player ... but playing is started
315                 in async interface call "dispatch()" too. And caller forget us immediately. But then our uno ref count
316                 will decreased to 0 and will die. The only solution is to use own reference to our implementation.
317                 But we do it for really started jobs only and release it during call back of vcl.
318 
319     @seealso    class vcl/Sound
320     @seealso    method implts_PlayerNotify()
321 
322     @param      "aURL"      , URL to dispatch.
323     @param      "lArguments", list of optional arguments.
324     @return     -
325 
326     @onerror    We do nothing.
327     @threadsafe yes
328 *//*-*************************************************************************************************************/
329 void SAL_CALL SoundHandler::dispatchWithNotification(const css::util::URL&                                             aURL      ,
330                                                      const css::uno::Sequence< css::beans::PropertyValue >&            lDescriptor,
331                                                      const css::uno::Reference< css::frame::XDispatchResultListener >& xListener ) throw(css::uno::RuntimeException)
332 {
333     // SAFE {
334     const ::vos::OGuard aLock( m_aLock );
335 
336     {
337     //close streams otherwise on windows we can't reopen the file in the
338     //media player when we pass the url to directx as it'll already be open
339         ::comphelper::MediaDescriptor aDescriptor(lDescriptor);
340 
341     css::uno::Reference< css::io::XInputStream > xInputStream =
342         aDescriptor.getUnpackedValueOrDefault(::comphelper::MediaDescriptor::PROP_INPUTSTREAM(),
343         css::uno::Reference< css::io::XInputStream >());
344     if (xInputStream.is()) xInputStream->closeInput();
345     }
346 
347     // If player currently used for other dispatch() requests ...
348     // cancel it by calling stop()!
349     m_aUpdateTimer.Stop();
350     if (m_xPlayer.is())
351     {
352         if (m_xPlayer->isPlaying())
353             m_xPlayer->stop();
354         m_xPlayer.clear();
355     }
356 
357     // Try to initialize player.
358     m_xListener = xListener;
359     try
360     {
361         m_bError = false;
362         m_xPlayer.set( avmedia::MediaWindow::createPlayer( aURL.Complete ), css::uno::UNO_QUERY_THROW );
363         // OK- we can start async playing ...
364         // Count this request and initialize self-holder against dying by uno ref count ...
365         m_xSelfHold = css::uno::Reference< css::uno::XInterface >(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY);
366         m_xPlayer->start();
367         m_aUpdateTimer.SetTimeout( 200 );
368         m_aUpdateTimer.Start();
369     }
370     catch( css::uno::Exception& e )
371     {
372         m_bError = true;
373         (void)e;
374         m_xPlayer.clear();
375     }
376 
377     // } SAFE
378 }
379 
380 void SAL_CALL SoundHandler::dispatch( const css::util::URL&                                  aURL       ,
381                                       const css::uno::Sequence< css::beans::PropertyValue >& lArguments ) throw( css::uno::RuntimeException )
382 {
383     dispatchWithNotification(aURL, lArguments, css::uno::Reference< css::frame::XDispatchResultListener >());
384 }
385 
386 /*-************************************************************************************************************//**
387     @interface  ::com::sun::star::document::XExtendedFilterDetection
388 
389     @short      try to detect file (given as argument included in "lDescriptor")
390     @descr      We try to detect, if given file could be handled by this class and is a well known one.
391                 If it is - we return right internal type name - otherwise we return nothing!
392                 So call can search for another detect service and ask him too.
393 
394     @attention  a) We don't need any mutex here ... because we don't use any member!
395                 b) Don't use internal player instance "m_pPlayer" to detect given sound file!
396                    It's not necessary to do that ... and we can use temp. variable to do the same.
397                    This way is easy - we don't must synchronize it with currently played sounds!
398                    Another reason to do so ... We are a listener on our internal ma_Player object.
399                    If you would call "IsSoundFile()" on this instance, he would call us back and
400                    we make some unnecessary things ...
401 
402     @seealso    -
403 
404     @param      "lDescriptor", description of file to detect
405     @return     Internal type name which match this file ... or nothing if it is unknown.
406 
407     @onerror    We return nothing.
408     @threadsafe yes
409 *//*-*************************************************************************************************************/
410 ::rtl::OUString SAL_CALL SoundHandler::detect( css::uno::Sequence< css::beans::PropertyValue >& lDescriptor ) throw( css::uno::RuntimeException )
411 {
412     // Our default is "nothing". So we can return it, if detection failed or file type is really unknown.
413     ::rtl::OUString sTypeName;
414 
415     // Analyze given descriptor to find filename or input stream or ...
416     ::comphelper::MediaDescriptor aDescriptor(lDescriptor);
417     ::rtl::OUString               sURL       = aDescriptor.getUnpackedValueOrDefault(::comphelper::MediaDescriptor::PROP_URL(), ::rtl::OUString());
418 
419     if (
420         !sURL.isEmpty() &&
421         (avmedia::MediaWindow::isMediaURL(sURL))
422        )
423     {
424         // If the file type is supported depends on the OS, so...
425         // I think we can the following ones:
426         //  a) look for given extension of url to map our type decision HARD CODED!!!
427         //  b) return preferred type every time... it's easy :-)
428         sTypeName = ::rtl::OUString::createFromAscii("wav_Wave_Audio_File");
429         aDescriptor[::comphelper::MediaDescriptor::PROP_TYPENAME()] <<= sTypeName;
430         aDescriptor >> lDescriptor;
431     }
432 
433     // Return our decision.
434     return sTypeName;
435 }
436 
437 /*-************************************************************************************************************//**
438     @short      call back of sound player
439     @descr      Our player call us back to give us some informations.
440                 We use these informations to callback our might existing listener.
441 
442     @seealso    method dispatchWithNotification()
443 
444     @param      -
445     @return     0 every time ... it doesn't matter for us.
446 
447     @onerror    -
448     @threadsafe yes
449 *//*-*************************************************************************************************************/
450 IMPL_LINK( SoundHandler, implts_PlayerNotify, void*, EMPTYARG )
451 {
452     // SAFE {
453     ::vos::OClearableGuard aLock( m_aLock );
454 
455     if (m_xPlayer.is() && m_xPlayer->isPlaying() && m_xPlayer->getMediaTime() < m_xPlayer->getDuration())
456     {
457         m_aUpdateTimer.Start();
458         return 0L;
459     }
460     m_xPlayer.clear();
461 
462     // We use m_xSelfHold to let us die ... but we must live till real finishing of this method too!!!
463     // So we SHOULD use another "self-holder" temp. to provide that ...
464     css::uno::Reference< css::uno::XInterface > xOperationHold = m_xSelfHold;
465     m_xSelfHold = css::uno::Reference< css::uno::XInterface >();
466 
467     // notify might existing listener
468     // And forget this listener!
469     // Because the corresponding dispatch was finished.
470     if (m_xListener.is())
471     {
472         css::frame::DispatchResultEvent aEvent;
473         if (!m_bError)
474             aEvent.State = css::frame::DispatchResultState::SUCCESS;
475         else
476             aEvent.State = css::frame::DispatchResultState::FAILURE;
477         m_xListener->dispatchFinished(aEvent);
478         m_xListener = css::uno::Reference< css::frame::XDispatchResultListener >();
479     }
480 
481     // } SAFE
482     //release aLock before end of method at which point xOperationHold goes out of scope and pThis dies
483     aLock.clear();
484     return 0;
485 }
486 
487 } // namespace framework
488 
489 // ------------------------------------------
490 // - component_getImplementationEnvironment -
491 // ------------------------------------------
492 
493 extern "C" SAL_DLLPUBLIC_EXPORT void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** /*ppEnv*/ )
494 {
495        *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
496 }
497 
498 // ------------------------
499 // - component_getFactory -
500 // ------------------------
501 
502 extern "C" SAL_DLLPUBLIC_EXPORT void* SAL_CALL component_getFactory(const sal_Char* pImplementationName, void* pServiceManager, void* pRegistryKey )
503 {
504     return ::cppu::component_getFactoryHelper( pImplementationName, pServiceManager, pRegistryKey, avmedia::g_component_entries );
505 }
506