code stringlengths 4 1.01M |
|---|
package v1
import (
configv1 "github.com/openshift/api/config/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
)
var (
GroupName = "operator.openshift.io"
GroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1"}
schemeBuilder = runtime.NewSchemeBuilder(addKnownTypes, configv1.Install)
// Install is a function which adds this version to a scheme
Install = schemeBuilder.AddToScheme
// SchemeGroupVersion generated code relies on this name
// Deprecated
SchemeGroupVersion = GroupVersion
// AddToScheme exists solely to keep the old generators creating valid code
// DEPRECATED
AddToScheme = schemeBuilder.AddToScheme
)
// Resource generated code relies on this being here, but it logically belongs to the group
// DEPRECATED
func Resource(resource string) schema.GroupResource {
return schema.GroupResource{Group: GroupName, Resource: resource}
}
func addKnownTypes(scheme *runtime.Scheme) error {
metav1.AddToGroupVersion(scheme, GroupVersion)
scheme.AddKnownTypes(GroupVersion,
&Authentication{},
&AuthenticationList{},
&DNS{},
&DNSList{},
&CloudCredential{},
&CloudCredentialList{},
&ClusterCSIDriver{},
&ClusterCSIDriverList{},
&Console{},
&ConsoleList{},
&CSISnapshotController{},
&CSISnapshotControllerList{},
&Etcd{},
&EtcdList{},
&KubeAPIServer{},
&KubeAPIServerList{},
&KubeControllerManager{},
&KubeControllerManagerList{},
&KubeScheduler{},
&KubeSchedulerList{},
&KubeStorageVersionMigrator{},
&KubeStorageVersionMigratorList{},
&Network{},
&NetworkList{},
&OpenShiftAPIServer{},
&OpenShiftAPIServerList{},
&OpenShiftControllerManager{},
&OpenShiftControllerManagerList{},
&ServiceCA{},
&ServiceCAList{},
&ServiceCatalogAPIServer{},
&ServiceCatalogAPIServerList{},
&ServiceCatalogControllerManager{},
&ServiceCatalogControllerManagerList{},
&IngressController{},
&IngressControllerList{},
&Storage{},
&StorageList{},
)
return nil
}
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>SuperLU: NRformat_loc Struct Reference</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">
</head><body>
<!-- Generated by Doxygen 1.5.5 -->
<div class="navigation" id="top">
<div class="tabs">
<ul>
<li><a href="index.html"><span>Main Page</span></a></li>
<li class="current"><a href="annotated.html"><span>Data Structures</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div class="tabs">
<ul>
<li><a href="annotated.html"><span>Data Structures</span></a></li>
<li><a href="functions.html"><span>Data Fields</span></a></li>
</ul>
</div>
</div>
<div class="contents">
<h1>NRformat_loc Struct Reference</h1><!-- doxytag: class="NRformat_loc" --><code>#include <<a class="el" href="supermatrix_8h-source.html">supermatrix.h</a>></code>
<p>
<table border="0" cellpadding="0" cellspacing="0">
<tr><td></td></tr>
<tr><td colspan="2"><br><h2>Data Fields</h2></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="el" href="slu__zdefs_8h.html#b6fd6105e64ed14a0c9281326f05e623">int_t</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="structNRformat__loc.html#41c309cb83dedeaa82c0e4e137ea4785">nnz_loc</a></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="el" href="slu__zdefs_8h.html#b6fd6105e64ed14a0c9281326f05e623">int_t</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="structNRformat__loc.html#90413dc3eb197a83b70cc0d97e4c54af">m_loc</a></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="el" href="slu__zdefs_8h.html#b6fd6105e64ed14a0c9281326f05e623">int_t</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="structNRformat__loc.html#cab0ad4c74c4b4f0c68647f98b430cd9">fst_row</a></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">void * </td><td class="memItemRight" valign="bottom"><a class="el" href="structNRformat__loc.html#08b19d74f15e6475f43565035ae898ca">nzval</a></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="el" href="slu__zdefs_8h.html#b6fd6105e64ed14a0c9281326f05e623">int_t</a> * </td><td class="memItemRight" valign="bottom"><a class="el" href="structNRformat__loc.html#add0788ee704ffb7000b0485ee128061">rowptr</a></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="el" href="slu__zdefs_8h.html#b6fd6105e64ed14a0c9281326f05e623">int_t</a> * </td><td class="memItemRight" valign="bottom"><a class="el" href="structNRformat__loc.html#5d192fc35ba0915afa42f36eca0e2d78">colind</a></td></tr>
</table>
<hr><h2>Field Documentation</h2>
<a class="anchor" name="41c309cb83dedeaa82c0e4e137ea4785"></a><!-- doxytag: member="NRformat_loc::nnz_loc" ref="41c309cb83dedeaa82c0e4e137ea4785" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="slu__zdefs_8h.html#b6fd6105e64ed14a0c9281326f05e623">int_t</a> <a class="el" href="structNRformat__loc.html#41c309cb83dedeaa82c0e4e137ea4785">NRformat_loc::nnz_loc</a> </td>
</tr>
</table>
</div>
<div class="memdoc">
<p>
</div>
</div><p>
<a class="anchor" name="90413dc3eb197a83b70cc0d97e4c54af"></a><!-- doxytag: member="NRformat_loc::m_loc" ref="90413dc3eb197a83b70cc0d97e4c54af" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="slu__zdefs_8h.html#b6fd6105e64ed14a0c9281326f05e623">int_t</a> <a class="el" href="structNRformat__loc.html#90413dc3eb197a83b70cc0d97e4c54af">NRformat_loc::m_loc</a> </td>
</tr>
</table>
</div>
<div class="memdoc">
<p>
</div>
</div><p>
<a class="anchor" name="cab0ad4c74c4b4f0c68647f98b430cd9"></a><!-- doxytag: member="NRformat_loc::fst_row" ref="cab0ad4c74c4b4f0c68647f98b430cd9" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="slu__zdefs_8h.html#b6fd6105e64ed14a0c9281326f05e623">int_t</a> <a class="el" href="structNRformat__loc.html#cab0ad4c74c4b4f0c68647f98b430cd9">NRformat_loc::fst_row</a> </td>
</tr>
</table>
</div>
<div class="memdoc">
<p>
</div>
</div><p>
<a class="anchor" name="08b19d74f15e6475f43565035ae898ca"></a><!-- doxytag: member="NRformat_loc::nzval" ref="08b19d74f15e6475f43565035ae898ca" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void* <a class="el" href="structNRformat__loc.html#08b19d74f15e6475f43565035ae898ca">NRformat_loc::nzval</a> </td>
</tr>
</table>
</div>
<div class="memdoc">
<p>
</div>
</div><p>
<a class="anchor" name="add0788ee704ffb7000b0485ee128061"></a><!-- doxytag: member="NRformat_loc::rowptr" ref="add0788ee704ffb7000b0485ee128061" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="slu__zdefs_8h.html#b6fd6105e64ed14a0c9281326f05e623">int_t</a>* <a class="el" href="structNRformat__loc.html#add0788ee704ffb7000b0485ee128061">NRformat_loc::rowptr</a> </td>
</tr>
</table>
</div>
<div class="memdoc">
<p>
</div>
</div><p>
<a class="anchor" name="5d192fc35ba0915afa42f36eca0e2d78"></a><!-- doxytag: member="NRformat_loc::colind" ref="5d192fc35ba0915afa42f36eca0e2d78" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="slu__zdefs_8h.html#b6fd6105e64ed14a0c9281326f05e623">int_t</a>* <a class="el" href="structNRformat__loc.html#5d192fc35ba0915afa42f36eca0e2d78">NRformat_loc::colind</a> </td>
</tr>
</table>
</div>
<div class="memdoc">
<p>
</div>
</div><p>
<hr>The documentation for this struct was generated from the following file:<ul>
<li>SRC/<a class="el" href="supermatrix_8h-source.html">supermatrix.h</a></ul>
</div>
<hr size="1"><address style="text-align: right;"><small>Generated on Mon Nov 22 10:23:48 2010 for SuperLU by
<a href="http://www.doxygen.org/index.html">
<img src="doxygen.png" alt="doxygen" align="middle" border="0"></a> 1.5.5 </small></address>
</body>
</html>
|
*> \brief \b ZERRSYX
*
* =========== DOCUMENTATION ===========
*
* Online html documentation available at
* http://www.netlib.org/lapack/explore-html/
*
* Definition:
* ===========
*
* SUBROUTINE ZERRSY( PATH, NUNIT )
*
* .. Scalar Arguments ..
* CHARACTER*3 PATH
* INTEGER NUNIT
* ..
*
*
*> \par Purpose:
* =============
*>
*> \verbatim
*>
*> ZERRSY tests the error exits for the COMPLEX*16 routines
*> for symmetric indefinite matrices.
*>
*> Note that this file is used only when the XBLAS are available,
*> otherwise zerrsy.f defines this subroutine.
*> \endverbatim
*
* Arguments:
* ==========
*
*> \param[in] PATH
*> \verbatim
*> PATH is CHARACTER*3
*> The LAPACK path name for the routines to be tested.
*> \endverbatim
*>
*> \param[in] NUNIT
*> \verbatim
*> NUNIT is INTEGER
*> The unit number for output.
*> \endverbatim
*
* Authors:
* ========
*
*> \author Univ. of Tennessee
*> \author Univ. of California Berkeley
*> \author Univ. of Colorado Denver
*> \author NAG Ltd.
*
*> \date November 2013
*
*> \ingroup complex16_lin
*
* =====================================================================
SUBROUTINE ZERRSY( PATH, NUNIT )
*
* -- LAPACK test routine (version 3.5.0) --
* -- LAPACK is a software package provided by Univ. of Tennessee, --
* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..--
* November 2013
*
* .. Scalar Arguments ..
CHARACTER*3 PATH
INTEGER NUNIT
* ..
*
* =====================================================================
*
* .. Parameters ..
INTEGER NMAX
PARAMETER ( NMAX = 4 )
* ..
* .. Local Scalars ..
CHARACTER EQ
CHARACTER*2 C2
INTEGER I, INFO, J, N_ERR_BNDS, NPARAMS
DOUBLE PRECISION ANRM, RCOND, BERR
* ..
* .. Local Arrays ..
INTEGER IP( NMAX )
DOUBLE PRECISION R( NMAX ), R1( NMAX ), R2( NMAX ),
$ S( NMAX ), ERR_BNDS_N( NMAX, 3 ),
$ ERR_BNDS_C( NMAX, 3 ), PARAMS( 1 )
COMPLEX*16 A( NMAX, NMAX ), AF( NMAX, NMAX ), B( NMAX ),
$ W( 2*NMAX ), X( NMAX )
* ..
* .. External Functions ..
LOGICAL LSAMEN
EXTERNAL LSAMEN
* ..
* .. External Subroutines ..
EXTERNAL ALAESM, CHKXER, ZSPCON, ZSPRFS, ZSPTRF, ZSPTRI,
$ ZSPTRS, ZSYCON, ZSYCON_ROOK, ZSYRFS, ZSYTF2,
$ ZSYTF2_ROOK, ZSYTRF, ZSYTRF_ROOK, ZSYTRI,
$ ZSYTRI_ROOK, ZSYTRI2, ZSYTRS, ZSYTRS_ROOK,
$ ZSYRFSX
* ..
* .. Scalars in Common ..
LOGICAL LERR, OK
CHARACTER*32 SRNAMT
INTEGER INFOT, NOUT
* ..
* .. Common blocks ..
COMMON / INFOC / INFOT, NOUT, OK, LERR
COMMON / SRNAMC / SRNAMT
* ..
* .. Intrinsic Functions ..
INTRINSIC DBLE, DCMPLX
* ..
* .. Executable Statements ..
*
NOUT = NUNIT
WRITE( NOUT, FMT = * )
C2 = PATH( 2: 3 )
*
* Set the variables to innocuous values.
*
DO 20 J = 1, NMAX
DO 10 I = 1, NMAX
A( I, J ) = DCMPLX( 1.D0 / DBLE( I+J ),
$ -1.D0 / DBLE( I+J ) )
AF( I, J ) = DCMPLX( 1.D0 / DBLE( I+J ),
$ -1.D0 / DBLE( I+J ) )
10 CONTINUE
B( J ) = 0.D0
R1( J ) = 0.D0
R2( J ) = 0.D0
W( J ) = 0.D0
X( J ) = 0.D0
S( J ) = 0.D0
IP( J ) = J
20 CONTINUE
ANRM = 1.0D0
OK = .TRUE.
*
* Test error exits of the routines that use factorization
* of a symmetric indefinite matrix with patrial
* (Bunch-Kaufman) diagonal pivoting method.
*
IF( LSAMEN( 2, C2, 'SY' ) ) THEN
*
* ZSYTRF
*
SRNAMT = 'ZSYTRF'
INFOT = 1
CALL ZSYTRF( '/', 0, A, 1, IP, W, 1, INFO )
CALL CHKXER( 'ZSYTRF', INFOT, NOUT, LERR, OK )
INFOT = 2
CALL ZSYTRF( 'U', -1, A, 1, IP, W, 1, INFO )
CALL CHKXER( 'ZSYTRF', INFOT, NOUT, LERR, OK )
INFOT = 4
CALL ZSYTRF( 'U', 2, A, 1, IP, W, 4, INFO )
CALL CHKXER( 'ZSYTRF', INFOT, NOUT, LERR, OK )
*
* ZSYTF2
*
SRNAMT = 'ZSYTF2'
INFOT = 1
CALL ZSYTF2( '/', 0, A, 1, IP, INFO )
CALL CHKXER( 'ZSYTF2', INFOT, NOUT, LERR, OK )
INFOT = 2
CALL ZSYTF2( 'U', -1, A, 1, IP, INFO )
CALL CHKXER( 'ZSYTF2', INFOT, NOUT, LERR, OK )
INFOT = 4
CALL ZSYTF2( 'U', 2, A, 1, IP, INFO )
CALL CHKXER( 'ZSYTF2', INFOT, NOUT, LERR, OK )
*
* ZSYTRI
*
SRNAMT = 'ZSYTRI'
INFOT = 1
CALL ZSYTRI( '/', 0, A, 1, IP, W, INFO )
CALL CHKXER( 'ZSYTRI', INFOT, NOUT, LERR, OK )
INFOT = 2
CALL ZSYTRI( 'U', -1, A, 1, IP, W, INFO )
CALL CHKXER( 'ZSYTRI', INFOT, NOUT, LERR, OK )
INFOT = 4
CALL ZSYTRI( 'U', 2, A, 1, IP, W, INFO )
CALL CHKXER( 'ZSYTRI', INFOT, NOUT, LERR, OK )
*
* ZSYTRI2
*
SRNAMT = 'ZSYTRI2'
INFOT = 1
CALL ZSYTRI2( '/', 0, A, 1, IP, W, 1, INFO )
CALL CHKXER( 'ZSYTRI2', INFOT, NOUT, LERR, OK )
INFOT = 2
CALL ZSYTRI2( 'U', -1, A, 1, IP, W, 1, INFO )
CALL CHKXER( 'ZSYTRI2', INFOT, NOUT, LERR, OK )
INFOT = 4
CALL ZSYTRI2( 'U', 2, A, 1, IP, W, 1, INFO )
CALL CHKXER( 'ZSYTRI2', INFOT, NOUT, LERR, OK )
*
* ZSYTRS
*
SRNAMT = 'ZSYTRS'
INFOT = 1
CALL ZSYTRS( '/', 0, 0, A, 1, IP, B, 1, INFO )
CALL CHKXER( 'ZSYTRS', INFOT, NOUT, LERR, OK )
INFOT = 2
CALL ZSYTRS( 'U', -1, 0, A, 1, IP, B, 1, INFO )
CALL CHKXER( 'ZSYTRS', INFOT, NOUT, LERR, OK )
INFOT = 3
CALL ZSYTRS( 'U', 0, -1, A, 1, IP, B, 1, INFO )
CALL CHKXER( 'ZSYTRS', INFOT, NOUT, LERR, OK )
INFOT = 5
CALL ZSYTRS( 'U', 2, 1, A, 1, IP, B, 2, INFO )
CALL CHKXER( 'ZSYTRS', INFOT, NOUT, LERR, OK )
INFOT = 8
CALL ZSYTRS( 'U', 2, 1, A, 2, IP, B, 1, INFO )
CALL CHKXER( 'ZSYTRS', INFOT, NOUT, LERR, OK )
*
* ZSYRFS
*
SRNAMT = 'ZSYRFS'
INFOT = 1
CALL ZSYRFS( '/', 0, 0, A, 1, AF, 1, IP, B, 1, X, 1, R1, R2, W,
$ R, INFO )
CALL CHKXER( 'ZSYRFS', INFOT, NOUT, LERR, OK )
INFOT = 2
CALL ZSYRFS( 'U', -1, 0, A, 1, AF, 1, IP, B, 1, X, 1, R1, R2,
$ W, R, INFO )
CALL CHKXER( 'ZSYRFS', INFOT, NOUT, LERR, OK )
INFOT = 3
CALL ZSYRFS( 'U', 0, -1, A, 1, AF, 1, IP, B, 1, X, 1, R1, R2,
$ W, R, INFO )
CALL CHKXER( 'ZSYRFS', INFOT, NOUT, LERR, OK )
INFOT = 5
CALL ZSYRFS( 'U', 2, 1, A, 1, AF, 2, IP, B, 2, X, 2, R1, R2, W,
$ R, INFO )
CALL CHKXER( 'ZSYRFS', INFOT, NOUT, LERR, OK )
INFOT = 7
CALL ZSYRFS( 'U', 2, 1, A, 2, AF, 1, IP, B, 2, X, 2, R1, R2, W,
$ R, INFO )
CALL CHKXER( 'ZSYRFS', INFOT, NOUT, LERR, OK )
INFOT = 10
CALL ZSYRFS( 'U', 2, 1, A, 2, AF, 2, IP, B, 1, X, 2, R1, R2, W,
$ R, INFO )
CALL CHKXER( 'ZSYRFS', INFOT, NOUT, LERR, OK )
INFOT = 12
CALL ZSYRFS( 'U', 2, 1, A, 2, AF, 2, IP, B, 2, X, 1, R1, R2, W,
$ R, INFO )
CALL CHKXER( 'ZSYRFS', INFOT, NOUT, LERR, OK )
*
* ZSYRFSX
*
N_ERR_BNDS = 3
NPARAMS = 0
SRNAMT = 'ZSYRFSX'
INFOT = 1
CALL ZSYRFSX( '/', EQ, 0, 0, A, 1, AF, 1, IP, S, B, 1, X, 1,
$ RCOND, BERR, N_ERR_BNDS, ERR_BNDS_N, ERR_BNDS_C, NPARAMS,
$ PARAMS, W, R, INFO )
CALL CHKXER( 'ZSYRFSX', INFOT, NOUT, LERR, OK )
INFOT = 2
CALL ZSYRFSX( 'U', EQ, -1, 0, A, 1, AF, 1, IP, S, B, 1, X, 1,
$ RCOND, BERR, N_ERR_BNDS, ERR_BNDS_N, ERR_BNDS_C, NPARAMS,
$ PARAMS, W, R, INFO )
CALL CHKXER( 'ZSYRFSX', INFOT, NOUT, LERR, OK )
EQ = 'N'
INFOT = 3
CALL ZSYRFSX( 'U', EQ, -1, 0, A, 1, AF, 1, IP, S, B, 1, X, 1,
$ RCOND, BERR, N_ERR_BNDS, ERR_BNDS_N, ERR_BNDS_C, NPARAMS,
$ PARAMS, W, R, INFO )
CALL CHKXER( 'ZSYRFSX', INFOT, NOUT, LERR, OK )
INFOT = 4
CALL ZSYRFSX( 'U', EQ, 0, -1, A, 1, AF, 1, IP, S, B, 1, X, 1,
$ RCOND, BERR, N_ERR_BNDS, ERR_BNDS_N, ERR_BNDS_C, NPARAMS,
$ PARAMS, W, R, INFO )
CALL CHKXER( 'ZSYRFSX', INFOT, NOUT, LERR, OK )
INFOT = 6
CALL ZSYRFSX( 'U', EQ, 2, 1, A, 1, AF, 2, IP, S, B, 2, X, 2,
$ RCOND, BERR, N_ERR_BNDS, ERR_BNDS_N, ERR_BNDS_C, NPARAMS,
$ PARAMS, W, R, INFO )
CALL CHKXER( 'ZSYRFSX', INFOT, NOUT, LERR, OK )
INFOT = 8
CALL ZSYRFSX( 'U', EQ, 2, 1, A, 2, AF, 1, IP, S, B, 2, X, 2,
$ RCOND, BERR, N_ERR_BNDS, ERR_BNDS_N, ERR_BNDS_C, NPARAMS,
$ PARAMS, W, R, INFO )
CALL CHKXER( 'ZSYRFSX', INFOT, NOUT, LERR, OK )
INFOT = 12
CALL ZSYRFSX( 'U', EQ, 2, 1, A, 2, AF, 2, IP, S, B, 1, X, 2,
$ RCOND, BERR, N_ERR_BNDS, ERR_BNDS_N, ERR_BNDS_C, NPARAMS,
$ PARAMS, W, R, INFO )
CALL CHKXER( 'ZSYRFSX', INFOT, NOUT, LERR, OK )
INFOT = 14
CALL ZSYRFSX( 'U', EQ, 2, 1, A, 2, AF, 2, IP, S, B, 2, X, 1,
$ RCOND, BERR, N_ERR_BNDS, ERR_BNDS_N, ERR_BNDS_C, NPARAMS,
$ PARAMS, W, R, INFO )
CALL CHKXER( 'ZSYRFSX', INFOT, NOUT, LERR, OK )
*
* ZSYCON
*
SRNAMT = 'ZSYCON'
INFOT = 1
CALL ZSYCON( '/', 0, A, 1, IP, ANRM, RCOND, W, INFO )
CALL CHKXER( 'ZSYCON', INFOT, NOUT, LERR, OK )
INFOT = 2
CALL ZSYCON( 'U', -1, A, 1, IP, ANRM, RCOND, W, INFO )
CALL CHKXER( 'ZSYCON', INFOT, NOUT, LERR, OK )
INFOT = 4
CALL ZSYCON( 'U', 2, A, 1, IP, ANRM, RCOND, W, INFO )
CALL CHKXER( 'ZSYCON', INFOT, NOUT, LERR, OK )
INFOT = 6
CALL ZSYCON( 'U', 1, A, 1, IP, -ANRM, RCOND, W, INFO )
CALL CHKXER( 'ZSYCON', INFOT, NOUT, LERR, OK )
*
* Test error exits of the routines that use factorization
* of a symmetric indefinite matrix with "rook"
* (bounded Bunch-Kaufman) diagonal pivoting method.
*
ELSE IF( LSAMEN( 2, C2, 'SR' ) ) THEN
*
* ZSYTRF_ROOK
*
SRNAMT = 'ZSYTRF_ROOK'
INFOT = 1
CALL ZSYTRF_ROOK( '/', 0, A, 1, IP, W, 1, INFO )
CALL CHKXER( 'ZSYTRF_ROOK', INFOT, NOUT, LERR, OK )
INFOT = 2
CALL ZSYTRF_ROOK( 'U', -1, A, 1, IP, W, 1, INFO )
CALL CHKXER( 'ZSYTRF_ROOK', INFOT, NOUT, LERR, OK )
INFOT = 4
CALL ZSYTRF_ROOK( 'U', 2, A, 1, IP, W, 4, INFO )
CALL CHKXER( 'ZSYTRF_ROOK', INFOT, NOUT, LERR, OK )
*
* ZSYTF2_ROOK
*
SRNAMT = 'ZSYTF2_ROOK'
INFOT = 1
CALL ZSYTF2_ROOK( '/', 0, A, 1, IP, INFO )
CALL CHKXER( 'ZSYTF2_ROOK', INFOT, NOUT, LERR, OK )
INFOT = 2
CALL ZSYTF2_ROOK( 'U', -1, A, 1, IP, INFO )
CALL CHKXER( 'ZSYTF2_ROOK', INFOT, NOUT, LERR, OK )
INFOT = 4
CALL ZSYTF2_ROOK( 'U', 2, A, 1, IP, INFO )
CALL CHKXER( 'ZSYTF2_ROOK', INFOT, NOUT, LERR, OK )
*
* ZSYTRI_ROOK
*
SRNAMT = 'ZSYTRI_ROOK'
INFOT = 1
CALL ZSYTRI_ROOK( '/', 0, A, 1, IP, W, INFO )
CALL CHKXER( 'ZSYTRI_ROOK', INFOT, NOUT, LERR, OK )
INFOT = 2
CALL ZSYTRI_ROOK( 'U', -1, A, 1, IP, W, INFO )
CALL CHKXER( 'ZSYTRI_ROOK', INFOT, NOUT, LERR, OK )
INFOT = 4
CALL ZSYTRI_ROOK( 'U', 2, A, 1, IP, W, INFO )
CALL CHKXER( 'ZSYTRI_ROOK', INFOT, NOUT, LERR, OK )
*
* ZSYTRS_ROOK
*
SRNAMT = 'ZSYTRS_ROOK'
INFOT = 1
CALL ZSYTRS_ROOK( '/', 0, 0, A, 1, IP, B, 1, INFO )
CALL CHKXER( 'ZSYTRS_ROOK', INFOT, NOUT, LERR, OK )
INFOT = 2
CALL ZSYTRS_ROOK( 'U', -1, 0, A, 1, IP, B, 1, INFO )
CALL CHKXER( 'ZSYTRS_ROOK', INFOT, NOUT, LERR, OK )
INFOT = 3
CALL ZSYTRS_ROOK( 'U', 0, -1, A, 1, IP, B, 1, INFO )
CALL CHKXER( 'ZSYTRS_ROOK', INFOT, NOUT, LERR, OK )
INFOT = 5
CALL ZSYTRS_ROOK( 'U', 2, 1, A, 1, IP, B, 2, INFO )
CALL CHKXER( 'ZSYTRS_ROOK', INFOT, NOUT, LERR, OK )
INFOT = 8
CALL ZSYTRS_ROOK( 'U', 2, 1, A, 2, IP, B, 1, INFO )
CALL CHKXER( 'ZSYTRS_ROOK', INFOT, NOUT, LERR, OK )
*
* ZSYCON_ROOK
*
SRNAMT = 'ZSYCON_ROOK'
INFOT = 1
CALL ZSYCON_ROOK( '/', 0, A, 1, IP, ANRM, RCOND, W, INFO )
CALL CHKXER( 'ZSYCON_ROOK', INFOT, NOUT, LERR, OK )
INFOT = 2
CALL ZSYCON_ROOK( 'U', -1, A, 1, IP, ANRM, RCOND, W, INFO )
CALL CHKXER( 'ZSYCON_ROOK', INFOT, NOUT, LERR, OK )
INFOT = 4
CALL ZSYCON_ROOK( 'U', 2, A, 1, IP, ANRM, RCOND, W, INFO )
CALL CHKXER( 'ZSYCON_ROOK', INFOT, NOUT, LERR, OK )
INFOT = 6
CALL ZSYCON_ROOK( 'U', 1, A, 1, IP, -ANRM, RCOND, W, INFO )
CALL CHKXER( 'ZSYCON_ROOK', INFOT, NOUT, LERR, OK )
*
* Test error exits of the routines that use factorization
* of a symmetric indefinite packed matrix with patrial
* (Bunch-Kaufman) pivoting.
*
ELSE IF( LSAMEN( 2, C2, 'SP' ) ) THEN
*
* ZSPTRF
*
SRNAMT = 'ZSPTRF'
INFOT = 1
CALL ZSPTRF( '/', 0, A, IP, INFO )
CALL CHKXER( 'ZSPTRF', INFOT, NOUT, LERR, OK )
INFOT = 2
CALL ZSPTRF( 'U', -1, A, IP, INFO )
CALL CHKXER( 'ZSPTRF', INFOT, NOUT, LERR, OK )
*
* ZSPTRI
*
SRNAMT = 'ZSPTRI'
INFOT = 1
CALL ZSPTRI( '/', 0, A, IP, W, INFO )
CALL CHKXER( 'ZSPTRI', INFOT, NOUT, LERR, OK )
INFOT = 2
CALL ZSPTRI( 'U', -1, A, IP, W, INFO )
CALL CHKXER( 'ZSPTRI', INFOT, NOUT, LERR, OK )
*
* ZSPTRS
*
SRNAMT = 'ZSPTRS'
INFOT = 1
CALL ZSPTRS( '/', 0, 0, A, IP, B, 1, INFO )
CALL CHKXER( 'ZSPTRS', INFOT, NOUT, LERR, OK )
INFOT = 2
CALL ZSPTRS( 'U', -1, 0, A, IP, B, 1, INFO )
CALL CHKXER( 'ZSPTRS', INFOT, NOUT, LERR, OK )
INFOT = 3
CALL ZSPTRS( 'U', 0, -1, A, IP, B, 1, INFO )
CALL CHKXER( 'ZSPTRS', INFOT, NOUT, LERR, OK )
INFOT = 7
CALL ZSPTRS( 'U', 2, 1, A, IP, B, 1, INFO )
CALL CHKXER( 'ZSPTRS', INFOT, NOUT, LERR, OK )
*
* ZSPRFS
*
SRNAMT = 'ZSPRFS'
INFOT = 1
CALL ZSPRFS( '/', 0, 0, A, AF, IP, B, 1, X, 1, R1, R2, W, R,
$ INFO )
CALL CHKXER( 'ZSPRFS', INFOT, NOUT, LERR, OK )
INFOT = 2
CALL ZSPRFS( 'U', -1, 0, A, AF, IP, B, 1, X, 1, R1, R2, W, R,
$ INFO )
CALL CHKXER( 'ZSPRFS', INFOT, NOUT, LERR, OK )
INFOT = 3
CALL ZSPRFS( 'U', 0, -1, A, AF, IP, B, 1, X, 1, R1, R2, W, R,
$ INFO )
CALL CHKXER( 'ZSPRFS', INFOT, NOUT, LERR, OK )
INFOT = 8
CALL ZSPRFS( 'U', 2, 1, A, AF, IP, B, 1, X, 2, R1, R2, W, R,
$ INFO )
CALL CHKXER( 'ZSPRFS', INFOT, NOUT, LERR, OK )
INFOT = 10
CALL ZSPRFS( 'U', 2, 1, A, AF, IP, B, 2, X, 1, R1, R2, W, R,
$ INFO )
CALL CHKXER( 'ZSPRFS', INFOT, NOUT, LERR, OK )
*
* ZSPCON
*
SRNAMT = 'ZSPCON'
INFOT = 1
CALL ZSPCON( '/', 0, A, IP, ANRM, RCOND, W, INFO )
CALL CHKXER( 'ZSPCON', INFOT, NOUT, LERR, OK )
INFOT = 2
CALL ZSPCON( 'U', -1, A, IP, ANRM, RCOND, W, INFO )
CALL CHKXER( 'ZSPCON', INFOT, NOUT, LERR, OK )
INFOT = 5
CALL ZSPCON( 'U', 1, A, IP, -ANRM, RCOND, W, INFO )
CALL CHKXER( 'ZSPCON', INFOT, NOUT, LERR, OK )
END IF
*
* Print a summary line.
*
CALL ALAESM( PATH, OK, NOUT )
*
RETURN
*
* End of ZERRSY
*
END
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Esprima: Coverage Analysis Report</title>
<link rel="stylesheet" type="text/css" href="../assets/style.css"/>
</head>
<style>
span.covered {
}
span.uncovered {
background: #FDD;
}
span.partial {
background: #FFA;
}
</style>
<body>
<div class="container">
<div class="topbar">
<ul class="nav">
<li><a href="../index.html">← Home</a></li>
<li><a href="http://github.com/ariya/esprima">Code</a></li>
<li><a href="../doc/index.html">Documentation</a></li>
<li><a href="http://issues.esprima.org">Issues</a></li>
</ul>
</div>
<h1>Coverage Analysis <small>ensures systematic exercise of the parser</small></h1>
<p><strong>Note</strong>: This is not a live (in-browser) code coverage report.
The analysis is <a href="http://code.google.com/p/esprima/wiki/Testing#Code_coverage_test">performed</a> offline
(using <a href="https://github.com/itay/node-cover">node-cover</a>).<br>
|
<?php
/**
* Param 'colorpicker' field
*
* @param $settings
* @param $value
*
* @since 4.4
* @return string
*/
function vc_colorpicker_form_field( $settings, $value ) {
return '<div class="color-group">'
. '<input name="' . $settings['param_name'] . '" class="wpb_vc_param_value wpb-textinput ' . $settings['param_name'] . ' ' . $settings['type'] . '_field vc_color-control" type="text" value="' . $value . '"/>'
. '</div>';
} |
/**
* Add your manual test filenames and display names below.
**/
var tests = [
{ href: "test-add.html", name: "Add Events" },
{ href: "test-delete.html", name: "Delete Events" },
{ href: "test-tracks.html", name: "Add Tracks" },
{ href: "test-vimeo.html", name: "Change Media to Vimeo" },
{ href: "test-youtube.html", name: "Change Media to YouTube" },
{ href: "test-save.html", name: "Save and Load" },
{ href: "test-share.html", name: "Share HTML5 project" },
{ href: "test-sharevimeo.html", name: "Share Vimeo project" },
{ href: "test-shareyoutube.html", name: "Share YouTube project" },
{ href: "test-export.html", name: "Export HTML5 project" }
].reverse();
|
package ic2.api.event;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import cpw.mods.fml.common.eventhandler.Cancelable;
import net.minecraftforge.event.world.WorldEvent;
/**
* A bunch of Events to handle the power of the Mining Laser.
*/
@Cancelable
public class LaserEvent extends WorldEvent {
// the Laser Entity
public final Entity lasershot;
// the following variables can be changed and the Laser will adjust to them
// the Player firing the Laser. If the Laser gets "reflected" the Player could change.
public EntityLivingBase owner;
// Range of the Laser Shot. Determine the amount of broken blocks, as well, as each broken block will subtract ~1F from range.
public float range, power;
public int blockBreaks;
// Determines whether the laser will explode upon hitting something
public boolean explosive, smelt;
public LaserEvent(World world1, Entity lasershot1, EntityLivingBase owner1, float range1, float power1, int blockBreaks1, boolean explosive1, boolean smelt1) {
super(world1);
this.lasershot = lasershot1;
this.owner = owner1;
this.range = range1;
this.power = power1;
this.blockBreaks = blockBreaks1;
this.explosive = explosive1;
this.smelt = smelt1;
}
/**
* Event when the Laser is getting shot by a Player.
*
* The Item is the Laser Gun which the "Player" has shot
*/
public static class LaserShootEvent extends LaserEvent {
ItemStack laseritem;
public LaserShootEvent(World world1, Entity lasershot1, EntityLivingBase owner1, float range1, float power1, int blockBreaks1, boolean explosive1, boolean smelt1, ItemStack laseritem1) {
super(world1, lasershot1, owner1, range1, power1, blockBreaks1, explosive1, smelt1);
this.laseritem = laseritem1;
}
}
/**
* Event when the Laser is exploding for some Reason.
*
* The Laser will no longer exist after this Event is posted as it either Explodes or despawns after the Event is fired.
*/
public static class LaserExplodesEvent extends LaserEvent {
// explosion strength, even that can be changed!
public float explosionpower, explosiondroprate, explosionentitydamage;
public LaserExplodesEvent(World world1, Entity lasershot1, EntityLivingBase owner1, float range1, float power1, int blockBreaks1, boolean explosive1, boolean smelt1, float explosionpower1, float explosiondroprate1, float explosionentitydamage1) {
super(world1, lasershot1, owner1, range1, power1, blockBreaks1, explosive1, smelt1);
this.explosionpower = explosionpower1;
this.explosiondroprate = explosiondroprate1;
this.explosionentitydamage = explosionentitydamage1;
}
}
/**
* Event when the Laser is hitting a Block
* x, y and z are the Coords of the Block.
*
* Canceling this Event stops the Laser from attempting to break the Block, what is very useful for Glass.
* Use lasershot.setDead() to remove the Shot entirely.
*/
public static class LaserHitsBlockEvent extends LaserEvent {
// targeted block, even that can be changed!
public int x, y, z;
public int side;
// removeBlock determines if the Block will be removed. dropBlock determines if the Block should drop something.
public boolean removeBlock, dropBlock;
public float dropChance;
public LaserHitsBlockEvent(World world1, Entity lasershot1, EntityLivingBase owner1, float range1, float power1, int blockBreaks1, boolean explosive1, boolean smelt1, int x1, int y1, int z1, int side1, float dropChance1, boolean removeBlock1, boolean dropBlock1) {
super(world1, lasershot1, owner1, range1, power1, blockBreaks1, explosive1, smelt1);
this.x = x1;
this.y = y1;
this.z = z1;
this.side = side1;
this.removeBlock = removeBlock1;
this.dropBlock = dropBlock1;
this.dropChance = dropChance1;
}
}
/**
* Event when the Laser is getting at a Living Entity
*
* Canceling this Event ignores the Entity
* Use lasershot.setDead() to remove the Shot entirely.
*/
public static class LaserHitsEntityEvent extends LaserEvent {
// the Entity which the Laser has shot at, even the target can be changed!
public Entity hitentity;
public LaserHitsEntityEvent(World world1, Entity lasershot1, EntityLivingBase owner1, float range1, float power1, int blockBreaks1, boolean explosive1, boolean smelt1, Entity hitentity1) {
super(world1, lasershot1, owner1, range1, power1, blockBreaks1, explosive1, smelt1);
this.hitentity = hitentity1;
}
}
}
|
/*
* Copyright (c) 1996, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.rmi.transport.tcp;
import java.io.*;
import java.util.*;
import java.rmi.server.LogStream;
import sun.rmi.runtime.Log;
/**
* ConnectionMultiplexer manages the transparent multiplexing of
* multiple virtual connections from one endpoint to another through
* one given real connection to that endpoint. The input and output
* streams for the the underlying real connection must be supplied.
* A callback object is also supplied to be informed of new virtual
* connections opened by the remote endpoint. After creation, the
* run() method must be called in a thread created for demultiplexing
* the connections. The openConnection() method is called to
* initiate a virtual connection from this endpoint.
*
* @author Peter Jones
*/
final class ConnectionMultiplexer {
/** "multiplex" log level */
static int logLevel = LogStream.parseLevel(getLogLevel());
private static String getLogLevel() {
return java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction("sun.rmi.transport.tcp.multiplex.logLevel"));
}
/* multiplex system log */
static final Log multiplexLog =
Log.getLog("sun.rmi.transport.tcp.multiplex",
"multiplex", ConnectionMultiplexer.logLevel);
/** multiplexing protocol operation codes */
private final static int OPEN = 0xE1;
private final static int CLOSE = 0xE2;
private final static int CLOSEACK = 0xE3;
private final static int REQUEST = 0xE4;
private final static int TRANSMIT = 0xE5;
/** object to notify for new connections from remote endpoint */
private TCPChannel channel;
/** input stream for underlying single connection */
private InputStream in;
/** output stream for underlying single connection */
private OutputStream out;
/** true if underlying connection originated from this endpoint
(used for generating unique connection IDs) */
private boolean orig;
/** layered stream for reading formatted data from underlying connection */
private DataInputStream dataIn;
/** layered stream for writing formatted data to underlying connection */
private DataOutputStream dataOut;
/** table holding currently open connection IDs and related info */
private Hashtable connectionTable = new Hashtable(7);
/** number of currently open connections */
private int numConnections = 0;
/** maximum allowed open connections */
private final static int maxConnections = 256;
/** ID of last connection opened */
private int lastID = 0x1001;
/** true if this mechanism is still alive */
private boolean alive = true;
/**
* Create a new ConnectionMultiplexer using the given underlying
* input/output stream pair. The run method must be called
* (possibly on a new thread) to handle the demultiplexing.
* @param channel object to notify when new connection is received
* @param in input stream of underlying connection
* @param out output stream of underlying connection
* @param orig true if this endpoint intiated the underlying
* connection (needs to be set differently at both ends)
*/
public ConnectionMultiplexer(
TCPChannel channel,
InputStream in,
OutputStream out,
boolean orig)
{
this.channel = channel;
this.in = in;
this.out = out;
this.orig = orig;
dataIn = new DataInputStream(in);
dataOut = new DataOutputStream(out);
}
/**
* Process multiplexing protocol received from underlying connection.
*/
public void run() throws IOException
{
try {
int op, id, length;
Integer idObj;
MultiplexConnectionInfo info;
while (true) {
// read next op code from remote endpoint
op = dataIn.readUnsignedByte();
switch (op) {
// remote endpoint initiating new connection
case OPEN:
id = dataIn.readUnsignedShort();
if (multiplexLog.isLoggable(Log.VERBOSE)) {
multiplexLog.log(Log.VERBOSE, "operation OPEN " + id);
}
idObj = new Integer(id);
info =
(MultiplexConnectionInfo) connectionTable.get(idObj);
if (info != null)
throw new IOException(
"OPEN: Connection ID already exists");
info = new MultiplexConnectionInfo(id);
info.in = new MultiplexInputStream(this, info, 2048);
info.out = new MultiplexOutputStream(this, info, 2048);
synchronized (connectionTable) {
connectionTable.put(idObj, info);
++ numConnections;
}
sun.rmi.transport.Connection conn;
conn = new TCPConnection(channel, info.in, info.out);
channel.acceptMultiplexConnection(conn);
break;
// remote endpoint closing connection
case CLOSE:
id = dataIn.readUnsignedShort();
if (multiplexLog.isLoggable(Log.VERBOSE)) {
multiplexLog.log(Log.VERBOSE, "operation CLOSE " + id);
}
idObj = new Integer(id);
info =
(MultiplexConnectionInfo) connectionTable.get(idObj);
if (info == null)
throw new IOException(
"CLOSE: Invalid connection ID");
info.in.disconnect();
info.out.disconnect();
if (!info.closed)
sendCloseAck(info);
synchronized (connectionTable) {
connectionTable.remove(idObj);
-- numConnections;
}
break;
// remote endpoint acknowledging close of connection
case CLOSEACK:
id = dataIn.readUnsignedShort();
if (multiplexLog.isLoggable(Log.VERBOSE)) {
multiplexLog.log(Log.VERBOSE,
"operation CLOSEACK " + id);
}
idObj = new Integer(id);
info =
(MultiplexConnectionInfo) connectionTable.get(idObj);
if (info == null)
throw new IOException(
"CLOSEACK: Invalid connection ID");
if (!info.closed)
throw new IOException(
"CLOSEACK: Connection not closed");
info.in.disconnect();
info.out.disconnect();
synchronized (connectionTable) {
connectionTable.remove(idObj);
-- numConnections;
}
break;
// remote endpoint declaring additional bytes receivable
case REQUEST:
id = dataIn.readUnsignedShort();
idObj = new Integer(id);
info =
(MultiplexConnectionInfo) connectionTable.get(idObj);
if (info == null)
throw new IOException(
"REQUEST: Invalid connection ID");
length = dataIn.readInt();
if (multiplexLog.isLoggable(Log.VERBOSE)) {
multiplexLog.log(Log.VERBOSE,
"operation REQUEST " + id + ": " + length);
}
info.out.request(length);
break;
// remote endpoint transmitting data packet
case TRANSMIT:
id = dataIn.readUnsignedShort();
idObj = new Integer(id);
info =
(MultiplexConnectionInfo) connectionTable.get(idObj);
if (info == null)
throw new IOException("SEND: Invalid connection ID");
length = dataIn.readInt();
if (multiplexLog.isLoggable(Log.VERBOSE)) {
multiplexLog.log(Log.VERBOSE,
"operation TRANSMIT " + id + ": " + length);
}
info.in.receive(length, dataIn);
break;
default:
throw new IOException("Invalid operation: " +
Integer.toHexString(op));
}
}
} finally {
shutDown();
}
}
/**
* Initiate a new multiplexed connection through the underlying
* connection.
*/
public synchronized TCPConnection openConnection() throws IOException
{
// generate ID that should not be already used
// If all possible 32768 IDs are used,
// this method will block searching for a new ID forever.
int id;
Integer idObj;
do {
lastID = (++ lastID) & 0x7FFF;
id = lastID;
// The orig flag (copied to the high bit of the ID) is used
// to have two distinct ranges to choose IDs from for the
// two endpoints.
if (orig)
id |= 0x8000;
idObj = new Integer(id);
} while (connectionTable.get(idObj) != null);
// create multiplexing streams and bookkeeping information
MultiplexConnectionInfo info = new MultiplexConnectionInfo(id);
info.in = new MultiplexInputStream(this, info, 2048);
info.out = new MultiplexOutputStream(this, info, 2048);
// add to connection table if multiplexer has not died
synchronized (connectionTable) {
if (!alive)
throw new IOException("Multiplexer connection dead");
if (numConnections >= maxConnections)
throw new IOException("Cannot exceed " + maxConnections +
" simultaneous multiplexed connections");
connectionTable.put(idObj, info);
++ numConnections;
}
// inform remote endpoint of new connection
synchronized (dataOut) {
try {
dataOut.writeByte(OPEN);
dataOut.writeShort(id);
dataOut.flush();
} catch (IOException e) {
multiplexLog.log(Log.BRIEF, "exception: ", e);
shutDown();
throw e;
}
}
return new TCPConnection(channel, info.in, info.out);
}
/**
* Shut down all connections and clean up.
*/
public void shutDown()
{
// inform all associated streams
synchronized (connectionTable) {
// return if multiplexer already officially dead
if (!alive)
return;
alive = false;
Enumeration enum_ = connectionTable.elements();
while (enum_.hasMoreElements()) {
MultiplexConnectionInfo info =
(MultiplexConnectionInfo) enum_.nextElement();
info.in.disconnect();
info.out.disconnect();
}
connectionTable.clear();
numConnections = 0;
}
// close underlying connection, if possible (and not already done)
try {
in.close();
} catch (IOException e) {
}
try {
out.close();
} catch (IOException e) {
}
}
/**
* Send request for more data on connection to remote endpoint.
* @param info connection information structure
* @param len number of more bytes that can be received
*/
void sendRequest(MultiplexConnectionInfo info, int len) throws IOException
{
synchronized (dataOut) {
if (alive && !info.closed)
try {
dataOut.writeByte(REQUEST);
dataOut.writeShort(info.id);
dataOut.writeInt(len);
dataOut.flush();
} catch (IOException e) {
multiplexLog.log(Log.BRIEF, "exception: ", e);
shutDown();
throw e;
}
}
}
/**
* Send packet of requested data on connection to remote endpoint.
* @param info connection information structure
* @param buf array containg bytes to send
* @param off offset of first array index of packet
* @param len number of bytes in packet to send
*/
void sendTransmit(MultiplexConnectionInfo info,
byte buf[], int off, int len) throws IOException
{
synchronized (dataOut) {
if (alive && !info.closed)
try {
dataOut.writeByte(TRANSMIT);
dataOut.writeShort(info.id);
dataOut.writeInt(len);
dataOut.write(buf, off, len);
dataOut.flush();
} catch (IOException e) {
multiplexLog.log(Log.BRIEF, "exception: ", e);
shutDown();
throw e;
}
}
}
/**
* Inform remote endpoint that connection has been closed.
* @param info connection information structure
*/
void sendClose(MultiplexConnectionInfo info) throws IOException
{
info.out.disconnect();
synchronized (dataOut) {
if (alive && !info.closed)
try {
dataOut.writeByte(CLOSE);
dataOut.writeShort(info.id);
dataOut.flush();
info.closed = true;
} catch (IOException e) {
multiplexLog.log(Log.BRIEF, "exception: ", e);
shutDown();
throw e;
}
}
}
/**
* Acknowledge remote endpoint's closing of connection.
* @param info connection information structure
*/
void sendCloseAck(MultiplexConnectionInfo info) throws IOException
{
synchronized (dataOut) {
if (alive && !info.closed)
try {
dataOut.writeByte(CLOSEACK);
dataOut.writeShort(info.id);
dataOut.flush();
info.closed = true;
} catch (IOException e) {
multiplexLog.log(Log.BRIEF, "exception: ", e);
shutDown();
throw e;
}
}
}
/**
* Shut down connection upon finalization.
*/
protected void finalize() throws Throwable
{
super.finalize();
shutDown();
}
}
|
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @file Horizontal Page Break
*/
// Register a plugin named "pagebreak".
CKEDITOR.plugins.add( 'pagebreak',
{
init : function( editor )
{
// Register the command.
editor.addCommand( 'pagebreak', CKEDITOR.plugins.pagebreakCmd );
// Register the toolbar button.
editor.ui.addButton( 'PageBreak',
{
label : editor.lang.pagebreak,
command : 'pagebreak'
});
// Add the style that renders our placeholder.
editor.addCss(
'img.cke_pagebreak' +
'{' +
'background-image: url(' + CKEDITOR.getUrl( this.path + 'images/pagebreak.gif' ) + ');' +
'background-position: center center;' +
'background-repeat: no-repeat;' +
'clear: both;' +
'display: block;' +
'float: none;' +
'width: 100%;' +
'border-top: #999999 1px dotted;' +
'border-bottom: #999999 1px dotted;' +
'height: 5px;' +
'}' );
},
afterInit : function( editor )
{
// Register a filter to displaying placeholders after mode change.
var dataProcessor = editor.dataProcessor,
dataFilter = dataProcessor && dataProcessor.dataFilter;
if ( dataFilter )
{
dataFilter.addRules(
{
elements :
{
div : function( element )
{
var attributes = element.attributes,
style = attributes && attributes.style,
child = style && element.children.length == 1 && element.children[ 0 ],
childStyle = child && ( child.name == 'span' ) && child.attributes.style;
if ( childStyle && ( /page-break-after\s*:\s*always/i ).test( style ) && ( /display\s*:\s*none/i ).test( childStyle ) )
return editor.createFakeParserElement( element, 'cke_pagebreak', 'div' );
}
}
});
}
},
requires : [ 'fakeobjects' ]
});
CKEDITOR.plugins.pagebreakCmd =
{
exec : function( editor )
{
// Create the element that represents a print break.
var breakObject = CKEDITOR.dom.element.createFromHtml( '<div style="page-break-after: always;"><span style="display: none;"> </span></div>' );
// Creates the fake image used for this element.
breakObject = editor.createFakeElement( breakObject, 'cke_pagebreak', 'div' );
var ranges = editor.getSelection().getRanges();
for ( var range, i = 0 ; i < ranges.length ; i++ )
{
range = ranges[ i ];
if ( i > 0 )
breakObject = breakObject.clone( true );
range.splitBlock( 'p' );
range.insertNode( breakObject );
}
}
};
|
/*!
* Cropper.js v1.2.2
* https://github.com/fengyuanchen/cropperjs
*
* Copyright (c) 2015-2018 Chen Fengyuan
* Released under the MIT license
*
* Date: 2018-01-03T13:26:29.610Z
*/
.cropper-container {
direction: ltr;
font-size: 0;
line-height: 0;
position: relative;
-ms-touch-action: none;
touch-action: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.cropper-container img {/*Avoid margin top issue (Occur only when margin-top <= -height)
*/
display: block;
height: 100%;
image-orientation: 0deg;
max-height: none !important;
max-width: none !important;
min-height: 0 !important;
min-width: 0 !important;
width: 100%;
}
.cropper-wrap-box,
.cropper-canvas,
.cropper-drag-box,
.cropper-crop-box,
.cropper-modal {
bottom: 0;
left: 0;
position: absolute;
right: 0;
top: 0;
}
.cropper-wrap-box,
.cropper-canvas {
overflow: hidden;
}
.cropper-drag-box {
background-color: #fff;
opacity: 0;
}
.cropper-modal {
background-color: #000;
opacity: .5;
}
.cropper-view-box {
display: block;
height: 100%;
outline-color: rgba(51, 153, 255, 0.75);
outline: 1px solid #39f;
overflow: hidden;
width: 100%;
}
.cropper-dashed {
border: 0 dashed #eee;
display: block;
opacity: .5;
position: absolute;
}
.cropper-dashed.dashed-h {
border-bottom-width: 1px;
border-top-width: 1px;
height: 33.33333%;
left: 0;
top: 33.33333%;
width: 100%;
}
.cropper-dashed.dashed-v {
border-left-width: 1px;
border-right-width: 1px;
height: 100%;
left: 33.33333%;
top: 0;
width: 33.33333%;
}
.cropper-center {
display: block;
height: 0;
left: 50%;
opacity: .75;
position: absolute;
top: 50%;
width: 0;
}
.cropper-center:before,
.cropper-center:after {
background-color: #eee;
content: ' ';
display: block;
position: absolute;
}
.cropper-center:before {
height: 1px;
left: -3px;
top: 0;
width: 7px;
}
.cropper-center:after {
height: 7px;
left: 0;
top: -3px;
width: 1px;
}
.cropper-face,
.cropper-line,
.cropper-point {
display: block;
height: 100%;
opacity: .1;
position: absolute;
width: 100%;
}
.cropper-face {
background-color: #fff;
left: 0;
top: 0;
}
.cropper-line {
background-color: #39f;
}
.cropper-line.line-e {
cursor: ew-resize;
right: -3px;
top: 0;
width: 5px;
}
.cropper-line.line-n {
cursor: ns-resize;
height: 5px;
left: 0;
top: -3px;
}
.cropper-line.line-w {
cursor: ew-resize;
left: -3px;
top: 0;
width: 5px;
}
.cropper-line.line-s {
bottom: -3px;
cursor: ns-resize;
height: 5px;
left: 0;
}
.cropper-point {
background-color: #39f;
height: 5px;
opacity: .75;
width: 5px;
}
.cropper-point.point-e {
cursor: ew-resize;
margin-top: -3px;
right: -3px;
top: 50%;
}
.cropper-point.point-n {
cursor: ns-resize;
left: 50%;
margin-left: -3px;
top: -3px;
}
.cropper-point.point-w {
cursor: ew-resize;
left: -3px;
margin-top: -3px;
top: 50%;
}
.cropper-point.point-s {
bottom: -3px;
cursor: s-resize;
left: 50%;
margin-left: -3px;
}
.cropper-point.point-ne {
cursor: nesw-resize;
right: -3px;
top: -3px;
}
.cropper-point.point-nw {
cursor: nwse-resize;
left: -3px;
top: -3px;
}
.cropper-point.point-sw {
bottom: -3px;
cursor: nesw-resize;
left: -3px;
}
.cropper-point.point-se {
bottom: -3px;
cursor: nwse-resize;
height: 20px;
opacity: 1;
right: -3px;
width: 20px;
}
@media (min-width: 768px) {
.cropper-point.point-se {
height: 15px;
width: 15px;
}
}
@media (min-width: 992px) {
.cropper-point.point-se {
height: 10px;
width: 10px;
}
}
@media (min-width: 1200px) {
.cropper-point.point-se {
height: 5px;
opacity: .75;
width: 5px;
}
}
.cropper-point.point-se:before {
background-color: #39f;
bottom: -50%;
content: ' ';
display: block;
height: 200%;
opacity: 0;
position: absolute;
right: -50%;
width: 200%;
}
.cropper-invisible {
opacity: 0;
}
.cropper-bg {
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAAA3NCSVQICAjb4U/gAAAABlBMVEXMzMz////TjRV2AAAACXBIWXMAAArrAAAK6wGCiw1aAAAAHHRFWHRTb2Z0d2FyZQBBZG9iZSBGaXJld29ya3MgQ1M26LyyjAAAABFJREFUCJlj+M/AgBVhF/0PAH6/D/HkDxOGAAAAAElFTkSuQmCC');
}
.cropper-hide {
display: block;
height: 0;
position: absolute;
width: 0;
}
.cropper-hidden {
display: none !important;
}
.cropper-move {
cursor: move;
}
.cropper-crop {
cursor: crosshair;
}
.cropper-disabled .cropper-drag-box,
.cropper-disabled .cropper-face,
.cropper-disabled .cropper-line,
.cropper-disabled .cropper-point {
cursor: not-allowed;
}
|
/**
* Copyright (c) 2010-2016, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.lcn.connection;
import java.util.Dictionary;
import org.openhab.binding.lcn.common.LcnDefs;
/**
* Settings for a connection to LCN-PCHK.
*
* @author Tobias Jüttner
*/
public class ConnectionSettings {
/** Unique identifier for this connection. */
private final String id;
/** The user name for authentication. */
private final String username;
/** The password for authentication. */
private final String password;
/** The TCP/IP address or IP of the connection. */
private final String address;
/** The TCP/IP port of the connection. */
private final int port;
/** The dimming mode to use. */
private final LcnDefs.OutputPortDimMode dimMode;
/** The status-messages mode to use. */
private final LcnDefs.OutputPortStatusMode statusMode;
/** The default timeout to use for requests. Worst case: Requesting threshold 4-4 takes at least 1.8s */
private static final long DEFAULT_TIMEOUT_MSEC = 3500;
/** Timeout for requests. */
private final long timeoutMSec;
/**
* Constructor.
*
* @param id the connnection's unique identifier
* @param address the connection's TCP/IP address or IP
* @param port the connection's TCP/IP port
* @param username the user name for authentication
* @param password the password for authentication
* @param dimMode the dimming mode
* @param statusMode the status-messages mode
* @param timeout the request timeout
*/
private ConnectionSettings(String id, String address, int port, String username, String password,
LcnDefs.OutputPortDimMode dimMode, LcnDefs.OutputPortStatusMode statusMode, int timeout) {
this.id = id;
this.address = address;
this.port = port;
this.username = username;
this.password = password;
this.dimMode = dimMode;
this.statusMode = statusMode;
this.timeoutMSec = timeout;
}
/**
* Gets the unique identifier for the connection.
*
* @return the unique identifier
*/
public String getId() {
return this.id;
}
/**
* Gets the user name used for authentication.
*
* @return the user name
*/
public String getUsername() {
return this.username;
}
/**
* Gets the password used for authentication.
*
* @return the password
*/
public String getPassword() {
return this.password;
}
/**
* Gets the TCP/IP address or IP of the connection.
*
* @return the address or IP
*/
public String getAddress() {
return this.address;
}
/**
* Gets the TCP/IP port of the connection.
*
* @return the port
*/
public int getPort() {
return this.port;
}
/**
* Gets the dimming mode to use for the connection.
*
* @return the dimming mode
*/
public LcnDefs.OutputPortDimMode getDimMode() {
return this.dimMode;
}
/**
* Gets the status-messages mode to use for the connection.
*
* @return the status-messages mode
*/
public LcnDefs.OutputPortStatusMode getStatusMode() {
return this.statusMode;
}
/**
* Gets the request timeout.
*
* @return the timeout in milliseconds
*/
public long getTimeout() {
return this.timeoutMSec;
}
/**
* Tries to parse LCN-PCHK connection settings from the given openHAB configuration.
*
* @param config the binding's configuration
* @param counter 0..x (1..x+1 in actual configuration file)
* @return the connection settings on success or null
*/
public static ConnectionSettings tryParse(Dictionary<String, ?> config, int counter) {
if (config == null) {
return null;
}
String id = (String) config.get("id" + (counter + 1));
id = id == null ? "" : id.trim();
String addressWithOptPort = (String) config.get("address" + (counter + 1));
addressWithOptPort = addressWithOptPort == null ? "" : addressWithOptPort.trim();
String username = (String) config.get("username" + (counter + 1));
username = username == null ? "" : username.trim();
String password = (String) config.get("password" + (counter + 1));
password = password == null ? "" : password.trim();
String mode = (String) config.get("mode" + (counter + 1));
mode = mode == null ? "" : mode.trim();
if (id.isEmpty() || addressWithOptPort.isEmpty() || username.isEmpty() || password.isEmpty()
|| mode.isEmpty()) {
return null;
}
String dataRequestTimeout = (String) config.get("timeout" + (counter + 1));
dataRequestTimeout = dataRequestTimeout == null ? Long.valueOf(DEFAULT_TIMEOUT_MSEC).toString()
: dataRequestTimeout.trim();
try {
String address = addressWithOptPort.contains(":") ? addressWithOptPort.split(":")[0] : addressWithOptPort;
int port = addressWithOptPort.contains(":") ? Integer.parseInt(addressWithOptPort.split(":")[1]) : 4114;
LcnDefs.OutputPortDimMode dimMode = mode.equalsIgnoreCase("percent200")
|| mode.equalsIgnoreCase("native200") ? LcnDefs.OutputPortDimMode.STEPS200
: LcnDefs.OutputPortDimMode.STEPS50;
LcnDefs.OutputPortStatusMode statusMode = mode.equalsIgnoreCase("percent50")
|| mode.equalsIgnoreCase("percent200") ? LcnDefs.OutputPortStatusMode.PERCENT
: LcnDefs.OutputPortStatusMode.NATIVE;
int timeout = Integer.parseInt(dataRequestTimeout);
return new ConnectionSettings(id, address, port, username, password, dimMode, statusMode, timeout);
} catch (NumberFormatException ex) {
}
return null;
}
/** {@inheritDoc} */
@Override
public boolean equals(Object o) {
if (!(o instanceof ConnectionSettings)) {
return false;
}
ConnectionSettings other = (ConnectionSettings) o;
return this.id.equals(other.id) && this.address.equals(other.address) && this.port == other.port
&& this.username.equals(other.username) && this.password.equals(other.password)
&& this.dimMode == other.dimMode && this.statusMode == other.statusMode
&& this.timeoutMSec == other.timeoutMSec;
}
}
|
/* Define a default password for telnetd here.
* NOTES:
* - this can be overridden at run-time by setting
* the "TELNETD_PASSWD" environment variable.
* As soon as that variable is set, the new password
* is effective - no need to restart telnetd.
* - this must be set to an _encrypted_ password, NOT
* the cleartext. Use the 'genpw' utility to generate
* a password string:
*
* 1) Compile 'genpw.c' for the HOST, i.e.
* cc -o genpw genpw.c -lcrypt
* 1) delete an old password definition from this file.
* 2) run './genpw >> passwd.h'. This will append
* a new definition to this file.
*
* - if no password is defined here, no authentication
* is needed, i.e. telnet is open to the world.
*
* T. Straumann <strauman@slac.stanford.edu>
*/
/* #undef TELNETD_DEFAULT_PASSWD */
/* Default password: 'rtems' */
#define TELNETD_DEFAULT_PASSWD "tduDcyLX12owo"
|
// license:BSD-3-Clause
// copyright-holders: F. Ulivi
/*********************************************************************
82900.h
82900 module (CP/M auxiliary processor)
*********************************************************************/
#ifndef MAME_BUS_HP80_IO_82900_H
#define MAME_BUS_HP80_IO_82900_H
#pragma once
#include "hp80_io.h"
#include "cpu/z80/z80.h"
#include "machine/1mb5.h"
class hp82900_io_card_device : public device_t, public device_hp80_io_interface
{
public:
// construction/destruction
hp82900_io_card_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock);
virtual ~hp82900_io_card_device();
protected:
virtual void device_start() override;
virtual void device_reset() override;
// device-level overrides
virtual ioport_constructor device_input_ports() const override;
virtual const tiny_rom_entry *device_rom_region() const override;
virtual void device_add_mconfig(machine_config &config) override;
virtual void install_read_write_handlers(address_space& space , uint16_t base_addr) override;
virtual void inten() override;
virtual void clear_service() override;
private:
required_device<z80_device> m_cpu;
required_device<hp_1mb5_device> m_translator;
// Boot ROM
required_region_ptr<uint8_t> m_rom;
// RAM
std::unique_ptr<uint8_t []> m_ram;
bool m_rom_enabled;
uint8_t m_addr_latch;
DECLARE_WRITE_LINE_MEMBER(reset_w);
uint8_t cpu_mem_r(offs_t offset);
void cpu_mem_w(offs_t offset, uint8_t data);
uint8_t cpu_io_r(offs_t offset);
void cpu_io_w(offs_t offset, uint8_t data);
void cpu_mem_map(address_map &map);
void cpu_io_map(address_map &map);
void z80_m1_w(uint8_t data);
};
// device type definition
DECLARE_DEVICE_TYPE(HP82900_IO_CARD, hp82900_io_card_device)
#endif // MAME_BUS_HP80_IO_82900_H
|
VERSION = 3
PATCHLEVEL = 4
SUBLEVEL = 0
EXTRAVERSION =
NAME = Saber-toothed Squirrel
# *DOCUMENTATION*
# To see a list of typical targets execute "make help"
# More info can be located in ./README
# Comments in this file are targeted only to the developer, do not
# expect to learn how to build the kernel reading this file.
# Do not:
# o use make's built-in rules and variables
# (this increases performance and avoids hard-to-debug behaviour);
# o print "Entering directory ...";
MAKEFLAGS += -rR --no-print-directory
# Avoid funny character set dependencies
unexport LC_ALL
LC_COLLATE=C
LC_NUMERIC=C
export LC_COLLATE LC_NUMERIC
# We are using a recursive build, so we need to do a little thinking
# to get the ordering right.
#
# Most importantly: sub-Makefiles should only ever modify files in
# their own directory. If in some directory we have a dependency on
# a file in another dir (which doesn't happen often, but it's often
# unavoidable when linking the built-in.o targets which finally
# turn into vmlinux), we will call a sub make in that other dir, and
# after that we are sure that everything which is in that other dir
# is now up to date.
#
# The only cases where we need to modify files which have global
# effects are thus separated out and done before the recursive
# descending is started. They are now explicitly listed as the
# prepare rule.
# To put more focus on warnings, be less verbose as default
# Use 'make V=1' to see the full commands
ifeq ("$(origin V)", "command line")
KBUILD_VERBOSE = $(V)
endif
ifndef KBUILD_VERBOSE
KBUILD_VERBOSE = 0
endif
# Call a source code checker (by default, "sparse") as part of the
# C compilation.
#
# Use 'make C=1' to enable checking of only re-compiled files.
# Use 'make C=2' to enable checking of *all* source files, regardless
# of whether they are re-compiled or not.
#
# See the file "Documentation/sparse.txt" for more details, including
# where to get the "sparse" utility.
ifeq ("$(origin C)", "command line")
KBUILD_CHECKSRC = $(C)
endif
ifndef KBUILD_CHECKSRC
KBUILD_CHECKSRC = 0
endif
# Use make M=dir to specify directory of external module to build
# Old syntax make ... SUBDIRS=$PWD is still supported
# Setting the environment variable KBUILD_EXTMOD take precedence
ifdef SUBDIRS
KBUILD_EXTMOD ?= $(SUBDIRS)
endif
ifeq ("$(origin M)", "command line")
KBUILD_EXTMOD := $(M)
endif
# kbuild supports saving output files in a separate directory.
# To locate output files in a separate directory two syntaxes are supported.
# In both cases the working directory must be the root of the kernel src.
# 1) O=
# Use "make O=dir/to/store/output/files/"
#
# 2) Set KBUILD_OUTPUT
# Set the environment variable KBUILD_OUTPUT to point to the directory
# where the output files shall be placed.
# export KBUILD_OUTPUT=dir/to/store/output/files/
# make
#
# The O= assignment takes precedence over the KBUILD_OUTPUT environment
# variable.
# KBUILD_SRC is set on invocation of make in OBJ directory
# KBUILD_SRC is not intended to be used by the regular user (for now)
ifeq ($(KBUILD_SRC),)
# OK, Make called in directory where kernel src resides
# Do we want to locate output files in a separate directory?
ifeq ("$(origin O)", "command line")
KBUILD_OUTPUT := $(O)
endif
ifeq ("$(origin W)", "command line")
export KBUILD_ENABLE_EXTRA_GCC_CHECKS := $(W)
endif
# That's our default target when none is given on the command line
PHONY := _all
_all:
# Cancel implicit rules on top Makefile
$(CURDIR)/Makefile Makefile: ;
ifneq ($(KBUILD_OUTPUT),)
# Invoke a second make in the output directory, passing relevant variables
# check that the output directory actually exists
saved-output := $(KBUILD_OUTPUT)
KBUILD_OUTPUT := $(shell cd $(KBUILD_OUTPUT) && /bin/pwd)
$(if $(KBUILD_OUTPUT),, \
$(error output directory "$(saved-output)" does not exist))
PHONY += $(MAKECMDGOALS) sub-make
$(filter-out _all sub-make $(CURDIR)/Makefile, $(MAKECMDGOALS)) _all: sub-make
$(Q)@:
sub-make: FORCE
$(if $(KBUILD_VERBOSE:1=),@)$(MAKE) -C $(KBUILD_OUTPUT) \
KBUILD_SRC=$(CURDIR) \
KBUILD_EXTMOD="$(KBUILD_EXTMOD)" -f $(CURDIR)/Makefile \
$(filter-out _all sub-make,$(MAKECMDGOALS))
# Leave processing to above invocation of make
skip-makefile := 1
endif # ifneq ($(KBUILD_OUTPUT),)
endif # ifeq ($(KBUILD_SRC),)
# We process the rest of the Makefile if this is the final invocation of make
ifeq ($(skip-makefile),)
# If building an external module we do not care about the all: rule
# but instead _all depend on modules
PHONY += all
ifeq ($(KBUILD_EXTMOD),)
_all: all
else
_all: modules
endif
srctree := $(if $(KBUILD_SRC),$(KBUILD_SRC),$(CURDIR))
objtree := $(CURDIR)
src := $(srctree)
obj := $(objtree)
VPATH := $(srctree)$(if $(KBUILD_EXTMOD),:$(KBUILD_EXTMOD))
export srctree objtree VPATH
# SUBARCH tells the usermode build what the underlying arch is. That is set
# first, and if a usermode build is happening, the "ARCH=um" on the command
# line overrides the setting of ARCH below. If a native build is happening,
# then ARCH is assigned, getting whatever value it gets normally, and
# SUBARCH is subsequently ignored.
SUBARCH := $(shell uname -m | sed -e s/i.86/i386/ -e s/sun4u/sparc64/ \
-e s/arm.*/arm/ -e s/sa110/arm/ \
-e s/s390x/s390/ -e s/parisc64/parisc/ \
-e s/ppc.*/powerpc/ -e s/mips.*/mips/ \
-e s/sh[234].*/sh/ )
# Cross compiling and selecting different set of gcc/bin-utils
# ---------------------------------------------------------------------------
#
# When performing cross compilation for other architectures ARCH shall be set
# to the target architecture. (See arch/* for the possibilities).
# ARCH can be set during invocation of make:
# make ARCH=ia64
# Another way is to have ARCH set in the environment.
# The default ARCH is the host where make is executed.
# CROSS_COMPILE specify the prefix used for all executables used
# during compilation. Only gcc and related bin-utils executables
# are prefixed with $(CROSS_COMPILE).
# CROSS_COMPILE can be set on the command line
# make CROSS_COMPILE=ia64-linux-
# Alternatively CROSS_COMPILE can be set in the environment.
# A third alternative is to store a setting in .config so that plain
# "make" in the configured kernel build directory always uses that.
# Default value for CROSS_COMPILE is not to prefix executables
# Note: Some architectures assign CROSS_COMPILE in their arch/*/Makefile
export KBUILD_BUILDHOST := $(SUBARCH)
ARCH ?= $(SUBARCH)
CROSS_COMPILE ?= $(CONFIG_CROSS_COMPILE:"%"=%)
# Architecture as present in compile.h
UTS_MACHINE := $(ARCH)
SRCARCH := $(ARCH)
# Additional ARCH settings for x86
ifeq ($(ARCH),i386)
SRCARCH := x86
endif
ifeq ($(ARCH),x86_64)
SRCARCH := x86
endif
# Additional ARCH settings for sparc
ifeq ($(ARCH),sparc32)
SRCARCH := sparc
endif
ifeq ($(ARCH),sparc64)
SRCARCH := sparc
endif
# Additional ARCH settings for sh
ifeq ($(ARCH),sh64)
SRCARCH := sh
endif
# Additional ARCH settings for tile
ifeq ($(ARCH),tilepro)
SRCARCH := tile
endif
ifeq ($(ARCH),tilegx)
SRCARCH := tile
endif
# Where to locate arch specific headers
hdr-arch := $(SRCARCH)
ifeq ($(ARCH),m68knommu)
hdr-arch := m68k
endif
KCONFIG_CONFIG ?= .config
export KCONFIG_CONFIG
# SHELL used by kbuild
CONFIG_SHELL := $(shell if [ -x "$$BASH" ]; then echo $$BASH; \
else if [ -x /bin/bash ]; then echo /bin/bash; \
else echo sh; fi ; fi)
HOSTCC = gcc
HOSTCXX = g++
HOSTCFLAGS = -Wall -Wmissing-prototypes -Wstrict-prototypes -O2 -fomit-frame-pointer
HOSTCXXFLAGS = -O2
# Decide whether to build built-in, modular, or both.
# Normally, just do built-in.
KBUILD_MODULES :=
KBUILD_BUILTIN := 1
# If we have only "make modules", don't compile built-in objects.
# When we're building modules with modversions, we need to consider
# the built-in objects during the descend as well, in order to
# make sure the checksums are up to date before we record them.
ifeq ($(MAKECMDGOALS),modules)
KBUILD_BUILTIN := $(if $(CONFIG_MODVERSIONS),1)
endif
# If we have "make <whatever> modules", compile modules
# in addition to whatever we do anyway.
# Just "make" or "make all" shall build modules as well
ifneq ($(filter all _all modules,$(MAKECMDGOALS)),)
KBUILD_MODULES := 1
endif
ifeq ($(MAKECMDGOALS),)
KBUILD_MODULES := 1
endif
export KBUILD_MODULES KBUILD_BUILTIN
export KBUILD_CHECKSRC KBUILD_SRC KBUILD_EXTMOD
# Beautify output
# ---------------------------------------------------------------------------
#
# Normally, we echo the whole command before executing it. By making
# that echo $($(quiet)$(cmd)), we now have the possibility to set
# $(quiet) to choose other forms of output instead, e.g.
#
# quiet_cmd_cc_o_c = Compiling $(RELDIR)/$@
# cmd_cc_o_c = $(CC) $(c_flags) -c -o $@ $<
#
# If $(quiet) is empty, the whole command will be printed.
# If it is set to "quiet_", only the short version will be printed.
# If it is set to "silent_", nothing will be printed at all, since
# the variable $(silent_cmd_cc_o_c) doesn't exist.
#
# A simple variant is to prefix commands with $(Q) - that's useful
# for commands that shall be hidden in non-verbose mode.
#
# $(Q)ln $@ :<
#
# If KBUILD_VERBOSE equals 0 then the above command will be hidden.
# If KBUILD_VERBOSE equals 1 then the above command is displayed.
ifeq ($(KBUILD_VERBOSE),1)
quiet =
Q =
else
quiet=quiet_
Q = @
endif
# If the user is running make -s (silent mode), suppress echoing of
# commands
ifneq ($(filter s% -s%,$(MAKEFLAGS)),)
quiet=silent_
endif
export quiet Q KBUILD_VERBOSE
# Look for make include files relative to root of kernel src
MAKEFLAGS += --include-dir=$(srctree)
# We need some generic definitions (do not try to remake the file).
$(srctree)/scripts/Kbuild.include: ;
include $(srctree)/scripts/Kbuild.include
# Make variables (CC, etc...)
AS = $(CROSS_COMPILE)as
LD = $(CROSS_COMPILE)ld
REAL_CC = $(CROSS_COMPILE)gcc
CPP = $(CC) -E
AR = $(CROSS_COMPILE)ar
NM = $(CROSS_COMPILE)nm
STRIP = $(CROSS_COMPILE)strip
OBJCOPY = $(CROSS_COMPILE)objcopy
OBJDUMP = $(CROSS_COMPILE)objdump
AWK = awk
GENKSYMS = scripts/genksyms/genksyms
INSTALLKERNEL := installkernel
DEPMOD = /sbin/depmod
KALLSYMS = scripts/kallsyms
PERL = perl
CHECK = sparse
ifeq ($(CONFIG_CRYPTO_FIPS),)
READELF = $(CROSS_COMPILE)readelf
export READELF
endif
# Use the wrapper for the compiler. This wrapper scans for new
# warnings and causes the build to stop upon encountering them.
CC = $(srctree)/scripts/gcc-wrapper.py $(REAL_CC)
CHECKFLAGS := -D__linux__ -Dlinux -D__STDC__ -Dunix -D__unix__ \
-Wbitwise -Wno-return-void $(CF)
CFLAGS_MODULE =
AFLAGS_MODULE =
LDFLAGS_MODULE =
CFLAGS_KERNEL =
AFLAGS_KERNEL =
CFLAGS_GCOV = -fprofile-arcs -ftest-coverage
# Use LINUXINCLUDE when you must reference the include/ directory.
# Needed to be compatible with the O= option
LINUXINCLUDE := -I$(srctree)/arch/$(hdr-arch)/include \
-Iarch/$(hdr-arch)/include/generated -Iinclude \
$(if $(KBUILD_SRC), -I$(srctree)/include) \
-include $(srctree)/include/linux/kconfig.h
KBUILD_CPPFLAGS := -D__KERNEL__
KBUILD_CFLAGS := -Wall -Wundef -Wstrict-prototypes -Wno-trigraphs \
-fno-strict-aliasing -fno-common \
-Werror-implicit-function-declaration \
-Wno-format-security \
-fno-delete-null-pointer-checks
KBUILD_AFLAGS_KERNEL :=
KBUILD_CFLAGS_KERNEL :=
KBUILD_AFLAGS := -D__ASSEMBLY__
KBUILD_AFLAGS_MODULE := -DMODULE
KBUILD_CFLAGS_MODULE := -DMODULE
KBUILD_LDFLAGS_MODULE := -T $(srctree)/scripts/module-common.lds
# Read KERNELRELEASE from include/config/kernel.release (if it exists)
KERNELRELEASE = $(shell cat include/config/kernel.release 2> /dev/null)
KERNELVERSION = $(VERSION)$(if $(PATCHLEVEL),.$(PATCHLEVEL)$(if $(SUBLEVEL),.$(SUBLEVEL)))$(EXTRAVERSION)
export VERSION PATCHLEVEL SUBLEVEL KERNELRELEASE KERNELVERSION
export ARCH SRCARCH CONFIG_SHELL HOSTCC HOSTCFLAGS CROSS_COMPILE AS LD CC
export CPP AR NM STRIP OBJCOPY OBJDUMP
export MAKE AWK GENKSYMS INSTALLKERNEL PERL UTS_MACHINE
export HOSTCXX HOSTCXXFLAGS LDFLAGS_MODULE CHECK CHECKFLAGS
export KBUILD_CPPFLAGS NOSTDINC_FLAGS LINUXINCLUDE OBJCOPYFLAGS LDFLAGS
export KBUILD_CFLAGS CFLAGS_KERNEL CFLAGS_MODULE CFLAGS_GCOV
export KBUILD_AFLAGS AFLAGS_KERNEL AFLAGS_MODULE
export KBUILD_AFLAGS_MODULE KBUILD_CFLAGS_MODULE KBUILD_LDFLAGS_MODULE
export KBUILD_AFLAGS_KERNEL KBUILD_CFLAGS_KERNEL
export KBUILD_ARFLAGS
# When compiling out-of-tree modules, put MODVERDIR in the module
# tree rather than in the kernel tree. The kernel tree might
# even be read-only.
export MODVERDIR := $(if $(KBUILD_EXTMOD),$(firstword $(KBUILD_EXTMOD))/).tmp_versions
# Files to ignore in find ... statements
RCS_FIND_IGNORE := \( -name SCCS -o -name BitKeeper -o -name .svn -o -name CVS -o -name .pc -o -name .hg -o -name .git \) -prune -o
export RCS_TAR_IGNORE := --exclude SCCS --exclude BitKeeper --exclude .svn --exclude CVS --exclude .pc --exclude .hg --exclude .git
# ===========================================================================
# Rules shared between *config targets and build targets
# Basic helpers built in scripts/
PHONY += scripts_basic
scripts_basic:
$(Q)$(MAKE) $(build)=scripts/basic
$(Q)rm -f .tmp_quiet_recordmcount
# To avoid any implicit rule to kick in, define an empty command.
scripts/basic/%: scripts_basic ;
PHONY += outputmakefile
# outputmakefile generates a Makefile in the output directory, if using a
# separate output directory. This allows convenient use of make in the
# output directory.
outputmakefile:
ifneq ($(KBUILD_SRC),)
$(Q)ln -fsn $(srctree) source
$(Q)$(CONFIG_SHELL) $(srctree)/scripts/mkmakefile \
$(srctree) $(objtree) $(VERSION) $(PATCHLEVEL)
endif
# Support for using generic headers in asm-generic
PHONY += asm-generic
asm-generic:
$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.asm-generic \
obj=arch/$(SRCARCH)/include/generated/asm
# To make sure we do not include .config for any of the *config targets
# catch them early, and hand them over to scripts/kconfig/Makefile
# It is allowed to specify more targets when calling make, including
# mixing *config targets and build targets.
# For example 'make oldconfig all'.
# Detect when mixed targets is specified, and make a second invocation
# of make so .config is not included in this case either (for *config).
no-dot-config-targets := clean mrproper distclean \
cscope gtags TAGS tags help %docs check% coccicheck \
include/linux/version.h headers_% archheaders archscripts \
kernelversion %src-pkg
config-targets := 0
mixed-targets := 0
dot-config := 1
ifneq ($(filter $(no-dot-config-targets), $(MAKECMDGOALS)),)
ifeq ($(filter-out $(no-dot-config-targets), $(MAKECMDGOALS)),)
dot-config := 0
endif
endif
ifeq ($(KBUILD_EXTMOD),)
ifneq ($(filter config %config,$(MAKECMDGOALS)),)
config-targets := 1
ifneq ($(filter-out config %config,$(MAKECMDGOALS)),)
mixed-targets := 1
endif
endif
endif
ifeq ($(mixed-targets),1)
# ===========================================================================
# We're called with mixed targets (*config and build targets).
# Handle them one by one.
%:: FORCE
$(Q)$(MAKE) -C $(srctree) KBUILD_SRC= $@
else
ifeq ($(config-targets),1)
# ===========================================================================
# *config targets only - make sure prerequisites are updated, and descend
# in scripts/kconfig to make the *config target
# Read arch specific Makefile to set KBUILD_DEFCONFIG as needed.
# KBUILD_DEFCONFIG may point out an alternative default configuration
# used for 'make defconfig'
include $(srctree)/arch/$(SRCARCH)/Makefile
export KBUILD_DEFCONFIG KBUILD_KCONFIG
config: scripts_basic outputmakefile FORCE
$(Q)mkdir -p include/linux include/config
$(Q)$(MAKE) $(build)=scripts/kconfig $@
%config: scripts_basic outputmakefile FORCE
$(Q)mkdir -p include/linux include/config
$(Q)$(MAKE) $(build)=scripts/kconfig $@
else
# ===========================================================================
# Build targets only - this includes vmlinux, arch specific targets, clean
# targets and others. In general all targets except *config targets.
ifeq ($(KBUILD_EXTMOD),)
# Additional helpers built in scripts/
# Carefully list dependencies so we do not try to build scripts twice
# in parallel
PHONY += scripts
scripts: scripts_basic include/config/auto.conf include/config/tristate.conf
$(Q)$(MAKE) $(build)=$(@)
# Objects we will link into vmlinux / subdirs we need to visit
init-y := init/
drivers-y := drivers/ sound/ firmware/
net-y := net/
libs-y := lib/
core-y := usr/
endif # KBUILD_EXTMOD
ifeq ($(dot-config),1)
# Read in config
-include include/config/auto.conf
ifeq ($(KBUILD_EXTMOD),)
# Read in dependencies to all Kconfig* files, make sure to run
# oldconfig if changes are detected.
-include include/config/auto.conf.cmd
# To avoid any implicit rule to kick in, define an empty command
$(KCONFIG_CONFIG) include/config/auto.conf.cmd: ;
# If .config is newer than include/config/auto.conf, someone tinkered
# with it and forgot to run make oldconfig.
# if auto.conf.cmd is missing then we are probably in a cleaned tree so
# we execute the config step to be sure to catch updated Kconfig files
include/config/%.conf: $(KCONFIG_CONFIG) include/config/auto.conf.cmd
$(Q)$(MAKE) -f $(srctree)/Makefile silentoldconfig
else
# external modules needs include/generated/autoconf.h and include/config/auto.conf
# but do not care if they are up-to-date. Use auto.conf to trigger the test
PHONY += include/config/auto.conf
include/config/auto.conf:
$(Q)test -e include/generated/autoconf.h -a -e $@ || ( \
echo; \
echo " ERROR: Kernel configuration is invalid."; \
echo " include/generated/autoconf.h or $@ are missing.";\
echo " Run 'make oldconfig && make prepare' on kernel src to fix it."; \
echo; \
/bin/false)
endif # KBUILD_EXTMOD
else
# Dummy target needed, because used as prerequisite
include/config/auto.conf: ;
endif # $(dot-config)
# The all: target is the default when no target is given on the
# command line.
# This allow a user to issue only 'make' to build a kernel including modules
# Defaults to vmlinux, but the arch makefile usually adds further targets
all: vmlinux
ifdef CONFIG_CC_OPTIMIZE_FOR_SIZE
KBUILD_CFLAGS += -Os $(call cc-disable-warning,maybe-uninitialized,)
else
KBUILD_CFLAGS += -O2
endif
include $(srctree)/arch/$(SRCARCH)/Makefile
ifneq ($(CONFIG_FRAME_WARN),0)
KBUILD_CFLAGS += $(call cc-option,-Wframe-larger-than=${CONFIG_FRAME_WARN})
endif
# Force gcc to behave correct even for buggy distributions
ifndef CONFIG_CC_STACKPROTECTOR
KBUILD_CFLAGS += $(call cc-option, -fno-stack-protector)
endif
# This warning generated too much noise in a regular build.
# Use make W=1 to enable this warning (see scripts/Makefile.build)
KBUILD_CFLAGS += $(call cc-disable-warning, unused-but-set-variable)
ifdef CONFIG_FRAME_POINTER
KBUILD_CFLAGS += -fno-omit-frame-pointer -fno-optimize-sibling-calls
else
# Some targets (ARM with Thumb2, for example), can't be built with frame
# pointers. For those, we don't have FUNCTION_TRACER automatically
# select FRAME_POINTER. However, FUNCTION_TRACER adds -pg, and this is
# incompatible with -fomit-frame-pointer with current GCC, so we don't use
# -fomit-frame-pointer with FUNCTION_TRACER.
ifndef CONFIG_FUNCTION_TRACER
KBUILD_CFLAGS += -fomit-frame-pointer
endif
endif
ifdef CONFIG_DEBUG_INFO
KBUILD_CFLAGS += -g
KBUILD_AFLAGS += -gdwarf-2
endif
ifdef CONFIG_DEBUG_INFO_REDUCED
KBUILD_CFLAGS += $(call cc-option, -femit-struct-debug-baseonly)
endif
ifdef CONFIG_FUNCTION_TRACER
KBUILD_CFLAGS += -pg
ifdef CONFIG_DYNAMIC_FTRACE
ifdef CONFIG_HAVE_C_RECORDMCOUNT
BUILD_C_RECORDMCOUNT := y
export BUILD_C_RECORDMCOUNT
endif
endif
endif
# We trigger additional mismatches with less inlining
ifdef CONFIG_DEBUG_SECTION_MISMATCH
KBUILD_CFLAGS += $(call cc-option, -fno-inline-functions-called-once)
endif
# arch Makefile may override CC so keep this after arch Makefile is included
NOSTDINC_FLAGS += -nostdinc -isystem $(shell $(CC) -print-file-name=include)
CHECKFLAGS += $(NOSTDINC_FLAGS)
# warn about C99 declaration after statement
KBUILD_CFLAGS += $(call cc-option,-Wdeclaration-after-statement,)
# disable pointer signed / unsigned warnings in gcc 4.0
KBUILD_CFLAGS += $(call cc-disable-warning, pointer-sign)
# disable invalid "can't wrap" optimizations for signed / pointers
KBUILD_CFLAGS += $(call cc-option,-fno-strict-overflow)
# conserve stack if available
KBUILD_CFLAGS += $(call cc-option,-fconserve-stack)
# use the deterministic mode of AR if available
KBUILD_ARFLAGS := $(call ar-option,D)
# check for 'asm goto'
ifeq ($(shell $(CONFIG_SHELL) $(srctree)/scripts/gcc-goto.sh $(CC)), y)
KBUILD_CFLAGS += -DCC_HAVE_ASM_GOTO
endif
# Add user supplied CPPFLAGS, AFLAGS and CFLAGS as the last assignments
# But warn user when we do so
warn-assign = \
$(warning "WARNING: Appending $$K$(1) ($(K$(1))) from $(origin K$(1)) to kernel $$$(1)")
ifneq ($(KCPPFLAGS),)
$(call warn-assign,CPPFLAGS)
KBUILD_CPPFLAGS += $(KCPPFLAGS)
endif
ifneq ($(KAFLAGS),)
$(call warn-assign,AFLAGS)
KBUILD_AFLAGS += $(KAFLAGS)
endif
ifneq ($(KCFLAGS),)
$(call warn-assign,CFLAGS)
KBUILD_CFLAGS += $(KCFLAGS)
endif
# Use --build-id when available.
LDFLAGS_BUILD_ID = $(patsubst -Wl$(comma)%,%,\
$(call cc-ldoption, -Wl$(comma)--build-id,))
KBUILD_LDFLAGS_MODULE += $(LDFLAGS_BUILD_ID)
LDFLAGS_vmlinux += $(LDFLAGS_BUILD_ID)
ifeq ($(CONFIG_STRIP_ASM_SYMS),y)
LDFLAGS_vmlinux += $(call ld-option, -X,)
endif
# Default kernel image to build when no specific target is given.
# KBUILD_IMAGE may be overruled on the command line or
# set in the environment
# Also any assignments in arch/$(ARCH)/Makefile take precedence over
# this default value
export KBUILD_IMAGE ?= vmlinux
#
# INSTALL_PATH specifies where to place the updated kernel and system map
# images. Default is /boot, but you can set it to other values
export INSTALL_PATH ?= /boot
#
# INSTALL_MOD_PATH specifies a prefix to MODLIB for module directory
# relocations required by build roots. This is not defined in the
# makefile but the argument can be passed to make if needed.
#
MODLIB = $(INSTALL_MOD_PATH)/lib/modules/$(KERNELRELEASE)
export MODLIB
#
# INSTALL_MOD_STRIP, if defined, will cause modules to be
# stripped after they are installed. If INSTALL_MOD_STRIP is '1', then
# the default option --strip-debug will be used. Otherwise,
# INSTALL_MOD_STRIP value will be used as the options to the strip command.
ifdef INSTALL_MOD_STRIP
ifeq ($(INSTALL_MOD_STRIP),1)
mod_strip_cmd = $(STRIP) --strip-debug
else
mod_strip_cmd = $(STRIP) $(INSTALL_MOD_STRIP)
endif # INSTALL_MOD_STRIP=1
else
mod_strip_cmd = true
endif # INSTALL_MOD_STRIP
export mod_strip_cmd
ifeq ($(KBUILD_EXTMOD),)
core-y += kernel/ mm/ fs/ ipc/ security/ crypto/ block/
vmlinux-dirs := $(patsubst %/,%,$(filter %/, $(init-y) $(init-m) \
$(core-y) $(core-m) $(drivers-y) $(drivers-m) \
$(net-y) $(net-m) $(libs-y) $(libs-m)))
vmlinux-alldirs := $(sort $(vmlinux-dirs) $(patsubst %/,%,$(filter %/, \
$(init-n) $(init-) \
$(core-n) $(core-) $(drivers-n) $(drivers-) \
$(net-n) $(net-) $(libs-n) $(libs-))))
init-y := $(patsubst %/, %/built-in.o, $(init-y))
core-y := $(patsubst %/, %/built-in.o, $(core-y))
drivers-y := $(patsubst %/, %/built-in.o, $(drivers-y))
net-y := $(patsubst %/, %/built-in.o, $(net-y))
libs-y1 := $(patsubst %/, %/lib.a, $(libs-y))
libs-y2 := $(patsubst %/, %/built-in.o, $(libs-y))
libs-y := $(libs-y1) $(libs-y2)
# Build vmlinux
# ---------------------------------------------------------------------------
# vmlinux is built from the objects selected by $(vmlinux-init) and
# $(vmlinux-main). Most are built-in.o files from top-level directories
# in the kernel tree, others are specified in arch/$(ARCH)/Makefile.
# Ordering when linking is important, and $(vmlinux-init) must be first.
#
# vmlinux
# ^
# |
# +-< $(vmlinux-init)
# | +--< init/version.o + more
# |
# +--< $(vmlinux-main)
# | +--< driver/built-in.o mm/built-in.o + more
# |
# +-< kallsyms.o (see description in CONFIG_KALLSYMS section)
#
# vmlinux version (uname -v) cannot be updated during normal
# descending-into-subdirs phase since we do not yet know if we need to
# update vmlinux.
# Therefore this step is delayed until just before final link of vmlinux -
# except in the kallsyms case where it is done just before adding the
# symbols to the kernel.
#
# System.map is generated to document addresses of all kernel symbols
vmlinux-init := $(head-y) $(init-y)
vmlinux-main := $(core-y) $(libs-y) $(drivers-y) $(net-y)
vmlinux-all := $(vmlinux-init) $(vmlinux-main)
vmlinux-lds := arch/$(SRCARCH)/kernel/vmlinux.lds
export KBUILD_VMLINUX_OBJS := $(vmlinux-all)
# Rule to link vmlinux - also used during CONFIG_KALLSYMS
# May be overridden by arch/$(ARCH)/Makefile
quiet_cmd_vmlinux__ ?= LD $@
cmd_vmlinux__ ?= $(LD) $(LDFLAGS) $(LDFLAGS_vmlinux) -o $@ \
-T $(vmlinux-lds) $(vmlinux-init) \
--start-group $(vmlinux-main) --end-group \
$(filter-out $(vmlinux-lds) $(vmlinux-init) $(vmlinux-main) vmlinux.o FORCE ,$^)
# Generate new vmlinux version
quiet_cmd_vmlinux_version = GEN .version
cmd_vmlinux_version = set -e; \
if [ ! -r .version ]; then \
rm -f .version; \
echo 1 >.version; \
else \
mv .version .old_version; \
expr 0$$(cat .old_version) + 1 >.version; \
fi; \
$(MAKE) $(build)=init
# Generate System.map
quiet_cmd_sysmap = SYSMAP
cmd_sysmap = $(CONFIG_SHELL) $(srctree)/scripts/mksysmap
# Link of vmlinux
# If CONFIG_KALLSYMS is set .version is already updated
# Generate System.map and verify that the content is consistent
# Use + in front of the vmlinux_version rule to silent warning with make -j2
# First command is ':' to allow us to use + in front of the rule
define rule_vmlinux__
:
$(if $(CONFIG_KALLSYMS),,+$(call cmd,vmlinux_version))
$(call cmd,vmlinux__)
$(Q)echo 'cmd_$@ := $(cmd_vmlinux__)' > $(@D)/.$(@F).cmd
$(Q)$(if $($(quiet)cmd_sysmap), \
echo ' $($(quiet)cmd_sysmap) System.map' &&) \
$(cmd_sysmap) $@ System.map; \
if [ $$? -ne 0 ]; then \
rm -f $@; \
/bin/false; \
fi;
$(verify_kallsyms)
$(if $(CONFIG_CRYPTO_FIPS),
@$(kecho) ' FIPS : Generating hmac of crypto and updating vmlinux... ';
$(Q)$(CONFIG_SHELL) $(srctree)/scripts/fips_crypto_hmac.sh $(objtree)/vmlinux $(objtree)/System.map)
endef
ifdef CONFIG_KALLSYMS
# Generate section listing all symbols and add it into vmlinux $(kallsyms.o)
# It's a three stage process:
# o .tmp_vmlinux1 has all symbols and sections, but __kallsyms is
# empty
# Running kallsyms on that gives us .tmp_kallsyms1.o with
# the right size - vmlinux version (uname -v) is updated during this step
# o .tmp_vmlinux2 now has a __kallsyms section of the right size,
# but due to the added section, some addresses have shifted.
# From here, we generate a correct .tmp_kallsyms2.o
# o The correct .tmp_kallsyms2.o is linked into the final vmlinux.
# o Verify that the System.map from vmlinux matches the map from
# .tmp_vmlinux2, just in case we did not generate kallsyms correctly.
# o If 'make KALLSYMS_EXTRA_PASS=1" was used, do an extra pass using
# .tmp_vmlinux3 and .tmp_kallsyms3.o. This is only meant as a
# temporary bypass to allow the kernel to be built while the
# maintainers work out what went wrong with kallsyms.
last_kallsyms := 2
ifdef KALLSYMS_EXTRA_PASS
ifneq ($(KALLSYMS_EXTRA_PASS),0)
last_kallsyms := 3
endif
endif
kallsyms.o := .tmp_kallsyms$(last_kallsyms).o
define verify_kallsyms
$(Q)$(if $($(quiet)cmd_sysmap), \
echo ' $($(quiet)cmd_sysmap) .tmp_System.map' &&) \
$(cmd_sysmap) .tmp_vmlinux$(last_kallsyms) .tmp_System.map
$(Q)cmp -s System.map .tmp_System.map || \
(echo Inconsistent kallsyms data; \
echo This is a bug - please report about it; \
echo Try "make KALLSYMS_EXTRA_PASS=1" as a workaround; \
rm .tmp_kallsyms* ; /bin/false )
endef
# Update vmlinux version before link
# Use + in front of this rule to silent warning about make -j1
# First command is ':' to allow us to use + in front of this rule
cmd_ksym_ld = $(cmd_vmlinux__)
define rule_ksym_ld
:
+$(call cmd,vmlinux_version)
$(call cmd,vmlinux__)
$(Q)echo 'cmd_$@ := $(cmd_vmlinux__)' > $(@D)/.$(@F).cmd
endef
# Generate .S file with all kernel symbols
quiet_cmd_kallsyms = KSYM $@
cmd_kallsyms = $(NM) -n $< | $(KALLSYMS) \
--page-offset=$(CONFIG_PAGE_OFFSET) \
$(if $(CONFIG_KALLSYMS_ALL),--all-symbols) > $@
.tmp_kallsyms1.o .tmp_kallsyms2.o .tmp_kallsyms3.o: %.o: %.S scripts FORCE
$(call if_changed_dep,as_o_S)
.tmp_kallsyms%.S: .tmp_vmlinux% $(KALLSYMS)
$(call cmd,kallsyms)
# .tmp_vmlinux1 must be complete except kallsyms, so update vmlinux version
.tmp_vmlinux1: $(vmlinux-lds) $(vmlinux-all) FORCE
$(call if_changed_rule,ksym_ld)
.tmp_vmlinux2: $(vmlinux-lds) $(vmlinux-all) .tmp_kallsyms1.o FORCE
$(call if_changed,vmlinux__)
.tmp_vmlinux3: $(vmlinux-lds) $(vmlinux-all) .tmp_kallsyms2.o FORCE
$(call if_changed,vmlinux__)
# Needs to visit scripts/ before $(KALLSYMS) can be used.
$(KALLSYMS): scripts ;
# Generate some data for debugging strange kallsyms problems
debug_kallsyms: .tmp_map$(last_kallsyms)
.tmp_map%: .tmp_vmlinux% FORCE
($(OBJDUMP) -h $< | $(AWK) '/^ +[0-9]/{print $$4 " 0 " $$2}'; $(NM) $<) | sort > $@
.tmp_map3: .tmp_map2
.tmp_map2: .tmp_map1
endif # ifdef CONFIG_KALLSYMS
# Do modpost on a prelinked vmlinux. The finally linked vmlinux has
# relevant sections renamed as per the linker script.
quiet_cmd_vmlinux-modpost = LD $@
cmd_vmlinux-modpost = $(LD) $(LDFLAGS) -r -o $@ \
$(vmlinux-init) --start-group $(vmlinux-main) --end-group \
$(filter-out $(vmlinux-init) $(vmlinux-main) FORCE ,$^)
define rule_vmlinux-modpost
:
+$(call cmd,vmlinux-modpost)
$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.modpost $@
$(Q)echo 'cmd_$@ := $(cmd_vmlinux-modpost)' > $(dot-target).cmd
endef
# vmlinux image - including updated kernel symbols
vmlinux: $(vmlinux-lds) $(vmlinux-init) $(vmlinux-main) vmlinux.o $(kallsyms.o) FORCE
ifdef CONFIG_HEADERS_CHECK
$(Q)$(MAKE) -f $(srctree)/Makefile headers_check
endif
ifdef CONFIG_SAMPLES
$(Q)$(MAKE) $(build)=samples
endif
ifdef CONFIG_BUILD_DOCSRC
$(Q)$(MAKE) $(build)=Documentation
endif
$(call vmlinux-modpost)
$(call if_changed_rule,vmlinux__)
$(Q)rm -f .old_version
# build vmlinux.o first to catch section mismatch errors early
ifdef CONFIG_KALLSYMS
.tmp_vmlinux1: vmlinux.o
endif
modpost-init := $(filter-out init/built-in.o, $(vmlinux-init))
vmlinux.o: $(modpost-init) $(vmlinux-main) FORCE
$(call if_changed_rule,vmlinux-modpost)
# The actual objects are generated when descending,
# make sure no implicit rule kicks in
$(sort $(vmlinux-init) $(vmlinux-main)) $(vmlinux-lds): $(vmlinux-dirs) ;
# Handle descending into subdirectories listed in $(vmlinux-dirs)
# Preset locale variables to speed up the build process. Limit locale
# tweaks to this spot to avoid wrong language settings when running
# make menuconfig etc.
# Error messages still appears in the original language
PHONY += $(vmlinux-dirs)
$(vmlinux-dirs): prepare scripts
$(Q)$(MAKE) $(build)=$@
# Store (new) KERNELRELASE string in include/config/kernel.release
include/config/kernel.release: include/config/auto.conf FORCE
$(Q)rm -f $@
$(Q)echo "$(KERNELVERSION)$$($(CONFIG_SHELL) $(srctree)/scripts/setlocalversion $(srctree))" > $@
# Things we need to do before we recursively start building the kernel
# or the modules are listed in "prepare".
# A multi level approach is used. prepareN is processed before prepareN-1.
# archprepare is used in arch Makefiles and when processed asm symlink,
# version.h and scripts_basic is processed / created.
# Listed in dependency order
PHONY += prepare archprepare prepare0 prepare1 prepare2 prepare3
# prepare3 is used to check if we are building in a separate output directory,
# and if so do:
# 1) Check that make has not been executed in the kernel src $(srctree)
prepare3: include/config/kernel.release
ifneq ($(KBUILD_SRC),)
@$(kecho) ' Using $(srctree) as source for kernel'
$(Q)if [ -f $(srctree)/.config -o -d $(srctree)/include/config ]; then \
echo " $(srctree) is not clean, please run 'make mrproper'";\
echo " in the '$(srctree)' directory.";\
/bin/false; \
fi;
endif
# prepare2 creates a makefile if using a separate output directory
prepare2: prepare3 outputmakefile asm-generic
prepare1: prepare2 include/linux/version.h include/generated/utsrelease.h \
include/config/auto.conf
$(cmd_crmodverdir)
archprepare: archheaders archscripts prepare1 scripts_basic
prepare0: archprepare FORCE
$(Q)$(MAKE) $(build)=.
# All the preparing..
prepare: prepare0
# Generate some files
# ---------------------------------------------------------------------------
# KERNELRELEASE can change from a few different places, meaning version.h
# needs to be updated, so this check is forced on all builds
uts_len := 64
define filechk_utsrelease.h
if [ `echo -n "$(KERNELRELEASE)" | wc -c ` -gt $(uts_len) ]; then \
echo '"$(KERNELRELEASE)" exceeds $(uts_len) characters' >&2; \
exit 1; \
fi; \
(echo \#define UTS_RELEASE \"$(KERNELRELEASE)\";)
endef
define filechk_version.h
(echo \#define LINUX_VERSION_CODE $(shell \
expr $(VERSION) \* 65536 + 0$(PATCHLEVEL) \* 256 + 0$(SUBLEVEL)); \
echo '#define KERNEL_VERSION(a,b,c) (((a) << 16) + ((b) << 8) + (c))';)
endef
include/linux/version.h: $(srctree)/Makefile FORCE
$(call filechk,version.h)
include/generated/utsrelease.h: include/config/kernel.release FORCE
$(call filechk,utsrelease.h)
PHONY += headerdep
headerdep:
$(Q)find $(srctree)/include/ -name '*.h' | xargs --max-args 1 \
$(srctree)/scripts/headerdep.pl -I$(srctree)/include
# ---------------------------------------------------------------------------
PHONY += depend dep
depend dep:
@echo '*** Warning: make $@ is unnecessary now.'
# ---------------------------------------------------------------------------
# Firmware install
INSTALL_FW_PATH=$(INSTALL_MOD_PATH)/lib/firmware
export INSTALL_FW_PATH
PHONY += firmware_install
firmware_install: FORCE
@mkdir -p $(objtree)/firmware
$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.fwinst obj=firmware __fw_install
# ---------------------------------------------------------------------------
# Kernel headers
#Default location for installed headers
export INSTALL_HDR_PATH = $(objtree)/usr
hdr-inst := -rR -f $(srctree)/scripts/Makefile.headersinst obj
# If we do an all arch process set dst to asm-$(hdr-arch)
hdr-dst = $(if $(KBUILD_HEADERS), dst=include/asm-$(hdr-arch), dst=include/asm)
PHONY += archheaders
archheaders:
PHONY += archscripts
archscripts:
PHONY += __headers
__headers: include/linux/version.h scripts_basic asm-generic archheaders archscripts FORCE
$(Q)$(MAKE) $(build)=scripts build_unifdef
PHONY += headers_install_all
headers_install_all:
$(Q)$(CONFIG_SHELL) $(srctree)/scripts/headers.sh install
PHONY += headers_install
headers_install: __headers
$(if $(wildcard $(srctree)/arch/$(hdr-arch)/include/asm/Kbuild),, \
$(error Headers not exportable for the $(SRCARCH) architecture))
$(Q)$(MAKE) $(hdr-inst)=include
$(Q)$(MAKE) $(hdr-inst)=arch/$(hdr-arch)/include/asm $(hdr-dst)
PHONY += headers_check_all
headers_check_all: headers_install_all
$(Q)$(CONFIG_SHELL) $(srctree)/scripts/headers.sh check
PHONY += headers_check
headers_check: headers_install
$(Q)$(MAKE) $(hdr-inst)=include HDRCHECK=1
$(Q)$(MAKE) $(hdr-inst)=arch/$(hdr-arch)/include/asm $(hdr-dst) HDRCHECK=1
# ---------------------------------------------------------------------------
# Modules
ifdef CONFIG_MODULES
# By default, build modules as well
all: modules
# Build modules
#
# A module can be listed more than once in obj-m resulting in
# duplicate lines in modules.order files. Those are removed
# using awk while concatenating to the final file.
PHONY += modules
modules: $(vmlinux-dirs) $(if $(KBUILD_BUILTIN),vmlinux) modules.builtin
$(Q)$(AWK) '!x[$$0]++' $(vmlinux-dirs:%=$(objtree)/%/modules.order) > $(objtree)/modules.order
@$(kecho) ' Building modules, stage 2.';
$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.modpost
$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.fwinst obj=firmware __fw_modbuild
modules.builtin: $(vmlinux-dirs:%=%/modules.builtin)
$(Q)$(AWK) '!x[$$0]++' $^ > $(objtree)/modules.builtin
%/modules.builtin: include/config/auto.conf
$(Q)$(MAKE) $(modbuiltin)=$*
# Target to prepare building external modules
PHONY += modules_prepare
modules_prepare: prepare scripts
# Target to install modules
PHONY += modules_install
modules_install: _modinst_ _modinst_post
PHONY += _modinst_
_modinst_:
@rm -rf $(MODLIB)/kernel
@rm -f $(MODLIB)/source
@mkdir -p $(MODLIB)/kernel
@ln -s $(srctree) $(MODLIB)/source
@if [ ! $(objtree) -ef $(MODLIB)/build ]; then \
rm -f $(MODLIB)/build ; \
ln -s $(objtree) $(MODLIB)/build ; \
fi
@cp -f $(objtree)/modules.order $(MODLIB)/
@cp -f $(objtree)/modules.builtin $(MODLIB)/
$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.modinst
# This depmod is only for convenience to give the initial
# boot a modules.dep even before / is mounted read-write. However the
# boot script depmod is the master version.
PHONY += _modinst_post
_modinst_post: _modinst_
$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.fwinst obj=firmware __fw_modinst
$(call cmd,depmod)
else # CONFIG_MODULES
# Modules not configured
# ---------------------------------------------------------------------------
modules modules_install: FORCE
@echo
@echo "The present kernel configuration has modules disabled."
@echo "Type 'make config' and enable loadable module support."
@echo "Then build a kernel with module support enabled."
@echo
@exit 1
endif # CONFIG_MODULES
###
# Cleaning is done on three levels.
# make clean Delete most generated files
# Leave enough to build external modules
# make mrproper Delete the current configuration, and all generated files
# make distclean Remove editor backup files, patch leftover files and the like
# Directories & files removed with 'make clean'
CLEAN_DIRS += $(MODVERDIR)
CLEAN_FILES += vmlinux System.map \
.tmp_kallsyms* .tmp_version .tmp_vmlinux* .tmp_System.map
# Directories & files removed with 'make mrproper'
MRPROPER_DIRS += include/config usr/include include/generated \
arch/*/include/generated
MRPROPER_FILES += .config .config.old .version .old_version \
include/linux/version.h \
Module.symvers tags TAGS cscope* GPATH GTAGS GRTAGS GSYMS
# clean - Delete most, but leave enough to build external modules
#
clean: rm-dirs := $(CLEAN_DIRS)
clean: rm-files := $(CLEAN_FILES)
clean-dirs := $(addprefix _clean_, . $(vmlinux-alldirs) Documentation samples)
PHONY += $(clean-dirs) clean archclean
$(clean-dirs):
$(Q)$(MAKE) $(clean)=$(patsubst _clean_%,%,$@)
clean: archclean
# mrproper - Delete all generated files, including .config
#
mrproper: rm-dirs := $(wildcard $(MRPROPER_DIRS))
mrproper: rm-files := $(wildcard $(MRPROPER_FILES))
mrproper-dirs := $(addprefix _mrproper_,Documentation/DocBook scripts)
PHONY += $(mrproper-dirs) mrproper archmrproper
$(mrproper-dirs):
$(Q)$(MAKE) $(clean)=$(patsubst _mrproper_%,%,$@)
mrproper: clean archmrproper $(mrproper-dirs)
$(call cmd,rmdirs)
$(call cmd,rmfiles)
# distclean
#
PHONY += distclean
distclean: mrproper
@find $(srctree) $(RCS_FIND_IGNORE) \
\( -name '*.orig' -o -name '*.rej' -o -name '*~' \
-o -name '*.bak' -o -name '#*#' -o -name '.*.orig' \
-o -name '.*.rej' \
-o -name '*%' -o -name '.*.cmd' -o -name 'core' \) \
-type f -print | xargs rm -f
# Packaging of the kernel to various formats
# ---------------------------------------------------------------------------
# rpm target kept for backward compatibility
package-dir := $(srctree)/scripts/package
%src-pkg: FORCE
$(Q)$(MAKE) $(build)=$(package-dir) $@
%pkg: include/config/kernel.release FORCE
$(Q)$(MAKE) $(build)=$(package-dir) $@
rpm: include/config/kernel.release FORCE
$(Q)$(MAKE) $(build)=$(package-dir) $@
# Brief documentation of the typical targets used
# ---------------------------------------------------------------------------
boards := $(wildcard $(srctree)/arch/$(SRCARCH)/configs/*_defconfig)
boards := $(notdir $(boards))
board-dirs := $(dir $(wildcard $(srctree)/arch/$(SRCARCH)/configs/*/*_defconfig))
board-dirs := $(sort $(notdir $(board-dirs:/=)))
help:
@echo 'Cleaning targets:'
@echo ' clean - Remove most generated files but keep the config and'
@echo ' enough build support to build external modules'
@echo ' mrproper - Remove all generated files + config + various backup files'
@echo ' distclean - mrproper + remove editor backup and patch files'
@echo ''
@echo 'Configuration targets:'
@$(MAKE) -f $(srctree)/scripts/kconfig/Makefile help
@echo ''
@echo 'Other generic targets:'
@echo ' all - Build all targets marked with [*]'
@echo '* vmlinux - Build the bare kernel'
@echo '* modules - Build all modules'
@echo ' modules_install - Install all modules to INSTALL_MOD_PATH (default: /)'
@echo ' firmware_install- Install all firmware to INSTALL_FW_PATH'
@echo ' (default: $$(INSTALL_MOD_PATH)/lib/firmware)'
@echo ' dir/ - Build all files in dir and below'
@echo ' dir/file.[oisS] - Build specified target only'
@echo ' dir/file.lst - Build specified mixed source/assembly target only'
@echo ' (requires a recent binutils and recent build (System.map))'
@echo ' dir/file.ko - Build module including final link'
@echo ' modules_prepare - Set up for building external modules'
@echo ' tags/TAGS - Generate tags file for editors'
@echo ' cscope - Generate cscope index'
@echo ' gtags - Generate GNU GLOBAL index'
@echo ' kernelrelease - Output the release version string'
@echo ' kernelversion - Output the version stored in Makefile'
@echo ' headers_install - Install sanitised kernel headers to INSTALL_HDR_PATH'; \
echo ' (default: $(INSTALL_HDR_PATH))'; \
echo ''
@echo 'Static analysers'
@echo ' checkstack - Generate a list of stack hogs'
@echo ' namespacecheck - Name space analysis on compiled kernel'
@echo ' versioncheck - Sanity check on version.h usage'
@echo ' includecheck - Check for duplicate included header files'
@echo ' export_report - List the usages of all exported symbols'
@echo ' headers_check - Sanity check on exported headers'
@echo ' headerdep - Detect inclusion cycles in headers'
@$(MAKE) -f $(srctree)/scripts/Makefile.help checker-help
@echo ''
@echo 'Kernel packaging:'
@$(MAKE) $(build)=$(package-dir) help
@echo ''
@echo 'Documentation targets:'
@$(MAKE) -f $(srctree)/Documentation/DocBook/Makefile dochelp
@echo ''
@echo 'Architecture specific targets ($(SRCARCH)):'
@$(if $(archhelp),$(archhelp),\
echo ' No architecture specific help defined for $(SRCARCH)')
@echo ''
@$(if $(boards), \
$(foreach b, $(boards), \
printf " %-24s - Build for %s\\n" $(b) $(subst _defconfig,,$(b));) \
echo '')
@$(if $(board-dirs), \
$(foreach b, $(board-dirs), \
printf " %-16s - Show %s-specific targets\\n" help-$(b) $(b);) \
printf " %-16s - Show all of the above\\n" help-boards; \
echo '')
@echo ' make V=0|1 [targets] 0 => quiet build (default), 1 => verbose build'
@echo ' make V=2 [targets] 2 => give reason for rebuild of target'
@echo ' make O=dir [targets] Locate all output files in "dir", including .config'
@echo ' make C=1 [targets] Check all c source with $$CHECK (sparse by default)'
@echo ' make C=2 [targets] Force check of all c source with $$CHECK'
@echo ' make RECORDMCOUNT_WARN=1 [targets] Warn about ignored mcount sections'
@echo ' make W=n [targets] Enable extra gcc checks, n=1,2,3 where'
@echo ' 1: warnings which may be relevant and do not occur too often'
@echo ' 2: warnings which occur quite often but may still be relevant'
@echo ' 3: more obscure warnings, can most likely be ignored'
@echo ' Multiple levels can be combined with W=12 or W=123'
@echo ''
@echo 'Execute "make" or "make all" to build all targets marked with [*] '
@echo 'For further info see the ./README file'
help-board-dirs := $(addprefix help-,$(board-dirs))
help-boards: $(help-board-dirs)
boards-per-dir = $(notdir $(wildcard $(srctree)/arch/$(SRCARCH)/configs/$*/*_defconfig))
$(help-board-dirs): help-%:
@echo 'Architecture specific targets ($(SRCARCH) $*):'
@$(if $(boards-per-dir), \
$(foreach b, $(boards-per-dir), \
printf " %-24s - Build for %s\\n" $*/$(b) $(subst _defconfig,,$(b));) \
echo '')
# Documentation targets
# ---------------------------------------------------------------------------
%docs: scripts_basic FORCE
$(Q)$(MAKE) $(build)=scripts build_docproc
$(Q)$(MAKE) $(build)=Documentation/DocBook $@
else # KBUILD_EXTMOD
###
# External module support.
# When building external modules the kernel used as basis is considered
# read-only, and no consistency checks are made and the make
# system is not used on the basis kernel. If updates are required
# in the basis kernel ordinary make commands (without M=...) must
# be used.
#
# The following are the only valid targets when building external
# modules.
# make M=dir clean Delete all automatically generated files
# make M=dir modules Make all modules in specified dir
# make M=dir Same as 'make M=dir modules'
# make M=dir modules_install
# Install the modules built in the module directory
# Assumes install directory is already created
# We are always building modules
KBUILD_MODULES := 1
PHONY += crmodverdir
crmodverdir:
$(cmd_crmodverdir)
PHONY += $(objtree)/Module.symvers
$(objtree)/Module.symvers:
@test -e $(objtree)/Module.symvers || ( \
echo; \
echo " WARNING: Symbol version dump $(objtree)/Module.symvers"; \
echo " is missing; modules will have no dependencies and modversions."; \
echo )
module-dirs := $(addprefix _module_,$(KBUILD_EXTMOD))
PHONY += $(module-dirs) modules
$(module-dirs): crmodverdir $(objtree)/Module.symvers
$(Q)$(MAKE) $(build)=$(patsubst _module_%,%,$@)
modules: $(module-dirs)
@$(kecho) ' Building modules, stage 2.';
$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.modpost
PHONY += modules_install
modules_install: _emodinst_ _emodinst_post
install-dir := $(if $(INSTALL_MOD_DIR),$(INSTALL_MOD_DIR),extra)
PHONY += _emodinst_
_emodinst_:
$(Q)mkdir -p $(MODLIB)/$(install-dir)
$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.modinst
PHONY += _emodinst_post
_emodinst_post: _emodinst_
$(call cmd,depmod)
clean-dirs := $(addprefix _clean_,$(KBUILD_EXTMOD))
PHONY += $(clean-dirs) clean
$(clean-dirs):
$(Q)$(MAKE) $(clean)=$(patsubst _clean_%,%,$@)
clean: rm-dirs := $(MODVERDIR)
clean: rm-files := $(KBUILD_EXTMOD)/Module.symvers
help:
@echo ' Building external modules.'
@echo ' Syntax: make -C path/to/kernel/src M=$$PWD target'
@echo ''
@echo ' modules - default target, build the module(s)'
@echo ' modules_install - install the module'
@echo ' clean - remove generated files in module directory only'
@echo ''
# Dummies...
PHONY += prepare scripts
prepare: ;
scripts: ;
endif # KBUILD_EXTMOD
clean: $(clean-dirs)
$(call cmd,rmdirs)
$(call cmd,rmfiles)
@find $(if $(KBUILD_EXTMOD), $(KBUILD_EXTMOD), .) $(RCS_FIND_IGNORE) \
\( -name '*.[oas]' -o -name '*.ko' -o -name '.*.cmd' \
-o -name '.*.d' -o -name '.*.tmp' -o -name '*.mod.c' \
-o -name '*.symtypes' -o -name 'modules.order' \
-o -name modules.builtin -o -name '.tmp_*.o.*' \
-o -name '*.gcno' \) -type f -print | xargs rm -f
# Generate tags for editors
# ---------------------------------------------------------------------------
quiet_cmd_tags = GEN $@
cmd_tags = $(CONFIG_SHELL) $(srctree)/scripts/tags.sh $@
tags TAGS cscope gtags: FORCE
$(call cmd,tags)
# Scripts to check various things for consistency
# ---------------------------------------------------------------------------
PHONY += includecheck versioncheck coccicheck namespacecheck export_report
includecheck:
find $(srctree)/* $(RCS_FIND_IGNORE) \
-name '*.[hcS]' -type f -print | sort \
| xargs $(PERL) -w $(srctree)/scripts/checkincludes.pl
versioncheck:
find $(srctree)/* $(RCS_FIND_IGNORE) \
-name '*.[hcS]' -type f -print | sort \
| xargs $(PERL) -w $(srctree)/scripts/checkversion.pl
coccicheck:
$(Q)$(CONFIG_SHELL) $(srctree)/scripts/$@
namespacecheck:
$(PERL) $(srctree)/scripts/namespace.pl
export_report:
$(PERL) $(srctree)/scripts/export_report.pl
endif #ifeq ($(config-targets),1)
endif #ifeq ($(mixed-targets),1)
PHONY += checkstack kernelrelease kernelversion
# UML needs a little special treatment here. It wants to use the host
# toolchain, so needs $(SUBARCH) passed to checkstack.pl. Everyone
# else wants $(ARCH), including people doing cross-builds, which means
# that $(SUBARCH) doesn't work here.
ifeq ($(ARCH), um)
CHECKSTACK_ARCH := $(SUBARCH)
else
CHECKSTACK_ARCH := $(ARCH)
endif
checkstack:
$(OBJDUMP) -d vmlinux $$(find . -name '*.ko') | \
$(PERL) $(src)/scripts/checkstack.pl $(CHECKSTACK_ARCH)
kernelrelease:
@echo "$(KERNELVERSION)$$($(CONFIG_SHELL) $(srctree)/scripts/setlocalversion $(srctree))"
kernelversion:
@echo $(KERNELVERSION)
# Single targets
# ---------------------------------------------------------------------------
# Single targets are compatible with:
# - build with mixed source and output
# - build with separate output dir 'make O=...'
# - external modules
#
# target-dir => where to store outputfile
# build-dir => directory in kernel source tree to use
ifeq ($(KBUILD_EXTMOD),)
build-dir = $(patsubst %/,%,$(dir $@))
target-dir = $(dir $@)
else
zap-slash=$(filter-out .,$(patsubst %/,%,$(dir $@)))
build-dir = $(KBUILD_EXTMOD)$(if $(zap-slash),/$(zap-slash))
target-dir = $(if $(KBUILD_EXTMOD),$(dir $<),$(dir $@))
endif
%.s: %.c prepare scripts FORCE
$(Q)$(MAKE) $(build)=$(build-dir) $(target-dir)$(notdir $@)
%.i: %.c prepare scripts FORCE
$(Q)$(MAKE) $(build)=$(build-dir) $(target-dir)$(notdir $@)
%.o: %.c prepare scripts FORCE
$(Q)$(MAKE) $(build)=$(build-dir) $(target-dir)$(notdir $@)
%.lst: %.c prepare scripts FORCE
$(Q)$(MAKE) $(build)=$(build-dir) $(target-dir)$(notdir $@)
%.s: %.S prepare scripts FORCE
$(Q)$(MAKE) $(build)=$(build-dir) $(target-dir)$(notdir $@)
%.o: %.S prepare scripts FORCE
$(Q)$(MAKE) $(build)=$(build-dir) $(target-dir)$(notdir $@)
%.symtypes: %.c prepare scripts FORCE
$(Q)$(MAKE) $(build)=$(build-dir) $(target-dir)$(notdir $@)
# Modules
/: prepare scripts FORCE
$(cmd_crmodverdir)
$(Q)$(MAKE) KBUILD_MODULES=$(if $(CONFIG_MODULES),1) \
$(build)=$(build-dir)
%/: prepare scripts FORCE
$(cmd_crmodverdir)
$(Q)$(MAKE) KBUILD_MODULES=$(if $(CONFIG_MODULES),1) \
$(build)=$(build-dir)
%.ko: prepare scripts FORCE
$(cmd_crmodverdir)
$(Q)$(MAKE) KBUILD_MODULES=$(if $(CONFIG_MODULES),1) \
$(build)=$(build-dir) $(@:.ko=.o)
$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.modpost
# FIXME Should go into a make.lib or something
# ===========================================================================
quiet_cmd_rmdirs = $(if $(wildcard $(rm-dirs)),CLEAN $(wildcard $(rm-dirs)))
cmd_rmdirs = rm -rf $(rm-dirs)
quiet_cmd_rmfiles = $(if $(wildcard $(rm-files)),CLEAN $(wildcard $(rm-files)))
cmd_rmfiles = rm -f $(rm-files)
# Run depmod only if we have System.map and depmod is executable
quiet_cmd_depmod = DEPMOD $(KERNELRELEASE)
cmd_depmod = $(CONFIG_SHELL) $(srctree)/scripts/depmod.sh $(DEPMOD) \
$(KERNELRELEASE)
# Create temporary dir for module support files
# clean it up only when building all modules
cmd_crmodverdir = $(Q)mkdir -p $(MODVERDIR) \
$(if $(KBUILD_MODULES),; rm -f $(MODVERDIR)/*)
a_flags = -Wp,-MD,$(depfile) $(KBUILD_AFLAGS) $(AFLAGS_KERNEL) \
$(KBUILD_AFLAGS_KERNEL) \
$(NOSTDINC_FLAGS) $(LINUXINCLUDE) $(KBUILD_CPPFLAGS) \
$(modkern_aflags) $(EXTRA_AFLAGS) $(AFLAGS_$(basetarget).o)
quiet_cmd_as_o_S = AS $@
cmd_as_o_S = $(CC) $(a_flags) -c -o $@ $<
# read all saved command lines
targets := $(wildcard $(sort $(targets)))
cmd_files := $(wildcard .*.cmd $(foreach f,$(targets),$(dir $(f)).$(notdir $(f)).cmd))
ifneq ($(cmd_files),)
$(cmd_files): ; # Do not try to update included dependency files
include $(cmd_files)
endif
# Shorthand for $(Q)$(MAKE) -f scripts/Makefile.clean obj=dir
# Usage:
# $(Q)$(MAKE) $(clean)=dir
clean := -f $(if $(KBUILD_SRC),$(srctree)/)scripts/Makefile.clean obj
endif # skip-makefile
PHONY += FORCE
FORCE:
# Declare the contents of the .PHONY variable as phony. We keep that
# information in a variable so we can use it in if_changed and friends.
.PHONY: $(PHONY)
|
/*
Unix SMB/CIFS implementation.
Test NTP authentication support
Copyright (C) Andrew Bartlet <abartlet@samba.org> 2008
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "includes.h"
#include "torture/torture.h"
#include "torture/smbtorture.h"
#include <tevent.h>
#include "lib/socket/socket.h"
#include "lib/stream/packet.h"
#include "auth/credentials/credentials.h"
#include "torture/rpc/rpc.h"
#include "torture/rpc/netlogon.h"
#include "../lib/crypto/crypto.h"
#include "libcli/auth/libcli_auth.h"
#include "librpc/gen_ndr/ndr_netlogon_c.h"
#include "librpc/gen_ndr/ndr_netlogon.h"
#include "librpc/gen_ndr/ndr_ntp_signd.h"
#include "param/param.h"
#define TEST_MACHINE_NAME "ntpsigndtest"
struct signd_client_socket {
struct socket_context *sock;
/* the fd event */
struct tevent_fd *fde;
NTSTATUS status;
DATA_BLOB request, reply;
struct packet_context *packet;
size_t partial_read;
};
static NTSTATUS signd_client_full_packet(void *private_data, DATA_BLOB data)
{
struct signd_client_socket *signd_client = talloc_get_type(private_data, struct signd_client_socket);
talloc_steal(signd_client, data.data);
signd_client->reply = data;
signd_client->reply.length -= 4;
signd_client->reply.data += 4;
return NT_STATUS_OK;
}
static void signd_client_error_handler(void *private_data, NTSTATUS status)
{
struct signd_client_socket *signd_client = talloc_get_type(private_data, struct signd_client_socket);
signd_client->status = status;
}
/*
handle fd events on a signd_client_socket
*/
static void signd_client_socket_handler(struct tevent_context *ev, struct tevent_fd *fde,
uint16_t flags, void *private_data)
{
struct signd_client_socket *signd_client = talloc_get_type(private_data, struct signd_client_socket);
if (flags & TEVENT_FD_READ) {
packet_recv(signd_client->packet);
return;
}
if (flags & TEVENT_FD_WRITE) {
packet_queue_run(signd_client->packet);
return;
}
/* not reached */
return;
}
/* A torture test to show that the unix domain socket protocol is
* operating correctly, and the signatures are as expected */
static bool test_ntp_signd(struct torture_context *tctx,
struct dcerpc_pipe *p,
struct cli_credentials *credentials)
{
struct netlogon_creds_CredentialState *creds;
TALLOC_CTX *mem_ctx = talloc_new(tctx);
NTSTATUS status;
struct netr_ServerReqChallenge r;
struct netr_ServerAuthenticate3 a;
struct netr_Credential credentials1, credentials2, credentials3;
uint32_t rid;
const char *machine_name;
const struct samr_Password *pwhash = cli_credentials_get_nt_hash(credentials, mem_ctx);
uint32_t negotiate_flags = NETLOGON_NEG_AUTH2_ADS_FLAGS;
struct sign_request sign_req;
struct signed_reply signed_reply;
DATA_BLOB sign_req_blob;
struct signd_client_socket *signd_client;
char *signd_socket_address;
struct MD5Context ctx;
uint8_t sig[16];
enum ndr_err_code ndr_err;
machine_name = cli_credentials_get_workstation(credentials);
torture_comment(tctx, "Testing ServerReqChallenge\n");
r.in.server_name = NULL;
r.in.computer_name = machine_name;
r.in.credentials = &credentials1;
r.out.return_credentials = &credentials2;
generate_random_buffer(credentials1.data, sizeof(credentials1.data));
status = dcerpc_netr_ServerReqChallenge(p, tctx, &r);
torture_assert_ntstatus_ok(tctx, status, "ServerReqChallenge");
a.in.server_name = NULL;
a.in.account_name = talloc_asprintf(tctx, "%s$", machine_name);
a.in.secure_channel_type = SEC_CHAN_WKSTA;
a.in.computer_name = machine_name;
a.in.negotiate_flags = &negotiate_flags;
a.in.credentials = &credentials3;
a.out.return_credentials = &credentials3;
a.out.negotiate_flags = &negotiate_flags;
a.out.rid = &rid;
creds = netlogon_creds_client_init(tctx, a.in.account_name,
a.in.computer_name,
&credentials1, &credentials2,
pwhash, &credentials3,
negotiate_flags);
torture_assert(tctx, creds != NULL, "memory allocation");
torture_comment(tctx, "Testing ServerAuthenticate3\n");
status = dcerpc_netr_ServerAuthenticate3(p, tctx, &a);
torture_assert_ntstatus_ok(tctx, status, "ServerAuthenticate3");
torture_assert(tctx, netlogon_creds_client_check(creds, &credentials3), "Credential chaining failed");
sign_req.op = SIGN_TO_CLIENT;
sign_req.packet_id = 1;
sign_req.key_id = rid;
sign_req.packet_to_sign = data_blob_string_const("I am a tea pot");
ndr_err = ndr_push_struct_blob(&sign_req_blob, mem_ctx, NULL, &sign_req, (ndr_push_flags_fn_t)ndr_push_sign_request);
torture_assert(tctx, NDR_ERR_CODE_IS_SUCCESS(ndr_err), "Failed to push sign_req");
signd_client = talloc(mem_ctx, struct signd_client_socket);
status = socket_create("unix", SOCKET_TYPE_STREAM, &signd_client->sock, 0);
signd_socket_address = talloc_asprintf(signd_client, "%s/socket",
lp_ntp_signd_socket_directory(tctx->lp_ctx));
status = socket_connect_ev(signd_client->sock, NULL,
socket_address_from_strings(signd_client,
"unix", signd_socket_address, 0), 0, tctx->ev);
torture_assert_ntstatus_ok(tctx, status, "Failed to connect to signd!");
/* Setup the FDE, start listening for read events
* from the start (otherwise we may miss a socket
* drop) and mark as AUTOCLOSE along with the fde */
/* Ths is equivilant to EVENT_FD_READABLE(signd_client->fde) */
signd_client->fde = tevent_add_fd(tctx->ev, signd_client->sock,
socket_get_fd(signd_client->sock),
TEVENT_FD_READ,
signd_client_socket_handler, signd_client);
/* its now the job of the event layer to close the socket */
tevent_fd_set_close_fn(signd_client->fde, socket_tevent_fd_close_fn);
socket_set_flags(signd_client->sock, SOCKET_FLAG_NOCLOSE);
signd_client->status = NT_STATUS_OK;
signd_client->reply = data_blob(NULL, 0);
signd_client->packet = packet_init(signd_client);
if (signd_client->packet == NULL) {
talloc_free(signd_client);
return ENOMEM;
}
packet_set_private(signd_client->packet, signd_client);
packet_set_socket(signd_client->packet, signd_client->sock);
packet_set_callback(signd_client->packet, signd_client_full_packet);
packet_set_full_request(signd_client->packet, packet_full_request_u32);
packet_set_error_handler(signd_client->packet, signd_client_error_handler);
packet_set_event_context(signd_client->packet, tctx->ev);
packet_set_fde(signd_client->packet, signd_client->fde);
signd_client->request = data_blob_talloc(signd_client, NULL, sign_req_blob.length + 4);
RSIVAL(signd_client->request.data, 0, sign_req_blob.length);
memcpy(signd_client->request.data+4, sign_req_blob.data, sign_req_blob.length);
packet_send(signd_client->packet, signd_client->request);
while ((NT_STATUS_IS_OK(signd_client->status)) && !signd_client->reply.length) {
if (tevent_loop_once(tctx->ev) != 0) {
talloc_free(signd_client);
return EINVAL;
}
}
torture_assert_ntstatus_ok(tctx, signd_client->status, "Error reading signd_client reply packet");
ndr_err = ndr_pull_struct_blob_all(&signd_client->reply, mem_ctx,
lp_iconv_convenience(tctx->lp_ctx),
&signed_reply,
(ndr_pull_flags_fn_t)ndr_pull_signed_reply);
torture_assert(tctx, NDR_ERR_CODE_IS_SUCCESS(ndr_err), ndr_map_error2string(ndr_err));
torture_assert_u64_equal(tctx, signed_reply.version,
NTP_SIGND_PROTOCOL_VERSION_0, "Invalid Version");
torture_assert_u64_equal(tctx, signed_reply.packet_id,
sign_req.packet_id, "Invalid Packet ID");
torture_assert_u64_equal(tctx, signed_reply.op,
SIGNING_SUCCESS, "Should have replied with signing success");
torture_assert_u64_equal(tctx, signed_reply.signed_packet.length,
sign_req.packet_to_sign.length + 20, "Invalid reply length from signd");
torture_assert_u64_equal(tctx, rid,
IVAL(signed_reply.signed_packet.data, sign_req.packet_to_sign.length),
"Incorrect RID in reply");
/* Check computed signature */
MD5Init(&ctx);
MD5Update(&ctx, pwhash->hash, sizeof(pwhash->hash));
MD5Update(&ctx, sign_req.packet_to_sign.data, sign_req.packet_to_sign.length);
MD5Final(sig, &ctx);
torture_assert_mem_equal(tctx, &signed_reply.signed_packet.data[sign_req.packet_to_sign.length + 4],
sig, 16, "Signature on reply was incorrect!");
talloc_free(mem_ctx);
return true;
}
NTSTATUS torture_ntp_init(void)
{
struct torture_suite *suite = torture_suite_create(talloc_autofree_context(), "NTP");
struct torture_rpc_tcase *tcase;
tcase = torture_suite_add_machine_workstation_rpc_iface_tcase(suite, "SIGND",
&ndr_table_netlogon, TEST_MACHINE_NAME);
torture_rpc_tcase_add_test_creds(tcase, "ntp_signd", test_ntp_signd);
suite->description = talloc_strdup(suite, "NTP tests");
torture_register_suite(suite);
return NT_STATUS_OK;
}
|
/*
* Copyright (c) 1997 - 2007 Kungliga Tekniska Högskolan
* (Royal Institute of Technology, Stockholm, Sweden).
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/* $Id: hdb.h,v 1.1.1.1 2011/06/10 09:34:42 andrew Exp $ */
#ifndef __HDB_H__
#define __HDB_H__
#include <hdb_err.h>
#include <heim_asn1.h>
#include <hdb_asn1.h>
struct hdb_dbinfo;
enum hdb_lockop{ HDB_RLOCK, HDB_WLOCK };
/* flags for various functions */
#define HDB_F_DECRYPT 1 /* decrypt keys */
#define HDB_F_REPLACE 2 /* replace entry */
#define HDB_F_GET_CLIENT 4 /* fetch client */
#define HDB_F_GET_SERVER 8 /* fetch server */
#define HDB_F_GET_KRBTGT 16 /* fetch krbtgt */
#define HDB_F_GET_ANY 28 /* fetch any of client,server,krbtgt */
#define HDB_F_CANON 32 /* want canonicalition */
/* hdb_capability_flags */
#define HDB_CAP_F_HANDLE_ENTERPRISE_PRINCIPAL 1
#define HDB_CAP_F_HANDLE_PASSWORDS 2
#define HDB_CAP_F_PASSWORD_UPDATE_KEYS 4
/* auth status values */
#define HDB_AUTH_SUCCESS 0
#define HDB_AUTH_WRONG_PASSWORD 1
#define HDB_AUTH_INVALID_SIGNATURE 2
/* key usage for master key */
#define HDB_KU_MKEY 0x484442
typedef struct hdb_master_key_data *hdb_master_key;
typedef struct hdb_entry_ex {
void *ctx;
hdb_entry entry;
void (*free_entry)(krb5_context, struct hdb_entry_ex *);
} hdb_entry_ex;
/**
* HDB backend function pointer structure
*
* The HDB structure is what the KDC and kadmind framework uses to
* query the backend database when talking about principals.
*/
typedef struct HDB{
void *hdb_db;
void *hdb_dbc; /** don't use, only for DB3 */
char *hdb_name;
int hdb_master_key_set;
hdb_master_key hdb_master_key;
int hdb_openp;
int hdb_capability_flags;
/**
* Open (or create) the a Kerberos database.
*
* Open (or create) the a Kerberos database that was resolved with
* hdb_create(). The third and fourth flag to the function are the
* same as open(), thus passing O_CREAT will create the data base
* if it doesn't exists.
*
* Then done the caller should call hdb_close(), and to release
* all resources hdb_destroy().
*/
krb5_error_code (*hdb_open)(krb5_context, struct HDB*, int, mode_t);
/**
* Close the database for transaction
*
* Closes the database for further transactions, wont release any
* permanant resources. the database can be ->hdb_open-ed again.
*/
krb5_error_code (*hdb_close)(krb5_context, struct HDB*);
/**
* Free an entry after use.
*/
void (*hdb_free)(krb5_context, struct HDB*, hdb_entry_ex*);
/**
* Fetch an entry from the backend
*
* Fetch an entry from the backend, flags are what type of entry
* should be fetch: client, server, krbtgt.
*/
krb5_error_code (*hdb_fetch)(krb5_context, struct HDB*,
krb5_const_principal, unsigned,
hdb_entry_ex*);
/**
* Store an entry to database
*/
krb5_error_code (*hdb_store)(krb5_context, struct HDB*,
unsigned, hdb_entry_ex*);
/**
* Remove an entry from the database.
*/
krb5_error_code (*hdb_remove)(krb5_context, struct HDB*,
krb5_const_principal);
/**
* As part of iteration, fetch one entry
*/
krb5_error_code (*hdb_firstkey)(krb5_context, struct HDB*,
unsigned, hdb_entry_ex*);
/**
* As part of iteration, fetch next entry
*/
krb5_error_code (*hdb_nextkey)(krb5_context, struct HDB*,
unsigned, hdb_entry_ex*);
/**
* Lock database
*
* A lock can only be held by one consumers. Transaction can still
* happen on the database while the lock is held, so the entry is
* only useful for syncroning creation of the database and renaming of the database.
*/
krb5_error_code (*hdb_lock)(krb5_context, struct HDB*, int);
/**
* Unlock database
*/
krb5_error_code (*hdb_unlock)(krb5_context, struct HDB*);
/**
* Rename the data base.
*/
krb5_error_code (*hdb_rename)(krb5_context, struct HDB*, const char*);
/**
* Get an hdb_entry from a classical DB backend
*
* If the database is a classical DB (ie BDB, NDBM, GDBM, etc)
* backend, this function will take a principal key (krb5_data)
* and return all data related to principal in the return
* krb5_data. The returned encoded entry is of type hdb_entry or
* hdb_entry_alias.
*/
krb5_error_code (*hdb__get)(krb5_context, struct HDB*,
krb5_data, krb5_data*);
/**
* Store an hdb_entry from a classical DB backend
*
* Same discussion as in @ref HDB::hdb__get
*/
krb5_error_code (*hdb__put)(krb5_context, struct HDB*, int,
krb5_data, krb5_data);
/**
* Delete and hdb_entry from a classical DB backend
*
* Same discussion as in @ref HDB::hdb__get
*/
krb5_error_code (*hdb__del)(krb5_context, struct HDB*, krb5_data);
/**
* Destroy the handle to the database.
*
* Destroy the handle to the database, deallocate all memory and
* related resources. Does not remove any permanent data. Its the
* logical reverse of hdb_create() function that is the entry
* point for the module.
*/
krb5_error_code (*hdb_destroy)(krb5_context, struct HDB*);
/**
* Change password.
*
* Will update keys for the entry when given password. The new
* keys must be written into the entry and and will then later be
* ->hdb_store() into the database. The backend will still perform
* all other operations, increasing the kvno, and update
* modification timestamp.
*
* The backen need to call _kadm5_set_keys() and perform password
* quality checks.
*/
krb5_error_code (*hdb_password)(krb5_context, struct HDB*, hdb_entry_ex*, const char *, int);
/**
* Auth feedback
*
* This is a feedback call that allows backends that provides
* lockout functionality to register failure and/or successes.
*
* In case the entry is locked out, the backend should set the
* hdb_entry.flags.locked-out flag.
*/
krb5_error_code (*hdb_auth_status)(krb5_context, struct HDB *, hdb_entry_ex *, int);
/**
* Check is delegation is allowed.
*/
krb5_error_code (*hdb_check_constrained_delegation)(krb5_context, struct HDB *, hdb_entry_ex *, krb5_const_principal);
/**
* Check if this name is an alias for the supplied client for PKINIT userPrinicpalName logins
*/
krb5_error_code (*hdb_check_pkinit_ms_upn_match)(krb5_context, struct HDB *, hdb_entry_ex *, krb5_const_principal);
}HDB;
#define HDB_INTERFACE_VERSION 6
struct hdb_so_method {
int version;
const char *prefix;
krb5_error_code (*create)(krb5_context, HDB **, const char *filename);
};
typedef krb5_error_code (*hdb_foreach_func_t)(krb5_context, HDB*,
hdb_entry_ex*, void*);
extern krb5_kt_ops hdb_kt_ops;
struct hdb_method {
int interface_version;
const char *prefix;
krb5_error_code (*create)(krb5_context, HDB **, const char *filename);
};
#include <hdb-protos.h>
#endif /* __HDB_H__ */
|
// license:BSD-3-Clause
// copyright-holders:Phil Stroffolino
/*************************************************************************
Munch Mobile
*************************************************************************/
#ifndef MAME_INCLUDES_MUNCHMO_H
#define MAME_INCLUDES_MUNCHMO_H
#pragma once
#include "machine/gen_latch.h"
#include "machine/74259.h"
#include "sound/ay8910.h"
#include "emupal.h"
class munchmo_state : public driver_device
{
public:
munchmo_state(const machine_config &mconfig, device_type type, const char *tag)
: driver_device(mconfig, type, tag)
, m_sprite_xpos(*this, "sprite_xpos")
, m_sprite_tile(*this, "sprite_tile")
, m_sprite_attr(*this, "sprite_attr")
, m_videoram(*this, "videoram")
, m_status_vram(*this, "status_vram")
, m_vreg(*this, "vreg")
, m_maincpu(*this, "maincpu")
, m_audiocpu(*this, "audiocpu")
, m_mainlatch(*this, "mainlatch")
, m_gfxdecode(*this, "gfxdecode")
, m_palette(*this, "palette")
, m_soundlatch(*this, "soundlatch")
, m_ay8910(*this, "ay%u", 1U)
{
}
void mnchmobl(machine_config &config);
protected:
virtual void machine_start() override;
virtual void video_start() override;
private:
DECLARE_WRITE_LINE_MEMBER(nmi_enable_w);
void nmi_ack_w(uint8_t data);
void sound_nmi_ack_w(uint8_t data);
uint8_t ay1reset_r();
uint8_t ay2reset_r();
DECLARE_WRITE_LINE_MEMBER(palette_bank_0_w);
DECLARE_WRITE_LINE_MEMBER(palette_bank_1_w);
DECLARE_WRITE_LINE_MEMBER(flipscreen_w);
void munchmo_palette(palette_device &palette) const;
DECLARE_WRITE_LINE_MEMBER(vblank_irq);
IRQ_CALLBACK_MEMBER(generic_irq_ack);
uint32_t screen_update(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
void draw_status( bitmap_ind16 &bitmap, const rectangle &cliprect );
void draw_background( bitmap_ind16 &bitmap, const rectangle &cliprect );
void draw_sprites( bitmap_ind16 &bitmap, const rectangle &cliprect );
void mnchmobl_map(address_map &map);
void sound_map(address_map &map);
/* memory pointers */
required_shared_ptr<uint8_t> m_sprite_xpos;
required_shared_ptr<uint8_t> m_sprite_tile;
required_shared_ptr<uint8_t> m_sprite_attr;
required_shared_ptr<uint8_t> m_videoram;
required_shared_ptr<uint8_t> m_status_vram;
required_shared_ptr<uint8_t> m_vreg;
/* video-related */
std::unique_ptr<bitmap_ind16> m_tmpbitmap;
int m_palette_bank;
int m_flipscreen;
/* misc */
int m_nmi_enable;
/* devices */
required_device<cpu_device> m_maincpu;
required_device<cpu_device> m_audiocpu;
required_device<ls259_device> m_mainlatch;
required_device<gfxdecode_device> m_gfxdecode;
required_device<palette_device> m_palette;
required_device<generic_latch_8_device> m_soundlatch;
required_device_array<ay8910_device, 2> m_ay8910;
};
#endif // MAME_INCLUDES_MUNCHMO_H
|
// license:BSD-3-Clause
// copyright-holders:Nicola Salmoria
#ifndef MAME_INCLUDES_FLSTORY_H
#define MAME_INCLUDES_FLSTORY_H
#pragma once
#include "machine/gen_latch.h"
#include "machine/input_merger.h"
#include "sound/msm5232.h"
#include "machine/taito68705interface.h"
#include "sound/ta7630.h"
#include "sound/ay8910.h"
#include "emupal.h"
#include "tilemap.h"
class flstory_state : public driver_device
{
public:
flstory_state(const machine_config &mconfig, device_type type, const char *tag) :
driver_device(mconfig, type, tag),
m_videoram(*this, "videoram"),
m_spriteram(*this, "spriteram"),
m_scrlram(*this, "scrlram"),
m_workram(*this, "workram"),
m_maincpu(*this, "maincpu"),
m_audiocpu(*this, "audiocpu"),
m_bmcu(*this, "bmcu"),
m_msm(*this, "msm"),
m_ay(*this, "aysnd"),
m_ta7630(*this, "ta7630"),
m_gfxdecode(*this, "gfxdecode"),
m_palette(*this, "palette"),
m_soundlatch(*this, "soundlatch"),
m_soundlatch2(*this, "soundlatch2"),
m_soundnmi(*this, "soundnmi"),
m_extraio1(*this, "EXTRA_P1")
{ }
void common(machine_config &config);
void flstory(machine_config &config);
void rumba(machine_config &config);
void onna34ro(machine_config &config);
void victnine(machine_config &config);
void onna34ro_mcu(machine_config &config);
protected:
virtual void machine_start() override;
private:
/* memory pointers */
required_shared_ptr<uint8_t> m_videoram;
required_shared_ptr<uint8_t> m_spriteram;
required_shared_ptr<uint8_t> m_scrlram;
optional_shared_ptr<uint8_t> m_workram;
/* video-related */
tilemap_t *m_bg_tilemap;
std::vector<uint8_t> m_paletteram;
std::vector<uint8_t> m_paletteram_ext;
uint8_t m_gfxctrl;
uint8_t m_char_bank;
uint8_t m_palette_bank;
/* sound-related */
uint8_t m_snd_ctrl0;
uint8_t m_snd_ctrl1;
uint8_t m_snd_ctrl2;
uint8_t m_snd_ctrl3;
/* protection sims */
uint8_t m_from_mcu;
int m_mcu_select;
/* devices */
required_device<cpu_device> m_maincpu;
required_device<cpu_device> m_audiocpu;
optional_device<taito68705_mcu_device> m_bmcu;
required_device<msm5232_device> m_msm;
required_device<ay8910_device> m_ay;
required_device<ta7630_device> m_ta7630;
required_device<gfxdecode_device> m_gfxdecode;
required_device<palette_device> m_palette;
required_device<generic_latch_8_device> m_soundlatch;
required_device<generic_latch_8_device> m_soundlatch2;
required_device<input_merger_device> m_soundnmi;
optional_ioport m_extraio1;
uint8_t snd_flag_r();
void snd_reset_w(uint8_t data);
uint8_t flstory_mcu_status_r();
uint8_t victnine_mcu_status_r();
void flstory_videoram_w(offs_t offset, uint8_t data);
void flstory_palette_w(offs_t offset, uint8_t data);
uint8_t flstory_palette_r(offs_t offset);
void flstory_gfxctrl_w(uint8_t data);
uint8_t victnine_gfxctrl_r();
void victnine_gfxctrl_w(uint8_t data);
void flstory_scrlram_w(offs_t offset, uint8_t data);
void sound_control_0_w(uint8_t data);
void sound_control_1_w(uint8_t data);
void sound_control_2_w(uint8_t data);
void sound_control_3_w(uint8_t data);
TILE_GET_INFO_MEMBER(get_tile_info);
TILE_GET_INFO_MEMBER(victnine_get_tile_info);
TILE_GET_INFO_MEMBER(get_rumba_tile_info);
DECLARE_MACHINE_RESET(flstory);
DECLARE_VIDEO_START(flstory);
DECLARE_VIDEO_START(victnine);
DECLARE_MACHINE_RESET(rumba);
DECLARE_VIDEO_START(rumba);
DECLARE_MACHINE_RESET(ta7630);
uint32_t screen_update_flstory(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
uint32_t screen_update_victnine(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
uint32_t screen_update_rumba(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
void flstory_draw_sprites( bitmap_ind16 &bitmap, const rectangle &cliprect, int pri );
void victnine_draw_sprites( bitmap_ind16 &bitmap, const rectangle &cliprect );
void base_map(address_map &map);
void flstory_map(address_map &map);
void onna34ro_map(address_map &map);
void onna34ro_mcu_map(address_map &map);
void rumba_map(address_map &map);
void sound_map(address_map &map);
void victnine_map(address_map &map);
};
#endif // MAME_INCLUDES_FLSTORY_H
|
/* SPDX-License-Identifier: GPL-2.0-only */
/*
* Copyright (C) 2009 Chen Liqin <liqin.chen@sunplusct.com>
* Copyright (C) 2012 Regents of the University of California
* Copyright (C) 2017 SiFive
* Copyright (C) 2017 XiaojingZhu <zhuxiaoj@ict.ac.cn>
*/
#ifndef _ASM_RISCV_PAGE_H
#define _ASM_RISCV_PAGE_H
#include <linux/pfn.h>
#include <linux/const.h>
#define PAGE_SHIFT (12)
#define PAGE_SIZE (_AC(1, UL) << PAGE_SHIFT)
#define PAGE_MASK (~(PAGE_SIZE - 1))
#ifdef CONFIG_64BIT
#define HUGE_MAX_HSTATE 2
#else
#define HUGE_MAX_HSTATE 1
#endif
#define HPAGE_SHIFT PMD_SHIFT
#define HPAGE_SIZE (_AC(1, UL) << HPAGE_SHIFT)
#define HPAGE_MASK (~(HPAGE_SIZE - 1))
#define HUGETLB_PAGE_ORDER (HPAGE_SHIFT - PAGE_SHIFT)
/*
* PAGE_OFFSET -- the first address of the first page of memory.
* When not using MMU this corresponds to the first free page in
* physical memory (aligned on a page boundary).
*/
#define PAGE_OFFSET _AC(CONFIG_PAGE_OFFSET, UL)
#define KERN_VIRT_SIZE (-PAGE_OFFSET)
#ifndef __ASSEMBLY__
#define PAGE_UP(addr) (((addr)+((PAGE_SIZE)-1))&(~((PAGE_SIZE)-1)))
#define PAGE_DOWN(addr) ((addr)&(~((PAGE_SIZE)-1)))
/* align addr on a size boundary - adjust address up/down if needed */
#define _ALIGN_UP(addr, size) (((addr)+((size)-1))&(~((size)-1)))
#define _ALIGN_DOWN(addr, size) ((addr)&(~((size)-1)))
/* align addr on a size boundary - adjust address up if needed */
#define _ALIGN(addr, size) _ALIGN_UP(addr, size)
#define clear_page(pgaddr) memset((pgaddr), 0, PAGE_SIZE)
#define copy_page(to, from) memcpy((to), (from), PAGE_SIZE)
#define clear_user_page(pgaddr, vaddr, page) memset((pgaddr), 0, PAGE_SIZE)
#define copy_user_page(vto, vfrom, vaddr, topg) \
memcpy((vto), (vfrom), PAGE_SIZE)
/*
* Use struct definitions to apply C type checking
*/
/* Page Global Directory entry */
typedef struct {
unsigned long pgd;
} pgd_t;
/* Page Table entry */
typedef struct {
unsigned long pte;
} pte_t;
typedef struct {
unsigned long pgprot;
} pgprot_t;
typedef struct page *pgtable_t;
#define pte_val(x) ((x).pte)
#define pgd_val(x) ((x).pgd)
#define pgprot_val(x) ((x).pgprot)
#define __pte(x) ((pte_t) { (x) })
#define __pgd(x) ((pgd_t) { (x) })
#define __pgprot(x) ((pgprot_t) { (x) })
#ifdef CONFIG_64BIT
#define PTE_FMT "%016lx"
#else
#define PTE_FMT "%08lx"
#endif
#ifdef CONFIG_MMU
extern unsigned long va_pa_offset;
extern unsigned long pfn_base;
#define ARCH_PFN_OFFSET (pfn_base)
#else
#define va_pa_offset 0
#define ARCH_PFN_OFFSET (PAGE_OFFSET >> PAGE_SHIFT)
#endif /* CONFIG_MMU */
#define __pa_to_va_nodebug(x) ((void *)((unsigned long) (x) + va_pa_offset))
#define __va_to_pa_nodebug(x) ((unsigned long)(x) - va_pa_offset)
#ifdef CONFIG_DEBUG_VIRTUAL
extern phys_addr_t __virt_to_phys(unsigned long x);
extern phys_addr_t __phys_addr_symbol(unsigned long x);
#else
#define __virt_to_phys(x) __va_to_pa_nodebug(x)
#define __phys_addr_symbol(x) __va_to_pa_nodebug(x)
#endif /* CONFIG_DEBUG_VIRTUAL */
#define __pa_symbol(x) __phys_addr_symbol(RELOC_HIDE((unsigned long)(x), 0))
#define __pa(x) __virt_to_phys((unsigned long)(x))
#define __va(x) ((void *)__pa_to_va_nodebug((phys_addr_t)(x)))
#define phys_to_pfn(phys) (PFN_DOWN(phys))
#define pfn_to_phys(pfn) (PFN_PHYS(pfn))
#define virt_to_pfn(vaddr) (phys_to_pfn(__pa(vaddr)))
#define pfn_to_virt(pfn) (__va(pfn_to_phys(pfn)))
#define virt_to_page(vaddr) (pfn_to_page(virt_to_pfn(vaddr)))
#define page_to_virt(page) (pfn_to_virt(page_to_pfn(page)))
#define page_to_phys(page) (pfn_to_phys(page_to_pfn(page)))
#define page_to_bus(page) (page_to_phys(page))
#define phys_to_page(paddr) (pfn_to_page(phys_to_pfn(paddr)))
#ifdef CONFIG_FLATMEM
#define pfn_valid(pfn) \
(((pfn) >= ARCH_PFN_OFFSET) && (((pfn) - ARCH_PFN_OFFSET) < max_mapnr))
#endif
#endif /* __ASSEMBLY__ */
#define virt_addr_valid(vaddr) ({ \
unsigned long _addr = (unsigned long)vaddr; \
(unsigned long)(_addr) >= PAGE_OFFSET && pfn_valid(virt_to_pfn(_addr)); \
})
#define VM_DATA_DEFAULT_FLAGS VM_DATA_FLAGS_NON_EXEC
#include <asm-generic/memory_model.h>
#include <asm-generic/getorder.h>
#endif /* _ASM_RISCV_PAGE_H */
|
// license:BSD-3-Clause
// copyright-holders:Brad Oliver
/***************************************************************************
arkanoid.cpp
Functions to emulate the video hardware of the machine.
***************************************************************************/
#include "emu.h"
#include "includes/arkanoid.h"
void arkanoid_state::arkanoid_videoram_w(offs_t offset, uint8_t data)
{
m_videoram[offset] = data;
m_bg_tilemap->mark_tile_dirty(offset / 2);
}
void arkanoid_state::arkanoid_d008_w(uint8_t data)
{
int bank;
/* bits 0 and 1 flip X and Y */
flip_screen_x_set(data & 0x01);
flip_screen_y_set(data & 0x02);
/* bit 2 selects the input paddle */
m_paddle_select = data & 0x04;
/* bit 3 is coin lockout (but not the service coin) */
machine().bookkeeping().coin_lockout_w(0, !(data & 0x08));
machine().bookkeeping().coin_lockout_w(1, !(data & 0x08));
/* bit 4 is unknown */
/* bit 5 controls the graphics rom bank */
bank = (data & 0x20) >> 5;
if (m_gfxbank != bank)
{
m_gfxbank = bank;
m_bg_tilemap->mark_all_dirty();
}
/* bit 6 controls the palette bank */
bank = (data & 0x40) >> 6;
if (m_palettebank != bank)
{
m_palettebank = bank;
m_bg_tilemap->mark_all_dirty();
}
// bit 7 resets the MCU and semaphore flipflops
// This bit is flipped early in bootup just prior to accessing the MCU for the first time.
if (m_mcuintf.found()) // Bootlegs don't have the MCU but still set this bit
m_mcuintf->reset_w(BIT(data, 7) ? CLEAR_LINE : ASSERT_LINE);
}
void arkanoid_state::brixian_d008_w(uint8_t data)
{
int bank;
/* bits 0 and 1 flip X and Y */
flip_screen_x_set(data & 0x01);
flip_screen_y_set(data & 0x02);
/* bit 2 selects the input paddle */
/* - not relevant to brixian */
/* bit 3 is coin lockout (but not the service coin) */
/* - not here, means you can only play 1 game */
/* bit 4 is unknown */
/* bit 5 controls the graphics rom bank */
bank = (data & 0x20) >> 5;
if (m_gfxbank != bank)
{
m_gfxbank = bank;
m_bg_tilemap->mark_all_dirty();
}
/* bit 6 controls the palette bank */
bank = (data & 0x40) >> 6;
if (m_palettebank != bank)
{
m_palettebank = bank;
m_bg_tilemap->mark_all_dirty();
}
/* bit 7 is MCU reset on Arkanoid */
/* - does it reset the Brixian MCU too? */
}
/* different hook-up, everything except for bits 0-1 and 7 aren't tested afaik. */
void arkanoid_state::tetrsark_d008_w(uint8_t data)
{
int bank;
/* bits 0 and 1 flip X and Y */
flip_screen_x_set(data & 0x01);
flip_screen_y_set(data & 0x02);
/* bit 2 selects the input paddle? */
m_paddle_select = data & 0x04;
/* bit 3-4 is unknown? */
/* bit 5 controls the graphics rom bank */
bank = (data & 0x20) >> 5;
if (m_gfxbank != bank)
{
m_gfxbank = bank;
m_bg_tilemap->mark_all_dirty();
}
/* bit 6 controls the palette bank */
bank = (data & 0x40) >> 6;
if (m_palettebank != bank)
{
m_palettebank = bank;
m_bg_tilemap->mark_all_dirty();
}
/* bit 7 is coin lockout (but not the service coin) */
machine().bookkeeping().coin_lockout_w(0, !(data & 0x80));
machine().bookkeeping().coin_lockout_w(1, !(data & 0x80));
}
void arkanoid_state::hexa_d008_w(uint8_t data)
{
/* bits 0 and 1 flip X and Y */
flip_screen_x_set(data & 0x01);
flip_screen_y_set(data & 0x02);
/* bit 2 - 3 unknown */
/* bit 4 could be the ROM bank selector for 8000-bfff (not sure) */
membank("bank1")->set_entry(((data & 0x10) >> 4));
/* bit 5 controls the graphics rom bank */
if (m_gfxbank != ((data & 0x20) >> 5))
{
m_gfxbank = (data & 0x20) >> 5;
m_bg_tilemap->mark_all_dirty();
}
/* bit 6 - 7 unknown */
}
TILE_GET_INFO_MEMBER(arkanoid_state::get_bg_tile_info)
{
int offs = tile_index * 2;
int code = m_videoram[offs + 1] + ((m_videoram[offs] & 0x07) << 8) + 2048 * m_gfxbank;
int color = ((m_videoram[offs] & 0xf8) >> 3) + 32 * m_palettebank;
tileinfo.set(0, code, color, 0);
}
void arkanoid_state::video_start()
{
m_bg_tilemap = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(*this, FUNC(arkanoid_state::get_bg_tile_info)), TILEMAP_SCAN_ROWS, 8, 8, 32, 32);
}
void arkanoid_state::draw_sprites( bitmap_ind16 &bitmap, const rectangle &cliprect )
{
int offs;
for (offs = 0; offs < m_spriteram.bytes(); offs += 4)
{
int sx, sy, code;
sx = m_spriteram[offs];
sy = 248 - m_spriteram[offs + 1];
if (flip_screen_x())
sx = 248 - sx;
if (flip_screen_y())
sy = 248 - sy;
code = m_spriteram[offs + 3] + ((m_spriteram[offs + 2] & 0x03) << 8) + 1024 * m_gfxbank;
m_gfxdecode->gfx(0)->transpen(bitmap,cliprect,
2 * code,
((m_spriteram[offs + 2] & 0xf8) >> 3) + 32 * m_palettebank,
flip_screen_x(),flip_screen_y(),
sx,sy + (flip_screen_y() ? 8 : -8),0);
m_gfxdecode->gfx(0)->transpen(bitmap,cliprect,
2 * code + 1,
((m_spriteram[offs + 2] & 0xf8) >> 3) + 32 * m_palettebank,
flip_screen_x(),flip_screen_y(),
sx,sy,0);
}
}
uint32_t arkanoid_state::screen_update_arkanoid(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect)
{
m_bg_tilemap->draw(screen, bitmap, cliprect, 0, 0);
draw_sprites(bitmap, cliprect);
return 0;
}
uint32_t arkanoid_state::screen_update_hexa(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect)
{
m_bg_tilemap->draw(screen, bitmap, cliprect, 0, 0);
return 0;
}
|
/* $NoKeywords:$ */
/**
* @file
*
* Four node Square Topology.
*
* @xrefitem bom "File Content Label" "Release Content"
* @e project: AGESA
* @e sub-project: HyperTransport
* @e \$Revision: 44324 $ @e \$Date: 2010-12-22 17:16:51 +0800 (Wed, 22 Dec 2010) $
*
*/
/*
*****************************************************************************
*
* Copyright (c) 2011, Advanced Micro Devices, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Advanced Micro Devices, Inc. nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL ADVANCED MICRO DEVICES, INC. BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* ***************************************************************************
*
*/
#include "Porting.h"
#include "htTopologies.h"
CODE_GROUP (G1_PEICC)
RDATA_GROUP (G1_PEICC)
/*
* 2---3
* | |
* | |
* 0---1
*/
/**
* Four Node square
*/
/**
* @dot
strict graph square4 {
node [shape="plaintext"];
{rank=same; 0; 1}
{rank=same; 2; 3}
0 -- 1 ;
0 -- 2 ;
1 -- 3 ;
2 -- 3 ;
}
@enddot
*
*/
CONST UINT8 ROMDATA amdHtTopologyFourSquare[] =
{
0x04,
0x06, 0xFF, 0x00, 0x11, 0x02, 0x22, 0x00, 0x22, // Node 0
0x00, 0x00, 0x09, 0xFF, 0x00, 0x33, 0x01, 0x33, // Node 1
0x08, 0x00, 0x00, 0x00, 0x09, 0xFF, 0x00, 0x33, // Node 2
0x00, 0x11, 0x04, 0x11, 0x00, 0x22, 0x06, 0xFF // Node 3
};
|
/* Copyright (c) 2012-2014, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#ifndef _APR_AUDIO_V2_H_
#define _APR_AUDIO_V2_H_
#include <mach/qdsp6v2/apr.h>
#define ADSP_ADM_VERSION 0x00070000
#define ADM_CMD_SHARED_MEM_MAP_REGIONS 0x00010322
#define ADM_CMDRSP_SHARED_MEM_MAP_REGIONS 0x00010323
#define ADM_CMD_SHARED_MEM_UNMAP_REGIONS 0x00010324
#define ADM_CMD_MATRIX_MAP_ROUTINGS_V5 0x00010325
/* Enumeration for an audio Rx matrix ID.*/
#define ADM_MATRIX_ID_AUDIO_RX 0
#define ADM_MATRIX_ID_AUDIO_TX 1
/* Enumeration for an audio Tx matrix ID.*/
#define ADM_MATRIX_ID_AUDIOX 1
#define ADM_MAX_COPPS 5
/* Session map node structure.
* Immediately following this structure are num_copps
* entries of COPP IDs. The COPP IDs are 16 bits, so
* there might be a padding 16-bit field if num_copps
* is odd.
*/
struct adm_session_map_node_v5 {
u16 session_id;
/* Handle of the ASM session to be routed. Supported values: 1
* to 8.
*/
u16 num_copps;
/* Number of COPPs to which this session is to be routed.
Supported values: 0 < num_copps <= ADM_MAX_COPPS.
*/
} __packed;
/* Payload of the #ADM_CMD_MATRIX_MAP_ROUTINGS_V5 command.
* Immediately following this structure are num_sessions of the session map
* node payload (adm_session_map_node_v5).
*/
struct adm_cmd_matrix_map_routings_v5 {
struct apr_hdr hdr;
u32 matrix_id;
/* Specifies whether the matrix ID is Audio Rx (0) or Audio Tx
* (1). Use the ADM_MATRIX_ID_AUDIO_RX or ADM_MATRIX_ID_AUDIOX
* macros to set this field.
*/
u32 num_sessions;
/* Number of sessions being updated by this command (optional).*/
} __packed;
/* This command allows a client to open a COPP/Voice Proc. TX module
* and sets up the device session: Matrix -> COPP -> AFE on the RX
* and AFE -> COPP -> Matrix on the TX. This enables PCM data to
* be transferred to/from the endpoint (AFEPortID).
*
* @return
* #ADM_CMDRSP_DEVICE_OPEN_V5 with the resulting status and
* COPP ID.
*/
#define ADM_CMD_DEVICE_OPEN_V5 0x00010326
/* Definition for a low latency stream session. */
#define ADM_LOW_LATENCY_DEVICE_SESSION 0x2000
/* Definition for a ultra low latency stream session. */
#define ADM_ULTRA_LOW_LATENCY_DEVICE_SESSION 0x4000
/* Definition for a legacy device session. */
#define ADM_LEGACY_DEVICE_SESSION 0
/* Indicates that endpoint_id_2 is to be ignored.*/
#define ADM_CMD_COPP_OPEN_END_POINT_ID_2_IGNORE 0xFFFF
#define ADM_CMD_COPP_OPEN_MODE_OF_OPERATION_RX_PATH_COPP 1
#define ADM_CMD_COPP_OPEN_MODE_OF_OPERATIONX_PATH_LIVE_COPP 2
#define ADM_CMD_COPP_OPEN_MODE_OF_OPERATIONX_PATH_NON_LIVE_COPP 3
/* Indicates that an audio COPP is to send/receive a mono PCM
* stream to/from
* END_POINT_ID_1.
*/
#define ADM_CMD_COPP_OPEN_CHANNEL_CONFIG_MONO 1
/* Indicates that an audio COPP is to send/receive a
* stereo PCM stream to/from END_POINT_ID_1.
*/
#define ADM_CMD_COPP_OPEN_CHANNEL_CONFIG_STEREO 2
/* Sample rate is 8000 Hz.*/
#define ADM_CMD_COPP_OPEN_SAMPLE_RATE_8K 8000
/* Sample rate is 16000 Hz.*/
#define ADM_CMD_COPP_OPEN_SAMPLE_RATE_16K 16000
/* Sample rate is 48000 Hz.*/
#define ADM_CMD_COPP_OPEN_SAMPLE_RATE_48K 48000
/* Definition for a COPP live input flag bitmask.*/
#define ADM_BIT_MASK_COPP_LIVE_INPUT_FLAG (0x0001U)
/* Definition for a COPP live shift value bitmask.*/
#define ADM_SHIFT_COPP_LIVE_INPUT_FLAG 0
/* Definition for the COPP ID bitmask.*/
#define ADM_BIT_MASK_COPP_ID (0x0000FFFFUL)
/* Definition for the COPP ID shift value.*/
#define ADM_SHIFT_COPP_ID 0
/* Definition for the service ID bitmask.*/
#define ADM_BIT_MASK_SERVICE_ID (0x00FF0000UL)
/* Definition for the service ID shift value.*/
#define ADM_SHIFT_SERVICE_ID 16
/* Definition for the domain ID bitmask.*/
#define ADM_BIT_MASK_DOMAIN_ID (0xFF000000UL)
/* Definition for the domain ID shift value.*/
#define ADM_SHIFT_DOMAIN_ID 24
/* ADM device open command payload of the
#ADM_CMD_DEVICE_OPEN_V5 command.
*/
struct adm_cmd_device_open_v5 {
struct apr_hdr hdr;
u16 flags;
/* Reserved for future use. Clients must set this field
* to zero.
*/
u16 mode_of_operation;
/* Specifies whether the COPP must be opened on the Tx or Rx
* path. Use the ADM_CMD_COPP_OPEN_MODE_OF_OPERATION_* macros for
* supported values and interpretation.
* Supported values:
* - 0x1 -- Rx path COPP
* - 0x2 -- Tx path live COPP
* - 0x3 -- Tx path nonlive COPP
* Live connections cause sample discarding in the Tx device
* matrix if the destination output ports do not pull them
* fast enough. Nonlive connections queue the samples
* indefinitely.
*/
u16 endpoint_id_1;
/* Logical and physical endpoint ID of the audio path.
* If the ID is a voice processor Tx block, it receives near
* samples. Supported values: Any pseudoport, AFE Rx port,
* or AFE Tx port For a list of valid IDs, refer to
* @xhyperref{Q4,[Q4]}.
* Q4 = Hexagon Multimedia: AFE Interface Specification
*/
u16 endpoint_id_2;
/* Logical and physical endpoint ID 2 for a voice processor
* Tx block.
* This is not applicable to audio COPP.
* Supported values:
* - AFE Rx port
* - 0xFFFF -- Endpoint 2 is unavailable and the voice
* processor Tx
* block ignores this endpoint
* When the voice processor Tx block is created on the audio
* record path,
* it can receive far-end samples from an AFE Rx port if the
* voice call
* is active. The ID of the AFE port is provided in this
* field.
* For a list of valid IDs, refer @xhyperref{Q4,[Q4]}.
*/
u32 topology_id;
/* Audio COPP topology ID; 32-bit GUID. */
u16 dev_num_channel;
/* Number of channels the audio COPP sends to/receives from
* the endpoint.
* Supported values: 1 to 8.
* The value is ignored for the voice processor Tx block,
* where channel
* configuration is derived from the topology ID.
*/
u16 bit_width;
/* Bit width (in bits) that the audio COPP sends to/receives
* from the
* endpoint. The value is ignored for the voice processing
* Tx block,
* where the PCM width is 16 bits.
*/
u32 sample_rate;
/* Sampling rate at which the audio COPP/voice processor
* Tx block
* interfaces with the endpoint.
* Supported values for voice processor Tx: 8000, 16000,
* 48000 Hz
* Supported values for audio COPP: >0 and <=192 kHz
*/
u8 dev_channel_mapping[8];
/* Array of channel mapping of buffers that the audio COPP
* sends to the endpoint. Channel[i] mapping describes channel
* I inside the buffer, where 0 < i < dev_num_channel.
* This value is relevent only for an audio Rx COPP.
* For the voice processor block and Tx audio block, this field
* is set to zero and is ignored.
*/
} __packed;
/*
* This command allows the client to close a COPP and disconnect
* the device session.
*/
#define ADM_CMD_DEVICE_CLOSE_V5 0x00010327
/* Sets one or more parameters to a COPP.
*/
#define ADM_CMD_SET_PP_PARAMS_V5 0x00010328
/* Payload of the #ADM_CMD_SET_PP_PARAMS_V5 command.
* If the data_payload_addr_lsw and data_payload_addr_msw element
* are NULL, a series of adm_param_datastructures immediately
* follows, whose total size is data_payload_size bytes.
*/
struct adm_cmd_set_pp_params_v5 {
struct apr_hdr hdr;
u32 payload_addr_lsw;
/* LSW of parameter data payload address.*/
u32 payload_addr_msw;
/* MSW of parameter data payload address.*/
u32 mem_map_handle;
/* Memory map handle returned by ADM_CMD_SHARED_MEM_MAP_REGIONS
* command */
/* If mem_map_handle is zero implies the message is in
* the payload */
u32 payload_size;
/* Size in bytes of the variable payload accompanying this
* message or
* in shared memory. This is used for parsing the parameter
* payload.
*/
} __packed;
/* Payload format for COPP parameter data.
* Immediately following this structure are param_size bytes
* of parameter
* data.
*/
struct adm_param_data_v5 {
u32 module_id;
/* Unique ID of the module. */
u32 param_id;
/* Unique ID of the parameter. */
u16 param_size;
/* Data size of the param_id/module_id combination.
This value is a
multiple of 4 bytes. */
u16 reserved;
/* Reserved for future enhancements.
* This field must be set to zero.
*/
} __packed;
/* Defined specifically for in-band use, includes params */
struct adm_cmd_set_pp_params_inband_v5 {
struct apr_hdr hdr;
/* LSW of parameter data payload address.*/
u32 payload_addr_lsw;
/* MSW of parameter data payload address.*/
u32 payload_addr_msw;
/* Memory map handle returned by ADM_CMD_SHARED_MEM_MAP_REGIONS */
/* command. If mem_map_handle is zero implies the message is in */
/* the payload */
u32 mem_map_handle;
/* Size in bytes of the variable payload accompanying this */
/* message or in shared memory. This is used for parsing the */
/* parameter payload. */
u32 payload_size;
/* Parameters passed for in band payload */
struct adm_param_data_v5 params;
} __packed;
/* Returns the status and COPP ID to an #ADM_CMD_DEVICE_OPEN_V5 command.
*/
#define ADM_CMDRSP_DEVICE_OPEN_V5 0x00010329
/* Payload of the #ADM_CMDRSP_DEVICE_OPEN_V5 message,
* which returns the
* status and COPP ID to an #ADM_CMD_DEVICE_OPEN_V5 command.
*/
struct adm_cmd_rsp_device_open_v5 {
u32 status;
/* Status message (error code).*/
u16 copp_id;
/* COPP ID: Supported values: 0 <= copp_id < ADM_MAX_COPPS*/
u16 reserved;
/* Reserved. This field must be set to zero.*/
} __packed;
/* This command allows a query of one COPP parameter.
*/
#define ADM_CMD_GET_PP_PARAMS_V5 0x0001032A
/* Payload an #ADM_CMD_GET_PP_PARAMS_V5 command.
*/
struct adm_cmd_get_pp_params_v5 {
struct apr_hdr hdr;
u32 data_payload_addr_lsw;
/* LSW of parameter data payload address.*/
u32 data_payload_addr_msw;
/* MSW of parameter data payload address.*/
/* If the mem_map_handle is non zero,
* on ACK, the ParamData payloads begin at
* the address specified (out-of-band).
*/
u32 mem_map_handle;
/* Memory map handle returned
* by ADM_CMD_SHARED_MEM_MAP_REGIONS command.
* If the mem_map_handle is 0, it implies that
* the ACK's payload will contain the ParamData (in-band).
*/
u32 module_id;
/* Unique ID of the module. */
u32 param_id;
/* Unique ID of the parameter. */
u16 param_max_size;
/* Maximum data size of the parameter
*ID/module ID combination. This
* field is a multiple of 4 bytes.
*/
u16 reserved;
/* Reserved for future enhancements.
* This field must be set to zero.
*/
} __packed;
/* Returns parameter values
* in response to an #ADM_CMD_GET_PP_PARAMS_V5 command.
*/
#define ADM_CMDRSP_GET_PP_PARAMS_V5 0x0001032B
/* Payload of the #ADM_CMDRSP_GET_PP_PARAMS_V5 message,
* which returns parameter values in response
* to an #ADM_CMD_GET_PP_PARAMS_V5 command.
* Immediately following this
* structure is the adm_param_data_v5
* structure containing the pre/postprocessing
* parameter data. For an in-band
* scenario, the variable payload depends
* on the size of the parameter.
*/
struct adm_cmd_rsp_get_pp_params_v5 {
u32 status;
/* Status message (error code).*/
} __packed;
/* Allows a client to control the gains on various session-to-COPP paths.
*/
#define ADM_CMD_MATRIX_RAMP_GAINS_V5 0x0001032C
/* Indicates that the target gain in the
* current adm_session_copp_gain_v5
* structure is to be applied to all
* the session-to-COPP paths that exist for
* the specified session.
*/
#define ADM_CMD_MATRIX_RAMP_GAINS_COPP_ID_ALL_CONNECTED_COPPS 0xFFFF
/* Indicates that the target gain is
* to be immediately applied to the
* specified session-to-COPP path,
* without a ramping fashion.
*/
#define ADM_CMD_MATRIX_RAMP_GAINS_RAMP_DURATION_IMMEDIATE 0x0000
/* Enumeration for a linear ramping curve.*/
#define ADM_CMD_MATRIX_RAMP_GAINS_RAMP_CURVE_LINEAR 0x0000
/* Payload of the #ADM_CMD_MATRIX_RAMP_GAINS_V5 command.
* Immediately following this structure are num_gains of the
* adm_session_copp_gain_v5structure.
*/
struct adm_cmd_matrix_ramp_gains_v5 {
u32 matrix_id;
/* Specifies whether the matrix ID is Audio Rx (0) or Audio Tx (1).
* Use the ADM_MATRIX_ID_AUDIO_RX or ADM_MATRIX_ID_AUDIOX
* macros to set this field.
*/
u16 num_gains;
/* Number of gains being applied. */
u16 reserved_for_align;
/* Reserved. This field must be set to zero.*/
} __packed;
/* Session-to-COPP path gain structure, used by the
* #ADM_CMD_MATRIX_RAMP_GAINS_V5 command.
* This structure specifies the target
* gain (per channel) that must be applied
* to a particular session-to-COPP path in
* the audio matrix. The structure can
* also be used to apply the gain globally
* to all session-to-COPP paths that
* exist for the given session.
* The aDSP uses device channel mapping to
* determine which channel gains to
* use from this command. For example,
* if the device is configured as stereo,
* the aDSP uses only target_gain_ch_1 and
* target_gain_ch_2, and it ignores
* the others.
*/
struct adm_session_copp_gain_v5 {
u16 session_id;
/* Handle of the ASM session.
* Supported values: 1 to 8.
*/
u16 copp_id;
/* Handle of the COPP. Gain will be applied on the Session ID
* COPP ID path.
*/
u16 ramp_duration;
/* Duration (in milliseconds) of the ramp over
* which target gains are
* to be applied. Use
* #ADM_CMD_MATRIX_RAMP_GAINS_RAMP_DURATION_IMMEDIATE
* to indicate that gain must be applied immediately.
*/
u16 step_duration;
/* Duration (in milliseconds) of each step in the ramp.
* This parameter is ignored if ramp_duration is equal to
* #ADM_CMD_MATRIX_RAMP_GAINS_RAMP_DURATION_IMMEDIATE.
* Supported value: 1
*/
u16 ramp_curve;
/* Type of ramping curve.
* Supported value: #ADM_CMD_MATRIX_RAMP_GAINS_RAMP_CURVE_LINEAR
*/
u16 reserved_for_align;
/* Reserved. This field must be set to zero. */
u16 target_gain_ch_1;
/* Target linear gain for channel 1 in Q13 format; */
u16 target_gain_ch_2;
/* Target linear gain for channel 2 in Q13 format; */
u16 target_gain_ch_3;
/* Target linear gain for channel 3 in Q13 format; */
u16 target_gain_ch_4;
/* Target linear gain for channel 4 in Q13 format; */
u16 target_gain_ch_5;
/* Target linear gain for channel 5 in Q13 format; */
u16 target_gain_ch_6;
/* Target linear gain for channel 6 in Q13 format; */
u16 target_gain_ch_7;
/* Target linear gain for channel 7 in Q13 format; */
u16 target_gain_ch_8;
/* Target linear gain for channel 8 in Q13 format; */
} __packed;
/* Allows to set mute/unmute on various session-to-COPP paths.
* For every session-to-COPP path (stream-device interconnection),
* mute/unmute can be set individually on the output channels.
*/
#define ADM_CMD_MATRIX_MUTE_V5 0x0001032D
/* Indicates that mute/unmute in the
* current adm_session_copp_mute_v5structure
* is to be applied to all the session-to-COPP
* paths that exist for the specified session.
*/
#define ADM_CMD_MATRIX_MUTE_COPP_ID_ALL_CONNECTED_COPPS 0xFFFF
/* Payload of the #ADM_CMD_MATRIX_MUTE_V5 command*/
struct adm_cmd_matrix_mute_v5 {
u32 matrix_id;
/* Specifies whether the matrix ID is Audio Rx (0) or Audio Tx (1).
* Use the ADM_MATRIX_ID_AUDIO_RX or ADM_MATRIX_ID_AUDIOX
* macros to set this field.
*/
u16 session_id;
/* Handle of the ASM session.
* Supported values: 1 to 8.
*/
u16 copp_id;
/* Handle of the COPP.
* Use ADM_CMD_MATRIX_MUTE_COPP_ID_ALL_CONNECTED_COPPS
* to indicate that mute/unmute must be applied to
* all the COPPs connected to session_id.
* Supported values:
* - 0xFFFF -- Apply mute/unmute to all connected COPPs
* - Other values -- Valid COPP ID
*/
u8 mute_flag_ch_1;
/* Mute flag for channel 1 is set to unmute (0) or mute (1). */
u8 mute_flag_ch_2;
/* Mute flag for channel 2 is set to unmute (0) or mute (1). */
u8 mute_flag_ch_3;
/* Mute flag for channel 3 is set to unmute (0) or mute (1). */
u8 mute_flag_ch_4;
/* Mute flag for channel 4 is set to unmute (0) or mute (1). */
u8 mute_flag_ch_5;
/* Mute flag for channel 5 is set to unmute (0) or mute (1). */
u8 mute_flag_ch_6;
/* Mute flag for channel 6 is set to unmute (0) or mute (1). */
u8 mute_flag_ch_7;
/* Mute flag for channel 7 is set to unmute (0) or mute (1). */
u8 mute_flag_ch_8;
/* Mute flag for channel 8 is set to unmute (0) or mute (1). */
u16 ramp_duration;
/* Period (in milliseconds) over which the soft mute/unmute will be
* applied.
* Supported values: 0 (Default) to 0xFFFF
* The default of 0 means mute/unmute will be applied immediately.
*/
u16 reserved_for_align;
/* Clients must set this field to zero.*/
} __packed;
#define ASM_PARAM_ID_AAC_STEREO_MIX_COEFF_SELECTION_FLAG_V2 (0x00010DD8)
struct asm_aac_stereo_mix_coeff_selection_param_v2 {
struct apr_hdr hdr;
u32 param_id;
u32 param_size;
u32 aac_stereo_mix_coeff_flag;
} __packed;
/* Allows a client to connect the desired stream to
* the desired AFE port through the stream router
*
* This command allows the client to connect specified session to
* specified AFE port. This is used for compressed streams only
* opened using the #ASM_STREAM_CMD_OPEN_WRITE_COMPRESSED or
* #ASM_STREAM_CMD_OPEN_READ_COMPRESSED command.
*
* @prerequisites
* Session ID and AFE Port ID must be valid.
* #ASM_STREAM_CMD_OPEN_WRITE_COMPRESSED or
* #ASM_STREAM_CMD_OPEN_READ_COMPRESSED
* must have been called on this session.
*/
#define ADM_CMD_CONNECT_AFE_PORT_V5 0x0001032E
#define ADM_CMD_DISCONNECT_AFE_PORT_V5 0x0001032F
/* Enumeration for the Rx stream router ID.*/
#define ADM_STRTR_ID_RX 0
/* Enumeration for the Tx stream router ID.*/
#define ADM_STRTR_IDX 1
/* Payload of the #ADM_CMD_CONNECT_AFE_PORT_V5 command.*/
struct adm_cmd_connect_afe_port_v5 {
struct apr_hdr hdr;
u8 mode;
/* ID of the stream router (RX/TX). Use the
* ADM_STRTR_ID_RX or ADM_STRTR_IDX macros
* to set this field.
*/
u8 session_id;
/* Session ID of the stream to connect */
u16 afe_port_id;
/* Port ID of the AFE port to connect to.*/
u32 num_channels;
/* Number of device channels
* Supported values: 2(Audio Sample Packet),
* 8 (HBR Audio Stream Sample Packet)
*/
u32 sampling_rate;
/* Device sampling rate
* Supported values: Any
*/
} __packed;
/* adsp_adm_api.h */
/* Port ID. Update afe_get_port_index
* when a new port is added here. */
#define PRIMARY_I2S_RX 0
#define PRIMARY_I2S_TX 1
#define SECONDARY_I2S_RX 4
#define SECONDARY_I2S_TX 5
#define MI2S_RX 6
#define MI2S_TX 7
#define HDMI_RX 8
#define RSVD_2 9
#define RSVD_3 10
#define DIGI_MIC_TX 11
#define VOICE2_PLAYBACK_TX 0x8002
#define VOICE_RECORD_RX 0x8003
#define VOICE_RECORD_TX 0x8004
#define VOICE_PLAYBACK_TX 0x8005
/* Slimbus Multi channel port id pool */
#define SLIMBUS_0_RX 0x4000
#define SLIMBUS_0_TX 0x4001
#define SLIMBUS_1_RX 0x4002
#define SLIMBUS_1_TX 0x4003
#define SLIMBUS_2_RX 0x4004
#define SLIMBUS_2_TX 0x4005
#define SLIMBUS_3_RX 0x4006
#define SLIMBUS_3_TX 0x4007
#define SLIMBUS_4_RX 0x4008
#define SLIMBUS_4_TX 0x4009
#define SLIMBUS_5_RX 0x400a
#define SLIMBUS_5_TX 0x400b
#define SLIMBUS_6_RX 0x400c
#define SLIMBUS_6_TX 0x400d
#define SLIMBUS_PORT_LAST SLIMBUS_6_TX
#define INT_BT_SCO_RX 0x3000
#define INT_BT_SCO_TX 0x3001
#define INT_BT_A2DP_RX 0x3002
#define INT_FM_RX 0x3004
#define INT_FM_TX 0x3005
#define RT_PROXY_PORT_001_RX 0x2000
#define RT_PROXY_PORT_001_TX 0x2001
#define AFE_PORT_INVALID 0xFFFF
#define SLIMBUS_INVALID AFE_PORT_INVALID
#define AFE_PORT_CMD_START 0x000100ca
#define AFE_EVENT_RTPORT_START 0
#define AFE_EVENT_RTPORT_STOP 1
#define AFE_EVENT_RTPORT_LOW_WM 2
#define AFE_EVENT_RTPORT_HI_WM 3
#define ADSP_AFE_VERSION 0x00200000
/* Size of the range of port IDs for the audio interface. */
#define AFE_PORT_ID_AUDIO_IF_PORT_RANGE_SIZE 0xF
/* Size of the range of port IDs for internal BT-FM ports. */
#define AFE_PORT_ID_INTERNAL_BT_FM_RANGE_SIZE 0x6
/* Size of the range of port IDs for SLIMbus<sup>®
* </sup> multichannel
* ports.
*/
#define AFE_PORT_ID_SLIMBUS_RANGE_SIZE 0xA
/* Size of the range of port IDs for real-time proxy ports. */
#define AFE_PORT_ID_RT_PROXY_PORT_RANGE_SIZE 0x2
/* Size of the range of port IDs for pseudoports. */
#define AFE_PORT_ID_PSEUDOPORT_RANGE_SIZE 0x5
/* Start of the range of port IDs for the audio interface. */
#define AFE_PORT_ID_AUDIO_IF_PORT_RANGE_START 0x1000
/* End of the range of port IDs for the audio interface. */
#define AFE_PORT_ID_AUDIO_IF_PORT_RANGE_END \
(AFE_PORT_ID_AUDIO_IF_PORT_RANGE_START +\
AFE_PORT_ID_AUDIO_IF_PORT_RANGE_SIZE - 1)
/* Start of the range of port IDs for real-time proxy ports. */
#define AFE_PORT_ID_RT_PROXY_PORT_RANGE_START 0x2000
/* End of the range of port IDs for real-time proxy ports. */
#define AFE_PORT_ID_RT_PROXY_PORT_RANGE_END \
(AFE_PORT_ID_RT_PROXY_PORT_RANGE_START +\
AFE_PORT_ID_RT_PROXY_PORT_RANGE_SIZE-1)
/* Start of the range of port IDs for internal BT-FM devices. */
#define AFE_PORT_ID_INTERNAL_BT_FM_RANGE_START 0x3000
/* End of the range of port IDs for internal BT-FM devices. */
#define AFE_PORT_ID_INTERNAL_BT_FM_RANGE_END \
(AFE_PORT_ID_INTERNAL_BT_FM_RANGE_START +\
AFE_PORT_ID_INTERNAL_BT_FM_RANGE_SIZE-1)
/* Start of the range of port IDs for SLIMbus devices. */
#define AFE_PORT_ID_SLIMBUS_RANGE_START 0x4000
/* End of the range of port IDs for SLIMbus devices. */
#define AFE_PORT_ID_SLIMBUS_RANGE_END \
(AFE_PORT_ID_SLIMBUS_RANGE_START +\
AFE_PORT_ID_SLIMBUS_RANGE_SIZE-1)
/* Start of the range of port IDs for pseudoports. */
#define AFE_PORT_ID_PSEUDOPORT_RANGE_START 0x8001
/* End of the range of port IDs for pseudoports. */
#define AFE_PORT_ID_PSEUDOPORT_RANGE_END \
(AFE_PORT_ID_PSEUDOPORT_RANGE_START +\
AFE_PORT_ID_PSEUDOPORT_RANGE_SIZE-1)
#define AFE_PORT_ID_PRIMARY_MI2S_RX 0x1000
#define AFE_PORT_ID_PRIMARY_MI2S_TX 0x1001
#define AFE_PORT_ID_SECONDARY_MI2S_RX 0x1002
#define AFE_PORT_ID_SECONDARY_MI2S_TX 0x1003
#define AFE_PORT_ID_TERTIARY_MI2S_RX 0x1004
#define AFE_PORT_ID_TERTIARY_MI2S_TX 0x1005
#define AFE_PORT_ID_QUATERNARY_MI2S_RX 0x1006
#define AFE_PORT_ID_QUATERNARY_MI2S_TX 0x1007
#define AUDIO_PORT_ID_I2S_RX 0x1008
#define AFE_PORT_ID_DIGITAL_MIC_TX 0x1009
#define AFE_PORT_ID_PRIMARY_PCM_RX 0x100A
#define AFE_PORT_ID_PRIMARY_PCM_TX 0x100B
#define AFE_PORT_ID_SECONDARY_PCM_RX 0x100C
#define AFE_PORT_ID_SECONDARY_PCM_TX 0x100D
#define AFE_PORT_ID_MULTICHAN_HDMI_RX 0x100E
#define AFE_PORT_ID_SECONDARY_MI2S_RX_VIBRA 0x1010
#define AFE_PORT_ID_RT_PROXY_PORT_001_RX 0x2000
#define AFE_PORT_ID_RT_PROXY_PORT_001_TX 0x2001
#define AFE_PORT_ID_INTERNAL_BT_SCO_RX 0x3000
#define AFE_PORT_ID_INTERNAL_BT_SCO_TX 0x3001
#define AFE_PORT_ID_INTERNAL_BT_A2DP_RX 0x3002
#define AFE_PORT_ID_INTERNAL_FM_RX 0x3004
#define AFE_PORT_ID_INTERNAL_FM_TX 0x3005
/* SLIMbus Rx port on channel 0. */
#define AFE_PORT_ID_SLIMBUS_MULTI_CHAN_0_RX 0x4000
/* SLIMbus Tx port on channel 0. */
#define AFE_PORT_ID_SLIMBUS_MULTI_CHAN_0_TX 0x4001
/* SLIMbus Rx port on channel 1. */
#define AFE_PORT_ID_SLIMBUS_MULTI_CHAN_1_RX 0x4002
/* SLIMbus Tx port on channel 1. */
#define AFE_PORT_ID_SLIMBUS_MULTI_CHAN_1_TX 0x4003
/* SLIMbus Rx port on channel 2. */
#define AFE_PORT_ID_SLIMBUS_MULTI_CHAN_2_RX 0x4004
/* SLIMbus Tx port on channel 2. */
#define AFE_PORT_ID_SLIMBUS_MULTI_CHAN_2_TX 0x4005
/* SLIMbus Rx port on channel 3. */
#define AFE_PORT_ID_SLIMBUS_MULTI_CHAN_3_RX 0x4006
/* SLIMbus Tx port on channel 3. */
#define AFE_PORT_ID_SLIMBUS_MULTI_CHAN_3_TX 0x4007
/* SLIMbus Rx port on channel 4. */
#define AFE_PORT_ID_SLIMBUS_MULTI_CHAN_4_RX 0x4008
/* SLIMbus Tx port on channel 4. */
#define AFE_PORT_ID_SLIMBUS_MULTI_CHAN_4_TX 0x4009
/* SLIMbus Rx port on channel 5. */
#define AFE_PORT_ID_SLIMBUS_MULTI_CHAN_5_RX 0x400a
/* SLIMbus Tx port on channel 5. */
#define AFE_PORT_ID_SLIMBUS_MULTI_CHAN_5_TX 0x400b
/* SLIMbus Rx port on channel 6. */
#define AFE_PORT_ID_SLIMBUS_MULTI_CHAN_6_RX 0x400c
/* SLIMbus Tx port on channel 6. */
#define AFE_PORT_ID_SLIMBUS_MULTI_CHAN_6_TX 0x400d
/* Generic pseudoport 1. */
#define AFE_PORT_ID_PSEUDOPORT_01 0x8001
/* Generic pseudoport 2. */
#define AFE_PORT_ID_PSEUDOPORT_02 0x8002
/* @xreflabel{hdr:AfePortIdPrimaryAuxPcmTx}
Primary Aux PCM Tx port ID.
*/
#define AFE_PORT_ID_PRIMARY_PCM_TX 0x100B
/* Pseudoport that corresponds to the voice Rx path.
* For recording, the voice Rx path samples are written to this
* port and consumed by the audio path.
*/
#define AFE_PORT_ID_VOICE_RECORD_RX 0x8003
/* Pseudoport that corresponds to the voice Tx path.
* For recording, the voice Tx path samples are written to this
* port and consumed by the audio path.
*/
#define AFE_PORT_ID_VOICE_RECORD_TX 0x8004
/* Pseudoport that corresponds to in-call voice delivery samples.
* During in-call audio delivery, the audio path delivers samples
* to this port from where the voice path delivers them on the
* Rx path.
*/
#define AFE_PORT_ID_VOICE2_PLAYBACK_TX 0x8002
#define AFE_PORT_ID_VOICE_PLAYBACK_TX 0x8005
#define AFE_PORT_ID_INVALID 0xFFFF
#define AAC_ENC_MODE_AAC_LC 0x02
#define AAC_ENC_MODE_AAC_P 0x05
#define AAC_ENC_MODE_EAAC_P 0x1D
#define AFE_PSEUDOPORT_CMD_START 0x000100cf
struct afe_pseudoport_start_command {
struct apr_hdr hdr;
u16 port_id; /* Pseudo Port 1 = 0x8000 */
/* Pseudo Port 2 = 0x8001 */
/* Pseudo Port 3 = 0x8002 */
u16 timing; /* FTRT = 0 , AVTimer = 1, */
} __packed;
#define AFE_PSEUDOPORT_CMD_STOP 0x000100d0
struct afe_pseudoport_stop_command {
struct apr_hdr hdr;
u16 port_id; /* Pseudo Port 1 = 0x8000 */
/* Pseudo Port 2 = 0x8001 */
/* Pseudo Port 3 = 0x8002 */
u16 reserved;
} __packed;
#define AFE_MODULE_SIDETONE_IIR_FILTER 0x00010202
#define AFE_PARAM_ID_ENABLE 0x00010203
/* Payload of the #AFE_PARAM_ID_ENABLE
* parameter, which enables or
* disables any module.
* The fixed size of this structure is four bytes.
*/
struct afe_mod_enable_param {
u16 enable;
/* Enables (1) or disables (0) the module. */
u16 reserved;
/* This field must be set to zero.
*/
} __packed;
/* ID of the configuration parameter used by the
* #AFE_MODULE_SIDETONE_IIR_FILTER module.
*/
#define AFE_PARAM_ID_SIDETONE_IIR_FILTER_CONFIG 0x00010204
struct afe_sidetone_iir_filter_config_params {
u16 num_biquad_stages;
/* Number of stages.
* Supported values: Minimum of 5 and maximum of 10
*/
u16 pregain;
/* Pregain for the compensating filter response.
* Supported values: Any number in Q13 format
*/
} __packed;
#define AFE_MODULE_LOOPBACK 0x00010205
#define AFE_PARAM_ID_LOOPBACK_GAIN_PER_PATH 0x00010206
/* Payload of the #AFE_PARAM_ID_LOOPBACK_GAIN_PER_PATH parameter,
* which gets/sets loopback gain of a port to an Rx port.
* The Tx port ID of the loopback is part of the set_param command.
*/
/* Payload of the #AFE_PORT_CMD_SET_PARAM_V2 command's
* configuration/calibration settings for the AFE port.
*/
struct afe_port_cmd_set_param_v2 {
u16 port_id;
/* Port interface and direction (Rx or Tx) to start.
*/
u16 payload_size;
/* Actual size of the payload in bytes.
* This is used for parsing the parameter payload.
* Supported values: > 0
*/
u32 payload_address_lsw;
/* LSW of 64 bit Payload address.
* Address should be 32-byte,
* 4kbyte aligned and must be contiguous memory.
*/
u32 payload_address_msw;
/* MSW of 64 bit Payload address.
* In case of 32-bit shared memory address,
* this field must be set to zero.
* In case of 36-bit shared memory address,
* bit-4 to bit-31 must be set to zero.
* Address should be 32-byte, 4kbyte aligned
* and must be contiguous memory.
*/
u32 mem_map_handle;
/* Memory map handle returned by
* AFE_SERVICE_CMD_SHARED_MEM_MAP_REGIONS commands.
* Supported Values:
* - NULL -- Message. The parameter data is in-band.
* - Non-NULL -- The parameter data is Out-band.Pointer to
* the physical address
* in shared memory of the payload data.
* An optional field is available if parameter
* data is in-band:
* afe_param_data_v2 param_data[...].
* For detailed payload content, see the
* afe_port_param_data_v2 structure.
*/
} __packed;
#define AFE_PORT_CMD_SET_PARAM_V2 0x000100EF
struct afe_port_param_data_v2 {
u32 module_id;
/* ID of the module to be configured.
* Supported values: Valid module ID
*/
u32 param_id;
/* ID of the parameter corresponding to the supported parameters
* for the module ID.
* Supported values: Valid parameter ID
*/
u16 param_size;
/* Actual size of the data for the
* module_id/param_id pair. The size is a
* multiple of four bytes.
* Supported values: > 0
*/
u16 reserved;
/* This field must be set to zero.
*/
} __packed;
struct afe_loopback_gain_per_path_param {
struct apr_hdr hdr;
struct afe_port_cmd_set_param_v2 param;
struct afe_port_param_data_v2 pdata;
u16 rx_port_id;
/* Rx port of the loopback. */
u16 gain;
/* Loopback gain per path of the port.
* Supported values: Any number in Q13 format
*/
} __packed;
/* Parameter ID used to configure and enable/disable the
* loopback path. The difference with respect to the existing
* API, AFE_PORT_CMD_LOOPBACK, is that it allows Rx port to be
* configured as source port in loopback path. Port-id in
* AFE_PORT_CMD_SET_PARAM cmd is the source port whcih can be
* Tx or Rx port. In addition, we can configure the type of
* routing mode to handle different use cases.
*/
#define AFE_PARAM_ID_LOOPBACK_CONFIG 0x0001020B
#define AFE_API_VERSION_LOOPBACK_CONFIG 0x1
enum afe_loopback_routing_mode {
LB_MODE_DEFAULT = 1,
/* Regular loopback from source to destination port */
LB_MODE_SIDETONE,
/* Sidetone feed from Tx source to Rx destination port */
LB_MODE_EC_REF_VOICE_AUDIO,
/* Echo canceller reference, voice + audio + DTMF */
LB_MODE_EC_REF_VOICE
/* Echo canceller reference, voice alone */
} __packed;
/* Payload of the #AFE_PARAM_ID_LOOPBACK_CONFIG ,
* which enables/disables one AFE loopback.
*/
struct afe_loopback_cfg_v1 {
struct apr_hdr hdr;
struct afe_port_cmd_set_param_v2 param;
struct afe_port_param_data_v2 pdata;
u32 loopback_cfg_minor_version;
/* Minor version used for tracking the version of the RMC module
* configuration interface.
* Supported values: #AFE_API_VERSION_LOOPBACK_CONFIG
*/
u16 dst_port_id;
/* Destination Port Id. */
u16 routing_mode;
/* Specifies data path type from src to dest port.
* Supported values:
* #LB_MODE_DEFAULT
* #LB_MODE_SIDETONE
* #LB_MODE_EC_REF_VOICE_AUDIO
* #LB_MODE_EC_REF_VOICE_A
* #LB_MODE_EC_REF_VOICE
*/
u16 enable;
/* Specifies whether to enable (1) or
* disable (0) an AFE loopback.
*/
u16 reserved;
/* Reserved for 32-bit alignment. This field must be set to 0.
*/
} __packed;
#define AFE_MODULE_SPEAKER_PROTECTION 0x00010209
#define AFE_PARAM_ID_SPKR_PROT_CONFIG 0x0001020a
#define AFE_API_VERSION_SPKR_PROT_CONFIG 0x1
#define AFE_SPKR_PROT_EXCURSIONF_LEN 512
struct afe_spkr_prot_cfg_param_v1 {
u32 spkr_prot_minor_version;
/*
* Minor version used for tracking the version of the
* speaker protection module configuration interface.
* Supported values: #AFE_API_VERSION_SPKR_PROT_CONFIG
*/
int16_t win_size;
/* Analysis and synthesis window size (nWinSize).
* Supported values: 1024, 512, 256 samples
*/
int16_t margin;
/* Allowable margin for excursion prediction,
* in L16Q15 format. This is a
* control parameter to allow
* for overestimation of peak excursion.
*/
int16_t spkr_exc_limit;
/* Speaker excursion limit, in L16Q15 format.*/
int16_t spkr_resonance_freq;
/* Resonance frequency of the speaker; used
* to define a frequency range
* for signal modification.
*
* Supported values: 0 to 2000 Hz */
int16_t limhresh;
/* Threshold of the hard limiter; used to
* prevent overshooting beyond a
* signal level that was set by the limiter
* prior to speaker protection.
* Supported values: 0 to 32767
*/
int16_t hpf_cut_off_freq;
/* High pass filter cutoff frequency.
* Supported values: 100, 200, 300 Hz
*/
int16_t hpf_enable;
/* Specifies whether the high pass filter
* is enabled (0) or disabled (1).
*/
int16_t reserved;
/* This field must be set to zero. */
int32_t amp_gain;
/* Amplifier gain in L32Q15 format.
* This is the RMS voltage at the
* loudspeaker when a 0dBFS tone
* is played in the digital domain.
*/
int16_t excursionf[AFE_SPKR_PROT_EXCURSIONF_LEN];
/* Array of the excursion transfer function.
* The peak excursion of the
* loudspeaker diaphragm is
* measured in millimeters for 1 Vrms Sine
* tone at all FFT bin frequencies.
* Supported values: Q15 format
*/
} __packed;
#define AFE_SERVICE_CMD_REGISTER_RT_PORT_DRIVER 0x000100E0
/* Payload of the #AFE_SERVICE_CMD_REGISTER_RT_PORT_DRIVER
* command, which registers a real-time port driver
* with the AFE service.
*/
struct afe_service_cmd_register_rt_port_driver {
struct apr_hdr hdr;
u16 port_id;
/* Port ID with which the real-time driver exchanges data
* (registers for events).
* Supported values: #AFE_PORT_ID_RT_PROXY_PORT_RANGE_START to
* #AFE_PORT_ID_RT_PROXY_PORT_RANGE_END
*/
u16 reserved;
/* This field must be set to zero. */
} __packed;
#define AFE_SERVICE_CMD_UNREGISTER_RT_PORT_DRIVER 0x000100E1
/* Payload of the #AFE_SERVICE_CMD_UNREGISTER_RT_PORT_DRIVER
* command, which unregisters a real-time port driver from
* the AFE service.
*/
struct afe_service_cmd_unregister_rt_port_driver {
struct apr_hdr hdr;
u16 port_id;
/* Port ID from which the real-time
* driver unregisters for events.
* Supported values: #AFE_PORT_ID_RT_PROXY_PORT_RANGE_START to
* #AFE_PORT_ID_RT_PROXY_PORT_RANGE_END
*/
u16 reserved;
/* This field must be set to zero. */
} __packed;
#define AFE_EVENT_RT_PROXY_PORT_STATUS 0x00010105
#define AFE_EVENTYPE_RT_PROXY_PORT_START 0
#define AFE_EVENTYPE_RT_PROXY_PORT_STOP 1
#define AFE_EVENTYPE_RT_PROXY_PORT_LOW_WATER_MARK 2
#define AFE_EVENTYPE_RT_PROXY_PORT_HIGH_WATER_MARK 3
#define AFE_EVENTYPE_RT_PROXY_PORT_INVALID 0xFFFF
/* Payload of the #AFE_EVENT_RT_PROXY_PORT_STATUS
* message, which sends an event from the AFE service
* to a registered client.
*/
struct afe_event_rt_proxy_port_status {
u16 port_id;
/* Port ID to which the event is sent.
* Supported values: #AFE_PORT_ID_RT_PROXY_PORT_RANGE_START to
* #AFE_PORT_ID_RT_PROXY_PORT_RANGE_END
*/
u16 eventype;
/* Type of event.
* Supported values:
* - #AFE_EVENTYPE_RT_PROXY_PORT_START
* - #AFE_EVENTYPE_RT_PROXY_PORT_STOP
* - #AFE_EVENTYPE_RT_PROXY_PORT_LOW_WATER_MARK
* - #AFE_EVENTYPE_RT_PROXY_PORT_HIGH_WATER_MARK
*/
} __packed;
#define AFE_PORT_DATA_CMD_RT_PROXY_PORT_WRITE_V2 0x000100ED
struct afe_port_data_cmd_rt_proxy_port_write_v2 {
struct apr_hdr hdr;
u16 port_id;
/* Tx (mic) proxy port ID with which the real-time
* driver exchanges data.
* Supported values: #AFE_PORT_ID_RT_PROXY_PORT_RANGE_START to
* #AFE_PORT_ID_RT_PROXY_PORT_RANGE_END
*/
u16 reserved;
/* This field must be set to zero. */
u32 buffer_address_lsw;
/* LSW Address of the buffer containing the
* data from the real-time source
* device on a client.
*/
u32 buffer_address_msw;
/* MSW Address of the buffer containing the
* data from the real-time source
* device on a client.
*/
u32 mem_map_handle;
/* A memory map handle encapsulating shared memory
* attributes is returned if
* AFE_SERVICE_CMD_SHARED_MEM_MAP_REGIONS
* command is successful.
* Supported Values:
* - Any 32 bit value
*/
u32 available_bytes;
/* Number of valid bytes available
* in the buffer (including all
* channels: number of bytes per
* channel = availableBytesumChannels).
* Supported values: > 0
*
* This field must be equal to the frame
* size specified in the #AFE_PORT_AUDIO_IF_CONFIG
* command that was sent to configure this
* port.
*/
} __packed;
#define AFE_PORT_DATA_CMD_RT_PROXY_PORT_READ_V2 0x000100EE
/* Payload of the
* #AFE_PORT_DATA_CMD_RT_PROXY_PORT_READ_V2 command, which
* delivers an empty buffer to the AFE service. On
* acknowledgment, data is filled in the buffer.
*/
struct afe_port_data_cmd_rt_proxy_port_read_v2 {
struct apr_hdr hdr;
u16 port_id;
/* Rx proxy port ID with which the real-time
* driver exchanges data.
* Supported values: #AFE_PORT_ID_RT_PROXY_PORT_RANGE_START to
* #AFE_PORT_ID_RT_PROXY_PORT_RANGE_END
* (This must be an Rx (speaker) port.)
*/
u16 reserved;
/* This field must be set to zero. */
u32 buffer_address_lsw;
/* LSW Address of the buffer containing the data sent from the AFE
* service to a real-time sink device on the client.
*/
u32 buffer_address_msw;
/* MSW Address of the buffer containing the data sent from the AFE
* service to a real-time sink device on the client.
*/
u32 mem_map_handle;
/* A memory map handle encapsulating shared memory attributes is
* returned if AFE_SERVICE_CMD_SHARED_MEM_MAP_REGIONS command is
* successful.
* Supported Values:
* - Any 32 bit value
*/
u32 available_bytes;
/* Number of valid bytes available in the buffer (including all
* channels).
* Supported values: > 0
* This field must be equal to the frame size specified in the
* #AFE_PORT_AUDIO_IF_CONFIG command that was sent to configure
* this port.
*/
} __packed;
/* This module ID is related to device configuring like I2S,PCM,
* HDMI, SLIMBus etc. This module supports follwing parameter ids.
* - #AFE_PARAM_ID_I2S_CONFIG
* - #AFE_PARAM_ID_PCM_CONFIG
* - #AFE_PARAM_ID_DIGI_MIC_CONFIG
* - #AFE_PARAM_ID_HDMI_CONFIG
* - #AFE_PARAM_ID_INTERNAL_BT_FM_CONFIG
* - #AFE_PARAM_ID_SLIMBUS_CONFIG
* - #AFE_PARAM_ID_RT_PROXY_CONFIG
*/
#define AFE_MODULE_AUDIO_DEV_INTERFACE 0x0001020C
#define AFE_PORT_SAMPLE_RATE_8K 8000
#define AFE_PORT_SAMPLE_RATE_16K 16000
#define AFE_PORT_SAMPLE_RATE_48K 48000
#define AFE_PORT_SAMPLE_RATE_96K 96000
#define AFE_PORT_SAMPLE_RATE_192K 192000
#define AFE_LINEAR_PCM_DATA 0x0
#define AFE_NON_LINEAR_DATA 0x1
#define AFE_LINEAR_PCM_DATA_PACKED_60958 0x2
#define AFE_NON_LINEAR_DATA_PACKED_60958 0x3
/* This param id is used to configure I2S interface */
#define AFE_PARAM_ID_I2S_CONFIG 0x0001020D
#define AFE_API_VERSION_I2S_CONFIG 0x1
/* Enumeration for setting the I2S configuration
* channel_mode parameter to
* serial data wire number 1-3 (SD3).
*/
#define AFE_PORT_I2S_SD0 0x1
#define AFE_PORT_I2S_SD1 0x2
#define AFE_PORT_I2S_SD2 0x3
#define AFE_PORT_I2S_SD3 0x4
#define AFE_PORT_I2S_QUAD01 0x5
#define AFE_PORT_I2S_QUAD23 0x6
#define AFE_PORT_I2S_6CHS 0x7
#define AFE_PORT_I2S_8CHS 0x8
#define AFE_PORT_I2S_MONO 0x0
#define AFE_PORT_I2S_STEREO 0x1
#define AFE_PORT_CONFIG_I2S_WS_SRC_EXTERNAL 0x0
#define AFE_PORT_CONFIG_I2S_WS_SRC_INTERNAL 0x1
/* Payload of the #AFE_PARAM_ID_I2S_CONFIG
* command's (I2S configuration
* parameter).
*/
struct afe_param_id_i2s_cfg {
u32 i2s_cfg_minor_version;
/* Minor version used for tracking the version of the I2S
* configuration interface.
* Supported values: #AFE_API_VERSION_I2S_CONFIG
*/
u16 bit_width;
/* Bit width of the sample.
* Supported values: 16, 24
*/
u16 channel_mode;
/* I2S lines and multichannel operation.
* Supported values:
* - #AFE_PORT_I2S_SD0
* - #AFE_PORT_I2S_SD1
* - #AFE_PORT_I2S_SD2
* - #AFE_PORT_I2S_SD3
* - #AFE_PORT_I2S_QUAD01
* - #AFE_PORT_I2S_QUAD23
* - #AFE_PORT_I2S_6CHS
* - #AFE_PORT_I2S_8CHS
*/
u16 mono_stereo;
/* Specifies mono or stereo. This applies only when
* a single I2S line is used.
* Supported values:
* - #AFE_PORT_I2S_MONO
* - #AFE_PORT_I2S_STEREO
*/
u16 ws_src;
/* Word select source: internal or external.
* Supported values:
* - #AFE_PORT_CONFIG_I2S_WS_SRC_EXTERNAL
* - #AFE_PORT_CONFIG_I2S_WS_SRC_INTERNAL
*/
u32 sample_rate;
/* Sampling rate of the port.
* Supported values:
* - #AFE_PORT_SAMPLE_RATE_8K
* - #AFE_PORT_SAMPLE_RATE_16K
* - #AFE_PORT_SAMPLE_RATE_48K
* - #AFE_PORT_SAMPLE_RATE_96K
* - #AFE_PORT_SAMPLE_RATE_192K
*/
u16 data_format;
/* data format
* Supported values:
* - #LINEAR_PCM_DATA
* - #NON_LINEAR_DATA
* - #LINEAR_PCM_DATA_PACKED_IN_60958
* - #NON_LINEAR_DATA_PACKED_IN_60958
*/
u16 reserved;
/* This field must be set to zero. */
} __packed;
/*
* This param id is used to configure PCM interface
*/
#define AFE_PARAM_ID_PCM_CONFIG 0x0001020E
#define AFE_API_VERSION_PCM_CONFIG 0x1
/* Enumeration for the auxiliary PCM synchronization signal
* provided by an external source.
*/
#define AFE_PORT_PCM_SYNC_SRC_EXTERNAL 0x0
/* Enumeration for the auxiliary PCM synchronization signal
* provided by an internal source.
*/
#define AFE_PORT_PCM_SYNC_SRC_INTERNAL 0x1
/* Enumeration for the PCM configuration aux_mode parameter,
* which configures the auxiliary PCM interface to use
* short synchronization.
*/
#define AFE_PORT_PCM_AUX_MODE_PCM 0x0
/*
* Enumeration for the PCM configuration aux_mode parameter,
* which configures the auxiliary PCM interface to use long
* synchronization.
*/
#define AFE_PORT_PCM_AUX_MODE_AUX 0x1
/*
* Enumeration for setting the PCM configuration frame to 8.
*/
#define AFE_PORT_PCM_BITS_PER_FRAME_8 0x0
/*
* Enumeration for setting the PCM configuration frame to 16.
*/
#define AFE_PORT_PCM_BITS_PER_FRAME_16 0x1
/* Enumeration for setting the PCM configuration frame to 32.*/
#define AFE_PORT_PCM_BITS_PER_FRAME_32 0x2
/* Enumeration for setting the PCM configuration frame to 64.*/
#define AFE_PORT_PCM_BITS_PER_FRAME_64 0x3
/* Enumeration for setting the PCM configuration frame to 128.*/
#define AFE_PORT_PCM_BITS_PER_FRAME_128 0x4
/* Enumeration for setting the PCM configuration frame to 256.*/
#define AFE_PORT_PCM_BITS_PER_FRAME_256 0x5
/* Enumeration for setting the PCM configuration
* quantype parameter to A-law with no padding.
*/
#define AFE_PORT_PCM_ALAW_NOPADDING 0x0
/* Enumeration for setting the PCM configuration quantype
* parameter to mu-law with no padding.
*/
#define AFE_PORT_PCM_MULAW_NOPADDING 0x1
/* Enumeration for setting the PCM configuration quantype
* parameter to linear with no padding.
*/
#define AFE_PORT_PCM_LINEAR_NOPADDING 0x2
/* Enumeration for setting the PCM configuration quantype
* parameter to A-law with padding.
*/
#define AFE_PORT_PCM_ALAW_PADDING 0x3
/* Enumeration for setting the PCM configuration quantype
* parameter to mu-law with padding.
*/
#define AFE_PORT_PCM_MULAW_PADDING 0x4
/* Enumeration for setting the PCM configuration quantype
* parameter to linear with padding.
*/
#define AFE_PORT_PCM_LINEAR_PADDING 0x5
/* Enumeration for disabling the PCM configuration
* ctrl_data_out_enable parameter.
* The PCM block is the only master.
*/
#define AFE_PORT_PCM_CTRL_DATA_OE_DISABLE 0x0
/*
* Enumeration for enabling the PCM configuration
* ctrl_data_out_enable parameter. The PCM block shares
* the signal with other masters.
*/
#define AFE_PORT_PCM_CTRL_DATA_OE_ENABLE 0x1
/* Payload of the #AFE_PARAM_ID_PCM_CONFIG command's
* (PCM configuration parameter).
*/
struct afe_param_id_pcm_cfg {
u32 pcm_cfg_minor_version;
/* Minor version used for tracking the version of the AUX PCM
* configuration interface.
* Supported values: #AFE_API_VERSION_PCM_CONFIG
*/
u16 aux_mode;
/* PCM synchronization setting.
* Supported values:
* - #AFE_PORT_PCM_AUX_MODE_PCM
* - #AFE_PORT_PCM_AUX_MODE_AUX
*/
u16 sync_src;
/* Synchronization source.
* Supported values:
* - #AFE_PORT_PCM_SYNC_SRC_EXTERNAL
* - #AFE_PORT_PCM_SYNC_SRC_INTERNAL
*/
u16 frame_setting;
/* Number of bits per frame.
* Supported values:
* - #AFE_PORT_PCM_BITS_PER_FRAME_8
* - #AFE_PORT_PCM_BITS_PER_FRAME_16
* - #AFE_PORT_PCM_BITS_PER_FRAME_32
* - #AFE_PORT_PCM_BITS_PER_FRAME_64
* - #AFE_PORT_PCM_BITS_PER_FRAME_128
* - #AFE_PORT_PCM_BITS_PER_FRAME_256
*/
u16 quantype;
/* PCM quantization type.
* Supported values:
* - #AFE_PORT_PCM_ALAW_NOPADDING
* - #AFE_PORT_PCM_MULAW_NOPADDING
* - #AFE_PORT_PCM_LINEAR_NOPADDING
* - #AFE_PORT_PCM_ALAW_PADDING
* - #AFE_PORT_PCM_MULAW_PADDING
* - #AFE_PORT_PCM_LINEAR_PADDING
*/
u16 ctrl_data_out_enable;
/* Specifies whether the PCM block shares the data-out
* signal to the drive with other masters.
* Supported values:
* - #AFE_PORT_PCM_CTRL_DATA_OE_DISABLE
* - #AFE_PORT_PCM_CTRL_DATA_OE_ENABLE
*/
u16 reserved;
/* This field must be set to zero. */
u32 sample_rate;
/* Sampling rate of the port.
* Supported values:
* - #AFE_PORT_SAMPLE_RATE_8K
* - #AFE_PORT_SAMPLE_RATE_16K
*/
u16 bit_width;
/* Bit width of the sample.
* Supported values: 16
*/
u16 num_channels;
/* Number of channels.
* Supported values: 1 to 4
*/
u16 slot_number_mapping[4];
/* Specifies the slot number for the each channel in
* multi channel scenario.
* Supported values: 1 to 32
*/
} __packed;
/*
* This param id is used to configure DIGI MIC interface
*/
#define AFE_PARAM_ID_DIGI_MIC_CONFIG 0x0001020F
/* This version information is used to handle the new
* additions to the config interface in future in backward
* compatible manner.
*/
#define AFE_API_VERSION_DIGI_MIC_CONFIG 0x1
/* Enumeration for setting the digital mic configuration
* channel_mode parameter to left 0.
*/
#define AFE_PORT_DIGI_MIC_MODE_LEFT0 0x1
/*Enumeration for setting the digital mic configuration
* channel_mode parameter to right 0.
*/
#define AFE_PORT_DIGI_MIC_MODE_RIGHT0 0x2
/* Enumeration for setting the digital mic configuration
* channel_mode parameter to left 1.
*/
#define AFE_PORT_DIGI_MIC_MODE_LEFT1 0x3
/* Enumeration for setting the digital mic configuration
* channel_mode parameter to right 1.
*/
#define AFE_PORT_DIGI_MIC_MODE_RIGHT1 0x4
/* Enumeration for setting the digital mic configuration
* channel_mode parameter to stereo 0.
*/
#define AFE_PORT_DIGI_MIC_MODE_STEREO0 0x5
/* Enumeration for setting the digital mic configuration
* channel_mode parameter to stereo 1.
*/
#define AFE_PORT_DIGI_MIC_MODE_STEREO1 0x6
/* Enumeration for setting the digital mic configuration
* channel_mode parameter to quad.
*/
#define AFE_PORT_DIGI_MIC_MODE_QUAD 0x7
/* Payload of the #AFE_PARAM_ID_DIGI_MIC_CONFIG command's
* (DIGI MIC configuration
* parameter).
*/
struct afe_param_id_digi_mic_cfg {
u32 digi_mic_cfg_minor_version;
/* Minor version used for tracking the version of the DIGI Mic
* configuration interface.
* Supported values: #AFE_API_VERSION_DIGI_MIC_CONFIG
*/
u16 bit_width;
/* Bit width of the sample.
* Supported values: 16
*/
u16 channel_mode;
/* Digital mic and multichannel operation.
* Supported values:
* - #AFE_PORT_DIGI_MIC_MODE_LEFT0
* - #AFE_PORT_DIGI_MIC_MODE_RIGHT0
* - #AFE_PORT_DIGI_MIC_MODE_LEFT1
* - #AFE_PORT_DIGI_MIC_MODE_RIGHT1
* - #AFE_PORT_DIGI_MIC_MODE_STEREO0
* - #AFE_PORT_DIGI_MIC_MODE_STEREO1
* - #AFE_PORT_DIGI_MIC_MODE_QUAD
*/
u32 sample_rate;
/* Sampling rate of the port.
* Supported values:
* - #AFE_PORT_SAMPLE_RATE_8K
* - #AFE_PORT_SAMPLE_RATE_16K
* - #AFE_PORT_SAMPLE_RATE_48K
*/
} __packed;
/*
* This param id is used to configure HDMI interface
*/
#define AFE_PARAM_ID_HDMI_CONFIG 0x00010210
/* This version information is used to handle the new
* additions to the config interface in future in backward
* compatible manner.
*/
#define AFE_API_VERSION_HDMI_CONFIG 0x1
/* Payload of the #AFE_PARAM_ID_HDMI_CONFIG command,
* which configures a multichannel HDMI audio interface.
*/
struct afe_param_id_hdmi_multi_chan_audio_cfg {
u32 hdmi_cfg_minor_version;
/* Minor version used for tracking the version of the HDMI
* configuration interface.
* Supported values: #AFE_API_VERSION_HDMI_CONFIG
*/
u16 datatype;
/* data type
* Supported values:
* - #LINEAR_PCM_DATA
* - #NON_LINEAR_DATA
* - #LINEAR_PCM_DATA_PACKED_IN_60958
* - #NON_LINEAR_DATA_PACKED_IN_60958
*/
u16 channel_allocation;
/* HDMI channel allocation information for programming an HDMI
* frame. The default is 0 (Stereo).
*
* This information is defined in the HDMI standard, CEA 861-D
* (refer to @xhyperref{S1,[S1]}). The number of channels is also
* inferred from this parameter.
*/
u32 sample_rate;
/* Sampling rate of the port.
* Supported values:
* - #AFE_PORT_SAMPLE_RATE_8K
* - #AFE_PORT_SAMPLE_RATE_16K
* - #AFE_PORT_SAMPLE_RATE_48K
* - #AFE_PORT_SAMPLE_RATE_96K
* - 22050, 44100, 176400 for compressed streams
*/
u16 bit_width;
/* Bit width of the sample.
* Supported values: 16, 24
*/
u16 reserved;
/* This field must be set to zero. */
} __packed;
/*
* This param id is used to configure BT or FM(RIVA) interface
*/
#define AFE_PARAM_ID_INTERNAL_BT_FM_CONFIG 0x00010211
/* This version information is used to handle the new
* additions to the config interface in future in backward
* compatible manner.
*/
#define AFE_API_VERSION_INTERNAL_BT_FM_CONFIG 0x1
/* Payload of the #AFE_PARAM_ID_INTERNAL_BT_FM_CONFIG
* command's BT voice/BT audio/FM configuration parameter.
*/
struct afe_param_id_internal_bt_fm_cfg {
u32 bt_fm_cfg_minor_version;
/* Minor version used for tracking the version of the BT and FM
* configuration interface.
* Supported values: #AFE_API_VERSION_INTERNAL_BT_FM_CONFIG
*/
u16 num_channels;
/* Number of channels.
* Supported values: 1 to 2
*/
u16 bit_width;
/* Bit width of the sample.
* Supported values: 16
*/
u32 sample_rate;
/* Sampling rate of the port.
* Supported values:
* - #AFE_PORT_SAMPLE_RATE_8K (only for BTSCO)
* - #AFE_PORT_SAMPLE_RATE_16K (only for BTSCO)
* - #AFE_PORT_SAMPLE_RATE_48K (FM and A2DP)
*/
} __packed;
/* This param id is used to configure SLIMBUS interface using
* shared channel approach.
*/
#define AFE_PARAM_ID_SLIMBUS_CONFIG 0x00010212
/* This version information is used to handle the new
* additions to the config interface in future in backward
* compatible manner.
*/
#define AFE_API_VERSION_SLIMBUS_CONFIG 0x1
/* Enumeration for setting SLIMbus device ID 1.
*/
#define AFE_SLIMBUS_DEVICE_1 0x0
/* Enumeration for setting SLIMbus device ID 2.
*/
#define AFE_SLIMBUS_DEVICE_2 0x1
/* Enumeration for setting the SLIMbus data formats.
*/
#define AFE_SB_DATA_FORMAT_NOT_INDICATED 0x0
/* Enumeration for setting the maximum number of streams per
* device.
*/
#define AFE_PORT_MAX_AUDIO_CHAN_CNT 0x8
/* Payload of the #AFE_PORT_CMD_SLIMBUS_CONFIG command's SLIMbus
* port configuration parameter.
*/
struct afe_param_id_slimbus_cfg {
u32 sb_cfg_minor_version;
/* Minor version used for tracking the version of the SLIMBUS
* configuration interface.
* Supported values: #AFE_API_VERSION_SLIMBUS_CONFIG
*/
u16 slimbus_dev_id;
/* SLIMbus hardware device ID, which is required to handle
* multiple SLIMbus hardware blocks.
* Supported values: - #AFE_SLIMBUS_DEVICE_1 - #AFE_SLIMBUS_DEVICE_2
*/
u16 bit_width;
/* Bit width of the sample.
* Supported values: 16, 24
*/
u16 data_format;
/* Data format supported by the SLIMbus hardware. The default is
* 0 (#AFE_SB_DATA_FORMAT_NOT_INDICATED), which indicates the
* hardware does not perform any format conversions before the data
* transfer.
*/
u16 num_channels;
/* Number of channels.
* Supported values: 1 to #AFE_PORT_MAX_AUDIO_CHAN_CNT
*/
u8 shared_ch_mapping[AFE_PORT_MAX_AUDIO_CHAN_CNT];
/* Mapping of shared channel IDs (128 to 255) to which the
* master port is to be connected.
* Shared_channel_mapping[i] represents the shared channel assigned
* for audio channel i in multichannel audio data.
*/
u32 sample_rate;
/* Sampling rate of the port.
* Supported values:
* - #AFE_PORT_SAMPLE_RATE_8K
* - #AFE_PORT_SAMPLE_RATE_16K
* - #AFE_PORT_SAMPLE_RATE_48K
* - #AFE_PORT_SAMPLE_RATE_96K
* - #AFE_PORT_SAMPLE_RATE_192K
*/
} __packed;
/*
* This param id is used to configure Real Time Proxy interface.
*/
#define AFE_PARAM_ID_RT_PROXY_CONFIG 0x00010213
/* This version information is used to handle the new
* additions to the config interface in future in backward
* compatible manner.
*/
#define AFE_API_VERSION_RT_PROXY_CONFIG 0x1
/* Payload of the #AFE_PARAM_ID_RT_PROXY_CONFIG
* command (real-time proxy port configuration parameter).
*/
struct afe_param_id_rt_proxy_port_cfg {
u32 rt_proxy_cfg_minor_version;
/* Minor version used for tracking the version of rt-proxy
* config interface.
*/
u16 bit_width;
/* Bit width of the sample.
* Supported values: 16
*/
u16 interleaved;
/* Specifies whether the data exchanged between the AFE
* interface and real-time port is interleaved.
* Supported values: - 0 -- Non-interleaved (samples from each
* channel are contiguous in the buffer) - 1 -- Interleaved
* (corresponding samples from each input channel are interleaved
* within the buffer)
*/
u16 frame_size;
/* Size of the frames that are used for PCM exchanges with this
* port.
* Supported values: > 0, in bytes
* For example, 5 ms buffers of 16 bits and 16 kHz stereo samples
* is 5 ms * 16 samples/ms * 2 bytes/sample * 2 channels = 320
* bytes.
*/
u16 jitter_allowance;
/* Configures the amount of jitter that the port will allow.
* Supported values: > 0
* For example, if +/-10 ms of jitter is anticipated in the timing
* of sending frames to the port, and the configuration is 16 kHz
* mono with 16-bit samples, this field is 10 ms * 16 samples/ms * 2
* bytes/sample = 320.
*/
u16 low_water_mark;
/* Low watermark in bytes (including all channels).
* Supported values:
* - 0 -- Do not send any low watermark events
* - > 0 -- Low watermark for triggering an event
* If the number of bytes in an internal circular buffer is lower
* than this low_water_mark parameter, a LOW_WATER_MARK event is
* sent to applications (via the #AFE_EVENT_RT_PROXY_PORT_STATUS
* event).
* Use of watermark events is optional for debugging purposes.
*/
u16 high_water_mark;
/* High watermark in bytes (including all channels).
* Supported values:
* - 0 -- Do not send any high watermark events
* - > 0 -- High watermark for triggering an event
* If the number of bytes in an internal circular buffer exceeds
* TOTAL_CIRC_BUF_SIZE minus high_water_mark, a high watermark event
* is sent to applications (via the #AFE_EVENT_RT_PROXY_PORT_STATUS
* event).
* The use of watermark events is optional and for debugging
* purposes.
*/
u32 sample_rate;
/* Sampling rate of the port.
* Supported values:
* - #AFE_PORT_SAMPLE_RATE_8K
* - #AFE_PORT_SAMPLE_RATE_16K
* - #AFE_PORT_SAMPLE_RATE_48K
*/
u16 num_channels;
/* Number of channels.
* Supported values: 1 to #AFE_PORT_MAX_AUDIO_CHAN_CNT
*/
u16 reserved;
/* For 32 bit alignment. */
} __packed;
/* This param id is used to configure the Pseudoport interface */
#define AFE_PARAM_ID_PSEUDO_PORT_CONFIG 0x00010219
/* Version information used to handle future additions to the configuration
* interface (for backward compatibility).
*/
#define AFE_API_VERSION_PSEUDO_PORT_CONFIG 0x1
/* Enumeration for setting the timing_mode parameter to faster than real
* time.
*/
#define AFE_PSEUDOPORT_TIMING_MODE_FTRT 0x0
/* Enumeration for setting the timing_mode parameter to real time using
* timers.
*/
#define AFE_PSEUDOPORT_TIMING_MODE_TIMER 0x1
/* Payload of the AFE_PARAM_ID_PSEUDO_PORT_CONFIG parameter used by
AFE_MODULE_AUDIO_DEV_INTERFACE.
*/
struct afe_param_id_pseudo_port_cfg {
u32 pseud_port_cfg_minor_version;
/*
* Minor version used for tracking the version of the pseudoport
* configuration interface.
*/
u16 bit_width;
/* Bit width of the sample at values 16, 24 */
u16 num_channels;
/* Number of channels at values 1 to 8 */
u16 data_format;
/* Non-linear data format supported by the pseudoport (for future use).
* At values #AFE_LINEAR_PCM_DATA
*/
u16 timing_mode;
/* Indicates whether the pseudoport synchronizes to the clock or
* operates faster than real time.
* at values
* - #AFE_PSEUDOPORT_TIMING_MODE_FTRT
* - #AFE_PSEUDOPORT_TIMING_MODE_TIMER @tablebulletend
*/
u32 sample_rate;
/* Sample rate at which the pseudoport will run.
* at values
* - #AFE_PORT_SAMPLE_RATE_8K
* - #AFE_PORT_SAMPLE_RATE_32K
* - #AFE_PORT_SAMPLE_RATE_48K
* - #AFE_PORT_SAMPLE_RATE_96K
* - #AFE_PORT_SAMPLE_RATE_192K @tablebulletend
*/
} __packed;
#define AFE_PARAM_ID_DEVICE_HW_DELAY 0x00010243
#define AFE_API_VERSION_DEVICE_HW_DELAY 0x1
struct afe_param_id_device_hw_delay_cfg {
uint32_t device_hw_delay_minor_version;
uint32_t delay_in_us;
} __packed;
union afe_port_config {
struct afe_param_id_pcm_cfg pcm;
struct afe_param_id_i2s_cfg i2s;
struct afe_param_id_hdmi_multi_chan_audio_cfg hdmi_multi_ch;
struct afe_param_id_slimbus_cfg slim_sch;
struct afe_param_id_rt_proxy_port_cfg rtproxy;
struct afe_param_id_internal_bt_fm_cfg int_bt_fm;
struct afe_param_id_pseudo_port_cfg pseudo_port;
struct afe_param_id_device_hw_delay_cfg hw_delay;
} __packed;
struct afe_audioif_config_command_no_payload {
struct apr_hdr hdr;
struct afe_port_cmd_set_param_v2 param;
} __packed;
struct afe_audioif_config_command {
struct apr_hdr hdr;
struct afe_port_cmd_set_param_v2 param;
struct afe_port_param_data_v2 pdata;
union afe_port_config port;
} __packed;
#define AFE_PORT_CMD_DEVICE_START 0x000100E5
/* Payload of the #AFE_PORT_CMD_DEVICE_START.*/
struct afe_port_cmd_device_start {
struct apr_hdr hdr;
u16 port_id;
/* Port interface and direction (Rx or Tx) to start. An even
* number represents the Rx direction, and an odd number represents
* the Tx direction.
*/
u16 reserved;
/* Reserved for 32-bit alignment. This field must be set to 0.*/
} __packed;
#define AFE_PORT_CMD_DEVICE_STOP 0x000100E6
/* Payload of the #AFE_PORT_CMD_DEVICE_STOP.
*/
struct afe_port_cmd_device_stop {
struct apr_hdr hdr;
u16 port_id;
/* Port interface and direction (Rx or Tx) to start. An even
* number represents the Rx direction, and an odd number represents
* the Tx direction.
*/
u16 reserved;
/* Reserved for 32-bit alignment. This field must be set to 0.*/
} __packed;
#define AFE_SERVICE_CMD_SHARED_MEM_MAP_REGIONS 0x000100EA
/* Memory map regions command payload used by the
* #AFE_SERVICE_CMD_SHARED_MEM_MAP_REGIONS .
* This structure allows clients to map multiple shared memory
* regions in a single command. Following this structure are
* num_regions of afe_service_shared_map_region_payload.
*/
struct afe_service_cmd_shared_mem_map_regions {
struct apr_hdr hdr;
u16 mem_pool_id;
/* Type of memory on which this memory region is mapped.
* Supported values:
* - #ADSP_MEMORY_MAP_EBI_POOL
* - #ADSP_MEMORY_MAP_SMI_POOL
* - #ADSP_MEMORY_MAP_SHMEM8_4K_POOL
* - Other values are reserved
*
* The memory pool ID implicitly defines the characteristics of the
* memory. Characteristics may include alignment type, permissions,
* etc.
*
* ADSP_MEMORY_MAP_EBI_POOL is External Buffer Interface type memory
* ADSP_MEMORY_MAP_SMI_POOL is Shared Memory Interface type memory
* ADSP_MEMORY_MAP_SHMEM8_4K_POOL is shared memory, byte
* addressable, and 4 KB aligned.
*/
u16 num_regions;
/* Number of regions to map.
* Supported values:
* - Any value greater than zero
*/
u32 property_flag;
/* Configures one common property for all the regions in the
* payload.
*
* Supported values: - 0x00000000 to 0x00000001
*
* b0 - bit 0 indicates physical or virtual mapping 0 Shared memory
* address provided in afe_service_shared_map_region_payloadis a
* physical address. The shared memory needs to be mapped( hardware
* TLB entry) and a software entry needs to be added for internal
* book keeping.
*
* 1 Shared memory address provided in
* afe_service_shared_map_region_payloadis a virtual address. The
* shared memory must not be mapped (since hardware TLB entry is
* already available) but a software entry needs to be added for
* internal book keeping. This can be useful if two services with in
* ADSP is communicating via APR. They can now directly communicate
* via the Virtual address instead of Physical address. The virtual
* regions must be contiguous. num_regions must be 1 in this case.
*
* b31-b1 - reserved bits. must be set to zero
*/
} __packed;
/* Map region payload used by the
* afe_service_shared_map_region_payloadstructure.
*/
struct afe_service_shared_map_region_payload {
u32 shm_addr_lsw;
/* least significant word of starting address in the memory
* region to map. It must be contiguous memory, and it must be 4 KB
* aligned.
* Supported values: - Any 32 bit value
*/
u32 shm_addr_msw;
/* most significant word of startng address in the memory region
* to map. For 32 bit shared memory address, this field must be set
* to zero. For 36 bit shared memory address, bit31 to bit 4 must be
* set to zero
*
* Supported values: - For 32 bit shared memory address, this field
* must be set to zero. - For 36 bit shared memory address, bit31 to
* bit 4 must be set to zero - For 64 bit shared memory address, any
* 32 bit value
*/
u32 mem_size_bytes;
/* Number of bytes in the region. The aDSP will always map the
* regions as virtual contiguous memory, but the memory size must be
* in multiples of 4 KB to avoid gaps in the virtually contiguous
* mapped memory.
*
* Supported values: - multiples of 4KB
*/
} __packed;
#define AFE_SERVICE_CMDRSP_SHARED_MEM_MAP_REGIONS 0x000100EB
struct afe_service_cmdrsp_shared_mem_map_regions {
u32 mem_map_handle;
/* A memory map handle encapsulating shared memory attributes is
* returned iff AFE_SERVICE_CMD_SHARED_MEM_MAP_REGIONS command is
* successful. In the case of failure , a generic APR error response
* is returned to the client.
*
* Supported Values: - Any 32 bit value
*/
} __packed;
#define AFE_SERVICE_CMD_SHARED_MEM_UNMAP_REGIONS 0x000100EC
/* Memory unmap regions command payload used by the
* #AFE_SERVICE_CMD_SHARED_MEM_UNMAP_REGIONS
*
* This structure allows clients to unmap multiple shared memory
* regions in a single command.
*/
struct afe_service_cmd_shared_mem_unmap_regions {
struct apr_hdr hdr;
u32 mem_map_handle;
/* memory map handle returned by
* AFE_SERVICE_CMD_SHARED_MEM_MAP_REGIONS commands
*
* Supported Values:
* - Any 32 bit value
*/
} __packed;
#define AFE_PORT_CMD_GET_PARAM_V2 0x000100F0
/* Payload of the #AFE_PORT_CMD_GET_PARAM_V2 command,
* which queries for one post/preprocessing parameter of a
* stream.
*/
struct afe_port_cmd_get_param_v2 {
struct apr_hdr hdr;
u16 port_id;
/* Port interface and direction (Rx or Tx) to start. */
u16 payload_size;
/* Maximum data size of the parameter ID/module ID combination.
* This is a multiple of four bytes
* Supported values: > 0
*/
u32 payload_address_lsw;
/* LSW of 64 bit Payload address. Address should be 32-byte,
* 4kbyte aligned and must be contig memory.
*/
u32 payload_address_msw;
/* MSW of 64 bit Payload address. In case of 32-bit shared
* memory address, this field must be set to zero. In case of 36-bit
* shared memory address, bit-4 to bit-31 must be set to zero.
* Address should be 32-byte, 4kbyte aligned and must be contiguous
* memory.
*/
u32 mem_map_handle;
/* Memory map handle returned by
* AFE_SERVICE_CMD_SHARED_MEM_MAP_REGIONS commands.
* Supported Values: - NULL -- Message. The parameter data is
* in-band. - Non-NULL -- The parameter data is Out-band.Pointer to
* - the physical address in shared memory of the payload data.
* For detailed payload content, see the afe_port_param_data_v2
* structure
*/
u32 module_id;
/* ID of the module to be queried.
* Supported values: Valid module ID
*/
u32 param_id;
/* ID of the parameter to be queried.
* Supported values: Valid parameter ID
*/
} __packed;
#define AFE_PORT_CMDRSP_GET_PARAM_V2 0x00010106
/* Payload of the #AFE_PORT_CMDRSP_GET_PARAM_V2 message, which
* responds to an #AFE_PORT_CMD_GET_PARAM_V2 command.
*
* Immediately following this structure is the parameters structure
* (afe_port_param_data) containing the response(acknowledgment)
* parameter payload. This payload is included for an in-band
* scenario. For an address/shared memory-based set parameter, this
* payload is not needed.
*/
struct afe_port_cmdrsp_get_param_v2 {
u32 status;
} __packed;
/* adsp_afe_service_commands.h */
#define ADSP_MEMORY_MAP_EBI_POOL 0
#define ADSP_MEMORY_MAP_SMI_POOL 1
#define ADSP_MEMORY_MAP_IMEM_POOL 2
#define ADSP_MEMORY_MAP_SHMEM8_4K_POOL 3
/*
* Definition of virtual memory flag
*/
#define ADSP_MEMORY_MAP_VIRTUAL_MEMORY 1
/*
* Definition of physical memory flag
*/
#define ADSP_MEMORY_MAP_PHYSICAL_MEMORY 0
#define NULL_COPP_TOPOLOGY 0x00010312
#define DEFAULT_COPP_TOPOLOGY 0x00010be3
#define DEFAULT_POPP_TOPOLOGY 0x00010be4
#define VPM_TX_SM_ECNS_COPP_TOPOLOGY 0x00010F71
#define VPM_TX_DM_FLUENCE_COPP_TOPOLOGY 0x00010F72
#define VPM_TX_QMIC_FLUENCE_COPP_TOPOLOGY 0x00010F75
#define VPM_TX_DM_RFECNS_COPP_TOPOLOGY 0x00010F86
/* Memory map regions command payload used by the
* #ASM_CMD_SHARED_MEM_MAP_REGIONS ,#ADM_CMD_SHARED_MEM_MAP_REGIONS
* commands.
*
* This structure allows clients to map multiple shared memory
* regions in a single command. Following this structure are
* num_regions of avs_shared_map_region_payload.
*/
struct avs_cmd_shared_mem_map_regions {
struct apr_hdr hdr;
u16 mem_pool_id;
/* Type of memory on which this memory region is mapped.
*
* Supported values: - #ADSP_MEMORY_MAP_EBI_POOL -
* #ADSP_MEMORY_MAP_SMI_POOL - #ADSP_MEMORY_MAP_IMEM_POOL
* (unsupported) - #ADSP_MEMORY_MAP_SHMEM8_4K_POOL - Other values
* are reserved
*
* The memory ID implicitly defines the characteristics of the
* memory. Characteristics may include alignment type, permissions,
* etc.
*
* SHMEM8_4K is shared memory, byte addressable, and 4 KB aligned.
*/
u16 num_regions;
/* Number of regions to map.*/
u32 property_flag;
/* Configures one common property for all the regions in the
* payload. No two regions in the same memory map regions cmd can
* have differnt property. Supported values: - 0x00000000 to
* 0x00000001
*
* b0 - bit 0 indicates physical or virtual mapping 0 shared memory
* address provided in avs_shared_map_regions_payload is physical
* address. The shared memory needs to be mapped( hardware TLB
* entry)
*
* and a software entry needs to be added for internal book keeping.
*
* 1 Shared memory address provided in MayPayload[usRegions] is
* virtual address. The shared memory must not be mapped (since
* hardware TLB entry is already available) but a software entry
* needs to be added for internal book keeping. This can be useful
* if two services with in ADSP is communicating via APR. They can
* now directly communicate via the Virtual address instead of
* Physical address. The virtual regions must be contiguous.
*
* b31-b1 - reserved bits. must be set to zero
*/
} __packed;
struct avs_shared_map_region_payload {
u32 shm_addr_lsw;
/* least significant word of shared memory address of the memory
* region to map. It must be contiguous memory, and it must be 4 KB
* aligned.
*/
u32 shm_addr_msw;
/* most significant word of shared memory address of the memory
* region to map. For 32 bit shared memory address, this field must
* tbe set to zero. For 36 bit shared memory address, bit31 to bit 4
* must be set to zero
*/
u32 mem_size_bytes;
/* Number of bytes in the region.
*
* The aDSP will always map the regions as virtual contiguous
* memory, but the memory size must be in multiples of 4 KB to avoid
* gaps in the virtually contiguous mapped memory.
*/
} __packed;
struct avs_cmd_shared_mem_unmap_regions {
struct apr_hdr hdr;
u32 mem_map_handle;
/* memory map handle returned by ASM_CMD_SHARED_MEM_MAP_REGIONS
* , ADM_CMD_SHARED_MEM_MAP_REGIONS, commands
*/
} __packed;
/* Memory map command response payload used by the
* #ASM_CMDRSP_SHARED_MEM_MAP_REGIONS
* ,#ADM_CMDRSP_SHARED_MEM_MAP_REGIONS
*/
struct avs_cmdrsp_shared_mem_map_regions {
u32 mem_map_handle;
/* A memory map handle encapsulating shared memory attributes is
* returned
*/
} __packed;
/*adsp_audio_memmap_api.h*/
/* ASM related data structures */
struct asm_wma_cfg {
u16 format_tag;
u16 ch_cfg;
u32 sample_rate;
u32 avg_bytes_per_sec;
u16 block_align;
u16 valid_bits_per_sample;
u32 ch_mask;
u16 encode_opt;
u16 adv_encode_opt;
u32 adv_encode_opt2;
u32 drc_peak_ref;
u32 drc_peak_target;
u32 drc_ave_ref;
u32 drc_ave_target;
} __packed;
struct asm_wmapro_cfg {
u16 format_tag;
u16 ch_cfg;
u32 sample_rate;
u32 avg_bytes_per_sec;
u16 block_align;
u16 valid_bits_per_sample;
u32 ch_mask;
u16 encode_opt;
u16 adv_encode_opt;
u32 adv_encode_opt2;
u32 drc_peak_ref;
u32 drc_peak_target;
u32 drc_ave_ref;
u32 drc_ave_target;
} __packed;
struct asm_aac_cfg {
u16 format;
u16 aot;
u16 ep_config;
u16 section_data_resilience;
u16 scalefactor_data_resilience;
u16 spectral_data_resilience;
u16 ch_cfg;
u16 reserved;
u32 sample_rate;
} __packed;
struct asm_amrwbplus_cfg {
u32 size_bytes;
u32 version;
u32 num_channels;
u32 amr_band_mode;
u32 amr_dtx_mode;
u32 amr_frame_fmt;
u32 amr_lsf_idx;
} __packed;
struct asm_softpause_params {
u32 enable;
u32 period;
u32 step;
u32 rampingcurve;
} __packed;
struct asm_softvolume_params {
u32 period;
u32 step;
u32 rampingcurve;
} __packed;
#define ASM_END_POINT_DEVICE_MATRIX 0
#define PCM_CHANNEL_NULL 0
/* Front left channel. */
#define PCM_CHANNEL_FL 1
/* Front right channel. */
#define PCM_CHANNEL_FR 2
/* Front center channel. */
#define PCM_CHANNEL_FC 3
/* Left surround channel.*/
#define PCM_CHANNEL_LS 4
/* Right surround channel.*/
#define PCM_CHANNEL_RS 5
/* Low frequency effect channel. */
#define PCM_CHANNEL_LFE 6
/* Center surround channel; Rear center channel. */
#define PCM_CHANNEL_CS 7
/* Left back channel; Rear left channel. */
#define PCM_CHANNEL_LB 8
/* Right back channel; Rear right channel. */
#define PCM_CHANNEL_RB 9
/* Top surround channel. */
#define PCM_CHANNELS 10
/* Center vertical height channel.*/
#define PCM_CHANNEL_CVH 11
/* Mono surround channel.*/
#define PCM_CHANNEL_MS 12
/* Front left of center. */
#define PCM_CHANNEL_FLC 13
/* Front right of center. */
#define PCM_CHANNEL_FRC 14
/* Rear left of center. */
#define PCM_CHANNEL_RLC 15
/* Rear right of center. */
#define PCM_CHANNEL_RRC 16
#define PCM_FORMAT_MAX_NUM_CHANNEL 8
#define ASM_MEDIA_FMT_MULTI_CHANNEL_PCM_V2 0x00010DA5
#define ASM_STREAM_POSTPROC_TOPO_ID_DEFAULT 0x00010BE4
#define ASM_STREAM_POSTPROC_TOPO_ID_NONE 0x00010C68
#define ASM_MEDIA_FMT_EVRCB_FS 0x00010BEF
#define ASM_MEDIA_FMT_EVRCWB_FS 0x00010BF0
#define ASM_MAX_EQ_BANDS 12
#define ASM_DATA_CMD_MEDIA_FMT_UPDATE_V2 0x00010D98
struct asm_data_cmd_media_fmt_update_v2 {
u32 fmt_blk_size;
/* Media format block size in bytes.*/
} __packed;
struct asm_multi_channel_pcm_fmt_blk_v2 {
struct apr_hdr hdr;
struct asm_data_cmd_media_fmt_update_v2 fmt_blk;
u16 num_channels;
/* Number of channels. Supported values: 1 to 8 */
u16 bits_per_sample;
/* Number of bits per sample per channel. * Supported values:
* 16, 24 * When used for playback, the client must send 24-bit
* samples packed in 32-bit words. The 24-bit samples must be placed
* in the most significant 24 bits of the 32-bit word. When used for
* recording, the aDSP sends 24-bit samples packed in 32-bit words.
* The 24-bit samples are placed in the most significant 24 bits of
* the 32-bit word.
*/
u32 sample_rate;
/* Number of samples per second (in Hertz).
* Supported values: 2000 to 48000
*/
u16 is_signed;
/* Flag that indicates the samples are signed (1). */
u16 reserved;
/* reserved field for 32 bit alignment. must be set to zero. */
u8 channel_mapping[8];
/* Channel array of size 8.
* Supported values:
* - #PCM_CHANNEL_L
* - #PCM_CHANNEL_R
* - #PCM_CHANNEL_C
* - #PCM_CHANNEL_LS
* - #PCM_CHANNEL_RS
* - #PCM_CHANNEL_LFE
* - #PCM_CHANNEL_CS
* - #PCM_CHANNEL_LB
* - #PCM_CHANNEL_RB
* - #PCM_CHANNELS
* - #PCM_CHANNEL_CVH
* - #PCM_CHANNEL_MS
* - #PCM_CHANNEL_FLC
* - #PCM_CHANNEL_FRC
* - #PCM_CHANNEL_RLC
* - #PCM_CHANNEL_RRC
*
* Channel[i] mapping describes channel I. Each element i of the
* array describes channel I inside the buffer where 0 @le I <
* num_channels. An unused channel is set to zero.
*/
} __packed;
struct asm_stream_cmd_set_encdec_param {
u32 param_id;
/* ID of the parameter. */
u32 param_size;
/* Data size of this parameter, in bytes. The size is a multiple
* of 4 bytes.
*/
} __packed;
struct asm_enc_cfg_blk_param_v2 {
u32 frames_per_buf;
/* Number of encoded frames to pack into each buffer.
*
* @note1hang This is only guidance information for the aDSP. The
* number of encoded frames put into each buffer (specified by the
* client) is less than or equal to this number.
*/
u32 enc_cfg_blk_size;
/* Size in bytes of the encoder configuration block that follows
* this member.
*/
} __packed;
/* @brief Dolby Digital Plus end point configuration structure
*/
struct asm_dec_ddp_endp_param_v2 {
struct apr_hdr hdr;
struct asm_stream_cmd_set_encdec_param encdec;
int endp_param_value;
} __packed;
/* @brief Multichannel PCM encoder configuration structure used
* in the #ASM_STREAM_CMD_OPEN_READ_V2 command.
*/
struct asm_multi_channel_pcm_enc_cfg_v2 {
struct apr_hdr hdr;
struct asm_stream_cmd_set_encdec_param encdec;
struct asm_enc_cfg_blk_param_v2 encblk;
uint16_t num_channels;
/*< Number of PCM channels.
*
* Supported values: - 0 -- Native mode - 1 -- 8 Native mode
* indicates that encoding must be performed with the number of
* channels at the input.
*/
uint16_t bits_per_sample;
/*< Number of bits per sample per channel.
* Supported values: 16, 24
*/
uint32_t sample_rate;
/*< Number of samples per second (in Hertz).
*
* Supported values: 0, 8000 to 48000 A value of 0 indicates the
* native sampling rate. Encoding is performed at the input sampling
* rate.
*/
uint16_t is_signed;
/*< Specifies whether the samples are signed (1). Currently,
* only signed samples are supported.
*/
uint16_t reserved;
/*< reserved field for 32 bit alignment. must be set to zero.*/
uint8_t channel_mapping[8];
} __packed;
#define ASM_MEDIA_FMT_MP3 0x00010BE9
#define ASM_MEDIA_FMT_AAC_V2 0x00010DA6
/* @xreflabel
* {hdr:AsmMediaFmtDolbyAac} Media format ID for the
* Dolby AAC decoder. This format ID is be used if the client wants
* to use the Dolby AAC decoder to decode MPEG2 and MPEG4 AAC
* contents.
*/
#define ASM_MEDIA_FMT_DOLBY_AAC 0x00010D86
/* Enumeration for the audio data transport stream AAC format. */
#define ASM_MEDIA_FMT_AAC_FORMAT_FLAG_ADTS 0
/* Enumeration for low overhead audio stream AAC format. */
#define ASM_MEDIA_FMT_AAC_FORMAT_FLAG_LOAS 1
/* Enumeration for the audio data interchange format
* AAC format.
*/
#define ASM_MEDIA_FMT_AAC_FORMAT_FLAG_ADIF 2
/* Enumeration for the raw AAC format. */
#define ASM_MEDIA_FMT_AAC_FORMAT_FLAG_RAW 3
#define ASM_MEDIA_FMT_AAC_AOT_LC 2
#define ASM_MEDIA_FMT_AAC_AOT_SBR 5
#define ASM_MEDIA_FMT_AAC_AOT_PS 29
#define ASM_MEDIA_FMT_AAC_AOT_BSAC 22
struct asm_aac_fmt_blk_v2 {
struct apr_hdr hdr;
struct asm_data_cmd_media_fmt_update_v2 fmt_blk;
u16 aac_fmt_flag;
/* Bitstream format option.
* Supported values:
* - #ASM_MEDIA_FMT_AAC_FORMAT_FLAG_ADTS
* - #ASM_MEDIA_FMT_AAC_FORMAT_FLAG_LOAS
* - #ASM_MEDIA_FMT_AAC_FORMAT_FLAG_ADIF
* - #ASM_MEDIA_FMT_AAC_FORMAT_FLAG_RAW
*/
u16 audio_objype;
/* Audio Object Type (AOT) present in the AAC stream.
* Supported values:
* - #ASM_MEDIA_FMT_AAC_AOT_LC
* - #ASM_MEDIA_FMT_AAC_AOT_SBR
* - #ASM_MEDIA_FMT_AAC_AOT_BSAC
* - #ASM_MEDIA_FMT_AAC_AOT_PS
* - Otherwise -- Not supported
*/
u16 channel_config;
/* Number of channels present in the AAC stream.
* Supported values:
* - 1 -- Mono
* - 2 -- Stereo
* - 6 -- 5.1 content
*/
u16 total_size_of_PCE_bits;
/* greater or equal to zero. * -In case of RAW formats and
* channel config = 0 (PCE), client can send * the bit stream
* containing PCE immediately following this structure * (in-band).
* -This number does not include bits included for 32 bit alignment.
* -If zero, then the PCE info is assumed to be available in the
* audio -bit stream & not in-band.
*/
u32 sample_rate;
/* Number of samples per second (in Hertz).
*
* Supported values: 8000, 11025, 12000, 16000, 22050, 24000, 32000,
* 44100, 48000
*
* This field must be equal to the sample rate of the AAC-LC
* decoder's output. - For MP4 or 3GP containers, this is indicated
* by the samplingFrequencyIndex field in the AudioSpecificConfig
* element. - For ADTS format, this is indicated by the
* samplingFrequencyIndex in the ADTS fixed header. - For ADIF
* format, this is indicated by the samplingFrequencyIndex in the
* program_config_element present in the ADIF header.
*/
} __packed;
struct asm_aac_enc_cfg_v2 {
struct apr_hdr hdr;
struct asm_stream_cmd_set_encdec_param encdec;
struct asm_enc_cfg_blk_param_v2 encblk;
u32 bit_rate;
/* Encoding rate in bits per second. */
u32 enc_mode;
/* Encoding mode.
* Supported values:
* - #ASM_MEDIA_FMT_AAC_AOT_LC
* - #ASM_MEDIA_FMT_AAC_AOT_SBR
* - #ASM_MEDIA_FMT_AAC_AOT_PS
*/
u16 aac_fmt_flag;
/* AAC format flag.
* Supported values:
* - #ASM_MEDIA_FMT_AAC_FORMAT_FLAG_ADTS
* - #ASM_MEDIA_FMT_AAC_FORMAT_FLAG_RAW
*/
u16 channel_cfg;
/* Number of channels to encode.
* Supported values:
* - 0 -- Native mode
* - 1 -- Mono
* - 2 -- Stereo
* - Other values are not supported.
* @note1hang The eAAC+ encoder mode supports only stereo.
* Native mode indicates that encoding must be performed with the
* number of channels at the input.
* The number of channels must not change during encoding.
*/
u32 sample_rate;
/* Number of samples per second.
* Supported values: - 0 -- Native mode - For other values,
* Native mode indicates that encoding must be performed with the
* sampling rate at the input.
* The sampling rate must not change during encoding.
*/
} __packed;
#define ASM_MEDIA_FMT_AMRNB_FS 0x00010BEB
/* Enumeration for 4.75 kbps AMR-NB Encoding mode. */
#define ASM_MEDIA_FMT_AMRNB_FS_ENCODE_MODE_MR475 0
/* Enumeration for 5.15 kbps AMR-NB Encoding mode. */
#define ASM_MEDIA_FMT_AMRNB_FS_ENCODE_MODE_MR515 1
/* Enumeration for 5.90 kbps AMR-NB Encoding mode. */
#define ASM_MEDIA_FMT_AMRNB_FS_ENCODE_MODE_MMR59 2
/* Enumeration for 6.70 kbps AMR-NB Encoding mode. */
#define ASM_MEDIA_FMT_AMRNB_FS_ENCODE_MODE_MMR67 3
/* Enumeration for 7.40 kbps AMR-NB Encoding mode. */
#define ASM_MEDIA_FMT_AMRNB_FS_ENCODE_MODE_MMR74 4
/* Enumeration for 7.95 kbps AMR-NB Encoding mode. */
#define ASM_MEDIA_FMT_AMRNB_FS_ENCODE_MODE_MMR795 5
/* Enumeration for 10.20 kbps AMR-NB Encoding mode. */
#define ASM_MEDIA_FMT_AMRNB_FS_ENCODE_MODE_MMR102 6
/* Enumeration for 12.20 kbps AMR-NB Encoding mode. */
#define ASM_MEDIA_FMT_AMRNB_FS_ENCODE_MODE_MMR122 7
/* Enumeration for AMR-NB Discontinuous Transmission mode off. */
#define ASM_MEDIA_FMT_AMRNB_FS_DTX_MODE_OFF 0
/* Enumeration for AMR-NB DTX mode VAD1. */
#define ASM_MEDIA_FMT_AMRNB_FS_DTX_MODE_VAD1 1
/* Enumeration for AMR-NB DTX mode VAD2. */
#define ASM_MEDIA_FMT_AMRNB_FS_DTX_MODE_VAD2 2
/* Enumeration for AMR-NB DTX mode auto.
*/
#define ASM_MEDIA_FMT_AMRNB_FS_DTX_MODE_AUTO 3
struct asm_amrnb_enc_cfg {
struct apr_hdr hdr;
struct asm_stream_cmd_set_encdec_param encdec;
struct asm_enc_cfg_blk_param_v2 encblk;
u16 enc_mode;
/* AMR-NB encoding rate.
* Supported values:
* Use the ASM_MEDIA_FMT_AMRNB_FS_ENCODE_MODE_*
* macros
*/
u16 dtx_mode;
/* Specifies whether DTX mode is disabled or enabled.
* Supported values:
* - #ASM_MEDIA_FMT_AMRNB_FS_DTX_MODE_OFF
* - #ASM_MEDIA_FMT_AMRNB_FS_DTX_MODE_VAD1
*/
} __packed;
#define ASM_MEDIA_FMT_AMRWB_FS 0x00010BEC
/* Enumeration for 6.6 kbps AMR-WB Encoding mode. */
#define ASM_MEDIA_FMT_AMRWB_FS_ENCODE_MODE_MR66 0
/* Enumeration for 8.85 kbps AMR-WB Encoding mode. */
#define ASM_MEDIA_FMT_AMRWB_FS_ENCODE_MODE_MR885 1
/* Enumeration for 12.65 kbps AMR-WB Encoding mode. */
#define ASM_MEDIA_FMT_AMRWB_FS_ENCODE_MODE_MR1265 2
/* Enumeration for 14.25 kbps AMR-WB Encoding mode. */
#define ASM_MEDIA_FMT_AMRWB_FS_ENCODE_MODE_MR1425 3
/* Enumeration for 15.85 kbps AMR-WB Encoding mode. */
#define ASM_MEDIA_FMT_AMRWB_FS_ENCODE_MODE_MR1585 4
/* Enumeration for 18.25 kbps AMR-WB Encoding mode. */
#define ASM_MEDIA_FMT_AMRWB_FS_ENCODE_MODE_MR1825 5
/* Enumeration for 19.85 kbps AMR-WB Encoding mode. */
#define ASM_MEDIA_FMT_AMRWB_FS_ENCODE_MODE_MR1985 6
/* Enumeration for 23.05 kbps AMR-WB Encoding mode. */
#define ASM_MEDIA_FMT_AMRWB_FS_ENCODE_MODE_MR2305 7
/* Enumeration for 23.85 kbps AMR-WB Encoding mode.
*/
#define ASM_MEDIA_FMT_AMRWB_FS_ENCODE_MODE_MR2385 8
struct asm_amrwb_enc_cfg {
struct apr_hdr hdr;
struct asm_stream_cmd_set_encdec_param encdec;
struct asm_enc_cfg_blk_param_v2 encblk;
u16 enc_mode;
/* AMR-WB encoding rate.
* Suupported values:
* Use the ASM_MEDIA_FMT_AMRWB_FS_ENCODE_MODE_*
* macros
*/
u16 dtx_mode;
/* Specifies whether DTX mode is disabled or enabled.
* Supported values:
* - #ASM_MEDIA_FMT_AMRNB_FS_DTX_MODE_OFF
* - #ASM_MEDIA_FMT_AMRNB_FS_DTX_MODE_VAD1
*/
} __packed;
#define ASM_MEDIA_FMT_V13K_FS 0x00010BED
/* Enumeration for 14.4 kbps V13K Encoding mode. */
#define ASM_MEDIA_FMT_V13K_FS_ENCODE_MODE_MR1440 0
/* Enumeration for 12.2 kbps V13K Encoding mode. */
#define ASM_MEDIA_FMT_V13K_FS_ENCODE_MODE_MR1220 1
/* Enumeration for 11.2 kbps V13K Encoding mode. */
#define ASM_MEDIA_FMT_V13K_FS_ENCODE_MODE_MR1120 2
/* Enumeration for 9.0 kbps V13K Encoding mode. */
#define ASM_MEDIA_FMT_V13K_FS_ENCODE_MODE_MR90 3
/* Enumeration for 7.2 kbps V13K eEncoding mode. */
#define ASM_MEDIA_FMT_V13K_FS_ENCODE_MODE_MR720 4
/* Enumeration for 1/8 vocoder rate.*/
#define ASM_MEDIA_FMT_VOC_ONE_EIGHTH_RATE 1
/* Enumeration for 1/4 vocoder rate. */
#define ASM_MEDIA_FMT_VOC_ONE_FOURTH_RATE 2
/* Enumeration for 1/2 vocoder rate. */
#define ASM_MEDIA_FMT_VOC_HALF_RATE 3
/* Enumeration for full vocoder rate.
*/
#define ASM_MEDIA_FMT_VOC_FULL_RATE 4
struct asm_v13k_enc_cfg {
struct apr_hdr hdr;
struct asm_stream_cmd_set_encdec_param encdec;
struct asm_enc_cfg_blk_param_v2 encblk;
u16 max_rate;
/* Maximum allowed encoder frame rate.
* Supported values:
* - #ASM_MEDIA_FMT_VOC_ONE_EIGHTH_RATE
* - #ASM_MEDIA_FMT_VOC_ONE_FOURTH_RATE
* - #ASM_MEDIA_FMT_VOC_HALF_RATE
* - #ASM_MEDIA_FMT_VOC_FULL_RATE
*/
u16 min_rate;
/* Minimum allowed encoder frame rate.
* Supported values:
* - #ASM_MEDIA_FMT_VOC_ONE_EIGHTH_RATE
* - #ASM_MEDIA_FMT_VOC_ONE_FOURTH_RATE
* - #ASM_MEDIA_FMT_VOC_HALF_RATE
* - #ASM_MEDIA_FMT_VOC_FULL_RATE
*/
u16 reduced_rate_cmd;
/* Reduced rate command, used to change
* the average bitrate of the V13K
* vocoder.
* Supported values:
* - #ASM_MEDIA_FMT_V13K_FS_ENCODE_MODE_MR1440 (Default)
* - #ASM_MEDIA_FMT_V13K_FS_ENCODE_MODE_MR1220
* - #ASM_MEDIA_FMT_V13K_FS_ENCODE_MODE_MR1120
* - #ASM_MEDIA_FMT_V13K_FS_ENCODE_MODE_MR90
* - #ASM_MEDIA_FMT_V13K_FS_ENCODE_MODE_MR720
*/
u16 rate_mod_cmd;
/* Rate modulation command. Default = 0.
*- If bit 0=1, rate control is enabled.
*- If bit 1=1, the maximum number of consecutive full rate
* frames is limited with numbers supplied in
* bits 2 to 10.
*- If bit 1=0, the minimum number of non-full rate frames
* in between two full rate frames is forced to
* the number supplied in bits 2 to 10. In both cases, if necessary,
* half rate is used to substitute full rate. - Bits 15 to 10 are
* reserved and must all be set to zero.
*/
} __packed;
#define ASM_MEDIA_FMT_EVRC_FS 0x00010BEE
/* EVRC encoder configuration structure used in the
* #ASM_STREAM_CMD_OPEN_READ_V2 command.
*/
struct asm_evrc_enc_cfg {
struct apr_hdr hdr;
struct asm_stream_cmd_set_encdec_param encdec;
struct asm_enc_cfg_blk_param_v2 encblk;
u16 max_rate;
/* Maximum allowed encoder frame rate.
* Supported values:
* - #ASM_MEDIA_FMT_VOC_ONE_EIGHTH_RATE
* - #ASM_MEDIA_FMT_VOC_ONE_FOURTH_RATE
* - #ASM_MEDIA_FMT_VOC_HALF_RATE
* - #ASM_MEDIA_FMT_VOC_FULL_RATE
*/
u16 min_rate;
/* Minimum allowed encoder frame rate.
* Supported values:
* - #ASM_MEDIA_FMT_VOC_ONE_EIGHTH_RATE
* - #ASM_MEDIA_FMT_VOC_ONE_FOURTH_RATE
* - #ASM_MEDIA_FMT_VOC_HALF_RATE
* - #ASM_MEDIA_FMT_VOC_FULL_RATE
*/
u16 rate_mod_cmd;
/* Rate modulation command. Default: 0.
* - If bit 0=1, rate control is enabled.
* - If bit 1=1, the maximum number of consecutive full rate frames
* is limited with numbers supplied in bits 2 to 10.
*
* - If bit 1=0, the minimum number of non-full rate frames in
* between two full rate frames is forced to the number supplied in
* bits 2 to 10. In both cases, if necessary, half rate is used to
* substitute full rate.
*
* - Bits 15 to 10 are reserved and must all be set to zero.
*/
u16 reserved;
/* Reserved. Clients must set this field to zero. */
} __packed;
#define ASM_MEDIA_FMT_WMA_V10PRO_V2 0x00010DA7
struct asm_wmaprov10_fmt_blk_v2 {
struct apr_hdr hdr;
struct asm_data_cmd_media_fmt_update_v2 fmtblk;
u16 fmtag;
/* WMA format type.
* Supported values:
* - 0x162 -- WMA 9 Pro
* - 0x163 -- WMA 9 Pro Lossless
* - 0x166 -- WMA 10 Pro
* - 0x167 -- WMA 10 Pro Lossless
*/
u16 num_channels;
/* Number of channels encoded in the input stream.
* Supported values: 1 to 8
*/
u32 sample_rate;
/* Number of samples per second (in Hertz).
* Supported values: 11025, 16000, 22050, 32000, 44100, 48000,
* 88200, 96000
*/
u32 avg_bytes_per_sec;
/* Bitrate expressed as the average bytes per second.
* Supported values: 2000 to 96000
*/
u16 blk_align;
/* Size of the bitstream packet size in bytes. WMA Pro files
* have a payload of one block per bitstream packet.
* Supported values: @le 13376
*/
u16 bits_per_sample;
/* Number of bits per sample in the encoded WMA stream.
* Supported values: 16, 24
*/
u32 channel_mask;
/* Bit-packed double word (32-bits) that indicates the
* recommended speaker positions for each source channel.
*/
u16 enc_options;
/* Bit-packed word with values that indicate whether certain
* features of the bitstream are used.
* Supported values: - 0x0001 -- ENCOPT3_PURE_LOSSLESS - 0x0006 --
* ENCOPT3_FRM_SIZE_MOD - 0x0038 -- ENCOPT3_SUBFRM_DIV - 0x0040 --
* ENCOPT3_WRITE_FRAMESIZE_IN_HDR - 0x0080 --
* ENCOPT3_GENERATE_DRC_PARAMS - 0x0100 -- ENCOPT3_RTMBITS
*/
u16 usAdvancedEncodeOpt;
/* Advanced encoding option. */
u32 advanced_enc_options2;
/* Advanced encoding option 2. */
} __packed;
#define ASM_MEDIA_FMT_WMA_V9_V2 0x00010DA8
struct asm_wmastdv9_fmt_blk_v2 {
struct apr_hdr hdr;
struct asm_data_cmd_media_fmt_update_v2 fmtblk;
u16 fmtag;
/* WMA format tag.
* Supported values: 0x161 (WMA 9 standard)
*/
u16 num_channels;
/* Number of channels in the stream.
* Supported values: 1, 2
*/
u32 sample_rate;
/* Number of samples per second (in Hertz).
* Supported values: 48000
*/
u32 avg_bytes_per_sec;
/* Bitrate expressed as the average bytes per second. */
u16 blk_align;
/* Block align. All WMA files with a maximum packet size of
* 13376 are supported.
*/
u16 bits_per_sample;
/* Number of bits per sample in the output.
* Supported values: 16
*/
u32 channel_mask;
/* Channel mask.
* Supported values:
* - 3 -- Stereo (front left/front right)
* - 4 -- Mono (center)
*/
u16 enc_options;
/* Options used during encoding. */
u16 reserved;
} __packed;
#define ASM_MEDIA_FMT_WMA_V8 0x00010D91
struct asm_wmastdv8_enc_cfg {
struct apr_hdr hdr;
struct asm_stream_cmd_set_encdec_param encdec;
struct asm_enc_cfg_blk_param_v2 encblk;
u32 bit_rate;
/* Encoding rate in bits per second. */
u32 sample_rate;
/* Number of samples per second.
*
* Supported values:
* - 0 -- Native mode
* - Other Supported values are 22050, 32000, 44100, and 48000.
*
* Native mode indicates that encoding must be performed with the
* sampling rate at the input.
* The sampling rate must not change during encoding.
*/
u16 channel_cfg;
/* Number of channels to encode.
* Supported values:
* - 0 -- Native mode
* - 1 -- Mono
* - 2 -- Stereo
* - Other values are not supported.
*
* Native mode indicates that encoding must be performed with the
* number of channels at the input.
* The number of channels must not change during encoding.
*/
u16 reserved;
/* Reserved. Clients must set this field to zero.*/
} __packed;
#define ASM_MEDIA_FMT_AMR_WB_PLUS_V2 0x00010DA9
struct asm_amrwbplus_fmt_blk_v2 {
struct apr_hdr hdr;
struct asm_data_cmd_media_fmt_update_v2 fmtblk;
u32 amr_frame_fmt;
/* AMR frame format.
* Supported values:
* - 6 -- Transport Interface Format (TIF)
* - Any other value -- File storage format (FSF)
*
* TIF stream contains 2-byte header for each frame within the
* superframe. FSF stream contains one 2-byte header per superframe.
*/
} __packed;
#define ASM_MEDIA_FMT_AC3_DEC 0x00010BF6
#define ASM_MEDIA_FMT_EAC3_DEC 0x00010C3C
#define ASM_MEDIA_FMT_DTS 0x00010D88
/* Media format ID for adaptive transform acoustic coding. This
* ID is used by the #ASM_STREAM_CMD_OPEN_WRITE_COMPRESSED command
* only.
*/
#define ASM_MEDIA_FMT_ATRAC 0x00010D89
/* Media format ID for metadata-enhanced audio transmission.
* This ID is used by the #ASM_STREAM_CMD_OPEN_WRITE_COMPRESSED
* command only.
*/
#define ASM_MEDIA_FMT_MAT 0x00010D8A
/* adsp_media_fmt.h */
#define ASM_DATA_CMD_WRITE_V2 0x00010DAB
struct asm_data_cmd_write_v2 {
struct apr_hdr hdr;
u32 buf_addr_lsw;
/* The 64 bit address msw-lsw should be a valid, mapped address.
* 64 bit address should be a multiple of 32 bytes
*/
u32 buf_addr_msw;
/* The 64 bit address msw-lsw should be a valid, mapped address.
* 64 bit address should be a multiple of 32 bytes.
* -Address of the buffer containing the data to be decoded.
* The buffer should be aligned to a 32 byte boundary.
* -In the case of 32 bit Shared memory address, msw field must
* -be set to zero.
* -In the case of 36 bit shared memory address, bit 31 to bit 4
* -of msw must be set to zero.
*/
u32 mem_map_handle;
/* memory map handle returned by DSP through
* ASM_CMD_SHARED_MEM_MAP_REGIONS command
*/
u32 buf_size;
/* Number of valid bytes available in the buffer for decoding. The
* first byte starts at buf_addr.
*/
u32 seq_id;
/* Optional buffer sequence ID. */
u32 timestamp_lsw;
/* Lower 32 bits of the 64-bit session time in microseconds of the
* first buffer sample.
*/
u32 timestamp_msw;
/* Upper 32 bits of the 64-bit session time in microseconds of the
* first buffer sample.
*/
u32 flags;
/* Bitfield of flags.
* Supported values for bit 31:
* - 1 -- Valid timestamp.
* - 0 -- Invalid timestamp.
* - Use #ASM_BIT_MASKIMESTAMP_VALID_FLAG as the bitmask and
* #ASM_SHIFTIMESTAMP_VALID_FLAG as the shift value to set this bit.
* Supported values for bit 30:
* - 1 -- Last buffer.
* - 0 -- Not the last buffer.
*
* Supported values for bit 29:
* - 1 -- Continue the timestamp from the previous buffer.
* - 0 -- Timestamp of the current buffer is not related
* to the timestamp of the previous buffer.
* - Use #ASM_BIT_MASKS_CONTINUE_FLAG and #ASM_SHIFTS_CONTINUE_FLAG
* to set this bit.
*
* Supported values for bit 4:
* - 1 -- End of the frame.
* - 0 -- Not the end of frame, or this information is not known.
* - Use #ASM_BIT_MASK_EOF_FLAG as the bitmask and #ASM_SHIFT_EOF_FLAG
* as the shift value to set this bit.
*
* All other bits are reserved and must be set to 0.
*
* If bit 31=0 and bit 29=1: The timestamp of the first sample in
* this buffer continues from the timestamp of the last sample in
* the previous buffer. If there is no previous buffer (i.e., this
* is the first buffer sent after opening the stream or after a
* flush operation), or if the previous buffer does not have a valid
* timestamp, the samples in the current buffer also do not have a
* valid timestamp. They are played out as soon as possible.
*
*
* If bit 31=0 and bit 29=0: No timestamp is associated with the
* first sample in this buffer. The samples are played out as soon
* as possible.
*
*
* If bit 31=1 and bit 29 is ignored: The timestamp specified in
* this payload is honored.
*
*
* If bit 30=0: Not the last buffer in the stream. This is useful
* in removing trailing samples.
*
*
* For bit 4: The client can set this flag for every buffer sent in
* which the last byte is the end of a frame. If this flag is set,
* the buffer can contain data from multiple frames, but it should
* always end at a frame boundary. Restrictions allow the aDSP to
* detect an end of frame without requiring additional processing.
*/
} __packed;
#define ASM_DATA_CMD_READ_V2 0x00010DAC
struct asm_data_cmd_read_v2 {
struct apr_hdr hdr;
u32 buf_addr_lsw;
/* the 64 bit address msw-lsw should be a valid mapped address
* and should be a multiple of 32 bytes
*/
u32 buf_addr_msw;
/* the 64 bit address msw-lsw should be a valid mapped address
* and should be a multiple of 32 bytes.
* - Address of the buffer where the DSP puts the encoded data,
* potentially, at an offset specified by the uOffset field in
* ASM_DATA_EVENT_READ_DONE structure. The buffer should be aligned
* to a 32 byte boundary.
*- In the case of 32 bit Shared memory address, msw field must
*- be set to zero.
*- In the case of 36 bit shared memory address, bit 31 to bit
*- 4 of msw must be set to zero.
*/
u32 mem_map_handle;
/* memory map handle returned by DSP through
* ASM_CMD_SHARED_MEM_MAP_REGIONS command.
*/
u32 buf_size;
/* Number of bytes available for the aDSP to write. The aDSP
* starts writing from buf_addr.
*/
u32 seq_id;
/* Optional buffer sequence ID.
*/
} __packed;
#define ASM_DATA_CMD_EOS 0x00010BDB
#define ASM_DATA_EVENT_RENDERED_EOS 0x00010C1C
#define ASM_DATA_EVENT_EOS 0x00010BDD
#define ASM_DATA_EVENT_WRITE_DONE_V2 0x00010D99
struct asm_data_event_write_done_v2 {
u32 buf_addr_lsw;
/* lsw of the 64 bit address */
u32 buf_addr_msw;
/* msw of the 64 bit address. address given by the client in
* ASM_DATA_CMD_WRITE_V2 command.
*/
u32 mem_map_handle;
/* memory map handle in the ASM_DATA_CMD_WRITE_V2 */
u32 status;
/* Status message (error code) that indicates whether the
* referenced buffer has been successfully consumed.
* Supported values: Refer to @xhyperref{Q3,[Q3]}
*/
} __packed;
#define ASM_DATA_EVENT_READ_DONE_V2 0x00010D9A
/* Definition of the frame metadata flag bitmask.*/
#define ASM_BIT_MASK_FRAME_METADATA_FLAG (0x40000000UL)
/* Definition of the frame metadata flag shift value. */
#define ASM_SHIFT_FRAME_METADATA_FLAG 30
struct asm_data_event_read_done_v2 {
u32 status;
/* Status message (error code).
* Supported values: Refer to @xhyperref{Q3,[Q3]}
*/
u32 buf_addr_lsw;
/* 64 bit address msw-lsw is a valid, mapped address. 64 bit
* address is a multiple of 32 bytes.
*/
u32 buf_addr_msw;
/* 64 bit address msw-lsw is a valid, mapped address. 64 bit
* address is a multiple of 32 bytes.
*
* -Same address provided by the client in ASM_DATA_CMD_READ_V2
* -In the case of 32 bit Shared memory address, msw field is set to
* zero.
* -In the case of 36 bit shared memory address, bit 31 to bit 4
* -of msw is set to zero.
*/
u32 mem_map_handle;
/* memory map handle in the ASM_DATA_CMD_READ_V2 */
u32 enc_framesotal_size;
/* Total size of the encoded frames in bytes.
* Supported values: >0
*/
u32 offset;
/* Offset (from buf_addr) to the first byte of the first encoded
* frame. All encoded frames are consecutive, starting from this
* offset.
* Supported values: > 0
*/
u32 timestamp_lsw;
/* Lower 32 bits of the 64-bit session time in microseconds of
* the first sample in the buffer. If Bit 5 of mode_flags flag of
* ASM_STREAM_CMD_OPEN_READ_V2 is 1 then the 64 bit timestamp is
* absolute capture time otherwise it is relative session time. The
* absolute timestamp doesnt reset unless the system is reset.
*/
u32 timestamp_msw;
/* Upper 32 bits of the 64-bit session time in microseconds of
* the first sample in the buffer.
*/
u32 flags;
/* Bitfield of flags. Bit 30 indicates whether frame metadata is
* present. If frame metadata is present, num_frames consecutive
* instances of @xhyperref{hdr:FrameMetaData,Frame metadata} start
* at the buffer address.
* Supported values for bit 31:
* - 1 -- Timestamp is valid.
* - 0 -- Timestamp is invalid.
* - Use #ASM_BIT_MASKIMESTAMP_VALID_FLAG and
* #ASM_SHIFTIMESTAMP_VALID_FLAG to set this bit.
*
* Supported values for bit 30:
* - 1 -- Frame metadata is present.
* - 0 -- Frame metadata is absent.
* - Use #ASM_BIT_MASK_FRAME_METADATA_FLAG and
* #ASM_SHIFT_FRAME_METADATA_FLAG to set this bit.
*
* All other bits are reserved; the aDSP sets them to 0.
*/
u32 num_frames;
/* Number of encoded frames in the buffer. */
u32 seq_id;
/* Optional buffer sequence ID. */
} __packed;
struct asm_data_read_buf_metadata_v2 {
u32 offset;
/* Offset from buf_addr in #ASM_DATA_EVENT_READ_DONE_PAYLOAD to
* the frame associated with this metadata.
* Supported values: > 0
*/
u32 frm_size;
/* Size of the encoded frame in bytes.
* Supported values: > 0
*/
u32 num_encoded_pcm_samples;
/* Number of encoded PCM samples (per channel) in the frame
* associated with this metadata.
* Supported values: > 0
*/
u32 timestamp_lsw;
/* Lower 32 bits of the 64-bit session time in microseconds of the
* first sample for this frame.
* If Bit 5 of mode_flags flag of ASM_STREAM_CMD_OPEN_READ_V2 is 1
* then the 64 bit timestamp is absolute capture time otherwise it
* is relative session time. The absolute timestamp doesnt reset
* unless the system is reset.
*/
u32 timestamp_msw;
/* Lower 32 bits of the 64-bit session time in microseconds of the
* first sample for this frame.
*/
u32 flags;
/* Frame flags.
* Supported values for bit 31:
* - 1 -- Time stamp is valid
* - 0 -- Time stamp is not valid
* - All other bits are reserved; the aDSP sets them to 0.
*/
} __packed;
/* Notifies the client of a change in the data sampling rate or
* Channel mode. This event is raised by the decoder service. The
* event is enabled through the mode flags of
* #ASM_STREAM_CMD_OPEN_WRITE_V2 or
* #ASM_STREAM_CMD_OPEN_READWRITE_V2. - The decoder detects a change
* in the output sampling frequency or the number/positioning of
* output channels, or if it is the first frame decoded.The new
* sampling frequency or the new channel configuration is
* communicated back to the client asynchronously.
*/
#define ASM_DATA_EVENT_SR_CM_CHANGE_NOTIFY 0x00010C65
/* Payload of the #ASM_DATA_EVENT_SR_CM_CHANGE_NOTIFY event.
* This event is raised when the following conditions are both true:
* - The event is enabled through the mode_flags of
* #ASM_STREAM_CMD_OPEN_WRITE_V2 or
* #ASM_STREAM_CMD_OPEN_READWRITE_V2. - The decoder detects a change
* in either the output sampling frequency or the number/positioning
* of output channels, or if it is the first frame decoded.
* This event is not raised (even if enabled) if the decoder is
* MIDI, because
*/
struct asm_data_event_sr_cm_change_notify {
u32 sample_rate;
/* New sampling rate (in Hertz) after detecting a change in the
* bitstream.
* Supported values: 2000 to 48000
*/
u16 num_channels;
/* New number of channels after detecting a change in the
* bitstream.
* Supported values: 1 to 8
*/
u16 reserved;
/* Reserved for future use. This field must be set to 0.*/
u8 channel_mapping[8];
} __packed;
/* Notifies the client of a data sampling rate or channel mode
* change. This event is raised by the encoder service.
* This event is raised when :
* - Native mode encoding was requested in the encoder
* configuration (i.e., the channel number was 0), the sample rate
* was 0, or both were 0.
*
* - The input data frame at the encoder is the first one, or the
* sampling rate/channel mode is different from the previous input
* data frame.
*
*/
#define ASM_DATA_EVENT_ENC_SR_CM_CHANGE_NOTIFY 0x00010BDE
struct asm_data_event_enc_sr_cm_change_notify {
u32 sample_rate;
/* New sampling rate (in Hertz) after detecting a change in the
* input data.
* Supported values: 2000 to 48000
*/
u16 num_channels;
/* New number of channels after detecting a change in the input
* data. Supported values: 1 to 8
*/
u16 bits_per_sample;
/* New bits per sample after detecting a change in the input
* data.
* Supported values: 16, 24
*/
u8 channel_mapping[8];
} __packed;
#define ASM_DATA_CMD_IEC_60958_FRAME_RATE 0x00010D87
/* Payload of the #ASM_DATA_CMD_IEC_60958_FRAME_RATE command,
* which is used to indicate the IEC 60958 frame rate of a given
* packetized audio stream.
*/
struct asm_data_cmd_iec_60958_frame_rate {
u32 frame_rate;
/* IEC 60958 frame rate of the incoming IEC 61937 packetized stream.
* Supported values: Any valid frame rate
*/
} __packed;
/* adsp_asm_data_commands.h*/
#define ASM_SVC_CMD_GET_STREAM_HANDLES 0x00010C0B
#define ASM_SVC_CMDRSP_GET_STREAM_HANDLES 0x00010C1B
/* Definition of the stream ID bitmask.*/
#define ASM_BIT_MASK_STREAM_ID (0x000000FFUL)
/* Definition of the stream ID shift value.*/
#define ASM_SHIFT_STREAM_ID 0
/* Definition of the session ID bitmask.*/
#define ASM_BIT_MASK_SESSION_ID (0x0000FF00UL)
/* Definition of the session ID shift value.*/
#define ASM_SHIFT_SESSION_ID 8
/* Definition of the service ID bitmask.*/
#define ASM_BIT_MASK_SERVICE_ID (0x00FF0000UL)
/* Definition of the service ID shift value.*/
#define ASM_SHIFT_SERVICE_ID 16
/* Definition of the domain ID bitmask.*/
#define ASM_BIT_MASK_DOMAIN_ID (0xFF000000UL)
/* Definition of the domain ID shift value.*/
#define ASM_SHIFT_DOMAIN_ID 24
/* Payload of the #ASM_SVC_CMDRSP_GET_STREAM_HANDLES message,
* which returns a list of currently active stream handles.
* Immediately following this structure are num_handles of uint32
* stream handles.
*/
struct asm_svc_cmdrsp_get_stream_handles {
u32 num_handles;
/* Number of active stream handles. */
} __packed;
#define ASM_CMD_SHARED_MEM_MAP_REGIONS 0x00010D92
#define ASM_CMDRSP_SHARED_MEM_MAP_REGIONS 0x00010D93
#define ASM_CMD_SHARED_MEM_UNMAP_REGIONS 0x00010D94
/* adsp_asm_service_commands.h */
#define ASM_MAX_SESSION_ID (8)
/* Maximum number of sessions.*/
#define ASM_MAX_NUM_SESSIONS ASM_MAX_SESSION_ID
/* Maximum number of streams per session.*/
#define ASM_MAX_STREAMS_PER_SESSION (8)
#define ASM_SESSION_CMD_RUN_V2 0x00010DAA
#define ASM_SESSION_CMD_RUN_STARTIME_RUN_IMMEDIATE 0
#define ASM_SESSION_CMD_RUN_STARTIME_RUN_AT_ABSOLUTEIME 1
#define ASM_SESSION_CMD_RUN_STARTIME_RUN_AT_RELATIVEIME 2
#define ASM_SESSION_CMD_RUN_STARTIME_RUN_WITH_DELAY 3
#define ASM_BIT_MASK_RUN_STARTIME (0x00000003UL)
/* Bit shift value used to specify the start time for the
* ASM_SESSION_CMD_RUN_V2 command.
*/
#define ASM_SHIFT_RUN_STARTIME 0
struct asm_session_cmd_run_v2 {
struct apr_hdr hdr;
u32 flags;
/* Specifies whether to run immediately or at a specific
* rendering time or with a specified delay. Run with delay is
* useful for delaying in case of ASM loopback opened through
* ASM_STREAM_CMD_OPEN_LOOPBACK_V2. Use #ASM_BIT_MASK_RUN_STARTIME
* and #ASM_SHIFT_RUN_STARTIME to set this 2-bit flag.
*
*
*Bits 0 and 1 can take one of four possible values:
*
*- #ASM_SESSION_CMD_RUN_STARTIME_RUN_IMMEDIATE
*- #ASM_SESSION_CMD_RUN_STARTIME_RUN_AT_ABSOLUTEIME
*- #ASM_SESSION_CMD_RUN_STARTIME_RUN_AT_RELATIVEIME
*- #ASM_SESSION_CMD_RUN_STARTIME_RUN_WITH_DELAY
*
*All other bits are reserved; clients must set them to zero.
*/
u32 time_lsw;
/* Lower 32 bits of the time in microseconds used to align the
* session origin time. When bits 0-1 of flags is
* ASM_SESSION_CMD_RUN_START_RUN_WITH_DELAY, time lsw is the lsw of
* the delay in us. For ASM_SESSION_CMD_RUN_START_RUN_WITH_DELAY,
* maximum value of the 64 bit delay is 150 ms.
*/
u32 time_msw;
/* Upper 32 bits of the time in microseconds used to align the
* session origin time. When bits 0-1 of flags is
* ASM_SESSION_CMD_RUN_START_RUN_WITH_DELAY, time msw is the msw of
* the delay in us. For ASM_SESSION_CMD_RUN_START_RUN_WITH_DELAY,
* maximum value of the 64 bit delay is 150 ms.
*/
} __packed;
#define ASM_SESSION_CMD_PAUSE 0x00010BD3
#define ASM_SESSION_CMD_SUSPEND 0x00010DEC
#define ASM_SESSION_CMD_GET_SESSIONTIME_V3 0x00010D9D
#define ASM_SESSION_CMD_REGISTER_FOR_RX_UNDERFLOW_EVENTS 0x00010BD5
struct asm_session_cmd_rgstr_rx_underflow {
struct apr_hdr hdr;
u16 enable_flag;
/* Specifies whether a client is to receive events when an Rx
* session underflows.
* Supported values:
* - 0 -- Do not send underflow events
* - 1 -- Send underflow events
*/
u16 reserved;
/* Reserved. This field must be set to zero.*/
} __packed;
#define ASM_SESSION_CMD_REGISTER_FORX_OVERFLOW_EVENTS 0x00010BD6
struct asm_session_cmd_regx_overflow {
struct apr_hdr hdr;
u16 enable_flag;
/* Specifies whether a client is to receive events when a Tx
* session overflows.
* Supported values:
* - 0 -- Do not send overflow events
* - 1 -- Send overflow events
*/
u16 reserved;
/* Reserved. This field must be set to zero.*/
} __packed;
#define ASM_SESSION_EVENT_RX_UNDERFLOW 0x00010C17
#define ASM_SESSION_EVENTX_OVERFLOW 0x00010C18
#define ASM_SESSION_CMDRSP_GET_SESSIONTIME_V3 0x00010D9E
struct asm_session_cmdrsp_get_sessiontime_v3 {
u32 status;
/* Status message (error code).
* Supported values: Refer to @xhyperref{Q3,[Q3]}
*/
u32 sessiontime_lsw;
/* Lower 32 bits of the current session time in microseconds.*/
u32 sessiontime_msw;
/* Upper 32 bits of the current session time in microseconds.*/
u32 absolutetime_lsw;
/* Lower 32 bits in micro seconds of the absolute time at which
* the * sample corresponding to the above session time gets
* rendered * to hardware. This absolute time may be slightly in the
* future or past.
*/
u32 absolutetime_msw;
/* Upper 32 bits in micro seconds of the absolute time at which
* the * sample corresponding to the above session time gets
* rendered to * hardware. This absolute time may be slightly in the
* future or past.
*/
} __packed;
#define ASM_SESSION_CMD_ADJUST_SESSION_CLOCK_V2 0x00010D9F
struct asm_session_cmd_adjust_session_clock_v2 {
struct apr_hdr hdr;
u32 adjustime_lsw;
/* Lower 32 bits of the signed 64-bit quantity that specifies the
* adjustment time in microseconds to the session clock.
*
* Positive values indicate advancement of the session clock.
* Negative values indicate delay of the session clock.
*/
u32 adjustime_msw;
/* Upper 32 bits of the signed 64-bit quantity that specifies
* the adjustment time in microseconds to the session clock.
* Positive values indicate advancement of the session clock.
* Negative values indicate delay of the session clock.
*/
} __packed;
#define ASM_SESSION_CMDRSP_ADJUST_SESSION_CLOCK_V2 0x00010DA0
struct asm_session_cmdrsp_adjust_session_clock_v2 {
u32 status;
/* Status message (error code).
* Supported values: Refer to @xhyperref{Q3,[Q3]}
* An error means the session clock is not adjusted. In this case,
* the next two fields are irrelevant.
*/
u32 actual_adjustime_lsw;
/* Lower 32 bits of the signed 64-bit quantity that specifies
* the actual adjustment in microseconds performed by the aDSP.
* A positive value indicates advancement of the session clock. A
* negative value indicates delay of the session clock.
*/
u32 actual_adjustime_msw;
/* Upper 32 bits of the signed 64-bit quantity that specifies
* the actual adjustment in microseconds performed by the aDSP.
* A positive value indicates advancement of the session clock. A
* negative value indicates delay of the session clock.
*/
u32 cmd_latency_lsw;
/* Lower 32 bits of the unsigned 64-bit quantity that specifies
* the amount of time in microseconds taken to perform the session
* clock adjustment.
*/
u32 cmd_latency_msw;
/* Upper 32 bits of the unsigned 64-bit quantity that specifies
* the amount of time in microseconds taken to perform the session
* clock adjustment.
*/
} __packed;
#define ASM_SESSION_CMD_GET_PATH_DELAY_V2 0x00010DAF
#define ASM_SESSION_CMDRSP_GET_PATH_DELAY_V2 0x00010DB0
struct asm_session_cmdrsp_get_path_delay_v2 {
u32 status;
/* Status message (error code). Whether this get delay operation
* is successful or not. Delay value is valid only if status is
* success.
* Supported values: Refer to @xhyperref{Q5,[Q5]}
*/
u32 audio_delay_lsw;
/* Upper 32 bits of the aDSP delay in microseconds. */
u32 audio_delay_msw;
/* Lower 32 bits of the aDSP delay in microseconds. */
} __packed;
/* adsp_asm_session_command.h*/
#define ASM_STREAM_CMD_OPEN_WRITE_V2 0x00010D8F
#define ASM_STREAM_CMD_OPEN_WRITE_V3 0x00010DB3
#define ASM_LOW_LATENCY_STREAM_SESSION 0x10000000
#define ASM_ULTRA_LOW_LATENCY_STREAM_SESSION 0x20000000
#define ASM_LEGACY_STREAM_SESSION 0
struct asm_stream_cmd_open_write_v3 {
struct apr_hdr hdr;
uint32_t mode_flags;
/* Mode flags that configure the stream to notify the client
* whenever it detects an SR/CM change at the input to its POPP.
* Supported values for bits 0 to 1:
* - Reserved; clients must set them to zero.
* Supported values for bit 2:
* - 0 -- SR/CM change notification event is disabled.
* - 1 -- SR/CM change notification event is enabled.
* - Use #ASM_BIT_MASK_SR_CM_CHANGE_NOTIFY_FLAG and
* #ASM_SHIFT_SR_CM_CHANGE_NOTIFY_FLAG to set or get this bit.
*
* Supported values for bit 31:
* - 0 -- Stream to be opened in on-Gapless mode.
* - 1 -- Stream to be opened in Gapless mode. In Gapless mode,
* successive streams must be opened with same session ID but
* different stream IDs.
*
* - Use #ASM_BIT_MASK_GAPLESS_MODE_FLAG and
* #ASM_SHIFT_GAPLESS_MODE_FLAG to set or get this bit.
*
*
* @note1hang MIDI and DTMF streams cannot be opened in Gapless mode.
*/
uint16_t sink_endpointype;
/*< Sink point type.
* Supported values:
* - 0 -- Device matrix
* - Other values are reserved.
*
* The device matrix is the gateway to the hardware ports.
*/
uint16_t bits_per_sample;
/*< Number of bits per sample processed by ASM modules.
* Supported values: 16 and 24 bits per sample
*/
uint32_t postprocopo_id;
/*< Specifies the topology (order of processing) of
* postprocessing algorithms. <i>None</i> means no postprocessing.
* Supported values:
* - #ASM_STREAM_POSTPROCOPO_ID_DEFAULT
* - #ASM_STREAM_POSTPROCOPO_ID_MCH_PEAK_VOL
* - #ASM_STREAM_POSTPROCOPO_ID_NONE
*
* This field can also be enabled through SetParams flags.
*/
uint32_t dec_fmt_id;
/*< Configuration ID of the decoder media format.
*
* Supported values:
* - #ASM_MEDIA_FMT_MULTI_CHANNEL_PCM_V2
* - #ASM_MEDIA_FMT_ADPCM
* - #ASM_MEDIA_FMT_MP3
* - #ASM_MEDIA_FMT_AAC_V2
* - #ASM_MEDIA_FMT_DOLBY_AAC
* - #ASM_MEDIA_FMT_AMRNB_FS
* - #ASM_MEDIA_FMT_AMRWB_FS
* - #ASM_MEDIA_FMT_AMR_WB_PLUS_V2
* - #ASM_MEDIA_FMT_V13K_FS
* - #ASM_MEDIA_FMT_EVRC_FS
* - #ASM_MEDIA_FMT_EVRCB_FS
* - #ASM_MEDIA_FMT_EVRCWB_FS
* - #ASM_MEDIA_FMT_SBC
* - #ASM_MEDIA_FMT_WMA_V10PRO_V2
* - #ASM_MEDIA_FMT_WMA_V9_V2
* - #ASM_MEDIA_FMT_AC3_DEC
* - #ASM_MEDIA_FMT_EAC3_DEC
* - #ASM_MEDIA_FMT_G711_ALAW_FS
* - #ASM_MEDIA_FMT_G711_MLAW_FS
* - #ASM_MEDIA_FMT_G729A_FS
* - #ASM_MEDIA_FMT_FR_FS
* - #ASM_MEDIA_FMT_VORBIS
* - #ASM_MEDIA_FMT_FLAC
* - #ASM_MEDIA_FMT_EXAMPLE
*/
} __packed;
#define ASM_STREAM_CMD_OPEN_READ_V2 0x00010D8C
#define ASM_STREAM_CMD_OPEN_READ_V3 0x00010DB4
/* Definition of the timestamp type flag bitmask */
#define ASM_BIT_MASKIMESTAMPYPE_FLAG (0x00000020UL)
/* Definition of the timestamp type flag shift value. */
#define ASM_SHIFTIMESTAMPYPE_FLAG 5
/* Relative timestamp is identified by this value.*/
#define ASM_RELATIVEIMESTAMP 0
/* Absolute timestamp is identified by this value.*/
#define ASM_ABSOLUTEIMESTAMP 1
/* Bit shift for the stream_perf_mode subfield. */
#define ASM_SHIFT_STREAM_PERF_MODE_FLAG_IN_OPEN_READ 29
struct asm_stream_cmd_open_read_v3 {
struct apr_hdr hdr;
u32 mode_flags;
/* Mode flags that indicate whether meta information per encoded
* frame is to be provided.
* Supported values for bit 4:
*
* - 0 -- Return data buffer contains all encoded frames only; it
* does not contain frame metadata.
*
* - 1 -- Return data buffer contains an array of metadata and
* encoded frames.
*
* - Use #ASM_BIT_MASK_META_INFO_FLAG as the bitmask and
* #ASM_SHIFT_META_INFO_FLAG as the shift value for this bit.
*
*
* Supported values for bit 5:
*
* - ASM_RELATIVEIMESTAMP -- ASM_DATA_EVENT_READ_DONE_V2 will have
* - relative time-stamp.
* - ASM_ABSOLUTEIMESTAMP -- ASM_DATA_EVENT_READ_DONE_V2 will
* - have absolute time-stamp.
*
* - Use #ASM_BIT_MASKIMESTAMPYPE_FLAG as the bitmask and
* #ASM_SHIFTIMESTAMPYPE_FLAG as the shift value for this bit.
*
* All other bits are reserved; clients must set them to zero.
*/
u32 src_endpointype;
/* Specifies the endpoint providing the input samples.
* Supported values:
* - 0 -- Device matrix
* - All other values are reserved; clients must set them to zero.
* Otherwise, an error is returned.
* The device matrix is the gateway from the tunneled Tx ports.
*/
u32 preprocopo_id;
/* Specifies the topology (order of processing) of preprocessing
* algorithms. <i>None</i> means no preprocessing.
* Supported values:
* - #ASM_STREAM_PREPROCOPO_ID_DEFAULT
* - #ASM_STREAM_PREPROCOPO_ID_NONE
*
* This field can also be enabled through SetParams flags.
*/
u32 enc_cfg_id;
/* Media configuration ID for encoded output.
* Supported values:
* - #ASM_MEDIA_FMT_MULTI_CHANNEL_PCM_V2
* - #ASM_MEDIA_FMT_AAC_V2
* - #ASM_MEDIA_FMT_AMRNB_FS
* - #ASM_MEDIA_FMT_AMRWB_FS
* - #ASM_MEDIA_FMT_V13K_FS
* - #ASM_MEDIA_FMT_EVRC_FS
* - #ASM_MEDIA_FMT_EVRCB_FS
* - #ASM_MEDIA_FMT_EVRCWB_FS
* - #ASM_MEDIA_FMT_SBC
* - #ASM_MEDIA_FMT_G711_ALAW_FS
* - #ASM_MEDIA_FMT_G711_MLAW_FS
* - #ASM_MEDIA_FMT_G729A_FS
* - #ASM_MEDIA_FMT_EXAMPLE
* - #ASM_MEDIA_FMT_WMA_V8
*/
u16 bits_per_sample;
/* Number of bits per sample processed by ASM modules.
* Supported values: 16 and 24 bits per sample
*/
u16 reserved;
/* Reserved for future use. This field must be set to zero.*/
} __packed;
#define ASM_POPP_OUTPUT_SR_NATIVE_RATE 0
/* Enumeration for the maximum sampling rate at the POPP output.*/
#define ASM_POPP_OUTPUT_SR_MAX_RATE 48000
#define ASM_STREAM_CMD_OPEN_READWRITE_V2 0x00010D8D
#define ASM_STREAM_CMD_OPEN_READWRITE_V2 0x00010D8D
#define ASM_STREAM_CMD_OPEN_READ_V2 0x00010D8C
struct asm_stream_cmd_open_readwrite_v2 {
struct apr_hdr hdr;
u32 mode_flags;
/* Mode flags.
* Supported values for bit 2:
* - 0 -- SR/CM change notification event is disabled.
* - 1 -- SR/CM change notification event is enabled. Use
* #ASM_BIT_MASK_SR_CM_CHANGE_NOTIFY_FLAG and
* #ASM_SHIFT_SR_CM_CHANGE_NOTIFY_FLAG to set or
* getting this flag.
*
* Supported values for bit 4:
* - 0 -- Return read data buffer contains all encoded frames only; it
* does not contain frame metadata.
* - 1 -- Return read data buffer contains an array of metadata and
* encoded frames.
*
* All other bits are reserved; clients must set them to zero.
*/
u32 postprocopo_id;
/* Specifies the topology (order of processing) of postprocessing
* algorithms. <i>None</i> means no postprocessing.
*
* Supported values:
* - #ASM_STREAM_POSTPROCOPO_ID_DEFAULT
* - #ASM_STREAM_POSTPROCOPO_ID_MCH_PEAK_VOL
* - #ASM_STREAM_POSTPROCOPO_ID_NONE
*/
u32 dec_fmt_id;
/* Specifies the media type of the input data. PCM indicates that
* no decoding must be performed, e.g., this is an NT encoder
* session.
* Supported values:
* - #ASM_MEDIA_FMT_MULTI_CHANNEL_PCM_V2
* - #ASM_MEDIA_FMT_ADPCM
* - #ASM_MEDIA_FMT_MP3
* - #ASM_MEDIA_FMT_AAC_V2
* - #ASM_MEDIA_FMT_DOLBY_AAC
* - #ASM_MEDIA_FMT_AMRNB_FS
* - #ASM_MEDIA_FMT_AMRWB_FS
* - #ASM_MEDIA_FMT_V13K_FS
* - #ASM_MEDIA_FMT_EVRC_FS
* - #ASM_MEDIA_FMT_EVRCB_FS
* - #ASM_MEDIA_FMT_EVRCWB_FS
* - #ASM_MEDIA_FMT_SBC
* - #ASM_MEDIA_FMT_WMA_V10PRO_V2
* - #ASM_MEDIA_FMT_WMA_V9_V2
* - #ASM_MEDIA_FMT_AMR_WB_PLUS_V2
* - #ASM_MEDIA_FMT_AC3_DEC
* - #ASM_MEDIA_FMT_G711_ALAW_FS
* - #ASM_MEDIA_FMT_G711_MLAW_FS
* - #ASM_MEDIA_FMT_G729A_FS
* - #ASM_MEDIA_FMT_EXAMPLE
*/
u32 enc_cfg_id;
/* Specifies the media type for the output of the stream. PCM
* indicates that no encoding must be performed, e.g., this is an NT
* decoder session.
* Supported values:
* - #ASM_MEDIA_FMT_MULTI_CHANNEL_PCM_V2
* - #ASM_MEDIA_FMT_AAC_V2
* - #ASM_MEDIA_FMT_AMRNB_FS
* - #ASM_MEDIA_FMT_AMRWB_FS
* - #ASM_MEDIA_FMT_V13K_FS
* - #ASM_MEDIA_FMT_EVRC_FS
* - #ASM_MEDIA_FMT_EVRCB_FS
* - #ASM_MEDIA_FMT_EVRCWB_FS
* - #ASM_MEDIA_FMT_SBC
* - #ASM_MEDIA_FMT_G711_ALAW_FS
* - #ASM_MEDIA_FMT_G711_MLAW_FS
* - #ASM_MEDIA_FMT_G729A_FS
* - #ASM_MEDIA_FMT_EXAMPLE
* - #ASM_MEDIA_FMT_WMA_V8
*/
u16 bits_per_sample;
/* Number of bits per sample processed by ASM modules.
* Supported values: 16 and 24 bits per sample
*/
u16 reserved;
/* Reserved for future use. This field must be set to zero.*/
} __packed;
#define ASM_STREAM_CMD_OPEN_LOOPBACK_V2 0x00010D8E
struct asm_stream_cmd_open_loopback_v2 {
struct apr_hdr hdr;
u32 mode_flags;
/* Mode flags.
* Bit 0-31: reserved; client should set these bits to 0
*/
u16 src_endpointype;
/* Endpoint type. 0 = Tx Matrix */
u16 sink_endpointype;
/* Endpoint type. 0 = Rx Matrix */
u32 postprocopo_id;
/* Postprocessor topology ID. Specifies the topology of
* postprocessing algorithms.
*/
u16 bits_per_sample;
/* The number of bits per sample processed by ASM modules
* Supported values: 16 and 24 bits per sample
*/
u16 reserved;
/* Reserved for future use. This field must be set to zero. */
} __packed;
#define ASM_STREAM_CMD_CLOSE 0x00010BCD
#define ASM_STREAM_CMD_FLUSH 0x00010BCE
#define ASM_STREAM_CMD_FLUSH_READBUFS 0x00010C09
#define ASM_STREAM_CMD_SET_PP_PARAMS_V2 0x00010DA1
struct asm_stream_cmd_set_pp_params_v2 {
u32 data_payload_addr_lsw;
/* LSW of parameter data payload address. Supported values: any. */
u32 data_payload_addr_msw;
/* MSW of Parameter data payload address. Supported values: any.
* - Must be set to zero for in-band data.
* - In the case of 32 bit Shared memory address, msw field must be
* - set to zero.
* - In the case of 36 bit shared memory address, bit 31 to bit 4 of
* msw
*
* - must be set to zero.
*/
u32 mem_map_handle;
/* Supported Values: Any.
* memory map handle returned by DSP through
* ASM_CMD_SHARED_MEM_MAP_REGIONS
* command.
* if mmhandle is NULL, the ParamData payloads are within the
* message payload (in-band).
* If mmhandle is non-NULL, the ParamData payloads begin at the
* address specified in the address msw and lsw (out-of-band).
*/
u32 data_payload_size;
/* Size in bytes of the variable payload accompanying the
message, or in shared memory. This field is used for parsing the
parameter payload. */
} __packed;
struct asm_stream_param_data_v2 {
u32 module_id;
/* Unique module ID. */
u32 param_id;
/* Unique parameter ID. */
u16 param_size;
/* Data size of the param_id/module_id combination. This is
* a multiple of 4 bytes.
*/
u16 reserved;
/* Reserved for future enhancements. This field must be set to
* zero.
*/
} __packed;
#define ASM_STREAM_CMD_GET_PP_PARAMS_V2 0x00010DA2
struct asm_stream_cmd_get_pp_params_v2 {
u32 data_payload_addr_lsw;
/* LSW of the parameter data payload address. */
u32 data_payload_addr_msw;
/* MSW of the parameter data payload address.
* - Size of the shared memory, if specified, shall be large enough
* to contain the whole ParamData payload, including Module ID,
* Param ID, Param Size, and Param Values
* - Must be set to zero for in-band data
* - In the case of 32 bit Shared memory address, msw field must be
* set to zero.
* - In the case of 36 bit shared memory address, bit 31 to bit 4 of
* msw must be set to zero.
*/
u32 mem_map_handle;
/* Supported Values: Any.
* memory map handle returned by DSP through ASM_CMD_SHARED_MEM_MAP_REGIONS
* command.
* if mmhandle is NULL, the ParamData payloads in the ACK are within the
* message payload (in-band).
* If mmhandle is non-NULL, the ParamData payloads in the ACK begin at the
* address specified in the address msw and lsw.
* (out-of-band).
*/
u32 module_id;
/* Unique module ID. */
u32 param_id;
/* Unique parameter ID. */
u16 param_max_size;
/* Maximum data size of the module_id/param_id combination. This
* is a multiple of 4 bytes.
*/
u16 reserved;
/* Reserved for backward compatibility. Clients must set this
* field to zero.
*/
} __packed;
#define ASM_STREAM_CMD_SET_ENCDEC_PARAM 0x00010C10
#define ASM_PARAM_ID_ENCDEC_BITRATE 0x00010C13
struct asm_bitrate_param {
u32 bitrate;
/* Maximum supported bitrate. Only the AAC encoder is supported.*/
} __packed;
#define ASM_PARAM_ID_ENCDEC_ENC_CFG_BLK_V2 0x00010DA3
#define ASM_PARAM_ID_AAC_SBR_PS_FLAG 0x00010C63
/* Flag to turn off both SBR and PS processing, if they are
* present in the bitstream.
*/
#define ASM_AAC_SBR_OFF_PS_OFF (2)
/* Flag to turn on SBR but turn off PS processing,if they are
* present in the bitstream.
*/
#define ASM_AAC_SBR_ON_PS_OFF (1)
/* Flag to turn on both SBR and PS processing, if they are
* present in the bitstream (default behavior).
*/
#define ASM_AAC_SBR_ON_PS_ON (0)
/* Structure for an AAC SBR PS processing flag. */
/* Payload of the #ASM_PARAM_ID_AAC_SBR_PS_FLAG parameter in the
* #ASM_STREAM_CMD_SET_ENCDEC_PARAM command.
*/
struct asm_aac_sbr_ps_flag_param {
struct apr_hdr hdr;
struct asm_stream_cmd_set_encdec_param encdec;
struct asm_enc_cfg_blk_param_v2 encblk;
u32 sbr_ps_flag;
/* Control parameter to enable or disable SBR/PS processing in
* the AAC bitstream. Use the following macros to set this field:
* - #ASM_AAC_SBR_OFF_PS_OFF -- Turn off both SBR and PS
* processing, if they are present in the bitstream.
* - #ASM_AAC_SBR_ON_PS_OFF -- Turn on SBR processing, but not PS
* processing, if they are present in the bitstream.
* - #ASM_AAC_SBR_ON_PS_ON -- Turn on both SBR and PS processing,
* if they are present in the bitstream (default behavior).
* - All other values are invalid.
* Changes are applied to the next decoded frame.
*/
} __packed;
#define ASM_PARAM_ID_AAC_DUAL_MONO_MAPPING 0x00010C64
/* First single channel element in a dual mono bitstream.*/
#define ASM_AAC_DUAL_MONO_MAP_SCE_1 (1)
/* Second single channel element in a dual mono bitstream.*/
#define ASM_AAC_DUAL_MONO_MAP_SCE_2 (2)
/* Structure for AAC decoder dual mono channel mapping. */
struct asm_aac_dual_mono_mapping_param {
struct apr_hdr hdr;
struct asm_stream_cmd_set_encdec_param encdec;
u16 left_channel_sce;
u16 right_channel_sce;
} __packed;
#define ASM_STREAM_CMDRSP_GET_PP_PARAMS_V2 0x00010DA4
struct asm_stream_cmdrsp_get_pp_params_v2 {
u32 status;
} __packed;
#define ASM_PARAM_ID_AC3_KARAOKE_MODE 0x00010D73
/* Enumeration for both vocals in a karaoke stream.*/
#define AC3_KARAOKE_MODE_NO_VOCAL (0)
/* Enumeration for only the left vocal in a karaoke stream.*/
#define AC3_KARAOKE_MODE_LEFT_VOCAL (1)
/* Enumeration for only the right vocal in a karaoke stream.*/
#define AC3_KARAOKE_MODE_RIGHT_VOCAL (2)
/* Enumeration for both vocal channels in a karaoke stream.*/
#define AC3_KARAOKE_MODE_BOTH_VOCAL (3)
#define ASM_PARAM_ID_AC3_DRC_MODE 0x00010D74
/* Enumeration for the Custom Analog mode.*/
#define AC3_DRC_MODE_CUSTOM_ANALOG (0)
/* Enumeration for the Custom Digital mode.*/
#define AC3_DRC_MODE_CUSTOM_DIGITAL (1)
/* Enumeration for the Line Out mode (light compression).*/
#define AC3_DRC_MODE_LINE_OUT (2)
/* Enumeration for the RF remodulation mode (heavy compression).*/
#define AC3_DRC_MODE_RF_REMOD (3)
#define ASM_PARAM_ID_AC3_DUAL_MONO_MODE 0x00010D75
/* Enumeration for playing dual mono in stereo mode.*/
#define AC3_DUAL_MONO_MODE_STEREO (0)
/* Enumeration for playing left mono.*/
#define AC3_DUAL_MONO_MODE_LEFT_MONO (1)
/* Enumeration for playing right mono.*/
#define AC3_DUAL_MONO_MODE_RIGHT_MONO (2)
/* Enumeration for mixing both dual mono channels and playing them.*/
#define AC3_DUAL_MONO_MODE_MIXED_MONO (3)
#define ASM_PARAM_ID_AC3_STEREO_DOWNMIX_MODE 0x00010D76
/* Enumeration for using the Downmix mode indicated in the bitstream. */
#define AC3_STEREO_DOWNMIX_MODE_AUTO_DETECT (0)
/* Enumeration for Surround Compatible mode (preserves the
* surround information).
*/
#define AC3_STEREO_DOWNMIX_MODE_LT_RT (1)
/* Enumeration for Mono Compatible mode (if the output is to be
* further downmixed to mono).
*/
#define AC3_STEREO_DOWNMIX_MODE_LO_RO (2)
/* ID of the AC3 PCM scale factor parameter in the
* #ASM_STREAM_CMD_SET_ENCDEC_PARAM command.
*/
#define ASM_PARAM_ID_AC3_PCM_SCALEFACTOR 0x00010D78
/* ID of the AC3 DRC boost scale factor parameter in the
* #ASM_STREAM_CMD_SET_ENCDEC_PARAM command.
*/
#define ASM_PARAM_ID_AC3_DRC_BOOST_SCALEFACTOR 0x00010D79
/* ID of the AC3 DRC cut scale factor parameter in the
* #ASM_STREAM_CMD_SET_ENCDEC_PARAM command.
*/
#define ASM_PARAM_ID_AC3_DRC_CUT_SCALEFACTOR 0x00010D7A
/* Structure for AC3 Generic Parameter. */
/* Payload of the AC3 parameters in the
* #ASM_STREAM_CMD_SET_ENCDEC_PARAM command.
*/
struct asm_ac3_generic_param {
struct apr_hdr hdr;
struct asm_stream_cmd_set_encdec_param encdec;
struct asm_enc_cfg_blk_param_v2 encblk;
u32 generic_parameter;
/* AC3 generic parameter. Select from one of the following
* possible values.
*
* For #ASM_PARAM_ID_AC3_KARAOKE_MODE, supported values are:
* - AC3_KARAOKE_MODE_NO_VOCAL
* - AC3_KARAOKE_MODE_LEFT_VOCAL
* - AC3_KARAOKE_MODE_RIGHT_VOCAL
* - AC3_KARAOKE_MODE_BOTH_VOCAL
*
* For #ASM_PARAM_ID_AC3_DRC_MODE, supported values are:
* - AC3_DRC_MODE_CUSTOM_ANALOG
* - AC3_DRC_MODE_CUSTOM_DIGITAL
* - AC3_DRC_MODE_LINE_OUT
* - AC3_DRC_MODE_RF_REMOD
*
* For #ASM_PARAM_ID_AC3_DUAL_MONO_MODE, supported values are:
* - AC3_DUAL_MONO_MODE_STEREO
* - AC3_DUAL_MONO_MODE_LEFT_MONO
* - AC3_DUAL_MONO_MODE_RIGHT_MONO
* - AC3_DUAL_MONO_MODE_MIXED_MONO
*
* For #ASM_PARAM_ID_AC3_STEREO_DOWNMIX_MODE, supported values are:
* - AC3_STEREO_DOWNMIX_MODE_AUTO_DETECT
* - AC3_STEREO_DOWNMIX_MODE_LT_RT
* - AC3_STEREO_DOWNMIX_MODE_LO_RO
*
* For #ASM_PARAM_ID_AC3_PCM_SCALEFACTOR, supported values are
* 0 to 1 in Q31 format.
*
* For #ASM_PARAM_ID_AC3_DRC_BOOST_SCALEFACTOR, supported values are
* 0 to 1 in Q31 format.
*
* For #ASM_PARAM_ID_AC3_DRC_CUT_SCALEFACTOR, supported values are
* 0 to 1 in Q31 format.
*/
} __packed;
/* Enumeration for Raw mode (no downmixing), which specifies
* that all channels in the bitstream are to be played out as is
* without any downmixing. (Default)
*/
#define WMAPRO_CHANNEL_MASK_RAW (-1)
/* Enumeration for setting the channel mask to 0. The 7.1 mode
* (Home Theater) is assigned.
*/
#define WMAPRO_CHANNEL_MASK_ZERO 0x0000
/* Speaker layout mask for one channel (Home Theater, mono).
* - Speaker front center
*/
#define WMAPRO_CHANNEL_MASK_1_C 0x0004
/* Speaker layout mask for two channels (Home Theater, stereo).
* - Speaker front left
* - Speaker front right
*/
#define WMAPRO_CHANNEL_MASK_2_L_R 0x0003
/* Speaker layout mask for three channels (Home Theater).
* - Speaker front left
* - Speaker front right
* - Speaker front center
*/
#define WMAPRO_CHANNEL_MASK_3_L_C_R 0x0007
/* Speaker layout mask for two channels (stereo).
* - Speaker back left
* - Speaker back right
*/
#define WMAPRO_CHANNEL_MASK_2_Bl_Br 0x0030
/* Speaker layout mask for four channels.
* - Speaker front left
* - Speaker front right
* - Speaker back left
* - Speaker back right
*/
#define WMAPRO_CHANNEL_MASK_4_L_R_Bl_Br 0x0033
/* Speaker layout mask for four channels (Home Theater).
* - Speaker front left
* - Speaker front right
* - Speaker front center
* - Speaker back center
*/
#define WMAPRO_CHANNEL_MASK_4_L_R_C_Bc_HT 0x0107
/* Speaker layout mask for five channels.
* - Speaker front left
* - Speaker front right
* - Speaker front center
* - Speaker back left
* - Speaker back right
*/
#define WMAPRO_CHANNEL_MASK_5_L_C_R_Bl_Br 0x0037
/* Speaker layout mask for five channels (5 mode, Home Theater).
* - Speaker front left
* - Speaker front right
* - Speaker front center
* - Speaker side left
* - Speaker side right
*/
#define WMAPRO_CHANNEL_MASK_5_L_C_R_Sl_Sr_HT 0x0607
/* Speaker layout mask for six channels (5.1 mode).
* - Speaker front left
* - Speaker front right
* - Speaker front center
* - Speaker low frequency
* - Speaker back left
* - Speaker back right
*/
#define WMAPRO_CHANNEL_MASK_5DOT1_L_C_R_Bl_Br_SLF 0x003F
/* Speaker layout mask for six channels (5.1 mode, Home Theater).
* - Speaker front left
* - Speaker front right
* - Speaker front center
* - Speaker low frequency
* - Speaker side left
* - Speaker side right
*/
#define WMAPRO_CHANNEL_MASK_5DOT1_L_C_R_Sl_Sr_SLF_HT 0x060F
/* Speaker layout mask for six channels (5.1 mode, no LFE).
* - Speaker front left
* - Speaker front right
* - Speaker front center
* - Speaker back left
* - Speaker back right
* - Speaker back center
*/
#define WMAPRO_CHANNEL_MASK_5DOT1_L_C_R_Bl_Br_Bc 0x0137
/* Speaker layout mask for six channels (5.1 mode, Home Theater,
* no LFE).
* - Speaker front left
* - Speaker front right
* - Speaker front center
* - Speaker back center
* - Speaker side left
* - Speaker side right
*/
#define WMAPRO_CHANNEL_MASK_5DOT1_L_C_R_Sl_Sr_Bc_HT 0x0707
/* Speaker layout mask for seven channels (6.1 mode).
* - Speaker front left
* - Speaker front right
* - Speaker front center
* - Speaker low frequency
* - Speaker back left
* - Speaker back right
* - Speaker back center
*/
#define WMAPRO_CHANNEL_MASK_6DOT1_L_C_R_Bl_Br_Bc_SLF 0x013F
/* Speaker layout mask for seven channels (6.1 mode, Home
* Theater).
* - Speaker front left
* - Speaker front right
* - Speaker front center
* - Speaker low frequency
* - Speaker back center
* - Speaker side left
* - Speaker side right
*/
#define WMAPRO_CHANNEL_MASK_6DOT1_L_C_R_Sl_Sr_Bc_SLF_HT 0x070F
/* Speaker layout mask for seven channels (6.1 mode, no LFE).
* - Speaker front left
* - Speaker front right
* - Speaker front center
* - Speaker back left
* - Speaker back right
* - Speaker front left of center
* - Speaker front right of center
*/
#define WMAPRO_CHANNEL_MASK_6DOT1_L_C_R_Bl_Br_SFLOC_SFROC 0x00F7
/* Speaker layout mask for seven channels (6.1 mode, Home
* Theater, no LFE).
* - Speaker front left
* - Speaker front right
* - Speaker front center
* - Speaker side left
* - Speaker side right
* - Speaker front left of center
* - Speaker front right of center
*/
#define WMAPRO_CHANNEL_MASK_6DOT1_L_C_R_Sl_Sr_SFLOC_SFROC_HT 0x0637
/* Speaker layout mask for eight channels (7.1 mode).
* - Speaker front left
* - Speaker front right
* - Speaker front center
* - Speaker back left
* - Speaker back right
* - Speaker low frequency
* - Speaker front left of center
* - Speaker front right of center
*/
#define WMAPRO_CHANNEL_MASK_7DOT1_L_C_R_Bl_Br_SLF_SFLOC_SFROC \
0x00FF
/* Speaker layout mask for eight channels (7.1 mode, Home Theater).
* - Speaker front left
* - Speaker front right
* - Speaker front center
* - Speaker side left
* - Speaker side right
* - Speaker low frequency
* - Speaker front left of center
* - Speaker front right of center
*
*/
#define WMAPRO_CHANNEL_MASK_7DOT1_L_C_R_Sl_Sr_SLF_SFLOC_SFROC_HT \
0x063F
#define ASM_PARAM_ID_DEC_OUTPUT_CHAN_MAP 0x00010D82
/* Maximum number of decoder output channels.*/
#define MAX_CHAN_MAP_CHANNELS 16
/* Structure for decoder output channel mapping. */
/* Payload of the #ASM_PARAM_ID_DEC_OUTPUT_CHAN_MAP parameter in the
* #ASM_STREAM_CMD_SET_ENCDEC_PARAM command.
*/
struct asm_dec_out_chan_map_param {
struct apr_hdr hdr;
struct asm_stream_cmd_set_encdec_param encdec;
u32 num_channels;
/* Number of decoder output channels.
* Supported values: 0 to #MAX_CHAN_MAP_CHANNELS
*
* A value of 0 indicates native channel mapping, which is valid
* only for NT mode. This means the output of the decoder is to be
* preserved as is.
*/
u8 channel_mapping[MAX_CHAN_MAP_CHANNELS];
} __packed;
#define ASM_STREAM_CMD_OPEN_WRITE_COMPRESSED 0x00010D84
/* Bitmask for the IEC 61937 enable flag.*/
#define ASM_BIT_MASK_IEC_61937_STREAM_FLAG (0x00000001UL)
/* Shift value for the IEC 61937 enable flag.*/
#define ASM_SHIFT_IEC_61937_STREAM_FLAG 0
/* Bitmask for the IEC 60958 enable flag.*/
#define ASM_BIT_MASK_IEC_60958_STREAM_FLAG (0x00000002UL)
/* Shift value for the IEC 60958 enable flag.*/
#define ASM_SHIFT_IEC_60958_STREAM_FLAG 1
/* Payload format for open write compressed comand */
/* Payload format for the #ASM_STREAM_CMD_OPEN_WRITE_COMPRESSED
* comand, which opens a stream for a given session ID and stream ID
* to be rendered in the compressed format.
*/
struct asm_stream_cmd_open_write_compressed {
struct apr_hdr hdr;
u32 flags;
/* Mode flags that configure the stream for a specific format.
* Supported values:
* - Bit 0 -- IEC 61937 compatibility
* - 0 -- Stream is not in IEC 61937 format
* - 1 -- Stream is in IEC 61937 format
* - Bit 1 -- IEC 60958 compatibility
* - 0 -- Stream is not in IEC 60958 format
* - 1 -- Stream is in IEC 60958 format
* - Bits 2 to 31 -- 0 (Reserved)
*
* For the same stream, bit 0 cannot be set to 0 and bit 1 cannot
* be set to 1. A compressed stream connot have IEC 60958
* packetization applied without IEC 61937 packetization.
* @note1hang Currently, IEC 60958 packetized input streams are not
* supported.
*/
u32 fmt_id;
/* Specifies the media type of the HDMI stream to be opened.
* Supported values:
* - #ASM_MEDIA_FMT_AC3_DEC
* - #ASM_MEDIA_FMT_EAC3_DEC
* - #ASM_MEDIA_FMT_DTS
* - #ASM_MEDIA_FMT_ATRAC
* - #ASM_MEDIA_FMT_MAT
*
* @note1hang This field must be set to a valid media type even if
* IEC 61937 packetization is not performed by the aDSP.
*/
} __packed;
/*
Indicates the number of samples per channel to be removed from the
beginning of the stream.
*/
#define ASM_DATA_CMD_REMOVE_INITIAL_SILENCE 0x00010D67
/*
Indicates the number of samples per channel to be removed from
the end of the stream.
*/
#define ASM_DATA_CMD_REMOVE_TRAILING_SILENCE 0x00010D68
struct asm_data_cmd_remove_silence {
struct apr_hdr hdr;
u32 num_samples_to_remove;
/**< Number of samples per channel to be removed.
@values 0 to (2@sscr{32}-1) */
} __packed;
#define ASM_STREAM_CMD_OPEN_READ_COMPRESSED 0x00010D95
struct asm_stream_cmd_open_read_compressed {
struct apr_hdr hdr;
u32 mode_flags;
/* Mode flags that indicate whether meta information per encoded
* frame is to be provided.
* Supported values for bit 4:
* - 0 -- Return data buffer contains all encoded frames only; it does
* not contain frame metadata.
* - 1 -- Return data buffer contains an array of metadata and encoded
* frames.
* - Use #ASM_BIT_MASK_META_INFO_FLAG to set the bitmask and
* #ASM_SHIFT_META_INFO_FLAG to set the shift value for this bit.
* All other bits are reserved; clients must set them to zero.
*/
u32 frames_per_buf;
/* Indicates the number of frames that need to be returned per
* read buffer
* Supported values: should be greater than 0
*/
} __packed;
/* adsp_asm_stream_commands.h*/
/* adsp_asm_api.h (no changes)*/
#define ASM_STREAM_POSTPROCOPO_ID_DEFAULT \
0x00010BE4
#define ASM_STREAM_POSTPROCOPO_ID_PEAKMETER \
0x00010D83
#define ASM_STREAM_POSTPROCOPO_ID_NONE \
0x00010C68
#define ASM_STREAM_POSTPROCOPO_ID_MCH_PEAK_VOL \
0x00010D8B
#define ASM_STREAM_PREPROCOPO_ID_DEFAULT \
ASM_STREAM_POSTPROCOPO_ID_DEFAULT
#define ASM_STREAM_PREPROCOPO_ID_NONE \
ASM_STREAM_POSTPROCOPO_ID_NONE
#define ADM_CMD_COPP_OPENOPOLOGY_ID_NONE_AUDIO_COPP \
0x00010312
#define ADM_CMD_COPP_OPENOPOLOGY_ID_SPEAKER_MONO_AUDIO_COPP \
0x00010313
#define ADM_CMD_COPP_OPENOPOLOGY_ID_SPEAKER_STEREO_AUDIO_COPP \
0x00010314
#define ADM_CMD_COPP_OPENOPOLOGY_ID_SPEAKER_STEREO_IIR_AUDIO_COPP\
0x00010704
#define ADM_CMD_COPP_OPENOPOLOGY_ID_SPEAKER_MONO_AUDIO_COPP_MBDRCV2\
0x0001070D
#define ADM_CMD_COPP_OPENOPOLOGY_ID_SPEAKER_STEREO_AUDIO_COPP_MBDRCV2\
0x0001070E
#define ADM_CMD_COPP_OPENOPOLOGY_ID_SPEAKER_STEREO_IIR_AUDIO_COPP_MBDRCV2\
0x0001070F
#define ADM_CMD_COPP_OPENOPOLOGY_ID_SPEAKER_MCH_PEAK_VOL \
0x0001031B
#define ADM_CMD_COPP_OPENOPOLOGY_ID_MIC_MONO_AUDIO_COPP 0x00010315
#define ADM_CMD_COPP_OPENOPOLOGY_ID_MIC_STEREO_AUDIO_COPP 0x00010316
#define AUDPROC_COPPOPOLOGY_ID_MCHAN_IIR_AUDIO 0x00010715
#define ADM_CMD_COPP_OPENOPOLOGY_ID_DEFAULT_AUDIO_COPP 0x00010BE3
#define ADM_CMD_COPP_OPENOPOLOGY_ID_PEAKMETER_AUDIO_COPP 0x00010317
#define AUDPROC_MODULE_ID_AIG 0x00010716
#define AUDPROC_PARAM_ID_AIG_ENABLE 0x00010717
#define AUDPROC_PARAM_ID_AIG_CONFIG 0x00010718
struct Audio_AigParam {
uint16_t mode;
/*< Mode word for enabling AIG/SIG mode .
* Byte offset: 0
*/
int16_t staticGainL16Q12;
/*< Static input gain when aigMode is set to 1.
* Byte offset: 2
*/
int16_t initialGainDBL16Q7;
/*<Initial value that the adaptive gain update starts from dB
* Q7 Byte offset: 4
*/
int16_t idealRMSDBL16Q7;
/*<Average RMS level that AIG attempts to achieve Q8.7
* Byte offset: 6
*/
int32_t noiseGateL32;
/*Threshold below which signal is considered as noise and AIG
* Byte offset: 8
*/
int32_t minGainL32Q15;
/*Minimum gain that can be provided by AIG Q16.15
* Byte offset: 12
*/
int32_t maxGainL32Q15;
/*Maximum gain that can be provided by AIG Q16.15
* Byte offset: 16
*/
uint32_t gainAtRtUL32Q31;
/*Attack/release time for AIG update Q1.31
* Byte offset: 20
*/
uint32_t longGainAtRtUL32Q31;
/*Long attack/release time while updating gain for
* noise/silence Q1.31 Byte offset: 24
*/
uint32_t rmsTavUL32Q32;
/* RMS smoothing time constant used for long-term RMS estimate
* Q0.32 Byte offset: 28
*/
uint32_t gainUpdateStartTimMsUL32Q0;
/* The waiting time before which AIG starts to apply adaptive
* gain update Q32.0 Byte offset: 32
*/
} __packed;
#define ADM_MODULE_ID_EANS 0x00010C4A
#define ADM_PARAM_ID_EANS_ENABLE 0x00010C4B
#define ADM_PARAM_ID_EANS_PARAMS 0x00010C4C
struct adm_eans_enable {
uint32_t enable_flag;
/*< Specifies whether EANS is disabled (0) or enabled
* (nonzero).
* This is supported only for sampling rates of 8, 12, 16, 24, 32,
* and 48 kHz. It is not supported for sampling rates of 11.025,
* 22.05, or 44.1 kHz.
*/
} __packed;
struct adm_eans_params {
int16_t eans_mode;
/*< Mode word for enabling/disabling submodules.
* Byte offset: 0
*/
int16_t eans_input_gain;
/*< Q2.13 input gain to the EANS module.
* Byte offset: 2
*/
int16_t eans_output_gain;
/*< Q2.13 output gain to the EANS module.
* Byte offset: 4
*/
int16_t eansarget_ns;
/*< Target noise suppression level in dB.
* Byte offset: 6
*/
int16_t eans_s_alpha;
/*< Q3.12 over-subtraction factor for stationary noise
* suppression.
* Byte offset: 8
*/
int16_t eans_n_alpha;
/* < Q3.12 over-subtraction factor for nonstationary noise
* suppression.
* Byte offset: 10
*/
int16_t eans_n_alphamax;
/*< Q3.12 maximum over-subtraction factor for nonstationary
* noise suppression.
* Byte offset: 12
*/
int16_t eans_e_alpha;
/*< Q15 scaling factor for excess noise suppression.
* Byte offset: 14
*/
int16_t eans_ns_snrmax;
/*< Upper boundary in dB for SNR estimation.
* Byte offset: 16
*/
int16_t eans_sns_block;
/*< Quarter block size for stationary noise suppression.
* Byte offset: 18
*/
int16_t eans_ns_i;
/*< Initialization block size for noise suppression.
* Byte offset: 20
*/
int16_t eans_np_scale;
/*< Power scale factor for nonstationary noise update.
* Byte offset: 22
*/
int16_t eans_n_lambda;
/*< Smoothing factor for higher level nonstationary noise
* update.
* Byte offset: 24
*/
int16_t eans_n_lambdaf;
/*< Medium averaging factor for noise update.
* Byte offset: 26
*/
int16_t eans_gs_bias;
/*< Bias factor in dB for gain calculation.
* Byte offset: 28
*/
int16_t eans_gs_max;
/*< SNR lower boundary in dB for aggressive gain calculation.
* Byte offset: 30
*/
int16_t eans_s_alpha_hb;
/*< Q3.12 over-subtraction factor for high-band stationary
* noise suppression.
* Byte offset: 32
*/
int16_t eans_n_alphamax_hb;
/*< Q3.12 maximum over-subtraction factor for high-band
* nonstationary noise suppression.
* Byte offset: 34
*/
int16_t eans_e_alpha_hb;
/*< Q15 scaling factor for high-band excess noise suppression.
* Byte offset: 36
*/
int16_t eans_n_lambda0;
/*< Smoothing factor for nonstationary noise update during
* speech activity.
* Byte offset: 38
*/
int16_t thresh;
/*< Threshold for generating a binary VAD decision.
* Byte offset: 40
*/
int16_t pwr_scale;
/*< Indirect lower boundary of the noise level estimate.
* Byte offset: 42
*/
int16_t hangover_max;
/*< Avoids mid-speech clipping and reliably detects weak speech
* bursts at the end of speech activity.
* Byte offset: 44
*/
int16_t alpha_snr;
/*< Controls responsiveness of the VAD.
* Byte offset: 46
*/
int16_t snr_diff_max;
/*< Maximum SNR difference. Decreasing this parameter value may
* help in making correct decisions during abrupt changes; however,
* decreasing too much may increase false alarms during long
* pauses/silences.
* Byte offset: 48
*/
int16_t snr_diff_min;
/*< Minimum SNR difference. Decreasing this parameter value may
* help in making correct decisions during abrupt changes; however,
* decreasing too much may increase false alarms during long
* pauses/silences.
* Byte offset: 50
*/
int16_t init_length;
/*< Defines the number of frames for which a noise level
* estimate is set to a fixed value.
* Byte offset: 52
*/
int16_t max_val;
/*< Defines the upper limit of the noise level.
* Byte offset: 54
*/
int16_t init_bound;
/*< Defines the initial bounding value for the noise level
* estimate. This is used during the initial segment defined by the
* init_length parameter.
* Byte offset: 56
*/
int16_t reset_bound;
/*< Reset boundary for noise tracking.
* Byte offset: 58
*/
int16_t avar_scale;
/*< Defines the bias factor in noise estimation.
* Byte offset: 60
*/
int16_t sub_nc;
/*< Defines the window length for noise estimation.
* Byte offset: 62
*/
int16_t spow_min;
/*< Defines the minimum signal power required to update the
* boundaries for the noise floor estimate.
* Byte offset: 64
*/
int16_t eans_gs_fast;
/*< Fast smoothing factor for postprocessor gain.
* Byte offset: 66
*/
int16_t eans_gs_med;
/*< Medium smoothing factor for postprocessor gain.
* Byte offset: 68
*/
int16_t eans_gs_slow;
/*< Slow smoothing factor for postprocessor gain.
* Byte offset: 70
*/
int16_t eans_swb_salpha;
/*< Q3.12 super wideband aggressiveness factor for stationary
* noise suppression.
* Byte offset: 72
*/
int16_t eans_swb_nalpha;
/*< Q3.12 super wideband aggressiveness factor for
* nonstationary noise suppression.
* Byte offset: 74
*/
} __packed;
#define ADM_MODULE_IDX_MIC_GAIN_CTRL 0x00010C35
/* @addtogroup audio_pp_param_ids
* ID of the Tx mic gain control parameter used by the
* #ADM_MODULE_IDX_MIC_GAIN_CTRL module.
* @messagepayload
* @structure{admx_mic_gain}
* @tablespace
* @inputtable{Audio_Postproc_ADM_PARAM_IDX_MIC_GAIN.tex}
*/
#define ADM_PARAM_IDX_MIC_GAIN 0x00010C36
/* Structure for a Tx mic gain parameter for the mic gain
* control module.
*/
/* @brief Payload of the #ADM_PARAM_IDX_MIC_GAIN parameter in the
* Tx Mic Gain Control module.
*/
struct admx_mic_gain {
uint16_t tx_mic_gain;
/*< Linear gain in Q13 format. */
uint16_t reserved;
/*< Clients must set this field to zero. */
} __packed;
/* end_addtogroup audio_pp_param_ids */
/* @ingroup audio_pp_module_ids
* ID of the Rx Codec Gain Control module.
*
* This module supports the following parameter ID:
* - #ADM_PARAM_ID_RX_CODEC_GAIN
*/
#define ADM_MODULE_ID_RX_CODEC_GAIN_CTRL 0x00010C37
/* @addtogroup audio_pp_param_ids
* ID of the Rx codec gain control parameter used by the
* #ADM_MODULE_ID_RX_CODEC_GAIN_CTRL module.
*
* @messagepayload
* @structure{adm_rx_codec_gain}
* @tablespace
* @inputtable{Audio_Postproc_ADM_PARAM_ID_RX_CODEC_GAIN.tex}
*/
#define ADM_PARAM_ID_RX_CODEC_GAIN 0x00010C38
/* Structure for the Rx common codec gain control module. */
/* @brief Payload of the #ADM_PARAM_ID_RX_CODEC_GAIN parameter
* in the Rx Codec Gain Control module.
*/
struct adm_rx_codec_gain {
uint16_t rx_codec_gain;
/*< Linear gain in Q13 format. */
uint16_t reserved;
/*< Clients must set this field to zero.*/
} __packed;
/* end_addtogroup audio_pp_param_ids */
/* @ingroup audio_pp_module_ids
* ID of the HPF Tuning Filter module on the Tx path.
* This module supports the following parameter IDs:
* - #ADM_PARAM_ID_HPF_IIRX_FILTER_ENABLE_CONFIG
* - #ADM_PARAM_ID_HPF_IIRX_FILTER_PRE_GAIN
* - #ADM_PARAM_ID_HPF_IIRX_FILTER_CONFIG_PARAMS
*/
#define ADM_MODULE_ID_HPF_IIRX_FILTER 0x00010C3D
/* @addtogroup audio_pp_param_ids */
/* ID of the Tx HPF IIR filter enable parameter used by the
* #ADM_MODULE_ID_HPF_IIRX_FILTER module.
* @parspace Message payload
* @structure{adm_hpfx_iir_filter_enable_cfg}
* @tablespace
* @inputtable{Audio_Postproc_ADM_PARAM_ID_HPF_IIRX_FILTER_ENABLE_CONFIG.tex}
*/
#define ADM_PARAM_ID_HPF_IIRX_FILTER_ENABLE_CONFIG 0x00010C3E
/* ID of the Tx HPF IIR filter pregain parameter used by the
* #ADM_MODULE_ID_HPF_IIRX_FILTER module.
* @parspace Message payload
* @structure{adm_hpfx_iir_filter_pre_gain}
* @tablespace
* @inputtable{Audio_Postproc_ADM_PARAM_ID_HPF_IIRX_FILTER_PRE_GAIN.tex}
*/
#define ADM_PARAM_ID_HPF_IIRX_FILTER_PRE_GAIN 0x00010C3F
/* ID of the Tx HPF IIR filter configuration parameters used by the
* #ADM_MODULE_ID_HPF_IIRX_FILTER module.
* @parspace Message payload
* @structure{adm_hpfx_iir_filter_cfg_params}
* @tablespace
* @inputtable{Audio_Postproc_ADM_PARAM_ID_HPF_IIRX_FILTER_CONFIG_PA
* RAMS.tex}
*/
#define ADM_PARAM_ID_HPF_IIRX_FILTER_CONFIG_PARAMS 0x00010C40
/* Structure for enabling a configuration parameter for
* the HPF IIR tuning filter module on the Tx path.
*/
/* @brief Payload of the #ADM_PARAM_ID_HPF_IIRX_FILTER_ENABLE_CONFIG
* parameter in the Tx path HPF Tuning Filter module.
*/
struct adm_hpfx_iir_filter_enable_cfg {
uint32_t enable_flag;
/*< Specifies whether the HPF tuning filter is disabled (0) or
* enabled (nonzero).
*/
} __packed;
/* Structure for the pregain parameter for the HPF
IIR tuning filter module on the Tx path. */
/* @brief Payload of the #ADM_PARAM_ID_HPF_IIRX_FILTER_PRE_GAIN parameter
* in the Tx path HPF Tuning Filter module.
*/
struct adm_hpfx_iir_filter_pre_gain {
uint16_t pre_gain;
/*< Linear gain in Q13 format. */
uint16_t reserved;
/*< Clients must set this field to zero.*/
} __packed;
/* Structure for the configuration parameter for the
HPF IIR tuning filter module on the Tx path. */
/* @brief Payload of the #ADM_PARAM_ID_HPF_IIRX_FILTER_CONFIG_PARAMS
* parameters in the Tx path HPF Tuning Filter module. \n
* \n
* This structure is followed by tuning filter coefficients as follows: \n
* - Sequence of int32_t FilterCoeffs.
* Each band has five coefficients, each in int32_t format in the order of
* b0, b1, b2, a1, a2.
* - Sequence of int16_t NumShiftFactor.
* One int16_t per band. The numerator shift factor is related to the Q
* factor of the filter coefficients.
* - Sequence of uint16_t PanSetting.
* One uint16_t for each band to indicate application of the filter to
* left (0), right (1), or both (2) channels.
*/
struct adm_hpfx_iir_filter_cfg_params {
uint16_t num_biquad_stages;
/*< Number of bands.
* Supported values: 0 to 20
*/
uint16_t reserved;
/*< Clients must set this field to zero.*/
} __packed;
/* end_addtogroup audio_pp_module_ids */
/* @addtogroup audio_pp_module_ids */
/* ID of the Tx path IIR Tuning Filter module.
* This module supports the following parameter IDs:
* - #ADM_PARAM_IDX_IIR_FILTER_ENABLE_CONFIG
*/
#define ADM_MODULE_IDX_IIR_FILTER 0x00010C41
/* ID of the Rx path IIR Tuning Filter module for the left channel.
* The parameter IDs of the IIR tuning filter module
* (#ASM_MODULE_ID_IIRUNING_FILTER) are used for the left IIR Rx tuning
* filter.
*
* Pan parameters are not required for this per-channel IIR filter; the pan
* parameters are ignored by this module.
*/
#define ADM_MODULE_ID_LEFT_IIRUNING_FILTER 0x00010705
/* ID of the the Rx path IIR Tuning Filter module for the right
* channel.
* The parameter IDs of the IIR tuning filter module
* (#ASM_MODULE_ID_IIRUNING_FILTER) are used for the right IIR Rx
* tuning filter.
*
* Pan parameters are not required for this per-channel IIR filter;
* the pan parameters are ignored by this module.
*/
#define ADM_MODULE_ID_RIGHT_IIRUNING_FILTER 0x00010706
/* end_addtogroup audio_pp_module_ids */
/* @addtogroup audio_pp_param_ids */
/* ID of the Tx IIR filter enable parameter used by the
* #ADM_MODULE_IDX_IIR_FILTER module.
* @parspace Message payload
* @structure{admx_iir_filter_enable_cfg}
* @tablespace
* @inputtable{Audio_Postproc_ADM_PARAM_IDX_IIR_FILTER_ENABLE_CONFIG.tex}
*/
#define ADM_PARAM_IDX_IIR_FILTER_ENABLE_CONFIG 0x00010C42
/* ID of the Tx IIR filter pregain parameter used by the
* #ADM_MODULE_IDX_IIR_FILTER module.
* @parspace Message payload
* @structure{admx_iir_filter_pre_gain}
* @tablespace
* @inputtable{Audio_Postproc_ADM_PARAM_IDX_IIR_FILTER_PRE_GAIN.tex}
*/
#define ADM_PARAM_IDX_IIR_FILTER_PRE_GAIN 0x00010C43
/* ID of the Tx IIR filter configuration parameters used by the
* #ADM_MODULE_IDX_IIR_FILTER module.
* @parspace Message payload
* @structure{admx_iir_filter_cfg_params}
* @tablespace
* @inputtable{Audio_Postproc_ADM_PARAM_IDX_IIR_FILTER_CONFIG_PARAMS.tex}
*/
#define ADM_PARAM_IDX_IIR_FILTER_CONFIG_PARAMS 0x00010C44
/* Structure for enabling the configuration parameter for the
* IIR filter module on the Tx path.
*/
/* @brief Payload of the #ADM_PARAM_IDX_IIR_FILTER_ENABLE_CONFIG
* parameter in the Tx Path IIR Tuning Filter module.
*/
struct admx_iir_filter_enable_cfg {
uint32_t enable_flag;
/*< Specifies whether the IIR tuning filter is disabled (0) or
* enabled (nonzero).
*/
} __packed;
/* Structure for the pregain parameter for the
* IIR filter module on the Tx path.
*/
/* @brief Payload of the #ADM_PARAM_IDX_IIR_FILTER_PRE_GAIN
* parameter in the Tx Path IIR Tuning Filter module.
*/
struct admx_iir_filter_pre_gain {
uint16_t pre_gain;
/*< Linear gain in Q13 format. */
uint16_t reserved;
/*< Clients must set this field to zero.*/
} __packed;
/* Structure for the configuration parameter for the
* IIR filter module on the Tx path.
*/
/* @brief Payload of the #ADM_PARAM_IDX_IIR_FILTER_CONFIG_PARAMS
* parameter in the Tx Path IIR Tuning Filter module. \n
* \n
* This structure is followed by the HPF IIR filter coefficients on
* the Tx path as follows: \n
* - Sequence of int32_t ulFilterCoeffs. Each band has five
* coefficients, each in int32_t format in the order of b0, b1, b2,
* a1, a2.
* - Sequence of int16_t sNumShiftFactor. One int16_t per band. The
* numerator shift factor is related to the Q factor of the filter
* coefficients.
* - Sequence of uint16_t usPanSetting. One uint16_t for each band
* to indicate if the filter is applied to left (0), right (1), or
* both (2) channels.
*/
struct admx_iir_filter_cfg_params {
uint16_t num_biquad_stages;
/*< Number of bands.
* Supported values: 0 to 20
*/
uint16_t reserved;
/*< Clients must set this field to zero.*/
} __packed;
/* end_addtogroup audio_pp_module_ids */
/* @ingroup audio_pp_module_ids
* ID of the QEnsemble module.
* This module supports the following parameter IDs:
* - #ADM_PARAM_ID_QENSEMBLE_ENABLE
* - #ADM_PARAM_ID_QENSEMBLE_BACKGAIN
* - #ADM_PARAM_ID_QENSEMBLE_SET_NEW_ANGLE
*/
#define ADM_MODULE_ID_QENSEMBLE 0x00010C59
/* @addtogroup audio_pp_param_ids */
/* ID of the QEnsemble enable parameter used by the
* #ADM_MODULE_ID_QENSEMBLE module.
* @messagepayload
* @structure{adm_qensemble_enable}
* @tablespace
* @inputtable{Audio_Postproc_ADM_PARAM_ID_QENSEMBLE_ENABLE.tex}
*/
#define ADM_PARAM_ID_QENSEMBLE_ENABLE 0x00010C60
/* ID of the QEnsemble back gain parameter used by the
* #ADM_MODULE_ID_QENSEMBLE module.
* @messagepayload
* @structure{adm_qensemble_param_backgain}
* @tablespace
* @inputtable{Audio_Postproc_ADM_PARAM_ID_QENSEMBLE_BACKGAIN.tex}
*/
#define ADM_PARAM_ID_QENSEMBLE_BACKGAIN 0x00010C61
/* ID of the QEnsemble new angle parameter used by the
* #ADM_MODULE_ID_QENSEMBLE module.
* @messagepayload
* @structure{adm_qensemble_param_set_new_angle}
* @tablespace
* @inputtable{Audio_Postproc_ADM_PARAM_ID_QENSEMBLE_SET_NEW_ANGLE.tex}
*/
#define ADM_PARAM_ID_QENSEMBLE_SET_NEW_ANGLE 0x00010C62
/* Structure for enabling the configuration parameter for the
* QEnsemble module.
*/
/* @brief Payload of the #ADM_PARAM_ID_QENSEMBLE_ENABLE
* parameter used by the QEnsemble module.
*/
struct adm_qensemble_enable {
uint32_t enable_flag;
/*< Specifies whether the QEnsemble module is disabled (0) or enabled
* (nonzero).
*/
} __packed;
/* Structure for the background gain for the QEnsemble module. */
/* @brief Payload of the #ADM_PARAM_ID_QENSEMBLE_BACKGAIN
* parameter used by
* the QEnsemble module.
*/
struct adm_qensemble_param_backgain {
int16_t back_gain;
/*< Linear gain in Q15 format.
* Supported values: 0 to 32767
*/
uint16_t reserved;
/*< Clients must set this field to zero.*/
} __packed;
/* Structure for setting a new angle for the QEnsemble module. */
/* @brief Payload of the #ADM_PARAM_ID_QENSEMBLE_SET_NEW_ANGLE
* parameter used
* by the QEnsemble module.
*/
struct adm_qensemble_param_set_new_angle {
int16_t new_angle;
/*< New angle in degrees.
* Supported values: 0 to 359
*/
int16_t time_ms;
/*< Transition time in milliseconds to set the new angle.
* Supported values: 0 to 32767
*/
} __packed;
/* end_addtogroup audio_pp_module_ids */
/* @ingroup audio_pp_module_ids
* ID of the Volume Control module pre/postprocessing block.
* This module supports the following parameter IDs:
* - #ASM_PARAM_ID_VOL_CTRL_MASTER_GAIN
* - #ASM_PARAM_ID_VOL_CTRL_LR_CHANNEL_GAIN
* - #ASM_PARAM_ID_VOL_CTRL_MUTE_CONFIG
* - #ASM_PARAM_ID_SOFT_VOL_STEPPING_PARAMETERS
* - #ASM_PARAM_ID_SOFT_PAUSE_PARAMETERS
* - #ASM_PARAM_ID_MULTICHANNEL_GAIN
* - #ASM_PARAM_ID_MULTICHANNEL_MUTE
*/
#define ASM_MODULE_ID_VOL_CTRL 0x00010BFE
/* @addtogroup audio_pp_param_ids */
/* ID of the master gain parameter used by the #ASM_MODULE_ID_VOL_CTRL
* module.
* @messagepayload
* @structure{asm_volume_ctrl_master_gain}
* @tablespace
* @inputtable{Audio_Postproc_ASM_PARAM_ID_VOL_CTRL_MASTER_GAIN.tex}
*/
#define ASM_PARAM_ID_VOL_CTRL_MASTER_GAIN 0x00010BFF
/* ID of the left/right channel gain parameter used by the
* #ASM_MODULE_ID_VOL_CTRL module.
* @messagepayload
* @structure{asm_volume_ctrl_lr_chan_gain}
* @tablespace
* @inputtable{Audio_Postproc_ASM_PARAM_ID_VOL_CTRL_LR_CHANNEL_GAIN.tex}
*/
#define ASM_PARAM_ID_VOL_CTRL_LR_CHANNEL_GAIN 0x00010C00
/* ID of the mute configuration parameter used by the
* #ASM_MODULE_ID_VOL_CTRL module.
* @messagepayload
* @structure{asm_volume_ctrl_mute_config}
* @tablespace
* @inputtable{Audio_Postproc_ASM_PARAM_ID_VOL_CTRL_MUTE_CONFIG.tex}
*/
#define ASM_PARAM_ID_VOL_CTRL_MUTE_CONFIG 0x00010C01
/* ID of the soft stepping volume parameters used by the
* #ASM_MODULE_ID_VOL_CTRL module.
* @messagepayload
* @structure{asm_soft_step_volume_params}
* @tablespace
* @inputtable{Audio_Postproc_ASM_PARAM_ID_SOFT_VOL_STEPPING_PARAMET
* ERS.tex}
*/
#define ASM_PARAM_ID_SOFT_VOL_STEPPING_PARAMETERS 0x00010C29
/* ID of the soft pause parameters used by the #ASM_MODULE_ID_VOL_CTRL
* module.
*/
#define ASM_PARAM_ID_SOFT_PAUSE_PARAMETERS 0x00010D6A
/* ID of the multiple-channel volume control parameters used by the
* #ASM_MODULE_ID_VOL_CTRL module.
*/
#define ASM_PARAM_ID_MULTICHANNEL_GAIN 0x00010713
/* ID of the multiple-channel mute configuration parameters used by the
* #ASM_MODULE_ID_VOL_CTRL module.
*/
#define ASM_PARAM_ID_MULTICHANNEL_MUTE 0x00010714
/* Structure for the master gain parameter for a volume control
* module.
*/
/* @brief Payload of the #ASM_PARAM_ID_VOL_CTRL_MASTER_GAIN
* parameter used by the Volume Control module.
*/
struct asm_volume_ctrl_master_gain {
struct apr_hdr hdr;
struct asm_stream_cmd_set_pp_params_v2 param;
struct asm_stream_param_data_v2 data;
uint16_t master_gain;
/*< Linear gain in Q13 format. */
uint16_t reserved;
/*< Clients must set this field to zero.
*/
} __packed;
/* Structure for the left/right channel gain parameter for a
* volume control module.
*/
/* @brief Payload of the #ASM_PARAM_ID_VOL_CTRL_LR_CHANNEL_GAIN
* parameters used by the Volume Control module.
*/
struct asm_volume_ctrl_lr_chan_gain {
struct apr_hdr hdr;
struct asm_stream_cmd_set_pp_params_v2 param;
struct asm_stream_param_data_v2 data;
uint16_t l_chan_gain;
/*< Linear gain in Q13 format for the left channel. */
uint16_t r_chan_gain;
/*< Linear gain in Q13 format for the right channel.*/
} __packed;
/* Structure for the mute configuration parameter for a
volume control module. */
/* @brief Payload of the #ASM_PARAM_ID_VOL_CTRL_MUTE_CONFIG
* parameter used by the Volume Control module.
*/
struct asm_volume_ctrl_mute_config {
struct apr_hdr hdr;
struct asm_stream_cmd_set_pp_params_v2 param;
struct asm_stream_param_data_v2 data;
uint32_t mute_flag;
/*< Specifies whether mute is disabled (0) or enabled (nonzero).*/
} __packed;
/*
* Supported parameters for a soft stepping linear ramping curve.
*/
#define ASM_PARAM_SVC_RAMPINGCURVE_LINEAR 0
/*
* Exponential ramping curve.
*/
#define ASM_PARAM_SVC_RAMPINGCURVE_EXP 1
/*
* Logarithmic ramping curve.
*/
#define ASM_PARAM_SVC_RAMPINGCURVE_LOG 2
/* Structure for holding soft stepping volume parameters. */
/* Payload of the #ASM_PARAM_ID_SOFT_VOL_STEPPING_PARAMETERS
* parameters used by the Volume Control module.
*/
struct asm_soft_step_volume_params {
struct apr_hdr hdr;
struct asm_stream_cmd_set_pp_params_v2 param;
struct asm_stream_param_data_v2 data;
uint32_t period;
/*< Period in milliseconds.
* Supported values: 0 to 15000
*/
uint32_t step;
/*< Step in microseconds.
* Supported values: 0 to 15000000
*/
uint32_t ramping_curve;
/*< Ramping curve type.
* Supported values:
* - #ASM_PARAM_SVC_RAMPINGCURVE_LINEAR
* - #ASM_PARAM_SVC_RAMPINGCURVE_EXP
* - #ASM_PARAM_SVC_RAMPINGCURVE_LOG
*/
} __packed;
/* Structure for holding soft pause parameters. */
/* Payload of the #ASM_PARAM_ID_SOFT_PAUSE_PARAMETERS
* parameters used by the Volume Control module.
*/
struct asm_soft_pause_params {
struct apr_hdr hdr;
struct asm_stream_cmd_set_pp_params_v2 param;
struct asm_stream_param_data_v2 data;
uint32_t enable_flag;
/*< Specifies whether soft pause is disabled (0) or enabled
* (nonzero).
*/
uint32_t period;
/*< Period in milliseconds.
* Supported values: 0 to 15000
*/
uint32_t step;
/*< Step in microseconds.
* Supported values: 0 to 15000000
*/
uint32_t ramping_curve;
/*< Ramping curve.
* Supported values:
* - #ASM_PARAM_SVC_RAMPINGCURVE_LINEAR
* - #ASM_PARAM_SVC_RAMPINGCURVE_EXP
* - #ASM_PARAM_SVC_RAMPINGCURVE_LOG
*/
} __packed;
/* Maximum number of channels.*/
#define VOLUME_CONTROL_MAX_CHANNELS 8
/* Structure for holding one channel type - gain pair. */
/* Payload of the #ASM_PARAM_ID_MULTICHANNEL_GAIN channel
* type/gain pairs used by the Volume Control module. \n \n This
* structure immediately follows the
* asm_volume_ctrl_multichannel_gain structure.
*/
struct asm_volume_ctrl_channelype_gain_pair {
struct apr_hdr hdr;
struct asm_stream_cmd_set_pp_params_v2 param;
struct asm_stream_param_data_v2 data;
uint8_t channelype;
/*< Channel type for which the gain setting is to be applied.
* Supported values:
* - #PCM_CHANNEL_L
* - #PCM_CHANNEL_R
* - #PCM_CHANNEL_C
* - #PCM_CHANNEL_LS
* - #PCM_CHANNEL_RS
* - #PCM_CHANNEL_LFE
* - #PCM_CHANNEL_CS
* - #PCM_CHANNEL_LB
* - #PCM_CHANNEL_RB
* - #PCM_CHANNELS
* - #PCM_CHANNEL_CVH
* - #PCM_CHANNEL_MS
* - #PCM_CHANNEL_FLC
* - #PCM_CHANNEL_FRC
* - #PCM_CHANNEL_RLC
* - #PCM_CHANNEL_RRC
*/
uint8_t reserved1;
/*< Clients must set this field to zero. */
uint8_t reserved2;
/*< Clients must set this field to zero. */
uint8_t reserved3;
/*< Clients must set this field to zero. */
uint32_t gain;
/*< Gain value for this channel in Q28 format.
* Supported values: Any
*/
} __packed;
/* Structure for the multichannel gain command */
/* Payload of the #ASM_PARAM_ID_MULTICHANNEL_GAIN
* parameters used by the Volume Control module.
*/
struct asm_volume_ctrl_multichannel_gain {
struct apr_hdr hdr;
struct asm_stream_cmd_set_pp_params_v2 param;
struct asm_stream_param_data_v2 data;
uint32_t num_channels;
/*< Number of channels for which gain values are provided. Any
* channels present in the data for which gain is not provided are
* set to unity gain.
* Supported values: 1 to 8
*/
struct asm_volume_ctrl_channelype_gain_pair
gain_data[VOLUME_CONTROL_MAX_CHANNELS];
/*< Array of channel type/gain pairs.*/
} __packed;
/* Structure for holding one channel type - mute pair. */
/* Payload of the #ASM_PARAM_ID_MULTICHANNEL_MUTE channel
* type/mute setting pairs used by the Volume Control module. \n \n
* This structure immediately follows the
* asm_volume_ctrl_multichannel_mute structure.
*/
struct asm_volume_ctrl_channelype_mute_pair {
struct apr_hdr hdr;
struct asm_stream_cmd_set_pp_params_v2 param;
struct asm_stream_param_data_v2 data;
uint8_t channelype;
/*< Channel type for which the mute setting is to be applied.
* Supported values:
* - #PCM_CHANNEL_L
* - #PCM_CHANNEL_R
* - #PCM_CHANNEL_C
* - #PCM_CHANNEL_LS
* - #PCM_CHANNEL_RS
* - #PCM_CHANNEL_LFE
* - #PCM_CHANNEL_CS
* - #PCM_CHANNEL_LB
* - #PCM_CHANNEL_RB
* - #PCM_CHANNELS
* - #PCM_CHANNEL_CVH
* - #PCM_CHANNEL_MS
* - #PCM_CHANNEL_FLC
* - #PCM_CHANNEL_FRC
* - #PCM_CHANNEL_RLC
* - #PCM_CHANNEL_RRC
*/
uint8_t reserved1;
/*< Clients must set this field to zero. */
uint8_t reserved2;
/*< Clients must set this field to zero. */
uint8_t reserved3;
/*< Clients must set this field to zero. */
uint32_t mute;
/*< Mute setting for this channel.
* Supported values:
* - 0 = Unmute
* - Nonzero = Mute
*/
} __packed;
/* Structure for the multichannel mute command */
/* @brief Payload of the #ASM_PARAM_ID_MULTICHANNEL_MUTE
* parameters used by the Volume Control module.
*/
struct asm_volume_ctrl_multichannel_mute {
struct apr_hdr hdr;
struct asm_stream_cmd_set_pp_params_v2 param;
struct asm_stream_param_data_v2 data;
uint32_t num_channels;
/*< Number of channels for which mute configuration is
* provided. Any channels present in the data for which mute
* configuration is not provided are set to unmute.
* Supported values: 1 to 8
*/
struct asm_volume_ctrl_channelype_mute_pair
mute_data[VOLUME_CONTROL_MAX_CHANNELS];
/*< Array of channel type/mute setting pairs.*/
} __packed;
/* end_addtogroup audio_pp_param_ids */
/* audio_pp_module_ids
* ID of the IIR Tuning Filter module.
* This module supports the following parameter IDs:
* - #ASM_PARAM_ID_IIRUNING_FILTER_ENABLE_CONFIG
* - #ASM_PARAM_ID_IIRUNING_FILTER_PRE_GAIN
* - #ASM_PARAM_ID_IIRUNING_FILTER_CONFIG_PARAMS
*/
#define ASM_MODULE_ID_IIRUNING_FILTER 0x00010C02
/* @addtogroup audio_pp_param_ids */
/* ID of the IIR tuning filter enable parameter used by the
* #ASM_MODULE_ID_IIRUNING_FILTER module.
* @messagepayload
* @structure{asm_iiruning_filter_enable}
* @tablespace
* @inputtable{Audio_Postproc_ASM_PARAM_ID_IIRUNING_FILTER_ENABLE_CO
* NFIG.tex}
*/
#define ASM_PARAM_ID_IIRUNING_FILTER_ENABLE_CONFIG 0x00010C03
/* ID of the IIR tuning filter pregain parameter used by the
* #ASM_MODULE_ID_IIRUNING_FILTER module.
*/
#define ASM_PARAM_ID_IIRUNING_FILTER_PRE_GAIN 0x00010C04
/* ID of the IIR tuning filter configuration parameters used by the
* #ASM_MODULE_ID_IIRUNING_FILTER module.
*/
#define ASM_PARAM_ID_IIRUNING_FILTER_CONFIG_PARAMS 0x00010C05
/* Structure for an enable configuration parameter for an
* IIR tuning filter module.
*/
/* @brief Payload of the #ASM_PARAM_ID_IIRUNING_FILTER_ENABLE_CONFIG
* parameter used by the IIR Tuning Filter module.
*/
struct asm_iiruning_filter_enable {
uint32_t enable_flag;
/*< Specifies whether the IIR tuning filter is disabled (0) or
* enabled (1).
*/
} __packed;
/* Structure for the pregain parameter for an IIR tuning filter module. */
/* Payload of the #ASM_PARAM_ID_IIRUNING_FILTER_PRE_GAIN
* parameters used by the IIR Tuning Filter module.
*/
struct asm_iiruning_filter_pregain {
uint16_t pregain;
/*< Linear gain in Q13 format. */
uint16_t reserved;
/*< Clients must set this field to zero.*/
} __packed;
/* Structure for the configuration parameter for an IIR tuning filter
* module.
*/
/* @brief Payload of the #ASM_PARAM_ID_IIRUNING_FILTER_CONFIG_PARAMS
* parameters used by the IIR Tuning Filter module. \n
* \n
* This structure is followed by the IIR filter coefficients: \n
* - Sequence of int32_t FilterCoeffs \n
* Five coefficients for each band. Each coefficient is in int32_t format, in
* the order of b0, b1, b2, a1, a2.
* - Sequence of int16_t NumShiftFactor \n
* One int16_t per band. The numerator shift factor is related to the Q
* factor of the filter coefficients.
* - Sequence of uint16_t PanSetting \n
* One uint16_t per band, indicating if the filter is applied to left (0),
* right (1), or both (2) channels.
*/
struct asm_iir_filter_config_params {
uint16_t num_biquad_stages;
/*< Number of bands.
* Supported values: 0 to 20
*/
uint16_t reserved;
/*< Clients must set this field to zero.*/
} __packed;
/* audio_pp_module_ids
* ID of the Multiband Dynamic Range Control (MBDRC) module on the Tx/Rx
* paths.
* This module supports the following parameter IDs:
* - #ASM_PARAM_ID_MBDRC_ENABLE
* - #ASM_PARAM_ID_MBDRC_CONFIG_PARAMS
*/
#define ASM_MODULE_ID_MBDRC 0x00010C06
/* audio_pp_param_ids */
/* ID of the MBDRC enable parameter used by the #ASM_MODULE_ID_MBDRC module.
* @messagepayload
* @structure{asm_mbdrc_enable}
* @tablespace
* @inputtable{Audio_Postproc_ASM_PARAM_ID_MBDRC_ENABLE.tex}
*/
#define ASM_PARAM_ID_MBDRC_ENABLE 0x00010C07
/* ID of the MBDRC configuration parameters used by the
* #ASM_MODULE_ID_MBDRC module.
* @messagepayload
* @structure{asm_mbdrc_config_params}
* @tablespace
* @inputtable{Audio_Postproc_ASM_PARAM_ID_MBDRC_CONFIG_PARAMS.tex}
*
* @parspace Sub-band DRC configuration parameters
* @structure{asm_subband_drc_config_params}
* @tablespace
* @inputtable{Audio_Postproc_ASM_PARAM_ID_MBDRC_CONFIG_PARAMS_subband_DRC.tex}
*
* @keep{6}
* To obtain legacy ADRC from MBDRC, use the calibration tool to:
*
* - Enable MBDRC (EnableFlag = TRUE)
* - Set number of bands to 1 (uiNumBands = 1)
* - Enable the first MBDRC band (DrcMode[0] = DRC_ENABLED = 1)
* - Clear the first band mute flag (MuteFlag[0] = 0)
* - Set the first band makeup gain to unity (compMakeUpGain[0] = 0x2000)
* - Use the legacy ADRC parameters to calibrate the rest of the MBDRC
* parameters.
*/
#define ASM_PARAM_ID_MBDRC_CONFIG_PARAMS 0x00010C08
/* end_addtogroup audio_pp_param_ids */
/* audio_pp_module_ids
* ID of the MMBDRC module version 2 pre/postprocessing block.
* This module differs from the original MBDRC (#ASM_MODULE_ID_MBDRC) in
* the length of the filters used in each sub-band.
* This module supports the following parameter ID:
* - #ASM_PARAM_ID_MBDRC_CONFIG_PARAMS_IMPROVED_FILTBANK_V2
*/
#define ASM_MODULE_ID_MBDRCV2 0x0001070B
/* @addtogroup audio_pp_param_ids */
/* ID of the configuration parameters used by the
* #ASM_MODULE_ID_MBDRCV2 module for the improved filter structure
* of the MBDRC v2 pre/postprocessing block.
* The update to this configuration structure from the original
* MBDRC is the number of filter coefficients in the filter
* structure. The sequence for is as follows:
* - 1 band = 0 FIR coefficient + 1 mute flag + uint16_t padding
* - 2 bands = 141 FIR coefficients + 2 mute flags + uint16_t padding
* - 3 bands = 141+81 FIR coefficients + 3 mute flags + uint16_t padding
* - 4 bands = 141+81+61 FIR coefficients + 4 mute flags + uint16_t
* padding
* - 5 bands = 141+81+61+61 FIR coefficients + 5 mute flags +
* uint16_t padding
* This block uses the same parameter structure as
* #ASM_PARAM_ID_MBDRC_CONFIG_PARAMS.
*/
#define ASM_PARAM_ID_MBDRC_CONFIG_PARAMS_IMPROVED_FILTBANK_V2 \
0x0001070C
/* Structure for the enable parameter for an MBDRC module. */
/* Payload of the #ASM_PARAM_ID_MBDRC_ENABLE parameter used by the
* MBDRC module.
*/
struct asm_mbdrc_enable {
uint32_t enable_flag;
/*< Specifies whether MBDRC is disabled (0) or enabled (nonzero).*/
} __packed;
/* Structure for the configuration parameters for an MBDRC module. */
/* Payload of the #ASM_PARAM_ID_MBDRC_CONFIG_PARAMS
* parameters used by the MBDRC module. \n \n Following this
* structure is the payload for sub-band DRC configuration
* parameters (asm_subband_drc_config_params). This sub-band
* structure must be repeated for each band.
*/
struct asm_mbdrc_config_params {
uint16_t num_bands;
/*< Number of bands.
* Supported values: 1 to 5
*/
int16_t limiterhreshold;
/*< Threshold in decibels for the limiter output.
* Supported values: -72 to 18 \n
* Recommended value: 3994 (-0.22 db in Q3.12 format)
*/
int16_t limiter_makeup_gain;
/*< Makeup gain in decibels for the limiter output.
* Supported values: -42 to 42 \n
* Recommended value: 256 (0 dB in Q7.8 format)
*/
int16_t limiter_gc;
/*< Limiter gain recovery coefficient.
* Supported values: 0.5 to 0.99 \n
* Recommended value: 32440 (0.99 in Q15 format)
*/
int16_t limiter_delay;
/*< Limiter delay in samples.
* Supported values: 0 to 10 \n
* Recommended value: 262 (0.008 samples in Q15 format)
*/
int16_t limiter_max_wait;
/*< Maximum limiter waiting time in samples.
* Supported values: 0 to 10 \n
* Recommended value: 262 (0.008 samples in Q15 format)
*/
} __packed;
/* DRC configuration structure for each sub-band of an MBDRC module. */
/* Payload of the #ASM_PARAM_ID_MBDRC_CONFIG_PARAMS DRC
* configuration parameters for each sub-band in the MBDRC module.
* After this DRC structure is configured for valid bands, the next
* MBDRC setparams expects the sequence of sub-band MBDRC filter
* coefficients (the length depends on the number of bands) plus the
* mute flag for that band plus uint16_t padding.
*
* @keep{10}
* The filter coefficient and mute flag are of type int16_t:
* - FIR coefficient = int16_t firFilter
* - Mute flag = int16_t fMuteFlag
*
* The sequence is as follows:
* - 1 band = 0 FIR coefficient + 1 mute flag + uint16_t padding
* - 2 bands = 97 FIR coefficients + 2 mute flags + uint16_t padding
* - 3 bands = 97+33 FIR coefficients + 3 mute flags + uint16_t padding
* - 4 bands = 97+33+33 FIR coefficients + 4 mute flags + uint16_t padding
* - 5 bands = 97+33+33+33 FIR coefficients + 5 mute flags + uint16_t padding
*
* For improved filterbank, the sequence is as follows:
* - 1 band = 0 FIR coefficient + 1 mute flag + uint16_t padding
* - 2 bands = 141 FIR coefficients + 2 mute flags + uint16_t padding
* - 3 bands = 141+81 FIR coefficients + 3 mute flags + uint16_t padding
* - 4 bands = 141+81+61 FIR coefficients + 4 mute flags + uint16_t padding
* - 5 bands = 141+81+61+61 FIR coefficients + 5 mute flags + uint16_t padding
*/
struct asm_subband_drc_config_params {
int16_t drc_stereo_linked_flag;
/*< Specifies whether all stereo channels have the same applied
* dynamics (1) or if they process their dynamics independently (0).
* Supported values:
* - 0 -- Not linked
* - 1 -- Linked
*/
int16_t drc_mode;
/*< Specifies whether DRC mode is bypassed for sub-bands.
* Supported values:
* - 0 -- Disabled
* - 1 -- Enabled
*/
int16_t drc_down_sample_level;
/*< DRC down sample level.
* Supported values: @ge 1
*/
int16_t drc_delay;
/*< DRC delay in samples.
* Supported values: 0 to 1200
*/
uint16_t drc_rmsime_avg_const;
/*< RMS signal energy time-averaging constant.
* Supported values: 0 to 2^16-1
*/
uint16_t drc_makeup_gain;
/*< DRC makeup gain in decibels.
* Supported values: 258 to 64917
*/
/* Down expander settings */
int16_t down_expdrhreshold;
/*< Down expander threshold.
* Supported Q7 format values: 1320 to up_cmpsrhreshold
*/
int16_t down_expdr_slope;
/*< Down expander slope.
* Supported Q8 format values: -32768 to 0.
*/
uint32_t down_expdr_attack;
/*< Down expander attack constant.
* Supported Q31 format values: 196844 to 2^31.
*/
uint32_t down_expdr_release;
/*< Down expander release constant.
* Supported Q31 format values: 19685 to 2^31
*/
uint16_t down_expdr_hysteresis;
/*< Down expander hysteresis constant.
* Supported Q14 format values: 1 to 32690
*/
uint16_t reserved;
/*< Clients must set this field to zero. */
int32_t down_expdr_min_gain_db;
/*< Down expander minimum gain.
* Supported Q23 format values: -805306368 to 0.
*/
/* Up compressor settings */
int16_t up_cmpsrhreshold;
/*< Up compressor threshold.
* Supported Q7 format values: down_expdrhreshold to
* down_cmpsrhreshold.
*/
uint16_t up_cmpsr_slope;
/*< Up compressor slope.
* Supported Q16 format values: 0 to 64881.
*/
uint32_t up_cmpsr_attack;
/*< Up compressor attack constant.
* Supported Q31 format values: 196844 to 2^31.
*/
uint32_t up_cmpsr_release;
/*< Up compressor release constant.
* Supported Q31 format values: 19685 to 2^31.
*/
uint16_t up_cmpsr_hysteresis;
/*< Up compressor hysteresis constant.
* Supported Q14 format values: 1 to 32690.
*/
/* Down compressor settings */
int16_t down_cmpsrhreshold;
/*< Down compressor threshold.
* Supported Q7 format values: up_cmpsrhreshold to 11560.
*/
uint16_t down_cmpsr_slope;
/*< Down compressor slope.
* Supported Q16 format values: 0 to 64881.
*/
uint16_t reserved1;
/*< Clients must set this field to zero. */
uint32_t down_cmpsr_attack;
/*< Down compressor attack constant.
* Supported Q31 format values: 196844 to 2^31.
*/
uint32_t down_cmpsr_release;
/*< Down compressor release constant.
* Supported Q31 format values: 19685 to 2^31.
*/
uint16_t down_cmpsr_hysteresis;
/*< Down compressor hysteresis constant.
* Supported Q14 values: 1 to 32690.
*/
uint16_t reserved2;
/*< Clients must set this field to zero.*/
} __packed;
#define ASM_MODULE_ID_EQUALIZER 0x00010C27
#define ASM_PARAM_ID_EQUALIZER_PARAMETERS 0x00010C28
#define ASM_MAX_EQ_BANDS 12
struct asm_eq_per_band_params {
uint32_t band_idx;
/*< Band index.
* Supported values: 0 to 11
*/
uint32_t filterype;
/*< Type of filter.
* Supported values:
* - #ASM_PARAM_EQYPE_NONE
* - #ASM_PARAM_EQ_BASS_BOOST
* - #ASM_PARAM_EQ_BASS_CUT
* - #ASM_PARAM_EQREBLE_BOOST
* - #ASM_PARAM_EQREBLE_CUT
* - #ASM_PARAM_EQ_BAND_BOOST
* - #ASM_PARAM_EQ_BAND_CUT
*/
uint32_t center_freq_hz;
/*< Filter band center frequency in Hertz. */
int32_t filter_gain;
/*< Filter band initial gain.
* Supported values: +12 to -12 dB in 1 dB increments
*/
int32_t q_factor;
/*< Filter band quality factor expressed as a Q8 number, i.e., a
* fixed-point number with q factor of 8. For example, 3000/(2^8).
*/
} __packed;
struct asm_eq_params {
struct apr_hdr hdr;
struct asm_stream_cmd_set_pp_params_v2 param;
struct asm_stream_param_data_v2 data;
uint32_t enable_flag;
/*< Specifies whether the equalizer module is disabled (0) or enabled
* (nonzero).
*/
uint32_t num_bands;
/*< Number of bands.
* Supported values: 1 to 12
*/
struct asm_eq_per_band_params eq_bands[ASM_MAX_EQ_BANDS];
} __packed;
/* No equalizer effect.*/
#define ASM_PARAM_EQYPE_NONE 0
/* Bass boost equalizer effect.*/
#define ASM_PARAM_EQ_BASS_BOOST 1
/*Bass cut equalizer effect.*/
#define ASM_PARAM_EQ_BASS_CUT 2
/* Treble boost equalizer effect */
#define ASM_PARAM_EQREBLE_BOOST 3
/* Treble cut equalizer effect.*/
#define ASM_PARAM_EQREBLE_CUT 4
/* Band boost equalizer effect.*/
#define ASM_PARAM_EQ_BAND_BOOST 5
/* Band cut equalizer effect.*/
#define ASM_PARAM_EQ_BAND_CUT 6
/* Voice get & set params */
#define VOICE_CMD_SET_PARAM 0x0001133D
#define VOICE_CMD_GET_PARAM 0x0001133E
#define VOICE_EVT_GET_PARAM_ACK 0x00011008
/** ID of the Bass Boost module.
This module supports the following parameter IDs:
- #AUDPROC_PARAM_ID_BASS_BOOST_ENABLE
- #AUDPROC_PARAM_ID_BASS_BOOST_MODE
- #AUDPROC_PARAM_ID_BASS_BOOST_STRENGTH
*/
#define AUDPROC_MODULE_ID_BASS_BOOST 0x000108A1
/** ID of the Bass Boost enable parameter used by
AUDPROC_MODULE_ID_BASS_BOOST.
*/
#define AUDPROC_PARAM_ID_BASS_BOOST_ENABLE 0x000108A2
/** ID of the Bass Boost mode parameter used by
AUDPROC_MODULE_ID_BASS_BOOST.
*/
#define AUDPROC_PARAM_ID_BASS_BOOST_MODE 0x000108A3
/** ID of the Bass Boost strength parameter used by
AUDPROC_MODULE_ID_BASS_BOOST.
*/
#define AUDPROC_PARAM_ID_BASS_BOOST_STRENGTH 0x000108A4
/** ID of the Virtualizer module. This module supports the
following parameter IDs:
- #AUDPROC_PARAM_ID_VIRTUALIZER_ENABLE
- #AUDPROC_PARAM_ID_VIRTUALIZER_STRENGTH
- #AUDPROC_PARAM_ID_VIRTUALIZER_OUT_TYPE
- #AUDPROC_PARAM_ID_VIRTUALIZER_GAIN_ADJUST
*/
#define AUDPROC_MODULE_ID_VIRTUALIZER 0x000108A5
/** ID of the Virtualizer enable parameter used by
AUDPROC_MODULE_ID_VIRTUALIZER.
*/
#define AUDPROC_PARAM_ID_VIRTUALIZER_ENABLE 0x000108A6
/** ID of the Virtualizer strength parameter used by
AUDPROC_MODULE_ID_VIRTUALIZER.
*/
#define AUDPROC_PARAM_ID_VIRTUALIZER_STRENGTH 0x000108A7
/** ID of the Virtualizer out type parameter used by
AUDPROC_MODULE_ID_VIRTUALIZER.
*/
#define AUDPROC_PARAM_ID_VIRTUALIZER_OUT_TYPE 0x000108A8
/** ID of the Virtualizer out type parameter used by
AUDPROC_MODULE_ID_VIRTUALIZER.
*/
#define AUDPROC_PARAM_ID_VIRTUALIZER_GAIN_ADJUST 0x000108A9
/** ID of the Reverb module. This module supports the following
parameter IDs:
- #AUDPROC_PARAM_ID_REVERB_ENABLE
- #AUDPROC_PARAM_ID_REVERB_MODE
- #AUDPROC_PARAM_ID_REVERB_PRESET
- #AUDPROC_PARAM_ID_REVERB_WET_MIX
- #AUDPROC_PARAM_ID_REVERB_GAIN_ADJUST
- #AUDPROC_PARAM_ID_REVERB_ROOM_LEVEL
- #AUDPROC_PARAM_ID_REVERB_ROOM_HF_LEVEL
- #AUDPROC_PARAM_ID_REVERB_DECAY_TIME
- #AUDPROC_PARAM_ID_REVERB_DECAY_HF_RATIO
- #AUDPROC_PARAM_ID_REVERB_REFLECTIONS_LEVEL
- #AUDPROC_PARAM_ID_REVERB_REFLECTIONS_DELAY
- #AUDPROC_PARAM_ID_REVERB_LEVEL
- #AUDPROC_PARAM_ID_REVERB_DELAY
- #AUDPROC_PARAM_ID_REVERB_DIFFUSION
- #AUDPROC_PARAM_ID_REVERB_DENSITY
*/
#define AUDPROC_MODULE_ID_REVERB 0x000108AA
/** ID of the Reverb enable parameter used by
AUDPROC_MODULE_ID_REVERB.
*/
#define AUDPROC_PARAM_ID_REVERB_ENABLE 0x000108AB
/** ID of the Reverb mode parameter used by
AUDPROC_MODULE_ID_REVERB.
*/
#define AUDPROC_PARAM_ID_REVERB_MODE 0x000108AC
/** ID of the Reverb preset parameter used by
AUDPROC_MODULE_ID_REVERB.
*/
#define AUDPROC_PARAM_ID_REVERB_PRESET 0x000108AD
/** ID of the Reverb wet mix parameter used by
AUDPROC_MODULE_ID_REVERB.
*/
#define AUDPROC_PARAM_ID_REVERB_WET_MIX 0x000108AE
/** ID of the Reverb gain adjust parameter used by
AUDPROC_MODULE_ID_REVERB.
*/
#define AUDPROC_PARAM_ID_REVERB_GAIN_ADJUST 0x000108AF
/** ID of the Reverb room level parameter used by
AUDPROC_MODULE_ID_REVERB.
*/
#define AUDPROC_PARAM_ID_REVERB_ROOM_LEVEL 0x000108B0
/** ID of the Reverb room hf level parameter used by
AUDPROC_MODULE_ID_REVERB.
*/
#define AUDPROC_PARAM_ID_REVERB_ROOM_HF_LEVEL 0x000108B1
/** ID of the Reverb decay time parameter used by
AUDPROC_MODULE_ID_REVERB.
*/
#define AUDPROC_PARAM_ID_REVERB_DECAY_TIME 0x000108B2
/** ID of the Reverb decay hf ratio parameter used by
AUDPROC_MODULE_ID_REVERB.
*/
#define AUDPROC_PARAM_ID_REVERB_DECAY_HF_RATIO 0x000108B3
/** ID of the Reverb reflections level parameter used by
AUDPROC_MODULE_ID_REVERB.
*/
#define AUDPROC_PARAM_ID_REVERB_REFLECTIONS_LEVEL 0x000108B4
/** ID of the Reverb reflections delay parameter used by
AUDPROC_MODULE_ID_REVERB.
*/
#define AUDPROC_PARAM_ID_REVERB_REFLECTIONS_DELAY 0x000108B5
/** ID of the Reverb level parameter used by
AUDPROC_MODULE_ID_REVERB.
*/
#define AUDPROC_PARAM_ID_REVERB_LEVEL 0x000108B6
/** ID of the Reverb delay parameter used by
AUDPROC_MODULE_ID_REVERB.
*/
#define AUDPROC_PARAM_ID_REVERB_DELAY 0x000108B7
/** ID of the Reverb diffusion parameter used by
AUDPROC_MODULE_ID_REVERB.
*/
#define AUDPROC_PARAM_ID_REVERB_DIFFUSION 0x000108B8
/** ID of the Reverb density parameter used by
AUDPROC_MODULE_ID_REVERB.
*/
#define AUDPROC_PARAM_ID_REVERB_DENSITY 0x000108B9
/** ID of the Popless Equalizer module. This module supports the
following parameter IDs:
- #AUDPROC_PARAM_ID_EQ_ENABLE
- #AUDPROC_PARAM_ID_EQ_CONFIG
- #AUDPROC_PARAM_ID_EQ_NUM_BANDS
- #AUDPROC_PARAM_ID_EQ_BAND_LEVELS
- #AUDPROC_PARAM_ID_EQ_BAND_LEVEL_RANGE
- #AUDPROC_PARAM_ID_EQ_BAND_FREQS
- #AUDPROC_PARAM_ID_EQ_SINGLE_BAND_FREQ_RANGE
- #AUDPROC_PARAM_ID_EQ_SINGLE_BAND_FREQ
- #AUDPROC_PARAM_ID_EQ_BAND_INDEX
- #AUDPROC_PARAM_ID_EQ_PRESET_ID
- #AUDPROC_PARAM_ID_EQ_NUM_PRESETS
- #AUDPROC_PARAM_ID_EQ_GET_PRESET_NAME
*/
#define AUDPROC_MODULE_ID_POPLESS_EQUALIZER 0x000108BA
/** ID of the Popless Equalizer enable parameter used by
AUDPROC_MODULE_ID_POPLESS_EQUALIZER.
*/
#define AUDPROC_PARAM_ID_EQ_ENABLE 0x000108BB
/** ID of the Popless Equalizer config parameter used by
AUDPROC_MODULE_ID_POPLESS_EQUALIZER.
*/
#define AUDPROC_PARAM_ID_EQ_CONFIG 0x000108BC
/** ID of the Popless Equalizer number of bands parameter used
by AUDPROC_MODULE_ID_POPLESS_EQUALIZER. This param ID is
used for get param only.
*/
#define AUDPROC_PARAM_ID_EQ_NUM_BANDS 0x000108BD
/** ID of the Popless Equalizer band levels parameter used by
AUDPROC_MODULE_ID_POPLESS_EQUALIZER. This param ID is
used for get param only.
*/
#define AUDPROC_PARAM_ID_EQ_BAND_LEVELS 0x000108BE
/** ID of the Popless Equalizer band level range parameter used
by AUDPROC_MODULE_ID_POPLESS_EQUALIZER. This param ID is
used for get param only.
*/
#define AUDPROC_PARAM_ID_EQ_BAND_LEVEL_RANGE 0x000108BF
/** ID of the Popless Equalizer band frequencies parameter used
by AUDPROC_MODULE_ID_POPLESS_EQUALIZER. This param ID is
used for get param only.
*/
#define AUDPROC_PARAM_ID_EQ_BAND_FREQS 0x000108C0
/** ID of the Popless Equalizer single band frequency range
parameter used by AUDPROC_MODULE_ID_POPLESS_EQUALIZER.
This param ID is used for get param only.
*/
#define AUDPROC_PARAM_ID_EQ_SINGLE_BAND_FREQ_RANGE 0x000108C1
/** ID of the Popless Equalizer single band frequency parameter
used by AUDPROC_MODULE_ID_POPLESS_EQUALIZER. This param ID
is used for set param only.
*/
#define AUDPROC_PARAM_ID_EQ_SINGLE_BAND_FREQ 0x000108C2
/** ID of the Popless Equalizer band index parameter used by
AUDPROC_MODULE_ID_POPLESS_EQUALIZER.
*/
#define AUDPROC_PARAM_ID_EQ_BAND_INDEX 0x000108C3
/** ID of the Popless Equalizer preset id parameter used by
AUDPROC_MODULE_ID_POPLESS_EQUALIZER. This param ID is used
for get param only.
*/
#define AUDPROC_PARAM_ID_EQ_PRESET_ID 0x000108C4
/** ID of the Popless Equalizer number of presets parameter used
by AUDPROC_MODULE_ID_POPLESS_EQUALIZER. This param ID is used
for get param only.
*/
#define AUDPROC_PARAM_ID_EQ_NUM_PRESETS 0x000108C5
/** ID of the Popless Equalizer preset name parameter used by
AUDPROC_MODULE_ID_POPLESS_EQUALIZER. This param ID is used
for get param only.
*/
#define AUDPROC_PARAM_ID_EQ_PRESET_NAME 0x000108C6
/* Set Q6 topologies */
#define ASM_CMD_ADD_TOPOLOGIES 0x00010DBE
#define ADM_CMD_ADD_TOPOLOGIES 0x00010335
/* structure used for both ioctls */
struct cmd_set_topologies {
struct apr_hdr hdr;
u32 payload_addr_lsw;
/* LSW of parameter data payload address.*/
u32 payload_addr_msw;
/* MSW of parameter data payload address.*/
u32 mem_map_handle;
/* Memory map handle returned by mem map command */
u32 payload_size;
/* Size in bytes of the variable payload in shared memory */
} __packed;
/* This module represents the Rx processing of Feedback speaker protection.
* It contains the excursion control, thermal protection,
* analog clip manager features in it.
* This module id will support following param ids.
* - AFE_PARAM_ID_FBSP_MODE_RX_CFG
*/
#define AFE_MODULE_FB_SPKR_PROT_RX 0x0001021C
#define AFE_PARAM_ID_FBSP_MODE_RX_CFG 0x0001021D
struct asm_fbsp_mode_rx_cfg {
uint32_t minor_version;
uint32_t mode;
} __packed;
/* This module represents the VI processing of feedback speaker protection.
* It will receive Vsens and Isens from codec and generates necessary
* parameters needed by Rx processing.
* This module id will support following param ids.
* - AFE_PARAM_ID_SPKR_CALIB_VI_PROC_CFG
* - AFE_PARAM_ID_CALIB_RES_CFG
* - AFE_PARAM_ID_FEEDBACK_PATH_CFG
*/
#define AFE_MODULE_FB_SPKR_PROT_VI_PROC 0x00010226
#define AFE_PARAM_ID_SPKR_CALIB_VI_PROC_CFG 0x0001022A
struct asm_spkr_calib_vi_proc_cfg {
uint32_t minor_version;
int32_t r0_cali_q24;
int16_t t0_cali_q6;
int16_t reserved;
} __packed;
#define AFE_PARAM_ID_CALIB_RES_CFG 0x0001022B
struct asm_calib_res_cfg {
uint32_t minor_version;
int32_t r0_cali_q24;
uint32_t th_vi_ca_state;
} __packed;
#define AFE_PARAM_ID_FEEDBACK_PATH_CFG 0x0001022C
struct asm_feedback_path_cfg {
uint32_t minor_version;
int32_t dst_portid;
int32_t num_channels;
int32_t chan_info[4];
} __packed;
#define AFE_PARAM_ID_MODE_VI_PROC_CFG 0x00010227
struct asm_mode_vi_proc_cfg {
uint32_t minor_version;
uint32_t cal_mode;
} __packed;
union afe_spkr_prot_config {
struct asm_fbsp_mode_rx_cfg mode_rx_cfg;
struct asm_spkr_calib_vi_proc_cfg vi_proc_cfg;
struct asm_feedback_path_cfg feedback_path_cfg;
struct asm_mode_vi_proc_cfg mode_vi_proc_cfg;
} __packed;
struct afe_spkr_prot_config_command {
struct apr_hdr hdr;
struct afe_port_cmd_set_param_v2 param;
struct afe_port_param_data_v2 pdata;
union afe_spkr_prot_config prot_config;
} __packed;
struct afe_spkr_prot_get_vi_calib {
struct afe_port_cmd_get_param_v2 get_param;
struct afe_port_param_data_v2 pdata;
struct asm_calib_res_cfg res_cfg;
} __packed;
struct afe_spkr_prot_calib_get_resp {
uint32_t status;
struct afe_port_param_data_v2 pdata;
struct asm_calib_res_cfg res_cfg;
} __packed;
/* SRS TRUMEDIA start */
/* topology */
#define SRS_TRUMEDIA_TOPOLOGY_ID 0x00010D90
/* module */
#define SRS_TRUMEDIA_MODULE_ID 0x10005010
/* parameters */
#define SRS_TRUMEDIA_PARAMS 0x10005011
#define SRS_TRUMEDIA_PARAMS_WOWHD 0x10005012
#define SRS_TRUMEDIA_PARAMS_CSHP 0x10005013
#define SRS_TRUMEDIA_PARAMS_HPF 0x10005014
#define SRS_TRUMEDIA_PARAMS_PEQ 0x10005015
#define SRS_TRUMEDIA_PARAMS_HL 0x10005016
#define SRS_ID_GLOBAL 0x00000001
#define SRS_ID_WOWHD 0x00000002
#define SRS_ID_CSHP 0x00000003
#define SRS_ID_HPF 0x00000004
#define SRS_ID_PEQ 0x00000005
#define SRS_ID_HL 0x00000006
#define SRS_CMD_UPLOAD 0x7FFF0000
#define SRS_PARAM_INDEX_MASK 0x80000000
#define SRS_PARAM_OFFSET_MASK 0x3FFF0000
#define SRS_PARAM_VALUE_MASK 0x0000FFFF
struct srs_trumedia_params_GLOBAL {
uint8_t v1;
uint8_t v2;
uint8_t v3;
uint8_t v4;
uint8_t v5;
uint8_t v6;
uint8_t v7;
uint8_t v8;
} __packed;
struct srs_trumedia_params_WOWHD {
uint32_t v1;
uint16_t v2;
uint16_t v3;
uint16_t v4;
uint16_t v5;
uint16_t v6;
uint16_t v7;
uint16_t v8;
uint16_t v____A1;
uint32_t v9;
uint16_t v10;
uint16_t v11;
uint32_t v12[16];
} __packed;
struct srs_trumedia_params_CSHP {
uint32_t v1;
uint16_t v2;
uint16_t v3;
uint16_t v4;
uint16_t v5;
uint16_t v6;
uint16_t v____A1;
uint32_t v7;
uint16_t v8;
uint16_t v9;
uint32_t v10[16];
} __packed;
struct srs_trumedia_params_HPF {
uint32_t v1;
uint32_t v2[26];
} __packed;
struct srs_trumedia_params_PEQ {
uint32_t v1;
uint16_t v2;
uint16_t v3;
uint16_t v4;
uint16_t v____A1;
uint32_t v5[26];
uint32_t v6[26];
} __packed;
struct srs_trumedia_params_HL {
uint16_t v1;
uint16_t v2;
uint16_t v3;
uint16_t v____A1;
int32_t v4;
uint32_t v5;
uint16_t v6;
uint16_t v____A2;
uint32_t v7;
} __packed;
struct srs_trumedia_params {
struct srs_trumedia_params_GLOBAL global;
struct srs_trumedia_params_WOWHD wowhd;
struct srs_trumedia_params_CSHP cshp;
struct srs_trumedia_params_HPF hpf;
struct srs_trumedia_params_PEQ peq;
struct srs_trumedia_params_HL hl;
} __packed;
/* SRS TruMedia end */
/* LSM Specific */
#define VW_FEAT_DIM (39)
#define APRV2_IDS_SERVICE_ID_ADSP_LSM_V (0xD)
#define APRV2_IDS_DOMAIN_ID_ADSP_V (0x4)
#define APRV2_IDS_DOMAIN_ID_APPS_V (0x5)
#define LSM_SESSION_CMD_SHARED_MEM_MAP_REGIONS (0x00012A7F)
#define LSM_SESSION_CMDRSP_SHARED_MEM_MAP_REGIONS (0x00012A80)
#define LSM_SESSION_CMD_SHARED_MEM_UNMAP_REGIONS (0x00012A81)
#define LSM_SESSION_CMD_OPEN_TX (0x00012A82)
#define LSM_SESSION_CMD_CLOSE_TX (0x00012A88)
#define LSM_SESSION_CMD_SET_PARAMS (0x00012A83)
#define LSM_SESSION_CMD_REGISTER_SOUND_MODEL (0x00012A84)
#define LSM_SESSION_CMD_DEREGISTER_SOUND_MODEL (0x00012A85)
#define LSM_SESSION_CMD_START (0x00012A86)
#define LSM_SESSION_CMD_STOP (0x00012A87)
#define LSM_SESSION_EVENT_DETECTION_STATUS (0x00012B00)
#define LSM_MODULE_ID_VOICE_WAKEUP (0x00012C00)
#define LSM_PARAM_ID_ENDPOINT_DETECT_THRESHOLD (0x00012C01)
#define LSM_PARAM_ID_OPERATION_MODE (0x00012C02)
#define LSM_PARAM_ID_GAIN (0x00012C03)
#define LSM_PARAM_ID_CONNECT_TO_PORT (0x00012C04)
#define LSM_PARAM_ID_KEYWORD_DETECT_SENSITIVITY (0x00012C05)
#define LSM_PARAM_ID_USER_DETECT_SENSITIVITY (0x00012C06)
#define LSM_PARAM_ID_FEATURE_COMPENSATION_DATA (0x00012C07)
/* HW MAD specific */
#define AFE_MODULE_HW_MAD (0x00010230)
#define AFE_PARAM_ID_HW_MAD_CFG (0x00010231)
#define AFE_PARAM_ID_HW_MAD_CTRL (0x00010232)
#define AFE_PARAM_ID_SLIMBUS_SLAVE_PORT_CFG (0x00010233)
/* SW MAD specific */
#define AFE_MODULE_SW_MAD (0x0001022D)
#define AFE_PARAM_ID_SW_MAD_CFG (0x0001022E)
#define AFE_PARAM_ID_SVM_MODEL (0x0001022F)
/* Commands/Params to pass the codec/slimbus data to DSP */
#define AFE_SVC_CMD_SET_PARAM (0x000100f3)
#define AFE_MODULE_CDC_DEV_CFG (0x00010234)
#define AFE_PARAM_ID_CDC_SLIMBUS_SLAVE_CFG (0x00010235)
#define AFE_PARAM_ID_CDC_REG_CFG (0x00010236)
#define AFE_PARAM_ID_CDC_REG_CFG_INIT (0x00010237)
#define AFE_MAX_CDC_REGISTERS_TO_CONFIG (20)
/* AANC Port Config Specific */
#define AFE_PARAM_ID_AANC_PORT_CONFIG (0x00010215)
#define AFE_API_VERSION_AANC_PORT_CONFIG (0x1)
#define AANC_TX_MIC_UNUSED (0)
#define AANC_TX_VOICE_MIC (1)
#define AANC_TX_ERROR_MIC (2)
#define AANC_TX_NOISE_MIC (3)
#define AFE_PORT_MAX_CHANNEL_CNT (8)
#define AFE_MODULE_AANC (0x00010214)
#define AFE_PARAM_ID_CDC_AANC_VERSION (0x0001023A)
#define AFE_API_VERSION_CDC_AANC_VERSION (0x1)
#define AANC_HW_BLOCK_VERSION_1 (1)
#define AANC_HW_BLOCK_VERSION_2 (2)
/*Clip bank selection*/
#define AFE_API_VERSION_CLIP_BANK_SEL_CFG 0x1
#define AFE_CLIP_MAX_BANKS 4
#define AFE_PARAM_ID_CLIP_BANK_SEL_CFG 0x00010242
struct afe_param_aanc_port_cfg {
/* Minor version used for tracking the version of the module's
* source port configuration.
*/
uint32_t aanc_port_cfg_minor_version;
/* Sampling rate of the source Tx port. 8k - 192k*/
uint32_t tx_port_sample_rate;
/* Channel mapping for the Tx port signal carrying Noise (X),
* Error (E), and Voice (V) signals.
*/
uint8_t tx_port_channel_map[AFE_PORT_MAX_CHANNEL_CNT];
/* Number of channels on the source Tx port. */
uint16_t tx_port_num_channels;
/* Port ID of the Rx path reference signal. */
uint16_t rx_path_ref_port_id;
/* Sampling rate of the reference port. 8k - 192k*/
uint32_t ref_port_sample_rate;
} __packed;
struct afe_param_id_cdc_aanc_version {
/* Minor version used for tracking the version of the module's
* hw version
*/
uint32_t cdc_aanc_minor_version;
/* HW version. */
uint32_t aanc_hw_version;
} __packed;
struct afe_param_id_clip_bank_sel {
/* Minor version used for tracking the version of the module's
* hw version
*/
uint32_t minor_version;
/* Number of banks to be read */
uint32_t num_banks;
uint32_t bank_map[AFE_CLIP_MAX_BANKS];
} __packed;
/* ERROR CODES */
/* Success. The operation completed with no errors. */
#define ADSP_EOK 0x00000000
/* General failure. */
#define ADSP_EFAILED 0x00000001
/* Bad operation parameter. */
#define ADSP_EBADPARAM 0x00000002
/* Unsupported routine or operation. */
#define ADSP_EUNSUPPORTED 0x00000003
/* Unsupported version. */
#define ADSP_EVERSION 0x00000004
/* Unexpected problem encountered. */
#define ADSP_EUNEXPECTED 0x00000005
/* Unhandled problem occurred. */
#define ADSP_EPANIC 0x00000006
/* Unable to allocate resource. */
#define ADSP_ENORESOURCE 0x00000007
/* Invalid handle. */
#define ADSP_EHANDLE 0x00000008
/* Operation is already processed. */
#define ADSP_EALREADY 0x00000009
/* Operation is not ready to be processed. */
#define ADSP_ENOTREADY 0x0000000A
/* Operation is pending completion. */
#define ADSP_EPENDING 0x0000000B
/* Operation could not be accepted or processed. */
#define ADSP_EBUSY 0x0000000C
/* Operation aborted due to an error. */
#define ADSP_EABORTED 0x0000000D
/* Operation preempted by a higher priority. */
#define ADSP_EPREEMPTED 0x0000000E
/* Operation requests intervention to complete. */
#define ADSP_ECONTINUE 0x0000000F
/* Operation requests immediate intervention to complete. */
#define ADSP_EIMMEDIATE 0x00000010
/* Operation is not implemented. */
#define ADSP_ENOTIMPL 0x00000011
/* Operation needs more data or resources. */
#define ADSP_ENEEDMORE 0x00000012
/* Operation does not have memory. */
#define ADSP_ENOMEMORY 0x00000014
/* Item does not exist. */
#define ADSP_ENOTEXIST 0x00000015
/* Operation is finished. */
#define ADSP_ETERMINATED 0x00011174
/*bharath, adsp_error_codes.h */
/* LPASS clock for I2S Interface */
/* Supported OSR clock values */
#define Q6AFE_LPASS_OSR_CLK_12_P288_MHZ 0xBB8000
#define Q6AFE_LPASS_OSR_CLK_8_P192_MHZ 0x7D0000
#define Q6AFE_LPASS_OSR_CLK_6_P144_MHZ 0x5DC000
#define Q6AFE_LPASS_OSR_CLK_4_P096_MHZ 0x3E8000
#define Q6AFE_LPASS_OSR_CLK_3_P072_MHZ 0x2EE000
#define Q6AFE_LPASS_OSR_CLK_2_P048_MHZ 0x1F4000
#define Q6AFE_LPASS_OSR_CLK_1_P536_MHZ 0x177000
#define Q6AFE_LPASS_OSR_CLK_1_P024_MHZ 0xFA000
#define Q6AFE_LPASS_OSR_CLK_768_kHZ 0xBB800
#define Q6AFE_LPASS_OSR_CLK_512_kHZ 0x7D000
#define Q6AFE_LPASS_OSR_CLK_DISABLE 0x0
/* Supported Bit clock values */
#define Q6AFE_LPASS_IBIT_CLK_8_P192_MHZ 0x7D0000
#define Q6AFE_LPASS_IBIT_CLK_6_P144_MHZ 0x5DC000
#define Q6AFE_LPASS_IBIT_CLK_4_P096_MHZ 0x3E8000
#define Q6AFE_LPASS_IBIT_CLK_3_P072_MHZ 0x2EE000
#define Q6AFE_LPASS_IBIT_CLK_2_P048_MHZ 0x1F4000
#define Q6AFE_LPASS_IBIT_CLK_1_P536_MHZ 0x177000
#define Q6AFE_LPASS_IBIT_CLK_1_P024_MHZ 0xFA000
#define Q6AFE_LPASS_IBIT_CLK_768_KHZ 0xBB800
#define Q6AFE_LPASS_IBIT_CLK_512_KHZ 0x7D000
#define Q6AFE_LPASS_IBIT_CLK_256_KHZ 0x3E800
#define Q6AFE_LPASS_IBIT_CLK_DISABLE 0x0
/* Supported LPASS CLK sources */
#define Q6AFE_LPASS_CLK_SRC_EXTERNAL 0
#define Q6AFE_LPASS_CLK_SRC_INTERNAL 1
/* Supported LPASS CLK root*/
#define Q6AFE_LPASS_CLK_ROOT_DEFAULT 0
enum afe_lpass_clk_mode {
Q6AFE_LPASS_MODE_BOTH_INVALID,
Q6AFE_LPASS_MODE_CLK1_VALID,
Q6AFE_LPASS_MODE_CLK2_VALID,
Q6AFE_LPASS_MODE_BOTH_VALID,
} __packed;
struct afe_clk_cfg {
/* Minor version used for tracking the version of the I2S
* configuration interface.
* Supported values: #AFE_API_VERSION_I2S_CONFIG
*/
u32 i2s_cfg_minor_version;
/* clk value 1 in MHz. */
u32 clk_val1;
/* clk value 2 in MHz. */
u32 clk_val2;
/* clk_src
* #Q6AFE_LPASS_CLK_SRC_EXTERNAL
* #Q6AFE_LPASS_CLK_SRC_INTERNAL
*/
u16 clk_src;
/* clk_root -0 for default */
u16 clk_root;
/* clk_set_mode
* #Q6AFE_LPASS_MODE_BOTH_INVALID
* #Q6AFE_LPASS_MODE_CLK1_VALID
* #Q6AFE_LPASS_MODE_CLK2_VALID
* #Q6AFE_LPASS_MODE_BOTH_VALID
*/
u16 clk_set_mode;
/* This param id is used to configure I2S clk */
u16 reserved;
} __packed;
/* This param id is used to configure I2S clk */
#define AFE_PARAM_ID_LPAIF_CLK_CONFIG 0x00010238
struct afe_lpass_clk_config_command {
struct apr_hdr hdr;
struct afe_port_cmd_set_param_v2 param;
struct afe_port_param_data_v2 pdata;
struct afe_clk_cfg clk_cfg;
} __packed;
enum afe_lpass_digital_clk_src {
Q6AFE_LPASS_DIGITAL_ROOT_INVALID,
Q6AFE_LPASS_DIGITAL_ROOT_PRI_MI2S_OSR,
Q6AFE_LPASS_DIGITAL_ROOT_SEC_MI2S_OSR,
Q6AFE_LPASS_DIGITAL_ROOT_TER_MI2S_OSR,
Q6AFE_LPASS_DIGITAL_ROOT_QUAD_MI2S_OSR,
Q6AFE_LPASS_DIGITAL_ROOT_CDC_ROOT_CLK,
} __packed;
/* This param id is used to configure internal clk */
#define AFE_PARAM_ID_INTERNAL_DIGIATL_CDC_CLK_CONFIG 0x00010239
struct afe_digital_clk_cfg {
/* Minor version used for tracking the version of the I2S
* configuration interface.
* Supported values: #AFE_API_VERSION_I2S_CONFIG
*/
u32 i2s_cfg_minor_version;
/* clk value in MHz. */
u32 clk_val;
/* INVALID
* PRI_MI2S_OSR
* SEC_MI2S_OSR
* TER_MI2S_OSR
* QUAD_MI2S_OSR
* DIGT_CDC_ROOT
*/
u16 clk_root;
/* This field must be set to zero. */
u16 reserved;
} __packed;
struct afe_lpass_digital_clk_config_command {
struct apr_hdr hdr;
struct afe_port_cmd_set_param_v2 param;
struct afe_port_param_data_v2 pdata;
struct afe_digital_clk_cfg clk_cfg;
} __packed;
/*
* Opcode for AFE to start DTMF.
*/
#define AFE_PORTS_CMD_DTMF_CTL 0x00010102
/** DTMF payload.*/
struct afe_dtmf_generation_command {
struct apr_hdr hdr;
/*
* Duration of the DTMF tone in ms.
* -1 -> continuous,
* 0 -> disable
*/
int64_t duration_in_ms;
/*
* The DTMF high tone frequency.
*/
uint16_t high_freq;
/*
* The DTMF low tone frequency.
*/
uint16_t low_freq;
/*
* The DTMF volume setting
*/
uint16_t gain;
/*
* The number of ports to enable/disable on.
*/
uint16_t num_ports;
/*
* The Destination ports - array .
* For DTMF on multiple ports, portIds needs to
* be populated numPorts times.
*/
uint16_t port_ids;
/*
* variable for 32 bit alignment of APR packet.
*/
uint16_t reserved;
} __packed;
enum afe_config_type {
AFE_SLIMBUS_SLAVE_PORT_CONFIG,
AFE_SLIMBUS_SLAVE_CONFIG,
AFE_CDC_REGISTERS_CONFIG,
AFE_AANC_VERSION,
AFE_CDC_CLIP_REGISTERS_CONFIG,
AFE_CLIP_BANK_SEL,
AFE_MAX_CONFIG_TYPES,
};
struct afe_param_slimbus_slave_port_cfg {
uint32_t minor_version;
uint16_t slimbus_dev_id;
uint16_t slave_dev_pgd_la;
uint16_t slave_dev_intfdev_la;
uint16_t bit_width;
uint16_t data_format;
uint16_t num_channels;
uint16_t slave_port_mapping[AFE_PORT_MAX_AUDIO_CHAN_CNT];
} __packed;
struct afe_param_cdc_slimbus_slave_cfg {
uint32_t minor_version;
uint32_t device_enum_addr_lsw;
uint32_t device_enum_addr_msw;
uint16_t tx_slave_port_offset;
uint16_t rx_slave_port_offset;
} __packed;
struct afe_param_cdc_reg_cfg {
uint32_t minor_version;
uint32_t reg_logical_addr;
uint32_t reg_field_type;
uint32_t reg_field_bit_mask;
uint16_t reg_bit_width;
uint16_t reg_offset_scale;
} __packed;
struct afe_param_cdc_reg_cfg_data {
uint32_t num_registers;
struct afe_param_cdc_reg_cfg *reg_data;
} __packed;
struct afe_svc_cmd_set_param {
uint32_t payload_size;
uint32_t payload_address_lsw;
uint32_t payload_address_msw;
uint32_t mem_map_handle;
} __packed;
struct afe_param_hw_mad_ctrl {
uint32_t minor_version;
uint16_t mad_type;
uint16_t mad_enable;
} __packed;
struct afe_cmd_hw_mad_ctrl {
struct apr_hdr hdr;
struct afe_port_cmd_set_param_v2 param;
struct afe_port_param_data_v2 pdata;
struct afe_param_hw_mad_ctrl payload;
} __packed;
struct afe_cmd_hw_mad_slimbus_slave_port_cfg {
struct apr_hdr hdr;
struct afe_port_cmd_set_param_v2 param;
struct afe_port_param_data_v2 pdata;
struct afe_param_slimbus_slave_port_cfg sb_port_cfg;
} __packed;
struct afe_cmd_sw_mad_enable {
struct apr_hdr hdr;
struct afe_port_cmd_set_param_v2 param;
struct afe_port_param_data_v2 pdata;
} __packed;
struct afe_param_cdc_reg_cfg_payload {
struct afe_port_param_data_v2 common;
struct afe_param_cdc_reg_cfg reg_cfg;
} __packed;
/*
* reg_data's size can be up to AFE_MAX_CDC_REGISTERS_TO_CONFIG
*/
struct afe_svc_cmd_cdc_reg_cfg {
struct apr_hdr hdr;
struct afe_svc_cmd_set_param param;
struct afe_param_cdc_reg_cfg_payload reg_data[0];
} __packed;
struct afe_svc_cmd_init_cdc_reg_cfg {
struct apr_hdr hdr;
struct afe_svc_cmd_set_param param;
struct afe_port_param_data_v2 init;
} __packed;
struct afe_svc_cmd_sb_slave_cfg {
struct apr_hdr hdr;
struct afe_svc_cmd_set_param param;
struct afe_port_param_data_v2 pdata;
struct afe_param_cdc_slimbus_slave_cfg sb_slave_cfg;
} __packed;
struct afe_svc_cmd_cdc_aanc_version {
struct apr_hdr hdr;
struct afe_svc_cmd_set_param param;
struct afe_port_param_data_v2 pdata;
struct afe_param_id_cdc_aanc_version version;
} __packed;
struct afe_port_cmd_set_aanc_param {
struct apr_hdr hdr;
struct afe_port_cmd_set_param_v2 param;
struct afe_port_param_data_v2 pdata;
union {
struct afe_param_aanc_port_cfg aanc_port_cfg;
struct afe_mod_enable_param mod_enable;
} __packed data;
} __packed;
struct afe_port_cmd_set_aanc_acdb_table {
struct apr_hdr hdr;
struct afe_port_cmd_set_param_v2 param;
} __packed;
/* Dolby DAP topology */
#define DOLBY_ADM_COPP_TOPOLOGY_ID 0x0001033B
/* RMS value from DSP */
#define RMS_MODULEID_APPI_PASSTHRU 0x10009011
#define RMS_PARAM_FIRST_SAMPLE 0x10009012
#define RMS_PAYLOAD_LEN 4
struct afe_svc_cmd_set_clip_bank_selection {
struct apr_hdr hdr;
struct afe_svc_cmd_set_param param;
struct afe_port_param_data_v2 pdata;
struct afe_param_id_clip_bank_sel bank_sel;
} __packed;
/* Ultrasound supported formats */
#define US_POINT_EPOS_FORMAT_V2 0x0001272D
#define US_RAW_FORMAT_V2 0x0001272C
#define US_PROX_FORMAT_V4 0x0001273B
#define US_RAW_SYNC_FORMAT 0x0001272F
#define US_GES_SYNC_FORMAT 0x00012730
#define AFE_MODULE_GROUP_DEVICE 0x00010254
#define AFE_PARAM_ID_GROUP_DEVICE_CFG 0x00010255
#define AFE_PARAM_ID_GROUP_DEVICE_ENABLE 0x00010256
#define AFE_GROUP_DEVICE_ID_SECONDARY_MI2S_RX 0x1102
/* Payload of the #AFE_PARAM_ID_GROUP_DEVICE_CFG
* parameter, which configures max of 8 AFE ports
* into a group.
* The fixed size of this structure is sixteen bytes.
*/
struct afe_group_device_group_cfg {
u32 minor_version;
u16 group_id;
u16 num_channels;
u16 port_id[8];
} __packed;
/* Payload of the #AFE_PARAM_ID_GROUP_DEVICE_ENABLE
* parameter, which enables or
* disables any module.
* The fixed size of this structure is four bytes.
*/
struct afe_group_device_enable {
u16 group_id;
/* valid value is AFE_GROUP_DEVICE_ID_SECONDARY_MI2S_RX */
u16 enable;
/* Enables (1) or disables (0) the module. */
} __packed;
struct afe_port_group_create {
struct apr_hdr hdr;
struct afe_svc_cmd_set_param param;
struct afe_port_param_data_v2 pdata;
union {
struct afe_group_device_group_cfg group_cfg;
struct afe_group_device_enable group_enable;
} __packed data;
} __packed;
#endif /*_APR_AUDIO_V2_H_ */
|
/*
* aeskeywrap.c
* Perform RFC3394 AES-based key wrap and unwrap functions.
*
* Copyright (C) 2014, Broadcom Corporation
* All Rights Reserved.
*
* This is UNPUBLISHED PROPRIETARY SOURCE CODE of Broadcom Corporation;
* the contents of this file may not be disclosed to third parties, copied
* or duplicated in any form, in whole or in part, without the prior
* written permission of Broadcom Corporation.
*
* $Id: aeskeywrap.c 241182 2011-02-17 21:50:03Z $
*/
#include <typedefs.h>
#ifdef BCMDRIVER
#include <osl.h>
#else
#include <string.h>
#endif /* BCMDRIVER */
#include <bcmcrypto/aes.h>
#include <bcmcrypto/aeskeywrap.h>
#include <bcmcrypto/rijndael-alg-fst.h>
#ifdef BCMAESKEYWRAP_TEST
#include <stdio.h>
#define dbg(args) printf args
void
pinter(const char *label, const uint8 *A, const size_t il, const uint8 *R)
{
unsigned int k;
printf("%s", label);
for (k = 0; k < AKW_BLOCK_LEN; k++)
printf("%02X", A[k]);
printf(" ");
for (k = 0; k < il; k++) {
printf("%02X", R[k]);
if (!((k+1)%AKW_BLOCK_LEN))
printf(" ");
}
printf("\n");
}
void
pres(const char *label, const size_t len, const uint8 *data)
{
unsigned int k;
printf("%lu %s", (unsigned long)len, label);
for (k = 0; k < len; k++) {
printf("%02x", data[k]);
if (!((k + 1) % AKW_BLOCK_LEN))
printf(" ");
}
printf("\n");
}
#else
#define dbg(args)
#define pinter(label, A, il, R)
#endif /* BCMAESKEYWRAP_TEST */
static const uint8 aeskeywrapIV[] = { 0xa6, 0xa6, 0xa6, 0xa6, 0xa6, 0xa6, 0xa6, 0xa6 };
/* aes_wrap: perform AES-based keywrap function defined in RFC3394
* return 0 on success, 1 on error
* input is il bytes
* output is (il+8) bytes
*/
int
BCMROMFN(aes_wrap)(size_t kl, uint8 *key, size_t il, uint8 *input, uint8 *output)
{
uint32 rk[4*(AES_MAXROUNDS+1)];
uint8 A[AES_BLOCK_SZ];
uint8 R[AKW_MAX_WRAP_LEN];
uint8 B[AES_BLOCK_SZ];
int n = (int)(il/AKW_BLOCK_LEN), i, j, k;
/* validate kl (must be valid AES key length) */
if ((kl != 16) && (kl != 24) && (kl != 32)) {
dbg(("aes_wrap: invlaid key length %lu\n", (unsigned long)kl));
return (1);
}
if (il > AKW_MAX_WRAP_LEN) {
dbg(("aes_wrap: input length %lu too large\n", (unsigned long)il));
return (1);
}
if (il % AKW_BLOCK_LEN) {
dbg(("aes_wrap: input length %lu must be a multiple of block length\n",
(unsigned long)il));
return (1);
}
dbg((" Input:\n"));
dbg((" KEK: "));
for (k = 0; k < (int)kl; k++)
dbg(("%02X", key[k]));
dbg(("\n Key Data: "));
for (k = 0; k < (int)il; k++)
dbg(("%02X", input[k]));
dbg(("\n\n Wrap: \n"));
rijndaelKeySetupEnc(rk, key, (int)AES_KEY_BITLEN(kl));
/* Set A = IV */
memcpy(A, aeskeywrapIV, AKW_BLOCK_LEN);
/* For i = 1 to n */
/* R[i] = P[i] */
memcpy(R, input, il);
/* For j = 0 to 5 */
for (j = 0; j < 6; j++) {
/* For i = 1 to n */
for (i = 0; i < n; i++) {
dbg(("\n %d\n", (n*j)+i+1));
pinter(" In ", A, il, R);
/* B = AES(K, A | R[i]) */
memcpy(&A[AKW_BLOCK_LEN], &R[i*AKW_BLOCK_LEN], AKW_BLOCK_LEN);
aes_block_encrypt((int)AES_ROUNDS(kl), rk, A, B);
/* R[i] = LSB(64, B) */
memcpy(&R[i*AKW_BLOCK_LEN], &B[AKW_BLOCK_LEN], AKW_BLOCK_LEN);
/* A = MSB(64, B) ^ t where t = (n*j)+i */
memcpy(&A[0], &B[0], AKW_BLOCK_LEN);
pinter(" Enc ", A, il, R);
A[AKW_BLOCK_LEN-1] ^= ((n*j)+i+1);
pinter(" XorT ", A, il, R);
}
}
/* Set C[0] = A */
memcpy(output, A, AKW_BLOCK_LEN);
/* For i = 1 to n */
/* C[i] = R[i] */
memcpy(&output[AKW_BLOCK_LEN], R, il);
return (0);
}
/* aes_unwrap: perform AES-based key unwrap function defined in RFC3394,
* return 0 on success, 1 on error
* input is il bytes
* output is (il-8) bytes
*/
int
BCMROMFN(aes_unwrap)(size_t kl, uint8 *key, size_t il, uint8 *input, uint8 *output)
{
uint32 rk[4*(AES_MAXROUNDS+1)];
uint8 A[AES_BLOCK_SZ];
uint8 R[AKW_MAX_WRAP_LEN + AKW_BLOCK_LEN];
uint8 B[AES_BLOCK_SZ];
size_t ol = il - AKW_BLOCK_LEN;
int n = (int)(ol/AKW_BLOCK_LEN), i, j, k;
/* validate kl (must be valid AES key length) */
if ((kl != 16) && (kl != 24) && (kl != 32)) {
dbg(("aes_wrap: invlaid key length %lu\n", (unsigned long)kl));
return (1);
}
if (il > (AKW_MAX_WRAP_LEN + AKW_BLOCK_LEN)) {
dbg(("aes_unwrap: input length %lu too large\n", (unsigned long)il));
return (1);
}
if (il % AKW_BLOCK_LEN) {
dbg(("aes_unwrap: input length %lu must be a multiple of block length\n",
(unsigned long)il));
return (1);
}
dbg((" Input:\n"));
dbg((" KEK: "));
for (k = 0; k < (int)kl; k++)
dbg(("%02X", key[k]));
dbg(("\n Data: "));
for (k = 0; k < (int)il; k++)
dbg(("%02X", input[k]));
dbg(("\n\n Unwrap: \n"));
rijndaelKeySetupDec(rk, key, (int)AES_KEY_BITLEN(kl));
/* Set A = C[0] */
memcpy(A, input, AKW_BLOCK_LEN);
/* For i = 1 to n */
/* R[i] = C[i] */
memcpy(R, &input[AKW_BLOCK_LEN], ol);
/* For j = 5 to 0 */
for (j = 5; j >= 0; j--) {
/* For i = n to 1 */
for (i = n - 1; i >= 0; i--) {
dbg(("\n %d\n", (n*j)+i+1));
pinter(" In ", A, ol, R);
/* B = AES - 1 (K, (A ^ t) | R[i]) where t = n * j + i */
A[AKW_BLOCK_LEN - 1] ^= ((n*j)+i+1);
pinter(" XorT ", A, ol, R);
memcpy(&A[AKW_BLOCK_LEN], &R[i*AKW_BLOCK_LEN], AKW_BLOCK_LEN);
aes_block_decrypt((int)AES_ROUNDS(kl), rk, A, B);
/* A = MSB(64, B) */
memcpy(&A[0], &B[0], AKW_BLOCK_LEN);
/* R[i] = LSB(64, B) */
memcpy(&R[i*AKW_BLOCK_LEN], &B[AKW_BLOCK_LEN], AKW_BLOCK_LEN);
pinter(" Dec ", A, ol, R);
}
}
if (!memcmp(A, aeskeywrapIV, AKW_BLOCK_LEN)) {
/* For i = 1 to n */
/* P[i] = R[i] */
memcpy(&output[0], R, ol);
return 0;
} else {
dbg(("aes_unwrap: IV mismatch in unwrapped data\n"));
return 1;
}
}
#ifdef BCMAESKEYWRAP_TEST
#include "aeskeywrap_vectors.h"
#define NUM_VECTORS (sizeof(akw_vec)/sizeof(akw_vec[0]))
#define NUM_WRAP_FAIL_VECTORS \
(sizeof(akw_wrap_fail_vec)/sizeof(akw_wrap_fail_vec[0]))
#define NUM_UNWRAP_FAIL_VECTORS \
(sizeof(akw_unwrap_fail_vec)/sizeof(akw_unwrap_fail_vec[0]))
int
main(int argc, char **argv)
{
uint8 output[AKW_MAX_WRAP_LEN+AKW_BLOCK_LEN];
uint8 input2[AKW_MAX_WRAP_LEN];
int retv, k, fail = 0;
for (k = 0; k < NUM_VECTORS; k++) {
retv = aes_wrap(akw_vec[k].kl, akw_vec[k].key, akw_vec[k].il,
akw_vec[k].input, output);
pres("\n AES Wrap: ", akw_vec[k].il+AKW_BLOCK_LEN, output);
if (retv) {
dbg(("%s: aes_wrap failed\n", *argv));
fail++;
}
if (memcmp(output, akw_vec[k].ref, akw_vec[k].il+AKW_BLOCK_LEN) != 0) {
dbg(("%s: aes_wrap failed\n", *argv));
fail++;
}
retv = aes_unwrap(akw_vec[k].kl, akw_vec[k].key, akw_vec[k].il + AKW_BLOCK_LEN,
output, input2);
pres("\n AES Unwrap: ", akw_vec[k].il, input2);
if (retv) {
dbg(("%s: aes_unwrap failed\n", *argv));
fail++;
}
if (memcmp(akw_vec[k].input, input2, akw_vec[k].il) != 0) {
dbg(("%s: aes_unwrap failed\n", *argv));
fail++;
}
}
for (k = 0; k < NUM_WRAP_FAIL_VECTORS; k++) {
if (!aes_wrap(akw_wrap_fail_vec[k].kl, akw_wrap_fail_vec[k].key,
akw_wrap_fail_vec[k].il, akw_wrap_fail_vec[k].input, output)) {
dbg(("%s: aes_wrap didn't detect failure case\n", *argv));
fail++;
}
}
for (k = 0; k < NUM_UNWRAP_FAIL_VECTORS; k++) {
if (!aes_unwrap(akw_unwrap_fail_vec[k].kl, akw_unwrap_fail_vec[k].key,
akw_unwrap_fail_vec[k].il, akw_unwrap_fail_vec[k].input, input2)) {
dbg(("%s: aes_unwrap didn't detect failure case\n", *argv));
fail++;
}
}
dbg(("%s: %s\n", *argv, fail?"FAILED":"PASSED"));
return (fail);
}
#endif /* BCMAESKEYWRAP_TEST */
|
# -*- coding: utf-8 -*-
# ########################## Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Bill Mill <bill.mill@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2013 davidbrai <davidbrai@gmail.com> #
# #
# This file is part of PyGithub. http://jacquev6.github.com/PyGithub/ #
# #
# PyGithub is free software: you can redistribute it and/or modify it under #
# the terms of the GNU Lesser General Public License as published by the Free #
# Software Foundation, either version 3 of the License, or (at your option) #
# any later version. #
# #
# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY #
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS #
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more #
# details. #
# #
# You should have received a copy of the GNU Lesser General Public License #
# along with PyGithub. If not, see <http://www.gnu.org/licenses/>. #
# #
# ##############################################################################
import github.GithubObject
class PaginatedListBase:
def __init__(self):
self.__elements = list()
def __getitem__(self, index):
assert isinstance(index, (int, slice))
if isinstance(index, (int, long)):
self.__fetchToIndex(index)
return self.__elements[index]
else:
return self._Slice(self, index)
def __iter__(self):
for element in self.__elements:
yield element
while self._couldGrow():
newElements = self._grow()
for element in newElements:
yield element
def _isBiggerThan(self, index):
return len(self.__elements) > index or self._couldGrow()
def __fetchToIndex(self, index):
while len(self.__elements) <= index and self._couldGrow():
self._grow()
def _grow(self):
newElements = self._fetchNextPage()
self.__elements += newElements
return newElements
class _Slice:
def __init__(self, theList, theSlice):
self.__list = theList
self.__start = theSlice.start or 0
self.__stop = theSlice.stop
self.__step = theSlice.step or 1
def __iter__(self):
index = self.__start
while not self.__finished(index):
if self.__list._isBiggerThan(index):
yield self.__list[index]
index += self.__step
else:
return
def __finished(self, index):
return self.__stop is not None and index >= self.__stop
class PaginatedList(PaginatedListBase):
"""
This class abstracts the `pagination of the API <http://developer.github.com/v3/#pagination>`_.
You can simply enumerate through instances of this class::
for repo in user.get_repos():
print repo.name
You can also index them or take slices::
second_repo = user.get_repos()[1]
first_repos = user.get_repos()[:10]
If you want to iterate in reversed order, just do::
for repo in user.get_repos().reversed:
print repo.name
And if you really need it, you can explicitely access a specific page::
some_repos = user.get_repos().get_page(0)
some_other_repos = user.get_repos().get_page(3)
"""
def __init__(self, contentClass, requester, firstUrl, firstParams, headers=None):
PaginatedListBase.__init__(self)
self.__requester = requester
self.__contentClass = contentClass
self.__firstUrl = firstUrl
self.__firstParams = firstParams or ()
self.__nextUrl = firstUrl
self.__nextParams = firstParams or {}
self.__headers = headers
if self.__requester.per_page != 30:
self.__nextParams["per_page"] = self.__requester.per_page
self._reversed = False
self.__totalCount = None
@property
def totalCount(self):
if not self.__totalCount:
self._grow()
return self.__totalCount
def _getLastPageUrl(self):
headers, data = self.__requester.requestJsonAndCheck(
"GET",
self.__firstUrl,
parameters=self.__nextParams,
headers=self.__headers
)
links = self.__parseLinkHeader(headers)
lastUrl = links.get("last")
return lastUrl
@property
def reversed(self):
r = PaginatedList(self.__contentClass, self.__requester, self.__firstUrl, self.__firstParams)
r.__reverse()
return r
def __reverse(self):
self._reversed = True
lastUrl = self._getLastPageUrl()
if lastUrl:
self.__nextUrl = lastUrl
def _couldGrow(self):
return self.__nextUrl is not None
def _fetchNextPage(self):
headers, data = self.__requester.requestJsonAndCheck(
"GET",
self.__nextUrl,
parameters=self.__nextParams,
headers=self.__headers
)
data = data if data else []
self.__nextUrl = None
if len(data) > 0:
links = self.__parseLinkHeader(headers)
if self._reversed:
if "prev" in links:
self.__nextUrl = links["prev"]
elif "next" in links:
self.__nextUrl = links["next"]
self.__nextParams = None
if 'items' in data:
self.__totalCount = data['total_count']
data = data["items"]
content = [
self.__contentClass(self.__requester, headers, element, completed=False)
for element in data if element is not None
]
if self._reversed:
return content[::-1]
return content
def __parseLinkHeader(self, headers):
links = {}
if "link" in headers:
linkHeaders = headers["link"].split(", ")
for linkHeader in linkHeaders:
(url, rel) = linkHeader.split("; ")
url = url[1:-1]
rel = rel[5:-1]
links[rel] = url
return links
def get_page(self, page):
params = dict(self.__firstParams)
if page != 0:
params["page"] = page + 1
if self.__requester.per_page != 30:
params["per_page"] = self.__requester.per_page
headers, data = self.__requester.requestJsonAndCheck(
"GET",
self.__firstUrl,
parameters=params,
headers=self.__headers
)
if 'items' in data:
self.__totalCount = data['total_count']
data = data["items"]
return [
self.__contentClass(self.__requester, headers, element, completed=False)
for element in data
]
|
define(["dojo/_base/declare","./AnalogIndicatorBase"],
function(declare, AnalogIndicatorBase) {
return declare("dojox.gauges.AnalogArrowIndicator", [AnalogIndicatorBase],{
// summary:
// An indicator for the AnalogGauge that draws an arrow. The arrow is drawn on the angle that corresponds
// to the value of the indicator.
_getShapes: function(group){
// summary:
// Override of dojox.gauges.AnalogLineIndicator._getShapes
if(!this._gauge){
return null;
}
var color = this.color ? this.color : 'black';
var strokeColor = this.strokeColor ? this.strokeColor : color;
var stroke = { color: strokeColor, width: 1};
if (this.color.type && !this.strokeColor){
stroke.color = this.color.colors[0].color;
}
var x = Math.floor(this.width/2);
var head = this.width * 5;
var odd = (this.width & 1);
var shapes = [];
var points = [{x:-x, y:0},
{x:-x, y:-this.length+head},
{x:-2*x, y:-this.length+head},
{x:0, y:-this.length},
{x:2*x+odd,y:-this.length+head},
{x:x+odd, y:-this.length+head},
{x:x+odd, y:0},
{x:-x, y:0}];
shapes[0] = group.createPolyline(points)
.setStroke(stroke)
.setFill(color);
shapes[1] = group.createLine({ x1:-x, y1: 0, x2: -x, y2:-this.length+head })
.setStroke({color: this.highlight});
shapes[2] = group.createLine({ x1:-x-3, y1: -this.length+head, x2: 0, y2:-this.length })
.setStroke({color: this.highlight});
shapes[3] = group.createCircle({cx: 0, cy: 0, r: this.width})
.setStroke(stroke)
.setFill(color);
return shapes;
}
});
}); |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Gdata
* @subpackage Docs
* @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: DocumentListEntry.php 16971 2009-07-22 18:05:45Z mikaelkael $
*/
/**
* @see Zend_Gdata_EntryAtom
*/
require_once 'Zend/Gdata/Entry.php';
/**
* Represents a Documents List entry in the Documents List data API meta feed
* of a user's documents.
*
* @category Zend
* @package Zend_Gdata
* @subpackage Docs
* @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Gdata_Docs_DocumentListEntry extends Zend_Gdata_Entry
{
/**
* Create a new instance of an entry representing a document.
*
* @param DOMElement $element (optional) DOMElement from which this
* object should be constructed.
*/
public function __construct($element = null)
{
$this->registerAllNamespaces(Zend_Gdata_Docs::$namespaces);
parent::__construct($element);
}
}
|
/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include <seastar/core/thread.hh>
#include "core/do_with.hh"
#include "cql_test_env.hh"
#include "cql3/query_processor.hh"
#include "cql3/query_options.hh"
#include "core/distributed.hh"
#include "core/shared_ptr.hh"
#include "utils/UUID_gen.hh"
#include "service/migration_manager.hh"
#include "message/messaging_service.hh"
#include "service/storage_service.hh"
#include "db/config.hh"
#include "db/batchlog_manager.hh"
#include "schema_builder.hh"
#include "tmpdir.hh"
// TODO: remove (#293)
#include "message/messaging_service.hh"
#include "gms/failure_detector.hh"
#include "gms/gossiper.hh"
#include "service/storage_service.hh"
// TODO : remove once shutdown is ok.
// Broke these test when doing horror patch for #293
// Simpler to copy the code from init.cc than trying to do clever parameterization
// and whatnot.
static future<> tst_init_storage_service(distributed<database>& db) {
return service::init_storage_service(db).then([] {
engine().at_exit([] { return service::deinit_storage_service(); });
});
}
static future<> tst_init_ms_fd_gossiper(sstring listen_address, db::seed_provider_type seed_provider, sstring cluster_name = "Test Cluster") {
const gms::inet_address listen(listen_address);
// Init messaging_service
return net::get_messaging_service().start(listen).then([]{
engine().at_exit([] { return net::get_messaging_service().stop(); });
}).then([] {
// Init failure_detector
return gms::get_failure_detector().start().then([] {
engine().at_exit([]{ return gms::get_failure_detector().stop(); });
});
}).then([listen_address, seed_provider, cluster_name] {
// Init gossiper
std::set<gms::inet_address> seeds;
if (seed_provider.parameters.count("seeds") > 0) {
size_t begin = 0;
size_t next = 0;
sstring seeds_str = seed_provider.parameters.find("seeds")->second;
while (begin < seeds_str.length() && begin != (next=seeds_str.find(",",begin))) {
seeds.emplace(gms::inet_address(seeds_str.substr(begin,next-begin)));
begin = next+1;
}
}
if (seeds.empty()) {
seeds.emplace(gms::inet_address("127.0.0.1"));
}
return gms::get_gossiper().start().then([seeds, cluster_name] {
auto& gossiper = gms::get_local_gossiper();
gossiper.set_seeds(seeds);
gossiper.set_cluster_name(cluster_name);
engine().at_exit([]{ return gms::get_gossiper().stop(); });
});
});
}
// END TODO
future<> init_once(shared_ptr<distributed<database>> db) {
static bool done = false;
if (!done) {
done = true;
// FIXME: we leak db, since we're initializing the global storage_service with it.
new shared_ptr<distributed<database>>(db);
return tst_init_storage_service(*db).then([] {
return tst_init_ms_fd_gossiper("127.0.0.1", db::config::seed_provider_type());
}).then([] {
return db::system_keyspace::init_local_cache();
});
} else {
return make_ready_future();
}
}
class single_node_cql_env : public cql_test_env {
public:
static auto constexpr ks_name = "ks";
private:
::shared_ptr<distributed<database>> _db;
::shared_ptr<distributed<cql3::query_processor>> _qp;
lw_shared_ptr<tmpdir> _data_dir;
private:
struct core_local_state {
service::client_state client_state;
core_local_state()
: client_state(service::client_state::for_external_calls()) {
}
future<> stop() {
return make_ready_future<>();
}
};
distributed<core_local_state> _core_local;
private:
auto make_query_state() {
try {
_core_local.local().client_state.set_keyspace(*_db, ks_name);
} catch (exceptions::invalid_request_exception&) { }
return ::make_shared<service::query_state>(_core_local.local().client_state);
}
public:
single_node_cql_env()
{ }
virtual future<::shared_ptr<transport::messages::result_message>> execute_cql(const sstring& text) override {
auto qs = make_query_state();
return _qp->local().process(text, *qs, cql3::query_options::DEFAULT).finally([qs] {});
}
virtual future<::shared_ptr<transport::messages::result_message>> execute_cql(
const sstring& text,
std::unique_ptr<cql3::query_options> qo) override
{
auto qs = make_query_state();
auto& lqo = *qo;
return _qp->local().process(text, *qs, lqo).finally([qs, qo = std::move(qo)] {});
}
virtual future<bytes> prepare(sstring query) override {
return _qp->invoke_on_all([query, this] (auto& local_qp) {
auto qs = this->make_query_state();
return local_qp.prepare(query, *qs).finally([qs] {}).discard_result();
}).then([query, this] {
return _qp->local().compute_id(query, ks_name);
});
}
virtual future<::shared_ptr<transport::messages::result_message>> execute_prepared(
bytes id,
std::vector<bytes_opt> values) override
{
auto prepared = _qp->local().get_prepared(id);
assert(bool(prepared));
auto stmt = prepared->statement;
assert(stmt->get_bound_terms() == values.size());
auto options = ::make_shared<cql3::query_options>(std::move(values));
options->prepare(prepared->bound_names);
auto qs = make_query_state();
return _qp->local().process_statement(stmt, *qs, *options)
.finally([options, qs] {});
}
virtual future<> create_table(std::function<schema(const sstring&)> schema_maker) override {
auto id = utils::UUID_gen::get_time_UUID();
return _db->invoke_on_all([schema_maker, id, this] (database& db) {
schema_builder builder(make_lw_shared(schema_maker(ks_name)));
builder.set_uuid(id);
auto cf_schema = builder.build(schema_builder::compact_storage::no);
auto& ks = db.find_keyspace(ks_name);
auto cfg = ks.make_column_family_config(*cf_schema);
db.add_column_family(std::move(cf_schema), std::move(cfg));
});
}
virtual future<> require_keyspace_exists(const sstring& ks_name) override {
auto& db = _db->local();
assert(db.has_keyspace(ks_name));
return make_ready_future<>();
}
virtual future<> require_table_exists(const sstring& ks_name, const sstring& table_name) override {
auto& db = _db->local();
assert(db.has_schema(ks_name, table_name));
return make_ready_future<>();
}
virtual future<> require_column_has_value(const sstring& table_name,
std::vector<boost::any> pk,
std::vector<boost::any> ck,
const sstring& column_name,
boost::any expected) override {
auto& db = _db->local();
auto& cf = db.find_column_family(ks_name, table_name);
auto schema = cf.schema();
auto pkey = partition_key::from_deeply_exploded(*schema, pk);
auto dk = dht::global_partitioner().decorate_key(*schema, pkey);
auto shard = db.shard_of(dk._token);
return _db->invoke_on(shard, [pkey = std::move(pkey),
ck = std::move(ck),
ks_name = std::move(ks_name),
column_name = std::move(column_name),
expected = std::move(expected),
table_name = std::move(table_name)] (database& db) mutable {
auto& cf = db.find_column_family(ks_name, table_name);
auto schema = cf.schema();
return cf.find_partition_slow(pkey).then([schema, ck, column_name, expected] (column_family::const_mutation_partition_ptr p) {
assert(p != nullptr);
auto row = p->find_row(clustering_key::from_deeply_exploded(*schema, ck));
assert(row != nullptr);
auto col_def = schema->get_column_definition(utf8_type->decompose(column_name));
assert(col_def != nullptr);
const atomic_cell_or_collection* cell = row->find_cell(col_def->id);
if (!cell) {
assert(((void)"column not set", 0));
}
bytes actual;
if (!col_def->type->is_multi_cell()) {
auto c = cell->as_atomic_cell();
assert(c.is_live());
actual = { c.value().begin(), c.value().end() };
} else {
auto c = cell->as_collection_mutation();
auto type = dynamic_pointer_cast<const collection_type_impl>(col_def->type);
actual = type->to_value(type->deserialize_mutation_form(c),
serialization_format::internal());
}
assert(col_def->type->equal(actual, col_def->type->decompose(expected)));
});
});
}
virtual database& local_db() override {
return _db->local();
}
cql3::query_processor& local_qp() override {
return _qp->local();
}
future<> start() {
return seastar::async([this] {
locator::i_endpoint_snitch::create_snitch("SimpleSnitch").get();
auto db = ::make_shared<distributed<database>>();
init_once(db).get();
auto cfg = make_lw_shared<db::config>();
_data_dir = make_lw_shared<tmpdir>();
cfg->data_file_directories() = { _data_dir->path };
boost::filesystem::create_directories((_data_dir->path + "/system").c_str());
db->start(std::move(*cfg)).get();
distributed<service::storage_proxy>& proxy = service::get_storage_proxy();
distributed<service::migration_manager>& mm = service::get_migration_manager();
distributed<db::batchlog_manager>& bm = db::get_batchlog_manager();
auto qp = ::make_shared<distributed<cql3::query_processor>>();
proxy.start(std::ref(*db)).get();
mm.start().get();
qp->start(std::ref(proxy), std::ref(*db)).get();
auto& ss = service::get_local_storage_service();
static bool storage_service_started = false;
if (!storage_service_started) {
storage_service_started = true;
ss.init_server().get();
}
bm.start(std::ref(*qp)).get();
_core_local.start().get();
_db = std::move(db);
_qp = std::move(qp);
auto query = sprint("create keyspace %s with replication = { 'class' : 'org.apache.cassandra.locator.SimpleStrategy', 'replication_factor' : 1 };", sstring{ks_name});
execute_cql(query).get();
});
}
virtual future<> stop() override {
return _core_local.stop().then([this] {
return db::get_batchlog_manager().stop().then([this] {
return _qp->stop().then([this] {
return service::get_migration_manager().stop().then([this] {
return service::get_storage_proxy().stop().then([this] {
return _db->stop().then([this] {
return locator::i_endpoint_snitch::stop_snitch();
});
});
});
});
});
});
}
};
future<::shared_ptr<cql_test_env>> make_env_for_test() {
return seastar::async([] {
auto env = ::make_shared<single_node_cql_env>();
env->start().get();
return dynamic_pointer_cast<cql_test_env>(env);
});
}
future<> do_with_cql_env(std::function<future<>(cql_test_env&)> func) {
return make_env_for_test().then([func = std::move(func)] (auto e) mutable {
return do_with(std::move(func), [e] (auto& f) {
return f(*e);
}).finally([e] {
return e->stop().finally([e] {});
});
});
}
|
/**
******************************************************************************
* @file stm32l4xx_ll_crc.h
* @author MCD Application Team
* @version V1.7.1
* @date 21-April-2017
* @brief Header file of CRC LL module.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2017 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32L4xx_LL_CRC_H
#define __STM32L4xx_LL_CRC_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32l4xx.h"
/** @addtogroup STM32L4xx_LL_Driver
* @{
*/
#if defined(CRC)
/** @defgroup CRC_LL CRC
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/
/** @defgroup CRC_LL_Exported_Constants CRC Exported Constants
* @{
*/
/** @defgroup CRC_LL_EC_POLYLENGTH Polynomial length
* @{
*/
#define LL_CRC_POLYLENGTH_32B 0x00000000U /*!< 32 bits Polynomial size */
#define LL_CRC_POLYLENGTH_16B CRC_CR_POLYSIZE_0 /*!< 16 bits Polynomial size */
#define LL_CRC_POLYLENGTH_8B CRC_CR_POLYSIZE_1 /*!< 8 bits Polynomial size */
#define LL_CRC_POLYLENGTH_7B (CRC_CR_POLYSIZE_1 | CRC_CR_POLYSIZE_0) /*!< 7 bits Polynomial size */
/**
* @}
*/
/** @defgroup CRC_LL_EC_INDATA_REVERSE Input Data Reverse
* @{
*/
#define LL_CRC_INDATA_REVERSE_NONE 0x00000000U /*!< Input Data bit order not affected */
#define LL_CRC_INDATA_REVERSE_BYTE CRC_CR_REV_IN_0 /*!< Input Data bit reversal done by byte */
#define LL_CRC_INDATA_REVERSE_HALFWORD CRC_CR_REV_IN_1 /*!< Input Data bit reversal done by half-word */
#define LL_CRC_INDATA_REVERSE_WORD (CRC_CR_REV_IN_1 | CRC_CR_REV_IN_0) /*!< Input Data bit reversal done by word */
/**
* @}
*/
/** @defgroup CRC_LL_EC_OUTDATA_REVERSE Output Data Reverse
* @{
*/
#define LL_CRC_OUTDATA_REVERSE_NONE 0x00000000U /*!< Output Data bit order not affected */
#define LL_CRC_OUTDATA_REVERSE_BIT CRC_CR_REV_OUT /*!< Output Data bit reversal done by bit */
/**
* @}
*/
/** @defgroup CRC_LL_EC_Default_Polynomial_Value Default CRC generating polynomial value
* @brief Normal representation of this polynomial value is
* X^32 + X^26 + X^23 + X^22 + X^16 + X^12 + X^11 + X^10 +X^8 + X^7 + X^5 + X^4 + X^2 + X + 1 .
* @{
*/
#define LL_CRC_DEFAULT_CRC32_POLY 0x04C11DB7U /*!< Default CRC generating polynomial value */
/**
* @}
*/
/** @defgroup CRC_LL_EC_Default_InitValue Default CRC computation initialization value
* @{
*/
#define LL_CRC_DEFAULT_CRC_INITVALUE 0xFFFFFFFFU /*!< Default CRC computation initialization value */
/**
* @}
*/
/**
* @}
*/
/* Exported macro ------------------------------------------------------------*/
/** @defgroup CRC_LL_Exported_Macros CRC Exported Macros
* @{
*/
/** @defgroup CRC_LL_EM_WRITE_READ Common Write and read registers Macros
* @{
*/
/**
* @brief Write a value in CRC register
* @param __INSTANCE__ CRC Instance
* @param __REG__ Register to be written
* @param __VALUE__ Value to be written in the register
* @retval None
*/
#define LL_CRC_WriteReg(__INSTANCE__, __REG__, __VALUE__) WRITE_REG(__INSTANCE__->__REG__, (__VALUE__))
/**
* @brief Read a value in CRC register
* @param __INSTANCE__ CRC Instance
* @param __REG__ Register to be read
* @retval Register value
*/
#define LL_CRC_ReadReg(__INSTANCE__, __REG__) READ_REG(__INSTANCE__->__REG__)
/**
* @}
*/
/**
* @}
*/
/* Exported functions --------------------------------------------------------*/
/** @defgroup CRC_LL_Exported_Functions CRC Exported Functions
* @{
*/
/** @defgroup CRC_LL_EF_Configuration CRC Configuration functions
* @{
*/
/**
* @brief Reset the CRC calculation unit.
* @note If Programmable Initial CRC value feature
* is available, also set the Data Register to the value stored in the
* CRC_INIT register, otherwise, reset Data Register to its default value.
* @rmtoll CR RESET LL_CRC_ResetCRCCalculationUnit
* @param CRCx CRC Instance
* @retval None
*/
__STATIC_INLINE void LL_CRC_ResetCRCCalculationUnit(CRC_TypeDef *CRCx)
{
SET_BIT(CRCx->CR, CRC_CR_RESET);
}
/**
* @brief Configure size of the polynomial.
* @rmtoll CR POLYSIZE LL_CRC_SetPolynomialSize
* @param CRCx CRC Instance
* @param PolySize This parameter can be one of the following values:
* @arg @ref LL_CRC_POLYLENGTH_32B
* @arg @ref LL_CRC_POLYLENGTH_16B
* @arg @ref LL_CRC_POLYLENGTH_8B
* @arg @ref LL_CRC_POLYLENGTH_7B
* @retval None
*/
__STATIC_INLINE void LL_CRC_SetPolynomialSize(CRC_TypeDef *CRCx, uint32_t PolySize)
{
MODIFY_REG(CRCx->CR, CRC_CR_POLYSIZE, PolySize);
}
/**
* @brief Return size of the polynomial.
* @rmtoll CR POLYSIZE LL_CRC_GetPolynomialSize
* @param CRCx CRC Instance
* @retval Returned value can be one of the following values:
* @arg @ref LL_CRC_POLYLENGTH_32B
* @arg @ref LL_CRC_POLYLENGTH_16B
* @arg @ref LL_CRC_POLYLENGTH_8B
* @arg @ref LL_CRC_POLYLENGTH_7B
*/
__STATIC_INLINE uint32_t LL_CRC_GetPolynomialSize(CRC_TypeDef *CRCx)
{
return (uint32_t)(READ_BIT(CRCx->CR, CRC_CR_POLYSIZE));
}
/**
* @brief Configure the reversal of the bit order of the input data
* @rmtoll CR REV_IN LL_CRC_SetInputDataReverseMode
* @param CRCx CRC Instance
* @param ReverseMode This parameter can be one of the following values:
* @arg @ref LL_CRC_INDATA_REVERSE_NONE
* @arg @ref LL_CRC_INDATA_REVERSE_BYTE
* @arg @ref LL_CRC_INDATA_REVERSE_HALFWORD
* @arg @ref LL_CRC_INDATA_REVERSE_WORD
* @retval None
*/
__STATIC_INLINE void LL_CRC_SetInputDataReverseMode(CRC_TypeDef *CRCx, uint32_t ReverseMode)
{
MODIFY_REG(CRCx->CR, CRC_CR_REV_IN, ReverseMode);
}
/**
* @brief Return type of reversal for input data bit order
* @rmtoll CR REV_IN LL_CRC_GetInputDataReverseMode
* @param CRCx CRC Instance
* @retval Returned value can be one of the following values:
* @arg @ref LL_CRC_INDATA_REVERSE_NONE
* @arg @ref LL_CRC_INDATA_REVERSE_BYTE
* @arg @ref LL_CRC_INDATA_REVERSE_HALFWORD
* @arg @ref LL_CRC_INDATA_REVERSE_WORD
*/
__STATIC_INLINE uint32_t LL_CRC_GetInputDataReverseMode(CRC_TypeDef *CRCx)
{
return (uint32_t)(READ_BIT(CRCx->CR, CRC_CR_REV_IN));
}
/**
* @brief Configure the reversal of the bit order of the Output data
* @rmtoll CR REV_OUT LL_CRC_SetOutputDataReverseMode
* @param CRCx CRC Instance
* @param ReverseMode This parameter can be one of the following values:
* @arg @ref LL_CRC_OUTDATA_REVERSE_NONE
* @arg @ref LL_CRC_OUTDATA_REVERSE_BIT
* @retval None
*/
__STATIC_INLINE void LL_CRC_SetOutputDataReverseMode(CRC_TypeDef *CRCx, uint32_t ReverseMode)
{
MODIFY_REG(CRCx->CR, CRC_CR_REV_OUT, ReverseMode);
}
/**
* @brief Configure the reversal of the bit order of the Output data
* @rmtoll CR REV_OUT LL_CRC_GetOutputDataReverseMode
* @param CRCx CRC Instance
* @retval Returned value can be one of the following values:
* @arg @ref LL_CRC_OUTDATA_REVERSE_NONE
* @arg @ref LL_CRC_OUTDATA_REVERSE_BIT
*/
__STATIC_INLINE uint32_t LL_CRC_GetOutputDataReverseMode(CRC_TypeDef *CRCx)
{
return (uint32_t)(READ_BIT(CRCx->CR, CRC_CR_REV_OUT));
}
/**
* @brief Initialize the Programmable initial CRC value.
* @note If the CRC size is less than 32 bits, the least significant bits
* are used to write the correct value
* @note LL_CRC_DEFAULT_CRC_INITVALUE could be used as value for InitCrc parameter.
* @rmtoll INIT INIT LL_CRC_SetInitialData
* @param CRCx CRC Instance
* @param InitCrc Value to be programmed in Programmable initial CRC value register
* @retval None
*/
__STATIC_INLINE void LL_CRC_SetInitialData(CRC_TypeDef *CRCx, uint32_t InitCrc)
{
WRITE_REG(CRCx->INIT, InitCrc);
}
/**
* @brief Return current Initial CRC value.
* @note If the CRC size is less than 32 bits, the least significant bits
* are used to read the correct value
* @rmtoll INIT INIT LL_CRC_GetInitialData
* @param CRCx CRC Instance
* @retval Value programmed in Programmable initial CRC value register
*/
__STATIC_INLINE uint32_t LL_CRC_GetInitialData(CRC_TypeDef *CRCx)
{
return (uint32_t)(READ_REG(CRCx->INIT));
}
/**
* @brief Initialize the Programmable polynomial value
* (coefficients of the polynomial to be used for CRC calculation).
* @note LL_CRC_DEFAULT_CRC32_POLY could be used as value for PolynomCoef parameter.
* @note Please check Reference Manual and existing Errata Sheets,
* regarding possible limitations for Polynomial values usage.
* For example, for a polynomial of degree 7, X^7 + X^6 + X^5 + X^2 + 1 is written 0x65
* @rmtoll POL POL LL_CRC_SetPolynomialCoef
* @param CRCx CRC Instance
* @param PolynomCoef Value to be programmed in Programmable Polynomial value register
* @retval None
*/
__STATIC_INLINE void LL_CRC_SetPolynomialCoef(CRC_TypeDef *CRCx, uint32_t PolynomCoef)
{
WRITE_REG(CRCx->POL, PolynomCoef);
}
/**
* @brief Return current Programmable polynomial value
* @note Please check Reference Manual and existing Errata Sheets,
* regarding possible limitations for Polynomial values usage.
* For example, for a polynomial of degree 7, X^7 + X^6 + X^5 + X^2 + 1 is written 0x65
* @rmtoll POL POL LL_CRC_GetPolynomialCoef
* @param CRCx CRC Instance
* @retval Value programmed in Programmable Polynomial value register
*/
__STATIC_INLINE uint32_t LL_CRC_GetPolynomialCoef(CRC_TypeDef *CRCx)
{
return (uint32_t)(READ_REG(CRCx->POL));
}
/**
* @}
*/
/** @defgroup CRC_LL_EF_Data_Management Data_Management
* @{
*/
/**
* @brief Write given 32-bit data to the CRC calculator
* @rmtoll DR DR LL_CRC_FeedData32
* @param CRCx CRC Instance
* @param InData value to be provided to CRC calculator between between Min_Data=0 and Max_Data=0xFFFFFFFF
* @retval None
*/
__STATIC_INLINE void LL_CRC_FeedData32(CRC_TypeDef *CRCx, uint32_t InData)
{
WRITE_REG(CRCx->DR, InData);
}
/**
* @brief Write given 16-bit data to the CRC calculator
* @rmtoll DR DR LL_CRC_FeedData16
* @param CRCx CRC Instance
* @param InData 16 bit value to be provided to CRC calculator between between Min_Data=0 and Max_Data=0xFFFF
* @retval None
*/
__STATIC_INLINE void LL_CRC_FeedData16(CRC_TypeDef *CRCx, uint16_t InData)
{
*(uint16_t __IO *)(&CRCx->DR) = (uint16_t) InData;
}
/**
* @brief Write given 8-bit data to the CRC calculator
* @rmtoll DR DR LL_CRC_FeedData8
* @param CRCx CRC Instance
* @param InData 8 bit value to be provided to CRC calculator between between Min_Data=0 and Max_Data=0xFF
* @retval None
*/
__STATIC_INLINE void LL_CRC_FeedData8(CRC_TypeDef *CRCx, uint8_t InData)
{
*(uint8_t __IO *)(&CRCx->DR) = (uint8_t) InData;
}
/**
* @brief Return current CRC calculation result. 32 bits value is returned.
* @rmtoll DR DR LL_CRC_ReadData32
* @param CRCx CRC Instance
* @retval Current CRC calculation result as stored in CRC_DR register (32 bits).
*/
__STATIC_INLINE uint32_t LL_CRC_ReadData32(CRC_TypeDef *CRCx)
{
return (uint32_t)(READ_REG(CRCx->DR));
}
/**
* @brief Return current CRC calculation result. 16 bits value is returned.
* @note This function is expected to be used in a 16 bits CRC polynomial size context.
* @rmtoll DR DR LL_CRC_ReadData16
* @param CRCx CRC Instance
* @retval Current CRC calculation result as stored in CRC_DR register (16 bits).
*/
__STATIC_INLINE uint16_t LL_CRC_ReadData16(CRC_TypeDef *CRCx)
{
return (uint16_t)READ_REG(CRCx->DR);
}
/**
* @brief Return current CRC calculation result. 8 bits value is returned.
* @note This function is expected to be used in a 8 bits CRC polynomial size context.
* @rmtoll DR DR LL_CRC_ReadData8
* @param CRCx CRC Instance
* @retval Current CRC calculation result as stored in CRC_DR register (8 bits).
*/
__STATIC_INLINE uint8_t LL_CRC_ReadData8(CRC_TypeDef *CRCx)
{
return (uint8_t)READ_REG(CRCx->DR);
}
/**
* @brief Return current CRC calculation result. 7 bits value is returned.
* @note This function is expected to be used in a 7 bits CRC polynomial size context.
* @rmtoll DR DR LL_CRC_ReadData7
* @param CRCx CRC Instance
* @retval Current CRC calculation result as stored in CRC_DR register (7 bits).
*/
__STATIC_INLINE uint8_t LL_CRC_ReadData7(CRC_TypeDef *CRCx)
{
return (uint8_t)(READ_REG(CRCx->DR) & 0x7FU);
}
/**
* @brief Return data stored in the Independent Data(IDR) register.
* @note This register can be used as a temporary storage location for one byte.
* @rmtoll IDR IDR LL_CRC_Read_IDR
* @param CRCx CRC Instance
* @retval Value stored in CRC_IDR register (General-purpose 8-bit data register).
*/
__STATIC_INLINE uint32_t LL_CRC_Read_IDR(CRC_TypeDef *CRCx)
{
return (uint32_t)(READ_REG(CRCx->IDR));
}
/**
* @brief Store data in the Independent Data(IDR) register.
* @note This register can be used as a temporary storage location for one byte.
* @rmtoll IDR IDR LL_CRC_Write_IDR
* @param CRCx CRC Instance
* @param InData value to be stored in CRC_IDR register (8-bit) between between Min_Data=0 and Max_Data=0xFF
* @retval None
*/
__STATIC_INLINE void LL_CRC_Write_IDR(CRC_TypeDef *CRCx, uint32_t InData)
{
*((uint8_t __IO *)(&CRCx->IDR)) = (uint8_t) InData;
}
/**
* @}
*/
#if defined(USE_FULL_LL_DRIVER)
/** @defgroup CRC_LL_EF_Init Initialization and de-initialization functions
* @{
*/
ErrorStatus LL_CRC_DeInit(CRC_TypeDef *CRCx);
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
/**
* @}
*/
/**
* @}
*/
#endif /* defined(CRC) */
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __STM32L4xx_LL_CRC_H */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
package cognitoidentity_test
import (
"bytes"
"fmt"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cognitoidentity"
)
var _ time.Duration
var _ bytes.Buffer
func ExampleCognitoIdentity_CreateIdentityPool() {
sess, err := session.NewSession()
if err != nil {
fmt.Println("failed to create session,", err)
return
}
svc := cognitoidentity.New(sess)
params := &cognitoidentity.CreateIdentityPoolInput{
AllowUnauthenticatedIdentities: aws.Bool(true), // Required
IdentityPoolName: aws.String("IdentityPoolName"), // Required
CognitoIdentityProviders: []*cognitoidentity.Provider{
{ // Required
ClientId: aws.String("ProviderClientId"),
ProviderName: aws.String("ProviderName"),
},
// More values...
},
DeveloperProviderName: aws.String("DeveloperProviderName"),
OpenIdConnectProviderARNs: []*string{
aws.String("ARNString"), // Required
// More values...
},
SamlProviderARNs: []*string{
aws.String("ARNString"), // Required
// More values...
},
SupportedLoginProviders: map[string]*string{
"Key": aws.String("IdentityProviderId"), // Required
// More values...
},
}
resp, err := svc.CreateIdentityPool(params)
if err != nil {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
return
}
// Pretty-print the response data.
fmt.Println(resp)
}
func ExampleCognitoIdentity_DeleteIdentities() {
sess, err := session.NewSession()
if err != nil {
fmt.Println("failed to create session,", err)
return
}
svc := cognitoidentity.New(sess)
params := &cognitoidentity.DeleteIdentitiesInput{
IdentityIdsToDelete: []*string{ // Required
aws.String("IdentityId"), // Required
// More values...
},
}
resp, err := svc.DeleteIdentities(params)
if err != nil {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
return
}
// Pretty-print the response data.
fmt.Println(resp)
}
func ExampleCognitoIdentity_DeleteIdentityPool() {
sess, err := session.NewSession()
if err != nil {
fmt.Println("failed to create session,", err)
return
}
svc := cognitoidentity.New(sess)
params := &cognitoidentity.DeleteIdentityPoolInput{
IdentityPoolId: aws.String("IdentityPoolId"), // Required
}
resp, err := svc.DeleteIdentityPool(params)
if err != nil {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
return
}
// Pretty-print the response data.
fmt.Println(resp)
}
func ExampleCognitoIdentity_DescribeIdentity() {
sess, err := session.NewSession()
if err != nil {
fmt.Println("failed to create session,", err)
return
}
svc := cognitoidentity.New(sess)
params := &cognitoidentity.DescribeIdentityInput{
IdentityId: aws.String("IdentityId"), // Required
}
resp, err := svc.DescribeIdentity(params)
if err != nil {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
return
}
// Pretty-print the response data.
fmt.Println(resp)
}
func ExampleCognitoIdentity_DescribeIdentityPool() {
sess, err := session.NewSession()
if err != nil {
fmt.Println("failed to create session,", err)
return
}
svc := cognitoidentity.New(sess)
params := &cognitoidentity.DescribeIdentityPoolInput{
IdentityPoolId: aws.String("IdentityPoolId"), // Required
}
resp, err := svc.DescribeIdentityPool(params)
if err != nil {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
return
}
// Pretty-print the response data.
fmt.Println(resp)
}
func ExampleCognitoIdentity_GetCredentialsForIdentity() {
sess, err := session.NewSession()
if err != nil {
fmt.Println("failed to create session,", err)
return
}
svc := cognitoidentity.New(sess)
params := &cognitoidentity.GetCredentialsForIdentityInput{
IdentityId: aws.String("IdentityId"), // Required
CustomRoleArn: aws.String("ARNString"),
Logins: map[string]*string{
"Key": aws.String("IdentityProviderToken"), // Required
// More values...
},
}
resp, err := svc.GetCredentialsForIdentity(params)
if err != nil {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
return
}
// Pretty-print the response data.
fmt.Println(resp)
}
func ExampleCognitoIdentity_GetId() {
sess, err := session.NewSession()
if err != nil {
fmt.Println("failed to create session,", err)
return
}
svc := cognitoidentity.New(sess)
params := &cognitoidentity.GetIdInput{
IdentityPoolId: aws.String("IdentityPoolId"), // Required
AccountId: aws.String("AccountId"),
Logins: map[string]*string{
"Key": aws.String("IdentityProviderToken"), // Required
// More values...
},
}
resp, err := svc.GetId(params)
if err != nil {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
return
}
// Pretty-print the response data.
fmt.Println(resp)
}
func ExampleCognitoIdentity_GetIdentityPoolRoles() {
sess, err := session.NewSession()
if err != nil {
fmt.Println("failed to create session,", err)
return
}
svc := cognitoidentity.New(sess)
params := &cognitoidentity.GetIdentityPoolRolesInput{
IdentityPoolId: aws.String("IdentityPoolId"), // Required
}
resp, err := svc.GetIdentityPoolRoles(params)
if err != nil {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
return
}
// Pretty-print the response data.
fmt.Println(resp)
}
func ExampleCognitoIdentity_GetOpenIdToken() {
sess, err := session.NewSession()
if err != nil {
fmt.Println("failed to create session,", err)
return
}
svc := cognitoidentity.New(sess)
params := &cognitoidentity.GetOpenIdTokenInput{
IdentityId: aws.String("IdentityId"), // Required
Logins: map[string]*string{
"Key": aws.String("IdentityProviderToken"), // Required
// More values...
},
}
resp, err := svc.GetOpenIdToken(params)
if err != nil {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
return
}
// Pretty-print the response data.
fmt.Println(resp)
}
func ExampleCognitoIdentity_GetOpenIdTokenForDeveloperIdentity() {
sess, err := session.NewSession()
if err != nil {
fmt.Println("failed to create session,", err)
return
}
svc := cognitoidentity.New(sess)
params := &cognitoidentity.GetOpenIdTokenForDeveloperIdentityInput{
IdentityPoolId: aws.String("IdentityPoolId"), // Required
Logins: map[string]*string{ // Required
"Key": aws.String("IdentityProviderToken"), // Required
// More values...
},
IdentityId: aws.String("IdentityId"),
TokenDuration: aws.Int64(1),
}
resp, err := svc.GetOpenIdTokenForDeveloperIdentity(params)
if err != nil {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
return
}
// Pretty-print the response data.
fmt.Println(resp)
}
func ExampleCognitoIdentity_ListIdentities() {
sess, err := session.NewSession()
if err != nil {
fmt.Println("failed to create session,", err)
return
}
svc := cognitoidentity.New(sess)
params := &cognitoidentity.ListIdentitiesInput{
IdentityPoolId: aws.String("IdentityPoolId"), // Required
MaxResults: aws.Int64(1), // Required
HideDisabled: aws.Bool(true),
NextToken: aws.String("PaginationKey"),
}
resp, err := svc.ListIdentities(params)
if err != nil {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
return
}
// Pretty-print the response data.
fmt.Println(resp)
}
func ExampleCognitoIdentity_ListIdentityPools() {
sess, err := session.NewSession()
if err != nil {
fmt.Println("failed to create session,", err)
return
}
svc := cognitoidentity.New(sess)
params := &cognitoidentity.ListIdentityPoolsInput{
MaxResults: aws.Int64(1), // Required
NextToken: aws.String("PaginationKey"),
}
resp, err := svc.ListIdentityPools(params)
if err != nil {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
return
}
// Pretty-print the response data.
fmt.Println(resp)
}
func ExampleCognitoIdentity_LookupDeveloperIdentity() {
sess, err := session.NewSession()
if err != nil {
fmt.Println("failed to create session,", err)
return
}
svc := cognitoidentity.New(sess)
params := &cognitoidentity.LookupDeveloperIdentityInput{
IdentityPoolId: aws.String("IdentityPoolId"), // Required
DeveloperUserIdentifier: aws.String("DeveloperUserIdentifier"),
IdentityId: aws.String("IdentityId"),
MaxResults: aws.Int64(1),
NextToken: aws.String("PaginationKey"),
}
resp, err := svc.LookupDeveloperIdentity(params)
if err != nil {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
return
}
// Pretty-print the response data.
fmt.Println(resp)
}
func ExampleCognitoIdentity_MergeDeveloperIdentities() {
sess, err := session.NewSession()
if err != nil {
fmt.Println("failed to create session,", err)
return
}
svc := cognitoidentity.New(sess)
params := &cognitoidentity.MergeDeveloperIdentitiesInput{
DestinationUserIdentifier: aws.String("DeveloperUserIdentifier"), // Required
DeveloperProviderName: aws.String("DeveloperProviderName"), // Required
IdentityPoolId: aws.String("IdentityPoolId"), // Required
SourceUserIdentifier: aws.String("DeveloperUserIdentifier"), // Required
}
resp, err := svc.MergeDeveloperIdentities(params)
if err != nil {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
return
}
// Pretty-print the response data.
fmt.Println(resp)
}
func ExampleCognitoIdentity_SetIdentityPoolRoles() {
sess, err := session.NewSession()
if err != nil {
fmt.Println("failed to create session,", err)
return
}
svc := cognitoidentity.New(sess)
params := &cognitoidentity.SetIdentityPoolRolesInput{
IdentityPoolId: aws.String("IdentityPoolId"), // Required
Roles: map[string]*string{ // Required
"Key": aws.String("ARNString"), // Required
// More values...
},
}
resp, err := svc.SetIdentityPoolRoles(params)
if err != nil {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
return
}
// Pretty-print the response data.
fmt.Println(resp)
}
func ExampleCognitoIdentity_UnlinkDeveloperIdentity() {
sess, err := session.NewSession()
if err != nil {
fmt.Println("failed to create session,", err)
return
}
svc := cognitoidentity.New(sess)
params := &cognitoidentity.UnlinkDeveloperIdentityInput{
DeveloperProviderName: aws.String("DeveloperProviderName"), // Required
DeveloperUserIdentifier: aws.String("DeveloperUserIdentifier"), // Required
IdentityId: aws.String("IdentityId"), // Required
IdentityPoolId: aws.String("IdentityPoolId"), // Required
}
resp, err := svc.UnlinkDeveloperIdentity(params)
if err != nil {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
return
}
// Pretty-print the response data.
fmt.Println(resp)
}
func ExampleCognitoIdentity_UnlinkIdentity() {
sess, err := session.NewSession()
if err != nil {
fmt.Println("failed to create session,", err)
return
}
svc := cognitoidentity.New(sess)
params := &cognitoidentity.UnlinkIdentityInput{
IdentityId: aws.String("IdentityId"), // Required
Logins: map[string]*string{ // Required
"Key": aws.String("IdentityProviderToken"), // Required
// More values...
},
LoginsToRemove: []*string{ // Required
aws.String("IdentityProviderName"), // Required
// More values...
},
}
resp, err := svc.UnlinkIdentity(params)
if err != nil {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
return
}
// Pretty-print the response data.
fmt.Println(resp)
}
func ExampleCognitoIdentity_UpdateIdentityPool() {
sess, err := session.NewSession()
if err != nil {
fmt.Println("failed to create session,", err)
return
}
svc := cognitoidentity.New(sess)
params := &cognitoidentity.IdentityPool{
AllowUnauthenticatedIdentities: aws.Bool(true), // Required
IdentityPoolId: aws.String("IdentityPoolId"), // Required
IdentityPoolName: aws.String("IdentityPoolName"), // Required
CognitoIdentityProviders: []*cognitoidentity.Provider{
{ // Required
ClientId: aws.String("ProviderClientId"),
ProviderName: aws.String("ProviderName"),
},
// More values...
},
DeveloperProviderName: aws.String("DeveloperProviderName"),
OpenIdConnectProviderARNs: []*string{
aws.String("ARNString"), // Required
// More values...
},
SamlProviderARNs: []*string{
aws.String("ARNString"), // Required
// More values...
},
SupportedLoginProviders: map[string]*string{
"Key": aws.String("IdentityProviderId"), // Required
// More values...
},
}
resp, err := svc.UpdateIdentityPool(params)
if err != nil {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
return
}
// Pretty-print the response data.
fmt.Println(resp)
}
|
/*
*
* Copyright 2015-2016, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef GRPC_SUPPORT_LOG_WIN32_H
#define GRPC_SUPPORT_LOG_WIN32_H
#ifdef __cplusplus
extern "C" {
#endif
/* Returns a string allocated with gpr_malloc that contains a UTF-8
* formatted error message, corresponding to the error messageid.
* Use in conjunction with GetLastError() et al.
*/
GPR_API char *gpr_format_message(int messageid);
#ifdef __cplusplus
}
#endif
#endif /* GRPC_SUPPORT_LOG_WIN32_H */
|
/*
* Copyright 2013 Orient Technologies.
* Copyright 2013 Geomatys.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.sql.method.misc;
import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
/**
* Returns the value's Java type.
*
* @author Luca Garulli
*/
public class OSQLMethodJavaType extends OAbstractSQLMethod {
public static final String NAME = "javatype";
public OSQLMethodJavaType() {
super(NAME);
}
@Override
public Object execute(Object iThis, OIdentifiable iCurrentRecord, OCommandContext iContext, Object ioResult, Object[] iParams) {
if (ioResult == null) {
return null;
}
return ioResult.getClass().getName();
}
}
|
#!/bin/bash
#
# Copyright 2015 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# OS X relpath is not really working. This is a wrapper script around gcc
# to simulate relpath behavior.
#
# This wrapper uses install_name_tool to replace all paths in the binary
# (bazel-out/.../path/to/original/library.so) by the paths relative to
# the binary. It parses the command line to behave as rpath is supposed
# to work.
#
# See https://blogs.oracle.com/dipol/entry/dynamic_libraries_rpath_and_mac
# on how to set those paths for Mach-O binaries.
#
set -eu
GCC=/usr/bin/gcc
INSTALL_NAME_TOOL="/usr/bin/install_name_tool"
LIBS=
LIB_DIRS=
RPATH=
OUTPUT=
# let parse the option list
for i in "$@"; do
if [[ "${OUTPUT}" = "1" ]]; then
OUTPUT=$i
elif [[ "$i" =~ ^-l(.*)$ ]]; then
# lib
LIBS="${BASH_REMATCH[1]} $LIBS"
elif [[ "$i" =~ ^-L(.*)$ ]]; then
# lib
LIB_DIRS="${BASH_REMATCH[1]} $LIB_DIRS"
elif [[ "$i" =~ ^-Wl,-rpath,\$ORIGIN/(.*)$ ]]; then
# rpath
RPATH=${BASH_REMATCH[1]}
elif [[ "$i" = "-o" ]]; then
# output is coming
OUTPUT=1
fi
done
# Call gcc
${GCC} "$@"
function get_library_path() {
for libdir in ${LIB_DIRS}; do
if [ -f ${libdir}/lib$1.so ]; then
echo "${libdir}/lib$1.so"
fi
done
}
# A convenient method to return the actual path even for non symlinks
# and multi-level symlinks.
function get_realpath() {
local previous="$1"
local next=$(readlink "${previous}")
while [ -n "${next}" ]; do
previous="${next}"
next=$(readlink "${previous}")
done
echo "${previous}"
}
# Get the path of a lib inside a tool
function get_otool_path() {
# the lib path is the path of the original lib relative to the workspace
get_realpath $1 | sed 's|^.*/bazel-out/|bazel-out/|'
}
# Do replacements in the output
if [ -n "${RPATH}" ]; then
for lib in ${LIBS}; do
libpath=$(get_library_path ${lib})
if [ -n "${libpath}" ]; then
${INSTALL_NAME_TOOL} -change $(get_otool_path "${libpath}") "@loader_path/${RPATH}/lib${lib}.so" "${OUTPUT}"
fi
done
fi
|
// Copyright 2015 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef BAZEL_SRC_MAIN_CPP_UTIL_ERRORS_H_
#define BAZEL_SRC_MAIN_CPP_UTIL_ERRORS_H_
#include "src/main/cpp/util/port.h"
namespace blaze_util {
// Prints the specified error message and exits nonzero.
void die(const int exit_status, const char *format, ...) ATTRIBUTE_NORETURN
PRINTF_ATTRIBUTE(2, 3);
// Prints "Error: <formatted-message>: <strerror(errno)>\n", and exits nonzero.
void pdie(const int exit_status, const char *format, ...) ATTRIBUTE_NORETURN
PRINTF_ATTRIBUTE(2, 3);
} // namespace blaze_util
#endif // BAZEL_SRC_MAIN_CPP_UTIL_ERRORS_H_
|
package com.thinkaurelius.titan.graphdb.serializer;
/**
* @author Matthias Broecheler (me@matthiasb.com)
*/
public class NoDefaultConstructor {
private final int i;
public NoDefaultConstructor(int i) {
this.i=i;
}
}
|
/* GObject - GLib Type, Object, Parameter and Signal Library
* Copyright (C) 1997-1999, 2000-2001 Tim Janik and Red Hat, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307, USA.
*
* gparam.h: GParamSpec base class implementation
*/
#if !defined (__GLIB_GOBJECT_H_INSIDE__) && !defined (GOBJECT_COMPILATION)
#error "Only <glib-object.h> can be included directly."
#endif
#ifndef __G_PARAM_H__
#define __G_PARAM_H__
#include <gobject/gvalue.h>
G_BEGIN_DECLS
/* --- standard type macros --- */
/**
* G_TYPE_IS_PARAM:
* @type: a #GType ID
*
* Checks whether @type "is a" %G_TYPE_PARAM.
*/
#define G_TYPE_IS_PARAM(type) (G_TYPE_FUNDAMENTAL (type) == G_TYPE_PARAM)
/**
* G_PARAM_SPEC:
* @pspec: a valid #GParamSpec
*
* Casts a derived #GParamSpec object (e.g. of type #GParamSpecInt) into
* a #GParamSpec object.
*/
#define G_PARAM_SPEC(pspec) (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM, GParamSpec))
/**
* G_IS_PARAM_SPEC:
* @pspec: a #GParamSpec
*
* Checks whether @pspec "is a" valid #GParamSpec structure of type %G_TYPE_PARAM
* or derived.
*/
#define G_IS_PARAM_SPEC(pspec) (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM))
/**
* G_PARAM_SPEC_CLASS:
* @pclass: a valid #GParamSpecClass
*
* Casts a derived #GParamSpecClass structure into a #GParamSpecClass structure.
*/
#define G_PARAM_SPEC_CLASS(pclass) (G_TYPE_CHECK_CLASS_CAST ((pclass), G_TYPE_PARAM, GParamSpecClass))
/**
* G_IS_PARAM_SPEC_CLASS:
* @pclass: a #GParamSpecClass
*
* Checks whether @pclass "is a" valid #GParamSpecClass structure of type
* %G_TYPE_PARAM or derived.
*/
#define G_IS_PARAM_SPEC_CLASS(pclass) (G_TYPE_CHECK_CLASS_TYPE ((pclass), G_TYPE_PARAM))
/**
* G_PARAM_SPEC_GET_CLASS:
* @pspec: a valid #GParamSpec
*
* Retrieves the #GParamSpecClass of a #GParamSpec.
*/
#define G_PARAM_SPEC_GET_CLASS(pspec) (G_TYPE_INSTANCE_GET_CLASS ((pspec), G_TYPE_PARAM, GParamSpecClass))
/* --- convenience macros --- */
/**
* G_PARAM_SPEC_TYPE:
* @pspec: a valid #GParamSpec
*
* Retrieves the #GType of this @pspec.
*/
#define G_PARAM_SPEC_TYPE(pspec) (G_TYPE_FROM_INSTANCE (pspec))
/**
* G_PARAM_SPEC_TYPE_NAME:
* @pspec: a valid #GParamSpec
*
* Retrieves the #GType name of this @pspec.
*/
#define G_PARAM_SPEC_TYPE_NAME(pspec) (g_type_name (G_PARAM_SPEC_TYPE (pspec)))
/**
* G_PARAM_SPEC_VALUE_TYPE:
* @pspec: a valid #GParamSpec
*
* Retrieves the #GType to initialize a #GValue for this parameter.
*/
#define G_PARAM_SPEC_VALUE_TYPE(pspec) (G_PARAM_SPEC (pspec)->value_type)
/**
* G_VALUE_HOLDS_PARAM:
* @value: a valid #GValue structure
*
* Checks whether the given #GValue can hold values derived from type %G_TYPE_PARAM.
*
* Returns: %TRUE on success.
*/
#define G_VALUE_HOLDS_PARAM(value) (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_PARAM))
/* --- flags --- */
/**
* GParamFlags:
* @G_PARAM_READABLE: the parameter is readable
* @G_PARAM_WRITABLE: the parameter is writable
* @G_PARAM_CONSTRUCT: the parameter will be set upon object construction
* @G_PARAM_CONSTRUCT_ONLY: the parameter will only be set upon object construction
* @G_PARAM_LAX_VALIDATION: upon parameter conversion (see g_param_value_convert())
* strict validation is not required
* @G_PARAM_STATIC_NAME: the string used as name when constructing the
* parameter is guaranteed to remain valid and
* unmodified for the lifetime of the parameter.
* Since 2.8
* @G_PARAM_STATIC_NICK: the string used as nick when constructing the
* parameter is guaranteed to remain valid and
* unmmodified for the lifetime of the parameter.
* Since 2.8
* @G_PARAM_STATIC_BLURB: the string used as blurb when constructing the
* parameter is guaranteed to remain valid and
* unmodified for the lifetime of the parameter.
* Since 2.8
* @G_PARAM_PRIVATE: internal
* @G_PARAM_DEPRECATED: the parameter is deprecated and will be removed
* in a future version. A warning will be generated if it is used
* while running with G_ENABLE_DIAGNOSTIC=1.
* Since 2.26
*
* Through the #GParamFlags flag values, certain aspects of parameters
* can be configured.
*/
typedef enum
{
G_PARAM_READABLE = 1 << 0,
G_PARAM_WRITABLE = 1 << 1,
G_PARAM_CONSTRUCT = 1 << 2,
G_PARAM_CONSTRUCT_ONLY = 1 << 3,
G_PARAM_LAX_VALIDATION = 1 << 4,
G_PARAM_STATIC_NAME = 1 << 5,
#ifndef G_DISABLE_DEPRECATED
G_PARAM_PRIVATE = G_PARAM_STATIC_NAME,
#endif
G_PARAM_STATIC_NICK = 1 << 6,
G_PARAM_STATIC_BLURB = 1 << 7,
/* User defined flags go up to 30 */
G_PARAM_DEPRECATED = 1 << 31
} GParamFlags;
/**
* G_PARAM_READWRITE:
*
* #GParamFlags value alias for %G_PARAM_READABLE | %G_PARAM_WRITABLE.
*/
#define G_PARAM_READWRITE (G_PARAM_READABLE | G_PARAM_WRITABLE)
/**
* G_PARAM_STATIC_STRINGS:
*
* #GParamFlags value alias for %G_PARAM_STATIC_NAME | %G_PARAM_STATIC_NICK | %G_PARAM_STATIC_BLURB.
*
* Since 2.13.0
*/
#define G_PARAM_STATIC_STRINGS (G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB)
/* bits in the range 0xffffff00 are reserved for 3rd party usage */
/**
* G_PARAM_MASK:
*
* Mask containing the bits of #GParamSpec.flags which are reserved for GLib.
*/
#define G_PARAM_MASK (0x000000ff)
/**
* G_PARAM_USER_SHIFT:
*
* Minimum shift count to be used for user defined flags, to be stored in
* #GParamSpec.flags. The maximum allowed is 30 + G_PARAM_USER_SHIFT.
*/
#define G_PARAM_USER_SHIFT (8)
/* --- typedefs & structures --- */
typedef struct _GParamSpec GParamSpec;
typedef struct _GParamSpecClass GParamSpecClass;
typedef struct _GParameter GParameter;
typedef struct _GParamSpecPool GParamSpecPool;
/**
* GParamSpec:
* @g_type_instance: private #GTypeInstance portion
* @name: name of this parameter: always an interned string
* @flags: #GParamFlags flags for this parameter
* @value_type: the #GValue type for this parameter
* @owner_type: #GType type that uses (introduces) this parameter
*
* All other fields of the <structname>GParamSpec</structname> struct are private and
* should not be used directly.
*/
struct _GParamSpec
{
GTypeInstance g_type_instance;
const gchar *name; /* interned string */
GParamFlags flags;
GType value_type;
GType owner_type; /* class or interface using this property */
/*< private >*/
gchar *_nick;
gchar *_blurb;
GData *qdata;
guint ref_count;
guint param_id; /* sort-criteria */
};
/**
* GParamSpecClass:
* @g_type_class: the parent class
* @value_type: the #GValue type for this parameter
* @finalize: The instance finalization function (optional), should chain
* up to the finalize method of the parent class.
* @value_set_default: Resets a @value to the default value for this type
* (recommended, the default is g_value_reset()), see
* g_param_value_set_default().
* @value_validate: Ensures that the contents of @value comply with the
* specifications set out by this type (optional), see
* g_param_value_validate().
* @values_cmp: Compares @value1 with @value2 according to this type
* (recommended, the default is memcmp()), see g_param_values_cmp().
*
* The class structure for the <structname>GParamSpec</structname> type.
* Normally, <structname>GParamSpec</structname> classes are filled by
* g_param_type_register_static().
*/
struct _GParamSpecClass
{
GTypeClass g_type_class;
GType value_type;
void (*finalize) (GParamSpec *pspec);
/* GParam methods */
void (*value_set_default) (GParamSpec *pspec,
GValue *value);
gboolean (*value_validate) (GParamSpec *pspec,
GValue *value);
gint (*values_cmp) (GParamSpec *pspec,
const GValue *value1,
const GValue *value2);
/*< private >*/
gpointer dummy[4];
};
/**
* GParameter:
* @name: the parameter name
* @value: the parameter value
*
* The <structname>GParameter</structname> struct is an auxiliary structure used
* to hand parameter name/value pairs to g_object_newv().
*/
struct _GParameter /* auxiliary structure for _setv() variants */
{
const gchar *name;
GValue value;
};
/* --- prototypes --- */
GParamSpec* g_param_spec_ref (GParamSpec *pspec);
void g_param_spec_unref (GParamSpec *pspec);
void g_param_spec_sink (GParamSpec *pspec);
GParamSpec* g_param_spec_ref_sink (GParamSpec *pspec);
gpointer g_param_spec_get_qdata (GParamSpec *pspec,
GQuark quark);
void g_param_spec_set_qdata (GParamSpec *pspec,
GQuark quark,
gpointer data);
void g_param_spec_set_qdata_full (GParamSpec *pspec,
GQuark quark,
gpointer data,
GDestroyNotify destroy);
gpointer g_param_spec_steal_qdata (GParamSpec *pspec,
GQuark quark);
GParamSpec* g_param_spec_get_redirect_target (GParamSpec *pspec);
void g_param_value_set_default (GParamSpec *pspec,
GValue *value);
gboolean g_param_value_defaults (GParamSpec *pspec,
GValue *value);
gboolean g_param_value_validate (GParamSpec *pspec,
GValue *value);
gboolean g_param_value_convert (GParamSpec *pspec,
const GValue *src_value,
GValue *dest_value,
gboolean strict_validation);
gint g_param_values_cmp (GParamSpec *pspec,
const GValue *value1,
const GValue *value2);
const gchar * g_param_spec_get_name (GParamSpec *pspec);
const gchar * g_param_spec_get_nick (GParamSpec *pspec);
const gchar * g_param_spec_get_blurb (GParamSpec *pspec);
void g_value_set_param (GValue *value,
GParamSpec *param);
GParamSpec* g_value_get_param (const GValue *value);
GParamSpec* g_value_dup_param (const GValue *value);
void g_value_take_param (GValue *value,
GParamSpec *param);
GLIB_DEPRECATED_FOR(g_value_take_param)
void g_value_set_param_take_ownership (GValue *value,
GParamSpec *param);
/* --- convenience functions --- */
typedef struct _GParamSpecTypeInfo GParamSpecTypeInfo;
/**
* GParamSpecTypeInfo:
* @instance_size: Size of the instance (object) structure.
* @n_preallocs: Prior to GLib 2.10, it specified the number of pre-allocated (cached) instances to reserve memory for (0 indicates no caching). Since GLib 2.10, it is ignored, since instances are allocated with the <link linkend="glib-Memory-Slices">slice allocator</link> now.
* @instance_init: Location of the instance initialization function (optional).
* @value_type: The #GType of values conforming to this #GParamSpec
* @finalize: The instance finalization function (optional).
* @value_set_default: Resets a @value to the default value for @pspec
* (recommended, the default is g_value_reset()), see
* g_param_value_set_default().
* @value_validate: Ensures that the contents of @value comply with the
* specifications set out by @pspec (optional), see
* g_param_value_validate().
* @values_cmp: Compares @value1 with @value2 according to @pspec
* (recommended, the default is memcmp()), see g_param_values_cmp().
*
* This structure is used to provide the type system with the information
* required to initialize and destruct (finalize) a parameter's class and
* instances thereof.
* The initialized structure is passed to the g_param_type_register_static()
* The type system will perform a deep copy of this structure, so its memory
* does not need to be persistent across invocation of
* g_param_type_register_static().
*/
struct _GParamSpecTypeInfo
{
/* type system portion */
guint16 instance_size; /* obligatory */
guint16 n_preallocs; /* optional */
void (*instance_init) (GParamSpec *pspec); /* optional */
/* class portion */
GType value_type; /* obligatory */
void (*finalize) (GParamSpec *pspec); /* optional */
void (*value_set_default) (GParamSpec *pspec, /* recommended */
GValue *value);
gboolean (*value_validate) (GParamSpec *pspec, /* optional */
GValue *value);
gint (*values_cmp) (GParamSpec *pspec, /* recommended */
const GValue *value1,
const GValue *value2);
};
GType g_param_type_register_static (const gchar *name,
const GParamSpecTypeInfo *pspec_info);
/* For registering builting types */
GType _g_param_type_register_static_constant (const gchar *name,
const GParamSpecTypeInfo *pspec_info,
GType opt_type);
/* --- protected --- */
gpointer g_param_spec_internal (GType param_type,
const gchar *name,
const gchar *nick,
const gchar *blurb,
GParamFlags flags);
GParamSpecPool* g_param_spec_pool_new (gboolean type_prefixing);
void g_param_spec_pool_insert (GParamSpecPool *pool,
GParamSpec *pspec,
GType owner_type);
void g_param_spec_pool_remove (GParamSpecPool *pool,
GParamSpec *pspec);
GParamSpec* g_param_spec_pool_lookup (GParamSpecPool *pool,
const gchar *param_name,
GType owner_type,
gboolean walk_ancestors);
GList* g_param_spec_pool_list_owned (GParamSpecPool *pool,
GType owner_type);
GParamSpec** g_param_spec_pool_list (GParamSpecPool *pool,
GType owner_type,
guint *n_pspecs_p);
/* contracts:
*
* gboolean value_validate (GParamSpec *pspec,
* GValue *value):
* modify value contents in the least destructive way, so
* that it complies with pspec's requirements (i.e.
* according to minimum/maximum ranges etc...). return
* whether modification was necessary.
*
* gint values_cmp (GParamSpec *pspec,
* const GValue *value1,
* const GValue *value2):
* return value1 - value2, i.e. (-1) if value1 < value2,
* (+1) if value1 > value2, and (0) otherwise (equality)
*/
G_END_DECLS
#endif /* __G_PARAM_H__ */
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.Configuration.ConfigureSeverity;
using Microsoft.CodeAnalysis.CSharp.RemoveUnusedParametersAndValues;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.Configuration.ConfigureSeverity
{
public abstract partial class CSharpCodeStyleOptionBasedSeverityConfigurationTests : AbstractSuppressionDiagnosticTest
{
protected internal override string GetLanguage() => LanguageNames.CSharp;
protected override ParseOptions GetScriptOptions() => Options.Script;
internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace)
{
return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>(
new CSharpRemoveUnusedParametersAndValuesDiagnosticAnalyzer(), new ConfigureSeverityLevelCodeFixProvider());
}
public class ErrorConfigurationTests : CSharpCodeStyleOptionBasedSeverityConfigurationTests
{
protected override int CodeActionIndex => 4;
[ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_Empty_Error()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\Program.cs"">
public class Class1
{
public int Test()
{
var o = 1;
// csharp_style_unused_value_assignment_preference = discard_variable
var [|unused|] = o;
return 1;
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\Program.cs"">
public class Class1
{
public int Test()
{
var o = 1;
// csharp_style_unused_value_assignment_preference = discard_variable
var [|unused|] = o;
return 1;
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
# IDE0059: Unnecessary assignment of a value
dotnet_diagnostic.IDE0059.severity = error
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_ExistingRule_Error()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\Program.cs"">
public class Class1
{
public int Test()
{
var o = 1;
// csharp_style_unused_value_assignment_preference = discard_variable
var [|unused|] = o;
return 1;
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
# IDE0059: Unnecessary assignment of a value
csharp_style_unused_value_assignment_preference = discard_variable:warning
dotnet_diagnostic.IDE0059.severity = suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\Program.cs"">
public class Class1
{
public int Test()
{
var o = 1;
// csharp_style_unused_value_assignment_preference = discard_variable
var [|unused|] = o;
return 1;
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
# IDE0059: Unnecessary assignment of a value
csharp_style_unused_value_assignment_preference = discard_variable:error
dotnet_diagnostic.IDE0059.severity = error
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_ExistingRuleDotNetHeader_Error()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\Program.cs"">
public class Class1
{
public int Test()
{
var o = 1;
// csharp_style_unused_value_assignment_preference = discard_variable
var [|unused|] = o;
return 1;
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}]
# IDE0059: Unnecessary assignment of a value
csharp_style_unused_value_assignment_preference = discard_variable:warning
dotnet_diagnostic.IDE0059.severity = suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\Program.cs"">
public class Class1
{
public int Test()
{
var o = 1;
// csharp_style_unused_value_assignment_preference = discard_variable
var [|unused|] = o;
return 1;
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}]
# IDE0059: Unnecessary assignment of a value
csharp_style_unused_value_assignment_preference = discard_variable:error
dotnet_diagnostic.IDE0059.severity = error
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_ChooseBestHeader_Error()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\Program.cs"">
public class Class1
{
public int Test()
{
var o = 1;
// csharp_style_unused_value_assignment_preference = discard_variable
var [|unused|] = o;
return 1;
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
csharp_style_expression_bodied_methods = false:silent
[*.{vb,cs}]
dotnet_style_qualification_for_field = false:silent
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\Program.cs"">
public class Class1
{
public int Test()
{
var o = 1;
// csharp_style_unused_value_assignment_preference = discard_variable
var [|unused|] = o;
return 1;
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
csharp_style_expression_bodied_methods = false:silent
# IDE0059: Unnecessary assignment of a value
dotnet_diagnostic.IDE0059.severity = error
[*.{vb,cs}]
dotnet_style_qualification_for_field = false:silent
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_ChooseBestHeaderReversed_Error()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\Program.cs"">
public class Class1
{
public int Test()
{
var o = 1;
// csharp_style_unused_value_assignment_preference = discard_variable
var [|unused|] = o;
return 1;
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}]
dotnet_style_qualification_for_field = false:silent
[*.cs]
csharp_style_expression_bodied_methods = false:silent
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\Program.cs"">
public class Class1
{
public int Test()
{
var o = 1;
// csharp_style_unused_value_assignment_preference = discard_variable
var [|unused|] = o;
return 1;
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}]
dotnet_style_qualification_for_field = false:silent
[*.cs]
csharp_style_expression_bodied_methods = false:silent
# IDE0059: Unnecessary assignment of a value
dotnet_diagnostic.IDE0059.severity = error
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
}
}
}
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <Aclapi.h>
#include <windows.h>
#include <stddef.h>
#include <string>
#include "sandbox/win/tests/validation_tests/commands.h"
#include "sandbox/win/tests/common/controller.h"
namespace {
// Returns the HKEY corresponding to name. If there is no HKEY corresponding
// to the name it returns NULL.
HKEY GetHKEYFromString(const base::string16 &name) {
if (name == L"HKLM")
return HKEY_LOCAL_MACHINE;
if (name == L"HKCR")
return HKEY_CLASSES_ROOT;
if (name == L"HKCC")
return HKEY_CURRENT_CONFIG;
if (name == L"HKCU")
return HKEY_CURRENT_USER;
if (name == L"HKU")
return HKEY_USERS;
return NULL;
}
// Modifies string to remove the leading and trailing quotes.
void trim_quote(base::string16* string) {
base::string16::size_type pos1 = string->find_first_not_of(L'"');
base::string16::size_type pos2 = string->find_last_not_of(L'"');
if (pos1 == base::string16::npos || pos2 == base::string16::npos)
string->clear();
else
(*string) = string->substr(pos1, pos2 + 1);
}
int TestOpenFile(base::string16 path, bool for_write) {
wchar_t path_expanded[MAX_PATH + 1] = {0};
DWORD size = ::ExpandEnvironmentStrings(path.c_str(), path_expanded,
MAX_PATH);
if (!size)
return sandbox::SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
HANDLE file;
file = ::CreateFile(path_expanded,
for_write ? GENERIC_READ | GENERIC_WRITE : GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
NULL, // No security attributes.
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS,
NULL); // No template.
if (file != INVALID_HANDLE_VALUE) {
::CloseHandle(file);
return sandbox::SBOX_TEST_SUCCEEDED;
}
return (::GetLastError() == ERROR_ACCESS_DENIED) ?
sandbox::SBOX_TEST_DENIED : sandbox::SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
}
} // namespace
namespace sandbox {
SBOX_TESTS_COMMAND int ValidWindow(int argc, wchar_t **argv) {
return (argc == 1) ?
TestValidWindow(
reinterpret_cast<HWND>(static_cast<ULONG_PTR>(_wtoi(argv[0])))) :
SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
}
int TestValidWindow(HWND window) {
return ::IsWindow(window) ? SBOX_TEST_SUCCEEDED : SBOX_TEST_DENIED;
}
SBOX_TESTS_COMMAND int OpenProcessCmd(int argc, wchar_t **argv) {
return (argc == 2) ?
TestOpenProcess(_wtol(argv[0]), _wtol(argv[1])) :
SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
}
int TestOpenProcess(DWORD process_id, DWORD access_mask) {
HANDLE process = ::OpenProcess(access_mask,
FALSE, // Do not inherit handle.
process_id);
if (process != NULL) {
::CloseHandle(process);
return SBOX_TEST_SUCCEEDED;
}
return (::GetLastError() == ERROR_ACCESS_DENIED) ?
sandbox::SBOX_TEST_DENIED : sandbox::SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
}
SBOX_TESTS_COMMAND int OpenThreadCmd(int argc, wchar_t **argv) {
return (argc == 1) ?
TestOpenThread(_wtoi(argv[0])) : SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
}
int TestOpenThread(DWORD thread_id) {
HANDLE thread = ::OpenThread(THREAD_QUERY_INFORMATION,
FALSE, // Do not inherit handles.
thread_id);
if (thread != NULL) {
::CloseHandle(thread);
return SBOX_TEST_SUCCEEDED;
}
return (::GetLastError() == ERROR_ACCESS_DENIED) ?
sandbox::SBOX_TEST_DENIED : sandbox::SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
}
SBOX_TESTS_COMMAND int OpenFileCmd(int argc, wchar_t **argv) {
if (1 != argc)
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
base::string16 path = argv[0];
trim_quote(&path);
return TestOpenReadFile(path);
}
int TestOpenReadFile(const base::string16& path) {
return TestOpenFile(path, false);
}
int TestOpenWriteFile(int argc, wchar_t **argv) {
if (argc != 1)
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
base::string16 path = argv[0];
trim_quote(&path);
return TestOpenWriteFile(path);
}
int TestOpenWriteFile(const base::string16& path) {
return TestOpenFile(path, true);
}
SBOX_TESTS_COMMAND int OpenKey(int argc, wchar_t **argv) {
if (argc != 1 && argc != 2)
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
// Get the hive.
HKEY base_key = GetHKEYFromString(argv[0]);
// Get the subkey.
base::string16 subkey;
if (argc == 2) {
subkey = argv[1];
trim_quote(&subkey);
}
return TestOpenKey(base_key, subkey);
}
int TestOpenKey(HKEY base_key, base::string16 subkey) {
HKEY key;
LONG err_code = ::RegOpenKeyEx(base_key,
subkey.c_str(),
0, // Reserved, must be 0.
MAXIMUM_ALLOWED,
&key);
if (err_code == ERROR_SUCCESS) {
::RegCloseKey(key);
return SBOX_TEST_SUCCEEDED;
}
return (err_code == ERROR_INVALID_HANDLE || err_code == ERROR_ACCESS_DENIED) ?
SBOX_TEST_DENIED : SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
}
// Returns true if the current's thread desktop is the interactive desktop.
// In Vista there is a more direct test but for XP and w2k we need to check
// the object name.
bool IsInteractiveDesktop(bool* is_interactive) {
HDESK current_desk = ::GetThreadDesktop(::GetCurrentThreadId());
if (current_desk == NULL)
return false;
wchar_t current_desk_name[256] = {0};
if (!::GetUserObjectInformationW(current_desk, UOI_NAME, current_desk_name,
sizeof(current_desk_name), NULL))
return false;
*is_interactive = (0 == _wcsicmp(L"default", current_desk_name));
return true;
}
SBOX_TESTS_COMMAND int OpenInteractiveDesktop(int, wchar_t **) {
return TestOpenInputDesktop();
}
int TestOpenInputDesktop() {
bool is_interactive = false;
if (IsInteractiveDesktop(&is_interactive) && is_interactive)
return SBOX_TEST_SUCCEEDED;
HDESK desk = ::OpenInputDesktop(0, FALSE, DESKTOP_CREATEWINDOW);
if (desk) {
::CloseDesktop(desk);
return SBOX_TEST_SUCCEEDED;
}
return SBOX_TEST_DENIED;
}
SBOX_TESTS_COMMAND int SwitchToSboxDesktop(int, wchar_t **) {
return TestSwitchDesktop();
}
int TestSwitchDesktop() {
HDESK desktop = ::GetThreadDesktop(::GetCurrentThreadId());
if (desktop == NULL)
return SBOX_TEST_FAILED;
return ::SwitchDesktop(desktop) ? SBOX_TEST_SUCCEEDED : SBOX_TEST_DENIED;
}
SBOX_TESTS_COMMAND int OpenAlternateDesktop(int, wchar_t **argv) {
return TestOpenAlternateDesktop(argv[0]);
}
int TestOpenAlternateDesktop(wchar_t *desktop_name) {
// Test for WRITE_DAC permission on the handle.
HDESK desktop = ::GetThreadDesktop(::GetCurrentThreadId());
if (desktop) {
HANDLE test_handle;
if (::DuplicateHandle(::GetCurrentProcess(), desktop,
::GetCurrentProcess(), &test_handle,
WRITE_DAC, FALSE, 0)) {
DWORD result = ::SetSecurityInfo(test_handle, SE_WINDOW_OBJECT,
DACL_SECURITY_INFORMATION, NULL, NULL,
NULL, NULL);
::CloseHandle(test_handle);
if (result == ERROR_SUCCESS)
return SBOX_TEST_SUCCEEDED;
} else if (::GetLastError() != ERROR_ACCESS_DENIED) {
return SBOX_TEST_FAILED;
}
}
// Open by name with WRITE_DAC.
desktop = ::OpenDesktop(desktop_name, 0, FALSE, WRITE_DAC);
if (!desktop && ::GetLastError() == ERROR_ACCESS_DENIED)
return SBOX_TEST_DENIED;
::CloseDesktop(desktop);
return SBOX_TEST_SUCCEEDED;
}
BOOL CALLBACK DesktopTestEnumProc(LPTSTR desktop_name, LPARAM result) {
return TRUE;
}
SBOX_TESTS_COMMAND int EnumAlternateWinsta(int, wchar_t **) {
return TestEnumAlternateWinsta();
}
int TestEnumAlternateWinsta() {
// Try to enumerate the destops on the alternate windowstation.
return ::EnumDesktopsW(NULL, DesktopTestEnumProc, 0) ?
SBOX_TEST_SUCCEEDED : SBOX_TEST_DENIED;
}
SBOX_TESTS_COMMAND int SleepCmd(int argc, wchar_t **argv) {
if (argc != 1)
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
::Sleep(_wtoi(argv[0]));
return SBOX_TEST_SUCCEEDED;
}
SBOX_TESTS_COMMAND int AllocateCmd(int argc, wchar_t **argv) {
if (argc != 1)
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
size_t mem_size = static_cast<size_t>(_wtoll(argv[0]));
void* memory = ::VirtualAlloc(NULL, mem_size, MEM_COMMIT | MEM_RESERVE,
PAGE_READWRITE);
if (!memory) {
// We need to give the broker a chance to kill our process on failure.
::Sleep(5000);
return SBOX_TEST_DENIED;
}
return ::VirtualFree(memory, 0, MEM_RELEASE) ?
SBOX_TEST_SUCCEEDED : SBOX_TEST_FAILED;
}
} // namespace sandbox
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "config.h"
#include "platform/EventDispatchForbiddenScope.h"
namespace blink {
#if ENABLE(ASSERT)
unsigned EventDispatchForbiddenScope::s_count = 0;
#endif // ENABLE(ASSERT)
} // namespace blink
|
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\DBAL\Platforms;
use Doctrine\DBAL\Schema\Sequence;
/**
* Platform to ensure compatibility of Doctrine with Microsoft SQL Server 2012 version.
*
* Differences to SQL Server 2008 and before are that sequences are introduced.
*
* @author Steve Müller <st.mueller@dzh-online.de>
*/
class SQLServer2012Platform extends SQLServer2008Platform
{
/**
* {@inheritdoc}
*/
public function getAlterSequenceSQL(Sequence $sequence)
{
return 'ALTER SEQUENCE ' . $sequence->getQuotedName($this) .
' INCREMENT BY ' . $sequence->getAllocationSize();
}
/**
* {@inheritdoc}
*/
public function getCreateSequenceSQL(Sequence $sequence)
{
return 'CREATE SEQUENCE ' . $sequence->getQuotedName($this) .
' START WITH ' . $sequence->getInitialValue() .
' INCREMENT BY ' . $sequence->getAllocationSize() .
' MINVALUE ' . $sequence->getInitialValue();
}
/**
* {@inheritdoc}
*/
public function getDropSequenceSQL($sequence)
{
if ($sequence instanceof Sequence) {
$sequence = $sequence->getQuotedName($this);
}
return 'DROP SEQUENCE ' . $sequence;
}
/**
* {@inheritdoc}
*/
public function getListSequencesSQL($database)
{
return 'SELECT seq.name,
CAST(
seq.increment AS VARCHAR(MAX)
) AS increment, -- CAST avoids driver error for sql_variant type
CAST(
seq.start_value AS VARCHAR(MAX)
) AS start_value -- CAST avoids driver error for sql_variant type
FROM sys.sequences AS seq';
}
/**
* {@inheritdoc}
*/
public function getSequenceNextValSQL($sequenceName)
{
return 'SELECT NEXT VALUE FOR ' . $sequenceName;
}
/**
* {@inheritdoc}
*/
public function supportsSequences()
{
return true;
}
/**
* {@inheritdoc}
*
* Returns Microsoft SQL Server 2012 specific keywords class
*/
protected function getReservedKeywordsClass()
{
return 'Doctrine\DBAL\Platforms\Keywords\SQLServer2012Keywords';
}
/**
* {@inheritdoc}
*/
protected function doModifyLimitQuery($query, $limit, $offset = null)
{
if ($limit === null && $offset === null) {
return $query;
}
// Queries using OFFSET... FETCH MUST have an ORDER BY clause
// Find the position of the last instance of ORDER BY and ensure it is not within a parenthetical statement
// but can be in a newline
$matches = array();
$matchesCount = preg_match_all("/[\\s]+order by /i", $query, $matches, PREG_OFFSET_CAPTURE);
$orderByPos = false;
if ($matchesCount > 0) {
$orderByPos = $matches[0][($matchesCount - 1)][1];
}
if ($orderByPos === false
|| substr_count($query, "(", $orderByPos) - substr_count($query, ")", $orderByPos)
) {
if (stripos($query, 'SELECT DISTINCT') === 0) {
// SQL Server won't let us order by a non-selected column in a DISTINCT query,
// so we have to do this madness. This says, order by the first column in the
// result. SQL Server's docs say that a nonordered query's result order is non-
// deterministic anyway, so this won't do anything that a bunch of update and
// deletes to the table wouldn't do anyway.
$query .= " ORDER BY 1";
} else {
// In another DBMS, we could do ORDER BY 0, but SQL Server gets angry if you
// use constant expressions in the order by list.
$query .= " ORDER BY (SELECT 0)";
}
}
if ($offset === null) {
$offset = 0;
}
// This looks somewhat like MYSQL, but limit/offset are in inverse positions
// Supposedly SQL:2008 core standard.
// Per TSQL spec, FETCH NEXT n ROWS ONLY is not valid without OFFSET n ROWS.
$query .= " OFFSET " . (int) $offset . " ROWS";
if ($limit !== null) {
$query .= " FETCH NEXT " . (int) $limit . " ROWS ONLY";
}
return $query;
}
}
|
---
layout: docs
title: Progress
description: Documentation and examples for using Bootstrap custom progress bars featuring support for stacked bars, animated backgrounds, and text labels.
group: components
toc: true
---
## How it works
Progress components are built with two HTML elements, some CSS to set the width, and a few attributes. We don't use [the HTML5 `<progress>` element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/progress), ensuring you can stack progress bars, animate them, and place text labels over them.
- We use the `.progress` as a wrapper to indicate the max value of the progress bar.
- We use the inner `.progress-bar` to indicate the progress so far.
- The `.progress-bar` requires an inline style, utility class, or custom CSS to set their width.
- The `.progress-bar` also requires some `role` and `aria` attributes to make it accessible.
Put that all together, and you have the following examples.
{% example html %}
<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: 25%" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: 50%" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: 75%" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: 100%" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100"></div>
</div>
{% endexample %}
Bootstrap provides a handful of [utilities for setting width]({{ site.baseurl }}/docs/{{ site.docs_version }}/utilities/sizing/). Depending on your needs, these may help with quickly configuring progress.
{% example html %}
<div class="progress">
<div class="progress-bar w-75" role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100"></div>
</div>
{% endexample %}
## Labels
Add labels to your progress bars by placing text within the `.progress-bar`.
{% example html %}
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: 25%;" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100">25%</div>
</div>
{% endexample %}
## Height
We only set a `height` value on the `.progress`, so if you change that value the inner `.progress-bar` will automatically resize accordingly.
{% example html %}
<div class="progress" style="height: 1px;">
<div class="progress-bar" role="progressbar" style="width: 25%;" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<div class="progress" style="height: 20px;">
<div class="progress-bar" role="progressbar" style="width: 25%;" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div>
</div>
{% endexample %}
## Backgrounds
Use background utility classes to change the appearance of individual progress bars.
{% example html %}
<div class="progress">
<div class="progress-bar bg-success" role="progressbar" style="width: 25%" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<div class="progress">
<div class="progress-bar bg-info" role="progressbar" style="width: 50%" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<div class="progress">
<div class="progress-bar bg-warning" role="progressbar" style="width: 75%" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<div class="progress">
<div class="progress-bar bg-danger" role="progressbar" style="width: 100%" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100"></div>
</div>
{% endexample %}
## Multiple bars
Include multiple progress bars in a progress component if you need.
{% example html %}
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: 15%" aria-valuenow="15" aria-valuemin="0" aria-valuemax="100"></div>
<div class="progress-bar bg-success" role="progressbar" style="width: 30%" aria-valuenow="30" aria-valuemin="0" aria-valuemax="100"></div>
<div class="progress-bar bg-info" role="progressbar" style="width: 20%" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100"></div>
</div>
{% endexample %}
## Striped
Add `.progress-bar-striped` to any `.progress-bar` to apply a stripe via CSS gradient over the progress bar's background color.
{% example html %}
<div class="progress">
<div class="progress-bar progress-bar-striped" role="progressbar" style="width: 10%" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<div class="progress">
<div class="progress-bar progress-bar-striped bg-success" role="progressbar" style="width: 25%" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<div class="progress">
<div class="progress-bar progress-bar-striped bg-info" role="progressbar" style="width: 50%" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<div class="progress">
<div class="progress-bar progress-bar-striped bg-warning" role="progressbar" style="width: 75%" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<div class="progress">
<div class="progress-bar progress-bar-striped bg-danger" role="progressbar" style="width: 100%" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100"></div>
</div>
{% endexample %}
## Animated stripes
The striped gradient can also be animated. Add `.progress-bar-animated` to `.progress-bar` to animate the stripes right to left via CSS3 animations.
**Animated progress bars don't work in Opera 12**—as they don't support CSS3 animations.
<div class="bd-example">
<div class="progress">
<div class="progress-bar progress-bar-striped" role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100" style="width: 75%"></div>
</div>
<button type="button" class="btn btn-secondary bd-toggle-animated-progress" data-toggle="button" aria-pressed="false" autocomplete="off">
Toggle animation
</button>
</div>
{% highlight html %}
<div class="progress">
<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100" style="width: 75%"></div>
</div>
{% endhighlight %}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.CompilerServices;
class GitHub_26417
{
static int _a;
[MethodImplAttribute(MethodImplOptions.NoInlining)]
static void MyWriteLine(int v)
{
Console.WriteLine(v);
if (v == 0)
{
throw new Exception();
}
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
static void Test()
{
_a = 1;
while (_a == 1)
{
MyWriteLine(_a);
_a = 0;
}
}
static int Main()
{
int result = 100;
try {
Test();
}
catch (Exception)
{
Console.WriteLine("FAILED");
result = -1;
}
return result;
}
}
|
//
// detail/signal_blocker.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2014 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_DETAIL_SIGNAL_BLOCKER_HPP
#define ASIO_DETAIL_SIGNAL_BLOCKER_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#if !defined(ASIO_HAS_THREADS) || defined(ASIO_WINDOWS) \
|| defined(ASIO_WINDOWS_RUNTIME) \
|| defined(__CYGWIN__) || defined(__SYMBIAN32__)
# include "asio/detail/null_signal_blocker.hpp"
#elif defined(ASIO_HAS_PTHREADS)
# include "asio/detail/posix_signal_blocker.hpp"
#else
# error Only Windows and POSIX are supported!
#endif
namespace asio {
namespace detail {
#if !defined(ASIO_HAS_THREADS) || defined(ASIO_WINDOWS) \
|| defined(ASIO_WINDOWS_RUNTIME) \
|| defined(__CYGWIN__) || defined(__SYMBIAN32__)
typedef null_signal_blocker signal_blocker;
#elif defined(ASIO_HAS_PTHREADS)
typedef posix_signal_blocker signal_blocker;
#endif
} // namespace detail
} // namespace asio
#endif // ASIO_DETAIL_SIGNAL_BLOCKER_HPP
|
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using System.Web;
using System.Web.Mvc;
namespace OfficeDevPnP.MSGraphAPIGroups.Controllers
{
public class AccountController : Controller
{
public void SignIn()
{
if (!Request.IsAuthenticated)
{
HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/" }, OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
}
public void SignOut()
{
string callbackUrl = Url.Action("SignOutCallback", "Account", routeValues: null, protocol: Request.Url.Scheme);
HttpContext.GetOwinContext().Authentication.SignOut(
new AuthenticationProperties { RedirectUri = callbackUrl },
OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);
}
public ActionResult SignOutCallback()
{
if (Request.IsAuthenticated)
{
// Redirect to home page if the user is authenticated.
return RedirectToAction("Index", "Home");
}
return View();
}
}
} |
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'save', 'af', {
toolbar: 'Bewaar'
} );
|
/*
* The MIT License
* Copyright (c) 2012 Microsoft Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package microsoft.exchange.webservices.data.sync;
import microsoft.exchange.webservices.data.attribute.EditorBrowsable;
import microsoft.exchange.webservices.data.core.service.ServiceObject;
import microsoft.exchange.webservices.data.core.enumeration.sync.ChangeType;
import microsoft.exchange.webservices.data.core.enumeration.attribute.EditorBrowsableState;
import microsoft.exchange.webservices.data.core.exception.service.local.ServiceLocalException;
import microsoft.exchange.webservices.data.property.complex.ServiceId;
/**
* Represents a change as returned by a synchronization operation.
*/
@EditorBrowsable(state = EditorBrowsableState.Never)
public abstract class Change {
/**
* The type of change.
*/
private ChangeType changeType;
/**
* The service object the change applies to.
*/
private ServiceObject serviceObject;
/**
* The Id of the service object the change applies to.
*/
private ServiceId id;
/**
* Initializes a new instance of Change.
*/
protected Change() {
}
/**
* Initializes a new instance of Change.
*
* @return the service id
*/
public abstract ServiceId createId();
/**
* Gets the type of the change.
*
* @return the change type
*/
public ChangeType getChangeType() {
return this.changeType;
}
/**
* sets the type of the change.
*
* @param changeType the new change type
*/
public void setChangeType(ChangeType changeType) {
this.changeType = changeType;
}
/**
* Gets the service object the change applies to.
*
* @return the service object
*/
public ServiceObject getServiceObject() {
return this.serviceObject;
}
/**
* Sets the service object.
*
* @param serviceObject the new service object
*/
public void setServiceObject(ServiceObject serviceObject) {
this.serviceObject = serviceObject;
}
/**
* Gets the Id of the service object the change applies to.
*
* @return the id
* @throws ServiceLocalException the service local exception
*/
public ServiceId getId() throws ServiceLocalException {
return this.getServiceObject() != null ? this.getServiceObject()
.getId() : this.id;
}
/**
* Sets the id.
*
* @param id the new id
*/
public void setId(ServiceId id) {
this.id = id;
}
}
|
define(
//begin v1.x content
{
"field-sat-relative+0": "เสาร์นี้",
"field-sat-relative+1": "เสาร์หน้า",
"field-dayperiod": "ช่วงวัน",
"field-sun-relative+-1": "อาทิตย์ที่แล้ว",
"field-mon-relative+-1": "จันทร์ที่แล้ว",
"field-minute": "นาที",
"field-day-relative+-1": "เมื่อวาน",
"field-weekday": "วันในสัปดาห์",
"field-day-relative+-2": "เมื่อวานซืน",
"months-standAlone-narrow": [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13"
],
"field-era": "สมัย",
"field-hour": "ชั่วโมง",
"field-sun-relative+0": "อาทิตย์นี้",
"field-sun-relative+1": "อาทิตย์หน้า",
"months-standAlone-abbr": [
"เมสเคอเรม",
"เตเกมท",
"เฮดาร์",
"ทาฮ์ซัส",
"เทอร์",
"เยคาทิท",
"เมกาบิต",
"เมียเซีย",
"เจนบอต",
"เซเน",
"ฮัมเล",
"เนแฮซ",
"พากูเมน"
],
"field-wed-relative+-1": "พุธที่แล้ว",
"field-day-relative+0": "วันนี้",
"field-day-relative+1": "พรุ่งนี้",
"field-day-relative+2": "มะรืนนี้",
"field-tue-relative+0": "อังคารนี้",
"field-zone": "เขตเวลา",
"field-tue-relative+1": "อังคารหน้า",
"field-week-relative+-1": "สัปดาห์ที่แล้ว",
"field-year-relative+0": "ปีนี้",
"field-year-relative+1": "ปีหน้า",
"field-sat-relative+-1": "เสาร์ที่แล้ว",
"field-year-relative+-1": "ปีที่แล้ว",
"field-year": "ปี",
"field-fri-relative+0": "ศุกร์นี้",
"field-fri-relative+1": "ศุกร์หน้า",
"months-standAlone-wide": [
"เมสเคอเรม",
"เตเกมท",
"เฮดาร์",
"ทาฮ์ซัส",
"เทอร์",
"เยคาทิท",
"เมกาบิต",
"เมียเซีย",
"เจนบอต",
"เซเน",
"ฮัมเล",
"เนแฮซ",
"พากูเมน"
],
"field-week": "สัปดาห์",
"field-week-relative+0": "สัปดาห์นี้",
"field-week-relative+1": "สัปดาห์หน้า",
"months-format-abbr": [
"เมสเคอเรม",
"เตเกมท",
"เฮดาร์",
"ทาฮ์ซัส",
"เทอร์",
"เยคาทิท",
"เมกาบิต",
"เมียเซีย",
"เจนบอต",
"เซเน",
"ฮัมเล",
"เนแฮซ",
"พากูเมน"
],
"field-month-relative+0": "เดือนนี้",
"field-month": "เดือน",
"field-month-relative+1": "เดือนหน้า",
"field-fri-relative+-1": "ศุกร์ที่แล้ว",
"field-second": "วินาที",
"field-tue-relative+-1": "อังคารที่แล้ว",
"field-day": "วัน",
"months-format-narrow": [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13"
],
"field-mon-relative+0": "จันทร์นี้",
"field-mon-relative+1": "จันทร์หน้า",
"field-thu-relative+0": "พฤหัสนี้",
"field-second-relative+0": "ขณะนี้",
"field-thu-relative+1": "พฤหัสหน้า",
"months-format-wide": [
"เมสเคอเรม",
"เตเกมท",
"เฮดาร์",
"ทาฮ์ซัส",
"เทอร์",
"เยคาทิท",
"เมกาบิต",
"เมียเซีย",
"เจนบอต",
"เซเน",
"ฮัมเล",
"เนแฮซ",
"พากูเมน"
],
"field-wed-relative+0": "พุธนี้",
"field-wed-relative+1": "พุธหน้า",
"field-month-relative+-1": "เดือนที่แล้ว",
"field-thu-relative+-1": "พฤหัสที่แล้ว"
}
//end v1.x content
); |
/* Copyright (c) 2006 Yahoo! Inc. All rights reserved. */
/**
* @class The Yahoo global namespace
*/
var YAHOO = function() {
return {
/**
* Yahoo presentation platform utils namespace
*/
util: {},
/**
* Yahoo presentation platform widgets namespace
*/
widget: {},
/**
* Yahoo presentation platform examples namespace
*/
example: {},
/**
* Returns the namespace specified and creates it if it doesn't exist
*
* YAHOO.namespace("property.package");
* YAHOO.namespace("YAHOO.property.package");
*
* Either of the above would create YAHOO.property, then
* YAHOO.property.package
*
* @param {String} sNameSpace String representation of the desired
* namespace
* @return {Object} A reference to the namespace object
*/
namespace: function( sNameSpace ) {
if (!sNameSpace || !sNameSpace.length) {
return null;
}
var levels = sNameSpace.split(".");
var currentNS = YAHOO;
// YAHOO is implied, so it is ignored if it is included
for (var i=(levels[0] == "YAHOO") ? 1 : 0; i<levels.length; ++i) {
currentNS[levels[i]] = currentNS[levels[i]] || {};
currentNS = currentNS[levels[i]];
}
return currentNS;
}
};
} ();
|
// SPDX-License-Identifier: GPL-2.0
/*
* Hardware monitoring driver for Maxim MAX16508 and MAX16601.
*
* Implementation notes:
*
* This chip series supports two rails, VCORE and VSA. Telemetry information
* for the two rails is reported in two subsequent I2C addresses. The driver
* instantiates a dummy I2C client at the second I2C address to report
* information for the VSA rail in a single instance of the driver.
* Telemetry for the VSA rail is reported to the PMBus core in PMBus page 2.
*
* The chip reports input current using two separate methods. The input current
* reported with the standard READ_IIN command is derived from the output
* current. The first method is reported to the PMBus core with PMBus page 0,
* the second method is reported with PMBus page 1.
*
* The chip supports reading per-phase temperatures and per-phase input/output
* currents for VCORE. Telemetry is reported in vendor specific registers.
* The driver translates the vendor specific register values to PMBus standard
* register values and reports per-phase information in PMBus page 0.
*
* Copyright 2019, 2020 Google LLC.
*/
#include <linux/bits.h>
#include <linux/i2c.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include "pmbus.h"
enum chips { max16508, max16601 };
#define REG_DEFAULT_NUM_POP 0xc4
#define REG_SETPT_DVID 0xd1
#define DAC_10MV_MODE BIT(4)
#define REG_IOUT_AVG_PK 0xee
#define REG_IIN_SENSOR 0xf1
#define REG_TOTAL_INPUT_POWER 0xf2
#define REG_PHASE_ID 0xf3
#define CORE_RAIL_INDICATOR BIT(7)
#define REG_PHASE_REPORTING 0xf4
#define MAX16601_NUM_PHASES 8
struct max16601_data {
enum chips id;
struct pmbus_driver_info info;
struct i2c_client *vsa;
int iout_avg_pkg;
};
#define to_max16601_data(x) container_of(x, struct max16601_data, info)
static int max16601_read_byte(struct i2c_client *client, int page, int reg)
{
const struct pmbus_driver_info *info = pmbus_get_driver_info(client);
struct max16601_data *data = to_max16601_data(info);
if (page > 0) {
if (page == 2) /* VSA */
return i2c_smbus_read_byte_data(data->vsa, reg);
return -EOPNOTSUPP;
}
return -ENODATA;
}
static int max16601_read_word(struct i2c_client *client, int page, int phase,
int reg)
{
const struct pmbus_driver_info *info = pmbus_get_driver_info(client);
struct max16601_data *data = to_max16601_data(info);
u8 buf[I2C_SMBUS_BLOCK_MAX + 1];
int ret;
switch (page) {
case 0: /* VCORE */
if (phase == 0xff)
return -ENODATA;
switch (reg) {
case PMBUS_READ_IIN:
case PMBUS_READ_IOUT:
case PMBUS_READ_TEMPERATURE_1:
ret = i2c_smbus_write_byte_data(client, REG_PHASE_ID,
phase);
if (ret)
return ret;
ret = i2c_smbus_read_block_data(client,
REG_PHASE_REPORTING,
buf);
if (ret < 0)
return ret;
if (ret < 6)
return -EIO;
switch (reg) {
case PMBUS_READ_TEMPERATURE_1:
return buf[1] << 8 | buf[0];
case PMBUS_READ_IOUT:
return buf[3] << 8 | buf[2];
case PMBUS_READ_IIN:
return buf[5] << 8 | buf[4];
default:
break;
}
}
return -EOPNOTSUPP;
case 1: /* VCORE, read IIN/PIN from sensor element */
switch (reg) {
case PMBUS_READ_IIN:
return i2c_smbus_read_word_data(client, REG_IIN_SENSOR);
case PMBUS_READ_PIN:
return i2c_smbus_read_word_data(client,
REG_TOTAL_INPUT_POWER);
default:
break;
}
return -EOPNOTSUPP;
case 2: /* VSA */
switch (reg) {
case PMBUS_VIRT_READ_IOUT_MAX:
ret = i2c_smbus_read_word_data(data->vsa,
REG_IOUT_AVG_PK);
if (ret < 0)
return ret;
if (sign_extend32(ret, 10) >
sign_extend32(data->iout_avg_pkg, 10))
data->iout_avg_pkg = ret;
return data->iout_avg_pkg;
case PMBUS_VIRT_RESET_IOUT_HISTORY:
return 0;
case PMBUS_IOUT_OC_FAULT_LIMIT:
case PMBUS_IOUT_OC_WARN_LIMIT:
case PMBUS_OT_FAULT_LIMIT:
case PMBUS_OT_WARN_LIMIT:
case PMBUS_READ_IIN:
case PMBUS_READ_IOUT:
case PMBUS_READ_TEMPERATURE_1:
case PMBUS_STATUS_WORD:
return i2c_smbus_read_word_data(data->vsa, reg);
default:
return -EOPNOTSUPP;
}
default:
return -EOPNOTSUPP;
}
}
static int max16601_write_byte(struct i2c_client *client, int page, u8 reg)
{
const struct pmbus_driver_info *info = pmbus_get_driver_info(client);
struct max16601_data *data = to_max16601_data(info);
if (page == 2) {
if (reg == PMBUS_CLEAR_FAULTS)
return i2c_smbus_write_byte(data->vsa, reg);
return -EOPNOTSUPP;
}
return -ENODATA;
}
static int max16601_write_word(struct i2c_client *client, int page, int reg,
u16 value)
{
const struct pmbus_driver_info *info = pmbus_get_driver_info(client);
struct max16601_data *data = to_max16601_data(info);
switch (page) {
case 0: /* VCORE */
return -ENODATA;
case 1: /* VCORE IIN/PIN from sensor element */
default:
return -EOPNOTSUPP;
case 2: /* VSA */
switch (reg) {
case PMBUS_VIRT_RESET_IOUT_HISTORY:
data->iout_avg_pkg = 0xfc00;
return 0;
case PMBUS_IOUT_OC_FAULT_LIMIT:
case PMBUS_IOUT_OC_WARN_LIMIT:
case PMBUS_OT_FAULT_LIMIT:
case PMBUS_OT_WARN_LIMIT:
return i2c_smbus_write_word_data(data->vsa, reg, value);
default:
return -EOPNOTSUPP;
}
}
}
static int max16601_identify(struct i2c_client *client,
struct pmbus_driver_info *info)
{
struct max16601_data *data = to_max16601_data(info);
int reg;
reg = i2c_smbus_read_byte_data(client, REG_SETPT_DVID);
if (reg < 0)
return reg;
if (reg & DAC_10MV_MODE)
info->vrm_version[0] = vr13;
else
info->vrm_version[0] = vr12;
if (data->id != max16601)
return 0;
reg = i2c_smbus_read_byte_data(client, REG_DEFAULT_NUM_POP);
if (reg < 0)
return reg;
/*
* If REG_DEFAULT_NUM_POP returns 0, we don't know how many phases
* are populated. Stick with the default in that case.
*/
reg &= 0x0f;
if (reg && reg <= MAX16601_NUM_PHASES)
info->phases[0] = reg;
return 0;
}
static struct pmbus_driver_info max16601_info = {
.pages = 3,
.format[PSC_VOLTAGE_IN] = linear,
.format[PSC_VOLTAGE_OUT] = vid,
.format[PSC_CURRENT_IN] = linear,
.format[PSC_CURRENT_OUT] = linear,
.format[PSC_TEMPERATURE] = linear,
.format[PSC_POWER] = linear,
.func[0] = PMBUS_HAVE_VIN | PMBUS_HAVE_IIN | PMBUS_HAVE_PIN |
PMBUS_HAVE_STATUS_INPUT |
PMBUS_HAVE_VOUT | PMBUS_HAVE_STATUS_VOUT |
PMBUS_HAVE_IOUT | PMBUS_HAVE_STATUS_IOUT |
PMBUS_HAVE_TEMP | PMBUS_HAVE_STATUS_TEMP |
PMBUS_HAVE_POUT | PMBUS_PAGE_VIRTUAL | PMBUS_PHASE_VIRTUAL,
.func[1] = PMBUS_HAVE_IIN | PMBUS_HAVE_PIN | PMBUS_PAGE_VIRTUAL,
.func[2] = PMBUS_HAVE_IIN | PMBUS_HAVE_STATUS_INPUT |
PMBUS_HAVE_IOUT | PMBUS_HAVE_STATUS_IOUT |
PMBUS_HAVE_TEMP | PMBUS_HAVE_STATUS_TEMP | PMBUS_PAGE_VIRTUAL,
.phases[0] = MAX16601_NUM_PHASES,
.pfunc[0] = PMBUS_HAVE_IIN | PMBUS_HAVE_IOUT | PMBUS_HAVE_TEMP,
.pfunc[1] = PMBUS_HAVE_IIN | PMBUS_HAVE_IOUT,
.pfunc[2] = PMBUS_HAVE_IIN | PMBUS_HAVE_IOUT | PMBUS_HAVE_TEMP,
.pfunc[3] = PMBUS_HAVE_IIN | PMBUS_HAVE_IOUT,
.pfunc[4] = PMBUS_HAVE_IIN | PMBUS_HAVE_IOUT | PMBUS_HAVE_TEMP,
.pfunc[5] = PMBUS_HAVE_IIN | PMBUS_HAVE_IOUT,
.pfunc[6] = PMBUS_HAVE_IIN | PMBUS_HAVE_IOUT | PMBUS_HAVE_TEMP,
.pfunc[7] = PMBUS_HAVE_IIN | PMBUS_HAVE_IOUT,
.identify = max16601_identify,
.read_byte_data = max16601_read_byte,
.read_word_data = max16601_read_word,
.write_byte = max16601_write_byte,
.write_word_data = max16601_write_word,
};
static void max16601_remove(void *_data)
{
struct max16601_data *data = _data;
i2c_unregister_device(data->vsa);
}
static const struct i2c_device_id max16601_id[] = {
{"max16508", max16508},
{"max16601", max16601},
{}
};
MODULE_DEVICE_TABLE(i2c, max16601_id);
static int max16601_get_id(struct i2c_client *client)
{
struct device *dev = &client->dev;
u8 buf[I2C_SMBUS_BLOCK_MAX + 1];
enum chips id;
int ret;
ret = i2c_smbus_read_block_data(client, PMBUS_IC_DEVICE_ID, buf);
if (ret < 0 || ret < 11)
return -ENODEV;
/*
* PMBUS_IC_DEVICE_ID is expected to return "MAX16601y.xx"
* or "MAX16500y.xx".
*/
if (!strncmp(buf, "MAX16500", 8)) {
id = max16508;
} else if (!strncmp(buf, "MAX16601", 8)) {
id = max16601;
} else {
buf[ret] = '\0';
dev_err(dev, "Unsupported chip '%s'\n", buf);
return -ENODEV;
}
return id;
}
static int max16601_probe(struct i2c_client *client)
{
struct device *dev = &client->dev;
const struct i2c_device_id *id;
struct max16601_data *data;
int ret, chip_id;
if (!i2c_check_functionality(client->adapter,
I2C_FUNC_SMBUS_READ_BYTE_DATA |
I2C_FUNC_SMBUS_READ_BLOCK_DATA))
return -ENODEV;
chip_id = max16601_get_id(client);
if (chip_id < 0)
return chip_id;
id = i2c_match_id(max16601_id, client);
if (chip_id != id->driver_data)
dev_warn(&client->dev,
"Device mismatch: Configured %s (%d), detected %d\n",
id->name, (int) id->driver_data, chip_id);
ret = i2c_smbus_read_byte_data(client, REG_PHASE_ID);
if (ret < 0)
return ret;
if (!(ret & CORE_RAIL_INDICATOR)) {
dev_err(dev,
"Driver must be instantiated on CORE rail I2C address\n");
return -ENODEV;
}
data = devm_kzalloc(dev, sizeof(*data), GFP_KERNEL);
if (!data)
return -ENOMEM;
data->id = chip_id;
data->iout_avg_pkg = 0xfc00;
data->vsa = i2c_new_dummy_device(client->adapter, client->addr + 1);
if (IS_ERR(data->vsa)) {
dev_err(dev, "Failed to register VSA client\n");
return PTR_ERR(data->vsa);
}
ret = devm_add_action_or_reset(dev, max16601_remove, data);
if (ret)
return ret;
data->info = max16601_info;
return pmbus_do_probe(client, &data->info);
}
static struct i2c_driver max16601_driver = {
.driver = {
.name = "max16601",
},
.probe_new = max16601_probe,
.id_table = max16601_id,
};
module_i2c_driver(max16601_driver);
MODULE_AUTHOR("Guenter Roeck <linux@roeck-us.net>");
MODULE_DESCRIPTION("PMBus driver for Maxim MAX16601");
MODULE_LICENSE("GPL v2");
|
/*
---
name: Picker.Date
description: Creates a DatePicker, can be used for picking years/months/days and time, or all of them
authors: Arian Stolwijk
requires: [Picker, Picker.Attach, Locale.en-US.DatePicker, More/Locale, More/Date]
provides: Picker.Date
...
*/
(function(){this.DatePicker=Picker.Date=new Class({Extends:Picker.Attach,options:{timePicker:false,timePickerOnly:false,timeWheelStep:1,yearPicker:true,yearsPerPage:20,startDay:1,rtl:false,startView:"days",openLastView:false,pickOnly:false,canAlwaysGoUp:["months","days"],updateAll:false,weeknumbers:false,months_abbr:null,days_abbr:null,years_title:function(f,e){var g=f.get("year");
return g+"-"+(g+e.yearsPerPage-1);},months_title:function(f,e){return f.get("year");},days_title:function(f,e){return f.format("%b %Y");},time_title:function(f,e){return(e.pickOnly=="time")?Locale.get("DatePicker.select_a_time"):f.format("%d %B, %Y");
}},initialize:function(g,f){this.parent(g,f);this.setOptions(f);f=this.options;["year","month","day","time"].some(function(h){if(f[h+"PickerOnly"]){f.pickOnly=h;
return true;}return false;});if(f.pickOnly){f[f.pickOnly+"Picker"]=true;f.startView=f.pickOnly;}var e=["days","months","years"];["month","year","decades"].some(function(j,h){return(f.startView==j)&&(f.startView=e[h]);
});f.canAlwaysGoUp=f.canAlwaysGoUp?Array.from(f.canAlwaysGoUp):[];if(f.minDate){if(!(f.minDate instanceof Date)){f.minDate=Date.parse(f.minDate);}f.minDate.clearTime();
}if(f.maxDate){if(!(f.maxDate instanceof Date)){f.maxDate=Date.parse(f.maxDate);}f.maxDate.clearTime();}if(!f.format){f.format=(f.pickOnly!="time")?Locale.get("Date.shortDate"):"";
if(f.timePicker){f.format=(f.format)+(f.format?" ":"")+Locale.get("Date.shortTime");}}this.addEvent("attached",function(l,k){if(!this.currentView||!f.openLastView){this.currentView=f.startView;
}this.date=c(new Date(),f.minDate,f.maxDate);var h=k.get("tag"),i;if(h=="input"){i=k;}else{var j=this.toggles.indexOf(k);if(this.inputs[j]){i=this.inputs[j];
}}this.getInputDate(i);this.input=i;this.setColumns(this.originalColumns);}.bind(this),true);},getInputDate:function(e){this.date=new Date();if(!e){return;
}var g=Date.parse(e.get("value"));if(g==null||!g.isValid()){var f=e.retrieve("datepicker:value");if(f){g=Date.parse(f);}}if(g!=null&&g.isValid()){this.date=g;
}},constructPicker:function(){this.parent();if(!this.options.rtl){this.previous=new Element("div.previous[html=«]").inject(this.header);this.next=new Element("div.next[html=»]").inject(this.header);
}else{this.next=new Element("div.previous[html=«]").inject(this.header);this.previous=new Element("div.next[html=»]").inject(this.header);}},hidePrevious:function(e,f){this[e?"next":"previous"].setStyle("display",f?"block":"none");
return this;},showPrevious:function(e){return this.hidePrevious(e,true);},setPreviousEvent:function(f,e){this[e?"next":"previous"].removeEvents("click");
if(f){this[e?"next":"previous"].addEvent("click",f);}return this;},hideNext:function(){return this.hidePrevious(true);},showNext:function(){return this.showPrevious(true);
},setNextEvent:function(e){return this.setPreviousEvent(e,true);},setColumns:function(h,e,g,i){var f=this.parent(h),j;if((e||this.currentView)&&(j="render"+(e||this.currentView).capitalize())&&this[j]){this[j](g||this.date.clone(),i);
}return f;},renderYears:function(g,j){var q=this.options,f=q.columns,o=q.yearsPerPage,e=[],h=[];this.dateElements=[];g=g.clone().decrement("year",g.get("year")%o);
var k=g.clone().decrement("year",Math.floor((f-1)/2)*o);for(var l=f;l--;){var p=k.clone();h.push(p);e.push(a.years(b.years(q,p.clone()),q,this.date.clone(),this.dateElements,function(i){if(q.pickOnly=="years"){this.select(i);
}else{this.renderMonths(i,"fade");}this.date=i;}.bind(this)));k.increment("year",o);}this.setColumnsContent(e,j);this.setTitle(h,q.years_title);var n=(q.minDate&&g.get("year")<=q.minDate.get("year")),m=(q.maxDate&&(g.get("year")+q.yearsPerPage)>=q.maxDate.get("year"));
this[(n?"hide":"show")+"Previous"]();this[(m?"hide":"show")+"Next"]();this.setPreviousEvent(function(){this.renderYears(g.decrement("year",o),"left");}.bind(this));
this.setNextEvent(function(){this.renderYears(g.increment("year",o),"right");}.bind(this));this.setTitleEvent(null);this.currentView="years";},renderMonths:function(g,j){var s=this.options,n=s.columns,f=[],h=[],k=g.clone().decrement("year",Math.floor((n-1)/2));
this.dateElements=[];for(var l=n;l--;){var r=k.clone();h.push(r);f.push(a.months(b.months(s,r.clone()),s,this.date.clone(),this.dateElements,function(i){if(s.pickOnly=="months"){this.select(i);
}else{this.renderDays(i,"fade");}this.date=i;}.bind(this)));k.increment("year",1);}this.setColumnsContent(f,j);this.setTitle(h,s.months_title);var p=g.get("year"),o=(s.minDate&&p<=s.minDate.get("year")),m=(s.maxDate&&p>=s.maxDate.get("year"));
this[(o?"hide":"show")+"Previous"]();this[(m?"hide":"show")+"Next"]();this.setPreviousEvent(function(){this.renderMonths(g.decrement("year",n),"left");
}.bind(this));this.setNextEvent(function(){this.renderMonths(g.increment("year",n),"right");}.bind(this));var e=s.yearPicker&&(s.pickOnly!="months"||s.canAlwaysGoUp.contains("months"));
var q=(e)?function(){this.renderYears(g,"fade");}.bind(this):null;this.setTitleEvent(q);this.currentView="months";},renderDays:function(h,k){var r=this.options,f=r.columns,g=[],j=[],m=h.clone().decrement("month",Math.floor((f-1)/2));
this.dateElements=[];for(var n=f;n--;){_date=m.clone();j.push(_date);g.push(a.days(b.days(r,_date.clone()),r,this.date.clone(),this.dateElements,function(i){if(r.pickOnly=="days"||!r.timePicker){this.select(i);
}else{this.renderTime(i,"fade");}this.date=i;}.bind(this)));m.increment("month",1);}this.setColumnsContent(g,k);this.setTitle(j,r.days_title);var l=h.format("%Y%m").toInt(),p=(r.minDate&&l<=r.minDate.format("%Y%m")),o=(r.maxDate&&l>=r.maxDate.format("%Y%m"));
this[(p?"hide":"show")+"Previous"]();this[(o?"hide":"show")+"Next"]();this.setPreviousEvent(function(){this.renderDays(h.decrement("month",f),"left");}.bind(this));
this.setNextEvent(function(){this.renderDays(h.increment("month",f),"right");}.bind(this));var e=r.pickOnly!="days"||r.canAlwaysGoUp.contains("days");var q=(e)?function(){this.renderMonths(h,"fade");
}.bind(this):null;this.setTitleEvent(q);this.currentView="days";},renderTime:function(i,j){var h=this.options;this.setTitle(i,h.time_title);var f=this.originalColumns=h.columns;
this.currentView=null;if(f!=1){this.setColumns(1);}this.setContent(a.time(h,i.clone(),function(k){this.select(k);}.bind(this)),j);this.hidePrevious().hideNext().setPreviousEvent(null).setNextEvent(null);
var g=h.pickOnly!="time"||h.canAlwaysGoUp.contains("time");var e=(g)?function(){this.setColumns(f,"days",i,"fade");}.bind(this):null;this.setTitleEvent(e);
this.currentView="time";},select:function(f,g){this.date=f;var h=f.format(this.options.format),i=f.strftime(),e=(!this.options.updateAll&&!g&&this.input)?[this.input]:this.inputs;
e.each(function(j){j.set("value",h).store("datepicker:value",i).fireEvent("change");},this);this.fireEvent("select",[f].concat(e));this.close();return this;
}});var b={years:function(f,e){var h=[];for(var g=0;g<f.yearsPerPage;g++){h.push(+e);e.increment("year",1);}return h;},months:function(f,e){var h=[];e.set("month",0);
for(var g=0;g<=11;g++){h.push(+e);e.increment("month",1);}return h;},days:function(f,e){var h=[];e.set("date",1);while(e.get("day")!=f.startDay){e.set("date",e.get("date")-1);
}for(var g=0;g<42;g++){h.push(+e);e.increment("day",1);}return h;}};var a={years:function(j,m,f,i,l){var e=new Element("div.years"),k=new Date(),h,g;j.each(function(o,p){var n=new Date(o),q=n.get("year");
g=".year.year"+p;if(q==k.get("year")){g+=".today";}if(q==f.get("year")){g+=".selected";}h=new Element("div"+g,{text:q}).inject(e);i.push({element:h,time:o});
if(d("year",n,m)){h.addClass("unavailable");}else{h.addEvent("click",l.pass(n));}});return e;},months:function(g,q,f,l,p){var o=new Date(),m=o.get("month"),k=o.get("year"),n=f.get("year"),e=new Element("div.months"),h=q.months_abbr||Locale.get("Date.months_abbr"),j,i;
g.each(function(s,t){var r=new Date(s),u=r.get("year");i=".month.month"+(t+1);if(t==m&&u==k){i+=".today";}if(t==f.get("month")&&u==n){i+=".selected";}j=new Element("div"+i,{text:h[t]}).inject(e);
l.push({element:j,time:s});if(d("month",r,q)){j.addClass("unavailable");}else{j.addEvent("click",p.pass(r));}});return e;},days:function(j,g,m,w,l){var v=new Date(j[14]).get("month"),k=new Date().toDateString(),e=m.toDateString(),n=g.weeknumbers,q=new Element("table.days"+(n?".weeknumbers":""),{role:"grid","aria-labelledby":this.titleID}),s=new Element("thead").inject(q),p=new Element("tbody").inject(q),x=new Element("tr.titles").inject(s),i=g.days_abbr||Locale.get("Date.days_abbr"),r,t,f,h,u,o=g.rtl?"top":"bottom";
if(n){new Element("th.title.day.weeknumber",{text:Locale.get("DatePicker.week")}).inject(x);}for(r=g.startDay;r<(g.startDay+7);r++){new Element("th.title.day.day"+(r%7),{text:i[(r%7)],role:"columnheader"}).inject(x,o);
}j.each(function(y,A){var z=new Date(y);if(A%7==0){h=new Element("tr.week.week"+(Math.floor(A/7))).set("role","row").inject(p);if(n){new Element("th.day.weeknumber",{text:z.get("week"),scope:"row",role:"rowheader"}).inject(h);
}}u=z.toDateString();t=".day.day"+z.get("day");if(u==k){t+=".today";}if(z.get("month")!=v){t+=".otherMonth";}f=new Element("td"+t,{text:z.getDate(),role:"gridcell"}).inject(h,o);
if(u==e){f.addClass("selected").set("aria-selected","true");}else{f.set("aria-selected","false");}w.push({element:f,time:y});if(d("date",z,g)){f.addClass("unavailable");
}else{f.addEvent("click",l.pass(z.clone()));}});return q;},time:function(g,f,h){var e=new Element("div.time"),j=(f.get("minutes")/g.timeWheelStep).round()*g.timeWheelStep;
if(j>=60){j=0;}f.set("minutes",j);var i=new Element("input.hour[type=text]",{title:Locale.get("DatePicker.use_mouse_wheel"),value:f.format("%H"),events:{click:function(l){l.target.focus();
l.stop();},mousewheel:function(l){l.stop();i.focus();var m=i.get("value").toInt();m=(l.wheel>0)?((m<23)?m+1:0):((m>0)?m-1:23);f.set("hours",m);i.set("value",f.format("%H"));
}.bind(this)},maxlength:2}).inject(e);var k=new Element("input.minutes[type=text]",{title:Locale.get("DatePicker.use_mouse_wheel"),value:f.format("%M"),events:{click:function(l){l.target.focus();
l.stop();},mousewheel:function(l){l.stop();k.focus();var m=k.get("value").toInt();m=(l.wheel>0)?((m<59)?(m+g.timeWheelStep):0):((m>0)?(m-g.timeWheelStep):(60-g.timeWheelStep));
if(m>=60){m=0;}f.set("minutes",m);k.set("value",f.format("%M"));}.bind(this)},maxlength:2}).inject(e);new Element("div.separator[text=:]").inject(e);new Element("input.ok[type=submit]",{value:Locale.get("DatePicker.time_confirm_button"),events:{click:function(l){l.stop();
f.set({hours:i.get("value").toInt(),minutes:k.get("value").toInt()});h(f.clone());}}}).inject(e);return e;}};Picker.Date.defineRenderer=function(e,f){a[e]=f;
return this;};var c=function(f,g,e){if(g&&f<g){return g;}if(e&&f>e){return e;}return f;};var d=function(k,g,o){var h=o.minDate,f=o.maxDate,n=o.availableDates,l,j,m,e;
if(!h&&!f&&!n){return false;}g.clearTime();if(k=="year"){l=g.get("year");return((h&&l<h.get("year"))||(f&&l>f.get("year"))||((n!=null&&!o.invertAvailable)&&(n[l]==null||Object.getLength(n[l])==0||Object.getLength(Object.filter(n[l],function(p){return(p.length>0);
}))==0)));}if(k=="month"){l=g.get("year");j=g.get("month")+1;e=g.format("%Y%m").toInt();return((h&&e<h.format("%Y%m").toInt())||(f&&e>f.format("%Y%m").toInt())||((n!=null&&!o.invertAvailable)&&(n[l]==null||n[l][j]==null||n[l][j].length==0)));
}l=g.get("year");j=g.get("month")+1;m=g.get("date");var i=(h&&g<h)||(h&&g>f);if(n!=null){i=i||n[l]==null||n[l][j]==null||!n[l][j].contains(m);if(o.invertAvailable){i=!i;
}}return i;};})(); |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h"
#include "ash/ash_switches.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/memory/ref_counted_memory.h"
#include "base/values.h"
#include "chrome/browser/browser_about_handler.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/chromeos/kiosk_mode/kiosk_mode_settings.h"
#include "chrome/browser/chromeos/login/enrollment/enrollment_screen_actor.h"
#include "chrome/browser/chromeos/login/login_display_host_impl.h"
#include "chrome/browser/chromeos/login/screen_locker.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/chromeos/login/wizard_controller.h"
#include "chrome/browser/chromeos/system/input_device_settings.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/about_ui.h"
#include "chrome/browser/ui/webui/chromeos/login/app_launch_splash_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/base_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/enrollment_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/error_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/eula_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/kiosk_app_menu_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/kiosk_autolaunch_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/kiosk_enable_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/locally_managed_user_creation_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/network_dropdown_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/network_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/network_state_informer.h"
#include "chrome/browser/ui/webui/chromeos/login/reset_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/terms_of_service_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/update_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/user_image_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/wrong_hwid_screen_handler.h"
#include "chrome/browser/ui/webui/options/chromeos/user_image_source.h"
#include "chrome/browser/ui/webui/theme_source.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/url_constants.h"
#include "chromeos/chromeos_constants.h"
#include "chromeos/chromeos_switches.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
#include "grit/browser_resources.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/webui/web_ui_util.h"
namespace chromeos {
namespace {
// List of known types of OobeUI. Type added as path in chrome://oobe url, for
// example chrome://oobe/user-adding.
const char kOobeDisplay[] = "oobe";
const char kLoginDisplay[] = "login";
const char kLockDisplay[] = "lock";
const char kUserAddingDisplay[] = "user-adding";
const char kAppLaunchSplashDisplay[] = "app-launch-splash";
const char* kKnownDisplayTypes[] = {
kOobeDisplay,
kLoginDisplay,
kLockDisplay,
kUserAddingDisplay,
kAppLaunchSplashDisplay
};
const char kStringsJSPath[] = "strings.js";
const char kLoginJSPath[] = "login.js";
const char kOobeJSPath[] = "oobe.js";
const char kKeyboardUtilsJSPath[] = "keyboard_utils.js";
const char kDemoUserLoginJSPath[] = "demo_user_login.js";
// Paths for deferred resource loading.
const char kEnrollmentHTMLPath[] = "enrollment.html";
const char kEnrollmentCSSPath[] = "enrollment.css";
const char kEnrollmentJSPath[] = "enrollment.js";
// Creates a WebUIDataSource for chrome://oobe
content::WebUIDataSource* CreateOobeUIDataSource(
const base::DictionaryValue& localized_strings,
const std::string& display_type) {
content::WebUIDataSource* source =
content::WebUIDataSource::Create(chrome::kChromeUIOobeHost);
source->SetUseJsonJSFormatV2();
source->AddLocalizedStrings(localized_strings);
source->SetJsonPath(kStringsJSPath);
if (chromeos::KioskModeSettings::Get()->IsKioskModeEnabled()) {
source->SetDefaultResource(IDR_DEMO_USER_LOGIN_HTML);
source->AddResourcePath(kDemoUserLoginJSPath, IDR_DEMO_USER_LOGIN_JS);
return source;
}
if (display_type == kOobeDisplay) {
source->SetDefaultResource(IDR_OOBE_HTML);
source->AddResourcePath(kOobeJSPath, IDR_OOBE_JS);
} else {
source->SetDefaultResource(IDR_LOGIN_HTML);
source->AddResourcePath(kLoginJSPath, IDR_LOGIN_JS);
}
source->AddResourcePath(kKeyboardUtilsJSPath, IDR_KEYBOARD_UTILS_JS);
source->OverrideContentSecurityPolicyFrameSrc(
"frame-src chrome://terms/ "
"chrome-extension://mfffpogegjflfpflabcdkioaeobkgjik/;");
// Serve deferred resources.
source->AddResourcePath(kEnrollmentHTMLPath, IDR_OOBE_ENROLLMENT_HTML);
source->AddResourcePath(kEnrollmentCSSPath, IDR_OOBE_ENROLLMENT_CSS);
source->AddResourcePath(kEnrollmentJSPath, IDR_OOBE_ENROLLMENT_JS);
return source;
}
std::string GetDisplayType(const GURL& url) {
std::string path = url.path().size() ? url.path().substr(1) : "";
if (std::find(kKnownDisplayTypes,
kKnownDisplayTypes + arraysize(kKnownDisplayTypes),
path) == kKnownDisplayTypes + arraysize(kKnownDisplayTypes)) {
LOG(ERROR) << "Unknown display type '" << path << "'. Setting default.";
return kLoginDisplay;
}
return path;
}
} // namespace
// static
const char OobeUI::kScreenOobeNetwork[] = "connect";
const char OobeUI::kScreenOobeEula[] = "eula";
const char OobeUI::kScreenOobeUpdate[] = "update";
const char OobeUI::kScreenOobeEnrollment[] = "oauth-enrollment";
const char OobeUI::kScreenGaiaSignin[] = "gaia-signin";
const char OobeUI::kScreenAccountPicker[] = "account-picker";
const char OobeUI::kScreenKioskAutolaunch[] = "autolaunch";
const char OobeUI::kScreenKioskEnable[] = "kiosk-enable";
const char OobeUI::kScreenErrorMessage[] = "error-message";
const char OobeUI::kScreenUserImagePicker[] = "user-image";
const char OobeUI::kScreenTpmError[] = "tpm-error-message";
const char OobeUI::kScreenPasswordChanged[] = "password-changed";
const char OobeUI::kScreenManagedUserCreationFlow[]
= "managed-user-creation";
const char OobeUI::kScreenTermsOfService[] = "terms-of-service";
const char OobeUI::kScreenWrongHWID[] = "wrong-hwid";
const char OobeUI::kScreenAppLaunchSplash[] = "app-launch-splash";
const char OobeUI::kScreenConfirmPassword[] = "confirm-password";
const char OobeUI::kScreenMessageBox[] = "message-box";
OobeUI::OobeUI(content::WebUI* web_ui, const GURL& url)
: WebUIController(web_ui),
core_handler_(NULL),
network_dropdown_handler_(NULL),
update_screen_handler_(NULL),
network_screen_actor_(NULL),
eula_screen_actor_(NULL),
reset_screen_actor_(NULL),
autolaunch_screen_actor_(NULL),
kiosk_enable_screen_actor_(NULL),
wrong_hwid_screen_actor_(NULL),
locally_managed_user_creation_screen_actor_(NULL),
error_screen_handler_(NULL),
signin_screen_handler_(NULL),
terms_of_service_screen_actor_(NULL),
user_image_screen_actor_(NULL),
kiosk_app_menu_handler_(NULL),
current_screen_(SCREEN_UNKNOWN),
ready_(false) {
display_type_ = GetDisplayType(url);
InitializeScreenMaps();
network_state_informer_ = new NetworkStateInformer();
network_state_informer_->Init();
core_handler_ = new CoreOobeHandler(this);
AddScreenHandler(core_handler_);
core_handler_->SetDelegate(this);
network_dropdown_handler_ = new NetworkDropdownHandler();
AddScreenHandler(network_dropdown_handler_);
update_screen_handler_ = new UpdateScreenHandler();
AddScreenHandler(update_screen_handler_);
network_dropdown_handler_->AddObserver(update_screen_handler_);
if (display_type_ == kOobeDisplay) {
NetworkScreenHandler* network_screen_handler =
new NetworkScreenHandler(core_handler_);
network_screen_actor_ = network_screen_handler;
AddScreenHandler(network_screen_handler);
}
EulaScreenHandler* eula_screen_handler = new EulaScreenHandler(core_handler_);
eula_screen_actor_ = eula_screen_handler;
AddScreenHandler(eula_screen_handler);
ResetScreenHandler* reset_screen_handler = new ResetScreenHandler();
reset_screen_actor_ = reset_screen_handler;
AddScreenHandler(reset_screen_handler);
KioskAutolaunchScreenHandler* autolaunch_screen_handler =
new KioskAutolaunchScreenHandler();
autolaunch_screen_actor_ = autolaunch_screen_handler;
AddScreenHandler(autolaunch_screen_handler);
KioskEnableScreenHandler* kiosk_enable_screen_handler =
new KioskEnableScreenHandler();
kiosk_enable_screen_actor_ = kiosk_enable_screen_handler;
AddScreenHandler(kiosk_enable_screen_handler);
LocallyManagedUserCreationScreenHandler*
locally_managed_user_creation_screen_handler =
new LocallyManagedUserCreationScreenHandler();
locally_managed_user_creation_screen_actor_ =
locally_managed_user_creation_screen_handler;
AddScreenHandler(locally_managed_user_creation_screen_handler);
WrongHWIDScreenHandler* wrong_hwid_screen_handler =
new WrongHWIDScreenHandler();
wrong_hwid_screen_actor_ = wrong_hwid_screen_handler;
AddScreenHandler(wrong_hwid_screen_handler);
EnrollmentScreenHandler* enrollment_screen_handler =
new EnrollmentScreenHandler();
enrollment_screen_actor_ = enrollment_screen_handler;
AddScreenHandler(enrollment_screen_handler);
TermsOfServiceScreenHandler* terms_of_service_screen_handler =
new TermsOfServiceScreenHandler;
terms_of_service_screen_actor_ = terms_of_service_screen_handler;
AddScreenHandler(terms_of_service_screen_handler);
UserImageScreenHandler* user_image_screen_handler =
new UserImageScreenHandler();
user_image_screen_actor_ = user_image_screen_handler;
AddScreenHandler(user_image_screen_handler);
error_screen_handler_ = new ErrorScreenHandler(network_state_informer_);
AddScreenHandler(error_screen_handler_);
gaia_screen_handler_ = new GaiaScreenHandler(network_state_informer_);
AddScreenHandler(gaia_screen_handler_);
signin_screen_handler_ = new SigninScreenHandler(network_state_informer_,
error_screen_handler_,
core_handler_,
gaia_screen_handler_);
AddScreenHandler(signin_screen_handler_);
AppLaunchSplashScreenHandler* app_launch_splash_screen_handler =
new AppLaunchSplashScreenHandler(network_state_informer_,
error_screen_handler_);
AddScreenHandler(app_launch_splash_screen_handler);
app_launch_splash_screen_actor_ = app_launch_splash_screen_handler;
// Initialize KioskAppMenuHandler. Note that it is NOT a screen handler.
kiosk_app_menu_handler_ = new KioskAppMenuHandler;
web_ui->AddMessageHandler(kiosk_app_menu_handler_);
base::DictionaryValue localized_strings;
GetLocalizedStrings(&localized_strings);
Profile* profile = Profile::FromWebUI(web_ui);
// Set up the chrome://theme/ source, for Chrome logo.
ThemeSource* theme = new ThemeSource(profile);
content::URLDataSource::Add(profile, theme);
// Set up the chrome://terms/ data source, for EULA content.
AboutUIHTMLSource* about_source =
new AboutUIHTMLSource(chrome::kChromeUITermsHost, profile);
content::URLDataSource::Add(profile, about_source);
// Set up the chrome://oobe/ source.
content::WebUIDataSource::Add(profile,
CreateOobeUIDataSource(localized_strings,
display_type_));
// Set up the chrome://userimage/ source.
options::UserImageSource* user_image_source =
new options::UserImageSource();
content::URLDataSource::Add(profile, user_image_source);
}
OobeUI::~OobeUI() {
core_handler_->SetDelegate(NULL);
network_dropdown_handler_->RemoveObserver(update_screen_handler_);
}
void OobeUI::ShowScreen(WizardScreen* screen) {
screen->Show();
}
void OobeUI::HideScreen(WizardScreen* screen) {
screen->Hide();
}
UpdateScreenActor* OobeUI::GetUpdateScreenActor() {
return update_screen_handler_;
}
NetworkScreenActor* OobeUI::GetNetworkScreenActor() {
return network_screen_actor_;
}
EulaScreenActor* OobeUI::GetEulaScreenActor() {
return eula_screen_actor_;
}
EnrollmentScreenActor* OobeUI::GetEnrollmentScreenActor() {
return enrollment_screen_actor_;
}
ResetScreenActor* OobeUI::GetResetScreenActor() {
return reset_screen_actor_;
}
KioskAutolaunchScreenActor* OobeUI::GetKioskAutolaunchScreenActor() {
return autolaunch_screen_actor_;
}
KioskEnableScreenActor* OobeUI::GetKioskEnableScreenActor() {
return kiosk_enable_screen_actor_;
}
TermsOfServiceScreenActor* OobeUI::GetTermsOfServiceScreenActor() {
return terms_of_service_screen_actor_;
}
WrongHWIDScreenActor* OobeUI::GetWrongHWIDScreenActor() {
return wrong_hwid_screen_actor_;
}
UserImageScreenActor* OobeUI::GetUserImageScreenActor() {
return user_image_screen_actor_;
}
ErrorScreenActor* OobeUI::GetErrorScreenActor() {
return error_screen_handler_;
}
LocallyManagedUserCreationScreenHandler*
OobeUI::GetLocallyManagedUserCreationScreenActor() {
return locally_managed_user_creation_screen_actor_;
}
AppLaunchSplashScreenActor*
OobeUI::GetAppLaunchSplashScreenActor() {
return app_launch_splash_screen_actor_;
}
void OobeUI::GetLocalizedStrings(base::DictionaryValue* localized_strings) {
// Note, handlers_[0] is a GenericHandler used by the WebUI.
for (size_t i = 0; i < handlers_.size(); ++i)
handlers_[i]->GetLocalizedStrings(localized_strings);
webui::SetFontAndTextDirection(localized_strings);
kiosk_app_menu_handler_->GetLocalizedStrings(localized_strings);
#if defined(GOOGLE_CHROME_BUILD)
localized_strings->SetString("buildType", "chrome");
#else
localized_strings->SetString("buildType", "chromium");
#endif
// If we're not doing boot animation then WebUI should trigger
// wallpaper load on boot.
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableBootAnimation)) {
localized_strings->SetString("bootIntoWallpaper", "on");
} else {
localized_strings->SetString("bootIntoWallpaper", "off");
}
bool keyboard_driven_oobe =
system::keyboard_settings::ForceKeyboardDrivenUINavigation();
localized_strings->SetString("highlightStrength",
keyboard_driven_oobe ? "strong" : "normal");
}
void OobeUI::InitializeScreenMaps() {
screen_names_.resize(SCREEN_UNKNOWN);
screen_names_[SCREEN_OOBE_NETWORK] = kScreenOobeNetwork;
screen_names_[SCREEN_OOBE_EULA] = kScreenOobeEula;
screen_names_[SCREEN_OOBE_UPDATE] = kScreenOobeUpdate;
screen_names_[SCREEN_OOBE_ENROLLMENT] = kScreenOobeEnrollment;
screen_names_[SCREEN_GAIA_SIGNIN] = kScreenGaiaSignin;
screen_names_[SCREEN_ACCOUNT_PICKER] = kScreenAccountPicker;
screen_names_[SCREEN_KIOSK_AUTOLAUNCH] = kScreenKioskAutolaunch;
screen_names_[SCREEN_KIOSK_ENABLE] = kScreenKioskEnable;
screen_names_[SCREEN_ERROR_MESSAGE] = kScreenErrorMessage;
screen_names_[SCREEN_USER_IMAGE_PICKER] = kScreenUserImagePicker;
screen_names_[SCREEN_TPM_ERROR] = kScreenTpmError;
screen_names_[SCREEN_PASSWORD_CHANGED] = kScreenPasswordChanged;
screen_names_[SCREEN_CREATE_MANAGED_USER_FLOW] =
kScreenManagedUserCreationFlow;
screen_names_[SCREEN_TERMS_OF_SERVICE] = kScreenTermsOfService;
screen_names_[SCREEN_WRONG_HWID] = kScreenWrongHWID;
screen_names_[SCREEN_APP_LAUNCH_SPLASH] = kScreenAppLaunchSplash;
screen_names_[SCREEN_CONFIRM_PASSWORD] = kScreenConfirmPassword;
screen_names_[SCREEN_MESSAGE_BOX] = kScreenMessageBox;
screen_ids_.clear();
for (size_t i = 0; i < screen_names_.size(); ++i)
screen_ids_[screen_names_[i]] = static_cast<Screen>(i);
}
void OobeUI::AddScreenHandler(BaseScreenHandler* handler) {
web_ui()->AddMessageHandler(handler);
handlers_.push_back(handler);
}
void OobeUI::InitializeHandlers() {
ready_ = true;
for (size_t i = 0; i < ready_callbacks_.size(); ++i)
ready_callbacks_[i].Run();
ready_callbacks_.clear();
// Notify 'initialize' for synchronously loaded screens.
for (size_t i = 0; i < handlers_.size(); ++i) {
if (handlers_[i]->async_assets_load_id().empty())
handlers_[i]->InitializeBase();
}
}
void OobeUI::OnScreenAssetsLoaded(const std::string& async_assets_load_id) {
DCHECK(!async_assets_load_id.empty());
for (size_t i = 0; i < handlers_.size(); ++i) {
if (handlers_[i]->async_assets_load_id() == async_assets_load_id)
handlers_[i]->InitializeBase();
}
}
bool OobeUI::IsJSReady(const base::Closure& display_is_ready_callback) {
if (!ready_)
ready_callbacks_.push_back(display_is_ready_callback);
return ready_;
}
void OobeUI::ShowOobeUI(bool show) {
core_handler_->ShowOobeUI(show);
}
void OobeUI::ShowRetailModeLoginSpinner() {
signin_screen_handler_->ShowRetailModeLoginSpinner();
}
void OobeUI::ShowSigninScreen(const LoginScreenContext& context,
SigninScreenHandlerDelegate* delegate,
NativeWindowDelegate* native_window_delegate) {
signin_screen_handler_->SetDelegate(delegate);
signin_screen_handler_->SetNativeWindowDelegate(native_window_delegate);
LoginScreenContext actual_context(context);
actual_context.set_oobe_ui(core_handler_->show_oobe_ui());
signin_screen_handler_->Show(actual_context);
}
void OobeUI::ResetSigninScreenHandlerDelegate() {
signin_screen_handler_->SetDelegate(NULL);
signin_screen_handler_->SetNativeWindowDelegate(NULL);
}
void OobeUI::AddObserver(Observer* observer) {
observer_list_.AddObserver(observer);
}
void OobeUI::RemoveObserver(Observer* observer) {
observer_list_.RemoveObserver(observer);
}
const std::string& OobeUI::GetScreenName(Screen screen) const {
DCHECK(screen >= 0 && screen < SCREEN_UNKNOWN);
return screen_names_[static_cast<size_t>(screen)];
}
void OobeUI::OnCurrentScreenChanged(const std::string& screen) {
if (screen_ids_.count(screen)) {
Screen new_screen = screen_ids_[screen];
FOR_EACH_OBSERVER(Observer,
observer_list_,
OnCurrentScreenChanged(current_screen_, new_screen));
current_screen_ = new_screen;
} else {
NOTREACHED() << "Screen should be registered in InitializeScreenMaps()";
current_screen_ = SCREEN_UNKNOWN;
}
}
} // namespace chromeos
|
require File.join(File.dirname(__FILE__), "acceptance_test_helper")
require 'mocha'
class StubbingMethodUnnecessarilyTest < Test::Unit::TestCase
include AcceptanceTest
def setup
setup_acceptance_test
end
def teardown
teardown_acceptance_test
end
def test_should_allow_stubbing_method_unnecessarily
Mocha::Configuration.allow(:stubbing_method_unnecessarily)
test_result = run_test do
mock = mock('mock')
mock.stubs(:public_method)
end
assert_passed(test_result)
assert !@logger.warnings.include?('stubbing method unnecessarily: #<Mock:mock>.public_method(any_parameters)')
end
def test_should_warn_when_stubbing_method_unnecessarily
Mocha::Configuration.warn_when(:stubbing_method_unnecessarily)
test_result = run_test do
mock = mock('mock')
mock.stubs(:public_method)
end
assert_passed(test_result)
assert @logger.warnings.include?('stubbing method unnecessarily: #<Mock:mock>.public_method(any_parameters)')
end
def test_should_prevent_stubbing_method_unnecessarily
Mocha::Configuration.prevent(:stubbing_method_unnecessarily)
test_result = run_test do
mock = mock('mock')
mock.stubs(:public_method)
end
assert_failed(test_result)
assert test_result.error_messages.include?('Mocha::StubbingError: stubbing method unnecessarily: #<Mock:mock>.public_method(any_parameters)')
end
def test_should_default_to_allow_stubbing_method_unnecessarily
test_result = run_test do
mock = mock('mock')
mock.stubs(:public_method)
end
assert_passed(test_result)
assert !@logger.warnings.include?('stubbing method unnecessarily: #<Mock:mock>.public_method(any_parameters)')
end
def test_should_allow_stubbing_method_when_stubbed_method_is_invoked
Mocha::Configuration.prevent(:stubbing_method_unnecessarily)
test_result = run_test do
mock = mock('mock')
mock.stubs(:public_method)
mock.public_method
end
assert_passed(test_result)
end
end |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/bidi_checker_web_ui_test.h"
#include "base/base_paths.h"
#include "base/i18n/rtl.h"
#include "base/message_loop/message_loop.h"
#include "base/path_service.h"
#include "base/prefs/pref_service.h"
#include "base/strings/utf_string_conversions.h"
#include "base/synchronization/waitable_event.h"
#include "base/threading/platform_thread.h"
#include "base/time/time.h"
#include "base/values.h"
#include "chrome/browser/autofill/personal_data_manager_factory.h"
#include "chrome/browser/history/history_service.h"
#include "chrome/browser/history/history_service_factory.h"
#include "chrome/browser/prefs/session_startup_pref.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/autofill/core/browser/autofill_profile.h"
#include "components/autofill/core/browser/autofill_test_utils.h"
#include "components/autofill/core/browser/personal_data_manager.h"
#include "content/public/browser/browser_thread.h"
#include "ui/base/resource/resource_bundle.h"
#if defined(TOOLKIT_GTK)
#include <gtk/gtk.h>
#endif
using autofill::AutofillProfile;
using autofill::PersonalDataManager;
static const base::FilePath::CharType* kWebUIBidiCheckerLibraryJS =
FILE_PATH_LITERAL("third_party/bidichecker/bidichecker_packaged.js");
namespace {
base::FilePath WebUIBidiCheckerLibraryJSPath() {
base::FilePath src_root;
if (!PathService::Get(base::DIR_SOURCE_ROOT, &src_root))
LOG(ERROR) << "Couldn't find source root";
return src_root.Append(kWebUIBidiCheckerLibraryJS);
}
// Since synchronization isn't complete for the ResourceBundle class, reload
// locale resources on the IO thread.
// crbug.com/95425, crbug.com/132752
void ReloadLocaleResourcesOnIOThread(const std::string& new_locale) {
if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)) {
LOG(ERROR)
<< content::BrowserThread::IO
<< " != " << base::PlatformThread::CurrentId();
NOTREACHED();
}
std::string locale;
{
base::ThreadRestrictions::ScopedAllowIO allow_io_scope;
locale.assign(
ResourceBundle::GetSharedInstance().ReloadLocaleResources(new_locale));
}
ASSERT_FALSE(locale.empty());
}
// Since synchronization isn't complete for the ResourceBundle class, reload
// locale resources on the IO thread.
// crbug.com/95425, crbug.com/132752
void ReloadLocaleResources(const std::string& new_locale) {
content::BrowserThread::PostTaskAndReply(
content::BrowserThread::IO,
FROM_HERE,
base::Bind(&ReloadLocaleResourcesOnIOThread, base::ConstRef(new_locale)),
base::MessageLoop::QuitClosure());
content::RunMessageLoop();
}
} // namespace
static const base::FilePath::CharType* kBidiCheckerTestsJS =
FILE_PATH_LITERAL("bidichecker_tests.js");
void WebUIBidiCheckerBrowserTest::SetUp() {
argv_ = CommandLine::ForCurrentProcess()->GetArgs();
}
void WebUIBidiCheckerBrowserTest::TearDown() {
// Reset command line to the way it was before the test was run.
CommandLine::ForCurrentProcess()->InitFromArgv(argv_);
}
WebUIBidiCheckerBrowserTest::~WebUIBidiCheckerBrowserTest() {}
WebUIBidiCheckerBrowserTest::WebUIBidiCheckerBrowserTest() {}
void WebUIBidiCheckerBrowserTest::SetUpInProcessBrowserTestFixture() {
WebUIBrowserTest::SetUpInProcessBrowserTestFixture();
WebUIBrowserTest::AddLibrary(WebUIBidiCheckerLibraryJSPath());
WebUIBrowserTest::AddLibrary(base::FilePath(kBidiCheckerTestsJS));
}
void WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(
const std::string& page_url, bool is_rtl) {
ui_test_utils::NavigateToURL(browser(), GURL(page_url));
ASSERT_TRUE(RunJavascriptTest("runBidiChecker",
Value::CreateStringValue(page_url),
Value::CreateBooleanValue(is_rtl)));
}
void WebUIBidiCheckerBrowserTestLTR::RunBidiCheckerOnPage(
const std::string& page_url) {
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(page_url, false);
}
void WebUIBidiCheckerBrowserTestRTL::RunBidiCheckerOnPage(
const std::string& page_url) {
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(page_url, true);
}
void WebUIBidiCheckerBrowserTestRTL::SetUpOnMainThread() {
WebUIBidiCheckerBrowserTest::SetUpOnMainThread();
base::FilePath pak_path;
app_locale_ = base::i18n::GetConfiguredLocale();
ASSERT_TRUE(PathService::Get(base::FILE_MODULE, &pak_path));
pak_path = pak_path.DirName();
pak_path = pak_path.AppendASCII("pseudo_locales");
pak_path = pak_path.AppendASCII("fake-bidi");
pak_path = pak_path.ReplaceExtension(FILE_PATH_LITERAL("pak"));
ResourceBundle::GetSharedInstance().OverrideLocalePakForTest(pak_path);
ReloadLocaleResources("he");
base::i18n::SetICUDefaultLocale("he");
#if defined(OS_POSIX) && defined(TOOLKIT_GTK)
gtk_widget_set_default_direction(GTK_TEXT_DIR_RTL);
#endif
}
void WebUIBidiCheckerBrowserTestRTL::CleanUpOnMainThread() {
WebUIBidiCheckerBrowserTest::CleanUpOnMainThread();
#if defined(OS_POSIX) && defined(TOOLKIT_GTK)
gtk_widget_set_default_direction(GTK_TEXT_DIR_LTR);
#endif
base::i18n::SetICUDefaultLocale(app_locale_);
ResourceBundle::GetSharedInstance().OverrideLocalePakForTest(
base::FilePath());
ReloadLocaleResources(app_locale_);
}
// Tests
//==============================
// chrome://settings/history
//==============================
static void SetupHistoryPageTest(Browser* browser,
const std::string& page_url,
const std::string& page_title) {
HistoryService* history_service = HistoryServiceFactory::GetForProfile(
browser->profile(), Profile::IMPLICIT_ACCESS);
const GURL history_url = GURL(page_url);
history_service->AddPage(
history_url, base::Time::Now(), history::SOURCE_BROWSED);
history_service->SetPageTitle(history_url, UTF8ToUTF16(page_title));
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR,
TestHistoryPage) {
// Test an Israeli news site with a Hebrew title.
SetupHistoryPageTest(browser(),
"http://www.ynet.co.il",
"\xD7\x91\xD7\x93\xD7\x99\xD7\xA7\xD7\x94\x21");
RunBidiCheckerOnPage(chrome::kChromeUIHistoryFrameURL);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL,
TestHistoryPage) {
SetupHistoryPageTest(browser(), "http://www.google.com", "Google");
RunBidiCheckerOnPage(chrome::kChromeUIHistoryFrameURL);
}
//==============================
// chrome://about
//==============================
// This page isn't localized to an RTL language so we test it only in English.
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestAboutPage) {
RunBidiCheckerOnPage(chrome::kChromeUIAboutURL);
}
//==============================
// chrome://crashes
//==============================
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestCrashesPage) {
RunBidiCheckerOnPage(chrome::kChromeUICrashesURL);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, TestCrashesPage) {
RunBidiCheckerOnPage(chrome::kChromeUICrashesURL);
}
//==============================
// chrome://downloads
//==============================
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR,
TestDownloadsPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUIDownloadsURL);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL,
TestDownloadsPageRTL) {
RunBidiCheckerOnPage(chrome::kChromeUIDownloadsURL);
}
//==============================
// chrome://newtab
//==============================
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestNewTabPage) {
RunBidiCheckerOnPage(chrome::kChromeUINewTabURL);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, TestNewTabPage) {
RunBidiCheckerOnPage(chrome::kChromeUINewTabURL);
}
//==============================
// chrome://plugins
//==============================
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestPluginsPage) {
RunBidiCheckerOnPage(chrome::kChromeUIPluginsURL);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, TestPluginsPage) {
RunBidiCheckerOnPage(chrome::kChromeUIPluginsURL);
}
//==============================
// chrome://settings-frame
//==============================
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestSettingsPage) {
RunBidiCheckerOnPage(chrome::kChromeUISettingsFrameURL);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, TestSettingsPage) {
RunBidiCheckerOnPage(chrome::kChromeUISettingsFrameURL);
}
static void SetupSettingsAutofillPageTest(Profile* profile,
const char* first_name,
const char* middle_name,
const char* last_name,
const char* email,
const char* company,
const char* address1,
const char* address2,
const char* city,
const char* state,
const char* zipcode,
const char* country,
const char* phone) {
autofill::test::DisableSystemServices(profile);
AutofillProfile autofill_profile;
autofill::test::SetProfileInfo(&autofill_profile,
first_name,
middle_name,
last_name,
email,
company,
address1,
address2,
city,
state,
zipcode,
country,
phone);
PersonalDataManager* personal_data_manager =
autofill::PersonalDataManagerFactory::GetForProfile(profile);
ASSERT_TRUE(personal_data_manager);
personal_data_manager->AddProfile(autofill_profile);
}
// http://crbug.com/94642
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR,
DISABLED_TestSettingsAutofillPage) {
SetupSettingsAutofillPageTest(browser()->profile(),
"\xD7\x9E\xD7\xA9\xD7\x94",
"\xD7\x91",
"\xD7\x9B\xD7\x94\xD7\x9F",
"moshe.b.cohen@biditest.com",
"\xD7\x91\xD7\x93\xD7\x99\xD7\xA7\xD7\x94\x20"
"\xD7\x91\xD7\xA2\xD7\x9E",
"\xD7\x93\xD7\xA8\xD7\x9A\x20\xD7\x9E\xD7\xA0"
"\xD7\x97\xD7\x9D\x20\xD7\x91\xD7\x92\xD7"
"\x99\xD7\x9F\x20\x32\x33",
"\xD7\xA7\xD7\x95\xD7\x9E\xD7\x94\x20\x32\x36",
"\xD7\xAA\xD7\x9C\x20\xD7\x90\xD7\x91\xD7\x99"
"\xD7\x91",
"",
"66183",
"\xD7\x99\xD7\xA9\xD7\xA8\xD7\x90\xD7\x9C",
"0000");
std::string url(chrome::kChromeUISettingsFrameURL);
url += std::string(chrome::kAutofillSubPage);
RunBidiCheckerOnPage(url);
}
// http://crbug.com/94642
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL,
DISABLED_TestSettingsAutofillPage) {
SetupSettingsAutofillPageTest(browser()->profile(),
"Milton",
"C.",
"Waddams",
"red.swingline@initech.com",
"Initech",
"4120 Freidrich Lane",
"Basement",
"Austin",
"Texas",
"78744",
"United States",
"5125551234");
std::string url(chrome::kChromeUISettingsFrameURL);
url += std::string(chrome::kAutofillSubPage);
RunBidiCheckerOnPage(url);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR,
TestSettingsClearBrowserDataPage) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += std::string(chrome::kClearBrowserDataSubPage);
RunBidiCheckerOnPage(url);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL,
TestSettingsClearBrowserDataPage) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += std::string(chrome::kClearBrowserDataSubPage);
RunBidiCheckerOnPage(url);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR,
TestSettingsContentSettingsPage) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += std::string(chrome::kContentSettingsSubPage);
RunBidiCheckerOnPage(url);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL,
TestSettingsContentSettingsPage) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += std::string(chrome::kContentSettingsSubPage);
RunBidiCheckerOnPage(url);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR,
TestSettingsContentSettingsExceptionsPage) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += std::string(chrome::kContentSettingsExceptionsSubPage);
RunBidiCheckerOnPage(url);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL,
TestSettingsContentSettingsExceptionsPage) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += std::string(chrome::kContentSettingsExceptionsSubPage);
RunBidiCheckerOnPage(url);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR,
TestSettingsLanguageOptionsPage) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += std::string(chrome::kLanguageOptionsSubPage);
RunBidiCheckerOnPage(url);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL,
TestSettingsLanguageOptionsPage) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += std::string(chrome::kLanguageOptionsSubPage);
RunBidiCheckerOnPage(url);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR,
TestSettingsSearchEnginesOptionsPage) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += std::string(chrome::kSearchEnginesSubPage);
RunBidiCheckerOnPage(url);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL,
TestSettingsSearchEnginesOptionsPage) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += std::string(chrome::kSearchEnginesSubPage);
RunBidiCheckerOnPage(url);
}
//===================================
// chrome://settings-frame/startup
//===================================
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR,
TestSettingsFrameStartup) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += "startup";
RunBidiCheckerOnPage(url);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL,
TestSettingsFrameStartup) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += "startup";
RunBidiCheckerOnPage(url);
}
//===================================
// chrome://settings-frame/importData
//===================================
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR,
TestSettingsFrameImportData) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += chrome::kImportDataSubPage;
RunBidiCheckerOnPage(url);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL,
TestSettingsFrameImportData) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += chrome::kImportDataSubPage;
RunBidiCheckerOnPage(url);
}
//========================================
// chrome://settings-frame/manageProfile
//========================================
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR,
TestSettingsFrameMangageProfile) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += chrome::kManageProfileSubPage;
RunBidiCheckerOnPage(url);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL,
TestSettingsFrameMangageProfile) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += chrome::kManageProfileSubPage;
RunBidiCheckerOnPage(url);
}
//===================================================
// chrome://settings-frame/contentExceptions#cookies
//===================================================
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR,
TestSettingsFrameContentExceptionsCookies) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += chrome::kContentSettingsExceptionsSubPage;
url += "#cookies";
RunBidiCheckerOnPage(url);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL,
TestSettingsFrameContentExceptionsCookies) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += chrome::kContentSettingsExceptionsSubPage;
url += "#cookies";
RunBidiCheckerOnPage(url);
}
//===================================================
// chrome://settings-frame/contentExceptions#images
//===================================================
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR,
TestSettingsFrameContentExceptionsImages) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += chrome::kContentSettingsExceptionsSubPage;
url += "#images";
RunBidiCheckerOnPage(url);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL,
TestSettingsFrameContentExceptionsImages) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += chrome::kContentSettingsExceptionsSubPage;
url += "#images";
RunBidiCheckerOnPage(url);
}
//======================================================
// chrome://settings-frame/contentExceptions#javascript
//======================================================
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR,
TestSettingsFrameContentExceptionsJavascript) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += chrome::kContentSettingsExceptionsSubPage;
url += "#javascript";
RunBidiCheckerOnPage(url);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL,
TestSettingsFrameContentExceptionsJavascript) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += chrome::kContentSettingsExceptionsSubPage;
url += "#javascript";
RunBidiCheckerOnPage(url);
}
//===================================================
// chrome://settings-frame/contentExceptions#plugins
//===================================================
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR,
TestSettingsFrameContentExceptionsPlugins) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += chrome::kContentSettingsExceptionsSubPage;
url += "#plugins";
RunBidiCheckerOnPage(url);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL,
TestSettingsFrameContentExceptionsPlugins) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += chrome::kContentSettingsExceptionsSubPage;
url += "#plugins";
RunBidiCheckerOnPage(url);
}
//===================================================
// chrome://settings-frame/contentExceptions#popups
//===================================================
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR,
TestSettingsFrameContentExceptionsPopups) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += chrome::kContentSettingsExceptionsSubPage;
url += "#popups";
RunBidiCheckerOnPage(url);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL,
TestSettingsFrameContentExceptionsPopups) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += chrome::kContentSettingsExceptionsSubPage;
url += "#popups";
RunBidiCheckerOnPage(url);
}
//===================================================
// chrome://settings-frame/contentExceptions#location
//===================================================
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR,
TestSettingsFrameContentExceptionsLocation) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += chrome::kContentSettingsExceptionsSubPage;
url += "#location";
RunBidiCheckerOnPage(url);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL,
TestSettingsFrameContentExceptionsLocation) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += chrome::kContentSettingsExceptionsSubPage;
url += "#location";
RunBidiCheckerOnPage(url);
}
//===================================================
// chrome://settings-frame/contentExceptions#notifications
//===================================================
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR,
TestSettingsFrameContentExceptionsNotifications) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += chrome::kContentSettingsExceptionsSubPage;
url += "#notifications";
RunBidiCheckerOnPage(url);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL,
TestSettingsFrameContentExceptionsNotifications) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += chrome::kContentSettingsExceptionsSubPage;
url += "#notifications";
RunBidiCheckerOnPage(url);
}
//===================================================
// chrome://settings-frame/contentExceptions#mouselock
//===================================================
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR,
TestSettingsFrameContentExceptionsMouseLock) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += chrome::kContentSettingsExceptionsSubPage;
url += "#mouselock";
RunBidiCheckerOnPage(url);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL,
TestSettingsFrameContentExceptionsMouseLock) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += chrome::kContentSettingsExceptionsSubPage;
url += "#mouselock";
RunBidiCheckerOnPage(url);
}
//========================================
// chrome://settings-frame/handlers
//========================================
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR,
TestSettingsFrameHandler) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += chrome::kHandlerSettingsSubPage;
RunBidiCheckerOnPage(url);
}
// Fails on chromeos. http://crbug.com/125367
#if defined(OS_CHROMEOS)
#define MAYBE_TestSettingsFrameHandler DISABLED_TestSettingsFrameHandler
#else
#define MAYBE_TestSettingsFrameHandler TestSettingsFrameHandler
#endif
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL,
MAYBE_TestSettingsFrameHandler) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += chrome::kHandlerSettingsSubPage;
RunBidiCheckerOnPage(url);
}
//========================================
// chrome://settings-frame/cookies
//========================================
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR,
TestSettingsFrameCookies) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += "cookies";
RunBidiCheckerOnPage(url);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL,
TestSettingsFrameCookies) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += "cookies";
RunBidiCheckerOnPage(url);
}
//========================================
// chrome://settings-frame/passwords
//========================================
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR,
TestSettingsFramePasswords) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += "passwords";
RunBidiCheckerOnPage(url);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL,
TestSettingsFramePasswords) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += "passwords";
RunBidiCheckerOnPage(url);
}
//========================================
// chrome://settings-frame/fonts
//========================================
#if defined(OS_MACOSX)
#define MAYBE_TestSettingsFrameFonts DISABLED_TestSettingsFrameFonts
#else
#define MAYBE_TestSettingsFrameFonts TestSettingsFrameFonts
#endif
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR,
MAYBE_TestSettingsFrameFonts) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += "fonts";
RunBidiCheckerOnPage(url);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL,
TestSettingsFrameFonts) {
std::string url(chrome::kChromeUISettingsFrameURL);
url += "fonts";
RunBidiCheckerOnPage(url);
}
// Test other uber iframes.
//==============================
// chrome://extensions-frame
//==============================
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestExtensionsFrame) {
RunBidiCheckerOnPage(chrome::kChromeUIExtensionsFrameURL);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL,
TestExtensionsFrame) {
RunBidiCheckerOnPage(chrome::kChromeUIExtensionsFrameURL);
}
//==============================
// chrome://help-frame
//==============================
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestHelpFrame) {
RunBidiCheckerOnPage(chrome::kChromeUIHelpFrameURL);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, TestHelpFrame) {
RunBidiCheckerOnPage(chrome::kChromeUIHelpFrameURL);
}
//==============================
// chrome://history-frame
//==============================
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestLTR, TestHistoryFrame) {
RunBidiCheckerOnPage(chrome::kChromeUIHistoryFrameURL);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestRTL, TestHistoryFrame) {
RunBidiCheckerOnPage(chrome::kChromeUIHistoryFrameURL);
}
|
// license:BSD-3-Clause
// copyright-holders:Tyler J. Stachecki,Ryan Holtz
// LBV, LDV, LLV, LSV, SBV, SDV, SLV, SSV
inline void vec_lbdlsv_sbdlsv(uint32_t iw, uint32_t rs)
{
const uint32_t shift_and_idx = (iw >> 11) & 0x3;
rsp_vec_t dqm = _mm_loadl_epi64((rsp_vec_t *) (m_vec_helpers.bdls_lut[shift_and_idx]));
const uint32_t addr = (rs + (sign_extend_6(iw) << shift_and_idx)) & 0xfff;
const uint32_t element = (iw >> 7) & 0xf;
uint16_t* regp = m_v[(iw >> 16) & 0x1f].s;
if (iw >> 29 & 0x1)
{
vec_store_group1(addr, element, regp, vec_load_unshuffled_operand(regp), dqm);
}
else
{
vec_load_group1(addr, element, regp, vec_load_unshuffled_operand(regp), dqm);
}
}
// LPV, LUV, SPV, SUV
inline void vec_lfhpuv_sfhpuv(uint32_t iw, uint32_t rs)
{
static const enum rsp_mem_request_type fhpu_type_lut[4] = {
RSP_MEM_REQUEST_PACK,
RSP_MEM_REQUEST_UPACK,
RSP_MEM_REQUEST_HALF,
RSP_MEM_REQUEST_FOURTH
};
const uint32_t addr = (rs + (sign_extend_6(iw) << 3)) & 0xfff;
const uint32_t element = (iw >> 7) & 0xf;
uint16_t* regp = m_v[(iw >> 16) & 0x1f].s;
rsp_mem_request_type request_type = fhpu_type_lut[((iw >> 11) & 0x1f) - 6];
if ((iw >> 29) & 0x1)
{
vec_store_group2(addr, element, regp, vec_load_unshuffled_operand(regp), _mm_setzero_si128(), request_type);
}
else
{
vec_load_group2(addr, element, regp, vec_load_unshuffled_operand(regp), _mm_setzero_si128(), request_type);
}
}
// LQV, LRV, SQV, SRV
inline void vec_lqrv_sqrv(uint32_t iw, uint32_t rs)
{
rs &= 0xfff;
const uint32_t addr = rs + (sign_extend_6(iw) << 4);
const uint32_t element = (iw >> 7) & 0xf;
uint16_t* regp = m_v[(iw >> 16) & 0x1f].s;
memcpy(m_vdqm.s, m_vec_helpers.qr_lut[addr & 0xf], sizeof(m_vdqm.s));
rsp_mem_request_type request_type = (iw >> 11 & 0x1) ? RSP_MEM_REQUEST_REST : RSP_MEM_REQUEST_QUAD;
if ((iw >> 29) & 0x1)
{
vec_store_group4(addr, element, regp, vec_load_unshuffled_operand(regp), vec_load_unshuffled_operand(m_vdqm.s), request_type);
}
else
{
vec_load_group4(addr, element, regp, vec_load_unshuffled_operand(regp), vec_load_unshuffled_operand(m_vdqm.s), request_type);
}
}
|
// Generated by CoffeeScript 1.12.0
/*
ExternalEditor
Kevin Gravier <kevin@mrkmg.com>
MIT
*/
(function() {
var ReadFileError,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
ReadFileError = (function(superClass) {
extend(ReadFileError, superClass);
ReadFileError.prototype.message = 'Failed to read temporary file';
function ReadFileError(original_error) {
this.original_error = original_error;
}
return ReadFileError;
})(Error);
module.exports = ReadFileError;
}).call(this);
|
/** @file
* IPRT - Power management.
*/
/*
* Copyright (C) 2008-2010 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL) only, as it comes in the "COPYING.CDDL" file of the
* VirtualBox OSE distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*/
#ifndef ___iprt_power_h
#define ___iprt_power_h
#include <iprt/cdefs.h>
#include <iprt/types.h>
RT_C_DECLS_BEGIN
/** @defgroup grp_rt_power RTPower - Power management
* @ingroup grp_rt
* @{
*/
#ifdef IN_RING0
/**
* MP event, see FNRTPOWERNOTIFICATION.
*/
typedef enum RTPOWEREVENT
{
/** The system will go into suspend mode. */
RTPOWEREVENT_SUSPEND = 1,
/** The system has resumed. */
RTPOWEREVENT_RESUME
} RTPOWEREVENT;
/**
* Notification callback.
*
* The context this is called in differs a bit from platform to
* platform, so be careful while in here.
*
* @param enmEvent The event.
* @param pvUser The user argument.
*/
typedef DECLCALLBACK(void) FNRTPOWERNOTIFICATION(RTPOWEREVENT enmEvent, void *pvUser);
/** Pointer to a FNRTPOWERNOTIFICATION(). */
typedef FNRTPOWERNOTIFICATION *PFNRTPOWERNOTIFICATION;
/**
* Registers a notification callback for power events.
*
* @returns IPRT status code.
* @retval VINF_SUCCESS on success.
* @retval VERR_NO_MEMORY if a registration record cannot be allocated.
* @retval VERR_ALREADY_EXISTS if the pfnCallback and pvUser already exist
* in the callback list.
*
* @param pfnCallback The callback.
* @param pvUser The user argument to the callback function.
*/
RTDECL(int) RTPowerNotificationRegister(PFNRTPOWERNOTIFICATION pfnCallback, void *pvUser);
/**
* This deregisters a notification callback registered via RTPowerNotificationRegister().
*
* The pfnCallback and pvUser arguments must be identical to the registration call
* of we won't find the right entry.
*
* @returns IPRT status code.
* @retval VINF_SUCCESS on success.
* @retval VERR_NOT_FOUND if no matching entry was found.
*
* @param pfnCallback The callback.
* @param pvUser The user argument to the callback function.
*/
RTDECL(int) RTPowerNotificationDeregister(PFNRTPOWERNOTIFICATION pfnCallback, void *pvUser);
/**
* This calls all registered power management callback handlers registered via RTPowerNotificationRegister().
*
* @returns IPRT status code.
* @retval VINF_SUCCESS on success.
*
* @param enmEvent Power Management event
*/
RTDECL(int) RTPowerSignalEvent(RTPOWEREVENT enmEvent);
#endif /* IN_RING0 */
/** @} */
RT_C_DECLS_END
#endif
|
/* This file contains an example program from The Little Book of
Semaphores, available from Green Tea Press, greenteapress.com
Copyright 2014 Allen B. Downey
License: Creative Commons Attribution-ShareAlike 3.0
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define NUM_CHILDREN 2
void perror_exit (char *s)
{
perror (s); exit (-1);
}
void *check_malloc(int size)
{
void *p = malloc (size);
if (p == NULL) perror_exit ("malloc failed");
return p;
}
typedef sem_t Semaphore;
Semaphore *make_semaphore (int n)
{
Semaphore *sem = check_malloc (sizeof(Semaphore));
int ret = sem_init(sem, 0, n);
if (ret == -1) perror_exit ("sem_init failed");
return sem;
}
int sem_signal(Semaphore *sem)
{
return sem_post(sem);
}
typedef struct {
int counter;
int end;
int *array;
Semaphore *mutex;
} Shared;
Shared *make_shared (int end)
{
int i;
Shared *shared = check_malloc (sizeof (Shared));
shared->counter = 0;
shared->end = end;
shared->array = check_malloc (shared->end * sizeof(int));
for (i=0; i<shared->end; i++) {
shared->array[i] = 0;
}
shared->mutex = make_semaphore(1);
return shared;
}
pthread_t make_thread(void *(*entry)(void *), Shared *shared)
{
int ret;
pthread_t thread;
ret = pthread_create (&thread, NULL, entry, (void *) shared);
if (ret != 0) perror_exit ("pthread_create failed");
return thread;
}
void join_thread (pthread_t thread)
{
int ret = pthread_join (thread, NULL);
if (ret == -1) perror_exit ("pthread_join failed");
}
void child_code (Shared *shared)
{
printf ("Starting child at counter %d\n", shared->counter);
while (1) {
sem_wait(shared->mutex);
if (shared->counter >= shared->end) {
sem_signal(shared->mutex);
return;
}
shared->array[shared->counter]++;
shared->counter++;
if (shared->counter % 10000 == 0) {
printf ("%d\n", shared->counter);
}
sem_signal(shared->mutex);
}
}
void *entry (void *arg)
{
Shared *shared = (Shared *) arg;
child_code (shared);
printf ("Child done.\n");
pthread_exit (NULL);
}
void check_array (Shared *shared)
{
int i, errors=0;
printf ("Checking...\n");
for (i=0; i<shared->end; i++) {
if (shared->array[i] != 1) errors++;
}
printf ("%d errors.\n", errors);
}
int main ()
{
int i;
pthread_t child[NUM_CHILDREN];
Shared *shared = make_shared (100000000);
for (i=0; i<NUM_CHILDREN; i++) {
child[i] = make_thread (entry, shared);
}
for (i=0; i<NUM_CHILDREN; i++) {
join_thread (child[i]);
}
check_array (shared);
return 0;
}
|
/// \file
/// \ingroup tutorial_legacy
/// This script is a representation using TTasks of the Geant3 simulation program
/// This example uses directly TTask objects.
/// A real implementation would require one class per task derived from TTask.
///
/// \macro_code
///
/// \author Rene Brun
void geant3tasks()
{
TTask *geant3 = new TTask("geant3","Geant3 simulation main program");
gROOT->GetListOfTasks()->Add(geant3);
TTask *uginit = new TTask("uginit","Initialisation manager");
TTask *grun = new TTask("grun","Run manager");
TTask *uglast = new TTask("uglast","Termination manager");
geant3->Add(uginit);
geant3->Add(grun);
geant3->Add(uglast);
TTask *ginit = new TTask("ginit","Geant3 initialisation");
TTask *ugeom = new TTask("ugeom","Geometry initialisation manager");
TTask *gphysi = new TTask("gphysi","Initialise cross-sections and energy loss tables");
TTask *ggclos = new TTask("ggclos","Geometry analyzer and optimizer");
uginit->Add(ginit);
uginit->Add(ugeom);
uginit->Add(gphysi);
uginit->Add(ggclos);
TTask *gtrigi = new TTask("gtrigi","Event initialisation");
TTask *gtrig = new TTask("gtrig","Event manager");
TTask *gtrigc = new TTask("gtrigc","Event cleaner");
grun->Add(gtrigi);
grun->Add(gtrig);
grun->Add(gtrigc);
TTask *glast = new TTask("glast","Geant3 termination");
TTask *igend = new TTask("igend","Graphics package termination");
uglast->Add(glast);
uglast->Add(igend);
TTask *gukine = new TTask("gukine","Event generator manager");
TTask *gutrev = new TTask("gutrev","Event application manager");
TTask *gudigi = new TTask("gudigi","Event digitisation manager");
TTask *guout = new TTask("guout","Event termination manager");
gtrig->Add(gukine);
gtrig->Add(gutrev);
gtrig->Add(gudigi);
gtrig->Add(guout);
TTask *gtreve = new TTask("gtreve","Geant3 event manager");
gutrev->Add(gtreve);
TTask *gltrac = new TTask("gltrac","Initialize tracking parameters");
TTask *gftrac = new TTask("gftrac","select next track segment from stack JTRACK");
TTask *gutrak = new TTask("gutrak","Application track manager");
gtreve->Add(gltrac);
gtreve->Add(gftrac);
gtreve->Add(gutrak);
TTask *gtrack = new TTask("gtrack","Geant3 track manager");
gutrak->Add(gtrack);
TTask *gtgama = new TTask("gtgama","photon propagator");
TTask *gtelec = new TTask("gtelec","electron propagator");
TTask *gtneut = new TTask("gtneut","neutron propagator");
TTask *gthadr = new TTask("gthadr","hadron propagator");
TTask *gtmuon = new TTask("gtmuon","muon propagator");
TTask *gtnino = new TTask("gtnino","geantino propagator");
TTask *gtckov = new TTask("gtckov","Cherenkov light propagator");
TTask *gthion = new TTask("gthion","heavy ion propagator");
TTask *gustep = new TTask("gustep","Application step manager");
TTask *gtmedi = new TTask("gtmedi","Geometry volume finder");
gtrack->Add(gtgama);
gtrack->Add(gtelec);
gtrack->Add(gtneut);
gtrack->Add(gthadr);
gtrack->Add(gtmuon);
gtrack->Add(gtnino);
gtrack->Add(gtckov);
gtrack->Add(gthion);
gtrack->Add(gustep);
gtrack->Add(gtmedi);
TTask *gtnext = new TTask("gtnext","Geometry bounary manager");
TTask *gpairg = new TTask("gpairg","Generate pair production");
TTask *gcomp = new TTask("gcomp","Generate Compton scattering");
TTask *gphot = new TTask("gphot","Generate photo effect");
TTask *grayl = new TTask("grayl","Generate Rayleigh effect");
TTask *gpfis = new TTask("gpfis","Generate photo fission");
gtgama->Add(gtnext);
gtgama->Add(gpairg);
gtgama->Add(gcomp);
gtgama->Add(gphot);
gtgama->Add(grayl);
gtgama->Add(gpfis);
TTask *guswim = new TTask("guswim","magnetic field propagator");
TTask *ggckov = new TTask("ggckov","Generate Cherenkov photons");
TTask *gsync = new TTask("gsync","Generate synchrotron radiation");
TTask *gmults = new TTask("gmults","Apply multiple scattering");
TTask *gbreme = new TTask("gbreme","Generate Bremsstrahlung");
TTask *gdray = new TTask("gdray","Generate delta ray");
TTask *ganni = new TTask("ganni","Generate Positron annihilation");
TTask *gannir = new TTask("gannir","Stopped tracks and annihilation at rest");
gtelec->Add(gtnext);
gtelec->Add(guswim);
gtelec->Add(ggckov);
gtelec->Add(gsync);
gtelec->Add(gmults);
gtelec->Add(gbreme);
gtelec->Add(gdray);
gtelec->Add(ganni);
gtelec->Add(gannir);
TTask *guphad = new TTask("guphad","Hadronic cross-section manager");
TTask *guhadr = new TTask("guhadr","Hadronic cascade manager");
TTask *gdecay = new TTask("gdecay","Particle decay");
gtneut->Add(gtnext);
gtneut->Add(guphad);
gtneut->Add(guhadr);
gtneut->Add(gdecay);
gthadr->Add(gtnext);
gthadr->Add(guphad);
gthadr->Add(guswim);
gthadr->Add(ggckov);
gthadr->Add(gmults);
gthadr->Add(guhadr);
gthadr->Add(gdecay);
gthadr->Add(gdray);
TTask *gbremm = new TTask("gbremm","Generate Bremsstrahlung");
TTask *gpairm = new TTask("gpairm","Generate Pair production");
TTask *gmunu = new TTask("gmunu","Generate Nuclear interaction");
gtmuon->Add(gtnext);
gtmuon->Add(guswim);
gtmuon->Add(ggckov);
gtmuon->Add(gmults);
gtmuon->Add(gbremm);
gtmuon->Add(gpairm);
gtmuon->Add(gdecay);
gtmuon->Add(gdray);
gtmuon->Add(gmunu);
gtmuon->Add(gdecay);
gtnino->Add(gtnext);
TTask *glisur = new TTask("glisur","Photon is reflected");
gtckov->Add(gtnext);
gtckov->Add(glisur);
gthion->Add(gtnext);
gthion->Add(guswim);
gthion->Add(gmults);
gthion->Add(guhadr);
gthion->Add(gdray);
new TBrowser;
gDebug = 2;
}
|
//// [classDeclarationBlockScoping1.ts]
class C {
}
{
class C {
}
}
//// [classDeclarationBlockScoping1.js]
var C = (function () {
function C() {
}
return C;
}());
{
var C_1 = (function () {
function C_1() {
}
return C_1;
}());
}
|
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.actuate.autoconfigure.liquibase;
import liquibase.integration.spring.SpringLiquibase;
import org.junit.jupiter.api.Test;
import org.springframework.boot.actuate.liquibase.LiquibaseEndpoint;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.liquibase.DataSourceClosingSpringLiquibase;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link LiquibaseEndpointAutoConfiguration}.
*
* @author Phillip Webb
*/
class LiquibaseEndpointAutoConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(LiquibaseEndpointAutoConfiguration.class));
@Test
void runShouldHaveEndpointBean() {
this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=liquibase")
.withBean(SpringLiquibase.class, () -> mock(SpringLiquibase.class))
.run((context) -> assertThat(context).hasSingleBean(LiquibaseEndpoint.class));
}
@Test
void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() {
this.contextRunner.withBean(SpringLiquibase.class, () -> mock(SpringLiquibase.class))
.withPropertyValues("management.endpoint.liquibase.enabled:false")
.run((context) -> assertThat(context).doesNotHaveBean(LiquibaseEndpoint.class));
}
@Test
void runWhenNotExposedShouldNotHaveEndpointBean() {
this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(LiquibaseEndpoint.class));
}
@Test
void disablesCloseOfDataSourceWhenEndpointIsEnabled() {
this.contextRunner.withUserConfiguration(DataSourceClosingLiquibaseConfiguration.class)
.withPropertyValues("management.endpoints.web.exposure.include=liquibase").run((context) -> {
assertThat(context).hasSingleBean(LiquibaseEndpoint.class);
assertThat(context.getBean(DataSourceClosingSpringLiquibase.class))
.hasFieldOrPropertyWithValue("closeDataSourceOnceMigrated", false);
});
}
@Test
void doesNotDisableCloseOfDataSourceWhenEndpointIsDisabled() {
this.contextRunner.withUserConfiguration(DataSourceClosingLiquibaseConfiguration.class)
.withPropertyValues("management.endpoint.liquibase.enabled:false").run((context) -> {
assertThat(context).doesNotHaveBean(LiquibaseEndpoint.class);
DataSourceClosingSpringLiquibase bean = context.getBean(DataSourceClosingSpringLiquibase.class);
assertThat(bean).hasFieldOrPropertyWithValue("closeDataSourceOnceMigrated", true);
});
}
@Configuration(proxyBeanMethods = false)
static class DataSourceClosingLiquibaseConfiguration {
@Bean
SpringLiquibase liquibase() {
return new DataSourceClosingSpringLiquibase() {
private boolean propertiesSet = false;
@Override
public void setCloseDataSourceOnceMigrated(boolean closeDataSourceOnceMigrated) {
if (this.propertiesSet) {
throw new IllegalStateException(
"setCloseDataSourceOnceMigrated invoked after afterPropertiesSet");
}
super.setCloseDataSourceOnceMigrated(closeDataSourceOnceMigrated);
}
@Override
public void afterPropertiesSet() {
this.propertiesSet = true;
}
};
}
}
}
|
<?php
include ("../jpgraph.php");
include ("../jpgraph_radar.php");
// Some data to plot
$data = array(55,80,26,31,95);
// Create the graph and the plot
$graph = new RadarGraph(250,200,"auto");
// Add a drop shadow to the graph
$graph->SetShadow();
// Create the titles for the axis
$titles = $gDateLocale->GetShortMonth();
$graph->SetTitles($titles);
$graph->SetColor('lightyellow');
// ADjust the position to make more room
// for the legend
$graph->SetCenter(0.4,0.5);
// Add grid lines
$graph->grid->Show();
$graph->grid->SetColor('darkred');
$graph->grid->SetLineStyle('dotted');
$plot = new RadarPlot($data);
$plot->SetFillColor('lightblue');
$plot->SetLegend("QA results");
// Add the plot and display the graph
$graph->Add($plot);
$graph->Stroke();
?> |
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
trait A {
fn g(&self) -> int { 10 }
}
impl A for int { }
fn f<T:A>(i: T) {
assert_eq!(i.g(), 10);
}
pub fn main () {
f(0i);
}
|
import os
import shutil
import tempfile
import vmprof
import prof_six as six
from _prof_imports import TreeStats, CallTreeStat
class VmProfProfile(object):
""" Wrapper class that represents VmProf Python profiling backend with API matching
the cProfile.
"""
def __init__(self):
self.stats = None
self.basepath = None
self.file = None
self.is_enabled = False
def runcall(self, func, *args, **kw):
self.enable()
try:
return func(*args, **kw)
finally:
self.disable()
def enable(self):
if not self.is_enabled:
if not os.path.exists(self.basepath):
os.makedirs(self.basepath)
self.file = tempfile.NamedTemporaryFile(delete=False, dir=self.basepath)
try:
vmprof.enable(self.file.fileno(), lines=True)
except:
vmprof.enable(self.file.fileno())
self.is_enabled = True
def disable(self):
if self.is_enabled:
vmprof.disable()
self.file.close()
self.is_enabled = False
def create_stats(self):
return None
def getstats(self):
self.create_stats()
return self.stats
def dump_stats(self, file):
shutil.copyfile(self.file.name, file)
def _walk_tree(self, parent, node, callback):
tree = callback(parent, node)
for c in six.itervalues(node.children):
self._walk_tree(node, c, callback)
return tree
def tree_stats_to_response(self, filename, response):
tree_stats_to_response(filename, response)
def snapshot_extension(self):
return '.prof'
def _walk_tree(parent, node, callback):
if node is None:
return None
tree = callback(parent, node)
for c in six.itervalues(node.children):
_walk_tree(tree, c, callback)
return tree
def tree_stats_to_response(filename, response):
stats = vmprof.read_profile(filename)
response.tree_stats = TreeStats()
response.tree_stats.sampling_interval = vmprof.DEFAULT_PERIOD
try:
tree = stats.get_tree()
except vmprof.stats.EmptyProfileFile:
tree = None
def convert(parent, node):
tstats = CallTreeStat()
tstats.name = node.name
tstats.count = node.count
tstats.children = []
tstats.line_count = getattr(node, 'lines', {})
if parent is not None:
if parent.children is None:
parent.children = []
parent.children.append(tstats)
return tstats
response.tree_stats.call_tree = _walk_tree(None, tree, convert)
|
package test.verify;
import org.testng.Assert;
import org.testng.TestListenerAdapter;
import org.testng.TestNG;
import org.testng.annotations.Test;
import test.SimpleBaseTest;
public class VerifyTest extends SimpleBaseTest {
private void runTest(Class<?> cls, int expected) {
TestNG tng = create(cls);
TestListenerAdapter tla = new TestListenerAdapter();
tng.addListener(tla);
tng.run();
Assert.assertEquals(tla.getPassedTests().size(), expected);
}
@Test
public void verifyWithAnnotation() {
runTest(VerifySampleTest.class, 4);
}
@Test
public void verifyWithoutAnnotation() {
runTest(VerifyNoListenersSampleTest.class, 3);
}
@Test
public void verifyTestListener() {
TestNG tng = create(Verify2SampleTest.class);
VerifyTestListener.m_count = 0;
tng.run();
Assert.assertEquals(VerifyTestListener.m_count, 1);
}
@Test
public void verifyBaseClassTestListener() {
TestNG tng = create(Verify3SampleTest.class);
VerifyTestListener.m_count = 0;
tng.run();
Assert.assertEquals(VerifyTestListener.m_count, 1);
}
}
|
<?php
final class PhutilFileLockTestCase extends PhutilTestCase {
public function testLockTesting() {
// We should be able to acquire locks.
$file = new TempFile();
$this->assertTrue($this->lockTest($file));
$this->assertTrue($this->lockTest($file));
}
public function testLockHolding() {
// When a process is holding a lock, other processes should be unable
// to acquire it.
$file = new TempFile();
$hold = $this->holdLock($file);
$this->assertFalse($this->lockTest($file));
$hold->resolveKill();
$this->assertTrue($this->lockTest($file));
}
public function testInProcessLocking() {
// Other processes should be unable to lock a file if we hold the lock.
$file = new TempFile();
$lock = PhutilFileLock::newForPath($file);
$lock->lock();
$this->assertFalse($this->lockTest($file));
$lock->unlock();
$this->assertTrue($this->lockTest($file));
}
public function testInProcessHolding() {
// We should be unable to lock a file if another process is holding the
// lock.
$file = new TempFile();
$lock = PhutilFileLock::newForPath($file);
$hold = $this->holdLock($file);
$caught = null;
try {
$lock->lock();
} catch (PhutilLockException $ex) {
$caught = $ex;
}
$this->assertTrue($caught instanceof PhutilLockException);
$hold->resolveKill();
$this->assertTrue($this->lockTest($file));
$lock->lock();
$lock->unlock();
}
public function testRelock() {
// Trying to lock a file twice should throw an exception.
$file = new TempFile();
$lock = PhutilFileLock::newForPath($file);
$lock->lock();
$caught = null;
try {
$lock->lock();
} catch (Exception $ex) {
$caught = $ex;
}
$this->assertTrue($caught instanceof Exception);
}
public function testExcessiveUnlock() {
// Trying to unlock a file twice should throw an exception.
$file = new TempFile();
$lock = PhutilFileLock::newForPath($file);
$lock->lock();
$lock->unlock();
$caught = null;
try {
$lock->unlock();
} catch (Exception $ex) {
$caught = $ex;
}
$this->assertTrue($caught instanceof Exception);
}
public function testUnlockAll() {
// unlockAll() should release all locks.
$file = new TempFile();
$lock = PhutilFileLock::newForPath($file);
$lock->lock();
$this->assertFalse($this->lockTest($file));
PhutilFileLock::unlockAll();
$this->assertTrue($this->lockTest($file));
// Calling this again shouldn't do anything bad.
PhutilFileLock::unlockAll();
$this->assertTrue($this->lockTest($file));
$lock->lock();
$lock->unlock();
}
public function testIsLocked() {
// isLocked() should report lock status accurately.
$file = new TempFile();
$lock = PhutilFileLock::newForPath($file);
$this->assertFalse($lock->isLocked());
$lock->lock();
$this->assertTrue($lock->isLocked());
$lock->unlock();
$this->assertFalse($lock->isLocked());
}
private function lockTest($file) {
list($err) = $this->buildLockFuture('--test', $file)->resolve();
return ($err == 0);
}
private function holdLock($file) {
$future = $this->buildLockFuture('--hold', $file);
// We can't return until we're sure the subprocess has had time to acquire
// the lock. Since actually testing for the lock would be kind of silly
// and guarantee that we loop forever if the locking primitive broke,
// watch stdout for a *claim* that it has acquired the lock instead.
// Make sure we don't loop forever, no matter how bad things get.
$future->setTimeout(30);
$buf = '';
while (!$future->isReady()) {
list($stdout) = $future->read();
$buf .= $stdout;
if (strpos($buf, 'LOCK ACQUIRED') !== false) {
return $future;
}
}
throw new Exception(pht('Unable to hold lock in external process!'));
}
private function buildLockFuture($flags, $file) {
$root = dirname(phutil_get_library_root('phutil'));
$bin = $root.'/scripts/utils/lock.php';
// NOTE: Use `exec` so this passes on Ubuntu, where the default `dash` shell
// will eat any kills we send during the tests.
$future = new ExecFuture('exec php %s %C %s', $bin, $flags, $file);
$future->start();
return $future;
}
}
|
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package apiserver
import (
"fmt"
"sort"
"time"
"k8s.io/klog"
autoscaling "k8s.io/api/autoscaling/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime/schema"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/apimachinery/pkg/version"
"k8s.io/apiserver/pkg/endpoints/discovery"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/util/workqueue"
"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
informers "k8s.io/apiextensions-apiserver/pkg/client/informers/internalversion/apiextensions/internalversion"
listers "k8s.io/apiextensions-apiserver/pkg/client/listers/apiextensions/internalversion"
)
type DiscoveryController struct {
versionHandler *versionDiscoveryHandler
groupHandler *groupDiscoveryHandler
crdLister listers.CustomResourceDefinitionLister
crdsSynced cache.InformerSynced
// To allow injection for testing.
syncFn func(version schema.GroupVersion) error
queue workqueue.RateLimitingInterface
}
func NewDiscoveryController(crdInformer informers.CustomResourceDefinitionInformer, versionHandler *versionDiscoveryHandler, groupHandler *groupDiscoveryHandler) *DiscoveryController {
c := &DiscoveryController{
versionHandler: versionHandler,
groupHandler: groupHandler,
crdLister: crdInformer.Lister(),
crdsSynced: crdInformer.Informer().HasSynced,
queue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "DiscoveryController"),
}
crdInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: c.addCustomResourceDefinition,
UpdateFunc: c.updateCustomResourceDefinition,
DeleteFunc: c.deleteCustomResourceDefinition,
})
c.syncFn = c.sync
return c
}
func (c *DiscoveryController) sync(version schema.GroupVersion) error {
apiVersionsForDiscovery := []metav1.GroupVersionForDiscovery{}
apiResourcesForDiscovery := []metav1.APIResource{}
versionsForDiscoveryMap := map[metav1.GroupVersion]bool{}
crds, err := c.crdLister.List(labels.Everything())
if err != nil {
return err
}
foundVersion := false
foundGroup := false
for _, crd := range crds {
if !apiextensions.IsCRDConditionTrue(crd, apiextensions.Established) {
continue
}
if crd.Spec.Group != version.Group {
continue
}
foundThisVersion := false
for _, v := range crd.Spec.Versions {
if !v.Served {
continue
}
// If there is any Served version, that means the group should show up in discovery
foundGroup = true
gv := metav1.GroupVersion{Group: crd.Spec.Group, Version: v.Name}
if !versionsForDiscoveryMap[gv] {
versionsForDiscoveryMap[gv] = true
apiVersionsForDiscovery = append(apiVersionsForDiscovery, metav1.GroupVersionForDiscovery{
GroupVersion: crd.Spec.Group + "/" + v.Name,
Version: v.Name,
})
}
if v.Name == version.Version {
foundThisVersion = true
}
}
if !foundThisVersion {
continue
}
foundVersion = true
verbs := metav1.Verbs([]string{"delete", "deletecollection", "get", "list", "patch", "create", "update", "watch"})
// if we're terminating we don't allow some verbs
if apiextensions.IsCRDConditionTrue(crd, apiextensions.Terminating) {
verbs = metav1.Verbs([]string{"delete", "deletecollection", "get", "list", "watch"})
}
apiResourcesForDiscovery = append(apiResourcesForDiscovery, metav1.APIResource{
Name: crd.Status.AcceptedNames.Plural,
SingularName: crd.Status.AcceptedNames.Singular,
Namespaced: crd.Spec.Scope == apiextensions.NamespaceScoped,
Kind: crd.Status.AcceptedNames.Kind,
Verbs: verbs,
ShortNames: crd.Status.AcceptedNames.ShortNames,
Categories: crd.Status.AcceptedNames.Categories,
})
subresources, err := getSubresourcesForVersion(crd, version.Version)
if err != nil {
return err
}
if subresources != nil && subresources.Status != nil {
apiResourcesForDiscovery = append(apiResourcesForDiscovery, metav1.APIResource{
Name: crd.Status.AcceptedNames.Plural + "/status",
Namespaced: crd.Spec.Scope == apiextensions.NamespaceScoped,
Kind: crd.Status.AcceptedNames.Kind,
Verbs: metav1.Verbs([]string{"get", "patch", "update"}),
})
}
if subresources != nil && subresources.Scale != nil {
apiResourcesForDiscovery = append(apiResourcesForDiscovery, metav1.APIResource{
Group: autoscaling.GroupName,
Version: "v1",
Kind: "Scale",
Name: crd.Status.AcceptedNames.Plural + "/scale",
Namespaced: crd.Spec.Scope == apiextensions.NamespaceScoped,
Verbs: metav1.Verbs([]string{"get", "patch", "update"}),
})
}
}
if !foundGroup {
c.groupHandler.unsetDiscovery(version.Group)
c.versionHandler.unsetDiscovery(version)
return nil
}
sortGroupDiscoveryByKubeAwareVersion(apiVersionsForDiscovery)
apiGroup := metav1.APIGroup{
Name: version.Group,
Versions: apiVersionsForDiscovery,
// the preferred versions for a group is the first item in
// apiVersionsForDiscovery after it put in the right ordered
PreferredVersion: apiVersionsForDiscovery[0],
}
c.groupHandler.setDiscovery(version.Group, discovery.NewAPIGroupHandler(Codecs, apiGroup))
if !foundVersion {
c.versionHandler.unsetDiscovery(version)
return nil
}
c.versionHandler.setDiscovery(version, discovery.NewAPIVersionHandler(Codecs, version, discovery.APIResourceListerFunc(func() []metav1.APIResource {
return apiResourcesForDiscovery
})))
return nil
}
func sortGroupDiscoveryByKubeAwareVersion(gd []metav1.GroupVersionForDiscovery) {
sort.Slice(gd, func(i, j int) bool {
return version.CompareKubeAwareVersionStrings(gd[i].Version, gd[j].Version) > 0
})
}
func (c *DiscoveryController) Run(stopCh <-chan struct{}) {
defer utilruntime.HandleCrash()
defer c.queue.ShutDown()
defer klog.Infof("Shutting down DiscoveryController")
klog.Infof("Starting DiscoveryController")
if !cache.WaitForCacheSync(stopCh, c.crdsSynced) {
utilruntime.HandleError(fmt.Errorf("timed out waiting for caches to sync"))
return
}
// only start one worker thread since its a slow moving API
go wait.Until(c.runWorker, time.Second, stopCh)
<-stopCh
}
func (c *DiscoveryController) runWorker() {
for c.processNextWorkItem() {
}
}
// processNextWorkItem deals with one key off the queue. It returns false when it's time to quit.
func (c *DiscoveryController) processNextWorkItem() bool {
key, quit := c.queue.Get()
if quit {
return false
}
defer c.queue.Done(key)
err := c.syncFn(key.(schema.GroupVersion))
if err == nil {
c.queue.Forget(key)
return true
}
utilruntime.HandleError(fmt.Errorf("%v failed with: %v", key, err))
c.queue.AddRateLimited(key)
return true
}
func (c *DiscoveryController) enqueue(obj *apiextensions.CustomResourceDefinition) {
for _, v := range obj.Spec.Versions {
c.queue.Add(schema.GroupVersion{Group: obj.Spec.Group, Version: v.Name})
}
}
func (c *DiscoveryController) addCustomResourceDefinition(obj interface{}) {
castObj := obj.(*apiextensions.CustomResourceDefinition)
klog.V(4).Infof("Adding customresourcedefinition %s", castObj.Name)
c.enqueue(castObj)
}
func (c *DiscoveryController) updateCustomResourceDefinition(oldObj, newObj interface{}) {
castNewObj := newObj.(*apiextensions.CustomResourceDefinition)
castOldObj := oldObj.(*apiextensions.CustomResourceDefinition)
klog.V(4).Infof("Updating customresourcedefinition %s", castOldObj.Name)
// Enqueue both old and new object to make sure we remove and add appropriate Versions.
// The working queue will resolve any duplicates and only changes will stay in the queue.
c.enqueue(castNewObj)
c.enqueue(castOldObj)
}
func (c *DiscoveryController) deleteCustomResourceDefinition(obj interface{}) {
castObj, ok := obj.(*apiextensions.CustomResourceDefinition)
if !ok {
tombstone, ok := obj.(cache.DeletedFinalStateUnknown)
if !ok {
klog.Errorf("Couldn't get object from tombstone %#v", obj)
return
}
castObj, ok = tombstone.Obj.(*apiextensions.CustomResourceDefinition)
if !ok {
klog.Errorf("Tombstone contained object that is not expected %#v", obj)
return
}
}
klog.V(4).Infof("Deleting customresourcedefinition %q", castObj.Name)
c.enqueue(castObj)
}
|
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.refactoring;
import com.intellij.CommonBundle;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.PropertyKey;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.util.ResourceBundle;
/**
* @author ven
*/
public class RefactoringBundle {
public static String message(@NotNull @PropertyKey(resourceBundle = BUNDLE) String key, @NotNull Object... params) {
return CommonBundle.message(getBundle(), key, params);
}
private static Reference<ResourceBundle> ourBundle;
@NonNls private static final String BUNDLE = "messages.RefactoringBundle";
private RefactoringBundle() {
}
public static String getSearchInCommentsAndStringsText() {
return message("search.in.comments.and.strings");
}
public static String getSearchForTextOccurrencesText() {
return message("search.for.text.occurrences");
}
public static String getVisibilityPackageLocal() {
return message("visibility.package.local");
}
public static String getVisibilityPrivate() {
return message("visibility.private");
}
public static String getVisibilityProtected() {
return message("visibility.protected");
}
public static String getVisibilityPublic() {
return message("visibility.public");
}
public static String getVisibilityAsIs() {
return message("visibility.as.is");
}
public static String getEscalateVisibility() {
return message("visibility.escalate");
}
public static String getCannotRefactorMessage(@Nullable final String message) {
return message("cannot.perform.refactoring") + (message == null ? "" : "\n" + message);
}
public static String message(@PropertyKey(resourceBundle = BUNDLE) String key) {
return CommonBundle.message(getBundle(), key);
}
private static ResourceBundle getBundle() {
ResourceBundle bundle = com.intellij.reference.SoftReference.dereference(ourBundle);
if (bundle == null) {
bundle = ResourceBundle.getBundle(BUNDLE);
ourBundle = new SoftReference<>(bundle);
}
return bundle;
}
}
|
/*
* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.elasticbeanstalk.model;
import java.io.Serializable;
/**
* <p>
* Describes the properties of an application version.
* </p>
*/
public class ApplicationVersionDescription implements Serializable, Cloneable {
/**
* <p>
* The name of the application associated with this release.
* </p>
*/
private String applicationName;
/**
* <p>
* The description of this application version.
* </p>
*/
private String description;
/**
* <p>
* A label uniquely identifying the version for the associated application.
* </p>
*/
private String versionLabel;
/**
* <p>
* The location where the source bundle is located for this version.
* </p>
*/
private S3Location sourceBundle;
/**
* <p>
* The creation date of the application version.
* </p>
*/
private java.util.Date dateCreated;
/**
* <p>
* The last modified date of the application version.
* </p>
*/
private java.util.Date dateUpdated;
/**
* <p>
* The name of the application associated with this release.
* </p>
*
* @param applicationName
* The name of the application associated with this release.
*/
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
/**
* <p>
* The name of the application associated with this release.
* </p>
*
* @return The name of the application associated with this release.
*/
public String getApplicationName() {
return this.applicationName;
}
/**
* <p>
* The name of the application associated with this release.
* </p>
*
* @param applicationName
* The name of the application associated with this release.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ApplicationVersionDescription withApplicationName(
String applicationName) {
setApplicationName(applicationName);
return this;
}
/**
* <p>
* The description of this application version.
* </p>
*
* @param description
* The description of this application version.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* <p>
* The description of this application version.
* </p>
*
* @return The description of this application version.
*/
public String getDescription() {
return this.description;
}
/**
* <p>
* The description of this application version.
* </p>
*
* @param description
* The description of this application version.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ApplicationVersionDescription withDescription(String description) {
setDescription(description);
return this;
}
/**
* <p>
* A label uniquely identifying the version for the associated application.
* </p>
*
* @param versionLabel
* A label uniquely identifying the version for the associated
* application.
*/
public void setVersionLabel(String versionLabel) {
this.versionLabel = versionLabel;
}
/**
* <p>
* A label uniquely identifying the version for the associated application.
* </p>
*
* @return A label uniquely identifying the version for the associated
* application.
*/
public String getVersionLabel() {
return this.versionLabel;
}
/**
* <p>
* A label uniquely identifying the version for the associated application.
* </p>
*
* @param versionLabel
* A label uniquely identifying the version for the associated
* application.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ApplicationVersionDescription withVersionLabel(String versionLabel) {
setVersionLabel(versionLabel);
return this;
}
/**
* <p>
* The location where the source bundle is located for this version.
* </p>
*
* @param sourceBundle
* The location where the source bundle is located for this version.
*/
public void setSourceBundle(S3Location sourceBundle) {
this.sourceBundle = sourceBundle;
}
/**
* <p>
* The location where the source bundle is located for this version.
* </p>
*
* @return The location where the source bundle is located for this version.
*/
public S3Location getSourceBundle() {
return this.sourceBundle;
}
/**
* <p>
* The location where the source bundle is located for this version.
* </p>
*
* @param sourceBundle
* The location where the source bundle is located for this version.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ApplicationVersionDescription withSourceBundle(
S3Location sourceBundle) {
setSourceBundle(sourceBundle);
return this;
}
/**
* <p>
* The creation date of the application version.
* </p>
*
* @param dateCreated
* The creation date of the application version.
*/
public void setDateCreated(java.util.Date dateCreated) {
this.dateCreated = dateCreated;
}
/**
* <p>
* The creation date of the application version.
* </p>
*
* @return The creation date of the application version.
*/
public java.util.Date getDateCreated() {
return this.dateCreated;
}
/**
* <p>
* The creation date of the application version.
* </p>
*
* @param dateCreated
* The creation date of the application version.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ApplicationVersionDescription withDateCreated(
java.util.Date dateCreated) {
setDateCreated(dateCreated);
return this;
}
/**
* <p>
* The last modified date of the application version.
* </p>
*
* @param dateUpdated
* The last modified date of the application version.
*/
public void setDateUpdated(java.util.Date dateUpdated) {
this.dateUpdated = dateUpdated;
}
/**
* <p>
* The last modified date of the application version.
* </p>
*
* @return The last modified date of the application version.
*/
public java.util.Date getDateUpdated() {
return this.dateUpdated;
}
/**
* <p>
* The last modified date of the application version.
* </p>
*
* @param dateUpdated
* The last modified date of the application version.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ApplicationVersionDescription withDateUpdated(
java.util.Date dateUpdated) {
setDateUpdated(dateUpdated);
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getApplicationName() != null)
sb.append("ApplicationName: " + getApplicationName() + ",");
if (getDescription() != null)
sb.append("Description: " + getDescription() + ",");
if (getVersionLabel() != null)
sb.append("VersionLabel: " + getVersionLabel() + ",");
if (getSourceBundle() != null)
sb.append("SourceBundle: " + getSourceBundle() + ",");
if (getDateCreated() != null)
sb.append("DateCreated: " + getDateCreated() + ",");
if (getDateUpdated() != null)
sb.append("DateUpdated: " + getDateUpdated());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ApplicationVersionDescription == false)
return false;
ApplicationVersionDescription other = (ApplicationVersionDescription) obj;
if (other.getApplicationName() == null
^ this.getApplicationName() == null)
return false;
if (other.getApplicationName() != null
&& other.getApplicationName().equals(this.getApplicationName()) == false)
return false;
if (other.getDescription() == null ^ this.getDescription() == null)
return false;
if (other.getDescription() != null
&& other.getDescription().equals(this.getDescription()) == false)
return false;
if (other.getVersionLabel() == null ^ this.getVersionLabel() == null)
return false;
if (other.getVersionLabel() != null
&& other.getVersionLabel().equals(this.getVersionLabel()) == false)
return false;
if (other.getSourceBundle() == null ^ this.getSourceBundle() == null)
return false;
if (other.getSourceBundle() != null
&& other.getSourceBundle().equals(this.getSourceBundle()) == false)
return false;
if (other.getDateCreated() == null ^ this.getDateCreated() == null)
return false;
if (other.getDateCreated() != null
&& other.getDateCreated().equals(this.getDateCreated()) == false)
return false;
if (other.getDateUpdated() == null ^ this.getDateUpdated() == null)
return false;
if (other.getDateUpdated() != null
&& other.getDateUpdated().equals(this.getDateUpdated()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime
* hashCode
+ ((getApplicationName() == null) ? 0 : getApplicationName()
.hashCode());
hashCode = prime
* hashCode
+ ((getDescription() == null) ? 0 : getDescription().hashCode());
hashCode = prime
* hashCode
+ ((getVersionLabel() == null) ? 0 : getVersionLabel()
.hashCode());
hashCode = prime
* hashCode
+ ((getSourceBundle() == null) ? 0 : getSourceBundle()
.hashCode());
hashCode = prime
* hashCode
+ ((getDateCreated() == null) ? 0 : getDateCreated().hashCode());
hashCode = prime
* hashCode
+ ((getDateUpdated() == null) ? 0 : getDateUpdated().hashCode());
return hashCode;
}
@Override
public ApplicationVersionDescription clone() {
try {
return (ApplicationVersionDescription) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(
"Got a CloneNotSupportedException from Object.clone() "
+ "even though we're Cloneable!", e);
}
}
} |
PKG_NAME = node
PKG_VERS = 0.12.2
PKG_EXT = tar.gz
PKG_DIST_NAME = $(PKG_NAME)-v$(PKG_VERS).$(PKG_EXT)
PKG_DIST_SITE = http://nodejs.org/dist/v$(PKG_VERS)/
PKG_DIR = $(PKG_NAME)-v$(PKG_VERS)
REQUIRED_DSM = 5.0
UNSUPPORTED_ARCHS = $(ARMv5_ARCHES) $(PPC_ARCHES)
HOMEPAGE = http://nodejs.org/
COMMENT = Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications.
LICENSE = MIT
CONFIGURE_ARGS = --without-snapshot --dest-os=linux --prefix=$(STAGING_INSTALL_PREFIX)
ENV += LINK.target=$(TC_PATH)$(TC_PREFIX)g++
POST_INSTALL_TARGET = myPostInstall
include ../../mk/spksrc.cross-cc.mk
.PHONY: myPostInstall
myPostInstall:
sed -i -e 's|^#\!$(STAGING_INSTALL_PREFIX)|#\!$(INSTALL_PREFIX)|' $(STAGING_INSTALL_PREFIX)/lib/node_modules/npm/bin/npm-cli.js
|
// Generated by CoffeeScript 1.4.0
(function() {
"use strict";
var UserCommand, exports, _ref,
__slice = [].slice;
var exports = (_ref = window.chat) != null ? _ref : window.chat = {};
/*
* Represents a user command, like /kick or /say.
*/
UserCommand = (function() {
function UserCommand(name, description) {
this.description = description;
this.name = name;
this.describe(this.description);
this._hasValidArgs = false;
}
/*
* Describe the command using the following format:
* * description - a description of what the command does; used with /help
* <command>
* * category - what category the command falls under. This is used with /help
* * params - what parameters the command takes, 'opt_<name>' for optional,
* '<name>...' for variable
*##
* * validateArgs - returns a truthy variable if the given arguments are valid.
* * requires - what the command requires to run (e.g. a connections to an IRC
* server)
* * usage - manually set a usage message, one will be generated if not specified
* * run - the function to call when the command is run
*/
UserCommand.prototype.describe = function(description) {
var _ref1, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7;
if ((_ref1 = this._description) == null) {
this._description = description.description;
}
if ((_ref2 = this._params) == null) {
this._params = description.params;
}
if ((_ref3 = this._requires) == null) {
this._requires = description.requires;
}
if ((_ref4 = this._validateArgs) == null) {
this._validateArgs = description.validateArgs;
}
if ((_ref5 = this._usage) == null) {
this._usage = description.usage;
}
if ((_ref6 = this.run) == null) {
this.run = description.run;
}
return (_ref7 = this.category) != null ? _ref7 : this.category = description.category;
};
/*
* Try running the command. A command can fail to run if its requirements
* aren't met (e.g. needs a connection to the internet) or the specified
* arguments are invalid. In these cases a help message is displayed.
* @param {Context} context Which server/channel the command came from.
* @param {Object...} args Arguments for the command.
*/
UserCommand.prototype.tryToRun = function() {
var args, context;
context = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
this.setContext(context);
if (!this.canRun()) {
if (this.shouldDisplayFailedToRunMessage()) {
this.displayHelp();
}
return;
}
this.setArgs.apply(this, args);
if (this._hasValidArgs) {
return this.run();
} else {
return this.displayHelp();
}
};
UserCommand.prototype.setChat = function(chat) {
this.chat = chat;
};
UserCommand.prototype.setContext = function(context) {
this.win = this.chat.determineWindow(context);
if (this.win !== window.chat.NO_WINDOW) {
this.conn = this.win.conn;
return this.chan = this.win.target;
}
};
UserCommand.prototype.setArgs = function() {
var args;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return this._hasValidArgs = this._tryToAssignArgs(args) && (!this._validateArgs || !!this._validateArgs());
};
UserCommand.prototype._tryToAssignArgs = function(args) {
var i, param, params, _i, _len;
this.args = [];
this._removeTrailingWhiteSpace(args);
if (!this._params) {
return args.length === 0;
}
this._resetParams();
this._truncateVariableArgs(args);
params = this._truncateExtraOptionalParams(args.length);
if (args.length !== params.length) {
return false;
}
for (i = _i = 0, _len = params.length; _i < _len; i = ++_i) {
param = params[i];
this[this._getParamName(param)] = args[i];
}
this.args = args;
return true;
};
UserCommand.prototype._resetParams = function() {
var param, _i, _len, _ref1, _results;
_ref1 = this._params;
_results = [];
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
param = _ref1[_i];
_results.push(this[this._getParamName(param)] = void 0);
}
return _results;
};
UserCommand.prototype._removeTrailingWhiteSpace = function(args) {
var i, _i, _ref1, _results;
_results = [];
for (i = _i = _ref1 = args.length - 1; _ref1 <= 0 ? _i <= 0 : _i >= 0; i = _ref1 <= 0 ? ++_i : --_i) {
if (args[i] === '') {
_results.push(args.splice(i, 1));
} else {
break;
}
}
return _results;
};
/*
* Join all arguments that fit under the variable argument param.
* Note: only the last argument is allowd to be variable.
*/
UserCommand.prototype._truncateVariableArgs = function(args) {
var _ref1;
if (args.length < this._params.length) {
return args;
}
if (this._isVariable(this._params[this._params.length - 1])) {
args[this._params.length - 1] = (_ref1 = args.slice(this._params.length - 1)) != null ? _ref1.join(' ') : void 0;
return args.length = this._params.length;
}
};
UserCommand.prototype._truncateExtraOptionalParams = function(numArgs) {
var extraParams, i, param, params, _i, _ref1;
extraParams = this._params.length - numArgs;
if (extraParams <= 0) {
return this._params;
}
params = [];
for (i = _i = _ref1 = this._params.length - 1; _ref1 <= 0 ? _i <= 0 : _i >= 0; i = _ref1 <= 0 ? ++_i : --_i) {
param = this._params[i];
if (extraParams > 0 && this._isOptional(param)) {
extraParams--;
} else {
params.splice(0, 0, param);
}
}
return params;
};
/*
* When a command can't run, determine if a helpful message should be
* displayed to the user.
*/
UserCommand.prototype.shouldDisplayFailedToRunMessage = function() {
if (this.win === window.chat.NO_WINDOW) {
return false;
}
return this.name !== 'say';
};
/*
* Commands can only run if their requirements are met (e.g. connected to the
* internet, in a channel, etc) and a run method is defined.
*/
UserCommand.prototype.canRun = function(opt_context) {
var requirement, _i, _len, _ref1;
if (opt_context) {
this.setContext(opt_context);
}
if (!this.run) {
return false;
}
if (!this._requires) {
return true;
}
_ref1 = this._requires;
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
requirement = _ref1[_i];
if (!this._meetsRequirement(requirement)) {
return false;
}
}
return true;
};
UserCommand.prototype._meetsRequirement = function(requirement) {
var _ref1;
switch (requirement) {
case 'online':
return isOnline();
case 'connection':
return !!this.conn && isOnline();
case 'channel':
return !!this.chan;
default:
return ((_ref1 = this.conn) != null ? _ref1.irc.state : void 0) === requirement;
}
};
UserCommand.prototype.displayHelp = function(win) {
if (win == null) {
win = this.win;
}
return win.message('', html.escape(this.getHelp()), 'notice help');
};
UserCommand.prototype.getHelp = function() {
var descriptionText, usageText, _ref1;
descriptionText = this._description ? ", " + this._description : '';
if (this._usage) {
usageText = ' ' + this._usage;
}
if (usageText == null) {
usageText = ((_ref1 = this._params) != null ? _ref1.length : void 0) > 0 ? " " + (this._getUsage()) : '';
}
return this.name.toUpperCase() + usageText + descriptionText + '.';
};
UserCommand.prototype._getUsage = function() {
var param, paramDescription, paramName, _i, _len, _ref1;
paramDescription = [];
_ref1 = this._params;
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
param = _ref1[_i];
paramName = this._getParamName(param);
if (this._isOptional(param)) {
paramName = "[" + paramName + "]";
} else {
paramName = "<" + paramName + ">";
}
paramDescription.push(paramName);
}
return paramDescription.join(' ');
};
UserCommand.prototype._getParamName = function(param) {
if (this._isOptional(param)) {
param = param.slice(4);
}
if (this._isVariable(param)) {
param = param.slice(0, +(param.length - 4) + 1 || 9e9);
}
return param;
};
UserCommand.prototype._isOptional = function(param) {
return param.indexOf('opt_') === 0;
};
UserCommand.prototype._isVariable = function(param) {
return (param != null ? param.slice(param.length - 3) : void 0) === '...';
};
UserCommand.prototype.isOwnNick = function(nick) {
var _ref1;
if (nick == null) {
nick = this.nick;
}
return irc.util.nicksEqual((_ref1 = this.conn) != null ? _ref1.irc.nick : void 0, nick);
};
UserCommand.prototype.displayDirectMessage = function(nick, message) {
var _ref1;
if (nick == null) {
nick = this.nick;
}
if (message == null) {
message = this.message;
}
if (((_ref1 = this.conn) != null ? _ref1.windows[nick] : void 0) != null) {
return this._displayDirectMessageInPrivateChannel(nick, message);
} else {
return this._displayDirectMessageInline(nick, message);
}
};
/*
* Used with /msg. Displays the message in a private channel.
*/
UserCommand.prototype._displayDirectMessageInPrivateChannel = function(nick, message) {
var context;
context = {
server: this.conn.name,
channel: nick
};
return this.chat.displayMessage('privmsg', context, this.conn.irc.nick, message);
};
/*
* Used with /msg. Displays the private message in the current window.
* Direct messages always display inline until the user receives a response.
*/
UserCommand.prototype._displayDirectMessageInline = function(nick, message) {
return this.displayMessageWithStyle('privmsg', nick, message, 'direct');
};
UserCommand.prototype.displayMessage = function() {
var args, context, type, _ref1, _ref2;
type = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
context = {
server: (_ref1 = this.conn) != null ? _ref1.name : void 0,
channel: this.chan
};
return (_ref2 = this.chat).displayMessage.apply(_ref2, [type, context].concat(__slice.call(args)));
};
/*
* Displays a message with a custom style. This is useful for indicating that
* a message be rendered in a special way (e.g. no pretty formatting).
*/
UserCommand.prototype.displayMessageWithStyle = function() {
var args, e, style, type, _i, _ref1;
type = arguments[0], args = 3 <= arguments.length ? __slice.call(arguments, 1, _i = arguments.length - 1) : (_i = 1, []), style = arguments[_i++];
e = (function(func, args, ctor) {
ctor.prototype = func.prototype;
var child = new ctor, result = func.apply(child, args);
return Object(result) === result ? result : child;
})(Event, ['message', type].concat(__slice.call(args)), function(){});
e.setContext((_ref1 = this.conn) != null ? _ref1.name : void 0, this.chan);
e.addStyle(style);
return this.chat.emit(e.type, e);
};
UserCommand.prototype.handleCTCPRequest = function(nick, type) {
var delimiter, message;
this.displayDirectMessage(nick, "CTCP " + type);
delimiter = irc.CTCPHandler.DELIMITER;
message = delimiter + type + delimiter;
return this.conn.irc.doCommand('PRIVMSG', nick, message);
};
/*
* Used to set the arguments for MODE shortcut commands.
* @param {string} type E.g. /op, /voice, etc.
*/
UserCommand.prototype.setModeArgs = function(type) {
this.nicks = [this.nick];
this.target = this.chan;
return this.mode = type;
};
/*
* Determine if the given string is a valid mode expression.
* TODO: This can be improved. (e.g. ++ and +a++ shouldn't be valid)
* @param {string} mode E.g. +o, -o, +v, etc.
*/
UserCommand.prototype.isValidMode = function(mode) {
var _ref1;
return (_ref1 = mode != null ? mode[0] : void 0) === '+' || _ref1 === '-';
};
UserCommand.prototype.listInstalledScripts = function() {
var names;
names = this.chat.scriptHandler.getScriptNames();
if (names.length === 0) {
return "No scripts are currently installed";
} else {
return "Installed scripts: " + (getReadableList(names));
}
};
return UserCommand;
})();
exports.UserCommand = UserCommand;
}).call(this);
|
import { CSSModule } from '../index';
export interface CardDeckProps extends React.HTMLAttributes<HTMLElement> {
tag?: React.ReactType;
className?: string;
cssModule?: CSSModule;
}
declare const CardDeck: React.StatelessComponent<CardDeckProps>;
export default CardDeck;
|
/*++
Copyright (c) 2012 Microsoft Corporation
Module Name:
FiniteDomainSort.cs
Abstract:
Z3 Managed API: Finite Domain Sorts
Author:
Christoph Wintersteiger (cwinter) 2012-11-23
Notes:
--*/
using System;
using System.Diagnostics.Contracts;
namespace Microsoft.Z3
{
/// <summary>
/// Finite domain sorts.
/// </summary>
[ContractVerification(true)]
public class FiniteDomainSort : Sort
{
/// <summary>
/// The size of the finite domain sort.
/// </summary>
public ulong Size
{
get
{
ulong res = 0;
Native.Z3_get_finite_domain_sort_size(Context.nCtx, NativeObject, ref res);
return res;
}
}
#region Internal
internal FiniteDomainSort(Context ctx, IntPtr obj)
: base(ctx, obj)
{
Contract.Requires(ctx != null);
}
internal FiniteDomainSort(Context ctx, Symbol name, ulong size)
: base(ctx, Native.Z3_mk_finite_domain_sort(ctx.nCtx, name.NativeObject, size))
{
Contract.Requires(ctx != null);
Contract.Requires(name != null);
}
#endregion
}
}
|
(function (factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else if (typeof module === 'object' && typeof module.exports === 'object') {
factory(require('jquery'));
} else {
factory(jQuery);
}
}(function (jQuery) {
// Amharic
jQuery.timeago.settings.strings = {
prefixAgo: null,
prefixFromNow: null,
suffixAgo: "በፊት",
suffixFromNow: "በኋላ",
seconds: "ከአንድ ደቂቃ በታች",
minute: "ከአንድ ደቂቃ ገደማ",
minutes: "ከ%d ደቂቃ",
hour: "ከአንድ ሰዓት ገደማ",
hours: "ከ%d ሰዓት ገደማ",
day: "ከአንድ ቀን",
days: "ከ%d ቀን",
month: "ከአንድ ወር ገደማ",
months: "ከ%d ወር",
year: "ከአንድ ዓመት ገደማ",
years: "ከ%d ዓመት",
wordSeparator: " ",
numbers: []
};
}));
|
# [NATS](https://nats.io): A high-performance cloud native messaging system.
%%LOGO%%
`nats` is a high performance server for the NATS Messaging System.
# Example usage
```bash
# Run a NATS server
# Each server exposes multiple ports
# 4222 is for clients.
# 8222 is an HTTP management port for information reporting.
# 6222 is a routing port for clustering.
# use -p or -P as needed.
$ docker run -d --name nats-main nats
[INF] Starting gnatsd version 0.6.6
[INF] Starting http monitor on port 8222
[INF] Listening for route connections on 0.0.0.0:6222
[INF] Listening for client connections on 0.0.0.0:4222
[INF] gnatsd is ready
...
# To run a second server and cluster them together..
$ docker run -d --name=nats-2 --link nats-main nats --routes=nats-route://ruser:T0pS3cr3t@nats-main:6222
# If you want to verify the routes are connected, try
$ docker run -d --name=nats-2 --link nats-main nats --routes=nats-route://ruser:T0pS3cr3t@nats-main:6222 -DV
[INF] Starting gnatsd version 0.6.6
[INF] Starting http monitor on port 8222
[INF] Listening for route connections on :6222
[INF] Listening for client connections on 0.0.0.0:4222
[INF] gnatsd is ready
[DBG] Trying to connect to route on nats-main:6222
[DBG] 172.17.0.52:6222 - rid:1 - Route connection created
[DBG] 172.17.0.52:6222 - rid:1 - Route connect msg sent
[DBG] 172.17.0.52:6222 - rid:1 - Registering remote route "ee35d227433a738c729f9422a59667bb"
[DBG] 172.17.0.52:6222 - rid:1 - Route sent local subscriptions
```
The server will load the configuration file below. Any command line flags can override these values.
## Default Configuration File
```bash
# Client port of 4222 on all interfaces
port: 4222
# HTTP monitoring port
monitor_port: 8222
# This is for clustering multiple servers together.
cluster {
# Route connections to be received on any interface on port 6222
port: 6222
# Routes are protected, so need to use them with --routes flag
# e.g. --routes=nats-route://ruser:T0pS3cr3t@otherdockerhost:6222
authorization {
user: ruser
password: T0pS3cr3t
timeout: 0.75
}
# Routes are actively solicited and connected to from this server.
# This Docker image has none by default, but you can pass a
# flag to the gnatsd docker image to create one to an existing server.
routes = []
}
```
## Commandline Options
```bash
Server Options:
-a, --addr HOST Bind to HOST address (default: 0.0.0.0)
-p, --port PORT Use PORT for clients (default: 4222)
-P, --pid FILE File to store PID
-m, --http_port PORT Use HTTP PORT for monitoring
-c, --config FILE Configuration File
Logging Options:
-l, --log FILE File to redirect log output
-T, --logtime Timestamp log entries (default: true)
-s, --syslog Enable syslog as log method.
-r, --remote_syslog Syslog server addr (udp://localhost:514).
-D, --debug Enable debugging output
-V, --trace Trace the raw protocol
-DV Debug and Trace
Authorization Options:
--user user User required for connections
--pass password Password required for connections
Cluster Options:
--routes [rurl-1, rurl-2] Routes to solicit and connect
Common Options:
-h, --help Show this message
-v, --version Show version
```
|
import { changeProperties } from './property_events';
import { set } from './property_set';
/**
Set a list of properties on an object. These properties are set inside
a single `beginPropertyChanges` and `endPropertyChanges` batch, so
observers will be buffered.
```javascript
let anObject = Ember.Object.create();
anObject.setProperties({
firstName: 'Stanley',
lastName: 'Stuart',
age: 21
});
```
@method setProperties
@param obj
@param {Object} properties
@return properties
@public
*/
export default function setProperties(obj, properties) {
if (!properties || typeof properties !== 'object') { return properties; }
changeProperties(() => {
let props = Object.keys(properties);
let propertyName;
for (let i = 0; i < props.length; i++) {
propertyName = props[i];
set(obj, propertyName, properties[propertyName]);
}
});
return properties;
}
|
/*
* JsSIP v3.0.2
* the Javascript SIP library
* Copyright: 2012-2017 José Luis Millán <jmillan@aliax.net> (https://github.com/jmillan)
* Homepage: http://jssip.net
* License: MIT
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.JsSIP = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var pkg = require('../package.json');
var C = {
USER_AGENT: pkg.title + ' ' + pkg.version,
// SIP scheme
SIP: 'sip',
SIPS: 'sips',
// End and Failure causes
causes: {
// Generic error causes
CONNECTION_ERROR: 'Connection Error',
REQUEST_TIMEOUT: 'Request Timeout',
SIP_FAILURE_CODE: 'SIP Failure Code',
INTERNAL_ERROR: 'Internal Error',
// SIP error causes
BUSY: 'Busy',
REJECTED: 'Rejected',
REDIRECTED: 'Redirected',
UNAVAILABLE: 'Unavailable',
NOT_FOUND: 'Not Found',
ADDRESS_INCOMPLETE: 'Address Incomplete',
INCOMPATIBLE_SDP: 'Incompatible SDP',
MISSING_SDP: 'Missing SDP',
AUTHENTICATION_ERROR: 'Authentication Error',
// Session error causes
BYE: 'Terminated',
WEBRTC_ERROR: 'WebRTC Error',
CANCELED: 'Canceled',
NO_ANSWER: 'No Answer',
EXPIRES: 'Expires',
NO_ACK: 'No ACK',
DIALOG_ERROR: 'Dialog Error',
USER_DENIED_MEDIA_ACCESS: 'User Denied Media Access',
BAD_MEDIA_DESCRIPTION: 'Bad Media Description',
RTP_TIMEOUT: 'RTP Timeout'
},
SIP_ERROR_CAUSES: {
REDIRECTED: [300,301,302,305,380],
BUSY: [486,600],
REJECTED: [403,603],
NOT_FOUND: [404,604],
UNAVAILABLE: [480,410,408,430],
ADDRESS_INCOMPLETE: [484, 424],
INCOMPATIBLE_SDP: [488,606],
AUTHENTICATION_ERROR:[401,407]
},
// SIP Methods
ACK: 'ACK',
BYE: 'BYE',
CANCEL: 'CANCEL',
INFO: 'INFO',
INVITE: 'INVITE',
MESSAGE: 'MESSAGE',
NOTIFY: 'NOTIFY',
OPTIONS: 'OPTIONS',
REGISTER: 'REGISTER',
REFER: 'REFER',
UPDATE: 'UPDATE',
SUBSCRIBE: 'SUBSCRIBE',
/* SIP Response Reasons
* DOC: http://www.iana.org/assignments/sip-parameters
* Copied from https://github.com/versatica/OverSIP/blob/master/lib/oversip/sip/constants.rb#L7
*/
REASON_PHRASE: {
100: 'Trying',
180: 'Ringing',
181: 'Call Is Being Forwarded',
182: 'Queued',
183: 'Session Progress',
199: 'Early Dialog Terminated', // draft-ietf-sipcore-199
200: 'OK',
202: 'Accepted', // RFC 3265
204: 'No Notification', //RFC 5839
300: 'Multiple Choices',
301: 'Moved Permanently',
302: 'Moved Temporarily',
305: 'Use Proxy',
380: 'Alternative Service',
400: 'Bad Request',
401: 'Unauthorized',
402: 'Payment Required',
403: 'Forbidden',
404: 'Not Found',
405: 'Method Not Allowed',
406: 'Not Acceptable',
407: 'Proxy Authentication Required',
408: 'Request Timeout',
410: 'Gone',
412: 'Conditional Request Failed', // RFC 3903
413: 'Request Entity Too Large',
414: 'Request-URI Too Long',
415: 'Unsupported Media Type',
416: 'Unsupported URI Scheme',
417: 'Unknown Resource-Priority', // RFC 4412
420: 'Bad Extension',
421: 'Extension Required',
422: 'Session Interval Too Small', // RFC 4028
423: 'Interval Too Brief',
424: 'Bad Location Information', // RFC 6442
428: 'Use Identity Header', // RFC 4474
429: 'Provide Referrer Identity', // RFC 3892
430: 'Flow Failed', // RFC 5626
433: 'Anonymity Disallowed', // RFC 5079
436: 'Bad Identity-Info', // RFC 4474
437: 'Unsupported Certificate', // RFC 4744
438: 'Invalid Identity Header', // RFC 4744
439: 'First Hop Lacks Outbound Support', // RFC 5626
440: 'Max-Breadth Exceeded', // RFC 5393
469: 'Bad Info Package', // draft-ietf-sipcore-info-events
470: 'Consent Needed', // RFC 5360
478: 'Unresolvable Destination', // Custom code copied from Kamailio.
480: 'Temporarily Unavailable',
481: 'Call/Transaction Does Not Exist',
482: 'Loop Detected',
483: 'Too Many Hops',
484: 'Address Incomplete',
485: 'Ambiguous',
486: 'Busy Here',
487: 'Request Terminated',
488: 'Not Acceptable Here',
489: 'Bad Event', // RFC 3265
491: 'Request Pending',
493: 'Undecipherable',
494: 'Security Agreement Required', // RFC 3329
500: 'JsSIP Internal Error',
501: 'Not Implemented',
502: 'Bad Gateway',
503: 'Service Unavailable',
504: 'Server Time-out',
505: 'Version Not Supported',
513: 'Message Too Large',
580: 'Precondition Failure', // RFC 3312
600: 'Busy Everywhere',
603: 'Decline',
604: 'Does Not Exist Anywhere',
606: 'Not Acceptable'
},
ALLOWED_METHODS: 'INVITE,ACK,CANCEL,BYE,UPDATE,MESSAGE,OPTIONS,REFER,INFO',
ACCEPTED_BODY_TYPES: 'application/sdp, application/dtmf-relay',
MAX_FORWARDS: 69,
SESSION_EXPIRES: 90,
MIN_SESSION_EXPIRES: 60
};
module.exports = C;
},{"../package.json":50}],2:[function(require,module,exports){
module.exports = Dialog;
var C = {
// Dialog states
STATUS_EARLY: 1,
STATUS_CONFIRMED: 2
};
/**
* Expose C object.
*/
Dialog.C = C;
/**
* Dependencies.
*/
var debug = require('debug')('JsSIP:Dialog');
var SIPMessage = require('./SIPMessage');
var JsSIP_C = require('./Constants');
var Transactions = require('./Transactions');
var Dialog_RequestSender = require('./Dialog/RequestSender');
// RFC 3261 12.1
function Dialog(owner, message, type, state) {
var contact;
this.uac_pending_reply = false;
this.uas_pending_reply = false;
if(!message.hasHeader('contact')) {
return {
error: 'unable to create a Dialog without Contact header field'
};
}
if(message instanceof SIPMessage.IncomingResponse) {
state = (message.status_code < 200) ? C.STATUS_EARLY : C.STATUS_CONFIRMED;
} else {
// Create confirmed dialog if state is not defined
state = state || C.STATUS_CONFIRMED;
}
contact = message.parseHeader('contact');
// RFC 3261 12.1.1
if(type === 'UAS') {
this.id = {
call_id: message.call_id,
local_tag: message.to_tag,
remote_tag: message.from_tag,
toString: function() {
return this.call_id + this.local_tag + this.remote_tag;
}
};
this.state = state;
this.remote_seqnum = message.cseq;
this.local_uri = message.parseHeader('to').uri;
this.remote_uri = message.parseHeader('from').uri;
this.remote_target = contact.uri;
this.route_set = message.getHeaders('record-route');
}
// RFC 3261 12.1.2
else if(type === 'UAC') {
this.id = {
call_id: message.call_id,
local_tag: message.from_tag,
remote_tag: message.to_tag,
toString: function() {
return this.call_id + this.local_tag + this.remote_tag;
}
};
this.state = state;
this.local_seqnum = message.cseq;
this.local_uri = message.parseHeader('from').uri;
this.remote_uri = message.parseHeader('to').uri;
this.remote_target = contact.uri;
this.route_set = message.getHeaders('record-route').reverse();
}
this.owner = owner;
owner.ua.dialogs[this.id.toString()] = this;
debug('new ' + type + ' dialog created with status ' + (this.state === C.STATUS_EARLY ? 'EARLY': 'CONFIRMED'));
}
Dialog.prototype = {
update: function(message, type) {
this.state = C.STATUS_CONFIRMED;
debug('dialog '+ this.id.toString() +' changed to CONFIRMED state');
if(type === 'UAC') {
// RFC 3261 13.2.2.4
this.route_set = message.getHeaders('record-route').reverse();
}
},
terminate: function() {
debug('dialog ' + this.id.toString() + ' deleted');
delete this.owner.ua.dialogs[this.id.toString()];
},
// RFC 3261 12.2.1.1
createRequest: function(method, extraHeaders, body) {
var cseq, request;
extraHeaders = extraHeaders && extraHeaders.slice() || [];
if(!this.local_seqnum) { this.local_seqnum = Math.floor(Math.random() * 10000); }
cseq = (method === JsSIP_C.CANCEL || method === JsSIP_C.ACK) ? this.local_seqnum : this.local_seqnum += 1;
request = new SIPMessage.OutgoingRequest(
method,
this.remote_target,
this.owner.ua, {
'cseq': cseq,
'call_id': this.id.call_id,
'from_uri': this.local_uri,
'from_tag': this.id.local_tag,
'to_uri': this.remote_uri,
'to_tag': this.id.remote_tag,
'route_set': this.route_set
}, extraHeaders, body);
request.dialog = this;
return request;
},
// RFC 3261 12.2.2
checkInDialogRequest: function(request) {
var self = this;
if(!this.remote_seqnum) {
this.remote_seqnum = request.cseq;
} else if(request.cseq < this.remote_seqnum) {
//Do not try to reply to an ACK request.
if (request.method !== JsSIP_C.ACK) {
request.reply(500);
}
return false;
} else if(request.cseq > this.remote_seqnum) {
this.remote_seqnum = request.cseq;
}
// RFC3261 14.2 Modifying an Existing Session -UAS BEHAVIOR-
if (request.method === JsSIP_C.INVITE || (request.method === JsSIP_C.UPDATE && request.body)) {
if (this.uac_pending_reply === true) {
request.reply(491);
} else if (this.uas_pending_reply === true) {
var retryAfter = (Math.random() * 10 | 0) + 1;
request.reply(500, null, ['Retry-After:'+ retryAfter]);
return false;
} else {
this.uas_pending_reply = true;
request.server_transaction.on('stateChanged', function stateChanged(){
if (this.state === Transactions.C.STATUS_ACCEPTED ||
this.state === Transactions.C.STATUS_COMPLETED ||
this.state === Transactions.C.STATUS_TERMINATED) {
request.server_transaction.removeListener('stateChanged', stateChanged);
self.uas_pending_reply = false;
}
});
}
// RFC3261 12.2.2 Replace the dialog`s remote target URI if the request is accepted
if(request.hasHeader('contact')) {
request.server_transaction.on('stateChanged', function(){
if (this.state === Transactions.C.STATUS_ACCEPTED) {
self.remote_target = request.parseHeader('contact').uri;
}
});
}
}
else if (request.method === JsSIP_C.NOTIFY) {
// RFC6665 3.2 Replace the dialog`s remote target URI if the request is accepted
if(request.hasHeader('contact')) {
request.server_transaction.on('stateChanged', function(){
if (this.state === Transactions.C.STATUS_COMPLETED) {
self.remote_target = request.parseHeader('contact').uri;
}
});
}
}
return true;
},
sendRequest: function(applicant, method, options) {
options = options || {};
var
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [],
body = options.body || null,
request = this.createRequest(method, extraHeaders, body),
request_sender = new Dialog_RequestSender(this, applicant, request);
request_sender.send();
// Return the instance of OutgoingRequest
return request;
},
receiveRequest: function(request) {
//Check in-dialog request
if(!this.checkInDialogRequest(request)) {
return;
}
this.owner.receiveRequest(request);
}
};
},{"./Constants":1,"./Dialog/RequestSender":3,"./SIPMessage":18,"./Transactions":21,"debug":34}],3:[function(require,module,exports){
module.exports = DialogRequestSender;
/**
* Dependencies.
*/
var JsSIP_C = require('../Constants');
var Transactions = require('../Transactions');
var RTCSession = require('../RTCSession');
var RequestSender = require('../RequestSender');
function DialogRequestSender(dialog, applicant, request) {
this.dialog = dialog;
this.applicant = applicant;
this.request = request;
// RFC3261 14.1 Modifying an Existing Session. UAC Behavior.
this.reattempt = false;
this.reattemptTimer = null;
}
DialogRequestSender.prototype = {
send: function() {
var
self = this,
request_sender = new RequestSender(this, this.dialog.owner.ua);
request_sender.send();
// RFC3261 14.2 Modifying an Existing Session -UAC BEHAVIOR-
if ((this.request.method === JsSIP_C.INVITE || (this.request.method === JsSIP_C.UPDATE && this.request.body)) &&
request_sender.clientTransaction.state !== Transactions.C.STATUS_TERMINATED) {
this.dialog.uac_pending_reply = true;
request_sender.clientTransaction.on('stateChanged', function stateChanged(){
if (this.state === Transactions.C.STATUS_ACCEPTED ||
this.state === Transactions.C.STATUS_COMPLETED ||
this.state === Transactions.C.STATUS_TERMINATED) {
request_sender.clientTransaction.removeListener('stateChanged', stateChanged);
self.dialog.uac_pending_reply = false;
}
});
}
},
onRequestTimeout: function() {
this.applicant.onRequestTimeout();
},
onTransportError: function() {
this.applicant.onTransportError();
},
receiveResponse: function(response) {
var self = this;
// RFC3261 12.2.1.2 408 or 481 is received for a request within a dialog.
if (response.status_code === 408 || response.status_code === 481) {
this.applicant.onDialogError(response);
} else if (response.method === JsSIP_C.INVITE && response.status_code === 491) {
if (this.reattempt) {
this.applicant.receiveResponse(response);
} else {
this.request.cseq.value = this.dialog.local_seqnum += 1;
this.reattemptTimer = setTimeout(function() {
if (self.applicant.owner.status !== RTCSession.C.STATUS_TERMINATED) {
self.reattempt = true;
self.request_sender.send();
}
}, 1000);
}
} else {
this.applicant.receiveResponse(response);
}
}
};
},{"../Constants":1,"../RTCSession":11,"../RequestSender":17,"../Transactions":21}],4:[function(require,module,exports){
module.exports = DigestAuthentication;
/**
* Dependencies.
*/
var debug = require('debug')('JsSIP:DigestAuthentication');
var debugerror = require('debug')('JsSIP:ERROR:DigestAuthentication');
debugerror.log = console.warn.bind(console);
var Utils = require('./Utils');
function DigestAuthentication(credentials) {
this.credentials = credentials;
this.cnonce = null;
this.nc = 0;
this.ncHex = '00000000';
this.algorithm = null;
this.realm = null;
this.nonce = null;
this.opaque = null;
this.stale = null;
this.qop = null;
this.method = null;
this.uri = null;
this.ha1 = null;
this.response = null;
}
DigestAuthentication.prototype.get = function(parameter) {
switch (parameter) {
case 'realm':
return this.realm;
case 'ha1':
return this.ha1;
default:
debugerror('get() | cannot get "%s" parameter', parameter);
return undefined;
}
};
/**
* Performs Digest authentication given a SIP request and the challenge
* received in a response to that request.
* Returns true if auth was successfully generated, false otherwise.
*/
DigestAuthentication.prototype.authenticate = function(request, challenge) {
var ha2, hex;
this.algorithm = challenge.algorithm;
this.realm = challenge.realm;
this.nonce = challenge.nonce;
this.opaque = challenge.opaque;
this.stale = challenge.stale;
if (this.algorithm) {
if (this.algorithm !== 'MD5') {
debugerror('authenticate() | challenge with Digest algorithm different than "MD5", authentication aborted');
return false;
}
} else {
this.algorithm = 'MD5';
}
if (!this.nonce) {
debugerror('authenticate() | challenge without Digest nonce, authentication aborted');
return false;
}
if (!this.realm) {
debugerror('authenticate() | challenge without Digest realm, authentication aborted');
return false;
}
// If no plain SIP password is provided.
if (!this.credentials.password) {
// If ha1 is not provided we cannot authenticate.
if (!this.credentials.ha1) {
debugerror('authenticate() | no plain SIP password nor ha1 provided, authentication aborted');
return false;
}
// If the realm does not match the stored realm we cannot authenticate.
if (this.credentials.realm !== this.realm) {
debugerror('authenticate() | no plain SIP password, and stored `realm` does not match the given `realm`, cannot authenticate [stored:"%s", given:"%s"]', this.credentials.realm, this.realm);
return false;
}
}
// 'qop' can contain a list of values (Array). Let's choose just one.
if (challenge.qop) {
if (challenge.qop.indexOf('auth') > -1) {
this.qop = 'auth';
} else if (challenge.qop.indexOf('auth-int') > -1) {
this.qop = 'auth-int';
} else {
// Otherwise 'qop' is present but does not contain 'auth' or 'auth-int', so abort here.
debugerror('authenticate() | challenge without Digest qop different than "auth" or "auth-int", authentication aborted');
return false;
}
} else {
this.qop = null;
}
// Fill other attributes.
this.method = request.method;
this.uri = request.ruri;
this.cnonce = Utils.createRandomToken(12);
this.nc += 1;
hex = Number(this.nc).toString(16);
this.ncHex = '00000000'.substr(0, 8-hex.length) + hex;
// nc-value = 8LHEX. Max value = 'FFFFFFFF'.
if (this.nc === 4294967296) {
this.nc = 1;
this.ncHex = '00000001';
}
// Calculate the Digest "response" value.
// If we have plain SIP password then regenerate ha1.
if (this.credentials.password) {
// HA1 = MD5(A1) = MD5(username:realm:password)
this.ha1 = Utils.calculateMD5(this.credentials.username + ':' + this.realm + ':' + this.credentials.password);
//
// Otherwise reuse the stored ha1.
} else {
this.ha1 = this.credentials.ha1;
}
if (this.qop === 'auth') {
// HA2 = MD5(A2) = MD5(method:digestURI)
ha2 = Utils.calculateMD5(this.method + ':' + this.uri);
// response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2)
this.response = Utils.calculateMD5(this.ha1 + ':' + this.nonce + ':' + this.ncHex + ':' + this.cnonce + ':auth:' + ha2);
} else if (this.qop === 'auth-int') {
// HA2 = MD5(A2) = MD5(method:digestURI:MD5(entityBody))
ha2 = Utils.calculateMD5(this.method + ':' + this.uri + ':' + Utils.calculateMD5(this.body ? this.body : ''));
// response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2)
this.response = Utils.calculateMD5(this.ha1 + ':' + this.nonce + ':' + this.ncHex + ':' + this.cnonce + ':auth-int:' + ha2);
} else if (this.qop === null) {
// HA2 = MD5(A2) = MD5(method:digestURI)
ha2 = Utils.calculateMD5(this.method + ':' + this.uri);
// response = MD5(HA1:nonce:HA2)
this.response = Utils.calculateMD5(this.ha1 + ':' + this.nonce + ':' + ha2);
}
debug('authenticate() | response generated');
return true;
};
/**
* Return the Proxy-Authorization or WWW-Authorization header value.
*/
DigestAuthentication.prototype.toString = function() {
var auth_params = [];
if (!this.response) {
throw new Error('response field does not exist, cannot generate Authorization header');
}
auth_params.push('algorithm=' + this.algorithm);
auth_params.push('username="' + this.credentials.username + '"');
auth_params.push('realm="' + this.realm + '"');
auth_params.push('nonce="' + this.nonce + '"');
auth_params.push('uri="' + this.uri + '"');
auth_params.push('response="' + this.response + '"');
if (this.opaque) {
auth_params.push('opaque="' + this.opaque + '"');
}
if (this.qop) {
auth_params.push('qop=' + this.qop);
auth_params.push('cnonce="' + this.cnonce + '"');
auth_params.push('nc=' + this.ncHex);
}
return 'Digest ' + auth_params.join(', ');
};
},{"./Utils":25,"debug":34}],5:[function(require,module,exports){
/**
* @namespace Exceptions
* @memberOf JsSIP
*/
var Exceptions = {
/**
* Exception thrown when a valid parameter is given to the JsSIP.UA constructor.
* @class ConfigurationError
* @memberOf JsSIP.Exceptions
*/
ConfigurationError: (function(){
var exception = function(parameter, value) {
this.code = 1;
this.name = 'CONFIGURATION_ERROR';
this.parameter = parameter;
this.value = value;
this.message = (!this.value)? 'Missing parameter: '+ this.parameter : 'Invalid value '+ JSON.stringify(this.value) +' for parameter "'+ this.parameter +'"';
};
exception.prototype = new Error();
return exception;
}()),
InvalidStateError: (function(){
var exception = function(status) {
this.code = 2;
this.name = 'INVALID_STATE_ERROR';
this.status = status;
this.message = 'Invalid status: '+ status;
};
exception.prototype = new Error();
return exception;
}()),
NotSupportedError: (function(){
var exception = function(message) {
this.code = 3;
this.name = 'NOT_SUPPORTED_ERROR';
this.message = message;
};
exception.prototype = new Error();
return exception;
}()),
NotReadyError: (function(){
var exception = function(message) {
this.code = 4;
this.name = 'NOT_READY_ERROR';
this.message = message;
};
exception.prototype = new Error();
return exception;
}())
};
module.exports = Exceptions;
},{}],6:[function(require,module,exports){
module.exports = (function(){
/*
* Generated by PEG.js 0.7.0.
*
* http://pegjs.majda.cz/
*/
function quote(s) {
/*
* ECMA-262, 5th ed., 7.8.4: All characters may appear literally in a
* string literal except for the closing quote character, backslash,
* carriage return, line separator, paragraph separator, and line feed.
* Any character may appear in the form of an escape sequence.
*
* For portability, we also escape escape all control and non-ASCII
* characters. Note that "\0" and "\v" escape sequences are not used
* because JSHint does not like the first and IE the second.
*/
return '"' + s
.replace(/\\/g, '\\\\') // backslash
.replace(/"/g, '\\"') // closing quote character
.replace(/\x08/g, '\\b') // backspace
.replace(/\t/g, '\\t') // horizontal tab
.replace(/\n/g, '\\n') // line feed
.replace(/\f/g, '\\f') // form feed
.replace(/\r/g, '\\r') // carriage return
.replace(/[\x00-\x07\x0B\x0E-\x1F\x80-\uFFFF]/g, escape)
+ '"';
}
var result = {
/*
* Parses the input with a generated parser. If the parsing is successfull,
* returns a value explicitly or implicitly specified by the grammar from
* which the parser was generated (see |PEG.buildParser|). If the parsing is
* unsuccessful, throws |PEG.parser.SyntaxError| describing the error.
*/
parse: function(input, startRule) {
var parseFunctions = {
"CRLF": parse_CRLF,
"DIGIT": parse_DIGIT,
"ALPHA": parse_ALPHA,
"HEXDIG": parse_HEXDIG,
"WSP": parse_WSP,
"OCTET": parse_OCTET,
"DQUOTE": parse_DQUOTE,
"SP": parse_SP,
"HTAB": parse_HTAB,
"alphanum": parse_alphanum,
"reserved": parse_reserved,
"unreserved": parse_unreserved,
"mark": parse_mark,
"escaped": parse_escaped,
"LWS": parse_LWS,
"SWS": parse_SWS,
"HCOLON": parse_HCOLON,
"TEXT_UTF8_TRIM": parse_TEXT_UTF8_TRIM,
"TEXT_UTF8char": parse_TEXT_UTF8char,
"UTF8_NONASCII": parse_UTF8_NONASCII,
"UTF8_CONT": parse_UTF8_CONT,
"LHEX": parse_LHEX,
"token": parse_token,
"token_nodot": parse_token_nodot,
"separators": parse_separators,
"word": parse_word,
"STAR": parse_STAR,
"SLASH": parse_SLASH,
"EQUAL": parse_EQUAL,
"LPAREN": parse_LPAREN,
"RPAREN": parse_RPAREN,
"RAQUOT": parse_RAQUOT,
"LAQUOT": parse_LAQUOT,
"COMMA": parse_COMMA,
"SEMI": parse_SEMI,
"COLON": parse_COLON,
"LDQUOT": parse_LDQUOT,
"RDQUOT": parse_RDQUOT,
"comment": parse_comment,
"ctext": parse_ctext,
"quoted_string": parse_quoted_string,
"quoted_string_clean": parse_quoted_string_clean,
"qdtext": parse_qdtext,
"quoted_pair": parse_quoted_pair,
"SIP_URI_noparams": parse_SIP_URI_noparams,
"SIP_URI": parse_SIP_URI,
"uri_scheme": parse_uri_scheme,
"uri_scheme_sips": parse_uri_scheme_sips,
"uri_scheme_sip": parse_uri_scheme_sip,
"userinfo": parse_userinfo,
"user": parse_user,
"user_unreserved": parse_user_unreserved,
"password": parse_password,
"hostport": parse_hostport,
"host": parse_host,
"hostname": parse_hostname,
"domainlabel": parse_domainlabel,
"toplabel": parse_toplabel,
"IPv6reference": parse_IPv6reference,
"IPv6address": parse_IPv6address,
"h16": parse_h16,
"ls32": parse_ls32,
"IPv4address": parse_IPv4address,
"dec_octet": parse_dec_octet,
"port": parse_port,
"uri_parameters": parse_uri_parameters,
"uri_parameter": parse_uri_parameter,
"transport_param": parse_transport_param,
"user_param": parse_user_param,
"method_param": parse_method_param,
"ttl_param": parse_ttl_param,
"maddr_param": parse_maddr_param,
"lr_param": parse_lr_param,
"other_param": parse_other_param,
"pname": parse_pname,
"pvalue": parse_pvalue,
"paramchar": parse_paramchar,
"param_unreserved": parse_param_unreserved,
"headers": parse_headers,
"header": parse_header,
"hname": parse_hname,
"hvalue": parse_hvalue,
"hnv_unreserved": parse_hnv_unreserved,
"Request_Response": parse_Request_Response,
"Request_Line": parse_Request_Line,
"Request_URI": parse_Request_URI,
"absoluteURI": parse_absoluteURI,
"hier_part": parse_hier_part,
"net_path": parse_net_path,
"abs_path": parse_abs_path,
"opaque_part": parse_opaque_part,
"uric": parse_uric,
"uric_no_slash": parse_uric_no_slash,
"path_segments": parse_path_segments,
"segment": parse_segment,
"param": parse_param,
"pchar": parse_pchar,
"scheme": parse_scheme,
"authority": parse_authority,
"srvr": parse_srvr,
"reg_name": parse_reg_name,
"query": parse_query,
"SIP_Version": parse_SIP_Version,
"INVITEm": parse_INVITEm,
"ACKm": parse_ACKm,
"OPTIONSm": parse_OPTIONSm,
"BYEm": parse_BYEm,
"CANCELm": parse_CANCELm,
"REGISTERm": parse_REGISTERm,
"SUBSCRIBEm": parse_SUBSCRIBEm,
"NOTIFYm": parse_NOTIFYm,
"REFERm": parse_REFERm,
"Method": parse_Method,
"Status_Line": parse_Status_Line,
"Status_Code": parse_Status_Code,
"extension_code": parse_extension_code,
"Reason_Phrase": parse_Reason_Phrase,
"Allow_Events": parse_Allow_Events,
"Call_ID": parse_Call_ID,
"Contact": parse_Contact,
"contact_param": parse_contact_param,
"name_addr": parse_name_addr,
"display_name": parse_display_name,
"contact_params": parse_contact_params,
"c_p_q": parse_c_p_q,
"c_p_expires": parse_c_p_expires,
"delta_seconds": parse_delta_seconds,
"qvalue": parse_qvalue,
"generic_param": parse_generic_param,
"gen_value": parse_gen_value,
"Content_Disposition": parse_Content_Disposition,
"disp_type": parse_disp_type,
"disp_param": parse_disp_param,
"handling_param": parse_handling_param,
"Content_Encoding": parse_Content_Encoding,
"Content_Length": parse_Content_Length,
"Content_Type": parse_Content_Type,
"media_type": parse_media_type,
"m_type": parse_m_type,
"discrete_type": parse_discrete_type,
"composite_type": parse_composite_type,
"extension_token": parse_extension_token,
"x_token": parse_x_token,
"m_subtype": parse_m_subtype,
"m_parameter": parse_m_parameter,
"m_value": parse_m_value,
"CSeq": parse_CSeq,
"CSeq_value": parse_CSeq_value,
"Expires": parse_Expires,
"Event": parse_Event,
"event_type": parse_event_type,
"From": parse_From,
"from_param": parse_from_param,
"tag_param": parse_tag_param,
"Max_Forwards": parse_Max_Forwards,
"Min_Expires": parse_Min_Expires,
"Name_Addr_Header": parse_Name_Addr_Header,
"Proxy_Authenticate": parse_Proxy_Authenticate,
"challenge": parse_challenge,
"other_challenge": parse_other_challenge,
"auth_param": parse_auth_param,
"digest_cln": parse_digest_cln,
"realm": parse_realm,
"realm_value": parse_realm_value,
"domain": parse_domain,
"URI": parse_URI,
"nonce": parse_nonce,
"nonce_value": parse_nonce_value,
"opaque": parse_opaque,
"stale": parse_stale,
"algorithm": parse_algorithm,
"qop_options": parse_qop_options,
"qop_value": parse_qop_value,
"Proxy_Require": parse_Proxy_Require,
"Record_Route": parse_Record_Route,
"rec_route": parse_rec_route,
"Reason": parse_Reason,
"reason_param": parse_reason_param,
"reason_cause": parse_reason_cause,
"Require": parse_Require,
"Route": parse_Route,
"route_param": parse_route_param,
"Subscription_State": parse_Subscription_State,
"substate_value": parse_substate_value,
"subexp_params": parse_subexp_params,
"event_reason_value": parse_event_reason_value,
"Subject": parse_Subject,
"Supported": parse_Supported,
"To": parse_To,
"to_param": parse_to_param,
"Via": parse_Via,
"via_param": parse_via_param,
"via_params": parse_via_params,
"via_ttl": parse_via_ttl,
"via_maddr": parse_via_maddr,
"via_received": parse_via_received,
"via_branch": parse_via_branch,
"response_port": parse_response_port,
"sent_protocol": parse_sent_protocol,
"protocol_name": parse_protocol_name,
"transport": parse_transport,
"sent_by": parse_sent_by,
"via_host": parse_via_host,
"via_port": parse_via_port,
"ttl": parse_ttl,
"WWW_Authenticate": parse_WWW_Authenticate,
"Session_Expires": parse_Session_Expires,
"s_e_expires": parse_s_e_expires,
"s_e_params": parse_s_e_params,
"s_e_refresher": parse_s_e_refresher,
"extension_header": parse_extension_header,
"header_value": parse_header_value,
"message_body": parse_message_body,
"uuid_URI": parse_uuid_URI,
"uuid": parse_uuid,
"hex4": parse_hex4,
"hex8": parse_hex8,
"hex12": parse_hex12,
"Refer_To": parse_Refer_To,
"Replaces": parse_Replaces,
"call_id": parse_call_id,
"replaces_param": parse_replaces_param,
"to_tag": parse_to_tag,
"from_tag": parse_from_tag,
"early_flag": parse_early_flag
};
if (startRule !== undefined) {
if (parseFunctions[startRule] === undefined) {
throw new Error("Invalid rule name: " + quote(startRule) + ".");
}
} else {
startRule = "CRLF";
}
var pos = 0;
var reportFailures = 0;
var rightmostFailuresPos = 0;
var rightmostFailuresExpected = [];
function padLeft(input, padding, length) {
var result = input;
var padLength = length - input.length;
for (var i = 0; i < padLength; i++) {
result = padding + result;
}
return result;
}
function escape(ch) {
var charCode = ch.charCodeAt(0);
var escapeChar;
var length;
if (charCode <= 0xFF) {
escapeChar = 'x';
length = 2;
} else {
escapeChar = 'u';
length = 4;
}
return '\\' + escapeChar + padLeft(charCode.toString(16).toUpperCase(), '0', length);
}
function matchFailed(failure) {
if (pos < rightmostFailuresPos) {
return;
}
if (pos > rightmostFailuresPos) {
rightmostFailuresPos = pos;
rightmostFailuresExpected = [];
}
rightmostFailuresExpected.push(failure);
}
function parse_CRLF() {
var result0;
if (input.substr(pos, 2) === "\r\n") {
result0 = "\r\n";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\r\\n\"");
}
}
return result0;
}
function parse_DIGIT() {
var result0;
if (/^[0-9]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[0-9]");
}
}
return result0;
}
function parse_ALPHA() {
var result0;
if (/^[a-zA-Z]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[a-zA-Z]");
}
}
return result0;
}
function parse_HEXDIG() {
var result0;
if (/^[0-9a-fA-F]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[0-9a-fA-F]");
}
}
return result0;
}
function parse_WSP() {
var result0;
result0 = parse_SP();
if (result0 === null) {
result0 = parse_HTAB();
}
return result0;
}
function parse_OCTET() {
var result0;
if (/^[\0-\xFF]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\\0-\\xFF]");
}
}
return result0;
}
function parse_DQUOTE() {
var result0;
if (/^["]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\"]");
}
}
return result0;
}
function parse_SP() {
var result0;
if (input.charCodeAt(pos) === 32) {
result0 = " ";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\" \"");
}
}
return result0;
}
function parse_HTAB() {
var result0;
if (input.charCodeAt(pos) === 9) {
result0 = "\t";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\t\"");
}
}
return result0;
}
function parse_alphanum() {
var result0;
if (/^[a-zA-Z0-9]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[a-zA-Z0-9]");
}
}
return result0;
}
function parse_reserved() {
var result0;
if (input.charCodeAt(pos) === 59) {
result0 = ";";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 47) {
result0 = "/";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 63) {
result0 = "?";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 58) {
result0 = ":";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 64) {
result0 = "@";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 38) {
result0 = "&";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 61) {
result0 = "=";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 43) {
result0 = "+";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 36) {
result0 = "$";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 44) {
result0 = ",";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
}
}
}
}
}
}
}
}
}
return result0;
}
function parse_unreserved() {
var result0;
result0 = parse_alphanum();
if (result0 === null) {
result0 = parse_mark();
}
return result0;
}
function parse_mark() {
var result0;
if (input.charCodeAt(pos) === 45) {
result0 = "-";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 95) {
result0 = "_";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 46) {
result0 = ".";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 33) {
result0 = "!";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 126) {
result0 = "~";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 42) {
result0 = "*";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 39) {
result0 = "'";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"'\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 40) {
result0 = "(";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"(\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 41) {
result0 = ")";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\")\"");
}
}
}
}
}
}
}
}
}
}
return result0;
}
function parse_escaped() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 37) {
result0 = "%";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"%\"");
}
}
if (result0 !== null) {
result1 = parse_HEXDIG();
if (result1 !== null) {
result2 = parse_HEXDIG();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, escaped) {return escaped.join(''); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_LWS() {
var result0, result1, result2;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
pos2 = pos;
result0 = [];
result1 = parse_WSP();
while (result1 !== null) {
result0.push(result1);
result1 = parse_WSP();
}
if (result0 !== null) {
result1 = parse_CRLF();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos2;
}
} else {
result0 = null;
pos = pos2;
}
result0 = result0 !== null ? result0 : "";
if (result0 !== null) {
result2 = parse_WSP();
if (result2 !== null) {
result1 = [];
while (result2 !== null) {
result1.push(result2);
result2 = parse_WSP();
}
} else {
result1 = null;
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return " "; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_SWS() {
var result0;
result0 = parse_LWS();
result0 = result0 !== null ? result0 : "";
return result0;
}
function parse_HCOLON() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = [];
result1 = parse_SP();
if (result1 === null) {
result1 = parse_HTAB();
}
while (result1 !== null) {
result0.push(result1);
result1 = parse_SP();
if (result1 === null) {
result1 = parse_HTAB();
}
}
if (result0 !== null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return ':'; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_TEXT_UTF8_TRIM() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result1 = parse_TEXT_UTF8char();
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_TEXT_UTF8char();
}
} else {
result0 = null;
}
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = [];
result3 = parse_LWS();
while (result3 !== null) {
result2.push(result3);
result3 = parse_LWS();
}
if (result2 !== null) {
result3 = parse_TEXT_UTF8char();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = [];
result3 = parse_LWS();
while (result3 !== null) {
result2.push(result3);
result3 = parse_LWS();
}
if (result2 !== null) {
result3 = parse_TEXT_UTF8char();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_TEXT_UTF8char() {
var result0;
if (/^[!-~]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[!-~]");
}
}
if (result0 === null) {
result0 = parse_UTF8_NONASCII();
}
return result0;
}
function parse_UTF8_NONASCII() {
var result0;
if (/^[\x80-\uFFFF]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\\x80-\\uFFFF]");
}
}
return result0;
}
function parse_UTF8_CONT() {
var result0;
if (/^[\x80-\xBF]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\\x80-\\xBF]");
}
}
return result0;
}
function parse_LHEX() {
var result0;
result0 = parse_DIGIT();
if (result0 === null) {
if (/^[a-f]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[a-f]");
}
}
}
return result0;
}
function parse_token() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_alphanum();
if (result1 === null) {
if (input.charCodeAt(pos) === 45) {
result1 = "-";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 46) {
result1 = ".";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 33) {
result1 = "!";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 37) {
result1 = "%";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"%\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 42) {
result1 = "*";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 95) {
result1 = "_";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 96) {
result1 = "`";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"`\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 39) {
result1 = "'";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"'\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 126) {
result1 = "~";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
}
}
}
}
}
}
}
}
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_alphanum();
if (result1 === null) {
if (input.charCodeAt(pos) === 45) {
result1 = "-";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 46) {
result1 = ".";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 33) {
result1 = "!";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 37) {
result1 = "%";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"%\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 42) {
result1 = "*";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 95) {
result1 = "_";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 96) {
result1 = "`";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"`\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 39) {
result1 = "'";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"'\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 126) {
result1 = "~";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
}
}
}
}
}
}
}
}
}
}
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset) {
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_token_nodot() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_alphanum();
if (result1 === null) {
if (input.charCodeAt(pos) === 45) {
result1 = "-";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 33) {
result1 = "!";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 37) {
result1 = "%";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"%\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 42) {
result1 = "*";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 95) {
result1 = "_";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 96) {
result1 = "`";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"`\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 39) {
result1 = "'";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"'\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 126) {
result1 = "~";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
}
}
}
}
}
}
}
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_alphanum();
if (result1 === null) {
if (input.charCodeAt(pos) === 45) {
result1 = "-";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 33) {
result1 = "!";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 37) {
result1 = "%";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"%\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 42) {
result1 = "*";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 95) {
result1 = "_";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 96) {
result1 = "`";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"`\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 39) {
result1 = "'";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"'\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 126) {
result1 = "~";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
}
}
}
}
}
}
}
}
}
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset) {
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_separators() {
var result0;
if (input.charCodeAt(pos) === 40) {
result0 = "(";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"(\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 41) {
result0 = ")";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\")\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 60) {
result0 = "<";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"<\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 62) {
result0 = ">";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\">\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 64) {
result0 = "@";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 44) {
result0 = ",";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 59) {
result0 = ";";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 58) {
result0 = ":";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 92) {
result0 = "\\";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\\\\"");
}
}
if (result0 === null) {
result0 = parse_DQUOTE();
if (result0 === null) {
if (input.charCodeAt(pos) === 47) {
result0 = "/";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 91) {
result0 = "[";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"[\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 93) {
result0 = "]";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"]\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 63) {
result0 = "?";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 61) {
result0 = "=";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 123) {
result0 = "{";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"{\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 125) {
result0 = "}";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"}\"");
}
}
if (result0 === null) {
result0 = parse_SP();
if (result0 === null) {
result0 = parse_HTAB();
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
return result0;
}
function parse_word() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_alphanum();
if (result1 === null) {
if (input.charCodeAt(pos) === 45) {
result1 = "-";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 46) {
result1 = ".";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 33) {
result1 = "!";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 37) {
result1 = "%";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"%\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 42) {
result1 = "*";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 95) {
result1 = "_";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 96) {
result1 = "`";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"`\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 39) {
result1 = "'";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"'\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 126) {
result1 = "~";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 40) {
result1 = "(";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"(\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 41) {
result1 = ")";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\")\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 60) {
result1 = "<";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"<\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 62) {
result1 = ">";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\">\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 92) {
result1 = "\\";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"\\\\\"");
}
}
if (result1 === null) {
result1 = parse_DQUOTE();
if (result1 === null) {
if (input.charCodeAt(pos) === 47) {
result1 = "/";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 91) {
result1 = "[";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"[\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 93) {
result1 = "]";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"]\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 63) {
result1 = "?";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 123) {
result1 = "{";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"{\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 125) {
result1 = "}";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"}\"");
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_alphanum();
if (result1 === null) {
if (input.charCodeAt(pos) === 45) {
result1 = "-";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 46) {
result1 = ".";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 33) {
result1 = "!";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 37) {
result1 = "%";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"%\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 42) {
result1 = "*";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 95) {
result1 = "_";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 96) {
result1 = "`";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"`\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 39) {
result1 = "'";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"'\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 126) {
result1 = "~";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 40) {
result1 = "(";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"(\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 41) {
result1 = ")";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\")\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 60) {
result1 = "<";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"<\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 62) {
result1 = ">";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\">\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 92) {
result1 = "\\";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"\\\\\"");
}
}
if (result1 === null) {
result1 = parse_DQUOTE();
if (result1 === null) {
if (input.charCodeAt(pos) === 47) {
result1 = "/";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 91) {
result1 = "[";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"[\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 93) {
result1 = "]";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"]\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 63) {
result1 = "?";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 123) {
result1 = "{";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"{\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 125) {
result1 = "}";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"}\"");
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset) {
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_STAR() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 42) {
result1 = "*";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return "*"; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_SLASH() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 47) {
result1 = "/";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return "/"; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_EQUAL() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 61) {
result1 = "=";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return "="; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_LPAREN() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 40) {
result1 = "(";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"(\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return "("; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_RPAREN() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 41) {
result1 = ")";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\")\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return ")"; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_RAQUOT() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 62) {
result0 = ">";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\">\"");
}
}
if (result0 !== null) {
result1 = parse_SWS();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return ">"; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_LAQUOT() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 60) {
result1 = "<";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"<\"");
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return "<"; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_COMMA() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 44) {
result1 = ",";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return ","; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_SEMI() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 59) {
result1 = ";";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return ";"; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_COLON() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return ":"; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_LDQUOT() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
result1 = parse_DQUOTE();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return "\""; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_RDQUOT() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_DQUOTE();
if (result0 !== null) {
result1 = parse_SWS();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return "\""; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_comment() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_LPAREN();
if (result0 !== null) {
result1 = [];
result2 = parse_ctext();
if (result2 === null) {
result2 = parse_quoted_pair();
if (result2 === null) {
result2 = parse_comment();
}
}
while (result2 !== null) {
result1.push(result2);
result2 = parse_ctext();
if (result2 === null) {
result2 = parse_quoted_pair();
if (result2 === null) {
result2 = parse_comment();
}
}
}
if (result1 !== null) {
result2 = parse_RPAREN();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_ctext() {
var result0;
if (/^[!-']/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[!-']");
}
}
if (result0 === null) {
if (/^[*-[]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[*-[]");
}
}
if (result0 === null) {
if (/^[\]-~]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\\]-~]");
}
}
if (result0 === null) {
result0 = parse_UTF8_NONASCII();
if (result0 === null) {
result0 = parse_LWS();
}
}
}
}
return result0;
}
function parse_quoted_string() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
result1 = parse_DQUOTE();
if (result1 !== null) {
result2 = [];
result3 = parse_qdtext();
if (result3 === null) {
result3 = parse_quoted_pair();
}
while (result3 !== null) {
result2.push(result3);
result3 = parse_qdtext();
if (result3 === null) {
result3 = parse_quoted_pair();
}
}
if (result2 !== null) {
result3 = parse_DQUOTE();
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_quoted_string_clean() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
result1 = parse_DQUOTE();
if (result1 !== null) {
result2 = [];
result3 = parse_qdtext();
if (result3 === null) {
result3 = parse_quoted_pair();
}
while (result3 !== null) {
result2.push(result3);
result3 = parse_qdtext();
if (result3 === null) {
result3 = parse_quoted_pair();
}
}
if (result2 !== null) {
result3 = parse_DQUOTE();
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
return input.substring(pos-1, offset+1); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_qdtext() {
var result0;
result0 = parse_LWS();
if (result0 === null) {
if (input.charCodeAt(pos) === 33) {
result0 = "!";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result0 === null) {
if (/^[#-[]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[#-[]");
}
}
if (result0 === null) {
if (/^[\]-~]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\\]-~]");
}
}
if (result0 === null) {
result0 = parse_UTF8_NONASCII();
}
}
}
}
return result0;
}
function parse_quoted_pair() {
var result0, result1;
var pos0;
pos0 = pos;
if (input.charCodeAt(pos) === 92) {
result0 = "\\";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\\\\"");
}
}
if (result0 !== null) {
if (/^[\0-\t]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[\\0-\\t]");
}
}
if (result1 === null) {
if (/^[\x0B-\f]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[\\x0B-\\f]");
}
}
if (result1 === null) {
if (/^[\x0E-]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[\\x0E-]");
}
}
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_SIP_URI_noparams() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_uri_scheme();
if (result0 !== null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_userinfo();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result3 = parse_hostport();
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
try {
data.uri = new URI(data.scheme, data.user, data.host, data.port);
delete data.scheme;
delete data.user;
delete data.host;
delete data.host_type;
delete data.port;
} catch(e) {
data = -1;
}})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_SIP_URI() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_uri_scheme();
if (result0 !== null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_userinfo();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result3 = parse_hostport();
if (result3 !== null) {
result4 = parse_uri_parameters();
if (result4 !== null) {
result5 = parse_headers();
result5 = result5 !== null ? result5 : "";
if (result5 !== null) {
result0 = [result0, result1, result2, result3, result4, result5];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
var header;
try {
data.uri = new URI(data.scheme, data.user, data.host, data.port, data.uri_params, data.uri_headers);
delete data.scheme;
delete data.user;
delete data.host;
delete data.host_type;
delete data.port;
delete data.uri_params;
if (startRule === 'SIP_URI') { data = data.uri;}
} catch(e) {
data = -1;
}})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_uri_scheme() {
var result0;
result0 = parse_uri_scheme_sips();
if (result0 === null) {
result0 = parse_uri_scheme_sip();
}
return result0;
}
function parse_uri_scheme_sips() {
var result0;
var pos0;
pos0 = pos;
if (input.substr(pos, 4).toLowerCase() === "sips") {
result0 = input.substr(pos, 4);
pos += 4;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"sips\"");
}
}
if (result0 !== null) {
result0 = (function(offset, scheme) {
data.scheme = scheme.toLowerCase(); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_uri_scheme_sip() {
var result0;
var pos0;
pos0 = pos;
if (input.substr(pos, 3).toLowerCase() === "sip") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"sip\"");
}
}
if (result0 !== null) {
result0 = (function(offset, scheme) {
data.scheme = scheme.toLowerCase(); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_userinfo() {
var result0, result1, result2;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_user();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_password();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
if (input.charCodeAt(pos) === 64) {
result2 = "@";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
data.user = decodeURIComponent(input.substring(pos-1, offset));})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_user() {
var result0, result1;
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
if (result1 === null) {
result1 = parse_user_unreserved();
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
if (result1 === null) {
result1 = parse_user_unreserved();
}
}
}
} else {
result0 = null;
}
return result0;
}
function parse_user_unreserved() {
var result0;
if (input.charCodeAt(pos) === 38) {
result0 = "&";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 61) {
result0 = "=";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 43) {
result0 = "+";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 36) {
result0 = "$";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 44) {
result0 = ",";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 59) {
result0 = ";";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 63) {
result0 = "?";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 47) {
result0 = "/";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
}
}
}
}
}
}
}
return result0;
}
function parse_password() {
var result0, result1;
var pos0;
pos0 = pos;
result0 = [];
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
if (result1 === null) {
if (input.charCodeAt(pos) === 38) {
result1 = "&";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 61) {
result1 = "=";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 36) {
result1 = "$";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 44) {
result1 = ",";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
}
}
}
}
}
}
while (result1 !== null) {
result0.push(result1);
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
if (result1 === null) {
if (input.charCodeAt(pos) === 38) {
result1 = "&";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 61) {
result1 = "=";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 36) {
result1 = "$";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 44) {
result1 = ",";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
}
}
}
}
}
}
}
if (result0 !== null) {
result0 = (function(offset) {
data.password = input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_hostport() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
result0 = parse_host();
if (result0 !== null) {
pos1 = pos;
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_port();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos1;
}
} else {
result1 = null;
pos = pos1;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_host() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_hostname();
if (result0 === null) {
result0 = parse_IPv4address();
if (result0 === null) {
result0 = parse_IPv6reference();
}
}
if (result0 !== null) {
result0 = (function(offset) {
data.host = input.substring(pos, offset).toLowerCase();
return data.host; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_hostname() {
var result0, result1, result2;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = [];
pos2 = pos;
result1 = parse_domainlabel();
if (result1 !== null) {
if (input.charCodeAt(pos) === 46) {
result2 = ".";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
while (result1 !== null) {
result0.push(result1);
pos2 = pos;
result1 = parse_domainlabel();
if (result1 !== null) {
if (input.charCodeAt(pos) === 46) {
result2 = ".";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
}
if (result0 !== null) {
result1 = parse_toplabel();
if (result1 !== null) {
if (input.charCodeAt(pos) === 46) {
result2 = ".";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
data.host_type = 'domain';
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_domainlabel() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_alphanum();
if (result0 !== null) {
result1 = [];
result2 = parse_alphanum();
if (result2 === null) {
if (input.charCodeAt(pos) === 45) {
result2 = "-";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result2 === null) {
if (input.charCodeAt(pos) === 95) {
result2 = "_";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
}
}
while (result2 !== null) {
result1.push(result2);
result2 = parse_alphanum();
if (result2 === null) {
if (input.charCodeAt(pos) === 45) {
result2 = "-";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result2 === null) {
if (input.charCodeAt(pos) === 95) {
result2 = "_";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
}
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_toplabel() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_ALPHA();
if (result0 !== null) {
result1 = [];
result2 = parse_alphanum();
if (result2 === null) {
if (input.charCodeAt(pos) === 45) {
result2 = "-";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result2 === null) {
if (input.charCodeAt(pos) === 95) {
result2 = "_";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
}
}
while (result2 !== null) {
result1.push(result2);
result2 = parse_alphanum();
if (result2 === null) {
if (input.charCodeAt(pos) === 45) {
result2 = "-";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result2 === null) {
if (input.charCodeAt(pos) === 95) {
result2 = "_";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
}
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_IPv6reference() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 91) {
result0 = "[";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"[\"");
}
}
if (result0 !== null) {
result1 = parse_IPv6address();
if (result1 !== null) {
if (input.charCodeAt(pos) === 93) {
result2 = "]";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"]\"");
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
data.host_type = 'IPv6';
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_IPv6address() {
var result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10, result11, result12;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_h16();
if (result0 !== null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
if (input.charCodeAt(pos) === 58) {
result3 = ":";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result3 !== null) {
result4 = parse_h16();
if (result4 !== null) {
if (input.charCodeAt(pos) === 58) {
result5 = ":";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result5 !== null) {
result6 = parse_h16();
if (result6 !== null) {
if (input.charCodeAt(pos) === 58) {
result7 = ":";
pos++;
} else {
result7 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result7 !== null) {
result8 = parse_h16();
if (result8 !== null) {
if (input.charCodeAt(pos) === 58) {
result9 = ":";
pos++;
} else {
result9 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result9 !== null) {
result10 = parse_h16();
if (result10 !== null) {
if (input.charCodeAt(pos) === 58) {
result11 = ":";
pos++;
} else {
result11 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result11 !== null) {
result12 = parse_ls32();
if (result12 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10, result11, result12];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
if (input.substr(pos, 2) === "::") {
result0 = "::";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result0 !== null) {
result1 = parse_h16();
if (result1 !== null) {
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
if (input.charCodeAt(pos) === 58) {
result4 = ":";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result4 !== null) {
result5 = parse_h16();
if (result5 !== null) {
if (input.charCodeAt(pos) === 58) {
result6 = ":";
pos++;
} else {
result6 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result6 !== null) {
result7 = parse_h16();
if (result7 !== null) {
if (input.charCodeAt(pos) === 58) {
result8 = ":";
pos++;
} else {
result8 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result8 !== null) {
result9 = parse_h16();
if (result9 !== null) {
if (input.charCodeAt(pos) === 58) {
result10 = ":";
pos++;
} else {
result10 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result10 !== null) {
result11 = parse_ls32();
if (result11 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10, result11];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
if (input.substr(pos, 2) === "::") {
result0 = "::";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result0 !== null) {
result1 = parse_h16();
if (result1 !== null) {
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
if (input.charCodeAt(pos) === 58) {
result4 = ":";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result4 !== null) {
result5 = parse_h16();
if (result5 !== null) {
if (input.charCodeAt(pos) === 58) {
result6 = ":";
pos++;
} else {
result6 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result6 !== null) {
result7 = parse_h16();
if (result7 !== null) {
if (input.charCodeAt(pos) === 58) {
result8 = ":";
pos++;
} else {
result8 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result8 !== null) {
result9 = parse_ls32();
if (result9 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
if (input.substr(pos, 2) === "::") {
result0 = "::";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result0 !== null) {
result1 = parse_h16();
if (result1 !== null) {
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
if (input.charCodeAt(pos) === 58) {
result4 = ":";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result4 !== null) {
result5 = parse_h16();
if (result5 !== null) {
if (input.charCodeAt(pos) === 58) {
result6 = ":";
pos++;
} else {
result6 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result6 !== null) {
result7 = parse_ls32();
if (result7 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
if (input.substr(pos, 2) === "::") {
result0 = "::";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result0 !== null) {
result1 = parse_h16();
if (result1 !== null) {
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
if (input.charCodeAt(pos) === 58) {
result4 = ":";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result4 !== null) {
result5 = parse_ls32();
if (result5 !== null) {
result0 = [result0, result1, result2, result3, result4, result5];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
if (input.substr(pos, 2) === "::") {
result0 = "::";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result0 !== null) {
result1 = parse_h16();
if (result1 !== null) {
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_ls32();
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
if (input.substr(pos, 2) === "::") {
result0 = "::";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result0 !== null) {
result1 = parse_ls32();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
if (input.substr(pos, 2) === "::") {
result0 = "::";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result0 !== null) {
result1 = parse_h16();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
result0 = parse_h16();
if (result0 !== null) {
if (input.substr(pos, 2) === "::") {
result1 = "::";
pos += 2;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
if (input.charCodeAt(pos) === 58) {
result3 = ":";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result3 !== null) {
result4 = parse_h16();
if (result4 !== null) {
if (input.charCodeAt(pos) === 58) {
result5 = ":";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result5 !== null) {
result6 = parse_h16();
if (result6 !== null) {
if (input.charCodeAt(pos) === 58) {
result7 = ":";
pos++;
} else {
result7 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result7 !== null) {
result8 = parse_h16();
if (result8 !== null) {
if (input.charCodeAt(pos) === 58) {
result9 = ":";
pos++;
} else {
result9 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result9 !== null) {
result10 = parse_ls32();
if (result10 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
result0 = parse_h16();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
if (input.substr(pos, 2) === "::") {
result2 = "::";
pos += 2;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
if (input.charCodeAt(pos) === 58) {
result4 = ":";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result4 !== null) {
result5 = parse_h16();
if (result5 !== null) {
if (input.charCodeAt(pos) === 58) {
result6 = ":";
pos++;
} else {
result6 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result6 !== null) {
result7 = parse_h16();
if (result7 !== null) {
if (input.charCodeAt(pos) === 58) {
result8 = ":";
pos++;
} else {
result8 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result8 !== null) {
result9 = parse_ls32();
if (result9 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
result0 = parse_h16();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
if (input.substr(pos, 2) === "::") {
result3 = "::";
pos += 2;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result3 !== null) {
result4 = parse_h16();
if (result4 !== null) {
if (input.charCodeAt(pos) === 58) {
result5 = ":";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result5 !== null) {
result6 = parse_h16();
if (result6 !== null) {
if (input.charCodeAt(pos) === 58) {
result7 = ":";
pos++;
} else {
result7 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result7 !== null) {
result8 = parse_ls32();
if (result8 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
result0 = parse_h16();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result3 = ":";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result3 !== null) {
result4 = parse_h16();
if (result4 !== null) {
result3 = [result3, result4];
} else {
result3 = null;
pos = pos2;
}
} else {
result3 = null;
pos = pos2;
}
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
if (input.substr(pos, 2) === "::") {
result4 = "::";
pos += 2;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result4 !== null) {
result5 = parse_h16();
if (result5 !== null) {
if (input.charCodeAt(pos) === 58) {
result6 = ":";
pos++;
} else {
result6 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result6 !== null) {
result7 = parse_ls32();
if (result7 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
result0 = parse_h16();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result3 = ":";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result3 !== null) {
result4 = parse_h16();
if (result4 !== null) {
result3 = [result3, result4];
} else {
result3 = null;
pos = pos2;
}
} else {
result3 = null;
pos = pos2;
}
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result4 = ":";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result4 !== null) {
result5 = parse_h16();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos2;
}
} else {
result4 = null;
pos = pos2;
}
result4 = result4 !== null ? result4 : "";
if (result4 !== null) {
if (input.substr(pos, 2) === "::") {
result5 = "::";
pos += 2;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result5 !== null) {
result6 = parse_ls32();
if (result6 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
result0 = parse_h16();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result3 = ":";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result3 !== null) {
result4 = parse_h16();
if (result4 !== null) {
result3 = [result3, result4];
} else {
result3 = null;
pos = pos2;
}
} else {
result3 = null;
pos = pos2;
}
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result4 = ":";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result4 !== null) {
result5 = parse_h16();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos2;
}
} else {
result4 = null;
pos = pos2;
}
result4 = result4 !== null ? result4 : "";
if (result4 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result5 = ":";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result5 !== null) {
result6 = parse_h16();
if (result6 !== null) {
result5 = [result5, result6];
} else {
result5 = null;
pos = pos2;
}
} else {
result5 = null;
pos = pos2;
}
result5 = result5 !== null ? result5 : "";
if (result5 !== null) {
if (input.substr(pos, 2) === "::") {
result6 = "::";
pos += 2;
} else {
result6 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result6 !== null) {
result7 = parse_h16();
if (result7 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
result0 = parse_h16();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result3 = ":";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result3 !== null) {
result4 = parse_h16();
if (result4 !== null) {
result3 = [result3, result4];
} else {
result3 = null;
pos = pos2;
}
} else {
result3 = null;
pos = pos2;
}
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result4 = ":";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result4 !== null) {
result5 = parse_h16();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos2;
}
} else {
result4 = null;
pos = pos2;
}
result4 = result4 !== null ? result4 : "";
if (result4 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result5 = ":";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result5 !== null) {
result6 = parse_h16();
if (result6 !== null) {
result5 = [result5, result6];
} else {
result5 = null;
pos = pos2;
}
} else {
result5 = null;
pos = pos2;
}
result5 = result5 !== null ? result5 : "";
if (result5 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result6 = ":";
pos++;
} else {
result6 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result6 !== null) {
result7 = parse_h16();
if (result7 !== null) {
result6 = [result6, result7];
} else {
result6 = null;
pos = pos2;
}
} else {
result6 = null;
pos = pos2;
}
result6 = result6 !== null ? result6 : "";
if (result6 !== null) {
if (input.substr(pos, 2) === "::") {
result7 = "::";
pos += 2;
} else {
result7 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result7 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
if (result0 !== null) {
result0 = (function(offset) {
data.host_type = 'IPv6';
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_h16() {
var result0, result1, result2, result3;
var pos0;
pos0 = pos;
result0 = parse_HEXDIG();
if (result0 !== null) {
result1 = parse_HEXDIG();
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result2 = parse_HEXDIG();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result3 = parse_HEXDIG();
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_ls32() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_h16();
if (result0 !== null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
if (result0 === null) {
result0 = parse_IPv4address();
}
return result0;
}
function parse_IPv4address() {
var result0, result1, result2, result3, result4, result5, result6;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_dec_octet();
if (result0 !== null) {
if (input.charCodeAt(pos) === 46) {
result1 = ".";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result1 !== null) {
result2 = parse_dec_octet();
if (result2 !== null) {
if (input.charCodeAt(pos) === 46) {
result3 = ".";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result3 !== null) {
result4 = parse_dec_octet();
if (result4 !== null) {
if (input.charCodeAt(pos) === 46) {
result5 = ".";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result5 !== null) {
result6 = parse_dec_octet();
if (result6 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
data.host_type = 'IPv4';
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_dec_octet() {
var result0, result1, result2;
var pos0;
pos0 = pos;
if (input.substr(pos, 2) === "25") {
result0 = "25";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"25\"");
}
}
if (result0 !== null) {
if (/^[0-5]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[0-5]");
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.charCodeAt(pos) === 50) {
result0 = "2";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"2\"");
}
}
if (result0 !== null) {
if (/^[0-4]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[0-4]");
}
}
if (result1 !== null) {
result2 = parse_DIGIT();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.charCodeAt(pos) === 49) {
result0 = "1";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"1\"");
}
}
if (result0 !== null) {
result1 = parse_DIGIT();
if (result1 !== null) {
result2 = parse_DIGIT();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (/^[1-9]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[1-9]");
}
}
if (result0 !== null) {
result1 = parse_DIGIT();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
if (result0 === null) {
result0 = parse_DIGIT();
}
}
}
}
return result0;
}
function parse_port() {
var result0, result1, result2, result3, result4;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_DIGIT();
result0 = result0 !== null ? result0 : "";
if (result0 !== null) {
result1 = parse_DIGIT();
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result2 = parse_DIGIT();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result3 = parse_DIGIT();
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
result4 = parse_DIGIT();
result4 = result4 !== null ? result4 : "";
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, port) {
port = parseInt(port.join(''));
data.port = port;
return port; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_uri_parameters() {
var result0, result1, result2;
var pos0;
result0 = [];
pos0 = pos;
if (input.charCodeAt(pos) === 59) {
result1 = ";";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result1 !== null) {
result2 = parse_uri_parameter();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos0;
}
} else {
result1 = null;
pos = pos0;
}
while (result1 !== null) {
result0.push(result1);
pos0 = pos;
if (input.charCodeAt(pos) === 59) {
result1 = ";";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result1 !== null) {
result2 = parse_uri_parameter();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos0;
}
} else {
result1 = null;
pos = pos0;
}
}
return result0;
}
function parse_uri_parameter() {
var result0;
result0 = parse_transport_param();
if (result0 === null) {
result0 = parse_user_param();
if (result0 === null) {
result0 = parse_method_param();
if (result0 === null) {
result0 = parse_ttl_param();
if (result0 === null) {
result0 = parse_maddr_param();
if (result0 === null) {
result0 = parse_lr_param();
if (result0 === null) {
result0 = parse_other_param();
}
}
}
}
}
}
return result0;
}
function parse_transport_param() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 10).toLowerCase() === "transport=") {
result0 = input.substr(pos, 10);
pos += 10;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"transport=\"");
}
}
if (result0 !== null) {
if (input.substr(pos, 3).toLowerCase() === "udp") {
result1 = input.substr(pos, 3);
pos += 3;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"udp\"");
}
}
if (result1 === null) {
if (input.substr(pos, 3).toLowerCase() === "tcp") {
result1 = input.substr(pos, 3);
pos += 3;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"tcp\"");
}
}
if (result1 === null) {
if (input.substr(pos, 4).toLowerCase() === "sctp") {
result1 = input.substr(pos, 4);
pos += 4;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"sctp\"");
}
}
if (result1 === null) {
if (input.substr(pos, 3).toLowerCase() === "tls") {
result1 = input.substr(pos, 3);
pos += 3;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"tls\"");
}
}
if (result1 === null) {
result1 = parse_token();
}
}
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, transport) {
if(!data.uri_params) data.uri_params={};
data.uri_params['transport'] = transport.toLowerCase(); })(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_user_param() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 5).toLowerCase() === "user=") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"user=\"");
}
}
if (result0 !== null) {
if (input.substr(pos, 5).toLowerCase() === "phone") {
result1 = input.substr(pos, 5);
pos += 5;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"phone\"");
}
}
if (result1 === null) {
if (input.substr(pos, 2).toLowerCase() === "ip") {
result1 = input.substr(pos, 2);
pos += 2;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"ip\"");
}
}
if (result1 === null) {
result1 = parse_token();
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, user) {
if(!data.uri_params) data.uri_params={};
data.uri_params['user'] = user.toLowerCase(); })(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_method_param() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 7).toLowerCase() === "method=") {
result0 = input.substr(pos, 7);
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"method=\"");
}
}
if (result0 !== null) {
result1 = parse_Method();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, method) {
if(!data.uri_params) data.uri_params={};
data.uri_params['method'] = method; })(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_ttl_param() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 4).toLowerCase() === "ttl=") {
result0 = input.substr(pos, 4);
pos += 4;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"ttl=\"");
}
}
if (result0 !== null) {
result1 = parse_ttl();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, ttl) {
if(!data.params) data.params={};
data.params['ttl'] = ttl; })(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_maddr_param() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 6).toLowerCase() === "maddr=") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"maddr=\"");
}
}
if (result0 !== null) {
result1 = parse_host();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, maddr) {
if(!data.uri_params) data.uri_params={};
data.uri_params['maddr'] = maddr; })(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_lr_param() {
var result0, result1, result2;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 2).toLowerCase() === "lr") {
result0 = input.substr(pos, 2);
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"lr\"");
}
}
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 61) {
result1 = "=";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result1 !== null) {
result2 = parse_token();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
if(!data.uri_params) data.uri_params={};
data.uri_params['lr'] = undefined; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_other_param() {
var result0, result1, result2;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_pname();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 61) {
result1 = "=";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result1 !== null) {
result2 = parse_pvalue();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, param, value) {
if(!data.uri_params) data.uri_params = {};
if (typeof value === 'undefined'){
value = undefined;
}
else {
value = value[1];
}
data.uri_params[param.toLowerCase()] = value;})(pos0, result0[0], result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_pname() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_paramchar();
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_paramchar();
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset, pname) {return pname.join(''); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_pvalue() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_paramchar();
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_paramchar();
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset, pvalue) {return pvalue.join(''); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_paramchar() {
var result0;
result0 = parse_param_unreserved();
if (result0 === null) {
result0 = parse_unreserved();
if (result0 === null) {
result0 = parse_escaped();
}
}
return result0;
}
function parse_param_unreserved() {
var result0;
if (input.charCodeAt(pos) === 91) {
result0 = "[";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"[\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 93) {
result0 = "]";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"]\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 47) {
result0 = "/";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 58) {
result0 = ":";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 38) {
result0 = "&";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 43) {
result0 = "+";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 36) {
result0 = "$";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
}
}
}
}
}
}
return result0;
}
function parse_headers() {
var result0, result1, result2, result3, result4;
var pos0, pos1;
pos0 = pos;
if (input.charCodeAt(pos) === 63) {
result0 = "?";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result0 !== null) {
result1 = parse_header();
if (result1 !== null) {
result2 = [];
pos1 = pos;
if (input.charCodeAt(pos) === 38) {
result3 = "&";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result3 !== null) {
result4 = parse_header();
if (result4 !== null) {
result3 = [result3, result4];
} else {
result3 = null;
pos = pos1;
}
} else {
result3 = null;
pos = pos1;
}
while (result3 !== null) {
result2.push(result3);
pos1 = pos;
if (input.charCodeAt(pos) === 38) {
result3 = "&";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result3 !== null) {
result4 = parse_header();
if (result4 !== null) {
result3 = [result3, result4];
} else {
result3 = null;
pos = pos1;
}
} else {
result3 = null;
pos = pos1;
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_header() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_hname();
if (result0 !== null) {
if (input.charCodeAt(pos) === 61) {
result1 = "=";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result1 !== null) {
result2 = parse_hvalue();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, hname, hvalue) {
hname = hname.join('').toLowerCase();
hvalue = hvalue.join('');
if(!data.uri_headers) data.uri_headers = {};
if (!data.uri_headers[hname]) {
data.uri_headers[hname] = [hvalue];
} else {
data.uri_headers[hname].push(hvalue);
}})(pos0, result0[0], result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_hname() {
var result0, result1;
result1 = parse_hnv_unreserved();
if (result1 === null) {
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_hnv_unreserved();
if (result1 === null) {
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
}
}
}
} else {
result0 = null;
}
return result0;
}
function parse_hvalue() {
var result0, result1;
result0 = [];
result1 = parse_hnv_unreserved();
if (result1 === null) {
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
}
}
while (result1 !== null) {
result0.push(result1);
result1 = parse_hnv_unreserved();
if (result1 === null) {
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
}
}
}
return result0;
}
function parse_hnv_unreserved() {
var result0;
if (input.charCodeAt(pos) === 91) {
result0 = "[";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"[\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 93) {
result0 = "]";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"]\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 47) {
result0 = "/";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 63) {
result0 = "?";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 58) {
result0 = ":";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 43) {
result0 = "+";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 36) {
result0 = "$";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
}
}
}
}
}
}
return result0;
}
function parse_Request_Response() {
var result0;
result0 = parse_Status_Line();
if (result0 === null) {
result0 = parse_Request_Line();
}
return result0;
}
function parse_Request_Line() {
var result0, result1, result2, result3, result4;
var pos0;
pos0 = pos;
result0 = parse_Method();
if (result0 !== null) {
result1 = parse_SP();
if (result1 !== null) {
result2 = parse_Request_URI();
if (result2 !== null) {
result3 = parse_SP();
if (result3 !== null) {
result4 = parse_SIP_Version();
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Request_URI() {
var result0;
result0 = parse_SIP_URI();
if (result0 === null) {
result0 = parse_absoluteURI();
}
return result0;
}
function parse_absoluteURI() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_scheme();
if (result0 !== null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_hier_part();
if (result2 === null) {
result2 = parse_opaque_part();
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_hier_part() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
result0 = parse_net_path();
if (result0 === null) {
result0 = parse_abs_path();
}
if (result0 !== null) {
pos1 = pos;
if (input.charCodeAt(pos) === 63) {
result1 = "?";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result1 !== null) {
result2 = parse_query();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos1;
}
} else {
result1 = null;
pos = pos1;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_net_path() {
var result0, result1, result2;
var pos0;
pos0 = pos;
if (input.substr(pos, 2) === "//") {
result0 = "//";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"//\"");
}
}
if (result0 !== null) {
result1 = parse_authority();
if (result1 !== null) {
result2 = parse_abs_path();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_abs_path() {
var result0, result1;
var pos0;
pos0 = pos;
if (input.charCodeAt(pos) === 47) {
result0 = "/";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result0 !== null) {
result1 = parse_path_segments();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_opaque_part() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_uric_no_slash();
if (result0 !== null) {
result1 = [];
result2 = parse_uric();
while (result2 !== null) {
result1.push(result2);
result2 = parse_uric();
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_uric() {
var result0;
result0 = parse_reserved();
if (result0 === null) {
result0 = parse_unreserved();
if (result0 === null) {
result0 = parse_escaped();
}
}
return result0;
}
function parse_uric_no_slash() {
var result0;
result0 = parse_unreserved();
if (result0 === null) {
result0 = parse_escaped();
if (result0 === null) {
if (input.charCodeAt(pos) === 59) {
result0 = ";";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 63) {
result0 = "?";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 58) {
result0 = ":";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 64) {
result0 = "@";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 38) {
result0 = "&";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 61) {
result0 = "=";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 43) {
result0 = "+";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 36) {
result0 = "$";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 44) {
result0 = ",";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
}
}
}
}
}
}
}
}
}
}
return result0;
}
function parse_path_segments() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_segment();
if (result0 !== null) {
result1 = [];
pos1 = pos;
if (input.charCodeAt(pos) === 47) {
result2 = "/";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result2 !== null) {
result3 = parse_segment();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
if (input.charCodeAt(pos) === 47) {
result2 = "/";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result2 !== null) {
result3 = parse_segment();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_segment() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = [];
result1 = parse_pchar();
while (result1 !== null) {
result0.push(result1);
result1 = parse_pchar();
}
if (result0 !== null) {
result1 = [];
pos1 = pos;
if (input.charCodeAt(pos) === 59) {
result2 = ";";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result2 !== null) {
result3 = parse_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
if (input.charCodeAt(pos) === 59) {
result2 = ";";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result2 !== null) {
result3 = parse_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_param() {
var result0, result1;
result0 = [];
result1 = parse_pchar();
while (result1 !== null) {
result0.push(result1);
result1 = parse_pchar();
}
return result0;
}
function parse_pchar() {
var result0;
result0 = parse_unreserved();
if (result0 === null) {
result0 = parse_escaped();
if (result0 === null) {
if (input.charCodeAt(pos) === 58) {
result0 = ":";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 64) {
result0 = "@";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 38) {
result0 = "&";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 61) {
result0 = "=";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 43) {
result0 = "+";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 36) {
result0 = "$";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 44) {
result0 = ",";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
}
}
}
}
}
}
}
}
return result0;
}
function parse_scheme() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_ALPHA();
if (result0 !== null) {
result1 = [];
result2 = parse_ALPHA();
if (result2 === null) {
result2 = parse_DIGIT();
if (result2 === null) {
if (input.charCodeAt(pos) === 43) {
result2 = "+";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result2 === null) {
if (input.charCodeAt(pos) === 45) {
result2 = "-";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result2 === null) {
if (input.charCodeAt(pos) === 46) {
result2 = ".";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
}
}
}
}
while (result2 !== null) {
result1.push(result2);
result2 = parse_ALPHA();
if (result2 === null) {
result2 = parse_DIGIT();
if (result2 === null) {
if (input.charCodeAt(pos) === 43) {
result2 = "+";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result2 === null) {
if (input.charCodeAt(pos) === 45) {
result2 = "-";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result2 === null) {
if (input.charCodeAt(pos) === 46) {
result2 = ".";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
}
}
}
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
data.scheme= input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_authority() {
var result0;
result0 = parse_srvr();
if (result0 === null) {
result0 = parse_reg_name();
}
return result0;
}
function parse_srvr() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_userinfo();
if (result0 !== null) {
if (input.charCodeAt(pos) === 64) {
result1 = "@";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
result0 = result0 !== null ? result0 : "";
if (result0 !== null) {
result1 = parse_hostport();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
result0 = result0 !== null ? result0 : "";
return result0;
}
function parse_reg_name() {
var result0, result1;
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
if (result1 === null) {
if (input.charCodeAt(pos) === 36) {
result1 = "$";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 44) {
result1 = ",";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 59) {
result1 = ";";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 64) {
result1 = "@";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 38) {
result1 = "&";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 61) {
result1 = "=";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
}
}
}
}
}
}
}
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
if (result1 === null) {
if (input.charCodeAt(pos) === 36) {
result1 = "$";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 44) {
result1 = ",";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 59) {
result1 = ";";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 64) {
result1 = "@";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 38) {
result1 = "&";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 61) {
result1 = "=";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
}
}
}
}
}
}
}
}
}
}
} else {
result0 = null;
}
return result0;
}
function parse_query() {
var result0, result1;
result0 = [];
result1 = parse_uric();
while (result1 !== null) {
result0.push(result1);
result1 = parse_uric();
}
return result0;
}
function parse_SIP_Version() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 3).toLowerCase() === "sip") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"SIP\"");
}
}
if (result0 !== null) {
if (input.charCodeAt(pos) === 47) {
result1 = "/";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result1 !== null) {
result3 = parse_DIGIT();
if (result3 !== null) {
result2 = [];
while (result3 !== null) {
result2.push(result3);
result3 = parse_DIGIT();
}
} else {
result2 = null;
}
if (result2 !== null) {
if (input.charCodeAt(pos) === 46) {
result3 = ".";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result3 !== null) {
result5 = parse_DIGIT();
if (result5 !== null) {
result4 = [];
while (result5 !== null) {
result4.push(result5);
result5 = parse_DIGIT();
}
} else {
result4 = null;
}
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
data.sip_version = input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_INVITEm() {
var result0;
if (input.substr(pos, 6) === "INVITE") {
result0 = "INVITE";
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"INVITE\"");
}
}
return result0;
}
function parse_ACKm() {
var result0;
if (input.substr(pos, 3) === "ACK") {
result0 = "ACK";
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"ACK\"");
}
}
return result0;
}
function parse_OPTIONSm() {
var result0;
if (input.substr(pos, 7) === "OPTIONS") {
result0 = "OPTIONS";
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"OPTIONS\"");
}
}
return result0;
}
function parse_BYEm() {
var result0;
if (input.substr(pos, 3) === "BYE") {
result0 = "BYE";
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"BYE\"");
}
}
return result0;
}
function parse_CANCELm() {
var result0;
if (input.substr(pos, 6) === "CANCEL") {
result0 = "CANCEL";
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"CANCEL\"");
}
}
return result0;
}
function parse_REGISTERm() {
var result0;
if (input.substr(pos, 8) === "REGISTER") {
result0 = "REGISTER";
pos += 8;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"REGISTER\"");
}
}
return result0;
}
function parse_SUBSCRIBEm() {
var result0;
if (input.substr(pos, 9) === "SUBSCRIBE") {
result0 = "SUBSCRIBE";
pos += 9;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"SUBSCRIBE\"");
}
}
return result0;
}
function parse_NOTIFYm() {
var result0;
if (input.substr(pos, 6) === "NOTIFY") {
result0 = "NOTIFY";
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"NOTIFY\"");
}
}
return result0;
}
function parse_REFERm() {
var result0;
if (input.substr(pos, 5) === "REFER") {
result0 = "REFER";
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"REFER\"");
}
}
return result0;
}
function parse_Method() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_INVITEm();
if (result0 === null) {
result0 = parse_ACKm();
if (result0 === null) {
result0 = parse_OPTIONSm();
if (result0 === null) {
result0 = parse_BYEm();
if (result0 === null) {
result0 = parse_CANCELm();
if (result0 === null) {
result0 = parse_REGISTERm();
if (result0 === null) {
result0 = parse_SUBSCRIBEm();
if (result0 === null) {
result0 = parse_NOTIFYm();
if (result0 === null) {
result0 = parse_REFERm();
if (result0 === null) {
result0 = parse_token();
}
}
}
}
}
}
}
}
}
if (result0 !== null) {
result0 = (function(offset) {
data.method = input.substring(pos, offset);
return data.method; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Status_Line() {
var result0, result1, result2, result3, result4;
var pos0;
pos0 = pos;
result0 = parse_SIP_Version();
if (result0 !== null) {
result1 = parse_SP();
if (result1 !== null) {
result2 = parse_Status_Code();
if (result2 !== null) {
result3 = parse_SP();
if (result3 !== null) {
result4 = parse_Reason_Phrase();
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Status_Code() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_extension_code();
if (result0 !== null) {
result0 = (function(offset, status_code) {
data.status_code = parseInt(status_code.join('')); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_extension_code() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_DIGIT();
if (result0 !== null) {
result1 = parse_DIGIT();
if (result1 !== null) {
result2 = parse_DIGIT();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Reason_Phrase() {
var result0, result1;
var pos0;
pos0 = pos;
result0 = [];
result1 = parse_reserved();
if (result1 === null) {
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
if (result1 === null) {
result1 = parse_UTF8_NONASCII();
if (result1 === null) {
result1 = parse_UTF8_CONT();
if (result1 === null) {
result1 = parse_SP();
if (result1 === null) {
result1 = parse_HTAB();
}
}
}
}
}
}
while (result1 !== null) {
result0.push(result1);
result1 = parse_reserved();
if (result1 === null) {
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
if (result1 === null) {
result1 = parse_UTF8_NONASCII();
if (result1 === null) {
result1 = parse_UTF8_CONT();
if (result1 === null) {
result1 = parse_SP();
if (result1 === null) {
result1 = parse_HTAB();
}
}
}
}
}
}
}
if (result0 !== null) {
result0 = (function(offset) {
data.reason_phrase = input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Allow_Events() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_event_type();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_event_type();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_event_type();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Call_ID() {
var result0, result1, result2;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_word();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 64) {
result1 = "@";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result1 !== null) {
result2 = parse_word();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
data = input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Contact() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
result0 = parse_STAR();
if (result0 === null) {
pos1 = pos;
result0 = parse_contact_param();
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_contact_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_contact_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
}
if (result0 !== null) {
result0 = (function(offset) {
var idx, length;
length = data.multi_header.length;
for (idx = 0; idx < length; idx++) {
if (data.multi_header[idx].parsed === null) {
data = null;
break;
}
}
if (data !== null) {
data = data.multi_header;
} else {
data = -1;
}})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_contact_param() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_SIP_URI_noparams();
if (result0 === null) {
result0 = parse_name_addr();
}
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_contact_params();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_contact_params();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
var header;
if(!data.multi_header) data.multi_header = [];
try {
header = new NameAddrHeader(data.uri, data.display_name, data.params);
delete data.uri;
delete data.display_name;
delete data.params;
} catch(e) {
header = null;
}
data.multi_header.push( { 'possition': pos,
'offset': offset,
'parsed': header
});})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_name_addr() {
var result0, result1, result2, result3;
var pos0;
pos0 = pos;
result0 = parse_display_name();
result0 = result0 !== null ? result0 : "";
if (result0 !== null) {
result1 = parse_LAQUOT();
if (result1 !== null) {
result2 = parse_SIP_URI();
if (result2 !== null) {
result3 = parse_RAQUOT();
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_display_name() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_LWS();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_LWS();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
result0 = parse_quoted_string();
}
if (result0 !== null) {
result0 = (function(offset, display_name) {
display_name = input.substring(pos, offset).trim();
if (display_name[0] === '\"') {
display_name = display_name.substring(1, display_name.length-1);
}
data.display_name = display_name; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_contact_params() {
var result0;
result0 = parse_c_p_q();
if (result0 === null) {
result0 = parse_c_p_expires();
if (result0 === null) {
result0 = parse_generic_param();
}
}
return result0;
}
function parse_c_p_q() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 1).toLowerCase() === "q") {
result0 = input.substr(pos, 1);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"q\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_qvalue();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, q) {
if(!data.params) data.params = {};
data.params['q'] = q; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_c_p_expires() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 7).toLowerCase() === "expires") {
result0 = input.substr(pos, 7);
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"expires\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_delta_seconds();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, expires) {
if(!data.params) data.params = {};
data.params['expires'] = expires; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_delta_seconds() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_DIGIT();
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_DIGIT();
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset, delta_seconds) {
return parseInt(delta_seconds.join('')); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_qvalue() {
var result0, result1, result2, result3, result4;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 48) {
result0 = "0";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"0\"");
}
}
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 46) {
result1 = ".";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result1 !== null) {
result2 = parse_DIGIT();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result3 = parse_DIGIT();
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
result4 = parse_DIGIT();
result4 = result4 !== null ? result4 : "";
if (result4 !== null) {
result1 = [result1, result2, result3, result4];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
return parseFloat(input.substring(pos, offset)); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_generic_param() {
var result0, result1, result2;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_token();
if (result0 !== null) {
pos2 = pos;
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_gen_value();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, param, value) {
if(!data.params) data.params = {};
if (typeof value === 'undefined'){
value = undefined;
}
else {
value = value[1];
}
data.params[param.toLowerCase()] = value;})(pos0, result0[0], result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_gen_value() {
var result0;
result0 = parse_token();
if (result0 === null) {
result0 = parse_host();
if (result0 === null) {
result0 = parse_quoted_string();
}
}
return result0;
}
function parse_Content_Disposition() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_disp_type();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_disp_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_disp_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_disp_type() {
var result0;
if (input.substr(pos, 6).toLowerCase() === "render") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"render\"");
}
}
if (result0 === null) {
if (input.substr(pos, 7).toLowerCase() === "session") {
result0 = input.substr(pos, 7);
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"session\"");
}
}
if (result0 === null) {
if (input.substr(pos, 4).toLowerCase() === "icon") {
result0 = input.substr(pos, 4);
pos += 4;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"icon\"");
}
}
if (result0 === null) {
if (input.substr(pos, 5).toLowerCase() === "alert") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"alert\"");
}
}
if (result0 === null) {
result0 = parse_token();
}
}
}
}
return result0;
}
function parse_disp_param() {
var result0;
result0 = parse_handling_param();
if (result0 === null) {
result0 = parse_generic_param();
}
return result0;
}
function parse_handling_param() {
var result0, result1, result2;
var pos0;
pos0 = pos;
if (input.substr(pos, 8).toLowerCase() === "handling") {
result0 = input.substr(pos, 8);
pos += 8;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"handling\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
if (input.substr(pos, 8).toLowerCase() === "optional") {
result2 = input.substr(pos, 8);
pos += 8;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"optional\"");
}
}
if (result2 === null) {
if (input.substr(pos, 8).toLowerCase() === "required") {
result2 = input.substr(pos, 8);
pos += 8;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"required\"");
}
}
if (result2 === null) {
result2 = parse_token();
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Content_Encoding() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Content_Length() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_DIGIT();
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_DIGIT();
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset, length) {
data = parseInt(length.join('')); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Content_Type() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_media_type();
if (result0 !== null) {
result0 = (function(offset) {
data = input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_media_type() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1;
pos0 = pos;
result0 = parse_m_type();
if (result0 !== null) {
result1 = parse_SLASH();
if (result1 !== null) {
result2 = parse_m_subtype();
if (result2 !== null) {
result3 = [];
pos1 = pos;
result4 = parse_SEMI();
if (result4 !== null) {
result5 = parse_m_parameter();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos1;
}
} else {
result4 = null;
pos = pos1;
}
while (result4 !== null) {
result3.push(result4);
pos1 = pos;
result4 = parse_SEMI();
if (result4 !== null) {
result5 = parse_m_parameter();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos1;
}
} else {
result4 = null;
pos = pos1;
}
}
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_m_type() {
var result0;
result0 = parse_discrete_type();
if (result0 === null) {
result0 = parse_composite_type();
}
return result0;
}
function parse_discrete_type() {
var result0;
if (input.substr(pos, 4).toLowerCase() === "text") {
result0 = input.substr(pos, 4);
pos += 4;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"text\"");
}
}
if (result0 === null) {
if (input.substr(pos, 5).toLowerCase() === "image") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"image\"");
}
}
if (result0 === null) {
if (input.substr(pos, 5).toLowerCase() === "audio") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"audio\"");
}
}
if (result0 === null) {
if (input.substr(pos, 5).toLowerCase() === "video") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"video\"");
}
}
if (result0 === null) {
if (input.substr(pos, 11).toLowerCase() === "application") {
result0 = input.substr(pos, 11);
pos += 11;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"application\"");
}
}
if (result0 === null) {
result0 = parse_extension_token();
}
}
}
}
}
return result0;
}
function parse_composite_type() {
var result0;
if (input.substr(pos, 7).toLowerCase() === "message") {
result0 = input.substr(pos, 7);
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"message\"");
}
}
if (result0 === null) {
if (input.substr(pos, 9).toLowerCase() === "multipart") {
result0 = input.substr(pos, 9);
pos += 9;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"multipart\"");
}
}
if (result0 === null) {
result0 = parse_extension_token();
}
}
return result0;
}
function parse_extension_token() {
var result0;
result0 = parse_token();
if (result0 === null) {
result0 = parse_x_token();
}
return result0;
}
function parse_x_token() {
var result0, result1;
var pos0;
pos0 = pos;
if (input.substr(pos, 2).toLowerCase() === "x-") {
result0 = input.substr(pos, 2);
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"x-\"");
}
}
if (result0 !== null) {
result1 = parse_token();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_m_subtype() {
var result0;
result0 = parse_extension_token();
if (result0 === null) {
result0 = parse_token();
}
return result0;
}
function parse_m_parameter() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_m_value();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_m_value() {
var result0;
result0 = parse_token();
if (result0 === null) {
result0 = parse_quoted_string();
}
return result0;
}
function parse_CSeq() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_CSeq_value();
if (result0 !== null) {
result1 = parse_LWS();
if (result1 !== null) {
result2 = parse_Method();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_CSeq_value() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_DIGIT();
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_DIGIT();
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset, cseq_value) {
data.value=parseInt(cseq_value.join('')); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Expires() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_delta_seconds();
if (result0 !== null) {
result0 = (function(offset, expires) {data = expires; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Event() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_event_type();
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_generic_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_generic_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, event_type) {
data.event = event_type.join('').toLowerCase(); })(pos0, result0[0]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_event_type() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_token_nodot();
if (result0 !== null) {
result1 = [];
pos1 = pos;
if (input.charCodeAt(pos) === 46) {
result2 = ".";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result2 !== null) {
result3 = parse_token_nodot();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
if (input.charCodeAt(pos) === 46) {
result2 = ".";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result2 !== null) {
result3 = parse_token_nodot();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_From() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_SIP_URI_noparams();
if (result0 === null) {
result0 = parse_name_addr();
}
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_from_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_from_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
var tag = data.tag;
try {
data = new NameAddrHeader(data.uri, data.display_name, data.params);
if (tag) {data.setParam('tag',tag)}
} catch(e) {
data = -1;
}})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_from_param() {
var result0;
result0 = parse_tag_param();
if (result0 === null) {
result0 = parse_generic_param();
}
return result0;
}
function parse_tag_param() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 3).toLowerCase() === "tag") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"tag\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_token();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, tag) {data.tag = tag; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Max_Forwards() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_DIGIT();
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_DIGIT();
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset, forwards) {
data = parseInt(forwards.join('')); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Min_Expires() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_delta_seconds();
if (result0 !== null) {
result0 = (function(offset, min_expires) {data = min_expires; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Name_Addr_Header() {
var result0, result1, result2, result3, result4, result5, result6;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = [];
result1 = parse_display_name();
while (result1 !== null) {
result0.push(result1);
result1 = parse_display_name();
}
if (result0 !== null) {
result1 = parse_LAQUOT();
if (result1 !== null) {
result2 = parse_SIP_URI();
if (result2 !== null) {
result3 = parse_RAQUOT();
if (result3 !== null) {
result4 = [];
pos2 = pos;
result5 = parse_SEMI();
if (result5 !== null) {
result6 = parse_generic_param();
if (result6 !== null) {
result5 = [result5, result6];
} else {
result5 = null;
pos = pos2;
}
} else {
result5 = null;
pos = pos2;
}
while (result5 !== null) {
result4.push(result5);
pos2 = pos;
result5 = parse_SEMI();
if (result5 !== null) {
result6 = parse_generic_param();
if (result6 !== null) {
result5 = [result5, result6];
} else {
result5 = null;
pos = pos2;
}
} else {
result5 = null;
pos = pos2;
}
}
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
try {
data = new NameAddrHeader(data.uri, data.display_name, data.params);
} catch(e) {
data = -1;
}})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Proxy_Authenticate() {
var result0;
result0 = parse_challenge();
return result0;
}
function parse_challenge() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1;
pos0 = pos;
if (input.substr(pos, 6).toLowerCase() === "digest") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"Digest\"");
}
}
if (result0 !== null) {
result1 = parse_LWS();
if (result1 !== null) {
result2 = parse_digest_cln();
if (result2 !== null) {
result3 = [];
pos1 = pos;
result4 = parse_COMMA();
if (result4 !== null) {
result5 = parse_digest_cln();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos1;
}
} else {
result4 = null;
pos = pos1;
}
while (result4 !== null) {
result3.push(result4);
pos1 = pos;
result4 = parse_COMMA();
if (result4 !== null) {
result5 = parse_digest_cln();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos1;
}
} else {
result4 = null;
pos = pos1;
}
}
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
if (result0 === null) {
result0 = parse_other_challenge();
}
return result0;
}
function parse_other_challenge() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1;
pos0 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = parse_LWS();
if (result1 !== null) {
result2 = parse_auth_param();
if (result2 !== null) {
result3 = [];
pos1 = pos;
result4 = parse_COMMA();
if (result4 !== null) {
result5 = parse_auth_param();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos1;
}
} else {
result4 = null;
pos = pos1;
}
while (result4 !== null) {
result3.push(result4);
pos1 = pos;
result4 = parse_COMMA();
if (result4 !== null) {
result5 = parse_auth_param();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos1;
}
} else {
result4 = null;
pos = pos1;
}
}
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_auth_param() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_token();
if (result2 === null) {
result2 = parse_quoted_string();
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_digest_cln() {
var result0;
result0 = parse_realm();
if (result0 === null) {
result0 = parse_domain();
if (result0 === null) {
result0 = parse_nonce();
if (result0 === null) {
result0 = parse_opaque();
if (result0 === null) {
result0 = parse_stale();
if (result0 === null) {
result0 = parse_algorithm();
if (result0 === null) {
result0 = parse_qop_options();
if (result0 === null) {
result0 = parse_auth_param();
}
}
}
}
}
}
}
return result0;
}
function parse_realm() {
var result0, result1, result2;
var pos0;
pos0 = pos;
if (input.substr(pos, 5).toLowerCase() === "realm") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"realm\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_realm_value();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_realm_value() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_quoted_string_clean();
if (result0 !== null) {
result0 = (function(offset, realm) { data.realm = realm; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_domain() {
var result0, result1, result2, result3, result4, result5, result6;
var pos0, pos1;
pos0 = pos;
if (input.substr(pos, 6).toLowerCase() === "domain") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"domain\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_LDQUOT();
if (result2 !== null) {
result3 = parse_URI();
if (result3 !== null) {
result4 = [];
pos1 = pos;
result6 = parse_SP();
if (result6 !== null) {
result5 = [];
while (result6 !== null) {
result5.push(result6);
result6 = parse_SP();
}
} else {
result5 = null;
}
if (result5 !== null) {
result6 = parse_URI();
if (result6 !== null) {
result5 = [result5, result6];
} else {
result5 = null;
pos = pos1;
}
} else {
result5 = null;
pos = pos1;
}
while (result5 !== null) {
result4.push(result5);
pos1 = pos;
result6 = parse_SP();
if (result6 !== null) {
result5 = [];
while (result6 !== null) {
result5.push(result6);
result6 = parse_SP();
}
} else {
result5 = null;
}
if (result5 !== null) {
result6 = parse_URI();
if (result6 !== null) {
result5 = [result5, result6];
} else {
result5 = null;
pos = pos1;
}
} else {
result5 = null;
pos = pos1;
}
}
if (result4 !== null) {
result5 = parse_RDQUOT();
if (result5 !== null) {
result0 = [result0, result1, result2, result3, result4, result5];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_URI() {
var result0;
result0 = parse_absoluteURI();
if (result0 === null) {
result0 = parse_abs_path();
}
return result0;
}
function parse_nonce() {
var result0, result1, result2;
var pos0;
pos0 = pos;
if (input.substr(pos, 5).toLowerCase() === "nonce") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"nonce\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_nonce_value();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_nonce_value() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_quoted_string_clean();
if (result0 !== null) {
result0 = (function(offset, nonce) { data.nonce=nonce; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_opaque() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 6).toLowerCase() === "opaque") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"opaque\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_quoted_string_clean();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, opaque) { data.opaque=opaque; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_stale() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
if (input.substr(pos, 5).toLowerCase() === "stale") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"stale\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
pos1 = pos;
if (input.substr(pos, 4).toLowerCase() === "true") {
result2 = input.substr(pos, 4);
pos += 4;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"true\"");
}
}
if (result2 !== null) {
result2 = (function(offset) { data.stale=true; })(pos1);
}
if (result2 === null) {
pos = pos1;
}
if (result2 === null) {
pos1 = pos;
if (input.substr(pos, 5).toLowerCase() === "false") {
result2 = input.substr(pos, 5);
pos += 5;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"false\"");
}
}
if (result2 !== null) {
result2 = (function(offset) { data.stale=false; })(pos1);
}
if (result2 === null) {
pos = pos1;
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_algorithm() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 9).toLowerCase() === "algorithm") {
result0 = input.substr(pos, 9);
pos += 9;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"algorithm\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
if (input.substr(pos, 3).toLowerCase() === "md5") {
result2 = input.substr(pos, 3);
pos += 3;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"MD5\"");
}
}
if (result2 === null) {
if (input.substr(pos, 8).toLowerCase() === "md5-sess") {
result2 = input.substr(pos, 8);
pos += 8;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"MD5-sess\"");
}
}
if (result2 === null) {
result2 = parse_token();
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, algorithm) {
data.algorithm=algorithm.toUpperCase(); })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_qop_options() {
var result0, result1, result2, result3, result4, result5, result6;
var pos0, pos1, pos2;
pos0 = pos;
if (input.substr(pos, 3).toLowerCase() === "qop") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"qop\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_LDQUOT();
if (result2 !== null) {
pos1 = pos;
result3 = parse_qop_value();
if (result3 !== null) {
result4 = [];
pos2 = pos;
if (input.charCodeAt(pos) === 44) {
result5 = ",";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
if (result5 !== null) {
result6 = parse_qop_value();
if (result6 !== null) {
result5 = [result5, result6];
} else {
result5 = null;
pos = pos2;
}
} else {
result5 = null;
pos = pos2;
}
while (result5 !== null) {
result4.push(result5);
pos2 = pos;
if (input.charCodeAt(pos) === 44) {
result5 = ",";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
if (result5 !== null) {
result6 = parse_qop_value();
if (result6 !== null) {
result5 = [result5, result6];
} else {
result5 = null;
pos = pos2;
}
} else {
result5 = null;
pos = pos2;
}
}
if (result4 !== null) {
result3 = [result3, result4];
} else {
result3 = null;
pos = pos1;
}
} else {
result3 = null;
pos = pos1;
}
if (result3 !== null) {
result4 = parse_RDQUOT();
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_qop_value() {
var result0;
var pos0;
pos0 = pos;
if (input.substr(pos, 8).toLowerCase() === "auth-int") {
result0 = input.substr(pos, 8);
pos += 8;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"auth-int\"");
}
}
if (result0 === null) {
if (input.substr(pos, 4).toLowerCase() === "auth") {
result0 = input.substr(pos, 4);
pos += 4;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"auth\"");
}
}
if (result0 === null) {
result0 = parse_token();
}
}
if (result0 !== null) {
result0 = (function(offset, qop_value) {
data.qop || (data.qop=[]);
data.qop.push(qop_value.toLowerCase()); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Proxy_Require() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Record_Route() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_rec_route();
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_rec_route();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_rec_route();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
var idx, length;
length = data.multi_header.length;
for (idx = 0; idx < length; idx++) {
if (data.multi_header[idx].parsed === null) {
data = null;
break;
}
}
if (data !== null) {
data = data.multi_header;
} else {
data = -1;
}})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_rec_route() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_name_addr();
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_generic_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_generic_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
var header;
if(!data.multi_header) data.multi_header = [];
try {
header = new NameAddrHeader(data.uri, data.display_name, data.params);
delete data.uri;
delete data.display_name;
delete data.params;
} catch(e) {
header = null;
}
data.multi_header.push( { 'possition': pos,
'offset': offset,
'parsed': header
});})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Reason() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 3).toLowerCase() === "sip") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"SIP\"");
}
}
if (result0 === null) {
result0 = parse_token();
}
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_reason_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_reason_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, protocol) {
data.protocol = protocol.toLowerCase();
if (!data.params) data.params = {};
if (data.params.text && data.params.text[0] === '"') {
var text = data.params.text;
data.text = text.substring(1, text.length-1);
delete data.params.text;
}
})(pos0, result0[0]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_reason_param() {
var result0;
result0 = parse_reason_cause();
if (result0 === null) {
result0 = parse_generic_param();
}
return result0;
}
function parse_reason_cause() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 5).toLowerCase() === "cause") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"cause\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result3 = parse_DIGIT();
if (result3 !== null) {
result2 = [];
while (result3 !== null) {
result2.push(result3);
result3 = parse_DIGIT();
}
} else {
result2 = null;
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, cause) {
data.cause = parseInt(cause.join(''));
})(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Require() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Route() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_route_param();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_route_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_route_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_route_param() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_name_addr();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_generic_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_generic_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Subscription_State() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_substate_value();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_subexp_params();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_subexp_params();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_substate_value() {
var result0;
var pos0;
pos0 = pos;
if (input.substr(pos, 6).toLowerCase() === "active") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"active\"");
}
}
if (result0 === null) {
if (input.substr(pos, 7).toLowerCase() === "pending") {
result0 = input.substr(pos, 7);
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"pending\"");
}
}
if (result0 === null) {
if (input.substr(pos, 10).toLowerCase() === "terminated") {
result0 = input.substr(pos, 10);
pos += 10;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"terminated\"");
}
}
if (result0 === null) {
result0 = parse_token();
}
}
}
if (result0 !== null) {
result0 = (function(offset) {
data.state = input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_subexp_params() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 6).toLowerCase() === "reason") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"reason\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_event_reason_value();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, reason) {
if (typeof reason !== 'undefined') data.reason = reason; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 7).toLowerCase() === "expires") {
result0 = input.substr(pos, 7);
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"expires\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_delta_seconds();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, expires) {
if (typeof expires !== 'undefined') data.expires = expires; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 11).toLowerCase() === "retry_after") {
result0 = input.substr(pos, 11);
pos += 11;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"retry_after\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_delta_seconds();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, retry_after) {
if (typeof retry_after !== 'undefined') data.retry_after = retry_after; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
result0 = parse_generic_param();
}
}
}
return result0;
}
function parse_event_reason_value() {
var result0;
if (input.substr(pos, 11).toLowerCase() === "deactivated") {
result0 = input.substr(pos, 11);
pos += 11;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"deactivated\"");
}
}
if (result0 === null) {
if (input.substr(pos, 9).toLowerCase() === "probation") {
result0 = input.substr(pos, 9);
pos += 9;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"probation\"");
}
}
if (result0 === null) {
if (input.substr(pos, 8).toLowerCase() === "rejected") {
result0 = input.substr(pos, 8);
pos += 8;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"rejected\"");
}
}
if (result0 === null) {
if (input.substr(pos, 7).toLowerCase() === "timeout") {
result0 = input.substr(pos, 7);
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"timeout\"");
}
}
if (result0 === null) {
if (input.substr(pos, 6).toLowerCase() === "giveup") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"giveup\"");
}
}
if (result0 === null) {
if (input.substr(pos, 10).toLowerCase() === "noresource") {
result0 = input.substr(pos, 10);
pos += 10;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"noresource\"");
}
}
if (result0 === null) {
if (input.substr(pos, 9).toLowerCase() === "invariant") {
result0 = input.substr(pos, 9);
pos += 9;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"invariant\"");
}
}
if (result0 === null) {
result0 = parse_token();
}
}
}
}
}
}
}
return result0;
}
function parse_Subject() {
var result0;
result0 = parse_TEXT_UTF8_TRIM();
result0 = result0 !== null ? result0 : "";
return result0;
}
function parse_Supported() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
result0 = result0 !== null ? result0 : "";
return result0;
}
function parse_To() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_SIP_URI_noparams();
if (result0 === null) {
result0 = parse_name_addr();
}
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_to_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_to_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
var tag = data.tag;
try {
data = new NameAddrHeader(data.uri, data.display_name, data.params);
if (tag) {data.setParam('tag',tag)}
} catch(e) {
data = -1;
}})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_to_param() {
var result0;
result0 = parse_tag_param();
if (result0 === null) {
result0 = parse_generic_param();
}
return result0;
}
function parse_Via() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_via_param();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_via_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_via_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_via_param() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1;
pos0 = pos;
result0 = parse_sent_protocol();
if (result0 !== null) {
result1 = parse_LWS();
if (result1 !== null) {
result2 = parse_sent_by();
if (result2 !== null) {
result3 = [];
pos1 = pos;
result4 = parse_SEMI();
if (result4 !== null) {
result5 = parse_via_params();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos1;
}
} else {
result4 = null;
pos = pos1;
}
while (result4 !== null) {
result3.push(result4);
pos1 = pos;
result4 = parse_SEMI();
if (result4 !== null) {
result5 = parse_via_params();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos1;
}
} else {
result4 = null;
pos = pos1;
}
}
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_via_params() {
var result0;
result0 = parse_via_ttl();
if (result0 === null) {
result0 = parse_via_maddr();
if (result0 === null) {
result0 = parse_via_received();
if (result0 === null) {
result0 = parse_via_branch();
if (result0 === null) {
result0 = parse_response_port();
if (result0 === null) {
result0 = parse_generic_param();
}
}
}
}
}
return result0;
}
function parse_via_ttl() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 3).toLowerCase() === "ttl") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"ttl\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_ttl();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, via_ttl_value) {
data.ttl = via_ttl_value; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_via_maddr() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 5).toLowerCase() === "maddr") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"maddr\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_host();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, via_maddr) {
data.maddr = via_maddr; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_via_received() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 8).toLowerCase() === "received") {
result0 = input.substr(pos, 8);
pos += 8;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"received\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_IPv4address();
if (result2 === null) {
result2 = parse_IPv6address();
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, via_received) {
data.received = via_received; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_via_branch() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 6).toLowerCase() === "branch") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"branch\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_token();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, via_branch) {
data.branch = via_branch; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_response_port() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 5).toLowerCase() === "rport") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"rport\"");
}
}
if (result0 !== null) {
pos2 = pos;
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = [];
result3 = parse_DIGIT();
while (result3 !== null) {
result2.push(result3);
result3 = parse_DIGIT();
}
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
if(typeof response_port !== 'undefined')
data.rport = response_port.join(''); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_sent_protocol() {
var result0, result1, result2, result3, result4;
var pos0;
pos0 = pos;
result0 = parse_protocol_name();
if (result0 !== null) {
result1 = parse_SLASH();
if (result1 !== null) {
result2 = parse_token();
if (result2 !== null) {
result3 = parse_SLASH();
if (result3 !== null) {
result4 = parse_transport();
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_protocol_name() {
var result0;
var pos0;
pos0 = pos;
if (input.substr(pos, 3).toLowerCase() === "sip") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"SIP\"");
}
}
if (result0 === null) {
result0 = parse_token();
}
if (result0 !== null) {
result0 = (function(offset, via_protocol) {
data.protocol = via_protocol; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_transport() {
var result0;
var pos0;
pos0 = pos;
if (input.substr(pos, 3).toLowerCase() === "udp") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"UDP\"");
}
}
if (result0 === null) {
if (input.substr(pos, 3).toLowerCase() === "tcp") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"TCP\"");
}
}
if (result0 === null) {
if (input.substr(pos, 3).toLowerCase() === "tls") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"TLS\"");
}
}
if (result0 === null) {
if (input.substr(pos, 4).toLowerCase() === "sctp") {
result0 = input.substr(pos, 4);
pos += 4;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"SCTP\"");
}
}
if (result0 === null) {
result0 = parse_token();
}
}
}
}
if (result0 !== null) {
result0 = (function(offset, via_transport) {
data.transport = via_transport; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_sent_by() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
result0 = parse_via_host();
if (result0 !== null) {
pos1 = pos;
result1 = parse_COLON();
if (result1 !== null) {
result2 = parse_via_port();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos1;
}
} else {
result1 = null;
pos = pos1;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_via_host() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_IPv4address();
if (result0 === null) {
result0 = parse_IPv6reference();
if (result0 === null) {
result0 = parse_hostname();
}
}
if (result0 !== null) {
result0 = (function(offset) {
data.host = input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_via_port() {
var result0, result1, result2, result3, result4;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_DIGIT();
result0 = result0 !== null ? result0 : "";
if (result0 !== null) {
result1 = parse_DIGIT();
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result2 = parse_DIGIT();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result3 = parse_DIGIT();
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
result4 = parse_DIGIT();
result4 = result4 !== null ? result4 : "";
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, via_sent_by_port) {
data.port = parseInt(via_sent_by_port.join('')); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_ttl() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_DIGIT();
if (result0 !== null) {
result1 = parse_DIGIT();
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result2 = parse_DIGIT();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, ttl) {
return parseInt(ttl.join('')); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_WWW_Authenticate() {
var result0;
result0 = parse_challenge();
return result0;
}
function parse_Session_Expires() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_s_e_expires();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_s_e_params();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_s_e_params();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_s_e_expires() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_delta_seconds();
if (result0 !== null) {
result0 = (function(offset, expires) { data.expires = expires; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_s_e_params() {
var result0;
result0 = parse_s_e_refresher();
if (result0 === null) {
result0 = parse_generic_param();
}
return result0;
}
function parse_s_e_refresher() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 9).toLowerCase() === "refresher") {
result0 = input.substr(pos, 9);
pos += 9;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"refresher\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
if (input.substr(pos, 3).toLowerCase() === "uac") {
result2 = input.substr(pos, 3);
pos += 3;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"uac\"");
}
}
if (result2 === null) {
if (input.substr(pos, 3).toLowerCase() === "uas") {
result2 = input.substr(pos, 3);
pos += 3;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"uas\"");
}
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, s_e_refresher_value) { data.refresher = s_e_refresher_value.toLowerCase(); })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_extension_header() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = parse_HCOLON();
if (result1 !== null) {
result2 = parse_header_value();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_header_value() {
var result0, result1;
result0 = [];
result1 = parse_TEXT_UTF8char();
if (result1 === null) {
result1 = parse_UTF8_CONT();
if (result1 === null) {
result1 = parse_LWS();
}
}
while (result1 !== null) {
result0.push(result1);
result1 = parse_TEXT_UTF8char();
if (result1 === null) {
result1 = parse_UTF8_CONT();
if (result1 === null) {
result1 = parse_LWS();
}
}
}
return result0;
}
function parse_message_body() {
var result0, result1;
result0 = [];
result1 = parse_OCTET();
while (result1 !== null) {
result0.push(result1);
result1 = parse_OCTET();
}
return result0;
}
function parse_uuid_URI() {
var result0, result1;
var pos0;
pos0 = pos;
if (input.substr(pos, 5) === "uuid:") {
result0 = "uuid:";
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"uuid:\"");
}
}
if (result0 !== null) {
result1 = parse_uuid();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_uuid() {
var result0, result1, result2, result3, result4, result5, result6, result7, result8;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_hex8();
if (result0 !== null) {
if (input.charCodeAt(pos) === 45) {
result1 = "-";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result1 !== null) {
result2 = parse_hex4();
if (result2 !== null) {
if (input.charCodeAt(pos) === 45) {
result3 = "-";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result3 !== null) {
result4 = parse_hex4();
if (result4 !== null) {
if (input.charCodeAt(pos) === 45) {
result5 = "-";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result5 !== null) {
result6 = parse_hex4();
if (result6 !== null) {
if (input.charCodeAt(pos) === 45) {
result7 = "-";
pos++;
} else {
result7 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result7 !== null) {
result8 = parse_hex12();
if (result8 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, uuid) {
data = input.substring(pos+5, offset); })(pos0, result0[0]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_hex4() {
var result0, result1, result2, result3;
var pos0;
pos0 = pos;
result0 = parse_HEXDIG();
if (result0 !== null) {
result1 = parse_HEXDIG();
if (result1 !== null) {
result2 = parse_HEXDIG();
if (result2 !== null) {
result3 = parse_HEXDIG();
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_hex8() {
var result0, result1;
var pos0;
pos0 = pos;
result0 = parse_hex4();
if (result0 !== null) {
result1 = parse_hex4();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_hex12() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_hex4();
if (result0 !== null) {
result1 = parse_hex4();
if (result1 !== null) {
result2 = parse_hex4();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Refer_To() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_SIP_URI_noparams();
if (result0 === null) {
result0 = parse_name_addr();
}
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_generic_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_generic_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
try {
data = new NameAddrHeader(data.uri, data.display_name, data.params);
} catch(e) {
data = -1;
}})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Replaces() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_call_id();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_replaces_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_replaces_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_call_id() {
var result0, result1, result2;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_word();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 64) {
result1 = "@";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result1 !== null) {
result2 = parse_word();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
data.call_id = input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_replaces_param() {
var result0;
result0 = parse_to_tag();
if (result0 === null) {
result0 = parse_from_tag();
if (result0 === null) {
result0 = parse_early_flag();
if (result0 === null) {
result0 = parse_generic_param();
}
}
}
return result0;
}
function parse_to_tag() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 6) === "to-tag") {
result0 = "to-tag";
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"to-tag\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_token();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, to_tag) {
data.to_tag = to_tag; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_from_tag() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 8) === "from-tag") {
result0 = "from-tag";
pos += 8;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"from-tag\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_token();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, from_tag) {
data.from_tag = from_tag; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_early_flag() {
var result0;
var pos0;
pos0 = pos;
if (input.substr(pos, 10) === "early-only") {
result0 = "early-only";
pos += 10;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"early-only\"");
}
}
if (result0 !== null) {
result0 = (function(offset) {
data.early_only = true; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function cleanupExpected(expected) {
expected.sort();
var lastExpected = null;
var cleanExpected = [];
for (var i = 0; i < expected.length; i++) {
if (expected[i] !== lastExpected) {
cleanExpected.push(expected[i]);
lastExpected = expected[i];
}
}
return cleanExpected;
}
function computeErrorPosition() {
/*
* The first idea was to use |String.split| to break the input up to the
* error position along newlines and derive the line and column from
* there. However IE's |split| implementation is so broken that it was
* enough to prevent it.
*/
var line = 1;
var column = 1;
var seenCR = false;
for (var i = 0; i < Math.max(pos, rightmostFailuresPos); i++) {
var ch = input.charAt(i);
if (ch === "\n") {
if (!seenCR) { line++; }
column = 1;
seenCR = false;
} else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") {
line++;
column = 1;
seenCR = true;
} else {
column++;
seenCR = false;
}
}
return { line: line, column: column };
}
var URI = require('./URI');
var NameAddrHeader = require('./NameAddrHeader');
var data = {};
var result = parseFunctions[startRule]();
/*
* The parser is now in one of the following three states:
*
* 1. The parser successfully parsed the whole input.
*
* - |result !== null|
* - |pos === input.length|
* - |rightmostFailuresExpected| may or may not contain something
*
* 2. The parser successfully parsed only a part of the input.
*
* - |result !== null|
* - |pos < input.length|
* - |rightmostFailuresExpected| may or may not contain something
*
* 3. The parser did not successfully parse any part of the input.
*
* - |result === null|
* - |pos === 0|
* - |rightmostFailuresExpected| contains at least one failure
*
* All code following this comment (including called functions) must
* handle these states.
*/
if (result === null || pos !== input.length) {
var offset = Math.max(pos, rightmostFailuresPos);
var found = offset < input.length ? input.charAt(offset) : null;
var errorPosition = computeErrorPosition();
new this.SyntaxError(
cleanupExpected(rightmostFailuresExpected),
found,
offset,
errorPosition.line,
errorPosition.column
);
return -1;
}
return data;
},
/* Returns the parser source code. */
toSource: function() { return this._source; }
};
/* Thrown when a parser encounters a syntax error. */
result.SyntaxError = function(expected, found, offset, line, column) {
function buildMessage(expected, found) {
var expectedHumanized, foundHumanized;
switch (expected.length) {
case 0:
expectedHumanized = "end of input";
break;
case 1:
expectedHumanized = expected[0];
break;
default:
expectedHumanized = expected.slice(0, expected.length - 1).join(", ")
+ " or "
+ expected[expected.length - 1];
}
foundHumanized = found ? quote(found) : "end of input";
return "Expected " + expectedHumanized + " but " + foundHumanized + " found.";
}
this.name = "SyntaxError";
this.expected = expected;
this.found = found;
this.message = buildMessage(expected, found);
this.offset = offset;
this.line = line;
this.column = column;
};
result.SyntaxError.prototype = Error.prototype;
return result;
})();
},{"./NameAddrHeader":9,"./URI":24}],7:[function(require,module,exports){
/**
* Dependencies.
*/
var debug = require('debug')('JsSIP');
var adapter = require('webrtc-adapter');
var pkg = require('../package.json');
debug('version %s', pkg.version);
var C = require('./Constants');
var Exceptions = require('./Exceptions');
var Utils = require('./Utils');
var UA = require('./UA');
var URI = require('./URI');
var NameAddrHeader = require('./NameAddrHeader');
var Grammar = require('./Grammar');
var WebSocketInterface = require('./WebSocketInterface');
/**
* Expose the JsSIP module.
*/
var JsSIP = module.exports = {
C: C,
Exceptions: Exceptions,
Utils: Utils,
UA: UA,
URI: URI,
NameAddrHeader: NameAddrHeader,
WebSocketInterface: WebSocketInterface,
Grammar: Grammar,
// Expose the debug module.
debug: require('debug'),
// Expose the adapter module.
adapter: adapter
};
Object.defineProperties(JsSIP, {
name: {
get: function() { return pkg.title; }
},
version: {
get: function() { return pkg.version; }
}
});
},{"../package.json":50,"./Constants":1,"./Exceptions":5,"./Grammar":6,"./NameAddrHeader":9,"./UA":23,"./URI":24,"./Utils":25,"./WebSocketInterface":26,"debug":34,"webrtc-adapter":41}],8:[function(require,module,exports){
module.exports = Message;
/**
* Dependencies.
*/
var util = require('util');
var events = require('events');
var JsSIP_C = require('./Constants');
var SIPMessage = require('./SIPMessage');
var Utils = require('./Utils');
var RequestSender = require('./RequestSender');
var Transactions = require('./Transactions');
var Exceptions = require('./Exceptions');
function Message(ua) {
this.ua = ua;
// Custom message empty object for high level use
this.data = {};
events.EventEmitter.call(this);
}
util.inherits(Message, events.EventEmitter);
Message.prototype.send = function(target, body, options) {
var request_sender, event, contentType, eventHandlers, extraHeaders,
originalTarget = target;
if (target === undefined || body === undefined) {
throw new TypeError('Not enough arguments');
}
// Check target validity
target = this.ua.normalizeTarget(target);
if (!target) {
throw new TypeError('Invalid target: '+ originalTarget);
}
// Get call options
options = options || {};
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [];
eventHandlers = options.eventHandlers || {};
contentType = options.contentType || 'text/plain';
this.content_type = contentType;
// Set event handlers
for (event in eventHandlers) {
this.on(event, eventHandlers[event]);
}
this.closed = false;
this.ua.applicants[this] = this;
extraHeaders.push('Content-Type: '+ contentType);
this.request = new SIPMessage.OutgoingRequest(JsSIP_C.MESSAGE, target, this.ua, null, extraHeaders);
if(body) {
this.request.body = body;
this.content = body;
} else {
this.content = null;
}
request_sender = new RequestSender(this, this.ua);
this.newMessage('local', this.request);
request_sender.send();
};
Message.prototype.receiveResponse = function(response) {
var cause;
if(this.closed) {
return;
}
switch(true) {
case /^1[0-9]{2}$/.test(response.status_code):
// Ignore provisional responses.
break;
case /^2[0-9]{2}$/.test(response.status_code):
delete this.ua.applicants[this];
this.emit('succeeded', {
originator: 'remote',
response: response
});
break;
default:
delete this.ua.applicants[this];
cause = Utils.sipErrorCause(response.status_code);
this.emit('failed', {
originator: 'remote',
response: response,
cause: cause
});
break;
}
};
Message.prototype.onRequestTimeout = function() {
if(this.closed) {
return;
}
this.emit('failed', {
originator: 'system',
cause: JsSIP_C.causes.REQUEST_TIMEOUT
});
};
Message.prototype.onTransportError = function() {
if(this.closed) {
return;
}
this.emit('failed', {
originator: 'system',
cause: JsSIP_C.causes.CONNECTION_ERROR
});
};
Message.prototype.close = function() {
this.closed = true;
delete this.ua.applicants[this];
};
Message.prototype.init_incoming = function(request) {
var transaction;
this.request = request;
this.content_type = request.getHeader('Content-Type');
if (request.body) {
this.content = request.body;
} else {
this.content = null;
}
this.newMessage('remote', request);
transaction = this.ua.transactions.nist[request.via_branch];
if (transaction && (transaction.state === Transactions.C.STATUS_TRYING || transaction.state === Transactions.C.STATUS_PROCEEDING)) {
request.reply(200);
}
};
/**
* Accept the incoming Message
* Only valid for incoming Messages
*/
Message.prototype.accept = function(options) {
options = options || {};
var
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [],
body = options.body;
if (this.direction !== 'incoming') {
throw new Exceptions.NotSupportedError('"accept" not supported for outgoing Message');
}
this.request.reply(200, null, extraHeaders, body);
};
/**
* Reject the incoming Message
* Only valid for incoming Messages
*/
Message.prototype.reject = function(options) {
options = options || {};
var
status_code = options.status_code || 480,
reason_phrase = options.reason_phrase,
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [],
body = options.body;
if (this.direction !== 'incoming') {
throw new Exceptions.NotSupportedError('"reject" not supported for outgoing Message');
}
if (status_code < 300 || status_code >= 700) {
throw new TypeError('Invalid status_code: '+ status_code);
}
this.request.reply(status_code, reason_phrase, extraHeaders, body);
};
/**
* Internal Callbacks
*/
Message.prototype.newMessage = function(originator, request) {
if (originator === 'remote') {
this.direction = 'incoming';
this.local_identity = request.to;
this.remote_identity = request.from;
} else if (originator === 'local'){
this.direction = 'outgoing';
this.local_identity = request.from;
this.remote_identity = request.to;
}
this.ua.newMessage({
originator: originator,
message: this,
request: request
});
};
},{"./Constants":1,"./Exceptions":5,"./RequestSender":17,"./SIPMessage":18,"./Transactions":21,"./Utils":25,"events":28,"util":32}],9:[function(require,module,exports){
module.exports = NameAddrHeader;
/**
* Dependencies.
*/
var URI = require('./URI');
var Grammar = require('./Grammar');
function NameAddrHeader(uri, display_name, parameters) {
var param;
// Checks
if(!uri || !(uri instanceof URI)) {
throw new TypeError('missing or invalid "uri" parameter');
}
// Initialize parameters
this.uri = uri;
this.parameters = {};
for (param in parameters) {
this.setParam(param, parameters[param]);
}
Object.defineProperties(this, {
display_name: {
get: function() { return display_name; },
set: function(value) {
display_name = (value === 0) ? '0' : value;
}
}
});
}
NameAddrHeader.prototype = {
setParam: function(key, value) {
if (key) {
this.parameters[key.toLowerCase()] = (typeof value === 'undefined' || value === null) ? null : value.toString();
}
},
getParam: function(key) {
if(key) {
return this.parameters[key.toLowerCase()];
}
},
hasParam: function(key) {
if(key) {
return (this.parameters.hasOwnProperty(key.toLowerCase()) && true) || false;
}
},
deleteParam: function(parameter) {
var value;
parameter = parameter.toLowerCase();
if (this.parameters.hasOwnProperty(parameter)) {
value = this.parameters[parameter];
delete this.parameters[parameter];
return value;
}
},
clearParams: function() {
this.parameters = {};
},
clone: function() {
return new NameAddrHeader(
this.uri.clone(),
this.display_name,
JSON.parse(JSON.stringify(this.parameters)));
},
toString: function() {
var body, parameter;
body = (this.display_name || this.display_name === 0) ? '"' + this.display_name + '" ' : '';
body += '<' + this.uri.toString() + '>';
for (parameter in this.parameters) {
body += ';' + parameter;
if (this.parameters[parameter] !== null) {
body += '='+ this.parameters[parameter];
}
}
return body;
}
};
/**
* Parse the given string and returns a NameAddrHeader instance or undefined if
* it is an invalid NameAddrHeader.
*/
NameAddrHeader.parse = function(name_addr_header) {
name_addr_header = Grammar.parse(name_addr_header,'Name_Addr_Header');
if (name_addr_header !== -1) {
return name_addr_header;
} else {
return undefined;
}
};
},{"./Grammar":6,"./URI":24}],10:[function(require,module,exports){
var Parser = {};
module.exports = Parser;
/**
* Dependencies.
*/
var debugerror = require('debug')('JsSIP:ERROR:Parser');
debugerror.log = console.warn.bind(console);
var Grammar = require('./Grammar');
var SIPMessage = require('./SIPMessage');
/**
* Extract and parse every header of a SIP message.
*/
function getHeader(data, headerStart) {
var
// 'start' position of the header.
start = headerStart,
// 'end' position of the header.
end = 0,
// 'partial end' position of the header.
partialEnd = 0;
//End of message.
if (data.substring(start, start + 2).match(/(^\r\n)/)) {
return -2;
}
while(end === 0) {
// Partial End of Header.
partialEnd = data.indexOf('\r\n', start);
// 'indexOf' returns -1 if the value to be found never occurs.
if (partialEnd === -1) {
return partialEnd;
}
if(!data.substring(partialEnd + 2, partialEnd + 4).match(/(^\r\n)/) && data.charAt(partialEnd + 2).match(/(^\s+)/)) {
// Not the end of the message. Continue from the next position.
start = partialEnd + 2;
} else {
end = partialEnd;
}
}
return end;
}
function parseHeader(message, data, headerStart, headerEnd) {
var header, idx, length, parsed,
hcolonIndex = data.indexOf(':', headerStart),
headerName = data.substring(headerStart, hcolonIndex).trim(),
headerValue = data.substring(hcolonIndex + 1, headerEnd).trim();
// If header-field is well-known, parse it.
switch(headerName.toLowerCase()) {
case 'via':
case 'v':
message.addHeader('via', headerValue);
if(message.getHeaders('via').length === 1) {
parsed = message.parseHeader('Via');
if(parsed) {
message.via = parsed;
message.via_branch = parsed.branch;
}
} else {
parsed = 0;
}
break;
case 'from':
case 'f':
message.setHeader('from', headerValue);
parsed = message.parseHeader('from');
if(parsed) {
message.from = parsed;
message.from_tag = parsed.getParam('tag');
}
break;
case 'to':
case 't':
message.setHeader('to', headerValue);
parsed = message.parseHeader('to');
if(parsed) {
message.to = parsed;
message.to_tag = parsed.getParam('tag');
}
break;
case 'record-route':
parsed = Grammar.parse(headerValue, 'Record_Route');
if (parsed === -1) {
parsed = undefined;
} else {
length = parsed.length;
for (idx = 0; idx < length; idx++) {
header = parsed[idx];
message.addHeader('record-route', headerValue.substring(header.possition, header.offset));
message.headers['Record-Route'][message.getHeaders('record-route').length - 1].parsed = header.parsed;
}
}
break;
case 'call-id':
case 'i':
message.setHeader('call-id', headerValue);
parsed = message.parseHeader('call-id');
if(parsed) {
message.call_id = headerValue;
}
break;
case 'contact':
case 'm':
parsed = Grammar.parse(headerValue, 'Contact');
if (parsed === -1) {
parsed = undefined;
} else {
length = parsed.length;
for (idx = 0; idx < length; idx++) {
header = parsed[idx];
message.addHeader('contact', headerValue.substring(header.possition, header.offset));
message.headers.Contact[message.getHeaders('contact').length - 1].parsed = header.parsed;
}
}
break;
case 'content-length':
case 'l':
message.setHeader('content-length', headerValue);
parsed = message.parseHeader('content-length');
break;
case 'content-type':
case 'c':
message.setHeader('content-type', headerValue);
parsed = message.parseHeader('content-type');
break;
case 'cseq':
message.setHeader('cseq', headerValue);
parsed = message.parseHeader('cseq');
if(parsed) {
message.cseq = parsed.value;
}
if(message instanceof SIPMessage.IncomingResponse) {
message.method = parsed.method;
}
break;
case 'max-forwards':
message.setHeader('max-forwards', headerValue);
parsed = message.parseHeader('max-forwards');
break;
case 'www-authenticate':
message.setHeader('www-authenticate', headerValue);
parsed = message.parseHeader('www-authenticate');
break;
case 'proxy-authenticate':
message.setHeader('proxy-authenticate', headerValue);
parsed = message.parseHeader('proxy-authenticate');
break;
case 'session-expires':
case 'x':
message.setHeader('session-expires', headerValue);
parsed = message.parseHeader('session-expires');
if (parsed) {
message.session_expires = parsed.expires;
message.session_expires_refresher = parsed.refresher;
}
break;
case 'refer-to':
case 'r':
message.setHeader('refer-to', headerValue);
parsed = message.parseHeader('refer-to');
if(parsed) {
message.refer_to = parsed;
}
break;
case 'replaces':
message.setHeader('replaces', headerValue);
parsed = message.parseHeader('replaces');
if(parsed) {
message.replaces = parsed;
}
break;
case 'event':
case 'o':
message.setHeader('event', headerValue);
parsed = message.parseHeader('event');
if(parsed) {
message.event = parsed;
}
break;
default:
// Do not parse this header.
message.setHeader(headerName, headerValue);
parsed = 0;
}
if (parsed === undefined) {
return {
error: 'error parsing header "'+ headerName +'"'
};
} else {
return true;
}
}
/**
* Parse SIP Message
*/
Parser.parseMessage = function(data, ua) {
var message, firstLine, contentLength, bodyStart, parsed,
headerStart = 0,
headerEnd = data.indexOf('\r\n');
if(headerEnd === -1) {
debugerror('parseMessage() | no CRLF found, not a SIP message');
return;
}
// Parse first line. Check if it is a Request or a Reply.
firstLine = data.substring(0, headerEnd);
parsed = Grammar.parse(firstLine, 'Request_Response');
if(parsed === -1) {
debugerror('parseMessage() | error parsing first line of SIP message: "' + firstLine + '"');
return;
} else if(!parsed.status_code) {
message = new SIPMessage.IncomingRequest(ua);
message.method = parsed.method;
message.ruri = parsed.uri;
} else {
message = new SIPMessage.IncomingResponse();
message.status_code = parsed.status_code;
message.reason_phrase = parsed.reason_phrase;
}
message.data = data;
headerStart = headerEnd + 2;
/* Loop over every line in data. Detect the end of each header and parse
* it or simply add to the headers collection.
*/
while(true) {
headerEnd = getHeader(data, headerStart);
// The SIP message has normally finished.
if(headerEnd === -2) {
bodyStart = headerStart + 2;
break;
}
// data.indexOf returned -1 due to a malformed message.
else if(headerEnd === -1) {
debugerror('parseMessage() | malformed message');
return;
}
parsed = parseHeader(message, data, headerStart, headerEnd);
if(parsed !== true) {
debugerror('parseMessage() |', parsed.error);
return;
}
headerStart = headerEnd + 2;
}
/* RFC3261 18.3.
* If there are additional bytes in the transport packet
* beyond the end of the body, they MUST be discarded.
*/
if(message.hasHeader('content-length')) {
contentLength = message.getHeader('content-length');
message.body = data.substr(bodyStart, contentLength);
} else {
message.body = data.substring(bodyStart);
}
return message;
};
},{"./Grammar":6,"./SIPMessage":18,"debug":34}],11:[function(require,module,exports){
/* globals RTCPeerConnection: false, RTCSessionDescription: false */
module.exports = RTCSession;
var C = {
// RTCSession states
STATUS_NULL: 0,
STATUS_INVITE_SENT: 1,
STATUS_1XX_RECEIVED: 2,
STATUS_INVITE_RECEIVED: 3,
STATUS_WAITING_FOR_ANSWER: 4,
STATUS_ANSWERED: 5,
STATUS_WAITING_FOR_ACK: 6,
STATUS_CANCELED: 7,
STATUS_TERMINATED: 8,
STATUS_CONFIRMED: 9
};
/**
* Expose C object.
*/
RTCSession.C = C;
/**
* Dependencies.
*/
var util = require('util');
var events = require('events');
var debug = require('debug')('JsSIP:RTCSession');
var debugerror = require('debug')('JsSIP:ERROR:RTCSession');
debugerror.log = console.warn.bind(console);
var sdp_transform = require('sdp-transform');
var JsSIP_C = require('./Constants');
var Exceptions = require('./Exceptions');
var Transactions = require('./Transactions');
var Utils = require('./Utils');
var Timers = require('./Timers');
var SIPMessage = require('./SIPMessage');
var Dialog = require('./Dialog');
var RequestSender = require('./RequestSender');
var RTCSession_Request = require('./RTCSession/Request');
var RTCSession_DTMF = require('./RTCSession/DTMF');
var RTCSession_ReferNotifier = require('./RTCSession/ReferNotifier');
var RTCSession_ReferSubscriber = require('./RTCSession/ReferSubscriber');
/**
* Local variables.
*/
var holdMediaTypes = ['audio', 'video'];
function RTCSession(ua) {
debug('new');
this.ua = ua;
this.status = C.STATUS_NULL;
this.dialog = null;
this.earlyDialogs = {};
this.connection = null; // The RTCPeerConnection instance (public attribute).
// RTCSession confirmation flag
this.is_confirmed = false;
// is late SDP being negotiated
this.late_sdp = false;
// Default rtcOfferConstraints and rtcAnswerConstrainsts (passed in connect() or answer()).
this.rtcOfferConstraints = null;
this.rtcAnswerConstraints = null;
// Local MediaStream.
this.localMediaStream = null;
this.localMediaStreamLocallyGenerated = false;
// Flag to indicate PeerConnection ready for new actions.
this.rtcReady = true;
// SIP Timers
this.timers = {
ackTimer: null,
expiresTimer: null,
invite2xxTimer: null,
userNoAnswerTimer: null
};
// Session info
this.direction = null;
this.local_identity = null;
this.remote_identity = null;
this.start_time = null;
this.end_time = null;
this.tones = null;
// Mute/Hold state
this.audioMuted = false;
this.videoMuted = false;
this.localHold = false;
this.remoteHold = false;
// Session Timers (RFC 4028)
this.sessionTimers = {
enabled: this.ua.configuration.session_timers,
defaultExpires: JsSIP_C.SESSION_EXPIRES,
currentExpires: null,
running: false,
refresher: false,
timer: null // A setTimeout.
};
// Map of ReferSubscriber instances indexed by the REFER's CSeq number
this.referSubscribers = {};
// Custom session empty object for high level use
this.data = {};
// Expose session failed/ended causes as a property of the RTCSession instance
this.causes = JsSIP_C.causes;
events.EventEmitter.call(this);
}
util.inherits(RTCSession, events.EventEmitter);
/**
* User API
*/
RTCSession.prototype.isInProgress = function() {
switch(this.status) {
case C.STATUS_NULL:
case C.STATUS_INVITE_SENT:
case C.STATUS_1XX_RECEIVED:
case C.STATUS_INVITE_RECEIVED:
case C.STATUS_WAITING_FOR_ANSWER:
return true;
default:
return false;
}
};
RTCSession.prototype.isEstablished = function() {
switch(this.status) {
case C.STATUS_ANSWERED:
case C.STATUS_WAITING_FOR_ACK:
case C.STATUS_CONFIRMED:
return true;
default:
return false;
}
};
RTCSession.prototype.isEnded = function() {
switch(this.status) {
case C.STATUS_CANCELED:
case C.STATUS_TERMINATED:
return true;
default:
return false;
}
};
RTCSession.prototype.isMuted = function() {
return {
audio: this.audioMuted,
video: this.videoMuted
};
};
RTCSession.prototype.isOnHold = function() {
return {
local: this.localHold,
remote: this.remoteHold
};
};
/**
* Check if RTCSession is ready for an outgoing re-INVITE or UPDATE with SDP.
*/
RTCSession.prototype.isReadyToReOffer = function() {
if (! this.rtcReady) {
debug('isReadyToReOffer() | internal WebRTC status not ready');
return false;
}
// No established yet.
if (! this.dialog) {
debug('isReadyToReOffer() | session not established yet');
return false;
}
// Another INVITE transaction is in progress
if (this.dialog.uac_pending_reply === true || this.dialog.uas_pending_reply === true) {
debug('isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress');
return false;
}
return true;
};
RTCSession.prototype.connect = function(target, options, initCallback) {
debug('connect()');
options = options || {};
var event, requestParams,
originalTarget = target,
eventHandlers = options.eventHandlers || {},
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [],
mediaConstraints = options.mediaConstraints || {audio: true, video: true},
mediaStream = options.mediaStream || null,
pcConfig = options.pcConfig || {iceServers:[]},
rtcConstraints = options.rtcConstraints || null,
rtcOfferConstraints = options.rtcOfferConstraints || null;
this.rtcOfferConstraints = rtcOfferConstraints;
this.rtcAnswerConstraints = options.rtcAnswerConstraints || null;
// Session Timers.
if (this.sessionTimers.enabled) {
if (Utils.isDecimal(options.sessionTimersExpires)) {
if (options.sessionTimersExpires >= JsSIP_C.MIN_SESSION_EXPIRES) {
this.sessionTimers.defaultExpires = options.sessionTimersExpires;
}
else {
this.sessionTimers.defaultExpires = JsSIP_C.SESSION_EXPIRES;
}
}
}
this.data = options.data || this.data;
if (target === undefined) {
throw new TypeError('Not enough arguments');
}
// Check WebRTC support.
if (!window.RTCPeerConnection) {
throw new Exceptions.NotSupportedError('WebRTC not supported');
}
// Check target validity
target = this.ua.normalizeTarget(target);
if (!target) {
throw new TypeError('Invalid target: '+ originalTarget);
}
// Check Session Status
if (this.status !== C.STATUS_NULL) {
throw new Exceptions.InvalidStateError(this.status);
}
// Set event handlers
for (event in eventHandlers) {
this.on(event, eventHandlers[event]);
}
// Session parameter initialization
this.from_tag = Utils.newTag();
// Set anonymous property
this.anonymous = options.anonymous || false;
// OutgoingSession specific parameters
this.isCanceled = false;
requestParams = {from_tag: this.from_tag};
this.contact = this.ua.contact.toString({
anonymous: this.anonymous,
outbound: true
});
if (this.anonymous) {
requestParams.from_display_name = 'Anonymous';
requestParams.from_uri = 'sip:anonymous@anonymous.invalid';
extraHeaders.push('P-Preferred-Identity: '+ this.ua.configuration.uri.toString());
extraHeaders.push('Privacy: id');
}
extraHeaders.push('Contact: '+ this.contact);
extraHeaders.push('Content-Type: application/sdp');
if (this.sessionTimers.enabled) {
extraHeaders.push('Session-Expires: ' + this.sessionTimers.defaultExpires);
}
this.request = new SIPMessage.OutgoingRequest(JsSIP_C.INVITE, target, this.ua, requestParams, extraHeaders);
this.id = this.request.call_id + this.from_tag;
// Create a new RTCPeerConnection instance.
createRTCConnection.call(this, pcConfig, rtcConstraints);
// Save the session into the ua sessions collection.
this.ua.sessions[this.id] = this;
// Set internal properties
this.direction = 'outgoing';
this.local_identity = this.request.from;
this.remote_identity = this.request.to;
// User explicitly provided a newRTCSession callback for this session
if (initCallback) {
initCallback(this);
} else {
newRTCSession.call(this, 'local', this.request);
}
sendInitialRequest.call(this, mediaConstraints, rtcOfferConstraints, mediaStream);
};
RTCSession.prototype.init_incoming = function(request, initCallback) {
debug('init_incoming()');
var expires,
self = this,
contentType = request.getHeader('Content-Type');
// Check body and content type
if (request.body && (contentType !== 'application/sdp')) {
request.reply(415);
return;
}
// Session parameter initialization
this.status = C.STATUS_INVITE_RECEIVED;
this.from_tag = request.from_tag;
this.id = request.call_id + this.from_tag;
this.request = request;
this.contact = this.ua.contact.toString();
// Save the session into the ua sessions collection.
this.ua.sessions[this.id] = this;
// Get the Expires header value if exists
if (request.hasHeader('expires')) {
expires = request.getHeader('expires') * 1000;
}
/* Set the to_tag before
* replying a response code that will create a dialog.
*/
request.to_tag = Utils.newTag();
// An error on dialog creation will fire 'failed' event
if (! createDialog.call(this, request, 'UAS', true)) {
request.reply(500, 'Missing Contact header field');
return;
}
if (request.body) {
this.late_sdp = false;
}
else {
this.late_sdp = true;
}
this.status = C.STATUS_WAITING_FOR_ANSWER;
// Set userNoAnswerTimer
this.timers.userNoAnswerTimer = setTimeout(function() {
request.reply(408);
failed.call(self, 'local',null, JsSIP_C.causes.NO_ANSWER);
}, this.ua.configuration.no_answer_timeout
);
/* Set expiresTimer
* RFC3261 13.3.1
*/
if (expires) {
this.timers.expiresTimer = setTimeout(function() {
if(self.status === C.STATUS_WAITING_FOR_ANSWER) {
request.reply(487);
failed.call(self, 'system', null, JsSIP_C.causes.EXPIRES);
}
}, expires
);
}
// Set internal properties
this.direction = 'incoming';
this.local_identity = request.to;
this.remote_identity = request.from;
// A init callback was specifically defined
if (initCallback) {
initCallback(this);
// Fire 'newRTCSession' event.
} else {
newRTCSession.call(this, 'remote', request);
}
// The user may have rejected the call in the 'newRTCSession' event.
if (this.status === C.STATUS_TERMINATED) {
return;
}
// Reply 180.
request.reply(180, null, ['Contact: ' + self.contact]);
// Fire 'progress' event.
// TODO: Document that 'response' field in 'progress' event is null for
// incoming calls.
progress.call(self, 'local', null);
};
/**
* Answer the call.
*/
RTCSession.prototype.answer = function(options) {
debug('answer()');
options = options || {};
var idx, length, sdp, tracks,
peerHasAudioLine = false,
peerHasVideoLine = false,
peerOffersFullAudio = false,
peerOffersFullVideo = false,
self = this,
request = this.request,
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [],
mediaConstraints = options.mediaConstraints || {},
mediaStream = options.mediaStream || null,
pcConfig = options.pcConfig || {iceServers:[]},
rtcConstraints = options.rtcConstraints || null,
rtcAnswerConstraints = options.rtcAnswerConstraints || null;
this.rtcAnswerConstraints = rtcAnswerConstraints;
this.rtcOfferConstraints = options.rtcOfferConstraints || null;
// Session Timers.
if (this.sessionTimers.enabled) {
if (Utils.isDecimal(options.sessionTimersExpires)) {
if (options.sessionTimersExpires >= JsSIP_C.MIN_SESSION_EXPIRES) {
this.sessionTimers.defaultExpires = options.sessionTimersExpires;
}
else {
this.sessionTimers.defaultExpires = JsSIP_C.SESSION_EXPIRES;
}
}
}
this.data = options.data || this.data;
// Check Session Direction and Status
if (this.direction !== 'incoming') {
throw new Exceptions.NotSupportedError('"answer" not supported for outgoing RTCSession');
} else if (this.status !== C.STATUS_WAITING_FOR_ANSWER) {
throw new Exceptions.InvalidStateError(this.status);
}
this.status = C.STATUS_ANSWERED;
// An error on dialog creation will fire 'failed' event
if (! createDialog.call(this, request, 'UAS')) {
request.reply(500, 'Error creating dialog');
return;
}
clearTimeout(this.timers.userNoAnswerTimer);
extraHeaders.unshift('Contact: ' + self.contact);
// Determine incoming media from incoming SDP offer (if any).
sdp = request.parseSDP();
// Make sure sdp.media is an array, not the case if there is only one media
if (! Array.isArray(sdp.media)) {
sdp.media = [sdp.media];
}
// Go through all medias in SDP to find offered capabilities to answer with
idx = sdp.media.length;
while(idx--) {
var m = sdp.media[idx];
if (m.type === 'audio') {
peerHasAudioLine = true;
if (!m.direction || m.direction === 'sendrecv') {
peerOffersFullAudio = true;
}
}
if (m.type === 'video') {
peerHasVideoLine = true;
if (!m.direction || m.direction === 'sendrecv') {
peerOffersFullVideo = true;
}
}
}
// Remove audio from mediaStream if suggested by mediaConstraints
if (mediaStream && mediaConstraints.audio === false) {
tracks = mediaStream.getAudioTracks();
length = tracks.length;
for (idx=0; idx<length; idx++) {
mediaStream.removeTrack(tracks[idx]);
}
}
// Remove video from mediaStream if suggested by mediaConstraints
if (mediaStream && mediaConstraints.video === false) {
tracks = mediaStream.getVideoTracks();
length = tracks.length;
for (idx=0; idx<length; idx++) {
mediaStream.removeTrack(tracks[idx]);
}
}
// Set audio constraints based on incoming stream if not supplied
if (!mediaStream && mediaConstraints.audio === undefined) {
mediaConstraints.audio = peerOffersFullAudio;
}
// Set video constraints based on incoming stream if not supplied
if (!mediaStream && mediaConstraints.video === undefined) {
mediaConstraints.video = peerOffersFullVideo;
}
// Don't ask for audio if the incoming offer has no audio section
if (!mediaStream && !peerHasAudioLine) {
mediaConstraints.audio = false;
}
// Don't ask for video if the incoming offer has no video section
if (!mediaStream && !peerHasVideoLine) {
mediaConstraints.video = false;
}
// Create a new RTCPeerConnection instance.
// TODO: This may throw an error, should react.
createRTCConnection.call(this, pcConfig, rtcConstraints);
// If a local MediaStream is given use it.
if (mediaStream) {
userMediaSucceeded(mediaStream);
// If at least audio or video is requested prompt getUserMedia.
} else if (mediaConstraints.audio || mediaConstraints.video) {
self.localMediaStreamLocallyGenerated = true;
navigator.mediaDevices.getUserMedia(mediaConstraints)
.then(userMediaSucceeded)
.catch(function(error) {
userMediaFailed(error);
self.emit('getusermediafailed', error);
});
// Otherwise don't prompt getUserMedia.
} else {
userMediaSucceeded(null);
}
// User media succeeded
function userMediaSucceeded(stream) {
if (self.status === C.STATUS_TERMINATED) { return; }
self.localMediaStream = stream;
if (stream) {
self.connection.addStream(stream);
}
// If it's an incoming INVITE without SDP notify the app with the
// RTCPeerConnection so it can do stuff on it before generating the offer.
if (! self.request.body) {
self.emit('peerconnection', {
peerconnection: self.connection
});
}
if (! self.late_sdp) {
var e = {originator:'remote', type:'offer', sdp:request.body};
var offer = new RTCSessionDescription({type:'offer', sdp:e.sdp});
self.emit('sdp', e);
self.connection.setRemoteDescription(offer)
.then(remoteDescriptionSucceededOrNotNeeded)
.catch(function(error) {
request.reply(488);
failed.call(self, 'system', null, JsSIP_C.causes.WEBRTC_ERROR);
self.emit('peerconnection:setremotedescriptionfailed', error);
});
}
else {
remoteDescriptionSucceededOrNotNeeded();
}
}
// User media failed
function userMediaFailed() {
if (self.status === C.STATUS_TERMINATED) { return; }
request.reply(480);
failed.call(self, 'local', null, JsSIP_C.causes.USER_DENIED_MEDIA_ACCESS);
}
function remoteDescriptionSucceededOrNotNeeded() {
connecting.call(self, request);
if (! self.late_sdp) {
createLocalDescription.call(self, 'answer', rtcSucceeded, rtcFailed, rtcAnswerConstraints);
} else {
createLocalDescription.call(self, 'offer', rtcSucceeded, rtcFailed, self.rtcOfferConstraints);
}
}
function rtcSucceeded(desc) {
if (self.status === C.STATUS_TERMINATED) { return; }
// run for reply success callback
function replySucceeded() {
self.status = C.STATUS_WAITING_FOR_ACK;
setInvite2xxTimer.call(self, request, desc);
setACKTimer.call(self);
accepted.call(self, 'local');
}
// run for reply failure callback
function replyFailed() {
failed.call(self, 'system', null, JsSIP_C.causes.CONNECTION_ERROR);
}
handleSessionTimersInIncomingRequest.call(self, request, extraHeaders);
request.reply(200, null, extraHeaders,
desc,
replySucceeded,
replyFailed
);
}
function rtcFailed() {
if (self.status === C.STATUS_TERMINATED) { return; }
request.reply(500);
failed.call(self, 'system', null, JsSIP_C.causes.WEBRTC_ERROR);
}
};
/**
* Terminate the call.
*/
RTCSession.prototype.terminate = function(options) {
debug('terminate()');
options = options || {};
var cancel_reason, dialog,
cause = options.cause || JsSIP_C.causes.BYE,
status_code = options.status_code,
reason_phrase = options.reason_phrase,
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [],
body = options.body,
self = this;
// Check Session Status
if (this.status === C.STATUS_TERMINATED) {
throw new Exceptions.InvalidStateError(this.status);
}
switch(this.status) {
// - UAC -
case C.STATUS_NULL:
case C.STATUS_INVITE_SENT:
case C.STATUS_1XX_RECEIVED:
debug('canceling session');
if (status_code && (status_code < 200 || status_code >= 700)) {
throw new TypeError('Invalid status_code: '+ status_code);
} else if (status_code) {
reason_phrase = reason_phrase || JsSIP_C.REASON_PHRASE[status_code] || '';
cancel_reason = 'SIP ;cause=' + status_code + ' ;text="' + reason_phrase + '"';
}
// Check Session Status
if (this.status === C.STATUS_NULL) {
this.isCanceled = true;
this.cancelReason = cancel_reason;
} else if (this.status === C.STATUS_INVITE_SENT) {
this.isCanceled = true;
this.cancelReason = cancel_reason;
} else if(this.status === C.STATUS_1XX_RECEIVED) {
this.request.cancel(cancel_reason);
}
this.status = C.STATUS_CANCELED;
failed.call(this, 'local', null, JsSIP_C.causes.CANCELED);
break;
// - UAS -
case C.STATUS_WAITING_FOR_ANSWER:
case C.STATUS_ANSWERED:
debug('rejecting session');
status_code = status_code || 480;
if (status_code < 300 || status_code >= 700) {
throw new TypeError('Invalid status_code: '+ status_code);
}
this.request.reply(status_code, reason_phrase, extraHeaders, body);
failed.call(this, 'local', null, JsSIP_C.causes.REJECTED);
break;
case C.STATUS_WAITING_FOR_ACK:
case C.STATUS_CONFIRMED:
debug('terminating session');
reason_phrase = options.reason_phrase || JsSIP_C.REASON_PHRASE[status_code] || '';
if (status_code && (status_code < 200 || status_code >= 700)) {
throw new TypeError('Invalid status_code: '+ status_code);
} else if (status_code) {
extraHeaders.push('Reason: SIP ;cause=' + status_code + '; text="' + reason_phrase + '"');
}
/* RFC 3261 section 15 (Terminating a session):
*
* "...the callee's UA MUST NOT send a BYE on a confirmed dialog
* until it has received an ACK for its 2xx response or until the server
* transaction times out."
*/
if (this.status === C.STATUS_WAITING_FOR_ACK &&
this.direction === 'incoming' &&
this.request.server_transaction.state !== Transactions.C.STATUS_TERMINATED) {
// Save the dialog for later restoration
dialog = this.dialog;
// Send the BYE as soon as the ACK is received...
this.receiveRequest = function(request) {
if(request.method === JsSIP_C.ACK) {
sendRequest.call(this, JsSIP_C.BYE, {
extraHeaders: extraHeaders,
body: body
});
dialog.terminate();
}
};
// .., or when the INVITE transaction times out
this.request.server_transaction.on('stateChanged', function(){
if (this.state === Transactions.C.STATUS_TERMINATED) {
sendRequest.call(self, JsSIP_C.BYE, {
extraHeaders: extraHeaders,
body: body
});
dialog.terminate();
}
});
ended.call(this, 'local', null, cause);
// Restore the dialog into 'this' in order to be able to send the in-dialog BYE :-)
this.dialog = dialog;
// Restore the dialog into 'ua' so the ACK can reach 'this' session
this.ua.dialogs[dialog.id.toString()] = dialog;
} else {
sendRequest.call(this, JsSIP_C.BYE, {
extraHeaders: extraHeaders,
body: body
});
ended.call(this, 'local', null, cause);
}
}
};
RTCSession.prototype.close = function() {
debug('close()');
var idx;
if (this.status === C.STATUS_TERMINATED) {
return;
}
// Terminate RTC.
if (this.connection) {
try {
this.connection.close();
} catch(error) {
debugerror('close() | error closing the RTCPeerConnection: %o', error);
}
}
// Close local MediaStream if it was not given by the user.
if (this.localMediaStream && this.localMediaStreamLocallyGenerated) {
debug('close() | closing local MediaStream');
Utils.closeMediaStream(this.localMediaStream);
}
// Terminate signaling.
// Clear SIP timers
for(idx in this.timers) {
clearTimeout(this.timers[idx]);
}
// Clear Session Timers.
clearTimeout(this.sessionTimers.timer);
// Terminate confirmed dialog
if (this.dialog) {
this.dialog.terminate();
delete this.dialog;
}
// Terminate early dialogs
for(idx in this.earlyDialogs) {
this.earlyDialogs[idx].terminate();
delete this.earlyDialogs[idx];
}
this.status = C.STATUS_TERMINATED;
delete this.ua.sessions[this.id];
};
RTCSession.prototype.sendDTMF = function(tones, options) {
debug('sendDTMF() | tones: %s', tones);
var duration, interToneGap,
position = 0,
self = this;
options = options || {};
duration = options.duration || null;
interToneGap = options.interToneGap || null;
if (tones === undefined) {
throw new TypeError('Not enough arguments');
}
// Check Session Status
if (this.status !== C.STATUS_CONFIRMED && this.status !== C.STATUS_WAITING_FOR_ACK) {
throw new Exceptions.InvalidStateError(this.status);
}
// Convert to string
if(typeof tones === 'number') {
tones = tones.toString();
}
// Check tones
if (!tones || typeof tones !== 'string' || !tones.match(/^[0-9A-DR#*,]+$/i)) {
throw new TypeError('Invalid tones: '+ tones);
}
// Check duration
if (duration && !Utils.isDecimal(duration)) {
throw new TypeError('Invalid tone duration: '+ duration);
} else if (!duration) {
duration = RTCSession_DTMF.C.DEFAULT_DURATION;
} else if (duration < RTCSession_DTMF.C.MIN_DURATION) {
debug('"duration" value is lower than the minimum allowed, setting it to '+ RTCSession_DTMF.C.MIN_DURATION+ ' milliseconds');
duration = RTCSession_DTMF.C.MIN_DURATION;
} else if (duration > RTCSession_DTMF.C.MAX_DURATION) {
debug('"duration" value is greater than the maximum allowed, setting it to '+ RTCSession_DTMF.C.MAX_DURATION +' milliseconds');
duration = RTCSession_DTMF.C.MAX_DURATION;
} else {
duration = Math.abs(duration);
}
options.duration = duration;
// Check interToneGap
if (interToneGap && !Utils.isDecimal(interToneGap)) {
throw new TypeError('Invalid interToneGap: '+ interToneGap);
} else if (!interToneGap) {
interToneGap = RTCSession_DTMF.C.DEFAULT_INTER_TONE_GAP;
} else if (interToneGap < RTCSession_DTMF.C.MIN_INTER_TONE_GAP) {
debug('"interToneGap" value is lower than the minimum allowed, setting it to '+ RTCSession_DTMF.C.MIN_INTER_TONE_GAP +' milliseconds');
interToneGap = RTCSession_DTMF.C.MIN_INTER_TONE_GAP;
} else {
interToneGap = Math.abs(interToneGap);
}
if (this.tones) {
// Tones are already queued, just add to the queue
this.tones += tones;
return;
}
this.tones = tones;
// Send the first tone
_sendDTMF();
function _sendDTMF() {
var tone, timeout;
if (self.status === C.STATUS_TERMINATED || !self.tones || position >= self.tones.length) {
// Stop sending DTMF
self.tones = null;
return;
}
tone = self.tones[position];
position += 1;
if (tone === ',') {
timeout = 2000;
} else {
var dtmf = new RTCSession_DTMF(self);
options.eventHandlers = {
onFailed: function() { self.tones = null; }
};
dtmf.send(tone, options);
timeout = duration + interToneGap;
}
// Set timeout for the next tone
setTimeout(_sendDTMF, timeout);
}
};
/**
* Mute
*/
RTCSession.prototype.mute = function(options) {
debug('mute()');
options = options || {audio:true, video:false};
var
audioMuted = false,
videoMuted = false;
if (this.audioMuted === false && options.audio) {
audioMuted = true;
this.audioMuted = true;
toogleMuteAudio.call(this, true);
}
if (this.videoMuted === false && options.video) {
videoMuted = true;
this.videoMuted = true;
toogleMuteVideo.call(this, true);
}
if (audioMuted === true || videoMuted === true) {
onmute.call(this, {
audio: audioMuted,
video: videoMuted
});
}
};
/**
* Unmute
*/
RTCSession.prototype.unmute = function(options) {
debug('unmute()');
options = options || {audio:true, video:true};
var
audioUnMuted = false,
videoUnMuted = false;
if (this.audioMuted === true && options.audio) {
audioUnMuted = true;
this.audioMuted = false;
if (this.localHold === false) {
toogleMuteAudio.call(this, false);
}
}
if (this.videoMuted === true && options.video) {
videoUnMuted = true;
this.videoMuted = false;
if (this.localHold === false) {
toogleMuteVideo.call(this, false);
}
}
if (audioUnMuted === true || videoUnMuted === true) {
onunmute.call(this, {
audio: audioUnMuted,
video: videoUnMuted
});
}
};
/**
* Hold
*/
RTCSession.prototype.hold = function(options, done) {
debug('hold()');
options = options || {};
var self = this,
eventHandlers;
if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) {
return false;
}
if (this.localHold === true) {
return false;
}
if (! this.isReadyToReOffer()) {
return false;
}
this.localHold = true;
onhold.call(this, 'local');
eventHandlers = {
succeeded: function() {
if (done) { done(); }
},
failed: function() {
self.terminate({
cause: JsSIP_C.causes.WEBRTC_ERROR,
status_code: 500,
reason_phrase: 'Hold Failed'
});
}
};
if (options.useUpdate) {
sendUpdate.call(this, {
sdpOffer: true,
eventHandlers: eventHandlers,
extraHeaders: options.extraHeaders
});
} else {
sendReinvite.call(this, {
eventHandlers: eventHandlers,
extraHeaders: options.extraHeaders
});
}
return true;
};
RTCSession.prototype.unhold = function(options, done) {
debug('unhold()');
options = options || {};
var self = this,
eventHandlers;
if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) {
return false;
}
if (this.localHold === false) {
return false;
}
if (! this.isReadyToReOffer()) {
return false;
}
this.localHold = false;
onunhold.call(this, 'local');
eventHandlers = {
succeeded: function() {
if (done) { done(); }
},
failed: function() {
self.terminate({
cause: JsSIP_C.causes.WEBRTC_ERROR,
status_code: 500,
reason_phrase: 'Unhold Failed'
});
}
};
if (options.useUpdate) {
sendUpdate.call(this, {
sdpOffer: true,
eventHandlers: eventHandlers,
extraHeaders: options.extraHeaders
});
} else {
sendReinvite.call(this, {
eventHandlers: eventHandlers,
extraHeaders: options.extraHeaders
});
}
return true;
};
RTCSession.prototype.renegotiate = function(options, done) {
debug('renegotiate()');
options = options || {};
var self = this,
eventHandlers,
rtcOfferConstraints = options.rtcOfferConstraints || null;
if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) {
return false;
}
if (! this.isReadyToReOffer()) {
return false;
}
eventHandlers = {
succeeded: function() {
if (done) { done(); }
},
failed: function() {
self.terminate({
cause: JsSIP_C.causes.WEBRTC_ERROR,
status_code: 500,
reason_phrase: 'Media Renegotiation Failed'
});
}
};
setLocalMediaStatus.call(this);
if (options.useUpdate) {
sendUpdate.call(this, {
sdpOffer: true,
eventHandlers: eventHandlers,
rtcOfferConstraints: rtcOfferConstraints,
extraHeaders: options.extraHeaders
});
} else {
sendReinvite.call(this, {
eventHandlers: eventHandlers,
rtcOfferConstraints: rtcOfferConstraints,
extraHeaders: options.extraHeaders
});
}
return true;
};
/**
* Refer
*/
RTCSession.prototype.refer = function(target, options) {
debug('refer()');
var self = this,
originalTarget = target,
referSubscriber,
id;
if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) {
return false;
}
// Check target validity
target = this.ua.normalizeTarget(target);
if (!target) {
throw new TypeError('Invalid target: '+ originalTarget);
}
referSubscriber = new RTCSession_ReferSubscriber(this);
referSubscriber.sendRefer(target, options);
// Store in the map
id = referSubscriber.outgoingRequest.cseq;
this.referSubscribers[id] = referSubscriber;
// Listen for ending events so we can remove it from the map
referSubscriber.on('requestFailed', function() {
delete self.referSubscribers[id];
});
referSubscriber.on('accepted', function() {
delete self.referSubscribers[id];
});
referSubscriber.on('failed', function() {
delete self.referSubscribers[id];
});
return referSubscriber;
};
/**
* In dialog Request Reception
*/
RTCSession.prototype.receiveRequest = function(request) {
debug('receiveRequest()');
var contentType,
self = this;
if(request.method === JsSIP_C.CANCEL) {
/* RFC3261 15 States that a UAS may have accepted an invitation while a CANCEL
* was in progress and that the UAC MAY continue with the session established by
* any 2xx response, or MAY terminate with BYE. JsSIP does continue with the
* established session. So the CANCEL is processed only if the session is not yet
* established.
*/
/*
* Terminate the whole session in case the user didn't accept (or yet send the answer)
* nor reject the request opening the session.
*/
if(this.status === C.STATUS_WAITING_FOR_ANSWER || this.status === C.STATUS_ANSWERED) {
this.status = C.STATUS_CANCELED;
this.request.reply(487);
failed.call(this, 'remote', request, JsSIP_C.causes.CANCELED);
}
} else {
// Requests arriving here are in-dialog requests.
switch(request.method) {
case JsSIP_C.ACK:
if (this.status !== C.STATUS_WAITING_FOR_ACK) {
return;
}
// Update signaling status.
this.status = C.STATUS_CONFIRMED;
clearTimeout(this.timers.ackTimer);
clearTimeout(this.timers.invite2xxTimer);
if (this.late_sdp) {
if (!request.body) {
this.terminate({
cause: JsSIP_C.causes.MISSING_SDP,
status_code: 400
});
break;
}
var e = {originator:'remote', type:'answer', sdp:request.body};
var answer = new RTCSessionDescription({type:'answer', sdp:e.sdp});
this.emit('sdp', e);
this.connection.setRemoteDescription(answer)
.then(function() {
if (!self.is_confirmed) {
confirmed.call(self, 'remote', request);
}
})
.catch(function(error) {
self.terminate({
cause: JsSIP_C.causes.BAD_MEDIA_DESCRIPTION,
status_code: 488
});
self.emit('peerconnection:setremotedescriptionfailed', error);
});
}
else {
if (!this.is_confirmed) {
confirmed.call(this, 'remote', request);
}
}
break;
case JsSIP_C.BYE:
if(this.status === C.STATUS_CONFIRMED) {
request.reply(200);
ended.call(this, 'remote', request, JsSIP_C.causes.BYE);
}
else if (this.status === C.STATUS_INVITE_RECEIVED) {
request.reply(200);
this.request.reply(487, 'BYE Received');
ended.call(this, 'remote', request, JsSIP_C.causes.BYE);
}
else {
request.reply(403, 'Wrong Status');
}
break;
case JsSIP_C.INVITE:
if(this.status === C.STATUS_CONFIRMED) {
if (request.hasHeader('replaces')) {
receiveReplaces.call(this, request);
} else {
receiveReinvite.call(this, request);
}
}
else {
request.reply(403, 'Wrong Status');
}
break;
case JsSIP_C.INFO:
if(this.status === C.STATUS_CONFIRMED || this.status === C.STATUS_WAITING_FOR_ACK || this.status === C.STATUS_INVITE_RECEIVED) {
contentType = request.getHeader('content-type');
if (contentType && (contentType.match(/^application\/dtmf-relay/i))) {
new RTCSession_DTMF(this).init_incoming(request);
}
else {
request.reply(415);
}
}
else {
request.reply(403, 'Wrong Status');
}
break;
case JsSIP_C.UPDATE:
if(this.status === C.STATUS_CONFIRMED) {
receiveUpdate.call(this, request);
}
else {
request.reply(403, 'Wrong Status');
}
break;
case JsSIP_C.REFER:
if(this.status === C.STATUS_CONFIRMED) {
receiveRefer.call(this, request);
}
else {
request.reply(403, 'Wrong Status');
}
break;
case JsSIP_C.NOTIFY:
if(this.status === C.STATUS_CONFIRMED) {
receiveNotify.call(this, request);
}
else {
request.reply(403, 'Wrong Status');
}
break;
default:
request.reply(501);
}
}
};
/**
* Session Callbacks
*/
RTCSession.prototype.onTransportError = function() {
debugerror('onTransportError()');
if(this.status !== C.STATUS_TERMINATED) {
this.terminate({
status_code: 500,
reason_phrase: JsSIP_C.causes.CONNECTION_ERROR,
cause: JsSIP_C.causes.CONNECTION_ERROR
});
}
};
RTCSession.prototype.onRequestTimeout = function() {
debug('onRequestTimeout');
if(this.status !== C.STATUS_TERMINATED) {
this.terminate({
status_code: 408,
reason_phrase: JsSIP_C.causes.REQUEST_TIMEOUT,
cause: JsSIP_C.causes.REQUEST_TIMEOUT
});
}
};
RTCSession.prototype.onDialogError = function() {
debugerror('onDialogError()');
if(this.status !== C.STATUS_TERMINATED) {
this.terminate({
status_code: 500,
reason_phrase: JsSIP_C.causes.DIALOG_ERROR,
cause: JsSIP_C.causes.DIALOG_ERROR
});
}
};
// Called from DTMF handler.
RTCSession.prototype.newDTMF = function(data) {
debug('newDTMF()');
this.emit('newDTMF', data);
};
RTCSession.prototype.resetLocalMedia = function() {
debug('resetLocalMedia()');
// Reset all but remoteHold.
this.localHold = false;
this.audioMuted = false;
this.videoMuted = false;
setLocalMediaStatus.call(this);
};
/**
* Private API.
*/
/**
* RFC3261 13.3.1.4
* Response retransmissions cannot be accomplished by transaction layer
* since it is destroyed when receiving the first 2xx answer
*/
function setInvite2xxTimer(request, body) {
var
self = this,
timeout = Timers.T1;
this.timers.invite2xxTimer = setTimeout(function invite2xxRetransmission() {
if (self.status !== C.STATUS_WAITING_FOR_ACK) {
return;
}
request.reply(200, null, ['Contact: '+ self.contact], body);
if (timeout < Timers.T2) {
timeout = timeout * 2;
if (timeout > Timers.T2) {
timeout = Timers.T2;
}
}
self.timers.invite2xxTimer = setTimeout(
invite2xxRetransmission, timeout
);
}, timeout);
}
/**
* RFC3261 14.2
* If a UAS generates a 2xx response and never receives an ACK,
* it SHOULD generate a BYE to terminate the dialog.
*/
function setACKTimer() {
var self = this;
this.timers.ackTimer = setTimeout(function() {
if(self.status === C.STATUS_WAITING_FOR_ACK) {
debug('no ACK received, terminating the session');
clearTimeout(self.timers.invite2xxTimer);
sendRequest.call(self, JsSIP_C.BYE);
ended.call(self, 'remote', null, JsSIP_C.causes.NO_ACK);
}
}, Timers.TIMER_H);
}
function createRTCConnection(pcConfig, rtcConstraints) {
var self = this;
this.connection = new RTCPeerConnection(pcConfig, rtcConstraints);
this.connection.addEventListener('iceconnectionstatechange', function() {
var state = self.connection.iceConnectionState;
// TODO: Do more with different states.
if (state === 'failed') {
self.terminate({
cause: JsSIP_C.causes.RTP_TIMEOUT,
status_code: 200,
reason_phrase: JsSIP_C.causes.RTP_TIMEOUT
});
}
});
}
function createLocalDescription(type, onSuccess, onFailure, constraints) {
debug('createLocalDescription()');
var self = this;
var connection = this.connection;
this.rtcReady = false;
if (type === 'offer') {
connection.createOffer(constraints)
.then(createSucceeded)
.catch(function(error) {
self.rtcReady = true;
if (onFailure) { onFailure(error); }
self.emit('peerconnection:createofferfailed', error);
});
}
else if (type === 'answer') {
connection.createAnswer(constraints)
.then(createSucceeded)
.catch(function(error) {
self.rtcReady = true;
if (onFailure) { onFailure(error); }
self.emit('peerconnection:createanswerfailed', error);
});
}
else {
throw new Error('createLocalDescription() | type must be "offer" or "answer", but "' +type+ '" was given');
}
// createAnswer or createOffer succeeded
function createSucceeded(desc) {
var listener;
connection.addEventListener('icecandidate', listener = function(event) {
var candidate = event.candidate;
if (! candidate) {
connection.removeEventListener('icecandidate', listener);
self.rtcReady = true;
if (onSuccess) {
var e = {originator:'local', type:type, sdp:connection.localDescription.sdp};
self.emit('sdp', e);
onSuccess(e.sdp);
}
onSuccess = null;
}
});
connection.setLocalDescription(desc)
.then(function() {
if (connection.iceGatheringState === 'complete') {
self.rtcReady = true;
if (onSuccess) {
var e = {originator:'local', type:type, sdp:connection.localDescription.sdp};
self.emit('sdp', e);
onSuccess(e.sdp);
onSuccess = null;
}
}
})
.catch(function(error) {
self.rtcReady = true;
if (onFailure) { onFailure(error); }
self.emit('peerconnection:setlocaldescriptionfailed', error);
});
}
}
/**
* Dialog Management
*/
function createDialog(message, type, early) {
var dialog, early_dialog,
local_tag = (type === 'UAS') ? message.to_tag : message.from_tag,
remote_tag = (type === 'UAS') ? message.from_tag : message.to_tag,
id = message.call_id + local_tag + remote_tag;
early_dialog = this.earlyDialogs[id];
// Early Dialog
if (early) {
if (early_dialog) {
return true;
} else {
early_dialog = new Dialog(this, message, type, Dialog.C.STATUS_EARLY);
// Dialog has been successfully created.
if(early_dialog.error) {
debug(early_dialog.error);
failed.call(this, 'remote', message, JsSIP_C.causes.INTERNAL_ERROR);
return false;
} else {
this.earlyDialogs[id] = early_dialog;
return true;
}
}
}
// Confirmed Dialog
else {
this.from_tag = message.from_tag;
this.to_tag = message.to_tag;
// In case the dialog is in _early_ state, update it
if (early_dialog) {
early_dialog.update(message, type);
this.dialog = early_dialog;
delete this.earlyDialogs[id];
return true;
}
// Otherwise, create a _confirmed_ dialog
dialog = new Dialog(this, message, type);
if(dialog.error) {
debug(dialog.error);
failed.call(this, 'remote', message, JsSIP_C.causes.INTERNAL_ERROR);
return false;
} else {
this.dialog = dialog;
return true;
}
}
}
/**
* In dialog INVITE Reception
*/
function receiveReinvite(request) {
debug('receiveReinvite()');
var
sdp, idx, direction, m,
self = this,
contentType = request.getHeader('Content-Type'),
hold = false,
rejected = false,
data = {
request: request,
callback: undefined,
reject: reject.bind(this)
};
function reject(options) {
options = options || {};
rejected = true;
var
status_code = options.status_code || 403,
reason_phrase = options.reason_phrase || '',
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [];
if (this.status !== C.STATUS_CONFIRMED) {
return false;
}
if (status_code < 300 || status_code >= 700) {
throw new TypeError('Invalid status_code: '+ status_code);
}
request.reply(status_code, reason_phrase, extraHeaders);
}
// Emit 'reinvite'.
this.emit('reinvite', data);
if (rejected) {
return;
}
if (request.body) {
this.late_sdp = false;
if (contentType !== 'application/sdp') {
debug('invalid Content-Type');
request.reply(415);
return;
}
sdp = request.parseSDP();
for (idx=0; idx < sdp.media.length; idx++) {
m = sdp.media[idx];
if (holdMediaTypes.indexOf(m.type) === -1) {
continue;
}
direction = m.direction || sdp.direction || 'sendrecv';
if (direction === 'sendonly' || direction === 'inactive') {
hold = true;
}
// If at least one of the streams is active don't emit 'hold'.
else {
hold = false;
break;
}
}
var e = {originator:'remote', type:'offer', sdp:request.body};
var offer = new RTCSessionDescription({type:'offer', sdp:e.sdp});
this.emit('sdp', e);
this.connection.setRemoteDescription(offer)
.then(doAnswer)
.catch(function(error) {
request.reply(488);
self.emit('peerconnection:setremotedescriptionfailed', error);
});
}
else {
this.late_sdp = true;
doAnswer();
}
function doAnswer() {
createSdp(
// onSuccess
function(sdp) {
var extraHeaders = ['Contact: ' + self.contact];
handleSessionTimersInIncomingRequest.call(self, request, extraHeaders);
if (self.late_sdp) {
sdp = mangleOffer.call(self, sdp);
}
request.reply(200, null, extraHeaders, sdp,
function() {
self.status = C.STATUS_WAITING_FOR_ACK;
setInvite2xxTimer.call(self, request, sdp);
setACKTimer.call(self);
}
);
// If callback is given execute it.
if (typeof data.callback === 'function') {
data.callback();
}
},
// onFailure
function() {
request.reply(500);
}
);
}
function createSdp(onSuccess, onFailure) {
if (! self.late_sdp) {
if (self.remoteHold === true && hold === false) {
self.remoteHold = false;
onunhold.call(self, 'remote');
} else if (self.remoteHold === false && hold === true) {
self.remoteHold = true;
onhold.call(self, 'remote');
}
createLocalDescription.call(self, 'answer', onSuccess, onFailure, self.rtcAnswerConstraints);
} else {
createLocalDescription.call(self, 'offer', onSuccess, onFailure, self.rtcOfferConstraints);
}
}
}
/**
* In dialog UPDATE Reception
*/
function receiveUpdate(request) {
debug('receiveUpdate()');
var
sdp, idx, direction, m,
self = this,
contentType = request.getHeader('Content-Type'),
rejected = false,
hold = false,
data = {
request: request,
callback: undefined,
reject: reject.bind(this)
};
function reject(options) {
options = options || {};
rejected = true;
var
status_code = options.status_code || 403,
reason_phrase = options.reason_phrase || '',
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [];
if (this.status !== C.STATUS_CONFIRMED) {
return false;
}
if (status_code < 300 || status_code >= 700) {
throw new TypeError('Invalid status_code: '+ status_code);
}
request.reply(status_code, reason_phrase, extraHeaders);
}
// Emit 'update'.
this.emit('update', data);
if (rejected) {
return;
}
if (! request.body) {
var extraHeaders = [];
handleSessionTimersInIncomingRequest.call(this, request, extraHeaders);
request.reply(200, null, extraHeaders);
return;
}
if (contentType !== 'application/sdp') {
debug('invalid Content-Type');
request.reply(415);
return;
}
sdp = request.parseSDP();
for (idx=0; idx < sdp.media.length; idx++) {
m = sdp.media[idx];
if (holdMediaTypes.indexOf(m.type) === -1) {
continue;
}
direction = m.direction || sdp.direction || 'sendrecv';
if (direction === 'sendonly' || direction === 'inactive') {
hold = true;
}
// If at least one of the streams is active don't emit 'hold'.
else {
hold = false;
break;
}
}
var e = {originator:'remote', type:'offer', sdp:request.body};
var offer = new RTCSessionDescription({type:'offer', sdp:e.sdp});
this.emit('sdp', e);
this.connection.setRemoteDescription(offer)
.then(function() {
if (self.remoteHold === true && hold === false) {
self.remoteHold = false;
onunhold.call(self, 'remote');
} else if (self.remoteHold === false && hold === true) {
self.remoteHold = true;
onhold.call(self, 'remote');
}
createLocalDescription.call(self, 'answer',
// success
function(sdp) {
var extraHeaders = ['Contact: ' + self.contact];
handleSessionTimersInIncomingRequest.call(self, request, extraHeaders);
request.reply(200, null, extraHeaders, sdp);
// If callback is given execute it.
if (typeof data.callback === 'function') {
data.callback();
}
},
// failure
function() {
request.reply(500);
}
);
})
.catch(function(error) {
request.reply(488);
self.emit('peerconnection:setremotedescriptionfailed', error);
});
}
/**
* In dialog Refer Reception
*/
function receiveRefer(request) {
debug('receiveRefer()');
var notifier,
self = this;
function accept(initCallback, options) {
var session, replaces;
options = options || {};
initCallback = (typeof initCallback === 'function')? initCallback : null;
if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) {
return false;
}
session = new RTCSession(this.ua);
session.on('progress', function(e) {
notifier.notify(e.response.status_code, e.response.reason_phrase);
});
session.on('accepted', function(e) {
notifier.notify(e.response.status_code, e.response.reason_phrase);
});
session.on('failed', function(e) {
if (e.message) {
notifier.notify(e.message.status_code, e.message.reason_phrase);
} else {
notifier.notify(487, e.cause);
}
});
// Consider the Replaces header present in the Refer-To URI
if (request.refer_to.uri.hasHeader('replaces')) {
replaces = decodeURIComponent(request.refer_to.uri.getHeader('replaces'));
options.extraHeaders = options.extraHeaders || [];
options.extraHeaders.push('Replaces: '+ replaces);
}
session.connect(request.refer_to.uri.toAor(), options, initCallback);
}
function reject() {
notifier.notify(603);
}
if (typeof request.refer_to === undefined) {
debug('no Refer-To header field present in REFER');
request.reply(400);
return;
}
if (request.refer_to.uri.scheme !== JsSIP_C.SIP) {
debug('Refer-To header field points to a non-SIP URI scheme');
request.reply(416);
return;
}
// reply before the transaction timer expires
request.reply(202);
notifier = new RTCSession_ReferNotifier(this, request.cseq);
// Emit 'refer'.
this.emit('refer', {
request: request,
accept: function(initCallback, options) { accept.call(self, initCallback, options); },
reject: function() { reject.call(self); }
});
}
/**
* In dialog Notify Reception
*/
function receiveNotify(request) {
debug('receiveNotify()');
if (typeof request.event === undefined) {
request.reply(400);
}
switch (request.event.event) {
case 'refer': {
var id = request.event.params.id;
var referSubscriber = this.referSubscribers[id];
if (!referSubscriber) {
request.reply(481, 'Subscription does not exist');
return;
}
referSubscriber.receiveNotify(request);
request.reply(200);
break;
}
default: {
request.reply(489);
}
}
}
/**
* INVITE with Replaces Reception
*/
function receiveReplaces(request) {
debug('receiveReplaces()');
var self = this;
function accept(initCallback) {
var session;
if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) {
return false;
}
session = new RTCSession(this.ua);
// terminate the current session when the new one is confirmed
session.on('confirmed', function() {
self.terminate();
});
session.init_incoming(request, initCallback);
}
function reject() {
debug('Replaced INVITE rejected by the user');
request.reply(486);
}
// Emit 'replace'.
this.emit('replaces', {
request: request,
accept: function(initCallback) { accept.call(self, initCallback); },
reject: function() { reject.call(self); }
});
}
/**
* Initial Request Sender
*/
function sendInitialRequest(mediaConstraints, rtcOfferConstraints, mediaStream) {
var self = this;
var request_sender = new RequestSender(self, this.ua);
this.receiveResponse = function(response) {
receiveInviteResponse.call(self, response);
};
// If a local MediaStream is given use it.
if (mediaStream) {
// Wait a bit so the app can set events such as 'peerconnection' and 'connecting'.
setTimeout(function() {
userMediaSucceeded(mediaStream);
});
// If at least audio or video is requested prompt getUserMedia.
} else if (mediaConstraints.audio || mediaConstraints.video) {
this.localMediaStreamLocallyGenerated = true;
navigator.mediaDevices.getUserMedia(mediaConstraints)
.then(userMediaSucceeded)
.catch(function(error)
{
userMediaFailed(error);
self.emit('getusermediafailed', error);
});
// Otherwise don't prompt getUserMedia.
} else {
userMediaSucceeded(null);
}
// User media succeeded
function userMediaSucceeded(stream) {
if (self.status === C.STATUS_TERMINATED) { return; }
self.localMediaStream = stream;
if (stream) {
self.connection.addStream(stream);
}
// Notify the app with the RTCPeerConnection so it can do stuff on it
// before generating the offer.
self.emit('peerconnection', {
peerconnection: self.connection
});
connecting.call(self, self.request);
createLocalDescription.call(self, 'offer', rtcSucceeded, rtcFailed, rtcOfferConstraints);
}
// User media failed
function userMediaFailed() {
if (self.status === C.STATUS_TERMINATED) { return; }
failed.call(self, 'local', null, JsSIP_C.causes.USER_DENIED_MEDIA_ACCESS);
}
function rtcSucceeded(desc) {
if (self.isCanceled || self.status === C.STATUS_TERMINATED) { return; }
self.request.body = desc;
self.status = C.STATUS_INVITE_SENT;
// Emit 'sending' so the app can mangle the body before the request
// is sent.
self.emit('sending', {
request: self.request
});
request_sender.send();
}
function rtcFailed() {
if (self.status === C.STATUS_TERMINATED) { return; }
failed.call(self, 'system', null, JsSIP_C.causes.WEBRTC_ERROR);
}
}
/**
* Reception of Response for Initial INVITE
*/
function receiveInviteResponse(response) {
debug('receiveInviteResponse()');
var cause, dialog, e,
self = this;
// Handle 2XX retransmissions and responses from forked requests
if (this.dialog && (response.status_code >=200 && response.status_code <=299)) {
/*
* If it is a retransmission from the endpoint that established
* the dialog, send an ACK
*/
if (this.dialog.id.call_id === response.call_id &&
this.dialog.id.local_tag === response.from_tag &&
this.dialog.id.remote_tag === response.to_tag) {
sendRequest.call(this, JsSIP_C.ACK);
return;
}
// If not, send an ACK and terminate
else {
dialog = new Dialog(this, response, 'UAC');
if (dialog.error !== undefined) {
debug(dialog.error);
return;
}
dialog.sendRequest({
owner: {status: C.STATUS_TERMINATED},
onRequestTimeout: function(){},
onTransportError: function(){},
onDialogError: function(){},
receiveResponse: function(){}
}, JsSIP_C.ACK);
dialog.sendRequest({
owner: {status: C.STATUS_TERMINATED},
onRequestTimeout: function(){},
onTransportError: function(){},
onDialogError: function(){},
receiveResponse: function(){}
}, JsSIP_C.BYE);
return;
}
}
// Proceed to cancellation if the user requested.
if(this.isCanceled) {
// Remove the flag. We are done.
this.isCanceled = false;
if(response.status_code >= 100 && response.status_code < 200) {
this.request.cancel(this.cancelReason);
} else if(response.status_code >= 200 && response.status_code < 299) {
acceptAndTerminate.call(this, response);
}
return;
}
if(this.status !== C.STATUS_INVITE_SENT && this.status !== C.STATUS_1XX_RECEIVED) {
return;
}
switch(true) {
case /^100$/.test(response.status_code):
this.status = C.STATUS_1XX_RECEIVED;
break;
case /^1[0-9]{2}$/.test(response.status_code):
// Do nothing with 1xx responses without To tag.
if (!response.to_tag) {
debug('1xx response received without to tag');
break;
}
// Create Early Dialog if 1XX comes with contact
if (response.hasHeader('contact')) {
// An error on dialog creation will fire 'failed' event
if(! createDialog.call(this, response, 'UAC', true)) {
break;
}
}
this.status = C.STATUS_1XX_RECEIVED;
progress.call(this, 'remote', response);
if (!response.body) {
break;
}
e = {originator:'remote', type:'pranswer', sdp:response.body};
this.emit('sdp', e);
var pranswer = new RTCSessionDescription({type:'pranswer', sdp:e.sdp});
this.connection.setRemoteDescription(pranswer)
.catch(function(error) {
self.emit('peerconnection:setremotedescriptionfailed', error);
});
break;
case /^2[0-9]{2}$/.test(response.status_code):
this.status = C.STATUS_CONFIRMED;
if(!response.body) {
acceptAndTerminate.call(this, response, 400, JsSIP_C.causes.MISSING_SDP);
failed.call(this, 'remote', response, JsSIP_C.causes.BAD_MEDIA_DESCRIPTION);
break;
}
// An error on dialog creation will fire 'failed' event
if (! createDialog.call(this, response, 'UAC')) {
break;
}
e = {originator:'remote', type:'answer', sdp:response.body};
this.emit('sdp', e);
var answer = new RTCSessionDescription({type:'answer', sdp:e.sdp});
this.connection.setRemoteDescription(answer)
.then(function() {
// Handle Session Timers.
handleSessionTimersInIncomingResponse.call(self, response);
accepted.call(self, 'remote', response);
sendRequest.call(self, JsSIP_C.ACK);
confirmed.call(self, 'local', null);
})
.catch(function(error) {
acceptAndTerminate.call(self, response, 488, 'Not Acceptable Here');
failed.call(self, 'remote', response, JsSIP_C.causes.BAD_MEDIA_DESCRIPTION);
self.emit('peerconnection:setremotedescriptionfailed', error);
});
break;
default:
cause = Utils.sipErrorCause(response.status_code);
failed.call(this, 'remote', response, cause);
}
}
/**
* Send Re-INVITE
*/
function sendReinvite(options) {
debug('sendReinvite()');
options = options || {};
var
self = this,
extraHeaders = options.extraHeaders || [],
eventHandlers = options.eventHandlers || {},
rtcOfferConstraints = options.rtcOfferConstraints || this.rtcOfferConstraints || null,
succeeded = false;
extraHeaders.push('Contact: ' + this.contact);
extraHeaders.push('Content-Type: application/sdp');
// Session Timers.
if (this.sessionTimers.running) {
extraHeaders.push('Session-Expires: ' + this.sessionTimers.currentExpires + ';refresher=' + (this.sessionTimers.refresher ? 'uac' : 'uas'));
}
createLocalDescription.call(this, 'offer',
// success
function(sdp) {
sdp = mangleOffer.call(self, sdp);
var request = new RTCSession_Request(self, JsSIP_C.INVITE);
request.send({
extraHeaders: extraHeaders,
body: sdp,
eventHandlers: {
onSuccessResponse: function(response) {
onSucceeded(response);
succeeded = true;
},
onErrorResponse: function(response) {
onFailed(response);
},
onTransportError: function() {
self.onTransportError(); // Do nothing because session ends.
},
onRequestTimeout: function() {
self.onRequestTimeout(); // Do nothing because session ends.
},
onDialogError: function() {
self.onDialogError(); // Do nothing because session ends.
}
}
});
},
// failure
function() {
onFailed();
},
// RTC constraints.
rtcOfferConstraints
);
function onSucceeded(response) {
if (self.status === C.STATUS_TERMINATED) {
return;
}
sendRequest.call(self, JsSIP_C.ACK);
// If it is a 2XX retransmission exit now.
if (succeeded) { return; }
// Handle Session Timers.
handleSessionTimersInIncomingResponse.call(self, response);
// Must have SDP answer.
if(! response.body) {
onFailed();
return;
} else if (response.getHeader('Content-Type') !== 'application/sdp') {
onFailed();
return;
}
var e = {originator:'remote', type:'answer', sdp:response.body};
var answer = new RTCSessionDescription({type:'answer', sdp:e.sdp});
self.emit('sdp', e);
self.connection.setRemoteDescription(answer)
.then(function() {
if (eventHandlers.succeeded) {
eventHandlers.succeeded(response);
}
})
.catch(function(error) {
onFailed();
self.emit('peerconnection:setremotedescriptionfailed', error);
});
}
function onFailed(response) {
if (eventHandlers.failed) {
eventHandlers.failed(response);
}
}
}
/**
* Send UPDATE
*/
function sendUpdate(options) {
debug('sendUpdate()');
options = options || {};
var
self = this,
extraHeaders = options.extraHeaders || [],
eventHandlers = options.eventHandlers || {},
rtcOfferConstraints = options.rtcOfferConstraints || this.rtcOfferConstraints || null,
sdpOffer = options.sdpOffer || false,
succeeded = false;
extraHeaders.push('Contact: ' + this.contact);
// Session Timers.
if (this.sessionTimers.running) {
extraHeaders.push('Session-Expires: ' + this.sessionTimers.currentExpires + ';refresher=' + (this.sessionTimers.refresher ? 'uac' : 'uas'));
}
if (sdpOffer) {
extraHeaders.push('Content-Type: application/sdp');
createLocalDescription.call(this, 'offer',
// success
function(sdp) {
sdp = mangleOffer.call(self, sdp);
var request = new RTCSession_Request(self, JsSIP_C.UPDATE);
request.send({
extraHeaders: extraHeaders,
body: sdp,
eventHandlers: {
onSuccessResponse: function(response) {
onSucceeded(response);
succeeded = true;
},
onErrorResponse: function(response) {
onFailed(response);
},
onTransportError: function() {
self.onTransportError(); // Do nothing because session ends.
},
onRequestTimeout: function() {
self.onRequestTimeout(); // Do nothing because session ends.
},
onDialogError: function() {
self.onDialogError(); // Do nothing because session ends.
}
}
});
},
// failure
function() {
onFailed();
},
// RTC constraints.
rtcOfferConstraints
);
}
// No SDP.
else {
var request = new RTCSession_Request(self, JsSIP_C.UPDATE);
request.send({
extraHeaders: extraHeaders,
eventHandlers: {
onSuccessResponse: function(response) {
onSucceeded(response);
},
onErrorResponse: function(response) {
onFailed(response);
},
onTransportError: function() {
self.onTransportError(); // Do nothing because session ends.
},
onRequestTimeout: function() {
self.onRequestTimeout(); // Do nothing because session ends.
},
onDialogError: function() {
self.onDialogError(); // Do nothing because session ends.
}
}
});
}
function onSucceeded(response) {
if (self.status === C.STATUS_TERMINATED) {
return;
}
// If it is a 2XX retransmission exit now.
if (succeeded) { return; }
// Handle Session Timers.
handleSessionTimersInIncomingResponse.call(self, response);
// Must have SDP answer.
if (sdpOffer) {
if(! response.body) {
onFailed();
return;
} else if (response.getHeader('Content-Type') !== 'application/sdp') {
onFailed();
return;
}
var e = {originator:'remote', type:'answer', sdp:response.body};
var answer = new RTCSessionDescription({type:'answer', sdp:e.sdp});
self.emit('sdp', e);
self.connection.setRemoteDescription(answer)
.then(function() {
if (eventHandlers.succeeded) {
eventHandlers.succeeded(response);
}
})
.catch(function(error) {
onFailed();
self.emit('peerconnection:setremotedescriptionfailed', error);
});
}
// No SDP answer.
else {
if (eventHandlers.succeeded) {
eventHandlers.succeeded(response);
}
}
}
function onFailed(response) {
if (eventHandlers.failed) { eventHandlers.failed(response); }
}
}
function acceptAndTerminate(response, status_code, reason_phrase) {
debug('acceptAndTerminate()');
var extraHeaders = [];
if (status_code) {
reason_phrase = reason_phrase || JsSIP_C.REASON_PHRASE[status_code] || '';
extraHeaders.push('Reason: SIP ;cause=' + status_code + '; text="' + reason_phrase + '"');
}
// An error on dialog creation will fire 'failed' event
if (this.dialog || createDialog.call(this, response, 'UAC')) {
sendRequest.call(this, JsSIP_C.ACK);
sendRequest.call(this, JsSIP_C.BYE, {
extraHeaders: extraHeaders
});
}
// Update session status.
this.status = C.STATUS_TERMINATED;
}
/**
* Send a generic in-dialog Request
*/
function sendRequest(method, options) {
debug('sendRequest()');
var request = new RTCSession_Request(this, method);
request.send(options);
}
/**
* Correctly set the SDP direction attributes if the call is on local hold
*/
function mangleOffer(sdp) {
var idx, length, m;
if (! this.localHold && ! this.remoteHold) {
return sdp;
}
sdp = sdp_transform.parse(sdp);
// Local hold.
if (this.localHold && ! this.remoteHold) {
debug('mangleOffer() | me on hold, mangling offer');
length = sdp.media.length;
for (idx=0; idx<length; idx++) {
m = sdp.media[idx];
if (holdMediaTypes.indexOf(m.type) === -1) {
continue;
}
if (!m.direction) {
m.direction = 'sendonly';
} else if (m.direction === 'sendrecv') {
m.direction = 'sendonly';
} else if (m.direction === 'recvonly') {
m.direction = 'inactive';
}
}
}
// Local and remote hold.
else if (this.localHold && this.remoteHold) {
debug('mangleOffer() | both on hold, mangling offer');
length = sdp.media.length;
for (idx=0; idx<length; idx++) {
m = sdp.media[idx];
if (holdMediaTypes.indexOf(m.type) === -1) {
continue;
}
m.direction = 'inactive';
}
}
// Remote hold.
else if (this.remoteHold) {
debug('mangleOffer() | remote on hold, mangling offer');
length = sdp.media.length;
for (idx=0; idx<length; idx++) {
m = sdp.media[idx];
if (holdMediaTypes.indexOf(m.type) === -1) {
continue;
}
if (!m.direction) {
m.direction = 'recvonly';
} else if (m.direction === 'sendrecv') {
m.direction = 'recvonly';
} else if (m.direction === 'recvonly') {
m.direction = 'inactive';
}
}
}
return sdp_transform.write(sdp);
}
function setLocalMediaStatus() {
var enableAudio = true,
enableVideo = true;
if (this.localHold || this.remoteHold) {
enableAudio = false;
enableVideo = false;
}
if (this.audioMuted) {
enableAudio = false;
}
if (this.videoMuted) {
enableVideo = false;
}
toogleMuteAudio.call(this, !enableAudio);
toogleMuteVideo.call(this, !enableVideo);
}
/**
* Handle SessionTimers for an incoming INVITE or UPDATE.
* @param {IncomingRequest} request
* @param {Array} responseExtraHeaders Extra headers for the 200 response.
*/
function handleSessionTimersInIncomingRequest(request, responseExtraHeaders) {
if (! this.sessionTimers.enabled) { return; }
var session_expires_refresher;
if (request.session_expires && request.session_expires >= JsSIP_C.MIN_SESSION_EXPIRES) {
this.sessionTimers.currentExpires = request.session_expires;
session_expires_refresher = request.session_expires_refresher || 'uas';
}
else {
this.sessionTimers.currentExpires = this.sessionTimers.defaultExpires;
session_expires_refresher = 'uas';
}
responseExtraHeaders.push('Session-Expires: ' + this.sessionTimers.currentExpires + ';refresher=' + session_expires_refresher);
this.sessionTimers.refresher = (session_expires_refresher === 'uas');
runSessionTimer.call(this);
}
/**
* Handle SessionTimers for an incoming response to INVITE or UPDATE.
* @param {IncomingResponse} response
*/
function handleSessionTimersInIncomingResponse(response) {
if (! this.sessionTimers.enabled) { return; }
var session_expires_refresher;
if (response.session_expires && response.session_expires >= JsSIP_C.MIN_SESSION_EXPIRES) {
this.sessionTimers.currentExpires = response.session_expires;
session_expires_refresher = response.session_expires_refresher || 'uac';
}
else {
this.sessionTimers.currentExpires = this.sessionTimers.defaultExpires;
session_expires_refresher = 'uac';
}
this.sessionTimers.refresher = (session_expires_refresher === 'uac');
runSessionTimer.call(this);
}
function runSessionTimer() {
var self = this;
var expires = this.sessionTimers.currentExpires;
this.sessionTimers.running = true;
clearTimeout(this.sessionTimers.timer);
// I'm the refresher.
if (this.sessionTimers.refresher) {
this.sessionTimers.timer = setTimeout(function() {
if (self.status === C.STATUS_TERMINATED) { return; }
debug('runSessionTimer() | sending session refresh request');
sendUpdate.call(self, {
eventHandlers: {
succeeded: function(response) {
handleSessionTimersInIncomingResponse.call(self, response);
}
}
});
}, expires * 500); // Half the given interval (as the RFC states).
}
// I'm not the refresher.
else {
this.sessionTimers.timer = setTimeout(function() {
if (self.status === C.STATUS_TERMINATED) { return; }
debugerror('runSessionTimer() | timer expired, terminating the session');
self.terminate({
cause: JsSIP_C.causes.REQUEST_TIMEOUT,
status_code: 408,
reason_phrase: 'Session Timer Expired'
});
}, expires * 1100);
}
}
function toogleMuteAudio(mute) {
var streamIdx, trackIdx, streamsLength, tracksLength, tracks,
localStreams = this.connection.getLocalStreams();
streamsLength = localStreams.length;
for (streamIdx = 0; streamIdx < streamsLength; streamIdx++) {
tracks = localStreams[streamIdx].getAudioTracks();
tracksLength = tracks.length;
for (trackIdx = 0; trackIdx < tracksLength; trackIdx++) {
tracks[trackIdx].enabled = !mute;
}
}
}
function toogleMuteVideo(mute) {
var streamIdx, trackIdx, streamsLength, tracksLength, tracks,
localStreams = this.connection.getLocalStreams();
streamsLength = localStreams.length;
for (streamIdx = 0; streamIdx < streamsLength; streamIdx++) {
tracks = localStreams[streamIdx].getVideoTracks();
tracksLength = tracks.length;
for (trackIdx = 0; trackIdx < tracksLength; trackIdx++) {
tracks[trackIdx].enabled = !mute;
}
}
}
function newRTCSession(originator, request) {
debug('newRTCSession');
this.ua.newRTCSession({
originator: originator,
session: this,
request: request
});
}
function connecting(request) {
debug('session connecting');
this.emit('connecting', {
request: request
});
}
function progress(originator, response) {
debug('session progress');
this.emit('progress', {
originator: originator,
response: response || null
});
}
function accepted(originator, message) {
debug('session accepted');
this.start_time = new Date();
this.emit('accepted', {
originator: originator,
response: message || null
});
}
function confirmed(originator, ack) {
debug('session confirmed');
this.is_confirmed = true;
this.emit('confirmed', {
originator: originator,
ack: ack || null
});
}
function ended(originator, message, cause) {
debug('session ended');
this.end_time = new Date();
this.close();
this.emit('ended', {
originator: originator,
message: message || null,
cause: cause
});
}
function failed(originator, message, cause) {
debug('session failed');
this.close();
this.emit('failed', {
originator: originator,
message: message || null,
cause: cause
});
}
function onhold(originator) {
debug('session onhold');
setLocalMediaStatus.call(this);
this.emit('hold', {
originator: originator
});
}
function onunhold(originator) {
debug('session onunhold');
setLocalMediaStatus.call(this);
this.emit('unhold', {
originator: originator
});
}
function onmute(options) {
debug('session onmute');
setLocalMediaStatus.call(this);
this.emit('muted', {
audio: options.audio,
video: options.video
});
}
function onunmute(options) {
debug('session onunmute');
setLocalMediaStatus.call(this);
this.emit('unmuted', {
audio: options.audio,
video: options.video
});
}
},{"./Constants":1,"./Dialog":2,"./Exceptions":5,"./RTCSession/DTMF":12,"./RTCSession/ReferNotifier":13,"./RTCSession/ReferSubscriber":14,"./RTCSession/Request":15,"./RequestSender":17,"./SIPMessage":18,"./Timers":20,"./Transactions":21,"./Utils":25,"debug":34,"events":28,"sdp-transform":37,"util":32}],12:[function(require,module,exports){
module.exports = DTMF;
var C = {
MIN_DURATION: 70,
MAX_DURATION: 6000,
DEFAULT_DURATION: 100,
MIN_INTER_TONE_GAP: 50,
DEFAULT_INTER_TONE_GAP: 500
};
/**
* Expose C object.
*/
DTMF.C = C;
/**
* Dependencies.
*/
var util = require('util');
var events = require('events');
var debug = require('debug')('JsSIP:RTCSession:DTMF');
var debugerror = require('debug')('JsSIP:ERROR:RTCSession:DTMF');
debugerror.log = console.warn.bind(console);
var JsSIP_C = require('../Constants');
var Exceptions = require('../Exceptions');
var RTCSession = require('../RTCSession');
function DTMF(session) {
this.owner = session;
this.direction = null;
this.tone = null;
this.duration = null;
events.EventEmitter.call(this);
}
util.inherits(DTMF, events.EventEmitter);
DTMF.prototype.send = function(tone, options) {
var extraHeaders, body;
if (tone === undefined) {
throw new TypeError('Not enough arguments');
}
this.direction = 'outgoing';
// Check RTCSession Status
if (this.owner.status !== RTCSession.C.STATUS_CONFIRMED &&
this.owner.status !== RTCSession.C.STATUS_WAITING_FOR_ACK) {
throw new Exceptions.InvalidStateError(this.owner.status);
}
// Get DTMF options
options = options || {};
extraHeaders = options.extraHeaders ? options.extraHeaders.slice() : [];
this.eventHandlers = options.eventHandlers || {};
// Check tone type
if (typeof tone === 'string' ) {
tone = tone.toUpperCase();
} else if (typeof tone === 'number') {
tone = tone.toString();
} else {
throw new TypeError('Invalid tone: '+ tone);
}
// Check tone value
if (!tone.match(/^[0-9A-DR#*]$/)) {
throw new TypeError('Invalid tone: '+ tone);
} else {
this.tone = tone;
}
// Duration is checked/corrected in RTCSession
this.duration = options.duration;
extraHeaders.push('Content-Type: application/dtmf-relay');
body = 'Signal=' + this.tone + '\r\n';
body += 'Duration=' + this.duration;
this.owner.newDTMF({
originator: 'local',
dtmf: this,
request: this.request
});
this.owner.dialog.sendRequest(this, JsSIP_C.INFO, {
extraHeaders: extraHeaders,
body: body
});
};
DTMF.prototype.receiveResponse = function(response) {
switch(true) {
case /^1[0-9]{2}$/.test(response.status_code):
// Ignore provisional responses.
break;
case /^2[0-9]{2}$/.test(response.status_code):
this.emit('succeeded', {
originator: 'remote',
response: response
});
break;
default:
if (this.eventHandlers.onFailed) {
this.eventHandlers.onFailed();
}
this.emit('failed', {
originator: 'remote',
response: response
});
break;
}
};
DTMF.prototype.onRequestTimeout = function() {
debugerror('onRequestTimeout');
this.owner.onRequestTimeout();
};
DTMF.prototype.onTransportError = function() {
debugerror('onTransportError');
this.owner.onTransportError();
};
DTMF.prototype.onDialogError = function() {
debugerror('onDialogError');
this.owner.onDialogError();
};
DTMF.prototype.init_incoming = function(request) {
var body,
reg_tone = /^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/,
reg_duration = /^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;
this.direction = 'incoming';
this.request = request;
request.reply(200);
if (request.body) {
body = request.body.split('\n');
if (body.length >= 1) {
if (reg_tone.test(body[0])) {
this.tone = body[0].replace(reg_tone,'$2');
}
}
if (body.length >=2) {
if (reg_duration.test(body[1])) {
this.duration = parseInt(body[1].replace(reg_duration,'$2'), 10);
}
}
}
if (!this.duration) {
this.duration = C.DEFAULT_DURATION;
}
if (!this.tone) {
debug('invalid INFO DTMF received, discarded');
} else {
this.owner.newDTMF({
originator: 'remote',
dtmf: this,
request: request
});
}
};
},{"../Constants":1,"../Exceptions":5,"../RTCSession":11,"debug":34,"events":28,"util":32}],13:[function(require,module,exports){
module.exports = ReferNotifier;
var C = {
event_type: 'refer',
body_type: 'message/sipfrag;version=2.0',
expires: 300
};
/**
* Dependencies.
*/
var debug = require('debug')('JsSIP:RTCSession:ReferNotifier');
var JsSIP_C = require('../Constants');
var RTCSession_Request = require('./Request');
function ReferNotifier(session, id, expires) {
this.session = session;
this.id = id;
this.expires = expires || C.expires;
this.active = true;
// The creation of a Notifier results in an immediate NOTIFY
this.notify(100);
}
ReferNotifier.prototype.notify = function(code, reason) {
debug('notify()');
var state,
self = this;
if (this.active === false) {
return;
}
reason = reason || JsSIP_C.REASON_PHRASE[code] || '';
if (code >= 200) {
state = 'terminated;reason=noresource';
} else {
state = 'active;expires='+ this.expires;
}
// put this in a try/catch block
var request = new RTCSession_Request(this.session, JsSIP_C.NOTIFY);
request.send({
extraHeaders: [
'Event: '+ C.event_type +';id='+ self.id,
'Subscription-State: '+ state,
'Content-Type: '+ C.body_type
],
body: 'SIP/2.0 ' + code + ' ' + reason,
eventHandlers: {
// if a negative response is received, subscription is canceled
onErrorResponse: function() { self.active = false; }
}
});
};
},{"../Constants":1,"./Request":15,"debug":34}],14:[function(require,module,exports){
module.exports = ReferSubscriber;
var C = {
expires: 120
};
/**
* Dependencies.
*/
var util = require('util');
var events = require('events');
var debug = require('debug')('JsSIP:RTCSession:ReferSubscriber');
var JsSIP_C = require('../Constants');
var Grammar = require('../Grammar');
var RTCSession_Request = require('./Request');
function ReferSubscriber(session) {
this.session = session;
this.timer = null;
// Instance of REFER OutgoingRequest
this.outgoingRequest = null;
events.EventEmitter.call(this);
}
util.inherits(ReferSubscriber, events.EventEmitter);
ReferSubscriber.prototype.sendRefer = function(target, options) {
debug('sendRefer()');
var extraHeaders, eventHandlers, referTo,
replaces = null,
self = this;
// Get REFER options
options = options || {};
extraHeaders = options.extraHeaders ? options.extraHeaders.slice() : [];
eventHandlers = options.eventHandlers || {};
// Set event handlers
for (var event in eventHandlers) {
this.on(event, eventHandlers[event]);
}
// Replaces URI header field
if (options.replaces) {
replaces = options.replaces.request.call_id;
replaces += ';to-tag='+ options.replaces.to_tag;
replaces += ';from-tag='+ options.replaces.from_tag;
replaces = encodeURIComponent(replaces);
}
// Refer-To header field
referTo = 'Refer-To: <'+ target + (replaces?'?Replaces='+ replaces:'') +'>';
extraHeaders.push(referTo);
var request = new RTCSession_Request(this.session, JsSIP_C.REFER);
this.timer = setTimeout(function() {
removeSubscriber.call(self);
}, C.expires * 1000);
request.send({
extraHeaders: extraHeaders,
eventHandlers: {
onSuccessResponse: function(response) {
self.emit('requestSucceeded', {
response: response
});
},
onErrorResponse: function(response) {
self.emit('requestFailed', {
response: response,
cause: JsSIP_C.causes.REJECTED
});
},
onTransportError: function() {
removeSubscriber.call(self);
self.emit('requestFailed', {
response: null,
cause: JsSIP_C.causes.CONNECTION_ERROR
});
},
onRequestTimeout: function() {
removeSubscriber.call(self);
self.emit('requestFailed', {
response: null,
cause: JsSIP_C.causes.REQUEST_TIMEOUT
});
},
onDialogError: function() {
removeSubscriber.call(self);
self.emit('requestFailed', {
response: null,
cause: JsSIP_C.causes.DIALOG_ERROR
});
}
}
});
this.outgoingRequest = request.outgoingRequest;
};
ReferSubscriber.prototype.receiveNotify = function(request) {
debug('receiveNotify()');
var status_line;
if (!request.body) {
return;
}
status_line = Grammar.parse(request.body, 'Status_Line');
if(status_line === -1) {
debug('receiveNotify() | error parsing NOTIFY body: "' + request.body + '"');
return;
}
switch(true) {
case /^100$/.test(status_line.status_code):
this.emit('trying', {
request: request,
status_line: status_line
});
break;
case /^1[0-9]{2}$/.test(status_line.status_code):
this.emit('progress', {
request: request,
status_line: status_line
});
break;
case /^2[0-9]{2}$/.test(status_line.status_code):
removeSubscriber.call(this);
this.emit('accepted', {
request: request,
status_line: status_line
});
break;
default:
removeSubscriber.call(this);
this.emit('failed', {
request: request,
status_line: status_line
});
break;
}
};
// remove refer subscriber from the session
function removeSubscriber() {
console.log('removeSubscriber()');
clearTimeout(this.timer);
this.session.referSubscriber = null;
}
},{"../Constants":1,"../Grammar":6,"./Request":15,"debug":34,"events":28,"util":32}],15:[function(require,module,exports){
module.exports = Request;
/**
* Dependencies.
*/
var debug = require('debug')('JsSIP:RTCSession:Request');
var debugerror = require('debug')('JsSIP:ERROR:RTCSession:Request');
debugerror.log = console.warn.bind(console);
var JsSIP_C = require('../Constants');
var Exceptions = require('../Exceptions');
var RTCSession = require('../RTCSession');
function Request(session, method) {
debug('new | %s', method);
this.session = session;
this.method = method;
// Instance of OutgoingRequest
this.outgoingRequest = null;
// Check RTCSession Status
if (this.session.status !== RTCSession.C.STATUS_1XX_RECEIVED &&
this.session.status !== RTCSession.C.STATUS_WAITING_FOR_ANSWER &&
this.session.status !== RTCSession.C.STATUS_WAITING_FOR_ACK &&
this.session.status !== RTCSession.C.STATUS_CONFIRMED &&
this.session.status !== RTCSession.C.STATUS_TERMINATED) {
throw new Exceptions.InvalidStateError(this.session.status);
}
/*
* Allow sending BYE in TERMINATED status since the RTCSession
* could had been terminated before the ACK had arrived.
* RFC3261 Section 15, Paragraph 2
*/
else if (this.session.status === RTCSession.C.STATUS_TERMINATED && method !== JsSIP_C.BYE) {
throw new Exceptions.InvalidStateError(this.session.status);
}
}
Request.prototype.send = function(options) {
options = options || {};
var
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [],
body = options.body || null;
this.eventHandlers = options.eventHandlers || {};
this.outgoingRequest = this.session.dialog.sendRequest(this, this.method, {
extraHeaders: extraHeaders,
body: body
});
};
Request.prototype.receiveResponse = function(response) {
switch(true) {
case /^1[0-9]{2}$/.test(response.status_code):
debug('onProgressResponse');
if (this.eventHandlers.onProgressResponse) { this.eventHandlers.onProgressResponse(response); }
break;
case /^2[0-9]{2}$/.test(response.status_code):
debug('onSuccessResponse');
if (this.eventHandlers.onSuccessResponse) { this.eventHandlers.onSuccessResponse(response); }
break;
default:
debug('onErrorResponse');
if (this.eventHandlers.onErrorResponse) { this.eventHandlers.onErrorResponse(response); }
break;
}
};
Request.prototype.onRequestTimeout = function() {
debugerror('onRequestTimeout');
if (this.eventHandlers.onRequestTimeout) { this.eventHandlers.onRequestTimeout(); }
};
Request.prototype.onTransportError = function() {
debugerror('onTransportError');
if (this.eventHandlers.onTransportError) { this.eventHandlers.onTransportError(); }
};
Request.prototype.onDialogError = function() {
debugerror('onDialogError');
if (this.eventHandlers.onDialogError) { this.eventHandlers.onDialogError(); }
};
},{"../Constants":1,"../Exceptions":5,"../RTCSession":11,"debug":34}],16:[function(require,module,exports){
module.exports = Registrator;
/**
* Dependecies
*/
var debug = require('debug')('JsSIP:Registrator');
var Utils = require('./Utils');
var JsSIP_C = require('./Constants');
var SIPMessage = require('./SIPMessage');
var RequestSender = require('./RequestSender');
function Registrator(ua, transport) {
var reg_id=1; //Force reg_id to 1.
this.ua = ua;
this.transport = transport;
this.registrar = ua.configuration.registrar_server;
this.expires = ua.configuration.register_expires;
// Call-ID and CSeq values RFC3261 10.2
this.call_id = Utils.createRandomToken(22);
this.cseq = 0;
// this.to_uri
this.to_uri = ua.configuration.uri;
this.registrationTimer = null;
// Set status
this.registered = false;
// Contact header
this.contact = this.ua.contact.toString();
// sip.ice media feature tag (RFC 5768)
this.contact += ';+sip.ice';
// Custom headers for REGISTER and un-REGISTER.
this.extraHeaders = [];
// Custom Contact header params for REGISTER and un-REGISTER.
this.extraContactParams = '';
if(reg_id) {
this.contact += ';reg-id='+ reg_id;
this.contact += ';+sip.instance="<urn:uuid:'+ this.ua.configuration.instance_id+'>"';
}
}
Registrator.prototype = {
setExtraHeaders: function(extraHeaders) {
if (! Array.isArray(extraHeaders)) {
extraHeaders = [];
}
this.extraHeaders = extraHeaders.slice();
},
setExtraContactParams: function(extraContactParams) {
if (! (extraContactParams instanceof Object)) {
extraContactParams = {};
}
// Reset it.
this.extraContactParams = '';
for(var param_key in extraContactParams) {
var param_value = extraContactParams[param_key];
this.extraContactParams += (';' + param_key);
if (param_value) {
this.extraContactParams += ('=' + param_value);
}
}
},
register: function() {
var request_sender, cause, extraHeaders,
self = this;
extraHeaders = this.extraHeaders.slice();
extraHeaders.push('Contact: ' + this.contact + ';expires=' + this.expires + this.extraContactParams);
extraHeaders.push('Expires: '+ this.expires);
this.request = new SIPMessage.OutgoingRequest(JsSIP_C.REGISTER, this.registrar, this.ua, {
'to_uri': this.to_uri,
'call_id': this.call_id,
'cseq': (this.cseq += 1)
}, extraHeaders);
request_sender = new RequestSender(this, this.ua);
this.receiveResponse = function(response) {
var contact, expires,
contacts = response.getHeaders('contact').length;
// Discard responses to older REGISTER/un-REGISTER requests.
if(response.cseq !== this.cseq) {
return;
}
// Clear registration timer
if (this.registrationTimer !== null) {
clearTimeout(this.registrationTimer);
this.registrationTimer = null;
}
switch(true) {
case /^1[0-9]{2}$/.test(response.status_code):
// Ignore provisional responses.
break;
case /^2[0-9]{2}$/.test(response.status_code):
if(response.hasHeader('expires')) {
expires = response.getHeader('expires');
}
// Search the Contact pointing to us and update the expires value accordingly.
if (!contacts) {
debug('no Contact header in response to REGISTER, response ignored');
break;
}
while(contacts--) {
contact = response.parseHeader('contact', contacts);
if(contact.uri.user === this.ua.contact.uri.user) {
expires = contact.getParam('expires');
break;
} else {
contact = null;
}
}
if (!contact) {
debug('no Contact header pointing to us, response ignored');
break;
}
if(!expires) {
expires = this.expires;
}
// Re-Register before the expiration interval has elapsed.
// For that, decrease the expires value. ie: 3 seconds
this.registrationTimer = setTimeout(function() {
self.registrationTimer = null;
self.register();
}, (expires * 1000) - 3000);
//Save gruu values
if (contact.hasParam('temp-gruu')) {
this.ua.contact.temp_gruu = contact.getParam('temp-gruu').replace(/"/g,'');
}
if (contact.hasParam('pub-gruu')) {
this.ua.contact.pub_gruu = contact.getParam('pub-gruu').replace(/"/g,'');
}
if (! this.registered) {
this.registered = true;
this.ua.registered({
response: response
});
}
break;
// Interval too brief RFC3261 10.2.8
case /^423$/.test(response.status_code):
if(response.hasHeader('min-expires')) {
// Increase our registration interval to the suggested minimum
this.expires = response.getHeader('min-expires');
// Attempt the registration again immediately
this.register();
} else { //This response MUST contain a Min-Expires header field
debug('423 response received for REGISTER without Min-Expires');
this.registrationFailure(response, JsSIP_C.causes.SIP_FAILURE_CODE);
}
break;
default:
cause = Utils.sipErrorCause(response.status_code);
this.registrationFailure(response, cause);
}
};
this.onRequestTimeout = function() {
this.registrationFailure(null, JsSIP_C.causes.REQUEST_TIMEOUT);
};
this.onTransportError = function() {
this.registrationFailure(null, JsSIP_C.causes.CONNECTION_ERROR);
};
request_sender.send();
},
unregister: function(options) {
var extraHeaders;
if(!this.registered) {
debug('already unregistered');
return;
}
options = options || {};
this.registered = false;
// Clear the registration timer.
if (this.registrationTimer !== null) {
clearTimeout(this.registrationTimer);
this.registrationTimer = null;
}
extraHeaders = this.extraHeaders.slice();
if(options.all) {
extraHeaders.push('Contact: *' + this.extraContactParams);
extraHeaders.push('Expires: 0');
this.request = new SIPMessage.OutgoingRequest(JsSIP_C.REGISTER, this.registrar, this.ua, {
'to_uri': this.to_uri,
'call_id': this.call_id,
'cseq': (this.cseq += 1)
}, extraHeaders);
} else {
extraHeaders.push('Contact: '+ this.contact + ';expires=0' + this.extraContactParams);
extraHeaders.push('Expires: 0');
this.request = new SIPMessage.OutgoingRequest(JsSIP_C.REGISTER, this.registrar, this.ua, {
'to_uri': this.to_uri,
'call_id': this.call_id,
'cseq': (this.cseq += 1)
}, extraHeaders);
}
var request_sender = new RequestSender(this, this.ua);
this.receiveResponse = function(response) {
var cause;
switch(true) {
case /^1[0-9]{2}$/.test(response.status_code):
// Ignore provisional responses.
break;
case /^2[0-9]{2}$/.test(response.status_code):
this.unregistered(response);
break;
default:
cause = Utils.sipErrorCause(response.status_code);
this.unregistered(response, cause);
}
};
this.onRequestTimeout = function() {
this.unregistered(null, JsSIP_C.causes.REQUEST_TIMEOUT);
};
this.onTransportError = function() {
this.unregistered(null, JsSIP_C.causes.CONNECTION_ERROR);
};
request_sender.send();
},
registrationFailure: function(response, cause) {
this.ua.registrationFailed({
response: response || null,
cause: cause
});
if (this.registered) {
this.registered = false;
this.ua.unregistered({
response: response || null,
cause: cause
});
}
},
unregistered: function(response, cause) {
this.registered = false;
this.ua.unregistered({
response: response || null,
cause: cause || null
});
},
onTransportClosed: function() {
if (this.registrationTimer !== null) {
clearTimeout(this.registrationTimer);
this.registrationTimer = null;
}
if(this.registered) {
this.registered = false;
this.ua.unregistered({});
}
},
close: function() {
if (this.registered) {
this.unregister();
}
}
};
},{"./Constants":1,"./RequestSender":17,"./SIPMessage":18,"./Utils":25,"debug":34}],17:[function(require,module,exports){
module.exports = RequestSender;
/**
* Dependencies.
*/
var debug = require('debug')('JsSIP:RequestSender');
var JsSIP_C = require('./Constants');
var UA = require('./UA');
var DigestAuthentication = require('./DigestAuthentication');
var Transactions = require('./Transactions');
function RequestSender(applicant, ua) {
this.ua = ua;
this.applicant = applicant;
this.method = applicant.request.method;
this.request = applicant.request;
this.auth = null;
this.challenged = false;
this.staled = false;
// If ua is in closing process or even closed just allow sending Bye and ACK
if (ua.status === UA.C.STATUS_USER_CLOSED && (this.method !== JsSIP_C.BYE || this.method !== JsSIP_C.ACK)) {
this.onTransportError();
}
}
/**
* Create the client transaction and send the message.
*/
RequestSender.prototype = {
send: function() {
switch(this.method) {
case 'INVITE':
this.clientTransaction = new Transactions.InviteClientTransaction(this, this.request, this.ua.transport);
break;
case 'ACK':
this.clientTransaction = new Transactions.AckClientTransaction(this, this.request, this.ua.transport);
break;
default:
this.clientTransaction = new Transactions.NonInviteClientTransaction(this, this.request, this.ua.transport);
}
this.clientTransaction.send();
},
/**
* Callback fired when receiving a request timeout error from the client transaction.
* To be re-defined by the applicant.
*/
onRequestTimeout: function() {
this.applicant.onRequestTimeout();
},
/**
* Callback fired when receiving a transport error from the client transaction.
* To be re-defined by the applicant.
*/
onTransportError: function() {
this.applicant.onTransportError();
},
/**
* Called from client transaction when receiving a correct response to the request.
* Authenticate request if needed or pass the response back to the applicant.
*/
receiveResponse: function(response) {
var
cseq, challenge, authorization_header_name,
status_code = response.status_code;
/*
* Authentication
* Authenticate once. _challenged_ flag used to avoid infinite authentications.
*/
if ((status_code === 401 || status_code === 407) &&
(this.ua.configuration.password !== null || this.ua.configuration.ha1 !== null)) {
// Get and parse the appropriate WWW-Authenticate or Proxy-Authenticate header.
if (response.status_code === 401) {
challenge = response.parseHeader('www-authenticate');
authorization_header_name = 'authorization';
} else {
challenge = response.parseHeader('proxy-authenticate');
authorization_header_name = 'proxy-authorization';
}
// Verify it seems a valid challenge.
if (!challenge) {
debug(response.status_code + ' with wrong or missing challenge, cannot authenticate');
this.applicant.receiveResponse(response);
return;
}
if (!this.challenged || (!this.staled && challenge.stale === true)) {
if (!this.auth) {
this.auth = new DigestAuthentication({
username : this.ua.configuration.authorization_user,
password : this.ua.configuration.password,
realm : this.ua.configuration.realm,
ha1 : this.ua.configuration.ha1
});
}
// Verify that the challenge is really valid.
if (!this.auth.authenticate(this.request, challenge)) {
this.applicant.receiveResponse(response);
return;
}
this.challenged = true;
// Update ha1 and realm in the UA.
this.ua.set('realm', this.auth.get('realm'));
this.ua.set('ha1', this.auth.get('ha1'));
if (challenge.stale) {
this.staled = true;
}
if (response.method === JsSIP_C.REGISTER) {
cseq = this.applicant.cseq += 1;
} else if (this.request.dialog) {
cseq = this.request.dialog.local_seqnum += 1;
} else {
cseq = this.request.cseq + 1;
}
this.request = this.applicant.request = this.request.clone();
this.request.cseq = cseq;
this.request.setHeader('cseq', cseq +' '+ this.method);
this.request.setHeader(authorization_header_name, this.auth.toString());
this.send();
} else {
this.applicant.receiveResponse(response);
}
} else {
this.applicant.receiveResponse(response);
}
}
};
},{"./Constants":1,"./DigestAuthentication":4,"./Transactions":21,"./UA":23,"debug":34}],18:[function(require,module,exports){
module.exports = {
OutgoingRequest: OutgoingRequest,
IncomingRequest: IncomingRequest,
IncomingResponse: IncomingResponse
};
/**
* Dependencies.
*/
var debug = require('debug')('JsSIP:SIPMessage');
var sdp_transform = require('sdp-transform');
var JsSIP_C = require('./Constants');
var Utils = require('./Utils');
var NameAddrHeader = require('./NameAddrHeader');
var Grammar = require('./Grammar');
/**
* -param {String} method request method
* -param {String} ruri request uri
* -param {UA} ua
* -param {Object} params parameters that will have priority over ua.configuration parameters:
* <br>
* - cseq, call_id, from_tag, from_uri, from_display_name, to_uri, to_tag, route_set
* -param {Object} [headers] extra headers
* -param {String} [body]
*/
function OutgoingRequest(method, ruri, ua, params, extraHeaders, body) {
var
to,
from,
call_id,
cseq;
params = params || {};
// Mandatory parameters check
if(!method || !ruri || !ua) {
return null;
}
this.ua = ua;
this.headers = {};
this.method = method;
this.ruri = ruri;
this.body = body;
this.extraHeaders = extraHeaders && extraHeaders.slice() || [];
// Fill the Common SIP Request Headers
// Route
if (params.route_set) {
this.setHeader('route', params.route_set);
} else if (ua.configuration.use_preloaded_route) {
this.setHeader('route', '<' + ua.transport.sip_uri + ';lr>');
}
// Via
// Empty Via header. Will be filled by the client transaction.
this.setHeader('via', '');
// Max-Forwards
this.setHeader('max-forwards', JsSIP_C.MAX_FORWARDS);
// To
to = (params.to_display_name || params.to_display_name === 0) ? '"' + params.to_display_name + '" ' : '';
to += '<' + (params.to_uri || ruri) + '>';
to += params.to_tag ? ';tag=' + params.to_tag : '';
this.to = new NameAddrHeader.parse(to);
this.setHeader('to', to);
// From
if (params.from_display_name || params.from_display_name === 0) {
from = '"' + params.from_display_name + '" ';
} else if (ua.configuration.display_name) {
from = '"' + ua.configuration.display_name + '" ';
} else {
from = '';
}
from += '<' + (params.from_uri || ua.configuration.uri) + '>;tag=';
from += params.from_tag || Utils.newTag();
this.from = new NameAddrHeader.parse(from);
this.setHeader('from', from);
// Call-ID
call_id = params.call_id || (ua.configuration.jssip_id + Utils.createRandomToken(15));
this.call_id = call_id;
this.setHeader('call-id', call_id);
// CSeq
cseq = params.cseq || Math.floor(Math.random() * 10000);
this.cseq = cseq;
this.setHeader('cseq', cseq + ' ' + method);
}
OutgoingRequest.prototype = {
/**
* Replace the the given header by the given value.
* -param {String} name header name
* -param {String | Array} value header value
*/
setHeader: function(name, value) {
var regexp, idx;
// Remove the header from extraHeaders if present.
regexp = new RegExp('^\\s*'+ name +'\\s*:','i');
for (idx=0; idx<this.extraHeaders.length; idx++) {
if (regexp.test(this.extraHeaders[idx])) {
this.extraHeaders.splice(idx, 1);
}
}
this.headers[Utils.headerize(name)] = (Array.isArray(value)) ? value : [value];
},
/**
* Get the value of the given header name at the given position.
* -param {String} name header name
* -returns {String|undefined} Returns the specified header, null if header doesn't exist.
*/
getHeader: function(name) {
var regexp, idx,
length = this.extraHeaders.length,
header = this.headers[Utils.headerize(name)];
if(header) {
if(header[0]) {
return header[0];
}
} else {
regexp = new RegExp('^\\s*'+ name +'\\s*:','i');
for (idx=0; idx<length; idx++) {
header = this.extraHeaders[idx];
if (regexp.test(header)) {
return header.substring(header.indexOf(':')+1).trim();
}
}
}
return;
},
/**
* Get the header/s of the given name.
* -param {String} name header name
* -returns {Array} Array with all the headers of the specified name.
*/
getHeaders: function(name) {
var idx, length, regexp,
header = this.headers[Utils.headerize(name)],
result = [];
if (header) {
length = header.length;
for (idx = 0; idx < length; idx++) {
result.push(header[idx]);
}
return result;
} else {
length = this.extraHeaders.length;
regexp = new RegExp('^\\s*'+ name +'\\s*:','i');
for (idx=0; idx<length; idx++) {
header = this.extraHeaders[idx];
if (regexp.test(header)) {
result.push(header.substring(header.indexOf(':')+1).trim());
}
}
return result;
}
},
/**
* Verify the existence of the given header.
* -param {String} name header name
* -returns {boolean} true if header with given name exists, false otherwise
*/
hasHeader: function(name) {
var regexp, idx,
length = this.extraHeaders.length;
if (this.headers[Utils.headerize(name)]) {
return true;
} else {
regexp = new RegExp('^\\s*'+ name +'\\s*:','i');
for (idx=0; idx<length; idx++) {
if (regexp.test(this.extraHeaders[idx])) {
return true;
}
}
}
return false;
},
/**
* Parse the current body as a SDP and store the resulting object
* into this.sdp.
* -param {Boolean} force: Parse even if this.sdp already exists.
*
* Returns this.sdp.
*/
parseSDP: function(force) {
if (!force && this.sdp) {
return this.sdp;
} else {
this.sdp = sdp_transform.parse(this.body || '');
return this.sdp;
}
},
toString: function() {
var msg = '', header, length, idx,
supported = [];
msg += this.method + ' ' + this.ruri + ' SIP/2.0\r\n';
for (header in this.headers) {
length = this.headers[header].length;
for (idx = 0; idx < length; idx++) {
msg += header + ': ' + this.headers[header][idx] + '\r\n';
}
}
length = this.extraHeaders.length;
for (idx = 0; idx < length; idx++) {
msg += this.extraHeaders[idx].trim() +'\r\n';
}
// Supported
switch (this.method) {
case JsSIP_C.REGISTER:
supported.push('path', 'gruu');
break;
case JsSIP_C.INVITE:
if (this.ua.configuration.session_timers) {
supported.push('timer');
}
if (this.ua.contact.pub_gruu || this.ua.contact.temp_gruu) {
supported.push('gruu');
}
supported.push('ice','replaces');
break;
case JsSIP_C.UPDATE:
if (this.ua.configuration.session_timers) {
supported.push('timer');
}
supported.push('ice');
break;
}
supported.push('outbound');
// Allow
msg += 'Allow: '+ JsSIP_C.ALLOWED_METHODS +'\r\n';
msg += 'Supported: ' + supported +'\r\n';
msg += 'User-Agent: ' + JsSIP_C.USER_AGENT +'\r\n';
if (this.body) {
length = Utils.str_utf8_length(this.body);
msg += 'Content-Length: ' + length + '\r\n\r\n';
msg += this.body;
} else {
msg += 'Content-Length: 0\r\n\r\n';
}
return msg;
},
clone: function() {
var request = new OutgoingRequest(this.method, this.ruri, this.ua);
Object.keys(this.headers).forEach(function(name) {
request.headers[name] = this.headers[name].slice();
}, this);
request.body = this.body;
request.extraHeaders = this.extraHeaders && this.extraHeaders.slice() || [];
request.to = this.to;
request.from = this.from;
request.call_id = this.call_id;
request.cseq = this.cseq;
return request;
}
};
function IncomingMessage(){
this.data = null;
this.headers = null;
this.method = null;
this.via = null;
this.via_branch = null;
this.call_id = null;
this.cseq = null;
this.from = null;
this.from_tag = null;
this.to = null;
this.to_tag = null;
this.body = null;
this.sdp = null;
}
IncomingMessage.prototype = {
/**
* Insert a header of the given name and value into the last position of the
* header array.
*/
addHeader: function(name, value) {
var header = { raw: value };
name = Utils.headerize(name);
if(this.headers[name]) {
this.headers[name].push(header);
} else {
this.headers[name] = [header];
}
},
/**
* Get the value of the given header name at the given position.
*/
getHeader: function(name) {
var header = this.headers[Utils.headerize(name)];
if(header) {
if(header[0]) {
return header[0].raw;
}
} else {
return;
}
},
/**
* Get the header/s of the given name.
*/
getHeaders: function(name) {
var idx, length,
header = this.headers[Utils.headerize(name)],
result = [];
if(!header) {
return [];
}
length = header.length;
for (idx = 0; idx < length; idx++) {
result.push(header[idx].raw);
}
return result;
},
/**
* Verify the existence of the given header.
*/
hasHeader: function(name) {
return(this.headers[Utils.headerize(name)]) ? true : false;
},
/**
* Parse the given header on the given index.
* -param {String} name header name
* -param {Number} [idx=0] header index
* -returns {Object|undefined} Parsed header object, undefined if the header is not present or in case of a parsing error.
*/
parseHeader: function(name, idx) {
var header, value, parsed;
name = Utils.headerize(name);
idx = idx || 0;
if(!this.headers[name]) {
debug('header "' + name + '" not present');
return;
} else if(idx >= this.headers[name].length) {
debug('not so many "' + name + '" headers present');
return;
}
header = this.headers[name][idx];
value = header.raw;
if(header.parsed) {
return header.parsed;
}
//substitute '-' by '_' for grammar rule matching.
parsed = Grammar.parse(value, name.replace(/-/g, '_'));
if(parsed === -1) {
this.headers[name].splice(idx, 1); //delete from headers
debug('error parsing "' + name + '" header field with value "' + value + '"');
return;
} else {
header.parsed = parsed;
return parsed;
}
},
/**
* Message Header attribute selector. Alias of parseHeader.
* -param {String} name header name
* -param {Number} [idx=0] header index
* -returns {Object|undefined} Parsed header object, undefined if the header is not present or in case of a parsing error.
*
* -example
* message.s('via',3).port
*/
s: function(name, idx) {
return this.parseHeader(name, idx);
},
/**
* Replace the value of the given header by the value.
* -param {String} name header name
* -param {String} value header value
*/
setHeader: function(name, value) {
var header = { raw: value };
this.headers[Utils.headerize(name)] = [header];
},
/**
* Parse the current body as a SDP and store the resulting object
* into this.sdp.
* -param {Boolean} force: Parse even if this.sdp already exists.
*
* Returns this.sdp.
*/
parseSDP: function(force) {
if (!force && this.sdp) {
return this.sdp;
} else {
this.sdp = sdp_transform.parse(this.body || '');
return this.sdp;
}
},
toString: function() {
return this.data;
}
};
function IncomingRequest(ua) {
this.ua = ua;
this.headers = {};
this.ruri = null;
this.transport = null;
this.server_transaction = null;
}
IncomingRequest.prototype = new IncomingMessage();
/**
* Stateful reply.
* -param {Number} code status code
* -param {String} reason reason phrase
* -param {Object} headers extra headers
* -param {String} body body
* -param {Function} [onSuccess] onSuccess callback
* -param {Function} [onFailure] onFailure callback
*/
IncomingRequest.prototype.reply = function(code, reason, extraHeaders, body, onSuccess, onFailure) {
var rr, vias, length, idx, response,
supported = [],
to = this.getHeader('To'),
r = 0,
v = 0;
code = code || null;
reason = reason || null;
// Validate code and reason values
if (!code || (code < 100 || code > 699)) {
throw new TypeError('Invalid status_code: '+ code);
} else if (reason && typeof reason !== 'string' && !(reason instanceof String)) {
throw new TypeError('Invalid reason_phrase: '+ reason);
}
reason = reason || JsSIP_C.REASON_PHRASE[code] || '';
extraHeaders = extraHeaders && extraHeaders.slice() || [];
response = 'SIP/2.0 ' + code + ' ' + reason + '\r\n';
if(this.method === JsSIP_C.INVITE && code > 100 && code <= 200) {
rr = this.getHeaders('record-route');
length = rr.length;
for(r; r < length; r++) {
response += 'Record-Route: ' + rr[r] + '\r\n';
}
}
vias = this.getHeaders('via');
length = vias.length;
for(v; v < length; v++) {
response += 'Via: ' + vias[v] + '\r\n';
}
if(!this.to_tag && code > 100) {
to += ';tag=' + Utils.newTag();
} else if(this.to_tag && !this.s('to').hasParam('tag')) {
to += ';tag=' + this.to_tag;
}
response += 'To: ' + to + '\r\n';
response += 'From: ' + this.getHeader('From') + '\r\n';
response += 'Call-ID: ' + this.call_id + '\r\n';
response += 'CSeq: ' + this.cseq + ' ' + this.method + '\r\n';
length = extraHeaders.length;
for (idx = 0; idx < length; idx++) {
response += extraHeaders[idx].trim() +'\r\n';
}
// Supported
switch (this.method) {
case JsSIP_C.INVITE:
if (this.ua.configuration.session_timers) {
supported.push('timer');
}
if (this.ua.contact.pub_gruu || this.ua.contact.temp_gruu) {
supported.push('gruu');
}
supported.push('ice','replaces');
break;
case JsSIP_C.UPDATE:
if (this.ua.configuration.session_timers) {
supported.push('timer');
}
if (body) {
supported.push('ice');
}
supported.push('replaces');
}
supported.push('outbound');
// Allow and Accept
if (this.method === JsSIP_C.OPTIONS) {
response += 'Allow: '+ JsSIP_C.ALLOWED_METHODS +'\r\n';
response += 'Accept: '+ JsSIP_C.ACCEPTED_BODY_TYPES +'\r\n';
} else if (code === 405) {
response += 'Allow: '+ JsSIP_C.ALLOWED_METHODS +'\r\n';
} else if (code === 415 ) {
response += 'Accept: '+ JsSIP_C.ACCEPTED_BODY_TYPES +'\r\n';
}
response += 'Supported: ' + supported +'\r\n';
if(body) {
length = Utils.str_utf8_length(body);
response += 'Content-Type: application/sdp\r\n';
response += 'Content-Length: ' + length + '\r\n\r\n';
response += body;
} else {
response += 'Content-Length: ' + 0 + '\r\n\r\n';
}
this.server_transaction.receiveResponse(code, response, onSuccess, onFailure);
};
/**
* Stateless reply.
* -param {Number} code status code
* -param {String} reason reason phrase
*/
IncomingRequest.prototype.reply_sl = function(code, reason) {
var to, response,
v = 0,
vias = this.getHeaders('via'),
length = vias.length;
code = code || null;
reason = reason || null;
// Validate code and reason values
if (!code || (code < 100 || code > 699)) {
throw new TypeError('Invalid status_code: '+ code);
} else if (reason && typeof reason !== 'string' && !(reason instanceof String)) {
throw new TypeError('Invalid reason_phrase: '+ reason);
}
reason = reason || JsSIP_C.REASON_PHRASE[code] || '';
response = 'SIP/2.0 ' + code + ' ' + reason + '\r\n';
for(v; v < length; v++) {
response += 'Via: ' + vias[v] + '\r\n';
}
to = this.getHeader('To');
if(!this.to_tag && code > 100) {
to += ';tag=' + Utils.newTag();
} else if(this.to_tag && !this.s('to').hasParam('tag')) {
to += ';tag=' + this.to_tag;
}
response += 'To: ' + to + '\r\n';
response += 'From: ' + this.getHeader('From') + '\r\n';
response += 'Call-ID: ' + this.call_id + '\r\n';
response += 'CSeq: ' + this.cseq + ' ' + this.method + '\r\n';
response += 'Content-Length: ' + 0 + '\r\n\r\n';
this.transport.send(response);
};
function IncomingResponse() {
this.headers = {};
this.status_code = null;
this.reason_phrase = null;
}
IncomingResponse.prototype = new IncomingMessage();
},{"./Constants":1,"./Grammar":6,"./NameAddrHeader":9,"./Utils":25,"debug":34,"sdp-transform":37}],19:[function(require,module,exports){
module.exports = Socket;
/**
* Interface documentation: http://jssip.net/documentation/$last_version/api/socket/
*
* interface Socket {
* attribute String via_transport
* attribute String url
* attribute String sip_uri
*
* method connect();
* method disconnect();
* method send(data);
*
* attribute EventHandler onconnect
* attribute EventHandler ondisconnect
* attribute EventHandler ondata
* }
*
*/
/**
* Dependencies.
*/
var Utils = require('./Utils');
var Grammar = require('./Grammar');
var debugerror = require('debug')('JsSIP:ERROR:Socket');
debugerror.log = console.warn.bind(console);
function Socket() {}
Socket.isSocket = function(socket) {
// Ignore if an array is given
if (Array.isArray(socket)) {
return false;
}
if (typeof socket === 'undefined') {
debugerror('undefined JsSIP.Socket instance');
return false;
}
// Check Properties
try {
if (!Utils.isString(socket.url)) {
debugerror('missing or invalid JsSIP.Socket url property');
throw new Error();
}
if (!Utils.isString(socket.via_transport)) {
debugerror('missing or invalid JsSIP.Socket via_transport property');
throw new Error();
}
if (Grammar.parse(socket.sip_uri, 'SIP_URI') === -1) {
debugerror('missing or invalid JsSIP.Socket sip_uri property');
throw new Error();
}
} catch(e) {
return false;
}
// Check Methods
try {
['connect', 'disconnect', 'send'].forEach(function(method) {
if (!Utils.isFunction(socket[method])) {
debugerror('missing or invalid JsSIP.Socket method: ' + method);
throw new Error();
}
});
} catch(e) {
return false;
}
return true;
};
},{"./Grammar":6,"./Utils":25,"debug":34}],20:[function(require,module,exports){
var T1 = 500,
T2 = 4000,
T4 = 5000;
var Timers = {
T1: T1,
T2: T2,
T4: T4,
TIMER_B: 64 * T1,
TIMER_D: 0 * T1,
TIMER_F: 64 * T1,
TIMER_H: 64 * T1,
TIMER_I: 0 * T1,
TIMER_J: 0 * T1,
TIMER_K: 0 * T4,
TIMER_L: 64 * T1,
TIMER_M: 64 * T1,
PROVISIONAL_RESPONSE_INTERVAL: 60000 // See RFC 3261 Section 13.3.1.1
};
module.exports = Timers;
},{}],21:[function(require,module,exports){
module.exports = {
C: null,
NonInviteClientTransaction: NonInviteClientTransaction,
InviteClientTransaction: InviteClientTransaction,
AckClientTransaction: AckClientTransaction,
NonInviteServerTransaction: NonInviteServerTransaction,
InviteServerTransaction: InviteServerTransaction,
checkTransaction: checkTransaction
};
var C = {
// Transaction states
STATUS_TRYING: 1,
STATUS_PROCEEDING: 2,
STATUS_CALLING: 3,
STATUS_ACCEPTED: 4,
STATUS_COMPLETED: 5,
STATUS_TERMINATED: 6,
STATUS_CONFIRMED: 7,
// Transaction types
NON_INVITE_CLIENT: 'nict',
NON_INVITE_SERVER: 'nist',
INVITE_CLIENT: 'ict',
INVITE_SERVER: 'ist'
};
/**
* Expose C object.
*/
module.exports.C = C;
/**
* Dependencies.
*/
var util = require('util');
var events = require('events');
var debugnict = require('debug')('JsSIP:NonInviteClientTransaction');
var debugict = require('debug')('JsSIP:InviteClientTransaction');
var debugact = require('debug')('JsSIP:AckClientTransaction');
var debugnist = require('debug')('JsSIP:NonInviteServerTransaction');
var debugist = require('debug')('JsSIP:InviteServerTransaction');
var JsSIP_C = require('./Constants');
var Timers = require('./Timers');
function NonInviteClientTransaction(request_sender, request, transport) {
var via;
this.type = C.NON_INVITE_CLIENT;
this.transport = transport;
this.id = 'z9hG4bK' + Math.floor(Math.random() * 10000000);
this.request_sender = request_sender;
this.request = request;
via = 'SIP/2.0/' + transport.via_transport;
via += ' ' + request_sender.ua.configuration.via_host + ';branch=' + this.id;
this.request.setHeader('via', via);
this.request_sender.ua.newTransaction(this);
events.EventEmitter.call(this);
}
util.inherits(NonInviteClientTransaction, events.EventEmitter);
NonInviteClientTransaction.prototype.stateChanged = function(state) {
this.state = state;
this.emit('stateChanged');
};
NonInviteClientTransaction.prototype.send = function() {
var tr = this;
this.stateChanged(C.STATUS_TRYING);
this.F = setTimeout(function() {tr.timer_F();}, Timers.TIMER_F);
if(!this.transport.send(this.request)) {
this.onTransportError();
}
};
NonInviteClientTransaction.prototype.onTransportError = function() {
debugnict('transport error occurred, deleting transaction ' + this.id);
clearTimeout(this.F);
clearTimeout(this.K);
this.stateChanged(C.STATUS_TERMINATED);
this.request_sender.ua.destroyTransaction(this);
this.request_sender.onTransportError();
};
NonInviteClientTransaction.prototype.timer_F = function() {
debugnict('Timer F expired for transaction ' + this.id);
this.stateChanged(C.STATUS_TERMINATED);
this.request_sender.ua.destroyTransaction(this);
this.request_sender.onRequestTimeout();
};
NonInviteClientTransaction.prototype.timer_K = function() {
this.stateChanged(C.STATUS_TERMINATED);
this.request_sender.ua.destroyTransaction(this);
};
NonInviteClientTransaction.prototype.receiveResponse = function(response) {
var
tr = this,
status_code = response.status_code;
if(status_code < 200) {
switch(this.state) {
case C.STATUS_TRYING:
case C.STATUS_PROCEEDING:
this.stateChanged(C.STATUS_PROCEEDING);
this.request_sender.receiveResponse(response);
break;
}
} else {
switch(this.state) {
case C.STATUS_TRYING:
case C.STATUS_PROCEEDING:
this.stateChanged(C.STATUS_COMPLETED);
clearTimeout(this.F);
if(status_code === 408) {
this.request_sender.onRequestTimeout();
} else {
this.request_sender.receiveResponse(response);
}
this.K = setTimeout(function() {tr.timer_K();}, Timers.TIMER_K);
break;
case C.STATUS_COMPLETED:
break;
}
}
};
function InviteClientTransaction(request_sender, request, transport) {
var via,
tr = this;
this.type = C.INVITE_CLIENT;
this.transport = transport;
this.id = 'z9hG4bK' + Math.floor(Math.random() * 10000000);
this.request_sender = request_sender;
this.request = request;
via = 'SIP/2.0/' + transport.via_transport;
via += ' ' + request_sender.ua.configuration.via_host + ';branch=' + this.id;
this.request.setHeader('via', via);
this.request_sender.ua.newTransaction(this);
// TODO: Adding here the cancel() method is a hack that must be fixed.
// Add the cancel property to the request.
//Will be called from the request instance, not the transaction itself.
this.request.cancel = function(reason) {
tr.cancel_request(tr, reason);
};
events.EventEmitter.call(this);
}
util.inherits(InviteClientTransaction, events.EventEmitter);
InviteClientTransaction.prototype.stateChanged = function(state) {
this.state = state;
this.emit('stateChanged');
};
InviteClientTransaction.prototype.send = function() {
var tr = this;
this.stateChanged(C.STATUS_CALLING);
this.B = setTimeout(function() {
tr.timer_B();
}, Timers.TIMER_B);
if(!this.transport.send(this.request)) {
this.onTransportError();
}
};
InviteClientTransaction.prototype.onTransportError = function() {
clearTimeout(this.B);
clearTimeout(this.D);
clearTimeout(this.M);
if (this.state !== C.STATUS_ACCEPTED) {
debugict('transport error occurred, deleting transaction ' + this.id);
this.request_sender.onTransportError();
}
this.stateChanged(C.STATUS_TERMINATED);
this.request_sender.ua.destroyTransaction(this);
};
// RFC 6026 7.2
InviteClientTransaction.prototype.timer_M = function() {
debugict('Timer M expired for transaction ' + this.id);
if(this.state === C.STATUS_ACCEPTED) {
clearTimeout(this.B);
this.stateChanged(C.STATUS_TERMINATED);
this.request_sender.ua.destroyTransaction(this);
}
};
// RFC 3261 17.1.1
InviteClientTransaction.prototype.timer_B = function() {
debugict('Timer B expired for transaction ' + this.id);
if(this.state === C.STATUS_CALLING) {
this.stateChanged(C.STATUS_TERMINATED);
this.request_sender.ua.destroyTransaction(this);
this.request_sender.onRequestTimeout();
}
};
InviteClientTransaction.prototype.timer_D = function() {
debugict('Timer D expired for transaction ' + this.id);
clearTimeout(this.B);
this.stateChanged(C.STATUS_TERMINATED);
this.request_sender.ua.destroyTransaction(this);
};
InviteClientTransaction.prototype.sendACK = function(response) {
var tr = this;
this.ack = 'ACK ' + this.request.ruri + ' SIP/2.0\r\n';
this.ack += 'Via: ' + this.request.headers.Via.toString() + '\r\n';
if(this.request.headers.Route) {
this.ack += 'Route: ' + this.request.headers.Route.toString() + '\r\n';
}
this.ack += 'To: ' + response.getHeader('to') + '\r\n';
this.ack += 'From: ' + this.request.headers.From.toString() + '\r\n';
this.ack += 'Call-ID: ' + this.request.headers['Call-ID'].toString() + '\r\n';
this.ack += 'CSeq: ' + this.request.headers.CSeq.toString().split(' ')[0];
this.ack += ' ACK\r\n';
this.ack += 'Content-Length: 0\r\n\r\n';
this.D = setTimeout(function() {tr.timer_D();}, Timers.TIMER_D);
this.transport.send(this.ack);
};
InviteClientTransaction.prototype.cancel_request = function(tr, reason) {
var request = tr.request;
this.cancel = JsSIP_C.CANCEL + ' ' + request.ruri + ' SIP/2.0\r\n';
this.cancel += 'Via: ' + request.headers.Via.toString() + '\r\n';
if(this.request.headers.Route) {
this.cancel += 'Route: ' + request.headers.Route.toString() + '\r\n';
}
this.cancel += 'To: ' + request.headers.To.toString() + '\r\n';
this.cancel += 'From: ' + request.headers.From.toString() + '\r\n';
this.cancel += 'Call-ID: ' + request.headers['Call-ID'].toString() + '\r\n';
this.cancel += 'CSeq: ' + request.headers.CSeq.toString().split(' ')[0] +
' CANCEL\r\n';
if(reason) {
this.cancel += 'Reason: ' + reason + '\r\n';
}
this.cancel += 'Content-Length: 0\r\n\r\n';
// Send only if a provisional response (>100) has been received.
if(this.state === C.STATUS_PROCEEDING) {
this.transport.send(this.cancel);
}
};
InviteClientTransaction.prototype.receiveResponse = function(response) {
var
tr = this,
status_code = response.status_code;
if(status_code >= 100 && status_code <= 199) {
switch(this.state) {
case C.STATUS_CALLING:
this.stateChanged(C.STATUS_PROCEEDING);
this.request_sender.receiveResponse(response);
break;
case C.STATUS_PROCEEDING:
this.request_sender.receiveResponse(response);
break;
}
} else if(status_code >= 200 && status_code <= 299) {
switch(this.state) {
case C.STATUS_CALLING:
case C.STATUS_PROCEEDING:
this.stateChanged(C.STATUS_ACCEPTED);
this.M = setTimeout(function() {
tr.timer_M();
}, Timers.TIMER_M);
this.request_sender.receiveResponse(response);
break;
case C.STATUS_ACCEPTED:
this.request_sender.receiveResponse(response);
break;
}
} else if(status_code >= 300 && status_code <= 699) {
switch(this.state) {
case C.STATUS_CALLING:
case C.STATUS_PROCEEDING:
this.stateChanged(C.STATUS_COMPLETED);
this.sendACK(response);
this.request_sender.receiveResponse(response);
break;
case C.STATUS_COMPLETED:
this.sendACK(response);
break;
}
}
};
function AckClientTransaction(request_sender, request, transport) {
var via;
this.transport = transport;
this.id = 'z9hG4bK' + Math.floor(Math.random() * 10000000);
this.request_sender = request_sender;
this.request = request;
via = 'SIP/2.0/' + transport.via_transport;
via += ' ' + request_sender.ua.configuration.via_host + ';branch=' + this.id;
this.request.setHeader('via', via);
events.EventEmitter.call(this);
}
util.inherits(AckClientTransaction, events.EventEmitter);
AckClientTransaction.prototype.send = function() {
if(!this.transport.send(this.request)) {
this.onTransportError();
}
};
AckClientTransaction.prototype.onTransportError = function() {
debugact('transport error occurred for transaction ' + this.id);
this.request_sender.onTransportError();
};
function NonInviteServerTransaction(request, ua) {
this.type = C.NON_INVITE_SERVER;
this.id = request.via_branch;
this.request = request;
this.transport = request.transport;
this.ua = ua;
this.last_response = '';
request.server_transaction = this;
this.state = C.STATUS_TRYING;
ua.newTransaction(this);
events.EventEmitter.call(this);
}
util.inherits(NonInviteServerTransaction, events.EventEmitter);
NonInviteServerTransaction.prototype.stateChanged = function(state) {
this.state = state;
this.emit('stateChanged');
};
NonInviteServerTransaction.prototype.timer_J = function() {
debugnist('Timer J expired for transaction ' + this.id);
this.stateChanged(C.STATUS_TERMINATED);
this.ua.destroyTransaction(this);
};
NonInviteServerTransaction.prototype.onTransportError = function() {
if (!this.transportError) {
this.transportError = true;
debugnist('transport error occurred, deleting transaction ' + this.id);
clearTimeout(this.J);
this.stateChanged(C.STATUS_TERMINATED);
this.ua.destroyTransaction(this);
}
};
NonInviteServerTransaction.prototype.receiveResponse = function(status_code, response, onSuccess, onFailure) {
var tr = this;
if(status_code === 100) {
/* RFC 4320 4.1
* 'A SIP element MUST NOT
* send any provisional response with a
* Status-Code other than 100 to a non-INVITE request.'
*/
switch(this.state) {
case C.STATUS_TRYING:
this.stateChanged(C.STATUS_PROCEEDING);
if(!this.transport.send(response)) {
this.onTransportError();
}
break;
case C.STATUS_PROCEEDING:
this.last_response = response;
if(!this.transport.send(response)) {
this.onTransportError();
if (onFailure) {
onFailure();
}
} else if (onSuccess) {
onSuccess();
}
break;
}
} else if(status_code >= 200 && status_code <= 699) {
switch(this.state) {
case C.STATUS_TRYING:
case C.STATUS_PROCEEDING:
this.stateChanged(C.STATUS_COMPLETED);
this.last_response = response;
this.J = setTimeout(function() {
tr.timer_J();
}, Timers.TIMER_J);
if(!this.transport.send(response)) {
this.onTransportError();
if (onFailure) {
onFailure();
}
} else if (onSuccess) {
onSuccess();
}
break;
case C.STATUS_COMPLETED:
break;
}
}
};
function InviteServerTransaction(request, ua) {
this.type = C.INVITE_SERVER;
this.id = request.via_branch;
this.request = request;
this.transport = request.transport;
this.ua = ua;
this.last_response = '';
request.server_transaction = this;
this.state = C.STATUS_PROCEEDING;
ua.newTransaction(this);
this.resendProvisionalTimer = null;
request.reply(100);
events.EventEmitter.call(this);
}
util.inherits(InviteServerTransaction, events.EventEmitter);
InviteServerTransaction.prototype.stateChanged = function(state) {
this.state = state;
this.emit('stateChanged');
};
InviteServerTransaction.prototype.timer_H = function() {
debugist('Timer H expired for transaction ' + this.id);
if(this.state === C.STATUS_COMPLETED) {
debugist('ACK not received, dialog will be terminated');
}
this.stateChanged(C.STATUS_TERMINATED);
this.ua.destroyTransaction(this);
};
InviteServerTransaction.prototype.timer_I = function() {
this.stateChanged(C.STATUS_TERMINATED);
};
// RFC 6026 7.1
InviteServerTransaction.prototype.timer_L = function() {
debugist('Timer L expired for transaction ' + this.id);
if(this.state === C.STATUS_ACCEPTED) {
this.stateChanged(C.STATUS_TERMINATED);
this.ua.destroyTransaction(this);
}
};
InviteServerTransaction.prototype.onTransportError = function() {
if (!this.transportError) {
this.transportError = true;
debugist('transport error occurred, deleting transaction ' + this.id);
if (this.resendProvisionalTimer !== null) {
clearInterval(this.resendProvisionalTimer);
this.resendProvisionalTimer = null;
}
clearTimeout(this.L);
clearTimeout(this.H);
clearTimeout(this.I);
this.stateChanged(C.STATUS_TERMINATED);
this.ua.destroyTransaction(this);
}
};
InviteServerTransaction.prototype.resend_provisional = function() {
if(!this.transport.send(this.last_response)) {
this.onTransportError();
}
};
// INVITE Server Transaction RFC 3261 17.2.1
InviteServerTransaction.prototype.receiveResponse = function(status_code, response, onSuccess, onFailure) {
var tr = this;
if(status_code >= 100 && status_code <= 199) {
switch(this.state) {
case C.STATUS_PROCEEDING:
if(!this.transport.send(response)) {
this.onTransportError();
}
this.last_response = response;
break;
}
}
if(status_code > 100 && status_code <= 199 && this.state === C.STATUS_PROCEEDING) {
// Trigger the resendProvisionalTimer only for the first non 100 provisional response.
if(this.resendProvisionalTimer === null) {
this.resendProvisionalTimer = setInterval(function() {
tr.resend_provisional();}, Timers.PROVISIONAL_RESPONSE_INTERVAL);
}
} else if(status_code >= 200 && status_code <= 299) {
switch(this.state) {
case C.STATUS_PROCEEDING:
this.stateChanged(C.STATUS_ACCEPTED);
this.last_response = response;
this.L = setTimeout(function() {
tr.timer_L();
}, Timers.TIMER_L);
if (this.resendProvisionalTimer !== null) {
clearInterval(this.resendProvisionalTimer);
this.resendProvisionalTimer = null;
}
/* falls through */
case C.STATUS_ACCEPTED:
// Note that this point will be reached for proceeding tr.state also.
if(!this.transport.send(response)) {
this.onTransportError();
if (onFailure) {
onFailure();
}
} else if (onSuccess) {
onSuccess();
}
break;
}
} else if(status_code >= 300 && status_code <= 699) {
switch(this.state) {
case C.STATUS_PROCEEDING:
if (this.resendProvisionalTimer !== null) {
clearInterval(this.resendProvisionalTimer);
this.resendProvisionalTimer = null;
}
if(!this.transport.send(response)) {
this.onTransportError();
if (onFailure) {
onFailure();
}
} else {
this.stateChanged(C.STATUS_COMPLETED);
this.H = setTimeout(function() {
tr.timer_H();
}, Timers.TIMER_H);
if (onSuccess) {
onSuccess();
}
}
break;
}
}
};
/**
* INVITE:
* _true_ if retransmission
* _false_ new request
*
* ACK:
* _true_ ACK to non2xx response
* _false_ ACK must be passed to TU (accepted state)
* ACK to 2xx response
*
* CANCEL:
* _true_ no matching invite transaction
* _false_ matching invite transaction and no final response sent
*
* OTHER:
* _true_ retransmission
* _false_ new request
*/
function checkTransaction(ua, request) {
var tr;
switch(request.method) {
case JsSIP_C.INVITE:
tr = ua.transactions.ist[request.via_branch];
if(tr) {
switch(tr.state) {
case C.STATUS_PROCEEDING:
tr.transport.send(tr.last_response);
break;
// RFC 6026 7.1 Invite retransmission
//received while in C.STATUS_ACCEPTED state. Absorb it.
case C.STATUS_ACCEPTED:
break;
}
return true;
}
break;
case JsSIP_C.ACK:
tr = ua.transactions.ist[request.via_branch];
// RFC 6026 7.1
if(tr) {
if(tr.state === C.STATUS_ACCEPTED) {
return false;
} else if(tr.state === C.STATUS_COMPLETED) {
tr.state = C.STATUS_CONFIRMED;
tr.I = setTimeout(function() {tr.timer_I();}, Timers.TIMER_I);
return true;
}
}
// ACK to 2XX Response.
else {
return false;
}
break;
case JsSIP_C.CANCEL:
tr = ua.transactions.ist[request.via_branch];
if(tr) {
request.reply_sl(200);
if(tr.state === C.STATUS_PROCEEDING) {
return false;
} else {
return true;
}
} else {
request.reply_sl(481);
return true;
}
break;
default:
// Non-INVITE Server Transaction RFC 3261 17.2.2
tr = ua.transactions.nist[request.via_branch];
if(tr) {
switch(tr.state) {
case C.STATUS_TRYING:
break;
case C.STATUS_PROCEEDING:
case C.STATUS_COMPLETED:
tr.transport.send(tr.last_response);
break;
}
return true;
}
break;
}
}
},{"./Constants":1,"./Timers":20,"debug":34,"events":28,"util":32}],22:[function(require,module,exports){
module.exports = Transport;
/**
* Dependencies.
*/
var Socket = require('./Socket');
var debug = require('debug')('JsSIP:Transport');
var debugerror = require('debug')('JsSIP:ERROR:Transport');
/**
* Constants
*/
var C = {
// Transport status
STATUS_CONNECTED: 0,
STATUS_CONNECTING: 1,
STATUS_DISCONNECTED: 2,
// Socket status
SOCKET_STATUS_READY: 0,
SOCKET_STATUS_ERROR: 1,
// Recovery options
recovery_options: {
min_interval: 2, // minimum interval in seconds between recover attempts
max_interval: 30 // maximum interval in seconds between recover attempts
}
};
/*
* Manages one or multiple JsSIP.Socket instances.
* Is reponsible for transport recovery logic among all socket instances.
*
* @socket JsSIP::Socket instance
*/
function Transport(sockets, recovery_options) {
debug('new()');
this.status = C.STATUS_DISCONNECTED;
// current socket
this.socket = null;
// socket collection
this.sockets = [];
this.recovery_options = recovery_options || C.recovery_options;
this.recover_attempts = 0;
this.recovery_timer = null;
this.close_requested = false;
if (typeof sockets === 'undefined') {
throw new TypeError('Invalid argument.' +
' undefined \'sockets\' argument');
}
if (!(sockets instanceof Array)) {
sockets = [ sockets ];
}
sockets.forEach(function(socket) {
if (!Socket.isSocket(socket.socket)) {
throw new TypeError('Invalid argument.' +
' invalid \'JsSIP.Socket\' instance');
}
if (socket.weight && !Number(socket.weight)) {
throw new TypeError('Invalid argument.' +
' \'weight\' attribute is not a number');
}
this.sockets.push({
socket: socket.socket,
weight: socket.weight || 0,
status: C.SOCKET_STATUS_READY
});
}, this);
// read only properties
Object.defineProperties(this, {
via_transport: { get: function() { return this.socket.via_transport; } },
url: { get: function() { return this.socket.url; } },
sip_uri: { get: function() { return this.socket.sip_uri; } }
});
// get the socket with higher weight
getSocket.call(this);
}
/**
* Instance Methods
*/
Transport.prototype.connect = function() {
debug('connect()');
if (this.isConnected()) {
debug('Transport is already connected');
return;
} else if (this.isConnecting()) {
debug('Transport is connecting');
return;
}
this.close_requested = false;
this.status = C.STATUS_CONNECTING;
this.onconnecting({ socket:this.socket, attempts:this.recover_attempts });
if (!this.close_requested) {
// bind socket event callbacks
this.socket.onconnect = onConnect.bind(this);
this.socket.ondisconnect = onDisconnect.bind(this);
this.socket.ondata = onData.bind(this);
this.socket.connect();
}
return;
};
Transport.prototype.disconnect = function() {
debug('close()');
this.close_requested = true;
this.recover_attempts = 0;
this.status = C.STATUS_DISCONNECTED;
// clear recovery_timer
if (this.recovery_timer !== null) {
clearTimeout(this.recovery_timer);
this.recovery_timer = null;
}
// unbind socket event callbacks
this.socket.onconnect = function() {};
this.socket.ondisconnect = function() {};
this.socket.ondata = function() {};
this.socket.disconnect();
this.ondisconnect();
};
Transport.prototype.send = function(data) {
debug('send()');
if (!this.isConnected()) {
debugerror('unable to send message, transport is not connected');
return false;
}
var message = data.toString();
debug('sending message:\n\n' + message + '\n');
return this.socket.send(message);
};
Transport.prototype.isConnected = function() {
return this.status === C.STATUS_CONNECTED;
};
Transport.prototype.isConnecting = function() {
return this.status === C.STATUS_CONNECTING;
};
/**
* Socket Event Handlers
*/
function onConnect() {
this.recover_attempts = 0;
this.status = C.STATUS_CONNECTED;
// clear recovery_timer
if (this.recovery_timer !== null) {
clearTimeout(this.recovery_timer);
this.recovery_timer = null;
}
this.onconnect( {socket:this} );
}
function onDisconnect(error, code, reason) {
this.status = C.STATUS_DISCONNECTED;
this.ondisconnect({ socket:this.socket, error:error, code:code, reason:reason });
if (this.close_requested) {
return;
}
// update socket status
else {
this.sockets.forEach(function(socket) {
if (this.socket === socket.socket) {
socket.status = C.SOCKET_STATUS_ERROR;
}
}, this);
}
reconnect.call(this, error);
}
function onData(data) {
// CRLF Keep Alive response from server. Ignore it.
if(data === '\r\n') {
debug('received message with CRLF Keep Alive response');
return;
}
// binary message.
else if (typeof data !== 'string') {
try {
data = String.fromCharCode.apply(null, new Uint8Array(data));
} catch(evt) {
debug('received binary message failed to be converted into string,' +
' message discarded');
return;
}
debug('received binary message:\n\n' + data + '\n');
}
// text message.
else {
debug('received text message:\n\n' + data + '\n');
}
this.ondata({ transport:this, message:data });
}
function reconnect() {
var k,
self = this;
this.recover_attempts+=1;
k = Math.floor((Math.random() * Math.pow(2,this.recover_attempts)) +1);
if (k < this.recovery_options.min_interval) {
k = this.recovery_options.min_interval;
}
else if (k > this.recovery_options.max_interval) {
k = this.recovery_options.max_interval;
}
debug('reconnection attempt: '+ this.recover_attempts +
'. next connection attempt in '+ k +' seconds');
this.recovery_timer = setTimeout(function() {
if (!self.close_requested && !(self.isConnected() || self.isConnecting())) {
// get the next available socket with higher weight
getSocket.call(self);
// connect the socket
self.connect();
}
}, k * 1000);
}
/**
* get the next available socket with higher weight
*/
function getSocket() {
var candidates = [];
this.sockets.forEach(function(socket) {
if (socket.status === C.SOCKET_STATUS_ERROR) {
return; // continue the array iteration
} else if (candidates.length === 0) {
candidates.push(socket);
} else if (socket.weight > candidates[0].weight) {
candidates = [socket];
} else if (socket.weight === candidates[0].weight) {
candidates.push(socket);
}
});
if (candidates.length === 0) {
// all sockets have failed. reset sockets status
this.sockets.forEach(function(socket) {
socket.status = C.SOCKET_STATUS_READY;
});
// get next available socket
getSocket.call(this);
return;
}
var idx = Math.floor((Math.random()* candidates.length));
this.socket = candidates[idx].socket;
}
},{"./Socket":19,"debug":34}],23:[function(require,module,exports){
module.exports = UA;
var C = {
// UA status codes
STATUS_INIT : 0,
STATUS_READY: 1,
STATUS_USER_CLOSED: 2,
STATUS_NOT_READY: 3,
// UA error codes
CONFIGURATION_ERROR: 1,
NETWORK_ERROR: 2
};
/**
* Expose C object.
*/
UA.C = C;
/**
* Dependencies.
*/
var util = require('util');
var events = require('events');
var debug = require('debug')('JsSIP:UA');
var debugerror = require('debug')('JsSIP:ERROR:UA');
debugerror.log = console.warn.bind(console);
var JsSIP_C = require('./Constants');
var Registrator = require('./Registrator');
var RTCSession = require('./RTCSession');
var Message = require('./Message');
var Transactions = require('./Transactions');
var Transport = require('./Transport');
var Socket = require('./Socket');
var Utils = require('./Utils');
var Exceptions = require('./Exceptions');
var URI = require('./URI');
var Grammar = require('./Grammar');
var Parser = require('./Parser');
var SIPMessage = require('./SIPMessage');
var sanityCheck = require('./sanityCheck');
/**
* The User-Agent class.
* @class JsSIP.UA
* @param {Object} configuration Configuration parameters.
* @throws {JsSIP.Exceptions.ConfigurationError} If a configuration parameter is invalid.
* @throws {TypeError} If no configuration is given.
*/
function UA(configuration) {
debug('new() [configuration:%o]', configuration);
this.cache = {
credentials: {}
};
this.configuration = {};
this.dynConfiguration = {};
this.dialogs = {};
//User actions outside any session/dialog (MESSAGE)
this.applicants = {};
this.sessions = {};
this.transport = null;
this.contact = null;
this.status = C.STATUS_INIT;
this.error = null;
this.transactions = {
nist: {},
nict: {},
ist: {},
ict: {}
};
// Custom UA empty object for high level use
this.data = {};
this.closeTimer = null;
Object.defineProperties(this, {
transactionsCount: {
get: function() {
var type,
transactions = ['nist','nict','ist','ict'],
count = 0;
for (type in transactions) {
count += Object.keys(this.transactions[transactions[type]]).length;
}
return count;
}
},
nictTransactionsCount: {
get: function() {
return Object.keys(this.transactions.nict).length;
}
},
nistTransactionsCount: {
get: function() {
return Object.keys(this.transactions.nist).length;
}
},
ictTransactionsCount: {
get: function() {
return Object.keys(this.transactions.ict).length;
}
},
istTransactionsCount: {
get: function() {
return Object.keys(this.transactions.ist).length;
}
}
});
/**
* Load configuration
*/
if(configuration === undefined) {
throw new TypeError('Not enough arguments');
}
try {
this.loadConfig(configuration);
} catch(e) {
this.status = C.STATUS_NOT_READY;
this.error = C.CONFIGURATION_ERROR;
throw e;
}
// Initialize registrator
this._registrator = new Registrator(this);
events.EventEmitter.call(this);
}
util.inherits(UA, events.EventEmitter);
//=================
// High Level API
//=================
/**
* Connect to the server if status = STATUS_INIT.
* Resume UA after being closed.
*/
UA.prototype.start = function() {
debug('start()');
if (this.status === C.STATUS_INIT) {
this.transport.connect();
} else if(this.status === C.STATUS_USER_CLOSED) {
debug('restarting UA');
// disconnect
if (this.closeTimer !== null) {
clearTimeout(this.closeTimer);
this.closeTimer = null;
this.transport.disconnect();
}
// reconnect
this.status = C.STATUS_INIT;
this.transport.connect();
} else if (this.status === C.STATUS_READY) {
debug('UA is in READY status, not restarted');
} else {
debug('ERROR: connection is down, Auto-Recovery system is trying to reconnect');
}
// Set dynamic configuration.
this.dynConfiguration.register = this.configuration.register;
};
/**
* Register.
*/
UA.prototype.register = function() {
debug('register()');
this.dynConfiguration.register = true;
this._registrator.register();
};
/**
* Unregister.
*/
UA.prototype.unregister = function(options) {
debug('unregister()');
this.dynConfiguration.register = false;
this._registrator.unregister(options);
};
/**
* Get the Registrator instance.
*/
UA.prototype.registrator = function() {
return this._registrator;
};
/**
* Registration state.
*/
UA.prototype.isRegistered = function() {
if(this._registrator.registered) {
return true;
} else {
return false;
}
};
/**
* Connection state.
*/
UA.prototype.isConnected = function() {
return this.transport.isConnected();
};
/**
* Make an outgoing call.
*
* -param {String} target
* -param {Object} views
* -param {Object} [options]
*
* -throws {TypeError}
*
*/
UA.prototype.call = function(target, options) {
debug('call()');
var session;
session = new RTCSession(this);
session.connect(target, options);
return session;
};
/**
* Send a message.
*
* -param {String} target
* -param {String} body
* -param {Object} [options]
*
* -throws {TypeError}
*
*/
UA.prototype.sendMessage = function(target, body, options) {
debug('sendMessage()');
var message;
message = new Message(this);
message.send(target, body, options);
return message;
};
/**
* Terminate ongoing sessions.
*/
UA.prototype.terminateSessions = function(options) {
debug('terminateSessions()');
for(var idx in this.sessions) {
if (!this.sessions[idx].isEnded()) {
this.sessions[idx].terminate(options);
}
}
};
/**
* Gracefully close.
*
*/
UA.prototype.stop = function() {
debug('stop()');
var session;
var applicant;
var num_sessions;
var ua = this;
// Remove dynamic settings.
this.dynConfiguration = {};
if(this.status === C.STATUS_USER_CLOSED) {
debug('UA already closed');
return;
}
// Close registrator
this._registrator.close();
// If there are session wait a bit so CANCEL/BYE can be sent and their responses received.
num_sessions = Object.keys(this.sessions).length;
// Run _terminate_ on every Session
for(session in this.sessions) {
debug('closing session ' + session);
try { this.sessions[session].terminate(); } catch(error) {}
}
// Run _close_ on every applicant
for(applicant in this.applicants) {
try { this.applicants[applicant].close(); } catch(error) {}
}
this.status = C.STATUS_USER_CLOSED;
if (this.nistTransactionsCount === 0 &&
this.nictTransactionsCount === 0 &&
this.ictTransactionsCount === 0 &&
this.istTransactionsCount === 0 &&
num_sessions === 0) {
ua.transport.disconnect();
}
else {
this.closeTimer = setTimeout(function() {
ua.closeTimer = null;
ua.transport.disconnect();
}, 2000);
}
};
/**
* Normalice a string into a valid SIP request URI
* -param {String} target
* -returns {JsSIP.URI|undefined}
*/
UA.prototype.normalizeTarget = function(target) {
return Utils.normalizeTarget(target, this.configuration.hostport_params);
};
/**
* Allow retrieving configuration and autogenerated fields in runtime.
*/
UA.prototype.get = function(parameter) {
switch(parameter) {
case 'realm':
return this.configuration.realm;
case 'ha1':
return this.configuration.ha1;
default:
debugerror('get() | cannot get "%s" parameter in runtime', parameter);
return undefined;
}
return true;
};
/**
* Allow configuration changes in runtime.
* Returns true if the parameter could be set.
*/
UA.prototype.set = function(parameter, value) {
switch(parameter) {
case 'password': {
this.configuration.password = String(value);
break;
}
case 'realm': {
this.configuration.realm = String(value);
break;
}
case 'ha1': {
this.configuration.ha1 = String(value);
// Delete the plain SIP password.
this.configuration.password = null;
break;
}
case 'display_name': {
if (Grammar.parse('"' + value + '"', 'display_name') === -1) {
debugerror('set() | wrong "display_name"');
return false;
}
this.configuration.display_name = value;
break;
}
default:
debugerror('set() | cannot set "%s" parameter in runtime', parameter);
return false;
}
return true;
};
//===============================
// Private (For internal use)
//===============================
// UA.prototype.saveCredentials = function(credentials) {
// this.cache.credentials[credentials.realm] = this.cache.credentials[credentials.realm] || {};
// this.cache.credentials[credentials.realm][credentials.uri] = credentials;
// };
// UA.prototype.getCredentials = function(request) {
// var realm, credentials;
// realm = request.ruri.host;
// if (this.cache.credentials[realm] && this.cache.credentials[realm][request.ruri]) {
// credentials = this.cache.credentials[realm][request.ruri];
// credentials.method = request.method;
// }
// return credentials;
// };
//==========================
// Event Handlers
//==========================
/**
* new Transaction
*/
UA.prototype.newTransaction = function(transaction) {
this.transactions[transaction.type][transaction.id] = transaction;
this.emit('newTransaction', {
transaction: transaction
});
};
/**
* Transaction destroyed.
*/
UA.prototype.destroyTransaction = function(transaction) {
delete this.transactions[transaction.type][transaction.id];
this.emit('transactionDestroyed', {
transaction: transaction
});
};
/**
* new Message
*/
UA.prototype.newMessage = function(data) {
this.emit('newMessage', data);
};
/**
* new RTCSession
*/
UA.prototype.newRTCSession = function(data) {
this.emit('newRTCSession', data);
};
/**
* Registered
*/
UA.prototype.registered = function(data) {
this.emit('registered', data);
};
/**
* Unregistered
*/
UA.prototype.unregistered = function(data) {
this.emit('unregistered', data);
};
/**
* Registration Failed
*/
UA.prototype.registrationFailed = function(data) {
this.emit('registrationFailed', data);
};
//=========================
// receiveRequest
//=========================
/**
* Request reception
*/
UA.prototype.receiveRequest = function(request) {
var dialog, session, message, replaces,
method = request.method;
// Check that request URI points to us
if(request.ruri.user !== this.configuration.uri.user && request.ruri.user !== this.contact.uri.user) {
debug('Request-URI does not point to us');
if (request.method !== JsSIP_C.ACK) {
request.reply_sl(404);
}
return;
}
// Check request URI scheme
if(request.ruri.scheme === JsSIP_C.SIPS) {
request.reply_sl(416);
return;
}
// Check transaction
if(Transactions.checkTransaction(this, request)) {
return;
}
// Create the server transaction
if(method === JsSIP_C.INVITE) {
new Transactions.InviteServerTransaction(request, this);
} else if(method !== JsSIP_C.ACK && method !== JsSIP_C.CANCEL) {
new Transactions.NonInviteServerTransaction(request, this);
}
/* RFC3261 12.2.2
* Requests that do not change in any way the state of a dialog may be
* received within a dialog (for example, an OPTIONS request).
* They are processed as if they had been received outside the dialog.
*/
if(method === JsSIP_C.OPTIONS) {
request.reply(200);
} else if (method === JsSIP_C.MESSAGE) {
if (this.listeners('newMessage').length === 0) {
request.reply(405);
return;
}
message = new Message(this);
message.init_incoming(request);
} else if (method === JsSIP_C.INVITE) {
// Initial INVITE
if(!request.to_tag && this.listeners('newRTCSession').length === 0) {
request.reply(405);
return;
}
}
// Initial Request
if(!request.to_tag) {
switch(method) {
case JsSIP_C.INVITE:
if (window.RTCPeerConnection) { // TODO
if (request.hasHeader('replaces')) {
replaces = request.replaces;
dialog = this.findDialog(replaces.call_id, replaces.from_tag, replaces.to_tag);
if (dialog) {
session = dialog.owner;
if (!session.isEnded()) {
session.receiveRequest(request);
} else {
request.reply(603);
}
} else {
request.reply(481);
}
} else {
session = new RTCSession(this);
session.init_incoming(request);
}
} else {
debugerror('INVITE received but WebRTC is not supported');
request.reply(488);
}
break;
case JsSIP_C.BYE:
// Out of dialog BYE received
request.reply(481);
break;
case JsSIP_C.CANCEL:
session = this.findSession(request);
if (session) {
session.receiveRequest(request);
} else {
debug('received CANCEL request for a non existent session');
}
break;
case JsSIP_C.ACK:
/* Absorb it.
* ACK request without a corresponding Invite Transaction
* and without To tag.
*/
break;
default:
request.reply(405);
break;
}
}
// In-dialog request
else {
dialog = this.findDialog(request.call_id, request.from_tag, request.to_tag);
if(dialog) {
dialog.receiveRequest(request);
} else if (method === JsSIP_C.NOTIFY) {
session = this.findSession(request);
if(session) {
session.receiveRequest(request);
} else {
debug('received NOTIFY request for a non existent subscription');
request.reply(481, 'Subscription does not exist');
}
}
/* RFC3261 12.2.2
* Request with to tag, but no matching dialog found.
* Exception: ACK for an Invite request for which a dialog has not
* been created.
*/
else {
if(method !== JsSIP_C.ACK) {
request.reply(481);
}
}
}
};
//=================
// Utils
//=================
/**
* Get the session to which the request belongs to, if any.
*/
UA.prototype.findSession = function(request) {
var
sessionIDa = request.call_id + request.from_tag,
sessionA = this.sessions[sessionIDa],
sessionIDb = request.call_id + request.to_tag,
sessionB = this.sessions[sessionIDb];
if(sessionA) {
return sessionA;
} else if(sessionB) {
return sessionB;
} else {
return null;
}
};
/**
* Get the dialog to which the request belongs to, if any.
*/
UA.prototype.findDialog = function(call_id, from_tag, to_tag) {
var
id = call_id + from_tag + to_tag,
dialog = this.dialogs[id];
if(dialog) {
return dialog;
} else {
id = call_id + to_tag + from_tag;
dialog = this.dialogs[id];
if(dialog) {
return dialog;
} else {
return null;
}
}
};
UA.prototype.loadConfig = function(configuration) {
// Settings and default values
var parameter, value, checked_value, hostport_params, registrar_server,
settings = {
/* Host address
* Value to be set in Via sent_by and host part of Contact FQDN
*/
via_host: Utils.createRandomToken(12) + '.invalid',
// SIP Contact URI
contact_uri: null,
// SIP authentication password
password: null,
// SIP authentication realm
realm: null,
// SIP authentication HA1 hash
ha1: null,
// Registration parameters
register_expires: 600,
register: true,
registrar_server: null,
use_preloaded_route: false,
// Session parameters
no_answer_timeout: 60,
session_timers: true,
};
// Pre-Configuration
// Check Mandatory parameters
for(parameter in UA.configuration_check.mandatory) {
if(!configuration.hasOwnProperty(parameter)) {
throw new Exceptions.ConfigurationError(parameter);
} else {
value = configuration[parameter];
checked_value = UA.configuration_check.mandatory[parameter].call(this, value);
if (checked_value !== undefined) {
settings[parameter] = checked_value;
} else {
throw new Exceptions.ConfigurationError(parameter, value);
}
}
}
// Check Optional parameters
for(parameter in UA.configuration_check.optional) {
if(configuration.hasOwnProperty(parameter)) {
value = configuration[parameter];
/* If the parameter value is null, empty string, undefined, empty array
* or it's a number with NaN value, then apply its default value.
*/
if (Utils.isEmpty(value)) {
continue;
}
checked_value = UA.configuration_check.optional[parameter].call(this, value, configuration);
if (checked_value !== undefined) {
settings[parameter] = checked_value;
} else {
throw new Exceptions.ConfigurationError(parameter, value);
}
}
}
// Post Configuration Process
// Allow passing 0 number as display_name.
if (settings.display_name === 0) {
settings.display_name = '0';
}
// Instance-id for GRUU.
if (!settings.instance_id) {
settings.instance_id = Utils.newUUID();
}
// jssip_id instance parameter. Static random tag of length 5.
settings.jssip_id = Utils.createRandomToken(5);
// String containing settings.uri without scheme and user.
hostport_params = settings.uri.clone();
hostport_params.user = null;
settings.hostport_params = hostport_params.toString().replace(/^sip:/i, '');
// Transport
var sockets = [];
if (settings.sockets && Array.isArray(settings.sockets)) {
sockets = sockets.concat(settings.sockets);
}
if (sockets.length === 0) {
throw new Exceptions.ConfigurationError('sockets');
}
try {
this.transport = new Transport(sockets, { /* recovery options */
max_interval: settings.connection_recovery_max_interval,
min_interval: settings.connection_recovery_min_interval
});
// Transport event callbacks
this.transport.onconnecting = onTransportConnecting.bind(this);
this.transport.onconnect = onTransportConnect.bind(this);
this.transport.ondisconnect = onTransportDisconnect.bind(this);
this.transport.ondata = onTransportData.bind(this);
// transport options not needed here anymore
delete settings.connection_recovery_max_interval;
delete settings.connection_recovery_min_interval;
delete settings.sockets;
} catch (e) {
debugerror(e);
throw new Exceptions.ConfigurationError('sockets', sockets);
}
// Check whether authorization_user is explicitly defined.
// Take 'settings.uri.user' value if not.
if (!settings.authorization_user) {
settings.authorization_user = settings.uri.user;
}
// If no 'registrar_server' is set use the 'uri' value without user portion and
// without URI params/headers.
if (!settings.registrar_server) {
registrar_server = settings.uri.clone();
registrar_server.user = null;
registrar_server.clearParams();
registrar_server.clearHeaders();
settings.registrar_server = registrar_server;
}
// User no_answer_timeout.
settings.no_answer_timeout = settings.no_answer_timeout * 1000;
// Via Host
if (settings.contact_uri) {
settings.via_host = settings.contact_uri.host;
}
// Contact URI
else {
settings.contact_uri = new URI('sip', Utils.createRandomToken(8), settings.via_host, null, {transport: 'ws'});
}
this.contact = {
pub_gruu: null,
temp_gruu: null,
uri: settings.contact_uri,
toString: function(options) {
options = options || {};
var
anonymous = options.anonymous || null,
outbound = options.outbound || null,
contact = '<';
if (anonymous) {
contact += this.temp_gruu || 'sip:anonymous@anonymous.invalid;transport=ws';
} else {
contact += this.pub_gruu || this.uri.toString();
}
if (outbound && (anonymous ? !this.temp_gruu : !this.pub_gruu)) {
contact += ';ob';
}
contact += '>';
return contact;
}
};
// Fill the value of the configuration_skeleton
for(parameter in settings) {
UA.configuration_skeleton[parameter].value = settings[parameter];
}
Object.defineProperties(this.configuration, UA.configuration_skeleton);
// Clean UA.configuration_skeleton
for(parameter in settings) {
UA.configuration_skeleton[parameter].value = '';
}
debug('configuration parameters after validation:');
for(parameter in settings) {
switch(parameter) {
case 'uri':
case 'registrar_server':
debug('- ' + parameter + ': ' + settings[parameter]);
break;
case 'password':
case 'ha1':
debug('- ' + parameter + ': ' + 'NOT SHOWN');
break;
default:
debug('- ' + parameter + ': ' + JSON.stringify(settings[parameter]));
}
}
return;
};
/**
* Configuration Object skeleton.
*/
UA.configuration_skeleton = (function() {
var
idx, parameter, writable,
skeleton = {},
parameters = [
// Internal parameters
'jssip_id',
'hostport_params',
// Mandatory user configurable parameters
'uri',
// Optional user configurable parameters
'authorization_user',
'contact_uri',
'display_name',
'instance_id',
'no_answer_timeout', // 30 seconds
'session_timers', // true
'password',
'realm',
'ha1',
'register_expires', // 600 seconds
'registrar_server',
'sockets',
'use_preloaded_route',
// Post-configuration generated parameters
'via_core_value',
'via_host'
];
var writable_parameters = [
'password', 'realm', 'ha1', 'display_name'
];
for(idx in parameters) {
parameter = parameters[idx];
if (writable_parameters.indexOf(parameter) !== -1) {
writable = true;
} else {
writable = false;
}
skeleton[parameter] = {
value: '',
writable: writable,
configurable: false
};
}
skeleton.register = {
value: '',
writable: true,
configurable: false
};
return skeleton;
}());
/**
* Configuration checker.
*/
UA.configuration_check = {
mandatory: {
uri: function(uri) {
var parsed;
if (!/^sip:/i.test(uri)) {
uri = JsSIP_C.SIP + ':' + uri;
}
parsed = URI.parse(uri);
if(!parsed) {
return;
} else if(!parsed.user) {
return;
} else {
return parsed;
}
}
},
optional: {
authorization_user: function(authorization_user) {
if(Grammar.parse('"'+ authorization_user +'"', 'quoted_string') === -1) {
return;
} else {
return authorization_user;
}
},
connection_recovery_max_interval: function(connection_recovery_max_interval) {
var value;
if(Utils.isDecimal(connection_recovery_max_interval)) {
value = Number(connection_recovery_max_interval);
if(value > 0) {
return value;
}
}
},
connection_recovery_min_interval: function(connection_recovery_min_interval) {
var value;
if(Utils.isDecimal(connection_recovery_min_interval)) {
value = Number(connection_recovery_min_interval);
if(value > 0) {
return value;
}
}
},
contact_uri: function(contact_uri) {
if (typeof contact_uri === 'string') {
var uri = Grammar.parse(contact_uri,'SIP_URI');
if (uri !== -1) {
return uri;
}
}
},
display_name: function(display_name) {
if (Grammar.parse('"' + display_name + '"', 'display_name') === -1) {
return;
} else {
return display_name;
}
},
instance_id: function(instance_id) {
if ((/^uuid:/i.test(instance_id))) {
instance_id = instance_id.substr(5);
}
if(Grammar.parse(instance_id, 'uuid') === -1) {
return;
} else {
return instance_id;
}
},
no_answer_timeout: function(no_answer_timeout) {
var value;
if (Utils.isDecimal(no_answer_timeout)) {
value = Number(no_answer_timeout);
if (value > 0) {
return value;
}
}
},
session_timers: function(session_timers) {
if (typeof session_timers === 'boolean') {
return session_timers;
}
},
password: function(password) {
return String(password);
},
realm: function(realm) {
return String(realm);
},
ha1: function(ha1) {
return String(ha1);
},
register: function(register) {
if (typeof register === 'boolean') {
return register;
}
},
register_expires: function(register_expires) {
var value;
if (Utils.isDecimal(register_expires)) {
value = Number(register_expires);
if (value > 0) {
return value;
}
}
},
registrar_server: function(registrar_server) {
var parsed;
if (!/^sip:/i.test(registrar_server)) {
registrar_server = JsSIP_C.SIP + ':' + registrar_server;
}
parsed = URI.parse(registrar_server);
if(!parsed) {
return;
} else if(parsed.user) {
return;
} else {
return parsed;
}
},
sockets: function(sockets) {
var idx, length;
/* Allow defining sockets parameter as:
* Socket: socket
* Array of Socket: [socket1, socket2]
* Array of Objects: [{socket: socket1, weight:1}, {socket: Socket2, weight:0}]
* Array of Objects and Socket: [{socket: socket1}, socket2]
*/
if (Socket.isSocket(sockets)) {
sockets = [{socket: sockets}];
} else if (Array.isArray(sockets) && sockets.length) {
length = sockets.length;
for (idx = 0; idx < length; idx++) {
if (Socket.isSocket(sockets[idx])) {
sockets[idx] = {socket: sockets[idx]};
}
}
} else {
return;
}
return sockets;
},
use_preloaded_route: function(use_preloaded_route) {
if (typeof use_preloaded_route === 'boolean') {
return use_preloaded_route;
}
}
}
};
/**
* Transport event handlers
*/
// Transport connecting event
function onTransportConnecting(data) {
this.emit('connecting', data);
}
// Transport connected event.
function onTransportConnect(data) {
if(this.status === C.STATUS_USER_CLOSED) {
return;
}
this.status = C.STATUS_READY;
this.error = null;
this.emit('connected', data);
if(this.dynConfiguration.register) {
this._registrator.register();
}
}
// Transport disconnected event.
function onTransportDisconnect(data) {
// Run _onTransportError_ callback on every client transaction using _transport_
var type, idx, length,
client_transactions = ['nict', 'ict', 'nist', 'ist'];
length = client_transactions.length;
for (type = 0; type < length; type++) {
for(idx in this.transactions[client_transactions[type]]) {
this.transactions[client_transactions[type]][idx].onTransportError();
}
}
this.emit('disconnected', data);
// Call registrator _onTransportClosed_
this._registrator.onTransportClosed();
if (this.status !== C.STATUS_USER_CLOSED) {
this.status = C.STATUS_NOT_READY;
this.error = C.NETWORK_ERROR;
}
}
// Transport data event
function onTransportData(data) {
var transaction,
transport = data.transport,
message = data.message;
message = Parser.parseMessage(message, this);
if (! message) {
return;
}
if (this.status === UA.C.STATUS_USER_CLOSED &&
message instanceof SIPMessage.IncomingRequest) {
return;
}
// Do some sanity check
if(! sanityCheck(message, this, transport)) {
return;
}
if(message instanceof SIPMessage.IncomingRequest) {
message.transport = transport;
this.receiveRequest(message);
} else if(message instanceof SIPMessage.IncomingResponse) {
/* Unike stated in 18.1.2, if a response does not match
* any transaction, it is discarded here and no passed to the core
* in order to be discarded there.
*/
switch(message.method) {
case JsSIP_C.INVITE:
transaction = this.transactions.ict[message.via_branch];
if(transaction) {
transaction.receiveResponse(message);
}
break;
case JsSIP_C.ACK:
// Just in case ;-)
break;
default:
transaction = this.transactions.nict[message.via_branch];
if(transaction) {
transaction.receiveResponse(message);
}
break;
}
}
}
},{"./Constants":1,"./Exceptions":5,"./Grammar":6,"./Message":8,"./Parser":10,"./RTCSession":11,"./Registrator":16,"./SIPMessage":18,"./Socket":19,"./Transactions":21,"./Transport":22,"./URI":24,"./Utils":25,"./sanityCheck":27,"debug":34,"events":28,"util":32}],24:[function(require,module,exports){
module.exports = URI;
/**
* Dependencies.
*/
var JsSIP_C = require('./Constants');
var Utils = require('./Utils');
var Grammar = require('./Grammar');
/**
* -param {String} [scheme]
* -param {String} [user]
* -param {String} host
* -param {String} [port]
* -param {Object} [parameters]
* -param {Object} [headers]
*
*/
function URI(scheme, user, host, port, parameters, headers) {
var param, header;
// Checks
if(!host) {
throw new TypeError('missing or invalid "host" parameter');
}
// Initialize parameters
scheme = scheme || JsSIP_C.SIP;
this.parameters = {};
this.headers = {};
for (param in parameters) {
this.setParam(param, parameters[param]);
}
for (header in headers) {
this.setHeader(header, headers[header]);
}
Object.defineProperties(this, {
scheme: {
get: function(){ return scheme; },
set: function(value){
scheme = value.toLowerCase();
}
},
user: {
get: function(){ return user; },
set: function(value){
user = value;
}
},
host: {
get: function(){ return host; },
set: function(value){
host = value.toLowerCase();
}
},
port: {
get: function(){ return port; },
set: function(value){
port = value === 0 ? value : (parseInt(value,10) || null);
}
}
});
}
URI.prototype = {
setParam: function(key, value) {
if(key) {
this.parameters[key.toLowerCase()] = (typeof value === 'undefined' || value === null) ? null : value.toString();
}
},
getParam: function(key) {
if(key) {
return this.parameters[key.toLowerCase()];
}
},
hasParam: function(key) {
if(key) {
return (this.parameters.hasOwnProperty(key.toLowerCase()) && true) || false;
}
},
deleteParam: function(parameter) {
var value;
parameter = parameter.toLowerCase();
if (this.parameters.hasOwnProperty(parameter)) {
value = this.parameters[parameter];
delete this.parameters[parameter];
return value;
}
},
clearParams: function() {
this.parameters = {};
},
setHeader: function(name, value) {
this.headers[Utils.headerize(name)] = (Array.isArray(value)) ? value : [value];
},
getHeader: function(name) {
if(name) {
return this.headers[Utils.headerize(name)];
}
},
hasHeader: function(name) {
if(name) {
return (this.headers.hasOwnProperty(Utils.headerize(name)) && true) || false;
}
},
deleteHeader: function(header) {
var value;
header = Utils.headerize(header);
if(this.headers.hasOwnProperty(header)) {
value = this.headers[header];
delete this.headers[header];
return value;
}
},
clearHeaders: function() {
this.headers = {};
},
clone: function() {
return new URI(
this.scheme,
this.user,
this.host,
this.port,
JSON.parse(JSON.stringify(this.parameters)),
JSON.parse(JSON.stringify(this.headers)));
},
toString: function(){
var header, parameter, idx, uri,
headers = [];
uri = this.scheme + ':';
if (this.user) {
uri += Utils.escapeUser(this.user) + '@';
}
uri += this.host;
if (this.port || this.port === 0) {
uri += ':' + this.port;
}
for (parameter in this.parameters) {
uri += ';' + parameter;
if (this.parameters[parameter] !== null) {
uri += '='+ this.parameters[parameter];
}
}
for(header in this.headers) {
for(idx = 0; idx < this.headers[header].length; idx++) {
headers.push(header + '=' + this.headers[header][idx]);
}
}
if (headers.length > 0) {
uri += '?' + headers.join('&');
}
return uri;
},
toAor: function(show_port){
var aor;
aor = this.scheme + ':';
if (this.user) {
aor += Utils.escapeUser(this.user) + '@';
}
aor += this.host;
if (show_port && (this.port || this.port === 0)) {
aor += ':' + this.port;
}
return aor;
}
};
/**
* Parse the given string and returns a JsSIP.URI instance or undefined if
* it is an invalid URI.
*/
URI.parse = function(uri) {
uri = Grammar.parse(uri,'SIP_URI');
if (uri !== -1) {
return uri;
} else {
return undefined;
}
};
},{"./Constants":1,"./Grammar":6,"./Utils":25}],25:[function(require,module,exports){
var Utils = {};
module.exports = Utils;
/**
* Dependencies.
*/
var JsSIP_C = require('./Constants');
var URI = require('./URI');
var Grammar = require('./Grammar');
Utils.str_utf8_length = function(string) {
return unescape(encodeURIComponent(string)).length;
};
Utils.isFunction = function(fn) {
if (fn !== undefined) {
return (Object.prototype.toString.call(fn) === '[object Function]')? true : false;
} else {
return false;
}
};
Utils.isString = function(str) {
if (str !== undefined) {
return (Object.prototype.toString.call(str) === '[object String]')? true : false;
} else {
return false;
}
};
Utils.isDecimal = function(num) {
return !isNaN(num) && (parseFloat(num) === parseInt(num,10));
};
Utils.isEmpty = function(value) {
if (value === null || value === '' || value === undefined || (Array.isArray(value) && value.length === 0) || (typeof(value) === 'number' && isNaN(value))) {
return true;
}
};
Utils.hasMethods = function(obj /*, method list as strings */){
var i = 1, methodName;
while((methodName = arguments[i++])){
if(this.isFunction(obj[methodName])) {
return false;
}
}
return true;
};
Utils.createRandomToken = function(size, base) {
var i, r,
token = '';
base = base || 32;
for( i=0; i < size; i++ ) {
r = Math.random() * base|0;
token += r.toString(base);
}
return token;
};
Utils.newTag = function() {
return Utils.createRandomToken(10);
};
// http://stackoverflow.com/users/109538/broofa
Utils.newUUID = function() {
var UUID = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
return UUID;
};
Utils.hostType = function(host) {
if (!host) {
return;
} else {
host = Grammar.parse(host,'host');
if (host !== -1) {
return host.host_type;
}
}
};
/**
* Normalize SIP URI.
* NOTE: It does not allow a SIP URI without username.
* Accepts 'sip', 'sips' and 'tel' URIs and convert them into 'sip'.
* Detects the domain part (if given) and properly hex-escapes the user portion.
* If the user portion has only 'tel' number symbols the user portion is clean of 'tel' visual separators.
*/
Utils.normalizeTarget = function(target, domain) {
var uri, target_array, target_user, target_domain;
// If no target is given then raise an error.
if (!target) {
return;
// If a URI instance is given then return it.
} else if (target instanceof URI) {
return target;
// If a string is given split it by '@':
// - Last fragment is the desired domain.
// - Otherwise append the given domain argument.
} else if (typeof target === 'string') {
target_array = target.split('@');
switch(target_array.length) {
case 1:
if (!domain) {
return;
}
target_user = target;
target_domain = domain;
break;
case 2:
target_user = target_array[0];
target_domain = target_array[1];
break;
default:
target_user = target_array.slice(0, target_array.length-1).join('@');
target_domain = target_array[target_array.length-1];
}
// Remove the URI scheme (if present).
target_user = target_user.replace(/^(sips?|tel):/i, '');
// Remove 'tel' visual separators if the user portion just contains 'tel' number symbols.
if (/^[\-\.\(\)]*\+?[0-9\-\.\(\)]+$/.test(target_user)) {
target_user = target_user.replace(/[\-\.\(\)]/g, '');
}
// Build the complete SIP URI.
target = JsSIP_C.SIP + ':' + Utils.escapeUser(target_user) + '@' + target_domain;
// Finally parse the resulting URI.
if ((uri = URI.parse(target))) {
return uri;
} else {
return;
}
} else {
return;
}
};
/**
* Hex-escape a SIP URI user.
*/
Utils.escapeUser = function(user) {
// Don't hex-escape ':' (%3A), '+' (%2B), '?' (%3F"), '/' (%2F).
return encodeURIComponent(decodeURIComponent(user)).replace(/%3A/ig, ':').replace(/%2B/ig, '+').replace(/%3F/ig, '?').replace(/%2F/ig, '/');
};
Utils.headerize = function(string) {
var exceptions = {
'Call-Id': 'Call-ID',
'Cseq': 'CSeq',
'Www-Authenticate': 'WWW-Authenticate'
},
name = string.toLowerCase().replace(/_/g,'-').split('-'),
hname = '',
parts = name.length, part;
for (part = 0; part < parts; part++) {
if (part !== 0) {
hname +='-';
}
hname += name[part].charAt(0).toUpperCase()+name[part].substring(1);
}
if (exceptions[hname]) {
hname = exceptions[hname];
}
return hname;
};
Utils.sipErrorCause = function(status_code) {
var cause;
for (cause in JsSIP_C.SIP_ERROR_CAUSES) {
if (JsSIP_C.SIP_ERROR_CAUSES[cause].indexOf(status_code) !== -1) {
return JsSIP_C.causes[cause];
}
}
return JsSIP_C.causes.SIP_FAILURE_CODE;
};
/**
* Generate a random Test-Net IP (http://tools.ietf.org/html/rfc5735)
*/
Utils.getRandomTestNetIP = function() {
function getOctet(from,to) {
return Math.floor(Math.random()*(to-from+1)+from);
}
return '192.0.2.' + getOctet(1, 254);
};
// MD5 (Message-Digest Algorithm) http://www.webtoolkit.info
Utils.calculateMD5 = function(string) {
function rotateLeft(lValue, iShiftBits) {
return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits));
}
function addUnsigned(lX,lY) {
var lX4,lY4,lX8,lY8,lResult;
lX8 = (lX & 0x80000000);
lY8 = (lY & 0x80000000);
lX4 = (lX & 0x40000000);
lY4 = (lY & 0x40000000);
lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF);
if (lX4 & lY4) {
return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
}
if (lX4 | lY4) {
if (lResult & 0x40000000) {
return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
} else {
return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
}
} else {
return (lResult ^ lX8 ^ lY8);
}
}
function doF(x,y,z) {
return (x & y) | ((~x) & z);
}
function doG(x,y,z) {
return (x & z) | (y & (~z));
}
function doH(x,y,z) {
return (x ^ y ^ z);
}
function doI(x,y,z) {
return (y ^ (x | (~z)));
}
function doFF(a,b,c,d,x,s,ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(doF(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
}
function doGG(a,b,c,d,x,s,ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(doG(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
}
function doHH(a,b,c,d,x,s,ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(doH(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
}
function doII(a,b,c,d,x,s,ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(doI(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
}
function convertToWordArray(string) {
var lWordCount;
var lMessageLength = string.length;
var lNumberOfWords_temp1=lMessageLength + 8;
var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64;
var lNumberOfWords = (lNumberOfWords_temp2+1)*16;
var lWordArray = new Array(lNumberOfWords-1);
var lBytePosition = 0;
var lByteCount = 0;
while ( lByteCount < lMessageLength ) {
lWordCount = (lByteCount-(lByteCount % 4))/4;
lBytePosition = (lByteCount % 4)*8;
lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount)<<lBytePosition));
lByteCount++;
}
lWordCount = (lByteCount-(lByteCount % 4))/4;
lBytePosition = (lByteCount % 4)*8;
lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition);
lWordArray[lNumberOfWords-2] = lMessageLength<<3;
lWordArray[lNumberOfWords-1] = lMessageLength>>>29;
return lWordArray;
}
function wordToHex(lValue) {
var wordToHexValue='',wordToHexValue_temp='',lByte,lCount;
for (lCount = 0;lCount<=3;lCount++) {
lByte = (lValue>>>(lCount*8)) & 255;
wordToHexValue_temp = '0' + lByte.toString(16);
wordToHexValue = wordToHexValue + wordToHexValue_temp.substr(wordToHexValue_temp.length-2,2);
}
return wordToHexValue;
}
function utf8Encode(string) {
string = string.replace(/\r\n/g, '\n');
var utftext = '';
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
}
var x=[];
var k,AA,BB,CC,DD,a,b,c,d;
var S11=7, S12=12, S13=17, S14=22;
var S21=5, S22=9 , S23=14, S24=20;
var S31=4, S32=11, S33=16, S34=23;
var S41=6, S42=10, S43=15, S44=21;
string = utf8Encode(string);
x = convertToWordArray(string);
a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;
for (k=0;k<x.length;k+=16) {
AA=a; BB=b; CC=c; DD=d;
a=doFF(a,b,c,d,x[k+0], S11,0xD76AA478);
d=doFF(d,a,b,c,x[k+1], S12,0xE8C7B756);
c=doFF(c,d,a,b,x[k+2], S13,0x242070DB);
b=doFF(b,c,d,a,x[k+3], S14,0xC1BDCEEE);
a=doFF(a,b,c,d,x[k+4], S11,0xF57C0FAF);
d=doFF(d,a,b,c,x[k+5], S12,0x4787C62A);
c=doFF(c,d,a,b,x[k+6], S13,0xA8304613);
b=doFF(b,c,d,a,x[k+7], S14,0xFD469501);
a=doFF(a,b,c,d,x[k+8], S11,0x698098D8);
d=doFF(d,a,b,c,x[k+9], S12,0x8B44F7AF);
c=doFF(c,d,a,b,x[k+10],S13,0xFFFF5BB1);
b=doFF(b,c,d,a,x[k+11],S14,0x895CD7BE);
a=doFF(a,b,c,d,x[k+12],S11,0x6B901122);
d=doFF(d,a,b,c,x[k+13],S12,0xFD987193);
c=doFF(c,d,a,b,x[k+14],S13,0xA679438E);
b=doFF(b,c,d,a,x[k+15],S14,0x49B40821);
a=doGG(a,b,c,d,x[k+1], S21,0xF61E2562);
d=doGG(d,a,b,c,x[k+6], S22,0xC040B340);
c=doGG(c,d,a,b,x[k+11],S23,0x265E5A51);
b=doGG(b,c,d,a,x[k+0], S24,0xE9B6C7AA);
a=doGG(a,b,c,d,x[k+5], S21,0xD62F105D);
d=doGG(d,a,b,c,x[k+10],S22,0x2441453);
c=doGG(c,d,a,b,x[k+15],S23,0xD8A1E681);
b=doGG(b,c,d,a,x[k+4], S24,0xE7D3FBC8);
a=doGG(a,b,c,d,x[k+9], S21,0x21E1CDE6);
d=doGG(d,a,b,c,x[k+14],S22,0xC33707D6);
c=doGG(c,d,a,b,x[k+3], S23,0xF4D50D87);
b=doGG(b,c,d,a,x[k+8], S24,0x455A14ED);
a=doGG(a,b,c,d,x[k+13],S21,0xA9E3E905);
d=doGG(d,a,b,c,x[k+2], S22,0xFCEFA3F8);
c=doGG(c,d,a,b,x[k+7], S23,0x676F02D9);
b=doGG(b,c,d,a,x[k+12],S24,0x8D2A4C8A);
a=doHH(a,b,c,d,x[k+5], S31,0xFFFA3942);
d=doHH(d,a,b,c,x[k+8], S32,0x8771F681);
c=doHH(c,d,a,b,x[k+11],S33,0x6D9D6122);
b=doHH(b,c,d,a,x[k+14],S34,0xFDE5380C);
a=doHH(a,b,c,d,x[k+1], S31,0xA4BEEA44);
d=doHH(d,a,b,c,x[k+4], S32,0x4BDECFA9);
c=doHH(c,d,a,b,x[k+7], S33,0xF6BB4B60);
b=doHH(b,c,d,a,x[k+10],S34,0xBEBFBC70);
a=doHH(a,b,c,d,x[k+13],S31,0x289B7EC6);
d=doHH(d,a,b,c,x[k+0], S32,0xEAA127FA);
c=doHH(c,d,a,b,x[k+3], S33,0xD4EF3085);
b=doHH(b,c,d,a,x[k+6], S34,0x4881D05);
a=doHH(a,b,c,d,x[k+9], S31,0xD9D4D039);
d=doHH(d,a,b,c,x[k+12],S32,0xE6DB99E5);
c=doHH(c,d,a,b,x[k+15],S33,0x1FA27CF8);
b=doHH(b,c,d,a,x[k+2], S34,0xC4AC5665);
a=doII(a,b,c,d,x[k+0], S41,0xF4292244);
d=doII(d,a,b,c,x[k+7], S42,0x432AFF97);
c=doII(c,d,a,b,x[k+14],S43,0xAB9423A7);
b=doII(b,c,d,a,x[k+5], S44,0xFC93A039);
a=doII(a,b,c,d,x[k+12],S41,0x655B59C3);
d=doII(d,a,b,c,x[k+3], S42,0x8F0CCC92);
c=doII(c,d,a,b,x[k+10],S43,0xFFEFF47D);
b=doII(b,c,d,a,x[k+1], S44,0x85845DD1);
a=doII(a,b,c,d,x[k+8], S41,0x6FA87E4F);
d=doII(d,a,b,c,x[k+15],S42,0xFE2CE6E0);
c=doII(c,d,a,b,x[k+6], S43,0xA3014314);
b=doII(b,c,d,a,x[k+13],S44,0x4E0811A1);
a=doII(a,b,c,d,x[k+4], S41,0xF7537E82);
d=doII(d,a,b,c,x[k+11],S42,0xBD3AF235);
c=doII(c,d,a,b,x[k+2], S43,0x2AD7D2BB);
b=doII(b,c,d,a,x[k+9], S44,0xEB86D391);
a=addUnsigned(a,AA);
b=addUnsigned(b,BB);
c=addUnsigned(c,CC);
d=addUnsigned(d,DD);
}
var temp = wordToHex(a)+wordToHex(b)+wordToHex(c)+wordToHex(d);
return temp.toLowerCase();
};
Utils.closeMediaStream = function(stream) {
if (!stream) {
return;
}
// Latest spec states that MediaStream has no stop() method and instead must
// call stop() on every MediaStreamTrack.
try {
var tracks, i, len;
if (stream.getTracks) {
tracks = stream.getTracks();
for (i = 0, len = tracks.length; i < len; i += 1) {
tracks[i].stop();
}
} else {
tracks = stream.getAudioTracks();
for (i = 0, len = tracks.length; i < len; i += 1) {
tracks[i].stop();
}
tracks = stream.getVideoTracks();
for (i = 0, len = tracks.length; i < len; i += 1) {
tracks[i].stop();
}
}
} catch (error) {
// Deprecated by the spec, but still in use.
// NOTE: In Temasys IE plugin stream.stop is a callable 'object'.
if (typeof stream.stop === 'function' || typeof stream.stop === 'object') {
stream.stop();
}
}
};
},{"./Constants":1,"./Grammar":6,"./URI":24}],26:[function(require,module,exports){
module.exports = WebSocketInterface;
/**
* Dependencies.
*/
var Grammar = require('./Grammar');
var debug = require('debug')('JsSIP:WebSocketInterface');
var debugerror = require('debug')('JsSIP:ERROR:WebSocketInterface');
debugerror.log = console.warn.bind(console);
function WebSocketInterface(url) {
debug('new() [url:"%s"]', url);
var sip_uri = null;
var via_transport = null;
this.ws = null;
// setting the 'scheme' alters the sip_uri too (used in SIP Route header field)
Object.defineProperties(this, {
via_transport: {
get: function() { return via_transport; },
set: function(transport) {
via_transport = transport.toUpperCase();
}
},
sip_uri: { get: function() { return sip_uri; }},
url: { get: function() { return url; }}
});
var parsed_url = Grammar.parse(url, 'absoluteURI');
if (parsed_url === -1) {
debugerror('invalid WebSocket URI: ' + url);
throw new TypeError('Invalid argument: ' + url);
} else if(parsed_url.scheme !== 'wss' && parsed_url.scheme !== 'ws') {
debugerror('invalid WebSocket URI scheme: ' + parsed_url.scheme);
throw new TypeError('Invalid argument: ' + url);
} else {
sip_uri = 'sip:' + parsed_url.host +
(parsed_url.port ? ':' + parsed_url.port : '') + ';transport=ws';
this.via_transport = parsed_url.scheme;
}
}
WebSocketInterface.prototype.connect = function () {
debug('connect()');
if (this.isConnected()) {
debug('WebSocket ' + this.url + ' is already connected');
return;
} else if (this.isConnecting()) {
debug('WebSocket ' + this.url + ' is connecting');
return;
}
if (this.ws) {
this.disconnect();
}
debug('connecting to WebSocket ' + this.url);
try {
this.ws = new WebSocket(this.url, 'sip');
this.ws.binaryType = 'arraybuffer';
this.ws.onopen = onOpen.bind(this);
this.ws.onclose = onClose.bind(this);
this.ws.onmessage = onMessage.bind(this);
this.ws.onerror = onError.bind(this);
} catch(e) {
onError.call(this, e);
}
};
WebSocketInterface.prototype.disconnect = function() {
debug('disconnect()');
if (this.ws) {
// unbind websocket event callbacks
this.ws.onopen = function() {};
this.ws.onclose = function() {};
this.ws.onmessage = function() {};
this.ws.onerror = function() {};
this.ws.close();
this.ws = null;
}
};
WebSocketInterface.prototype.send = function(message) {
debug('send()');
if (this.isConnected()) {
this.ws.send(message);
return true;
} else {
debugerror('unable to send message, WebSocket is not open');
return false;
}
};
WebSocketInterface.prototype.isConnected = function() {
return this.ws && this.ws.readyState === this.ws.OPEN;
};
WebSocketInterface.prototype.isConnecting = function() {
return this.ws && this.ws.readyState === this.ws.CONNECTING;
};
/**
* WebSocket Event Handlers
*/
function onOpen() {
debug('WebSocket ' + this.url + ' connected');
this.onconnect();
}
function onClose(e) {
debug('WebSocket ' + this.url + ' closed');
if (e.wasClean === false) {
debug('WebSocket abrupt disconnection');
}
this.ondisconnect(e.wasClean, e.code, e.reason);
}
function onMessage(e) {
debug('received WebSocket message');
this.ondata(e.data);
}
function onError(e) {
debugerror('WebSocket ' + this.url + ' error: '+ e);
}
},{"./Grammar":6,"debug":34}],27:[function(require,module,exports){
module.exports = sanityCheck;
/**
* Dependencies.
*/
var debug = require('debug')('JsSIP:sanityCheck');
var JsSIP_C = require('./Constants');
var SIPMessage = require('./SIPMessage');
var Utils = require('./Utils');
var message, ua, transport,
requests = [],
responses = [],
all = [];
requests.push(rfc3261_8_2_2_1);
requests.push(rfc3261_16_3_4);
requests.push(rfc3261_18_3_request);
requests.push(rfc3261_8_2_2_2);
responses.push(rfc3261_8_1_3_3);
responses.push(rfc3261_18_3_response);
all.push(minimumHeaders);
function sanityCheck(m, u, t) {
var len, pass;
message = m;
ua = u;
transport = t;
len = all.length;
while(len--) {
pass = all[len](message);
if(pass === false) {
return false;
}
}
if(message instanceof SIPMessage.IncomingRequest) {
len = requests.length;
while(len--) {
pass = requests[len](message);
if(pass === false) {
return false;
}
}
}
else if(message instanceof SIPMessage.IncomingResponse) {
len = responses.length;
while(len--) {
pass = responses[len](message);
if(pass === false) {
return false;
}
}
}
//Everything is OK
return true;
}
/*
* Sanity Check for incoming Messages
*
* Requests:
* - _rfc3261_8_2_2_1_ Receive a Request with a non supported URI scheme
* - _rfc3261_16_3_4_ Receive a Request already sent by us
* Does not look at via sent-by but at jssip_id, which is inserted as
* a prefix in all initial requests generated by the ua
* - _rfc3261_18_3_request_ Body Content-Length
* - _rfc3261_8_2_2_2_ Merged Requests
*
* Responses:
* - _rfc3261_8_1_3_3_ Multiple Via headers
* - _rfc3261_18_3_response_ Body Content-Length
*
* All:
* - Minimum headers in a SIP message
*/
// Sanity Check functions for requests
function rfc3261_8_2_2_1() {
if(message.s('to').uri.scheme !== 'sip') {
reply(416);
return false;
}
}
function rfc3261_16_3_4() {
if(!message.to_tag) {
if(message.call_id.substr(0, 5) === ua.configuration.jssip_id) {
reply(482);
return false;
}
}
}
function rfc3261_18_3_request() {
var len = Utils.str_utf8_length(message.body),
contentLength = message.getHeader('content-length');
if(len < contentLength) {
reply(400);
return false;
}
}
function rfc3261_8_2_2_2() {
var tr, idx,
fromTag = message.from_tag,
call_id = message.call_id,
cseq = message.cseq;
// Accept any in-dialog request.
if(message.to_tag) {
return;
}
// INVITE request.
if (message.method === JsSIP_C.INVITE) {
// If the branch matches the key of any IST then assume it is a retransmission
// and ignore the INVITE.
// TODO: we should reply the last response.
if (ua.transactions.ist[message.via_branch]) {
return false;
}
// Otherwise check whether it is a merged request.
else {
for(idx in ua.transactions.ist) {
tr = ua.transactions.ist[idx];
if(tr.request.from_tag === fromTag && tr.request.call_id === call_id && tr.request.cseq === cseq) {
reply(482);
return false;
}
}
}
}
// Non INVITE request.
else {
// If the branch matches the key of any NIST then assume it is a retransmission
// and ignore the request.
// TODO: we should reply the last response.
if (ua.transactions.nist[message.via_branch]) {
return false;
}
// Otherwise check whether it is a merged request.
else {
for(idx in ua.transactions.nist) {
tr = ua.transactions.nist[idx];
if(tr.request.from_tag === fromTag && tr.request.call_id === call_id && tr.request.cseq === cseq) {
reply(482);
return false;
}
}
}
}
}
// Sanity Check functions for responses
function rfc3261_8_1_3_3() {
if(message.getHeaders('via').length > 1) {
debug('more than one Via header field present in the response, dropping the response');
return false;
}
}
function rfc3261_18_3_response() {
var
len = Utils.str_utf8_length(message.body),
contentLength = message.getHeader('content-length');
if(len < contentLength) {
debug('message body length is lower than the value in Content-Length header field, dropping the response');
return false;
}
}
// Sanity Check functions for requests and responses
function minimumHeaders() {
var
mandatoryHeaders = ['from', 'to', 'call_id', 'cseq', 'via'],
idx = mandatoryHeaders.length;
while(idx--) {
if(!message.hasHeader(mandatoryHeaders[idx])) {
debug('missing mandatory header field : ' + mandatoryHeaders[idx] + ', dropping the response');
return false;
}
}
}
// Reply
function reply(status_code) {
var to,
response = 'SIP/2.0 ' + status_code + ' ' + JsSIP_C.REASON_PHRASE[status_code] + '\r\n',
vias = message.getHeaders('via'),
length = vias.length,
idx = 0;
for(idx; idx < length; idx++) {
response += 'Via: ' + vias[idx] + '\r\n';
}
to = message.getHeader('To');
if(!message.to_tag) {
to += ';tag=' + Utils.newTag();
}
response += 'To: ' + to + '\r\n';
response += 'From: ' + message.getHeader('From') + '\r\n';
response += 'Call-ID: ' + message.call_id + '\r\n';
response += 'CSeq: ' + message.cseq + ' ' + message.method + '\r\n';
response += '\r\n';
transport.send(response);
}
},{"./Constants":1,"./SIPMessage":18,"./Utils":25,"debug":34}],28:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
} else {
// At least give some kind of context to the user
var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
err.context = er;
throw err;
}
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
} else if (isObject(handler)) {
args = Array.prototype.slice.call(arguments, 1);
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.prototype.listenerCount = function(type) {
if (this._events) {
var evlistener = this._events[type];
if (isFunction(evlistener))
return 1;
else if (evlistener)
return evlistener.length;
}
return 0;
};
EventEmitter.listenerCount = function(emitter, type) {
return emitter.listenerCount(type);
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
},{}],29:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],30:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],31:[function(require,module,exports){
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}
},{}],32:[function(require,module,exports){
(function (process,global){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up.
if (isUndefined(global.process)) {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
if (process.noDeprecation === true) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
if (isUndefined(debugEnviron))
debugEnviron = process.env.NODE_DEBUG || '';
set = set.toUpperCase();
if (!debugs[set]) {
if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = require('./support/isBuffer');
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = require('inherits');
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./support/isBuffer":31,"_process":29,"inherits":30}],33:[function(require,module,exports){
/**
* Helpers.
*/
var s = 1000
var m = s * 60
var h = m * 60
var d = h * 24
var y = d * 365.25
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} options
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
module.exports = function (val, options) {
options = options || {}
var type = typeof val
if (type === 'string' && val.length > 0) {
return parse(val)
} else if (type === 'number' && isNaN(val) === false) {
return options.long ?
fmtLong(val) :
fmtShort(val)
}
throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val))
}
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str)
if (str.length > 10000) {
return
}
var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str)
if (!match) {
return
}
var n = parseFloat(match[1])
var type = (match[2] || 'ms').toLowerCase()
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y
case 'days':
case 'day':
case 'd':
return n * d
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n
default:
return undefined
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
if (ms >= d) {
return Math.round(ms / d) + 'd'
}
if (ms >= h) {
return Math.round(ms / h) + 'h'
}
if (ms >= m) {
return Math.round(ms / m) + 'm'
}
if (ms >= s) {
return Math.round(ms / s) + 's'
}
return ms + 'ms'
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
return plural(ms, d, 'day') ||
plural(ms, h, 'hour') ||
plural(ms, m, 'minute') ||
plural(ms, s, 'second') ||
ms + ' ms'
}
/**
* Pluralization helper.
*/
function plural(ms, n, name) {
if (ms < n) {
return
}
if (ms < n * 1.5) {
return Math.floor(ms / n) + ' ' + name
}
return Math.ceil(ms / n) + ' ' + name + 's'
}
},{}],34:[function(require,module,exports){
(function (process){
/**
* This is the web browser implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = require('./debug');
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = 'undefined' != typeof chrome
&& 'undefined' != typeof chrome.storage
? chrome.storage.local
: localstorage();
/**
* Colors.
*/
exports.colors = [
'lightseagreen',
'forestgreen',
'goldenrod',
'dodgerblue',
'darkorchid',
'crimson'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
function useColors() {
// NB: In an Electron preload script, document will be defined but not fully
// initialized. Since we know we're in Chrome, we'll just detect this case
// explicitly
if (typeof window !== 'undefined' && window && typeof window.process !== 'undefined' && window.process.type === 'renderer') {
return true;
}
// is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return (typeof document !== 'undefined' && document && 'WebkitAppearance' in document.documentElement.style) ||
// is firebug? http://stackoverflow.com/a/398120/376773
(typeof window !== 'undefined' && window && window.console && (console.firebug || (console.exception && console.table))) ||
// is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
// double check webkit in userAgent just in case we are in a worker
(typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
}
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
exports.formatters.j = function(v) {
try {
return JSON.stringify(v);
} catch (err) {
return '[UnexpectedJSONParseError]: ' + err.message;
}
};
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs(args) {
var useColors = this.useColors;
args[0] = (useColors ? '%c' : '')
+ this.namespace
+ (useColors ? ' %c' : ' ')
+ args[0]
+ (useColors ? '%c ' : ' ')
+ '+' + exports.humanize(this.diff);
if (!useColors) return;
var c = 'color: ' + this.color;
args.splice(1, 0, c, 'color: inherit')
// the final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
var index = 0;
var lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, function(match) {
if ('%%' === match) return;
index++;
if ('%c' === match) {
// we only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
*
* @api public
*/
function log() {
// this hackery is required for IE8/9, where
// the `console.log` function doesn't have 'apply'
return 'object' === typeof console
&& console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (null == namespaces) {
exports.storage.removeItem('debug');
} else {
exports.storage.debug = namespaces;
}
} catch(e) {}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
try {
return exports.storage.debug;
} catch(e) {}
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (typeof process !== 'undefined' && 'env' in process) {
return process.env.DEBUG;
}
}
/**
* Enable namespaces listed in `localStorage.debug` initially.
*/
exports.enable(load());
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage() {
try {
return window.localStorage;
} catch (e) {}
}
}).call(this,require('_process'))
},{"./debug":35,"_process":29}],35:[function(require,module,exports){
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = createDebug.debug = createDebug.default = createDebug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
exports.enabled = enabled;
exports.humanize = require('ms');
/**
* The currently active debug mode names, and names to skip.
*/
exports.names = [];
exports.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
exports.formatters = {};
/**
* Previous log timestamp.
*/
var prevTime;
/**
* Select a color.
* @param {String} namespace
* @return {Number}
* @api private
*/
function selectColor(namespace) {
var hash = 0, i;
for (i in namespace) {
hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return exports.colors[Math.abs(hash) % exports.colors.length];
}
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function createDebug(namespace) {
function debug() {
// disabled?
if (!debug.enabled) return;
var self = debug;
// set `diff` timestamp
var curr = +new Date();
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
// turn the `arguments` into a proper Array
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
args[0] = exports.coerce(args[0]);
if ('string' !== typeof args[0]) {
// anything else let's inspect with %O
args.unshift('%O');
}
// apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
// if we encounter an escaped % then don't increase the array index
if (match === '%%') return match;
index++;
var formatter = exports.formatters[format];
if ('function' === typeof formatter) {
var val = args[index];
match = formatter.call(self, val);
// now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
// apply env-specific formatting (colors, etc.)
exports.formatArgs.call(self, args);
var logFn = debug.log || exports.log || console.log.bind(console);
logFn.apply(self, args);
}
debug.namespace = namespace;
debug.enabled = exports.enabled(namespace);
debug.useColors = exports.useColors();
debug.color = selectColor(namespace);
// env-specific initialization logic for debug instances
if ('function' === typeof exports.init) {
exports.init(debug);
}
return debug;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
exports.save(namespaces);
var split = (namespaces || '').split(/[\s,]+/);
var len = split.length;
for (var i = 0; i < len; i++) {
if (!split[i]) continue; // ignore empty strings
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
exports.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @api public
*/
function disable() {
exports.enable('');
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
var i, len;
for (i = 0, len = exports.skips.length; i < len; i++) {
if (exports.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = exports.names.length; i < len; i++) {
if (exports.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
},{"ms":33}],36:[function(require,module,exports){
var grammar = module.exports = {
v: [{
name: 'version',
reg: /^(\d*)$/
}],
o: [{ //o=- 20518 0 IN IP4 203.0.113.1
// NB: sessionId will be a String in most cases because it is huge
name: 'origin',
reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
format: "%s %s %d %s IP%d %s"
}],
// default parsing of these only (though some of these feel outdated)
s: [{ name: 'name' }],
i: [{ name: 'description' }],
u: [{ name: 'uri' }],
e: [{ name: 'email' }],
p: [{ name: 'phone' }],
z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
//k: [{}], // outdated thing ignored
t: [{ //t=0 0
name: 'timing',
reg: /^(\d*) (\d*)/,
names: ['start', 'stop'],
format: "%d %d"
}],
c: [{ //c=IN IP4 10.47.197.26
name: 'connection',
reg: /^IN IP(\d) (\S*)/,
names: ['version', 'ip'],
format: "IN IP%d %s"
}],
b: [{ //b=AS:4000
push: 'bandwidth',
reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
names: ['type', 'limit'],
format: "%s:%s"
}],
m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
// NB: special - pushes to session
// TODO: rtp/fmtp should be filtered by the payloads found here?
reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
names: ['type', 'port', 'protocol', 'payloads'],
format: "%s %d %s %s"
}],
a: [
{ //a=rtpmap:110 opus/48000/2
push: 'rtp',
reg: /^rtpmap:(\d*) ([\w\-\.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,
names: ['payload', 'codec', 'rate', 'encoding'],
format: function (o) {
return (o.encoding) ?
"rtpmap:%d %s/%s/%s":
o.rate ?
"rtpmap:%d %s/%s":
"rtpmap:%d %s";
}
},
{
//a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
//a=fmtp:111 minptime=10; useinbandfec=1
push: 'fmtp',
reg: /^fmtp:(\d*) ([\S| ]*)/,
names: ['payload', 'config'],
format: "fmtp:%d %s"
},
{ //a=control:streamid=0
name: 'control',
reg: /^control:(.*)/,
format: "control:%s"
},
{ //a=rtcp:65179 IN IP4 193.84.77.194
name: 'rtcp',
reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
names: ['port', 'netType', 'ipVer', 'address'],
format: function (o) {
return (o.address != null) ?
"rtcp:%d %s IP%d %s":
"rtcp:%d";
}
},
{ //a=rtcp-fb:98 trr-int 100
push: 'rtcpFbTrrInt',
reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
names: ['payload', 'value'],
format: "rtcp-fb:%d trr-int %d"
},
{ //a=rtcp-fb:98 nack rpsi
push: 'rtcpFb',
reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
names: ['payload', 'type', 'subtype'],
format: function (o) {
return (o.subtype != null) ?
"rtcp-fb:%s %s %s":
"rtcp-fb:%s %s";
}
},
{ //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
//a=extmap:1/recvonly URI-gps-string
push: 'ext',
reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
names: ['value', 'uri', 'config'], // value may include "/direction" suffix
format: function (o) {
return (o.config != null) ?
"extmap:%s %s %s":
"extmap:%s %s";
}
},
{
//a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
push: 'crypto',
reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
names: ['id', 'suite', 'config', 'sessionConfig'],
format: function (o) {
return (o.sessionConfig != null) ?
"crypto:%d %s %s %s":
"crypto:%d %s %s";
}
},
{ //a=setup:actpass
name: 'setup',
reg: /^setup:(\w*)/,
format: "setup:%s"
},
{ //a=mid:1
name: 'mid',
reg: /^mid:([^\s]*)/,
format: "mid:%s"
},
{ //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
name: 'msid',
reg: /^msid:(.*)/,
format: "msid:%s"
},
{ //a=ptime:20
name: 'ptime',
reg: /^ptime:(\d*)/,
format: "ptime:%d"
},
{ //a=maxptime:60
name: 'maxptime',
reg: /^maxptime:(\d*)/,
format: "maxptime:%d"
},
{ //a=sendrecv
name: 'direction',
reg: /^(sendrecv|recvonly|sendonly|inactive)/
},
{ //a=ice-lite
name: 'icelite',
reg: /^(ice-lite)/
},
{ //a=ice-ufrag:F7gI
name: 'iceUfrag',
reg: /^ice-ufrag:(\S*)/,
format: "ice-ufrag:%s"
},
{ //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
name: 'icePwd',
reg: /^ice-pwd:(\S*)/,
format: "ice-pwd:%s"
},
{ //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
name: 'fingerprint',
reg: /^fingerprint:(\S*) (\S*)/,
names: ['type', 'hash'],
format: "fingerprint:%s %s"
},
{
//a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
//a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
//a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
//a=candidate:229815620 1 tcp 1518280447 192.168.150.19 60017 typ host tcptype active generation 0
//a=candidate:3289912957 2 tcp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 tcptype passive generation 0
push:'candidates',
reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?/,
names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'tcptype', 'generation'],
format: function (o) {
var str = "candidate:%s %d %s %d %s %d typ %s";
str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
// NB: candidate has three optional chunks, so %void middles one if it's missing
str += (o.tcptype != null) ? " tcptype %s" : "%v";
if (o.generation != null) {
str += " generation %d";
}
return str;
}
},
{ //a=end-of-candidates (keep after the candidates line for readability)
name: 'endOfCandidates',
reg: /^(end-of-candidates)/
},
{ //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
name: 'remoteCandidates',
reg: /^remote-candidates:(.*)/,
format: "remote-candidates:%s"
},
{ //a=ice-options:google-ice
name: 'iceOptions',
reg: /^ice-options:(\S*)/,
format: "ice-options:%s"
},
{ //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
push: "ssrcs",
reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
names: ['id', 'attribute', 'value'],
format: "ssrc:%d %s:%s"
},
{ //a=ssrc-group:FEC 1 2
push: "ssrcGroups",
reg: /^ssrc-group:(\w*) (.*)/,
names: ['semantics', 'ssrcs'],
format: "ssrc-group:%s %s"
},
{ //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
name: "msidSemantic",
reg: /^msid-semantic:\s?(\w*) (\S*)/,
names: ['semantic', 'token'],
format: "msid-semantic: %s %s" // space after ":" is not accidental
},
{ //a=group:BUNDLE audio video
push: 'groups',
reg: /^group:(\w*) (.*)/,
names: ['type', 'mids'],
format: "group:%s %s"
},
{ //a=rtcp-mux
name: 'rtcpMux',
reg: /^(rtcp-mux)/
},
{ //a=rtcp-rsize
name: 'rtcpRsize',
reg: /^(rtcp-rsize)/
},
{ //a=sctpmap:5000 webrtc-datachannel 1024
name: 'sctpmap',
reg: /^sctpmap:([\w_\/]*) (\S*)(?: (\S*))?/,
names: ['sctpmapNumber', 'app', 'maxMessageSize'],
format: function (o) {
return (o.maxMessageSize != null) ?
"sctpmap:%s %s %s" :
"sctpmap:%s %s";
}
},
{ // any a= that we don't understand is kepts verbatim on media.invalid
push: 'invalid',
names: ["value"]
}
]
};
// set sensible defaults to avoid polluting the grammar with boring details
Object.keys(grammar).forEach(function (key) {
var objs = grammar[key];
objs.forEach(function (obj) {
if (!obj.reg) {
obj.reg = /(.*)/;
}
if (!obj.format) {
obj.format = "%s";
}
});
});
},{}],37:[function(require,module,exports){
var parser = require('./parser');
var writer = require('./writer');
exports.write = writer;
exports.parse = parser.parse;
exports.parseFmtpConfig = parser.parseFmtpConfig;
exports.parsePayloads = parser.parsePayloads;
exports.parseRemoteCandidates = parser.parseRemoteCandidates;
},{"./parser":38,"./writer":39}],38:[function(require,module,exports){
var toIntIfInt = function (v) {
return String(Number(v)) === v ? Number(v) : v;
};
var attachProperties = function (match, location, names, rawName) {
if (rawName && !names) {
location[rawName] = toIntIfInt(match[1]);
}
else {
for (var i = 0; i < names.length; i += 1) {
if (match[i+1] != null) {
location[names[i]] = toIntIfInt(match[i+1]);
}
}
}
};
var parseReg = function (obj, location, content) {
var needsBlank = obj.name && obj.names;
if (obj.push && !location[obj.push]) {
location[obj.push] = [];
}
else if (needsBlank && !location[obj.name]) {
location[obj.name] = {};
}
var keyLocation = obj.push ?
{} : // blank object that will be pushed
needsBlank ? location[obj.name] : location; // otherwise, named location or root
attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
if (obj.push) {
location[obj.push].push(keyLocation);
}
};
var grammar = require('./grammar');
var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
exports.parse = function (sdp) {
var session = {}
, media = []
, location = session; // points at where properties go under (one of the above)
// parse lines we understand
sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
var type = l[0];
var content = l.slice(2);
if (type === 'm') {
media.push({rtp: [], fmtp: []});
location = media[media.length-1]; // point at latest media line
}
for (var j = 0; j < (grammar[type] || []).length; j += 1) {
var obj = grammar[type][j];
if (obj.reg.test(content)) {
return parseReg(obj, location, content);
}
}
});
session.media = media; // link it up
return session;
};
var fmtpReducer = function (acc, expr) {
var s = expr.split(/=(.+)/, 2);
if (s.length === 2) {
acc[s[0]] = toIntIfInt(s[1]);
}
return acc;
};
exports.parseFmtpConfig = function (str) {
return str.split(/\;\s?/).reduce(fmtpReducer, {});
};
exports.parsePayloads = function (str) {
return str.split(' ').map(Number);
};
exports.parseRemoteCandidates = function (str) {
var candidates = [];
var parts = str.split(' ').map(toIntIfInt);
for (var i = 0; i < parts.length; i += 3) {
candidates.push({
component: parts[i],
ip: parts[i + 1],
port: parts[i + 2]
});
}
return candidates;
};
},{"./grammar":36}],39:[function(require,module,exports){
var grammar = require('./grammar');
// customized util.format - discards excess arguments and can void middle ones
var formatRegExp = /%[sdv%]/g;
var format = function (formatStr) {
var i = 1;
var args = arguments;
var len = args.length;
return formatStr.replace(formatRegExp, function (x) {
if (i >= len) {
return x; // missing argument
}
var arg = args[i];
i += 1;
switch (x) {
case '%%':
return '%';
case '%s':
return String(arg);
case '%d':
return Number(arg);
case '%v':
return '';
}
});
// NB: we discard excess arguments - they are typically undefined from makeLine
};
var makeLine = function (type, obj, location) {
var str = obj.format instanceof Function ?
(obj.format(obj.push ? location : location[obj.name])) :
obj.format;
var args = [type + '=' + str];
if (obj.names) {
for (var i = 0; i < obj.names.length; i += 1) {
var n = obj.names[i];
if (obj.name) {
args.push(location[obj.name][n]);
}
else { // for mLine and push attributes
args.push(location[obj.names[i]]);
}
}
}
else {
args.push(location[obj.name]);
}
return format.apply(null, args);
};
// RFC specified order
// TODO: extend this with all the rest
var defaultOuterOrder = [
'v', 'o', 's', 'i',
'u', 'e', 'p', 'c',
'b', 't', 'r', 'z', 'a'
];
var defaultInnerOrder = ['i', 'c', 'b', 'a'];
module.exports = function (session, opts) {
opts = opts || {};
// ensure certain properties exist
if (session.version == null) {
session.version = 0; // "v=0" must be there (only defined version atm)
}
if (session.name == null) {
session.name = " "; // "s= " must be there if no meaningful name set
}
session.media.forEach(function (mLine) {
if (mLine.payloads == null) {
mLine.payloads = "";
}
});
var outerOrder = opts.outerOrder || defaultOuterOrder;
var innerOrder = opts.innerOrder || defaultInnerOrder;
var sdp = [];
// loop through outerOrder for matching properties on session
outerOrder.forEach(function (type) {
grammar[type].forEach(function (obj) {
if (obj.name in session && session[obj.name] != null) {
sdp.push(makeLine(type, obj, session));
}
else if (obj.push in session && session[obj.push] != null) {
session[obj.push].forEach(function (el) {
sdp.push(makeLine(type, obj, el));
});
}
});
});
// then for each media line, follow the innerOrder
session.media.forEach(function (mLine) {
sdp.push(makeLine('m', grammar.m[0], mLine));
innerOrder.forEach(function (type) {
grammar[type].forEach(function (obj) {
if (obj.name in mLine && mLine[obj.name] != null) {
sdp.push(makeLine(type, obj, mLine));
}
else if (obj.push in mLine && mLine[obj.push] != null) {
mLine[obj.push].forEach(function (el) {
sdp.push(makeLine(type, obj, el));
});
}
});
});
});
return sdp.join('\r\n') + '\r\n';
};
},{"./grammar":36}],40:[function(require,module,exports){
/* eslint-env node */
'use strict';
// SDP helpers.
var SDPUtils = {};
// Generate an alphanumeric identifier for cname or mids.
// TODO: use UUIDs instead? https://gist.github.com/jed/982883
SDPUtils.generateIdentifier = function() {
return Math.random().toString(36).substr(2, 10);
};
// The RTCP CNAME used by all peerconnections from the same JS.
SDPUtils.localCName = SDPUtils.generateIdentifier();
// Splits SDP into lines, dealing with both CRLF and LF.
SDPUtils.splitLines = function(blob) {
return blob.trim().split('\n').map(function(line) {
return line.trim();
});
};
// Splits SDP into sessionpart and mediasections. Ensures CRLF.
SDPUtils.splitSections = function(blob) {
var parts = blob.split('\nm=');
return parts.map(function(part, index) {
return (index > 0 ? 'm=' + part : part).trim() + '\r\n';
});
};
// Returns lines that start with a certain prefix.
SDPUtils.matchPrefix = function(blob, prefix) {
return SDPUtils.splitLines(blob).filter(function(line) {
return line.indexOf(prefix) === 0;
});
};
// Parses an ICE candidate line. Sample input:
// candidate:702786350 2 udp 41819902 8.8.8.8 60769 typ relay raddr 8.8.8.8
// rport 55996"
SDPUtils.parseCandidate = function(line) {
var parts;
// Parse both variants.
if (line.indexOf('a=candidate:') === 0) {
parts = line.substring(12).split(' ');
} else {
parts = line.substring(10).split(' ');
}
var candidate = {
foundation: parts[0],
component: parts[1],
protocol: parts[2].toLowerCase(),
priority: parseInt(parts[3], 10),
ip: parts[4],
port: parseInt(parts[5], 10),
// skip parts[6] == 'typ'
type: parts[7]
};
for (var i = 8; i < parts.length; i += 2) {
switch (parts[i]) {
case 'raddr':
candidate.relatedAddress = parts[i + 1];
break;
case 'rport':
candidate.relatedPort = parseInt(parts[i + 1], 10);
break;
case 'tcptype':
candidate.tcpType = parts[i + 1];
break;
default: // Unknown extensions are silently ignored.
break;
}
}
return candidate;
};
// Translates a candidate object into SDP candidate attribute.
SDPUtils.writeCandidate = function(candidate) {
var sdp = [];
sdp.push(candidate.foundation);
sdp.push(candidate.component);
sdp.push(candidate.protocol.toUpperCase());
sdp.push(candidate.priority);
sdp.push(candidate.ip);
sdp.push(candidate.port);
var type = candidate.type;
sdp.push('typ');
sdp.push(type);
if (type !== 'host' && candidate.relatedAddress &&
candidate.relatedPort) {
sdp.push('raddr');
sdp.push(candidate.relatedAddress); // was: relAddr
sdp.push('rport');
sdp.push(candidate.relatedPort); // was: relPort
}
if (candidate.tcpType && candidate.protocol.toLowerCase() === 'tcp') {
sdp.push('tcptype');
sdp.push(candidate.tcpType);
}
return 'candidate:' + sdp.join(' ');
};
// Parses an rtpmap line, returns RTCRtpCoddecParameters. Sample input:
// a=rtpmap:111 opus/48000/2
SDPUtils.parseRtpMap = function(line) {
var parts = line.substr(9).split(' ');
var parsed = {
payloadType: parseInt(parts.shift(), 10) // was: id
};
parts = parts[0].split('/');
parsed.name = parts[0];
parsed.clockRate = parseInt(parts[1], 10); // was: clockrate
// was: channels
parsed.numChannels = parts.length === 3 ? parseInt(parts[2], 10) : 1;
return parsed;
};
// Generate an a=rtpmap line from RTCRtpCodecCapability or
// RTCRtpCodecParameters.
SDPUtils.writeRtpMap = function(codec) {
var pt = codec.payloadType;
if (codec.preferredPayloadType !== undefined) {
pt = codec.preferredPayloadType;
}
return 'a=rtpmap:' + pt + ' ' + codec.name + '/' + codec.clockRate +
(codec.numChannels !== 1 ? '/' + codec.numChannels : '') + '\r\n';
};
// Parses an a=extmap line (headerextension from RFC 5285). Sample input:
// a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
SDPUtils.parseExtmap = function(line) {
var parts = line.substr(9).split(' ');
return {
id: parseInt(parts[0], 10),
uri: parts[1]
};
};
// Generates a=extmap line from RTCRtpHeaderExtensionParameters or
// RTCRtpHeaderExtension.
SDPUtils.writeExtmap = function(headerExtension) {
return 'a=extmap:' + (headerExtension.id || headerExtension.preferredId) +
' ' + headerExtension.uri + '\r\n';
};
// Parses an ftmp line, returns dictionary. Sample input:
// a=fmtp:96 vbr=on;cng=on
// Also deals with vbr=on; cng=on
SDPUtils.parseFmtp = function(line) {
var parsed = {};
var kv;
var parts = line.substr(line.indexOf(' ') + 1).split(';');
for (var j = 0; j < parts.length; j++) {
kv = parts[j].trim().split('=');
parsed[kv[0].trim()] = kv[1];
}
return parsed;
};
// Generates an a=ftmp line from RTCRtpCodecCapability or RTCRtpCodecParameters.
SDPUtils.writeFmtp = function(codec) {
var line = '';
var pt = codec.payloadType;
if (codec.preferredPayloadType !== undefined) {
pt = codec.preferredPayloadType;
}
if (codec.parameters && Object.keys(codec.parameters).length) {
var params = [];
Object.keys(codec.parameters).forEach(function(param) {
params.push(param + '=' + codec.parameters[param]);
});
line += 'a=fmtp:' + pt + ' ' + params.join(';') + '\r\n';
}
return line;
};
// Parses an rtcp-fb line, returns RTCPRtcpFeedback object. Sample input:
// a=rtcp-fb:98 nack rpsi
SDPUtils.parseRtcpFb = function(line) {
var parts = line.substr(line.indexOf(' ') + 1).split(' ');
return {
type: parts.shift(),
parameter: parts.join(' ')
};
};
// Generate a=rtcp-fb lines from RTCRtpCodecCapability or RTCRtpCodecParameters.
SDPUtils.writeRtcpFb = function(codec) {
var lines = '';
var pt = codec.payloadType;
if (codec.preferredPayloadType !== undefined) {
pt = codec.preferredPayloadType;
}
if (codec.rtcpFeedback && codec.rtcpFeedback.length) {
// FIXME: special handling for trr-int?
codec.rtcpFeedback.forEach(function(fb) {
lines += 'a=rtcp-fb:' + pt + ' ' + fb.type +
(fb.parameter && fb.parameter.length ? ' ' + fb.parameter : '') +
'\r\n';
});
}
return lines;
};
// Parses an RFC 5576 ssrc media attribute. Sample input:
// a=ssrc:3735928559 cname:something
SDPUtils.parseSsrcMedia = function(line) {
var sp = line.indexOf(' ');
var parts = {
ssrc: parseInt(line.substr(7, sp - 7), 10)
};
var colon = line.indexOf(':', sp);
if (colon > -1) {
parts.attribute = line.substr(sp + 1, colon - sp - 1);
parts.value = line.substr(colon + 1);
} else {
parts.attribute = line.substr(sp + 1);
}
return parts;
};
// Extracts DTLS parameters from SDP media section or sessionpart.
// FIXME: for consistency with other functions this should only
// get the fingerprint line as input. See also getIceParameters.
SDPUtils.getDtlsParameters = function(mediaSection, sessionpart) {
var lines = SDPUtils.splitLines(mediaSection);
// Search in session part, too.
lines = lines.concat(SDPUtils.splitLines(sessionpart));
var fpLine = lines.filter(function(line) {
return line.indexOf('a=fingerprint:') === 0;
})[0].substr(14);
// Note: a=setup line is ignored since we use the 'auto' role.
var dtlsParameters = {
role: 'auto',
fingerprints: [{
algorithm: fpLine.split(' ')[0],
value: fpLine.split(' ')[1]
}]
};
return dtlsParameters;
};
// Serializes DTLS parameters to SDP.
SDPUtils.writeDtlsParameters = function(params, setupType) {
var sdp = 'a=setup:' + setupType + '\r\n';
params.fingerprints.forEach(function(fp) {
sdp += 'a=fingerprint:' + fp.algorithm + ' ' + fp.value + '\r\n';
});
return sdp;
};
// Parses ICE information from SDP media section or sessionpart.
// FIXME: for consistency with other functions this should only
// get the ice-ufrag and ice-pwd lines as input.
SDPUtils.getIceParameters = function(mediaSection, sessionpart) {
var lines = SDPUtils.splitLines(mediaSection);
// Search in session part, too.
lines = lines.concat(SDPUtils.splitLines(sessionpart));
var iceParameters = {
usernameFragment: lines.filter(function(line) {
return line.indexOf('a=ice-ufrag:') === 0;
})[0].substr(12),
password: lines.filter(function(line) {
return line.indexOf('a=ice-pwd:') === 0;
})[0].substr(10)
};
return iceParameters;
};
// Serializes ICE parameters to SDP.
SDPUtils.writeIceParameters = function(params) {
return 'a=ice-ufrag:' + params.usernameFragment + '\r\n' +
'a=ice-pwd:' + params.password + '\r\n';
};
// Parses the SDP media section and returns RTCRtpParameters.
SDPUtils.parseRtpParameters = function(mediaSection) {
var description = {
codecs: [],
headerExtensions: [],
fecMechanisms: [],
rtcp: []
};
var lines = SDPUtils.splitLines(mediaSection);
var mline = lines[0].split(' ');
for (var i = 3; i < mline.length; i++) { // find all codecs from mline[3..]
var pt = mline[i];
var rtpmapline = SDPUtils.matchPrefix(
mediaSection, 'a=rtpmap:' + pt + ' ')[0];
if (rtpmapline) {
var codec = SDPUtils.parseRtpMap(rtpmapline);
var fmtps = SDPUtils.matchPrefix(
mediaSection, 'a=fmtp:' + pt + ' ');
// Only the first a=fmtp:<pt> is considered.
codec.parameters = fmtps.length ? SDPUtils.parseFmtp(fmtps[0]) : {};
codec.rtcpFeedback = SDPUtils.matchPrefix(
mediaSection, 'a=rtcp-fb:' + pt + ' ')
.map(SDPUtils.parseRtcpFb);
description.codecs.push(codec);
// parse FEC mechanisms from rtpmap lines.
switch (codec.name.toUpperCase()) {
case 'RED':
case 'ULPFEC':
description.fecMechanisms.push(codec.name.toUpperCase());
break;
default: // only RED and ULPFEC are recognized as FEC mechanisms.
break;
}
}
}
SDPUtils.matchPrefix(mediaSection, 'a=extmap:').forEach(function(line) {
description.headerExtensions.push(SDPUtils.parseExtmap(line));
});
// FIXME: parse rtcp.
return description;
};
// Generates parts of the SDP media section describing the capabilities /
// parameters.
SDPUtils.writeRtpDescription = function(kind, caps) {
var sdp = '';
// Build the mline.
sdp += 'm=' + kind + ' ';
sdp += caps.codecs.length > 0 ? '9' : '0'; // reject if no codecs.
sdp += ' UDP/TLS/RTP/SAVPF ';
sdp += caps.codecs.map(function(codec) {
if (codec.preferredPayloadType !== undefined) {
return codec.preferredPayloadType;
}
return codec.payloadType;
}).join(' ') + '\r\n';
sdp += 'c=IN IP4 0.0.0.0\r\n';
sdp += 'a=rtcp:9 IN IP4 0.0.0.0\r\n';
// Add a=rtpmap lines for each codec. Also fmtp and rtcp-fb.
caps.codecs.forEach(function(codec) {
sdp += SDPUtils.writeRtpMap(codec);
sdp += SDPUtils.writeFmtp(codec);
sdp += SDPUtils.writeRtcpFb(codec);
});
sdp += 'a=rtcp-mux\r\n';
caps.headerExtensions.forEach(function(extension) {
sdp += SDPUtils.writeExtmap(extension);
});
// FIXME: write fecMechanisms.
return sdp;
};
// Parses the SDP media section and returns an array of
// RTCRtpEncodingParameters.
SDPUtils.parseRtpEncodingParameters = function(mediaSection) {
var encodingParameters = [];
var description = SDPUtils.parseRtpParameters(mediaSection);
var hasRed = description.fecMechanisms.indexOf('RED') !== -1;
var hasUlpfec = description.fecMechanisms.indexOf('ULPFEC') !== -1;
// filter a=ssrc:... cname:, ignore PlanB-msid
var ssrcs = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')
.map(function(line) {
return SDPUtils.parseSsrcMedia(line);
})
.filter(function(parts) {
return parts.attribute === 'cname';
});
var primarySsrc = ssrcs.length > 0 && ssrcs[0].ssrc;
var secondarySsrc;
var flows = SDPUtils.matchPrefix(mediaSection, 'a=ssrc-group:FID')
.map(function(line) {
var parts = line.split(' ');
parts.shift();
return parts.map(function(part) {
return parseInt(part, 10);
});
});
if (flows.length > 0 && flows[0].length > 1 && flows[0][0] === primarySsrc) {
secondarySsrc = flows[0][1];
}
description.codecs.forEach(function(codec) {
if (codec.name.toUpperCase() === 'RTX' && codec.parameters.apt) {
var encParam = {
ssrc: primarySsrc,
codecPayloadType: parseInt(codec.parameters.apt, 10),
rtx: {
payloadType: codec.payloadType,
ssrc: secondarySsrc
}
};
encodingParameters.push(encParam);
if (hasRed) {
encParam = JSON.parse(JSON.stringify(encParam));
encParam.fec = {
ssrc: secondarySsrc,
mechanism: hasUlpfec ? 'red+ulpfec' : 'red'
};
encodingParameters.push(encParam);
}
}
});
if (encodingParameters.length === 0 && primarySsrc) {
encodingParameters.push({
ssrc: primarySsrc
});
}
// we support both b=AS and b=TIAS but interpret AS as TIAS.
var bandwidth = SDPUtils.matchPrefix(mediaSection, 'b=');
if (bandwidth.length) {
if (bandwidth[0].indexOf('b=TIAS:') === 0) {
bandwidth = parseInt(bandwidth[0].substr(7), 10);
} else if (bandwidth[0].indexOf('b=AS:') === 0) {
bandwidth = parseInt(bandwidth[0].substr(5), 10);
}
encodingParameters.forEach(function(params) {
params.maxBitrate = bandwidth;
});
}
return encodingParameters;
};
SDPUtils.writeSessionBoilerplate = function() {
// FIXME: sess-id should be an NTP timestamp.
return 'v=0\r\n' +
'o=thisisadapterortc 8169639915646943137 2 IN IP4 127.0.0.1\r\n' +
's=-\r\n' +
't=0 0\r\n';
};
SDPUtils.writeMediaSection = function(transceiver, caps, type, stream) {
var sdp = SDPUtils.writeRtpDescription(transceiver.kind, caps);
// Map ICE parameters (ufrag, pwd) to SDP.
sdp += SDPUtils.writeIceParameters(
transceiver.iceGatherer.getLocalParameters());
// Map DTLS parameters to SDP.
sdp += SDPUtils.writeDtlsParameters(
transceiver.dtlsTransport.getLocalParameters(),
type === 'offer' ? 'actpass' : 'active');
sdp += 'a=mid:' + transceiver.mid + '\r\n';
if (transceiver.rtpSender && transceiver.rtpReceiver) {
sdp += 'a=sendrecv\r\n';
} else if (transceiver.rtpSender) {
sdp += 'a=sendonly\r\n';
} else if (transceiver.rtpReceiver) {
sdp += 'a=recvonly\r\n';
} else {
sdp += 'a=inactive\r\n';
}
// FIXME: for RTX there might be multiple SSRCs. Not implemented in Edge yet.
if (transceiver.rtpSender) {
var msid = 'msid:' + stream.id + ' ' +
transceiver.rtpSender.track.id + '\r\n';
sdp += 'a=' + msid;
sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
' ' + msid;
}
// FIXME: this should be written by writeRtpDescription.
sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
' cname:' + SDPUtils.localCName + '\r\n';
return sdp;
};
// Gets the direction from the mediaSection or the sessionpart.
SDPUtils.getDirection = function(mediaSection, sessionpart) {
// Look for sendrecv, sendonly, recvonly, inactive, default to sendrecv.
var lines = SDPUtils.splitLines(mediaSection);
for (var i = 0; i < lines.length; i++) {
switch (lines[i]) {
case 'a=sendrecv':
case 'a=sendonly':
case 'a=recvonly':
case 'a=inactive':
return lines[i].substr(2);
default:
// FIXME: What should happen here?
}
}
if (sessionpart) {
return SDPUtils.getDirection(sessionpart);
}
return 'sendrecv';
};
// Expose public methods.
module.exports = SDPUtils;
},{}],41:[function(require,module,exports){
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
'use strict';
// Shimming starts here.
(function() {
// Utils.
var logging = require('./utils').log;
var browserDetails = require('./utils').browserDetails;
// Export to the adapter global object visible in the browser.
module.exports.browserDetails = browserDetails;
module.exports.extractVersion = require('./utils').extractVersion;
module.exports.disableLog = require('./utils').disableLog;
// Uncomment the line below if you want logging to occur, including logging
// for the switch statement below. Can also be turned on in the browser via
// adapter.disableLog(false), but then logging from the switch statement below
// will not appear.
// require('./utils').disableLog(false);
// Browser shims.
var chromeShim = require('./chrome/chrome_shim') || null;
var edgeShim = require('./edge/edge_shim') || null;
var firefoxShim = require('./firefox/firefox_shim') || null;
var safariShim = require('./safari/safari_shim') || null;
// Shim browser if found.
switch (browserDetails.browser) {
case 'opera': // fallthrough as it uses chrome shims
case 'chrome':
if (!chromeShim || !chromeShim.shimPeerConnection) {
logging('Chrome shim is not included in this adapter release.');
return;
}
logging('adapter.js shimming chrome.');
// Export to the adapter global object visible in the browser.
module.exports.browserShim = chromeShim;
chromeShim.shimGetUserMedia();
chromeShim.shimMediaStream();
chromeShim.shimSourceObject();
chromeShim.shimPeerConnection();
chromeShim.shimOnTrack();
break;
case 'firefox':
if (!firefoxShim || !firefoxShim.shimPeerConnection) {
logging('Firefox shim is not included in this adapter release.');
return;
}
logging('adapter.js shimming firefox.');
// Export to the adapter global object visible in the browser.
module.exports.browserShim = firefoxShim;
firefoxShim.shimGetUserMedia();
firefoxShim.shimSourceObject();
firefoxShim.shimPeerConnection();
firefoxShim.shimOnTrack();
break;
case 'edge':
if (!edgeShim || !edgeShim.shimPeerConnection) {
logging('MS edge shim is not included in this adapter release.');
return;
}
logging('adapter.js shimming edge.');
// Export to the adapter global object visible in the browser.
module.exports.browserShim = edgeShim;
edgeShim.shimGetUserMedia();
edgeShim.shimPeerConnection();
break;
case 'safari':
if (!safariShim) {
logging('Safari shim is not included in this adapter release.');
return;
}
logging('adapter.js shimming safari.');
// Export to the adapter global object visible in the browser.
module.exports.browserShim = safariShim;
safariShim.shimGetUserMedia();
break;
default:
logging('Unsupported browser!');
}
})();
},{"./chrome/chrome_shim":42,"./edge/edge_shim":44,"./firefox/firefox_shim":46,"./safari/safari_shim":48,"./utils":49}],42:[function(require,module,exports){
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
'use strict';
var logging = require('../utils.js').log;
var browserDetails = require('../utils.js').browserDetails;
var chromeShim = {
shimMediaStream: function() {
window.MediaStream = window.MediaStream || window.webkitMediaStream;
},
shimOnTrack: function() {
if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in
window.RTCPeerConnection.prototype)) {
Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', {
get: function() {
return this._ontrack;
},
set: function(f) {
var self = this;
if (this._ontrack) {
this.removeEventListener('track', this._ontrack);
this.removeEventListener('addstream', this._ontrackpoly);
}
this.addEventListener('track', this._ontrack = f);
this.addEventListener('addstream', this._ontrackpoly = function(e) {
// onaddstream does not fire when a track is added to an existing
// stream. But stream.onaddtrack is implemented so we use that.
e.stream.addEventListener('addtrack', function(te) {
var event = new Event('track');
event.track = te.track;
event.receiver = {track: te.track};
event.streams = [e.stream];
self.dispatchEvent(event);
});
e.stream.getTracks().forEach(function(track) {
var event = new Event('track');
event.track = track;
event.receiver = {track: track};
event.streams = [e.stream];
this.dispatchEvent(event);
}.bind(this));
}.bind(this));
}
});
}
},
shimSourceObject: function() {
if (typeof window === 'object') {
if (window.HTMLMediaElement &&
!('srcObject' in window.HTMLMediaElement.prototype)) {
// Shim the srcObject property, once, when HTMLMediaElement is found.
Object.defineProperty(window.HTMLMediaElement.prototype, 'srcObject', {
get: function() {
return this._srcObject;
},
set: function(stream) {
var self = this;
// Use _srcObject as a private property for this shim
this._srcObject = stream;
if (this.src) {
URL.revokeObjectURL(this.src);
}
if (!stream) {
this.src = '';
return;
}
this.src = URL.createObjectURL(stream);
// We need to recreate the blob url when a track is added or
// removed. Doing it manually since we want to avoid a recursion.
stream.addEventListener('addtrack', function() {
if (self.src) {
URL.revokeObjectURL(self.src);
}
self.src = URL.createObjectURL(stream);
});
stream.addEventListener('removetrack', function() {
if (self.src) {
URL.revokeObjectURL(self.src);
}
self.src = URL.createObjectURL(stream);
});
}
});
}
}
},
shimPeerConnection: function() {
// The RTCPeerConnection object.
window.RTCPeerConnection = function(pcConfig, pcConstraints) {
// Translate iceTransportPolicy to iceTransports,
// see https://code.google.com/p/webrtc/issues/detail?id=4869
logging('PeerConnection');
if (pcConfig && pcConfig.iceTransportPolicy) {
pcConfig.iceTransports = pcConfig.iceTransportPolicy;
}
var pc = new webkitRTCPeerConnection(pcConfig, pcConstraints);
var origGetStats = pc.getStats.bind(pc);
pc.getStats = function(selector, successCallback, errorCallback) {
var self = this;
var args = arguments;
// If selector is a function then we are in the old style stats so just
// pass back the original getStats format to avoid breaking old users.
if (arguments.length > 0 && typeof selector === 'function') {
return origGetStats(selector, successCallback);
}
var fixChromeStats_ = function(response) {
var standardReport = {};
var reports = response.result();
reports.forEach(function(report) {
var standardStats = {
id: report.id,
timestamp: report.timestamp,
type: report.type
};
report.names().forEach(function(name) {
standardStats[name] = report.stat(name);
});
standardReport[standardStats.id] = standardStats;
});
return standardReport;
};
// shim getStats with maplike support
var makeMapStats = function(stats, legacyStats) {
var map = new Map(Object.keys(stats).map(function(key) {
return[key, stats[key]];
}));
legacyStats = legacyStats || stats;
Object.keys(legacyStats).forEach(function(key) {
map[key] = legacyStats[key];
});
return map;
};
if (arguments.length >= 2) {
var successCallbackWrapper_ = function(response) {
args[1](makeMapStats(fixChromeStats_(response)));
};
return origGetStats.apply(this, [successCallbackWrapper_,
arguments[0]]);
}
// promise-support
return new Promise(function(resolve, reject) {
if (args.length === 1 && typeof selector === 'object') {
origGetStats.apply(self, [
function(response) {
resolve(makeMapStats(fixChromeStats_(response)));
}, reject]);
} else {
// Preserve legacy chrome stats only on legacy access of stats obj
origGetStats.apply(self, [
function(response) {
resolve(makeMapStats(fixChromeStats_(response),
response.result()));
}, reject]);
}
}).then(successCallback, errorCallback);
};
return pc;
};
window.RTCPeerConnection.prototype = webkitRTCPeerConnection.prototype;
// wrap static methods. Currently just generateCertificate.
if (webkitRTCPeerConnection.generateCertificate) {
Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
get: function() {
return webkitRTCPeerConnection.generateCertificate;
}
});
}
['createOffer', 'createAnswer'].forEach(function(method) {
var nativeMethod = webkitRTCPeerConnection.prototype[method];
webkitRTCPeerConnection.prototype[method] = function() {
var self = this;
if (arguments.length < 1 || (arguments.length === 1 &&
typeof arguments[0] === 'object')) {
var opts = arguments.length === 1 ? arguments[0] : undefined;
return new Promise(function(resolve, reject) {
nativeMethod.apply(self, [resolve, reject, opts]);
});
}
return nativeMethod.apply(this, arguments);
};
});
// add promise support -- natively available in Chrome 51
if (browserDetails.version < 51) {
['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
.forEach(function(method) {
var nativeMethod = webkitRTCPeerConnection.prototype[method];
webkitRTCPeerConnection.prototype[method] = function() {
var args = arguments;
var self = this;
var promise = new Promise(function(resolve, reject) {
nativeMethod.apply(self, [args[0], resolve, reject]);
});
if (args.length < 2) {
return promise;
}
return promise.then(function() {
args[1].apply(null, []);
},
function(err) {
if (args.length >= 3) {
args[2].apply(null, [err]);
}
});
};
});
}
// shim implicit creation of RTCSessionDescription/RTCIceCandidate
['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
.forEach(function(method) {
var nativeMethod = webkitRTCPeerConnection.prototype[method];
webkitRTCPeerConnection.prototype[method] = function() {
arguments[0] = new ((method === 'addIceCandidate') ?
RTCIceCandidate : RTCSessionDescription)(arguments[0]);
return nativeMethod.apply(this, arguments);
};
});
// support for addIceCandidate(null or undefined)
var nativeAddIceCandidate =
RTCPeerConnection.prototype.addIceCandidate;
RTCPeerConnection.prototype.addIceCandidate = function() {
if (!arguments[0]) {
if (arguments[1]) {
arguments[1].apply(null);
}
return Promise.resolve();
}
return nativeAddIceCandidate.apply(this, arguments);
};
}
};
// Expose public methods.
module.exports = {
shimMediaStream: chromeShim.shimMediaStream,
shimOnTrack: chromeShim.shimOnTrack,
shimSourceObject: chromeShim.shimSourceObject,
shimPeerConnection: chromeShim.shimPeerConnection,
shimGetUserMedia: require('./getusermedia')
};
},{"../utils.js":49,"./getusermedia":43}],43:[function(require,module,exports){
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
'use strict';
var logging = require('../utils.js').log;
// Expose public methods.
module.exports = function() {
var constraintsToChrome_ = function(c) {
if (typeof c !== 'object' || c.mandatory || c.optional) {
return c;
}
var cc = {};
Object.keys(c).forEach(function(key) {
if (key === 'require' || key === 'advanced' || key === 'mediaSource') {
return;
}
var r = (typeof c[key] === 'object') ? c[key] : {ideal: c[key]};
if (r.exact !== undefined && typeof r.exact === 'number') {
r.min = r.max = r.exact;
}
var oldname_ = function(prefix, name) {
if (prefix) {
return prefix + name.charAt(0).toUpperCase() + name.slice(1);
}
return (name === 'deviceId') ? 'sourceId' : name;
};
if (r.ideal !== undefined) {
cc.optional = cc.optional || [];
var oc = {};
if (typeof r.ideal === 'number') {
oc[oldname_('min', key)] = r.ideal;
cc.optional.push(oc);
oc = {};
oc[oldname_('max', key)] = r.ideal;
cc.optional.push(oc);
} else {
oc[oldname_('', key)] = r.ideal;
cc.optional.push(oc);
}
}
if (r.exact !== undefined && typeof r.exact !== 'number') {
cc.mandatory = cc.mandatory || {};
cc.mandatory[oldname_('', key)] = r.exact;
} else {
['min', 'max'].forEach(function(mix) {
if (r[mix] !== undefined) {
cc.mandatory = cc.mandatory || {};
cc.mandatory[oldname_(mix, key)] = r[mix];
}
});
}
});
if (c.advanced) {
cc.optional = (cc.optional || []).concat(c.advanced);
}
return cc;
};
var shimConstraints_ = function(constraints, func) {
constraints = JSON.parse(JSON.stringify(constraints));
if (constraints && constraints.audio) {
constraints.audio = constraintsToChrome_(constraints.audio);
}
if (constraints && typeof constraints.video === 'object') {
// Shim facingMode for mobile, where it defaults to "user".
var face = constraints.video.facingMode;
face = face && ((typeof face === 'object') ? face : {ideal: face});
if ((face && (face.exact === 'user' || face.exact === 'environment' ||
face.ideal === 'user' || face.ideal === 'environment')) &&
!(navigator.mediaDevices.getSupportedConstraints &&
navigator.mediaDevices.getSupportedConstraints().facingMode)) {
delete constraints.video.facingMode;
if (face.exact === 'environment' || face.ideal === 'environment') {
// Look for "back" in label, or use last cam (typically back cam).
return navigator.mediaDevices.enumerateDevices()
.then(function(devices) {
devices = devices.filter(function(d) {
return d.kind === 'videoinput';
});
var back = devices.find(function(d) {
return d.label.toLowerCase().indexOf('back') !== -1;
}) || (devices.length && devices[devices.length - 1]);
if (back) {
constraints.video.deviceId = face.exact ? {exact: back.deviceId} :
{ideal: back.deviceId};
}
constraints.video = constraintsToChrome_(constraints.video);
logging('chrome: ' + JSON.stringify(constraints));
return func(constraints);
});
}
}
constraints.video = constraintsToChrome_(constraints.video);
}
logging('chrome: ' + JSON.stringify(constraints));
return func(constraints);
};
var shimError_ = function(e) {
return {
name: {
PermissionDeniedError: 'NotAllowedError',
ConstraintNotSatisfiedError: 'OverconstrainedError'
}[e.name] || e.name,
message: e.message,
constraint: e.constraintName,
toString: function() {
return this.name + (this.message && ': ') + this.message;
}
};
};
var getUserMedia_ = function(constraints, onSuccess, onError) {
shimConstraints_(constraints, function(c) {
navigator.webkitGetUserMedia(c, onSuccess, function(e) {
onError(shimError_(e));
});
});
};
navigator.getUserMedia = getUserMedia_;
// Returns the result of getUserMedia as a Promise.
var getUserMediaPromise_ = function(constraints) {
return new Promise(function(resolve, reject) {
navigator.getUserMedia(constraints, resolve, reject);
});
};
if (!navigator.mediaDevices) {
navigator.mediaDevices = {
getUserMedia: getUserMediaPromise_,
enumerateDevices: function() {
return new Promise(function(resolve) {
var kinds = {audio: 'audioinput', video: 'videoinput'};
return MediaStreamTrack.getSources(function(devices) {
resolve(devices.map(function(device) {
return {label: device.label,
kind: kinds[device.kind],
deviceId: device.id,
groupId: ''};
}));
});
});
}
};
}
// A shim for getUserMedia method on the mediaDevices object.
// TODO(KaptenJansson) remove once implemented in Chrome stable.
if (!navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia = function(constraints) {
return getUserMediaPromise_(constraints);
};
} else {
// Even though Chrome 45 has navigator.mediaDevices and a getUserMedia
// function which returns a Promise, it does not accept spec-style
// constraints.
var origGetUserMedia = navigator.mediaDevices.getUserMedia.
bind(navigator.mediaDevices);
navigator.mediaDevices.getUserMedia = function(cs) {
return shimConstraints_(cs, function(c) {
return origGetUserMedia(c).then(function(stream) {
if (c.audio && !stream.getAudioTracks().length ||
c.video && !stream.getVideoTracks().length) {
stream.getTracks().forEach(function(track) {
track.stop();
});
throw new DOMException('', 'NotFoundError');
}
return stream;
}, function(e) {
return Promise.reject(shimError_(e));
});
});
};
}
// Dummy devicechange event methods.
// TODO(KaptenJansson) remove once implemented in Chrome stable.
if (typeof navigator.mediaDevices.addEventListener === 'undefined') {
navigator.mediaDevices.addEventListener = function() {
logging('Dummy mediaDevices.addEventListener called.');
};
}
if (typeof navigator.mediaDevices.removeEventListener === 'undefined') {
navigator.mediaDevices.removeEventListener = function() {
logging('Dummy mediaDevices.removeEventListener called.');
};
}
};
},{"../utils.js":49}],44:[function(require,module,exports){
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
'use strict';
var SDPUtils = require('sdp');
var browserDetails = require('../utils').browserDetails;
var edgeShim = {
shimPeerConnection: function() {
if (window.RTCIceGatherer) {
// ORTC defines an RTCIceCandidate object but no constructor.
// Not implemented in Edge.
if (!window.RTCIceCandidate) {
window.RTCIceCandidate = function(args) {
return args;
};
}
// ORTC does not have a session description object but
// other browsers (i.e. Chrome) that will support both PC and ORTC
// in the future might have this defined already.
if (!window.RTCSessionDescription) {
window.RTCSessionDescription = function(args) {
return args;
};
}
// this adds an additional event listener to MediaStrackTrack that signals
// when a tracks enabled property was changed.
var origMSTEnabled = Object.getOwnPropertyDescriptor(
MediaStreamTrack.prototype, 'enabled');
Object.defineProperty(MediaStreamTrack.prototype, 'enabled', {
set: function(value) {
origMSTEnabled.set.call(this, value);
var ev = new Event('enabled');
ev.enabled = value;
this.dispatchEvent(ev);
}
});
}
window.RTCPeerConnection = function(config) {
var self = this;
var _eventTarget = document.createDocumentFragment();
['addEventListener', 'removeEventListener', 'dispatchEvent']
.forEach(function(method) {
self[method] = _eventTarget[method].bind(_eventTarget);
});
this.onicecandidate = null;
this.onaddstream = null;
this.ontrack = null;
this.onremovestream = null;
this.onsignalingstatechange = null;
this.oniceconnectionstatechange = null;
this.onnegotiationneeded = null;
this.ondatachannel = null;
this.localStreams = [];
this.remoteStreams = [];
this.getLocalStreams = function() {
return self.localStreams;
};
this.getRemoteStreams = function() {
return self.remoteStreams;
};
this.localDescription = new RTCSessionDescription({
type: '',
sdp: ''
});
this.remoteDescription = new RTCSessionDescription({
type: '',
sdp: ''
});
this.signalingState = 'stable';
this.iceConnectionState = 'new';
this.iceGatheringState = 'new';
this.iceOptions = {
gatherPolicy: 'all',
iceServers: []
};
if (config && config.iceTransportPolicy) {
switch (config.iceTransportPolicy) {
case 'all':
case 'relay':
this.iceOptions.gatherPolicy = config.iceTransportPolicy;
break;
case 'none':
// FIXME: remove once implementation and spec have added this.
throw new TypeError('iceTransportPolicy "none" not supported');
default:
// don't set iceTransportPolicy.
break;
}
}
this.usingBundle = config && config.bundlePolicy === 'max-bundle';
if (config && config.iceServers) {
// Edge does not like
// 1) stun:
// 2) turn: that does not have all of turn:host:port?transport=udp
// 3) turn: with ipv6 addresses
var iceServers = JSON.parse(JSON.stringify(config.iceServers));
this.iceOptions.iceServers = iceServers.filter(function(server) {
if (server && server.urls) {
var urls = server.urls;
if (typeof urls === 'string') {
urls = [urls];
}
urls = urls.filter(function(url) {
return (url.indexOf('turn:') === 0 &&
url.indexOf('transport=udp') !== -1 &&
url.indexOf('turn:[') === -1) ||
(url.indexOf('stun:') === 0 &&
browserDetails.version >= 14393);
})[0];
return !!urls;
}
return false;
});
}
this._config = config;
// per-track iceGathers, iceTransports, dtlsTransports, rtpSenders, ...
// everything that is needed to describe a SDP m-line.
this.transceivers = [];
// since the iceGatherer is currently created in createOffer but we
// must not emit candidates until after setLocalDescription we buffer
// them in this array.
this._localIceCandidatesBuffer = [];
};
window.RTCPeerConnection.prototype._emitBufferedCandidates = function() {
var self = this;
var sections = SDPUtils.splitSections(self.localDescription.sdp);
// FIXME: need to apply ice candidates in a way which is async but
// in-order
this._localIceCandidatesBuffer.forEach(function(event) {
var end = !event.candidate || Object.keys(event.candidate).length === 0;
if (end) {
for (var j = 1; j < sections.length; j++) {
if (sections[j].indexOf('\r\na=end-of-candidates\r\n') === -1) {
sections[j] += 'a=end-of-candidates\r\n';
}
}
} else if (event.candidate.candidate.indexOf('typ endOfCandidates')
=== -1) {
sections[event.candidate.sdpMLineIndex + 1] +=
'a=' + event.candidate.candidate + '\r\n';
}
self.localDescription.sdp = sections.join('');
self.dispatchEvent(event);
if (self.onicecandidate !== null) {
self.onicecandidate(event);
}
if (!event.candidate && self.iceGatheringState !== 'complete') {
var complete = self.transceivers.every(function(transceiver) {
return transceiver.iceGatherer &&
transceiver.iceGatherer.state === 'completed';
});
if (complete) {
self.iceGatheringState = 'complete';
}
}
});
this._localIceCandidatesBuffer = [];
};
window.RTCPeerConnection.prototype.getConfiguration = function() {
return this._config;
};
window.RTCPeerConnection.prototype.addStream = function(stream) {
// Clone is necessary for local demos mostly, attaching directly
// to two different senders does not work (build 10547).
var clonedStream = stream.clone();
stream.getTracks().forEach(function(track, idx) {
var clonedTrack = clonedStream.getTracks()[idx];
track.addEventListener('enabled', function(event) {
clonedTrack.enabled = event.enabled;
});
});
this.localStreams.push(clonedStream);
this._maybeFireNegotiationNeeded();
};
window.RTCPeerConnection.prototype.removeStream = function(stream) {
var idx = this.localStreams.indexOf(stream);
if (idx > -1) {
this.localStreams.splice(idx, 1);
this._maybeFireNegotiationNeeded();
}
};
window.RTCPeerConnection.prototype.getSenders = function() {
return this.transceivers.filter(function(transceiver) {
return !!transceiver.rtpSender;
})
.map(function(transceiver) {
return transceiver.rtpSender;
});
};
window.RTCPeerConnection.prototype.getReceivers = function() {
return this.transceivers.filter(function(transceiver) {
return !!transceiver.rtpReceiver;
})
.map(function(transceiver) {
return transceiver.rtpReceiver;
});
};
// Determines the intersection of local and remote capabilities.
window.RTCPeerConnection.prototype._getCommonCapabilities =
function(localCapabilities, remoteCapabilities) {
var commonCapabilities = {
codecs: [],
headerExtensions: [],
fecMechanisms: []
};
localCapabilities.codecs.forEach(function(lCodec) {
for (var i = 0; i < remoteCapabilities.codecs.length; i++) {
var rCodec = remoteCapabilities.codecs[i];
if (lCodec.name.toLowerCase() === rCodec.name.toLowerCase() &&
lCodec.clockRate === rCodec.clockRate) {
// number of channels is the highest common number of channels
rCodec.numChannels = Math.min(lCodec.numChannels,
rCodec.numChannels);
// push rCodec so we reply with offerer payload type
commonCapabilities.codecs.push(rCodec);
// determine common feedback mechanisms
rCodec.rtcpFeedback = rCodec.rtcpFeedback.filter(function(fb) {
for (var j = 0; j < lCodec.rtcpFeedback.length; j++) {
if (lCodec.rtcpFeedback[j].type === fb.type &&
lCodec.rtcpFeedback[j].parameter === fb.parameter) {
return true;
}
}
return false;
});
// FIXME: also need to determine .parameters
// see https://github.com/openpeer/ortc/issues/569
break;
}
}
});
localCapabilities.headerExtensions
.forEach(function(lHeaderExtension) {
for (var i = 0; i < remoteCapabilities.headerExtensions.length;
i++) {
var rHeaderExtension = remoteCapabilities.headerExtensions[i];
if (lHeaderExtension.uri === rHeaderExtension.uri) {
commonCapabilities.headerExtensions.push(rHeaderExtension);
break;
}
}
});
// FIXME: fecMechanisms
return commonCapabilities;
};
// Create ICE gatherer, ICE transport and DTLS transport.
window.RTCPeerConnection.prototype._createIceAndDtlsTransports =
function(mid, sdpMLineIndex) {
var self = this;
var iceGatherer = new RTCIceGatherer(self.iceOptions);
var iceTransport = new RTCIceTransport(iceGatherer);
iceGatherer.onlocalcandidate = function(evt) {
var event = new Event('icecandidate');
event.candidate = {sdpMid: mid, sdpMLineIndex: sdpMLineIndex};
var cand = evt.candidate;
var end = !cand || Object.keys(cand).length === 0;
// Edge emits an empty object for RTCIceCandidateComplete‥
if (end) {
// polyfill since RTCIceGatherer.state is not implemented in
// Edge 10547 yet.
if (iceGatherer.state === undefined) {
iceGatherer.state = 'completed';
}
// Emit a candidate with type endOfCandidates to make the samples
// work. Edge requires addIceCandidate with this empty candidate
// to start checking. The real solution is to signal
// end-of-candidates to the other side when getting the null
// candidate but some apps (like the samples) don't do that.
event.candidate.candidate =
'candidate:1 1 udp 1 0.0.0.0 9 typ endOfCandidates';
} else {
// RTCIceCandidate doesn't have a component, needs to be added
cand.component = iceTransport.component === 'RTCP' ? 2 : 1;
event.candidate.candidate = SDPUtils.writeCandidate(cand);
}
// update local description.
var sections = SDPUtils.splitSections(self.localDescription.sdp);
if (event.candidate.candidate.indexOf('typ endOfCandidates')
=== -1) {
sections[event.candidate.sdpMLineIndex + 1] +=
'a=' + event.candidate.candidate + '\r\n';
} else {
sections[event.candidate.sdpMLineIndex + 1] +=
'a=end-of-candidates\r\n';
}
self.localDescription.sdp = sections.join('');
var complete = self.transceivers.every(function(transceiver) {
return transceiver.iceGatherer &&
transceiver.iceGatherer.state === 'completed';
});
// Emit candidate if localDescription is set.
// Also emits null candidate when all gatherers are complete.
switch (self.iceGatheringState) {
case 'new':
self._localIceCandidatesBuffer.push(event);
if (end && complete) {
self._localIceCandidatesBuffer.push(
new Event('icecandidate'));
}
break;
case 'gathering':
self._emitBufferedCandidates();
self.dispatchEvent(event);
if (self.onicecandidate !== null) {
self.onicecandidate(event);
}
if (complete) {
self.dispatchEvent(new Event('icecandidate'));
if (self.onicecandidate !== null) {
self.onicecandidate(new Event('icecandidate'));
}
self.iceGatheringState = 'complete';
}
break;
case 'complete':
// should not happen... currently!
break;
default: // no-op.
break;
}
};
iceTransport.onicestatechange = function() {
self._updateConnectionState();
};
var dtlsTransport = new RTCDtlsTransport(iceTransport);
dtlsTransport.ondtlsstatechange = function() {
self._updateConnectionState();
};
dtlsTransport.onerror = function() {
// onerror does not set state to failed by itself.
dtlsTransport.state = 'failed';
self._updateConnectionState();
};
return {
iceGatherer: iceGatherer,
iceTransport: iceTransport,
dtlsTransport: dtlsTransport
};
};
// Start the RTP Sender and Receiver for a transceiver.
window.RTCPeerConnection.prototype._transceive = function(transceiver,
send, recv) {
var params = this._getCommonCapabilities(transceiver.localCapabilities,
transceiver.remoteCapabilities);
if (send && transceiver.rtpSender) {
params.encodings = transceiver.sendEncodingParameters;
params.rtcp = {
cname: SDPUtils.localCName
};
if (transceiver.recvEncodingParameters.length) {
params.rtcp.ssrc = transceiver.recvEncodingParameters[0].ssrc;
}
transceiver.rtpSender.send(params);
}
if (recv && transceiver.rtpReceiver) {
// remove RTX field in Edge 14942
if (transceiver.kind === 'video'
&& transceiver.recvEncodingParameters) {
transceiver.recvEncodingParameters.forEach(function(p) {
delete p.rtx;
});
}
params.encodings = transceiver.recvEncodingParameters;
params.rtcp = {
cname: transceiver.cname
};
if (transceiver.sendEncodingParameters.length) {
params.rtcp.ssrc = transceiver.sendEncodingParameters[0].ssrc;
}
transceiver.rtpReceiver.receive(params);
}
};
window.RTCPeerConnection.prototype.setLocalDescription =
function(description) {
var self = this;
var sections;
var sessionpart;
if (description.type === 'offer') {
// FIXME: What was the purpose of this empty if statement?
// if (!this._pendingOffer) {
// } else {
if (this._pendingOffer) {
// VERY limited support for SDP munging. Limited to:
// * changing the order of codecs
sections = SDPUtils.splitSections(description.sdp);
sessionpart = sections.shift();
sections.forEach(function(mediaSection, sdpMLineIndex) {
var caps = SDPUtils.parseRtpParameters(mediaSection);
self._pendingOffer[sdpMLineIndex].localCapabilities = caps;
});
this.transceivers = this._pendingOffer;
delete this._pendingOffer;
}
} else if (description.type === 'answer') {
sections = SDPUtils.splitSections(self.remoteDescription.sdp);
sessionpart = sections.shift();
var isIceLite = SDPUtils.matchPrefix(sessionpart,
'a=ice-lite').length > 0;
sections.forEach(function(mediaSection, sdpMLineIndex) {
var transceiver = self.transceivers[sdpMLineIndex];
var iceGatherer = transceiver.iceGatherer;
var iceTransport = transceiver.iceTransport;
var dtlsTransport = transceiver.dtlsTransport;
var localCapabilities = transceiver.localCapabilities;
var remoteCapabilities = transceiver.remoteCapabilities;
var rejected = mediaSection.split('\n', 1)[0]
.split(' ', 2)[1] === '0';
if (!rejected && !transceiver.isDatachannel) {
var remoteIceParameters = SDPUtils.getIceParameters(
mediaSection, sessionpart);
if (isIceLite) {
var cands = SDPUtils.matchPrefix(mediaSection, 'a=candidate:')
.map(function(cand) {
return SDPUtils.parseCandidate(cand);
})
.filter(function(cand) {
return cand.component === '1';
});
// ice-lite only includes host candidates in the SDP so we can
// use setRemoteCandidates (which implies an
// RTCIceCandidateComplete)
if (cands.length) {
iceTransport.setRemoteCandidates(cands);
}
}
var remoteDtlsParameters = SDPUtils.getDtlsParameters(
mediaSection, sessionpart);
if (isIceLite) {
remoteDtlsParameters.role = 'server';
}
if (!self.usingBundle || sdpMLineIndex === 0) {
iceTransport.start(iceGatherer, remoteIceParameters,
isIceLite ? 'controlling' : 'controlled');
dtlsTransport.start(remoteDtlsParameters);
}
// Calculate intersection of capabilities.
var params = self._getCommonCapabilities(localCapabilities,
remoteCapabilities);
// Start the RTCRtpSender. The RTCRtpReceiver for this
// transceiver has already been started in setRemoteDescription.
self._transceive(transceiver,
params.codecs.length > 0,
false);
}
});
}
this.localDescription = {
type: description.type,
sdp: description.sdp
};
switch (description.type) {
case 'offer':
this._updateSignalingState('have-local-offer');
break;
case 'answer':
this._updateSignalingState('stable');
break;
default:
throw new TypeError('unsupported type "' + description.type +
'"');
}
// If a success callback was provided, emit ICE candidates after it
// has been executed. Otherwise, emit callback after the Promise is
// resolved.
var hasCallback = arguments.length > 1 &&
typeof arguments[1] === 'function';
if (hasCallback) {
var cb = arguments[1];
window.setTimeout(function() {
cb();
if (self.iceGatheringState === 'new') {
self.iceGatheringState = 'gathering';
}
self._emitBufferedCandidates();
}, 0);
}
var p = Promise.resolve();
p.then(function() {
if (!hasCallback) {
if (self.iceGatheringState === 'new') {
self.iceGatheringState = 'gathering';
}
// Usually candidates will be emitted earlier.
window.setTimeout(self._emitBufferedCandidates.bind(self), 500);
}
});
return p;
};
window.RTCPeerConnection.prototype.setRemoteDescription =
function(description) {
var self = this;
var stream = new MediaStream();
var receiverList = [];
var sections = SDPUtils.splitSections(description.sdp);
var sessionpart = sections.shift();
var isIceLite = SDPUtils.matchPrefix(sessionpart,
'a=ice-lite').length > 0;
this.usingBundle = SDPUtils.matchPrefix(sessionpart,
'a=group:BUNDLE ').length > 0;
sections.forEach(function(mediaSection, sdpMLineIndex) {
var lines = SDPUtils.splitLines(mediaSection);
var mline = lines[0].substr(2).split(' ');
var kind = mline[0];
var rejected = mline[1] === '0';
var direction = SDPUtils.getDirection(mediaSection, sessionpart);
var mid = SDPUtils.matchPrefix(mediaSection, 'a=mid:');
if (mid.length) {
mid = mid[0].substr(6);
} else {
mid = SDPUtils.generateIdentifier();
}
// Reject datachannels which are not implemented yet.
if (kind === 'application' && mline[2] === 'DTLS/SCTP') {
self.transceivers[sdpMLineIndex] = {
mid: mid,
isDatachannel: true
};
return;
}
var transceiver;
var iceGatherer;
var iceTransport;
var dtlsTransport;
var rtpSender;
var rtpReceiver;
var sendEncodingParameters;
var recvEncodingParameters;
var localCapabilities;
var track;
// FIXME: ensure the mediaSection has rtcp-mux set.
var remoteCapabilities = SDPUtils.parseRtpParameters(mediaSection);
var remoteIceParameters;
var remoteDtlsParameters;
if (!rejected) {
remoteIceParameters = SDPUtils.getIceParameters(mediaSection,
sessionpart);
remoteDtlsParameters = SDPUtils.getDtlsParameters(mediaSection,
sessionpart);
remoteDtlsParameters.role = 'client';
}
recvEncodingParameters =
SDPUtils.parseRtpEncodingParameters(mediaSection);
var cname;
// Gets the first SSRC. Note that with RTX there might be multiple
// SSRCs.
var remoteSsrc = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')
.map(function(line) {
return SDPUtils.parseSsrcMedia(line);
})
.filter(function(obj) {
return obj.attribute === 'cname';
})[0];
if (remoteSsrc) {
cname = remoteSsrc.value;
}
var isComplete = SDPUtils.matchPrefix(mediaSection,
'a=end-of-candidates', sessionpart).length > 0;
var cands = SDPUtils.matchPrefix(mediaSection, 'a=candidate:')
.map(function(cand) {
return SDPUtils.parseCandidate(cand);
})
.filter(function(cand) {
return cand.component === '1';
});
if (description.type === 'offer' && !rejected) {
var transports = self.usingBundle && sdpMLineIndex > 0 ? {
iceGatherer: self.transceivers[0].iceGatherer,
iceTransport: self.transceivers[0].iceTransport,
dtlsTransport: self.transceivers[0].dtlsTransport
} : self._createIceAndDtlsTransports(mid, sdpMLineIndex);
if (isComplete) {
transports.iceTransport.setRemoteCandidates(cands);
}
localCapabilities = RTCRtpReceiver.getCapabilities(kind);
// filter RTX until additional stuff needed for RTX is implemented
// in adapter.js
localCapabilities.codecs = localCapabilities.codecs.filter(
function(codec) {
return codec.name !== 'rtx';
});
sendEncodingParameters = [{
ssrc: (2 * sdpMLineIndex + 2) * 1001
}];
rtpReceiver = new RTCRtpReceiver(transports.dtlsTransport, kind);
track = rtpReceiver.track;
receiverList.push([track, rtpReceiver]);
// FIXME: not correct when there are multiple streams but that is
// not currently supported in this shim.
stream.addTrack(track);
// FIXME: look at direction.
if (self.localStreams.length > 0 &&
self.localStreams[0].getTracks().length >= sdpMLineIndex) {
var localTrack;
if (kind === 'audio') {
localTrack = self.localStreams[0].getAudioTracks()[0];
} else if (kind === 'video') {
localTrack = self.localStreams[0].getVideoTracks()[0];
}
if (localTrack) {
rtpSender = new RTCRtpSender(localTrack,
transports.dtlsTransport);
}
}
self.transceivers[sdpMLineIndex] = {
iceGatherer: transports.iceGatherer,
iceTransport: transports.iceTransport,
dtlsTransport: transports.dtlsTransport,
localCapabilities: localCapabilities,
remoteCapabilities: remoteCapabilities,
rtpSender: rtpSender,
rtpReceiver: rtpReceiver,
kind: kind,
mid: mid,
cname: cname,
sendEncodingParameters: sendEncodingParameters,
recvEncodingParameters: recvEncodingParameters
};
// Start the RTCRtpReceiver now. The RTPSender is started in
// setLocalDescription.
self._transceive(self.transceivers[sdpMLineIndex],
false,
direction === 'sendrecv' || direction === 'sendonly');
} else if (description.type === 'answer' && !rejected) {
transceiver = self.transceivers[sdpMLineIndex];
iceGatherer = transceiver.iceGatherer;
iceTransport = transceiver.iceTransport;
dtlsTransport = transceiver.dtlsTransport;
rtpSender = transceiver.rtpSender;
rtpReceiver = transceiver.rtpReceiver;
sendEncodingParameters = transceiver.sendEncodingParameters;
localCapabilities = transceiver.localCapabilities;
self.transceivers[sdpMLineIndex].recvEncodingParameters =
recvEncodingParameters;
self.transceivers[sdpMLineIndex].remoteCapabilities =
remoteCapabilities;
self.transceivers[sdpMLineIndex].cname = cname;
if ((isIceLite || isComplete) && cands.length) {
iceTransport.setRemoteCandidates(cands);
}
if (!self.usingBundle || sdpMLineIndex === 0) {
iceTransport.start(iceGatherer, remoteIceParameters,
'controlling');
dtlsTransport.start(remoteDtlsParameters);
}
self._transceive(transceiver,
direction === 'sendrecv' || direction === 'recvonly',
direction === 'sendrecv' || direction === 'sendonly');
if (rtpReceiver &&
(direction === 'sendrecv' || direction === 'sendonly')) {
track = rtpReceiver.track;
receiverList.push([track, rtpReceiver]);
stream.addTrack(track);
} else {
// FIXME: actually the receiver should be created later.
delete transceiver.rtpReceiver;
}
}
});
this.remoteDescription = {
type: description.type,
sdp: description.sdp
};
switch (description.type) {
case 'offer':
this._updateSignalingState('have-remote-offer');
break;
case 'answer':
this._updateSignalingState('stable');
break;
default:
throw new TypeError('unsupported type "' + description.type +
'"');
}
if (stream.getTracks().length) {
self.remoteStreams.push(stream);
window.setTimeout(function() {
var event = new Event('addstream');
event.stream = stream;
self.dispatchEvent(event);
if (self.onaddstream !== null) {
window.setTimeout(function() {
self.onaddstream(event);
}, 0);
}
receiverList.forEach(function(item) {
var track = item[0];
var receiver = item[1];
var trackEvent = new Event('track');
trackEvent.track = track;
trackEvent.receiver = receiver;
trackEvent.streams = [stream];
self.dispatchEvent(event);
if (self.ontrack !== null) {
window.setTimeout(function() {
self.ontrack(trackEvent);
}, 0);
}
});
}, 0);
}
if (arguments.length > 1 && typeof arguments[1] === 'function') {
window.setTimeout(arguments[1], 0);
}
return Promise.resolve();
};
window.RTCPeerConnection.prototype.close = function() {
this.transceivers.forEach(function(transceiver) {
/* not yet
if (transceiver.iceGatherer) {
transceiver.iceGatherer.close();
}
*/
if (transceiver.iceTransport) {
transceiver.iceTransport.stop();
}
if (transceiver.dtlsTransport) {
transceiver.dtlsTransport.stop();
}
if (transceiver.rtpSender) {
transceiver.rtpSender.stop();
}
if (transceiver.rtpReceiver) {
transceiver.rtpReceiver.stop();
}
});
// FIXME: clean up tracks, local streams, remote streams, etc
this._updateSignalingState('closed');
};
// Update the signaling state.
window.RTCPeerConnection.prototype._updateSignalingState =
function(newState) {
this.signalingState = newState;
var event = new Event('signalingstatechange');
this.dispatchEvent(event);
if (this.onsignalingstatechange !== null) {
this.onsignalingstatechange(event);
}
};
// Determine whether to fire the negotiationneeded event.
window.RTCPeerConnection.prototype._maybeFireNegotiationNeeded =
function() {
// Fire away (for now).
var event = new Event('negotiationneeded');
this.dispatchEvent(event);
if (this.onnegotiationneeded !== null) {
this.onnegotiationneeded(event);
}
};
// Update the connection state.
window.RTCPeerConnection.prototype._updateConnectionState = function() {
var self = this;
var newState;
var states = {
'new': 0,
closed: 0,
connecting: 0,
checking: 0,
connected: 0,
completed: 0,
failed: 0
};
this.transceivers.forEach(function(transceiver) {
states[transceiver.iceTransport.state]++;
states[transceiver.dtlsTransport.state]++;
});
// ICETransport.completed and connected are the same for this purpose.
states.connected += states.completed;
newState = 'new';
if (states.failed > 0) {
newState = 'failed';
} else if (states.connecting > 0 || states.checking > 0) {
newState = 'connecting';
} else if (states.disconnected > 0) {
newState = 'disconnected';
} else if (states.new > 0) {
newState = 'new';
} else if (states.connected > 0 || states.completed > 0) {
newState = 'connected';
}
if (newState !== self.iceConnectionState) {
self.iceConnectionState = newState;
var event = new Event('iceconnectionstatechange');
this.dispatchEvent(event);
if (this.oniceconnectionstatechange !== null) {
this.oniceconnectionstatechange(event);
}
}
};
window.RTCPeerConnection.prototype.createOffer = function() {
var self = this;
if (this._pendingOffer) {
throw new Error('createOffer called while there is a pending offer.');
}
var offerOptions;
if (arguments.length === 1 && typeof arguments[0] !== 'function') {
offerOptions = arguments[0];
} else if (arguments.length === 3) {
offerOptions = arguments[2];
}
var tracks = [];
var numAudioTracks = 0;
var numVideoTracks = 0;
// Default to sendrecv.
if (this.localStreams.length) {
numAudioTracks = this.localStreams[0].getAudioTracks().length;
numVideoTracks = this.localStreams[0].getVideoTracks().length;
}
// Determine number of audio and video tracks we need to send/recv.
if (offerOptions) {
// Reject Chrome legacy constraints.
if (offerOptions.mandatory || offerOptions.optional) {
throw new TypeError(
'Legacy mandatory/optional constraints not supported.');
}
if (offerOptions.offerToReceiveAudio !== undefined) {
numAudioTracks = offerOptions.offerToReceiveAudio;
}
if (offerOptions.offerToReceiveVideo !== undefined) {
numVideoTracks = offerOptions.offerToReceiveVideo;
}
}
if (this.localStreams.length) {
// Push local streams.
this.localStreams[0].getTracks().forEach(function(track) {
tracks.push({
kind: track.kind,
track: track,
wantReceive: track.kind === 'audio' ?
numAudioTracks > 0 : numVideoTracks > 0
});
if (track.kind === 'audio') {
numAudioTracks--;
} else if (track.kind === 'video') {
numVideoTracks--;
}
});
}
// Create M-lines for recvonly streams.
while (numAudioTracks > 0 || numVideoTracks > 0) {
if (numAudioTracks > 0) {
tracks.push({
kind: 'audio',
wantReceive: true
});
numAudioTracks--;
}
if (numVideoTracks > 0) {
tracks.push({
kind: 'video',
wantReceive: true
});
numVideoTracks--;
}
}
var sdp = SDPUtils.writeSessionBoilerplate();
var transceivers = [];
tracks.forEach(function(mline, sdpMLineIndex) {
// For each track, create an ice gatherer, ice transport,
// dtls transport, potentially rtpsender and rtpreceiver.
var track = mline.track;
var kind = mline.kind;
var mid = SDPUtils.generateIdentifier();
var transports = self.usingBundle && sdpMLineIndex > 0 ? {
iceGatherer: transceivers[0].iceGatherer,
iceTransport: transceivers[0].iceTransport,
dtlsTransport: transceivers[0].dtlsTransport
} : self._createIceAndDtlsTransports(mid, sdpMLineIndex);
var localCapabilities = RTCRtpSender.getCapabilities(kind);
// filter RTX until additional stuff needed for RTX is implemented
// in adapter.js
localCapabilities.codecs = localCapabilities.codecs.filter(
function(codec) {
return codec.name !== 'rtx';
});
localCapabilities.codecs.forEach(function(codec) {
// work around https://bugs.chromium.org/p/webrtc/issues/detail?id=6552
// by adding level-asymmetry-allowed=1
if (codec.name === 'H264' &&
codec.parameters['level-asymmetry-allowed'] === undefined) {
codec.parameters['level-asymmetry-allowed'] = '1';
}
});
var rtpSender;
var rtpReceiver;
// generate an ssrc now, to be used later in rtpSender.send
var sendEncodingParameters = [{
ssrc: (2 * sdpMLineIndex + 1) * 1001
}];
if (track) {
rtpSender = new RTCRtpSender(track, transports.dtlsTransport);
}
if (mline.wantReceive) {
rtpReceiver = new RTCRtpReceiver(transports.dtlsTransport, kind);
}
transceivers[sdpMLineIndex] = {
iceGatherer: transports.iceGatherer,
iceTransport: transports.iceTransport,
dtlsTransport: transports.dtlsTransport,
localCapabilities: localCapabilities,
remoteCapabilities: null,
rtpSender: rtpSender,
rtpReceiver: rtpReceiver,
kind: kind,
mid: mid,
sendEncodingParameters: sendEncodingParameters,
recvEncodingParameters: null
};
});
if (this.usingBundle) {
sdp += 'a=group:BUNDLE ' + transceivers.map(function(t) {
return t.mid;
}).join(' ') + '\r\n';
}
tracks.forEach(function(mline, sdpMLineIndex) {
var transceiver = transceivers[sdpMLineIndex];
sdp += SDPUtils.writeMediaSection(transceiver,
transceiver.localCapabilities, 'offer', self.localStreams[0]);
});
this._pendingOffer = transceivers;
var desc = new RTCSessionDescription({
type: 'offer',
sdp: sdp
});
if (arguments.length && typeof arguments[0] === 'function') {
window.setTimeout(arguments[0], 0, desc);
}
return Promise.resolve(desc);
};
window.RTCPeerConnection.prototype.createAnswer = function() {
var self = this;
var sdp = SDPUtils.writeSessionBoilerplate();
if (this.usingBundle) {
sdp += 'a=group:BUNDLE ' + this.transceivers.map(function(t) {
return t.mid;
}).join(' ') + '\r\n';
}
this.transceivers.forEach(function(transceiver) {
if (transceiver.isDatachannel) {
sdp += 'm=application 0 DTLS/SCTP 5000\r\n' +
'c=IN IP4 0.0.0.0\r\n' +
'a=mid:' + transceiver.mid + '\r\n';
return;
}
// Calculate intersection of capabilities.
var commonCapabilities = self._getCommonCapabilities(
transceiver.localCapabilities,
transceiver.remoteCapabilities);
sdp += SDPUtils.writeMediaSection(transceiver, commonCapabilities,
'answer', self.localStreams[0]);
});
var desc = new RTCSessionDescription({
type: 'answer',
sdp: sdp
});
if (arguments.length && typeof arguments[0] === 'function') {
window.setTimeout(arguments[0], 0, desc);
}
return Promise.resolve(desc);
};
window.RTCPeerConnection.prototype.addIceCandidate = function(candidate) {
if (!candidate) {
this.transceivers.forEach(function(transceiver) {
transceiver.iceTransport.addRemoteCandidate({});
});
} else {
var mLineIndex = candidate.sdpMLineIndex;
if (candidate.sdpMid) {
for (var i = 0; i < this.transceivers.length; i++) {
if (this.transceivers[i].mid === candidate.sdpMid) {
mLineIndex = i;
break;
}
}
}
var transceiver = this.transceivers[mLineIndex];
if (transceiver) {
var cand = Object.keys(candidate.candidate).length > 0 ?
SDPUtils.parseCandidate(candidate.candidate) : {};
// Ignore Chrome's invalid candidates since Edge does not like them.
if (cand.protocol === 'tcp' && (cand.port === 0 || cand.port === 9)) {
return;
}
// Ignore RTCP candidates, we assume RTCP-MUX.
if (cand.component !== '1') {
return;
}
// A dirty hack to make samples work.
if (cand.type === 'endOfCandidates') {
cand = {};
}
transceiver.iceTransport.addRemoteCandidate(cand);
// update the remoteDescription.
var sections = SDPUtils.splitSections(this.remoteDescription.sdp);
sections[mLineIndex + 1] += (cand.type ? candidate.candidate.trim()
: 'a=end-of-candidates') + '\r\n';
this.remoteDescription.sdp = sections.join('');
}
}
if (arguments.length > 1 && typeof arguments[1] === 'function') {
window.setTimeout(arguments[1], 0);
}
return Promise.resolve();
};
window.RTCPeerConnection.prototype.getStats = function() {
var promises = [];
this.transceivers.forEach(function(transceiver) {
['rtpSender', 'rtpReceiver', 'iceGatherer', 'iceTransport',
'dtlsTransport'].forEach(function(method) {
if (transceiver[method]) {
promises.push(transceiver[method].getStats());
}
});
});
var cb = arguments.length > 1 && typeof arguments[1] === 'function' &&
arguments[1];
return new Promise(function(resolve) {
// shim getStats with maplike support
var results = new Map();
Promise.all(promises).then(function(res) {
res.forEach(function(result) {
Object.keys(result).forEach(function(id) {
results.set(id, result[id]);
results[id] = result[id];
});
});
if (cb) {
window.setTimeout(cb, 0, results);
}
resolve(results);
});
});
};
}
};
// Expose public methods.
module.exports = {
shimPeerConnection: edgeShim.shimPeerConnection,
shimGetUserMedia: require('./getusermedia')
};
},{"../utils":49,"./getusermedia":45,"sdp":40}],45:[function(require,module,exports){
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
'use strict';
// Expose public methods.
module.exports = function() {
var shimError_ = function(e) {
return {
name: {PermissionDeniedError: 'NotAllowedError'}[e.name] || e.name,
message: e.message,
constraint: e.constraint,
toString: function() {
return this.name;
}
};
};
// getUserMedia error shim.
var origGetUserMedia = navigator.mediaDevices.getUserMedia.
bind(navigator.mediaDevices);
navigator.mediaDevices.getUserMedia = function(c) {
return origGetUserMedia(c).catch(function(e) {
return Promise.reject(shimError_(e));
});
};
};
},{}],46:[function(require,module,exports){
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
'use strict';
var browserDetails = require('../utils').browserDetails;
var firefoxShim = {
shimOnTrack: function() {
if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in
window.RTCPeerConnection.prototype)) {
Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', {
get: function() {
return this._ontrack;
},
set: function(f) {
if (this._ontrack) {
this.removeEventListener('track', this._ontrack);
this.removeEventListener('addstream', this._ontrackpoly);
}
this.addEventListener('track', this._ontrack = f);
this.addEventListener('addstream', this._ontrackpoly = function(e) {
e.stream.getTracks().forEach(function(track) {
var event = new Event('track');
event.track = track;
event.receiver = {track: track};
event.streams = [e.stream];
this.dispatchEvent(event);
}.bind(this));
}.bind(this));
}
});
}
},
shimSourceObject: function() {
// Firefox has supported mozSrcObject since FF22, unprefixed in 42.
if (typeof window === 'object') {
if (window.HTMLMediaElement &&
!('srcObject' in window.HTMLMediaElement.prototype)) {
// Shim the srcObject property, once, when HTMLMediaElement is found.
Object.defineProperty(window.HTMLMediaElement.prototype, 'srcObject', {
get: function() {
return this.mozSrcObject;
},
set: function(stream) {
this.mozSrcObject = stream;
}
});
}
}
},
shimPeerConnection: function() {
if (typeof window !== 'object' || !(window.RTCPeerConnection ||
window.mozRTCPeerConnection)) {
return; // probably media.peerconnection.enabled=false in about:config
}
// The RTCPeerConnection object.
if (!window.RTCPeerConnection) {
window.RTCPeerConnection = function(pcConfig, pcConstraints) {
if (browserDetails.version < 38) {
// .urls is not supported in FF < 38.
// create RTCIceServers with a single url.
if (pcConfig && pcConfig.iceServers) {
var newIceServers = [];
for (var i = 0; i < pcConfig.iceServers.length; i++) {
var server = pcConfig.iceServers[i];
if (server.hasOwnProperty('urls')) {
for (var j = 0; j < server.urls.length; j++) {
var newServer = {
url: server.urls[j]
};
if (server.urls[j].indexOf('turn') === 0) {
newServer.username = server.username;
newServer.credential = server.credential;
}
newIceServers.push(newServer);
}
} else {
newIceServers.push(pcConfig.iceServers[i]);
}
}
pcConfig.iceServers = newIceServers;
}
}
return new mozRTCPeerConnection(pcConfig, pcConstraints);
};
window.RTCPeerConnection.prototype = mozRTCPeerConnection.prototype;
// wrap static methods. Currently just generateCertificate.
if (mozRTCPeerConnection.generateCertificate) {
Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
get: function() {
return mozRTCPeerConnection.generateCertificate;
}
});
}
window.RTCSessionDescription = mozRTCSessionDescription;
window.RTCIceCandidate = mozRTCIceCandidate;
}
// shim away need for obsolete RTCIceCandidate/RTCSessionDescription.
['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
.forEach(function(method) {
var nativeMethod = RTCPeerConnection.prototype[method];
RTCPeerConnection.prototype[method] = function() {
arguments[0] = new ((method === 'addIceCandidate') ?
RTCIceCandidate : RTCSessionDescription)(arguments[0]);
return nativeMethod.apply(this, arguments);
};
});
// support for addIceCandidate(null or undefined)
var nativeAddIceCandidate =
RTCPeerConnection.prototype.addIceCandidate;
RTCPeerConnection.prototype.addIceCandidate = function() {
if (!arguments[0]) {
if (arguments[1]) {
arguments[1].apply(null);
}
return Promise.resolve();
}
return nativeAddIceCandidate.apply(this, arguments);
};
if (browserDetails.version < 48) {
// shim getStats with maplike support
var makeMapStats = function(stats) {
var map = new Map();
Object.keys(stats).forEach(function(key) {
map.set(key, stats[key]);
map[key] = stats[key];
});
return map;
};
var nativeGetStats = RTCPeerConnection.prototype.getStats;
RTCPeerConnection.prototype.getStats = function(selector, onSucc, onErr) {
return nativeGetStats.apply(this, [selector || null])
.then(function(stats) {
return makeMapStats(stats);
})
.then(onSucc, onErr);
};
}
}
};
// Expose public methods.
module.exports = {
shimOnTrack: firefoxShim.shimOnTrack,
shimSourceObject: firefoxShim.shimSourceObject,
shimPeerConnection: firefoxShim.shimPeerConnection,
shimGetUserMedia: require('./getusermedia')
};
},{"../utils":49,"./getusermedia":47}],47:[function(require,module,exports){
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
'use strict';
var logging = require('../utils').log;
var browserDetails = require('../utils').browserDetails;
// Expose public methods.
module.exports = function() {
var shimError_ = function(e) {
return {
name: {
SecurityError: 'NotAllowedError',
PermissionDeniedError: 'NotAllowedError'
}[e.name] || e.name,
message: {
'The operation is insecure.': 'The request is not allowed by the ' +
'user agent or the platform in the current context.'
}[e.message] || e.message,
constraint: e.constraint,
toString: function() {
return this.name + (this.message && ': ') + this.message;
}
};
};
// getUserMedia constraints shim.
var getUserMedia_ = function(constraints, onSuccess, onError) {
var constraintsToFF37_ = function(c) {
if (typeof c !== 'object' || c.require) {
return c;
}
var require = [];
Object.keys(c).forEach(function(key) {
if (key === 'require' || key === 'advanced' || key === 'mediaSource') {
return;
}
var r = c[key] = (typeof c[key] === 'object') ?
c[key] : {ideal: c[key]};
if (r.min !== undefined ||
r.max !== undefined || r.exact !== undefined) {
require.push(key);
}
if (r.exact !== undefined) {
if (typeof r.exact === 'number') {
r. min = r.max = r.exact;
} else {
c[key] = r.exact;
}
delete r.exact;
}
if (r.ideal !== undefined) {
c.advanced = c.advanced || [];
var oc = {};
if (typeof r.ideal === 'number') {
oc[key] = {min: r.ideal, max: r.ideal};
} else {
oc[key] = r.ideal;
}
c.advanced.push(oc);
delete r.ideal;
if (!Object.keys(r).length) {
delete c[key];
}
}
});
if (require.length) {
c.require = require;
}
return c;
};
constraints = JSON.parse(JSON.stringify(constraints));
if (browserDetails.version < 38) {
logging('spec: ' + JSON.stringify(constraints));
if (constraints.audio) {
constraints.audio = constraintsToFF37_(constraints.audio);
}
if (constraints.video) {
constraints.video = constraintsToFF37_(constraints.video);
}
logging('ff37: ' + JSON.stringify(constraints));
}
return navigator.mozGetUserMedia(constraints, onSuccess, function(e) {
onError(shimError_(e));
});
};
// Returns the result of getUserMedia as a Promise.
var getUserMediaPromise_ = function(constraints) {
return new Promise(function(resolve, reject) {
getUserMedia_(constraints, resolve, reject);
});
};
// Shim for mediaDevices on older versions.
if (!navigator.mediaDevices) {
navigator.mediaDevices = {getUserMedia: getUserMediaPromise_,
addEventListener: function() { },
removeEventListener: function() { }
};
}
navigator.mediaDevices.enumerateDevices =
navigator.mediaDevices.enumerateDevices || function() {
return new Promise(function(resolve) {
var infos = [
{kind: 'audioinput', deviceId: 'default', label: '', groupId: ''},
{kind: 'videoinput', deviceId: 'default', label: '', groupId: ''}
];
resolve(infos);
});
};
if (browserDetails.version < 41) {
// Work around http://bugzil.la/1169665
var orgEnumerateDevices =
navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices);
navigator.mediaDevices.enumerateDevices = function() {
return orgEnumerateDevices().then(undefined, function(e) {
if (e.name === 'NotFoundError') {
return [];
}
throw e;
});
};
}
if (browserDetails.version < 49) {
var origGetUserMedia = navigator.mediaDevices.getUserMedia.
bind(navigator.mediaDevices);
navigator.mediaDevices.getUserMedia = function(c) {
return origGetUserMedia(c).then(function(stream) {
// Work around https://bugzil.la/802326
if (c.audio && !stream.getAudioTracks().length ||
c.video && !stream.getVideoTracks().length) {
stream.getTracks().forEach(function(track) {
track.stop();
});
throw new DOMException('The object can not be found here.',
'NotFoundError');
}
return stream;
}, function(e) {
return Promise.reject(shimError_(e));
});
};
}
navigator.getUserMedia = function(constraints, onSuccess, onError) {
if (browserDetails.version < 44) {
return getUserMedia_(constraints, onSuccess, onError);
}
// Replace Firefox 44+'s deprecation warning with unprefixed version.
console.warn('navigator.getUserMedia has been replaced by ' +
'navigator.mediaDevices.getUserMedia');
navigator.mediaDevices.getUserMedia(constraints).then(onSuccess, onError);
};
};
},{"../utils":49}],48:[function(require,module,exports){
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
'use strict';
var safariShim = {
// TODO: DrAlex, should be here, double check against LayoutTests
// shimOnTrack: function() { },
// TODO: once the back-end for the mac port is done, add.
// TODO: check for webkitGTK+
// shimPeerConnection: function() { },
shimGetUserMedia: function() {
navigator.getUserMedia = navigator.webkitGetUserMedia;
}
};
// Expose public methods.
module.exports = {
shimGetUserMedia: safariShim.shimGetUserMedia
// TODO
// shimOnTrack: safariShim.shimOnTrack,
// shimPeerConnection: safariShim.shimPeerConnection
};
},{}],49:[function(require,module,exports){
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
'use strict';
var logDisabled_ = true;
// Utility methods.
var utils = {
disableLog: function(bool) {
if (typeof bool !== 'boolean') {
return new Error('Argument type: ' + typeof bool +
'. Please use a boolean.');
}
logDisabled_ = bool;
return (bool) ? 'adapter.js logging disabled' :
'adapter.js logging enabled';
},
log: function() {
if (typeof window === 'object') {
if (logDisabled_) {
return;
}
if (typeof console !== 'undefined' && typeof console.log === 'function') {
console.log.apply(console, arguments);
}
}
},
/**
* Extract browser version out of the provided user agent string.
*
* @param {!string} uastring userAgent string.
* @param {!string} expr Regular expression used as match criteria.
* @param {!number} pos position in the version string to be returned.
* @return {!number} browser version.
*/
extractVersion: function(uastring, expr, pos) {
var match = uastring.match(expr);
return match && match.length >= pos && parseInt(match[pos], 10);
},
/**
* Browser detector.
*
* @return {object} result containing browser and version
* properties.
*/
detectBrowser: function() {
// Returned result object.
var result = {};
result.browser = null;
result.version = null;
// Fail early if it's not a browser
if (typeof window === 'undefined' || !window.navigator) {
result.browser = 'Not a browser.';
return result;
}
// Firefox.
if (navigator.mozGetUserMedia) {
result.browser = 'firefox';
result.version = this.extractVersion(navigator.userAgent,
/Firefox\/([0-9]+)\./, 1);
// all webkit-based browsers
} else if (navigator.webkitGetUserMedia) {
// Chrome, Chromium, Webview, Opera, all use the chrome shim for now
if (window.webkitRTCPeerConnection) {
result.browser = 'chrome';
result.version = this.extractVersion(navigator.userAgent,
/Chrom(e|ium)\/([0-9]+)\./, 2);
// Safari or unknown webkit-based
// for the time being Safari has support for MediaStreams but not webRTC
} else {
// Safari UA substrings of interest for reference:
// - webkit version: AppleWebKit/602.1.25 (also used in Op,Cr)
// - safari UI version: Version/9.0.3 (unique to Safari)
// - safari UI webkit version: Safari/601.4.4 (also used in Op,Cr)
//
// if the webkit version and safari UI webkit versions are equals,
// ... this is a stable version.
//
// only the internal webkit version is important today to know if
// media streams are supported
//
if (navigator.userAgent.match(/Version\/(\d+).(\d+)/)) {
result.browser = 'safari';
result.version = this.extractVersion(navigator.userAgent,
/AppleWebKit\/([0-9]+)\./, 1);
// unknown webkit-based browser
} else {
result.browser = 'Unsupported webkit-based browser ' +
'with GUM support but no WebRTC support.';
return result;
}
}
// Edge.
} else if (navigator.mediaDevices &&
navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)) {
result.browser = 'edge';
result.version = this.extractVersion(navigator.userAgent,
/Edge\/(\d+).(\d+)$/, 2);
// Default fallthrough: not supported.
} else {
result.browser = 'Not a supported browser.';
return result;
}
return result;
}
};
// Export.
module.exports = {
log: utils.log,
disableLog: utils.disableLog,
browserDetails: utils.detectBrowser(),
extractVersion: utils.extractVersion
};
},{}],50:[function(require,module,exports){
module.exports={
"name": "jssip",
"title": "JsSIP",
"description": "the Javascript SIP library",
"version": "3.0.2",
"homepage": "http://jssip.net",
"author": "José Luis Millán <jmillan@aliax.net> (https://github.com/jmillan)",
"contributors": [
"Iñaki Baz Castillo <ibc@aliax.net> (https://github.com/ibc)",
"Saúl Ibarra Corretgé <saghul@gmail.com> (https://github.com/saghul)"
],
"main": "lib/JsSIP.js",
"keywords": [
"sip",
"websocket",
"webrtc",
"node",
"browser",
"library"
],
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/versatica/JsSIP.git"
},
"bugs": {
"url": "https://github.com/versatica/JsSIP/issues"
},
"dependencies": {
"debug": "^2.3.3",
"sdp-transform": "^1.6.2",
"webrtc-adapter": "^2.0.8"
},
"devDependencies": {
"browserify": "^13.1.1",
"gulp": "git+https://github.com/gulpjs/gulp.git#4.0",
"gulp-expect-file": "0.0.7",
"gulp-header": "1.8.8",
"gulp-jshint": "^2.0.4",
"gulp-nodeunit-runner": "^0.2.2",
"gulp-rename": "^1.2.2",
"gulp-uglify": "^2.0.0",
"gulp-util": "^3.0.7",
"jshint": "^2.9.4",
"jshint-stylish": "^2.2.1",
"pegjs": "0.7.0",
"vinyl-buffer": "^1.0.0",
"vinyl-source-stream": "^1.1.0"
},
"scripts": {
"test": "gulp test"
}
}
},{}]},{},[7])(7)
}); |
var five = require("../lib/johnny-five.js");
var board = new five.Board();
board.on("ready", function() {
var temperature = new five.Temperature({
controller: "MPL115A2"
});
temperature.on("data", function() {
console.log("temperature");
console.log(" celsius : ", this.celsius);
console.log(" fahrenheit : ", this.fahrenheit);
console.log(" kelvin : ", this.kelvin);
console.log("--------------------------------------");
});
});
// @markdown
// - [MPL115A2 - I2C Barometric Pressure/Temperature Sensor](https://www.adafruit.com/product/992)
// @markdown
|
// array allocator -*- C++ -*-
// Copyright (C) 2004-2015 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
/** @file ext/array_allocator.h
* This file is a GNU extension to the Standard C++ Library.
*/
#ifndef _ARRAY_ALLOCATOR_H
#define _ARRAY_ALLOCATOR_H 1
#include <bits/c++config.h>
#include <new>
#include <bits/functexcept.h>
#include <tr1/array>
#include <bits/move.h>
#if __cplusplus >= 201103L
#include <type_traits>
#endif
// Suppress deprecated warning for this file.
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
namespace __gnu_cxx _GLIBCXX_VISIBILITY(default)
{
_GLIBCXX_BEGIN_NAMESPACE_VERSION
using std::size_t;
using std::ptrdiff_t;
/// Base class.
template<typename _Tp>
class array_allocator_base
{
public:
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef _Tp* pointer;
typedef const _Tp* const_pointer;
typedef _Tp& reference;
typedef const _Tp& const_reference;
typedef _Tp value_type;
pointer
address(reference __x) const _GLIBCXX_NOEXCEPT
{ return std::__addressof(__x); }
const_pointer
address(const_reference __x) const _GLIBCXX_NOEXCEPT
{ return std::__addressof(__x); }
void
deallocate(pointer, size_type)
{
// Does nothing.
}
size_type
max_size() const _GLIBCXX_USE_NOEXCEPT
{ return size_t(-1) / sizeof(_Tp); }
#if __cplusplus >= 201103L
template<typename _Up, typename... _Args>
void
construct(_Up* __p, _Args&&... __args)
{ ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }
template<typename _Up>
void
destroy(_Up* __p) { __p->~_Up(); }
#else
// _GLIBCXX_RESOLVE_LIB_DEFECTS
// 402. wrong new expression in [some_] allocator::construct
void
construct(pointer __p, const _Tp& __val)
{ ::new((void *)__p) value_type(__val); }
void
destroy(pointer __p) { __p->~_Tp(); }
#endif
} _GLIBCXX_DEPRECATED;
/**
* @brief An allocator that uses previously allocated memory.
* This memory can be externally, globally, or otherwise allocated.
* @ingroup allocators
*/
template<typename _Tp, typename _Array = std::tr1::array<_Tp, 1> >
class array_allocator : public array_allocator_base<_Tp>
{
public:
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef _Tp* pointer;
typedef const _Tp* const_pointer;
typedef _Tp& reference;
typedef const _Tp& const_reference;
typedef _Tp value_type;
typedef _Array array_type;
#if __cplusplus >= 201103L
// _GLIBCXX_RESOLVE_LIB_DEFECTS
// 2103. std::allocator propagate_on_container_move_assignment
typedef std::true_type propagate_on_container_move_assignment;
typedef std::true_type is_always_equal;
#endif
private:
array_type* _M_array;
size_type _M_used;
public:
template<typename _Tp1, typename _Array1 = _Array>
struct rebind
{
typedef array_allocator<_Tp1, _Array1> other _GLIBCXX_DEPRECATED;
} _GLIBCXX_DEPRECATED;
array_allocator(array_type* __array = 0) _GLIBCXX_USE_NOEXCEPT
: _M_array(__array), _M_used(size_type()) { }
array_allocator(const array_allocator& __o) _GLIBCXX_USE_NOEXCEPT
: _M_array(__o._M_array), _M_used(__o._M_used) { }
template<typename _Tp1, typename _Array1>
array_allocator(const array_allocator<_Tp1, _Array1>&)
_GLIBCXX_USE_NOEXCEPT
: _M_array(0), _M_used(size_type()) { }
~array_allocator() _GLIBCXX_USE_NOEXCEPT { }
pointer
allocate(size_type __n, const void* = 0)
{
if (_M_array == 0 || _M_used + __n > _M_array->size())
std::__throw_bad_alloc();
pointer __ret = _M_array->begin() + _M_used;
_M_used += __n;
return __ret;
}
} _GLIBCXX_DEPRECATED;
template<typename _Tp, typename _Array>
inline bool
operator==(const array_allocator<_Tp, _Array>&,
const array_allocator<_Tp, _Array>&)
{ return true; }
template<typename _Tp, typename _Array>
inline bool
operator!=(const array_allocator<_Tp, _Array>&,
const array_allocator<_Tp, _Array>&)
{ return false; }
_GLIBCXX_END_NAMESPACE_VERSION
} // namespace
#pragma GCC diagnostic pop
#endif
|
local combat = createCombatObject()
setCombatParam(combat, COMBAT_PARAM_TYPE, COMBAT_PHYSICALDAMAGE)
setCombatParam(combat, COMBAT_PARAM_EFFECT, CONST_ME_HITAREA)
setCombatParam(combat, COMBAT_PARAM_USECHARGES, 1)
local area = createCombatArea(AREA_WAVE6, AREADIAGONAL_WAVE6)
setCombatArea(combat, area)
function onGetFormulaValues(cid, skill, attack, factor)
local skillTotal, levelTotal = skill * attack, getPlayerLevel(cid) / 5
return -(((skillTotal * 0.04) + 31) + (levelTotal)), -(((skillTotal * 0.08) + 45) + (levelTotal))
end
setCombatCallback(combat, CALLBACK_PARAM_SKILLVALUE, "onGetFormulaValues")
function onCastSpell(cid, var)
return doCombat(cid, combat, var)
end
|
/*
* linux/arch/arm/vfp/vfpmodule.c
*
* Copyright (C) 2004 ARM Limited.
* Written by Deep Blue Solutions Limited.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/types.h>
#include <linux/cpu.h>
#include <linux/cpu_pm.h>
#include <linux/hardirq.h>
#include <linux/kernel.h>
#include <linux/notifier.h>
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/smp.h>
#include <linux/init.h>
#include <linux/uaccess.h>
#include <linux/user.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <asm/cp15.h>
#include <asm/cputype.h>
#include <asm/system_info.h>
#include <asm/thread_notify.h>
#include <asm/vfp.h>
#include "vfpinstr.h"
#include "vfp.h"
/*
* Our undef handlers (in entry.S)
*/
void vfp_testing_entry(void);
void vfp_support_entry(void);
void vfp_null_entry(void);
void (*vfp_vector)(void) = vfp_null_entry;
/*
* Dual-use variable.
* Used in startup: set to non-zero if VFP checks fail
* After startup, holds VFP architecture
*/
unsigned int VFP_arch;
/*
* The pointer to the vfpstate structure of the thread which currently
* owns the context held in the VFP hardware, or NULL if the hardware
* context is invalid.
*
* For UP, this is sufficient to tell which thread owns the VFP context.
* However, for SMP, we also need to check the CPU number stored in the
* saved state too to catch migrations.
*/
union vfp_state *vfp_current_hw_state[NR_CPUS];
/*
* Is 'thread's most up to date state stored in this CPUs hardware?
* Must be called from non-preemptible context.
*/
static bool vfp_state_in_hw(unsigned int cpu, struct thread_info *thread)
{
#ifdef CONFIG_SMP
if (thread->vfpstate.hard.cpu != cpu)
return false;
#endif
return vfp_current_hw_state[cpu] == &thread->vfpstate;
}
/*
* Force a reload of the VFP context from the thread structure. We do
* this by ensuring that access to the VFP hardware is disabled, and
* clear vfp_current_hw_state. Must be called from non-preemptible context.
*/
static void vfp_force_reload(unsigned int cpu, struct thread_info *thread)
{
if (vfp_state_in_hw(cpu, thread)) {
fmxr(FPEXC, fmrx(FPEXC) & ~FPEXC_EN);
vfp_current_hw_state[cpu] = NULL;
}
#ifdef CONFIG_SMP
thread->vfpstate.hard.cpu = NR_CPUS;
vfp_current_hw_state[cpu] = NULL;
#endif
}
/*
* Used for reporting emulation statistics via /proc
*/
static atomic64_t vfp_bounce_count = ATOMIC64_INIT(0);
/*
* Per-thread VFP initialization.
*/
static void vfp_thread_flush(struct thread_info *thread)
{
union vfp_state *vfp = &thread->vfpstate;
unsigned int cpu;
/*
* Disable VFP to ensure we initialize it first. We must ensure
* that the modification of vfp_current_hw_state[] and hardware
* disable are done for the same CPU and without preemption.
*
* Do this first to ensure that preemption won't overwrite our
* state saving should access to the VFP be enabled at this point.
*/
cpu = get_cpu();
if (vfp_current_hw_state[cpu] == vfp)
vfp_current_hw_state[cpu] = NULL;
fmxr(FPEXC, fmrx(FPEXC) & ~FPEXC_EN);
put_cpu();
memset(vfp, 0, sizeof(union vfp_state));
vfp->hard.fpexc = FPEXC_EN;
vfp->hard.fpscr = FPSCR_ROUND_NEAREST;
#ifdef CONFIG_SMP
vfp->hard.cpu = NR_CPUS;
#endif
}
static void vfp_thread_exit(struct thread_info *thread)
{
/* release case: Per-thread VFP cleanup. */
union vfp_state *vfp = &thread->vfpstate;
unsigned int cpu = get_cpu();
if (vfp_current_hw_state[cpu] == vfp)
vfp_current_hw_state[cpu] = NULL;
put_cpu();
}
static void vfp_thread_copy(struct thread_info *thread)
{
struct thread_info *parent = current_thread_info();
vfp_sync_hwstate(parent);
thread->vfpstate = parent->vfpstate;
#ifdef CONFIG_SMP
thread->vfpstate.hard.cpu = NR_CPUS;
#endif
}
/*
* When this function is called with the following 'cmd's, the following
* is true while this function is being run:
* THREAD_NOFTIFY_SWTICH:
* - the previously running thread will not be scheduled onto another CPU.
* - the next thread to be run (v) will not be running on another CPU.
* - thread->cpu is the local CPU number
* - not preemptible as we're called in the middle of a thread switch
* THREAD_NOTIFY_FLUSH:
* - the thread (v) will be running on the local CPU, so
* v === current_thread_info()
* - thread->cpu is the local CPU number at the time it is accessed,
* but may change at any time.
* - we could be preempted if tree preempt rcu is enabled, so
* it is unsafe to use thread->cpu.
* THREAD_NOTIFY_EXIT
* - the thread (v) will be running on the local CPU, so
* v === current_thread_info()
* - thread->cpu is the local CPU number at the time it is accessed,
* but may change at any time.
* - we could be preempted if tree preempt rcu is enabled, so
* it is unsafe to use thread->cpu.
*/
static int vfp_notifier(struct notifier_block *self, unsigned long cmd, void *v)
{
struct thread_info *thread = v;
u32 fpexc;
#ifdef CONFIG_SMP
unsigned int cpu;
#endif
switch (cmd) {
case THREAD_NOTIFY_SWITCH:
fpexc = fmrx(FPEXC);
#ifdef CONFIG_SMP
cpu = thread->cpu;
/*
* On SMP, if VFP is enabled, save the old state in
* case the thread migrates to a different CPU. The
* restoring is done lazily.
*/
if ((fpexc & FPEXC_EN) && vfp_current_hw_state[cpu])
vfp_save_state(vfp_current_hw_state[cpu], fpexc);
#endif
/*
* Always disable VFP so we can lazily save/restore the
* old state.
*/
fmxr(FPEXC, fpexc & ~FPEXC_EN);
break;
case THREAD_NOTIFY_FLUSH:
vfp_thread_flush(thread);
break;
case THREAD_NOTIFY_EXIT:
vfp_thread_exit(thread);
break;
case THREAD_NOTIFY_COPY:
vfp_thread_copy(thread);
break;
}
return NOTIFY_DONE;
}
static struct notifier_block vfp_notifier_block = {
.notifier_call = vfp_notifier,
};
/*
* Raise a SIGFPE for the current process.
* sicode describes the signal being raised.
*/
static void vfp_raise_sigfpe(unsigned int sicode, struct pt_regs *regs)
{
siginfo_t info;
memset(&info, 0, sizeof(info));
info.si_signo = SIGFPE;
info.si_code = sicode;
info.si_addr = (void __user *)(instruction_pointer(regs) - 4);
/*
* This is the same as NWFPE, because it's not clear what
* this is used for
*/
current->thread.error_code = 0;
current->thread.trap_no = 6;
send_sig_info(SIGFPE, &info, current);
}
static void vfp_panic(char *reason, u32 inst)
{
int i;
printk(KERN_ERR "VFP: Error: %s\n", reason);
printk(KERN_ERR "VFP: EXC 0x%08x SCR 0x%08x INST 0x%08x\n",
fmrx(FPEXC), fmrx(FPSCR), inst);
for (i = 0; i < 32; i += 2)
printk(KERN_ERR "VFP: s%2u: 0x%08x s%2u: 0x%08x\n",
i, vfp_get_float(i), i+1, vfp_get_float(i+1));
}
/*
* Process bitmask of exception conditions.
*/
static void vfp_raise_exceptions(u32 exceptions, u32 inst, u32 fpscr, struct pt_regs *regs)
{
int si_code = 0;
pr_debug("VFP: raising exceptions %08x\n", exceptions);
if (exceptions == VFP_EXCEPTION_ERROR) {
vfp_panic("unhandled bounce", inst);
vfp_raise_sigfpe(0, regs);
return;
}
/*
* If any of the status flags are set, update the FPSCR.
* Comparison instructions always return at least one of
* these flags set.
*/
if (exceptions & (FPSCR_N|FPSCR_Z|FPSCR_C|FPSCR_V))
fpscr &= ~(FPSCR_N|FPSCR_Z|FPSCR_C|FPSCR_V);
fpscr |= exceptions;
fmxr(FPSCR, fpscr);
#define RAISE(stat,en,sig) \
if (exceptions & stat && fpscr & en) \
si_code = sig;
/*
* These are arranged in priority order, least to highest.
*/
RAISE(FPSCR_DZC, FPSCR_DZE, FPE_FLTDIV);
RAISE(FPSCR_IXC, FPSCR_IXE, FPE_FLTRES);
RAISE(FPSCR_UFC, FPSCR_UFE, FPE_FLTUND);
RAISE(FPSCR_OFC, FPSCR_OFE, FPE_FLTOVF);
RAISE(FPSCR_IOC, FPSCR_IOE, FPE_FLTINV);
if (si_code)
vfp_raise_sigfpe(si_code, regs);
}
/*
* Emulate a VFP instruction.
*/
static u32 vfp_emulate_instruction(u32 inst, u32 fpscr, struct pt_regs *regs)
{
u32 exceptions = VFP_EXCEPTION_ERROR;
pr_debug("VFP: emulate: INST=0x%08x SCR=0x%08x\n", inst, fpscr);
if (INST_CPRTDO(inst)) {
if (!INST_CPRT(inst)) {
/*
* CPDO
*/
if (vfp_single(inst)) {
exceptions = vfp_single_cpdo(inst, fpscr);
} else {
exceptions = vfp_double_cpdo(inst, fpscr);
}
} else {
/*
* A CPRT instruction can not appear in FPINST2, nor
* can it cause an exception. Therefore, we do not
* have to emulate it.
*/
}
} else {
/*
* A CPDT instruction can not appear in FPINST2, nor can
* it cause an exception. Therefore, we do not have to
* emulate it.
*/
}
return exceptions & ~VFP_NAN_FLAG;
}
/*
* Package up a bounce condition.
*/
void VFP_bounce(u32 trigger, u32 fpexc, struct pt_regs *regs)
{
u32 fpscr, orig_fpscr, fpsid, exceptions;
pr_debug("VFP: bounce: trigger %08x fpexc %08x\n", trigger, fpexc);
atomic64_inc(&vfp_bounce_count);
/*
* At this point, FPEXC can have the following configuration:
*
* EX DEX IXE
* 0 1 x - synchronous exception
* 1 x 0 - asynchronous exception
* 1 x 1 - sychronous on VFP subarch 1 and asynchronous on later
* 0 0 1 - synchronous on VFP9 (non-standard subarch 1
* implementation), undefined otherwise
*
* Clear various bits and enable access to the VFP so we can
* handle the bounce.
*/
fmxr(FPEXC, fpexc & ~(FPEXC_EX|FPEXC_DEX|FPEXC_FP2V|FPEXC_VV|FPEXC_TRAP_MASK));
fpsid = fmrx(FPSID);
orig_fpscr = fpscr = fmrx(FPSCR);
/*
* Check for the special VFP subarch 1 and FPSCR.IXE bit case
*/
if ((fpsid & FPSID_ARCH_MASK) == (1 << FPSID_ARCH_BIT)
&& (fpscr & FPSCR_IXE)) {
/*
* Synchronous exception, emulate the trigger instruction
*/
goto emulate;
}
if (fpexc & FPEXC_EX) {
#ifndef CONFIG_CPU_FEROCEON
/*
* Asynchronous exception. The instruction is read from FPINST
* and the interrupted instruction has to be restarted.
*/
trigger = fmrx(FPINST);
regs->ARM_pc -= 4;
#endif
} else if (!(fpexc & FPEXC_DEX)) {
/*
* Illegal combination of bits. It can be caused by an
* unallocated VFP instruction but with FPSCR.IXE set and not
* on VFP subarch 1.
*/
vfp_raise_exceptions(VFP_EXCEPTION_ERROR, trigger, fpscr, regs);
goto exit;
}
/*
* Modify fpscr to indicate the number of iterations remaining.
* If FPEXC.EX is 0, FPEXC.DEX is 1 and the FPEXC.VV bit indicates
* whether FPEXC.VECITR or FPSCR.LEN is used.
*/
if (fpexc & (FPEXC_EX | FPEXC_VV)) {
u32 len;
len = fpexc + (1 << FPEXC_LENGTH_BIT);
fpscr &= ~FPSCR_LENGTH_MASK;
fpscr |= (len & FPEXC_LENGTH_MASK) << (FPSCR_LENGTH_BIT - FPEXC_LENGTH_BIT);
}
/*
* Handle the first FP instruction. We used to take note of the
* FPEXC bounce reason, but this appears to be unreliable.
* Emulate the bounced instruction instead.
*/
exceptions = vfp_emulate_instruction(trigger, fpscr, regs);
if (exceptions)
vfp_raise_exceptions(exceptions, trigger, orig_fpscr, regs);
/*
* If there isn't a second FP instruction, exit now. Note that
* the FPEXC.FP2V bit is valid only if FPEXC.EX is 1.
*/
if (fpexc ^ (FPEXC_EX | FPEXC_FP2V))
goto exit;
/*
* The barrier() here prevents fpinst2 being read
* before the condition above.
*/
barrier();
trigger = fmrx(FPINST2);
emulate:
exceptions = vfp_emulate_instruction(trigger, orig_fpscr, regs);
if (exceptions)
vfp_raise_exceptions(exceptions, trigger, orig_fpscr, regs);
exit:
preempt_enable();
}
static void vfp_enable(void *unused)
{
u32 access;
BUG_ON(preemptible());
access = get_copro_access();
/*
* Enable full access to VFP (cp10 and cp11)
*/
set_copro_access(access | CPACC_FULL(10) | CPACC_FULL(11));
}
#ifdef CONFIG_CPU_PM
int vfp_pm_suspend(void)
{
struct thread_info *ti = current_thread_info();
u32 fpexc = fmrx(FPEXC);
/* if vfp is on, then save state for resumption */
if (fpexc & FPEXC_EN) {
printk(KERN_DEBUG "%s: saving vfp state\n", __func__);
vfp_save_state(&ti->vfpstate, fpexc);
/* disable, just in case */
fmxr(FPEXC, fmrx(FPEXC) & ~FPEXC_EN);
} else if (vfp_current_hw_state[ti->cpu]) {
#ifndef CONFIG_SMP
fmxr(FPEXC, fpexc | FPEXC_EN);
vfp_save_state(vfp_current_hw_state[ti->cpu], fpexc);
fmxr(FPEXC, fpexc);
#endif
}
/* clear any information we had about last context state */
vfp_current_hw_state[ti->cpu] = NULL;
return 0;
}
void vfp_pm_resume(void)
{
/* ensure we have access to the vfp */
vfp_enable(NULL);
/* and disable it to ensure the next usage restores the state */
fmxr(FPEXC, fmrx(FPEXC) & ~FPEXC_EN);
}
static int vfp_cpu_pm_notifier(struct notifier_block *self, unsigned long cmd,
void *v)
{
switch (cmd) {
case CPU_PM_ENTER:
vfp_pm_suspend();
break;
case CPU_PM_ENTER_FAILED:
case CPU_PM_EXIT:
vfp_pm_resume();
break;
}
return NOTIFY_OK;
}
static struct notifier_block vfp_cpu_pm_notifier_block = {
.notifier_call = vfp_cpu_pm_notifier,
};
static void vfp_pm_init(void)
{
cpu_pm_register_notifier(&vfp_cpu_pm_notifier_block);
}
#else
static inline void vfp_pm_init(void) { }
#endif /* CONFIG_CPU_PM */
/*
* Ensure that the VFP state stored in 'thread->vfpstate' is up to date
* with the hardware state.
*/
void vfp_sync_hwstate(struct thread_info *thread)
{
unsigned int cpu = get_cpu();
if (vfp_state_in_hw(cpu, thread)) {
u32 fpexc = fmrx(FPEXC);
/*
* Save the last VFP state on this CPU.
*/
fmxr(FPEXC, fpexc | FPEXC_EN);
vfp_save_state(&thread->vfpstate, fpexc | FPEXC_EN);
fmxr(FPEXC, fpexc);
}
put_cpu();
}
/* Ensure that the thread reloads the hardware VFP state on the next use. */
void vfp_flush_hwstate(struct thread_info *thread)
{
unsigned int cpu = get_cpu();
vfp_force_reload(cpu, thread);
put_cpu();
}
/*
* Save the current VFP state into the provided structures and prepare
* for entry into a new function (signal handler).
*/
int vfp_preserve_user_clear_hwstate(struct user_vfp __user *ufp,
struct user_vfp_exc __user *ufp_exc)
{
struct thread_info *thread = current_thread_info();
struct vfp_hard_struct *hwstate = &thread->vfpstate.hard;
int err = 0;
/* Ensure that the saved hwstate is up-to-date. */
vfp_sync_hwstate(thread);
/*
* Copy the floating point registers. There can be unused
* registers see asm/hwcap.h for details.
*/
err |= __copy_to_user(&ufp->fpregs, &hwstate->fpregs,
sizeof(hwstate->fpregs));
/*
* Copy the status and control register.
*/
__put_user_error(hwstate->fpscr, &ufp->fpscr, err);
/*
* Copy the exception registers.
*/
__put_user_error(hwstate->fpexc, &ufp_exc->fpexc, err);
__put_user_error(hwstate->fpinst, &ufp_exc->fpinst, err);
__put_user_error(hwstate->fpinst2, &ufp_exc->fpinst2, err);
if (err)
return -EFAULT;
/* Ensure that VFP is disabled. */
vfp_flush_hwstate(thread);
/*
* As per the PCS, clear the length and stride bits for function
* entry.
*/
hwstate->fpscr &= ~(FPSCR_LENGTH_MASK | FPSCR_STRIDE_MASK);
return 0;
}
/* Sanitise and restore the current VFP state from the provided structures. */
int vfp_restore_user_hwstate(struct user_vfp __user *ufp,
struct user_vfp_exc __user *ufp_exc)
{
struct thread_info *thread = current_thread_info();
struct vfp_hard_struct *hwstate = &thread->vfpstate.hard;
unsigned long fpexc;
int err = 0;
/* Disable VFP to avoid corrupting the new thread state. */
vfp_flush_hwstate(thread);
/*
* Copy the floating point registers. There can be unused
* registers see asm/hwcap.h for details.
*/
err |= __copy_from_user(&hwstate->fpregs, &ufp->fpregs,
sizeof(hwstate->fpregs));
/*
* Copy the status and control register.
*/
__get_user_error(hwstate->fpscr, &ufp->fpscr, err);
/*
* Sanitise and restore the exception registers.
*/
__get_user_error(fpexc, &ufp_exc->fpexc, err);
/* Ensure the VFP is enabled. */
fpexc |= FPEXC_EN;
/* Ensure FPINST2 is invalid and the exception flag is cleared. */
fpexc &= ~(FPEXC_EX | FPEXC_FP2V);
hwstate->fpexc = fpexc;
__get_user_error(hwstate->fpinst, &ufp_exc->fpinst, err);
__get_user_error(hwstate->fpinst2, &ufp_exc->fpinst2, err);
return err ? -EFAULT : 0;
}
/*
* VFP hardware can lose all context when a CPU goes offline.
* As we will be running in SMP mode with CPU hotplug, we will save the
* hardware state at every thread switch. We clear our held state when
* a CPU has been killed, indicating that the VFP hardware doesn't contain
* a threads VFP state. When a CPU starts up, we re-enable access to the
* VFP hardware.
*
* Both CPU_DYING and CPU_STARTING are called on the CPU which
* is being offlined/onlined.
*/
static int vfp_hotplug(struct notifier_block *b, unsigned long action,
void *hcpu)
{
if (action == CPU_DYING || action == CPU_DYING_FROZEN) {
vfp_force_reload((long)hcpu, current_thread_info());
} else if (action == CPU_STARTING || action == CPU_STARTING_FROZEN)
vfp_enable(NULL);
return NOTIFY_OK;
}
#ifdef CONFIG_PROC_FS
static int vfp_bounce_show(struct seq_file *m, void *v)
{
seq_printf(m, "%llu\n", atomic64_read(&vfp_bounce_count));
return 0;
}
static int vfp_bounce_open(struct inode *inode, struct file *file)
{
return single_open(file, vfp_bounce_show, NULL);
}
static const struct file_operations vfp_bounce_fops = {
.open = vfp_bounce_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
#endif
/*
* VFP support code initialisation.
*/
static int __init vfp_init(void)
{
unsigned int vfpsid;
unsigned int cpu_arch = cpu_architecture();
#ifdef CONFIG_PROC_FS
static struct proc_dir_entry *procfs_entry;
#endif
if (cpu_arch >= CPU_ARCH_ARMv6)
on_each_cpu(vfp_enable, NULL, 1);
/*
* First check that there is a VFP that we can use.
* The handler is already setup to just log calls, so
* we just need to read the VFPSID register.
*/
vfp_vector = vfp_testing_entry;
barrier();
vfpsid = fmrx(FPSID);
barrier();
vfp_vector = vfp_null_entry;
printk(KERN_INFO "VFP support v0.3: ");
if (VFP_arch)
printk("not present\n");
else if (vfpsid & FPSID_NODOUBLE) {
printk("no double precision support\n");
} else {
hotcpu_notifier(vfp_hotplug, 0);
VFP_arch = (vfpsid & FPSID_ARCH_MASK) >> FPSID_ARCH_BIT; /* Extract the architecture version */
printk("implementor %02x architecture %d part %02x variant %x rev %x\n",
(vfpsid & FPSID_IMPLEMENTER_MASK) >> FPSID_IMPLEMENTER_BIT,
(vfpsid & FPSID_ARCH_MASK) >> FPSID_ARCH_BIT,
(vfpsid & FPSID_PART_MASK) >> FPSID_PART_BIT,
(vfpsid & FPSID_VARIANT_MASK) >> FPSID_VARIANT_BIT,
(vfpsid & FPSID_REV_MASK) >> FPSID_REV_BIT);
vfp_vector = vfp_support_entry;
thread_register_notifier(&vfp_notifier_block);
vfp_pm_init();
/*
* We detected VFP, and the support code is
* in place; report VFP support to userspace.
*/
elf_hwcap |= HWCAP_VFP;
#ifdef CONFIG_VFPv3
if (VFP_arch >= 2) {
elf_hwcap |= HWCAP_VFPv3;
/*
* Check for VFPv3 D16. CPUs in this configuration
* only have 16 x 64bit registers.
*/
if (((fmrx(MVFR0) & MVFR0_A_SIMD_MASK)) == 1)
elf_hwcap |= HWCAP_VFPv3D16;
}
#endif
/*
* Check for the presence of the Advanced SIMD
* load/store instructions, integer and single
* precision floating point operations. Only check
* for NEON if the hardware has the MVFR registers.
*/
if ((read_cpuid_id() & 0x000f0000) == 0x000f0000) {
#ifdef CONFIG_NEON
if ((fmrx(MVFR1) & 0x000fff00) == 0x00011100)
elf_hwcap |= HWCAP_NEON;
#endif
if ((fmrx(MVFR1) & 0xf0000000) == 0x10000000 ||
(read_cpuid_id() & 0xff00fc00) == 0x51000400)
elf_hwcap |= HWCAP_VFPv4;
}
}
#ifdef CONFIG_PROC_FS
procfs_entry = proc_create("cpu/vfp_bounce", S_IRUGO, NULL,
&vfp_bounce_fops);
if (!procfs_entry)
pr_err("Failed to create procfs node for VFP bounce reporting\n");
#endif
#ifdef CONFIG_MACH_LGE
printk(KERN_INFO "VFP support v0.3: Return ");
#endif
return 0;
}
#ifdef CONFIG_MACH_LGE
rootfs_initcall(vfp_init);
#else /* origin */
late_initcall(vfp_init);
#endif
|
<?php
/**
* @package Joomla.Site
* @subpackage com_content
*
* @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
JHtml::addIncludePath(JPATH_COMPONENT.'/helpers');
?>
<section class="category-list <?php echo strtolower($this->pageclass_sfx);?>">
<?php if ($this->params->get('show_page_heading')) : ?>
<h1>
<?php echo $this->escape($this->params->get('page_heading')); ?>
</h1>
<?php endif; ?>
<?php if ($this->params->get('show_category_title', 1) or $this->params->get('page_subheading')) : ?>
<h2>
<?php echo $this->escape($this->params->get('page_subheading')); ?>
<?php if ($this->params->get('show_category_title')) : ?>
<span class="subheading-category"><?php echo $this->category->title;?></span>
<?php endif; ?>
</h2>
<?php endif; ?>
<?php if ($this->params->get('show_description', 1) || $this->params->def('show_description_image', 1)) : ?>
<section class="category-desc">
<?php if ($this->params->get('show_description_image') && $this->category->getParams()->get('image')) : ?>
<img src="<?php echo $this->category->getParams()->get('image'); ?>" alt="<?php echo $this->category->title;?>" />
<?php endif; ?>
<?php if ($this->params->get('show_description') && $this->category->description) : ?>
<?php echo JHtml::_('content.prepare', $this->category->description); ?>
<?php endif; ?>
</section>
<?php endif; ?>
<section class="cat-items">
<?php echo $this->loadTemplate('articles'); ?>
</section>
<?php if (!empty($this->children[$this->category->id])&& $this->maxLevel != 0) : ?>
<?php echo $this->loadTemplate('children'); ?>
<?php endif; ?>
</section> |
<?php
/* ----------------------------------------------------------------------
* views/administrate/setup/list_item_editor_delete_html.php :
* ----------------------------------------------------------------------
* CollectiveAccess
* Open-source collections management software
* ----------------------------------------------------------------------
*
* Software by Whirl-i-Gig (http://www.whirl-i-gig.com)
* Copyright 2008-2011 Whirl-i-Gig
*
* For more information visit http://www.CollectiveAccess.org
*
* This program is free software; you may redistribute it and/or modify it under
* the terms of the provided license as published by Whirl-i-Gig
*
* CollectiveAccess is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTIES whatsoever, including any implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* This source code is free and modifiable under the terms of
* GNU General Public License. (http://www.gnu.org/copyleft/gpl.html). See
* the "license.txt" file for details, or visit the CollectiveAccess web site at
* http://www.CollectiveAccess.org
*
* ----------------------------------------------------------------------
*/
$t_item = $this->getVar('t_subject');
$vn_type_id = $this->getVar('subject_id');
?>
<div class="sectionBox">
<?php
if (!$this->getVar('confirmed')) {
// show delete confirmation notice
print caDeleteWarningBox($this->request, $t_item, $this->getVar('subject_name'), 'administrate/setup/relationship_type_editor', 'RelationshipTypeEditor', 'Edit/'.$this->request->getActionExtra(), array('type_id' => $vn_type_id));
}
?>
</div> |
<?php
/*
* Fields and groups functions
*
* $HeadURL: http://plugins.svn.wordpress.org/types/tags/1.6.4/includes/fields.php $
* $LastChangedDate: 2014-11-18 06:47:25 +0000 (Tue, 18 Nov 2014) $
* $LastChangedRevision: 1027712 $
* $LastChangedBy: iworks $
*
*/
require_once WPCF_EMBEDDED_INC_ABSPATH . '/fields.php';
/**
* Gets post_types supported by specific group.
*
* @global type $wpdb
* @param type $group_id
* @return type
*/
function wpcf_admin_get_post_types_by_group( $group_id ) {
$post_types = get_post_meta( $group_id, '_wp_types_group_post_types', true );
if ( $post_types == 'all' ) {
return array();
}
$post_types = explode( ',', trim( $post_types, ',' ) );
return $post_types;
}
/**
* Gets taxonomies supported by specific group.
*
* @global type $wpdb
* @param type $group_id
* @return type
*/
function wpcf_admin_get_taxonomies_by_group( $group_id ) {
global $wpdb;
$terms = get_post_meta( $group_id, '_wp_types_group_terms', true );
if ( $terms == 'all' ) {
return array();
}
$terms = explode( ',', trim( $terms, ',' ) );
$taxonomies = array();
if ( !empty( $terms ) ) {
foreach ( $terms as $term ) {
$term = $wpdb->get_row( "SELECT tt.term_taxonomy_id, tt.taxonomy,
t.term_id, t.slug, t.name
FROM {$wpdb->prefix}term_taxonomy tt
JOIN {$wpdb->prefix}terms t
WHERE t.term_id = tt.term_id AND tt.term_taxonomy_id="
. intval( $term ), ARRAY_A );
if ( !empty( $term ) ) {
$taxonomies[$term['taxonomy']][$term['term_taxonomy_id']] = $term;
}
}
} else {
return array();
}
return $taxonomies;
}
/**
* Gets templates supported by specific group.
*
* @global type $wpdb
* @param type $group_id
* @return type
*/
function wpcf_admin_get_templates_by_group( $group_id ) {
global $wpdb;
$data = get_post_meta( $group_id, '_wp_types_group_templates', true );
if ( $data == 'all' ) {
return array();
}
$data = explode( ',', trim( $data, ',' ) );
$templates = get_page_templates();
$templates[] = 'default';
$templates_views = get_posts( 'post_type=view-template&numberposts=-1&status=publish' );
foreach ( $templates_views as $template_view ) {
$templates[] = $template_view->ID;
}
$result = array();
if ( !empty( $data ) ) {
foreach ( $templates as $template ) {
if ( in_array( $template, $data ) ) {
$result[] = $template;
}
}
}
return $result;
}
/**
* Activates group.
* Modified by Gen, 13.02.2013
*
* @global type $wpdb
* @param type $group_id
* @return type
*/
function wpcf_admin_fields_activate_group( $group_id,
$post_type = 'wp-types-group' ) {
global $wpdb;
return $wpdb->update( $wpdb->posts, array('post_status' => 'publish'),
array('ID' => intval( $group_id ), 'post_type' => $post_type),
array('%s'), array('%d', '%s')
);
}
/**
* Deactivates group.
* Modified by Gen, 13.02.2013
*
* @global type $wpdb
* @param type $group_id
* @return type
*/
function wpcf_admin_fields_deactivate_group( $group_id,
$post_type = 'wp-types-group' ) {
global $wpdb;
return $wpdb->update( $wpdb->posts, array('post_status' => 'draft'),
array('ID' => intval( $group_id ), 'post_type' => $post_type),
array('%s'), array('%d', '%s')
);
}
/**
* Removes specific field from group.
*
* @global type $wpdb
* @global type $wpdb
* @param type $group_id
* @param type $field_id
* @return type
*/
function wpcf_admin_fields_remove_field_from_group( $group_id, $field_id ) {
$group_fields = get_post_meta( $group_id, '_wp_types_group_fields', true );
if ( empty( $group_fields ) ) {
return false;
}
$group_fields = str_replace( ',' . $field_id . ',', ',', $group_fields );
update_post_meta( $group_id, '_wp_types_group_fields', $group_fields );
}
/**
* Bulk removal
*
* @param type $group_id
* @param type $fields
* @return type
*/
function wpcf_admin_fields_remove_field_from_group_bulk( $group_id, $fields ) {
foreach ( $fields as $field_id ) {
wpcf_admin_fields_remove_field_from_group( $group_id, $field_id );
}
}
/**
* Deletes field.
* Modified by Gen, 13.02.2013
*
* @param type $field_id
*/
function wpcf_admin_fields_delete_field( $field_id,
$post_type = 'wp-types-group', $meta_name = 'wpcf-fields' ) {
global $wpdb;
$fields = get_option( $meta_name, array() );
if ( isset( $fields[$field_id] ) ) {
// Remove from groups
$groups = wpcf_admin_fields_get_groups( $post_type );
foreach ( $groups as $key => $group ) {
wpcf_admin_fields_remove_field_from_group( $group['id'], $field_id );
}
// Remove from posts
if ( !wpcf_types_cf_under_control( 'check_outsider', $field_id,
$post_type, $meta_name ) ) {
$results = $wpdb->get_results( "SELECT post_id, meta_key FROM $wpdb->postmeta WHERE meta_key = '" . wpcf_types_get_meta_prefix( $fields[$field_id] ) . strval( $field_id ) . "'" );
foreach ( $results as $result ) {
delete_post_meta( $result->post_id, $result->meta_key );
}
}
unset( $fields[$field_id] );
wpcf_admin_fields_save_fields( $fields, true, $meta_name );
return true;
} else {
return false;
}
}
/**
* Deletes group by ID.
* Modified by Gen, 13.02.2013
*
* @global type $wpdb
* @param type $group_id
* @return type
*/
function wpcf_admin_fields_delete_group( $group_id,
$post_type = 'wp-types-group' ) {
$group = get_post( $group_id );
if ( empty( $group ) || $group->post_type != $post_type ) {
return false;
}
wp_delete_post( $group_id, true );
}
/**
* Saves group.
* Modified by Gen, 13.02.2013
*
* @param type $group
* @return type
*/
function wpcf_admin_fields_save_group( $group, $post_type = 'wp-types-group' ) {
if ( !isset( $group['name'] ) ) {
return false;
}
$post = array(
'post_status' => 'publish',
'post_type' => $post_type,
'post_title' => $group['name'],
'post_name' => $group['name'],
'post_content' => !empty( $group['description'] ) ? $group['description'] : '',
);
$update = false;
if ( isset( $group['id'] ) ) {
$update = true;
$post_to_update = get_post( $group['id'] );
if ( empty( $post_to_update ) || $post_to_update->post_type != $post_type ) {
return false;
}
$post['ID'] = $post_to_update->ID;
$post['post_status'] = $post_to_update->post_status;
}
if ( $update ) {
$group_id = wp_update_post( $post );
if ( !$group_id ) {
return false;
}
} else {
$group_id = wp_insert_post( $post, true );
if ( is_wp_error( $group_id ) ) {
return false;
}
}
if ( !empty( $group['filters_association'] ) ) {
update_post_meta( $group_id, '_wp_types_group_filters_association', $group['filters_association'] );
} else {
delete_post_meta( $group_id, '_wp_types_group_filters_association' );
}
// WPML register strings
if ( function_exists( 'icl_register_string' ) ) {
wpcf_translate_register_string( 'plugin Types',
'group ' . $group_id . ' name', $group['name'] );
wpcf_translate_register_string( 'plugin Types',
'group ' . $group_id . ' description', $group['description'] );
}
return $group_id;
}
/**
* Saves all fields.
* Modified by Gen, 13.02.2013
*
* @param type $fields
*/
function wpcf_admin_fields_save_fields( $fields, $forced = false,
$option_name = 'wpcf-fields' ) {
$original = get_option( $option_name, array() );
if ( !$forced ) {
$fields = array_merge( $original, $fields );
}
update_option( $option_name, $fields );
}
/**
* Saves field.
* Modified by Gen, 13.02.2013
*
* @param type $field
* @return type
*/
function wpcf_admin_fields_save_field( $field, $post_type = 'wp-types-group',
$meta_name = 'wpcf-fields' ) {
if ( !isset( $field['name'] ) || !isset( $field['type'] ) ) {
return new WP_Error( 'wpcf_save_field_no_name_or_type', __( "Error saving field",
'wpcf' ) );
}
$field = wpcf_sanitize_field( $field );
if ( empty( $field['name'] ) || empty( $field['slug'] ) ) {
return new WP_Error( 'wpcf_save_field_no_name', __( "Please set name for field",
'wpcf' ) );
}
$field['id'] = $field['slug'];
// Set field specific data
// NOTE: This was $field['data'] = $field and seemed to work on most systems.
// I changed it to asign via a temporary variable to fix on one system.
$temp_field = $field;
$field['data'] = $temp_field;
// Unset default fields
unset( $field['data']['type'], $field['data']['slug'],
$field['data']['name'], $field['data']['description'],
$field['data']['user_id'], $field['data']['id'],
$field['data']['data'] );
// Merge previous data (added because of outside fields)
// @TODO Remember why
if ( wpcf_types_cf_under_control( 'check_outsider', $field['id'],
$post_type, $meta_name ) ) {
$field_previous_data = wpcf_admin_fields_get_field( $field['id'], false,
true, false, $meta_name );
if ( !empty( $field_previous_data['data'] ) ) {
$field['data'] = array_merge( $field_previous_data['data'],
$field['data'] );
}
}
$field['data'] = apply_filters( 'wpcf_fields_' . $field['type'] . '_meta_data', $field['data'], $field );
// Check validation
if ( isset( $field['data']['validate'] ) ) {
foreach ( $field['data']['validate'] as $method => $data ) {
if ( !isset( $data['active'] ) ) {
unset( $field['data']['validate'][$method] );
}
}
if ( empty( $field['data']['validate'] ) ) {
unset( $field['data']['validate'] );
}
}
$save_data = array();
$save_data['id'] = $field['id'];
$save_data['slug'] = $field['slug'];
$save_data['type'] = $field['type'];
$save_data['name'] = $field['name'];
$save_data['description'] = $field['description'];
$save_data['data'] = $field['data'];
$save_data['data']['disabled_by_type'] = 0;
// For radios or select
if ( !empty( $field['data']['options'] ) ) {
foreach ( $field['data']['options'] as $name => $option ) {
if ( isset( $option['title'] ) ) {
$option['title'] = $field['data']['options'][$name]['title'] = htmlspecialchars_decode( $option['title'] );
}
if ( isset( $option['value'] ) ) {
$option['value'] = $field['data']['options'][$name]['value'] = htmlspecialchars_decode( $option['value'] );
}
if ( isset( $option['display_value'] ) ) {
$option['display_value'] = $field['data']['options'][$name]['display_value'] = htmlspecialchars_decode( $option['display_value'] );
}
// For checkboxes
if ( $field['type'] == 'checkboxes' && isset( $option['set_value'] )
&& $option['set_value'] != '1' ) {
$option['set_value'] = $field['data']['options'][$name]['set_value'] = htmlspecialchars_decode( $option['set_value'] );
}
if ( $field['type'] == 'checkboxes' && !empty( $option['display_value_selected'] ) ) {
$option['display_value_selected'] = $field['data']['options'][$name]['display_value_selected'] = htmlspecialchars_decode( $option['display_value_selected'] );
}
if ( $field['type'] == 'checkboxes' && !empty( $option['display_value_not_selected'] ) ) {
$option['display_value_not_selected'] = $field['data']['options'][$name]['display_value_not_selected'] = htmlspecialchars_decode( $option['display_value_not_selected'] );
}
}
}
// For checkboxes
if ( $field['type'] == 'checkbox' && $field['set_value'] != '1' ) {
$field['set_value'] = htmlspecialchars_decode( $field['set_value'] );
}
if ( $field['type'] == 'checkbox' && !empty( $field['display_value_selected'] ) ) {
$field['display_value_selected'] = htmlspecialchars_decode( $field['display_value_selected'] );
}
if ( $field['type'] == 'checkbox' && !empty( $field['display_value_not_selected'] ) ) {
$field['display_value_not_selected'] = htmlspecialchars_decode( $field['display_value_not_selected'] );
}
// Save field
$fields = get_option( $meta_name, array() );
$fields[$field['slug']] = $save_data;
update_option( $meta_name, $fields );
$field_id = $field['slug'];
// WPML register strings
if ( function_exists( 'icl_register_string' ) ) {
if ( isset($_POST['wpml_cf_translation_preferences'][$field_id] ) ) {
$__wpml_action = intval( $_POST['wpml_cf_translation_preferences'][$field_id] );
} else {
$__wpml_action = wpcf_wpml_get_action_by_type( $field['type'] );
}
wpcf_translate_register_string( 'plugin Types',
'field ' . $field_id . ' name', $field['name'] );
wpcf_translate_register_string( 'plugin Types',
'field ' . $field_id . ' description', $field['description'] );
// For radios or select
if ( !empty( $field['data']['options'] ) ) {
foreach ( $field['data']['options'] as $name => $option ) {
if ( $name == 'default' ) {
continue;
}
if ( isset( $option['title'] ) ) {
wpcf_translate_register_string( 'plugin Types',
'field ' . $field_id . ' option ' . $name . ' title',
$option['title'] );
}
if ($__wpml_action === 2) {
if ( isset( $option['value'] ) ) {
wpcf_translate_register_string( 'plugin Types',
'field ' . $field_id . ' option ' . $name . ' value',
$option['value'] );
}
}
if ( isset( $option['display_value'] ) ) {
wpcf_translate_register_string( 'plugin Types',
'field ' . $field_id . ' option ' . $name . ' display value',
$option['display_value'] );
}
// For checkboxes
if ( isset( $option['set_value'] ) && $option['set_value'] != '1' ) {
wpcf_translate_register_string( 'plugin Types',
'field ' . $field_id . ' option ' . $name . ' value',
$option['set_value'] );
}
if ( !empty( $option['display_value_selected'] ) ) {
wpcf_translate_register_string( 'plugin Types',
'field ' . $field_id . ' option ' . $name . ' display value selected',
$option['display_value_selected'] );
}
if ( !empty( $option['display_value_not_selected'] ) ) {
wpcf_translate_register_string( 'plugin Types',
'field ' . $field_id . ' option ' . $name . ' display value not selected',
$option['display_value_not_selected'] );
}
}
}
if ( $field['type'] == 'checkbox' && $field['set_value'] != '1' ) {
// we need to translate the check box value to store
wpcf_translate_register_string( 'plugin Types',
'field ' . $field_id . ' checkbox value',
$field['set_value'] );
}
if ( $field['type'] == 'checkbox' && !empty( $field['display_value_selected'] ) ) {
// we need to translate the check box value to store
wpcf_translate_register_string( 'plugin Types',
'field ' . $field_id . ' checkbox value selected',
$field['display_value_selected'] );
}
if ( $field['type'] == 'checkbox' && !empty( $field['display_value_not_selected'] ) ) {
// we need to translate the check box value to store
wpcf_translate_register_string( 'plugin Types',
'field ' . $field_id . ' checkbox value not selected',
$field['display_value_not_selected'] );
}
// Validation message
if ( !empty( $field['data']['validate'] ) ) {
foreach ( $field['data']['validate'] as $method => $validation ) {
if ( !empty( $validation['message'] ) ) {
// Skip if it's same as default
$default_message = wpcf_admin_validation_messages( $method );
if ( $validation['message'] != $default_message ) {
wpcf_translate_register_string( 'plugin Types',
'field ' . $field_id . ' validation message ' . $method,
$validation['message'] );
}
}
}
}
}
return $field_id;
}
/**
* Changes field type.
* Modified by Gen, 13.02.2013
*
* @param type $fields
* @param type $type
*/
function wpcf_admin_custom_fields_change_type( $fields, $type,
$post_type = 'wp-types-group', $meta_name = 'wpcf-fields' ) {
if ( !is_array( $fields ) ) {
$fields = array(strval( $fields ));
}
$fields = wpcf_types_cf_under_control( 'add',
array('fields' => $fields, 'type' => $type), $post_type, $meta_name );
$allowed = array(
'audio' => array('wysiwyg', 'url', 'textarea', 'textfield', 'email', 'date', 'phone', 'file', 'image', 'numeric', 'audio', 'video', 'embed'),
'textfield' => array('wysiwyg', 'textfield', 'textarea', 'email', 'url', 'date', 'phone', 'file', 'image', 'numeric', 'audio', 'video', 'embed'),
'textarea' => array('wysiwyg', 'textfield', 'textarea', 'email', 'url', 'date', 'phone', 'file', 'image', 'numeric', 'audio', 'video', 'embed'),
'date' => array('wysiwyg', 'date', 'textarea', 'textfield', 'email', 'url', 'phone', 'file', 'image', 'numeric', 'audio', 'video', 'embed'),
'email' => array('wysiwyg', 'email', 'textarea', 'textfield', 'date', 'url', 'phone', 'file', 'image', 'numeric', 'audio', 'video', 'embed'),
'embed' => array('wysiwyg', 'url', 'textarea', 'textfield', 'email', 'date', 'phone', 'file', 'image', 'numeric', 'audio', 'video', 'embed'),
'file' => array('wysiwyg', 'file', 'textarea', 'textfield', 'email', 'url', 'phone', 'fdate', 'image', 'numeric', 'audio', 'video', 'embed'),
'image' => array('wysiwyg', 'image', 'textarea', 'textfield', 'email', 'url', 'phone', 'file', 'idate', 'numeric', 'audio', 'video', 'embed'),
'numeric' => array('wysiwyg', 'numeric', 'textarea', 'textfield', 'email', 'url', 'phone', 'file', 'image', 'date', 'audio', 'video', 'embed'),
'phone' => array('wysiwyg', 'phone', 'textarea', 'textfield', 'email', 'url', 'date', 'file', 'image', 'numeric', 'audio', 'video', 'embed'),
'select' => array('wysiwyg', 'select', 'textarea', 'textfield', 'date', 'email', 'url', 'phone', 'file', 'image', 'numeric', 'audio', 'video', 'embed'),
'skype' => array('wysiwyg', 'skype', 'textarea', 'textfield', 'date', 'email', 'url', 'phone', 'file', 'image', 'numeric', 'audio', 'video', 'embed'),
'url' => array('wysiwyg', 'url', 'textarea', 'textfield', 'email', 'date', 'phone', 'file', 'image', 'numeric', 'audio', 'video', 'embed'),
'checkbox' => array('wysiwyg', 'checkbox', 'textarea', 'textfield', 'email', 'url', 'date', 'phone', 'file', 'image', 'numeric', 'audio', 'video', 'embed'),
'radio' => array('wysiwyg', 'radio', 'textarea', 'textfield', 'email', 'url', 'date', 'phone', 'file', 'image', 'numeric', 'audio', 'video', 'embed'),
'video' => array('wysiwyg', 'url', 'textarea', 'textfield', 'email', 'date', 'phone', 'file', 'image', 'numeric', 'audio', 'video', 'embed'),
'wysiwyg' => array('wysiwyg', 'textarea'),
);
$all_fields = wpcf_admin_fields_get_fields( false, false, false, $meta_name );
foreach ( $fields as $field_id ) {
if ( !isset( $all_fields[$field_id] ) ) {
continue;
}
$field = $all_fields[$field_id];
if ( !in_array( $type, $allowed[$field['type']] ) ) {
wpcf_admin_message_store( sprintf( __( 'Field "%s" type was converted from %s to %s. You need to set some further settings in the group editor.',
'wpcf' ), $field['name'], $field['type'],
$type ) );
$all_fields[$field_id]['data']['disabled_by_type'] = 1;
} else {
$all_fields[$field_id]['data']['disabled'] = 0;
$all_fields[$field_id]['data']['disabled_by_type'] = 0;
}
if ( $field['type'] == 'numeric' && isset( $all_fields[$field_id]['data']['validate']['number'] ) ) {
unset( $all_fields[$field_id]['data']['validate']['number'] );
} else if ( $type == 'numeric' ) {
$all_fields[$field_id]['data']['validate'] = array('number' => array(
'active' => true, 'message' => __('Please enter numeric data', 'wpcf')));
}
$all_fields[$field_id]['type'] = $type;
}
update_option( $meta_name, $all_fields );
}
/**
* Saves group's fields.
* Modified by Gen, 13.02.2013
*
* @global type $wpdb
* @param type $group_id
* @param type $fields
*/
function wpcf_admin_fields_save_group_fields( $group_id, $fields, $add = false,
$post_type = 'wp-types-group' ) {
$meta_name = ($post_type == 'wp-types-group' ? 'wpcf-fields' : 'wpcf-usermeta');
$fields = wpcf_types_cf_under_control( 'add', array('fields' => $fields),
$post_type, $meta_name );
if ( $add ) {
$existing_fields = wpcf_admin_fields_get_fields_by_group( $group_id,
'slug', false, true, false, $post_type, $meta_name );
$order = array();
if ( !empty( $existing_fields ) ) {
foreach ( $existing_fields as $field_id => $field ) {
if ( in_array( $field['id'], $fields ) ) {
continue;
}
$order[] = $field['id'];
}
foreach ( $fields as $field ) {
$order[] = $field;
}
$fields = $order;
}
}
if ( empty( $fields ) ) {
delete_post_meta( $group_id, '_wp_types_group_fields' );
return false;
}
$fields = ',' . implode( ',', (array) $fields ) . ',';
update_post_meta( $group_id, '_wp_types_group_fields', $fields );
}
/**
* Saves group's post types.
*
* @global type $wpdb
* @param type $group_id
* @param type $post_types
*/
function wpcf_admin_fields_save_group_post_types( $group_id, $post_types ) {
if ( empty( $post_types ) ) {
update_post_meta( $group_id, '_wp_types_group_post_types', 'all' );
return true;
}
$post_types = ',' . implode( ',', (array) $post_types ) . ',';
update_post_meta( $group_id, '_wp_types_group_post_types', $post_types );
}
/**
* Saves group's terms.
*
* @global type $wpdb
* @param type $group_id
* @param type $terms
*/
function wpcf_admin_fields_save_group_terms( $group_id, $terms ) {
if ( empty( $terms ) ) {
update_post_meta( $group_id, '_wp_types_group_terms', 'all' );
return true;
}
$terms = ',' . implode( ',', (array) $terms ) . ',';
update_post_meta( $group_id, '_wp_types_group_terms', $terms );
}
/**
* Saves group's templates.
*
* @global type $wpdb
* @param type $group_id
* @param type $terms
*/
function wpcf_admin_fields_save_group_templates( $group_id, $templates ) {
if ( empty( $templates ) ) {
update_post_meta( $group_id, '_wp_types_group_templates', 'all' );
return true;
}
$templates = ',' . implode( ',', (array) $templates ) . ',';
update_post_meta( $group_id, '_wp_types_group_templates', $templates );
}
/**
* Returns HTML formatted AJAX activation link.
*
* @param type $group_id
* @return type
*/
function wpcf_admin_fields_get_ajax_activation_link( $group_id ) {
return '<a href="' . admin_url( 'admin-ajax.php?action=wpcf_ajax&'
. 'wpcf_action=activate_group&group_id='
. $group_id . '&wpcf_ajax_update=wpcf_list_ajax_response_'
. $group_id ) . '&_wpnonce=' . wp_create_nonce( 'activate_group' )
. '" class="wpcf-ajax-link" id="wpcf-list-activate-'
. $group_id . '">'
. __( 'Activate', 'wpcf' ) . '</a>';
}
/**
* Returns HTML formatted AJAX deactivation link.
* @param type $group_id
* @return type
*/
function wpcf_admin_fields_get_ajax_deactivation_link( $group_id ) {
return '<a href="' . admin_url( 'admin-ajax.php?action=wpcf_ajax&'
. 'wpcf_action=deactivate_group&group_id='
. $group_id . '&wpcf_ajax_update=wpcf_list_ajax_response_'
. $group_id ) . '&_wpnonce=' . wp_create_nonce( 'deactivate_group' )
. '" class="wpcf-ajax-link" id="wpcf-list-activate-'
. $group_id . '">'
. __( 'Deactivate', 'wpcf' ) . '</a>';
}
/**
* Check how many posts needs checkbox update.
*
* @param type $field
* @param type $action
* @return boolean|int
*/
function wpcf_admin_fields_checkbox_migrate_empty_check( $field, $action ) {
if ( $field['type'] != 'checkbox' ) {
return false;
}
if ($field['meta_type'] == 'postmeta') {
$filter = wpcf_admin_fields_get_filter_by_field( $field['id'] );
if ( !empty( $filter ) ) {
$posts = array();
$meta_key = wpcf_types_get_meta_prefix( $field ) . $field['id'];
$meta_query = '';
if ( $action == 'do_not_save_check' ) {
$meta_query = "(m.meta_key = '$meta_key' AND m.meta_value = '0')";
$posts = wpcf_admin_fields_get_posts_by_filter( $filter, $meta_query );
} else if ( $action == 'save_check' ) {
$posts = wpcf_admin_fields_get_posts_by_filter_missing_meta( $filter,
$meta_key );
}
$option = get_option( 'wpcf_checkbox_migration', array() );
$cache_key = $action == 'do_not_save_check' ? 'do_not_save' : 'save';
$option[$cache_key] = $posts;
update_option( 'wpcf_checkbox_migration', $option );
return $posts;
}
} else if ($field['meta_type'] == 'usermeta') {
$option = get_option( 'wpcf_checkbox_migration_usermeta', array() );
$cache_key = $action == 'do_not_save_check' ? 'do_not_save' : 'save';
if ( $action == 'do_not_save_check' ) {
$user_query = new WP_User_Query( array('meta_key' => $field['meta_key'],
'meta_value' => '0', 'meta_compare' => '=', 'fields' => 'ID') );
$r = $user_query->results;
} else if ( $action == 'save_check' ) {
global $wpdb;
$_query = "SELECT u.ID FROM {$wpdb->users} u WHERE NOT EXISTS (SELECT um.user_id FROM {$wpdb->usermeta} um WHERE u.ID = um.user_id AND um.meta_key = '%s')";
$r = $wpdb->get_col($wpdb->prepare( $_query, $field['meta_key']) );
}
$option[$field['meta_key']][$cache_key] = $r;
update_option( 'wpcf_checkbox_migration_usermeta', $option );
return $r;
}
return false;
}
/**
* Update posts checkboxes fields.
*
* @param type $field
* @param type $action
* @return boolean|int
*/
function wpcf_admin_fields_checkbox_migrate_empty( $field, $action ) {
if ( $field['type'] != 'checkbox' ) {
return false;
}
if ( $field['meta_type'] == 'usermeta' ) {
$option = get_option( 'wpcf_checkbox_migration_usermeta', array() );
if ( empty( $option[$field['meta_key']][$action] ) ) {
$users = wpcf_admin_fields_checkbox_migrate_empty_check( $field,
$action . '_check' );
} else {
$users = $option[$field['meta_key']][$action];
}
if ( !empty( $users ) ) {
if ( $action == 'do_not_save' ) {
$count = 0;
foreach ( $users as $temp_key => $user_id ) {
if ( $count == 1000 ) {
$option[$field['meta_key']][$action] = $users;
update_option( 'wpcf_checkbox_migration', $option );
$data = array('offset' => $temp_key);
return $data;
}
delete_user_meta( $user_id, $field['meta_key'], 0 );
unset( $users[$temp_key] );
$count++;
}
unset( $option[$field['meta_key']][$action] );
update_option( 'wpcf_checkbox_migration_usermeta', $option );
return $users;
} else if ( $action == 'save' ) {
$count = 0;
foreach ( $users as $temp_key => $user_id ) {
if ( $count == 1000 ) {
$option[$field['meta_key']][$action] = $users;
update_option( 'wpcf_checkbox_migration_usermeta', $option );
$data = array('offset' => $temp_key);
return $data;
}
update_user_meta( $user_id, $field['meta_key'], 0 );
unset( $users[$temp_key] );
$count++;
}
unset( $option[$field['meta_key']][$action] );
update_option( 'wpcf_checkbox_migration_usermeta', $option );
return $users;
}
}
return false;
}
$option = get_option( 'wpcf_checkbox_migration', array() );
$meta_key = wpcf_types_get_meta_prefix( $field ) . $field['id'];
if ( empty( $option[$action] ) ) {
$posts = wpcf_admin_fields_checkbox_migrate_empty_check( $field,
$action . '_check' );
} else {
$posts = $option[$action];
}
if ( !empty( $posts ) ) {
if ( $action == 'do_not_save' ) {
$count = 0;
foreach ( $posts as $temp_key => $post_id ) {
if ( $count == 1000 ) {
$option[$action] = $posts;
update_option( 'wpcf_checkbox_migration', $option );
$data = array('offset' => $temp_key);
return $data;
}
delete_post_meta( $post_id, $meta_key, 0 );
unset( $posts[$temp_key] );
$count++;
}
unset( $option[$action] );
update_option( 'wpcf_checkbox_migration', $option );
return $posts;
} else if ( $action == 'save' ) {
$count = 0;
foreach ( $posts as $temp_key => $post_id ) {
if ( $count == 1000 ) {
$option[$action] = $posts;
update_option( 'wpcf_checkbox_migration', $option );
$data = array('offset' => $temp_key);
return $data;
}
update_post_meta( $post_id, $meta_key, 0 );
unset( $posts[$temp_key] );
$count++;
}
unset( $option[$action] );
update_option( 'wpcf_checkbox_migration', $option );
return $posts;
}
}
return false;
}
/**
* Gets all filters required for field to be used.
*
* @param type $field
* @return boolean|string
*/
function wpcf_admin_fields_get_filter_by_field( $field ) {
$field = wpcf_admin_fields_get_field( $field );
if ( empty( $field ) ) {
return false;
}
$filter = array();
$filter['types'] = array();
$filter['terms'] = array();
$filter['templates'] = array();
$groups = wpcf_admin_fields_get_groups_by_field( $field['id'] );
foreach ( $groups as $group_id => $group_data ) {
// Get filters
$filter['types'] = array_merge( $filter['types'],
explode( ',',
trim( get_post_meta( $group_id,
'_wp_types_group_post_types', true ),
',' ) ) );
$filter['terms'] = array_merge( $filter['terms'],
explode( ',',
trim( get_post_meta( $group_id, '_wp_types_group_terms',
true ), ',' ) ) );
$filter['templates'] = array_merge( $filter['templates'],
explode( ',',
trim( get_post_meta( $group_id,
'_wp_types_group_templates', true ), ',' ) ) );
$filter['association'] = isset( $group_data['filters_association'] ) && $group_data['filters_association'] == 'any' ? 'OR' : 'AND';
}
if ( in_array( 'all', $filter['types'] ) ) {
$filter['types'] = 'all';
}
if ( in_array( 'all', $filter['terms'] ) ) {
$filter['terms'] = 'all';
}
if ( in_array( 'all', $filter['templates'] ) ) {
$filter['templates'] = 'all';
}
return $filter;
}
/**
* Gets posts by filter fetched with wpcf_admin_fields_get_filter_by_field().
*
* @global type $wpdb
* @param type $filter
* @return type
*/
function wpcf_admin_fields_get_posts_by_filter( $filter, $meta_query = '' ) {
global $wpdb, $wpcf;
$query = array();
$join = array();
if ( $filter['types'] != 'all' && !empty( $filter['types'] ) ) {
$query[] = 'p.post_type IN (\'' . implode( '\',\'', $filter['types'] ) . '\')';
} else {
$post_types = get_post_types( array('show_ui' => true), 'names' );
foreach ( $post_types as $post_type_slug => $post_type ) {
if ( in_array( $post_type_slug, $wpcf->excluded_post_types ) ) {
unset( $post_types[$post_type_slug] );
}
}
$query[] = 'p.post_type IN (\'' . implode( '\',\'', $post_types ) . '\')';
}
if ( $filter['terms'] != 'all' && !empty( $filter['terms'] ) ) {
$ttid = array();
foreach ( $filter['terms'] as $term_id ) {
$term_taxonomy_id = $wpdb->get_var( $wpdb->prepare( "SELECT term_taxonomy_id FROM $wpdb->term_taxonomy WHERE term_id=%d",
$term_id ) );
if ( !empty( $term_taxonomy_id ) ) {
$ttid[] = $term_taxonomy_id;
}
}
$query[] = 't.term_taxonomy_id IN (\'' . implode( '\',\'', $ttid ) . '\')';
$join[] = "LEFT JOIN $wpdb->term_relationships t ON p.ID = t.object_id ";
}
if ( $filter['templates'] != 'all' && !empty( $filter['templates'] ) ) {
$query[] = '(m.meta_key = \'_wp_page_template\' AND m.meta_value IN (\'' . implode( '\',\'',
$filter['templates'] ) . '\'))';
}
if ( !empty( $meta_query )
|| ($filter['templates'] != 'all' && !empty( $filter['templates'] )) ) {
$join[] = "LEFT JOIN $wpdb->postmeta m ON p.ID = m.post_id ";
}
$_query = "SELECT p.ID FROM $wpdb->posts p " . implode( '', $join );
if ( !empty( $query ) ) {
$_query .= "WHERE " . implode( ' ' . $filter['association'] . ' ',
$query ) . ' ';
if ( !empty( $meta_query ) ) {
$_query .= ' AND ' . $meta_query . ' ';
}
} else if ( !empty( $meta_query ) ) {
$_query .= "WHERE " . $meta_query . ' ';
}
$_query .= "GROUP BY p.ID";
$posts = $wpdb->get_col( $_query );
return $posts;
}
/**
* Gets posts by filter with missing meta fetched
* with wpcf_admin_fields_get_filter_by_field().
*
* @global type $wpdb
* @param type $filter
* @return type
*/
function wpcf_admin_fields_get_posts_by_filter_missing_meta( $filter,
$meta_key = '' ) {
global $wpdb, $wpcf;
$query = array();
$join = array();
if ( $filter['types'] != 'all' && !empty( $filter['types'] ) ) {
$query[] = 'p.post_type IN (\'' . implode( '\',\'', $filter['types'] ) . '\')';
} else {
$post_types = get_post_types( array('show_ui' => true), 'names' );
foreach ( $post_types as $post_type_slug => $post_type ) {
if ( in_array( $post_type_slug, $wpcf->excluded_post_types ) ) {
unset( $post_types[$post_type_slug] );
}
}
$query[] = 'p.post_type IN (\'' . implode( '\',\'', $post_types ) . '\')';
}
if ( $filter['terms'] != 'all' && !empty( $filter['terms'] ) ) {
$ttid = array();
foreach ( $filter['terms'] as $term_id ) {
$term_taxonomy_id = $wpdb->get_var( $wpdb->prepare( "SELECT term_taxonomy_id FROM $wpdb->term_taxonomy WHERE term_id=%d",
$term_id ) );
if ( !empty( $term_taxonomy_id ) ) {
$ttid[] = $term_taxonomy_id;
}
}
$query[] = 't.term_taxonomy_id IN (\'' . implode( '\',\'', $ttid ) . '\')';
$join[] = "LEFT JOIN $wpdb->term_relationships t ON p.ID = t.object_id ";
}
if ( $filter['templates'] != 'all' && !empty( $filter['templates'] ) ) {
$query[] = '(m.meta_key = \'_wp_page_template\' AND m.meta_value IN (\'' . implode( '\',\'',
$filter['templates'] ) . '\'))';
$join[] = "LEFT JOIN $wpdb->postmeta m ON p.ID = m.post_id ";
}
$_query = "SELECT DISTINCT p.ID FROM $wpdb->posts p " . implode( '', $join );
$_query .= "WHERE NOT EXISTS (SELECT * FROM $wpdb->postmeta mm WHERE p.ID = mm.post_id AND mm.meta_key = '$meta_key')";
if ( !empty( $query ) ) {
$_query .= "AND (" . implode( ' ' . $filter['association'] . ' ', $query ) . ') ';
}
$_query .= "GROUP BY p.ID";
$posts = $wpdb->get_col( $_query );
return $posts;
}
/**
* Check how many posts needs checkboxes update.
*
* @param type $field
* @param type $action
* @return boolean|int
*/
function wpcf_admin_fields_checkboxes_migrate_empty_check( $field, $action ) {
if ( $field['type'] != 'checkboxes' || empty( $field['data']['options'] ) ) {
return false;
}
if ( $field['meta_type'] == 'usermeta' ) {
global $wpdb;
if ( $action == 'do_not_save_check' ) {
$query = array();
foreach ( $field['data']['options'] as $option_id => $option_data ) {
// $query[] = '\"' . $option_id . '\";s:1:\"0\";';
$query[] = '\"' . $option_id . '\";i:0;';
}
$meta_query = "SELECT u.ID FROM {$wpdb->users} u
LEFT JOIN {$wpdb->usermeta} um ON u.ID = um.user_id
WHERE (um.meta_key = '%s' AND (um.meta_value LIKE '%%"
. implode( "%%' OR um.meta_value LIKE '%%", $query ) . "%%'))";
} else if ( $action == 'save_check' ) {
$query = array();
foreach ( $field['data']['options'] as $option_id => $option_data ) {
// $query[] = '\"' . $option_id . '\";s:1:\"0\";';
// Check only if missing
$query[] = '\"' . $option_id . '\"';
}
$meta_query = "SELECT u.ID FROM {$wpdb->users} u
LEFT JOIN {$wpdb->usermeta} um ON u.ID = um.user_id
WHERE (um.meta_key = '%s' AND (um.meta_value NOT LIKE '%%"
. implode( "%%' OR um.meta_value NOT LIKE '%%", $query ) . "%%'))";
}
$users = $wpdb->get_col( $wpdb->prepare( $meta_query, $field['meta_key'] ) );
$option = get_option( 'wpcf_checkboxes_migration_usermeta', array() );
$cache_key = $action == 'do_not_save_check' ? 'do_not_save' : 'save';
$option[$field['meta_key']][$cache_key] = $users;
update_option( 'wpcf_checkboxes_migration_usermeta', $option );
return $users;
}
$filter = wpcf_admin_fields_get_filter_by_field( $field['id'] );
if ( !empty( $filter ) ) {
$posts = array();
$meta_key = wpcf_types_get_meta_prefix( $field ) . $field['id'];
$meta_query = '';
// "wpcf-fields-checkboxes-option-1873650245";s:1:"1";
if ( $action == 'do_not_save_check' ) {
$query = array();
foreach ( $field['data']['options'] as $option_id => $option_data ) {
$query[] = '\"' . $option_id . '\";i:0;';
}
$meta_query = "(m.meta_key = '$meta_key' AND (m.meta_value LIKE '%%"
. implode( "%%' OR m.meta_value LIKE '%%", $query ) . "%%'))";
$posts = wpcf_admin_fields_get_posts_by_filter( $filter, $meta_query );
} else if ( $action == 'save_check' ) {
$query = array();
foreach ( $field['data']['options'] as $option_id => $option_data ) {
// Check only if missing
$query[] = '\"' . $option_id . '\"';
}
$meta_query = "(m.meta_key = '$meta_key' AND (m.meta_value NOT LIKE '%%"
. implode( "%%' OR m.meta_value NOT LIKE '%%", $query ) . "%%'))";
$posts = wpcf_admin_fields_get_posts_by_filter( $filter, $meta_query );
}
$option = get_option( 'wpcf_checkboxes_migration', array() );
$cache_key = $action == 'do_not_save_check' ? 'do_not_save' : 'save';
$option[$cache_key] = $posts;
update_option( 'wpcf_checkboxes_migration', $option );
return $posts;
}
return false;
}
/**
* Update posts checkboxes fields.
*
* @param type $field
* @param type $action
* @return boolean|int
*/
function wpcf_admin_fields_checkboxes_migrate_empty( $field, $action ) {
if ( $field['type'] != 'checkboxes' || empty( $field['data']['options'] ) ) {
return false;
}
if ( $field['meta_type'] == 'usermeta' ) {
$option = get_option( 'wpcf_checkboxes_migration_usermeta', array() );
if ( empty( $option[$field['meta_key']][$action] ) ) {
$users = wpcf_admin_fields_checkboxes_migrate_empty_check( $field,
$action . '_check' );
} else {
$users = $option[$field['meta_key']][$action];
}
if ( !empty( $users ) ) {
if ( $action == 'do_not_save' ) {
$count = 0;
foreach ( $users as $temp_key => $user_id ) {
if ( $count == 1000 ) {
$option[$field['meta_key']][$action] = $users;
update_option( 'wpcf_checkboxes_migration_usermeta', $option );
$data = array('offset' => $temp_key);
return $data;
}
$meta_saved = get_user_meta( $user_id, $field['meta_key'] );
if ( !empty( $meta_saved ) ) {
foreach ( $meta_saved as $key => $value ) {
if ( !is_array( $value ) ) {
$value_check = array();
} else {
$value_check = $value;
}
foreach ( $field['data']['options'] as $option_id => $option_data ) {
if ( isset( $value_check[$option_id] ) && $value_check[$option_id] == '0' ) {
unset( $value_check[$option_id] );
}
}
update_user_meta( $user_id, $field['meta_key'], $value_check,
$value );
}
}
unset( $users[$temp_key] );
$count++;
}
unset( $option[$field['meta_key']][$action] );
update_option( 'wpcf_checkboxes_migration_usermeta', $option );
return $users;
} else if ( $action == 'save' ) {
$count = 0;
foreach ( $users as $temp_key => $user_id ) {
if ( $count == 1000 ) {
$option[$field['meta_key']][$action] = $users;
update_option( 'wpcf_checkboxes_migration_usermeta', $option );
$data = array('offset' => $temp_key);
return $data;
}
$meta_saved = get_user_meta( $user_id, $field['meta_key'] );
if ( !empty( $meta_saved ) ) {
foreach ( $meta_saved as $key => $value ) {
if ( !is_array( $value ) ) {
$value_check = array();
} else {
$value_check = $value;
}
$set_value = array();
foreach ( $field['data']['options'] as $option_id => $option_data ) {
if ( !isset( $value_check[$option_id] ) ) {
$set_value[$option_id] = 0;
}
}
$updated_value = $value_check + $set_value;
update_user_meta( $user_id, $field['meta_key'],
$updated_value, $value );
}
}
unset( $users[$temp_key] );
$count++;
}
unset( $option[$field['meta_key']][$action] );
update_option( 'wpcf_checkboxes_migration_usermeta', $option );
return $users;
}
}
return false;
}
$option = get_option( 'wpcf_checkboxes_migration', array() );
$meta_key = wpcf_types_get_meta_prefix( $field ) . $field['id'];
if ( empty( $option[$action] ) ) {
$posts = wpcf_admin_fields_checkboxes_migrate_empty_check( $field,
$action . '_check' );
} else {
$posts = $option[$action];
}
if ( !empty( $posts ) ) {
if ( $action == 'do_not_save' ) {
$count = 0;
foreach ( $posts as $temp_key => $post_id ) {
if ( $count == 1000 ) {
$option[$action] = $posts;
update_option( 'wpcf_checkboxes_migration', $option );
$data = array('offset' => $temp_key);
return $data;
}
$meta_saved = get_post_meta( $post_id, $meta_key );
if ( !empty( $meta_saved ) ) {
foreach ( $meta_saved as $key => $value ) {
if ( !is_array( $value ) ) {
$value_check = array();
} else {
$value_check = $value;
}
foreach ( $field['data']['options'] as $option_id =>
$option_data ) {
if ( isset( $value_check[$option_id] ) && $value_check[$option_id] == '0' ) {
unset( $value_check[$option_id] );
}
}
update_post_meta( $post_id, $meta_key, $value_check, $value );
}
}
unset( $posts[$temp_key] );
$count++;
}
unset( $option[$action] );
update_option( 'wpcf_checkboxes_migration', $option );
return $posts;
} else if ( $action == 'save' ) {
$count = 0;
foreach ( $posts as $temp_key => $post_id ) {
if ( $count == 1000 ) {
$option[$action] = $posts;
update_option( 'wpcf_checkboxes_migration', $option );
$data = array('offset' => $temp_key);
return $data;
}
$meta_saved = get_post_meta( $post_id, $meta_key );
if ( !empty( $meta_saved ) ) {
foreach ( $meta_saved as $key => $value ) {
if ( !is_array( $value ) ) {
$value_check = array();
} else {
$value_check = $value;
}
$set_value = array();
foreach ( $field['data']['options'] as $option_id =>
$option_data ) {
if ( !isset( $value_check[$option_id] ) ) {
$set_value[$option_id] = 0;
}
}
$updated_value = $value_check + $set_value;
update_post_meta( $post_id, $meta_key, $updated_value, $value );
}
}
unset( $posts[$temp_key] );
$count++;
}
unset( $option[$action] );
update_option( 'wpcf_checkboxes_migration', $option );
return $posts;
}
}
return false;
}
function wpcf_admin_fields_form_fix_styles()
{
$suffix = SCRIPT_DEBUG ? '' : '.min';
wp_enqueue_style(
'wpcf-dashicons',
site_url( "/wp-includes/css/dashicons$suffix.css" )
);
}
|
/* Copyright (C) 1991, 1995, 1996, 1997, 2002 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
#include <errno.h>
#include <sys/socket.h>
/* Put the local address of FD into *ADDR and its length in *LEN. */
int
__getsockname (fd, addr, len)
int fd;
__SOCKADDR_ARG addr;
socklen_t *len;
{
__set_errno (ENOSYS);
return -1;
}
weak_alias (__getsockname, getsockname)
stub_warning (getsockname)
#include <stub-tag.h>
|
//*****************************************************************************
//*****************************************************************************
// FILENAME: Driver.h
// TrueTouch Host Emulator Version Information: 3.2.1823
// TrueTouch Firmware Version Information: 0.6.485370
//
// DESCRIPTION: This file contains configuration values.
//-----------------------------------------------------------------------------
// Copyright (c) Cypress Semiconductor 2012. All Rights Reserved.
//*****************************************************************************
//*****************************************************************************
//-----------------------------------------------------------------------------
/* Touchscreen Version Information */
static u8 ttconfig_fw_ver[] = {
0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0B, 0x34, 0x91, 0x0B, 0x00, 0x11, 0x9B, 0x00, 0x02
};
#if 0
/* Touchscreen Parameters Endianess (Endianess: 0:Little; 1:Big)*/
static const uint8_t cyttsp5_param_endianess = 0;
#endif
/* Touchscreen Parameters */
static const uint8_t cyttsp5_param_regs[] = {
/* Value Name */
0x1C, 0x04, /* CONFIG_DATA_SIZE */
0x1C, 0x04, /* CONFIG_DATA_MAX_SIZE */
0xD0, 0x02, /* X_RESOLUTION */
0x00, 0x05, /* Y_RESOLUTION */
0xCE, 0x18, /* X_LEN_PHY */
0xAC, 0x2B, /* Y_LEN_PHY */
0x2B, 0x01, /* CROSS_NUM */
0x17, /* TX_NUM */
0x0D, /* RX_NUM */
0x24, /* SENS_NUM */
0x00, /* SENSOR_ASSIGNMENT */
0x00, /* PROXIMITY_SCAN_AXIS */
0x01, /* BL_H20_RJCT */
0x00, /* CHARGER_ARMOR_ENABLE */
0x01, /* TOUCHMODE_ENABLED */
0x02, /* LRG_OBJ_CFG */
0x00, /* BUTTON_NUM */
0x02, /* PROXIMITY_GRIP_SUPPRESSION_SIZE */
0x0A, /* MAX_NUM_OF_REPORTED_TOUCHES */
0x0A, /* MAX_NUM_OF_SUPPORTED_TOUCHES */
0x03, /* SCANNING_MODE_BUTTON */
0x08, /* OPMODE_CFG */
0x01, /* SELF_Z_MODE */
0x00, /* WF_ENABLE */
0x01, /* PALM_DETECTION_ENABLE */
0x00, 0x00, 0x00, 0x00, /* PQ_CTRL */
0x00, 0x00, 0x00, 0x00, /* PQ_CTRL2 */
0x00, 0x00, 0x00, 0x00, /* PQ_CTRL3 */
0x00, 0xB0, 0x0B, 0xA0, /* REFGEN_CTL */
0x00, 0x00, 0xFF, 0x80, /* TX_CTRL */
0x00, 0x00, 0x27, 0x00, /* RX_CTRL */
0x00, 0x20, 0x00, 0x00, /* INFRA_CTRL */
0x64, /* STARTUP_DELAY */
0x00, /* FORCE_SINGLE_TX */
0x01, /* SLOTS_MUT */
0x01, /* SLOTS_SELF_RX */
0x02, /* SLOTS_SELF_TX */
0x03, /* SLOTS_SELF */
0x5E, 0x01, /* SCALING_FACTOR_MUTUAL */
0x2C, 0x01, /* SCALING_FACTOR_SELF */
0xC8, 0x00, /* SCALING_FACTOR_BUTTON_MUTUAL */
0xC8, 0x00, /* SCALING_FACTOR_BUTTON_SELF */
0xC8, 0x00, /* SCALING_FACTOR_PROXIMITY */
0x02, /* TX_PUMP_VOLTAGE */
0x50, /* DISCARD_TIME */
0x00, /* VDDA_MODE */
0x00, /* BUTTON_LAYOUT */
0x04, /* MTX_ORDER */
0x00, /* Reserved81 */
0x02, /* TX_FREQ_METHOD_MUTUAL */
0x00, /* TX_FREQ_METHOD_SELF */
0x2D, 0x00, /* CA_WIDEBAND_TX_PERIOD */
0x01, /* CA_WIDEBAND_TX_PERIOD_DITHER */
0x18, /* IDAC_WB */
0x00, /* RX_ATTEN_RES_BYPASS */
0x19, /* SAFE_RAW_RANGE_PERCENT_MUTUAL */
0x32, /* SAFE_RAW_RANGE_PERCENT_SELF */
0x32, /* SAFE_RAW_RANGE_PERCENT_BTN_MUTUAL */
0x32, /* SAFE_RAW_RANGE_PERCENT_BTN_SELF */
0x00, /* Reserved93 */
0xFA, 0x00, /* INTEGRATOR_VOLTAGE_MUTUAL */
0xFA, 0x00, /* INTEGRATOR_VOLTAGE_SELF */
0xFA, 0x00, /* INTEGRATOR_VOLTAGE_BUTTON_MUTUAL */
0xFA, 0x00, /* INTEGRATOR_VOLTAGE_BUTTON_SELF */
0x1E, /* BALANCING_TARGET_MUTUAL */
0x32, /* BALANCING_TARGET_SELF */
0x1E, /* BALANCING_TARGET_BUTTON_MUTUAL */
0x1E, /* BALANCING_TARGET_BUTTON_SELF */
0xD0, 0x07, /* ILEAK_MAX */
0xB8, 0x0B, /* OPENS_TEST_RAW_THRESHOLD_MUTUAL */
0x4C, 0x04, /* OPENS_TEST_RAW_THRESHOLD_BUTTON */
0x67, /* OPENS_TEST_IDAC_MUTUAL */
0x08, /* OPENS_TEST_ATTEN_MUTUAL */
0x7F, /* OPENS_TEST_IDAC_BUTTON */
0x08, /* OPENS_TEST_ATTEN_BUTTON */
0xFF, /* Reserved116 */
0xFF, /* Reserved117 */
0xFF, /* Reserved118 */
0xFF, /* Reserved119 */
0xC8, 0x00, /* TX_PERIOD_MUTUAL */
0x40, 0x00, /* TX_PULSES_NUM_MUTUAL */
0x3D, 0x00, /* CA_TX_PERIOD_MUTUAL */
0x7F, 0x00, /* CA_BASE_TX_PULSES_NUM_MUTUAL */
0x30, 0x00, /* CA_HOP0_TX_PERIOD_MUTUAL */
0x7F, 0x00, /* CA_HOP0_TX_PULSES_NUM_MUTUAL */
0x38, 0x00, /* CA_HOP1_TX_PERIOD_MUTUAL */
0x7F, 0x00, /* CA_HOP1_TX_PULSES_NUM_MUTUAL */
0x3C, 0x00, /* CA_HOP2_TX_PERIOD_MUTUAL */
0x7F, 0x00, /* CA_HOP2_TX_PULSES_NUM_MUTUAL */
0x3F, 0x00, /* CA_HOP3_TX_PERIOD_MUTUAL */
0x7F, 0x00, /* CA_HOP3_TX_PULSES_NUM_MUTUAL */
0x4B, 0x00, /* CA_HOP4_TX_PERIOD_MUTUAL */
0x7F, 0x00, /* CA_HOP4_TX_PULSES_NUM_MUTUAL */
0xC8, 0x00, /* TX_PERIOD_SELF */
0x40, 0x00, /* TX_PULSES_NUM_SELF */
0x3D, 0x00, /* TX_PERIOD_BTN_MUTUAL */
0x40, 0x00, /* TX_PULSES_NUM_BUTTON_MUTUAL */
0xA0, 0x00, /* TX_PERIOD_BTN_SELF */
0x20, 0x00, /* TX_PULSES_NUM_BUTTON_SELF */
0xA0, 0x00, /* TX_PERIOD_PROX */
0x40, 0x00, /* TX_PULSES_NUM_PROXIMITY */
0x3D, 0x00, /* TX_PERIOD_GLOVE_MUTUAL */
0x40, 0x00, /* TX_PULSES_NUM_GLOVE_MUTUAL */
0xA0, 0x00, /* TX_PERIOD_GLOVE_SELF */
0x40, 0x00, /* TX_PULSES_NUM_GLOVE_SELF */
0x3D, 0x00, /* TX_PERIOD_GLOVE_BUTTON_MUTUAL */
0x40, 0x00, /* TX_PULSES_NUM_GLOVE_BUTTON_MUTUAL */
0xA0, 0x00, /* TX_PERIOD_GLOVE_BUTTON_SELF */
0x20, 0x00, /* TX_PULSES_NUM_GLOVE_BUTTON_SELF */
0x00, 0xF8, 0xFF, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0xFF, 0x07, 0x00, 0xFF,
0x0F, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0xFF, 0xFF, 0xFF, 0xFF,
0x0F, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, /* CDC_SENSOR_MASKS */
0x17, 0x16, 0x15, 0x14,
0x13, 0x12, 0x11, 0x10,
0x0F, 0x0E, 0x0D, 0x0C,
0x0B, 0x18, 0x19, 0x1A,
0x1B, 0x1C, 0x1D, 0x1E,
0x1F, 0x20, 0x21, 0x22,
0x23, 0x0A, 0x09, 0x08,
0x07, 0x06, 0x05, 0x04,
0x03, 0x02, 0x01, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, /* CDC_PIN_INDEX_TABLE */
0x00, 0x00, 0x00, /* Reserved269 */
0x07, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, /* CDC_MTX_PHASE_VECTOR */
0x00, 0x20, 0x00, 0x20,
0x00, 0x20, 0x00, 0xE0,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, /* CDC_MTX_DECONV_COEF */
0x00, 0xF8, 0xFF, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0xFF, 0x1F, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x0B, 0x0D, 0x0C, 0x0B,
0x0A, 0x09, 0x08, 0x07,
0x06, 0x05, 0x04, 0x03,
0x02, 0x01, 0x00, 0xFF,
0x7F, 0x00, 0x00, 0x7F,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0xFF, 0x3F, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x04, 0x0E, 0x1F, 0x1E,
0x1D, 0x23, 0x22, 0x21,
0x20, 0x0E, 0x0F, 0x10,
0x11, 0x12, 0x13, 0x0D,
0x80, 0x07, 0x00, 0x80,
0x0F, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0xF8, 0x27, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0xFF, 0x09, 0xFF, 0xFF,
0xFF, 0x1C, 0x1B, 0x1A,
0x19, 0x15, 0x16, 0x17,
0x18, 0xFF, 0xFF, 0x14,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0xFF, 0x00, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, /* CDC_SLOT_TABLE */
0x80, 0x0C, /* MAX_SELF_SIG_THRESHOLD */
0x08, 0x07, /* MAX_POSITIVE_THRESHOLD */
0x03, /* BL_DELAY_BTN */
0x0A, /* BL_THRESHOLD_MUT */
0x0A, /* BL_THRESHOLD_SELF */
0x07, /* RATIO_MAXMUT_TO_MAXSELF */
0x1E, /* MIN_POSITIVE_THRESHOLD */
0x07, /* RATIO_SUMALL_TO_POSITIVE */
0x05, /* COUNTS_TO_BL_RESET_MUT */
0x05, /* COUNTS_TO_BL_RESET_SELF */
0x50, /* BL_FILT_BTN_MUT */
0x50, /* BL_FILT_BTN_SELF */
0xC8, 0x00, /* SELF_LIFTOFF_THRESHOLD */
0x0A, /* BASELINE_DELAY */
0x0A, /* DEBOUNCE_BASELINE_AFTER_REMOVE */
0x14, /* SLOW_BL_THRSH */
0x02, /* SLOW_BL_SS */
0xC8, /* FAST_BL_THRSH */
0x02, /* FAST_BL_SS */
0xF4, 0x01, /* WIPE_RESET_COUNTER */
0xF4, 0x01, /* DECREASE_BY_WATER */
0x90, 0x01, /* PREV_RAW_FRAME_NUM */
0x02, 0x00, /* WIPE_DELAY */
0x64, 0x00, /* DROP_RESET_COUNTER */
0xC0, 0x27, 0x09, 0x00, /* WATER_TIMEOUT */
0x05, 0x00, /* INIT_BL_DELAY */
0xE8, 0x03, /* TOUCH_THRESHOLD */
0x64, 0x00, /* BL_FRAME_NUM_AFTER_LIFTOFF */
0x00, /* Reserved570 */
0x00, /* Reserved571 */
0x64, 0x00, /* MAX_MUTUAL_SCAN_INTERVAL */
0x64, 0x00, /* MAX_SELF_SCAN_INTERVAL */
0x0A, 0x00, /* BL_BTN_THRSH_MUT */
0x0A, 0x00, /* BL_BTN_THRSH_SELF */
0x0A, 0x00, /* BL_BTN_THRSH_MUT_CA */
0x0A, 0x00, /* BL_BTN_THRSH_MUT_GLOVE */
0x0A, 0x00, /* BL_BTN_THRSH_SELF_GLOVE */
0x00, 0x00, /* Reserved586 */
0x03, /* CMF_DELTA_TEMPCO_INCREMENT */
0x00, /* Reserved589 */
0x00, /* Reserved590 */
0x00, /* Reserved591 */
0x00, /* Reserved592 */
0x00, /* Reserved593 */
0xDC, 0x05, /* WF_RAW_VAR_THOLD */
0xAC, 0x0D, /* WF_RAW_HIGH_THOLD */
0xF4, 0x01, /* WF_DIFF_VAR_THOLD */
0xFA, 0x00, /* WF_RAW_CALC_THOLD */
0xC8, 0x00, /* WF_DIFF_CALC_THOLD */
0x03, /* FILT_FILTER_MASK */
0x01, /* FILT_IIR_COEFF_MUT */
0x55, 0x00, /* FILT_IIR_THRESHOLD_MUT */
0x4B, 0x00, /* FILT_CMF_THRESHOLD_MUT */
0x03, /* FILT_FILTER_MASK_BASE_SELF */
0x01, /* FILT_IIR_COEFF_SELF */
0x28, 0x00, /* FILT_IIR_THRESHOLD_SELF */
0x1E, 0x00, /* CMF_THR_SELF */
0x03, /* FILT_FILTER_MASK_BTN_MUT */
0x01, /* FILT_IIR_COEFF_BUT */
0x14, 0x00, /* FILT_IIR_THRESHOLD_BUT */
0x3C, 0x00, /* CMF_THR_BTN_MUT */
0x03, /* FILT_FILTER_MASK_BTN_SELF */
0x01, /* FILT_IIR_COEFF_BUT_BASE_SELF */
0x14, 0x00, /* FILT_IIR_THRESHOLD_BUT_BASE_SELF */
0x3C, 0x00, /* CMF_THR_BTN_SELF */
0x03, /* FILT_FILTER_MASK_PROX */
0x01, /* IIR_COEF */
0x14, 0x00, /* IIR_THRESHOLD */
0x3C, 0x00, /* FILT_CMF_THRESHOLD_PROX */
0x03, /* CAFILT_FILTER_MASK */
0x01, /* CAFILT_IIR_COEFF_MUT */
0x14, 0x00, /* CAFILT_IIR_THRESHOLD_MUT */
0x3C, 0x00, /* CAFILT_CMF_THRESHOLD_MUT */
0x03, /* CAFILT_FILT_BTN_MUT */
0x01, /* CAFILT_IIR_COEFF_BUT */
0x14, 0x00, /* CAFILT_IIR_THRESHOLD_BUT */
0x3C, 0x00, /* CAFILT_CMF_THRESHOLD_BUT_MUT */
0x03, /* FILT_FILTER_MASK_GLOVE_MUT */
0x01, /* FILT_IIR_COEFF_GLOVE_MUT */
0x14, 0x00, /* FILT_IIR_THRESHOLD_GLOVE_MUT */
0x3C, 0x00, /* FILT_CMF_THRESHOLD_GLOVE_MUT */
0x03, /* FILT_FILTER_MASK_GLOVE_SELF */
0x01, /* FILT_IIR_COEFF_GLOVE_SELF */
0x14, 0x00, /* FILT_IIR_THRESHOLD_GLOVE_SELF */
0x3C, 0x00, /* FILT_CMF_THRESHOLD_GLOVE_SELF */
0x03, /* FILT_FILTER_MASK_BUT_GLOVE_MUT */
0x01, /* FILT_IIR_COEFF_BUT_GLOVE_MUT */
0x14, 0x00, /* FILT_IIR_THRESHOLD_BUT_GLOVE_MUT */
0x3C, 0x00, /* FILT_CMF_THRESHOLD_GLOVE_BUT_MUT */
0x03, /* FILT_FILTER_MASK_BUT_GLOVE_SELF */
0x01, /* FILT_IIR_COEFF_BUT_GLOVE_SELF */
0x14, 0x00, /* FILT_IIR_THRESHOLD_BUT_GLOVE_SELF */
0x3C, 0x00, /* FILT_CMF_THRESHOLD_GLOVE_BUT_SELF */
0x00, /* FILT_FILTER_MASK_NOFILT */
0x00, /* FILT_IIR_COEFF_NOFILT */
0x14, 0x00, /* FILT_IIR_THRESHOLD_NOFILT */
0x3C, 0x00, /* FILT_CMF_THRESHOLD_NOFILT */
0x00, /* CA_HOST_CONTROLLED_CHARGER */
0x00, /* CHARGER_STATUS */
0x06, /* AFH_LISTEN_SCAN_CYCLE_REPEATS */
0x06, /* AFH_LISTENING_SCAN_COUNT */
0xB4, 0x00, /* CA_INJTCH_MAGNITUDE */
0x5A, 0x00, /* CA_INJTCH_FINGER_THOLD */
0xE8, 0x03, 0x00, 0x00, /* CA_DEFAULT_REVERT_TIME */
0x0F, 0x00, /* DETECT_CHARGER_THRESHOLD */
0x0F, 0x00, /* NM_INJ_TCH_THRESHOLD */
0x01, /* CA_WB_CMF_ENABLE */
0x0F, /* CA_WB_REVERT_THOLD */
0x00, /* TRIGGER_CA */
0x4B, /* CA_DYN_CAL_NUM_SENSOR_THLD_PERCENT */
0x1A, 0x00, /* CA_DYN_CAL_SAFE_RAW_RANGE */
0x00, 0x80, /* CA_MIN_SELF_ALLOWED */
0x01, /* ACT_LFT_EN */
0x28, /* INNER_EDGE_GAIN */
0x78, /* OUTER_EDGE_GAIN */
0x08, /* ACT_INTRVL0 */
0x03, 0x00, /* ACT_LFT_INTRVL0 */
0x64, 0x00, /* LP_INTRVL0 */
0xE8, 0x03, /* TCH_TMOUT0 */
0xC8, 0x00, /* FINGER_THRESH_SELF */
0x28, 0x00, /* GLOVE_THRSH_SELF */
0x01, /* LOW_POWER_ENABLE */
0x00, /* Reserved715 */
0x00, /* ACT_DIST0 */
0x00, /* ACT_DIST2 */
0x00, /* ACT_DIST_TOUCHDOWN */
0x00, /* ACT_DIST_LIFTOFF */
0x00, /* ACT_DIST_COUNTER */
0xFF, /* ACT_DIST_Z_THRESHOLD */
0x00, /* FIRST_TOUCH_SUPPRESSION */
0x00, /* OBJ_WITHHOLD_CFG */
0x01, /* ACTIVE_DELTA_Z */
0x02, /* MAX_ACCEPTED_FINGER */
0x00, 0x00, /* Reserved726 */
0x04, 0x17, 0x03, 0x00, /* FINGER_ID_MAX_FINGER_VELOCITY2 */
0x00, 0x00, /* GRIP_XEDG_A */
0x00, 0x00, /* GRIP_XEDG_B */
0x00, 0x00, /* GRIP_XEXC_A */
0x00, 0x00, /* GRIP_XEXC_B */
0x00, 0x00, /* GRIP_YEDG_A */
0x00, 0x00, /* GRIP_YEDG_B */
0x00, 0x00, /* GRIP_YEXC_A */
0x00, 0x00, /* GRIP_YEXC_B */
0x01, /* GRIP_FIRST_EXC */
0x00, /* GRIP_EXC_EDGE_ORIGIN */
0x00, /* GRIP_ENABLE */
0x00, /* LIFTOFF_DEBOUNCE */
0x00, /* LIFTOFF_DEBOUNCE_PROXIMITY */
0x00, /* LIFTOFF_DEBOUNCE_STYLUS */
0x00, /* LIFTOFF_DEBOUNCE_HOVER */
0x00, /* GLOVE_LIFTOFF_DEBOUNCE */
0x00, 0x00, /* TOUCHMODE_GLOVE_SWITCH_DEBOUNCE */
0x00, 0x00, /* TOUCHMODE_FINGER_SWITCH_DEBOUNCE */
0x00, 0x00, /* TOUCHMODE_GLOVE_FINGER_SWITCH_DEBOUNCE */
0x00, 0x00, /* TOUCHMODE_GLOVE_EXIT_DELAY */
0x00, 0x00, /* TOUCHMODE_FINGER_EXIT_DELAY */
0x50, 0x00, /* SELF_Z_THRSH */
0x00, /* CLIPPING_X_LOW */
0x00, /* CLIPPING_X_HIGH */
0x00, /* CLIPPING_Y_LOW */
0x00, /* CLIPPING_Y_HIGH */
0x03, /* H2O_REJECTION_SNS_WIDTH */
0x00, /* SLIM_POSITION_OFFSET_ALONG_TX */
0x00, /* SLIM_POSITION_OFFSET_ALONG_RX */
0x03, /* LARGE_OBJECT_DEBOUNCE */
0x20, /* MAX_SELF_TX_RANGE */
0x20, /* MAX_SELF_RX_RANGE */
0x20, /* MAX_MUTUAL_TX_RANGE */
0x20, /* MAX_MUTUAL_RX_RANGE */
0x00, /* BR2_ALWAYS_ON_FLAG */
0x03, /* EDGE_DEBOUNCE_COUNT */
0x02, 0x00, /* CALC_THRESHOLD */
0x05, 0x00, /* OFFSET_S1 */
0x02, 0x00, /* OFFSET_S2 */
0x4A, 0x01, 0x00, 0x00, /* Z1_SUM_8MM */
0x82, 0x00, 0x00, 0x00, /* Z2_SUM_4MM */
0x4A, 0x01, 0x00, 0x00, /* Z1_SUM_3MM */
0x82, 0x00, 0x00, 0x00, /* Z2_SUM_1MM */
0x78, 0x00, 0x00, 0x00, /* LOW_PIVOT */
0xB4, 0x00, 0x00, 0x00, /* HIGH_PIVOT */
0x78, 0x00, 0x00, 0x00, /* LOW_PIVOT2 */
0xB4, 0x00, 0x00, 0x00, /* HIGH_PIVOT2 */
0x64, 0x00, /* EDGE_DEBOUNCE_COUNT_THRESHOLD */
0x78, 0x00, /* CENTER_MAGNITUDE_SCALE */
0x03, /* CENTROID_CORNER_NUMER */
0x04, /* CENTROID_CORNER_DENOM */
0x03, /* CENTROID_FINGER_MAX_JUMP */
0x68, /* GRADIENT_OUTER_EDGE_CONST_GAIN */
0x80, /* GRADIENT_OUTER_EDGE_CONST_RESPONSE */
0x40, /* GRADIENT_EDGE_COEF */
0x04, /* GRADIENT_COEF */
0x19, /* GRADIENT_THRESHOLD */
0x04, /* CORE_TO_CORNER_ZSUM_RATIO */
0x00, /* Reserved833 */
0x00, 0x00, /* Reserved834 */
0x60, 0xEA, 0x00, 0x00, /* MIN_FAT_FINGER_Z9 */
0x90, 0x5F, 0x01, 0x00, /* MAX_MULTI_FINGER_Z9 */
0x60, 0xEA, 0x00, 0x00, /* MIN_FAT_FINGER_SIG_SUM_ON_EDGE */
0x30, /* CENTER_SIGNAL_TO_MIN_PEAK_RATIO */
0x09, /* SD_SIZE_THRESHOLD */
0x9F, 0x24, /* SD_ENTER_SIGNAL_THRESHOLD */
0x45, 0x33, /* SD_EXIT_SIGNAL_THRESHOLD */
0xDC, 0x05, /* VIRTUAL_PEAK_DELTA_RESET_THRESHOLD */
0x30, 0x75, /* VIRTUAL_PEAK_DELTA_THRESHOLD */
0x05, /* FAT_AXIS_LENGTH_THRESHOLD */
0x00, /* TOUCH_IGNORE_COEFF */
0x10, 0x27, /* UPPER_THRSH */
0x20, 0x03, /* LOWER_THRSH */
0xC8, 0x00, /* OFF_THRSH */
0x64, 0x00, /* ACTIVE_SENSOR_THRESHOLD */
0xE8, 0x03, /* ACTIVE_SENSOR_THRESHOLD_FINGER */
0x0A, 0x00, /* DEBOUNCE_ON_DETECT_FINGER */
0x03, /* DEBOUNCE_ON_DETECT */
0x01, /* DEBOUNCE_AFTER_REMOVE */
0x1E, /* MAX_NUM_SHORT_SCAN */
0x08, /* SENSOR_NUM_THRSH */
0x04, /* SENSOR_NUM_THRSH_FINGER */
0x01, /* DISCARD_SCAN */
0x00, 0x00, /* Reserved878 */
0x2C, 0x01, /* FINGER_THRESH_MUTUAL_ON */
0xFA, 0x00, /* FINGER_THRESH_MUTUAL_OFF */
0x80, 0x00, /* Z_SCALING */
0x38, 0x00, /* CA_FINGER_THRESHOLD_MUTUAL */
0x00, /* MULTI_TOUCH_DEBOUNCE */
0x02, /* Z9_FILTER_SCALE */
0x05, /* CA_MULTI_TOUCH_DEBOUNCE */
0x04, /* CA_Z9_FILTER_SCALE */
0x01, /* MIN_FAT_FINGER_SIZE_HYST */
0x0A, /* MIN_FAT_FINGER_SIZE_ON */
0x01, /* MAX_FAT_FINGER_SIZE_HYST */
0x18, /* MAX_FAT_FINGER_SIZE_ON */
0x0F, /* CA_MIN_FAT_FINGER_SIZE */
0x28, /* CA_MAX_FAT_FINGER_SIZE */
0x03, /* TOUCH_TRACKING_FEATURES */
0x40, /* SIGNAL_THRESHOLD_MULTIPLIER */
0x40, /* WF_FT_COEF */
0x05, /* WF_MT_DEBOUNCE */
0x01, /* RX_LINE_FILTER */
0x02, /* RX_LINE_FILTER_DEBOUNCE */
0x58, /* RX_LINE_FILTER_THRESHOLD */
0x00, 0x00, 0x00, /* Reserved905 */
0x05, /* WF_Z8_MULTIPLIER */
0x00, 0x00, 0x00, /* Reserved909 */
0x50, /* BTN_LS_ON_THRSH_MUT_0 */
0x50, /* BTN_LS_ON_THRSH_MUT_1 */
0x50, /* BTN_LS_ON_THRSH_MUT_2 */
0x50, /* BTN_LS_ON_THRSH_MUT_3 */
0x46, /* BTN_LS_OFF_THRSH_MUT_0 */
0x46, /* BTN_LS_OFF_THRSH_MUT_1 */
0x46, /* BTN_LS_OFF_THRSH_MUT_2 */
0x46, /* BTN_LS_OFF_THRSH_MUT_3 */
0x41, /* BTN_LS_ON_THRSH_SELF_0 */
0x41, /* BTN_LS_ON_THRSH_SELF_1 */
0x41, /* BTN_LS_ON_THRSH_SELF_2 */
0x41, /* BTN_LS_ON_THRSH_SELF_3 */
0x28, /* BTN_LS_OFF_THRSH_SELF_0 */
0x28, /* BTN_LS_OFF_THRSH_SELF_1 */
0x28, /* BTN_LS_OFF_THRSH_SELF_2 */
0x28, /* BTN_LS_OFF_THRSH_SELF_3 */
0x00, 0x00, /* BTN_LS_TOUCHDOWN_DEBOUNCE */
0x00, 0x00, /* Reserved930 */
0x14, /* BTN_HS_ON_THRSH_MUT_0 */
0x14, /* BTN_HS_ON_THRSH_MUT_1 */
0x14, /* BTN_HS_ON_THRSH_MUT_2 */
0x14, /* BTN_HS_ON_THRSH_MUT_3 */
0x0A, /* BTN_HS_OFF_THRSH_MUT_0 */
0x0A, /* BTN_HS_OFF_THRSH_MUT_1 */
0x0A, /* BTN_HS_OFF_THRSH_MUT_2 */
0x0A, /* BTN_HS_OFF_THRSH_MUT_3 */
0x1E, /* BTN_HS_ON_THRSH_SELF_0 */
0x1E, /* BTN_HS_ON_THRSH_SELF_1 */
0x1E, /* BTN_HS_ON_THRSH_SELF_2 */
0x1E, /* BTN_HS_ON_THRSH_SELF_3 */
0x0A, /* BTN_HS_OFF_THRSH_SELF_0 */
0x0A, /* BTN_HS_OFF_THRSH_SELF_1 */
0x0A, /* BTN_HS_OFF_THRSH_SELF_2 */
0x0A, /* BTN_HS_OFF_THRSH_SELF_3 */
0x01, 0x00, /* BTN_HS_TOUCHDOWN_DEBOUNCE */
0x00, 0x00, /* Reserved950 */
0x0A, 0x00, /* GLOVE_BTN_FORBID_DEBOUNCE */
0x28, 0x00, /* GLOVE_BTN_TO_HIGHSEN_MODE_SWITCH_THRSH_MUT */
0x28, 0x00, /* GLOVE_BTN_TO_HIGHSEN_MODE_SWITCH_THRSH_SELF */
0xC8, 0x00, /* GLOVE_BTN_TO_LOWSEN_MODE_SWITCH_THRSH_MUT */
0x5E, 0x01, /* GLOVE_BTN_TO_LOWSEN_MODE_SWITCH_THRSH_SELF */
0x01, 0x00, /* GLOVE_BTN_MODE_SWITCH_DEBOUNCE */
0x00, /* BTN_PROCESS_IF_TOUCH_DETECTED */
0x00, /* Reserved965 */
0x00, 0x00, /* Reserved966 */
0xF4, 0x01, /* TOUCHMODE_GLOVE_MAX_PEAK */
0x3C, 0x00, /* GLOVE_ON_THRSH_MUTUAL */
0x32, 0x00, /* GLOVE_OFF_THRSH_MUTUAL */
0x02, /* GLOVE_FIRST_TOUCH_DEBOUNCE */
0x00, /* GLOVE_FIRST_TOUCH_DEBOUNCE_EDGE_MASK */
0x00, /* GLOVE_MULTI_TOUCH_DEBOUNCE */
0x01, /* GLOVE_Z8_FILTER_SCALE */
0x04, /* GLOVE_Z9_FILTER_SCALE */
0x04, /* GLOVE_GRIP_FILTER_SCALE */
0x0A, 0x00, /* GLOVE_Z_SCALING */
0x28, /* GLOVE_MAX_FAT_FINGER_SIZE */
0x00, /* GLOVE_MAX_FAT_FINGER_HYST */
0x0A, /* GLOVE_MIN_FAT_FINGER_SIZE */
0x00, /* GLOVE_MIN_FAT_FINGER_HYST */
0x40, /* GLOVE_SIGNAL_THRESHOLD_MULTIPLIER */
0x08, /* GLOVE_INNER_EDGE_GAIN */
0x78, /* GLOVE_OUTER_EDGE_GAIN */
0x00, /* Reserved989 */
0x00, 0x00, /* Reserved990 */
0xF0, 0x00, 0x00, 0x00, /* XY_FILTER_MASK */
0x02, 0x00, 0x00, 0x00, /* XY_FILT_IIR_COEFF */
0x01, 0x00, 0x00, 0x00, /* XY_FILT_Z_IIR_COEFF */
0xFF, /* XY_FILT_XY_FAST_THR */
0xFF, /* XY_FILT_XY_SLOW_THR */
0x01, /* XY_FILT_IIR_FAST_COEFF */
0x00, /* XY_FILT_PREDICTION_COEF */
0xF0, 0x00, 0x00, 0x00, /* XY_FILTER_MASK_CA */
0x02, 0x00, 0x00, 0x00, /* XY_FILT_IIR_COEFF_CA */
0x02, 0x00, 0x00, 0x00, /* XY_FILT_Z_IIR_COEFF_CA */
0xFF, /* XY_FILT_XY_FAST_THR_CA */
0xFF, /* XY_FILT_XY_SLOW_THR_CA */
0x01, /* XY_FILT_IIR_FAST_COEFF_CA */
0x00, /* XY_FILT_PREDICTION_COEF_CA */
0x00, /* XY_FILT_EXTRA_IIR_FILTER */
0x00, /* XY_FILT_TOUCH_SIZE_IIR_COEFF */
0x00, /* XY_FILT_TOUCH_SIZE_HYST */
0x00, /* XY_FILT_TOUCH_ORIENTATION_IIR_COEFF */
0x00, /* XY_FILT_TOUCH_ORIENTATION_HYST */
0x00, 0x00, 0x00, /* Reserved1029 */
0x03, /* SIZE_ORIENTATION_ENABLE */
0x00, 0x00, 0x00, /* Reserved1033 */
0x00, /* EXT_SYNC */
0x00, /* PWR_CFG */
0x02, 0x00, /* CONFIG_VER */
0x00, /* SEND_REPORT_AFTER_ACTIVE_INTERVAL_CFG */
0x00, /* PIP_REPORTING_DISABLE */
0x00, 0x00, /* INTERRUPT_PIN_OVERRIDE */
0x00, /* POST_CFG */
0x00, /* PINS_GND_GND */
0x05, /* PINS_GND_NC */
0x02, /* PINS_NC_GND */
0x06, /* PINS_NC_NC */
0x00, 0x00, 0x00, /* Reserved1049 */
0xCA, 0x96, /* CONFIG_CRC */
};
/* Touchscreen Parameters Field Sizes (Writable: 0:Readonly; 1:Writable) */
static const uint16_t cyttsp5_param_size[] = {
/* Size Name */
2, /* CONFIG_DATA_SIZE */
2, /* CONFIG_DATA_MAX_SIZE */
2, /* X_RESOLUTION */
2, /* Y_RESOLUTION */
2, /* X_LEN_PHY */
2, /* Y_LEN_PHY */
2, /* CROSS_NUM */
1, /* TX_NUM */
1, /* RX_NUM */
1, /* SENS_NUM */
1, /* SENSOR_ASSIGNMENT */
1, /* PROXIMITY_SCAN_AXIS */
1, /* BL_H20_RJCT */
1, /* CHARGER_ARMOR_ENABLE */
1, /* TOUCHMODE_ENABLED */
1, /* LRG_OBJ_CFG */
1, /* BUTTON_NUM */
1, /* PROXIMITY_GRIP_SUPPRESSION_SIZE */
1, /* MAX_NUM_OF_REPORTED_TOUCHES */
1, /* MAX_NUM_OF_SUPPORTED_TOUCHES */
1, /* SCANNING_MODE_BUTTON */
1, /* OPMODE_CFG */
1, /* SELF_Z_MODE */
1, /* WF_ENABLE */
1, /* PALM_DETECTION_ENABLE */
4, /* PQ_CTRL */
4, /* PQ_CTRL2 */
4, /* PQ_CTRL3 */
4, /* REFGEN_CTL */
4, /* TX_CTRL */
4, /* RX_CTRL */
4, /* INFRA_CTRL */
1, /* STARTUP_DELAY */
1, /* FORCE_SINGLE_TX */
1, /* SLOTS_MUT */
1, /* SLOTS_SELF_RX */
1, /* SLOTS_SELF_TX */
1, /* SLOTS_SELF */
2, /* SCALING_FACTOR_MUTUAL */
2, /* SCALING_FACTOR_SELF */
2, /* SCALING_FACTOR_BUTTON_MUTUAL */
2, /* SCALING_FACTOR_BUTTON_SELF */
2, /* SCALING_FACTOR_PROXIMITY */
1, /* TX_PUMP_VOLTAGE */
1, /* DISCARD_TIME */
1, /* VDDA_MODE */
1, /* BUTTON_LAYOUT */
1, /* MTX_ORDER */
1, /* Reserved81 */
1, /* TX_FREQ_METHOD_MUTUAL */
1, /* TX_FREQ_METHOD_SELF */
2, /* CA_WIDEBAND_TX_PERIOD */
1, /* CA_WIDEBAND_TX_PERIOD_DITHER */
1, /* IDAC_WB */
1, /* RX_ATTEN_RES_BYPASS */
1, /* SAFE_RAW_RANGE_PERCENT_MUTUAL */
1, /* SAFE_RAW_RANGE_PERCENT_SELF */
1, /* SAFE_RAW_RANGE_PERCENT_BTN_MUTUAL */
1, /* SAFE_RAW_RANGE_PERCENT_BTN_SELF */
1, /* Reserved93 */
2, /* INTEGRATOR_VOLTAGE_MUTUAL */
2, /* INTEGRATOR_VOLTAGE_SELF */
2, /* INTEGRATOR_VOLTAGE_BUTTON_MUTUAL */
2, /* INTEGRATOR_VOLTAGE_BUTTON_SELF */
1, /* BALANCING_TARGET_MUTUAL */
1, /* BALANCING_TARGET_SELF */
1, /* BALANCING_TARGET_BUTTON_MUTUAL */
1, /* BALANCING_TARGET_BUTTON_SELF */
2, /* ILEAK_MAX */
2, /* OPENS_TEST_RAW_THRESHOLD_MUTUAL */
2, /* OPENS_TEST_RAW_THRESHOLD_BUTTON */
1, /* OPENS_TEST_IDAC_MUTUAL */
1, /* OPENS_TEST_ATTEN_MUTUAL */
1, /* OPENS_TEST_IDAC_BUTTON */
1, /* OPENS_TEST_ATTEN_BUTTON */
1, /* Reserved116 */
1, /* Reserved117 */
1, /* Reserved118 */
1, /* Reserved119 */
2, /* TX_PERIOD_MUTUAL */
2, /* TX_PULSES_NUM_MUTUAL */
2, /* CA_TX_PERIOD_MUTUAL */
2, /* CA_BASE_TX_PULSES_NUM_MUTUAL */
2, /* CA_HOP0_TX_PERIOD_MUTUAL */
2, /* CA_HOP0_TX_PULSES_NUM_MUTUAL */
2, /* CA_HOP1_TX_PERIOD_MUTUAL */
2, /* CA_HOP1_TX_PULSES_NUM_MUTUAL */
2, /* CA_HOP2_TX_PERIOD_MUTUAL */
2, /* CA_HOP2_TX_PULSES_NUM_MUTUAL */
2, /* CA_HOP3_TX_PERIOD_MUTUAL */
2, /* CA_HOP3_TX_PULSES_NUM_MUTUAL */
2, /* CA_HOP4_TX_PERIOD_MUTUAL */
2, /* CA_HOP4_TX_PULSES_NUM_MUTUAL */
2, /* TX_PERIOD_SELF */
2, /* TX_PULSES_NUM_SELF */
2, /* TX_PERIOD_BTN_MUTUAL */
2, /* TX_PULSES_NUM_BUTTON_MUTUAL */
2, /* TX_PERIOD_BTN_SELF */
2, /* TX_PULSES_NUM_BUTTON_SELF */
2, /* TX_PERIOD_PROX */
2, /* TX_PULSES_NUM_PROXIMITY */
2, /* TX_PERIOD_GLOVE_MUTUAL */
2, /* TX_PULSES_NUM_GLOVE_MUTUAL */
2, /* TX_PERIOD_GLOVE_SELF */
2, /* TX_PULSES_NUM_GLOVE_SELF */
2, /* TX_PERIOD_GLOVE_BUTTON_MUTUAL */
2, /* TX_PULSES_NUM_GLOVE_BUTTON_MUTUAL */
2, /* TX_PERIOD_GLOVE_BUTTON_SELF */
2, /* TX_PULSES_NUM_GLOVE_BUTTON_SELF */
48, /* CDC_SENSOR_MASKS */
41, /* CDC_PIN_INDEX_TABLE */
3, /* Reserved269 */
8, /* CDC_MTX_PHASE_VECTOR */
48, /* CDC_MTX_DECONV_COEF */
200, /* CDC_SLOT_TABLE */
2, /* MAX_SELF_SIG_THRESHOLD */
2, /* MAX_POSITIVE_THRESHOLD */
1, /* BL_DELAY_BTN */
1, /* BL_THRESHOLD_MUT */
1, /* BL_THRESHOLD_SELF */
1, /* RATIO_MAXMUT_TO_MAXSELF */
1, /* MIN_POSITIVE_THRESHOLD */
1, /* RATIO_SUMALL_TO_POSITIVE */
1, /* COUNTS_TO_BL_RESET_MUT */
1, /* COUNTS_TO_BL_RESET_SELF */
1, /* BL_FILT_BTN_MUT */
1, /* BL_FILT_BTN_SELF */
2, /* SELF_LIFTOFF_THRESHOLD */
1, /* BASELINE_DELAY */
1, /* DEBOUNCE_BASELINE_AFTER_REMOVE */
1, /* SLOW_BL_THRSH */
1, /* SLOW_BL_SS */
1, /* FAST_BL_THRSH */
1, /* FAST_BL_SS */
2, /* WIPE_RESET_COUNTER */
2, /* DECREASE_BY_WATER */
2, /* PREV_RAW_FRAME_NUM */
2, /* WIPE_DELAY */
2, /* DROP_RESET_COUNTER */
4, /* WATER_TIMEOUT */
2, /* INIT_BL_DELAY */
2, /* TOUCH_THRESHOLD */
2, /* BL_FRAME_NUM_AFTER_LIFTOFF */
1, /* Reserved570 */
1, /* Reserved571 */
2, /* MAX_MUTUAL_SCAN_INTERVAL */
2, /* MAX_SELF_SCAN_INTERVAL */
2, /* BL_BTN_THRSH_MUT */
2, /* BL_BTN_THRSH_SELF */
2, /* BL_BTN_THRSH_MUT_CA */
2, /* BL_BTN_THRSH_MUT_GLOVE */
2, /* BL_BTN_THRSH_SELF_GLOVE */
2, /* Reserved586 */
1, /* CMF_DELTA_TEMPCO_INCREMENT */
1, /* Reserved589 */
1, /* Reserved590 */
1, /* Reserved591 */
1, /* Reserved592 */
1, /* Reserved593 */
2, /* WF_RAW_VAR_THOLD */
2, /* WF_RAW_HIGH_THOLD */
2, /* WF_DIFF_VAR_THOLD */
2, /* WF_RAW_CALC_THOLD */
2, /* WF_DIFF_CALC_THOLD */
1, /* FILT_FILTER_MASK */
1, /* FILT_IIR_COEFF_MUT */
2, /* FILT_IIR_THRESHOLD_MUT */
2, /* FILT_CMF_THRESHOLD_MUT */
1, /* FILT_FILTER_MASK_BASE_SELF */
1, /* FILT_IIR_COEFF_SELF */
2, /* FILT_IIR_THRESHOLD_SELF */
2, /* CMF_THR_SELF */
1, /* FILT_FILTER_MASK_BTN_MUT */
1, /* FILT_IIR_COEFF_BUT */
2, /* FILT_IIR_THRESHOLD_BUT */
2, /* CMF_THR_BTN_MUT */
1, /* FILT_FILTER_MASK_BTN_SELF */
1, /* FILT_IIR_COEFF_BUT_BASE_SELF */
2, /* FILT_IIR_THRESHOLD_BUT_BASE_SELF */
2, /* CMF_THR_BTN_SELF */
1, /* FILT_FILTER_MASK_PROX */
1, /* IIR_COEF */
2, /* IIR_THRESHOLD */
2, /* FILT_CMF_THRESHOLD_PROX */
1, /* CAFILT_FILTER_MASK */
1, /* CAFILT_IIR_COEFF_MUT */
2, /* CAFILT_IIR_THRESHOLD_MUT */
2, /* CAFILT_CMF_THRESHOLD_MUT */
1, /* CAFILT_FILT_BTN_MUT */
1, /* CAFILT_IIR_COEFF_BUT */
2, /* CAFILT_IIR_THRESHOLD_BUT */
2, /* CAFILT_CMF_THRESHOLD_BUT_MUT */
1, /* FILT_FILTER_MASK_GLOVE_MUT */
1, /* FILT_IIR_COEFF_GLOVE_MUT */
2, /* FILT_IIR_THRESHOLD_GLOVE_MUT */
2, /* FILT_CMF_THRESHOLD_GLOVE_MUT */
1, /* FILT_FILTER_MASK_GLOVE_SELF */
1, /* FILT_IIR_COEFF_GLOVE_SELF */
2, /* FILT_IIR_THRESHOLD_GLOVE_SELF */
2, /* FILT_CMF_THRESHOLD_GLOVE_SELF */
1, /* FILT_FILTER_MASK_BUT_GLOVE_MUT */
1, /* FILT_IIR_COEFF_BUT_GLOVE_MUT */
2, /* FILT_IIR_THRESHOLD_BUT_GLOVE_MUT */
2, /* FILT_CMF_THRESHOLD_GLOVE_BUT_MUT */
1, /* FILT_FILTER_MASK_BUT_GLOVE_SELF */
1, /* FILT_IIR_COEFF_BUT_GLOVE_SELF */
2, /* FILT_IIR_THRESHOLD_BUT_GLOVE_SELF */
2, /* FILT_CMF_THRESHOLD_GLOVE_BUT_SELF */
1, /* FILT_FILTER_MASK_NOFILT */
1, /* FILT_IIR_COEFF_NOFILT */
2, /* FILT_IIR_THRESHOLD_NOFILT */
2, /* FILT_CMF_THRESHOLD_NOFILT */
1, /* CA_HOST_CONTROLLED_CHARGER */
1, /* CHARGER_STATUS */
1, /* AFH_LISTEN_SCAN_CYCLE_REPEATS */
1, /* AFH_LISTENING_SCAN_COUNT */
2, /* CA_INJTCH_MAGNITUDE */
2, /* CA_INJTCH_FINGER_THOLD */
4, /* CA_DEFAULT_REVERT_TIME */
2, /* DETECT_CHARGER_THRESHOLD */
2, /* NM_INJ_TCH_THRESHOLD */
1, /* CA_WB_CMF_ENABLE */
1, /* CA_WB_REVERT_THOLD */
1, /* TRIGGER_CA */
1, /* CA_DYN_CAL_NUM_SENSOR_THLD_PERCENT */
2, /* CA_DYN_CAL_SAFE_RAW_RANGE */
2, /* CA_MIN_SELF_ALLOWED */
1, /* ACT_LFT_EN */
1, /* INNER_EDGE_GAIN */
1, /* OUTER_EDGE_GAIN */
1, /* ACT_INTRVL0 */
2, /* ACT_LFT_INTRVL0 */
2, /* LP_INTRVL0 */
2, /* TCH_TMOUT0 */
2, /* FINGER_THRESH_SELF */
2, /* GLOVE_THRSH_SELF */
1, /* LOW_POWER_ENABLE */
1, /* Reserved715 */
1, /* ACT_DIST0 */
1, /* ACT_DIST2 */
1, /* ACT_DIST_TOUCHDOWN */
1, /* ACT_DIST_LIFTOFF */
1, /* ACT_DIST_COUNTER */
1, /* ACT_DIST_Z_THRESHOLD */
1, /* FIRST_TOUCH_SUPPRESSION */
1, /* OBJ_WITHHOLD_CFG */
1, /* ACTIVE_DELTA_Z */
1, /* MAX_ACCEPTED_FINGER */
2, /* Reserved726 */
4, /* FINGER_ID_MAX_FINGER_VELOCITY2 */
2, /* GRIP_XEDG_A */
2, /* GRIP_XEDG_B */
2, /* GRIP_XEXC_A */
2, /* GRIP_XEXC_B */
2, /* GRIP_YEDG_A */
2, /* GRIP_YEDG_B */
2, /* GRIP_YEXC_A */
2, /* GRIP_YEXC_B */
1, /* GRIP_FIRST_EXC */
1, /* GRIP_EXC_EDGE_ORIGIN */
1, /* GRIP_ENABLE */
1, /* LIFTOFF_DEBOUNCE */
1, /* LIFTOFF_DEBOUNCE_PROXIMITY */
1, /* LIFTOFF_DEBOUNCE_STYLUS */
1, /* LIFTOFF_DEBOUNCE_HOVER */
1, /* GLOVE_LIFTOFF_DEBOUNCE */
2, /* TOUCHMODE_GLOVE_SWITCH_DEBOUNCE */
2, /* TOUCHMODE_FINGER_SWITCH_DEBOUNCE */
2, /* TOUCHMODE_GLOVE_FINGER_SWITCH_DEBOUNCE */
2, /* TOUCHMODE_GLOVE_EXIT_DELAY */
2, /* TOUCHMODE_FINGER_EXIT_DELAY */
2, /* SELF_Z_THRSH */
1, /* CLIPPING_X_LOW */
1, /* CLIPPING_X_HIGH */
1, /* CLIPPING_Y_LOW */
1, /* CLIPPING_Y_HIGH */
1, /* H2O_REJECTION_SNS_WIDTH */
1, /* SLIM_POSITION_OFFSET_ALONG_TX */
1, /* SLIM_POSITION_OFFSET_ALONG_RX */
1, /* LARGE_OBJECT_DEBOUNCE */
1, /* MAX_SELF_TX_RANGE */
1, /* MAX_SELF_RX_RANGE */
1, /* MAX_MUTUAL_TX_RANGE */
1, /* MAX_MUTUAL_RX_RANGE */
1, /* BR2_ALWAYS_ON_FLAG */
1, /* EDGE_DEBOUNCE_COUNT */
2, /* CALC_THRESHOLD */
2, /* OFFSET_S1 */
2, /* OFFSET_S2 */
4, /* Z1_SUM_8MM */
4, /* Z2_SUM_4MM */
4, /* Z1_SUM_3MM */
4, /* Z2_SUM_1MM */
4, /* LOW_PIVOT */
4, /* HIGH_PIVOT */
4, /* LOW_PIVOT2 */
4, /* HIGH_PIVOT2 */
2, /* EDGE_DEBOUNCE_COUNT_THRESHOLD */
2, /* CENTER_MAGNITUDE_SCALE */
1, /* CENTROID_CORNER_NUMER */
1, /* CENTROID_CORNER_DENOM */
1, /* CENTROID_FINGER_MAX_JUMP */
1, /* GRADIENT_OUTER_EDGE_CONST_GAIN */
1, /* GRADIENT_OUTER_EDGE_CONST_RESPONSE */
1, /* GRADIENT_EDGE_COEF */
1, /* GRADIENT_COEF */
1, /* GRADIENT_THRESHOLD */
1, /* CORE_TO_CORNER_ZSUM_RATIO */
1, /* Reserved833 */
2, /* Reserved834 */
4, /* MIN_FAT_FINGER_Z9 */
4, /* MAX_MULTI_FINGER_Z9 */
4, /* MIN_FAT_FINGER_SIG_SUM_ON_EDGE */
1, /* CENTER_SIGNAL_TO_MIN_PEAK_RATIO */
1, /* SD_SIZE_THRESHOLD */
2, /* SD_ENTER_SIGNAL_THRESHOLD */
2, /* SD_EXIT_SIGNAL_THRESHOLD */
2, /* VIRTUAL_PEAK_DELTA_RESET_THRESHOLD */
2, /* VIRTUAL_PEAK_DELTA_THRESHOLD */
1, /* FAT_AXIS_LENGTH_THRESHOLD */
1, /* TOUCH_IGNORE_COEFF */
2, /* UPPER_THRSH */
2, /* LOWER_THRSH */
2, /* OFF_THRSH */
2, /* ACTIVE_SENSOR_THRESHOLD */
2, /* ACTIVE_SENSOR_THRESHOLD_FINGER */
2, /* DEBOUNCE_ON_DETECT_FINGER */
1, /* DEBOUNCE_ON_DETECT */
1, /* DEBOUNCE_AFTER_REMOVE */
1, /* MAX_NUM_SHORT_SCAN */
1, /* SENSOR_NUM_THRSH */
1, /* SENSOR_NUM_THRSH_FINGER */
1, /* DISCARD_SCAN */
2, /* Reserved878 */
2, /* FINGER_THRESH_MUTUAL_ON */
2, /* FINGER_THRESH_MUTUAL_OFF */
2, /* Z_SCALING */
2, /* CA_FINGER_THRESHOLD_MUTUAL */
1, /* MULTI_TOUCH_DEBOUNCE */
1, /* Z9_FILTER_SCALE */
1, /* CA_MULTI_TOUCH_DEBOUNCE */
1, /* CA_Z9_FILTER_SCALE */
1, /* MIN_FAT_FINGER_SIZE_HYST */
1, /* MIN_FAT_FINGER_SIZE_ON */
1, /* MAX_FAT_FINGER_SIZE_HYST */
1, /* MAX_FAT_FINGER_SIZE_ON */
1, /* CA_MIN_FAT_FINGER_SIZE */
1, /* CA_MAX_FAT_FINGER_SIZE */
1, /* TOUCH_TRACKING_FEATURES */
1, /* SIGNAL_THRESHOLD_MULTIPLIER */
1, /* WF_FT_COEF */
1, /* WF_MT_DEBOUNCE */
1, /* RX_LINE_FILTER */
1, /* RX_LINE_FILTER_DEBOUNCE */
1, /* RX_LINE_FILTER_THRESHOLD */
3, /* Reserved905 */
1, /* WF_Z8_MULTIPLIER */
3, /* Reserved909 */
1, /* BTN_LS_ON_THRSH_MUT_0 */
1, /* BTN_LS_ON_THRSH_MUT_1 */
1, /* BTN_LS_ON_THRSH_MUT_2 */
1, /* BTN_LS_ON_THRSH_MUT_3 */
1, /* BTN_LS_OFF_THRSH_MUT_0 */
1, /* BTN_LS_OFF_THRSH_MUT_1 */
1, /* BTN_LS_OFF_THRSH_MUT_2 */
1, /* BTN_LS_OFF_THRSH_MUT_3 */
1, /* BTN_LS_ON_THRSH_SELF_0 */
1, /* BTN_LS_ON_THRSH_SELF_1 */
1, /* BTN_LS_ON_THRSH_SELF_2 */
1, /* BTN_LS_ON_THRSH_SELF_3 */
1, /* BTN_LS_OFF_THRSH_SELF_0 */
1, /* BTN_LS_OFF_THRSH_SELF_1 */
1, /* BTN_LS_OFF_THRSH_SELF_2 */
1, /* BTN_LS_OFF_THRSH_SELF_3 */
2, /* BTN_LS_TOUCHDOWN_DEBOUNCE */
2, /* Reserved930 */
1, /* BTN_HS_ON_THRSH_MUT_0 */
1, /* BTN_HS_ON_THRSH_MUT_1 */
1, /* BTN_HS_ON_THRSH_MUT_2 */
1, /* BTN_HS_ON_THRSH_MUT_3 */
1, /* BTN_HS_OFF_THRSH_MUT_0 */
1, /* BTN_HS_OFF_THRSH_MUT_1 */
1, /* BTN_HS_OFF_THRSH_MUT_2 */
1, /* BTN_HS_OFF_THRSH_MUT_3 */
1, /* BTN_HS_ON_THRSH_SELF_0 */
1, /* BTN_HS_ON_THRSH_SELF_1 */
1, /* BTN_HS_ON_THRSH_SELF_2 */
1, /* BTN_HS_ON_THRSH_SELF_3 */
1, /* BTN_HS_OFF_THRSH_SELF_0 */
1, /* BTN_HS_OFF_THRSH_SELF_1 */
1, /* BTN_HS_OFF_THRSH_SELF_2 */
1, /* BTN_HS_OFF_THRSH_SELF_3 */
2, /* BTN_HS_TOUCHDOWN_DEBOUNCE */
2, /* Reserved950 */
2, /* GLOVE_BTN_FORBID_DEBOUNCE */
2, /* GLOVE_BTN_TO_HIGHSEN_MODE_SWITCH_THRSH_MUT */
2, /* GLOVE_BTN_TO_HIGHSEN_MODE_SWITCH_THRSH_SELF */
2, /* GLOVE_BTN_TO_LOWSEN_MODE_SWITCH_THRSH_MUT */
2, /* GLOVE_BTN_TO_LOWSEN_MODE_SWITCH_THRSH_SELF */
2, /* GLOVE_BTN_MODE_SWITCH_DEBOUNCE */
1, /* BTN_PROCESS_IF_TOUCH_DETECTED */
1, /* Reserved965 */
2, /* Reserved966 */
2, /* TOUCHMODE_GLOVE_MAX_PEAK */
2, /* GLOVE_ON_THRSH_MUTUAL */
2, /* GLOVE_OFF_THRSH_MUTUAL */
1, /* GLOVE_FIRST_TOUCH_DEBOUNCE */
1, /* GLOVE_FIRST_TOUCH_DEBOUNCE_EDGE_MASK */
1, /* GLOVE_MULTI_TOUCH_DEBOUNCE */
1, /* GLOVE_Z8_FILTER_SCALE */
1, /* GLOVE_Z9_FILTER_SCALE */
1, /* GLOVE_GRIP_FILTER_SCALE */
2, /* GLOVE_Z_SCALING */
1, /* GLOVE_MAX_FAT_FINGER_SIZE */
1, /* GLOVE_MAX_FAT_FINGER_HYST */
1, /* GLOVE_MIN_FAT_FINGER_SIZE */
1, /* GLOVE_MIN_FAT_FINGER_HYST */
1, /* GLOVE_SIGNAL_THRESHOLD_MULTIPLIER */
1, /* GLOVE_INNER_EDGE_GAIN */
1, /* GLOVE_OUTER_EDGE_GAIN */
1, /* Reserved989 */
2, /* Reserved990 */
4, /* XY_FILTER_MASK */
4, /* XY_FILT_IIR_COEFF */
4, /* XY_FILT_Z_IIR_COEFF */
1, /* XY_FILT_XY_FAST_THR */
1, /* XY_FILT_XY_SLOW_THR */
1, /* XY_FILT_IIR_FAST_COEFF */
1, /* XY_FILT_PREDICTION_COEF */
4, /* XY_FILTER_MASK_CA */
4, /* XY_FILT_IIR_COEFF_CA */
4, /* XY_FILT_Z_IIR_COEFF_CA */
1, /* XY_FILT_XY_FAST_THR_CA */
1, /* XY_FILT_XY_SLOW_THR_CA */
1, /* XY_FILT_IIR_FAST_COEFF_CA */
1, /* XY_FILT_PREDICTION_COEF_CA */
1, /* XY_FILT_EXTRA_IIR_FILTER */
1, /* XY_FILT_TOUCH_SIZE_IIR_COEFF */
1, /* XY_FILT_TOUCH_SIZE_HYST */
1, /* XY_FILT_TOUCH_ORIENTATION_IIR_COEFF */
1, /* XY_FILT_TOUCH_ORIENTATION_HYST */
3, /* Reserved1029 */
1, /* SIZE_ORIENTATION_ENABLE */
3, /* Reserved1033 */
1, /* EXT_SYNC */
1, /* PWR_CFG */
2, /* CONFIG_VER */
1, /* SEND_REPORT_AFTER_ACTIVE_INTERVAL_CFG */
1, /* PIP_REPORTING_DISABLE */
2, /* INTERRUPT_PIN_OVERRIDE */
1, /* POST_CFG */
1, /* PINS_GND_GND */
1, /* PINS_GND_NC */
1, /* PINS_NC_GND */
1, /* PINS_NC_NC */
3, /* Reserved1049 */
2, /* CONFIG_CRC */
};
#if 0
/* Touchscreen Parameters Field Address*/
static const uint8_t cyttsp5_param_addr[] = {
/* Address Name */
0xF1, 0x00, /* CONFIG_DATA_SIZE */
0xF1, 0x02, /* CONFIG_DATA_MAX_SIZE */
0xF1, 0x04, /* X_RESOLUTION */
0xF1, 0x06, /* Y_RESOLUTION */
0xF1, 0x08, /* X_LEN_PHY */
0xF1, 0x0A, /* Y_LEN_PHY */
0xF1, 0x0C, /* CROSS_NUM */
0xF1, 0x0E, /* TX_NUM */
0xF1, 0x0F, /* RX_NUM */
0xF1, 0x10, /* SENS_NUM */
0xF1, 0x11, /* SENSOR_ASSIGNMENT */
0xF1, 0x12, /* PROXIMITY_SCAN_AXIS */
0xF1, 0x13, /* BL_H20_RJCT */
0xF1, 0x14, /* CHARGER_ARMOR_ENABLE */
0xF1, 0x15, /* TOUCHMODE_ENABLED */
0xF1, 0x16, /* LRG_OBJ_CFG */
0xF1, 0x17, /* BUTTON_NUM */
0xF1, 0x18, /* PROXIMITY_GRIP_SUPPRESSION_SIZE */
0xF1, 0x19, /* MAX_NUM_OF_REPORTED_TOUCHES */
0xF1, 0x1A, /* MAX_NUM_OF_SUPPORTED_TOUCHES */
0xF1, 0x1B, /* SCANNING_MODE_BUTTON */
0xF1, 0x1C, /* OPMODE_CFG */
0xF1, 0x1D, /* SELF_Z_MODE */
0xF1, 0x1E, /* WF_ENABLE */
0xF1, 0x1F, /* PALM_DETECTION_ENABLE */
0xF1, 0x20, /* PQ_CTRL */
0xF1, 0x24, /* PQ_CTRL2 */
0xF1, 0x28, /* PQ_CTRL3 */
0xF1, 0x2C, /* REFGEN_CTL */
0xF1, 0x30, /* TX_CTRL */
0xF1, 0x34, /* RX_CTRL */
0xF1, 0x38, /* INFRA_CTRL */
0xF1, 0x3C, /* STARTUP_DELAY */
0xF1, 0x3D, /* FORCE_SINGLE_TX */
0xF1, 0x3E, /* SLOTS_MUT */
0xF1, 0x3F, /* SLOTS_SELF_RX */
0xF1, 0x40, /* SLOTS_SELF_TX */
0xF1, 0x41, /* SLOTS_SELF */
0xF1, 0x42, /* SCALING_FACTOR_MUTUAL */
0xF1, 0x44, /* SCALING_FACTOR_SELF */
0xF1, 0x46, /* SCALING_FACTOR_BUTTON_MUTUAL */
0xF1, 0x48, /* SCALING_FACTOR_BUTTON_SELF */
0xF1, 0x4A, /* SCALING_FACTOR_PROXIMITY */
0xF1, 0x4C, /* TX_PUMP_VOLTAGE */
0xF1, 0x4D, /* DISCARD_TIME */
0xF1, 0x4E, /* VDDA_MODE */
0xF1, 0x4F, /* BUTTON_LAYOUT */
0xF1, 0x50, /* MTX_ORDER */
0xF1, 0x51, /* Reserved81 */
0xF1, 0x52, /* TX_FREQ_METHOD_MUTUAL */
0xF1, 0x53, /* TX_FREQ_METHOD_SELF */
0xF1, 0x54, /* CA_WIDEBAND_TX_PERIOD */
0xF1, 0x56, /* CA_WIDEBAND_TX_PERIOD_DITHER */
0xF1, 0x57, /* IDAC_WB */
0xF1, 0x58, /* RX_ATTEN_RES_BYPASS */
0xF1, 0x59, /* SAFE_RAW_RANGE_PERCENT_MUTUAL */
0xF1, 0x5A, /* SAFE_RAW_RANGE_PERCENT_SELF */
0xF1, 0x5B, /* SAFE_RAW_RANGE_PERCENT_BTN_MUTUAL */
0xF1, 0x5C, /* SAFE_RAW_RANGE_PERCENT_BTN_SELF */
0xF1, 0x5D, /* Reserved93 */
0xF1, 0x5E, /* INTEGRATOR_VOLTAGE_MUTUAL */
0xF1, 0x60, /* INTEGRATOR_VOLTAGE_SELF */
0xF1, 0x62, /* INTEGRATOR_VOLTAGE_BUTTON_MUTUAL */
0xF1, 0x64, /* INTEGRATOR_VOLTAGE_BUTTON_SELF */
0xF1, 0x66, /* BALANCING_TARGET_MUTUAL */
0xF1, 0x67, /* BALANCING_TARGET_SELF */
0xF1, 0x68, /* BALANCING_TARGET_BUTTON_MUTUAL */
0xF1, 0x69, /* BALANCING_TARGET_BUTTON_SELF */
0xF1, 0x6A, /* ILEAK_MAX */
0xF1, 0x6C, /* OPENS_TEST_RAW_THRESHOLD_MUTUAL */
0xF1, 0x6E, /* OPENS_TEST_RAW_THRESHOLD_BUTTON */
0xF1, 0x70, /* OPENS_TEST_IDAC_MUTUAL */
0xF1, 0x71, /* OPENS_TEST_ATTEN_MUTUAL */
0xF1, 0x72, /* OPENS_TEST_IDAC_BUTTON */
0xF1, 0x73, /* OPENS_TEST_ATTEN_BUTTON */
0xF1, 0x74, /* Reserved116 */
0xF1, 0x75, /* Reserved117 */
0xF1, 0x76, /* Reserved118 */
0xF1, 0x77, /* Reserved119 */
0xF1, 0x78, /* TX_PERIOD_MUTUAL */
0xF1, 0x7A, /* TX_PULSES_NUM_MUTUAL */
0xF1, 0x7C, /* CA_TX_PERIOD_MUTUAL */
0xF1, 0x7E, /* CA_BASE_TX_PULSES_NUM_MUTUAL */
0xF1, 0x80, /* CA_HOP0_TX_PERIOD_MUTUAL */
0xF1, 0x82, /* CA_HOP0_TX_PULSES_NUM_MUTUAL */
0xF1, 0x84, /* CA_HOP1_TX_PERIOD_MUTUAL */
0xF1, 0x86, /* CA_HOP1_TX_PULSES_NUM_MUTUAL */
0xF1, 0x88, /* CA_HOP2_TX_PERIOD_MUTUAL */
0xF1, 0x8A, /* CA_HOP2_TX_PULSES_NUM_MUTUAL */
0xF1, 0x8C, /* CA_HOP3_TX_PERIOD_MUTUAL */
0xF1, 0x8E, /* CA_HOP3_TX_PULSES_NUM_MUTUAL */
0xF1, 0x90, /* CA_HOP4_TX_PERIOD_MUTUAL */
0xF1, 0x92, /* CA_HOP4_TX_PULSES_NUM_MUTUAL */
0xF1, 0x94, /* TX_PERIOD_SELF */
0xF1, 0x96, /* TX_PULSES_NUM_SELF */
0xF1, 0x98, /* TX_PERIOD_BTN_MUTUAL */
0xF1, 0x9A, /* TX_PULSES_NUM_BUTTON_MUTUAL */
0xF1, 0x9C, /* TX_PERIOD_BTN_SELF */
0xF1, 0x9E, /* TX_PULSES_NUM_BUTTON_SELF */
0xF1, 0xA0, /* TX_PERIOD_PROX */
0xF1, 0xA2, /* TX_PULSES_NUM_PROXIMITY */
0xF1, 0xA4, /* TX_PERIOD_GLOVE_MUTUAL */
0xF1, 0xA6, /* TX_PULSES_NUM_GLOVE_MUTUAL */
0xF1, 0xA8, /* TX_PERIOD_GLOVE_SELF */
0xF1, 0xAA, /* TX_PULSES_NUM_GLOVE_SELF */
0xF1, 0xAC, /* TX_PERIOD_GLOVE_BUTTON_MUTUAL */
0xF1, 0xAE, /* TX_PULSES_NUM_GLOVE_BUTTON_MUTUAL */
0xF1, 0xB0, /* TX_PERIOD_GLOVE_BUTTON_SELF */
0xF1, 0xB2, /* TX_PULSES_NUM_GLOVE_BUTTON_SELF */
0xF1, 0xB4, /* CDC_SENSOR_MASKS */
0xF1, 0xE4, /* CDC_PIN_INDEX_TABLE */
0xF2, 0x0D, /* Reserved269 */
0xF2, 0x10, /* CDC_MTX_PHASE_VECTOR */
0xF2, 0x18, /* CDC_MTX_DECONV_COEF */
0xF2, 0x48, /* CDC_SLOT_TABLE */
0xF3, 0x10, /* MAX_SELF_SIG_THRESHOLD */
0xF3, 0x12, /* MAX_POSITIVE_THRESHOLD */
0xF3, 0x14, /* BL_DELAY_BTN */
0xF3, 0x15, /* BL_THRESHOLD_MUT */
0xF3, 0x16, /* BL_THRESHOLD_SELF */
0xF3, 0x17, /* RATIO_MAXMUT_TO_MAXSELF */
0xF3, 0x18, /* MIN_POSITIVE_THRESHOLD */
0xF3, 0x19, /* RATIO_SUMALL_TO_POSITIVE */
0xF3, 0x1A, /* COUNTS_TO_BL_RESET_MUT */
0xF3, 0x1B, /* COUNTS_TO_BL_RESET_SELF */
0xF3, 0x1C, /* BL_FILT_BTN_MUT */
0xF3, 0x1D, /* BL_FILT_BTN_SELF */
0xF3, 0x1E, /* SELF_LIFTOFF_THRESHOLD */
0xF3, 0x20, /* BASELINE_DELAY */
0xF3, 0x21, /* DEBOUNCE_BASELINE_AFTER_REMOVE */
0xF3, 0x22, /* SLOW_BL_THRSH */
0xF3, 0x23, /* SLOW_BL_SS */
0xF3, 0x24, /* FAST_BL_THRSH */
0xF3, 0x25, /* FAST_BL_SS */
0xF3, 0x26, /* WIPE_RESET_COUNTER */
0xF3, 0x28, /* DECREASE_BY_WATER */
0xF3, 0x2A, /* PREV_RAW_FRAME_NUM */
0xF3, 0x2C, /* WIPE_DELAY */
0xF3, 0x2E, /* DROP_RESET_COUNTER */
0xF3, 0x30, /* WATER_TIMEOUT */
0xF3, 0x34, /* INIT_BL_DELAY */
0xF3, 0x36, /* TOUCH_THRESHOLD */
0xF3, 0x38, /* BL_FRAME_NUM_AFTER_LIFTOFF */
0xF3, 0x3A, /* Reserved570 */
0xF3, 0x3B, /* Reserved571 */
0xF3, 0x3C, /* MAX_MUTUAL_SCAN_INTERVAL */
0xF3, 0x3E, /* MAX_SELF_SCAN_INTERVAL */
0xF3, 0x40, /* BL_BTN_THRSH_MUT */
0xF3, 0x42, /* BL_BTN_THRSH_SELF */
0xF3, 0x44, /* BL_BTN_THRSH_MUT_CA */
0xF3, 0x46, /* BL_BTN_THRSH_MUT_GLOVE */
0xF3, 0x48, /* BL_BTN_THRSH_SELF_GLOVE */
0xF3, 0x4A, /* Reserved586 */
0xF3, 0x4C, /* CMF_DELTA_TEMPCO_INCREMENT */
0xF3, 0x4D, /* Reserved589 */
0xF3, 0x4E, /* Reserved590 */
0xF3, 0x4F, /* Reserved591 */
0xF3, 0x50, /* Reserved592 */
0xF3, 0x51, /* Reserved593 */
0xF3, 0x52, /* WF_RAW_VAR_THOLD */
0xF3, 0x54, /* WF_RAW_HIGH_THOLD */
0xF3, 0x56, /* WF_DIFF_VAR_THOLD */
0xF3, 0x58, /* WF_RAW_CALC_THOLD */
0xF3, 0x5A, /* WF_DIFF_CALC_THOLD */
0xF3, 0x5C, /* FILT_FILTER_MASK */
0xF3, 0x5D, /* FILT_IIR_COEFF_MUT */
0xF3, 0x5E, /* FILT_IIR_THRESHOLD_MUT */
0xF3, 0x60, /* FILT_CMF_THRESHOLD_MUT */
0xF3, 0x62, /* FILT_FILTER_MASK_BASE_SELF */
0xF3, 0x63, /* FILT_IIR_COEFF_SELF */
0xF3, 0x64, /* FILT_IIR_THRESHOLD_SELF */
0xF3, 0x66, /* CMF_THR_SELF */
0xF3, 0x68, /* FILT_FILTER_MASK_BTN_MUT */
0xF3, 0x69, /* FILT_IIR_COEFF_BUT */
0xF3, 0x6A, /* FILT_IIR_THRESHOLD_BUT */
0xF3, 0x6C, /* CMF_THR_BTN_MUT */
0xF3, 0x6E, /* FILT_FILTER_MASK_BTN_SELF */
0xF3, 0x6F, /* FILT_IIR_COEFF_BUT_BASE_SELF */
0xF3, 0x70, /* FILT_IIR_THRESHOLD_BUT_BASE_SELF */
0xF3, 0x72, /* CMF_THR_BTN_SELF */
0xF3, 0x74, /* FILT_FILTER_MASK_PROX */
0xF3, 0x75, /* IIR_COEF */
0xF3, 0x76, /* IIR_THRESHOLD */
0xF3, 0x78, /* FILT_CMF_THRESHOLD_PROX */
0xF3, 0x7A, /* CAFILT_FILTER_MASK */
0xF3, 0x7B, /* CAFILT_IIR_COEFF_MUT */
0xF3, 0x7C, /* CAFILT_IIR_THRESHOLD_MUT */
0xF3, 0x7E, /* CAFILT_CMF_THRESHOLD_MUT */
0xF3, 0x80, /* CAFILT_FILT_BTN_MUT */
0xF3, 0x81, /* CAFILT_IIR_COEFF_BUT */
0xF3, 0x82, /* CAFILT_IIR_THRESHOLD_BUT */
0xF3, 0x84, /* CAFILT_CMF_THRESHOLD_BUT_MUT */
0xF3, 0x86, /* FILT_FILTER_MASK_GLOVE_MUT */
0xF3, 0x87, /* FILT_IIR_COEFF_GLOVE_MUT */
0xF3, 0x88, /* FILT_IIR_THRESHOLD_GLOVE_MUT */
0xF3, 0x8A, /* FILT_CMF_THRESHOLD_GLOVE_MUT */
0xF3, 0x8C, /* FILT_FILTER_MASK_GLOVE_SELF */
0xF3, 0x8D, /* FILT_IIR_COEFF_GLOVE_SELF */
0xF3, 0x8E, /* FILT_IIR_THRESHOLD_GLOVE_SELF */
0xF3, 0x90, /* FILT_CMF_THRESHOLD_GLOVE_SELF */
0xF3, 0x92, /* FILT_FILTER_MASK_BUT_GLOVE_MUT */
0xF3, 0x93, /* FILT_IIR_COEFF_BUT_GLOVE_MUT */
0xF3, 0x94, /* FILT_IIR_THRESHOLD_BUT_GLOVE_MUT */
0xF3, 0x96, /* FILT_CMF_THRESHOLD_GLOVE_BUT_MUT */
0xF3, 0x98, /* FILT_FILTER_MASK_BUT_GLOVE_SELF */
0xF3, 0x99, /* FILT_IIR_COEFF_BUT_GLOVE_SELF */
0xF3, 0x9A, /* FILT_IIR_THRESHOLD_BUT_GLOVE_SELF */
0xF3, 0x9C, /* FILT_CMF_THRESHOLD_GLOVE_BUT_SELF */
0xF3, 0x9E, /* FILT_FILTER_MASK_NOFILT */
0xF3, 0x9F, /* FILT_IIR_COEFF_NOFILT */
0xF3, 0xA0, /* FILT_IIR_THRESHOLD_NOFILT */
0xF3, 0xA2, /* FILT_CMF_THRESHOLD_NOFILT */
0xF3, 0xA4, /* CA_HOST_CONTROLLED_CHARGER */
0xF3, 0xA5, /* CHARGER_STATUS */
0xF3, 0xA6, /* AFH_LISTEN_SCAN_CYCLE_REPEATS */
0xF3, 0xA7, /* AFH_LISTENING_SCAN_COUNT */
0xF3, 0xA8, /* CA_INJTCH_MAGNITUDE */
0xF3, 0xAA, /* CA_INJTCH_FINGER_THOLD */
0xF3, 0xAC, /* CA_DEFAULT_REVERT_TIME */
0xF3, 0xB0, /* DETECT_CHARGER_THRESHOLD */
0xF3, 0xB2, /* NM_INJ_TCH_THRESHOLD */
0xF3, 0xB4, /* CA_WB_CMF_ENABLE */
0xF3, 0xB5, /* CA_WB_REVERT_THOLD */
0xF3, 0xB6, /* TRIGGER_CA */
0xF3, 0xB7, /* CA_DYN_CAL_NUM_SENSOR_THLD_PERCENT */
0xF3, 0xB8, /* CA_DYN_CAL_SAFE_RAW_RANGE */
0xF3, 0xBA, /* CA_MIN_SELF_ALLOWED */
0xF3, 0xBC, /* ACT_LFT_EN */
0xF3, 0xBD, /* INNER_EDGE_GAIN */
0xF3, 0xBE, /* OUTER_EDGE_GAIN */
0xF3, 0xBF, /* ACT_INTRVL0 */
0xF3, 0xC0, /* ACT_LFT_INTRVL0 */
0xF3, 0xC2, /* LP_INTRVL0 */
0xF3, 0xC4, /* TCH_TMOUT0 */
0xF3, 0xC6, /* FINGER_THRESH_SELF */
0xF3, 0xC8, /* GLOVE_THRSH_SELF */
0xF3, 0xCA, /* LOW_POWER_ENABLE */
0xF3, 0xCB, /* Reserved715 */
0xF3, 0xCC, /* ACT_DIST0 */
0xF3, 0xCD, /* ACT_DIST2 */
0xF3, 0xCE, /* ACT_DIST_TOUCHDOWN */
0xF3, 0xCF, /* ACT_DIST_LIFTOFF */
0xF3, 0xD0, /* ACT_DIST_COUNTER */
0xF3, 0xD1, /* ACT_DIST_Z_THRESHOLD */
0xF3, 0xD2, /* FIRST_TOUCH_SUPPRESSION */
0xF3, 0xD3, /* OBJ_WITHHOLD_CFG */
0xF3, 0xD4, /* ACTIVE_DELTA_Z */
0xF3, 0xD5, /* MAX_ACCEPTED_FINGER */
0xF3, 0xD6, /* Reserved726 */
0xF3, 0xD8, /* FINGER_ID_MAX_FINGER_VELOCITY2 */
0xF3, 0xDC, /* GRIP_XEDG_A */
0xF3, 0xDE, /* GRIP_XEDG_B */
0xF3, 0xE0, /* GRIP_XEXC_A */
0xF3, 0xE2, /* GRIP_XEXC_B */
0xF3, 0xE4, /* GRIP_YEDG_A */
0xF3, 0xE6, /* GRIP_YEDG_B */
0xF3, 0xE8, /* GRIP_YEXC_A */
0xF3, 0xEA, /* GRIP_YEXC_B */
0xF3, 0xEC, /* GRIP_FIRST_EXC */
0xF3, 0xED, /* GRIP_EXC_EDGE_ORIGIN */
0xF3, 0xEE, /* GRIP_ENABLE */
0xF3, 0xEF, /* LIFTOFF_DEBOUNCE */
0xF3, 0xF0, /* LIFTOFF_DEBOUNCE_PROXIMITY */
0xF3, 0xF1, /* LIFTOFF_DEBOUNCE_STYLUS */
0xF3, 0xF2, /* LIFTOFF_DEBOUNCE_HOVER */
0xF3, 0xF3, /* GLOVE_LIFTOFF_DEBOUNCE */
0xF3, 0xF4, /* TOUCHMODE_GLOVE_SWITCH_DEBOUNCE */
0xF3, 0xF6, /* TOUCHMODE_FINGER_SWITCH_DEBOUNCE */
0xF3, 0xF8, /* TOUCHMODE_GLOVE_FINGER_SWITCH_DEBOUNCE */
0xF3, 0xFA, /* TOUCHMODE_GLOVE_EXIT_DELAY */
0xF3, 0xFC, /* TOUCHMODE_FINGER_EXIT_DELAY */
0xF3, 0xFE, /* SELF_Z_THRSH */
0xF4, 0x00, /* CLIPPING_X_LOW */
0xF4, 0x01, /* CLIPPING_X_HIGH */
0xF4, 0x02, /* CLIPPING_Y_LOW */
0xF4, 0x03, /* CLIPPING_Y_HIGH */
0xF4, 0x04, /* H2O_REJECTION_SNS_WIDTH */
0xF4, 0x05, /* SLIM_POSITION_OFFSET_ALONG_TX */
0xF4, 0x06, /* SLIM_POSITION_OFFSET_ALONG_RX */
0xF4, 0x07, /* LARGE_OBJECT_DEBOUNCE */
0xF4, 0x08, /* MAX_SELF_TX_RANGE */
0xF4, 0x09, /* MAX_SELF_RX_RANGE */
0xF4, 0x0A, /* MAX_MUTUAL_TX_RANGE */
0xF4, 0x0B, /* MAX_MUTUAL_RX_RANGE */
0xF4, 0x0C, /* BR2_ALWAYS_ON_FLAG */
0xF4, 0x0D, /* EDGE_DEBOUNCE_COUNT */
0xF4, 0x0E, /* CALC_THRESHOLD */
0xF4, 0x10, /* OFFSET_S1 */
0xF4, 0x12, /* OFFSET_S2 */
0xF4, 0x14, /* Z1_SUM_8MM */
0xF4, 0x18, /* Z2_SUM_4MM */
0xF4, 0x1C, /* Z1_SUM_3MM */
0xF4, 0x20, /* Z2_SUM_1MM */
0xF4, 0x24, /* LOW_PIVOT */
0xF4, 0x28, /* HIGH_PIVOT */
0xF4, 0x2C, /* LOW_PIVOT2 */
0xF4, 0x30, /* HIGH_PIVOT2 */
0xF4, 0x34, /* EDGE_DEBOUNCE_COUNT_THRESHOLD */
0xF4, 0x36, /* CENTER_MAGNITUDE_SCALE */
0xF4, 0x38, /* CENTROID_CORNER_NUMER */
0xF4, 0x39, /* CENTROID_CORNER_DENOM */
0xF4, 0x3A, /* CENTROID_FINGER_MAX_JUMP */
0xF4, 0x3B, /* GRADIENT_OUTER_EDGE_CONST_GAIN */
0xF4, 0x3C, /* GRADIENT_OUTER_EDGE_CONST_RESPONSE */
0xF4, 0x3D, /* GRADIENT_EDGE_COEF */
0xF4, 0x3E, /* GRADIENT_COEF */
0xF4, 0x3F, /* GRADIENT_THRESHOLD */
0xF4, 0x40, /* CORE_TO_CORNER_ZSUM_RATIO */
0xF4, 0x41, /* Reserved833 */
0xF4, 0x42, /* Reserved834 */
0xF4, 0x44, /* MIN_FAT_FINGER_Z9 */
0xF4, 0x48, /* MAX_MULTI_FINGER_Z9 */
0xF4, 0x4C, /* MIN_FAT_FINGER_SIG_SUM_ON_EDGE */
0xF4, 0x50, /* CENTER_SIGNAL_TO_MIN_PEAK_RATIO */
0xF4, 0x51, /* SD_SIZE_THRESHOLD */
0xF4, 0x52, /* SD_ENTER_SIGNAL_THRESHOLD */
0xF4, 0x54, /* SD_EXIT_SIGNAL_THRESHOLD */
0xF4, 0x56, /* VIRTUAL_PEAK_DELTA_RESET_THRESHOLD */
0xF4, 0x58, /* VIRTUAL_PEAK_DELTA_THRESHOLD */
0xF4, 0x5A, /* FAT_AXIS_LENGTH_THRESHOLD */
0xF4, 0x5B, /* TOUCH_IGNORE_COEFF */
0xF4, 0x5C, /* UPPER_THRSH */
0xF4, 0x5E, /* LOWER_THRSH */
0xF4, 0x60, /* OFF_THRSH */
0xF4, 0x62, /* ACTIVE_SENSOR_THRESHOLD */
0xF4, 0x64, /* ACTIVE_SENSOR_THRESHOLD_FINGER */
0xF4, 0x66, /* DEBOUNCE_ON_DETECT_FINGER */
0xF4, 0x68, /* DEBOUNCE_ON_DETECT */
0xF4, 0x69, /* DEBOUNCE_AFTER_REMOVE */
0xF4, 0x6A, /* MAX_NUM_SHORT_SCAN */
0xF4, 0x6B, /* SENSOR_NUM_THRSH */
0xF4, 0x6C, /* SENSOR_NUM_THRSH_FINGER */
0xF4, 0x6D, /* DISCARD_SCAN */
0xF4, 0x6E, /* Reserved878 */
0xF4, 0x70, /* FINGER_THRESH_MUTUAL_ON */
0xF4, 0x72, /* FINGER_THRESH_MUTUAL_OFF */
0xF4, 0x74, /* Z_SCALING */
0xF4, 0x76, /* CA_FINGER_THRESHOLD_MUTUAL */
0xF4, 0x78, /* MULTI_TOUCH_DEBOUNCE */
0xF4, 0x79, /* Z9_FILTER_SCALE */
0xF4, 0x7A, /* CA_MULTI_TOUCH_DEBOUNCE */
0xF4, 0x7B, /* CA_Z9_FILTER_SCALE */
0xF4, 0x7C, /* MIN_FAT_FINGER_SIZE_HYST */
0xF4, 0x7D, /* MIN_FAT_FINGER_SIZE_ON */
0xF4, 0x7E, /* MAX_FAT_FINGER_SIZE_HYST */
0xF4, 0x7F, /* MAX_FAT_FINGER_SIZE_ON */
0xF4, 0x80, /* CA_MIN_FAT_FINGER_SIZE */
0xF4, 0x81, /* CA_MAX_FAT_FINGER_SIZE */
0xF4, 0x82, /* TOUCH_TRACKING_FEATURES */
0xF4, 0x83, /* SIGNAL_THRESHOLD_MULTIPLIER */
0xF4, 0x84, /* WF_FT_COEF */
0xF4, 0x85, /* WF_MT_DEBOUNCE */
0xF4, 0x86, /* RX_LINE_FILTER */
0xF4, 0x87, /* RX_LINE_FILTER_DEBOUNCE */
0xF4, 0x88, /* RX_LINE_FILTER_THRESHOLD */
0xF4, 0x89, /* Reserved905 */
0xF4, 0x8C, /* WF_Z8_MULTIPLIER */
0xF4, 0x8D, /* Reserved909 */
0xF4, 0x90, /* BTN_LS_ON_THRSH_MUT_0 */
0xF4, 0x91, /* BTN_LS_ON_THRSH_MUT_1 */
0xF4, 0x92, /* BTN_LS_ON_THRSH_MUT_2 */
0xF4, 0x93, /* BTN_LS_ON_THRSH_MUT_3 */
0xF4, 0x94, /* BTN_LS_OFF_THRSH_MUT_0 */
0xF4, 0x95, /* BTN_LS_OFF_THRSH_MUT_1 */
0xF4, 0x96, /* BTN_LS_OFF_THRSH_MUT_2 */
0xF4, 0x97, /* BTN_LS_OFF_THRSH_MUT_3 */
0xF4, 0x98, /* BTN_LS_ON_THRSH_SELF_0 */
0xF4, 0x99, /* BTN_LS_ON_THRSH_SELF_1 */
0xF4, 0x9A, /* BTN_LS_ON_THRSH_SELF_2 */
0xF4, 0x9B, /* BTN_LS_ON_THRSH_SELF_3 */
0xF4, 0x9C, /* BTN_LS_OFF_THRSH_SELF_0 */
0xF4, 0x9D, /* BTN_LS_OFF_THRSH_SELF_1 */
0xF4, 0x9E, /* BTN_LS_OFF_THRSH_SELF_2 */
0xF4, 0x9F, /* BTN_LS_OFF_THRSH_SELF_3 */
0xF4, 0xA0, /* BTN_LS_TOUCHDOWN_DEBOUNCE */
0xF4, 0xA2, /* Reserved930 */
0xF4, 0xA4, /* BTN_HS_ON_THRSH_MUT_0 */
0xF4, 0xA5, /* BTN_HS_ON_THRSH_MUT_1 */
0xF4, 0xA6, /* BTN_HS_ON_THRSH_MUT_2 */
0xF4, 0xA7, /* BTN_HS_ON_THRSH_MUT_3 */
0xF4, 0xA8, /* BTN_HS_OFF_THRSH_MUT_0 */
0xF4, 0xA9, /* BTN_HS_OFF_THRSH_MUT_1 */
0xF4, 0xAA, /* BTN_HS_OFF_THRSH_MUT_2 */
0xF4, 0xAB, /* BTN_HS_OFF_THRSH_MUT_3 */
0xF4, 0xAC, /* BTN_HS_ON_THRSH_SELF_0 */
0xF4, 0xAD, /* BTN_HS_ON_THRSH_SELF_1 */
0xF4, 0xAE, /* BTN_HS_ON_THRSH_SELF_2 */
0xF4, 0xAF, /* BTN_HS_ON_THRSH_SELF_3 */
0xF4, 0xB0, /* BTN_HS_OFF_THRSH_SELF_0 */
0xF4, 0xB1, /* BTN_HS_OFF_THRSH_SELF_1 */
0xF4, 0xB2, /* BTN_HS_OFF_THRSH_SELF_2 */
0xF4, 0xB3, /* BTN_HS_OFF_THRSH_SELF_3 */
0xF4, 0xB4, /* BTN_HS_TOUCHDOWN_DEBOUNCE */
0xF4, 0xB6, /* Reserved950 */
0xF4, 0xB8, /* GLOVE_BTN_FORBID_DEBOUNCE */
0xF4, 0xBA, /* GLOVE_BTN_TO_HIGHSEN_MODE_SWITCH_THRSH_MUT */
0xF4, 0xBC, /* GLOVE_BTN_TO_HIGHSEN_MODE_SWITCH_THRSH_SELF */
0xF4, 0xBE, /* GLOVE_BTN_TO_LOWSEN_MODE_SWITCH_THRSH_MUT */
0xF4, 0xC0, /* GLOVE_BTN_TO_LOWSEN_MODE_SWITCH_THRSH_SELF */
0xF4, 0xC2, /* GLOVE_BTN_MODE_SWITCH_DEBOUNCE */
0xF4, 0xC4, /* BTN_PROCESS_IF_TOUCH_DETECTED */
0xF4, 0xC5, /* Reserved965 */
0xF4, 0xC6, /* Reserved966 */
0xF4, 0xC8, /* TOUCHMODE_GLOVE_MAX_PEAK */
0xF4, 0xCA, /* GLOVE_ON_THRSH_MUTUAL */
0xF4, 0xCC, /* GLOVE_OFF_THRSH_MUTUAL */
0xF4, 0xCE, /* GLOVE_FIRST_TOUCH_DEBOUNCE */
0xF4, 0xCF, /* GLOVE_FIRST_TOUCH_DEBOUNCE_EDGE_MASK */
0xF4, 0xD0, /* GLOVE_MULTI_TOUCH_DEBOUNCE */
0xF4, 0xD1, /* GLOVE_Z8_FILTER_SCALE */
0xF4, 0xD2, /* GLOVE_Z9_FILTER_SCALE */
0xF4, 0xD3, /* GLOVE_GRIP_FILTER_SCALE */
0xF4, 0xD4, /* GLOVE_Z_SCALING */
0xF4, 0xD6, /* GLOVE_MAX_FAT_FINGER_SIZE */
0xF4, 0xD7, /* GLOVE_MAX_FAT_FINGER_HYST */
0xF4, 0xD8, /* GLOVE_MIN_FAT_FINGER_SIZE */
0xF4, 0xD9, /* GLOVE_MIN_FAT_FINGER_HYST */
0xF4, 0xDA, /* GLOVE_SIGNAL_THRESHOLD_MULTIPLIER */
0xF4, 0xDB, /* GLOVE_INNER_EDGE_GAIN */
0xF4, 0xDC, /* GLOVE_OUTER_EDGE_GAIN */
0xF4, 0xDD, /* Reserved989 */
0xF4, 0xDE, /* Reserved990 */
0xF4, 0xE0, /* XY_FILTER_MASK */
0xF4, 0xE4, /* XY_FILT_IIR_COEFF */
0xF4, 0xE8, /* XY_FILT_Z_IIR_COEFF */
0xF4, 0xEC, /* XY_FILT_XY_FAST_THR */
0xF4, 0xED, /* XY_FILT_XY_SLOW_THR */
0xF4, 0xEE, /* XY_FILT_IIR_FAST_COEFF */
0xF4, 0xEF, /* XY_FILT_PREDICTION_COEF */
0xF4, 0xF0, /* XY_FILTER_MASK_CA */
0xF4, 0xF4, /* XY_FILT_IIR_COEFF_CA */
0xF4, 0xF8, /* XY_FILT_Z_IIR_COEFF_CA */
0xF4, 0xFC, /* XY_FILT_XY_FAST_THR_CA */
0xF4, 0xFD, /* XY_FILT_XY_SLOW_THR_CA */
0xF4, 0xFE, /* XY_FILT_IIR_FAST_COEFF_CA */
0xF4, 0xFF, /* XY_FILT_PREDICTION_COEF_CA */
0xF5, 0x00, /* XY_FILT_EXTRA_IIR_FILTER */
0xF5, 0x01, /* XY_FILT_TOUCH_SIZE_IIR_COEFF */
0xF5, 0x02, /* XY_FILT_TOUCH_SIZE_HYST */
0xF5, 0x03, /* XY_FILT_TOUCH_ORIENTATION_IIR_COEFF */
0xF5, 0x04, /* XY_FILT_TOUCH_ORIENTATION_HYST */
0xF5, 0x05, /* Reserved1029 */
0xF5, 0x08, /* SIZE_ORIENTATION_ENABLE */
0xF5, 0x09, /* Reserved1033 */
0xF5, 0x0C, /* EXT_SYNC */
0xF5, 0x0D, /* PWR_CFG */
0xF5, 0x0E, /* CONFIG_VER */
0xF5, 0x10, /* SEND_REPORT_AFTER_ACTIVE_INTERVAL_CFG */
0xF5, 0x11, /* PIP_REPORTING_DISABLE */
0xF5, 0x12, /* INTERRUPT_PIN_OVERRIDE */
0xF5, 0x14, /* POST_CFG */
0xF5, 0x15, /* PINS_GND_GND */
0xF5, 0x16, /* PINS_GND_NC */
0xF5, 0x17, /* PINS_NC_GND */
0xF5, 0x18, /* PINS_NC_NC */
0xF5, 0x19, /* Reserved1049 */
0xF5, 0x1C, /* CONFIG_CRC */
};
#endif
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.content_linker_test_apk;
import android.util.Log;
import org.chromium.base.JNINamespace;
import org.chromium.content.app.Linker;
// A class that is only used in linker test APK to perform runtime checks
// in the current process.
@JNINamespace("content")
public class LinkerTests implements Linker.TestRunner {
private static final String TAG = "LinkerTests";
public LinkerTests() {}
public boolean runChecks(int memoryDeviceConfig,
boolean isBrowserProcess) {
boolean checkSharedRelro;
if (isBrowserProcess) {
switch (Linker.BROWSER_SHARED_RELRO_CONFIG) {
case Linker.BROWSER_SHARED_RELRO_CONFIG_NEVER:
checkSharedRelro = false;
break;
case Linker.BROWSER_SHARED_RELRO_CONFIG_LOW_RAM_ONLY:
// A shared RELRO should only be used on low-end devices.
checkSharedRelro =
(memoryDeviceConfig == Linker.MEMORY_DEVICE_CONFIG_LOW);
break;
case Linker.BROWSER_SHARED_RELRO_CONFIG_ALWAYS:
// Always check for a shared RELRO.
checkSharedRelro = true;
break;
default:
Log.e(TAG, "Invalid shared RELRO linker configuration: " +
Linker.BROWSER_SHARED_RELRO_CONFIG);
return false;
}
} else {
// Service processes should always use a shared RELRO section.
checkSharedRelro = true;
}
if (checkSharedRelro)
return nativeCheckForSharedRelros(isBrowserProcess);
else
return nativeCheckForNoSharedRelros(isBrowserProcess);
}
// Check that there are shared RELRO sections in the current process,
// and that they are properly mapped read-only. Returns true on success.
private static native boolean nativeCheckForSharedRelros(boolean isBrowserProcess);
// Check that there are no shared RELRO sections in the current process,
// return true on success.
private static native boolean nativeCheckForNoSharedRelros(boolean isBrowserProcess);
}
|
/* **************************************************************************
qgsrastershader.h - description
-------------------
begin : Fri Dec 28 2007
copyright : (C) 2007 by Peter J. Ersts
email : ersts@amnh.org
****************************************************************************/
/* **************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#ifndef QGSRASTERSHADER_H
#define QGSRASTERSHADER_H
#include "qgis_core.h"
#include "qgis_sip.h"
#include "qgsreadwritecontext.h"
class QDomDocument;
class QDomElement;
class QgsRasterShaderFunction;
/**
* \ingroup core
* \brief Interface for all raster shaders.
*/
class CORE_EXPORT QgsRasterShader
{
public:
QgsRasterShader( double minimumValue = 0.0, double maximumValue = 255.0 );
//! QgsRasterShader cannot be copied
QgsRasterShader( const QgsRasterShader &rh ) = delete;
//! QgsRasterShader cannot be copied
QgsRasterShader &operator=( const QgsRasterShader &rh ) = delete;
/*
*
* Non-Static Inline methods
*
*/
/**
* Returns the maximum value for the raster shader.
* \see setMaximumValue()
* \see minimumValue()
*/
double maximumValue() const { return mMaximumValue; }
/**
* Returns the minimum value for the raster shader.
* \see setMinimumValue()
* \see maximumValue()
*/
double minimumValue() const { return mMinimumValue; }
QgsRasterShaderFunction *rasterShaderFunction() { return mRasterShaderFunction.get(); }
const QgsRasterShaderFunction *rasterShaderFunction() const { return mRasterShaderFunction.get(); } SIP_SKIP
/*
*
* Non-Static methods
*
*/
/**
* Generates a new RGBA value based on one input \a value.
*
* \param value The original value to base a new RGBA value on
* \param returnRedValue The red component of the new RGBA value
* \param returnGreenValue The green component of the new RGBA value
* \param returnBlueValue The blue component of the new RGBA value
* \param returnAlpha The alpha component of the new RGBA value
* \return TRUE if the return values are valid otherwise FALSE
*/
bool shade( double value,
int *returnRedValue SIP_OUT,
int *returnGreenValue SIP_OUT,
int *returnBlueValue SIP_OUT,
int *returnAlpha SIP_OUT );
/**
* Generates a new RGBA value based on an original RGBA value.
* \param redValue The red component of the original value to base a new RGBA value on
* \param greenValue The green component of the original value to base a new RGBA value on
* \param blueValue The blue component of the original value to base a new RGBA value on
* \param alphaValue The alpha component of the original value to base a new RGBA value on
* \param returnRedValue The red component of the new RGBA value
* \param returnGreenValue The green component of the new RGBA value
* \param returnBlueValue The blue component of the new RGBA value
* \param returnAlpha The alpha component of the new RGBA value
* \return TRUE if the return values are valid otherwise FALSE
*/
bool shade( double redValue,
double greenValue,
double blueValue,
double alphaValue,
int *returnRedValue SIP_OUT,
int *returnGreenValue SIP_OUT,
int *returnBlueValue SIP_OUT,
int *returnAlpha SIP_OUT );
/**
* \brief A public method that allows the user to set their own shader \a function.
* \note Raster shader takes ownership of the shader function instance
*/
void setRasterShaderFunction( QgsRasterShaderFunction *function SIP_TRANSFER );
/**
* Sets the maximum \a value for the raster shader.
* \see setMinimumValue()
* \see maximumValue()
*/
void setMaximumValue( double value );
/**
* Sets the minimum \a value for the raster shader.
* \see setMaximumValue()
* \see minimumValue()
*/
void setMinimumValue( double value );
/**
* Writes shader state to an XML element.
*/
void writeXml( QDomDocument &doc, QDomElement &parent, const QgsReadWriteContext &context = QgsReadWriteContext() ) const;
/**
* Reads shader state from an XML element.
*/
void readXml( const QDomElement &elem, const QgsReadWriteContext &context = QgsReadWriteContext() );
private:
#ifdef SIP_RUN
QgsRasterShader( const QgsRasterShader &rh );
#endif
//! \brief User defineable minimum value for the raster shader
double mMinimumValue;
//! \brief user defineable maximum value for the raster shader
double mMaximumValue;
//! \brief Pointer to the shader function
std::unique_ptr< QgsRasterShaderFunction > mRasterShaderFunction;
};
#endif
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* linux/kernel/power/snapshot.c
*
* This file provides system snapshot/restore functionality for swsusp.
*
* Copyright (C) 1998-2005 Pavel Machek <pavel@ucw.cz>
* Copyright (C) 2006 Rafael J. Wysocki <rjw@sisk.pl>
*/
#define pr_fmt(fmt) "PM: hibernation: " fmt
#include <linux/version.h>
#include <linux/module.h>
#include <linux/mm.h>
#include <linux/suspend.h>
#include <linux/delay.h>
#include <linux/bitops.h>
#include <linux/spinlock.h>
#include <linux/kernel.h>
#include <linux/pm.h>
#include <linux/device.h>
#include <linux/init.h>
#include <linux/memblock.h>
#include <linux/nmi.h>
#include <linux/syscalls.h>
#include <linux/console.h>
#include <linux/highmem.h>
#include <linux/list.h>
#include <linux/slab.h>
#include <linux/compiler.h>
#include <linux/ktime.h>
#include <linux/set_memory.h>
#include <linux/uaccess.h>
#include <asm/mmu_context.h>
#include <asm/tlbflush.h>
#include <asm/io.h>
#include "power.h"
#if defined(CONFIG_STRICT_KERNEL_RWX) && defined(CONFIG_ARCH_HAS_SET_MEMORY)
static bool hibernate_restore_protection;
static bool hibernate_restore_protection_active;
void enable_restore_image_protection(void)
{
hibernate_restore_protection = true;
}
static inline void hibernate_restore_protection_begin(void)
{
hibernate_restore_protection_active = hibernate_restore_protection;
}
static inline void hibernate_restore_protection_end(void)
{
hibernate_restore_protection_active = false;
}
static inline void hibernate_restore_protect_page(void *page_address)
{
if (hibernate_restore_protection_active)
set_memory_ro((unsigned long)page_address, 1);
}
static inline void hibernate_restore_unprotect_page(void *page_address)
{
if (hibernate_restore_protection_active)
set_memory_rw((unsigned long)page_address, 1);
}
#else
static inline void hibernate_restore_protection_begin(void) {}
static inline void hibernate_restore_protection_end(void) {}
static inline void hibernate_restore_protect_page(void *page_address) {}
static inline void hibernate_restore_unprotect_page(void *page_address) {}
#endif /* CONFIG_STRICT_KERNEL_RWX && CONFIG_ARCH_HAS_SET_MEMORY */
/*
* The calls to set_direct_map_*() should not fail because remapping a page
* here means that we only update protection bits in an existing PTE.
* It is still worth to have a warning here if something changes and this
* will no longer be the case.
*/
static inline void hibernate_map_page(struct page *page)
{
if (IS_ENABLED(CONFIG_ARCH_HAS_SET_DIRECT_MAP)) {
int ret = set_direct_map_default_noflush(page);
if (ret)
pr_warn_once("Failed to remap page\n");
} else {
debug_pagealloc_map_pages(page, 1);
}
}
static inline void hibernate_unmap_page(struct page *page)
{
if (IS_ENABLED(CONFIG_ARCH_HAS_SET_DIRECT_MAP)) {
unsigned long addr = (unsigned long)page_address(page);
int ret = set_direct_map_invalid_noflush(page);
if (ret)
pr_warn_once("Failed to remap page\n");
flush_tlb_kernel_range(addr, addr + PAGE_SIZE);
} else {
debug_pagealloc_unmap_pages(page, 1);
}
}
static int swsusp_page_is_free(struct page *);
static void swsusp_set_page_forbidden(struct page *);
static void swsusp_unset_page_forbidden(struct page *);
/*
* Number of bytes to reserve for memory allocations made by device drivers
* from their ->freeze() and ->freeze_noirq() callbacks so that they don't
* cause image creation to fail (tunable via /sys/power/reserved_size).
*/
unsigned long reserved_size;
void __init hibernate_reserved_size_init(void)
{
reserved_size = SPARE_PAGES * PAGE_SIZE;
}
/*
* Preferred image size in bytes (tunable via /sys/power/image_size).
* When it is set to N, swsusp will do its best to ensure the image
* size will not exceed N bytes, but if that is impossible, it will
* try to create the smallest image possible.
*/
unsigned long image_size;
void __init hibernate_image_size_init(void)
{
image_size = ((totalram_pages() * 2) / 5) * PAGE_SIZE;
}
/*
* List of PBEs needed for restoring the pages that were allocated before
* the suspend and included in the suspend image, but have also been
* allocated by the "resume" kernel, so their contents cannot be written
* directly to their "original" page frames.
*/
struct pbe *restore_pblist;
/* struct linked_page is used to build chains of pages */
#define LINKED_PAGE_DATA_SIZE (PAGE_SIZE - sizeof(void *))
struct linked_page {
struct linked_page *next;
char data[LINKED_PAGE_DATA_SIZE];
} __packed;
/*
* List of "safe" pages (ie. pages that were not used by the image kernel
* before hibernation) that may be used as temporary storage for image kernel
* memory contents.
*/
static struct linked_page *safe_pages_list;
/* Pointer to an auxiliary buffer (1 page) */
static void *buffer;
#define PG_ANY 0
#define PG_SAFE 1
#define PG_UNSAFE_CLEAR 1
#define PG_UNSAFE_KEEP 0
static unsigned int allocated_unsafe_pages;
/**
* get_image_page - Allocate a page for a hibernation image.
* @gfp_mask: GFP mask for the allocation.
* @safe_needed: Get pages that were not used before hibernation (restore only)
*
* During image restoration, for storing the PBE list and the image data, we can
* only use memory pages that do not conflict with the pages used before
* hibernation. The "unsafe" pages have PageNosaveFree set and we count them
* using allocated_unsafe_pages.
*
* Each allocated image page is marked as PageNosave and PageNosaveFree so that
* swsusp_free() can release it.
*/
static void *get_image_page(gfp_t gfp_mask, int safe_needed)
{
void *res;
res = (void *)get_zeroed_page(gfp_mask);
if (safe_needed)
while (res && swsusp_page_is_free(virt_to_page(res))) {
/* The page is unsafe, mark it for swsusp_free() */
swsusp_set_page_forbidden(virt_to_page(res));
allocated_unsafe_pages++;
res = (void *)get_zeroed_page(gfp_mask);
}
if (res) {
swsusp_set_page_forbidden(virt_to_page(res));
swsusp_set_page_free(virt_to_page(res));
}
return res;
}
static void *__get_safe_page(gfp_t gfp_mask)
{
if (safe_pages_list) {
void *ret = safe_pages_list;
safe_pages_list = safe_pages_list->next;
memset(ret, 0, PAGE_SIZE);
return ret;
}
return get_image_page(gfp_mask, PG_SAFE);
}
unsigned long get_safe_page(gfp_t gfp_mask)
{
return (unsigned long)__get_safe_page(gfp_mask);
}
static struct page *alloc_image_page(gfp_t gfp_mask)
{
struct page *page;
page = alloc_page(gfp_mask);
if (page) {
swsusp_set_page_forbidden(page);
swsusp_set_page_free(page);
}
return page;
}
static void recycle_safe_page(void *page_address)
{
struct linked_page *lp = page_address;
lp->next = safe_pages_list;
safe_pages_list = lp;
}
/**
* free_image_page - Free a page allocated for hibernation image.
* @addr: Address of the page to free.
* @clear_nosave_free: If set, clear the PageNosaveFree bit for the page.
*
* The page to free should have been allocated by get_image_page() (page flags
* set by it are affected).
*/
static inline void free_image_page(void *addr, int clear_nosave_free)
{
struct page *page;
BUG_ON(!virt_addr_valid(addr));
page = virt_to_page(addr);
swsusp_unset_page_forbidden(page);
if (clear_nosave_free)
swsusp_unset_page_free(page);
__free_page(page);
}
static inline void free_list_of_pages(struct linked_page *list,
int clear_page_nosave)
{
while (list) {
struct linked_page *lp = list->next;
free_image_page(list, clear_page_nosave);
list = lp;
}
}
/*
* struct chain_allocator is used for allocating small objects out of
* a linked list of pages called 'the chain'.
*
* The chain grows each time when there is no room for a new object in
* the current page. The allocated objects cannot be freed individually.
* It is only possible to free them all at once, by freeing the entire
* chain.
*
* NOTE: The chain allocator may be inefficient if the allocated objects
* are not much smaller than PAGE_SIZE.
*/
struct chain_allocator {
struct linked_page *chain; /* the chain */
unsigned int used_space; /* total size of objects allocated out
of the current page */
gfp_t gfp_mask; /* mask for allocating pages */
int safe_needed; /* if set, only "safe" pages are allocated */
};
static void chain_init(struct chain_allocator *ca, gfp_t gfp_mask,
int safe_needed)
{
ca->chain = NULL;
ca->used_space = LINKED_PAGE_DATA_SIZE;
ca->gfp_mask = gfp_mask;
ca->safe_needed = safe_needed;
}
static void *chain_alloc(struct chain_allocator *ca, unsigned int size)
{
void *ret;
if (LINKED_PAGE_DATA_SIZE - ca->used_space < size) {
struct linked_page *lp;
lp = ca->safe_needed ? __get_safe_page(ca->gfp_mask) :
get_image_page(ca->gfp_mask, PG_ANY);
if (!lp)
return NULL;
lp->next = ca->chain;
ca->chain = lp;
ca->used_space = 0;
}
ret = ca->chain->data + ca->used_space;
ca->used_space += size;
return ret;
}
/**
* Data types related to memory bitmaps.
*
* Memory bitmap is a structure consisting of many linked lists of
* objects. The main list's elements are of type struct zone_bitmap
* and each of them corresonds to one zone. For each zone bitmap
* object there is a list of objects of type struct bm_block that
* represent each blocks of bitmap in which information is stored.
*
* struct memory_bitmap contains a pointer to the main list of zone
* bitmap objects, a struct bm_position used for browsing the bitmap,
* and a pointer to the list of pages used for allocating all of the
* zone bitmap objects and bitmap block objects.
*
* NOTE: It has to be possible to lay out the bitmap in memory
* using only allocations of order 0. Additionally, the bitmap is
* designed to work with arbitrary number of zones (this is over the
* top for now, but let's avoid making unnecessary assumptions ;-).
*
* struct zone_bitmap contains a pointer to a list of bitmap block
* objects and a pointer to the bitmap block object that has been
* most recently used for setting bits. Additionally, it contains the
* PFNs that correspond to the start and end of the represented zone.
*
* struct bm_block contains a pointer to the memory page in which
* information is stored (in the form of a block of bitmap)
* It also contains the pfns that correspond to the start and end of
* the represented memory area.
*
* The memory bitmap is organized as a radix tree to guarantee fast random
* access to the bits. There is one radix tree for each zone (as returned
* from create_mem_extents).
*
* One radix tree is represented by one struct mem_zone_bm_rtree. There are
* two linked lists for the nodes of the tree, one for the inner nodes and
* one for the leave nodes. The linked leave nodes are used for fast linear
* access of the memory bitmap.
*
* The struct rtree_node represents one node of the radix tree.
*/
#define BM_END_OF_MAP (~0UL)
#define BM_BITS_PER_BLOCK (PAGE_SIZE * BITS_PER_BYTE)
#define BM_BLOCK_SHIFT (PAGE_SHIFT + 3)
#define BM_BLOCK_MASK ((1UL << BM_BLOCK_SHIFT) - 1)
/*
* struct rtree_node is a wrapper struct to link the nodes
* of the rtree together for easy linear iteration over
* bits and easy freeing
*/
struct rtree_node {
struct list_head list;
unsigned long *data;
};
/*
* struct mem_zone_bm_rtree represents a bitmap used for one
* populated memory zone.
*/
struct mem_zone_bm_rtree {
struct list_head list; /* Link Zones together */
struct list_head nodes; /* Radix Tree inner nodes */
struct list_head leaves; /* Radix Tree leaves */
unsigned long start_pfn; /* Zone start page frame */
unsigned long end_pfn; /* Zone end page frame + 1 */
struct rtree_node *rtree; /* Radix Tree Root */
int levels; /* Number of Radix Tree Levels */
unsigned int blocks; /* Number of Bitmap Blocks */
};
/* strcut bm_position is used for browsing memory bitmaps */
struct bm_position {
struct mem_zone_bm_rtree *zone;
struct rtree_node *node;
unsigned long node_pfn;
int node_bit;
};
struct memory_bitmap {
struct list_head zones;
struct linked_page *p_list; /* list of pages used to store zone
bitmap objects and bitmap block
objects */
struct bm_position cur; /* most recently used bit position */
};
/* Functions that operate on memory bitmaps */
#define BM_ENTRIES_PER_LEVEL (PAGE_SIZE / sizeof(unsigned long))
#if BITS_PER_LONG == 32
#define BM_RTREE_LEVEL_SHIFT (PAGE_SHIFT - 2)
#else
#define BM_RTREE_LEVEL_SHIFT (PAGE_SHIFT - 3)
#endif
#define BM_RTREE_LEVEL_MASK ((1UL << BM_RTREE_LEVEL_SHIFT) - 1)
/**
* alloc_rtree_node - Allocate a new node and add it to the radix tree.
*
* This function is used to allocate inner nodes as well as the
* leave nodes of the radix tree. It also adds the node to the
* corresponding linked list passed in by the *list parameter.
*/
static struct rtree_node *alloc_rtree_node(gfp_t gfp_mask, int safe_needed,
struct chain_allocator *ca,
struct list_head *list)
{
struct rtree_node *node;
node = chain_alloc(ca, sizeof(struct rtree_node));
if (!node)
return NULL;
node->data = get_image_page(gfp_mask, safe_needed);
if (!node->data)
return NULL;
list_add_tail(&node->list, list);
return node;
}
/**
* add_rtree_block - Add a new leave node to the radix tree.
*
* The leave nodes need to be allocated in order to keep the leaves
* linked list in order. This is guaranteed by the zone->blocks
* counter.
*/
static int add_rtree_block(struct mem_zone_bm_rtree *zone, gfp_t gfp_mask,
int safe_needed, struct chain_allocator *ca)
{
struct rtree_node *node, *block, **dst;
unsigned int levels_needed, block_nr;
int i;
block_nr = zone->blocks;
levels_needed = 0;
/* How many levels do we need for this block nr? */
while (block_nr) {
levels_needed += 1;
block_nr >>= BM_RTREE_LEVEL_SHIFT;
}
/* Make sure the rtree has enough levels */
for (i = zone->levels; i < levels_needed; i++) {
node = alloc_rtree_node(gfp_mask, safe_needed, ca,
&zone->nodes);
if (!node)
return -ENOMEM;
node->data[0] = (unsigned long)zone->rtree;
zone->rtree = node;
zone->levels += 1;
}
/* Allocate new block */
block = alloc_rtree_node(gfp_mask, safe_needed, ca, &zone->leaves);
if (!block)
return -ENOMEM;
/* Now walk the rtree to insert the block */
node = zone->rtree;
dst = &zone->rtree;
block_nr = zone->blocks;
for (i = zone->levels; i > 0; i--) {
int index;
if (!node) {
node = alloc_rtree_node(gfp_mask, safe_needed, ca,
&zone->nodes);
if (!node)
return -ENOMEM;
*dst = node;
}
index = block_nr >> ((i - 1) * BM_RTREE_LEVEL_SHIFT);
index &= BM_RTREE_LEVEL_MASK;
dst = (struct rtree_node **)&((*dst)->data[index]);
node = *dst;
}
zone->blocks += 1;
*dst = block;
return 0;
}
static void free_zone_bm_rtree(struct mem_zone_bm_rtree *zone,
int clear_nosave_free);
/**
* create_zone_bm_rtree - Create a radix tree for one zone.
*
* Allocated the mem_zone_bm_rtree structure and initializes it.
* This function also allocated and builds the radix tree for the
* zone.
*/
static struct mem_zone_bm_rtree *create_zone_bm_rtree(gfp_t gfp_mask,
int safe_needed,
struct chain_allocator *ca,
unsigned long start,
unsigned long end)
{
struct mem_zone_bm_rtree *zone;
unsigned int i, nr_blocks;
unsigned long pages;
pages = end - start;
zone = chain_alloc(ca, sizeof(struct mem_zone_bm_rtree));
if (!zone)
return NULL;
INIT_LIST_HEAD(&zone->nodes);
INIT_LIST_HEAD(&zone->leaves);
zone->start_pfn = start;
zone->end_pfn = end;
nr_blocks = DIV_ROUND_UP(pages, BM_BITS_PER_BLOCK);
for (i = 0; i < nr_blocks; i++) {
if (add_rtree_block(zone, gfp_mask, safe_needed, ca)) {
free_zone_bm_rtree(zone, PG_UNSAFE_CLEAR);
return NULL;
}
}
return zone;
}
/**
* free_zone_bm_rtree - Free the memory of the radix tree.
*
* Free all node pages of the radix tree. The mem_zone_bm_rtree
* structure itself is not freed here nor are the rtree_node
* structs.
*/
static void free_zone_bm_rtree(struct mem_zone_bm_rtree *zone,
int clear_nosave_free)
{
struct rtree_node *node;
list_for_each_entry(node, &zone->nodes, list)
free_image_page(node->data, clear_nosave_free);
list_for_each_entry(node, &zone->leaves, list)
free_image_page(node->data, clear_nosave_free);
}
static void memory_bm_position_reset(struct memory_bitmap *bm)
{
bm->cur.zone = list_entry(bm->zones.next, struct mem_zone_bm_rtree,
list);
bm->cur.node = list_entry(bm->cur.zone->leaves.next,
struct rtree_node, list);
bm->cur.node_pfn = 0;
bm->cur.node_bit = 0;
}
static void memory_bm_free(struct memory_bitmap *bm, int clear_nosave_free);
struct mem_extent {
struct list_head hook;
unsigned long start;
unsigned long end;
};
/**
* free_mem_extents - Free a list of memory extents.
* @list: List of extents to free.
*/
static void free_mem_extents(struct list_head *list)
{
struct mem_extent *ext, *aux;
list_for_each_entry_safe(ext, aux, list, hook) {
list_del(&ext->hook);
kfree(ext);
}
}
/**
* create_mem_extents - Create a list of memory extents.
* @list: List to put the extents into.
* @gfp_mask: Mask to use for memory allocations.
*
* The extents represent contiguous ranges of PFNs.
*/
static int create_mem_extents(struct list_head *list, gfp_t gfp_mask)
{
struct zone *zone;
INIT_LIST_HEAD(list);
for_each_populated_zone(zone) {
unsigned long zone_start, zone_end;
struct mem_extent *ext, *cur, *aux;
zone_start = zone->zone_start_pfn;
zone_end = zone_end_pfn(zone);
list_for_each_entry(ext, list, hook)
if (zone_start <= ext->end)
break;
if (&ext->hook == list || zone_end < ext->start) {
/* New extent is necessary */
struct mem_extent *new_ext;
new_ext = kzalloc(sizeof(struct mem_extent), gfp_mask);
if (!new_ext) {
free_mem_extents(list);
return -ENOMEM;
}
new_ext->start = zone_start;
new_ext->end = zone_end;
list_add_tail(&new_ext->hook, &ext->hook);
continue;
}
/* Merge this zone's range of PFNs with the existing one */
if (zone_start < ext->start)
ext->start = zone_start;
if (zone_end > ext->end)
ext->end = zone_end;
/* More merging may be possible */
cur = ext;
list_for_each_entry_safe_continue(cur, aux, list, hook) {
if (zone_end < cur->start)
break;
if (zone_end < cur->end)
ext->end = cur->end;
list_del(&cur->hook);
kfree(cur);
}
}
return 0;
}
/**
* memory_bm_create - Allocate memory for a memory bitmap.
*/
static int memory_bm_create(struct memory_bitmap *bm, gfp_t gfp_mask,
int safe_needed)
{
struct chain_allocator ca;
struct list_head mem_extents;
struct mem_extent *ext;
int error;
chain_init(&ca, gfp_mask, safe_needed);
INIT_LIST_HEAD(&bm->zones);
error = create_mem_extents(&mem_extents, gfp_mask);
if (error)
return error;
list_for_each_entry(ext, &mem_extents, hook) {
struct mem_zone_bm_rtree *zone;
zone = create_zone_bm_rtree(gfp_mask, safe_needed, &ca,
ext->start, ext->end);
if (!zone) {
error = -ENOMEM;
goto Error;
}
list_add_tail(&zone->list, &bm->zones);
}
bm->p_list = ca.chain;
memory_bm_position_reset(bm);
Exit:
free_mem_extents(&mem_extents);
return error;
Error:
bm->p_list = ca.chain;
memory_bm_free(bm, PG_UNSAFE_CLEAR);
goto Exit;
}
/**
* memory_bm_free - Free memory occupied by the memory bitmap.
* @bm: Memory bitmap.
*/
static void memory_bm_free(struct memory_bitmap *bm, int clear_nosave_free)
{
struct mem_zone_bm_rtree *zone;
list_for_each_entry(zone, &bm->zones, list)
free_zone_bm_rtree(zone, clear_nosave_free);
free_list_of_pages(bm->p_list, clear_nosave_free);
INIT_LIST_HEAD(&bm->zones);
}
/**
* memory_bm_find_bit - Find the bit for a given PFN in a memory bitmap.
*
* Find the bit in memory bitmap @bm that corresponds to the given PFN.
* The cur.zone, cur.block and cur.node_pfn members of @bm are updated.
*
* Walk the radix tree to find the page containing the bit that represents @pfn
* and return the position of the bit in @addr and @bit_nr.
*/
static int memory_bm_find_bit(struct memory_bitmap *bm, unsigned long pfn,
void **addr, unsigned int *bit_nr)
{
struct mem_zone_bm_rtree *curr, *zone;
struct rtree_node *node;
int i, block_nr;
zone = bm->cur.zone;
if (pfn >= zone->start_pfn && pfn < zone->end_pfn)
goto zone_found;
zone = NULL;
/* Find the right zone */
list_for_each_entry(curr, &bm->zones, list) {
if (pfn >= curr->start_pfn && pfn < curr->end_pfn) {
zone = curr;
break;
}
}
if (!zone)
return -EFAULT;
zone_found:
/*
* We have found the zone. Now walk the radix tree to find the leaf node
* for our PFN.
*/
/*
* If the zone we wish to scan is the current zone and the
* pfn falls into the current node then we do not need to walk
* the tree.
*/
node = bm->cur.node;
if (zone == bm->cur.zone &&
((pfn - zone->start_pfn) & ~BM_BLOCK_MASK) == bm->cur.node_pfn)
goto node_found;
node = zone->rtree;
block_nr = (pfn - zone->start_pfn) >> BM_BLOCK_SHIFT;
for (i = zone->levels; i > 0; i--) {
int index;
index = block_nr >> ((i - 1) * BM_RTREE_LEVEL_SHIFT);
index &= BM_RTREE_LEVEL_MASK;
BUG_ON(node->data[index] == 0);
node = (struct rtree_node *)node->data[index];
}
node_found:
/* Update last position */
bm->cur.zone = zone;
bm->cur.node = node;
bm->cur.node_pfn = (pfn - zone->start_pfn) & ~BM_BLOCK_MASK;
/* Set return values */
*addr = node->data;
*bit_nr = (pfn - zone->start_pfn) & BM_BLOCK_MASK;
return 0;
}
static void memory_bm_set_bit(struct memory_bitmap *bm, unsigned long pfn)
{
void *addr;
unsigned int bit;
int error;
error = memory_bm_find_bit(bm, pfn, &addr, &bit);
BUG_ON(error);
set_bit(bit, addr);
}
static int mem_bm_set_bit_check(struct memory_bitmap *bm, unsigned long pfn)
{
void *addr;
unsigned int bit;
int error;
error = memory_bm_find_bit(bm, pfn, &addr, &bit);
if (!error)
set_bit(bit, addr);
return error;
}
static void memory_bm_clear_bit(struct memory_bitmap *bm, unsigned long pfn)
{
void *addr;
unsigned int bit;
int error;
error = memory_bm_find_bit(bm, pfn, &addr, &bit);
BUG_ON(error);
clear_bit(bit, addr);
}
static void memory_bm_clear_current(struct memory_bitmap *bm)
{
int bit;
bit = max(bm->cur.node_bit - 1, 0);
clear_bit(bit, bm->cur.node->data);
}
static int memory_bm_test_bit(struct memory_bitmap *bm, unsigned long pfn)
{
void *addr;
unsigned int bit;
int error;
error = memory_bm_find_bit(bm, pfn, &addr, &bit);
BUG_ON(error);
return test_bit(bit, addr);
}
static bool memory_bm_pfn_present(struct memory_bitmap *bm, unsigned long pfn)
{
void *addr;
unsigned int bit;
return !memory_bm_find_bit(bm, pfn, &addr, &bit);
}
/*
* rtree_next_node - Jump to the next leaf node.
*
* Set the position to the beginning of the next node in the
* memory bitmap. This is either the next node in the current
* zone's radix tree or the first node in the radix tree of the
* next zone.
*
* Return true if there is a next node, false otherwise.
*/
static bool rtree_next_node(struct memory_bitmap *bm)
{
if (!list_is_last(&bm->cur.node->list, &bm->cur.zone->leaves)) {
bm->cur.node = list_entry(bm->cur.node->list.next,
struct rtree_node, list);
bm->cur.node_pfn += BM_BITS_PER_BLOCK;
bm->cur.node_bit = 0;
touch_softlockup_watchdog();
return true;
}
/* No more nodes, goto next zone */
if (!list_is_last(&bm->cur.zone->list, &bm->zones)) {
bm->cur.zone = list_entry(bm->cur.zone->list.next,
struct mem_zone_bm_rtree, list);
bm->cur.node = list_entry(bm->cur.zone->leaves.next,
struct rtree_node, list);
bm->cur.node_pfn = 0;
bm->cur.node_bit = 0;
return true;
}
/* No more zones */
return false;
}
/**
* memory_bm_rtree_next_pfn - Find the next set bit in a memory bitmap.
* @bm: Memory bitmap.
*
* Starting from the last returned position this function searches for the next
* set bit in @bm and returns the PFN represented by it. If no more bits are
* set, BM_END_OF_MAP is returned.
*
* It is required to run memory_bm_position_reset() before the first call to
* this function for the given memory bitmap.
*/
static unsigned long memory_bm_next_pfn(struct memory_bitmap *bm)
{
unsigned long bits, pfn, pages;
int bit;
do {
pages = bm->cur.zone->end_pfn - bm->cur.zone->start_pfn;
bits = min(pages - bm->cur.node_pfn, BM_BITS_PER_BLOCK);
bit = find_next_bit(bm->cur.node->data, bits,
bm->cur.node_bit);
if (bit < bits) {
pfn = bm->cur.zone->start_pfn + bm->cur.node_pfn + bit;
bm->cur.node_bit = bit + 1;
return pfn;
}
} while (rtree_next_node(bm));
return BM_END_OF_MAP;
}
/*
* This structure represents a range of page frames the contents of which
* should not be saved during hibernation.
*/
struct nosave_region {
struct list_head list;
unsigned long start_pfn;
unsigned long end_pfn;
};
static LIST_HEAD(nosave_regions);
static void recycle_zone_bm_rtree(struct mem_zone_bm_rtree *zone)
{
struct rtree_node *node;
list_for_each_entry(node, &zone->nodes, list)
recycle_safe_page(node->data);
list_for_each_entry(node, &zone->leaves, list)
recycle_safe_page(node->data);
}
static void memory_bm_recycle(struct memory_bitmap *bm)
{
struct mem_zone_bm_rtree *zone;
struct linked_page *p_list;
list_for_each_entry(zone, &bm->zones, list)
recycle_zone_bm_rtree(zone);
p_list = bm->p_list;
while (p_list) {
struct linked_page *lp = p_list;
p_list = lp->next;
recycle_safe_page(lp);
}
}
/**
* register_nosave_region - Register a region of unsaveable memory.
*
* Register a range of page frames the contents of which should not be saved
* during hibernation (to be used in the early initialization code).
*/
void __init __register_nosave_region(unsigned long start_pfn,
unsigned long end_pfn, int use_kmalloc)
{
struct nosave_region *region;
if (start_pfn >= end_pfn)
return;
if (!list_empty(&nosave_regions)) {
/* Try to extend the previous region (they should be sorted) */
region = list_entry(nosave_regions.prev,
struct nosave_region, list);
if (region->end_pfn == start_pfn) {
region->end_pfn = end_pfn;
goto Report;
}
}
if (use_kmalloc) {
/* During init, this shouldn't fail */
region = kmalloc(sizeof(struct nosave_region), GFP_KERNEL);
BUG_ON(!region);
} else {
/* This allocation cannot fail */
region = memblock_alloc(sizeof(struct nosave_region),
SMP_CACHE_BYTES);
if (!region)
panic("%s: Failed to allocate %zu bytes\n", __func__,
sizeof(struct nosave_region));
}
region->start_pfn = start_pfn;
region->end_pfn = end_pfn;
list_add_tail(®ion->list, &nosave_regions);
Report:
pr_info("Registered nosave memory: [mem %#010llx-%#010llx]\n",
(unsigned long long) start_pfn << PAGE_SHIFT,
((unsigned long long) end_pfn << PAGE_SHIFT) - 1);
}
/*
* Set bits in this map correspond to the page frames the contents of which
* should not be saved during the suspend.
*/
static struct memory_bitmap *forbidden_pages_map;
/* Set bits in this map correspond to free page frames. */
static struct memory_bitmap *free_pages_map;
/*
* Each page frame allocated for creating the image is marked by setting the
* corresponding bits in forbidden_pages_map and free_pages_map simultaneously
*/
void swsusp_set_page_free(struct page *page)
{
if (free_pages_map)
memory_bm_set_bit(free_pages_map, page_to_pfn(page));
}
static int swsusp_page_is_free(struct page *page)
{
return free_pages_map ?
memory_bm_test_bit(free_pages_map, page_to_pfn(page)) : 0;
}
void swsusp_unset_page_free(struct page *page)
{
if (free_pages_map)
memory_bm_clear_bit(free_pages_map, page_to_pfn(page));
}
static void swsusp_set_page_forbidden(struct page *page)
{
if (forbidden_pages_map)
memory_bm_set_bit(forbidden_pages_map, page_to_pfn(page));
}
int swsusp_page_is_forbidden(struct page *page)
{
return forbidden_pages_map ?
memory_bm_test_bit(forbidden_pages_map, page_to_pfn(page)) : 0;
}
static void swsusp_unset_page_forbidden(struct page *page)
{
if (forbidden_pages_map)
memory_bm_clear_bit(forbidden_pages_map, page_to_pfn(page));
}
/**
* mark_nosave_pages - Mark pages that should not be saved.
* @bm: Memory bitmap.
*
* Set the bits in @bm that correspond to the page frames the contents of which
* should not be saved.
*/
static void mark_nosave_pages(struct memory_bitmap *bm)
{
struct nosave_region *region;
if (list_empty(&nosave_regions))
return;
list_for_each_entry(region, &nosave_regions, list) {
unsigned long pfn;
pr_debug("Marking nosave pages: [mem %#010llx-%#010llx]\n",
(unsigned long long) region->start_pfn << PAGE_SHIFT,
((unsigned long long) region->end_pfn << PAGE_SHIFT)
- 1);
for (pfn = region->start_pfn; pfn < region->end_pfn; pfn++)
if (pfn_valid(pfn)) {
/*
* It is safe to ignore the result of
* mem_bm_set_bit_check() here, since we won't
* touch the PFNs for which the error is
* returned anyway.
*/
mem_bm_set_bit_check(bm, pfn);
}
}
}
/**
* create_basic_memory_bitmaps - Create bitmaps to hold basic page information.
*
* Create bitmaps needed for marking page frames that should not be saved and
* free page frames. The forbidden_pages_map and free_pages_map pointers are
* only modified if everything goes well, because we don't want the bits to be
* touched before both bitmaps are set up.
*/
int create_basic_memory_bitmaps(void)
{
struct memory_bitmap *bm1, *bm2;
int error = 0;
if (forbidden_pages_map && free_pages_map)
return 0;
else
BUG_ON(forbidden_pages_map || free_pages_map);
bm1 = kzalloc(sizeof(struct memory_bitmap), GFP_KERNEL);
if (!bm1)
return -ENOMEM;
error = memory_bm_create(bm1, GFP_KERNEL, PG_ANY);
if (error)
goto Free_first_object;
bm2 = kzalloc(sizeof(struct memory_bitmap), GFP_KERNEL);
if (!bm2)
goto Free_first_bitmap;
error = memory_bm_create(bm2, GFP_KERNEL, PG_ANY);
if (error)
goto Free_second_object;
forbidden_pages_map = bm1;
free_pages_map = bm2;
mark_nosave_pages(forbidden_pages_map);
pr_debug("Basic memory bitmaps created\n");
return 0;
Free_second_object:
kfree(bm2);
Free_first_bitmap:
memory_bm_free(bm1, PG_UNSAFE_CLEAR);
Free_first_object:
kfree(bm1);
return -ENOMEM;
}
/**
* free_basic_memory_bitmaps - Free memory bitmaps holding basic information.
*
* Free memory bitmaps allocated by create_basic_memory_bitmaps(). The
* auxiliary pointers are necessary so that the bitmaps themselves are not
* referred to while they are being freed.
*/
void free_basic_memory_bitmaps(void)
{
struct memory_bitmap *bm1, *bm2;
if (WARN_ON(!(forbidden_pages_map && free_pages_map)))
return;
bm1 = forbidden_pages_map;
bm2 = free_pages_map;
forbidden_pages_map = NULL;
free_pages_map = NULL;
memory_bm_free(bm1, PG_UNSAFE_CLEAR);
kfree(bm1);
memory_bm_free(bm2, PG_UNSAFE_CLEAR);
kfree(bm2);
pr_debug("Basic memory bitmaps freed\n");
}
static void clear_or_poison_free_page(struct page *page)
{
if (page_poisoning_enabled_static())
__kernel_poison_pages(page, 1);
else if (want_init_on_free())
clear_highpage(page);
}
void clear_or_poison_free_pages(void)
{
struct memory_bitmap *bm = free_pages_map;
unsigned long pfn;
if (WARN_ON(!(free_pages_map)))
return;
if (page_poisoning_enabled() || want_init_on_free()) {
memory_bm_position_reset(bm);
pfn = memory_bm_next_pfn(bm);
while (pfn != BM_END_OF_MAP) {
if (pfn_valid(pfn))
clear_or_poison_free_page(pfn_to_page(pfn));
pfn = memory_bm_next_pfn(bm);
}
memory_bm_position_reset(bm);
pr_info("free pages cleared after restore\n");
}
}
/**
* snapshot_additional_pages - Estimate the number of extra pages needed.
* @zone: Memory zone to carry out the computation for.
*
* Estimate the number of additional pages needed for setting up a hibernation
* image data structures for @zone (usually, the returned value is greater than
* the exact number).
*/
unsigned int snapshot_additional_pages(struct zone *zone)
{
unsigned int rtree, nodes;
rtree = nodes = DIV_ROUND_UP(zone->spanned_pages, BM_BITS_PER_BLOCK);
rtree += DIV_ROUND_UP(rtree * sizeof(struct rtree_node),
LINKED_PAGE_DATA_SIZE);
while (nodes > 1) {
nodes = DIV_ROUND_UP(nodes, BM_ENTRIES_PER_LEVEL);
rtree += nodes;
}
return 2 * rtree;
}
#ifdef CONFIG_HIGHMEM
/**
* count_free_highmem_pages - Compute the total number of free highmem pages.
*
* The returned number is system-wide.
*/
static unsigned int count_free_highmem_pages(void)
{
struct zone *zone;
unsigned int cnt = 0;
for_each_populated_zone(zone)
if (is_highmem(zone))
cnt += zone_page_state(zone, NR_FREE_PAGES);
return cnt;
}
/**
* saveable_highmem_page - Check if a highmem page is saveable.
*
* Determine whether a highmem page should be included in a hibernation image.
*
* We should save the page if it isn't Nosave or NosaveFree, or Reserved,
* and it isn't part of a free chunk of pages.
*/
static struct page *saveable_highmem_page(struct zone *zone, unsigned long pfn)
{
struct page *page;
if (!pfn_valid(pfn))
return NULL;
page = pfn_to_online_page(pfn);
if (!page || page_zone(page) != zone)
return NULL;
BUG_ON(!PageHighMem(page));
if (swsusp_page_is_forbidden(page) || swsusp_page_is_free(page))
return NULL;
if (PageReserved(page) || PageOffline(page))
return NULL;
if (page_is_guard(page))
return NULL;
return page;
}
/**
* count_highmem_pages - Compute the total number of saveable highmem pages.
*/
static unsigned int count_highmem_pages(void)
{
struct zone *zone;
unsigned int n = 0;
for_each_populated_zone(zone) {
unsigned long pfn, max_zone_pfn;
if (!is_highmem(zone))
continue;
mark_free_pages(zone);
max_zone_pfn = zone_end_pfn(zone);
for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
if (saveable_highmem_page(zone, pfn))
n++;
}
return n;
}
#else
static inline void *saveable_highmem_page(struct zone *z, unsigned long p)
{
return NULL;
}
#endif /* CONFIG_HIGHMEM */
/**
* saveable_page - Check if the given page is saveable.
*
* Determine whether a non-highmem page should be included in a hibernation
* image.
*
* We should save the page if it isn't Nosave, and is not in the range
* of pages statically defined as 'unsaveable', and it isn't part of
* a free chunk of pages.
*/
static struct page *saveable_page(struct zone *zone, unsigned long pfn)
{
struct page *page;
if (!pfn_valid(pfn))
return NULL;
page = pfn_to_online_page(pfn);
if (!page || page_zone(page) != zone)
return NULL;
BUG_ON(PageHighMem(page));
if (swsusp_page_is_forbidden(page) || swsusp_page_is_free(page))
return NULL;
if (PageOffline(page))
return NULL;
if (PageReserved(page)
&& (!kernel_page_present(page) || pfn_is_nosave(pfn)))
return NULL;
if (page_is_guard(page))
return NULL;
return page;
}
/**
* count_data_pages - Compute the total number of saveable non-highmem pages.
*/
static unsigned int count_data_pages(void)
{
struct zone *zone;
unsigned long pfn, max_zone_pfn;
unsigned int n = 0;
for_each_populated_zone(zone) {
if (is_highmem(zone))
continue;
mark_free_pages(zone);
max_zone_pfn = zone_end_pfn(zone);
for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
if (saveable_page(zone, pfn))
n++;
}
return n;
}
/*
* This is needed, because copy_page and memcpy are not usable for copying
* task structs.
*/
static inline void do_copy_page(long *dst, long *src)
{
int n;
for (n = PAGE_SIZE / sizeof(long); n; n--)
*dst++ = *src++;
}
/**
* safe_copy_page - Copy a page in a safe way.
*
* Check if the page we are going to copy is marked as present in the kernel
* page tables. This always is the case if CONFIG_DEBUG_PAGEALLOC or
* CONFIG_ARCH_HAS_SET_DIRECT_MAP is not set. In that case kernel_page_present()
* always returns 'true'.
*/
static void safe_copy_page(void *dst, struct page *s_page)
{
if (kernel_page_present(s_page)) {
do_copy_page(dst, page_address(s_page));
} else {
hibernate_map_page(s_page);
do_copy_page(dst, page_address(s_page));
hibernate_unmap_page(s_page);
}
}
#ifdef CONFIG_HIGHMEM
static inline struct page *page_is_saveable(struct zone *zone, unsigned long pfn)
{
return is_highmem(zone) ?
saveable_highmem_page(zone, pfn) : saveable_page(zone, pfn);
}
static void copy_data_page(unsigned long dst_pfn, unsigned long src_pfn)
{
struct page *s_page, *d_page;
void *src, *dst;
s_page = pfn_to_page(src_pfn);
d_page = pfn_to_page(dst_pfn);
if (PageHighMem(s_page)) {
src = kmap_atomic(s_page);
dst = kmap_atomic(d_page);
do_copy_page(dst, src);
kunmap_atomic(dst);
kunmap_atomic(src);
} else {
if (PageHighMem(d_page)) {
/*
* The page pointed to by src may contain some kernel
* data modified by kmap_atomic()
*/
safe_copy_page(buffer, s_page);
dst = kmap_atomic(d_page);
copy_page(dst, buffer);
kunmap_atomic(dst);
} else {
safe_copy_page(page_address(d_page), s_page);
}
}
}
#else
#define page_is_saveable(zone, pfn) saveable_page(zone, pfn)
static inline void copy_data_page(unsigned long dst_pfn, unsigned long src_pfn)
{
safe_copy_page(page_address(pfn_to_page(dst_pfn)),
pfn_to_page(src_pfn));
}
#endif /* CONFIG_HIGHMEM */
static void copy_data_pages(struct memory_bitmap *copy_bm,
struct memory_bitmap *orig_bm)
{
struct zone *zone;
unsigned long pfn;
for_each_populated_zone(zone) {
unsigned long max_zone_pfn;
mark_free_pages(zone);
max_zone_pfn = zone_end_pfn(zone);
for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
if (page_is_saveable(zone, pfn))
memory_bm_set_bit(orig_bm, pfn);
}
memory_bm_position_reset(orig_bm);
memory_bm_position_reset(copy_bm);
for(;;) {
pfn = memory_bm_next_pfn(orig_bm);
if (unlikely(pfn == BM_END_OF_MAP))
break;
copy_data_page(memory_bm_next_pfn(copy_bm), pfn);
}
}
/* Total number of image pages */
static unsigned int nr_copy_pages;
/* Number of pages needed for saving the original pfns of the image pages */
static unsigned int nr_meta_pages;
/*
* Numbers of normal and highmem page frames allocated for hibernation image
* before suspending devices.
*/
static unsigned int alloc_normal, alloc_highmem;
/*
* Memory bitmap used for marking saveable pages (during hibernation) or
* hibernation image pages (during restore)
*/
static struct memory_bitmap orig_bm;
/*
* Memory bitmap used during hibernation for marking allocated page frames that
* will contain copies of saveable pages. During restore it is initially used
* for marking hibernation image pages, but then the set bits from it are
* duplicated in @orig_bm and it is released. On highmem systems it is next
* used for marking "safe" highmem pages, but it has to be reinitialized for
* this purpose.
*/
static struct memory_bitmap copy_bm;
/**
* swsusp_free - Free pages allocated for hibernation image.
*
* Image pages are alocated before snapshot creation, so they need to be
* released after resume.
*/
void swsusp_free(void)
{
unsigned long fb_pfn, fr_pfn;
if (!forbidden_pages_map || !free_pages_map)
goto out;
memory_bm_position_reset(forbidden_pages_map);
memory_bm_position_reset(free_pages_map);
loop:
fr_pfn = memory_bm_next_pfn(free_pages_map);
fb_pfn = memory_bm_next_pfn(forbidden_pages_map);
/*
* Find the next bit set in both bitmaps. This is guaranteed to
* terminate when fb_pfn == fr_pfn == BM_END_OF_MAP.
*/
do {
if (fb_pfn < fr_pfn)
fb_pfn = memory_bm_next_pfn(forbidden_pages_map);
if (fr_pfn < fb_pfn)
fr_pfn = memory_bm_next_pfn(free_pages_map);
} while (fb_pfn != fr_pfn);
if (fr_pfn != BM_END_OF_MAP && pfn_valid(fr_pfn)) {
struct page *page = pfn_to_page(fr_pfn);
memory_bm_clear_current(forbidden_pages_map);
memory_bm_clear_current(free_pages_map);
hibernate_restore_unprotect_page(page_address(page));
__free_page(page);
goto loop;
}
out:
nr_copy_pages = 0;
nr_meta_pages = 0;
restore_pblist = NULL;
buffer = NULL;
alloc_normal = 0;
alloc_highmem = 0;
hibernate_restore_protection_end();
}
/* Helper functions used for the shrinking of memory. */
#define GFP_IMAGE (GFP_KERNEL | __GFP_NOWARN)
/**
* preallocate_image_pages - Allocate a number of pages for hibernation image.
* @nr_pages: Number of page frames to allocate.
* @mask: GFP flags to use for the allocation.
*
* Return value: Number of page frames actually allocated
*/
static unsigned long preallocate_image_pages(unsigned long nr_pages, gfp_t mask)
{
unsigned long nr_alloc = 0;
while (nr_pages > 0) {
struct page *page;
page = alloc_image_page(mask);
if (!page)
break;
memory_bm_set_bit(©_bm, page_to_pfn(page));
if (PageHighMem(page))
alloc_highmem++;
else
alloc_normal++;
nr_pages--;
nr_alloc++;
}
return nr_alloc;
}
static unsigned long preallocate_image_memory(unsigned long nr_pages,
unsigned long avail_normal)
{
unsigned long alloc;
if (avail_normal <= alloc_normal)
return 0;
alloc = avail_normal - alloc_normal;
if (nr_pages < alloc)
alloc = nr_pages;
return preallocate_image_pages(alloc, GFP_IMAGE);
}
#ifdef CONFIG_HIGHMEM
static unsigned long preallocate_image_highmem(unsigned long nr_pages)
{
return preallocate_image_pages(nr_pages, GFP_IMAGE | __GFP_HIGHMEM);
}
/**
* __fraction - Compute (an approximation of) x * (multiplier / base).
*/
static unsigned long __fraction(u64 x, u64 multiplier, u64 base)
{
return div64_u64(x * multiplier, base);
}
static unsigned long preallocate_highmem_fraction(unsigned long nr_pages,
unsigned long highmem,
unsigned long total)
{
unsigned long alloc = __fraction(nr_pages, highmem, total);
return preallocate_image_pages(alloc, GFP_IMAGE | __GFP_HIGHMEM);
}
#else /* CONFIG_HIGHMEM */
static inline unsigned long preallocate_image_highmem(unsigned long nr_pages)
{
return 0;
}
static inline unsigned long preallocate_highmem_fraction(unsigned long nr_pages,
unsigned long highmem,
unsigned long total)
{
return 0;
}
#endif /* CONFIG_HIGHMEM */
/**
* free_unnecessary_pages - Release preallocated pages not needed for the image.
*/
static unsigned long free_unnecessary_pages(void)
{
unsigned long save, to_free_normal, to_free_highmem, free;
save = count_data_pages();
if (alloc_normal >= save) {
to_free_normal = alloc_normal - save;
save = 0;
} else {
to_free_normal = 0;
save -= alloc_normal;
}
save += count_highmem_pages();
if (alloc_highmem >= save) {
to_free_highmem = alloc_highmem - save;
} else {
to_free_highmem = 0;
save -= alloc_highmem;
if (to_free_normal > save)
to_free_normal -= save;
else
to_free_normal = 0;
}
free = to_free_normal + to_free_highmem;
memory_bm_position_reset(©_bm);
while (to_free_normal > 0 || to_free_highmem > 0) {
unsigned long pfn = memory_bm_next_pfn(©_bm);
struct page *page = pfn_to_page(pfn);
if (PageHighMem(page)) {
if (!to_free_highmem)
continue;
to_free_highmem--;
alloc_highmem--;
} else {
if (!to_free_normal)
continue;
to_free_normal--;
alloc_normal--;
}
memory_bm_clear_bit(©_bm, pfn);
swsusp_unset_page_forbidden(page);
swsusp_unset_page_free(page);
__free_page(page);
}
return free;
}
/**
* minimum_image_size - Estimate the minimum acceptable size of an image.
* @saveable: Number of saveable pages in the system.
*
* We want to avoid attempting to free too much memory too hard, so estimate the
* minimum acceptable size of a hibernation image to use as the lower limit for
* preallocating memory.
*
* We assume that the minimum image size should be proportional to
*
* [number of saveable pages] - [number of pages that can be freed in theory]
*
* where the second term is the sum of (1) reclaimable slab pages, (2) active
* and (3) inactive anonymous pages, (4) active and (5) inactive file pages.
*/
static unsigned long minimum_image_size(unsigned long saveable)
{
unsigned long size;
size = global_node_page_state_pages(NR_SLAB_RECLAIMABLE_B)
+ global_node_page_state(NR_ACTIVE_ANON)
+ global_node_page_state(NR_INACTIVE_ANON)
+ global_node_page_state(NR_ACTIVE_FILE)
+ global_node_page_state(NR_INACTIVE_FILE);
return saveable <= size ? 0 : saveable - size;
}
/**
* hibernate_preallocate_memory - Preallocate memory for hibernation image.
*
* To create a hibernation image it is necessary to make a copy of every page
* frame in use. We also need a number of page frames to be free during
* hibernation for allocations made while saving the image and for device
* drivers, in case they need to allocate memory from their hibernation
* callbacks (these two numbers are given by PAGES_FOR_IO (which is a rough
* estimate) and reserved_size divided by PAGE_SIZE (which is tunable through
* /sys/power/reserved_size, respectively). To make this happen, we compute the
* total number of available page frames and allocate at least
*
* ([page frames total] + PAGES_FOR_IO + [metadata pages]) / 2
* + 2 * DIV_ROUND_UP(reserved_size, PAGE_SIZE)
*
* of them, which corresponds to the maximum size of a hibernation image.
*
* If image_size is set below the number following from the above formula,
* the preallocation of memory is continued until the total number of saveable
* pages in the system is below the requested image size or the minimum
* acceptable image size returned by minimum_image_size(), whichever is greater.
*/
int hibernate_preallocate_memory(void)
{
struct zone *zone;
unsigned long saveable, size, max_size, count, highmem, pages = 0;
unsigned long alloc, save_highmem, pages_highmem, avail_normal;
ktime_t start, stop;
int error;
pr_info("Preallocating image memory\n");
start = ktime_get();
error = memory_bm_create(&orig_bm, GFP_IMAGE, PG_ANY);
if (error) {
pr_err("Cannot allocate original bitmap\n");
goto err_out;
}
error = memory_bm_create(©_bm, GFP_IMAGE, PG_ANY);
if (error) {
pr_err("Cannot allocate copy bitmap\n");
goto err_out;
}
alloc_normal = 0;
alloc_highmem = 0;
/* Count the number of saveable data pages. */
save_highmem = count_highmem_pages();
saveable = count_data_pages();
/*
* Compute the total number of page frames we can use (count) and the
* number of pages needed for image metadata (size).
*/
count = saveable;
saveable += save_highmem;
highmem = save_highmem;
size = 0;
for_each_populated_zone(zone) {
size += snapshot_additional_pages(zone);
if (is_highmem(zone))
highmem += zone_page_state(zone, NR_FREE_PAGES);
else
count += zone_page_state(zone, NR_FREE_PAGES);
}
avail_normal = count;
count += highmem;
count -= totalreserve_pages;
/* Compute the maximum number of saveable pages to leave in memory. */
max_size = (count - (size + PAGES_FOR_IO)) / 2
- 2 * DIV_ROUND_UP(reserved_size, PAGE_SIZE);
/* Compute the desired number of image pages specified by image_size. */
size = DIV_ROUND_UP(image_size, PAGE_SIZE);
if (size > max_size)
size = max_size;
/*
* If the desired number of image pages is at least as large as the
* current number of saveable pages in memory, allocate page frames for
* the image and we're done.
*/
if (size >= saveable) {
pages = preallocate_image_highmem(save_highmem);
pages += preallocate_image_memory(saveable - pages, avail_normal);
goto out;
}
/* Estimate the minimum size of the image. */
pages = minimum_image_size(saveable);
/*
* To avoid excessive pressure on the normal zone, leave room in it to
* accommodate an image of the minimum size (unless it's already too
* small, in which case don't preallocate pages from it at all).
*/
if (avail_normal > pages)
avail_normal -= pages;
else
avail_normal = 0;
if (size < pages)
size = min_t(unsigned long, pages, max_size);
/*
* Let the memory management subsystem know that we're going to need a
* large number of page frames to allocate and make it free some memory.
* NOTE: If this is not done, performance will be hurt badly in some
* test cases.
*/
shrink_all_memory(saveable - size);
/*
* The number of saveable pages in memory was too high, so apply some
* pressure to decrease it. First, make room for the largest possible
* image and fail if that doesn't work. Next, try to decrease the size
* of the image as much as indicated by 'size' using allocations from
* highmem and non-highmem zones separately.
*/
pages_highmem = preallocate_image_highmem(highmem / 2);
alloc = count - max_size;
if (alloc > pages_highmem)
alloc -= pages_highmem;
else
alloc = 0;
pages = preallocate_image_memory(alloc, avail_normal);
if (pages < alloc) {
/* We have exhausted non-highmem pages, try highmem. */
alloc -= pages;
pages += pages_highmem;
pages_highmem = preallocate_image_highmem(alloc);
if (pages_highmem < alloc) {
pr_err("Image allocation is %lu pages short\n",
alloc - pages_highmem);
goto err_out;
}
pages += pages_highmem;
/*
* size is the desired number of saveable pages to leave in
* memory, so try to preallocate (all memory - size) pages.
*/
alloc = (count - pages) - size;
pages += preallocate_image_highmem(alloc);
} else {
/*
* There are approximately max_size saveable pages at this point
* and we want to reduce this number down to size.
*/
alloc = max_size - size;
size = preallocate_highmem_fraction(alloc, highmem, count);
pages_highmem += size;
alloc -= size;
size = preallocate_image_memory(alloc, avail_normal);
pages_highmem += preallocate_image_highmem(alloc - size);
pages += pages_highmem + size;
}
/*
* We only need as many page frames for the image as there are saveable
* pages in memory, but we have allocated more. Release the excessive
* ones now.
*/
pages -= free_unnecessary_pages();
out:
stop = ktime_get();
pr_info("Allocated %lu pages for snapshot\n", pages);
swsusp_show_speed(start, stop, pages, "Allocated");
return 0;
err_out:
swsusp_free();
return -ENOMEM;
}
#ifdef CONFIG_HIGHMEM
/**
* count_pages_for_highmem - Count non-highmem pages needed for copying highmem.
*
* Compute the number of non-highmem pages that will be necessary for creating
* copies of highmem pages.
*/
static unsigned int count_pages_for_highmem(unsigned int nr_highmem)
{
unsigned int free_highmem = count_free_highmem_pages() + alloc_highmem;
if (free_highmem >= nr_highmem)
nr_highmem = 0;
else
nr_highmem -= free_highmem;
return nr_highmem;
}
#else
static unsigned int count_pages_for_highmem(unsigned int nr_highmem) { return 0; }
#endif /* CONFIG_HIGHMEM */
/**
* enough_free_mem - Check if there is enough free memory for the image.
*/
static int enough_free_mem(unsigned int nr_pages, unsigned int nr_highmem)
{
struct zone *zone;
unsigned int free = alloc_normal;
for_each_populated_zone(zone)
if (!is_highmem(zone))
free += zone_page_state(zone, NR_FREE_PAGES);
nr_pages += count_pages_for_highmem(nr_highmem);
pr_debug("Normal pages needed: %u + %u, available pages: %u\n",
nr_pages, PAGES_FOR_IO, free);
return free > nr_pages + PAGES_FOR_IO;
}
#ifdef CONFIG_HIGHMEM
/**
* get_highmem_buffer - Allocate a buffer for highmem pages.
*
* If there are some highmem pages in the hibernation image, we may need a
* buffer to copy them and/or load their data.
*/
static inline int get_highmem_buffer(int safe_needed)
{
buffer = get_image_page(GFP_ATOMIC, safe_needed);
return buffer ? 0 : -ENOMEM;
}
/**
* alloc_highmem_image_pages - Allocate some highmem pages for the image.
*
* Try to allocate as many pages as needed, but if the number of free highmem
* pages is less than that, allocate them all.
*/
static inline unsigned int alloc_highmem_pages(struct memory_bitmap *bm,
unsigned int nr_highmem)
{
unsigned int to_alloc = count_free_highmem_pages();
if (to_alloc > nr_highmem)
to_alloc = nr_highmem;
nr_highmem -= to_alloc;
while (to_alloc-- > 0) {
struct page *page;
page = alloc_image_page(__GFP_HIGHMEM|__GFP_KSWAPD_RECLAIM);
memory_bm_set_bit(bm, page_to_pfn(page));
}
return nr_highmem;
}
#else
static inline int get_highmem_buffer(int safe_needed) { return 0; }
static inline unsigned int alloc_highmem_pages(struct memory_bitmap *bm,
unsigned int n) { return 0; }
#endif /* CONFIG_HIGHMEM */
/**
* swsusp_alloc - Allocate memory for hibernation image.
*
* We first try to allocate as many highmem pages as there are
* saveable highmem pages in the system. If that fails, we allocate
* non-highmem pages for the copies of the remaining highmem ones.
*
* In this approach it is likely that the copies of highmem pages will
* also be located in the high memory, because of the way in which
* copy_data_pages() works.
*/
static int swsusp_alloc(struct memory_bitmap *copy_bm,
unsigned int nr_pages, unsigned int nr_highmem)
{
if (nr_highmem > 0) {
if (get_highmem_buffer(PG_ANY))
goto err_out;
if (nr_highmem > alloc_highmem) {
nr_highmem -= alloc_highmem;
nr_pages += alloc_highmem_pages(copy_bm, nr_highmem);
}
}
if (nr_pages > alloc_normal) {
nr_pages -= alloc_normal;
while (nr_pages-- > 0) {
struct page *page;
page = alloc_image_page(GFP_ATOMIC);
if (!page)
goto err_out;
memory_bm_set_bit(copy_bm, page_to_pfn(page));
}
}
return 0;
err_out:
swsusp_free();
return -ENOMEM;
}
asmlinkage __visible int swsusp_save(void)
{
unsigned int nr_pages, nr_highmem;
pr_info("Creating image:\n");
drain_local_pages(NULL);
nr_pages = count_data_pages();
nr_highmem = count_highmem_pages();
pr_info("Need to copy %u pages\n", nr_pages + nr_highmem);
if (!enough_free_mem(nr_pages, nr_highmem)) {
pr_err("Not enough free memory\n");
return -ENOMEM;
}
if (swsusp_alloc(©_bm, nr_pages, nr_highmem)) {
pr_err("Memory allocation failed\n");
return -ENOMEM;
}
/*
* During allocating of suspend pagedir, new cold pages may appear.
* Kill them.
*/
drain_local_pages(NULL);
copy_data_pages(©_bm, &orig_bm);
/*
* End of critical section. From now on, we can write to memory,
* but we should not touch disk. This specially means we must _not_
* touch swap space! Except we must write out our image of course.
*/
nr_pages += nr_highmem;
nr_copy_pages = nr_pages;
nr_meta_pages = DIV_ROUND_UP(nr_pages * sizeof(long), PAGE_SIZE);
pr_info("Image created (%d pages copied)\n", nr_pages);
return 0;
}
#ifndef CONFIG_ARCH_HIBERNATION_HEADER
static int init_header_complete(struct swsusp_info *info)
{
memcpy(&info->uts, init_utsname(), sizeof(struct new_utsname));
info->version_code = LINUX_VERSION_CODE;
return 0;
}
static const char *check_image_kernel(struct swsusp_info *info)
{
if (info->version_code != LINUX_VERSION_CODE)
return "kernel version";
if (strcmp(info->uts.sysname,init_utsname()->sysname))
return "system type";
if (strcmp(info->uts.release,init_utsname()->release))
return "kernel release";
if (strcmp(info->uts.version,init_utsname()->version))
return "version";
if (strcmp(info->uts.machine,init_utsname()->machine))
return "machine";
return NULL;
}
#endif /* CONFIG_ARCH_HIBERNATION_HEADER */
unsigned long snapshot_get_image_size(void)
{
return nr_copy_pages + nr_meta_pages + 1;
}
static int init_header(struct swsusp_info *info)
{
memset(info, 0, sizeof(struct swsusp_info));
info->num_physpages = get_num_physpages();
info->image_pages = nr_copy_pages;
info->pages = snapshot_get_image_size();
info->size = info->pages;
info->size <<= PAGE_SHIFT;
return init_header_complete(info);
}
/**
* pack_pfns - Prepare PFNs for saving.
* @bm: Memory bitmap.
* @buf: Memory buffer to store the PFNs in.
*
* PFNs corresponding to set bits in @bm are stored in the area of memory
* pointed to by @buf (1 page at a time).
*/
static inline void pack_pfns(unsigned long *buf, struct memory_bitmap *bm)
{
int j;
for (j = 0; j < PAGE_SIZE / sizeof(long); j++) {
buf[j] = memory_bm_next_pfn(bm);
if (unlikely(buf[j] == BM_END_OF_MAP))
break;
}
}
/**
* snapshot_read_next - Get the address to read the next image page from.
* @handle: Snapshot handle to be used for the reading.
*
* On the first call, @handle should point to a zeroed snapshot_handle
* structure. The structure gets populated then and a pointer to it should be
* passed to this function every next time.
*
* On success, the function returns a positive number. Then, the caller
* is allowed to read up to the returned number of bytes from the memory
* location computed by the data_of() macro.
*
* The function returns 0 to indicate the end of the data stream condition,
* and negative numbers are returned on errors. If that happens, the structure
* pointed to by @handle is not updated and should not be used any more.
*/
int snapshot_read_next(struct snapshot_handle *handle)
{
if (handle->cur > nr_meta_pages + nr_copy_pages)
return 0;
if (!buffer) {
/* This makes the buffer be freed by swsusp_free() */
buffer = get_image_page(GFP_ATOMIC, PG_ANY);
if (!buffer)
return -ENOMEM;
}
if (!handle->cur) {
int error;
error = init_header((struct swsusp_info *)buffer);
if (error)
return error;
handle->buffer = buffer;
memory_bm_position_reset(&orig_bm);
memory_bm_position_reset(©_bm);
} else if (handle->cur <= nr_meta_pages) {
clear_page(buffer);
pack_pfns(buffer, &orig_bm);
} else {
struct page *page;
page = pfn_to_page(memory_bm_next_pfn(©_bm));
if (PageHighMem(page)) {
/*
* Highmem pages are copied to the buffer,
* because we can't return with a kmapped
* highmem page (we may not be called again).
*/
void *kaddr;
kaddr = kmap_atomic(page);
copy_page(buffer, kaddr);
kunmap_atomic(kaddr);
handle->buffer = buffer;
} else {
handle->buffer = page_address(page);
}
}
handle->cur++;
return PAGE_SIZE;
}
static void duplicate_memory_bitmap(struct memory_bitmap *dst,
struct memory_bitmap *src)
{
unsigned long pfn;
memory_bm_position_reset(src);
pfn = memory_bm_next_pfn(src);
while (pfn != BM_END_OF_MAP) {
memory_bm_set_bit(dst, pfn);
pfn = memory_bm_next_pfn(src);
}
}
/**
* mark_unsafe_pages - Mark pages that were used before hibernation.
*
* Mark the pages that cannot be used for storing the image during restoration,
* because they conflict with the pages that had been used before hibernation.
*/
static void mark_unsafe_pages(struct memory_bitmap *bm)
{
unsigned long pfn;
/* Clear the "free"/"unsafe" bit for all PFNs */
memory_bm_position_reset(free_pages_map);
pfn = memory_bm_next_pfn(free_pages_map);
while (pfn != BM_END_OF_MAP) {
memory_bm_clear_current(free_pages_map);
pfn = memory_bm_next_pfn(free_pages_map);
}
/* Mark pages that correspond to the "original" PFNs as "unsafe" */
duplicate_memory_bitmap(free_pages_map, bm);
allocated_unsafe_pages = 0;
}
static int check_header(struct swsusp_info *info)
{
const char *reason;
reason = check_image_kernel(info);
if (!reason && info->num_physpages != get_num_physpages())
reason = "memory size";
if (reason) {
pr_err("Image mismatch: %s\n", reason);
return -EPERM;
}
return 0;
}
/**
* load header - Check the image header and copy the data from it.
*/
static int load_header(struct swsusp_info *info)
{
int error;
restore_pblist = NULL;
error = check_header(info);
if (!error) {
nr_copy_pages = info->image_pages;
nr_meta_pages = info->pages - info->image_pages - 1;
}
return error;
}
/**
* unpack_orig_pfns - Set bits corresponding to given PFNs in a memory bitmap.
* @bm: Memory bitmap.
* @buf: Area of memory containing the PFNs.
*
* For each element of the array pointed to by @buf (1 page at a time), set the
* corresponding bit in @bm.
*/
static int unpack_orig_pfns(unsigned long *buf, struct memory_bitmap *bm)
{
int j;
for (j = 0; j < PAGE_SIZE / sizeof(long); j++) {
if (unlikely(buf[j] == BM_END_OF_MAP))
break;
if (pfn_valid(buf[j]) && memory_bm_pfn_present(bm, buf[j]))
memory_bm_set_bit(bm, buf[j]);
else
return -EFAULT;
}
return 0;
}
#ifdef CONFIG_HIGHMEM
/*
* struct highmem_pbe is used for creating the list of highmem pages that
* should be restored atomically during the resume from disk, because the page
* frames they have occupied before the suspend are in use.
*/
struct highmem_pbe {
struct page *copy_page; /* data is here now */
struct page *orig_page; /* data was here before the suspend */
struct highmem_pbe *next;
};
/*
* List of highmem PBEs needed for restoring the highmem pages that were
* allocated before the suspend and included in the suspend image, but have
* also been allocated by the "resume" kernel, so their contents cannot be
* written directly to their "original" page frames.
*/
static struct highmem_pbe *highmem_pblist;
/**
* count_highmem_image_pages - Compute the number of highmem pages in the image.
* @bm: Memory bitmap.
*
* The bits in @bm that correspond to image pages are assumed to be set.
*/
static unsigned int count_highmem_image_pages(struct memory_bitmap *bm)
{
unsigned long pfn;
unsigned int cnt = 0;
memory_bm_position_reset(bm);
pfn = memory_bm_next_pfn(bm);
while (pfn != BM_END_OF_MAP) {
if (PageHighMem(pfn_to_page(pfn)))
cnt++;
pfn = memory_bm_next_pfn(bm);
}
return cnt;
}
static unsigned int safe_highmem_pages;
static struct memory_bitmap *safe_highmem_bm;
/**
* prepare_highmem_image - Allocate memory for loading highmem data from image.
* @bm: Pointer to an uninitialized memory bitmap structure.
* @nr_highmem_p: Pointer to the number of highmem image pages.
*
* Try to allocate as many highmem pages as there are highmem image pages
* (@nr_highmem_p points to the variable containing the number of highmem image
* pages). The pages that are "safe" (ie. will not be overwritten when the
* hibernation image is restored entirely) have the corresponding bits set in
* @bm (it must be unitialized).
*
* NOTE: This function should not be called if there are no highmem image pages.
*/
static int prepare_highmem_image(struct memory_bitmap *bm,
unsigned int *nr_highmem_p)
{
unsigned int to_alloc;
if (memory_bm_create(bm, GFP_ATOMIC, PG_SAFE))
return -ENOMEM;
if (get_highmem_buffer(PG_SAFE))
return -ENOMEM;
to_alloc = count_free_highmem_pages();
if (to_alloc > *nr_highmem_p)
to_alloc = *nr_highmem_p;
else
*nr_highmem_p = to_alloc;
safe_highmem_pages = 0;
while (to_alloc-- > 0) {
struct page *page;
page = alloc_page(__GFP_HIGHMEM);
if (!swsusp_page_is_free(page)) {
/* The page is "safe", set its bit the bitmap */
memory_bm_set_bit(bm, page_to_pfn(page));
safe_highmem_pages++;
}
/* Mark the page as allocated */
swsusp_set_page_forbidden(page);
swsusp_set_page_free(page);
}
memory_bm_position_reset(bm);
safe_highmem_bm = bm;
return 0;
}
static struct page *last_highmem_page;
/**
* get_highmem_page_buffer - Prepare a buffer to store a highmem image page.
*
* For a given highmem image page get a buffer that suspend_write_next() should
* return to its caller to write to.
*
* If the page is to be saved to its "original" page frame or a copy of
* the page is to be made in the highmem, @buffer is returned. Otherwise,
* the copy of the page is to be made in normal memory, so the address of
* the copy is returned.
*
* If @buffer is returned, the caller of suspend_write_next() will write
* the page's contents to @buffer, so they will have to be copied to the
* right location on the next call to suspend_write_next() and it is done
* with the help of copy_last_highmem_page(). For this purpose, if
* @buffer is returned, @last_highmem_page is set to the page to which
* the data will have to be copied from @buffer.
*/
static void *get_highmem_page_buffer(struct page *page,
struct chain_allocator *ca)
{
struct highmem_pbe *pbe;
void *kaddr;
if (swsusp_page_is_forbidden(page) && swsusp_page_is_free(page)) {
/*
* We have allocated the "original" page frame and we can
* use it directly to store the loaded page.
*/
last_highmem_page = page;
return buffer;
}
/*
* The "original" page frame has not been allocated and we have to
* use a "safe" page frame to store the loaded page.
*/
pbe = chain_alloc(ca, sizeof(struct highmem_pbe));
if (!pbe) {
swsusp_free();
return ERR_PTR(-ENOMEM);
}
pbe->orig_page = page;
if (safe_highmem_pages > 0) {
struct page *tmp;
/* Copy of the page will be stored in high memory */
kaddr = buffer;
tmp = pfn_to_page(memory_bm_next_pfn(safe_highmem_bm));
safe_highmem_pages--;
last_highmem_page = tmp;
pbe->copy_page = tmp;
} else {
/* Copy of the page will be stored in normal memory */
kaddr = safe_pages_list;
safe_pages_list = safe_pages_list->next;
pbe->copy_page = virt_to_page(kaddr);
}
pbe->next = highmem_pblist;
highmem_pblist = pbe;
return kaddr;
}
/**
* copy_last_highmem_page - Copy most the most recent highmem image page.
*
* Copy the contents of a highmem image from @buffer, where the caller of
* snapshot_write_next() has stored them, to the right location represented by
* @last_highmem_page .
*/
static void copy_last_highmem_page(void)
{
if (last_highmem_page) {
void *dst;
dst = kmap_atomic(last_highmem_page);
copy_page(dst, buffer);
kunmap_atomic(dst);
last_highmem_page = NULL;
}
}
static inline int last_highmem_page_copied(void)
{
return !last_highmem_page;
}
static inline void free_highmem_data(void)
{
if (safe_highmem_bm)
memory_bm_free(safe_highmem_bm, PG_UNSAFE_CLEAR);
if (buffer)
free_image_page(buffer, PG_UNSAFE_CLEAR);
}
#else
static unsigned int count_highmem_image_pages(struct memory_bitmap *bm) { return 0; }
static inline int prepare_highmem_image(struct memory_bitmap *bm,
unsigned int *nr_highmem_p) { return 0; }
static inline void *get_highmem_page_buffer(struct page *page,
struct chain_allocator *ca)
{
return ERR_PTR(-EINVAL);
}
static inline void copy_last_highmem_page(void) {}
static inline int last_highmem_page_copied(void) { return 1; }
static inline void free_highmem_data(void) {}
#endif /* CONFIG_HIGHMEM */
#define PBES_PER_LINKED_PAGE (LINKED_PAGE_DATA_SIZE / sizeof(struct pbe))
/**
* prepare_image - Make room for loading hibernation image.
* @new_bm: Unitialized memory bitmap structure.
* @bm: Memory bitmap with unsafe pages marked.
*
* Use @bm to mark the pages that will be overwritten in the process of
* restoring the system memory state from the suspend image ("unsafe" pages)
* and allocate memory for the image.
*
* The idea is to allocate a new memory bitmap first and then allocate
* as many pages as needed for image data, but without specifying what those
* pages will be used for just yet. Instead, we mark them all as allocated and
* create a lists of "safe" pages to be used later. On systems with high
* memory a list of "safe" highmem pages is created too.
*/
static int prepare_image(struct memory_bitmap *new_bm, struct memory_bitmap *bm)
{
unsigned int nr_pages, nr_highmem;
struct linked_page *lp;
int error;
/* If there is no highmem, the buffer will not be necessary */
free_image_page(buffer, PG_UNSAFE_CLEAR);
buffer = NULL;
nr_highmem = count_highmem_image_pages(bm);
mark_unsafe_pages(bm);
error = memory_bm_create(new_bm, GFP_ATOMIC, PG_SAFE);
if (error)
goto Free;
duplicate_memory_bitmap(new_bm, bm);
memory_bm_free(bm, PG_UNSAFE_KEEP);
if (nr_highmem > 0) {
error = prepare_highmem_image(bm, &nr_highmem);
if (error)
goto Free;
}
/*
* Reserve some safe pages for potential later use.
*
* NOTE: This way we make sure there will be enough safe pages for the
* chain_alloc() in get_buffer(). It is a bit wasteful, but
* nr_copy_pages cannot be greater than 50% of the memory anyway.
*
* nr_copy_pages cannot be less than allocated_unsafe_pages too.
*/
nr_pages = nr_copy_pages - nr_highmem - allocated_unsafe_pages;
nr_pages = DIV_ROUND_UP(nr_pages, PBES_PER_LINKED_PAGE);
while (nr_pages > 0) {
lp = get_image_page(GFP_ATOMIC, PG_SAFE);
if (!lp) {
error = -ENOMEM;
goto Free;
}
lp->next = safe_pages_list;
safe_pages_list = lp;
nr_pages--;
}
/* Preallocate memory for the image */
nr_pages = nr_copy_pages - nr_highmem - allocated_unsafe_pages;
while (nr_pages > 0) {
lp = (struct linked_page *)get_zeroed_page(GFP_ATOMIC);
if (!lp) {
error = -ENOMEM;
goto Free;
}
if (!swsusp_page_is_free(virt_to_page(lp))) {
/* The page is "safe", add it to the list */
lp->next = safe_pages_list;
safe_pages_list = lp;
}
/* Mark the page as allocated */
swsusp_set_page_forbidden(virt_to_page(lp));
swsusp_set_page_free(virt_to_page(lp));
nr_pages--;
}
return 0;
Free:
swsusp_free();
return error;
}
/**
* get_buffer - Get the address to store the next image data page.
*
* Get the address that snapshot_write_next() should return to its caller to
* write to.
*/
static void *get_buffer(struct memory_bitmap *bm, struct chain_allocator *ca)
{
struct pbe *pbe;
struct page *page;
unsigned long pfn = memory_bm_next_pfn(bm);
if (pfn == BM_END_OF_MAP)
return ERR_PTR(-EFAULT);
page = pfn_to_page(pfn);
if (PageHighMem(page))
return get_highmem_page_buffer(page, ca);
if (swsusp_page_is_forbidden(page) && swsusp_page_is_free(page))
/*
* We have allocated the "original" page frame and we can
* use it directly to store the loaded page.
*/
return page_address(page);
/*
* The "original" page frame has not been allocated and we have to
* use a "safe" page frame to store the loaded page.
*/
pbe = chain_alloc(ca, sizeof(struct pbe));
if (!pbe) {
swsusp_free();
return ERR_PTR(-ENOMEM);
}
pbe->orig_address = page_address(page);
pbe->address = safe_pages_list;
safe_pages_list = safe_pages_list->next;
pbe->next = restore_pblist;
restore_pblist = pbe;
return pbe->address;
}
/**
* snapshot_write_next - Get the address to store the next image page.
* @handle: Snapshot handle structure to guide the writing.
*
* On the first call, @handle should point to a zeroed snapshot_handle
* structure. The structure gets populated then and a pointer to it should be
* passed to this function every next time.
*
* On success, the function returns a positive number. Then, the caller
* is allowed to write up to the returned number of bytes to the memory
* location computed by the data_of() macro.
*
* The function returns 0 to indicate the "end of file" condition. Negative
* numbers are returned on errors, in which cases the structure pointed to by
* @handle is not updated and should not be used any more.
*/
int snapshot_write_next(struct snapshot_handle *handle)
{
static struct chain_allocator ca;
int error = 0;
/* Check if we have already loaded the entire image */
if (handle->cur > 1 && handle->cur > nr_meta_pages + nr_copy_pages)
return 0;
handle->sync_read = 1;
if (!handle->cur) {
if (!buffer)
/* This makes the buffer be freed by swsusp_free() */
buffer = get_image_page(GFP_ATOMIC, PG_ANY);
if (!buffer)
return -ENOMEM;
handle->buffer = buffer;
} else if (handle->cur == 1) {
error = load_header(buffer);
if (error)
return error;
safe_pages_list = NULL;
error = memory_bm_create(©_bm, GFP_ATOMIC, PG_ANY);
if (error)
return error;
hibernate_restore_protection_begin();
} else if (handle->cur <= nr_meta_pages + 1) {
error = unpack_orig_pfns(buffer, ©_bm);
if (error)
return error;
if (handle->cur == nr_meta_pages + 1) {
error = prepare_image(&orig_bm, ©_bm);
if (error)
return error;
chain_init(&ca, GFP_ATOMIC, PG_SAFE);
memory_bm_position_reset(&orig_bm);
restore_pblist = NULL;
handle->buffer = get_buffer(&orig_bm, &ca);
handle->sync_read = 0;
if (IS_ERR(handle->buffer))
return PTR_ERR(handle->buffer);
}
} else {
copy_last_highmem_page();
hibernate_restore_protect_page(handle->buffer);
handle->buffer = get_buffer(&orig_bm, &ca);
if (IS_ERR(handle->buffer))
return PTR_ERR(handle->buffer);
if (handle->buffer != buffer)
handle->sync_read = 0;
}
handle->cur++;
return PAGE_SIZE;
}
/**
* snapshot_write_finalize - Complete the loading of a hibernation image.
*
* Must be called after the last call to snapshot_write_next() in case the last
* page in the image happens to be a highmem page and its contents should be
* stored in highmem. Additionally, it recycles bitmap memory that's not
* necessary any more.
*/
void snapshot_write_finalize(struct snapshot_handle *handle)
{
copy_last_highmem_page();
hibernate_restore_protect_page(handle->buffer);
/* Do that only if we have loaded the image entirely */
if (handle->cur > 1 && handle->cur > nr_meta_pages + nr_copy_pages) {
memory_bm_recycle(&orig_bm);
free_highmem_data();
}
}
int snapshot_image_loaded(struct snapshot_handle *handle)
{
return !(!nr_copy_pages || !last_highmem_page_copied() ||
handle->cur <= nr_meta_pages + nr_copy_pages);
}
#ifdef CONFIG_HIGHMEM
/* Assumes that @buf is ready and points to a "safe" page */
static inline void swap_two_pages_data(struct page *p1, struct page *p2,
void *buf)
{
void *kaddr1, *kaddr2;
kaddr1 = kmap_atomic(p1);
kaddr2 = kmap_atomic(p2);
copy_page(buf, kaddr1);
copy_page(kaddr1, kaddr2);
copy_page(kaddr2, buf);
kunmap_atomic(kaddr2);
kunmap_atomic(kaddr1);
}
/**
* restore_highmem - Put highmem image pages into their original locations.
*
* For each highmem page that was in use before hibernation and is included in
* the image, and also has been allocated by the "restore" kernel, swap its
* current contents with the previous (ie. "before hibernation") ones.
*
* If the restore eventually fails, we can call this function once again and
* restore the highmem state as seen by the restore kernel.
*/
int restore_highmem(void)
{
struct highmem_pbe *pbe = highmem_pblist;
void *buf;
if (!pbe)
return 0;
buf = get_image_page(GFP_ATOMIC, PG_SAFE);
if (!buf)
return -ENOMEM;
while (pbe) {
swap_two_pages_data(pbe->copy_page, pbe->orig_page, buf);
pbe = pbe->next;
}
free_image_page(buf, PG_UNSAFE_CLEAR);
return 0;
}
#endif /* CONFIG_HIGHMEM */
|
/* cpu.c: Dinky routines to look for the kind of Sparc cpu
* we are on.
*
* Copyright (C) 1996 David S. Miller (davem@caip.rutgers.edu)
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/smp.h>
#include <linux/threads.h>
#include <asm/oplib.h>
#include <asm/page.h>
#include <asm/head.h>
#include <asm/psr.h>
#include <asm/mbus.h>
#include <asm/cpudata.h>
DEFINE_PER_CPU(cpuinfo_sparc, __cpu_data) = { 0 };
struct cpu_iu_info {
int psr_impl;
int psr_vers;
char* cpu_name; /* should be enough I hope... */
};
struct cpu_fp_info {
int psr_impl;
int fp_vers;
char* fp_name;
};
/* In order to get the fpu type correct, you need to take the IDPROM's
* machine type value into consideration too. I will fix this.
*/
static struct cpu_fp_info linux_sparc_fpu[] = {
{ 0, 0, "Fujitsu MB86910 or Weitek WTL1164/5"},
{ 0, 1, "Fujitsu MB86911 or Weitek WTL1164/5 or LSI L64831"},
{ 0, 2, "LSI Logic L64802 or Texas Instruments ACT8847"},
/* SparcStation SLC, SparcStation1 */
{ 0, 3, "Weitek WTL3170/2"},
/* SPARCstation-5 */
{ 0, 4, "Lsi Logic/Meiko L64804 or compatible"},
{ 0, 5, "reserved"},
{ 0, 6, "reserved"},
{ 0, 7, "No FPU"},
{ 1, 0, "ROSS HyperSparc combined IU/FPU"},
{ 1, 1, "Lsi Logic L64814"},
{ 1, 2, "Texas Instruments TMS390-C602A"},
{ 1, 3, "Cypress CY7C602 FPU"},
{ 1, 4, "reserved"},
{ 1, 5, "reserved"},
{ 1, 6, "reserved"},
{ 1, 7, "No FPU"},
{ 2, 0, "BIT B5010 or B5110/20 or B5210"},
{ 2, 1, "reserved"},
{ 2, 2, "reserved"},
{ 2, 3, "reserved"},
{ 2, 4, "reserved"},
{ 2, 5, "reserved"},
{ 2, 6, "reserved"},
{ 2, 7, "No FPU"},
/* SuperSparc 50 module */
{ 4, 0, "SuperSparc on-chip FPU"},
/* SparcClassic */
{ 4, 4, "TI MicroSparc on chip FPU"},
{ 5, 0, "Matsushita MN10501"},
{ 5, 1, "reserved"},
{ 5, 2, "reserved"},
{ 5, 3, "reserved"},
{ 5, 4, "reserved"},
{ 5, 5, "reserved"},
{ 5, 6, "reserved"},
{ 5, 7, "No FPU"},
{ 9, 3, "Fujitsu or Weitek on-chip FPU"},
};
#define NSPARCFPU ARRAY_SIZE(linux_sparc_fpu)
static struct cpu_iu_info linux_sparc_chips[] = {
/* Sun4/100, 4/200, SLC */
{ 0, 0, "Fujitsu MB86900/1A or LSI L64831 SparcKIT-40"},
/* borned STP1012PGA */
{ 0, 4, "Fujitsu MB86904"},
{ 0, 5, "Fujitsu TurboSparc MB86907"},
/* SparcStation2, SparcServer 490 & 690 */
{ 1, 0, "LSI Logic Corporation - L64811"},
/* SparcStation2 */
{ 1, 1, "Cypress/ROSS CY7C601"},
/* Embedded controller */
{ 1, 3, "Cypress/ROSS CY7C611"},
/* Ross Technologies HyperSparc */
{ 1, 0xf, "ROSS HyperSparc RT620"},
{ 1, 0xe, "ROSS HyperSparc RT625 or RT626"},
/* ECL Implementation, CRAY S-MP Supercomputer... AIEEE! */
/* Someone please write the code to support this beast! ;) */
{ 2, 0, "Bipolar Integrated Technology - B5010"},
{ 3, 0, "LSI Logic Corporation - unknown-type"},
{ 4, 0, "Texas Instruments, Inc. - SuperSparc-(II)"},
/* SparcClassic -- borned STP1010TAB-50*/
{ 4, 1, "Texas Instruments, Inc. - MicroSparc"},
{ 4, 2, "Texas Instruments, Inc. - MicroSparc II"},
{ 4, 3, "Texas Instruments, Inc. - SuperSparc 51"},
{ 4, 4, "Texas Instruments, Inc. - SuperSparc 61"},
{ 4, 5, "Texas Instruments, Inc. - unknown"},
{ 5, 0, "Matsushita - MN10501"},
{ 6, 0, "Philips Corporation - unknown"},
{ 7, 0, "Harvest VLSI Design Center, Inc. - unknown"},
/* Gallium arsenide 200MHz, BOOOOGOOOOMIPS!!! */
{ 8, 0, "Systems and Processes Engineering Corporation (SPEC)"},
{ 9, 0, "Fujitsu or Weitek Power-UP"},
{ 9, 1, "Fujitsu or Weitek Power-UP"},
{ 9, 2, "Fujitsu or Weitek Power-UP"},
{ 9, 3, "Fujitsu or Weitek Power-UP"},
{ 0xa, 0, "UNKNOWN CPU-VENDOR/TYPE"},
{ 0xb, 0, "UNKNOWN CPU-VENDOR/TYPE"},
{ 0xc, 0, "UNKNOWN CPU-VENDOR/TYPE"},
{ 0xd, 0, "UNKNOWN CPU-VENDOR/TYPE"},
{ 0xe, 0, "UNKNOWN CPU-VENDOR/TYPE"},
{ 0xf, 0, "UNKNOWN CPU-VENDOR/TYPE"},
};
#define NSPARCCHIPS ARRAY_SIZE(linux_sparc_chips)
char *sparc_cpu_type;
char *sparc_fpu_type;
unsigned int fsr_storage;
void __cpuinit cpu_probe(void)
{
int psr_impl, psr_vers, fpu_vers;
int i, psr;
psr_impl = ((get_psr()>>28)&0xf);
psr_vers = ((get_psr()>>24)&0xf);
psr = get_psr();
put_psr(psr | PSR_EF);
fpu_vers = ((get_fsr()>>17)&0x7);
put_psr(psr);
for(i = 0; i<NSPARCCHIPS; i++) {
if(linux_sparc_chips[i].psr_impl == psr_impl)
if(linux_sparc_chips[i].psr_vers == psr_vers) {
sparc_cpu_type = linux_sparc_chips[i].cpu_name;
break;
}
}
if(i==NSPARCCHIPS)
printk("DEBUG: psr.impl = 0x%x psr.vers = 0x%x\n", psr_impl,
psr_vers);
for(i = 0; i<NSPARCFPU; i++) {
if(linux_sparc_fpu[i].psr_impl == psr_impl)
if(linux_sparc_fpu[i].fp_vers == fpu_vers) {
sparc_fpu_type = linux_sparc_fpu[i].fp_name;
break;
}
}
if(i == NSPARCFPU) {
printk("DEBUG: psr.impl = 0x%x fsr.vers = 0x%x\n", psr_impl,
fpu_vers);
sparc_fpu_type = linux_sparc_fpu[31].fp_name;
}
}
|
/*
* Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4851625 4900189 4939441
* @summary Tests for {Math, StrictMath}.{sinh, cosh, tanh}
* @author Joseph D. Darcy
*/
public class HyperbolicTests {
private HyperbolicTests(){}
static final double NaNd = Double.NaN;
/**
* Test accuracy of {Math, StrictMath}.sinh. The specified
* accuracy is 2.5 ulps.
*
* The defintion of sinh(x) is
*
* (e^x - e^(-x))/2
*
* The series expansion of sinh(x) =
*
* x + x^3/3! + x^5/5! + x^7/7! +...
*
* Therefore,
*
* 1. For large values of x sinh(x) ~= signum(x)*exp(|x|)/2
*
* 2. For small values of x, sinh(x) ~= x.
*
* Additionally, sinh is an odd function; sinh(-x) = -sinh(x).
*
*/
static int testSinh() {
int failures = 0;
/*
* Array elements below generated using a quad sinh
* implementation. Rounded to a double, the quad result
* *should* be correctly rounded, unless we are quite unlucky.
* Assuming the quad value is a correctly rounded double, the
* allowed error is 3.0 ulps instead of 2.5 since the quad
* value rounded to double can have its own 1/2 ulp error.
*/
double [][] testCases = {
// x sinh(x)
{0.0625, 0.06254069805219182172183988501029229},
{0.1250, 0.12532577524111545698205754229137154},
{0.1875, 0.18860056562029018382047025055167585},
{0.2500, 0.25261231680816830791412515054205787},
{0.3125, 0.31761115611357728583959867611490292},
{0.3750, 0.38385106791361456875429567642050245},
{0.4375, 0.45159088610312053032509815226723017},
{0.5000, 0.52109530549374736162242562641149155},
{0.5625, 0.59263591611468777373870867338492247},
{0.6250, 0.66649226445661608227260655608302908},
{0.6875, 0.74295294580567543571442036910465007},
{0.7500, 0.82231673193582998070366163444691386},
{0.8125, 0.90489373856606433650504536421491368},
{0.8750, 0.99100663714429475605317427568995231},
{0.9375, 1.08099191569306394011007867453992548},
{1.0000, 1.17520119364380145688238185059560082},
{1.0625, 1.27400259579739321279181130344911907},
{1.1250, 1.37778219077984075760379987065228373},
{1.1875, 1.48694549961380717221109202361777593},
{1.2500, 1.60191908030082563790283030151221415},
{1.3125, 1.72315219460596010219069206464391528},
{1.3750, 1.85111856355791532419998548438506416},
{1.4375, 1.98631821852425112898943304217629457},
{1.5000, 2.12927945509481749683438749467763195},
{1.5625, 2.28056089740825247058075476705718764},
{1.6250, 2.44075368098794353221372986997161132},
{1.6875, 2.61048376261693140366028569794027603},
{1.7500, 2.79041436627764265509289122308816092},
{1.8125, 2.98124857471401377943765253243875520},
{1.8750, 3.18373207674259205101326780071803724},
{1.9375, 3.39865608104779099764440244167531810},
{2.0000, 3.62686040784701876766821398280126192},
{2.0625, 3.86923677050642806693938384073620450},
{2.1250, 4.12673225993027252260441410537905269},
{2.1875, 4.40035304533919660406976249684469164},
{2.2500, 4.69116830589833069188357567763552003},
{2.3125, 5.00031440855811351554075363240262157},
{2.3750, 5.32899934843284576394645856548481489},
{2.4375, 5.67850746906785056212578751630266858},
{2.5000, 6.05020448103978732145032363835040319},
{2.5625, 6.44554279850040875063706020260185553},
{2.6250, 6.86606721451642172826145238779845813},
{2.6875, 7.31342093738196587585692115636603571},
{2.7500, 7.78935201149073201875513401029935330},
{2.8125, 8.29572014785741787167717932988491961},
{2.8750, 8.83450399097893197351853322827892144},
{2.9375, 9.40780885043076394429977972921690859},
{3.0000, 10.01787492740990189897459361946582867},
{3.0625, 10.66708606836969224165124519209968368},
{3.1250, 11.35797907995166028304704128775698426},
{3.1875, 12.09325364161259019614431093344260209},
{3.2500, 12.87578285468067003959660391705481220},
{3.3125, 13.70862446906136798063935858393686525},
{3.3750, 14.59503283146163690015482636921657975},
{3.4375, 15.53847160182039311025096666980558478},
{3.5000, 16.54262728763499762495673152901249743},
{3.5625, 17.61142364906941482858466494889121694},
{3.6250, 18.74903703113232171399165788088277979},
{3.6875, 19.95991268283598684128844120984214675},
{3.7500, 21.24878212710338697364101071825171163},
{3.8125, 22.62068164929685091969259499078125023},
{3.8750, 24.08097197661255803883403419733891573},
{3.9375, 25.63535922523855307175060244757748997},
{4.0000, 27.28991719712775244890827159079382096},
{4.0625, 29.05111111351106713777825462100160185},
{4.1250, 30.92582287788986031725487699744107092},
{4.1875, 32.92137796722343190618721270937061472},
{4.2500, 35.04557405638942942322929652461901154},
{4.3125, 37.30671148776788628118833357170042385},
{4.3750, 39.71362570500944929025069048612806024},
{4.4375, 42.27572177772344954814418332587050658},
{4.5000, 45.00301115199178562180965680564371424},
{4.5625, 47.90615077031205065685078058248081891},
{4.6250, 50.99648471383193131253995134526177467},
{4.6875, 54.28608852959281437757368957713936555},
{4.7500, 57.78781641599226874961859781628591635},
{4.8125, 61.51535145084362283008545918273109379},
{4.8750, 65.48325905829987165560146562921543361},
{4.9375, 69.70704392356508084094318094283346381},
{5.0000, 74.20321057778875897700947199606456364},
{5.0625, 78.98932788987998983462810080907521151},
{5.1250, 84.08409771724448958901392613147384951},
{5.1875, 89.50742798369883598816307922895346849},
{5.2500, 95.28051047011540739630959111303975956},
{5.3125, 101.42590362176666730633859252034238987},
{5.3750, 107.96762069594029162704530843962700133},
{5.4375, 114.93122359426386042048760580590182604},
{5.5000, 122.34392274639096192409774240457730721},
{5.5625, 130.23468343534638291488502321709913206},
{5.6250, 138.63433897999898233879574111119546728},
{5.6875, 147.57571121692522056519568264304815790},
{5.7500, 157.09373875244884423880085377625986165},
{5.8125, 167.22561348600435888568183143777868662},
{5.8750, 178.01092593829229887752609866133883987},
{5.9375, 189.49181995209921964640216682906501778},
{6.0000, 201.71315737027922812498206768797872263},
{6.0625, 214.72269333437984291483666459592578915},
{6.1250, 228.57126288889537420461281285729970085},
{6.1875, 243.31297962030799867970551767086092471},
{6.2500, 259.00544710710289911522315435345489966},
{6.3125, 275.70998400700299790136562219920451185},
{6.3750, 293.49186366095654566861661249898332253},
{6.4375, 312.42056915013535342987623229485223434},
{6.5000, 332.57006480258443156075705566965111346},
{6.5625, 354.01908521044116928437570109827956007},
{6.6250, 376.85144288706511933454985188849781703},
{6.6875, 401.15635576625530823119100750634165252},
{6.7500, 427.02879582326538080306830640235938517},
{6.8125, 454.56986017986077163530945733572724452},
{6.8750, 483.88716614351897894746751705315210621},
{6.9375, 515.09527172439720070161654727225752288},
{7.0000, 548.31612327324652237375611757601851598},
{7.0625, 583.67953198942753384680988096024373270},
{7.1250, 621.32368116099280160364794462812762880},
{7.1875, 661.39566611888784148449430491465857519},
{7.2500, 704.05206901515336623551137120663358760},
{7.3125, 749.45957067108712382864538206200700256},
{7.3750, 797.79560188617531521347351754559776282},
{7.4375, 849.24903675279739482863565789325699416},
{7.5000, 904.02093068584652953510919038935849651},
{7.5625, 962.32530605113249628368993221570636328},
{7.6250, 1024.38998846242707559349318193113614698},
{7.6875, 1090.45749701500081956792547346904792325},
{7.7500, 1160.78599193425808533255719118417856088},
{7.8125, 1235.65028334242796895820912936318532502},
{7.8750, 1315.34290508508890654067255740428824014},
{7.9375, 1400.17525781352742299995139486063802583},
{8.0000, 1490.47882578955018611587663903188144796},
{8.0625, 1586.60647216744061169450001100145859236},
{8.1250, 1688.93381781440241350635231605477507900},
{8.1875, 1797.86070905726094477721128358866360644},
{8.2500, 1913.81278009067446281883262689250118009},
{8.3125, 2037.24311615199935553277163192983440062},
{8.3750, 2168.63402396170125867037749369723761636},
{8.4375, 2308.49891634734644432370720900969004306},
{8.5000, 2457.38431841538268239359965370719928775},
{8.5625, 2615.87200310986940554256648824234335262},
{8.6250, 2784.58126450289932429469130598902487336},
{8.6875, 2964.17133769964321637973459949999057146},
{8.7500, 3155.34397481384944060352507473513108710},
{8.8125, 3358.84618707947841898217318996045550438},
{8.8750, 3575.47316381333288862617411467285480067},
{8.9375, 3806.07137963459383403903729660349293583},
{9.0000, 4051.54190208278996051522359589803425598},
{9.0625, 4312.84391255878980330955246931164633615},
{9.1250, 4590.99845434696991399363282718106006883},
{9.1875, 4887.09242236403719571363798584676797558},
{9.2500, 5202.28281022453561319352901552085348309},
{9.3125, 5537.80123121853803935727335892054791265},
{9.3750, 5894.95873086734181634245918412592155656},
{9.4375, 6275.15090986233399457103055108344546942},
{9.5000, 6679.86337740502119410058225086262108741},
{9.5625, 7110.67755625726876329967852256934334025},
{9.6250, 7569.27686218510919585241049433331592115},
{9.6875, 8057.45328194243077504648484392156371121},
{9.7500, 8577.11437549816065709098061006273039092},
{9.8125, 9130.29072986829727910801024120918114778},
{9.8750, 9719.14389367880274015504995181862860062},
{9.9375, 10345.97482346383208590278839409938269134},
{10.0000, 11013.23287470339337723652455484636420303},
};
for(int i = 0; i < testCases.length; i++) {
double [] testCase = testCases[i];
failures += testSinhCaseWithUlpDiff(testCase[0],
testCase[1],
3.0);
}
double [][] specialTestCases = {
{0.0, 0.0},
{NaNd, NaNd},
{Double.longBitsToDouble(0x7FF0000000000001L), NaNd},
{Double.longBitsToDouble(0xFFF0000000000001L), NaNd},
{Double.longBitsToDouble(0x7FF8555555555555L), NaNd},
{Double.longBitsToDouble(0xFFF8555555555555L), NaNd},
{Double.longBitsToDouble(0x7FFFFFFFFFFFFFFFL), NaNd},
{Double.longBitsToDouble(0xFFFFFFFFFFFFFFFFL), NaNd},
{Double.longBitsToDouble(0x7FFDeadBeef00000L), NaNd},
{Double.longBitsToDouble(0xFFFDeadBeef00000L), NaNd},
{Double.longBitsToDouble(0x7FFCafeBabe00000L), NaNd},
{Double.longBitsToDouble(0xFFFCafeBabe00000L), NaNd},
{Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY}
};
for(int i = 0; i < specialTestCases.length; i++) {
failures += testSinhCaseWithUlpDiff(specialTestCases[i][0],
specialTestCases[i][1],
0.0);
}
// For powers of 2 less than 2^(-27), the second and
// subsequent terms of the Taylor series expansion will get
// rounded away since |n-n^3| > 53, the binary precision of a
// double significand.
for(int i = DoubleConsts.MIN_SUB_EXPONENT; i < -27; i++) {
double d = Math.scalb(2.0, i);
// Result and expected are the same.
failures += testSinhCaseWithUlpDiff(d, d, 2.5);
}
// For values of x larger than 22, the e^(-x) term is
// insignificant to the floating-point result. Util exp(x)
// overflows around 709.8, sinh(x) ~= exp(x)/2; will will test
// 10000 values in this range.
long trans22 = Double.doubleToLongBits(22.0);
// (approximately) largest value such that exp shouldn't
// overflow
long transExpOvfl = Double.doubleToLongBits(Math.nextDown(709.7827128933841));
for(long i = trans22;
i < transExpOvfl;
i +=(transExpOvfl-trans22)/10000) {
double d = Double.longBitsToDouble(i);
// Allow 3.5 ulps of error to deal with error in exp.
failures += testSinhCaseWithUlpDiff(d, StrictMath.exp(d)*0.5, 3.5);
}
// (approximately) largest value such that sinh shouldn't
// overflow.
long transSinhOvfl = Double.doubleToLongBits(710.4758600739439);
// Make sure sinh(x) doesn't overflow as soon as exp(x)
// overflows.
/*
* For large values of x, sinh(x) ~= 0.5*(e^x). Therefore,
*
* sinh(x) ~= e^(ln 0.5) * e^x = e^(x + ln 0.5)
*
* So, we can calculate the approximate expected result as
* exp(x + -0.693147186). However, this sum suffers from
* roundoff, limiting the accuracy of the approximation. The
* accuracy can be improved by recovering the rounded-off
* information. Since x is larger than ln(0.5), the trailing
* bits of ln(0.5) get rounded away when the two values are
* added. However, high-order bits of ln(0.5) that
* contribute to the sum can be found:
*
* offset = log(0.5);
* effective_offset = (x + offset) - x; // exact subtraction
* rounded_away_offset = offset - effective_offset; // exact subtraction
*
* Therefore, the product
*
* exp(x + offset)*exp(rounded_away_offset)
*
* will be a better approximation to the exact value of
*
* e^(x + offset)
*
* than exp(x+offset) alone. (The expected result cannot be
* computed as exp(x)*exp(offset) since exp(x) by itself would
* overflow to infinity.)
*/
double offset = StrictMath.log(0.5);
for(long i = transExpOvfl+1; i < transSinhOvfl;
i += (transSinhOvfl-transExpOvfl)/1000 ) {
double input = Double.longBitsToDouble(i);
double expected =
StrictMath.exp(input + offset) *
StrictMath.exp( offset - ((input + offset) - input) );
failures += testSinhCaseWithUlpDiff(input, expected, 4.0);
}
// sinh(x) overflows for values greater than 710; in
// particular, it overflows for all 2^i, i > 10.
for(int i = 10; i <= Double.MAX_EXPONENT; i++) {
double d = Math.scalb(2.0, i);
// Result and expected are the same.
failures += testSinhCaseWithUlpDiff(d,
Double.POSITIVE_INFINITY, 0.0);
}
return failures;
}
public static int testSinhCaseWithTolerance(double input,
double expected,
double tolerance) {
int failures = 0;
failures += Tests.testTolerance("Math.sinh(double)",
input, Math.sinh(input),
expected, tolerance);
failures += Tests.testTolerance("Math.sinh(double)",
-input, Math.sinh(-input),
-expected, tolerance);
failures += Tests.testTolerance("StrictMath.sinh(double)",
input, StrictMath.sinh(input),
expected, tolerance);
failures += Tests.testTolerance("StrictMath.sinh(double)",
-input, StrictMath.sinh(-input),
-expected, tolerance);
return failures;
}
public static int testSinhCaseWithUlpDiff(double input,
double expected,
double ulps) {
int failures = 0;
failures += Tests.testUlpDiff("Math.sinh(double)",
input, Math.sinh(input),
expected, ulps);
failures += Tests.testUlpDiff("Math.sinh(double)",
-input, Math.sinh(-input),
-expected, ulps);
failures += Tests.testUlpDiff("StrictMath.sinh(double)",
input, StrictMath.sinh(input),
expected, ulps);
failures += Tests.testUlpDiff("StrictMath.sinh(double)",
-input, StrictMath.sinh(-input),
-expected, ulps);
return failures;
}
/**
* Test accuracy of {Math, StrictMath}.cosh. The specified
* accuracy is 2.5 ulps.
*
* The defintion of cosh(x) is
*
* (e^x + e^(-x))/2
*
* The series expansion of cosh(x) =
*
* 1 + x^2/2! + x^4/4! + x^6/6! +...
*
* Therefore,
*
* 1. For large values of x cosh(x) ~= exp(|x|)/2
*
* 2. For small values of x, cosh(x) ~= 1.
*
* Additionally, cosh is an even function; cosh(-x) = cosh(x).
*
*/
static int testCosh() {
int failures = 0;
/*
* Array elements below generated using a quad cosh
* implementation. Rounded to a double, the quad result
* *should* be correctly rounded, unless we are quite unlucky.
* Assuming the quad value is a correctly rounded double, the
* allowed error is 3.0 ulps instead of 2.5 since the quad
* value rounded to double can have its own 1/2 ulp error.
*/
double [][] testCases = {
// x cosh(x)
{0.0625, 1.001953760865667607841550709632597376},
{0.1250, 1.007822677825710859846949685520422223},
{0.1875, 1.017629683800690526835115759894757615},
{0.2500, 1.031413099879573176159295417520378622},
{0.3125, 1.049226785060219076999158096606305793},
{0.3750, 1.071140346704586767299498015567016002},
{0.4375, 1.097239412531012567673453832328262160},
{0.5000, 1.127625965206380785226225161402672030},
{0.5625, 1.162418740845610783505338363214045218},
{0.6250, 1.201753692975606324229229064105075301},
{0.6875, 1.245784523776616395403056980542275175},
{0.7500, 1.294683284676844687841708185390181730},
{0.8125, 1.348641048647144208352285714214372703},
{0.8750, 1.407868656822803158638471458026344506},
{0.9375, 1.472597542369862933336886403008640891},
{1.0000, 1.543080634815243778477905620757061497},
{1.0625, 1.619593348374367728682469968448090763},
{1.1250, 1.702434658138190487400868008124755757},
{1.1875, 1.791928268324866464246665745956119612},
{1.2500, 1.888423877161015738227715728160051696},
{1.3125, 1.992298543335143985091891077551921106},
{1.3750, 2.103958159362661802010972984204389619},
{1.4375, 2.223839037619709260803023946704272699},
{1.5000, 2.352409615243247325767667965441644201},
{1.5625, 2.490172284559350293104864895029231913},
{1.6250, 2.637665356192137582275019088061812951},
{1.6875, 2.795465162524235691253423614360562624},
{1.7500, 2.964188309728087781773608481754531801},
{1.8125, 3.144494087167972176411236052303565201},
{1.8750, 3.337087043587520514308832278928116525},
{1.9375, 3.542719740149244276729383650503145346},
{2.0000, 3.762195691083631459562213477773746099},
{2.0625, 3.996372503438463642260225717607554880},
{2.1250, 4.246165228196992140600291052990934410},
{2.1875, 4.512549935859540340856119781585096760},
{2.2500, 4.796567530460195028666793366876218854},
{2.3125, 5.099327816921939817643745917141739051},
{2.3750, 5.422013837643509250646323138888569746},
{2.4375, 5.765886495263270945949271410819116399},
{2.5000, 6.132289479663686116619852312817562517},
{2.5625, 6.522654518468725462969589397439224177},
{2.6250, 6.938506971550673190999796241172117288},
{2.6875, 7.381471791406976069645686221095397137},
{2.7500, 7.853279872697439591457564035857305647},
{2.8125, 8.355774815752725814638234943192709129},
{2.8750, 8.890920130482709321824793617157134961},
{2.9375, 9.460806908834119747071078865866737196},
{3.0000, 10.067661995777765841953936035115890343},
{3.0625, 10.713856690753651225304006562698007312},
{3.1250, 11.401916013575067700373788969458446177},
{3.1875, 12.134528570998387744547733730974713055},
{3.2500, 12.914557062512392049483503752322408761},
{3.3125, 13.745049466398732213877084541992751273},
{3.3750, 14.629250949773302934853381428660210721},
{3.4375, 15.570616549147269180921654324879141947},
{3.5000, 16.572824671057316125696517821376119469},
{3.5625, 17.639791465519127930722105721028711044},
{3.6250, 18.775686128468677200079039891415789429},
{3.6875, 19.984947192985946987799359614758598457},
{3.7500, 21.272299872959396081877161903352144126},
{3.8125, 22.642774526961913363958587775566619798},
{3.8750, 24.101726314486257781049388094955970560},
{3.9375, 25.654856121347151067170940701379544221},
{4.0000, 27.308232836016486629201989612067059978},
{4.0625, 29.068317063936918520135334110824828950},
{4.1250, 30.941986372478026192360480044849306606},
{4.1875, 32.936562165180269851350626768308756303},
{4.2500, 35.059838290298428678502583470475012235},
{4.3125, 37.320111495433027109832850313172338419},
{4.3750, 39.726213847251883288518263854094284091},
{4.4375, 42.287547242982546165696077854963452084},
{4.5000, 45.014120148530027928305799939930642658},
{4.5625, 47.916586706774825161786212701923307169},
{4.6250, 51.006288368867753140854830589583165950},
{4.6875, 54.295298211196782516984520211780624960},
{4.7500, 57.796468111195389383795669320243166117},
{4.8125, 61.523478966332915041549750463563672435},
{4.8750, 65.490894152518731617237739112888213645},
{4.9375, 69.714216430810089539924900313140922323},
{5.0000, 74.209948524787844444106108044487704798},
{5.0625, 78.995657605307475581204965926043112946},
{5.1250, 84.090043934600961683400343038519519678},
{5.1875, 89.513013937957834087706670952561002466},
{5.2500, 95.285757988514588780586084642381131013},
{5.3125, 101.430833209098212357990123684449846912},
{5.3750, 107.972251614673824873137995865940755392},
{5.4375, 114.935573939814969189535554289886848550},
{5.5000, 122.348009517829425991091207107262038316},
{5.5625, 130.238522601820409078244923165746295574},
{5.6250, 138.637945543134998069351279801575968875},
{5.6875, 147.579099269447055276899288971207106581},
{5.7500, 157.096921533245353905868840194264636395},
{5.8125, 167.228603431860671946045256541679445836},
{5.8750, 178.013734732486824390148614309727161925},
{5.9375, 189.494458570056311567917444025807275896},
{6.0000, 201.715636122455894483405112855409538488},
{6.0625, 214.725021906554080628430756558271312513},
{6.1250, 228.573450380013557089736092321068279231},
{6.1875, 243.315034578039208138752165587134488645},
{6.2500, 259.007377561239126824465367865430519592},
{6.3125, 275.711797500835732516530131577254654076},
{6.3750, 293.493567280752348242602902925987643443},
{6.4375, 312.422169552825597994104814531010579387},
{6.5000, 332.571568241777409133204438572983297292},
{6.5625, 354.020497560858198165985214519757890505},
{6.6250, 376.852769667496146326030849450983914197},
{6.6875, 401.157602161123700280816957271992998156},
{6.7500, 427.029966702886171977469256622451185850},
{6.8125, 454.570960119471524953536004647195906721},
{6.8750, 483.888199441157626584508920036981010995},
{6.9375, 515.096242417696720610477570797503766179},
{7.0000, 548.317035155212076889964120712102928484},
{7.0625, 583.680388623257719787307547662358502345},
{7.1250, 621.324485894002926216918634755431456031},
{7.1875, 661.396422095589629755266517362992812037},
{7.2500, 704.052779189542208784574955807004218856},
{7.3125, 749.460237818184878095966335081928645934},
{7.3750, 797.796228612873763671070863694973560629},
{7.4375, 849.249625508044731271830060572510241864},
{7.5000, 904.021483770216677368692292389446994987},
{7.5625, 962.325825625814651122171697031114091993},
{7.6250, 1024.390476557670599008492465853663578558},
{7.6875, 1090.457955538048482588540574008226583335},
{7.7500, 1160.786422676798661020094043586456606003},
{7.8125, 1235.650687987597295222707689125107720568},
{7.8750, 1315.343285214046776004329388551335841550},
{7.9375, 1400.175614911635999247504386054087931958},
{8.0000, 1490.479161252178088627715460421007179728},
{8.0625, 1586.606787305415349050508956232945539108},
{8.1250, 1688.934113859132470361718199038326340668},
{8.1875, 1797.860987165547537276364148450577336075},
{8.2500, 1913.813041349231764486365114317586148767},
{8.3125, 2037.243361581700856522236313401822532385},
{8.3750, 2168.634254521568851112005905503069409349},
{8.4375, 2308.499132938297821208734949028296170563},
{8.5000, 2457.384521883751693037774022640629666294},
{8.5625, 2615.872194250713123494312356053193077854},
{8.6250, 2784.581444063104750127653362960649823247},
{8.6875, 2964.171506380845754878370650565756538203},
{8.7500, 3155.344133275174556354775488913749659006},
{8.8125, 3358.846335940117183452010789979584950102},
{8.8750, 3575.473303654961482727206202358956274888},
{8.9375, 3806.071511003646460448021740303914939059},
{9.0000, 4051.542025492594047194773093534725371440},
{9.0625, 4312.844028491571841588188869958240355518},
{9.1250, 4590.998563255739769060078863130940205710},
{9.1875, 4887.092524674358252509551443117048351290},
{9.2500, 5202.282906336187674588222835339193136030},
{9.3125, 5537.801321507079474415176386655744387251},
{9.3750, 5894.958815685577062811620236195525504885},
{9.4375, 6275.150989541692149890530417987358096221},
{9.5000, 6679.863452256851081801173722051940058824},
{9.5625, 7110.677626574055535297758456126491707647},
{9.6250, 7569.276928241617224537226019600213961572},
{9.6875, 8057.453343996777301036241026375049070162},
{9.7500, 8577.114433792824387959788368429252257664},
{9.8125, 9130.290784631065880205118262838330689429},
{9.8750, 9719.143945123662919857326995631317996715},
{9.9375, 10345.974871791805753327922796701684092861},
{10.0000, 11013.232920103323139721376090437880844591},
};
for(int i = 0; i < testCases.length; i++) {
double [] testCase = testCases[i];
failures += testCoshCaseWithUlpDiff(testCase[0],
testCase[1],
3.0);
}
double [][] specialTestCases = {
{0.0, 1.0},
{NaNd, NaNd},
{Double.longBitsToDouble(0x7FF0000000000001L), NaNd},
{Double.longBitsToDouble(0xFFF0000000000001L), NaNd},
{Double.longBitsToDouble(0x7FF8555555555555L), NaNd},
{Double.longBitsToDouble(0xFFF8555555555555L), NaNd},
{Double.longBitsToDouble(0x7FFFFFFFFFFFFFFFL), NaNd},
{Double.longBitsToDouble(0xFFFFFFFFFFFFFFFFL), NaNd},
{Double.longBitsToDouble(0x7FFDeadBeef00000L), NaNd},
{Double.longBitsToDouble(0xFFFDeadBeef00000L), NaNd},
{Double.longBitsToDouble(0x7FFCafeBabe00000L), NaNd},
{Double.longBitsToDouble(0xFFFCafeBabe00000L), NaNd},
{Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY}
};
for(int i = 0; i < specialTestCases.length; i++ ) {
failures += testCoshCaseWithUlpDiff(specialTestCases[i][0],
specialTestCases[i][1],
0.0);
}
// For powers of 2 less than 2^(-27), the second and
// subsequent terms of the Taylor series expansion will get
// rounded.
for(int i = DoubleConsts.MIN_SUB_EXPONENT; i < -27; i++) {
double d = Math.scalb(2.0, i);
// Result and expected are the same.
failures += testCoshCaseWithUlpDiff(d, 1.0, 2.5);
}
// For values of x larger than 22, the e^(-x) term is
// insignificant to the floating-point result. Util exp(x)
// overflows around 709.8, cosh(x) ~= exp(x)/2; will will test
// 10000 values in this range.
long trans22 = Double.doubleToLongBits(22.0);
// (approximately) largest value such that exp shouldn't
// overflow
long transExpOvfl = Double.doubleToLongBits(Math.nextDown(709.7827128933841));
for(long i = trans22;
i < transExpOvfl;
i +=(transExpOvfl-trans22)/10000) {
double d = Double.longBitsToDouble(i);
// Allow 3.5 ulps of error to deal with error in exp.
failures += testCoshCaseWithUlpDiff(d, StrictMath.exp(d)*0.5, 3.5);
}
// (approximately) largest value such that cosh shouldn't
// overflow.
long transCoshOvfl = Double.doubleToLongBits(710.4758600739439);
// Make sure sinh(x) doesn't overflow as soon as exp(x)
// overflows.
/*
* For large values of x, cosh(x) ~= 0.5*(e^x). Therefore,
*
* cosh(x) ~= e^(ln 0.5) * e^x = e^(x + ln 0.5)
*
* So, we can calculate the approximate expected result as
* exp(x + -0.693147186). However, this sum suffers from
* roundoff, limiting the accuracy of the approximation. The
* accuracy can be improved by recovering the rounded-off
* information. Since x is larger than ln(0.5), the trailing
* bits of ln(0.5) get rounded away when the two values are
* added. However, high-order bits of ln(0.5) that
* contribute to the sum can be found:
*
* offset = log(0.5);
* effective_offset = (x + offset) - x; // exact subtraction
* rounded_away_offset = offset - effective_offset; // exact subtraction
*
* Therefore, the product
*
* exp(x + offset)*exp(rounded_away_offset)
*
* will be a better approximation to the exact value of
*
* e^(x + offset)
*
* than exp(x+offset) alone. (The expected result cannot be
* computed as exp(x)*exp(offset) since exp(x) by itself would
* overflow to infinity.)
*/
double offset = StrictMath.log(0.5);
for(long i = transExpOvfl+1; i < transCoshOvfl;
i += (transCoshOvfl-transExpOvfl)/1000 ) {
double input = Double.longBitsToDouble(i);
double expected =
StrictMath.exp(input + offset) *
StrictMath.exp( offset - ((input + offset) - input) );
failures += testCoshCaseWithUlpDiff(input, expected, 4.0);
}
// cosh(x) overflows for values greater than 710; in
// particular, it overflows for all 2^i, i > 10.
for(int i = 10; i <= Double.MAX_EXPONENT; i++) {
double d = Math.scalb(2.0, i);
// Result and expected are the same.
failures += testCoshCaseWithUlpDiff(d,
Double.POSITIVE_INFINITY, 0.0);
}
return failures;
}
public static int testCoshCaseWithTolerance(double input,
double expected,
double tolerance) {
int failures = 0;
failures += Tests.testTolerance("Math.cosh(double)",
input, Math.cosh(input),
expected, tolerance);
failures += Tests.testTolerance("Math.cosh(double)",
-input, Math.cosh(-input),
expected, tolerance);
failures += Tests.testTolerance("StrictMath.cosh(double)",
input, StrictMath.cosh(input),
expected, tolerance);
failures += Tests.testTolerance("StrictMath.cosh(double)",
-input, StrictMath.cosh(-input),
expected, tolerance);
return failures;
}
public static int testCoshCaseWithUlpDiff(double input,
double expected,
double ulps) {
int failures = 0;
failures += Tests.testUlpDiff("Math.cosh(double)",
input, Math.cosh(input),
expected, ulps);
failures += Tests.testUlpDiff("Math.cosh(double)",
-input, Math.cosh(-input),
expected, ulps);
failures += Tests.testUlpDiff("StrictMath.cosh(double)",
input, StrictMath.cosh(input),
expected, ulps);
failures += Tests.testUlpDiff("StrictMath.cosh(double)",
-input, StrictMath.cosh(-input),
expected, ulps);
return failures;
}
/**
* Test accuracy of {Math, StrictMath}.tanh. The specified
* accuracy is 2.5 ulps.
*
* The defintion of tanh(x) is
*
* (e^x - e^(-x))/(e^x + e^(-x))
*
* The series expansion of tanh(x) =
*
* x - x^3/3 + 2x^5/15 - 17x^7/315 + ...
*
* Therefore,
*
* 1. For large values of x tanh(x) ~= signum(x)
*
* 2. For small values of x, tanh(x) ~= x.
*
* Additionally, tanh is an odd function; tanh(-x) = -tanh(x).
*
*/
static int testTanh() {
int failures = 0;
/*
* Array elements below generated using a quad sinh
* implementation. Rounded to a double, the quad result
* *should* be correctly rounded, unless we are quite unlucky.
* Assuming the quad value is a correctly rounded double, the
* allowed error is 3.0 ulps instead of 2.5 since the quad
* value rounded to double can have its own 1/2 ulp error.
*/
double [][] testCases = {
// x tanh(x)
{0.0625, 0.06241874674751251449014289119421133},
{0.1250, 0.12435300177159620805464727580589271},
{0.1875, 0.18533319990813951753211997502482787},
{0.2500, 0.24491866240370912927780113149101697},
{0.3125, 0.30270972933210848724239738970991712},
{0.3750, 0.35835739835078594631936023155315807},
{0.4375, 0.41157005567402245143207555859415687},
{0.5000, 0.46211715726000975850231848364367256},
{0.5625, 0.50982997373525658248931213507053130},
{0.6250, 0.55459972234938229399903909532308371},
{0.6875, 0.59637355547924233984437303950726939},
{0.7500, 0.63514895238728731921443435731249638},
{0.8125, 0.67096707420687367394810954721913358},
{0.8750, 0.70390560393662106058763026963135371},
{0.9375, 0.73407151960434149263991588052503660},
{1.0000, 0.76159415595576488811945828260479366},
{1.0625, 0.78661881210869761781941794647736081},
{1.1250, 0.80930107020178101206077047354332696},
{1.1875, 0.82980190998595952708572559629034476},
{1.2500, 0.84828363995751289761338764670750445},
{1.3125, 0.86490661772074179125443141102709751},
{1.3750, 0.87982669965198475596055310881018259},
{1.4375, 0.89319334040035153149249598745889365},
{1.5000, 0.90514825364486643824230369645649557},
{1.5625, 0.91582454416876231820084311814416443},
{1.6250, 0.92534622531174107960457166792300374},
{1.6875, 0.93382804322259173763570528576138652},
{1.7500, 0.94137553849728736226942088377163687},
{1.8125, 0.94808528560440629971240651310180052},
{1.8750, 0.95404526017994877009219222661968285},
{1.9375, 0.95933529331468249183399461756952555},
{2.0000, 0.96402758007581688394641372410092317},
{2.0625, 0.96818721657637057702714316097855370},
{2.1250, 0.97187274591350905151254495374870401},
{2.1875, 0.97513669829362836159665586901156483},
{2.2500, 0.97802611473881363992272924300618321},
{2.3125, 0.98058304703705186541999427134482061},
{2.3750, 0.98284502917257603002353801620158861},
{2.4375, 0.98484551746427837912703608465407824},
{2.5000, 0.98661429815143028888127603923734964},
{2.5625, 0.98817786228751240824802592958012269},
{2.6250, 0.98955974861288320579361709496051109},
{2.6875, 0.99078085564125158320311117560719312},
{2.7500, 0.99185972456820774534967078914285035},
{2.8125, 0.99281279483715982021711715899682324},
{2.8750, 0.99365463431502962099607366282699651},
{2.9375, 0.99439814606575805343721743822723671},
{3.0000, 0.99505475368673045133188018525548849},
{3.0625, 0.99563456710930963835715538507891736},
{3.1250, 0.99614653067334504917102591131792951},
{3.1875, 0.99659855517712942451966113109487039},
{3.2500, 0.99699763548652601693227592643957226},
{3.3125, 0.99734995516557367804571991063376923},
{3.3750, 0.99766097946988897037219469409451602},
{3.4375, 0.99793553792649036103161966894686844},
{3.5000, 0.99817789761119870928427335245061171},
{3.5625, 0.99839182812874152902001617480606320},
{3.6250, 0.99858065920179882368897879066418294},
{3.6875, 0.99874733168378115962760304582965538},
{3.7500, 0.99889444272615280096784208280487888},
{3.8125, 0.99902428575443546808677966295308778},
{3.8750, 0.99913888583735077016137617231569011},
{3.9375, 0.99924003097049627100651907919688313},
{4.0000, 0.99932929973906704379224334434172499},
{4.0625, 0.99940808577297384603818654530731215},
{4.1250, 0.99947761936180856115470576756499454},
{4.1875, 0.99953898655601372055527046497863955},
{4.2500, 0.99959314604388958696521068958989891},
{4.3125, 0.99964094406130644525586201091350343},
{4.3750, 0.99968312756179494813069349082306235},
{4.4375, 0.99972035584870534179601447812936151},
{4.5000, 0.99975321084802753654050617379050162},
{4.5625, 0.99978220617994689112771768489030236},
{4.6250, 0.99980779516900105210240981251048167},
{4.6875, 0.99983037791655283849546303868853396},
{4.7500, 0.99985030754497877753787358852000255},
{4.8125, 0.99986789571029070417475400133989992},
{4.8750, 0.99988341746867772271011794614780441},
{4.9375, 0.99989711557251558205051185882773206},
{5.0000, 0.99990920426259513121099044753447306},
{5.0625, 0.99991987261554158551063867262784721},
{5.1250, 0.99992928749851651137225712249720606},
{5.1875, 0.99993759617721206697530526661105307},
{5.2500, 0.99994492861777083305830639416802036},
{5.3125, 0.99995139951851344080105352145538345},
{5.3750, 0.99995711010315817210152906092289064},
{5.4375, 0.99996214970350792531554669737676253},
{5.5000, 0.99996659715630380963848952941756868},
{5.5625, 0.99997052203605101013786592945475432},
{5.6250, 0.99997398574306704793434088941484766},
{5.6875, 0.99997704246374583929961850444364696},
{5.7500, 0.99997974001803825215761760428815437},
{5.8125, 0.99998212060739040166557477723121777},
{5.8750, 0.99998422147482750993344503195672517},
{5.9375, 0.99998607548749972326220227464612338},
{6.0000, 0.99998771165079557056434885235523206},
{6.0625, 0.99998915556205996764518917496149338},
{6.1250, 0.99999042981101021976277974520745310},
{6.1875, 0.99999155433311068015449574811497719},
{6.2500, 0.99999254672143162687722782398104276},
{6.3125, 0.99999342250186907900400800240980139},
{6.3750, 0.99999419537602957780612639767025158},
{6.4375, 0.99999487743557848265406225515388994},
{6.5000, 0.99999547935140419285107893831698753},
{6.5625, 0.99999601054055694588617385671796346},
{6.6250, 0.99999647931357331502887600387959900},
{6.6875, 0.99999689300449080997594368612277442},
{6.7500, 0.99999725808558628431084200832778748},
{6.8125, 0.99999758026863294516387464046135924},
{6.8750, 0.99999786459425991170635407313276785},
{6.9375, 0.99999811551081218572759991597586905},
{7.0000, 0.99999833694394467173571641595066708},
{7.0625, 0.99999853235803894918375164252059190},
{7.1250, 0.99999870481040359014665019356422927},
{7.1875, 0.99999885699910593255108365463415411},
{7.2500, 0.99999899130518359709674536482047025},
{7.3125, 0.99999910982989611769943303422227663},
{7.3750, 0.99999921442759946591163427422888252},
{7.4375, 0.99999930673475777603853435094943258},
{7.5000, 0.99999938819554614875054970643513124},
{7.5625, 0.99999946008444508183970109263856958},
{7.6250, 0.99999952352618001331402589096040117},
{7.6875, 0.99999957951331792817413683491979752},
{7.7500, 0.99999962892179632633374697389145081},
{7.8125, 0.99999967252462750190604116210421169},
{7.8750, 0.99999971100399253750324718031574484},
{7.9375, 0.99999974496191422474977283863588658},
{8.0000, 0.99999977492967588981001883295636840},
{8.0625, 0.99999980137613348259726597081723424},
{8.1250, 0.99999982471505097353529823063673263},
{8.1875, 0.99999984531157382142423402736529911},
{8.2500, 0.99999986348794179107425910499030547},
{8.3125, 0.99999987952853049895833839645847571},
{8.3750, 0.99999989368430056302584289932834041},
{8.4375, 0.99999990617672396471542088609051728},
{8.5000, 0.99999991720124905211338798152800748},
{8.5625, 0.99999992693035839516545287745322387},
{8.6250, 0.99999993551626733394129009365703767},
{8.6875, 0.99999994309330543951799157347876934},
{8.7500, 0.99999994978001814614368429416607424},
{8.8125, 0.99999995568102143535399207289008504},
{8.8750, 0.99999996088863858914831986187674522},
{8.9375, 0.99999996548434461974481685677429908},
{9.0000, 0.99999996954004097447930211118358244},
{9.0625, 0.99999997311918045901919121395899372},
{9.1250, 0.99999997627775997868467948564005257},
{9.1875, 0.99999997906519662964368381583648379},
{9.2500, 0.99999998152510084671976114264303159},
{9.3125, 0.99999998369595870397054673668361266},
{9.3750, 0.99999998561173404286033236040150950},
{9.4375, 0.99999998730239984852716512979473289},
{9.5000, 0.99999998879440718770812040917618843},
{9.5625, 0.99999999011109904501789298212541698},
{9.6250, 0.99999999127307553219220251303121960},
{9.6875, 0.99999999229851618412119275358396363},
{9.7500, 0.99999999320346438410630581726217930},
{9.8125, 0.99999999400207836827291739324060736},
{9.8750, 0.99999999470685273619047001387577653},
{9.9375, 0.99999999532881393331131526966058758},
{10.0000, 0.99999999587769276361959283713827574},
};
for(int i = 0; i < testCases.length; i++) {
double [] testCase = testCases[i];
failures += testTanhCaseWithUlpDiff(testCase[0],
testCase[1],
3.0);
}
double [][] specialTestCases = {
{0.0, 0.0},
{NaNd, NaNd},
{Double.longBitsToDouble(0x7FF0000000000001L), NaNd},
{Double.longBitsToDouble(0xFFF0000000000001L), NaNd},
{Double.longBitsToDouble(0x7FF8555555555555L), NaNd},
{Double.longBitsToDouble(0xFFF8555555555555L), NaNd},
{Double.longBitsToDouble(0x7FFFFFFFFFFFFFFFL), NaNd},
{Double.longBitsToDouble(0xFFFFFFFFFFFFFFFFL), NaNd},
{Double.longBitsToDouble(0x7FFDeadBeef00000L), NaNd},
{Double.longBitsToDouble(0xFFFDeadBeef00000L), NaNd},
{Double.longBitsToDouble(0x7FFCafeBabe00000L), NaNd},
{Double.longBitsToDouble(0xFFFCafeBabe00000L), NaNd},
{Double.POSITIVE_INFINITY, 1.0}
};
for(int i = 0; i < specialTestCases.length; i++) {
failures += testTanhCaseWithUlpDiff(specialTestCases[i][0],
specialTestCases[i][1],
0.0);
}
// For powers of 2 less than 2^(-27), the second and
// subsequent terms of the Taylor series expansion will get
// rounded away since |n-n^3| > 53, the binary precision of a
// double significand.
for(int i = DoubleConsts.MIN_SUB_EXPONENT; i < -27; i++) {
double d = Math.scalb(2.0, i);
// Result and expected are the same.
failures += testTanhCaseWithUlpDiff(d, d, 2.5);
}
// For values of x larger than 22, tanh(x) is 1.0 in double
// floating-point arithmetic.
for(int i = 22; i < 32; i++) {
failures += testTanhCaseWithUlpDiff(i, 1.0, 2.5);
}
for(int i = 5; i <= Double.MAX_EXPONENT; i++) {
double d = Math.scalb(2.0, i);
failures += testTanhCaseWithUlpDiff(d, 1.0, 2.5);
}
return failures;
}
public static int testTanhCaseWithTolerance(double input,
double expected,
double tolerance) {
int failures = 0;
failures += Tests.testTolerance("Math.tanh(double",
input, Math.tanh(input),
expected, tolerance);
failures += Tests.testTolerance("Math.tanh(double",
-input, Math.tanh(-input),
-expected, tolerance);
failures += Tests.testTolerance("StrictMath.tanh(double",
input, StrictMath.tanh(input),
expected, tolerance);
failures += Tests.testTolerance("StrictMath.tanh(double",
-input, StrictMath.tanh(-input),
-expected, tolerance);
return failures;
}
public static int testTanhCaseWithUlpDiff(double input,
double expected,
double ulps) {
int failures = 0;
failures += Tests.testUlpDiffWithAbsBound("Math.tanh(double)",
input, Math.tanh(input),
expected, ulps, 1.0);
failures += Tests.testUlpDiffWithAbsBound("Math.tanh(double)",
-input, Math.tanh(-input),
-expected, ulps, 1.0);
failures += Tests.testUlpDiffWithAbsBound("StrictMath.tanh(double)",
input, StrictMath.tanh(input),
expected, ulps, 1.0);
failures += Tests.testUlpDiffWithAbsBound("StrictMath.tanh(double)",
-input, StrictMath.tanh(-input),
-expected, ulps, 1.0);
return failures;
}
public static void main(String argv[]) {
int failures = 0;
failures += testSinh();
failures += testCosh();
failures += testTanh();
if (failures > 0) {
System.err.println("Testing the hyperbolic functions incurred "
+ failures + " failures.");
throw new RuntimeException();
}
}
}
|
/**
* eCryptfs: Linux filesystem encryption layer
*
* Copyright (C) 1997-2004 Erez Zadok
* Copyright (C) 2001-2004 Stony Brook University
* Copyright (C) 2004-2007 International Business Machines Corp.
* Author(s): Michael A. Halcrow <mahalcro@us.ibm.com>
* Michael C. Thompsion <mcthomps@us.ibm.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
#include <linux/file.h>
#include <linux/vmalloc.h>
#include <linux/pagemap.h>
#include <linux/dcache.h>
#include <linux/namei.h>
#include <linux/mount.h>
#include <linux/crypto.h>
#include <linux/fs_stack.h>
#include <linux/slab.h>
#include <linux/xattr.h>
#include <asm/unaligned.h>
#include "ecryptfs_kernel.h"
static struct dentry *lock_parent(struct dentry *dentry)
{
struct dentry *dir;
dir = dget_parent(dentry);
mutex_lock_nested(&(dir->d_inode->i_mutex), I_MUTEX_PARENT);
return dir;
}
static void unlock_dir(struct dentry *dir)
{
mutex_unlock(&dir->d_inode->i_mutex);
dput(dir);
}
static int ecryptfs_inode_test(struct inode *inode, void *lower_inode)
{
if (ecryptfs_inode_to_lower(inode) == (struct inode *)lower_inode)
return 1;
return 0;
}
static int ecryptfs_inode_set(struct inode *inode, void *opaque)
{
struct inode *lower_inode = opaque;
ecryptfs_set_inode_lower(inode, lower_inode);
fsstack_copy_attr_all(inode, lower_inode);
/* i_size will be overwritten for encrypted regular files */
fsstack_copy_inode_size(inode, lower_inode);
inode->i_ino = lower_inode->i_ino;
inode->i_version++;
inode->i_mapping->a_ops = &ecryptfs_aops;
inode->i_mapping->backing_dev_info = inode->i_sb->s_bdi;
if (S_ISLNK(inode->i_mode))
inode->i_op = &ecryptfs_symlink_iops;
else if (S_ISDIR(inode->i_mode))
inode->i_op = &ecryptfs_dir_iops;
else
inode->i_op = &ecryptfs_main_iops;
if (S_ISDIR(inode->i_mode))
inode->i_fop = &ecryptfs_dir_fops;
else if (special_file(inode->i_mode))
init_special_inode(inode, inode->i_mode, inode->i_rdev);
else
inode->i_fop = &ecryptfs_main_fops;
return 0;
}
static struct inode *__ecryptfs_get_inode(struct inode *lower_inode,
struct super_block *sb)
{
struct inode *inode;
if (lower_inode->i_sb != ecryptfs_superblock_to_lower(sb))
return ERR_PTR(-EXDEV);
if (!igrab(lower_inode))
return ERR_PTR(-ESTALE);
inode = iget5_locked(sb, (unsigned long)lower_inode,
ecryptfs_inode_test, ecryptfs_inode_set,
lower_inode);
if (!inode) {
iput(lower_inode);
return ERR_PTR(-EACCES);
}
if (!(inode->i_state & I_NEW))
iput(lower_inode);
return inode;
}
struct inode *ecryptfs_get_inode(struct inode *lower_inode,
struct super_block *sb)
{
struct inode *inode = __ecryptfs_get_inode(lower_inode, sb);
if (!IS_ERR(inode) && (inode->i_state & I_NEW))
unlock_new_inode(inode);
return inode;
}
/**
* ecryptfs_interpose
* @lower_dentry: Existing dentry in the lower filesystem
* @dentry: ecryptfs' dentry
* @sb: ecryptfs's super_block
*
* Interposes upper and lower dentries.
*
* Returns zero on success; non-zero otherwise
*/
static int ecryptfs_interpose(struct dentry *lower_dentry,
struct dentry *dentry, struct super_block *sb)
{
struct inode *inode = ecryptfs_get_inode(lower_dentry->d_inode, sb);
if (IS_ERR(inode))
return PTR_ERR(inode);
d_instantiate(dentry, inode);
return 0;
}
static int ecryptfs_do_unlink(struct inode *dir, struct dentry *dentry,
struct inode *inode)
{
struct dentry *lower_dentry = ecryptfs_dentry_to_lower(dentry);
struct inode *lower_dir_inode = ecryptfs_inode_to_lower(dir);
struct dentry *lower_dir_dentry;
int rc;
dget(lower_dentry);
lower_dir_dentry = lock_parent(lower_dentry);
rc = vfs_unlink(lower_dir_inode, lower_dentry);
if (rc) {
printk(KERN_ERR "Error in vfs_unlink; rc = [%d]\n", rc);
goto out_unlock;
}
fsstack_copy_attr_times(dir, lower_dir_inode);
set_nlink(inode, ecryptfs_inode_to_lower(inode)->i_nlink);
inode->i_ctime = dir->i_ctime;
d_drop(dentry);
out_unlock:
unlock_dir(lower_dir_dentry);
dput(lower_dentry);
return rc;
}
/**
* ecryptfs_do_create
* @directory_inode: inode of the new file's dentry's parent in ecryptfs
* @ecryptfs_dentry: New file's dentry in ecryptfs
* @mode: The mode of the new file
*
* Creates the underlying file and the eCryptfs inode which will link to
* it. It will also update the eCryptfs directory inode to mimic the
* stat of the lower directory inode.
*
* Returns the new eCryptfs inode on success; an ERR_PTR on error condition
*/
static struct inode *
ecryptfs_do_create(struct inode *directory_inode,
struct dentry *ecryptfs_dentry, umode_t mode)
{
int rc;
struct dentry *lower_dentry;
struct dentry *lower_dir_dentry;
struct inode *inode;
lower_dentry = ecryptfs_dentry_to_lower(ecryptfs_dentry);
lower_dir_dentry = lock_parent(lower_dentry);
if (IS_ERR(lower_dir_dentry)) {
ecryptfs_printk(KERN_ERR, "Error locking directory of "
"dentry\n");
inode = ERR_CAST(lower_dir_dentry);
goto out;
}
rc = vfs_create(lower_dir_dentry->d_inode, lower_dentry, mode, NULL);
if (rc) {
printk(KERN_ERR "%s: Failure to create dentry in lower fs; "
"rc = [%d]\n", __func__, rc);
inode = ERR_PTR(rc);
goto out_lock;
}
inode = __ecryptfs_get_inode(lower_dentry->d_inode,
directory_inode->i_sb);
if (IS_ERR(inode)) {
vfs_unlink(lower_dir_dentry->d_inode, lower_dentry);
goto out_lock;
}
fsstack_copy_attr_times(directory_inode, lower_dir_dentry->d_inode);
fsstack_copy_inode_size(directory_inode, lower_dir_dentry->d_inode);
out_lock:
unlock_dir(lower_dir_dentry);
out:
return inode;
}
/**
* ecryptfs_do_create2
* @directory_inode: inode of the new file's dentry's parent in ecryptfs
* @ecryptfs_dentry: New file's dentry in ecryptfs
* @mode: The mode of the new file
* @nd: nameidata of ecryptfs' parent's dentry & vfsmount
*
* Creates the underlying file and the eCryptfs inode which will link to
* it. It will also update the eCryptfs directory inode to mimic the
* stat of the lower directory inode.
*
* Returns the new eCryptfs inode on success; an ERR_PTR on error condition
*/
static struct inode *
ecryptfs_do_create2(struct inode *directory_inode,
struct dentry *ecryptfs_dentry, umode_t mode, struct nameidata *nd)
{
int rc;
struct dentry *lower_dentry;
struct dentry *lower_dir_dentry;
struct vfsmount *lower_mnt = NULL;
struct inode *inode = NULL;
struct dentry *dentry_save = NULL;
struct vfsmount *vfsmount_save = NULL;
lower_dentry = ecryptfs_dentry_to_lower(ecryptfs_dentry);
lower_mnt = ecryptfs_dentry_to_lower_mnt(ecryptfs_dentry);
if (!lower_dentry->d_op || !lower_dentry->d_op->d_revalidate)
goto out;
lower_dir_dentry = lock_parent(lower_dentry);
if (IS_ERR(lower_dir_dentry)) {
ecryptfs_printk(KERN_ERR, "Error locking directory of "
"dentry\n");
inode = ERR_CAST(lower_dir_dentry);
goto out;
}
if (nd) {
dentry_save = nd->path.dentry;
vfsmount_save = nd->path.mnt;
nd->path.dentry = lower_dentry;
nd->path.mnt = lower_mnt;
}
rc = vfs_create(lower_dir_dentry->d_inode, lower_dentry, mode, nd);
if (nd) {
nd->path.dentry = dentry_save;
nd->path.mnt = vfsmount_save;
}
if (rc) {
printk(KERN_ERR "%s: Failure to create dentry in lower fs; "
"rc = [%d]\n", __func__, rc);
inode = ERR_PTR(rc);
goto out_lock;
}
inode = __ecryptfs_get_inode(lower_dentry->d_inode,
directory_inode->i_sb);
if (IS_ERR(inode)) {
vfs_unlink(lower_dir_dentry->d_inode, lower_dentry);
goto out_lock;
}
fsstack_copy_attr_times(directory_inode, lower_dir_dentry->d_inode);
fsstack_copy_inode_size(directory_inode, lower_dir_dentry->d_inode);
out_lock:
unlock_dir(lower_dir_dentry);
out:
return inode;
}
/**
* ecryptfs_initialize_file
*
* Cause the file to be changed from a basic empty file to an ecryptfs
* file with a header and first data page.
*
* Returns zero on success
*/
int ecryptfs_initialize_file(struct dentry *ecryptfs_dentry,
struct inode *ecryptfs_inode)
{
struct ecryptfs_crypt_stat *crypt_stat =
&ecryptfs_inode_to_private(ecryptfs_inode)->crypt_stat;
int rc = 0;
if (S_ISDIR(ecryptfs_inode->i_mode)) {
ecryptfs_printk(KERN_DEBUG, "This is a directory\n");
crypt_stat->flags &= ~(ECRYPTFS_ENCRYPTED);
goto out;
}
ecryptfs_printk(KERN_DEBUG, "Initializing crypto context\n");
rc = ecryptfs_new_file_context(ecryptfs_inode);
if (rc) {
ecryptfs_printk(KERN_ERR, "Error creating new file "
"context; rc = [%d]\n", rc);
goto out;
}
rc = ecryptfs_get_lower_file(ecryptfs_dentry, ecryptfs_inode);
if (rc) {
printk(KERN_ERR "%s: Error attempting to initialize "
"the lower file for the dentry with name "
"[%s]; rc = [%d]\n", __func__,
ecryptfs_dentry->d_name.name, rc);
goto out;
}
#ifdef CONFIG_WTL_ENCRYPTION_FILTER
mutex_lock(&crypt_stat->cs_mutex);
if (crypt_stat->flags & ECRYPTFS_ENCRYPTED) {
struct dentry *fp_dentry =
ecryptfs_inode_to_private(ecryptfs_inode)
->lower_file->f_dentry;
struct ecryptfs_mount_crypt_stat *mount_crypt_stat =
&ecryptfs_superblock_to_private(ecryptfs_dentry->d_sb)
->mount_crypt_stat;
char filename[NAME_MAX+1] = {0};
if (fp_dentry->d_name.len <= NAME_MAX)
memcpy(filename, fp_dentry->d_name.name,
fp_dentry->d_name.len + 1);
if ((mount_crypt_stat->flags & ECRYPTFS_ENABLE_NEW_PASSTHROUGH)
|| ((mount_crypt_stat->flags & ECRYPTFS_ENABLE_FILTERING) &&
(is_file_name_match(mount_crypt_stat, fp_dentry) ||
is_file_ext_match(mount_crypt_stat, filename)))) {
crypt_stat->flags &= ~(ECRYPTFS_I_SIZE_INITIALIZED
| ECRYPTFS_ENCRYPTED);
ecryptfs_put_lower_file(ecryptfs_inode);
} else {
rc = ecryptfs_write_metadata(ecryptfs_dentry,
ecryptfs_inode);
if (rc)
printk(
KERN_ERR "Error writing headers; rc = [%d]\n"
, rc);
ecryptfs_put_lower_file(ecryptfs_inode);
}
}
mutex_unlock(&crypt_stat->cs_mutex);
#else
rc = ecryptfs_write_metadata(ecryptfs_dentry, ecryptfs_inode);
if (rc)
printk(KERN_ERR "Error writing headers; rc = [%d]\n", rc);
ecryptfs_put_lower_file(ecryptfs_inode);
#endif
out:
return rc;
}
int ecryptfs_check_subfs(struct dentry *de, struct nameidata *nd, char *fs)
{
struct dentry *lower_dentry = NULL;
lower_dentry = ecryptfs_dentry_to_lower(de);
if (!lower_dentry->d_op || !lower_dentry->d_op->d_revalidate)
{
return -1;
}
if(!strcmp(lower_dentry->d_sb->s_type->name, fs))
{
return 1;
}
return 0;
}
/**
* ecryptfs_create
* @dir: The inode of the directory in which to create the file.
* @dentry: The eCryptfs dentry
* @mode: The mode of the new file.
* @nd: nameidata
*
* Creates a new file.
*
* Returns zero on success; non-zero on error condition
*/
static int
ecryptfs_create(struct inode *directory_inode, struct dentry *ecryptfs_dentry,
umode_t mode, struct nameidata *nd)
{
struct inode *ecryptfs_inode;
int rc;
if(ecryptfs_check_subfs(ecryptfs_dentry, nd, "sdcardfs") == 1)
ecryptfs_inode = ecryptfs_do_create2(directory_inode, ecryptfs_dentry,
mode, nd);
else
ecryptfs_inode = ecryptfs_do_create(directory_inode, ecryptfs_dentry, mode);
if (unlikely(IS_ERR(ecryptfs_inode))) {
ecryptfs_printk(KERN_WARNING, "Failed to create file in"
"lower filesystem\n");
rc = PTR_ERR(ecryptfs_inode);
goto out;
}
/* At this point, a file exists on "disk"; we need to make sure
* that this on disk file is prepared to be an ecryptfs file */
rc = ecryptfs_initialize_file(ecryptfs_dentry, ecryptfs_inode);
if (rc) {
ecryptfs_do_unlink(directory_inode, ecryptfs_dentry,
ecryptfs_inode);
make_bad_inode(ecryptfs_inode);
unlock_new_inode(ecryptfs_inode);
iput(ecryptfs_inode);
goto out;
}
d_instantiate(ecryptfs_dentry, ecryptfs_inode);
unlock_new_inode(ecryptfs_inode);
out:
return rc;
}
static int ecryptfs_i_size_read(struct dentry *dentry, struct inode *inode)
{
struct ecryptfs_crypt_stat *crypt_stat;
int rc;
rc = ecryptfs_get_lower_file(dentry, inode);
if (rc) {
printk(KERN_ERR "%s: Error attempting to initialize "
"the lower file for the dentry with name "
"[%s]; rc = [%d]\n", __func__,
dentry->d_name.name, rc);
return rc;
}
crypt_stat = &ecryptfs_inode_to_private(inode)->crypt_stat;
/* TODO: lock for crypt_stat comparison */
if (!(crypt_stat->flags & ECRYPTFS_POLICY_APPLIED))
ecryptfs_set_default_sizes(crypt_stat);
rc = ecryptfs_read_and_validate_header_region(inode);
ecryptfs_put_lower_file(inode);
if (rc) {
rc = ecryptfs_read_and_validate_xattr_region(dentry, inode);
if (!rc)
crypt_stat->flags |= ECRYPTFS_METADATA_IN_XATTR;
}
/* Must return 0 to allow non-eCryptfs files to be looked up, too */
return 0;
}
/**
* ecryptfs_lookup_interpose - Dentry interposition for a lookup
*/
static int ecryptfs_lookup_interpose(struct dentry *dentry,
struct dentry *lower_dentry,
struct inode *dir_inode)
{
struct inode *inode, *lower_inode = lower_dentry->d_inode;
struct ecryptfs_dentry_info *dentry_info;
struct vfsmount *lower_mnt;
int rc = 0;
lower_mnt = mntget(ecryptfs_dentry_to_lower_mnt(dentry->d_parent));
fsstack_copy_attr_atime(dir_inode, lower_dentry->d_parent->d_inode);
BUG_ON(!lower_dentry->d_count);
dentry_info = kmem_cache_alloc(ecryptfs_dentry_info_cache, GFP_KERNEL);
ecryptfs_set_dentry_private(dentry, dentry_info);
if (!dentry_info) {
printk(KERN_ERR "%s: Out of memory whilst attempting "
"to allocate ecryptfs_dentry_info struct\n",
__func__);
dput(lower_dentry);
mntput(lower_mnt);
d_drop(dentry);
return -ENOMEM;
}
ecryptfs_set_dentry_lower(dentry, lower_dentry);
ecryptfs_set_dentry_lower_mnt(dentry, lower_mnt);
if (!lower_dentry->d_inode) {
/* We want to add because we couldn't find in lower */
d_add(dentry, NULL);
return 0;
}
inode = __ecryptfs_get_inode(lower_inode, dir_inode->i_sb);
if (IS_ERR(inode)) {
printk(KERN_ERR "%s: Error interposing; rc = [%ld]\n",
__func__, PTR_ERR(inode));
return PTR_ERR(inode);
}
if (S_ISREG(inode->i_mode)) {
rc = ecryptfs_i_size_read(dentry, inode);
if (rc) {
make_bad_inode(inode);
return rc;
}
}
if (inode->i_state & I_NEW)
unlock_new_inode(inode);
d_add(dentry, inode);
return rc;
}
/**
* ecryptfs_lookup
* @ecryptfs_dir_inode: The eCryptfs directory inode
* @ecryptfs_dentry: The eCryptfs dentry that we are looking up
* @ecryptfs_nd: nameidata; may be NULL
*
* Find a file on disk. If the file does not exist, then we'll add it to the
* dentry cache and continue on to read it from the disk.
*/
static struct dentry *ecryptfs_lookup(struct inode *ecryptfs_dir_inode,
struct dentry *ecryptfs_dentry,
struct nameidata *ecryptfs_nd)
{
char *encrypted_and_encoded_name = NULL;
size_t encrypted_and_encoded_name_size;
struct ecryptfs_mount_crypt_stat *mount_crypt_stat = NULL;
struct dentry *lower_dir_dentry, *lower_dentry;
int rc = 0;
if ((ecryptfs_dentry->d_name.len == 1
&& !strcmp(ecryptfs_dentry->d_name.name, "."))
|| (ecryptfs_dentry->d_name.len == 2
&& !strcmp(ecryptfs_dentry->d_name.name, ".."))) {
goto out_d_drop;
}
lower_dir_dentry = ecryptfs_dentry_to_lower(ecryptfs_dentry->d_parent);
mutex_lock(&lower_dir_dentry->d_inode->i_mutex);
lower_dentry = lookup_one_len(ecryptfs_dentry->d_name.name,
lower_dir_dentry,
ecryptfs_dentry->d_name.len);
mutex_unlock(&lower_dir_dentry->d_inode->i_mutex);
if (IS_ERR(lower_dentry)) {
rc = PTR_ERR(lower_dentry);
ecryptfs_printk(KERN_DEBUG, "%s: lookup_one_len() returned "
"[%d] on lower_dentry = [%s]\n", __func__, rc,
encrypted_and_encoded_name);
goto out_d_drop;
}
if (lower_dentry->d_inode)
goto interpose;
mount_crypt_stat = &ecryptfs_superblock_to_private(
ecryptfs_dentry->d_sb)->mount_crypt_stat;
if (!(mount_crypt_stat
&& (mount_crypt_stat->flags & ECRYPTFS_GLOBAL_ENCRYPT_FILENAMES)))
goto interpose;
dput(lower_dentry);
rc = ecryptfs_encrypt_and_encode_filename(
&encrypted_and_encoded_name, &encrypted_and_encoded_name_size,
NULL, mount_crypt_stat, ecryptfs_dentry->d_name.name,
ecryptfs_dentry->d_name.len);
if (rc) {
printk(KERN_ERR "%s: Error attempting to encrypt and encode "
"filename; rc = [%d]\n", __func__, rc);
goto out_d_drop;
}
mutex_lock(&lower_dir_dentry->d_inode->i_mutex);
lower_dentry = lookup_one_len(encrypted_and_encoded_name,
lower_dir_dentry,
encrypted_and_encoded_name_size);
mutex_unlock(&lower_dir_dentry->d_inode->i_mutex);
if (IS_ERR(lower_dentry)) {
rc = PTR_ERR(lower_dentry);
ecryptfs_printk(KERN_DEBUG, "%s: lookup_one_len() returned "
"[%d] on lower_dentry = [%s]\n", __func__, rc,
encrypted_and_encoded_name);
goto out_d_drop;
}
interpose:
rc = ecryptfs_lookup_interpose(ecryptfs_dentry, lower_dentry,
ecryptfs_dir_inode);
goto out;
out_d_drop:
d_drop(ecryptfs_dentry);
out:
kfree(encrypted_and_encoded_name);
return ERR_PTR(rc);
}
static int ecryptfs_link(struct dentry *old_dentry, struct inode *dir,
struct dentry *new_dentry)
{
struct dentry *lower_old_dentry;
struct dentry *lower_new_dentry;
struct dentry *lower_dir_dentry;
u64 file_size_save;
int rc;
file_size_save = i_size_read(old_dentry->d_inode);
lower_old_dentry = ecryptfs_dentry_to_lower(old_dentry);
lower_new_dentry = ecryptfs_dentry_to_lower(new_dentry);
dget(lower_old_dentry);
dget(lower_new_dentry);
lower_dir_dentry = lock_parent(lower_new_dentry);
rc = vfs_link(lower_old_dentry, lower_dir_dentry->d_inode,
lower_new_dentry);
if (rc || !lower_new_dentry->d_inode)
goto out_lock;
rc = ecryptfs_interpose(lower_new_dentry, new_dentry, dir->i_sb);
if (rc)
goto out_lock;
fsstack_copy_attr_times(dir, lower_dir_dentry->d_inode);
fsstack_copy_inode_size(dir, lower_dir_dentry->d_inode);
set_nlink(old_dentry->d_inode,
ecryptfs_inode_to_lower(old_dentry->d_inode)->i_nlink);
i_size_write(new_dentry->d_inode, file_size_save);
out_lock:
unlock_dir(lower_dir_dentry);
dput(lower_new_dentry);
dput(lower_old_dentry);
return rc;
}
static int ecryptfs_unlink(struct inode *dir, struct dentry *dentry)
{
return ecryptfs_do_unlink(dir, dentry, dentry->d_inode);
}
static int ecryptfs_symlink(struct inode *dir, struct dentry *dentry,
const char *symname)
{
int rc;
struct dentry *lower_dentry;
struct dentry *lower_dir_dentry;
char *encoded_symname;
size_t encoded_symlen;
struct ecryptfs_mount_crypt_stat *mount_crypt_stat = NULL;
lower_dentry = ecryptfs_dentry_to_lower(dentry);
dget(lower_dentry);
lower_dir_dentry = lock_parent(lower_dentry);
mount_crypt_stat = &ecryptfs_superblock_to_private(
dir->i_sb)->mount_crypt_stat;
rc = ecryptfs_encrypt_and_encode_filename(&encoded_symname,
&encoded_symlen,
NULL,
mount_crypt_stat, symname,
strlen(symname));
if (rc)
goto out_lock;
rc = vfs_symlink(lower_dir_dentry->d_inode, lower_dentry,
encoded_symname);
kfree(encoded_symname);
if (rc || !lower_dentry->d_inode)
goto out_lock;
rc = ecryptfs_interpose(lower_dentry, dentry, dir->i_sb);
if (rc)
goto out_lock;
fsstack_copy_attr_times(dir, lower_dir_dentry->d_inode);
fsstack_copy_inode_size(dir, lower_dir_dentry->d_inode);
out_lock:
unlock_dir(lower_dir_dentry);
dput(lower_dentry);
if (!dentry->d_inode)
d_drop(dentry);
return rc;
}
static int ecryptfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
{
int rc;
struct dentry *lower_dentry;
struct dentry *lower_dir_dentry;
lower_dentry = ecryptfs_dentry_to_lower(dentry);
lower_dir_dentry = lock_parent(lower_dentry);
rc = vfs_mkdir(lower_dir_dentry->d_inode, lower_dentry, mode);
if (rc || !lower_dentry->d_inode)
goto out;
rc = ecryptfs_interpose(lower_dentry, dentry, dir->i_sb);
if (rc)
goto out;
fsstack_copy_attr_times(dir, lower_dir_dentry->d_inode);
fsstack_copy_inode_size(dir, lower_dir_dentry->d_inode);
set_nlink(dir, lower_dir_dentry->d_inode->i_nlink);
out:
unlock_dir(lower_dir_dentry);
if (!dentry->d_inode)
d_drop(dentry);
return rc;
}
static int ecryptfs_rmdir(struct inode *dir, struct dentry *dentry)
{
struct dentry *lower_dentry;
struct dentry *lower_dir_dentry;
int rc;
lower_dentry = ecryptfs_dentry_to_lower(dentry);
dget(dentry);
lower_dir_dentry = lock_parent(lower_dentry);
dget(lower_dentry);
rc = vfs_rmdir(lower_dir_dentry->d_inode, lower_dentry);
dput(lower_dentry);
if (!rc && dentry->d_inode)
clear_nlink(dentry->d_inode);
fsstack_copy_attr_times(dir, lower_dir_dentry->d_inode);
set_nlink(dir, lower_dir_dentry->d_inode->i_nlink);
unlock_dir(lower_dir_dentry);
if (!rc)
d_drop(dentry);
dput(dentry);
return rc;
}
static int
ecryptfs_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
{
int rc;
struct dentry *lower_dentry;
struct dentry *lower_dir_dentry;
lower_dentry = ecryptfs_dentry_to_lower(dentry);
lower_dir_dentry = lock_parent(lower_dentry);
rc = vfs_mknod(lower_dir_dentry->d_inode, lower_dentry, mode, dev);
if (rc || !lower_dentry->d_inode)
goto out;
rc = ecryptfs_interpose(lower_dentry, dentry, dir->i_sb);
if (rc)
goto out;
fsstack_copy_attr_times(dir, lower_dir_dentry->d_inode);
fsstack_copy_inode_size(dir, lower_dir_dentry->d_inode);
out:
unlock_dir(lower_dir_dentry);
if (!dentry->d_inode)
d_drop(dentry);
return rc;
}
static int
ecryptfs_rename(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry)
{
int rc;
struct dentry *lower_old_dentry;
struct dentry *lower_new_dentry;
struct dentry *lower_old_dir_dentry;
struct dentry *lower_new_dir_dentry;
struct dentry *trap = NULL;
struct inode *target_inode;
lower_old_dentry = ecryptfs_dentry_to_lower(old_dentry);
lower_new_dentry = ecryptfs_dentry_to_lower(new_dentry);
dget(lower_old_dentry);
dget(lower_new_dentry);
lower_old_dir_dentry = dget_parent(lower_old_dentry);
lower_new_dir_dentry = dget_parent(lower_new_dentry);
target_inode = new_dentry->d_inode;
trap = lock_rename(lower_old_dir_dentry, lower_new_dir_dentry);
/* source should not be ancestor of target */
if (trap == lower_old_dentry) {
rc = -EINVAL;
goto out_lock;
}
/* target should not be ancestor of source */
if (trap == lower_new_dentry) {
rc = -ENOTEMPTY;
goto out_lock;
}
rc = vfs_rename(lower_old_dir_dentry->d_inode, lower_old_dentry,
lower_new_dir_dentry->d_inode, lower_new_dentry);
if (rc)
goto out_lock;
if (target_inode)
fsstack_copy_attr_all(target_inode,
ecryptfs_inode_to_lower(target_inode));
fsstack_copy_attr_all(new_dir, lower_new_dir_dentry->d_inode);
if (new_dir != old_dir)
fsstack_copy_attr_all(old_dir, lower_old_dir_dentry->d_inode);
out_lock:
unlock_rename(lower_old_dir_dentry, lower_new_dir_dentry);
dput(lower_new_dir_dentry);
dput(lower_old_dir_dentry);
dput(lower_new_dentry);
dput(lower_old_dentry);
return rc;
}
static int ecryptfs_readlink_lower(struct dentry *dentry, char **buf,
size_t *bufsiz)
{
struct dentry *lower_dentry = ecryptfs_dentry_to_lower(dentry);
char *lower_buf;
size_t lower_bufsiz = PATH_MAX;
mm_segment_t old_fs;
int rc;
lower_buf = kmalloc(lower_bufsiz, GFP_KERNEL);
if (!lower_buf) {
rc = -ENOMEM;
goto out;
}
old_fs = get_fs();
set_fs(get_ds());
rc = lower_dentry->d_inode->i_op->readlink(lower_dentry,
(char __user *)lower_buf,
lower_bufsiz);
set_fs(old_fs);
if (rc < 0)
goto out;
lower_bufsiz = rc;
rc = ecryptfs_decode_and_decrypt_filename(buf, bufsiz, dentry,
lower_buf, lower_bufsiz);
out:
kfree(lower_buf);
return rc;
}
static int
ecryptfs_readlink(struct dentry *dentry, char __user *buf, int bufsiz)
{
char *kbuf;
size_t kbufsiz, copied;
int rc;
rc = ecryptfs_readlink_lower(dentry, &kbuf, &kbufsiz);
if (rc)
goto out;
copied = min_t(size_t, bufsiz, kbufsiz);
rc = copy_to_user(buf, kbuf, copied) ? -EFAULT : copied;
kfree(kbuf);
fsstack_copy_attr_atime(dentry->d_inode,
ecryptfs_dentry_to_lower(dentry)->d_inode);
out:
return rc;
}
static void *ecryptfs_follow_link(struct dentry *dentry, struct nameidata *nd)
{
char *buf;
int len = PAGE_SIZE, rc;
mm_segment_t old_fs;
/* Released in ecryptfs_put_link(); only release here on error */
buf = kmalloc(len, GFP_KERNEL);
if (!buf) {
buf = ERR_PTR(-ENOMEM);
goto out;
}
old_fs = get_fs();
set_fs(get_ds());
rc = dentry->d_inode->i_op->readlink(dentry, (char __user *)buf, len);
set_fs(old_fs);
if (rc < 0) {
kfree(buf);
buf = ERR_PTR(rc);
} else
buf[rc] = '\0';
out:
nd_set_link(nd, buf);
return NULL;
}
static void
ecryptfs_put_link(struct dentry *dentry, struct nameidata *nd, void *ptr)
{
char *buf = nd_get_link(nd);
if (!IS_ERR(buf)) {
/* Free the char* */
kfree(buf);
}
}
/**
* upper_size_to_lower_size
* @crypt_stat: Crypt_stat associated with file
* @upper_size: Size of the upper file
*
* Calculate the required size of the lower file based on the
* specified size of the upper file. This calculation is based on the
* number of headers in the underlying file and the extent size.
*
* Returns Calculated size of the lower file.
*/
static loff_t
upper_size_to_lower_size(struct ecryptfs_crypt_stat *crypt_stat,
loff_t upper_size)
{
loff_t lower_size;
lower_size = ecryptfs_lower_header_size(crypt_stat);
if (upper_size != 0) {
loff_t num_extents;
num_extents = upper_size >> crypt_stat->extent_shift;
if (upper_size & ~crypt_stat->extent_mask)
num_extents++;
lower_size += (num_extents * crypt_stat->extent_size);
}
return lower_size;
}
/**
* truncate_upper
* @dentry: The ecryptfs layer dentry
* @ia: Address of the ecryptfs inode's attributes
* @lower_ia: Address of the lower inode's attributes
*
* Function to handle truncations modifying the size of the file. Note
* that the file sizes are interpolated. When expanding, we are simply
* writing strings of 0's out. When truncating, we truncate the upper
* inode and update the lower_ia according to the page index
* interpolations. If ATTR_SIZE is set in lower_ia->ia_valid upon return,
* the caller must use lower_ia in a call to notify_change() to perform
* the truncation of the lower inode.
*
* Returns zero on success; non-zero otherwise
*/
static int truncate_upper(struct dentry *dentry, struct iattr *ia,
struct iattr *lower_ia)
{
int rc = 0;
struct inode *inode = dentry->d_inode;
struct ecryptfs_crypt_stat *crypt_stat;
loff_t i_size = i_size_read(inode);
loff_t lower_size_before_truncate;
loff_t lower_size_after_truncate;
if (unlikely((ia->ia_size == i_size))) {
lower_ia->ia_valid &= ~ATTR_SIZE;
return 0;
}
rc = ecryptfs_get_lower_file(dentry, inode);
if (rc)
return rc;
crypt_stat = &ecryptfs_inode_to_private(dentry->d_inode)->crypt_stat;
/* Switch on growing or shrinking file */
if (ia->ia_size > i_size) {
char zero[] = { 0x00 };
lower_ia->ia_valid &= ~ATTR_SIZE;
/* Write a single 0 at the last position of the file;
* this triggers code that will fill in 0's throughout
* the intermediate portion of the previous end of the
* file and the new and of the file */
rc = ecryptfs_write(inode, zero,
(ia->ia_size - 1), 1);
} else { /* ia->ia_size < i_size_read(inode) */
/* We're chopping off all the pages down to the page
* in which ia->ia_size is located. Fill in the end of
* that page from (ia->ia_size & ~PAGE_CACHE_MASK) to
* PAGE_CACHE_SIZE with zeros. */
size_t num_zeros = (PAGE_CACHE_SIZE
- (ia->ia_size & ~PAGE_CACHE_MASK));
if (!(crypt_stat->flags & ECRYPTFS_ENCRYPTED)) {
truncate_setsize(inode, ia->ia_size);
lower_ia->ia_size = ia->ia_size;
lower_ia->ia_valid |= ATTR_SIZE;
goto out;
}
if (num_zeros) {
char *zeros_virt;
zeros_virt = kzalloc(num_zeros, GFP_KERNEL);
if (!zeros_virt) {
rc = -ENOMEM;
goto out;
}
rc = ecryptfs_write(inode, zeros_virt,
ia->ia_size, num_zeros);
kfree(zeros_virt);
if (rc) {
printk(KERN_ERR "Error attempting to zero out "
"the remainder of the end page on "
"reducing truncate; rc = [%d]\n", rc);
goto out;
}
}
truncate_setsize(inode, ia->ia_size);
rc = ecryptfs_write_inode_size_to_metadata(inode);
if (rc) {
printk(KERN_ERR "Problem with "
"ecryptfs_write_inode_size_to_metadata; "
"rc = [%d]\n", rc);
goto out;
}
/* We are reducing the size of the ecryptfs file, and need to
* know if we need to reduce the size of the lower file. */
lower_size_before_truncate =
upper_size_to_lower_size(crypt_stat, i_size);
lower_size_after_truncate =
upper_size_to_lower_size(crypt_stat, ia->ia_size);
if (lower_size_after_truncate < lower_size_before_truncate) {
lower_ia->ia_size = lower_size_after_truncate;
lower_ia->ia_valid |= ATTR_SIZE;
} else
lower_ia->ia_valid &= ~ATTR_SIZE;
}
out:
ecryptfs_put_lower_file(inode);
return rc;
}
static int ecryptfs_inode_newsize_ok(struct inode *inode, loff_t offset)
{
struct ecryptfs_crypt_stat *crypt_stat;
loff_t lower_oldsize, lower_newsize;
crypt_stat = &ecryptfs_inode_to_private(inode)->crypt_stat;
lower_oldsize = upper_size_to_lower_size(crypt_stat,
i_size_read(inode));
lower_newsize = upper_size_to_lower_size(crypt_stat, offset);
if (lower_newsize > lower_oldsize) {
/*
* The eCryptfs inode and the new *lower* size are mixed here
* because we may not have the lower i_mutex held and/or it may
* not be appropriate to call inode_newsize_ok() with inodes
* from other filesystems.
*/
return inode_newsize_ok(inode, lower_newsize);
}
return 0;
}
/**
* ecryptfs_truncate
* @dentry: The ecryptfs layer dentry
* @new_length: The length to expand the file to
*
* Simple function that handles the truncation of an eCryptfs inode and
* its corresponding lower inode.
*
* Returns zero on success; non-zero otherwise
*/
int ecryptfs_truncate(struct dentry *dentry, loff_t new_length)
{
struct iattr ia = { .ia_valid = ATTR_SIZE, .ia_size = new_length };
struct iattr lower_ia = { .ia_valid = 0 };
int rc;
rc = ecryptfs_inode_newsize_ok(dentry->d_inode, new_length);
if (rc)
return rc;
rc = truncate_upper(dentry, &ia, &lower_ia);
if (!rc && lower_ia.ia_valid & ATTR_SIZE) {
struct dentry *lower_dentry = ecryptfs_dentry_to_lower(dentry);
mutex_lock(&lower_dentry->d_inode->i_mutex);
rc = notify_change(lower_dentry, &lower_ia);
mutex_unlock(&lower_dentry->d_inode->i_mutex);
}
return rc;
}
static int
ecryptfs_permission(struct inode *inode, int mask)
{
return inode_permission(ecryptfs_inode_to_lower(inode), mask);
}
/**
* ecryptfs_setattr
* @dentry: dentry handle to the inode to modify
* @ia: Structure with flags of what to change and values
*
* Updates the metadata of an inode. If the update is to the size
* i.e. truncation, then ecryptfs_truncate will handle the size modification
* of both the ecryptfs inode and the lower inode.
*
* All other metadata changes will be passed right to the lower filesystem,
* and we will just update our inode to look like the lower.
*/
static int ecryptfs_setattr(struct dentry *dentry, struct iattr *ia)
{
int rc = 0;
struct dentry *lower_dentry;
struct iattr lower_ia;
struct inode *inode;
struct inode *lower_inode;
struct ecryptfs_crypt_stat *crypt_stat;
crypt_stat = &ecryptfs_inode_to_private(dentry->d_inode)->crypt_stat;
if (!(crypt_stat->flags & ECRYPTFS_STRUCT_INITIALIZED))
ecryptfs_init_crypt_stat(crypt_stat);
inode = dentry->d_inode;
lower_inode = ecryptfs_inode_to_lower(inode);
lower_dentry = ecryptfs_dentry_to_lower(dentry);
mutex_lock(&crypt_stat->cs_mutex);
if (S_ISDIR(dentry->d_inode->i_mode))
crypt_stat->flags &= ~(ECRYPTFS_ENCRYPTED);
else if (S_ISREG(dentry->d_inode->i_mode)
&& (!(crypt_stat->flags & ECRYPTFS_POLICY_APPLIED)
|| !(crypt_stat->flags & ECRYPTFS_KEY_VALID))) {
struct ecryptfs_mount_crypt_stat *mount_crypt_stat;
mount_crypt_stat = &ecryptfs_superblock_to_private(
dentry->d_sb)->mount_crypt_stat;
rc = ecryptfs_get_lower_file(dentry, inode);
if (rc) {
mutex_unlock(&crypt_stat->cs_mutex);
goto out;
}
rc = ecryptfs_read_metadata(dentry);
ecryptfs_put_lower_file(inode);
if (rc) {
if (!(mount_crypt_stat->flags
& ECRYPTFS_PLAINTEXT_PASSTHROUGH_ENABLED)) {
rc = -EIO;
printk(KERN_WARNING "Either the lower file "
"is not in a valid eCryptfs format, "
"or the key could not be retrieved. "
"Plaintext passthrough mode is not "
"enabled; returning -EIO\n");
mutex_unlock(&crypt_stat->cs_mutex);
goto out;
}
rc = 0;
crypt_stat->flags &= ~(ECRYPTFS_I_SIZE_INITIALIZED
| ECRYPTFS_ENCRYPTED);
}
}
mutex_unlock(&crypt_stat->cs_mutex);
rc = inode_change_ok(inode, ia);
if (rc)
goto out;
if (ia->ia_valid & ATTR_SIZE) {
rc = ecryptfs_inode_newsize_ok(inode, ia->ia_size);
if (rc)
goto out;
}
memcpy(&lower_ia, ia, sizeof(lower_ia));
if (ia->ia_valid & ATTR_FILE)
lower_ia.ia_file = ecryptfs_file_to_lower(ia->ia_file);
if (ia->ia_valid & ATTR_SIZE) {
rc = truncate_upper(dentry, ia, &lower_ia);
if (rc < 0)
goto out;
}
/*
* mode change is for clearing setuid/setgid bits. Allow lower fs
* to interpret this in its own way.
*/
if (lower_ia.ia_valid & (ATTR_KILL_SUID | ATTR_KILL_SGID))
lower_ia.ia_valid &= ~ATTR_MODE;
mutex_lock(&lower_dentry->d_inode->i_mutex);
rc = notify_change(lower_dentry, &lower_ia);
mutex_unlock(&lower_dentry->d_inode->i_mutex);
out:
fsstack_copy_attr_all(inode, lower_inode);
return rc;
}
int ecryptfs_getattr_link(struct vfsmount *mnt, struct dentry *dentry,
struct kstat *stat)
{
struct ecryptfs_mount_crypt_stat *mount_crypt_stat;
int rc = 0;
mount_crypt_stat = &ecryptfs_superblock_to_private(
dentry->d_sb)->mount_crypt_stat;
generic_fillattr(dentry->d_inode, stat);
if (mount_crypt_stat->flags & ECRYPTFS_GLOBAL_ENCRYPT_FILENAMES) {
char *target;
size_t targetsiz;
rc = ecryptfs_readlink_lower(dentry, &target, &targetsiz);
if (!rc) {
kfree(target);
stat->size = targetsiz;
}
}
return rc;
}
int ecryptfs_getattr(struct vfsmount *mnt, struct dentry *dentry,
struct kstat *stat)
{
struct kstat lower_stat;
int rc;
rc = vfs_getattr(ecryptfs_dentry_to_lower_mnt(dentry),
ecryptfs_dentry_to_lower(dentry), &lower_stat);
if (!rc) {
fsstack_copy_attr_all(dentry->d_inode,
ecryptfs_inode_to_lower(dentry->d_inode));
generic_fillattr(dentry->d_inode, stat);
stat->blocks = lower_stat.blocks;
}
return rc;
}
int
ecryptfs_setxattr(struct dentry *dentry, const char *name, const void *value,
size_t size, int flags)
{
int rc = 0;
struct dentry *lower_dentry;
lower_dentry = ecryptfs_dentry_to_lower(dentry);
if (!lower_dentry->d_inode->i_op->setxattr) {
rc = -EOPNOTSUPP;
goto out;
}
rc = vfs_setxattr(lower_dentry, name, value, size, flags);
if (!rc)
fsstack_copy_attr_all(dentry->d_inode, lower_dentry->d_inode);
out:
return rc;
}
ssize_t
ecryptfs_getxattr_lower(struct dentry *lower_dentry, const char *name,
void *value, size_t size)
{
int rc = 0;
if (!lower_dentry->d_inode->i_op->getxattr) {
rc = -EOPNOTSUPP;
goto out;
}
mutex_lock(&lower_dentry->d_inode->i_mutex);
rc = lower_dentry->d_inode->i_op->getxattr(lower_dentry, name, value,
size);
mutex_unlock(&lower_dentry->d_inode->i_mutex);
out:
return rc;
}
static ssize_t
ecryptfs_getxattr(struct dentry *dentry, const char *name, void *value,
size_t size)
{
return ecryptfs_getxattr_lower(ecryptfs_dentry_to_lower(dentry), name,
value, size);
}
static ssize_t
ecryptfs_listxattr(struct dentry *dentry, char *list, size_t size)
{
int rc = 0;
struct dentry *lower_dentry;
lower_dentry = ecryptfs_dentry_to_lower(dentry);
if (!lower_dentry->d_inode->i_op->listxattr) {
rc = -EOPNOTSUPP;
goto out;
}
mutex_lock(&lower_dentry->d_inode->i_mutex);
rc = lower_dentry->d_inode->i_op->listxattr(lower_dentry, list, size);
mutex_unlock(&lower_dentry->d_inode->i_mutex);
out:
return rc;
}
static int ecryptfs_removexattr(struct dentry *dentry, const char *name)
{
int rc = 0;
struct dentry *lower_dentry;
lower_dentry = ecryptfs_dentry_to_lower(dentry);
if (!lower_dentry->d_inode->i_op->removexattr) {
rc = -EOPNOTSUPP;
goto out;
}
mutex_lock(&lower_dentry->d_inode->i_mutex);
rc = lower_dentry->d_inode->i_op->removexattr(lower_dentry, name);
mutex_unlock(&lower_dentry->d_inode->i_mutex);
out:
return rc;
}
const struct inode_operations ecryptfs_symlink_iops = {
.readlink = ecryptfs_readlink,
.follow_link = ecryptfs_follow_link,
.put_link = ecryptfs_put_link,
.permission = ecryptfs_permission,
.setattr = ecryptfs_setattr,
.getattr = ecryptfs_getattr_link,
.setxattr = ecryptfs_setxattr,
.getxattr = ecryptfs_getxattr,
.listxattr = ecryptfs_listxattr,
.removexattr = ecryptfs_removexattr
};
const struct inode_operations ecryptfs_dir_iops = {
.create = ecryptfs_create,
.lookup = ecryptfs_lookup,
.link = ecryptfs_link,
.unlink = ecryptfs_unlink,
.symlink = ecryptfs_symlink,
.mkdir = ecryptfs_mkdir,
.rmdir = ecryptfs_rmdir,
.mknod = ecryptfs_mknod,
.rename = ecryptfs_rename,
.permission = ecryptfs_permission,
.setattr = ecryptfs_setattr,
.setxattr = ecryptfs_setxattr,
.getxattr = ecryptfs_getxattr,
.listxattr = ecryptfs_listxattr,
.removexattr = ecryptfs_removexattr
};
const struct inode_operations ecryptfs_main_iops = {
.permission = ecryptfs_permission,
.setattr = ecryptfs_setattr,
.getattr = ecryptfs_getattr,
.setxattr = ecryptfs_setxattr,
.getxattr = ecryptfs_getxattr,
.listxattr = ecryptfs_listxattr,
.removexattr = ecryptfs_removexattr
};
|
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#ifndef OS_SOLARIS_VM_OS_SOLARIS_INLINE_HPP
#define OS_SOLARIS_VM_OS_SOLARIS_INLINE_HPP
#include "runtime/atomic.inline.hpp"
#include "runtime/os.hpp"
#ifdef TARGET_OS_ARCH_solaris_x86
# include "orderAccess_solaris_x86.inline.hpp"
#endif
#ifdef TARGET_OS_ARCH_solaris_sparc
# include "orderAccess_solaris_sparc.inline.hpp"
#endif
// System includes
#include <sys/param.h>
#include <dlfcn.h>
#include <sys/socket.h>
#include <sys/poll.h>
#include <sys/filio.h>
#include <unistd.h>
#include <netdb.h>
#include <setjmp.h>
inline const char* os::file_separator() { return "/"; }
inline const char* os::line_separator() { return "\n"; }
inline const char* os::path_separator() { return ":"; }
// File names are case-sensitive on windows only
inline int os::file_name_strcmp(const char* s1, const char* s2) {
return strcmp(s1, s2);
}
inline bool os::uses_stack_guard_pages() {
return true;
}
inline bool os::allocate_stack_guard_pages() {
assert(uses_stack_guard_pages(), "sanity check");
int r = thr_main() ;
guarantee (r == 0 || r == 1, "CR6501650 or CR6493689") ;
return r;
}
// On Solaris, reservations are made on a page by page basis, nothing to do.
inline void os::pd_split_reserved_memory(char *base, size_t size,
size_t split, bool realloc) {
}
// Bang the shadow pages if they need to be touched to be mapped.
inline void os::bang_stack_shadow_pages() {
}
inline void os::dll_unload(void *lib) { ::dlclose(lib); }
inline DIR* os::opendir(const char* dirname) {
assert(dirname != NULL, "just checking");
return ::opendir(dirname);
}
inline int os::readdir_buf_size(const char *path) {
int size = pathconf(path, _PC_NAME_MAX);
return (size < 0 ? MAXPATHLEN : size) + sizeof(dirent) + 1;
}
inline struct dirent* os::readdir(DIR* dirp, dirent* dbuf) {
assert(dirp != NULL, "just checking");
#if defined(_LP64) || defined(_GNU_SOURCE) || _FILE_OFFSET_BITS==64
dirent* p;
int status;
if((status = ::readdir_r(dirp, dbuf, &p)) != 0) {
errno = status;
return NULL;
} else
return p;
#else // defined(_LP64) || defined(_GNU_SOURCE) || _FILE_OFFSET_BITS==64
return ::readdir_r(dirp, dbuf);
#endif // defined(_LP64) || defined(_GNU_SOURCE) || _FILE_OFFSET_BITS==64
}
inline int os::closedir(DIR *dirp) {
assert(dirp != NULL, "argument is NULL");
return ::closedir(dirp);
}
//////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// macros for interruptible io and system calls and system call restarting
#define _INTERRUPTIBLE(_setup, _cmd, _result, _thread, _clear, _before, _after, _int_enable) \
do { \
_setup; \
_before; \
OSThread* _osthread = _thread->osthread(); \
if (_int_enable && _thread->has_last_Java_frame()) { \
/* this is java interruptible io stuff */ \
if (os::is_interrupted(_thread, _clear)) { \
os::Solaris::bump_interrupted_before_count(); \
_result = OS_INTRPT; \
} else { \
/* _cmd always expands to an assignment to _result */ \
if ((_cmd) < 0 && errno == EINTR \
&& os::is_interrupted(_thread, _clear)) { \
os::Solaris::bump_interrupted_during_count(); \
_result = OS_INTRPT; \
} \
} \
} else { \
/* this is normal blocking io stuff */ \
_cmd; \
} \
_after; \
} while(false)
// Interruptible io support + restarting of interrupted system calls
#ifndef ASSERT
#define INTERRUPTIBLE(_cmd, _result, _clear) do { \
_INTERRUPTIBLE( JavaThread* _thread = (JavaThread*)ThreadLocalStorage::thread(),_result = _cmd, _result, _thread, _clear, , , UseVMInterruptibleIO); \
} while((_result == OS_ERR) && (errno == EINTR))
#else
// This adds an assertion that it is only called from thread_in_native
// The call overhead is skipped for performance in product mode
#define INTERRUPTIBLE(_cmd, _result, _clear) do { \
_INTERRUPTIBLE(JavaThread* _thread = os::Solaris::setup_interruptible_native(), _result = _cmd, _result, _thread, _clear, , os::Solaris::cleanup_interruptible_native(_thread), UseVMInterruptibleIO ); \
} while((_result == OS_ERR) && (errno == EINTR))
#endif
// Used for calls from _thread_in_vm, not from _thread_in_native
#define INTERRUPTIBLE_VM(_cmd, _result, _clear) do { \
_INTERRUPTIBLE(JavaThread* _thread = os::Solaris::setup_interruptible(), _result = _cmd, _result, _thread, _clear, , os::Solaris::cleanup_interruptible(_thread), UseVMInterruptibleIO ); \
} while((_result == OS_ERR) && (errno == EINTR))
/* Use NORESTART when the system call cannot return EINTR, when something other
than a system call is being invoked, or when the caller must do EINTR
handling. */
#ifndef ASSERT
#define INTERRUPTIBLE_NORESTART(_cmd, _result, _clear) \
_INTERRUPTIBLE( JavaThread* _thread = (JavaThread*)ThreadLocalStorage::thread(),_result = _cmd, _result, _thread, _clear, , , UseVMInterruptibleIO)
#else
// This adds an assertion that it is only called from thread_in_native
// The call overhead is skipped for performance in product mode
#define INTERRUPTIBLE_NORESTART(_cmd, _result, _clear) \
_INTERRUPTIBLE(JavaThread* _thread = os::Solaris::setup_interruptible_native(), _result = _cmd, _result, _thread, _clear, , os::Solaris::cleanup_interruptible_native(_thread), UseVMInterruptibleIO )
#endif
// Don't attend to UseVMInterruptibleIO. Always allow interruption.
// Also assumes that it is called from the _thread_blocked state.
// Used by os_sleep().
#define INTERRUPTIBLE_NORESTART_VM_ALWAYS(_cmd, _result, _thread, _clear) \
_INTERRUPTIBLE(os::Solaris::setup_interruptible_already_blocked(_thread), _result = _cmd, _result, _thread, _clear, , , true )
#define INTERRUPTIBLE_RETURN_INT(_cmd, _clear) do { \
int _result; \
do { \
INTERRUPTIBLE(_cmd, _result, _clear); \
} while((_result == OS_ERR) && (errno == EINTR)); \
return _result; \
} while(false)
#define INTERRUPTIBLE_RETURN_INT_VM(_cmd, _clear) do { \
int _result; \
do { \
INTERRUPTIBLE_VM(_cmd, _result, _clear); \
} while((_result == OS_ERR) && (errno == EINTR)); \
return _result; \
} while(false)
#define INTERRUPTIBLE_RETURN_INT_NORESTART(_cmd, _clear) do { \
int _result; \
INTERRUPTIBLE_NORESTART(_cmd, _result, _clear); \
return _result; \
} while(false)
/* Use the RESTARTABLE macros when interruptible io is not needed */
#define RESTARTABLE(_cmd, _result) do { \
do { \
_result = _cmd; \
} while((_result == OS_ERR) && (errno == EINTR)); \
} while(false)
#define RESTARTABLE_RETURN_INT(_cmd) do { \
int _result; \
RESTARTABLE(_cmd, _result); \
return _result; \
} while(false)
inline bool os::numa_has_static_binding() { return false; }
inline bool os::numa_has_group_homing() { return true; }
inline int os::socket(int domain, int type, int protocol) {
return ::socket(domain, type, protocol);
}
inline int os::listen(int fd, int count) {
if (fd < 0) return OS_ERR;
return ::listen(fd, count);
}
inline int os::socket_shutdown(int fd, int howto){
return ::shutdown(fd, howto);
}
inline int os::get_sock_name(int fd, struct sockaddr* him, socklen_t* len){
return ::getsockname(fd, him, len);
}
inline int os::get_host_name(char* name, int namelen){
return ::gethostname(name, namelen);
}
inline struct hostent* os::get_host_by_name(char* name) {
return ::gethostbyname(name);
}
inline int os::get_sock_opt(int fd, int level, int optname,
char* optval, socklen_t* optlen) {
return ::getsockopt(fd, level, optname, optval, optlen);
}
inline int os::set_sock_opt(int fd, int level, int optname,
const char *optval, socklen_t optlen) {
return ::setsockopt(fd, level, optname, optval, optlen);
}
#endif // OS_SOLARIS_VM_OS_SOLARIS_INLINE_HPP
|
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Unit tests for the question bank view class.
*
* @package core_question
* @category test
* @copyright 2018 the Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot . '/question/editlib.php');
/**
* Unit tests for the question bank view class.
*
* @copyright 2018 the Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class core_question_bank_view_testcase extends advanced_testcase {
public function test_viewing_question_bank_should_not_load_individual_questions() {
$this->resetAfterTest();
$this->setAdminUser();
$generator = $this->getDataGenerator();
/** @var core_question_generator $questiongenerator */
$questiongenerator = $generator->get_plugin_generator('core_question');
// Create a course.
$course = $generator->create_course();
$context = context_course::instance($course->id);
// Create a question in the default category.
$contexts = new question_edit_contexts($context);
$cat = question_make_default_categories($contexts->all());
$questiondata = $questiongenerator->create_question('numerical', null,
['name' => 'Example question', 'category' => $cat->id]);
// Ensure the question is not in the cache.
$cache = cache::make('core', 'questiondata');
$cache->delete($questiondata->id);
// Generate the view.
$view = new core_question\local\bank\view($contexts, new moodle_url('/'), $course);
ob_start();
$pagevars = [
'qpage' => 0,
'qperpage' => 20,
'cat' => $cat->id . ',' . $context->id,
'recurse' => false,
'showhidden' => false,
'qbshowtext' => false
];
$view->display($pagevars, 'editq');
$html = ob_get_clean();
// Verify the output includes the expected question.
$this->assertStringContainsString('Example question', $html);
// Verify the question has not been loaded into the cache.
$this->assertFalse($cache->has($questiondata->id));
}
public function test_unknown_qtype_does_not_break_view() {
global $DB;
$this->resetAfterTest();
$this->setAdminUser();
$generator = $this->getDataGenerator();
/** @var core_question_generator $questiongenerator */
$questiongenerator = $generator->get_plugin_generator('core_question');
// Create a course.
$course = $generator->create_course();
$context = context_course::instance($course->id);
// Create a question in the default category.
$contexts = new question_edit_contexts($context);
$cat = question_make_default_categories($contexts->all());
$questiondata = $questiongenerator->create_question('numerical', null,
['name' => 'Example question', 'category' => $cat->id]);
$DB->set_field('question', 'qtype', 'unknownqtype', ['id' => $questiondata->id]);
// Generate the view.
$view = new core_question\local\bank\view($contexts, new moodle_url('/'), $course);
ob_start();
$pagevars = [
'qpage' => 0,
'qperpage' => 20,
'cat' => $cat->id . ',' . $context->id,
'recurse' => false,
'showhidden' => false,
'qbshowtext' => false
];
$view->display($pagevars, 'editq');
$html = ob_get_clean();
// Mainly we are verifying that there was no fatal error.
// Verify the output includes the expected question.
$this->assertStringContainsString('Example question', $html);
}
}
|
#include <linux/kernel.h>
#include <linux/xlog.h>
#include "jpeg_drv_6589_reg.h"
#include "jpeg_drv_6589_common.h"
#define JPEG_ENC_RST_BIT 0x1
#define JPEG_ENC_CTRL_ENABLE_BIT 0x01
#define JPEG_ENC_CTRL_DIS_GMC_BIT 0x02
#define JPEG_ENC_CTRL_INT_EN_BIT 0x04
#define JPEG_ENC_CTRL_YUV_BIT 0x18
#define JPEG_ENC_CTRL_FILE_FORMAT_BIT 0x20
#define JPEG_ENC_CTRL_GRAY_EN_BIT 0x80
#define JPEG_ENC_CTRL_ULTRA_HIGH_EN_BIT 0x200
#define JPEG_ENC_CTRL_RESTART_EN_BIT 0x400
#define JPEG_ENC_CTRL_BURST_TYPE_MASK 0x00007000
#define JPEG_ENC_CTRL_BURST_TYPE_SHIFT_COUNT 12
#define JPEG_ENC_EN_DIS_GMC (1 << 2)
#define JPEG_ENC_EN_JFIF_EXIF (1 << 5)
#define JPEG_ENC_EN_SELF_INIT (1 << 16)
#define JPEG_ENC_DEBUG_INFO0_GMC_IDLE_MASK (1 << 13)
#define JPEG_MSG printk
#define JPEG_WRN printk
#define JPEG_ERR printk
kal_uint32 _jpeg_enc_int_status = 0;
int jpeg_isr_enc_lisr(void)
{
unsigned int tmp, tmp1 ;
//_jpeg_enc_int_status = REG_JPEG_ENC_INTERRUPT_STATUS;
tmp1 = REG_JPEG_ENC_INTERRUPT_STATUS ;
tmp = tmp1 & (JPEG_DRV_ENC_INT_STATUS_MASK_ALLIRQ);
if(tmp){
_jpeg_enc_int_status = tmp ;
/// clear the interrupt status register
//if(_jpeg_enc_int_status)
//{
IMG_REG_WRITE( 0, REG_ADDR_JPEG_ENC_INTERRUPT_STATUS); //REG_JPEG_ENC_INTERRUPT_STATUS = 0;
return 0;
//}
}else if(_jpeg_enc_int_status){
IMG_REG_WRITE( 0, REG_ADDR_JPEG_ENC_INTERRUPT_STATUS); //REG_JPEG_ENC_INTERRUPT_STATUS = 0;
return 0;
}
return -1;
}
kal_uint32 jpeg_drv_enc_set_src_image(kal_uint32 width, kal_uint32 height, kal_uint32 yuv_format, kal_uint32 totalEncDU)
{
kal_uint32 ret = 1;
ret &= jpeg_drv_enc_set_img_size(width, height);
ret &= jpeg_drv_enc_set_encFormat(yuv_format) ;
ret &= jpeg_drv_enc_set_blk_num(totalEncDU);
return ret;
}
kal_uint32 jpeg_drv_enc_set_src_buf(kal_uint32 yuv_format, kal_uint32 img_stride, kal_uint32 mem_stride, kal_uint32 srcAddr, kal_uint32 srcAddr_C)
{
kal_uint32 ret = 1;
if( yuv_format == 0x00 || yuv_format == 0x01 ){
if( (mem_stride & 0x1f) || (img_stride & 0x1f) ){
JPEG_MSG("JPEGENC: set image/memory stride not align 0x1f in fmt %x(%x/%x)!!\n", yuv_format, mem_stride, img_stride);
ret = 0;
}
}
ret &= jpeg_drv_enc_set_image_stride(img_stride);
ret &= jpeg_drv_enc_set_memory_stride(mem_stride);
ret &= jpeg_drv_enc_set_luma_addr(srcAddr);
ret &= jpeg_drv_enc_set_chroma_addr(srcAddr_C);
return ret;
}
///////////////////////////////////////////////////////////////////////////////
kal_uint32 jpeg_drv_enc_ctrl_cfg( kal_uint32 exif_en, kal_uint32 quality, kal_uint32 restart_interval)
{
jpeg_drv_enc_set_quality(quality);
jpeg_drv_enc_set_restart_interval(restart_interval);
jpeg_drv_enc_set_EncodeMode(exif_en);
return 1;
//if (0 != ctrl_cfg.gmc_disable)
// REG_JPEG_ENC_CTRL |= JPEG_ENC_CTRL_DIS_GMC_BIT;
//
//REG_JPEG_ENC_CTRL |= JPEG_ENC_EN_SELF_INIT;
}
void jpeg_drv_enc_dump_reg(void)
{
unsigned int reg_value = 0;
unsigned int index = 0;
JPEG_MSG("===== JPEG ENC DUMP =====\n");
for(index = 0x100 ; index < JPEG_ENC_REG_COUNT ; index += 4){
#ifdef FPGA_VERSION
reg_value = *(volatile kal_uint32 *)(JPEG_ENC_BASE + index);
#else
//reg_value = ioread32(JPEG_ENC_BASE + index);
IMG_REG_READ(reg_value, JPEG_ENC_BASE + index);
#endif
JPEG_MSG("+0x%x 0x%08x\n", index, reg_value);
}
}
void jpeg_drv_enc_start(void)
{
unsigned int u4Value ;
u4Value = REG_JPEG_ENC_CTRL ;
u4Value |= (JPEG_ENC_CTRL_INT_EN_BIT | JPEG_ENC_CTRL_ENABLE_BIT);
IMG_REG_WRITE( (u4Value), REG_ADDR_JPEG_ENC_CTRL);
//REG_JPEG_ENC_CTRL |= (JPEG_ENC_CTRL_INT_EN_BIT | JPEG_ENC_CTRL_ENABLE_BIT);
}
extern void jpeg_drv_enc_power_on(void);
extern void jpeg_drv_enc_power_off(void);
// workaround for jpeg odd read operation at cg gating state
void jpeg_drv_enc_verify_state_and_reset(void)
{
unsigned int temp, value;
IMG_REG_WRITE( (0), REG_ADDR_JPEG_ENC_RSTB); //REG_JPEG_ENC_RSTB = 0;
IMG_REG_WRITE( (0), REG_ADDR_JPEG_ENC_RSTB); //REG_JPEG_ENC_RSTB = 0;
IMG_REG_WRITE( (1), REG_ADDR_JPEG_ENC_RSTB); //REG_JPEG_ENC_RSTB = 1;
IMG_REG_WRITE( (1), REG_ADDR_JPEG_ENC_RSTB); //REG_JPEG_ENC_RSTB = 1;
IMG_REG_READ( temp, REG_ADDR_JPEG_ENC_ULTRA_THRES );
IMG_REG_READ( value, REG_ADDR_JPEG_ENC_DMA_ADDR0 );
// issue happen, need to do 1 read at cg gating state
if (value == 0xFFFFFFFF)
{
JPEG_MSG("JPGENC APB R/W issue found, start to do recovery!\n");
jpeg_drv_enc_power_off();
IMG_REG_READ( value, REG_ADDR_JPEG_ENC_ULTRA_THRES );
jpeg_drv_enc_power_on();
}
IMG_REG_WRITE( (0), REG_ADDR_JPEG_ENC_CODEC_SEL); //REG_JPEG_ENC_CODEC_SEL = 0; //switch SRAM to jpeg module
_jpeg_enc_int_status = 0;
}
void jpeg_drv_enc_reset(void)
{
IMG_REG_WRITE( (0), REG_ADDR_JPEG_ENC_RSTB); //REG_JPEG_ENC_RSTB = 0;
IMG_REG_WRITE( (1), REG_ADDR_JPEG_ENC_RSTB); //REG_JPEG_ENC_RSTB = 1;
IMG_REG_WRITE( (0), REG_ADDR_JPEG_ENC_CODEC_SEL); //REG_JPEG_ENC_CODEC_SEL = 0; //switch SRAM to jpeg module
_jpeg_enc_int_status = 0;
}
kal_uint32 jpeg_drv_enc_warm_reset(void)
{
kal_uint32 timeout = 0xFFFFF;
REG_JPEG_ENC_CTRL &= ~JPEG_ENC_CTRL_ENABLE_BIT;
REG_JPEG_ENC_CTRL |= JPEG_ENC_CTRL_ENABLE_BIT;
while (0 == (REG_JPEG_ENC_DEBUG_INFO0 & JPEG_ENC_DEBUG_INFO0_GMC_IDLE_MASK))
{
timeout--;
if (0 == timeout)
{
JPEG_MSG("Wait for GMC IDLE timeout\n");
return 0;
}
}
REG_JPEG_ENC_RSTB &= ~(JPEG_ENC_RST_BIT);
REG_JPEG_ENC_RSTB |= JPEG_ENC_RST_BIT;
IMG_REG_WRITE( (0), REG_ADDR_JPEG_ENC_CODEC_SEL); //REG_JPEG_ENC_CODEC_SEL = 0;
_jpeg_enc_int_status = 0;
return 1;
}
kal_uint32 jpeg_drv_enc_set_encFormat(kal_uint32 encFormat)
{
kal_uint32 val ;
unsigned int u4Value ;
if(encFormat & (~3)){
JPEG_ERR("JPEG_DRV_ENC: set encFormat Err %d!!\n", encFormat );
return 0;
}
val = (encFormat & 3) << 3;
#if 0
// REG_JPEG_ENC_CTRL &= ~JPEG_ENC_CTRL_YUV_BIT;
//
// REG_JPEG_ENC_CTRL |= val;
#else
u4Value = REG_JPEG_ENC_CTRL ;
u4Value &= ~JPEG_ENC_CTRL_YUV_BIT;
u4Value |= val;
IMG_REG_WRITE( (u4Value), REG_ADDR_JPEG_ENC_CTRL);
#endif
return 1;
}
kal_uint32 jpeg_drv_enc_set_quality(kal_uint32 quality)
{
unsigned int u4Value ;
if (quality == 0x8 || quality == 0xC)
{
JPEG_MSG("JPEGENC: set quality failed\n");
return 0;
}
u4Value = REG_JPEG_ENC_QUALITY;
u4Value = (u4Value & 0xFFFF0000) | quality ;
IMG_REG_WRITE( (u4Value), REG_ADDR_JPEG_ENC_QUALITY); //REG_JPEG_ENC_QUALITY = (REG_JPEG_ENC_QUALITY & 0xFFFF0000) | quality;
return 1;
}
kal_uint32 jpeg_drv_enc_set_img_size(kal_uint32 width, kal_uint32 height)
{
unsigned int u4Value ;
if ((width & 0xffff0000) || (height & 0xffff0000))
{
JPEG_MSG("JPEGENC: img size exceed 65535, (%x, %x)!!\n", width, height);
return 0;
}
u4Value = (width << 16) | height ;
IMG_REG_WRITE( (u4Value), REG_ADDR_JPEG_ENC_IMG_SIZE); //REG_JPEG_ENC_IMG_SIZE = (width << 16) | height;
return 1;
}
kal_uint32 jpeg_drv_enc_set_blk_num(kal_uint32 blk_num) //NO_USE
{
if (blk_num < 4)
{
return 0;
}
IMG_REG_WRITE( (blk_num), REG_ADDR_JPEG_ENC_BLK_NUM); //REG_JPEG_ENC_BLK_NUM = blk_num;
return 1;
}
kal_uint32 jpeg_drv_enc_set_luma_addr(kal_uint32 src_luma_addr)
{
if (src_luma_addr & 0x0F)
{
JPEG_MSG("JPEGENC: set LUMA addr not align (%x)!!\n", src_luma_addr);
//return 0;
}
IMG_REG_WRITE( (src_luma_addr), REG_ADDR_JPEG_ENC_SRC_LUMA_ADDR); //REG_JPEG_ENC_SRC_LUMA_ADDR = src_luma_addr;
return 1;
}
kal_uint32 jpeg_drv_enc_set_chroma_addr(kal_uint32 src_chroma_addr)
{
if (src_chroma_addr & 0x0F)
{
JPEG_MSG("JPEGENC: set CHROMA addr not align (%x)!!\n", src_chroma_addr);
//return 0;
}
IMG_REG_WRITE( (src_chroma_addr), REG_ADDR_JPEG_ENC_SRC_CHROMA_ADDR); //REG_JPEG_ENC_SRC_CHROMA_ADDR = src_chroma_addr;
return 1;
}
kal_uint32 jpeg_drv_enc_set_memory_stride(kal_uint32 mem_stride)
{
if ( mem_stride & 0x0F )
{
JPEG_MSG("JPEGENC: set memory stride failed, not align to 0x1f (%x)!!\n", mem_stride);
return 0;
}
IMG_REG_WRITE( (mem_stride), REG_ADDR_JPEG_ENC_STRIDE); //REG_JPEG_ENC_STRIDE = (mem_stride);
return 1;
}
kal_uint32 jpeg_drv_enc_set_image_stride(kal_uint32 img_stride)
{
if (img_stride & 0x0F)
{
JPEG_MSG("JPEGENC: set image stride failed, not align to 0x0f (%x)!!\n", img_stride);
return 0;
}
IMG_REG_WRITE( (img_stride), REG_ADDR_JPEG_ENC_IMG_STRIDE); //REG_JPEG_ENC_IMG_STRIDE = (img_stride);
return 1;
}
void jpeg_drv_enc_set_restart_interval(kal_uint32 restart_interval)
{
unsigned int u4Value ;
u4Value = REG_JPEG_ENC_CTRL ;
if (0 != restart_interval)
{
u4Value |= JPEG_ENC_CTRL_RESTART_EN_BIT ;
IMG_REG_WRITE( (u4Value), REG_ADDR_JPEG_ENC_CTRL); //REG_JPEG_ENC_CTRL |= JPEG_ENC_CTRL_RESTART_EN_BIT;
}
else
{
u4Value &= ~JPEG_ENC_CTRL_RESTART_EN_BIT;
IMG_REG_WRITE( (u4Value), REG_ADDR_JPEG_ENC_CTRL); //REG_JPEG_ENC_CTRL &= ~JPEG_ENC_CTRL_RESTART_EN_BIT;
}
IMG_REG_WRITE( (restart_interval), REG_ADDR_JPEG_ENC_RST_MCU_NUM); //REG_JPEG_ENC_RST_MCU_NUM = restart_interval;
}
kal_uint32 jpeg_drv_enc_set_offset_addr(kal_uint32 offset)
{
if (offset & 0x0F)
{
JPEG_MSG("JPEGENC:WARN set offset addr %x\n", offset);
//return 0;
}
IMG_REG_WRITE( (offset), REG_ADDR_JPEG_ENC_OFFSET_ADDR); //REG_JPEG_ENC_OFFSET_ADDR = offset;
return 1;
}
kal_uint32 jpeg_drv_enc_set_dst_buff(kal_uint32 dst_addr, kal_uint32 stall_size, kal_uint32 init_offset, kal_uint32 offset_mask)
{
if (stall_size < 624)
{
JPEG_MSG("JPEGENC:stall offset less than 624 to write header %d!!\n",stall_size);
return 0;
}
if (offset_mask & 0x0F)
{
JPEG_MSG("JPEGENC: set offset addr %x\n", offset_mask);
//return 0;
}
IMG_REG_WRITE( (init_offset & (~0xF)), REG_ADDR_JPEG_ENC_OFFSET_ADDR); //REG_JPEG_ENC_OFFSET_ADDR = init_offset & (~0xF);
IMG_REG_WRITE( (offset_mask & 0xF), REG_ADDR_JPEG_ENC_BYTE_OFFSET_MASK); //REG_JPEG_ENC_BYTE_OFFSET_MASK = (offset_mask & 0xF);
IMG_REG_WRITE( (dst_addr & (~0xF)), REG_ADDR_JPEG_ENC_DST_ADDR0); //REG_JPEG_ENC_DST_ADDR0 = dst_addr & (~0xF);
IMG_REG_WRITE( ((dst_addr + stall_size) & (~0xF)), REG_ADDR_JPEG_ENC_STALL_ADDR0); //REG_JPEG_ENC_STALL_ADDR0 = (dst_addr + stall_size) & (~0xF);
return 1;
}
// 0:JPG mode, 1:JFIF/EXIF mode
void jpeg_drv_enc_set_EncodeMode(kal_uint32 exif_en)
{
unsigned int u4Value ;
u4Value = REG_JPEG_ENC_CTRL;
u4Value &= ~(JPEG_ENC_CTRL_FILE_FORMAT_BIT);
IMG_REG_WRITE( (u4Value), REG_ADDR_JPEG_ENC_CTRL); //REG_JPEG_ENC_CTRL &= ~(JPEG_ENC_CTRL_FILE_FORMAT_BIT);
if (exif_en)
{
u4Value = REG_JPEG_ENC_CTRL;
u4Value |= JPEG_ENC_EN_JFIF_EXIF;
IMG_REG_WRITE( (u4Value), REG_ADDR_JPEG_ENC_CTRL); //REG_JPEG_ENC_CTRL |= JPEG_ENC_EN_JFIF_EXIF;
}
}
void jpeg_drv_enc_set_gmc_disable_bit(void)
{
unsigned int u4Value ;
u4Value = REG_JPEG_ENC_CTRL ;
u4Value |= JPEG_ENC_EN_DIS_GMC;
IMG_REG_WRITE( (u4Value), REG_ADDR_JPEG_ENC_CTRL);
}
void jpeg_drv_enc_set_burst_type(kal_uint32 burst_type)
{
unsigned int u4Value ;
u4Value = REG_JPEG_ENC_CTRL ;
u4Value &= ~JPEG_ENC_CTRL_BURST_TYPE_MASK;
u4Value |= (burst_type << JPEG_ENC_CTRL_BURST_TYPE_SHIFT_COUNT);
IMG_REG_WRITE( (u4Value), REG_ADDR_JPEG_ENC_CTRL);
}
kal_uint32 jpeg_drv_enc_get_cycle_count()
{
return REG_JPEG_ENC_TOTAL_CYCLE;
}
kal_uint32 jpeg_drv_enc_get_file_size()
{
return REG_JPEG_ENC_DMA_ADDR0 - REG_JPEG_ENC_DST_ADDR0;
//return REG_JPEG_ENC_CURR_DMA_ADDR - REG_JPEG_ENC_DST_ADDR0;
}
#ifdef FPGA_VERSION
kal_uint32 jpeg_drv_enc_get_result()
{
kal_uint32 file_size;
file_size = jpeg_drv_enc_get_file_size();
return file_size;
}
#else
kal_uint32 jpeg_drv_enc_get_result(kal_uint32 *fileSize)
{
*fileSize = jpeg_drv_enc_get_file_size();
if(_jpeg_enc_int_status & JPEG_DRV_ENC_INT_STATUS_DONE)
{
return 0;
}
else if(_jpeg_enc_int_status & JPEG_DRV_ENC_INT_STATUS_STALL)
{
return 1;
}else if( _jpeg_enc_int_status & JPEG_DRV_ENC_INT_STATUS_VCODEC_IRQ){
return 2;
}
JPEG_MSG("JPEGENC: int_st %x!!\n", _jpeg_enc_int_status);
return 3;
}
#endif
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2013 Zuza Software Foundation
#
# This file is part of translate.
#
# translate is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# translate is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
from pytest import mark
from translate.misc import wStringIO
from translate.storage import dtd, test_monolingual
def test_roundtrip_quoting():
specials = [
'Fish & chips',
'five < six',
'six > five',
'Use ',
'Use &nbsp;A "solution"',
"skop 'n bal",
'"""',
"'''",
'\n',
'\t',
'\r',
'Escape at end \\',
'',
'\\n',
'\\t',
'\\r',
'\\"',
'\r\n',
'\\r\\n',
'\\',
"Completed %S",
"&blockAttackSites;",
" ",
"&intro-point2-a;",
"&basePBMenu.label;",
#"Don't buy",
#"Don't \"buy\"",
"A \"thing\"",
"<a href=\"http"
]
for special in specials:
quoted_special = dtd.quotefordtd(special)
unquoted_special = dtd.unquotefromdtd(quoted_special)
print("special: %r\nquoted: %r\nunquoted: %r\n" % (special,
quoted_special,
unquoted_special))
assert special == unquoted_special
@mark.xfail(reason="Not Implemented")
def test_quotefordtd_unimplemented_cases():
"""Test unimplemented quoting DTD cases."""
assert dtd.quotefordtd("Between <p> and </p>") == ('"Between <p> and'
' </p>"')
def test_quotefordtd():
"""Test quoting DTD definitions"""
assert dtd.quotefordtd('') == '""'
assert dtd.quotefordtd("") == '""'
assert dtd.quotefordtd("Completed %S") == '"Completed %S"'
assert dtd.quotefordtd("&blockAttackSites;") == '"&blockAttackSites;"'
assert dtd.quotefordtd(" ") == '" "'
assert dtd.quotefordtd("&intro-point2-a;") == '"&intro-point2-a;"'
assert dtd.quotefordtd("&basePBMenu.label;") == '"&basePBMenu.label;"'
# The ' character isn't escaped as ' since the " char isn't present.
assert dtd.quotefordtd("Don't buy") == '"Don\'t buy"'
# The ' character is escaped as ' because the " character is present.
assert dtd.quotefordtd("Don't \"buy\"") == '"Don't "buy""'
assert dtd.quotefordtd("A \"thing\"") == '"A "thing""'
# The " character is not escaped when it indicates an attribute value.
assert dtd.quotefordtd("<a href=\"http") == "'<a href=\"http'"
# &
assert dtd.quotefordtd("Color & Light") == '"Color & Light"'
assert dtd.quotefordtd("Color & █") == '"Color & █"'
assert dtd.quotefordtd("Color&Light &red;") == '"Color&Light &red;"'
assert dtd.quotefordtd("Color & Light; Yes") == '"Color & Light; Yes"'
@mark.xfail(reason="Not Implemented")
def test_unquotefromdtd_unimplemented_cases():
"""Test unimplemented unquoting DTD cases."""
assert dtd.unquotefromdtd('"<p> and </p>"') == "<p> and </p>"
def test_unquotefromdtd():
"""Test unquoting DTD definitions"""
# %
assert dtd.unquotefromdtd('"Completed %S"') == "Completed %S"
assert dtd.unquotefromdtd('"Completed %S"') == "Completed %S"
assert dtd.unquotefromdtd('"Completed %S"') == "Completed %S"
# &entity;
assert dtd.unquotefromdtd('"Color&light █"') == "Color&light █"
assert dtd.unquotefromdtd('"Color & Light; Red"') == "Color & Light; Red"
assert dtd.unquotefromdtd('"&blockAttackSites;"') == "&blockAttackSites;"
assert dtd.unquotefromdtd('"&intro-point2-a;"') == "&intro-point2-a;"
assert dtd.unquotefromdtd('"&basePBMenu.label"') == "&basePBMenu.label"
# &
assert dtd.unquotefromdtd('"Color & Light"') == "Color & Light"
assert dtd.unquotefromdtd('"Color & █"') == "Color & █"
# nbsp
assert dtd.unquotefromdtd('" "') == " "
# '
assert dtd.unquotefromdtd("'Don't buy'") == "Don't buy"
# "
assert dtd.unquotefromdtd("'Don't "buy"'") == 'Don\'t "buy"'
assert dtd.unquotefromdtd('"A "thing""') == "A \"thing\""
assert dtd.unquotefromdtd('"A "thing""') == "A \"thing\""
assert dtd.unquotefromdtd("'<a href=\"http'") == "<a href=\"http"
# other chars
assert dtd.unquotefromdtd('"»"') == u"»"
def test_android_roundtrip_quoting():
specials = [
"don't",
'the "thing"'
]
for special in specials:
quoted_special = dtd.quoteforandroid(special)
unquoted_special = dtd.unquotefromandroid(quoted_special)
print("special: %r\nquoted: %r\nunquoted: %r\n" % (special,
quoted_special,
unquoted_special))
assert special == unquoted_special
def test_quoteforandroid():
"""Test quoting Android DTD definitions."""
assert dtd.quoteforandroid("don't") == r'"don\u0027t"'
assert dtd.quoteforandroid('the "thing"') == r'"the \"thing\""'
def test_unquotefromandroid():
"""Test unquoting Android DTD definitions."""
assert dtd.unquotefromandroid('"Don\\'t show"') == "Don't show"
assert dtd.unquotefromandroid('"Don\\\'t show"') == "Don't show"
assert dtd.unquotefromandroid('"Don\\u0027t show"') == "Don't show"
assert dtd.unquotefromandroid('"A \\"thing\\""') == "A \"thing\""
def test_removeinvalidamp(recwarn):
"""tests the the removeinvalidamps function"""
def tester(actual, expected=None):
if expected is None:
expected = actual
assert dtd.removeinvalidamps("test.name", actual) == expected
# No errors
tester("Valid &entity; included")
tester("Valid &entity.name; included")
tester("Valid Ӓ included")
tester("Valid &entity_name;")
# Errors that require & removal
tester("This & is broken", "This amp is broken")
tester("Mad & & &", "Mad amp &")
dtd.removeinvalidamps("simple.warningtest", "Dimpled &Ring")
assert recwarn.pop(UserWarning)
class TestDTDUnit(test_monolingual.TestMonolingualUnit):
UnitClass = dtd.dtdunit
def test_rich_get(self):
pass
def test_rich_set(self):
pass
class TestDTD(test_monolingual.TestMonolingualStore):
StoreClass = dtd.dtdfile
def dtdparse(self, dtdsource):
"""helper that parses dtd source without requiring files"""
dummyfile = wStringIO.StringIO(dtdsource)
dtdfile = dtd.dtdfile(dummyfile)
return dtdfile
def dtdregen(self, dtdsource):
"""helper that converts dtd source to dtdfile object and back"""
return str(self.dtdparse(dtdsource))
def test_simpleentity(self):
"""checks that a simple dtd entity definition is parsed correctly"""
dtdsource = '<!ENTITY test.me "bananas for sale">\n'
dtdfile = self.dtdparse(dtdsource)
assert len(dtdfile.units) == 1
dtdunit = dtdfile.units[0]
assert dtdunit.entity == "test.me"
assert dtdunit.definition == '"bananas for sale"'
def test_blanklines(self):
"""checks that blank lines don't break the parsing or regeneration"""
dtdsource = '<!ENTITY test.me "bananas for sale">\n\n'
dtdregen = self.dtdregen(dtdsource)
assert dtdsource == dtdregen
def test_simpleentity_source(self):
"""checks that a simple dtd entity definition can be regenerated as source"""
dtdsource = '<!ENTITY test.me "">\n'
dtdregen = self.dtdregen(dtdsource)
assert dtdsource == dtdregen
dtdsource = '<!ENTITY test.me "bananas for sale">\n'
dtdregen = self.dtdregen(dtdsource)
assert dtdsource == dtdregen
def test_hashcomment_source(self):
"""checks that a #expand comment is retained in the source"""
dtdsource = '#expand <!ENTITY lang.version "__MOZILLA_LOCALE_VERSION__">\n'
dtdregen = self.dtdregen(dtdsource)
assert dtdsource == dtdregen
def test_commentclosing(self):
"""tests that comment closes with trailing space aren't duplicated"""
dtdsource = '<!-- little comment --> \n<!ENTITY pane.title "Notifications">\n'
dtdregen = self.dtdregen(dtdsource)
assert dtdsource == dtdregen
def test_commententity(self):
"""check that we don't process messages in <!-- comments -->: bug 102"""
dtdsource = '''<!-- commenting out until bug 38906 is fixed
<!ENTITY messagesHeader.label "Messages"> -->'''
dtdfile = self.dtdparse(dtdsource)
assert len(dtdfile.units) == 1
dtdunit = dtdfile.units[0]
print(dtdunit)
assert dtdunit.isnull()
def test_newlines_in_entity(self):
"""tests that we can handle newlines in the entity itself"""
dtdsource = '''<!ENTITY fileNotFound.longDesc "
<ul>
<li>Check the file name for capitalisation or other typing errors.</li>
<li>Check to see if the file was moved, renamed or deleted.</li>
</ul>
">
'''
dtdregen = self.dtdregen(dtdsource)
print(dtdregen)
print(dtdsource)
assert dtdsource == dtdregen
def test_conflate_comments(self):
"""Tests that comments don't run onto the same line"""
dtdsource = '<!-- test comments -->\n<!-- getting conflated -->\n<!ENTITY sample.txt "hello">\n'
dtdregen = self.dtdregen(dtdsource)
print(dtdsource)
print(dtdregen)
assert dtdsource == dtdregen
def test_localisation_notes(self):
"""test to ensure that we retain the localisation note correctly"""
dtdsource = '''<!--LOCALIZATION NOTE (publishFtp.label): Edit box appears beside this label -->
<!ENTITY publishFtp.label "If publishing to a FTP site, enter the HTTP address to browse to:">
'''
dtdregen = self.dtdregen(dtdsource)
assert dtdsource == dtdregen
def test_entitityreference_in_source(self):
"""checks that an &entity; in the source is retained"""
dtdsource = '<!ENTITY % realBrandDTD SYSTEM "chrome://branding/locale/brand.dtd">\n%realBrandDTD;\n'
dtdregen = self.dtdregen(dtdsource)
assert dtdsource == dtdregen
#test for bug #610
def test_entitityreference_order_in_source(self):
"""checks that an &entity; in the source is retained"""
dtdsource = '<!ENTITY % realBrandDTD SYSTEM "chrome://branding/locale/brand.dtd">\n%realBrandDTD;\n<!-- some comment -->\n'
dtdregen = self.dtdregen(dtdsource)
assert dtdsource == dtdregen
# The following test is identical to the one above, except that the entity is split over two lines.
# This is to ensure that a recent bug fixed in dtdunit.parse() is at least partly documented.
# The essence of the bug was that after it had read "realBrandDTD", the line index is not reset
# before starting to parse the next line. It would then read the next available word (sequence of
# alphanum characters) in stead of SYSTEM and then get very confused by not finding an opening ' or
# " in the entity, borking the parsing for threst of the file.
dtdsource = '<!ENTITY % realBrandDTD\n SYSTEM "chrome://branding/locale/brand.dtd">\n%realBrandDTD;\n'
# FIXME: The following line is necessary, because of dtdfile's inability to remember the spacing of
# the source DTD file when converting back to DTD.
dtdregen = self.dtdregen(dtdsource).replace('realBrandDTD SYSTEM', 'realBrandDTD\n SYSTEM')
print(dtdsource)
print(dtdregen)
assert dtdsource == dtdregen
@mark.xfail(reason="Not Implemented")
def test_comment_following(self):
"""check that comments that appear after and entity are not pushed onto another line"""
dtdsource = '<!ENTITY textZoomEnlargeCmd.commandkey2 "="> <!-- + is above this key on many keyboards -->'
dtdregen = self.dtdregen(dtdsource)
assert dtdsource == dtdregen
def test_comment_newline_space_closing(self):
"""check that comments that are closed by a newline then space then --> don't break the following entries"""
dtdsource = '<!-- Comment\n -->\n<!ENTITY searchFocus.commandkey "k">\n'
dtdregen = self.dtdregen(dtdsource)
assert dtdsource == dtdregen
@mark.xfail(reason="Not Implemented")
def test_invalid_quoting(self):
"""checks that invalid quoting doesn't work - quotes can't be reopened"""
# TODO: we should rather raise an error
dtdsource = '<!ENTITY test.me "bananas for sale""room">\n'
assert dtd.unquotefromdtd(dtdsource[dtdsource.find('"'):]) == 'bananas for sale'
dtdfile = self.dtdparse(dtdsource)
assert len(dtdfile.units) == 1
dtdunit = dtdfile.units[0]
assert dtdunit.definition == '"bananas for sale"'
assert str(dtdfile) == '<!ENTITY test.me "bananas for sale">\n'
def test_missing_quotes(self, recwarn):
"""test that we fail graacefully when a message without quotes is found (bug #161)"""
dtdsource = '<!ENTITY bad no quotes">\n<!ENTITY good "correct quotes">\n'
dtdfile = self.dtdparse(dtdsource)
assert len(dtdfile.units) == 1
assert recwarn.pop(Warning)
# Test for bug #68
def test_entity_escaping(self):
"""Test entities escaping (& " < > ') (bug #68)"""
dtdsource = ('<!ENTITY securityView.privacy.header "Privacy & '
'History">\n<!ENTITY rights.safebrowsing-term3 "Uncheck '
'the options to "&blockAttackSites.label;" and '
'"&blockWebForgeries.label;"">\n<!ENTITY '
'translate.test1 \'XML encodings don't work\'>\n'
'<!ENTITY translate.test2 "In HTML the text paragraphs '
'are enclosed between <p> and </p> tags.">\n')
dtdfile = self.dtdparse(dtdsource)
assert len(dtdfile.units) == 4
#dtdunit = dtdfile.units[0]
#assert dtdunit.definition == '"Privacy & History"'
#assert dtdunit.target == "Privacy & History"
#assert dtdunit.source == "Privacy & History"
dtdunit = dtdfile.units[1]
assert dtdunit.definition == ('"Uncheck the options to "'
'&blockAttackSites.label;" and '
'"&blockWebForgeries.label;""')
assert dtdunit.target == ("Uncheck the options to \""
"&blockAttackSites.label;\" and \""
"&blockWebForgeries.label;\"")
assert dtdunit.source == ("Uncheck the options to \""
"&blockAttackSites.label;\" and \""
"&blockWebForgeries.label;\"")
dtdunit = dtdfile.units[2]
assert dtdunit.definition == "'XML encodings don't work'"
assert dtdunit.target == "XML encodings don\'t work"
assert dtdunit.source == "XML encodings don\'t work"
#dtdunit = dtdfile.units[3]
#assert dtdunit.definition == ('"In HTML the text paragraphs are '
# 'enclosed between <p> and </p'
# '> tags."')
#assert dtdunit.target == ("In HTML the text paragraphs are enclosed "
# "between <p> and </p> tags.")
#assert dtdunit.source == ("In HTML the text paragraphs are enclosed "
# "between <p> and </p> tags.")
# Test for bug #68
def test_entity_escaping_roundtrip(self):
"""Test entities escaping roundtrip (& " ...) (bug #68)"""
dtdsource = ('<!ENTITY securityView.privacy.header "Privacy & '
'History">\n<!ENTITY rights.safebrowsing-term3 "Uncheck '
'the options to "&blockAttackSites.label;" and '
'"&blockWebForgeries.label;"">\n<!ENTITY '
'translate.test1 \'XML encodings don't work\'>\n'
'<!ENTITY translate.test2 "In HTML the text paragraphs '
'are enclosed between <p> and </p> tags.">\n')
dtdregen = self.dtdregen(dtdsource)
assert dtdsource == dtdregen
class TestAndroidDTD(test_monolingual.TestMonolingualStore):
StoreClass = dtd.dtdfile
def dtdparse(self, dtdsource):
"""Parses an Android DTD source string and returns a DTD store.
This allows to simulate reading from Android DTD files without really
having real Android DTD files.
"""
dummyfile = wStringIO.StringIO(dtdsource)
dtdfile = dtd.dtdfile(dummyfile, android=True)
return dtdfile
def dtdregen(self, dtdsource):
"""Parses an Android DTD string to DTD store and then converts it back.
This allows to simulate reading from an Android DTD file to an
in-memory store and writing back to an Android DTD file without really
having a real file.
"""
return str(self.dtdparse(dtdsource))
# Test for bug #2480
def test_android_single_quote_escape(self):
"""Checks several single quote unescaping cases in Android DTD.
See bug #2480.
"""
dtdsource = ('<!ENTITY pref_char_encoding_off "Don\\\'t show menu">\n'
'<!ENTITY sync.nodevice.label \'Don\\'t show\'>\n'
'<!ENTITY sync.nodevice.label "Don\\u0027t show">\n')
dtdfile = self.dtdparse(dtdsource)
assert len(dtdfile.units) == 3
dtdunit = dtdfile.units[0]
assert dtdunit.definition == '"Don\\\'t show menu"'
assert dtdunit.target == "Don't show menu"
assert dtdunit.source == "Don't show menu"
dtdunit = dtdfile.units[1]
assert dtdunit.definition == "'Don\\'t show'"
assert dtdunit.target == "Don't show"
assert dtdunit.source == "Don't show"
dtdunit = dtdfile.units[2]
assert dtdunit.definition == '"Don\\u0027t show"'
assert dtdunit.target == "Don't show"
assert dtdunit.source == "Don't show"
# Test for bug #2480
def test_android_single_quote_escape_parse_and_convert_back(self):
"""Checks that Android DTD don't change after parse and convert back.
An Android DTD source string with several single quote escapes is used
instead of real files.
See bug #2480.
"""
dtdsource = ('<!ENTITY pref_char_encoding_off "Don\\\'t show menu">\n'
'<!ENTITY sync.nodevice.label \'Don\\'t show\'>\n'
'<!ENTITY sync.nodevice.label "Don\\u0027t show">\n')
dtdregen = self.dtdregen(dtdsource)
assert dtdsource == dtdregen
def test_android_double_quote_escape(self):
"""Checks double quote unescaping in Android DTD."""
dtdsource = '<!ENTITY translate.test "A \\"thing\\"">\n'
dtdfile = self.dtdparse(dtdsource)
assert len(dtdfile.units) == 1
dtdunit = dtdfile.units[0]
assert dtdunit.definition == '"A \\"thing\\""'
assert dtdunit.target == "A \"thing\""
assert dtdunit.source == "A \"thing\""
def test_android_double_quote_escape_parse_and_convert_back(self):
"""Checks that Android DTD don't change after parse and convert back.
An Android DTD source string with double quote escapes is used instead
of real files.
"""
dtdsource = '<!ENTITY translate.test "A \\"thing\\"">\n'
dtdregen = self.dtdregen(dtdsource)
assert dtdsource == dtdregen
|
class AddLastVoteAtToMotions < ActiveRecord::Migration
def up
add_column :motions, :last_vote_at, :datetime
remove_column :motions, :activity
end
def down
remove_column :motions, :last_vote_at
add_column :motions, :activity, :integer, :default => 0
end
end
|
require 'rails_helper'
describe 'Cache flow' do
describe 'Tag destroy' do
it 'invalidates Debate cache keys' do
debate = create(:debate, tag_list: "Good, Bad")
tag = ActsAsTaggableOn::Tag.find_by(name: "Bad")
expect{tag.destroy}.to change {debate.reload.cache_key}
end
end
end
|
# LiquidCrystal_I2C
LiquidCrystal Arduino library for the DFRobot I2C LCD displays
|
package DDG::Goodie::VIN;
# ABSTRACT: extract information about vehicle identification numbers
use strict;
use DDG::Goodie;
zci is_cached => 1;
zci answer_type => "vin";
triggers query_lc => qr/([\d+a-z]{17})|
(^\d+$)
/x;
# Regex for VIN.
my $vin_qr = qr/v(?:ehicle|)i(?:dentification|)n(?:umber|)/oi;
my $tracking_qr = qr/package|track(?:ing|)|num(?:ber|)|\#/i;
# Checksum for VIN.
my %vin_checksum = (
'A' => 1,
'B' => 2,
'C' => 3,
'D' => 4,
'E' => 5,
'F' => 6,
'G' => 7,
'H' => 8,
'I' => 'X',
'J' => 1,
'K' => 2,
'L' => 3,
'M' => 4,
'N' => 5,
'O' => 'X',
'P' => 7,
'Q' => 'X',
'R' => 9,
'S' => 2,
'T' => 3,
'U' => 4,
'V' => 5,
'W' => 6,
'X' => 7,
'Y' => 8,
'Z' => 9,
);
my %vin_checksum_weight = (
'1' => 8,
'2' => 7,
'3' => 6,
'4' => 5,
'5' => 4,
'6' => 3,
'7' => 2,
'8' => 10,
'9' => 0,
'10' => 9,
'11' => 8,
'12' => 7,
'13' => 6,
'14' => 5,
'15' => 4,
'16' => 3,
'17' => 2,
);
# VIN numbers.
# 2008.07.29 force some letters because
# "Alvin and the Chipmunks songs" passes checksum.
# See http://en.wikipedia.org/wiki/Vehicle_identification_number#Check_digit_calculation
# 2012.03.22 remove ^ and $ from 2nd regex term to also allow
# 'vin <vin>, etc' -- a regular vin just triggers w.js?
handle query_nowhitespace_nodash => sub {
my ($query) = @_;
# If a VIN number (2 for exclusively).
my $is_vin = 0;
# VIN number.
my $vin_number = '';
# Exclsuive trigger.
if ($query =~ /^$vin_qr.*?([A-Z\d]{17,})$/i || $query =~ /^([A-Z\d]{17,}).*?$vin_qr$/i) {
$vin_number = uc $1;
$is_vin = 2;
# No exclusive trigger, do checksum.
# Since the vin numbers are just numbers,
# we are more strict in regex (e.g. than UPS).
} elsif($query =~ /^(?:$tracking_qr|$vin_qr|)*([A-Z\d]{17})(?:$tracking_qr|$vin_qr|)*$/io || $query =~ /^(?:$tracking_qr|$vin_qr|)*([A-Z\d]{17})(?:$tracking_qr|$vin_qr|)*$/io) {
$vin_number = uc $1;
my $checksum = 0;
my @chars = split( //, $vin_number );
my $length = scalar(@chars);
my $char_count = 0;
my $sum = 0;
my $letter_count = 0;
foreach my $char (@chars) {
$char_count++;
$letter_count++ if $char =~ /[A-Z]/;
# Grab number.
my $char_num = $char;
$char_num = $vin_checksum{$char} if exists $vin_checksum{$char};
# Make sure number.
if ( $char_num eq 'X' ) {
$checksum = -1;
last;
}
# Use weight.
$sum += $char_num * $vin_checksum_weight{$char_count};
}
$checksum = $sum % 11;
$checksum = 'X' if $checksum == 10;
if ($checksum eq $chars[8] && $letter_count > 3) {
$is_vin = 1;
}
}
return unless $is_vin;
my $moreUrl = 'http://www.decodethis.com/VIN-Decoded/vin/' . $vin_number;
return "Decode VIN ($vin_number) at Decode This: $moreUrl",
structured_answer => {
data => {
title => "Vehicle Identification Number: $vin_number",
href => $moreUrl
},
templates => {
group => 'text',
options => {
subtitle_content => 'DDH.vin.subtitle'
}
}
};
return;
};
1;
|
// +build linux
package libcontainer
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"reflect"
"strings"
"sync"
"syscall"
"github.com/Sirupsen/logrus"
"github.com/golang/protobuf/proto"
"github.com/opencontainers/runc/libcontainer/cgroups"
"github.com/opencontainers/runc/libcontainer/configs"
"github.com/opencontainers/runc/libcontainer/criurpc"
"github.com/opencontainers/runc/libcontainer/utils"
"github.com/vishvananda/netlink/nl"
)
const stdioFdCount = 3
type linuxContainer struct {
id string
root string
config *configs.Config
cgroupManager cgroups.Manager
initPath string
initArgs []string
initProcess parentProcess
criuPath string
m sync.Mutex
criuVersion int
}
// State represents a running container's state
type State struct {
BaseState
// Platform specific fields below here
// Path to all the cgroups setup for a container. Key is cgroup subsystem name
// with the value as the path.
CgroupPaths map[string]string `json:"cgroup_paths"`
// NamespacePaths are filepaths to the container's namespaces. Key is the namespace type
// with the value as the path.
NamespacePaths map[configs.NamespaceType]string `json:"namespace_paths"`
// Container's standard descriptors (std{in,out,err}), needed for checkpoint and restore
ExternalDescriptors []string `json:"external_descriptors,omitempty"`
}
// A libcontainer container object.
//
// Each container is thread-safe within the same process. Since a container can
// be destroyed by a separate process, any function may return that the container
// was not found.
type Container interface {
BaseContainer
// Methods below here are platform specific
// Checkpoint checkpoints the running container's state to disk using the criu(8) utility.
//
// errors:
// Systemerror - System error.
Checkpoint(criuOpts *CriuOpts) error
// Restore restores the checkpointed container to a running state using the criu(8) utiity.
//
// errors:
// Systemerror - System error.
Restore(process *Process, criuOpts *CriuOpts) error
// If the Container state is RUNNING or PAUSING, sets the Container state to PAUSING and pauses
// the execution of any user processes. Asynchronously, when the container finished being paused the
// state is changed to PAUSED.
// If the Container state is PAUSED, do nothing.
//
// errors:
// ContainerDestroyed - Container no longer exists,
// Systemerror - System error.
Pause() error
// If the Container state is PAUSED, resumes the execution of any user processes in the
// Container before setting the Container state to RUNNING.
// If the Container state is RUNNING, do nothing.
//
// errors:
// ContainerDestroyed - Container no longer exists,
// Systemerror - System error.
Resume() error
// NotifyOOM returns a read-only channel signaling when the container receives an OOM notification.
//
// errors:
// Systemerror - System error.
NotifyOOM() (<-chan struct{}, error)
}
// ID returns the container's unique ID
func (c *linuxContainer) ID() string {
return c.id
}
// Config returns the container's configuration
func (c *linuxContainer) Config() configs.Config {
return *c.config
}
func (c *linuxContainer) Status() (Status, error) {
c.m.Lock()
defer c.m.Unlock()
return c.currentStatus()
}
func (c *linuxContainer) State() (*State, error) {
c.m.Lock()
defer c.m.Unlock()
return c.currentState()
}
func (c *linuxContainer) Processes() ([]int, error) {
pids, err := c.cgroupManager.GetPids()
if err != nil {
return nil, newSystemError(err)
}
return pids, nil
}
func (c *linuxContainer) Stats() (*Stats, error) {
var (
err error
stats = &Stats{}
)
if stats.CgroupStats, err = c.cgroupManager.GetStats(); err != nil {
return stats, newSystemError(err)
}
for _, iface := range c.config.Networks {
switch iface.Type {
case "veth":
istats, err := getNetworkInterfaceStats(iface.HostInterfaceName)
if err != nil {
return stats, newSystemError(err)
}
stats.Interfaces = append(stats.Interfaces, istats)
}
}
return stats, nil
}
func (c *linuxContainer) Set(config configs.Config) error {
c.m.Lock()
defer c.m.Unlock()
c.config = &config
return c.cgroupManager.Set(c.config)
}
func (c *linuxContainer) Start(process *Process) error {
c.m.Lock()
defer c.m.Unlock()
status, err := c.currentStatus()
if err != nil {
return err
}
doInit := status == Destroyed
parent, err := c.newParentProcess(process, doInit)
if err != nil {
return newSystemError(err)
}
if err := parent.start(); err != nil {
// terminate the process to ensure that it properly is reaped.
if err := parent.terminate(); err != nil {
logrus.Warn(err)
}
return newSystemError(err)
}
if doInit {
c.updateState(parent)
}
if c.config.Hooks != nil {
s := configs.HookState{
Version: c.config.Version,
ID: c.id,
Pid: parent.pid(),
Root: c.config.Rootfs,
}
for _, hook := range c.config.Hooks.Poststart {
if err := hook.Run(s); err != nil {
if err := parent.terminate(); err != nil {
logrus.Warn(err)
}
return newSystemError(err)
}
}
}
return nil
}
func (c *linuxContainer) Signal(s os.Signal) error {
if err := c.initProcess.signal(s); err != nil {
return newSystemError(err)
}
return nil
}
func (c *linuxContainer) newParentProcess(p *Process, doInit bool) (parentProcess, error) {
parentPipe, childPipe, err := newPipe()
if err != nil {
return nil, newSystemError(err)
}
cmd, err := c.commandTemplate(p, childPipe)
if err != nil {
return nil, newSystemError(err)
}
if !doInit {
return c.newSetnsProcess(p, cmd, parentPipe, childPipe)
}
return c.newInitProcess(p, cmd, parentPipe, childPipe)
}
func (c *linuxContainer) commandTemplate(p *Process, childPipe *os.File) (*exec.Cmd, error) {
cmd := &exec.Cmd{
Path: c.initPath,
Args: c.initArgs,
}
cmd.Stdin = p.Stdin
cmd.Stdout = p.Stdout
cmd.Stderr = p.Stderr
cmd.Dir = c.config.Rootfs
if cmd.SysProcAttr == nil {
cmd.SysProcAttr = &syscall.SysProcAttr{}
}
cmd.ExtraFiles = append(p.ExtraFiles, childPipe)
cmd.Env = append(cmd.Env, fmt.Sprintf("_LIBCONTAINER_INITPIPE=%d", stdioFdCount+len(cmd.ExtraFiles)-1))
// NOTE: when running a container with no PID namespace and the parent process spawning the container is
// PID1 the pdeathsig is being delivered to the container's init process by the kernel for some reason
// even with the parent still running.
if c.config.ParentDeathSignal > 0 {
cmd.SysProcAttr.Pdeathsig = syscall.Signal(c.config.ParentDeathSignal)
}
return cmd, nil
}
func (c *linuxContainer) newInitProcess(p *Process, cmd *exec.Cmd, parentPipe, childPipe *os.File) (*initProcess, error) {
t := "_LIBCONTAINER_INITTYPE=standard"
cloneFlags := c.config.Namespaces.CloneFlags()
if cloneFlags&syscall.CLONE_NEWUSER != 0 {
if err := c.addUidGidMappings(cmd.SysProcAttr); err != nil {
// user mappings are not supported
return nil, err
}
enableSetgroups(cmd.SysProcAttr)
// Default to root user when user namespaces are enabled.
if cmd.SysProcAttr.Credential == nil {
cmd.SysProcAttr.Credential = &syscall.Credential{}
}
}
cmd.Env = append(cmd.Env, t)
cmd.SysProcAttr.Cloneflags = cloneFlags
return &initProcess{
cmd: cmd,
childPipe: childPipe,
parentPipe: parentPipe,
manager: c.cgroupManager,
config: c.newInitConfig(p),
container: c,
process: p,
}, nil
}
func (c *linuxContainer) newSetnsProcess(p *Process, cmd *exec.Cmd, parentPipe, childPipe *os.File) (*setnsProcess, error) {
cmd.Env = append(cmd.Env, "_LIBCONTAINER_INITTYPE=setns")
// for setns process, we dont have to set cloneflags as the process namespaces
// will only be set via setns syscall
data, err := c.bootstrapData(0, c.initProcess.pid(), p.consolePath)
if err != nil {
return nil, err
}
// TODO: set on container for process management
return &setnsProcess{
cmd: cmd,
cgroupPaths: c.cgroupManager.GetPaths(),
childPipe: childPipe,
parentPipe: parentPipe,
config: c.newInitConfig(p),
process: p,
bootstrapData: data,
}, nil
}
func (c *linuxContainer) newInitConfig(process *Process) *initConfig {
return &initConfig{
Config: c.config,
Args: process.Args,
Env: process.Env,
User: process.User,
Cwd: process.Cwd,
Console: process.consolePath,
Capabilities: process.Capabilities,
PassedFilesCount: len(process.ExtraFiles),
}
}
func newPipe() (parent *os.File, child *os.File, err error) {
fds, err := syscall.Socketpair(syscall.AF_LOCAL, syscall.SOCK_STREAM|syscall.SOCK_CLOEXEC, 0)
if err != nil {
return nil, nil, err
}
return os.NewFile(uintptr(fds[1]), "parent"), os.NewFile(uintptr(fds[0]), "child"), nil
}
func (c *linuxContainer) Destroy() error {
c.m.Lock()
defer c.m.Unlock()
status, err := c.currentStatus()
if err != nil {
return err
}
if status != Destroyed {
return newGenericError(fmt.Errorf("container is not destroyed"), ContainerNotStopped)
}
if !c.config.Namespaces.Contains(configs.NEWPID) {
if err := killCgroupProcesses(c.cgroupManager); err != nil {
logrus.Warn(err)
}
}
err = c.cgroupManager.Destroy()
if rerr := os.RemoveAll(c.root); err == nil {
err = rerr
}
c.initProcess = nil
if c.config.Hooks != nil {
s := configs.HookState{
Version: c.config.Version,
ID: c.id,
Root: c.config.Rootfs,
}
for _, hook := range c.config.Hooks.Poststop {
if err := hook.Run(s); err != nil {
return err
}
}
}
return err
}
func (c *linuxContainer) Pause() error {
c.m.Lock()
defer c.m.Unlock()
return c.cgroupManager.Freeze(configs.Frozen)
}
func (c *linuxContainer) Resume() error {
c.m.Lock()
defer c.m.Unlock()
return c.cgroupManager.Freeze(configs.Thawed)
}
func (c *linuxContainer) NotifyOOM() (<-chan struct{}, error) {
return notifyOnOOM(c.cgroupManager.GetPaths())
}
// XXX debug support, remove when debugging done.
func addArgsFromEnv(evar string, args *[]string) {
if e := os.Getenv(evar); e != "" {
for _, f := range strings.Fields(e) {
*args = append(*args, f)
}
}
fmt.Printf(">>> criu %v\n", *args)
}
// check Criu version greater than or equal to min_version
func (c *linuxContainer) checkCriuVersion(min_version string) error {
var x, y, z, versionReq int
_, err := fmt.Sscanf(min_version, "%d.%d.%d\n", &x, &y, &z) // 1.5.2
if err != nil {
_, err = fmt.Sscanf(min_version, "Version: %d.%d\n", &x, &y) // 1.6
}
versionReq = x*10000 + y*100 + z
out, err := exec.Command(c.criuPath, "-V").Output()
if err != nil {
return fmt.Errorf("Unable to execute CRIU command: %s", c.criuPath)
}
x = 0
y = 0
z = 0
if ep := strings.Index(string(out), "-"); ep >= 0 {
// criu Git version format
var version string
if sp := strings.Index(string(out), "GitID"); sp > 0 {
version = string(out)[sp:ep]
} else {
return fmt.Errorf("Unable to parse the CRIU version: %s", c.criuPath)
}
n, err := fmt.Sscanf(string(version), "GitID: v%d.%d.%d", &x, &y, &z) // 1.5.2
if err != nil {
n, err = fmt.Sscanf(string(version), "GitID: v%d.%d", &x, &y) // 1.6
y++
} else {
z++
}
if n < 2 || err != nil {
return fmt.Errorf("Unable to parse the CRIU version: %s %d %s", version, n, err)
}
} else {
// criu release version format
n, err := fmt.Sscanf(string(out), "Version: %d.%d.%d\n", &x, &y, &z) // 1.5.2
if err != nil {
n, err = fmt.Sscanf(string(out), "Version: %d.%d\n", &x, &y) // 1.6
}
if n < 2 || err != nil {
return fmt.Errorf("Unable to parse the CRIU version: %s %d %s", out, n, err)
}
}
c.criuVersion = x*10000 + y*100 + z
if c.criuVersion < versionReq {
return fmt.Errorf("CRIU version must be %s or higher", min_version)
}
return nil
}
const descriptorsFilename = "descriptors.json"
func (c *linuxContainer) addCriuDumpMount(req *criurpc.CriuReq, m *configs.Mount) {
mountDest := m.Destination
if strings.HasPrefix(mountDest, c.config.Rootfs) {
mountDest = mountDest[len(c.config.Rootfs):]
}
extMnt := &criurpc.ExtMountMap{
Key: proto.String(mountDest),
Val: proto.String(mountDest),
}
req.Opts.ExtMnt = append(req.Opts.ExtMnt, extMnt)
}
func (c *linuxContainer) Checkpoint(criuOpts *CriuOpts) error {
c.m.Lock()
defer c.m.Unlock()
if err := c.checkCriuVersion("1.5.2"); err != nil {
return err
}
if criuOpts.ImagesDirectory == "" {
criuOpts.ImagesDirectory = filepath.Join(c.root, "criu.image")
}
// Since a container can be C/R'ed multiple times,
// the checkpoint directory may already exist.
if err := os.Mkdir(criuOpts.ImagesDirectory, 0755); err != nil && !os.IsExist(err) {
return err
}
if criuOpts.WorkDirectory == "" {
criuOpts.WorkDirectory = filepath.Join(c.root, "criu.work")
}
if err := os.Mkdir(criuOpts.WorkDirectory, 0755); err != nil && !os.IsExist(err) {
return err
}
workDir, err := os.Open(criuOpts.WorkDirectory)
if err != nil {
return err
}
defer workDir.Close()
imageDir, err := os.Open(criuOpts.ImagesDirectory)
if err != nil {
return err
}
defer imageDir.Close()
rpcOpts := criurpc.CriuOpts{
ImagesDirFd: proto.Int32(int32(imageDir.Fd())),
WorkDirFd: proto.Int32(int32(workDir.Fd())),
LogLevel: proto.Int32(4),
LogFile: proto.String("dump.log"),
Root: proto.String(c.config.Rootfs),
ManageCgroups: proto.Bool(true),
NotifyScripts: proto.Bool(true),
Pid: proto.Int32(int32(c.initProcess.pid())),
ShellJob: proto.Bool(criuOpts.ShellJob),
LeaveRunning: proto.Bool(criuOpts.LeaveRunning),
TcpEstablished: proto.Bool(criuOpts.TcpEstablished),
ExtUnixSk: proto.Bool(criuOpts.ExternalUnixConnections),
FileLocks: proto.Bool(criuOpts.FileLocks),
}
// append optional criu opts, e.g., page-server and port
if criuOpts.PageServer.Address != "" && criuOpts.PageServer.Port != 0 {
rpcOpts.Ps = &criurpc.CriuPageServerInfo{
Address: proto.String(criuOpts.PageServer.Address),
Port: proto.Int32(criuOpts.PageServer.Port),
}
}
// append optional manage cgroups mode
if criuOpts.ManageCgroupsMode != 0 {
if err := c.checkCriuVersion("1.7"); err != nil {
return err
}
rpcOpts.ManageCgroupsMode = proto.Uint32(uint32(criuOpts.ManageCgroupsMode))
}
t := criurpc.CriuReqType_DUMP
req := &criurpc.CriuReq{
Type: &t,
Opts: &rpcOpts,
}
for _, m := range c.config.Mounts {
switch m.Device {
case "bind":
c.addCriuDumpMount(req, m)
break
case "cgroup":
binds, err := getCgroupMounts(m)
if err != nil {
return err
}
for _, b := range binds {
c.addCriuDumpMount(req, b)
}
break
}
}
// Write the FD info to a file in the image directory
fdsJSON, err := json.Marshal(c.initProcess.externalDescriptors())
if err != nil {
return err
}
err = ioutil.WriteFile(filepath.Join(criuOpts.ImagesDirectory, descriptorsFilename), fdsJSON, 0655)
if err != nil {
return err
}
err = c.criuSwrk(nil, req, criuOpts, false)
if err != nil {
return err
}
return nil
}
func (c *linuxContainer) addCriuRestoreMount(req *criurpc.CriuReq, m *configs.Mount) {
mountDest := m.Destination
if strings.HasPrefix(mountDest, c.config.Rootfs) {
mountDest = mountDest[len(c.config.Rootfs):]
}
extMnt := &criurpc.ExtMountMap{
Key: proto.String(mountDest),
Val: proto.String(m.Source),
}
req.Opts.ExtMnt = append(req.Opts.ExtMnt, extMnt)
}
func (c *linuxContainer) Restore(process *Process, criuOpts *CriuOpts) error {
c.m.Lock()
defer c.m.Unlock()
if err := c.checkCriuVersion("1.5.2"); err != nil {
return err
}
if criuOpts.WorkDirectory == "" {
criuOpts.WorkDirectory = filepath.Join(c.root, "criu.work")
}
// Since a container can be C/R'ed multiple times,
// the work directory may already exist.
if err := os.Mkdir(criuOpts.WorkDirectory, 0655); err != nil && !os.IsExist(err) {
return err
}
workDir, err := os.Open(criuOpts.WorkDirectory)
if err != nil {
return err
}
defer workDir.Close()
if criuOpts.ImagesDirectory == "" {
criuOpts.ImagesDirectory = filepath.Join(c.root, "criu.image")
}
imageDir, err := os.Open(criuOpts.ImagesDirectory)
if err != nil {
return err
}
defer imageDir.Close()
// CRIU has a few requirements for a root directory:
// * it must be a mount point
// * its parent must not be overmounted
// c.config.Rootfs is bind-mounted to a temporary directory
// to satisfy these requirements.
root := filepath.Join(c.root, "criu-root")
if err := os.Mkdir(root, 0755); err != nil {
return err
}
defer os.Remove(root)
root, err = filepath.EvalSymlinks(root)
if err != nil {
return err
}
err = syscall.Mount(c.config.Rootfs, root, "", syscall.MS_BIND|syscall.MS_REC, "")
if err != nil {
return err
}
defer syscall.Unmount(root, syscall.MNT_DETACH)
t := criurpc.CriuReqType_RESTORE
req := &criurpc.CriuReq{
Type: &t,
Opts: &criurpc.CriuOpts{
ImagesDirFd: proto.Int32(int32(imageDir.Fd())),
WorkDirFd: proto.Int32(int32(workDir.Fd())),
EvasiveDevices: proto.Bool(true),
LogLevel: proto.Int32(4),
LogFile: proto.String("restore.log"),
RstSibling: proto.Bool(true),
Root: proto.String(root),
ManageCgroups: proto.Bool(true),
NotifyScripts: proto.Bool(true),
ShellJob: proto.Bool(criuOpts.ShellJob),
ExtUnixSk: proto.Bool(criuOpts.ExternalUnixConnections),
TcpEstablished: proto.Bool(criuOpts.TcpEstablished),
FileLocks: proto.Bool(criuOpts.FileLocks),
},
}
for _, m := range c.config.Mounts {
switch m.Device {
case "bind":
c.addCriuRestoreMount(req, m)
break
case "cgroup":
binds, err := getCgroupMounts(m)
if err != nil {
return err
}
for _, b := range binds {
c.addCriuRestoreMount(req, b)
}
break
}
}
for _, iface := range c.config.Networks {
switch iface.Type {
case "veth":
veth := new(criurpc.CriuVethPair)
veth.IfOut = proto.String(iface.HostInterfaceName)
veth.IfIn = proto.String(iface.Name)
req.Opts.Veths = append(req.Opts.Veths, veth)
break
case "loopback":
break
}
}
for _, i := range criuOpts.VethPairs {
veth := new(criurpc.CriuVethPair)
veth.IfOut = proto.String(i.HostInterfaceName)
veth.IfIn = proto.String(i.ContainerInterfaceName)
req.Opts.Veths = append(req.Opts.Veths, veth)
}
// append optional manage cgroups mode
if criuOpts.ManageCgroupsMode != 0 {
if err := c.checkCriuVersion("1.7"); err != nil {
return err
}
req.Opts.ManageCgroupsMode = proto.Uint32(uint32(criuOpts.ManageCgroupsMode))
}
var (
fds []string
fdJSON []byte
)
if fdJSON, err = ioutil.ReadFile(filepath.Join(criuOpts.ImagesDirectory, descriptorsFilename)); err != nil {
return err
}
if err = json.Unmarshal(fdJSON, &fds); err != nil {
return err
}
for i := range fds {
if s := fds[i]; strings.Contains(s, "pipe:") {
inheritFd := new(criurpc.InheritFd)
inheritFd.Key = proto.String(s)
inheritFd.Fd = proto.Int32(int32(i))
req.Opts.InheritFd = append(req.Opts.InheritFd, inheritFd)
}
}
err = c.criuSwrk(process, req, criuOpts, true)
if err != nil {
return err
}
return nil
}
func (c *linuxContainer) criuApplyCgroups(pid int, req *criurpc.CriuReq) error {
if err := c.cgroupManager.Apply(pid); err != nil {
return err
}
path := fmt.Sprintf("/proc/%d/cgroup", pid)
cgroupsPaths, err := cgroups.ParseCgroupFile(path)
if err != nil {
return err
}
for c, p := range cgroupsPaths {
cgroupRoot := &criurpc.CgroupRoot{
Ctrl: proto.String(c),
Path: proto.String(p),
}
req.Opts.CgRoot = append(req.Opts.CgRoot, cgroupRoot)
}
return nil
}
func (c *linuxContainer) criuSwrk(process *Process, req *criurpc.CriuReq, opts *CriuOpts, applyCgroups bool) error {
fds, err := syscall.Socketpair(syscall.AF_LOCAL, syscall.SOCK_SEQPACKET|syscall.SOCK_CLOEXEC, 0)
if err != nil {
return err
}
logPath := filepath.Join(opts.WorkDirectory, req.GetOpts().GetLogFile())
criuClient := os.NewFile(uintptr(fds[0]), "criu-transport-client")
criuServer := os.NewFile(uintptr(fds[1]), "criu-transport-server")
defer criuClient.Close()
defer criuServer.Close()
args := []string{"swrk", "3"}
logrus.Debugf("Using CRIU %d at: %s", c.criuVersion, c.criuPath)
logrus.Debugf("Using CRIU with following args: %s", args)
cmd := exec.Command(c.criuPath, args...)
if process != nil {
cmd.Stdin = process.Stdin
cmd.Stdout = process.Stdout
cmd.Stderr = process.Stderr
}
cmd.ExtraFiles = append(cmd.ExtraFiles, criuServer)
if err := cmd.Start(); err != nil {
return err
}
criuServer.Close()
defer func() {
criuClient.Close()
_, err := cmd.Process.Wait()
if err != nil {
return
}
}()
if applyCgroups {
err := c.criuApplyCgroups(cmd.Process.Pid, req)
if err != nil {
return err
}
}
var extFds []string
if process != nil {
extFds, err = getPipeFds(cmd.Process.Pid)
if err != nil {
return err
}
}
logrus.Debugf("Using CRIU in %s mode", req.GetType().String())
val := reflect.ValueOf(req.GetOpts())
v := reflect.Indirect(val)
for i := 0; i < v.NumField(); i++ {
st := v.Type()
name := st.Field(i).Name
if strings.HasPrefix(name, "XXX_") {
continue
}
value := val.MethodByName("Get" + name).Call([]reflect.Value{})
logrus.Debugf("CRIU option %s with value %v", name, value[0])
}
data, err := proto.Marshal(req)
if err != nil {
return err
}
_, err = criuClient.Write(data)
if err != nil {
return err
}
buf := make([]byte, 10*4096)
for true {
n, err := criuClient.Read(buf)
if err != nil {
return err
}
if n == 0 {
return fmt.Errorf("unexpected EOF")
}
if n == len(buf) {
return fmt.Errorf("buffer is too small")
}
resp := new(criurpc.CriuResp)
err = proto.Unmarshal(buf[:n], resp)
if err != nil {
return err
}
if !resp.GetSuccess() {
typeString := req.GetType().String()
return fmt.Errorf("criu failed: type %s errno %d\nlog file: %s", typeString, resp.GetCrErrno(), logPath)
}
t := resp.GetType()
switch {
case t == criurpc.CriuReqType_NOTIFY:
if err := c.criuNotifications(resp, process, opts, extFds); err != nil {
return err
}
t = criurpc.CriuReqType_NOTIFY
req = &criurpc.CriuReq{
Type: &t,
NotifySuccess: proto.Bool(true),
}
data, err = proto.Marshal(req)
if err != nil {
return err
}
n, err = criuClient.Write(data)
if err != nil {
return err
}
continue
case t == criurpc.CriuReqType_RESTORE:
case t == criurpc.CriuReqType_DUMP:
break
default:
return fmt.Errorf("unable to parse the response %s", resp.String())
}
break
}
// cmd.Wait() waits cmd.goroutines which are used for proxying file descriptors.
// Here we want to wait only the CRIU process.
st, err := cmd.Process.Wait()
if err != nil {
return err
}
if !st.Success() {
return fmt.Errorf("criu failed: %s\nlog file: %s", st.String(), logPath)
}
return nil
}
// block any external network activity
func lockNetwork(config *configs.Config) error {
for _, config := range config.Networks {
strategy, err := getStrategy(config.Type)
if err != nil {
return err
}
if err := strategy.detach(config); err != nil {
return err
}
}
return nil
}
func unlockNetwork(config *configs.Config) error {
for _, config := range config.Networks {
strategy, err := getStrategy(config.Type)
if err != nil {
return err
}
if err = strategy.attach(config); err != nil {
return err
}
}
return nil
}
func (c *linuxContainer) criuNotifications(resp *criurpc.CriuResp, process *Process, opts *CriuOpts, fds []string) error {
notify := resp.GetNotify()
if notify == nil {
return fmt.Errorf("invalid response: %s", resp.String())
}
switch {
case notify.GetScript() == "post-dump":
if !opts.LeaveRunning {
f, err := os.Create(filepath.Join(c.root, "checkpoint"))
if err != nil {
return err
}
f.Close()
}
break
case notify.GetScript() == "network-unlock":
if err := unlockNetwork(c.config); err != nil {
return err
}
break
case notify.GetScript() == "network-lock":
if err := lockNetwork(c.config); err != nil {
return err
}
break
case notify.GetScript() == "post-restore":
pid := notify.GetPid()
r, err := newRestoredProcess(int(pid), fds)
if err != nil {
return err
}
// TODO: crosbymichael restore previous process information by saving the init process information in
// the container's state file or separate process state files.
if err := c.updateState(r); err != nil {
return err
}
process.ops = r
break
}
return nil
}
func (c *linuxContainer) updateState(process parentProcess) error {
c.initProcess = process
state, err := c.currentState()
if err != nil {
return err
}
f, err := os.Create(filepath.Join(c.root, stateFilename))
if err != nil {
return err
}
defer f.Close()
os.Remove(filepath.Join(c.root, "checkpoint"))
return utils.WriteJSON(f, state)
}
func (c *linuxContainer) currentStatus() (Status, error) {
if _, err := os.Stat(filepath.Join(c.root, "checkpoint")); err == nil {
return Checkpointed, nil
}
if c.initProcess == nil {
return Destroyed, nil
}
// return Running if the init process is alive
if err := syscall.Kill(c.initProcess.pid(), 0); err != nil {
if err == syscall.ESRCH {
return Destroyed, nil
}
return 0, newSystemError(err)
}
if c.config.Cgroups != nil && c.config.Cgroups.Resources != nil && c.config.Cgroups.Resources.Freezer == configs.Frozen {
return Paused, nil
}
return Running, nil
}
func (c *linuxContainer) currentState() (*State, error) {
status, err := c.currentStatus()
if err != nil {
return nil, err
}
if status == Destroyed {
return nil, newGenericError(fmt.Errorf("container destroyed"), ContainerNotExists)
}
startTime, err := c.initProcess.startTime()
if err != nil {
return nil, newSystemError(err)
}
state := &State{
BaseState: BaseState{
ID: c.ID(),
Config: *c.config,
InitProcessPid: c.initProcess.pid(),
InitProcessStartTime: startTime,
},
CgroupPaths: c.cgroupManager.GetPaths(),
NamespacePaths: make(map[configs.NamespaceType]string),
ExternalDescriptors: c.initProcess.externalDescriptors(),
}
for _, ns := range c.config.Namespaces {
state.NamespacePaths[ns.Type] = ns.GetPath(c.initProcess.pid())
}
for _, nsType := range configs.NamespaceTypes() {
if _, ok := state.NamespacePaths[nsType]; !ok {
ns := configs.Namespace{Type: nsType}
state.NamespacePaths[ns.Type] = ns.GetPath(c.initProcess.pid())
}
}
return state, nil
}
// bootstrapData encodes the necessary data in netlink binary format as a io.Reader.
// Consumer can write the data to a bootstrap program such as one that uses
// nsenter package to bootstrap the container's init process correctly, i.e. with
// correct namespaces, uid/gid mapping etc.
func (c *linuxContainer) bootstrapData(cloneFlags uintptr, pid int, consolePath string) (io.Reader, error) {
// create the netlink message
r := nl.NewNetlinkRequest(int(InitMsg), 0)
// write pid
r.AddData(&Int32msg{
Type: PidAttr,
Value: uint32(pid),
})
// write console path
if consolePath != "" {
r.AddData(&Bytemsg{
Type: ConsolePathAttr,
Value: []byte(consolePath),
})
}
return bytes.NewReader(r.Serialize()), nil
}
|
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: google/protobuf/field_mask.proto
package types
import (
bytes "bytes"
fmt "fmt"
proto "github.com/gogo/protobuf/proto"
io "io"
math "math"
reflect "reflect"
strings "strings"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package
// `FieldMask` represents a set of symbolic field paths, for example:
//
// paths: "f.a"
// paths: "f.b.d"
//
// Here `f` represents a field in some root message, `a` and `b`
// fields in the message found in `f`, and `d` a field found in the
// message in `f.b`.
//
// Field masks are used to specify a subset of fields that should be
// returned by a get operation or modified by an update operation.
// Field masks also have a custom JSON encoding (see below).
//
// # Field Masks in Projections
//
// When used in the context of a projection, a response message or
// sub-message is filtered by the API to only contain those fields as
// specified in the mask. For example, if the mask in the previous
// example is applied to a response message as follows:
//
// f {
// a : 22
// b {
// d : 1
// x : 2
// }
// y : 13
// }
// z: 8
//
// The result will not contain specific values for fields x,y and z
// (their value will be set to the default, and omitted in proto text
// output):
//
//
// f {
// a : 22
// b {
// d : 1
// }
// }
//
// A repeated field is not allowed except at the last position of a
// paths string.
//
// If a FieldMask object is not present in a get operation, the
// operation applies to all fields (as if a FieldMask of all fields
// had been specified).
//
// Note that a field mask does not necessarily apply to the
// top-level response message. In case of a REST get operation, the
// field mask applies directly to the response, but in case of a REST
// list operation, the mask instead applies to each individual message
// in the returned resource list. In case of a REST custom method,
// other definitions may be used. Where the mask applies will be
// clearly documented together with its declaration in the API. In
// any case, the effect on the returned resource/resources is required
// behavior for APIs.
//
// # Field Masks in Update Operations
//
// A field mask in update operations specifies which fields of the
// targeted resource are going to be updated. The API is required
// to only change the values of the fields as specified in the mask
// and leave the others untouched. If a resource is passed in to
// describe the updated values, the API ignores the values of all
// fields not covered by the mask.
//
// If a repeated field is specified for an update operation, new values will
// be appended to the existing repeated field in the target resource. Note that
// a repeated field is only allowed in the last position of a `paths` string.
//
// If a sub-message is specified in the last position of the field mask for an
// update operation, then new value will be merged into the existing sub-message
// in the target resource.
//
// For example, given the target message:
//
// f {
// b {
// d: 1
// x: 2
// }
// c: [1]
// }
//
// And an update message:
//
// f {
// b {
// d: 10
// }
// c: [2]
// }
//
// then if the field mask is:
//
// paths: ["f.b", "f.c"]
//
// then the result will be:
//
// f {
// b {
// d: 10
// x: 2
// }
// c: [1, 2]
// }
//
// An implementation may provide options to override this default behavior for
// repeated and message fields.
//
// In order to reset a field's value to the default, the field must
// be in the mask and set to the default value in the provided resource.
// Hence, in order to reset all fields of a resource, provide a default
// instance of the resource and set all fields in the mask, or do
// not provide a mask as described below.
//
// If a field mask is not present on update, the operation applies to
// all fields (as if a field mask of all fields has been specified).
// Note that in the presence of schema evolution, this may mean that
// fields the client does not know and has therefore not filled into
// the request will be reset to their default. If this is unwanted
// behavior, a specific service may require a client to always specify
// a field mask, producing an error if not.
//
// As with get operations, the location of the resource which
// describes the updated values in the request message depends on the
// operation kind. In any case, the effect of the field mask is
// required to be honored by the API.
//
// ## Considerations for HTTP REST
//
// The HTTP kind of an update operation which uses a field mask must
// be set to PATCH instead of PUT in order to satisfy HTTP semantics
// (PUT must only be used for full updates).
//
// # JSON Encoding of Field Masks
//
// In JSON, a field mask is encoded as a single string where paths are
// separated by a comma. Fields name in each path are converted
// to/from lower-camel naming conventions.
//
// As an example, consider the following message declarations:
//
// message Profile {
// User user = 1;
// Photo photo = 2;
// }
// message User {
// string display_name = 1;
// string address = 2;
// }
//
// In proto a field mask for `Profile` may look as such:
//
// mask {
// paths: "user.display_name"
// paths: "photo"
// }
//
// In JSON, the same mask is represented as below:
//
// {
// mask: "user.displayName,photo"
// }
//
// # Field Masks and Oneof Fields
//
// Field masks treat fields in oneofs just as regular fields. Consider the
// following message:
//
// message SampleMessage {
// oneof test_oneof {
// string name = 4;
// SubMessage sub_message = 9;
// }
// }
//
// The field mask can be:
//
// mask {
// paths: "name"
// }
//
// Or:
//
// mask {
// paths: "sub_message"
// }
//
// Note that oneof type names ("test_oneof" in this case) cannot be used in
// paths.
//
// ## Field Mask Verification
//
// The implementation of any API method which has a FieldMask type field in the
// request should verify the included field paths, and return an
// `INVALID_ARGUMENT` error if any path is duplicated or unmappable.
type FieldMask struct {
// The set of field mask paths.
Paths []string `protobuf:"bytes,1,rep,name=paths,proto3" json:"paths,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *FieldMask) Reset() { *m = FieldMask{} }
func (*FieldMask) ProtoMessage() {}
func (*FieldMask) Descriptor() ([]byte, []int) {
return fileDescriptor_5158202634f0da48, []int{0}
}
func (m *FieldMask) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *FieldMask) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_FieldMask.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalTo(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *FieldMask) XXX_Merge(src proto.Message) {
xxx_messageInfo_FieldMask.Merge(m, src)
}
func (m *FieldMask) XXX_Size() int {
return m.Size()
}
func (m *FieldMask) XXX_DiscardUnknown() {
xxx_messageInfo_FieldMask.DiscardUnknown(m)
}
var xxx_messageInfo_FieldMask proto.InternalMessageInfo
func (m *FieldMask) GetPaths() []string {
if m != nil {
return m.Paths
}
return nil
}
func (*FieldMask) XXX_MessageName() string {
return "google.protobuf.FieldMask"
}
func init() {
proto.RegisterType((*FieldMask)(nil), "google.protobuf.FieldMask")
}
func init() { proto.RegisterFile("google/protobuf/field_mask.proto", fileDescriptor_5158202634f0da48) }
var fileDescriptor_5158202634f0da48 = []byte{
// 203 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x48, 0xcf, 0xcf, 0x4f,
0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0xcb, 0x4c, 0xcd,
0x49, 0x89, 0xcf, 0x4d, 0x2c, 0xce, 0xd6, 0x03, 0x8b, 0x09, 0xf1, 0x43, 0x54, 0xe8, 0xc1, 0x54,
0x28, 0x29, 0x72, 0x71, 0xba, 0x81, 0x14, 0xf9, 0x26, 0x16, 0x67, 0x0b, 0x89, 0x70, 0xb1, 0x16,
0x24, 0x96, 0x64, 0x14, 0x4b, 0x30, 0x2a, 0x30, 0x6b, 0x70, 0x06, 0x41, 0x38, 0x4e, 0x1d, 0x8c,
0x37, 0x1e, 0xca, 0x31, 0x7c, 0x78, 0x28, 0xc7, 0xf8, 0xe3, 0xa1, 0x1c, 0x63, 0xc3, 0x23, 0x39,
0xc6, 0x15, 0x8f, 0xe4, 0x18, 0x4f, 0x3c, 0x92, 0x63, 0xbc, 0xf0, 0x48, 0x8e, 0xf1, 0xc1, 0x23,
0x39, 0xc6, 0x17, 0x8f, 0xe4, 0x18, 0x3e, 0x80, 0xc4, 0x1f, 0xcb, 0x31, 0x9e, 0x78, 0x2c, 0xc7,
0xc8, 0x25, 0x9c, 0x9c, 0x9f, 0xab, 0x87, 0x66, 0x95, 0x13, 0x1f, 0xdc, 0xa2, 0x00, 0x90, 0x50,
0x00, 0x63, 0x14, 0x6b, 0x49, 0x65, 0x41, 0x6a, 0xf1, 0x0f, 0x46, 0xc6, 0x45, 0x4c, 0xcc, 0xee,
0x01, 0x4e, 0xab, 0x98, 0xe4, 0xdc, 0x21, 0x7a, 0x02, 0xa0, 0x7a, 0xf4, 0xc2, 0x53, 0x73, 0x72,
0xbc, 0xf3, 0xf2, 0xcb, 0xf3, 0x42, 0x40, 0x2a, 0x93, 0xd8, 0xc0, 0x86, 0x19, 0x03, 0x02, 0x00,
0x00, 0xff, 0xff, 0x43, 0xa0, 0x83, 0xd0, 0xe9, 0x00, 0x00, 0x00,
}
func (this *FieldMask) Compare(that interface{}) int {
if that == nil {
if this == nil {
return 0
}
return 1
}
that1, ok := that.(*FieldMask)
if !ok {
that2, ok := that.(FieldMask)
if ok {
that1 = &that2
} else {
return 1
}
}
if that1 == nil {
if this == nil {
return 0
}
return 1
} else if this == nil {
return -1
}
if len(this.Paths) != len(that1.Paths) {
if len(this.Paths) < len(that1.Paths) {
return -1
}
return 1
}
for i := range this.Paths {
if this.Paths[i] != that1.Paths[i] {
if this.Paths[i] < that1.Paths[i] {
return -1
}
return 1
}
}
if c := bytes.Compare(this.XXX_unrecognized, that1.XXX_unrecognized); c != 0 {
return c
}
return 0
}
func (this *FieldMask) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*FieldMask)
if !ok {
that2, ok := that.(FieldMask)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
return this == nil
} else if this == nil {
return false
}
if len(this.Paths) != len(that1.Paths) {
return false
}
for i := range this.Paths {
if this.Paths[i] != that1.Paths[i] {
return false
}
}
if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) {
return false
}
return true
}
func (this *FieldMask) GoString() string {
if this == nil {
return "nil"
}
s := make([]string, 0, 5)
s = append(s, "&types.FieldMask{")
s = append(s, "Paths: "+fmt.Sprintf("%#v", this.Paths)+",\n")
if this.XXX_unrecognized != nil {
s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
}
s = append(s, "}")
return strings.Join(s, "")
}
func valueToGoStringFieldMask(v interface{}, typ string) string {
rv := reflect.ValueOf(v)
if rv.IsNil() {
return "nil"
}
pv := reflect.Indirect(rv).Interface()
return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv)
}
func (m *FieldMask) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *FieldMask) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if len(m.Paths) > 0 {
for _, s := range m.Paths {
dAtA[i] = 0xa
i++
l = len(s)
for l >= 1<<7 {
dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
l >>= 7
i++
}
dAtA[i] = uint8(l)
i++
i += copy(dAtA[i:], s)
}
}
if m.XXX_unrecognized != nil {
i += copy(dAtA[i:], m.XXX_unrecognized)
}
return i, nil
}
func encodeVarintFieldMask(dAtA []byte, offset int, v uint64) int {
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
dAtA[offset] = uint8(v)
return offset + 1
}
func NewPopulatedFieldMask(r randyFieldMask, easy bool) *FieldMask {
this := &FieldMask{}
v1 := r.Intn(10)
this.Paths = make([]string, v1)
for i := 0; i < v1; i++ {
this.Paths[i] = string(randStringFieldMask(r))
}
if !easy && r.Intn(10) != 0 {
this.XXX_unrecognized = randUnrecognizedFieldMask(r, 2)
}
return this
}
type randyFieldMask interface {
Float32() float32
Float64() float64
Int63() int64
Int31() int32
Uint32() uint32
Intn(n int) int
}
func randUTF8RuneFieldMask(r randyFieldMask) rune {
ru := r.Intn(62)
if ru < 10 {
return rune(ru + 48)
} else if ru < 36 {
return rune(ru + 55)
}
return rune(ru + 61)
}
func randStringFieldMask(r randyFieldMask) string {
v2 := r.Intn(100)
tmps := make([]rune, v2)
for i := 0; i < v2; i++ {
tmps[i] = randUTF8RuneFieldMask(r)
}
return string(tmps)
}
func randUnrecognizedFieldMask(r randyFieldMask, maxFieldNumber int) (dAtA []byte) {
l := r.Intn(5)
for i := 0; i < l; i++ {
wire := r.Intn(4)
if wire == 3 {
wire = 5
}
fieldNumber := maxFieldNumber + r.Intn(100)
dAtA = randFieldFieldMask(dAtA, r, fieldNumber, wire)
}
return dAtA
}
func randFieldFieldMask(dAtA []byte, r randyFieldMask, fieldNumber int, wire int) []byte {
key := uint32(fieldNumber)<<3 | uint32(wire)
switch wire {
case 0:
dAtA = encodeVarintPopulateFieldMask(dAtA, uint64(key))
v3 := r.Int63()
if r.Intn(2) == 0 {
v3 *= -1
}
dAtA = encodeVarintPopulateFieldMask(dAtA, uint64(v3))
case 1:
dAtA = encodeVarintPopulateFieldMask(dAtA, uint64(key))
dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)))
case 2:
dAtA = encodeVarintPopulateFieldMask(dAtA, uint64(key))
ll := r.Intn(100)
dAtA = encodeVarintPopulateFieldMask(dAtA, uint64(ll))
for j := 0; j < ll; j++ {
dAtA = append(dAtA, byte(r.Intn(256)))
}
default:
dAtA = encodeVarintPopulateFieldMask(dAtA, uint64(key))
dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)))
}
return dAtA
}
func encodeVarintPopulateFieldMask(dAtA []byte, v uint64) []byte {
for v >= 1<<7 {
dAtA = append(dAtA, uint8(uint64(v)&0x7f|0x80))
v >>= 7
}
dAtA = append(dAtA, uint8(v))
return dAtA
}
func (m *FieldMask) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if len(m.Paths) > 0 {
for _, s := range m.Paths {
l = len(s)
n += 1 + l + sovFieldMask(uint64(l))
}
}
if m.XXX_unrecognized != nil {
n += len(m.XXX_unrecognized)
}
return n
}
func sovFieldMask(x uint64) (n int) {
for {
n++
x >>= 7
if x == 0 {
break
}
}
return n
}
func sozFieldMask(x uint64) (n int) {
return sovFieldMask(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (this *FieldMask) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&FieldMask{`,
`Paths:` + fmt.Sprintf("%v", this.Paths) + `,`,
`XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
`}`,
}, "")
return s
}
func valueToStringFieldMask(v interface{}) string {
rv := reflect.ValueOf(v)
if rv.IsNil() {
return "nil"
}
pv := reflect.Indirect(rv).Interface()
return fmt.Sprintf("*%v", pv)
}
func (m *FieldMask) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowFieldMask
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: FieldMask: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: FieldMask: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Paths", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowFieldMask
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthFieldMask
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthFieldMask
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Paths = append(m.Paths, string(dAtA[iNdEx:postIndex]))
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipFieldMask(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthFieldMask
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthFieldMask
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func skipFieldMask(dAtA []byte) (n int, err error) {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowFieldMask
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
wireType := int(wire & 0x7)
switch wireType {
case 0:
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowFieldMask
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
iNdEx++
if dAtA[iNdEx-1] < 0x80 {
break
}
}
return iNdEx, nil
case 1:
iNdEx += 8
return iNdEx, nil
case 2:
var length int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowFieldMask
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
length |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if length < 0 {
return 0, ErrInvalidLengthFieldMask
}
iNdEx += length
if iNdEx < 0 {
return 0, ErrInvalidLengthFieldMask
}
return iNdEx, nil
case 3:
for {
var innerWire uint64
var start int = iNdEx
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowFieldMask
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
innerWire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
innerWireType := int(innerWire & 0x7)
if innerWireType == 4 {
break
}
next, err := skipFieldMask(dAtA[start:])
if err != nil {
return 0, err
}
iNdEx = start + next
if iNdEx < 0 {
return 0, ErrInvalidLengthFieldMask
}
}
return iNdEx, nil
case 4:
return iNdEx, nil
case 5:
iNdEx += 4
return iNdEx, nil
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
}
panic("unreachable")
}
var (
ErrInvalidLengthFieldMask = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowFieldMask = fmt.Errorf("proto: integer overflow")
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.