1 /*
2  * manager.h
3  *
4  * OPAL system manager.
5  *
6  * Open Phone Abstraction Library (OPAL)
7  * Formally known as the Open H323 project.
8  *
9  * Copyright (c) 2001 Equivalence Pty. Ltd.
10  *
11  * The contents of this file are subject to the Mozilla Public License
12  * Version 1.0 (the "License"); you may not use this file except in
13  * compliance with the License. You may obtain a copy of the License at
14  * http://www.mozilla.org/MPL/
15  *
16  * Software distributed under the License is distributed on an "AS IS"
17  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
18  * the License for the specific language governing rights and limitations
19  * under the License.
20  *
21  * The Original Code is Open Phone Abstraction Library.
22  *
23  * The Initial Developer of the Original Code is Equivalence Pty. Ltd.
24  *
25  * Contributor(s): ______________________________________.
26  *
27  * $Revision: 27984 $
28  * $Author: rjongbloed $
29  * $Date: 2012-07-10 03:24:24 -0500 (Tue, 10 Jul 2012) $
30  */
31 
32 #ifndef OPAL_OPAL_MANAGER_H
33 #define OPAL_OPAL_MANAGER_H
34 
35 #ifdef P_USE_PRAGMA
36 #pragma interface
37 #endif
38 
39 #include <opal/buildopts.h>
40 
41 #include <opal/pres_ent.h>
42 #include <opal/call.h>
43 #include <opal/connection.h> //OpalConnection::AnswerCallResponse
44 #include <opal/guid.h>
45 #include <codec/silencedetect.h>
46 #include <codec/echocancel.h>
47 #include <ptclib/pstun.h>
48 #include <ptclib/url.h>
49 
50 #if OPAL_VIDEO
51 #include <ptlib/videoio.h>
52 #endif
53 
54 class OpalEndPoint;
55 class OpalMediaPatch;
56 
57 
58 /**This class is the central manager for OPAL.
59    The OpalManager embodies the root of the tree of objects that constitute an
60    OPAL system. It contains all of the endpoints that make up the system. Other
61    entities such as media streams etc are in turn contained in these objects.
62    It is expected that an application would only ever have one instance of
63    this class, and also descend from it to override call back functions.
64 
65    The manager is the eventual destination for call back indications from
66    various other objects. It is possible, for instance, to get an indication
67    of a completed call by creating a descendant of the OpalCall and overriding
68    the OnClearedCall() virtual. However, this could quite unwieldy for all of
69    the possible classes, so the default behaviour is to call the equivalent
70    function on the OpalManager. This allows most applications to only have to
71    create a descendant of the OpalManager and override virtual functions there
72    to get all the indications it needs.
73  */
74 class OpalManager : public PObject
75 {
76     PCLASSINFO(OpalManager, PObject);
77   public:
78   /**@name Construction */
79   //@{
80     /**Create a new manager.
81      */
82     OpalManager();
83 
84     /**Destroy the manager.
85        This will clear all calls, then delete all endpoints still attached to
86        the manager.
87      */
88     ~OpalManager();
89   //@}
90 
91   /**@name Endpoint management */
92   //@{
93     /**Attach a new endpoint to the manager.
94        This is an internal function called by the OpalEndPoint constructor.
95 
96        Note that usually the endpoint is automatically "owned" by the manager.
97        They should not be deleted directly. The DetachEndPoint() command
98        should be used to do this.
99       */
100     void AttachEndPoint(
101       OpalEndPoint * endpoint,    ///< EndPoint to add to the manager
102       const PString & prefix = PString::Empty()  ///< Prefix to use, if empty uses endpoint->GetPrefixName()
103     );
104 
105     /**Remove an endpoint from the manager.
106        This will delete the endpoint object.
107       */
108     void DetachEndPoint(
109       const PString & prefix
110     );
111     void DetachEndPoint(
112       OpalEndPoint * endpoint
113     );
114 
115     /**Find an endpoint instance that is using the specified prefix.
116       */
117     OpalEndPoint * FindEndPoint(
118       const PString & prefix
119     );
120 
121     /**Get the endpoints attached to this manager.
122       */
123     PList<OpalEndPoint> GetEndPoints() const;
124 
125     /**Shut down all of the endpoints, clearing all calls.
126        This is synchonous and will wait till everything is shut down.
127        This will also assure no new calls come in whilein the process of
128        shutting down.
129       */
130     void ShutDownEndpoints();
131   //@}
132 
133   /**@name Call management */
134   //@{
135     /**Set up a call between two parties.
136        This is used to initiate a call. Incoming calls are "answered" using a
137        different mechanism.
138 
139        The A party and B party strings indicate the protocol and address of
140        the party to call in the style of a URL. The A party is the initiator
141        of the call and the B party is the remote system being called. See the
142        MakeConnection() function for more details on the format of these
143        strings.
144 
145        The token returned is a unique identifier for the call that allows an
146        application to gain access to the call at later time. This is necesary
147        as any pointer being returned could become invalid (due to being
148        deleted) at any time due to the multithreaded nature of the OPAL
149        system.
150      */
151     virtual PSafePtr<OpalCall> SetUpCall(
152       const PString & partyA,       ///<  The A party of call
153       const PString & partyB,       ///<  The B party of call
154       void * userData = NULL,       ///<  user data passed to Call and Connection
155       unsigned options = 0,         ///<  options passed to connection
156       OpalConnection::StringOptions * stringOptions = NULL ///< Options to pass to connection
157     );
158     virtual PBoolean SetUpCall(
159       const PString & partyA,       ///<  The A party of call
160       const PString & partyB,       ///<  The B party of call
161       PString & token,              ///<  Token for call
162       void * userData = NULL,       ///<  user data passed to Call and Connection
163       unsigned options = 0,         ///<  options passed to connection
164       OpalConnection::StringOptions * stringOptions = NULL ///< Options to pass to connection
165     );
166 
167     /**Determine if a call is active.
168        Return true if there is an active call with the specified token. Note
169        that the call could clear any time (even milliseconds) after this
170        function returns true.
171       */
HasCall(const PString & token)172     virtual PBoolean HasCall(
173       const PString & token  ///<  Token for identifying call
174     ) { return activeCalls.FindWithLock(token, PSafeReference) != NULL; }
175 
176     /**Return the number of active calls.
177       */
GetCallCount()178     PINDEX GetCallCount() const { return activeCalls.GetSize(); }
179 
180     /**Get all tokens for active calls.
181       */
GetAllCalls()182      PArray<PString> GetAllCalls() const { return activeCalls.GetKeys(); }
183 
184     /**Find a call with the specified token.
185        This searches the manager database for the call that contains the token
186        as provided by functions such as SetUpCall().
187 
188        Note the caller of this function MUST call the OpalCall::Unlock()
189        function if this function returns a non-NULL pointer. If it does not
190        then a deadlock can occur.
191       */
192     PSafePtr<OpalCall> FindCallWithLock(
193       const PString & token,  ///<  Token to identify connection
194       PSafetyMode mode = PSafeReadWrite ///< Lock mode
195     ) { return activeCalls.FindWithLock(token, mode); }
196 
197     /**A call back function whenever a call is completed.
198        In telephony terminology a completed call is one where there is an
199        established link between two parties.
200 
201        This called from the OpalCall::OnEstablished() function.
202 
203        The default behaviour does nothing.
204       */
205     virtual void OnEstablishedCall(
206       OpalCall & call   ///<  Call that was completed
207     );
208 
209     /**Determine if a call is established.
210        Return true if there is an active call with the specified token and
211        that call has at least two parties with media flowing between them.
212        Note that the call could clear any time (even milliseconds) after this
213        function returns true.
214       */
215     virtual PBoolean IsCallEstablished(
216       const PString & token  ///<  Token for identifying call
217     );
218 
219     /**Clear a call.
220        This finds the call by using the token then calls the OpalCall::Clear()
221        function on it. All connections are released, and the connections and
222        call are disposed of. Note that this function returns quickly and the
223        disposal happens at some later time in a background thread. It is safe
224        to call this function from anywhere.
225 
226        If \p sync is not NULL then it is signalled when the calls are cleared.
227       */
228     virtual PBoolean ClearCall(
229       const PString & token,    ///<  Token for identifying connection
230       OpalConnection::CallEndReason reason = OpalConnection::EndedByLocalUser, ///<  Reason for call clearing
231       PSyncPoint * sync = NULL  ///<  Sync point to wait on.
232     );
233 
234     /**Clear a call.
235        This finds the call by using the token then calls the OpalCall::Clear()
236        function on it. All connections are released, and the connections and
237        caller disposed of. Note that this function waits until the call has
238        been cleared and all responses timeouts etc completed. Care must be
239        used as to when it is called as deadlocks may result.
240       */
241     virtual PBoolean ClearCallSynchronous(
242       const PString & token,    ///<  Token for identifying connection
243       OpalConnection::CallEndReason reason = OpalConnection::EndedByLocalUser ///<  Reason for call clearing
244     );
245 
246     /**Clear all current calls.
247        This effectively executes OpalCall::Clear() on every call that the
248        manager has active.
249        This function can not be called from several threads at the same time.
250       */
251     virtual void ClearAllCalls(
252       OpalConnection::CallEndReason reason = OpalConnection::EndedByLocalUser, ///<  Reason for call clearing
253       PBoolean wait = true   ///<  Flag to wait for calls to e cleared.
254     );
255 
256     /**A call back function whenever a call is cleared.
257        A call is cleared whenever there is no longer any connections attached
258        to it. This function is called just before the call is deleted.
259        However, it may be used to display information on the call after
260        completion, eg the call parties and duration.
261 
262        Note that there is not a one to one relationship with the
263        OnEstablishedCall() function. This function may be called without that
264        function being called. For example if MakeConnection() was used but
265        the call never completed.
266 
267        The default behaviour removes the call from the activeCalls dictionary.
268       */
269     virtual void OnClearedCall(
270       OpalCall & call   ///<  Connection that was established
271     );
272 
273     /**Create a call object.
274        This function allows an application to have the system create
275        desccendants of the OpalCall class instead of instances of that class
276        directly. The application can thus override call backs or add extra
277        information that it wishes to maintain on a call by call basis.
278 
279        The default behavious returns an instance of OpalCall.
280       */
281     virtual OpalCall * CreateCall(
282       void * userData            ///<  user data passed to SetUpCall
283     );
284     OpalCall * InternalCreateCall();
285 
286     /**Destroy a call object.
287        This gets called from background thread that garbage collects all calls
288        and connections. If an application has object lifetime issues with the
289        threading, it can override this function and take responsibility for
290        deleting the object at some later time.
291 
292        The default behaviour simply calls "delete call".
293       */
294     virtual void DestroyCall(
295       OpalCall * call
296     );
297 
298     /**Get next unique token ID for calls or connections.
299        This is an internal function called by the OpalCall and other
300        constructors.
301       */
302     virtual PString GetNextToken(char prefix);
303   //@}
304 
305   /**@name Presence management */
306   //@{
307     /**Add a presentity.
308        If the presentity is already present, a new one is not added, and the
309        existing instance is returned.
310 
311        Returns a Read/Write locked pointer to presentity.
312       */
313     virtual PSafePtr<OpalPresentity> AddPresentity(
314       const PString & presentity  ///< Presentity URI
315     );
316 
317     /**Get a presentity.
318       */
319     virtual PSafePtr<OpalPresentity> GetPresentity(
320       const PString & presentity,         ///< Presentity URI
321       PSafetyMode mode = PSafeReference   ///< Safety mode for presentity
322     );
323 
324     /**Get all presentities.
325       */
326     virtual PStringList GetPresentities() const;
327 
328     /**Remove a presentity.
329       */
330     virtual bool RemovePresentity(
331       const PString & presentity  ///< Presentity URI
332     );
333   //@}
334 
335   /**@name Instant Messaging management */
336   //@{
337     /**Send an IM to a remote party.
338      */
339     virtual PBoolean Message(
340       const PString & to,
341       const PString & body
342     );
343     virtual PBoolean Message(
344       const PURL & to,
345       const PString & type,
346       const PString & body,
347       PURL & from,
348       PString & conversationId
349     );
350     virtual PBoolean Message(
351       OpalIM & message
352     );
353 
354     /**Called when text message received
355      */
356     virtual void OnMessageReceived(
357       const OpalIM & message
358     );
359 
360   //@}
361 
362   /**@name Connection management */
363   //@{
364     /**Set up a connection to a remote party.
365        An appropriate protocol (endpoint) is determined from the party
366        parameter. That endpoint is then called to create a connection and that
367        connection is attached to the call provided.
368 
369        If the endpoint is already occupied in a call then the endpoints list
370        is further searched for additional endpoints that support the protocol.
371        For example multiple pstn endpoints may be present for multiple LID's.
372 
373        The general form for this party parameter is:
374 
375             [proto:][alias@][transport$]address[:port]
376 
377        where the various fields will have meanings specific to the endpoint
378        type. For example, with H.323 it could be "h323:Fred@site.com" which
379        indicates a user Fred at gatekeeper size.com. Whereas for the PSTN
380        endpoint it could be "pstn:5551234" which is to call 5551234 on the
381        first available PSTN line.
382 
383        The default for the proto is the name of the protocol for the first
384        endpoint attached to the manager. Other fields default to values on an
385        endpoint basis.
386 
387        This function usually returns almost immediately with the connection
388        continuing to occur in a new background thread.
389 
390        If false is returned then the connection could not be established. For
391        example if a PSTN endpoint is used and the associated line is engaged
392        then it may return immediately. Returning a non-NULL value does not
393        mean that the connection will succeed, only that an attempt is being
394        made.
395 
396        The default behaviour is pure.
397      */
398     virtual PSafePtr<OpalConnection> MakeConnection(
399       OpalCall & call,                   ///<  Owner of connection
400       const PString & party,             ///<  Party to call
401       void * userData = NULL,            ///<  user data to pass to connections
402       unsigned int options = 0,          ///<  options to pass to conneciton
403       OpalConnection::StringOptions * stringOptions = NULL ///< Options to pass to connection
404     );
405 
406     /**Call back for a new connection has been constructed.
407        This is called after CreateConnection has returned a new connection.
408        It allows an application to make any custom adjustments to the
409        connection before it begins to process the protocol. behind it.
410       */
411     virtual void OnNewConnection(
412       OpalConnection & connection   ///< New connection just created
413     );
414 
415     /**Call back for answering an incoming call.
416        This function is used for an application to control the answering of
417        incoming calls.
418 
419        If true is returned then the connection continues. If false then the
420        connection is aborted.
421 
422        Note this function should not block for any length of time. If the
423        decision to answer the call may take some time eg waiting for a user to
424        pick up the phone, then AnswerCallPending or AnswerCallDeferred should
425        be returned.
426 
427        If an application overrides this function, it should generally call the
428        ancestor version to complete calls. Unless the application completely
429        takes over that responsibility. Generally, an application would only
430        intercept this function if it wishes to do some form of logging. For
431        this you can obtain the name of the caller by using the function
432        OpalConnection::GetRemotePartyName().
433 
434        The default behaviour is to call OnRouteConnection to determine a
435        B party for the connection.
436 
437        If the call associated with the incoming call already had two parties
438        and this connection is a third party for a conference call then
439        AnswerCallNow is returned as a B party is not required.
440      */
441     virtual PBoolean OnIncomingConnection(
442       OpalConnection & connection,   ///<  Connection that is calling
443       unsigned options,              ///<  options for new connection (can't use default as overrides will fail)
444       OpalConnection::StringOptions * stringOptions ///< Options to pass to connection
445     );
446 
447     /**Route a connection to another connection from an endpoint.
448 
449        The default behaviour gets the destination address from the connection
450        and translates it into an address by using the routeTable member
451        variable and uses MakeConnection() to start the B-party connection.
452       */
453     virtual bool OnRouteConnection(
454       PStringSet & routesTried,     ///< Set of routes already tried
455       const PString & a_party,      ///< Source local address
456       const PString & b_party,      ///< Destination indicated by source
457       OpalCall & call,              ///< Call for new connection
458       unsigned options,             ///< Options for new connection (can't use default as overrides will fail)
459       OpalConnection::StringOptions * stringOptions ///< Options to pass to connection
460     );
461 
462     /**Call back for remote party is now responsible for completing the call.
463        This function is called when the remote system has been contacted and it
464        has accepted responsibility for completing, or failing, the call. This
465        is distinct from OnAlerting() in that it is not known at this time if
466        anything is ringing. This indication may be used to distinguish between
467        "transport" level error, in which case another host may be tried, and
468        that finalising the call has moved "upstream" and the local system has
469        no more to do but await a result.
470 
471        If an application overrides this function, it should generally call the
472        ancestor version for correct operation.
473 
474        The default behaviour calls the OnProceeding() on the connection's
475        associated OpalCall object.
476      */
477     virtual void OnProceeding(
478       OpalConnection & connection   ///<  Connection that is proceeeding
479     );
480 
481     /**Call back for remote party being alerted on outgoing call.
482        This function is called after the connection is informed that the
483        remote endpoint is "ringing". This function is generally called
484        some time after the MakeConnection() function was called.
485 
486        If false is returned the connection is aborted.
487 
488        If an application overrides this function, it should generally call the
489        ancestor version for correct operation. An application would typically
490        only intercept this function if it wishes to do some form of logging.
491        For this you can obtain the name of the caller by using the function
492        OpalConnection::GetRemotePartyName().
493 
494        The default behaviour calls the OnAlerting() on the connection's
495        associated OpalCall object.
496      */
497     virtual void OnAlerting(
498       OpalConnection & connection   ///<  Connection that was established
499     );
500 
501     /**Call back for answering an incoming call.
502        This function is called after the connection has been acknowledged
503        but before the connection is established
504 
505        This gives the application time to wait for some event before
506        signalling to the endpoint that the connection is to proceed. For
507        example the user pressing an "Answer call" button.
508 
509        If AnswerCallDenied is returned the connection is aborted and the
510        connetion specific end call PDU is sent. If AnswerCallNow is returned
511        then the connection proceeding, Finally if AnswerCallPending is returned then the
512        protocol negotiations are paused until the AnsweringCall() function is
513        called.
514 
515        The default behaviour simply returns AnswerNow.
516      */
517     virtual OpalConnection::AnswerCallResponse OnAnswerCall(
518       OpalConnection & connection,    ///<  connection that is being answered
519        const PString & caller         ///<  caller
520     );
521 
522     /**A call back function whenever a connection is "connected".
523        This indicates that a connection to an endpoint was connected. That
524        is the endpoint received acknowledgement via whatever protocol it uses
525        that the connection may now start media streams.
526 
527        In the context of H.323 this means that the CONNECT pdu has been
528        received.
529 
530        The default behaviour calls the OnConnected() on the connections
531        associated OpalCall object.
532       */
533     virtual void OnConnected(
534       OpalConnection & connection   ///<  Connection that was established
535     );
536 
537     /**A call back function whenever a connection is "established".
538        This indicates that a connection to an endpoint was established. This
539        usually occurs after OnConnected() and indicates that the connection
540        is both connected and has media flowing.
541 
542        In the context of H.323 this means that the CONNECT pdu has been
543        received and either fast start was in operation or the subsequent Open
544        Logical Channels have occurred. For SIP it indicates the INVITE/OK/ACK
545        sequence is complete.
546 
547        The default behaviour calls the OnEstablished() on the connection's
548        associated OpalCall object.
549       */
550     virtual void OnEstablished(
551       OpalConnection & connection   ///<  Connection that was established
552     );
553 
554     /**A call back function whenever a connection is released.
555        This function can do any internal cleaning up and waiting on background
556        threads that may be using the connection object.
557 
558        Classes that override this function should make sure they call the
559        ancestor version for correct operation.
560 
561        An application will not typically call this function as it is used by
562        the OpalManager during a release of the connection.
563 
564        The default behaviour calls OnReleased() on the connection's
565        associated OpalCall object. This indicates to the call that the
566        connection has been released so it can release the last remaining
567        connection and then returns true.
568       */
569     virtual void OnReleased(
570       OpalConnection & connection   ///<  Connection that was established
571     );
572 
573     /**A call back function whenever a connection is "held" or "retrieved".
574        This indicates that a connection to an endpoint was held, or
575        retrieved, either locally or by the remote endpoint.
576 
577        The default behaviour does nothing.
578       */
579     virtual void OnHold(
580       OpalConnection & connection,   ///<  Connection that was held/retrieved
581       bool fromRemote,               ///<  Indicates remote has held local connection
582       bool onHold                    ///<  Indicates have just been held/retrieved.
583     );
584     virtual void OnHold(OpalConnection & connection); // For backward compatibility
585 
586     /**A call back function whenever a connection is forwarded.
587 
588        The default behaviour does nothing.
589       */
590     virtual PBoolean OnForwarded(
591       OpalConnection & connection,  ///<  Connection that was held
592       const PString & remoteParty         ///<  The new remote party
593     );
594 
595     /**A call back function to monitor the progress of a transfer.
596        When a transfer operation is initiated, the Transfer() function will
597        generally return immediately and the transfer may take some time. This
598        call back can give an indication to the application of the progress of
599        the transfer.
600        the transfer.
601 
602        For example in SIP, the OpalCall::Transfer() function will have sent a
603        REFER request to the remote party. The remote party sends us NOTIFY
604        requests about the progress of the REFER request.
605 
606        An application can now make a decision during the transfer operation
607        to short circuit the sequence, or let it continue. It can also
608        determine if the transfer did not go through, and it should "take back"
609        the call. Note no action is required to "take back" the call other than
610        indicate to the user that they are back on.
611 
612        A return value of false will immediately disconnect the current call.
613 
614        The exact format of the \p info parameter is dependent on the protocol
615        being used. As a minimum, it will always have a values info["result"]
616        and info["party"].
617 
618        The info["party"] indicates the part the \p connection is playing in
619        the transfer. This will be:
620           "A"   party being transferred
621           "B"   party initiating the transfer of "A"
622           "C"   party "A" is being transferred to
623 
624        The info["result"] will be at least one of the following:
625           "success"     Transfer completed successfully (party A or B)
626           "incoming"    New call was from a transfer (party C)
627           "started"     Transfer operation has started (party A)
628           "progress"    Transfer is in progress (party B)
629           "blind"       Transfer is blind, no further notification (party B)
630           "error"       Transfer could not begin (party B)
631           "failed"      Transfer started but did not complete (party A or B)
632 
633        For SIP, there may be an additional info["state"] containing the NOTIFY
634        subscription state, an info["code"] entry containing the 3 digit
635        code returned in the NOTIFY body and info["Referred-By"] indicating the
636        URI of party B. Other fields may also be present.
637 
638        The default behaviour returns false if info["result"] == "success".
639       */
640     virtual bool OnTransferNotify(
641       OpalConnection & connection,  ///< Connection being transferred.
642       const PStringToString & info  ///< Information on the transfer
643     );
644   //@}
645 
646 
647   /**@name Media Streams management */
648   //@{
649     /**Get common media formats.
650        This is called by various places to get common media formats for the
651        basic connection classes.
652 
653        The default behaviour uses the mediaFormatOrder and mediaFormatMask
654        member variables to adjust the mediaFormats list.
655       */
656     virtual OpalMediaFormatList GetCommonMediaFormats(
657       bool transportable,  ///< Include transportable media formats
658       bool pcmAudio        ///< Include raw PCM audio media formats
659     ) const;
660 
661     /**Adjust media formats available on a connection.
662        This is called by a connection after it has called
663        OpalCall::GetMediaFormats() to get all media formats that it can use so
664        that an application may remove or reorder the media formats before they
665        are used to open media streams.
666 
667        The default behaviour uses the mediaFormatOrder and mediaFormatMask
668        member variables to adjust the mediaFormats list.
669       */
670     virtual void AdjustMediaFormats(
671       bool local,                         ///<  Media formats a local ones to be presented to remote
672       const OpalConnection & connection,  ///<  Connection that is about to use formats
673       OpalMediaFormatList & mediaFormats  ///<  Media formats to use
674     ) const;
675 
676     /**See if the media can bypass the local host.
677      */
678     virtual PBoolean IsMediaBypassPossible(
679       const OpalConnection & source,      ///<  Source connection
680       const OpalConnection & destination, ///<  Destination connection
681       unsigned sessionID                  ///<  Session ID for media channel
682     ) const;
683 
684     /**Call back when opening a media stream.
685        This function is called when a connection has created a new media
686        stream according to the logic of its underlying protocol.
687 
688        The usual requirement is that media streams are created on all other
689        connections participating in the call and all of the media streams are
690        attached to an instance of an OpalMediaPatch object that will read from
691        one of the media streams passing data to the other media streams.
692 
693        The default behaviour achieves the above using the FindMatchingCodecs()
694        to determine what (if any) software codecs are required, the
695        OpalConnection::CreateMediaStream() function to open streams and the
696        CreateMediaPatch() function to create a patch for all of the streams
697        and codecs just produced.
698       */
699     virtual PBoolean OnOpenMediaStream(
700       OpalConnection & connection,  ///<  Connection that owns the media stream
701       OpalMediaStream & stream    ///<  New media stream being opened
702     );
703 
704     /**Create an RTP session.
705        This function allows an application to have the system create descendant
706        class versions of the RTP_UDP class. The application could use this to
707 	   modify the default RTP transfer behaviour.
708 	   This is called when a connection determines that RTP is required for
709 	   transporting media.
710        The default behaviour returns a new RTP_UDP.
711       */
712 	virtual RTP_UDP * CreateRTPSession (const RTP_Session::Params & params);
713 
714 	/**Callback from the RTP session for statistics monitoring.
715        This is called every so many packets on the transmitter and receiver
716        threads of the RTP session indicating that the statistics have been
717        updated.
718 
719        The default behaviour does nothing.
720       */
721     virtual void OnRTPStatistics(
722       const OpalConnection & connection,  ///<  Connection for the channel
723       const RTP_Session & session         ///<  Session with statistics
724     );
725 
726     /**Indicate is a local RTP connection.
727        This is called when a new media stream has been created and it has been
728        detected that media will be flowing between two RTP sessions within the
729        same process. An application could take advantage of this by optimising
730        the transfer in some way, rather than the full media path of codecs and
731        sockets which might not be necessary.
732 
733        Note this is the complement to SetMediaPassThrough() as this function stops
734        RTP data from being sent/received, while SetMediaPassThrough() transfers
735        RTP data between the two endpoints.
736 
737        The default behaviour returns false.
738 
739        @return true if the application is going to execute some form of
740                bypass, and the media patch threads should not be started.
741       */
742     virtual bool OnLocalRTP(
743       OpalConnection & connection1, ///< First connection
744       OpalConnection & connection2, ///< Second connection
745       unsigned sessionID,           ///< Session ID of RTP session
746       bool opened                   ///< Media streams are opened/closed
747     ) const;
748 
749     /**Set pass though mode for media.
750 
751        Bypass the internal media handling, passing RTP data directly from
752        one call/connection to another.
753 
754        This can be useful for back to back calls that happen to be the same
755        media format and you wish to avoid double decoding and encoding of
756        media. Note this scenario is not the same as two OpalConnections within
757        the same OpalCall, but two completely independent OpalCall where one
758        connection is to be bypassed. For example, two OpalCall instances might
759        have two SIPConnection instances and two OpalMixerConnection instances
760        connected via a single OpalMixerNode. Now while there are ONLY two
761        calls in the node, it is a waste to decode the audio, add to mixer and
762        re-encode it again. In practice this is identical to just bypassing the
763        mixer node completely, until a third party is added, then we need to
764        switch back to normal (non-pass-through) operation.
765 
766        Note this is the complement to OnLocalRTP() as this function transfers
767        RTP data directly between the two endpoints, while OnLocalRTP() stops
768        the RTP data from being sent/received.
769 
770        @return true if pass through is started/stopped, false if there was no
771                such call/connection/stream, the streams are incompatible formats
772                or a conflicting bypass is already in place.
773       */
774     bool SetMediaPassThrough(
775       const PString & token1, ///< First calls token
776       const PString & token2, ///< Second calls token
777       bool bypass,            ///< Bypass the media
778       unsigned sessionID = 0, ///< Session ID of media stream, 0 indicates all
779       bool network  = true    ///< Pass through the network connections of the calls only
780     );
781     static bool SetMediaPassThrough(
782       OpalConnection & connection1, ///< First connection
783       OpalConnection & connection2, ///< Second connection
784       bool bypass,                  ///< Bypass the media
785       unsigned sessionID = 0        ///< Session ID of media stream, 0 indicates all
786     );
787 
788     /**Call back for closed a media stream.
789 
790        The default behaviour does nothing.
791       */
792     virtual void OnClosedMediaStream(
793       const OpalMediaStream & stream     ///<  Stream being closed
794     );
795 
796 #if OPAL_VIDEO
797     /**Create a PVideoInputDevice for a source media stream.
798       */
799     virtual PBoolean CreateVideoInputDevice(
800       const OpalConnection & connection,    ///<  Connection needing created video device
801       const OpalMediaFormat & mediaFormat,  ///<  Media format for stream
802       PVideoInputDevice * & device,         ///<  Created device
803       PBoolean & autoDelete                     ///<  Flag for auto delete device
804     );
805 
806     /**Create an PVideoOutputDevice for a sink media stream or the preview
807        display for a source media stream.
808       */
809     virtual PBoolean CreateVideoOutputDevice(
810       const OpalConnection & connection,    ///<  Connection needing created video device
811       const OpalMediaFormat & mediaFormat,  ///<  Media format for stream
812       PBoolean preview,                         ///<  Flag indicating is a preview output
813       PVideoOutputDevice * & device,        ///<  Created device
814       PBoolean & autoDelete                     ///<  Flag for auto delete device
815     );
816 #endif
817 
818     /**Create a OpalMediaPatch instance.
819        This function allows an application to have the system create descendant
820        class versions of the OpalMediPatch class. The application could use
821        this to modify the default behaviour of a patch.
822 
823        The default behaviour returns an instance of OpalMediaPatch.
824       */
825     virtual OpalMediaPatch * CreateMediaPatch(
826       OpalMediaStream & source,         ///<  Source media stream
827       PBoolean requiresPatchThread = true  ///< The patch requires a thread
828     );
829 
830     /**Call back for a media patch thread starting.
831        This function is called within the context of the thread associated
832        with the media patch.
833 
834        The default behaviour does nothing
835       */
836     virtual void OnStartMediaPatch(
837       OpalConnection & connection,  ///< Connection patch is in
838       OpalMediaPatch & patch        ///< Media patch being started
839     );
840 
841     /**Call back when media stream patch thread stops.
842       */
843     virtual void OnStopMediaPatch(
844       OpalConnection & connection,  ///< Connection patch is in
845       OpalMediaPatch & patch        ///< Media Patch being stopped
846     );
847   //@}
848 
849   /**@name User indications */
850   //@{
851     /**Call back for remote endpoint has sent user input as a string.
852 
853        The default behaviour call OpalConnection::SetUserInput() which
854        saves the value so the GetUserInput() function can return it.
855       */
856     virtual void OnUserInputString(
857       OpalConnection & connection,  ///<  Connection input has come from
858       const PString & value         ///<  String value of indication
859     );
860 
861     /**Call back for remote enpoint has sent user input as tones.
862        If duration is zero then this indicates the beginning of the tone. If
863        duration is non-zero then it indicates the end of the tone output.
864 
865        The default behaviour calls the OpalCall function of the same name.
866       */
867     virtual void OnUserInputTone(
868       OpalConnection & connection,  ///<  Connection input has come from
869       char tone,                    ///<  Tone received
870       int duration                  ///<  Duration of tone
871     );
872 
873     /**Read a sequence of user indications from connection with timeouts.
874       */
875     virtual PString ReadUserInput(
876       OpalConnection & connection,        ///<  Connection to read input from
877       const char * terminators = "#\r\n", ///<  Characters that can terminte input
878       unsigned lastDigitTimeout = 4,      ///<  Timeout on last digit in string
879       unsigned firstDigitTimeout = 30     ///<  Timeout on receiving any digits
880     );
881   //@}
882 
883   /**@name Other services */
884   //@{
885     /// Message waiting sub-types
886     enum MessageWaitingType {
887       NoMessageWaiting,
888       VoiceMessageWaiting,
889       FaxMessageWaiting,
890       PagerMessageWaiting,
891       MultimediaMessageWaiting,
892       TextMessageWaiting,
893       NumMessageWaitingTypes
894     };
895 
896     /**Callback called when Message Waiting Indication (MWI) is received.
897        Multiple callbacks may occur with each MessageWaitingType. A \p type
898        of NumMessageWaitingTypes indicates the server is unable to distinguish
899        the message type.
900 
901        The \p extraInfo parameter is generally of the form "a/b" where a and b
902        unsigned integers representing new and old message count. However, it
903        may be a simple "yes" or "no" if the remote cannot provide a message
904        count.
905      */
906     virtual void OnMWIReceived(
907       const PString & party,    ///< Name of party MWI is for
908       MessageWaitingType type,  ///< Type of message that is waiting
909       const PString & extraInfo ///< Addition information on the MWI
910     );
911 
912 
913     class RouteEntry : public PObject
914     {
915         PCLASSINFO(RouteEntry, PObject);
916       public:
917         RouteEntry(const PString & pat, const PString & dest);
918         void PrintOn(ostream & strm) const;
919         PString            pattern;
920         PString            destination;
921         PRegularExpression regex;
922     };
923     PARRAY(RouteTable, RouteEntry);
924 
925     /**Add a route entry to the route table.
926 
927        The specification string is of the form:
928 
929                  pattern '=' destination
930        where:
931 
932             pattern      regular expression used to select route
933 
934             destination  destination for the call
935 
936        The "pattern" string regex is compared against routing strings that are built
937        as follows:
938 
939                  a_party '\\t' b_party
940 
941        where:
942 
943             a_party      name associated with a local connection i.e. "pots:vpb:1/2" or
944                          "h323:myname@myhost.com".
945 
946             b_party      destination specified by the call, which may be a full URI
947                          or a simple digit string
948 
949        Note that all "pattern" strings have an implied '^' at the beginning and
950        a '$' at the end. This forces the "pattern" to match the entire source string.
951        For convenience, the sub-expression ".*\\t" is inserted immediately after
952        any ':' character if no '\\t' is present.
953 
954        Route entries are stored and searched in the route table in the order they are added.
955 
956        The "destination" string is determines the endpoint used for the outbound
957        leg of the route, when a match to the "pattern" is found. It can be a literal string,
958        or can be constructed using various meta-strings that correspond to parts of the source.
959        See below for a list of the available meta-strings
960 
961        A "destination" starting with the string 'label:' causes the router to restart
962        searching from the beginning of the route table using the new string as the "a_party".
963        Thus, a route table with the folllwing entries:
964 
965                   "label:speeddial=h323:10.0.1.1"
966                   "pots:26=label:speeddial"
967 
968        will produce the same result as the single entry "pots:26=h323:10.0.1.1".
969 
970        If the "destination" parameter is of the form \@filename, then the file
971        is read with each line consisting of a pattern=destination route
972        specification.
973 
974        "destination" strings without an equal sign or beginning with '#' are ignored.
975 
976        Pattern Regex Examples:
977        -----------------------
978 
979        1) A local H.323 endpoint with with name of "myname@myhost.com" that receives a
980           call with a destination h323Id of "boris" would generate:
981 
982                           "h323:myname@myhost.com\\tboris"
983 
984        2) A local SIP endpoint with with name of "fred@nurk.com" that receives a
985           call with a destination of "sip:fred@nurk.com" would generate:
986 
987                           "sip:fred@nurk.com\\tsip:fred@nurk.com"
988 
989        3) Using line 0 of a PhoneJACK handset with a serial # of 01AB3F4 to dial
990           the digits 2, 6 and # would generate:
991 
992                           "pots:Quicknet:01AB3F4:0\\t26"
993 
994 
995        Destination meta-strings:
996        -------------------------
997 
998        The available meta-strings are:
999 
1000          <da>    Replaced by the "b_party" string. For example
1001                  "pc:.*\\t.* = sip:<da>" directs calls to the SIP protocol. In
1002                  this case there is a special condition where if the original
1003                  destination had a valid protocol, eg h323:fred.com, then
1004                  the entire string is replaced not just the <da> part.
1005 
1006          <db>    Same as <da>, but without the special condtion.
1007 
1008          <du>    Copy the "user" part of the "b_party" string. This is
1009                  essentially the component after the : and before the '@', or
1010                  the whole "b_party" string if these are not present.
1011 
1012          <!du>   The rest of the "b_party" string after the <du> section. The
1013                  protocol is still omitted. This is usually the '@' and onward.
1014                  Note if there is already an '@' in the destination before the
1015                  <!du> and what is abour to replace it also has an '@' then
1016                  everything between the @ and the <!du> (inclusive) is deleted,
1017                  then the substitution is made so a legal URL can result.
1018 
1019          <dn>    Copy all valid consecutive E.164 digits from the "b_party" so
1020                  pots:0061298765\@vpb:1/2 becomes sip:0061298765@carrier.com
1021 
1022          <dnX>   As above but skip X digits, eg <dn2> skips 2 digits, so
1023                  pots:00612198765 becomes sip:61298765@carrier.com
1024 
1025          <!dn>   The rest of the "b_party" after the <dn> or <dnX> sections.
1026 
1027          <dn2ip> Translate digits separated by '*' characters to an IP
1028                  address. e.g. 10*0*1*1 becomes 10.0.1.1, also
1029                  1234*10*0*1*1 becomes 1234\@10.0.1.1 and
1030                  1234*10*0*1*1*1722 becomes 1234\@10.0.1.1:1722.
1031 
1032 
1033        Returns true if an entry was added.
1034       */
1035     virtual PBoolean AddRouteEntry(
1036       const PString & spec  ///<  Specification string to add
1037     );
1038 
1039     /**Parse a route table specification list for the manager.
1040        This removes the current routeTable and calls AddRouteEntry for every
1041        string in the array.
1042 
1043        Returns true if at least one entry was added.
1044       */
1045     PBoolean SetRouteTable(
1046       const PStringArray & specs  ///<  Array of specification strings.
1047     );
1048 
1049     /**Set a route table for the manager.
1050        Note that this will make a copy of the table and not maintain a
1051        reference.
1052       */
1053     void SetRouteTable(
1054       const RouteTable & table  ///<  New table to set for routing
1055     );
1056 
1057     /**Get the active route table for the manager.
1058       */
GetRouteTable()1059     const RouteTable & GetRouteTable() const { return m_routeTable; }
1060 
1061     /**Route the source address to a destination using the route table.
1062        The source parameter may be something like pots:vpb:1/2 or
1063        sip:fred\@nurk.com.
1064 
1065        The destination parameter is a partial URL, it does not include the
1066        protocol, but may be of the form user\@host, or simply digits.
1067       */
1068     virtual PString ApplyRouteTable(
1069       const PString & source,      ///< Source address, including endpoint protocol
1070       const PString & destination, ///< Destination address read from source protocol
1071       PINDEX & entry               ///< Index into table to start search
1072     );
1073   //@}
1074 
1075 #if OPAL_HAS_MIXER
1076   /**@name Call recording */
1077   //@{
1078     /**Start recording a call.
1079        Current version saves to a WAV file. It may either mix the receive and
1080        transmit audio stream to a single mono file, or the streams are placed
1081        into the left and right channels of a stereo WAV file.
1082 
1083        Returns true if the call exists and there is no recording in progress
1084                for the call.
1085       */
1086     virtual PBoolean StartRecording(
1087       const PString & callToken,  ///< Call token for call to record
1088       const PFilePath & filename, ///< File into which to record
1089       const OpalRecordManager::Options & options = false ///< Record mixing options
1090     );
1091 
1092     /**Indicate if recording is currently active on call.
1093       */
1094     virtual bool IsRecording(
1095       const PString & callToken   ///< Call token for call to check if recording
1096     );
1097 
1098     /** Stop a recording.
1099         Returns true if the call does exists, that recording is active is
1100                 not indicated.
1101       */
1102     virtual bool StopRecording(
1103       const PString & callToken   ///< Call token for call to stop recording
1104     );
1105 
1106   //@}
1107 #endif
1108 
1109   /**@name Member variable access */
1110   //@{
1111     /**Get the product info for all endpoints.
1112       */
GetProductInfo()1113     const OpalProductInfo & GetProductInfo() const { return productInfo; }
1114 
1115     /**Set the product info for all endpoints.
1116       */
1117     void SetProductInfo(
1118       const OpalProductInfo & info, ///< New information
1119       bool updateAll = true         ///< Update all registered endpoints
1120     );
1121 
1122     /**Get the default username for all endpoints.
1123       */
GetDefaultUserName()1124     const PString & GetDefaultUserName() const { return defaultUserName; }
1125 
1126     /**Set the default username for all endpoints.
1127       */
1128     void SetDefaultUserName(
1129       const PString & name,   ///< New name
1130       bool updateAll = true   ///< Update all registered endpoints
1131     );
1132 
1133     /**Get the default display name for all endpoints.
1134       */
GetDefaultDisplayName()1135     const PString & GetDefaultDisplayName() const { return defaultDisplayName; }
1136 
1137     /**Set the default display name for all endpoints.
1138       */
1139     void SetDefaultDisplayName(
1140       const PString & name,   ///< New name
1141       bool updateAll = true   ///< Update all registered endpoints
1142     );
1143 
1144 #if OPAL_VIDEO
1145 
1146     //
1147     // these functions are deprecated and used only for backwards compatibility
1148     // applications should use OpalConnection::GetAutoStart() to check whether
1149     // a specific media type can be auto-started
1150     //
1151 
1152     /**See if should auto-start receive video channels on connection.
1153      */
CanAutoStartReceiveVideo()1154     bool CanAutoStartReceiveVideo() const { return (OpalMediaType::Video().GetAutoStart()&OpalMediaType::Receive) != 0; }
1155 
1156     /**Set if should auto-start receive video channels on connection.
1157      */
SetAutoStartReceiveVideo(bool can)1158     void SetAutoStartReceiveVideo(bool can) { OpalMediaType::Video().GetDefinition()->SetAutoStart(OpalMediaType::Receive, can); }
1159 
1160     /**See if should auto-start transmit video channels on connection.
1161      */
CanAutoStartTransmitVideo()1162     bool CanAutoStartTransmitVideo() const { return (OpalMediaType::Video().GetAutoStart()&OpalMediaType::Transmit) != 0; }
1163 
1164     /**Set if should auto-start transmit video channels on connection.
1165      */
SetAutoStartTransmitVideo(bool can)1166     void SetAutoStartTransmitVideo(bool can) { OpalMediaType::Video().GetDefinition()->SetAutoStart(OpalMediaType::Transmit, can); }
1167 
1168 #endif
1169 
1170     /**Determine if the address is "local", ie does not need any address
1171        translation (fixed or via STUN) to access.
1172 
1173        The default behaviour checks if remoteAddress is a RFC1918 private
1174        IP address: 10.x.x.x, 172.16.x.x or 192.168.x.x.
1175      */
1176     virtual PBoolean IsLocalAddress(
1177       const PIPSocket::Address & remoteAddress
1178     ) const;
1179 
1180     /**Determine if the RTP session needs to accommodate a NAT router.
1181        For endpoints that do not use STUN or something similar to set up all the
1182        correct protocol embeddded addresses correctly when a NAT router is between
1183        the endpoints, it is possible to still accommodate the call, with some
1184        restrictions. This function determines if the RTP can proceed with special
1185        NAT allowances.
1186 
1187        The special allowance is that the RTP code will ignore whatever the remote
1188        indicates in the protocol for the address to send RTP data and wait for
1189        the first packet to arrive from the remote and will then proceed to send
1190        all RTP data back to that address AND port.
1191 
1192        The default behaviour checks the values of the physical link
1193        (localAddr/peerAddr) against the signaling address the remote indicated in
1194        the protocol, eg H.323 SETUP sourceCallSignalAddress or SIP "To" or
1195        "Contact" fields, and makes a guess that the remote is behind a NAT router.
1196      */
1197     virtual PBoolean IsRTPNATEnabled(
1198       OpalConnection & connection,            ///< Connection being checked
1199       const PIPSocket::Address & localAddr,   ///< Local physical address of connection
1200       const PIPSocket::Address & peerAddr,    ///< Remote physical address of connection
1201       const PIPSocket::Address & signalAddr,  ///< Remotes signaling address as indicated by protocol of connection
1202       PBoolean incoming                       ///< Incoming/outgoing connection
1203     );
1204 
1205     /**Provide address translation hook.
1206        This will check to see that remoteAddress is NOT a local address by
1207        using IsLocalAddress() and if not, set localAddress to the
1208        translationAddress (if valid) which would normally be the router
1209        address of a NAT system.
1210      */
1211     virtual PBoolean TranslateIPAddress(
1212       PIPSocket::Address & localAddress,
1213       const PIPSocket::Address & remoteAddress
1214     );
1215 
1216     /**Get the translation host to use for TranslateIPAddress().
1217       */
GetTranslationHost()1218     const PString & GetTranslationHost() const { return translationHost; }
1219 
1220     /**Set the translation host to use for TranslateIPAddress().
1221       */
1222     bool SetTranslationHost(
1223       const PString & host
1224     );
1225 
1226     /**Get the translation address to use for TranslateIPAddress().
1227       */
GetTranslationAddress()1228     const PIPSocket::Address & GetTranslationAddress() const { return translationAddress; }
1229 
1230     /**Set the translation address to use for TranslateIPAddress().
1231       */
1232     void SetTranslationAddress(
1233       const PIPSocket::Address & address
1234     );
1235 
1236     /**Return the NAT method to use.
1237        Returns NULL if address is a local address as per IsLocalAddress().
1238        Always returns the NAT method if address is zero.
1239        Note, the pointer is NOT to be deleted by the user.
1240       */
1241     virtual PNatMethod * GetNatMethod(
1242       const PIPSocket::Address & remoteAddress = PIPSocket::GetDefaultIpAny()
1243     ) const;
1244 
1245     /**Set the STUN server address, is of the form host[:port]
1246        Note that if the STUN server is found then the translationAddress
1247        is automatically set to the router address as determined by STUN.
1248       */
1249     PSTUNClient::NatTypes SetSTUNServer(
1250       const PString & server
1251     );
1252 
1253     /**Get the current host name and optional port for the STUN server.
1254       */
GetSTUNServer()1255     const PString & GetSTUNServer() const { return stunServer; }
1256 
1257     /**Return the STUN client instance in use.
1258       */
GetSTUNClient()1259     PSTUNClient * GetSTUNClient() const { return stun; }
1260 
1261     /**Get the TCP port number base for H.245 channels
1262      */
GetTCPPortBase()1263     WORD GetTCPPortBase() const { return tcpPorts.base; }
1264 
1265     /**Get the TCP port number base for H.245 channels.
1266      */
GetTCPPortMax()1267     WORD GetTCPPortMax() const { return tcpPorts.max; }
1268 
1269     /**Set the TCP port number base and max for H.245 channels.
1270      */
1271     void SetTCPPorts(unsigned tcpBase, unsigned tcpMax);
1272 
1273     /**Get the next TCP port number for H.245 channels
1274      */
1275     WORD GetNextTCPPort();
1276 
1277     /**Get the UDP port number base for RAS channels
1278      */
GetUDPPortBase()1279     WORD GetUDPPortBase() const { return udpPorts.base; }
1280 
1281     /**Get the UDP port number base for RAS channels.
1282      */
GetUDPPortMax()1283     WORD GetUDPPortMax() const { return udpPorts.max; }
1284 
1285     /**Set the TCP port number base and max for H.245 channels.
1286      */
1287     void SetUDPPorts(unsigned udpBase, unsigned udpMax);
1288 
1289     /**Get the next UDP port number for RAS channels
1290      */
1291     WORD GetNextUDPPort();
1292 
1293     /**Get the UDP port number base for RTP channels.
1294      */
GetRtpIpPortBase()1295     WORD GetRtpIpPortBase() const { return rtpIpPorts.base; }
1296 
1297     /**Get the max UDP port number for RTP channels.
1298      */
GetRtpIpPortMax()1299     WORD GetRtpIpPortMax() const { return rtpIpPorts.max; }
1300 
1301     /**Set the UDP port number base and max for RTP channels.
1302      */
1303     void SetRtpIpPorts(unsigned udpBase, unsigned udpMax);
1304 
1305     /**Get the UDP port number pair for RTP channels.
1306      */
1307     WORD GetRtpIpPortPair();
1308 
1309     /**Get the IP Type Of Service byte for media (eg RTP) channels.
1310      */
GetMediaTypeOfService()1311     BYTE GetMediaTypeOfService() const { return m_defaultMediaTypeOfService; }
1312 
1313     /**Set the IP Type Of Service byte for media (eg RTP) channels.
1314      */
SetMediaTypeOfService(unsigned tos)1315     void SetMediaTypeOfService(unsigned tos) { m_defaultMediaTypeOfService = (BYTE)tos; }
1316 
1317     // For backward compatibility
GetRtpIpTypeofService()1318     BYTE P_DEPRECATED GetRtpIpTypeofService() const { return m_defaultMediaTypeOfService; }
SetRtpIpTypeofService(unsigned tos)1319     void P_DEPRECATED SetRtpIpTypeofService(unsigned tos) { m_defaultMediaTypeOfService = (BYTE)tos; }
1320 
1321     /**Get the IP Type Of Service byte for media (eg RTP) channels.
1322      */
1323     BYTE GetMediaTypeOfService(const OpalMediaType & type) const;
1324 
1325     /**Set the IP Type Of Service byte for media (eg RTP) channels.
1326      */
1327     void SetMediaTypeOfService(const OpalMediaType & type, unsigned tos);
1328 
1329     /**Get the maximum transmitted RTP payload size.
1330        Defaults to maximum safe MTU size (576 bytes as per RFC879) minus the
1331        typical size of the IP, UDP an RTP headers.
1332       */
GetMaxRtpPayloadSize()1333     PINDEX GetMaxRtpPayloadSize() const { return rtpPayloadSizeMax; }
1334 
1335     /**Get the maximum transmitted RTP payload size.
1336        Defaults to maximum safe MTU size (576 bytes as per RFC879) minus the
1337        typical size of the IP, UDP an RTP headers.
1338       */
1339     void SetMaxRtpPayloadSize(
1340       PINDEX size,
1341       bool mtu = false
1342     ) { rtpPayloadSizeMax = size - (mtu ? (20+16+12) : 0); }
1343 
1344     /**Get the maximum received RTP packet size.
1345        Defaults to 2048.
1346       */
GetMaxRtpPacketSize()1347     PINDEX GetMaxRtpPacketSize() const { return rtpPacketSizeMax; }
1348 
1349     /**Get the maximum transmitted RTP payload size.
1350        Defaults to 2048.
1351       */
SetMaxRtpPacketSize(PINDEX size)1352     void SetMaxRtpPacketSize(
1353       PINDEX size
1354     ) { rtpPacketSizeMax = size; }
1355 
1356     /**Get the default maximum audio jitter delay parameter.
1357        Defaults to 50ms
1358      */
GetMinAudioJitterDelay()1359     unsigned GetMinAudioJitterDelay() const { return minAudioJitterDelay; }
1360 
1361     /**Get the default maximum audio jitter delay parameter.
1362        Defaults to 250ms.
1363      */
GetMaxAudioJitterDelay()1364     unsigned GetMaxAudioJitterDelay() const { return maxAudioJitterDelay; }
1365 
1366     /**Set the maximum audio jitter delay parameter.
1367 
1368        If minDelay is set to zero then both the minimum and maximum will be
1369        set to zero which will disable the jitter buffer entirely.
1370 
1371        If maxDelay is zero, or just less that minDelay, then the maximum
1372        jitter is set to the minimum and this disables the adaptive jitter, a
1373        fixed value is used.
1374      */
1375     void SetAudioJitterDelay(
1376       unsigned minDelay,   ///<  New minimum jitter buffer delay in milliseconds
1377       unsigned maxDelay    ///<  New maximum jitter buffer delay in milliseconds
1378     );
1379 
1380     /**Get the default media format order.
1381      */
GetMediaFormatOrder()1382     const PStringArray & GetMediaFormatOrder() const { return mediaFormatOrder; }
1383 
1384     /**Set the default media format order.
1385      */
1386     void SetMediaFormatOrder(
1387       const PStringArray & order   ///< New order
1388     );
1389 
1390     /**Get the default media format mask.
1391        The is the default list of media format names to be removed from media
1392        format lists bfeore use by a connection.
1393        See OpalMediaFormatList::Remove() for more information.
1394      */
GetMediaFormatMask()1395     const PStringArray & GetMediaFormatMask() const { return mediaFormatMask; }
1396 
1397     /**Set the default media format mask.
1398        The is the default list of media format names to be removed from media
1399        format lists bfeore use by a connection.
1400        See OpalMediaFormatList::Remove() for more information.
1401      */
1402     void SetMediaFormatMask(
1403       const PStringArray & mask   //< New mask
1404     );
1405 
1406     /**Set the default parameters for the silence detector.
1407      */
SetSilenceDetectParams(const OpalSilenceDetector::Params & params)1408     virtual void SetSilenceDetectParams(
1409       const OpalSilenceDetector::Params & params
1410     ) { silenceDetectParams = params; }
1411 
1412     /**Get the default parameters for the silence detector.
1413      */
GetSilenceDetectParams()1414     const OpalSilenceDetector::Params & GetSilenceDetectParams() const { return silenceDetectParams; }
1415 
1416 #if OPAL_AEC
1417     /**Set the default parameters for the echo cancelation.
1418      */
SetEchoCancelParams(const OpalEchoCanceler::Params & params)1419     virtual void SetEchoCancelParams(
1420       const OpalEchoCanceler::Params & params
1421     ) { echoCancelParams = params; }
1422 
1423     /**Get the default parameters for the silence detector.
1424      */
GetEchoCancelParams()1425     const OpalEchoCanceler::Params & GetEchoCancelParams() const { return echoCancelParams; }
1426 #endif
1427 
1428 #if OPAL_VIDEO
1429 
1430     /**Set the parameters for the video device to be used for input.
1431        If the name is not suitable for use with the PVideoInputDevice class
1432        then the function will return false and not change the device.
1433 
1434        This defaults to the value of the PVideoInputDevice::GetInputDeviceNames()
1435        function.
1436      */
1437     virtual PBoolean SetVideoInputDevice(
1438       const PVideoDevice::OpenArgs & deviceArgs ///<  Full description of device
1439     );
1440 
1441     /**Get the parameters for the video device to be used for input.
1442        This defaults to the value of the PSoundChannel::GetInputDeviceNames()[0].
1443      */
GetVideoInputDevice()1444     const PVideoDevice::OpenArgs & GetVideoInputDevice() const { return videoInputDevice; }
1445 
1446     /**Set the parameters for the video device to be used to preview input.
1447        If the name is not suitable for use with the PVideoOutputDevice class
1448        then the function will return false and not change the device.
1449 
1450        This defaults to the value of the PVideoInputDevice::GetOutputDeviceNames()
1451        function.
1452      */
1453     virtual PBoolean SetVideoPreviewDevice(
1454       const PVideoDevice::OpenArgs & deviceArgs ///<  Full description of device
1455     );
1456 
1457     /**Get the parameters for the video device to be used for input.
1458        This defaults to the value of the PSoundChannel::GetInputDeviceNames()[0].
1459      */
GetVideoPreviewDevice()1460     const PVideoDevice::OpenArgs & GetVideoPreviewDevice() const { return videoPreviewDevice; }
1461 
1462     /**Set the parameters for the video device to be used for output.
1463        If the name is not suitable for use with the PVideoOutputDevice class
1464        then the function will return false and not change the device.
1465 
1466        This defaults to the value of the PVideoInputDevice::GetOutputDeviceNames()
1467        function.
1468      */
1469     virtual PBoolean SetVideoOutputDevice(
1470       const PVideoDevice::OpenArgs & deviceArgs ///<  Full description of device
1471     );
1472 
1473     /**Get the parameters for the video device to be used for input.
1474        This defaults to the value of the PSoundChannel::GetOutputDeviceNames()[0].
1475      */
GetVideoOutputDevice()1476     const PVideoDevice::OpenArgs & GetVideoOutputDevice() const { return videoOutputDevice; }
1477 
1478 #endif
1479 
DetectInBandDTMFDisabled()1480     PBoolean DetectInBandDTMFDisabled() const
1481       { return disableDetectInBandDTMF; }
1482 
1483     /**Set the default H.245 tunneling mode.
1484       */
DisableDetectInBandDTMF(PBoolean mode)1485     void DisableDetectInBandDTMF(
1486       PBoolean mode ///<  New default mode
1487     ) { disableDetectInBandDTMF = mode; }
1488 
1489     /**Get the amount of time with no media that should cause a call to clear
1490      */
GetNoMediaTimeout()1491     const PTimeInterval & GetNoMediaTimeout() const { return noMediaTimeout; }
1492 
1493     /**Set the amount of time with no media that should cause a call to clear
1494      */
1495     PBoolean SetNoMediaTimeout(
1496       const PTimeInterval & newInterval  ///<  New timeout for media
1497     );
1498 
1499     /**Get the default ILS server to use for user lookup.
1500       */
GetDefaultILSServer()1501     const PString & GetDefaultILSServer() const { return ilsServer; }
1502 
1503     /**Set the default ILS server to use for user lookup.
1504       */
SetDefaultILSServer(const PString & server)1505     void SetDefaultILSServer(
1506       const PString & server
1507     ) { ilsServer = server; }
1508   //@}
1509 
1510     // needs to be public for gcc 3.4
1511     void GarbageCollection();
1512 
1513 #ifdef OPAL_ZRTP
1514     virtual bool GetZRTPEnabled() const;
1515 #endif
1516 
1517     virtual void OnApplyStringOptions(
1518       OpalConnection & conn,
1519       OpalConnection::StringOptions & stringOptions
1520     );
1521 
1522   protected:
1523     // Configuration variables
1524     OpalProductInfo productInfo;
1525 
1526     PString       defaultUserName;
1527     PString       defaultDisplayName;
1528 
1529     BYTE                     m_defaultMediaTypeOfService;
1530     map<OpalMediaType, BYTE> m_mediaTypeOfService;
1531 
1532     PINDEX        rtpPayloadSizeMax;
1533     PINDEX        rtpPacketSizeMax;
1534     unsigned      minAudioJitterDelay;
1535     unsigned      maxAudioJitterDelay;
1536     PStringArray  mediaFormatOrder;
1537     PStringArray  mediaFormatMask;
1538     PBoolean          disableDetectInBandDTMF;
1539     PTimeInterval noMediaTimeout;
1540     PString       ilsServer;
1541 
1542     OpalSilenceDetector::Params silenceDetectParams;
1543 #if OPAL_AEC
1544     OpalEchoCanceler::Params echoCancelParams;
1545 #endif
1546 
1547 #if OPAL_VIDEO
1548     PVideoDevice::OpenArgs videoInputDevice;
1549     PVideoDevice::OpenArgs videoPreviewDevice;
1550     PVideoDevice::OpenArgs videoOutputDevice;
1551 #endif
1552 
1553     struct PortInfo {
1554       void Set(
1555         unsigned base,
1556         unsigned max,
1557         unsigned range,
1558         unsigned dflt
1559       );
1560       WORD GetNext(
1561         unsigned increment
1562       );
1563 
1564       PMutex mutex;
1565       WORD   base;
1566       WORD   max;
1567       WORD   current;
1568     } tcpPorts, udpPorts, rtpIpPorts;
1569 
1570     class InterfaceMonitor : public PInterfaceMonitorClient
1571     {
1572       PCLASSINFO(InterfaceMonitor, PInterfaceMonitorClient);
1573 
1574       enum {
1575         OpalManagerInterfaceMonitorClientPriority = 100,
1576       };
1577       public:
1578         InterfaceMonitor(OpalManager & manager);
1579 
1580       protected:
1581         virtual void OnAddInterface(const PIPSocket::InterfaceEntry & entry);
1582         virtual void OnRemoveInterface(const PIPSocket::InterfaceEntry & entry);
1583 
1584         OpalManager & m_manager;
1585     };
1586 
1587     PString            translationHost;
1588     PIPSocket::Address translationAddress;
1589     PString            stunServer;
1590     PSTUNClient      * stun;
1591     InterfaceMonitor * interfaceMonitor;
1592 
1593     RouteTable m_routeTable;
1594     PMutex     m_routeMutex;
1595 
1596     // Dynamic variables
1597     PReadWriteMutex     endpointsMutex;
1598     PList<OpalEndPoint> endpointList;
1599     std::map<PString, OpalEndPoint *> endpointMap;
1600 
1601     PAtomicInteger lastCallTokenID;
1602 
1603     class CallDict : public PSafeDictionary<PString, OpalCall>
1604     {
1605       public:
CallDict(OpalManager & mgr)1606         CallDict(OpalManager & mgr) : manager(mgr) { }
1607         virtual void DeleteObject(PObject * object) const;
1608         OpalManager & manager;
1609     } activeCalls;
1610 
1611     PSafeDictionary<PString, OpalPresentity> m_presentities;
1612 
1613     PAtomicInteger m_clearingAllCallsCount;
1614     PMutex         m_clearingAllCallsMutex;
1615     PSyncPoint     m_allCallsCleared;
1616     void InternalClearAllCalls(OpalConnection::CallEndReason reason, bool wait, bool first);
1617 
1618     PThread    * garbageCollector;
1619     PSyncPoint   garbageCollectExit;
1620     bool         garbageCollectSkip;
1621     PDECLARE_NOTIFIER(PThread, OpalManager, GarbageMain);
1622 
1623 #ifdef OPAL_ZRTP
1624     bool zrtpEnabled;
1625 #endif
1626 
1627     friend OpalCall::OpalCall(OpalManager & mgr);
1628     friend void OpalCall::InternalOnClear();
1629 
1630   private:
1631     P_REMOVE_VIRTUAL(OpalCall *,CreateCall(), 0);
1632     P_REMOVE_VIRTUAL(PBoolean, OnIncomingConnection(OpalConnection &, unsigned), false);
1633     P_REMOVE_VIRTUAL(PBoolean, OnIncomingConnection(OpalConnection &), false);
1634     P_REMOVE_VIRTUAL(PBoolean, OnStartMediaPatch(const OpalMediaPatch &), false);
1635     P_REMOVE_VIRTUAL_VOID(AdjustMediaFormats(const OpalConnection &, OpalMediaFormatList &) const);
1636     P_REMOVE_VIRTUAL_VOID(OnMessageReceived(const PURL&,const PString&,const PURL&,const PString&,const PString&,const PString&));
1637 
1638 
1639 #ifdef OPAL_HAS_IM
1640   public:
GetIMManager()1641     OpalIMManager & GetIMManager() { return *m_imManager; }
1642 
1643   protected:
1644     OpalIMManager * m_imManager;
1645 #endif
1646 };
1647 
1648 
1649 PString  OpalGetVersion();
1650 unsigned OpalGetMajorVersion();
1651 unsigned OpalGetMinorVersion();
1652 unsigned OpalGetBuildNumber();
1653 
1654 
1655 #endif // OPAL_OPAL_MANAGER_H
1656 
1657 
1658 // End of File ///////////////////////////////////////////////////////////////
1659