id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
22,440
|
self-test.h
|
Nevcairiel_LAVFilters/thirdparty/32/include/gnutls/self-test.h
|
/*
* Copyright (C) 2014 Free Software Foundation, Inc.
*
* Author: Nikos Mavrogiannopoulos
*
* This file is part of GnuTLS.
*
* The GnuTLS 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.
*
* 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 program. If not, see <https://www.gnu.org/licenses/>
*
*/
#ifndef GNUTLS_SELF_TEST_H
#define GNUTLS_SELF_TEST_H
#include <gnutls/gnutls.h>
/* Self checking functions */
#define GNUTLS_SELF_TEST_FLAG_ALL 1
#define GNUTLS_SELF_TEST_FLAG_NO_COMPAT (1<<1)
int gnutls_cipher_self_test(unsigned flags, gnutls_cipher_algorithm_t cipher);
int gnutls_mac_self_test(unsigned flags, gnutls_mac_algorithm_t mac);
int gnutls_digest_self_test(unsigned flags, gnutls_digest_algorithm_t digest);
int gnutls_pk_self_test(unsigned flags, gnutls_pk_algorithm_t pk);
int gnutls_hkdf_self_test(unsigned flags, gnutls_mac_algorithm_t mac);
int gnutls_pbkdf2_self_test(unsigned flags, gnutls_mac_algorithm_t mac);
int gnutls_tlsprf_self_test(unsigned flags, gnutls_mac_algorithm_t mac);
#endif /* GNUTLS_SELF_TEST_H */
| 1,552
|
C++
|
.h
| 35
| 42.542857
| 78
| 0.771523
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,441
|
system-keys.h
|
Nevcairiel_LAVFilters/thirdparty/32/include/gnutls/system-keys.h
|
/*
* Copyright (C) 2014 Red Hat, Inc.
*
* Author: Nikos Mavrogiannopoulos
*
* This file is part of GnuTLS.
*
* The GnuTLS 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.
*
* 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 program. If not, see <https://www.gnu.org/licenses/>
*
*/
#ifndef GNUTLS_SYSTEM_KEYS_H
#define GNUTLS_SYSTEM_KEYS_H
#include <gnutls/gnutls.h>
#include <gnutls/x509.h>
/* This API allows to access user key and certificate pairs that are
* available in the current system. If any passwords are required,
* they will be requested through the pin callbacks.
*/
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
struct system_key_iter_st;
typedef struct system_key_iter_st *gnutls_system_key_iter_t;
void gnutls_system_key_iter_deinit(gnutls_system_key_iter_t iter);
int
gnutls_system_key_iter_get_info(gnutls_system_key_iter_t *iter,
unsigned cert_type /* gnutls_certificate_type_t */,
char **cert_url,
char **key_url,
char **label,
gnutls_datum_t *der,
unsigned int flags);
int gnutls_system_key_delete(const char *cert_url, const char *key_url);
int gnutls_system_key_add_x509(gnutls_x509_crt_t crt, gnutls_x509_privkey_t privkey,
const char *label, char **cert_url, char **key_url);
/* *INDENT-OFF* */
#ifdef __cplusplus
}
#endif
/* *INDENT-ON* */
#endif /* GNUTLS_SYSTEM_KEYS_H */
| 1,916
|
C++
|
.h
| 54
| 32.685185
| 84
| 0.723542
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,442
|
compat.h
|
Nevcairiel_LAVFilters/thirdparty/32/include/gnutls/compat.h
|
/*
* Copyright (C) 2008-2012 Free Software Foundation, Inc.
*
* Author: Nikos Mavrogiannopoulos
*
* This file is part of GnuTLS.
*
* The GnuTLS 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.
*
* 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 program. If not, see <https://www.gnu.org/licenses/>
*
*/
/* Typedefs for more compatibility with older GnuTLS. */
#ifndef GNUTLS_COMPAT_H
#define GNUTLS_COMPAT_H
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
#ifdef __GNUC__
#define _GNUTLS_GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#if !defined GNUTLS_INTERNAL_BUILD
#if _GNUTLS_GCC_VERSION >= 30100
#define _GNUTLS_GCC_ATTR_DEPRECATED __attribute__ ((__deprecated__))
#endif
#endif
#endif /* __GNUC__ */
#ifndef _GNUTLS_GCC_ATTR_DEPRECATED
#define _GNUTLS_GCC_ATTR_DEPRECATED
#endif
/* gnutls_connection_end_t was made redundant in 2.99.0 */
typedef unsigned int gnutls_connection_end_t _GNUTLS_GCC_ATTR_DEPRECATED;
/* Stuff deprecated in 2.x */
typedef gnutls_cipher_algorithm_t gnutls_cipher_algorithm
_GNUTLS_GCC_ATTR_DEPRECATED;
typedef gnutls_kx_algorithm_t gnutls_kx_algorithm
_GNUTLS_GCC_ATTR_DEPRECATED;
typedef gnutls_mac_algorithm_t gnutls_mac_algorithm
_GNUTLS_GCC_ATTR_DEPRECATED;
typedef gnutls_digest_algorithm_t gnutls_digest_algorithm
_GNUTLS_GCC_ATTR_DEPRECATED;
typedef gnutls_compression_method_t gnutls_compression_method
_GNUTLS_GCC_ATTR_DEPRECATED;
typedef gnutls_connection_end_t gnutls_connection_end
_GNUTLS_GCC_ATTR_DEPRECATED;
typedef gnutls_x509_crt_fmt_t gnutls_x509_crt_fmt
_GNUTLS_GCC_ATTR_DEPRECATED;
typedef gnutls_pk_algorithm_t gnutls_pk_algorithm
_GNUTLS_GCC_ATTR_DEPRECATED;
typedef gnutls_sign_algorithm_t gnutls_sign_algorithm
_GNUTLS_GCC_ATTR_DEPRECATED;
typedef gnutls_close_request_t gnutls_close_request
_GNUTLS_GCC_ATTR_DEPRECATED;
typedef gnutls_certificate_request_t gnutls_certificate_request
_GNUTLS_GCC_ATTR_DEPRECATED;
typedef gnutls_certificate_status_t gnutls_certificate_status
_GNUTLS_GCC_ATTR_DEPRECATED;
typedef gnutls_session_t gnutls_session _GNUTLS_GCC_ATTR_DEPRECATED;
typedef gnutls_alert_level_t gnutls_alert_level
_GNUTLS_GCC_ATTR_DEPRECATED;
typedef gnutls_alert_description_t gnutls_alert_description
_GNUTLS_GCC_ATTR_DEPRECATED;
typedef gnutls_x509_subject_alt_name_t gnutls_x509_subject_alt_name
_GNUTLS_GCC_ATTR_DEPRECATED;
typedef gnutls_openpgp_privkey_t gnutls_openpgp_privkey
_GNUTLS_GCC_ATTR_DEPRECATED;
typedef gnutls_openpgp_keyring_t gnutls_openpgp_keyring
_GNUTLS_GCC_ATTR_DEPRECATED;
typedef gnutls_x509_crt_t gnutls_x509_crt _GNUTLS_GCC_ATTR_DEPRECATED;
typedef gnutls_x509_privkey_t gnutls_x509_privkey
_GNUTLS_GCC_ATTR_DEPRECATED;
typedef gnutls_x509_crl_t gnutls_x509_crl _GNUTLS_GCC_ATTR_DEPRECATED;
typedef gnutls_x509_crq_t gnutls_x509_crq _GNUTLS_GCC_ATTR_DEPRECATED;
typedef gnutls_certificate_credentials_t
gnutls_certificate_credentials _GNUTLS_GCC_ATTR_DEPRECATED;
typedef gnutls_anon_server_credentials_t
gnutls_anon_server_credentials _GNUTLS_GCC_ATTR_DEPRECATED;
typedef gnutls_anon_client_credentials_t
gnutls_anon_client_credentials _GNUTLS_GCC_ATTR_DEPRECATED;
typedef gnutls_srp_client_credentials_t
gnutls_srp_client_credentials _GNUTLS_GCC_ATTR_DEPRECATED;
typedef gnutls_srp_server_credentials_t
gnutls_srp_server_credentials _GNUTLS_GCC_ATTR_DEPRECATED;
typedef gnutls_dh_params_t gnutls_dh_params _GNUTLS_GCC_ATTR_DEPRECATED;
typedef gnutls_rsa_params_t gnutls_rsa_params _GNUTLS_GCC_ATTR_DEPRECATED;
typedef gnutls_params_type_t gnutls_params_type
_GNUTLS_GCC_ATTR_DEPRECATED;
typedef gnutls_credentials_type_t gnutls_credentials_type
_GNUTLS_GCC_ATTR_DEPRECATED;
typedef gnutls_certificate_type_t gnutls_certificate_type
_GNUTLS_GCC_ATTR_DEPRECATED;
typedef gnutls_datum_t gnutls_datum _GNUTLS_GCC_ATTR_DEPRECATED;
typedef gnutls_transport_ptr_t gnutls_transport_ptr
_GNUTLS_GCC_ATTR_DEPRECATED;
/* Old verification flags */
#define GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT (0)
/* Old SRP alerts removed in 2.1.x because the TLS-SRP RFC was
modified to use the PSK alert. */
#define GNUTLS_A_MISSING_SRP_USERNAME GNUTLS_A_UNKNOWN_PSK_IDENTITY
#define GNUTLS_A_UNKNOWN_SRP_USERNAME GNUTLS_A_UNKNOWN_PSK_IDENTITY
/* OpenPGP stuff renamed in 2.1.x. */
#define GNUTLS_OPENPGP_KEY GNUTLS_OPENPGP_CERT
#define GNUTLS_OPENPGP_KEY_FINGERPRINT GNUTLS_OPENPGP_CERT_FINGERPRINT
#define gnutls_openpgp_send_key gnutls_openpgp_send_cert
typedef gnutls_openpgp_crt_status_t gnutls_openpgp_key_status_t
_GNUTLS_GCC_ATTR_DEPRECATED;
typedef gnutls_openpgp_crt_t gnutls_openpgp_key_t
_GNUTLS_GCC_ATTR_DEPRECATED;
#define gnutls_openpgp_key_init gnutls_openpgp_crt_init
#define gnutls_openpgp_key_deinit gnutls_openpgp_crt_deinit
#define gnutls_openpgp_key_import gnutls_openpgp_crt_import
#define gnutls_openpgp_key_export gnutls_openpgp_crt_export
#define gnutls_openpgp_key_get_key_usage gnutls_openpgp_crt_get_key_usage
#define gnutls_openpgp_key_get_fingerprint gnutls_openpgp_crt_get_fingerprint
#define gnutls_openpgp_key_get_pk_algorithm gnutls_openpgp_crt_get_pk_algorithm
#define gnutls_openpgp_key_get_name gnutls_openpgp_crt_get_name
#define gnutls_openpgp_key_get_version gnutls_openpgp_crt_get_version
#define gnutls_openpgp_key_get_creation_time gnutls_openpgp_crt_get_creation_time
#define gnutls_openpgp_key_get_expiration_time gnutls_openpgp_crt_get_expiration_time
#define gnutls_openpgp_key_get_id gnutls_openpgp_crt_get_id
#define gnutls_openpgp_key_check_hostname gnutls_openpgp_crt_check_hostname
/* OpenPGP stuff renamed in 2.3.x. */
#define gnutls_openpgp_crt_get_id gnutls_openpgp_crt_get_key_id
/* New better names renamed in 2.3.x, add these for backwards
compatibility with old poor names.*/
#define GNUTLS_X509_CRT_FULL GNUTLS_CRT_PRINT_FULL
#define GNUTLS_X509_CRT_ONELINE GNUTLS_CRT_PRINT_ONELINE
#define GNUTLS_X509_CRT_UNSIGNED_FULL GNUTLS_CRT_PRINT_UNSIGNED_FULL
/* Namespace problems. */
#define LIBGNUTLS_VERSION GNUTLS_VERSION
#define LIBGNUTLS_VERSION_MAJOR GNUTLS_VERSION_MAJOR
#define LIBGNUTLS_VERSION_MINOR GNUTLS_VERSION_MINOR
#define LIBGNUTLS_VERSION_PATCH GNUTLS_VERSION_PATCH
#define LIBGNUTLS_VERSION_NUMBER GNUTLS_VERSION_NUMBER
#define LIBGNUTLS_EXTRA_VERSION GNUTLS_VERSION
/* This is a very dangerous and error-prone function.
* Use gnutls_privkey_sign_hash() instead.
*/
int gnutls_x509_privkey_sign_hash(gnutls_x509_privkey_t key,
const gnutls_datum_t * hash,
gnutls_datum_t * signature)
_GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_privkey_sign_hash(gnutls_openpgp_privkey_t key,
const gnutls_datum_t * hash,
gnutls_datum_t * signature)
_GNUTLS_GCC_ATTR_DEPRECATED;
/* gnutls_pubkey_get_preferred_hash_algorithm() */
int gnutls_x509_crt_get_preferred_hash_algorithm(gnutls_x509_crt_t
crt,
gnutls_digest_algorithm_t
* hash, unsigned int
*mand)
_GNUTLS_GCC_ATTR_DEPRECATED;
/* use gnutls_privkey_sign_hash() with the GNUTLS_PRIVKEY_SIGN_FLAG_TLS1_RSA flag */
#ifdef _ISOC99_SOURCE
/* we provide older functions for compatibility as inline functions that
* depend on gnutls_session_get_random. */
static inline const void
*gnutls_session_get_server_random(gnutls_session_t session)
_GNUTLS_GCC_ATTR_DEPRECATED;
static inline const void
*gnutls_session_get_server_random(gnutls_session_t session)
{
gnutls_datum_t rnd;
gnutls_session_get_random(session, NULL, &rnd); /*doc-skip */
return rnd.data;
}
static inline const void
*gnutls_session_get_client_random(gnutls_session_t session)
_GNUTLS_GCC_ATTR_DEPRECATED;
static inline const void
*gnutls_session_get_client_random(gnutls_session_t session)
{
gnutls_datum_t rnd;
gnutls_session_get_random(session, &rnd, NULL); /*doc-skip */
return rnd.data;
}
#endif
void
gnutls_global_set_mem_functions(gnutls_alloc_function alloc_func,
gnutls_alloc_function secure_alloc_func,
gnutls_is_secure_function is_secure_func,
gnutls_realloc_function realloc_func,
gnutls_free_function free_func) _GNUTLS_GCC_ATTR_DEPRECATED;
/* defined in old headers - unused nevertheless */
#define GNUTLS_SUPPLEMENTAL_USER_MAPPING_DATA 0
/* old compression related functions */
gnutls_compression_method_t
gnutls_compression_get(gnutls_session_t session) _GNUTLS_GCC_ATTR_DEPRECATED;
const char *
gnutls_compression_get_name(gnutls_compression_method_t
algorithm) __GNUTLS_CONST__ _GNUTLS_GCC_ATTR_DEPRECATED;
gnutls_compression_method_t
gnutls_compression_get_id(const char *name) __GNUTLS_CONST__ _GNUTLS_GCC_ATTR_DEPRECATED;
const gnutls_compression_method_t *
gnutls_compression_list(void) __GNUTLS_PURE__ _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_priority_compression_list(gnutls_priority_t pcache,
const unsigned int **list) _GNUTLS_GCC_ATTR_DEPRECATED;
/* *INDENT-OFF* */
#ifdef __cplusplus
}
#endif
/* *INDENT-ON* */
#endif /* GNUTLS_COMPAT_H */
| 9,460
|
C++
|
.h
| 214
| 41.817757
| 91
| 0.788583
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,443
|
openpgp.h
|
Nevcairiel_LAVFilters/thirdparty/32/include/gnutls/openpgp.h
|
/*
* Copyright (C) 2003-2012 Free Software Foundation, Inc.
*
* Author: Nikos Mavrogiannopoulos
*
* This file is part of GnuTLS.
*
* The GnuTLS 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.
*
* 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 program. If not, see <https://www.gnu.org/licenses/>
*
*/
/* This file contains the types and prototypes for the OpenPGP
* key and private key parsing functions.
*/
#ifndef GNUTLS_OPENPGP_H
#define GNUTLS_OPENPGP_H
#include <gnutls/gnutls.h>
#include <limits.h>
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
/* Openpgp certificate stuff
*/
/**
* gnutls_openpgp_crt_fmt_t:
* @GNUTLS_OPENPGP_FMT_RAW: OpenPGP certificate in raw format.
* @GNUTLS_OPENPGP_FMT_BASE64: OpenPGP certificate in base64 format.
*
* Enumeration of different OpenPGP key formats.
*/
typedef enum gnutls_openpgp_crt_fmt {
GNUTLS_OPENPGP_FMT_RAW,
GNUTLS_OPENPGP_FMT_BASE64
} gnutls_openpgp_crt_fmt_t;
#define GNUTLS_OPENPGP_KEYID_SIZE 8
#define GNUTLS_OPENPGP_V4_FINGERPRINT_SIZE 20
typedef unsigned char
gnutls_openpgp_keyid_t[GNUTLS_OPENPGP_KEYID_SIZE];
/* gnutls_openpgp_cert_t should be defined in gnutls.h
*/
/* initializes the memory for gnutls_openpgp_crt_t struct */
int gnutls_openpgp_crt_init(gnutls_openpgp_crt_t * key) _GNUTLS_GCC_ATTR_DEPRECATED;
/* frees all memory */
void gnutls_openpgp_crt_deinit(gnutls_openpgp_crt_t key) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_crt_import(gnutls_openpgp_crt_t key,
const gnutls_datum_t * data,
gnutls_openpgp_crt_fmt_t format) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_crt_export(gnutls_openpgp_crt_t key,
gnutls_openpgp_crt_fmt_t format,
void *output_data,
size_t * output_data_size) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_crt_export2(gnutls_openpgp_crt_t key,
gnutls_openpgp_crt_fmt_t format,
gnutls_datum_t * out) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_crt_print(gnutls_openpgp_crt_t cert,
gnutls_certificate_print_formats_t
format, gnutls_datum_t * out) _GNUTLS_GCC_ATTR_DEPRECATED;
/* The key_usage flags are defined in gnutls.h. They are
* the GNUTLS_KEY_* definitions.
*/
#define GNUTLS_OPENPGP_MASTER_KEYID_IDX INT_MAX
int gnutls_openpgp_crt_get_key_usage(gnutls_openpgp_crt_t key,
unsigned int *key_usage) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_crt_get_fingerprint(gnutls_openpgp_crt_t key,
void *fpr, size_t * fprlen) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_crt_get_subkey_fingerprint(gnutls_openpgp_crt_t
key,
unsigned int idx,
void *fpr, size_t * fprlen) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_crt_get_name(gnutls_openpgp_crt_t key,
int idx, char *buf, size_t * sizeof_buf) _GNUTLS_GCC_ATTR_DEPRECATED;
gnutls_pk_algorithm_t
gnutls_openpgp_crt_get_pk_algorithm(gnutls_openpgp_crt_t key,
unsigned int *bits) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_crt_get_version(gnutls_openpgp_crt_t key) _GNUTLS_GCC_ATTR_DEPRECATED;
time_t gnutls_openpgp_crt_get_creation_time(gnutls_openpgp_crt_t key) _GNUTLS_GCC_ATTR_DEPRECATED;
time_t gnutls_openpgp_crt_get_expiration_time(gnutls_openpgp_crt_t key) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_crt_get_key_id(gnutls_openpgp_crt_t key,
gnutls_openpgp_keyid_t keyid) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_crt_check_hostname(gnutls_openpgp_crt_t key,
const char *hostname) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_crt_check_hostname2(gnutls_openpgp_crt_t key,
const char *hostname, unsigned int flags) _GNUTLS_GCC_ATTR_DEPRECATED;
int
gnutls_openpgp_crt_check_email(gnutls_openpgp_crt_t key, const char *email, unsigned flags) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_crt_get_revoked_status(gnutls_openpgp_crt_t key) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_crt_get_subkey_count(gnutls_openpgp_crt_t key) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_crt_get_subkey_idx(gnutls_openpgp_crt_t key,
const gnutls_openpgp_keyid_t keyid) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_crt_get_subkey_revoked_status
(gnutls_openpgp_crt_t key, unsigned int idx) _GNUTLS_GCC_ATTR_DEPRECATED;
gnutls_pk_algorithm_t
gnutls_openpgp_crt_get_subkey_pk_algorithm(gnutls_openpgp_crt_t
key,
unsigned int idx,
unsigned int *bits) _GNUTLS_GCC_ATTR_DEPRECATED;
time_t
gnutls_openpgp_crt_get_subkey_creation_time
(gnutls_openpgp_crt_t key, unsigned int idx) _GNUTLS_GCC_ATTR_DEPRECATED;
time_t
gnutls_openpgp_crt_get_subkey_expiration_time
(gnutls_openpgp_crt_t key, unsigned int idx) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_crt_get_subkey_id(gnutls_openpgp_crt_t key,
unsigned int idx,
gnutls_openpgp_keyid_t keyid) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_crt_get_subkey_usage(gnutls_openpgp_crt_t key,
unsigned int idx,
unsigned int *key_usage) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_crt_get_subkey_pk_dsa_raw(gnutls_openpgp_crt_t
crt, unsigned int idx,
gnutls_datum_t * p,
gnutls_datum_t * q,
gnutls_datum_t * g,
gnutls_datum_t * y) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_crt_get_subkey_pk_rsa_raw(gnutls_openpgp_crt_t
crt, unsigned int idx,
gnutls_datum_t * m,
gnutls_datum_t * e) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_crt_get_pk_dsa_raw(gnutls_openpgp_crt_t crt,
gnutls_datum_t * p,
gnutls_datum_t * q,
gnutls_datum_t * g,
gnutls_datum_t * y) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_crt_get_pk_rsa_raw(gnutls_openpgp_crt_t crt,
gnutls_datum_t * m,
gnutls_datum_t * e) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_crt_get_preferred_key_id(gnutls_openpgp_crt_t
key,
gnutls_openpgp_keyid_t keyid) _GNUTLS_GCC_ATTR_DEPRECATED;
int
gnutls_openpgp_crt_set_preferred_key_id(gnutls_openpgp_crt_t key,
const
gnutls_openpgp_keyid_t keyid) _GNUTLS_GCC_ATTR_DEPRECATED;
/* privkey stuff.
*/
int gnutls_openpgp_privkey_init(gnutls_openpgp_privkey_t * key) _GNUTLS_GCC_ATTR_DEPRECATED;
void gnutls_openpgp_privkey_deinit(gnutls_openpgp_privkey_t key) _GNUTLS_GCC_ATTR_DEPRECATED;
gnutls_pk_algorithm_t
gnutls_openpgp_privkey_get_pk_algorithm
(gnutls_openpgp_privkey_t key, unsigned int *bits) _GNUTLS_GCC_ATTR_DEPRECATED;
gnutls_sec_param_t
gnutls_openpgp_privkey_sec_param(gnutls_openpgp_privkey_t key) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_privkey_import(gnutls_openpgp_privkey_t key,
const gnutls_datum_t * data,
gnutls_openpgp_crt_fmt_t format,
const char *password,
unsigned int flags) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_privkey_get_fingerprint(gnutls_openpgp_privkey_t
key, void *fpr,
size_t * fprlen) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_privkey_get_subkey_fingerprint
(gnutls_openpgp_privkey_t key, unsigned int idx, void *fpr,
size_t * fprlen) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_privkey_get_key_id(gnutls_openpgp_privkey_t key,
gnutls_openpgp_keyid_t keyid) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_privkey_get_subkey_count(gnutls_openpgp_privkey_t key) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_privkey_get_subkey_idx(gnutls_openpgp_privkey_t
key,
const
gnutls_openpgp_keyid_t keyid) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_privkey_get_subkey_revoked_status
(gnutls_openpgp_privkey_t key, unsigned int idx) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_privkey_get_revoked_status
(gnutls_openpgp_privkey_t key) _GNUTLS_GCC_ATTR_DEPRECATED;
gnutls_pk_algorithm_t
gnutls_openpgp_privkey_get_subkey_pk_algorithm
(gnutls_openpgp_privkey_t key, unsigned int idx, unsigned int *bits) _GNUTLS_GCC_ATTR_DEPRECATED;
time_t
gnutls_openpgp_privkey_get_subkey_expiration_time
(gnutls_openpgp_privkey_t key, unsigned int idx) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_privkey_get_subkey_id(gnutls_openpgp_privkey_t
key, unsigned int idx,
gnutls_openpgp_keyid_t keyid) _GNUTLS_GCC_ATTR_DEPRECATED;
time_t
gnutls_openpgp_privkey_get_subkey_creation_time
(gnutls_openpgp_privkey_t key, unsigned int idx) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_privkey_export_subkey_dsa_raw
(gnutls_openpgp_privkey_t pkey, unsigned int idx,
gnutls_datum_t * p, gnutls_datum_t * q, gnutls_datum_t * g,
gnutls_datum_t * y, gnutls_datum_t * x) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_privkey_export_subkey_rsa_raw
(gnutls_openpgp_privkey_t pkey, unsigned int idx,
gnutls_datum_t * m, gnutls_datum_t * e, gnutls_datum_t * d,
gnutls_datum_t * p, gnutls_datum_t * q, gnutls_datum_t * u) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_privkey_export_dsa_raw(gnutls_openpgp_privkey_t
pkey, gnutls_datum_t * p,
gnutls_datum_t * q,
gnutls_datum_t * g,
gnutls_datum_t * y,
gnutls_datum_t * x) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_privkey_export_rsa_raw(gnutls_openpgp_privkey_t
pkey, gnutls_datum_t * m,
gnutls_datum_t * e,
gnutls_datum_t * d,
gnutls_datum_t * p,
gnutls_datum_t * q,
gnutls_datum_t * u) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_privkey_export(gnutls_openpgp_privkey_t key,
gnutls_openpgp_crt_fmt_t format,
const char *password,
unsigned int flags,
void *output_data,
size_t * output_data_size) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_privkey_export2(gnutls_openpgp_privkey_t key,
gnutls_openpgp_crt_fmt_t format,
const char *password,
unsigned int flags,
gnutls_datum_t * out) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_privkey_set_preferred_key_id
(gnutls_openpgp_privkey_t key, const gnutls_openpgp_keyid_t keyid) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_privkey_get_preferred_key_id
(gnutls_openpgp_privkey_t key, gnutls_openpgp_keyid_t keyid) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_crt_get_auth_subkey(gnutls_openpgp_crt_t crt,
gnutls_openpgp_keyid_t
keyid, unsigned int flag) _GNUTLS_GCC_ATTR_DEPRECATED;
/* Keyring stuff.
*/
int gnutls_openpgp_keyring_init(gnutls_openpgp_keyring_t * keyring) _GNUTLS_GCC_ATTR_DEPRECATED;
void gnutls_openpgp_keyring_deinit(gnutls_openpgp_keyring_t keyring) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_keyring_import(gnutls_openpgp_keyring_t keyring,
const gnutls_datum_t * data,
gnutls_openpgp_crt_fmt_t format) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_keyring_check_id(gnutls_openpgp_keyring_t ring,
const gnutls_openpgp_keyid_t
keyid, unsigned int flags) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_crt_verify_ring(gnutls_openpgp_crt_t key,
gnutls_openpgp_keyring_t
keyring, unsigned int flags,
unsigned int *verify
/* the output of the verification */
) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_crt_verify_self(gnutls_openpgp_crt_t key,
unsigned int flags,
unsigned int *verify) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_keyring_get_crt(gnutls_openpgp_keyring_t ring,
unsigned int idx,
gnutls_openpgp_crt_t * cert) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_openpgp_keyring_get_crt_count(gnutls_openpgp_keyring_t ring) _GNUTLS_GCC_ATTR_DEPRECATED;
/**
* gnutls_openpgp_recv_key_func:
* @session: a TLS session
* @keyfpr: key fingerprint
* @keyfpr_length: length of key fingerprint
* @key: output key.
*
* A callback of this type is used to retrieve OpenPGP keys. Only
* useful on the server, and will only be used if the peer send a key
* fingerprint instead of a full key. See also
* gnutls_openpgp_set_recv_key_function().
*
* The variable @key must be allocated using gnutls_malloc().
*
* Returns: On success, %GNUTLS_E_SUCCESS (zero) is returned,
* otherwise an error code is returned.
*/
typedef int (*gnutls_openpgp_recv_key_func) (gnutls_session_t
session,
const unsigned char
*keyfpr,
unsigned int
keyfpr_length,
gnutls_datum_t * key);
void
gnutls_openpgp_set_recv_key_function(gnutls_session_t session,
gnutls_openpgp_recv_key_func func) _GNUTLS_GCC_ATTR_DEPRECATED;
/* certificate authentication stuff.
*/
int gnutls_certificate_set_openpgp_key
(gnutls_certificate_credentials_t res,
gnutls_openpgp_crt_t crt, gnutls_openpgp_privkey_t pkey) _GNUTLS_GCC_ATTR_DEPRECATED;
int
gnutls_certificate_get_openpgp_key(gnutls_certificate_credentials_t res,
unsigned index,
gnutls_openpgp_privkey_t *key) _GNUTLS_GCC_ATTR_DEPRECATED;
int
gnutls_certificate_get_openpgp_crt(gnutls_certificate_credentials_t res,
unsigned index,
gnutls_openpgp_crt_t **crt_list,
unsigned *crt_list_size) _GNUTLS_GCC_ATTR_DEPRECATED;
int
gnutls_certificate_set_openpgp_key_file
(gnutls_certificate_credentials_t res, const char *certfile,
const char *keyfile, gnutls_openpgp_crt_fmt_t format) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_certificate_set_openpgp_key_mem
(gnutls_certificate_credentials_t res,
const gnutls_datum_t * cert, const gnutls_datum_t * key,
gnutls_openpgp_crt_fmt_t format) _GNUTLS_GCC_ATTR_DEPRECATED;
int
gnutls_certificate_set_openpgp_key_file2
(gnutls_certificate_credentials_t res, const char *certfile,
const char *keyfile, const char *subkey_id,
gnutls_openpgp_crt_fmt_t format) _GNUTLS_GCC_ATTR_DEPRECATED;
int
gnutls_certificate_set_openpgp_key_mem2
(gnutls_certificate_credentials_t res,
const gnutls_datum_t * cert, const gnutls_datum_t * key,
const char *subkey_id, gnutls_openpgp_crt_fmt_t format) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_certificate_set_openpgp_keyring_mem
(gnutls_certificate_credentials_t c, const unsigned char *data,
size_t dlen, gnutls_openpgp_crt_fmt_t format) _GNUTLS_GCC_ATTR_DEPRECATED;
int gnutls_certificate_set_openpgp_keyring_file
(gnutls_certificate_credentials_t c, const char *file,
gnutls_openpgp_crt_fmt_t format) _GNUTLS_GCC_ATTR_DEPRECATED;
/* *INDENT-OFF* */
#ifdef __cplusplus
}
#endif
/* *INDENT-ON* */
#endif /* GNUTLS_OPENPGP_H */
| 15,018
|
C++
|
.h
| 321
| 41.809969
| 120
| 0.729726
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
22,444
|
socket.h
|
Nevcairiel_LAVFilters/thirdparty/32/include/gnutls/socket.h
|
/*
* Copyright (C) 2016 Free Software Foundation, Inc.
*
* Author: Tim Ruehsen
*
* This file is part of GnuTLS.
*
* The GnuTLS 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.
*
* 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 program. If not, see <https://www.gnu.org/licenses/>
*
*/
/* This file contains socket related types, prototypes and includes.
*/
#ifndef GNUTLS_SOCKET_H
#define GNUTLS_SOCKET_H
#include <gnutls/gnutls.h>
/* Get socklen_t */
#include <sys/socket.h>
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
/**
* gnutls_transport_ktls_enable_flags_t:
* @GNUTLS_KTLS_RECV: ktls enabled for recv function.
* @GNUTLS_KTLS_SEND: ktls enabled for send function.
* @GNUTLS_KTLS_DUPLEX: ktls enabled for both recv and send functions.
*
* Flag enumeration of ktls enable status for recv and send functions.
* This is used by gnutls_transport_is_ktls_enabled().
*
* Since: 3.7.3
*/
typedef enum {
GNUTLS_KTLS_RECV = 1 << 0,
GNUTLS_KTLS_SEND = 1 << 1,
GNUTLS_KTLS_DUPLEX = GNUTLS_KTLS_RECV | GNUTLS_KTLS_SEND,
} gnutls_transport_ktls_enable_flags_t;
gnutls_transport_ktls_enable_flags_t
gnutls_transport_is_ktls_enabled(gnutls_session_t session);
void gnutls_transport_set_fastopen(gnutls_session_t session,
int fd,
struct sockaddr *connect_addr,
socklen_t connect_addrlen,
unsigned int flags);
/* *INDENT-OFF* */
#ifdef __cplusplus
}
#endif
/* *INDENT-ON* */
#endif /* GNUTLS_SOCKET_H */
| 2,098
|
C++
|
.h
| 62
| 29.854839
| 75
| 0.693827
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,445
|
ocsp.h
|
Nevcairiel_LAVFilters/thirdparty/32/include/gnutls/ocsp.h
|
/*
* Copyright (C) 2011-2012 Free Software Foundation, Inc.
*
* Author: Simon Josefsson
*
* This file is part of GnuTLS.
*
* The GnuTLS 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.
*
* 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 program. If not, see <https://www.gnu.org/licenses/>
*
*/
/* Online Certificate Status Protocol - RFC 2560
*/
#ifndef GNUTLS_OCSP_H
#define GNUTLS_OCSP_H
#include <gnutls/gnutls.h>
#include <gnutls/x509.h>
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
#define GNUTLS_OCSP_NONCE "1.3.6.1.5.5.7.48.1.2"
/**
* gnutls_ocsp_print_formats_t:
* @GNUTLS_OCSP_PRINT_FULL: Full information about OCSP request/response.
* @GNUTLS_OCSP_PRINT_COMPACT: More compact information about OCSP request/response.
*
* Enumeration of different OCSP printing variants.
*/
typedef enum gnutls_ocsp_print_formats_t {
GNUTLS_OCSP_PRINT_FULL = 0,
GNUTLS_OCSP_PRINT_COMPACT = 1
} gnutls_ocsp_print_formats_t;
/**
* gnutls_ocsp_resp_status_t:
* @GNUTLS_OCSP_RESP_SUCCESSFUL: Response has valid confirmations.
* @GNUTLS_OCSP_RESP_MALFORMEDREQUEST: Illegal confirmation request
* @GNUTLS_OCSP_RESP_INTERNALERROR: Internal error in issuer
* @GNUTLS_OCSP_RESP_TRYLATER: Try again later
* @GNUTLS_OCSP_RESP_SIGREQUIRED: Must sign the request
* @GNUTLS_OCSP_RESP_UNAUTHORIZED: Request unauthorized
*
* Enumeration of different OCSP response status codes.
*/
typedef enum gnutls_ocsp_resp_status_t {
GNUTLS_OCSP_RESP_SUCCESSFUL = 0,
GNUTLS_OCSP_RESP_MALFORMEDREQUEST = 1,
GNUTLS_OCSP_RESP_INTERNALERROR = 2,
GNUTLS_OCSP_RESP_TRYLATER = 3,
GNUTLS_OCSP_RESP_SIGREQUIRED = 5,
GNUTLS_OCSP_RESP_UNAUTHORIZED = 6
} gnutls_ocsp_resp_status_t;
/**
* gnutls_ocsp_cert_status_t:
* @GNUTLS_OCSP_CERT_GOOD: Positive response to status inquiry.
* @GNUTLS_OCSP_CERT_REVOKED: Certificate has been revoked.
* @GNUTLS_OCSP_CERT_UNKNOWN: The responder doesn't know about the
* certificate.
*
* Enumeration of different OCSP response certificate status codes.
*/
typedef enum gnutls_ocsp_cert_status_t {
GNUTLS_OCSP_CERT_GOOD = 0,
GNUTLS_OCSP_CERT_REVOKED = 1,
GNUTLS_OCSP_CERT_UNKNOWN = 2
} gnutls_ocsp_cert_status_t;
/**
* gnutls_x509_crl_reason_t:
* @GNUTLS_X509_CRLREASON_UNSPECIFIED: Unspecified reason.
* @GNUTLS_X509_CRLREASON_KEYCOMPROMISE: Private key compromised.
* @GNUTLS_X509_CRLREASON_CACOMPROMISE: CA compromised.
* @GNUTLS_X509_CRLREASON_AFFILIATIONCHANGED: Affiliation has changed.
* @GNUTLS_X509_CRLREASON_SUPERSEDED: Certificate superseded.
* @GNUTLS_X509_CRLREASON_CESSATIONOFOPERATION: Operation has ceased.
* @GNUTLS_X509_CRLREASON_CERTIFICATEHOLD: Certificate is on hold.
* @GNUTLS_X509_CRLREASON_REMOVEFROMCRL: Will be removed from delta CRL.
* @GNUTLS_X509_CRLREASON_PRIVILEGEWITHDRAWN: Privilege withdrawn.
* @GNUTLS_X509_CRLREASON_AACOMPROMISE: AA compromised.
*
* Enumeration of different reason codes. Note that this
* corresponds to the CRLReason ASN.1 enumeration type, and not the
* ReasonFlags ASN.1 bit string.
*/
typedef enum gnutls_x509_crl_reason_t {
GNUTLS_X509_CRLREASON_UNSPECIFIED = 0,
GNUTLS_X509_CRLREASON_KEYCOMPROMISE = 1,
GNUTLS_X509_CRLREASON_CACOMPROMISE = 2,
GNUTLS_X509_CRLREASON_AFFILIATIONCHANGED = 3,
GNUTLS_X509_CRLREASON_SUPERSEDED = 4,
GNUTLS_X509_CRLREASON_CESSATIONOFOPERATION = 5,
GNUTLS_X509_CRLREASON_CERTIFICATEHOLD = 6,
GNUTLS_X509_CRLREASON_REMOVEFROMCRL = 8,
GNUTLS_X509_CRLREASON_PRIVILEGEWITHDRAWN = 9,
GNUTLS_X509_CRLREASON_AACOMPROMISE = 10
} gnutls_x509_crl_reason_t;
/* When adding a verify failure reason update:
* _gnutls_ocsp_verify_status_to_str()
*/
/**
* gnutls_ocsp_verify_reason_t:
* @GNUTLS_OCSP_VERIFY_SIGNER_NOT_FOUND: Signer cert not found.
* @GNUTLS_OCSP_VERIFY_SIGNER_KEYUSAGE_ERROR: Signer keyusage bits incorrect.
* @GNUTLS_OCSP_VERIFY_UNTRUSTED_SIGNER: Signer is not trusted.
* @GNUTLS_OCSP_VERIFY_INSECURE_ALGORITHM: Signature using insecure algorithm.
* @GNUTLS_OCSP_VERIFY_SIGNATURE_FAILURE: Signature mismatch.
* @GNUTLS_OCSP_VERIFY_CERT_NOT_ACTIVATED: Signer cert is not yet activated.
* @GNUTLS_OCSP_VERIFY_CERT_EXPIRED: Signer cert has expired.
*
* Enumeration of OCSP verify status codes, used by
* gnutls_ocsp_resp_verify() and gnutls_ocsp_resp_verify_direct().
*/
typedef enum gnutls_ocsp_verify_reason_t {
GNUTLS_OCSP_VERIFY_SIGNER_NOT_FOUND = 1,
GNUTLS_OCSP_VERIFY_SIGNER_KEYUSAGE_ERROR = 2,
GNUTLS_OCSP_VERIFY_UNTRUSTED_SIGNER = 4,
GNUTLS_OCSP_VERIFY_INSECURE_ALGORITHM = 8,
GNUTLS_OCSP_VERIFY_SIGNATURE_FAILURE = 16,
GNUTLS_OCSP_VERIFY_CERT_NOT_ACTIVATED = 32,
GNUTLS_OCSP_VERIFY_CERT_EXPIRED = 64
} gnutls_ocsp_verify_reason_t;
struct gnutls_ocsp_req_int;
typedef struct gnutls_ocsp_req_int *gnutls_ocsp_req_t;
typedef const struct gnutls_ocsp_req_int *gnutls_ocsp_req_const_t;
int gnutls_ocsp_req_init(gnutls_ocsp_req_t * req);
void gnutls_ocsp_req_deinit(gnutls_ocsp_req_t req);
int gnutls_ocsp_req_import(gnutls_ocsp_req_t req,
const gnutls_datum_t * data);
int gnutls_ocsp_req_export(gnutls_ocsp_req_const_t req, gnutls_datum_t * data);
int gnutls_ocsp_req_print(gnutls_ocsp_req_const_t req,
gnutls_ocsp_print_formats_t format,
gnutls_datum_t * out);
int gnutls_ocsp_req_get_version(gnutls_ocsp_req_const_t req);
int gnutls_ocsp_req_get_cert_id(gnutls_ocsp_req_const_t req,
unsigned indx,
gnutls_digest_algorithm_t * digest,
gnutls_datum_t * issuer_name_hash,
gnutls_datum_t * issuer_key_hash,
gnutls_datum_t * serial_number);
int gnutls_ocsp_req_add_cert_id(gnutls_ocsp_req_t req,
gnutls_digest_algorithm_t digest,
const gnutls_datum_t *
issuer_name_hash,
const gnutls_datum_t *
issuer_key_hash,
const gnutls_datum_t * serial_number);
int gnutls_ocsp_req_add_cert(gnutls_ocsp_req_t req,
gnutls_digest_algorithm_t digest,
gnutls_x509_crt_t issuer,
gnutls_x509_crt_t cert);
int gnutls_ocsp_req_get_extension(gnutls_ocsp_req_const_t req,
unsigned indx,
gnutls_datum_t * oid,
unsigned int *critical,
gnutls_datum_t * data);
int gnutls_ocsp_req_set_extension(gnutls_ocsp_req_t req,
const char *oid,
unsigned int critical,
const gnutls_datum_t * data);
int gnutls_ocsp_req_get_nonce(gnutls_ocsp_req_const_t req,
unsigned int *critical,
gnutls_datum_t * nonce);
int gnutls_ocsp_req_set_nonce(gnutls_ocsp_req_t req,
unsigned int critical,
const gnutls_datum_t * nonce);
int gnutls_ocsp_req_randomize_nonce(gnutls_ocsp_req_t req);
struct gnutls_ocsp_resp_int;
typedef struct gnutls_ocsp_resp_int *gnutls_ocsp_resp_t;
typedef const struct gnutls_ocsp_resp_int *gnutls_ocsp_resp_const_t;
int gnutls_ocsp_resp_init(gnutls_ocsp_resp_t * resp);
void gnutls_ocsp_resp_deinit(gnutls_ocsp_resp_t resp);
int gnutls_ocsp_resp_import(gnutls_ocsp_resp_t resp,
const gnutls_datum_t * data);
int gnutls_ocsp_resp_import2(gnutls_ocsp_resp_t resp,
const gnutls_datum_t * data,
gnutls_x509_crt_fmt_t fmt);
int gnutls_ocsp_resp_export(gnutls_ocsp_resp_const_t resp,
gnutls_datum_t * data);
int gnutls_ocsp_resp_export2(gnutls_ocsp_resp_const_t resp,
gnutls_datum_t * data,
gnutls_x509_crt_fmt_t fmt);
int gnutls_ocsp_resp_print(gnutls_ocsp_resp_const_t resp,
gnutls_ocsp_print_formats_t format,
gnutls_datum_t * out);
int gnutls_ocsp_resp_get_status(gnutls_ocsp_resp_const_t resp);
int gnutls_ocsp_resp_get_response(gnutls_ocsp_resp_const_t resp,
gnutls_datum_t *
response_type_oid,
gnutls_datum_t * response);
int gnutls_ocsp_resp_get_version(gnutls_ocsp_resp_const_t resp);
int gnutls_ocsp_resp_get_responder(gnutls_ocsp_resp_const_t resp,
gnutls_datum_t * dn);
int gnutls_ocsp_resp_get_responder2(gnutls_ocsp_resp_const_t resp,
gnutls_datum_t * dn,
unsigned flags);
/* the raw key ID of the responder */
#define GNUTLS_OCSP_RESP_ID_KEY 1
/* the raw DN of the responder */
#define GNUTLS_OCSP_RESP_ID_DN 2
int
gnutls_ocsp_resp_get_responder_raw_id(gnutls_ocsp_resp_const_t resp,
unsigned type,
gnutls_datum_t * raw);
time_t gnutls_ocsp_resp_get_produced(gnutls_ocsp_resp_const_t resp);
int gnutls_ocsp_resp_get_single(gnutls_ocsp_resp_const_t resp,
unsigned indx,
gnutls_digest_algorithm_t * digest,
gnutls_datum_t * issuer_name_hash,
gnutls_datum_t * issuer_key_hash,
gnutls_datum_t * serial_number,
unsigned int *cert_status,
time_t * this_update,
time_t * next_update,
time_t * revocation_time,
unsigned int *revocation_reason);
int gnutls_ocsp_resp_get_extension(gnutls_ocsp_resp_const_t resp,
unsigned indx,
gnutls_datum_t * oid,
unsigned int *critical,
gnutls_datum_t * data);
int gnutls_ocsp_resp_get_nonce(gnutls_ocsp_resp_const_t resp,
unsigned int *critical,
gnutls_datum_t * nonce);
int gnutls_ocsp_resp_get_signature_algorithm(gnutls_ocsp_resp_const_t resp);
int gnutls_ocsp_resp_get_signature(gnutls_ocsp_resp_const_t resp,
gnutls_datum_t * sig);
int gnutls_ocsp_resp_get_certs(gnutls_ocsp_resp_const_t resp,
gnutls_x509_crt_t ** certs,
size_t * ncerts);
int gnutls_ocsp_resp_verify_direct(gnutls_ocsp_resp_const_t resp,
gnutls_x509_crt_t issuer,
unsigned int *verify,
unsigned int flags);
int gnutls_ocsp_resp_verify(gnutls_ocsp_resp_const_t resp,
gnutls_x509_trust_list_t trustlist,
unsigned int *verify, unsigned int flags);
int gnutls_ocsp_resp_check_crt(gnutls_ocsp_resp_const_t resp,
unsigned int indx, gnutls_x509_crt_t crt);
int
gnutls_ocsp_resp_list_import2(gnutls_ocsp_resp_t **ocsps,
unsigned int *size,
const gnutls_datum_t *resp_data,
gnutls_x509_crt_fmt_t format,
unsigned int flags);
/* *INDENT-OFF* */
#ifdef __cplusplus
}
#endif
/* *INDENT-ON* */
#endif /* GNUTLS_OCSP_H */
| 10,395
|
C++
|
.h
| 260
| 36.653846
| 84
| 0.740847
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
22,446
|
dtls.h
|
Nevcairiel_LAVFilters/thirdparty/32/include/gnutls/dtls.h
|
/*
* Copyright (C) 2011-2012 Free Software Foundation, Inc.
*
* Author: Nikos Mavrogiannopoulos
*
* This file is part of GnuTLS.
*
* The GnuTLS 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.
*
* 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 program. If not, see <https://www.gnu.org/licenses/>
*
*/
/* This file contains the types and prototypes for the X.509
* certificate and CRL handling functions.
*/
#ifndef GNUTLS_DTLS_H
#define GNUTLS_DTLS_H
#include <gnutls/gnutls.h>
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
#define GNUTLS_COOKIE_KEY_SIZE 16
void gnutls_dtls_set_timeouts(gnutls_session_t session,
unsigned int retrans_timeout,
unsigned int total_timeout);
unsigned int gnutls_dtls_get_mtu(gnutls_session_t session);
unsigned int gnutls_dtls_get_data_mtu(gnutls_session_t session);
void gnutls_dtls_set_mtu(gnutls_session_t session, unsigned int mtu);
int gnutls_dtls_set_data_mtu(gnutls_session_t session, unsigned int mtu);
unsigned int gnutls_dtls_get_timeout(gnutls_session_t session);
/**
* gnutls_dtls_prestate_st:
* @record_seq: record sequence number
* @hsk_read_seq: handshake read sequence number
* @hsk_write_seq: handshake write sequence number
*
* DTLS cookie prestate struct. This is usually never modified by
* the application, it is used to carry the cookie data between
* gnutls_dtls_cookie_send(), gnutls_dtls_cookie_verify() and
* gnutls_dtls_prestate_set().
*/
typedef struct {
unsigned int record_seq;
unsigned int hsk_read_seq;
unsigned int hsk_write_seq;
} gnutls_dtls_prestate_st;
int gnutls_dtls_cookie_send(gnutls_datum_t * key,
void *client_data,
size_t client_data_size,
gnutls_dtls_prestate_st * prestate,
gnutls_transport_ptr_t ptr,
gnutls_push_func push_func);
int gnutls_dtls_cookie_verify(gnutls_datum_t * key,
void *client_data,
size_t client_data_size, void *_msg,
size_t msg_size,
gnutls_dtls_prestate_st * prestate);
void gnutls_dtls_prestate_set(gnutls_session_t session,
gnutls_dtls_prestate_st * prestate);
unsigned int gnutls_record_get_discarded(gnutls_session_t session);
/* *INDENT-OFF* */
#ifdef __cplusplus
}
#endif
/* *INDENT-ON* */
#endif /* GNUTLS_DTLS_H */
| 2,793
|
C++
|
.h
| 77
| 33.337662
| 75
| 0.738519
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| false
| false
| false
| false
| false
| false
|
22,447
|
x509-ext.h
|
Nevcairiel_LAVFilters/thirdparty/32/include/gnutls/x509-ext.h
|
/*
* Copyright (C) 2014 Free Software Foundation, Inc.
*
* Author: Nikos Mavrogiannopoulos
*
* This file is part of GnuTLS.
*
* The GnuTLS 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.
*
* 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 program. If not, see <https://www.gnu.org/licenses/>
*
*/
/* Prototypes for direct handling of extension data */
#ifndef GNUTLS_X509_EXT_H
#define GNUTLS_X509_EXT_H
#include <gnutls/gnutls.h>
#include <gnutls/x509.h>
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
typedef struct gnutls_subject_alt_names_st *gnutls_subject_alt_names_t;
int gnutls_subject_alt_names_init(gnutls_subject_alt_names_t *);
void gnutls_subject_alt_names_deinit(gnutls_subject_alt_names_t sans);
int gnutls_subject_alt_names_get(gnutls_subject_alt_names_t sans, unsigned int seq,
unsigned int *san_type, gnutls_datum_t * san,
gnutls_datum_t * othername_oid);
int gnutls_subject_alt_names_set(gnutls_subject_alt_names_t sans,
unsigned int san_type,
const gnutls_datum_t * san,
const char* othername_oid);
int gnutls_x509_ext_import_subject_alt_names(const gnutls_datum_t * ext,
gnutls_subject_alt_names_t,
unsigned int flags);
int gnutls_x509_ext_export_subject_alt_names(gnutls_subject_alt_names_t,
gnutls_datum_t * ext);
/* They are exactly the same */
#define gnutls_x509_ext_import_issuer_alt_name gnutls_x509_ext_import_subject_alt_name
#define gnutls_x509_ext_export_issuer_alt_name gnutls_x509_ext_export_subject_alt_name
typedef struct gnutls_x509_crl_dist_points_st *gnutls_x509_crl_dist_points_t;
int gnutls_x509_crl_dist_points_init(gnutls_x509_crl_dist_points_t *);
void gnutls_x509_crl_dist_points_deinit(gnutls_x509_crl_dist_points_t);
int gnutls_x509_crl_dist_points_get(gnutls_x509_crl_dist_points_t, unsigned int seq,
unsigned int *type,
gnutls_datum_t *dist, unsigned int *reason_flags);
int gnutls_x509_crl_dist_points_set(gnutls_x509_crl_dist_points_t,
gnutls_x509_subject_alt_name_t type,
const gnutls_datum_t *dist, unsigned int reason_flags);
int gnutls_x509_ext_import_crl_dist_points(const gnutls_datum_t * ext,
gnutls_x509_crl_dist_points_t dp,
unsigned int flags);
int gnutls_x509_ext_export_crl_dist_points(gnutls_x509_crl_dist_points_t dp,
gnutls_datum_t * ext);
int gnutls_x509_ext_import_name_constraints(const gnutls_datum_t * ext,
gnutls_x509_name_constraints_t nc,
unsigned int flags);
int gnutls_x509_ext_export_name_constraints(gnutls_x509_name_constraints_t nc,
gnutls_datum_t * ext);
typedef struct gnutls_x509_aia_st *gnutls_x509_aia_t;
int gnutls_x509_aia_init(gnutls_x509_aia_t *);
void gnutls_x509_aia_deinit(gnutls_x509_aia_t);
int gnutls_x509_aia_get(gnutls_x509_aia_t aia, unsigned int seq,
gnutls_datum_t *oid,
unsigned *san_type,
gnutls_datum_t *san);
int gnutls_x509_aia_set(gnutls_x509_aia_t aia,
const char *oid,
unsigned san_type,
const gnutls_datum_t * san);
int gnutls_x509_ext_import_aia(const gnutls_datum_t * ext,
gnutls_x509_aia_t,
unsigned int flags);
int gnutls_x509_ext_export_aia(gnutls_x509_aia_t aia,
gnutls_datum_t * ext);
int gnutls_x509_ext_import_subject_key_id(const gnutls_datum_t * ext,
gnutls_datum_t * id);
int gnutls_x509_ext_export_subject_key_id(const gnutls_datum_t * id,
gnutls_datum_t * ext);
typedef struct gnutls_x509_aki_st *gnutls_x509_aki_t;
int gnutls_x509_ext_export_authority_key_id(gnutls_x509_aki_t,
gnutls_datum_t * ext);
int gnutls_x509_ext_import_authority_key_id(const gnutls_datum_t * ext,
gnutls_x509_aki_t,
unsigned int flags);
int gnutls_x509_othername_to_virtual(const char *oid,
const gnutls_datum_t *othername,
unsigned int *virt_type,
gnutls_datum_t *virt);
int gnutls_x509_aki_init(gnutls_x509_aki_t *);
int gnutls_x509_aki_get_id(gnutls_x509_aki_t, gnutls_datum_t *id);
int gnutls_x509_aki_get_cert_issuer(gnutls_x509_aki_t aki, unsigned int seq,
unsigned int *san_type, gnutls_datum_t * san,
gnutls_datum_t *othername_oid,
gnutls_datum_t *serial);
int gnutls_x509_aki_set_id(gnutls_x509_aki_t aki, const gnutls_datum_t *id);
int gnutls_x509_aki_set_cert_issuer(gnutls_x509_aki_t aki,
unsigned int san_type,
const gnutls_datum_t * san,
const char *othername_oid,
const gnutls_datum_t * serial);
void gnutls_x509_aki_deinit(gnutls_x509_aki_t);
int gnutls_x509_ext_import_private_key_usage_period(const gnutls_datum_t * ext,
time_t * activation,
time_t * expiration);
int gnutls_x509_ext_export_private_key_usage_period(time_t activation,
time_t expiration,
gnutls_datum_t * ext);
int gnutls_x509_ext_import_basic_constraints(const gnutls_datum_t * ext,
unsigned int *ca, int *pathlen);
int gnutls_x509_ext_export_basic_constraints(unsigned int ca, int pathlen,
gnutls_datum_t * ext);
typedef struct gnutls_x509_key_purposes_st *gnutls_x509_key_purposes_t;
int gnutls_x509_key_purpose_init(gnutls_x509_key_purposes_t *p);
void gnutls_x509_key_purpose_deinit(gnutls_x509_key_purposes_t p);
int gnutls_x509_key_purpose_set(gnutls_x509_key_purposes_t p, const char *oid);
int gnutls_x509_key_purpose_get(gnutls_x509_key_purposes_t p, unsigned idx, gnutls_datum_t *oid);
int gnutls_x509_ext_import_key_purposes(const gnutls_datum_t * ext,
gnutls_x509_key_purposes_t,
unsigned int flags);
int gnutls_x509_ext_export_key_purposes(gnutls_x509_key_purposes_t,
gnutls_datum_t * ext);
int gnutls_x509_ext_import_key_usage(const gnutls_datum_t * ext,
unsigned int *key_usage);
int gnutls_x509_ext_export_key_usage(unsigned int key_usage,
gnutls_datum_t * ext);
int gnutls_x509_ext_import_inhibit_anypolicy(const gnutls_datum_t * ext,
unsigned int *skipcerts);
int gnutls_x509_ext_export_inhibit_anypolicy(unsigned int skipcerts,
gnutls_datum_t * ext);
int gnutls_x509_ext_import_proxy(const gnutls_datum_t * ext, int *pathlen,
char **policyLanguage, char **policy,
size_t * sizeof_policy);
int gnutls_x509_ext_export_proxy(int pathLenConstraint, const char *policyLanguage,
const char *policy, size_t sizeof_policy,
gnutls_datum_t * ext);
typedef struct gnutls_x509_policies_st *gnutls_x509_policies_t;
int gnutls_x509_policies_init(gnutls_x509_policies_t *);
void gnutls_x509_policies_deinit(gnutls_x509_policies_t);
int gnutls_x509_policies_get(gnutls_x509_policies_t policies, unsigned int seq,
struct gnutls_x509_policy_st *policy);
int gnutls_x509_policies_set(gnutls_x509_policies_t policies,
const struct gnutls_x509_policy_st *policy);
int gnutls_x509_ext_import_policies(const gnutls_datum_t * ext, gnutls_x509_policies_t
policies,
unsigned int flags);
int gnutls_x509_ext_export_policies(gnutls_x509_policies_t policies,
gnutls_datum_t * ext);
int gnutls_x509_ext_import_tlsfeatures(const gnutls_datum_t * ext,
gnutls_x509_tlsfeatures_t,
unsigned int flags);
int gnutls_x509_ext_export_tlsfeatures(gnutls_x509_tlsfeatures_t f,
gnutls_datum_t * ext);
int gnutls_x509_tlsfeatures_add(gnutls_x509_tlsfeatures_t f, unsigned int feature);
typedef struct gnutls_x509_ct_scts_st *gnutls_x509_ct_scts_t;
int gnutls_x509_ext_ct_scts_init(gnutls_x509_ct_scts_t * scts);
void gnutls_x509_ext_ct_scts_deinit(gnutls_x509_ct_scts_t scts);
int gnutls_x509_ext_ct_import_scts(const gnutls_datum_t * ext,
gnutls_x509_ct_scts_t scts, unsigned int flags);
int gnutls_x509_ext_ct_export_scts(const gnutls_x509_ct_scts_t scts, gnutls_datum_t * ext);
int gnutls_x509_ct_sct_get_version(const gnutls_x509_ct_scts_t scts, unsigned idx,
unsigned int *version_out);
int gnutls_x509_ct_sct_get(const gnutls_x509_ct_scts_t scts,
unsigned idx,
time_t *timestamp,
gnutls_datum_t *logid,
gnutls_sign_algorithm_t *sigalg,
gnutls_datum_t *signature);
/* *INDENT-OFF* */
#ifdef __cplusplus
}
#endif
/* *INDENT-ON* */
#endif /* GNUTLS_X509_EXT_H */
| 8,576
|
C++
|
.h
| 183
| 42.961749
| 97
| 0.73647
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,448
|
pkcs11.h
|
Nevcairiel_LAVFilters/thirdparty/32/include/gnutls/pkcs11.h
|
/*
* Copyright (C) 2010-2012 Free Software Foundation, Inc.
* Copyright (C) 2016-2018 Red Hat, Inc.
*
* Author: Nikos Mavrogiannopoulos
*
* This file is part of GnuTLS.
*
* The GnuTLS 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.
*
* 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 program. If not, see <https://www.gnu.org/licenses/>
*
*/
#ifndef GNUTLS_PKCS11_H
#define GNUTLS_PKCS11_H
#include <stdarg.h>
#include <gnutls/gnutls.h>
#include <gnutls/x509.h>
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
#define GNUTLS_PKCS11_MAX_PIN_LEN 256
/**
* gnutls_pkcs11_token_callback_t:
* @userdata: user-controlled data from gnutls_pkcs11_set_token_function().
* @label: token label.
* @retry: retry counter, initially 0.
*
* Token callback function. The callback will be used to ask the user
* to re-insert the token with given (null terminated) label. The
* callback should return zero if token has been inserted by user and
* a negative error code otherwise. It might be called multiple times
* if the token is not detected and the retry counter will be
* increased.
*
* Returns: %GNUTLS_E_SUCCESS (0) on success or a negative error code
* on error.
*
* Since: 2.12.0
**/
typedef int (*gnutls_pkcs11_token_callback_t) (void *const
userdata,
const char *const
label, unsigned retry);
struct gnutls_pkcs11_obj_st;
typedef struct gnutls_pkcs11_obj_st *gnutls_pkcs11_obj_t;
#define GNUTLS_PKCS11_FLAG_MANUAL 0 /* Manual loading of libraries */
#define GNUTLS_PKCS11_FLAG_AUTO 1 /* Automatically load libraries by reading /etc/gnutls/pkcs11.conf */
#define GNUTLS_PKCS11_FLAG_AUTO_TRUSTED (1<<1) /* Automatically load trusted libraries by reading /etc/gnutls/pkcs11.conf */
/* pkcs11.conf format:
* load = /lib/xxx-pkcs11.so
* load = /lib/yyy-pkcs11.so
*/
int gnutls_pkcs11_init(unsigned int flags,
const char *deprecated_config_file);
int gnutls_pkcs11_reinit(void);
void gnutls_pkcs11_deinit(void);
void gnutls_pkcs11_set_token_function
(gnutls_pkcs11_token_callback_t fn, void *userdata);
void gnutls_pkcs11_set_pin_function(gnutls_pin_callback_t fn,
void *userdata);
gnutls_pin_callback_t gnutls_pkcs11_get_pin_function(void
**userdata);
int gnutls_pkcs11_add_provider(const char *name, const char *params);
int gnutls_pkcs11_obj_init(gnutls_pkcs11_obj_t * obj);
void gnutls_pkcs11_obj_set_pin_function(gnutls_pkcs11_obj_t obj,
gnutls_pin_callback_t fn,
void *userdata);
/**
* gnutls_pkcs11_obj_flags:
* @GNUTLS_PKCS11_OBJ_FLAG_LOGIN: Force login in the token for the operation (seek+store).
* @GNUTLS_PKCS11_OBJ_FLAG_MARK_TRUSTED: object marked as trusted (seek+store).
* @GNUTLS_PKCS11_OBJ_FLAG_MARK_SENSITIVE: object is explicitly marked as sensitive -unexportable (store).
* @GNUTLS_PKCS11_OBJ_FLAG_LOGIN_SO: force login as a security officer in the token for the operation (seek+store).
* @GNUTLS_PKCS11_OBJ_FLAG_MARK_PRIVATE: marked as private -requires PIN to access (store).
* @GNUTLS_PKCS11_OBJ_FLAG_MARK_NOT_PRIVATE: marked as not private (store).
* @GNUTLS_PKCS11_OBJ_FLAG_RETRIEVE_ANY: When retrieving an object, do not set any requirements (store).
* @GNUTLS_PKCS11_OBJ_FLAG_RETRIEVE_TRUSTED: When retrieving an object, only retrieve the marked as trusted (alias to %GNUTLS_PKCS11_OBJ_FLAG_MARK_TRUSTED).
* In gnutls_pkcs11_crt_is_known() it implies %GNUTLS_PKCS11_OBJ_FLAG_RETRIEVE_COMPARE if %GNUTLS_PKCS11_OBJ_FLAG_COMPARE_KEY is not given.
* @GNUTLS_PKCS11_OBJ_FLAG_MARK_DISTRUSTED: When writing an object, mark it as distrusted (store).
* @GNUTLS_PKCS11_OBJ_FLAG_RETRIEVE_DISTRUSTED: When retrieving an object, only retrieve the marked as distrusted (seek).
* @GNUTLS_PKCS11_OBJ_FLAG_COMPARE: When checking an object's presence, fully compare it before returning any result (seek).
* @GNUTLS_PKCS11_OBJ_FLAG_COMPARE_KEY: When checking an object's presence, compare the key before returning any result (seek).
* @GNUTLS_PKCS11_OBJ_FLAG_PRESENT_IN_TRUSTED_MODULE: The object must be present in a marked as trusted module (seek).
* @GNUTLS_PKCS11_OBJ_FLAG_MARK_CA: Mark the object as a CA (seek+store).
* @GNUTLS_PKCS11_OBJ_FLAG_MARK_KEY_WRAP: Mark the generated key pair as wrapping and unwrapping keys (store).
* @GNUTLS_PKCS11_OBJ_FLAG_OVERWRITE_TRUSTMOD_EXT: When an issuer is requested, override its extensions with the ones present in the trust module (seek).
* @GNUTLS_PKCS11_OBJ_FLAG_MARK_ALWAYS_AUTH: Mark the key pair as requiring authentication (pin entry) before every operation (seek+store).
* @GNUTLS_PKCS11_OBJ_FLAG_MARK_EXTRACTABLE: Mark the key pair as being extractable (store).
* @GNUTLS_PKCS11_OBJ_FLAG_NEVER_EXTRACTABLE: If set, the object was never marked as extractable (store).
* @GNUTLS_PKCS11_OBJ_FLAG_CRT: When searching, restrict to certificates only (seek).
* @GNUTLS_PKCS11_OBJ_FLAG_PUBKEY: When searching, restrict to public key objects only (seek).
* @GNUTLS_PKCS11_OBJ_FLAG_PRIVKEY: When searching, restrict to private key objects only (seek).
* @GNUTLS_PKCS11_OBJ_FLAG_NO_STORE_PUBKEY: When generating a keypair don't store the public key (store).
* @GNUTLS_PKCS11_OBJ_FLAG_MARK_NOT_SENSITIVE: object marked as not sensitive -exportable (store).
*
* Enumeration of different PKCS #11 object flags. Some flags are used
* to mark objects when storing, while others are also used while seeking
* or retrieving objects.
*/
typedef enum gnutls_pkcs11_obj_flags {
GNUTLS_PKCS11_OBJ_FLAG_LOGIN = (1<<0),
GNUTLS_PKCS11_OBJ_FLAG_MARK_TRUSTED = (1<<1),
GNUTLS_PKCS11_OBJ_FLAG_MARK_SENSITIVE = (1<<2),
GNUTLS_PKCS11_OBJ_FLAG_LOGIN_SO = (1<<3),
GNUTLS_PKCS11_OBJ_FLAG_MARK_PRIVATE = (1<<4),
GNUTLS_PKCS11_OBJ_FLAG_MARK_NOT_PRIVATE = (1<<5),
GNUTLS_PKCS11_OBJ_FLAG_RETRIEVE_ANY = (1<<6),
GNUTLS_PKCS11_OBJ_FLAG_RETRIEVE_TRUSTED = GNUTLS_PKCS11_OBJ_FLAG_MARK_TRUSTED,
GNUTLS_PKCS11_OBJ_FLAG_MARK_DISTRUSTED = (1<<8),
GNUTLS_PKCS11_OBJ_FLAG_RETRIEVE_DISTRUSTED = GNUTLS_PKCS11_OBJ_FLAG_MARK_DISTRUSTED,
GNUTLS_PKCS11_OBJ_FLAG_COMPARE = (1<<9),
GNUTLS_PKCS11_OBJ_FLAG_PRESENT_IN_TRUSTED_MODULE = (1<<10),
GNUTLS_PKCS11_OBJ_FLAG_MARK_CA = (1<<11),
GNUTLS_PKCS11_OBJ_FLAG_MARK_KEY_WRAP = (1<<12),
GNUTLS_PKCS11_OBJ_FLAG_COMPARE_KEY = (1<<13),
GNUTLS_PKCS11_OBJ_FLAG_OVERWRITE_TRUSTMOD_EXT = (1<<14),
GNUTLS_PKCS11_OBJ_FLAG_MARK_ALWAYS_AUTH = (1<<15),
GNUTLS_PKCS11_OBJ_FLAG_MARK_EXTRACTABLE = (1<<16),
GNUTLS_PKCS11_OBJ_FLAG_NEVER_EXTRACTABLE = (1<<17),
GNUTLS_PKCS11_OBJ_FLAG_CRT = (1<<18),
GNUTLS_PKCS11_OBJ_FLAG_WITH_PRIVKEY = (1<<19),
GNUTLS_PKCS11_OBJ_FLAG_PUBKEY = (1<<20),
GNUTLS_PKCS11_OBJ_FLAG_NO_STORE_PUBKEY = GNUTLS_PKCS11_OBJ_FLAG_PUBKEY,
GNUTLS_PKCS11_OBJ_FLAG_PRIVKEY = (1<<21),
GNUTLS_PKCS11_OBJ_FLAG_MARK_NOT_SENSITIVE = (1<<22),
/* flags 1<<29 and later are reserved - see pkcs11_int.h */
} gnutls_pkcs11_obj_flags;
#define gnutls_pkcs11_obj_attr_t gnutls_pkcs11_obj_flags
/**
* gnutls_pkcs11_url_type_t:
* @GNUTLS_PKCS11_URL_GENERIC: A generic-purpose URL.
* @GNUTLS_PKCS11_URL_LIB: A URL that specifies the library used as well.
* @GNUTLS_PKCS11_URL_LIB_VERSION: A URL that specifies the library and its version.
*
* Enumeration of different URL extraction flags.
*/
typedef enum {
GNUTLS_PKCS11_URL_GENERIC, /* URL specifies the object on token level */
GNUTLS_PKCS11_URL_LIB, /* URL specifies the object on module level */
GNUTLS_PKCS11_URL_LIB_VERSION /* URL specifies the object on module and version level */
} gnutls_pkcs11_url_type_t;
int gnutls_pkcs11_obj_import_url(gnutls_pkcs11_obj_t obj,
const char *url, unsigned int flags
/* GNUTLS_PKCS11_OBJ_FLAG_* */ );
int gnutls_pkcs11_obj_export_url(gnutls_pkcs11_obj_t obj,
gnutls_pkcs11_url_type_t detailed,
char **url);
void gnutls_pkcs11_obj_deinit(gnutls_pkcs11_obj_t obj);
int gnutls_pkcs11_obj_export(gnutls_pkcs11_obj_t obj,
void *output_data, size_t * output_data_size);
int gnutls_pkcs11_obj_export2(gnutls_pkcs11_obj_t obj,
gnutls_datum_t * out);
int gnutls_pkcs11_obj_export3(gnutls_pkcs11_obj_t obj, gnutls_x509_crt_fmt_t fmt,
gnutls_datum_t * out);
int gnutls_pkcs11_get_raw_issuer(const char *url, gnutls_x509_crt_t cert,
gnutls_datum_t * issuer,
gnutls_x509_crt_fmt_t fmt,
unsigned int flags);
int gnutls_pkcs11_get_raw_issuer_by_dn (const char *url, const gnutls_datum_t *dn,
gnutls_datum_t *issuer,
gnutls_x509_crt_fmt_t fmt,
unsigned int flags);
int gnutls_pkcs11_get_raw_issuer_by_subject_key_id (const char *url,
const gnutls_datum_t *dn,
const gnutls_datum_t *spki,
gnutls_datum_t *issuer,
gnutls_x509_crt_fmt_t fmt,
unsigned int flags);
unsigned gnutls_pkcs11_crt_is_known(const char *url, gnutls_x509_crt_t cert,
unsigned int flags);
#if 0
/* for documentation */
int gnutls_pkcs11_copy_x509_crt(const char *token_url,
gnutls_x509_crt_t crt,
const char *label, unsigned int flags
/* GNUTLS_PKCS11_OBJ_FLAG_* */ );
int gnutls_pkcs11_copy_x509_privkey(const char *token_url,
gnutls_x509_privkey_t key,
const char *label,
unsigned int key_usage,
unsigned int flags);
int
gnutls_pkcs11_privkey_generate2(const char *url, gnutls_pk_algorithm_t pk,
unsigned int bits, const char *label,
gnutls_x509_crt_fmt_t fmt,
gnutls_datum_t * pubkey,
unsigned int flags);
int
gnutls_pkcs11_privkey_generate(const char *url, gnutls_pk_algorithm_t pk,
unsigned int bits, const char *label,
unsigned int flags);
#endif
int
gnutls_pkcs11_copy_pubkey(const char *token_url,
gnutls_pubkey_t crt, const char *label,
const gnutls_datum_t *cid,
unsigned int key_usage, unsigned int flags);
#define gnutls_pkcs11_copy_x509_crt(url, crt, label, flags) \
gnutls_pkcs11_copy_x509_crt2(url, crt, label, NULL, flags)
int gnutls_pkcs11_copy_x509_crt2(const char *token_url,
gnutls_x509_crt_t crt,
const char *label,
const gnutls_datum_t *id,
unsigned int flags /* GNUTLS_PKCS11_OBJ_FLAG_* */);
#define gnutls_pkcs11_copy_x509_privkey(url, key, label, usage, flags) \
gnutls_pkcs11_copy_x509_privkey2(url, key, label, NULL, usage, flags)
int gnutls_pkcs11_copy_x509_privkey2(const char *token_url,
gnutls_x509_privkey_t key,
const char *label,
const gnutls_datum_t *cid,
unsigned int key_usage
/*GNUTLS_KEY_* */ ,
unsigned int flags
/* GNUTLS_PKCS11_OBJ_FLAG_* */
);
int gnutls_pkcs11_delete_url(const char *object_url, unsigned int flags
/* GNUTLS_PKCS11_OBJ_FLAG_* */ );
int gnutls_pkcs11_copy_secret_key(const char *token_url,
gnutls_datum_t * key,
const char *label, unsigned int key_usage
/* GNUTLS_KEY_* */ ,
unsigned int flags
/* GNUTLS_PKCS11_OBJ_FLAG_* */ );
/**
* gnutls_pkcs11_obj_info_t:
* @GNUTLS_PKCS11_OBJ_ID_HEX: The object ID in hex. Null-terminated text.
* @GNUTLS_PKCS11_OBJ_LABEL: The object label. Null-terminated text.
* @GNUTLS_PKCS11_OBJ_TOKEN_LABEL: The token's label. Null-terminated text.
* @GNUTLS_PKCS11_OBJ_TOKEN_SERIAL: The token's serial number. Null-terminated text.
* @GNUTLS_PKCS11_OBJ_TOKEN_MANUFACTURER: The token's manufacturer. Null-terminated text.
* @GNUTLS_PKCS11_OBJ_TOKEN_MODEL: The token's model. Null-terminated text.
* @GNUTLS_PKCS11_OBJ_ID: The object ID. Raw bytes.
* @GNUTLS_PKCS11_OBJ_LIBRARY_VERSION: The library's version. Null-terminated text.
* @GNUTLS_PKCS11_OBJ_LIBRARY_DESCRIPTION: The library's description. Null-terminated text.
* @GNUTLS_PKCS11_OBJ_LIBRARY_MANUFACTURER: The library's manufacturer name. Null-terminated text.
*
* Enumeration of several object information types.
*/
typedef enum {
GNUTLS_PKCS11_OBJ_ID_HEX = 1,
GNUTLS_PKCS11_OBJ_LABEL,
GNUTLS_PKCS11_OBJ_TOKEN_LABEL,
GNUTLS_PKCS11_OBJ_TOKEN_SERIAL,
GNUTLS_PKCS11_OBJ_TOKEN_MANUFACTURER,
GNUTLS_PKCS11_OBJ_TOKEN_MODEL,
GNUTLS_PKCS11_OBJ_ID,
/* the pkcs11 provider library info */
GNUTLS_PKCS11_OBJ_LIBRARY_VERSION,
GNUTLS_PKCS11_OBJ_LIBRARY_DESCRIPTION,
GNUTLS_PKCS11_OBJ_LIBRARY_MANUFACTURER
} gnutls_pkcs11_obj_info_t;
int
gnutls_pkcs11_obj_get_ptr(gnutls_pkcs11_obj_t obj, void **ptr,
void **session, void **ohandle,
unsigned long *slot_id,
unsigned int flags);
int gnutls_pkcs11_obj_get_info(gnutls_pkcs11_obj_t obj,
gnutls_pkcs11_obj_info_t itype,
void *output, size_t * output_size);
int gnutls_pkcs11_obj_set_info(gnutls_pkcs11_obj_t obj,
gnutls_pkcs11_obj_info_t itype,
const void *data, size_t data_size,
unsigned flags);
#define GNUTLS_PKCS11_OBJ_ATTR_CRT_ALL GNUTLS_PKCS11_OBJ_FLAG_CRT
#define GNUTLS_PKCS11_OBJ_ATTR_MATCH 0 /* always match the given URL */
#define GNUTLS_PKCS11_OBJ_ATTR_ALL 0 /* match everything! */
#define GNUTLS_PKCS11_OBJ_ATTR_CRT_TRUSTED (GNUTLS_PKCS11_OBJ_FLAG_CRT|GNUTLS_PKCS11_OBJ_FLAG_MARK_TRUSTED)
#define GNUTLS_PKCS11_OBJ_ATTR_CRT_WITH_PRIVKEY (GNUTLS_PKCS11_OBJ_FLAG_CRT|GNUTLS_PKCS11_OBJ_FLAG_WITH_PRIVKEY)
#define GNUTLS_PKCS11_OBJ_ATTR_CRT_TRUSTED_CA (GNUTLS_PKCS11_OBJ_FLAG_CRT|GNUTLS_PKCS11_OBJ_FLAG_MARK_CA|GNUTLS_PKCS11_OBJ_FLAG_MARK_TRUSTED)
#define GNUTLS_PKCS11_OBJ_ATTR_PUBKEY GNUTLS_PKCS11_OBJ_FLAG_PUBKEY
#define GNUTLS_PKCS11_OBJ_ATTR_PRIVKEY GNUTLS_PKCS11_OBJ_FLAG_PRIVKEY
/**
* gnutls_pkcs11_token_info_t:
* @GNUTLS_PKCS11_TOKEN_LABEL: The token's label (string)
* @GNUTLS_PKCS11_TOKEN_SERIAL: The token's serial number (string)
* @GNUTLS_PKCS11_TOKEN_MANUFACTURER: The token's manufacturer (string)
* @GNUTLS_PKCS11_TOKEN_MODEL: The token's model (string)
* @GNUTLS_PKCS11_TOKEN_MODNAME: The token's module name (string - since 3.4.3). This value is
* unavailable for providers which were manually loaded.
*
* Enumeration of types for retrieving token information.
*/
typedef enum {
GNUTLS_PKCS11_TOKEN_LABEL,
GNUTLS_PKCS11_TOKEN_SERIAL,
GNUTLS_PKCS11_TOKEN_MANUFACTURER,
GNUTLS_PKCS11_TOKEN_MODEL,
GNUTLS_PKCS11_TOKEN_MODNAME
} gnutls_pkcs11_token_info_t;
/**
* gnutls_pkcs11_obj_type_t:
* @GNUTLS_PKCS11_OBJ_UNKNOWN: Unknown PKCS11 object.
* @GNUTLS_PKCS11_OBJ_X509_CRT: X.509 certificate.
* @GNUTLS_PKCS11_OBJ_PUBKEY: Public key.
* @GNUTLS_PKCS11_OBJ_PRIVKEY: Private key.
* @GNUTLS_PKCS11_OBJ_SECRET_KEY: Secret key.
* @GNUTLS_PKCS11_OBJ_DATA: Data object.
* @GNUTLS_PKCS11_OBJ_X509_CRT_EXTENSION: X.509 certificate extension (supported by p11-kit trust module only).
*
* Enumeration of object types.
*/
typedef enum {
GNUTLS_PKCS11_OBJ_UNKNOWN,
GNUTLS_PKCS11_OBJ_X509_CRT,
GNUTLS_PKCS11_OBJ_PUBKEY,
GNUTLS_PKCS11_OBJ_PRIVKEY,
GNUTLS_PKCS11_OBJ_SECRET_KEY,
GNUTLS_PKCS11_OBJ_DATA,
GNUTLS_PKCS11_OBJ_X509_CRT_EXTENSION
} gnutls_pkcs11_obj_type_t;
int
gnutls_pkcs11_token_init(const char *token_url,
const char *so_pin, const char *label);
int
gnutls_pkcs11_token_get_ptr(const char *url, void **ptr, unsigned long *slot_id,
unsigned int flags);
int
gnutls_pkcs11_token_get_mechanism(const char *url,
unsigned int idx,
unsigned long *mechanism);
unsigned
gnutls_pkcs11_token_check_mechanism(const char *url,
unsigned long mechanism,
void *ptr, unsigned psize, unsigned flags);
int gnutls_pkcs11_token_set_pin(const char *token_url, const char *oldpin, const char *newpin, unsigned int flags /*gnutls_pin_flag_t */);
int gnutls_pkcs11_token_get_url(unsigned int seq,
gnutls_pkcs11_url_type_t detailed,
char **url);
int gnutls_pkcs11_token_get_info(const char *url,
gnutls_pkcs11_token_info_t ttype,
void *output, size_t * output_size);
#define GNUTLS_PKCS11_TOKEN_HW 1
#define GNUTLS_PKCS11_TOKEN_TRUSTED (1<<1) /* p11-kit trusted */
#define GNUTLS_PKCS11_TOKEN_RNG (1<<2) /* CKF_RNG */
#define GNUTLS_PKCS11_TOKEN_LOGIN_REQUIRED (1<<3) /* CKF_LOGIN_REQUIRED */
#define GNUTLS_PKCS11_TOKEN_PROTECTED_AUTHENTICATION_PATH (1<<4) /* CKF_PROTECTED_AUTHENTICATION_PATH */
#define GNUTLS_PKCS11_TOKEN_INITIALIZED (1<<5) /* CKF_TOKEN_INITIALIZED */
#define GNUTLS_PKCS11_TOKEN_USER_PIN_COUNT_LOW (1<<6) /* CKF_USER_PIN_COUNT_LOW */
#define GNUTLS_PKCS11_TOKEN_USER_PIN_FINAL_TRY (1<<7) /* CKF_USER_PIN_FINAL_TRY */
#define GNUTLS_PKCS11_TOKEN_USER_PIN_LOCKED (1<<8) /* CKF_USER_PIN_LOCKED */
#define GNUTLS_PKCS11_TOKEN_SO_PIN_COUNT_LOW (1<<9) /* CKF_SO_PIN_COUNT_LOW */
#define GNUTLS_PKCS11_TOKEN_SO_PIN_FINAL_TRY (1<<10) /* CKF_SO_PIN_FINAL_TRY */
#define GNUTLS_PKCS11_TOKEN_SO_PIN_LOCKED (1<<11) /* CKF_SO_PIN_LOCKED */
#define GNUTLS_PKCS11_TOKEN_USER_PIN_INITIALIZED (1<<12) /* CKF_USER_PIN_INITIALIZED */
#define GNUTLS_PKCS11_TOKEN_ERROR_STATE (1<<13) /* CKF_ERROR_STATE */
int gnutls_pkcs11_token_get_flags(const char *url, unsigned int *flags);
#define gnutls_pkcs11_obj_list_import_url(p_list, n_list, url, attrs, flags) gnutls_pkcs11_obj_list_import_url3(p_list, n_list, url, attrs|flags)
#define gnutls_pkcs11_obj_list_import_url2(p_list, n_list, url, attrs, flags) gnutls_pkcs11_obj_list_import_url4(p_list, n_list, url, attrs|flags)
int gnutls_pkcs11_obj_list_import_url3(gnutls_pkcs11_obj_t * p_list,
unsigned int *const n_list,
const char *url,
unsigned int flags
/* GNUTLS_PKCS11_OBJ_FLAG_* */
);
int
gnutls_pkcs11_obj_list_import_url4(gnutls_pkcs11_obj_t ** p_list,
unsigned int *n_list,
const char *url,
unsigned int flags
/* GNUTLS_PKCS11_OBJ_FLAG_* */
);
int gnutls_x509_crt_import_pkcs11(gnutls_x509_crt_t crt,
gnutls_pkcs11_obj_t pkcs11_crt);
gnutls_pkcs11_obj_type_t
gnutls_pkcs11_obj_get_type(gnutls_pkcs11_obj_t obj);
const char *gnutls_pkcs11_type_get_name(gnutls_pkcs11_obj_type_t type);
int
gnutls_pkcs11_obj_get_exts(gnutls_pkcs11_obj_t obj,
struct gnutls_x509_ext_st **exts, unsigned int *exts_size,
unsigned int flags);
int
gnutls_pkcs11_obj_get_flags(gnutls_pkcs11_obj_t obj, unsigned int *oflags);
char *gnutls_pkcs11_obj_flags_get_str(unsigned int flags);
int gnutls_x509_crt_list_import_pkcs11(gnutls_x509_crt_t * certs,
unsigned int cert_max,
gnutls_pkcs11_obj_t *
const objs, unsigned int flags
/* must be zero */ );
/* private key functions...*/
int gnutls_pkcs11_privkey_init(gnutls_pkcs11_privkey_t * key);
int
gnutls_pkcs11_privkey_cpy(gnutls_pkcs11_privkey_t dst,
gnutls_pkcs11_privkey_t src);
void gnutls_pkcs11_privkey_set_pin_function(gnutls_pkcs11_privkey_t
key,
gnutls_pin_callback_t
fn, void *userdata);
void gnutls_pkcs11_privkey_deinit(gnutls_pkcs11_privkey_t key);
int gnutls_pkcs11_privkey_get_pk_algorithm(gnutls_pkcs11_privkey_t
key, unsigned int *bits);
int gnutls_pkcs11_privkey_get_info(gnutls_pkcs11_privkey_t pkey,
gnutls_pkcs11_obj_info_t itype,
void *output, size_t * output_size);
int gnutls_pkcs11_privkey_import_url(gnutls_pkcs11_privkey_t pkey,
const char *url, unsigned int flags);
int gnutls_pkcs11_privkey_export_url(gnutls_pkcs11_privkey_t key,
gnutls_pkcs11_url_type_t
detailed, char **url);
unsigned gnutls_pkcs11_privkey_status(gnutls_pkcs11_privkey_t key);
#define gnutls_pkcs11_privkey_generate(url, pk, bits, label, flags) \
gnutls_pkcs11_privkey_generate3(url, pk, bits, label, NULL, 0, NULL, 0, flags)
#define gnutls_pkcs11_privkey_generate2(url, pk, bits, label, fmt, pubkey, flags) \
gnutls_pkcs11_privkey_generate3(url, pk, bits, label, NULL, fmt, pubkey, 0, flags)
int
gnutls_pkcs11_privkey_generate3(const char *url,
gnutls_pk_algorithm_t pk,
unsigned int bits,
const char *label,
const gnutls_datum_t *cid,
gnutls_x509_crt_fmt_t fmt,
gnutls_datum_t * pubkey,
unsigned int key_usage,
unsigned int flags);
int
gnutls_pkcs11_privkey_export_pubkey(gnutls_pkcs11_privkey_t pkey,
gnutls_x509_crt_fmt_t fmt,
gnutls_datum_t * pubkey,
unsigned int flags);
int
gnutls_pkcs11_token_get_random(const char *token_url,
void *data, size_t len);
int
gnutls_pkcs11_copy_attached_extension(const char *token_url,
gnutls_x509_crt_t crt,
gnutls_datum_t *data,
const char *label,
unsigned int flags);
#define gnutls_x509_crt_import_pkcs11_url gnutls_x509_crt_import_url
/* *INDENT-OFF* */
#ifdef __cplusplus
}
#endif
/* *INDENT-ON* */
#endif /* GNUTLS_PKCS11_H */
| 20,819
|
C++
|
.h
| 446
| 43.233184
| 156
| 0.732923
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,449
|
tpm.h
|
Nevcairiel_LAVFilters/thirdparty/32/include/gnutls/tpm.h
|
/*
* Copyright (C) 2010-2012 Free Software Foundation, Inc.
*
* Author: Nikos Mavrogiannopoulos
*
* This file is part of GnuTLS.
*
* The GnuTLS 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.
*
* 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 program. If not, see <https://www.gnu.org/licenses/>
*
*/
#ifndef GNUTLS_TPM_H
#define GNUTLS_TPM_H
#include <gnutls/gnutls.h>
#include <gnutls/x509.h>
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
struct tpm_key_list_st;
typedef struct tpm_key_list_st *gnutls_tpm_key_list_t;
#define GNUTLS_TPM_KEY_SIGNING (1<<1)
#define GNUTLS_TPM_REGISTER_KEY (1<<2)
#define GNUTLS_TPM_KEY_USER (1<<3)
/**
* gnutls_tpmkey_fmt_t:
* @GNUTLS_TPMKEY_FMT_RAW: The portable data format.
* @GNUTLS_TPMKEY_FMT_DER: An alias for the raw format.
* @GNUTLS_TPMKEY_FMT_CTK_PEM: A custom data format used by some TPM tools.
*
* Enumeration of different certificate encoding formats.
*/
typedef enum {
GNUTLS_TPMKEY_FMT_RAW = 0,
GNUTLS_TPMKEY_FMT_DER = GNUTLS_TPMKEY_FMT_RAW,
GNUTLS_TPMKEY_FMT_CTK_PEM = 1
} gnutls_tpmkey_fmt_t;
int
gnutls_tpm_privkey_generate(gnutls_pk_algorithm_t pk,
unsigned int bits,
const char *srk_password,
const char *key_password,
gnutls_tpmkey_fmt_t format,
gnutls_x509_crt_fmt_t pub_format,
gnutls_datum_t * privkey,
gnutls_datum_t * pubkey, unsigned int flags);
void gnutls_tpm_key_list_deinit(gnutls_tpm_key_list_t list);
int gnutls_tpm_key_list_get_url(gnutls_tpm_key_list_t list,
unsigned int idx, char **url,
unsigned int flags);
int gnutls_tpm_get_registered(gnutls_tpm_key_list_t * list);
int gnutls_tpm_privkey_delete(const char *url, const char *srk_password);
/* *INDENT-OFF* */
#ifdef __cplusplus
}
#endif
/* *INDENT-ON* */
#endif /* GNUTLS_TPM_H */
| 2,324
|
C++
|
.h
| 69
| 31.26087
| 75
| 0.730392
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,450
|
urls.h
|
Nevcairiel_LAVFilters/thirdparty/32/include/gnutls/urls.h
|
/*
* Copyright (C) 2014 Red Hat, Inc.
*
* Author: Nikos Mavrogiannopoulos
*
* This file is part of GnuTLS.
*
* The GnuTLS 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.
*
* 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 program. If not, see <https://www.gnu.org/licenses/>
*
*/
#ifndef GNUTLS_URLS_H
#define GNUTLS_URLS_H
#include <gnutls/gnutls.h>
#include <gnutls/x509.h>
#include <gnutls/abstract.h>
/* This API allows to register application specific URLs for
* keys and certificates.
*/
/* *INDENT-OFF* */
#ifdef __cplusplus
extern "C" {
#endif
/* *INDENT-ON* */
typedef int (*gnutls_privkey_import_url_func)(gnutls_privkey_t pkey,
const char *url, unsigned flags);
typedef int (*gnutls_x509_crt_import_url_func)(gnutls_x509_crt_t pkey,
const char *url, unsigned flags);
/* The following callbacks are optional */
/* This is to enable gnutls_pubkey_import_url() */
typedef int (*gnutls_pubkey_import_url_func)(gnutls_pubkey_t pkey,
const char *url, unsigned flags);
/* This is to allow constructing a certificate chain. It will be provided
* the initial certificate URL and the certificate to find its issuer, and must
* return zero and the DER encoding of the issuer's certificate. If not available,
* it should return GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE. */
typedef int (*gnutls_get_raw_issuer_func)(const char *url, gnutls_x509_crt_t crt,
gnutls_datum_t *issuer_der, unsigned flags);
typedef struct gnutls_custom_url_st {
const char *name;
unsigned name_size;
gnutls_privkey_import_url_func import_key;
gnutls_x509_crt_import_url_func import_crt;
gnutls_pubkey_import_url_func import_pubkey;
gnutls_get_raw_issuer_func get_issuer;
void *future1; /* replace in a future extension */
void *future2; /* replace in a future extension */
} gnutls_custom_url_st;
int gnutls_register_custom_url(const gnutls_custom_url_st *st);
/* *INDENT-OFF* */
#ifdef __cplusplus
}
#endif
/* *INDENT-ON* */
#endif /* GNUTLS_URLS_H */
| 2,502
|
C++
|
.h
| 65
| 36.138462
| 82
| 0.741749
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
22,451
|
interf_enc.h
|
Nevcairiel_LAVFilters/thirdparty/32/include/opencore-amrnb/interf_enc.h
|
/* ------------------------------------------------------------------
* Copyright (C) 2009 Martin Storsjo
*
* 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 OPENCORE_AMRNB_INTERF_ENC_H
#define OPENCORE_AMRNB_INTERF_ENC_H
#ifdef __cplusplus
extern "C" {
#endif
#ifndef AMRNB_WRAPPER_INTERNAL
/* Copied from enc/src/gsmamr_enc.h */
enum Mode {
MR475 = 0,/* 4.75 kbps */
MR515, /* 5.15 kbps */
MR59, /* 5.90 kbps */
MR67, /* 6.70 kbps */
MR74, /* 7.40 kbps */
MR795, /* 7.95 kbps */
MR102, /* 10.2 kbps */
MR122, /* 12.2 kbps */
MRDTX, /* DTX */
N_MODES /* Not Used */
};
#endif
void* Encoder_Interface_init(int dtx);
void Encoder_Interface_exit(void* state);
int Encoder_Interface_Encode(void* state, enum Mode mode, const short* speech, unsigned char* out, int forceSpeech);
#ifdef __cplusplus
}
#endif
#endif
| 1,456
|
C++
|
.h
| 44
| 31.363636
| 116
| 0.629445
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,452
|
interf_dec.h
|
Nevcairiel_LAVFilters/thirdparty/32/include/opencore-amrnb/interf_dec.h
|
/* ------------------------------------------------------------------
* Copyright (C) 2009 Martin Storsjo
*
* 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 OPENCORE_AMRNB_INTERF_DEC_H
#define OPENCORE_AMRNB_INTERF_DEC_H
#ifdef __cplusplus
extern "C" {
#endif
void* Decoder_Interface_init(void);
void Decoder_Interface_exit(void* state);
void Decoder_Interface_Decode(void* state, const unsigned char* in, short* out, int bfi);
#ifdef __cplusplus
}
#endif
#endif
| 1,063
|
C++
|
.h
| 29
| 34.931034
| 89
| 0.660836
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| false
| false
| false
| false
| false
| false
|
22,453
|
speex.h
|
Nevcairiel_LAVFilters/thirdparty/32/include/speex/speex.h
|
/* Copyright (C) 2002-2006 Jean-Marc Valin*/
/**
@file speex.h
@brief Describes the different modes of the codec
*/
/*
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 the Xiph.org Foundation 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 FOUNDATION 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 SPEEX_H
#define SPEEX_H
/** @defgroup Codec Speex encoder and decoder
* This is the Speex codec itself.
* @{
*/
#include "speex_types.h"
#include "speex_bits.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Values allowed for *ctl() requests */
/** Set enhancement on/off (decoder only) */
#define SPEEX_SET_ENH 0
/** Get enhancement state (decoder only) */
#define SPEEX_GET_ENH 1
/*Would be SPEEX_SET_FRAME_SIZE, but it's (currently) invalid*/
/** Obtain frame size used by encoder/decoder */
#define SPEEX_GET_FRAME_SIZE 3
/** Set quality value */
#define SPEEX_SET_QUALITY 4
/** Get current quality setting */
/* #define SPEEX_GET_QUALITY 5 -- Doesn't make much sense, does it? */
/** Set sub-mode to use */
#define SPEEX_SET_MODE 6
/** Get current sub-mode in use */
#define SPEEX_GET_MODE 7
/** Set low-band sub-mode to use (wideband only)*/
#define SPEEX_SET_LOW_MODE 8
/** Get current low-band mode in use (wideband only)*/
#define SPEEX_GET_LOW_MODE 9
/** Set high-band sub-mode to use (wideband only)*/
#define SPEEX_SET_HIGH_MODE 10
/** Get current high-band mode in use (wideband only)*/
#define SPEEX_GET_HIGH_MODE 11
/** Set VBR on (1) or off (0) */
#define SPEEX_SET_VBR 12
/** Get VBR status (1 for on, 0 for off) */
#define SPEEX_GET_VBR 13
/** Set quality value for VBR encoding (0-10) */
#define SPEEX_SET_VBR_QUALITY 14
/** Get current quality value for VBR encoding (0-10) */
#define SPEEX_GET_VBR_QUALITY 15
/** Set complexity of the encoder (0-10) */
#define SPEEX_SET_COMPLEXITY 16
/** Get current complexity of the encoder (0-10) */
#define SPEEX_GET_COMPLEXITY 17
/** Set bit-rate used by the encoder (or lower) */
#define SPEEX_SET_BITRATE 18
/** Get current bit-rate used by the encoder or decoder */
#define SPEEX_GET_BITRATE 19
/** Define a handler function for in-band Speex request*/
#define SPEEX_SET_HANDLER 20
/** Define a handler function for in-band user-defined request*/
#define SPEEX_SET_USER_HANDLER 22
/** Set sampling rate used in bit-rate computation */
#define SPEEX_SET_SAMPLING_RATE 24
/** Get sampling rate used in bit-rate computation */
#define SPEEX_GET_SAMPLING_RATE 25
/** Reset the encoder/decoder memories to zero*/
#define SPEEX_RESET_STATE 26
/** Get VBR info (mostly used internally) */
#define SPEEX_GET_RELATIVE_QUALITY 29
/** Set VAD status (1 for on, 0 for off) */
#define SPEEX_SET_VAD 30
/** Get VAD status (1 for on, 0 for off) */
#define SPEEX_GET_VAD 31
/** Set Average Bit-Rate (ABR) to n bits per seconds */
#define SPEEX_SET_ABR 32
/** Get Average Bit-Rate (ABR) setting (in bps) */
#define SPEEX_GET_ABR 33
/** Set DTX status (1 for on, 0 for off) */
#define SPEEX_SET_DTX 34
/** Get DTX status (1 for on, 0 for off) */
#define SPEEX_GET_DTX 35
/** Set submode encoding in each frame (1 for yes, 0 for no, setting to no breaks the standard) */
#define SPEEX_SET_SUBMODE_ENCODING 36
/** Get submode encoding in each frame */
#define SPEEX_GET_SUBMODE_ENCODING 37
/*#define SPEEX_SET_LOOKAHEAD 38*/
/** Returns the lookahead used by Speex separately for an encoder and a decoder.
* Sum encoder and decoder lookahead values to get the total codec lookahead. */
#define SPEEX_GET_LOOKAHEAD 39
/** Sets tuning for packet-loss concealment (expected loss rate) */
#define SPEEX_SET_PLC_TUNING 40
/** Gets tuning for PLC */
#define SPEEX_GET_PLC_TUNING 41
/** Sets the max bit-rate allowed in VBR mode */
#define SPEEX_SET_VBR_MAX_BITRATE 42
/** Gets the max bit-rate allowed in VBR mode */
#define SPEEX_GET_VBR_MAX_BITRATE 43
/** Turn on/off input/output high-pass filtering */
#define SPEEX_SET_HIGHPASS 44
/** Get status of input/output high-pass filtering */
#define SPEEX_GET_HIGHPASS 45
/** Get "activity level" of the last decoded frame, i.e.
how much damage we cause if we remove the frame */
#define SPEEX_GET_ACTIVITY 47
/* Preserving compatibility:*/
/** Equivalent to SPEEX_SET_ENH */
#define SPEEX_SET_PF 0
/** Equivalent to SPEEX_GET_ENH */
#define SPEEX_GET_PF 1
/* Values allowed for mode queries */
/** Query the frame size of a mode */
#define SPEEX_MODE_FRAME_SIZE 0
/** Query the size of an encoded frame for a particular sub-mode */
#define SPEEX_SUBMODE_BITS_PER_FRAME 1
/** Get major Speex version */
#define SPEEX_LIB_GET_MAJOR_VERSION 1
/** Get minor Speex version */
#define SPEEX_LIB_GET_MINOR_VERSION 3
/** Get micro Speex version */
#define SPEEX_LIB_GET_MICRO_VERSION 5
/** Get extra Speex version */
#define SPEEX_LIB_GET_EXTRA_VERSION 7
/** Get Speex version string */
#define SPEEX_LIB_GET_VERSION_STRING 9
/*#define SPEEX_LIB_SET_ALLOC_FUNC 10
#define SPEEX_LIB_GET_ALLOC_FUNC 11
#define SPEEX_LIB_SET_FREE_FUNC 12
#define SPEEX_LIB_GET_FREE_FUNC 13
#define SPEEX_LIB_SET_WARNING_FUNC 14
#define SPEEX_LIB_GET_WARNING_FUNC 15
#define SPEEX_LIB_SET_ERROR_FUNC 16
#define SPEEX_LIB_GET_ERROR_FUNC 17
*/
/** Number of defined modes in Speex */
#define SPEEX_NB_MODES 3
/** modeID for the defined narrowband mode */
#define SPEEX_MODEID_NB 0
/** modeID for the defined wideband mode */
#define SPEEX_MODEID_WB 1
/** modeID for the defined ultra-wideband mode */
#define SPEEX_MODEID_UWB 2
struct SpeexMode;
/* Prototypes for mode function pointers */
/** Encoder state initialization function */
typedef void *(*encoder_init_func)(const struct SpeexMode *mode);
/** Encoder state destruction function */
typedef void (*encoder_destroy_func)(void *st);
/** Main encoding function */
typedef int (*encode_func)(void *state, void *in, SpeexBits *bits);
/** Function for controlling the encoder options */
typedef int (*encoder_ctl_func)(void *state, int request, void *ptr);
/** Decoder state initialization function */
typedef void *(*decoder_init_func)(const struct SpeexMode *mode);
/** Decoder state destruction function */
typedef void (*decoder_destroy_func)(void *st);
/** Main decoding function */
typedef int (*decode_func)(void *state, SpeexBits *bits, void *out);
/** Function for controlling the decoder options */
typedef int (*decoder_ctl_func)(void *state, int request, void *ptr);
/** Query function for a mode */
typedef int (*mode_query_func)(const void *mode, int request, void *ptr);
/** Struct defining a Speex mode */
typedef struct SpeexMode {
/** Pointer to the low-level mode data */
const void *mode;
/** Pointer to the mode query function */
mode_query_func query;
/** The name of the mode (you should not rely on this to identify the mode)*/
const char *modeName;
/**ID of the mode*/
int modeID;
/**Version number of the bitstream (incremented every time we break
bitstream compatibility*/
int bitstream_version;
/** Pointer to encoder initialization function */
encoder_init_func enc_init;
/** Pointer to encoder destruction function */
encoder_destroy_func enc_destroy;
/** Pointer to frame encoding function */
encode_func enc;
/** Pointer to decoder initialization function */
decoder_init_func dec_init;
/** Pointer to decoder destruction function */
decoder_destroy_func dec_destroy;
/** Pointer to frame decoding function */
decode_func dec;
/** ioctl-like requests for encoder */
encoder_ctl_func enc_ctl;
/** ioctl-like requests for decoder */
decoder_ctl_func dec_ctl;
} SpeexMode;
/**
* Returns a handle to a newly created Speex encoder state structure. For now,
* the "mode" argument can be &nb_mode or &wb_mode . In the future, more modes
* may be added. Note that for now if you have more than one channels to
* encode, you need one state per channel.
*
* @param mode The mode to use (either speex_nb_mode or speex_wb.mode)
* @return A newly created encoder state or NULL if state allocation fails
*/
void *speex_encoder_init(const SpeexMode *mode);
/** Frees all resources associated to an existing Speex encoder state.
* @param state Encoder state to be destroyed */
void speex_encoder_destroy(void *state);
/** Uses an existing encoder state to encode one frame of speech pointed to by
"in". The encoded bit-stream is saved in "bits".
@param state Encoder state
@param in Frame that will be encoded with a +-2^15 range. This data MAY be
overwritten by the encoder and should be considered uninitialised
after the call.
@param bits Bit-stream where the data will be written
@return 0 if frame needs not be transmitted (DTX only), 1 otherwise
*/
int speex_encode(void *state, float *in, SpeexBits *bits);
/** Uses an existing encoder state to encode one frame of speech pointed to by
"in". The encoded bit-stream is saved in "bits".
@param state Encoder state
@param in Frame that will be encoded with a +-2^15 range
@param bits Bit-stream where the data will be written
@return 0 if frame needs not be transmitted (DTX only), 1 otherwise
*/
int speex_encode_int(void *state, spx_int16_t *in, SpeexBits *bits);
/** Used like the ioctl function to control the encoder parameters
*
* @param state Encoder state
* @param request ioctl-type request (one of the SPEEX_* macros)
* @param ptr Data exchanged to-from function
* @return 0 if no error, -1 if request in unknown, -2 for invalid parameter
*/
int speex_encoder_ctl(void *state, int request, void *ptr);
/** Returns a handle to a newly created decoder state structure. For now,
* the mode argument can be &nb_mode or &wb_mode . In the future, more modes
* may be added. Note that for now if you have more than one channels to
* decode, you need one state per channel.
*
* @param mode Speex mode (one of speex_nb_mode or speex_wb_mode)
* @return A newly created decoder state or NULL if state allocation fails
*/
void *speex_decoder_init(const SpeexMode *mode);
/** Frees all resources associated to an existing decoder state.
*
* @param state State to be destroyed
*/
void speex_decoder_destroy(void *state);
/** Uses an existing decoder state to decode one frame of speech from
* bit-stream bits. The output speech is saved written to out.
*
* @param state Decoder state
* @param bits Bit-stream from which to decode the frame (NULL if the packet was lost)
* @param out Where to write the decoded frame
* @return return status (0 for no error, -1 for end of stream, -2 corrupt stream)
*/
int speex_decode(void *state, SpeexBits *bits, float *out);
/** Uses an existing decoder state to decode one frame of speech from
* bit-stream bits. The output speech is saved written to out.
*
* @param state Decoder state
* @param bits Bit-stream from which to decode the frame (NULL if the packet was lost)
* @param out Where to write the decoded frame
* @return return status (0 for no error, -1 for end of stream, -2 corrupt stream)
*/
int speex_decode_int(void *state, SpeexBits *bits, spx_int16_t *out);
/** Used like the ioctl function to control the encoder parameters
*
* @param state Decoder state
* @param request ioctl-type request (one of the SPEEX_* macros)
* @param ptr Data exchanged to-from function
* @return 0 if no error, -1 if request in unknown, -2 for invalid parameter
*/
int speex_decoder_ctl(void *state, int request, void *ptr);
/** Query function for mode information
*
* @param mode Speex mode
* @param request ioctl-type request (one of the SPEEX_* macros)
* @param ptr Data exchanged to-from function
* @return 0 if no error, -1 if request in unknown, -2 for invalid parameter
*/
int speex_mode_query(const SpeexMode *mode, int request, void *ptr);
/** Functions for controlling the behavior of libspeex
* @param request ioctl-type request (one of the SPEEX_LIB_* macros)
* @param ptr Data exchanged to-from function
* @return 0 if no error, -1 if request in unknown, -2 for invalid parameter
*/
int speex_lib_ctl(int request, void *ptr);
/** Default narrowband mode */
extern const SpeexMode speex_nb_mode;
/** Default wideband mode */
extern const SpeexMode speex_wb_mode;
/** Default "ultra-wideband" mode */
extern const SpeexMode speex_uwb_mode;
/** List of all modes available */
extern const SpeexMode * const speex_mode_list[SPEEX_NB_MODES];
/** Obtain one of the modes available */
const SpeexMode * speex_lib_get_mode (int mode);
#ifndef _WIN32
/* We actually override the function in the narrowband case so that we can avoid linking in the wideband stuff */
#define speex_lib_get_mode(mode) ((mode)==SPEEX_MODEID_NB ? &speex_nb_mode : speex_lib_get_mode (mode))
#endif
#ifdef __cplusplus
}
#endif
/** @}*/
#endif
| 14,031
|
C++
|
.h
| 326
| 40.972393
| 113
| 0.743496
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
22,454
|
speex_bits.h
|
Nevcairiel_LAVFilters/thirdparty/32/include/speex/speex_bits.h
|
/* Copyright (C) 2002 Jean-Marc Valin */
/**
@file speex_bits.h
@brief Handles bit packing/unpacking
*/
/*
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 the Xiph.org Foundation 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 FOUNDATION 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 BITS_H
#define BITS_H
/** @defgroup SpeexBits SpeexBits: Bit-stream manipulations
* This is the structure that holds the bit-stream when encoding or decoding
* with Speex. It allows some manipulations as well.
* @{
*/
#ifdef __cplusplus
extern "C" {
#endif
/** Bit-packing data structure representing (part of) a bit-stream. */
typedef struct SpeexBits {
char *chars; /**< "raw" data */
int nbBits; /**< Total number of bits stored in the stream*/
int charPtr; /**< Position of the byte "cursor" */
int bitPtr; /**< Position of the bit "cursor" within the current char */
int owner; /**< Does the struct "own" the "raw" buffer (member "chars") */
int overflow;/**< Set to one if we try to read past the valid data */
int buf_size;/**< Allocated size for buffer */
int reserved1; /**< Reserved for future use */
void *reserved2; /**< Reserved for future use */
} SpeexBits;
/** Initializes and allocates resources for a SpeexBits struct */
void speex_bits_init(SpeexBits *bits);
/** Initializes SpeexBits struct using a pre-allocated buffer*/
void speex_bits_init_buffer(SpeexBits *bits, void *buff, int buf_size);
/** Sets the bits in a SpeexBits struct to use data from an existing buffer (for decoding without copying data) */
void speex_bits_set_bit_buffer(SpeexBits *bits, void *buff, int buf_size);
/** Frees all resources associated to a SpeexBits struct. Right now this does nothing since no resources are allocated, but this could change in the future.*/
void speex_bits_destroy(SpeexBits *bits);
/** Resets bits to initial value (just after initialization, erasing content)*/
void speex_bits_reset(SpeexBits *bits);
/** Rewind the bit-stream to the beginning (ready for read) without erasing the content */
void speex_bits_rewind(SpeexBits *bits);
/** Initializes the bit-stream from the data in an area of memory */
void speex_bits_read_from(SpeexBits *bits, const char *bytes, int len);
/** Append bytes to the bit-stream
*
* @param bits Bit-stream to operate on
* @param bytes pointer to the bytes what will be appended
* @param len Number of bytes of append
*/
void speex_bits_read_whole_bytes(SpeexBits *bits, const char *bytes, int len);
/** Write the content of a bit-stream to an area of memory
*
* @param bits Bit-stream to operate on
* @param bytes Memory location where to write the bits
* @param max_len Maximum number of bytes to write (i.e. size of the "bytes" buffer)
* @return Number of bytes written to the "bytes" buffer
*/
int speex_bits_write(SpeexBits *bits, char *bytes, int max_len);
/** Like speex_bits_write, but writes only the complete bytes in the stream. Also removes the written bytes from the stream */
int speex_bits_write_whole_bytes(SpeexBits *bits, char *bytes, int max_len);
/** Append bits to the bit-stream
* @param bits Bit-stream to operate on
* @param data Value to append as integer
* @param nbBits number of bits to consider in "data"
*/
void speex_bits_pack(SpeexBits *bits, int data, int nbBits);
/** Interpret the next bits in the bit-stream as a signed integer
*
* @param bits Bit-stream to operate on
* @param nbBits Number of bits to interpret
* @return A signed integer represented by the bits read
*/
int speex_bits_unpack_signed(SpeexBits *bits, int nbBits);
/** Interpret the next bits in the bit-stream as an unsigned integer
*
* @param bits Bit-stream to operate on
* @param nbBits Number of bits to interpret
* @return An unsigned integer represented by the bits read
*/
unsigned int speex_bits_unpack_unsigned(SpeexBits *bits, int nbBits);
/** Returns the number of bytes in the bit-stream, including the last one even if it is not "full"
*
* @param bits Bit-stream to operate on
* @return Number of bytes in the stream
*/
int speex_bits_nbytes(SpeexBits *bits);
/** Same as speex_bits_unpack_unsigned, but without modifying the cursor position
*
* @param bits Bit-stream to operate on
* @param nbBits Number of bits to look for
* @return Value of the bits peeked, interpreted as unsigned
*/
unsigned int speex_bits_peek_unsigned(SpeexBits *bits, int nbBits);
/** Get the value of the next bit in the stream, without modifying the
* "cursor" position
*
* @param bits Bit-stream to operate on
* @return Value of the bit peeked (one bit only)
*/
int speex_bits_peek(SpeexBits *bits);
/** Advances the position of the "bit cursor" in the stream
*
* @param bits Bit-stream to operate on
* @param n Number of bits to advance
*/
void speex_bits_advance(SpeexBits *bits, int n);
/** Returns the number of bits remaining to be read in a stream
*
* @param bits Bit-stream to operate on
* @return Number of bits that can still be read from the stream
*/
int speex_bits_remaining(SpeexBits *bits);
/** Insert a terminator so that the data can be sent as a packet while auto-detecting
* the number of frames in each packet
*
* @param bits Bit-stream to operate on
*/
void speex_bits_insert_terminator(SpeexBits *bits);
#ifdef __cplusplus
}
#endif
/* @} */
#endif
| 6,660
|
C++
|
.h
| 145
| 43.675862
| 158
| 0.75054
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| false
| false
| false
| false
| false
| false
|
22,455
|
speex_types.h
|
Nevcairiel_LAVFilters/thirdparty/32/include/speex/speex_types.h
|
/* speex_types.h taken from libogg */
/********************************************************************
* *
* THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
* USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
* GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
* IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
* *
* THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
* by the Xiph.Org Foundation http://www.xiph.org/ *
* *
********************************************************************
function: #ifdef jail to whip a few platforms into the UNIX ideal.
last mod: $Id: os_types.h 7524 2004-08-11 04:20:36Z conrad $
********************************************************************/
/**
@file speex_types.h
@brief Speex types
*/
#ifndef _SPEEX_TYPES_H
#define _SPEEX_TYPES_H
#if defined(_WIN32)
# if defined(__CYGWIN__)
# include <_G_config.h>
typedef _G_int32_t spx_int32_t;
typedef _G_uint32_t spx_uint32_t;
typedef _G_int16_t spx_int16_t;
typedef _G_uint16_t spx_uint16_t;
# elif defined(__MINGW32__)
typedef short spx_int16_t;
typedef unsigned short spx_uint16_t;
typedef int spx_int32_t;
typedef unsigned int spx_uint32_t;
# elif defined(__MWERKS__)
typedef int spx_int32_t;
typedef unsigned int spx_uint32_t;
typedef short spx_int16_t;
typedef unsigned short spx_uint16_t;
# else
/* MSVC/Borland */
typedef __int32 spx_int32_t;
typedef unsigned __int32 spx_uint32_t;
typedef __int16 spx_int16_t;
typedef unsigned __int16 spx_uint16_t;
# endif
#elif defined(__MACOS__)
# include <sys/types.h>
typedef SInt16 spx_int16_t;
typedef UInt16 spx_uint16_t;
typedef SInt32 spx_int32_t;
typedef UInt32 spx_uint32_t;
#elif (defined(__APPLE__) && defined(__MACH__)) /* MacOS X Framework build */
# include <sys/types.h>
typedef int16_t spx_int16_t;
typedef u_int16_t spx_uint16_t;
typedef int32_t spx_int32_t;
typedef u_int32_t spx_uint32_t;
#elif defined(__BEOS__)
/* Be */
# include <inttypes.h>
typedef int16_t spx_int16_t;
typedef u_int16_t spx_uint16_t;
typedef int32_t spx_int32_t;
typedef u_int32_t spx_uint32_t;
#elif defined (__EMX__)
/* OS/2 GCC */
typedef short spx_int16_t;
typedef unsigned short spx_uint16_t;
typedef int spx_int32_t;
typedef unsigned int spx_uint32_t;
#elif defined (DJGPP)
/* DJGPP */
typedef short spx_int16_t;
typedef int spx_int32_t;
typedef unsigned int spx_uint32_t;
#elif defined(R5900)
/* PS2 EE */
typedef int spx_int32_t;
typedef unsigned spx_uint32_t;
typedef short spx_int16_t;
#elif defined(__SYMBIAN32__)
/* Symbian GCC */
typedef signed short spx_int16_t;
typedef unsigned short spx_uint16_t;
typedef signed int spx_int32_t;
typedef unsigned int spx_uint32_t;
#elif defined(CONFIG_TI_C54X) || defined (CONFIG_TI_C55X)
typedef short spx_int16_t;
typedef unsigned short spx_uint16_t;
typedef long spx_int32_t;
typedef unsigned long spx_uint32_t;
#elif defined(CONFIG_TI_C6X)
typedef short spx_int16_t;
typedef unsigned short spx_uint16_t;
typedef int spx_int32_t;
typedef unsigned int spx_uint32_t;
#else
#include "speex_config_types.h"
#endif
#endif /* _SPEEX_TYPES_H */
| 3,582
|
C++
|
.h
| 100
| 32.35
| 77
| 0.608796
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
22,456
|
speex_stereo.h
|
Nevcairiel_LAVFilters/thirdparty/32/include/speex/speex_stereo.h
|
/* Copyright (C) 2002 Jean-Marc Valin*/
/**
@file speex_stereo.h
@brief Describes the handling for intensity stereo
*/
/*
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 the Xiph.org Foundation 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 FOUNDATION 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 STEREO_H
#define STEREO_H
/** @defgroup SpeexStereoState SpeexStereoState: Handling Speex stereo files
* This describes the Speex intensity stereo encoding/decoding
* @{
*/
#include "speex_types.h"
#include "speex_bits.h"
#ifdef __cplusplus
extern "C" {
#endif
/** If you access any of these fields directly, I'll personally come and bite you */
typedef struct SpeexStereoState {
float balance; /**< Left/right balance info */
float e_ratio; /**< Ratio of energies: E(left+right)/[E(left)+E(right)] */
float smooth_left; /**< Smoothed left channel gain */
float smooth_right; /**< Smoothed right channel gain */
float reserved1; /**< Reserved for future use */
float reserved2; /**< Reserved for future use */
} SpeexStereoState;
/** Deprecated. Use speex_stereo_state_init() instead. */
#define SPEEX_STEREO_STATE_INIT {1,.5,1,1,0,0}
/** Initialise/create a stereo stereo state */
SpeexStereoState *speex_stereo_state_init(void);
/** Reset/re-initialise an already allocated stereo state */
void speex_stereo_state_reset(SpeexStereoState *stereo);
/** Destroy a stereo stereo state */
void speex_stereo_state_destroy(SpeexStereoState *stereo);
/** Transforms a stereo frame into a mono frame and stores intensity stereo info in 'bits' */
void speex_encode_stereo(float *data, int frame_size, SpeexBits *bits);
/** Transforms a stereo frame into a mono frame and stores intensity stereo info in 'bits' */
void speex_encode_stereo_int(spx_int16_t *data, int frame_size, SpeexBits *bits);
/** Transforms a mono frame into a stereo frame using intensity stereo info */
void speex_decode_stereo(float *data, int frame_size, SpeexStereoState *stereo);
/** Transforms a mono frame into a stereo frame using intensity stereo info */
void speex_decode_stereo_int(spx_int16_t *data, int frame_size, SpeexStereoState *stereo);
/** Callback handler for intensity stereo info */
int speex_std_stereo_request_handler(SpeexBits *bits, void *state, void *data);
#ifdef __cplusplus
}
#endif
/** @} */
#endif
| 3,679
|
C++
|
.h
| 72
| 48.527778
| 93
| 0.761639
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
22,457
|
speex_header.h
|
Nevcairiel_LAVFilters/thirdparty/32/include/speex/speex_header.h
|
/* Copyright (C) 2002 Jean-Marc Valin */
/**
@file speex_header.h
@brief Describes the Speex header
*/
/*
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 the Xiph.org Foundation 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 FOUNDATION 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 SPEEX_HEADER_H
#define SPEEX_HEADER_H
/** @defgroup SpeexHeader SpeexHeader: Makes it easy to write/parse an Ogg/Speex header
* This is the Speex header for the Ogg encapsulation. You don't need that if you just use RTP.
* @{
*/
#include "speex_types.h"
#ifdef __cplusplus
extern "C" {
#endif
struct SpeexMode;
/** Length of the Speex header identifier */
#define SPEEX_HEADER_STRING_LENGTH 8
/** Maximum number of characters for encoding the Speex version number in the header */
#define SPEEX_HEADER_VERSION_LENGTH 20
/** Speex header info for file-based formats */
typedef struct SpeexHeader {
char speex_string[SPEEX_HEADER_STRING_LENGTH]; /**< Identifies a Speex bit-stream, always set to "Speex " */
char speex_version[SPEEX_HEADER_VERSION_LENGTH]; /**< Speex version */
spx_int32_t speex_version_id; /**< Version for Speex (for checking compatibility) */
spx_int32_t header_size; /**< Total size of the header ( sizeof(SpeexHeader) ) */
spx_int32_t rate; /**< Sampling rate used */
spx_int32_t mode; /**< Mode used (0 for narrowband, 1 for wideband) */
spx_int32_t mode_bitstream_version; /**< Version ID of the bit-stream */
spx_int32_t nb_channels; /**< Number of channels encoded */
spx_int32_t bitrate; /**< Bit-rate used */
spx_int32_t frame_size; /**< Size of frames */
spx_int32_t vbr; /**< 1 for a VBR encoding, 0 otherwise */
spx_int32_t frames_per_packet; /**< Number of frames stored per Ogg packet */
spx_int32_t extra_headers; /**< Number of additional headers after the comments */
spx_int32_t reserved1; /**< Reserved for future use, must be zero */
spx_int32_t reserved2; /**< Reserved for future use, must be zero */
} SpeexHeader;
/** Initializes a SpeexHeader using basic information */
void speex_init_header(SpeexHeader *header, int rate, int nb_channels, const struct SpeexMode *m);
/** Creates the header packet from the header itself (mostly involves endianness conversion) */
char *speex_header_to_packet(SpeexHeader *header, int *size);
/** Creates a SpeexHeader from a packet */
SpeexHeader *speex_packet_to_header(char *packet, int size);
/** Frees the memory allocated by either speex_header_to_packet() or speex_packet_to_header() */
void speex_header_free(void *ptr);
#ifdef __cplusplus
}
#endif
/** @} */
#endif
| 4,084
|
C++
|
.h
| 75
| 51.6
| 115
| 0.719549
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| false
| false
| false
| false
| false
| false
|
22,458
|
speex_config_types.h
|
Nevcairiel_LAVFilters/thirdparty/32/include/speex/speex_config_types.h
|
#ifndef __SPEEX_TYPES_H__
#define __SPEEX_TYPES_H__
#include <stdint.h>
typedef int16_t spx_int16_t;
typedef uint16_t spx_uint16_t;
typedef int32_t spx_int32_t;
typedef uint32_t spx_uint32_t;
#endif
| 203
|
C++
|
.h
| 8
| 23.875
| 30
| 0.759162
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,459
|
speex_callbacks.h
|
Nevcairiel_LAVFilters/thirdparty/32/include/speex/speex_callbacks.h
|
/* Copyright (C) 2002 Jean-Marc Valin*/
/**
@file speex_callbacks.h
@brief Describes callback handling and in-band signalling
*/
/*
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 the Xiph.org Foundation 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 FOUNDATION 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 SPEEX_CALLBACKS_H
#define SPEEX_CALLBACKS_H
/** @defgroup SpeexCallbacks Various definitions for Speex callbacks supported by the decoder.
* @{
*/
#include "speex.h"
#ifdef __cplusplus
extern "C" {
#endif
/** Total number of callbacks */
#define SPEEX_MAX_CALLBACKS 16
/* Describes all the in-band requests */
/*These are 1-bit requests*/
/** Request for perceptual enhancement (1 for on, 0 for off) */
#define SPEEX_INBAND_ENH_REQUEST 0
/** Reserved */
#define SPEEX_INBAND_RESERVED1 1
/*These are 4-bit requests*/
/** Request for a mode change */
#define SPEEX_INBAND_MODE_REQUEST 2
/** Request for a low mode change */
#define SPEEX_INBAND_LOW_MODE_REQUEST 3
/** Request for a high mode change */
#define SPEEX_INBAND_HIGH_MODE_REQUEST 4
/** Request for VBR (1 on, 0 off) */
#define SPEEX_INBAND_VBR_QUALITY_REQUEST 5
/** Request to be sent acknowledge */
#define SPEEX_INBAND_ACKNOWLEDGE_REQUEST 6
/** Request for VBR (1 for on, 0 for off) */
#define SPEEX_INBAND_VBR_REQUEST 7
/*These are 8-bit requests*/
/** Send a character in-band */
#define SPEEX_INBAND_CHAR 8
/** Intensity stereo information */
#define SPEEX_INBAND_STEREO 9
/*These are 16-bit requests*/
/** Transmit max bit-rate allowed */
#define SPEEX_INBAND_MAX_BITRATE 10
/*These are 32-bit requests*/
/** Acknowledge packet reception */
#define SPEEX_INBAND_ACKNOWLEDGE 12
/** Callback function type */
typedef int (*speex_callback_func)(SpeexBits *bits, void *state, void *data);
/** Callback information */
typedef struct SpeexCallback {
int callback_id; /**< ID associated to the callback */
speex_callback_func func; /**< Callback handler function */
void *data; /**< Data that will be sent to the handler */
void *reserved1; /**< Reserved for future use */
int reserved2; /**< Reserved for future use */
} SpeexCallback;
/** Handle in-band request */
int speex_inband_handler(SpeexBits *bits, SpeexCallback *callback_list, void *state);
/** Standard handler for mode request (change mode, no questions asked) */
int speex_std_mode_request_handler(SpeexBits *bits, void *state, void *data);
/** Standard handler for high mode request (change high mode, no questions asked) */
int speex_std_high_mode_request_handler(SpeexBits *bits, void *state, void *data);
/** Standard handler for in-band characters (write to stderr) */
int speex_std_char_handler(SpeexBits *bits, void *state, void *data);
/** Default handler for user-defined requests: in this case, just ignore */
int speex_default_user_handler(SpeexBits *bits, void *state, void *data);
/** Standard handler for low mode request (change low mode, no questions asked) */
int speex_std_low_mode_request_handler(SpeexBits *bits, void *state, void *data);
/** Standard handler for VBR request (Set VBR, no questions asked) */
int speex_std_vbr_request_handler(SpeexBits *bits, void *state, void *data);
/** Standard handler for enhancer request (Turn enhancer on/off, no questions asked) */
int speex_std_enh_request_handler(SpeexBits *bits, void *state, void *data);
/** Standard handler for VBR quality request (Set VBR quality, no questions asked) */
int speex_std_vbr_quality_request_handler(SpeexBits *bits, void *state, void *data);
#ifdef __cplusplus
}
#endif
/** @} */
#endif
| 5,033
|
C++
|
.h
| 103
| 46.718447
| 94
| 0.736069
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| false
| false
| false
| false
| false
| false
|
22,460
|
if_rom.h
|
Nevcairiel_LAVFilters/thirdparty/32/include/opencore-amrwb/if_rom.h
|
/* ------------------------------------------------------------------
* Copyright (C) 2009 Martin Storsjo
*
* 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 OPENCORE_AMRWB_IF_ROM_H
#define OPENCORE_AMRWB_IF_ROM_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
typedef int16_t Word16;
#ifdef __cplusplus
}
#endif
#endif
| 931
|
C++
|
.h
| 28
| 31.5
| 70
| 0.641425
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,461
|
dec_if.h
|
Nevcairiel_LAVFilters/thirdparty/32/include/opencore-amrwb/dec_if.h
|
/* ------------------------------------------------------------------
* Copyright (C) 2009 Martin Storsjo
*
* 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 OPENCORE_AMRWB_DEC_IF_H
#define OPENCORE_AMRWB_DEC_IF_H
#ifdef __cplusplus
extern "C" {
#endif
#define _good_frame 0
void* D_IF_init(void);
void D_IF_decode(void* state, const unsigned char* bits, short* synth, int bfi);
void D_IF_exit(void* state);
#ifdef __cplusplus
}
#endif
#endif
| 1,043
|
C++
|
.h
| 30
| 33.033333
| 80
| 0.648461
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| false
| false
| false
| false
| false
| false
|
22,462
|
gmp.h
|
Nevcairiel_LAVFilters/thirdparty/64/include/gmp.h
|
/* Definitions for GNU multiple precision functions. -*- mode: c -*-
Copyright 1991, 1993-1997, 1999-2016, 2020, 2021 Free Software
Foundation, Inc.
This file is part of the GNU MP Library.
The GNU MP Library is free software; you can redistribute it and/or modify
it under the terms of either:
* 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.
or
* 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.
or both in parallel, as here.
The GNU MP 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.
You should have received copies of the GNU General Public License and the
GNU Lesser General Public License along with the GNU MP Library. If not,
see https://www.gnu.org/licenses/. */
#ifndef __GMP_H__
#if defined (__cplusplus)
#include <iosfwd> /* for std::istream, std::ostream, std::string */
#include <cstdio>
#endif
/* Instantiated by configure. */
#if ! defined (__GMP_WITHIN_CONFIGURE)
#define __GMP_HAVE_HOST_CPU_FAMILY_power 0
#define __GMP_HAVE_HOST_CPU_FAMILY_powerpc 0
#define GMP_LIMB_BITS 64
#define GMP_NAIL_BITS 0
#endif
#define GMP_NUMB_BITS (GMP_LIMB_BITS - GMP_NAIL_BITS)
#define GMP_NUMB_MASK ((~ __GMP_CAST (mp_limb_t, 0)) >> GMP_NAIL_BITS)
#define GMP_NUMB_MAX GMP_NUMB_MASK
#define GMP_NAIL_MASK (~ GMP_NUMB_MASK)
#ifndef __GNU_MP__
#define __GNU_MP__ 6
#include <stddef.h> /* for size_t */
#include <limits.h>
/* Instantiated by configure. */
#if ! defined (__GMP_WITHIN_CONFIGURE)
#define _LONG_LONG_LIMB 1
#define __GMP_LIBGMP_DLL 0
#endif
/* __GMP_DECLSPEC supports Windows DLL versions of libgmp, and is empty in
all other circumstances.
When compiling objects for libgmp, __GMP_DECLSPEC is an export directive,
or when compiling for an application it's an import directive. The two
cases are differentiated by __GMP_WITHIN_GMP defined by the GMP Makefiles
(and not defined from an application).
__GMP_DECLSPEC_XX is similarly used for libgmpxx. __GMP_WITHIN_GMPXX
indicates when building libgmpxx, and in that case libgmpxx functions are
exports, but libgmp functions which might get called are imports.
Libtool DLL_EXPORT define is not used.
There's no attempt to support GMP built both static and DLL. Doing so
would mean applications would have to tell us which of the two is going
to be used when linking, and that seems very tedious and error prone if
using GMP by hand, and equally tedious from a package since autoconf and
automake don't give much help.
__GMP_DECLSPEC is required on all documented global functions and
variables, the various internals in gmp-impl.h etc can be left unadorned.
But internals used by the test programs or speed measuring programs
should have __GMP_DECLSPEC, and certainly constants or variables must
have it or the wrong address will be resolved.
In gcc __declspec can go at either the start or end of a prototype.
In Microsoft C __declspec must go at the start, or after the type like
void __declspec(...) *foo()". There's no __dllexport or anything to
guard against someone foolish #defining dllexport. _export used to be
available, but no longer.
In Borland C _export still exists, but needs to go after the type, like
"void _export foo();". Would have to change the __GMP_DECLSPEC syntax to
make use of that. Probably more trouble than it's worth. */
#if defined (__GNUC__)
#define __GMP_DECLSPEC_EXPORT __declspec(__dllexport__)
#define __GMP_DECLSPEC_IMPORT __declspec(__dllimport__)
#endif
#if defined (_MSC_VER) || defined (__BORLANDC__)
#define __GMP_DECLSPEC_EXPORT __declspec(dllexport)
#define __GMP_DECLSPEC_IMPORT __declspec(dllimport)
#endif
#ifdef __WATCOMC__
#define __GMP_DECLSPEC_EXPORT __export
#define __GMP_DECLSPEC_IMPORT __import
#endif
#ifdef __IBMC__
#define __GMP_DECLSPEC_EXPORT _Export
#define __GMP_DECLSPEC_IMPORT _Import
#endif
#if __GMP_LIBGMP_DLL
#ifdef __GMP_WITHIN_GMP
/* compiling to go into a DLL libgmp */
#define __GMP_DECLSPEC __GMP_DECLSPEC_EXPORT
#else
/* compiling to go into an application which will link to a DLL libgmp */
#define __GMP_DECLSPEC __GMP_DECLSPEC_IMPORT
#endif
#else
/* all other cases */
#define __GMP_DECLSPEC
#endif
#ifdef __GMP_SHORT_LIMB
typedef unsigned int mp_limb_t;
typedef int mp_limb_signed_t;
#else
#ifdef _LONG_LONG_LIMB
typedef unsigned long long int mp_limb_t;
typedef long long int mp_limb_signed_t;
#else
typedef unsigned long int mp_limb_t;
typedef long int mp_limb_signed_t;
#endif
#endif
typedef unsigned long int mp_bitcnt_t;
/* For reference, note that the name __mpz_struct gets into C++ mangled
function names, which means although the "__" suggests an internal, we
must leave this name for binary compatibility. */
typedef struct
{
int _mp_alloc; /* Number of *limbs* allocated and pointed
to by the _mp_d field. */
int _mp_size; /* abs(_mp_size) is the number of limbs the
last field points to. If _mp_size is
negative this is a negative number. */
mp_limb_t *_mp_d; /* Pointer to the limbs. */
} __mpz_struct;
#endif /* __GNU_MP__ */
typedef __mpz_struct MP_INT; /* gmp 1 source compatibility */
typedef __mpz_struct mpz_t[1];
typedef mp_limb_t * mp_ptr;
typedef const mp_limb_t * mp_srcptr;
#if defined (_CRAY) && ! defined (_CRAYMPP)
/* plain `int' is much faster (48 bits) */
#define __GMP_MP_SIZE_T_INT 1
typedef int mp_size_t;
typedef int mp_exp_t;
#else
#define __GMP_MP_SIZE_T_INT 0
typedef long int mp_size_t;
typedef long int mp_exp_t;
#endif
typedef struct
{
__mpz_struct _mp_num;
__mpz_struct _mp_den;
} __mpq_struct;
typedef __mpq_struct MP_RAT; /* gmp 1 source compatibility */
typedef __mpq_struct mpq_t[1];
typedef struct
{
int _mp_prec; /* Max precision, in number of `mp_limb_t's.
Set by mpf_init and modified by
mpf_set_prec. The area pointed to by the
_mp_d field contains `prec' + 1 limbs. */
int _mp_size; /* abs(_mp_size) is the number of limbs the
last field points to. If _mp_size is
negative this is a negative number. */
mp_exp_t _mp_exp; /* Exponent, in the base of `mp_limb_t'. */
mp_limb_t *_mp_d; /* Pointer to the limbs. */
} __mpf_struct;
/* typedef __mpf_struct MP_FLOAT; */
typedef __mpf_struct mpf_t[1];
/* Available random number generation algorithms. */
typedef enum
{
GMP_RAND_ALG_DEFAULT = 0,
GMP_RAND_ALG_LC = GMP_RAND_ALG_DEFAULT /* Linear congruential. */
} gmp_randalg_t;
/* Random state struct. */
typedef struct
{
mpz_t _mp_seed; /* _mp_d member points to state of the generator. */
gmp_randalg_t _mp_alg; /* Currently unused. */
union {
void *_mp_lc; /* Pointer to function pointers structure. */
} _mp_algdata;
} __gmp_randstate_struct;
typedef __gmp_randstate_struct gmp_randstate_t[1];
/* Types for function declarations in gmp files. */
/* ??? Should not pollute user name space with these ??? */
typedef const __mpz_struct *mpz_srcptr;
typedef __mpz_struct *mpz_ptr;
typedef const __mpf_struct *mpf_srcptr;
typedef __mpf_struct *mpf_ptr;
typedef const __mpq_struct *mpq_srcptr;
typedef __mpq_struct *mpq_ptr;
typedef __gmp_randstate_struct *gmp_randstate_ptr;
typedef const __gmp_randstate_struct *gmp_randstate_srcptr;
#if __GMP_LIBGMP_DLL
#ifdef __GMP_WITHIN_GMPXX
/* compiling to go into a DLL libgmpxx */
#define __GMP_DECLSPEC_XX __GMP_DECLSPEC_EXPORT
#else
/* compiling to go into a application which will link to a DLL libgmpxx */
#define __GMP_DECLSPEC_XX __GMP_DECLSPEC_IMPORT
#endif
#else
/* all other cases */
#define __GMP_DECLSPEC_XX
#endif
#ifndef __MPN
#define __MPN(x) __gmpn_##x
#endif
/* For reference, "defined(EOF)" cannot be used here. In g++ 2.95.4,
<iostream> defines EOF but not FILE. */
#if defined (FILE) \
|| defined (H_STDIO) \
|| defined (_H_STDIO) /* AIX */ \
|| defined (_STDIO_H) /* glibc, Sun, SCO */ \
|| defined (_STDIO_H_) /* BSD, OSF */ \
|| defined (__STDIO_H) /* Borland */ \
|| defined (__STDIO_H__) /* IRIX */ \
|| defined (_STDIO_INCLUDED) /* HPUX */ \
|| defined (__dj_include_stdio_h_) /* DJGPP */ \
|| defined (_FILE_DEFINED) /* Microsoft */ \
|| defined (__STDIO__) /* Apple MPW MrC */ \
|| defined (_MSL_STDIO_H) /* Metrowerks */ \
|| defined (_STDIO_H_INCLUDED) /* QNX4 */ \
|| defined (_ISO_STDIO_ISO_H) /* Sun C++ */ \
|| defined (__STDIO_LOADED) /* VMS */ \
|| defined (_STDIO) /* HPE NonStop */ \
|| defined (__DEFINED_FILE) /* musl */
#define _GMP_H_HAVE_FILE 1
#endif
/* In ISO C, if a prototype involving "struct obstack *" is given without
that structure defined, then the struct is scoped down to just the
prototype, causing a conflict if it's subsequently defined for real. So
only give prototypes if we've got obstack.h. */
#if defined (_OBSTACK_H) /* glibc <obstack.h> */
#define _GMP_H_HAVE_OBSTACK 1
#endif
/* The prototypes for gmp_vprintf etc are provided only if va_list is defined,
via an application having included <stdarg.h>. Usually va_list is a typedef
so can't be tested directly, but C99 specifies that va_start is a macro.
<stdio.h> will define some sort of va_list for vprintf and vfprintf, but
let's not bother trying to use that since it's not standard and since
application uses for gmp_vprintf etc will almost certainly require the
whole <stdarg.h> anyway. */
#ifdef va_start
#define _GMP_H_HAVE_VA_LIST 1
#endif
/* Test for gcc >= maj.min, as per __GNUC_PREREQ in glibc */
#if defined (__GNUC__) && defined (__GNUC_MINOR__)
#define __GMP_GNUC_PREREQ(maj, min) \
((__GNUC__ << 16) + __GNUC_MINOR__ >= ((maj) << 16) + (min))
#else
#define __GMP_GNUC_PREREQ(maj, min) 0
#endif
/* "pure" is in gcc 2.96 and up, see "(gcc)Function Attributes". Basically
it means a function does nothing but examine its arguments and memory
(global or via arguments) to generate a return value, but changes nothing
and has no side-effects. __GMP_NO_ATTRIBUTE_CONST_PURE lets
tune/common.c etc turn this off when trying to write timing loops. */
#if __GMP_GNUC_PREREQ (2,96) && ! defined (__GMP_NO_ATTRIBUTE_CONST_PURE)
#define __GMP_ATTRIBUTE_PURE __attribute__ ((__pure__))
#else
#define __GMP_ATTRIBUTE_PURE
#endif
/* __GMP_CAST allows us to use static_cast in C++, so our macros are clean
to "g++ -Wold-style-cast".
Casts in "extern inline" code within an extern "C" block don't induce
these warnings, so __GMP_CAST only needs to be used on documented
macros. */
#ifdef __cplusplus
#define __GMP_CAST(type, expr) (static_cast<type> (expr))
#else
#define __GMP_CAST(type, expr) ((type) (expr))
#endif
/* An empty "throw ()" means the function doesn't throw any C++ exceptions,
this can save some stack frame info in applications.
Currently it's given only on functions which never divide-by-zero etc,
don't allocate memory, and are expected to never need to allocate memory.
This leaves open the possibility of a C++ throw from a future GMP
exceptions scheme.
mpz_set_ui etc are omitted to leave open the lazy allocation scheme
described in doc/tasks.html. mpz_get_d etc are omitted to leave open
exceptions for float overflows.
Note that __GMP_NOTHROW must be given on any inlines the same as on their
prototypes (for g++ at least, where they're used together). Note also
that g++ 3.0 demands that __GMP_NOTHROW is before other attributes like
__GMP_ATTRIBUTE_PURE. */
#if defined (__cplusplus)
#if __cplusplus >= 201103L
#define __GMP_NOTHROW noexcept
#else
#define __GMP_NOTHROW throw ()
#endif
#else
#define __GMP_NOTHROW
#endif
/* PORTME: What other compilers have a useful "extern inline"? "static
inline" would be an acceptable substitute if the compiler (or linker)
discards unused statics. */
/* gcc has __inline__ in all modes, including strict ansi. Give a prototype
for an inline too, so as to correctly specify "dllimport" on windows, in
case the function is called rather than inlined.
GCC 4.3 and above with -std=c99 or -std=gnu99 implements ISO C99
inline semantics, unless -fgnu89-inline is used. */
#ifdef __GNUC__
#if (defined __GNUC_STDC_INLINE__) || (__GNUC__ == 4 && __GNUC_MINOR__ == 2) \
|| (defined __GNUC_GNU_INLINE__ && defined __cplusplus)
#define __GMP_EXTERN_INLINE extern __inline__ __attribute__ ((__gnu_inline__))
#else
#define __GMP_EXTERN_INLINE extern __inline__
#endif
#define __GMP_INLINE_PROTOTYPES 1
#endif
/* DEC C (eg. version 5.9) supports "static __inline foo()", even in -std1
strict ANSI mode. Inlining is done even when not optimizing (ie. -O0
mode, which is the default), but an unnecessary local copy of foo is
emitted unless -O is used. "extern __inline" is accepted, but the
"extern" appears to be ignored, ie. it becomes a plain global function
but which is inlined within its file. Don't know if all old versions of
DEC C supported __inline, but as a start let's do the right thing for
current versions. */
#ifdef __DECC
#define __GMP_EXTERN_INLINE static __inline
#endif
/* SCO OpenUNIX 8 cc supports "static inline foo()" but not in -Xc strict
ANSI mode (__STDC__ is 1 in that mode). Inlining only actually takes
place under -O. Without -O "foo" seems to be emitted whether it's used
or not, which is wasteful. "extern inline foo()" isn't useful, the
"extern" is apparently ignored, so foo is inlined if possible but also
emitted as a global, which causes multiple definition errors when
building a shared libgmp. */
#ifdef __SCO_VERSION__
#if __SCO_VERSION__ > 400000000 && __STDC__ != 1 \
&& ! defined (__GMP_EXTERN_INLINE)
#define __GMP_EXTERN_INLINE static inline
#endif
#endif
/* Microsoft's C compiler accepts __inline */
#ifdef _MSC_VER
#define __GMP_EXTERN_INLINE __inline
#endif
/* Recent enough Sun C compilers want "inline" */
#if defined (__SUNPRO_C) && __SUNPRO_C >= 0x560 \
&& ! defined (__GMP_EXTERN_INLINE)
#define __GMP_EXTERN_INLINE inline
#endif
/* Somewhat older Sun C compilers want "static inline" */
#if defined (__SUNPRO_C) && __SUNPRO_C >= 0x540 \
&& ! defined (__GMP_EXTERN_INLINE)
#define __GMP_EXTERN_INLINE static inline
#endif
/* C++ always has "inline" and since it's a normal feature the linker should
discard duplicate non-inlined copies, or if it doesn't then that's a
problem for everyone, not just GMP. */
#if defined (__cplusplus) && ! defined (__GMP_EXTERN_INLINE)
#define __GMP_EXTERN_INLINE inline
#endif
/* Don't do any inlining within a configure run, since if the compiler ends
up emitting copies of the code into the object file it can end up
demanding the various support routines (like mpn_popcount) for linking,
making the "alloca" test and perhaps others fail. And on hppa ia64 a
pre-release gcc 3.2 was seen not respecting the "extern" in "extern
__inline__", triggering this problem too. */
#if defined (__GMP_WITHIN_CONFIGURE) && ! __GMP_WITHIN_CONFIGURE_INLINE
#undef __GMP_EXTERN_INLINE
#endif
/* By default, don't give a prototype when there's going to be an inline
version. Note in particular that Cray C++ objects to the combination of
prototype and inline. */
#ifdef __GMP_EXTERN_INLINE
#ifndef __GMP_INLINE_PROTOTYPES
#define __GMP_INLINE_PROTOTYPES 0
#endif
#else
#define __GMP_INLINE_PROTOTYPES 1
#endif
#define __GMP_ABS(x) ((x) >= 0 ? (x) : -(x))
#define __GMP_MAX(h,i) ((h) > (i) ? (h) : (i))
/* __builtin_expect is in gcc 3.0, and not in 2.95. */
#if __GMP_GNUC_PREREQ (3,0)
#define __GMP_LIKELY(cond) __builtin_expect ((cond) != 0, 1)
#define __GMP_UNLIKELY(cond) __builtin_expect ((cond) != 0, 0)
#else
#define __GMP_LIKELY(cond) (cond)
#define __GMP_UNLIKELY(cond) (cond)
#endif
#ifdef _CRAY
#define __GMP_CRAY_Pragma(str) _Pragma (str)
#else
#define __GMP_CRAY_Pragma(str)
#endif
/* Allow direct user access to numerator and denominator of an mpq_t object. */
#define mpq_numref(Q) (&((Q)->_mp_num))
#define mpq_denref(Q) (&((Q)->_mp_den))
#if defined (__cplusplus)
extern "C" {
using std::FILE;
#endif
#define mp_set_memory_functions __gmp_set_memory_functions
__GMP_DECLSPEC void mp_set_memory_functions (void *(*) (size_t),
void *(*) (void *, size_t, size_t),
void (*) (void *, size_t)) __GMP_NOTHROW;
#define mp_get_memory_functions __gmp_get_memory_functions
__GMP_DECLSPEC void mp_get_memory_functions (void *(**) (size_t),
void *(**) (void *, size_t, size_t),
void (**) (void *, size_t)) __GMP_NOTHROW;
#define mp_bits_per_limb __gmp_bits_per_limb
__GMP_DECLSPEC extern const int mp_bits_per_limb;
#define gmp_errno __gmp_errno
__GMP_DECLSPEC extern int gmp_errno;
#define gmp_version __gmp_version
__GMP_DECLSPEC extern const char * const gmp_version;
/**************** Random number routines. ****************/
/* obsolete */
#define gmp_randinit __gmp_randinit
__GMP_DECLSPEC void gmp_randinit (gmp_randstate_ptr, gmp_randalg_t, ...);
#define gmp_randinit_default __gmp_randinit_default
__GMP_DECLSPEC void gmp_randinit_default (gmp_randstate_ptr);
#define gmp_randinit_lc_2exp __gmp_randinit_lc_2exp
__GMP_DECLSPEC void gmp_randinit_lc_2exp (gmp_randstate_ptr, mpz_srcptr, unsigned long int, mp_bitcnt_t);
#define gmp_randinit_lc_2exp_size __gmp_randinit_lc_2exp_size
__GMP_DECLSPEC int gmp_randinit_lc_2exp_size (gmp_randstate_ptr, mp_bitcnt_t);
#define gmp_randinit_mt __gmp_randinit_mt
__GMP_DECLSPEC void gmp_randinit_mt (gmp_randstate_ptr);
#define gmp_randinit_set __gmp_randinit_set
__GMP_DECLSPEC void gmp_randinit_set (gmp_randstate_ptr, gmp_randstate_srcptr);
#define gmp_randseed __gmp_randseed
__GMP_DECLSPEC void gmp_randseed (gmp_randstate_ptr, mpz_srcptr);
#define gmp_randseed_ui __gmp_randseed_ui
__GMP_DECLSPEC void gmp_randseed_ui (gmp_randstate_ptr, unsigned long int);
#define gmp_randclear __gmp_randclear
__GMP_DECLSPEC void gmp_randclear (gmp_randstate_ptr);
#define gmp_urandomb_ui __gmp_urandomb_ui
__GMP_DECLSPEC unsigned long gmp_urandomb_ui (gmp_randstate_ptr, unsigned long);
#define gmp_urandomm_ui __gmp_urandomm_ui
__GMP_DECLSPEC unsigned long gmp_urandomm_ui (gmp_randstate_ptr, unsigned long);
/**************** Formatted output routines. ****************/
#define gmp_asprintf __gmp_asprintf
__GMP_DECLSPEC int gmp_asprintf (char **, const char *, ...);
#define gmp_fprintf __gmp_fprintf
#ifdef _GMP_H_HAVE_FILE
__GMP_DECLSPEC int gmp_fprintf (FILE *, const char *, ...);
#endif
#define gmp_obstack_printf __gmp_obstack_printf
#if defined (_GMP_H_HAVE_OBSTACK)
__GMP_DECLSPEC int gmp_obstack_printf (struct obstack *, const char *, ...);
#endif
#define gmp_obstack_vprintf __gmp_obstack_vprintf
#if defined (_GMP_H_HAVE_OBSTACK) && defined (_GMP_H_HAVE_VA_LIST)
__GMP_DECLSPEC int gmp_obstack_vprintf (struct obstack *, const char *, va_list);
#endif
#define gmp_printf __gmp_printf
__GMP_DECLSPEC int gmp_printf (const char *, ...);
#define gmp_snprintf __gmp_snprintf
__GMP_DECLSPEC int gmp_snprintf (char *, size_t, const char *, ...);
#define gmp_sprintf __gmp_sprintf
__GMP_DECLSPEC int gmp_sprintf (char *, const char *, ...);
#define gmp_vasprintf __gmp_vasprintf
#if defined (_GMP_H_HAVE_VA_LIST)
__GMP_DECLSPEC int gmp_vasprintf (char **, const char *, va_list);
#endif
#define gmp_vfprintf __gmp_vfprintf
#if defined (_GMP_H_HAVE_FILE) && defined (_GMP_H_HAVE_VA_LIST)
__GMP_DECLSPEC int gmp_vfprintf (FILE *, const char *, va_list);
#endif
#define gmp_vprintf __gmp_vprintf
#if defined (_GMP_H_HAVE_VA_LIST)
__GMP_DECLSPEC int gmp_vprintf (const char *, va_list);
#endif
#define gmp_vsnprintf __gmp_vsnprintf
#if defined (_GMP_H_HAVE_VA_LIST)
__GMP_DECLSPEC int gmp_vsnprintf (char *, size_t, const char *, va_list);
#endif
#define gmp_vsprintf __gmp_vsprintf
#if defined (_GMP_H_HAVE_VA_LIST)
__GMP_DECLSPEC int gmp_vsprintf (char *, const char *, va_list);
#endif
/**************** Formatted input routines. ****************/
#define gmp_fscanf __gmp_fscanf
#ifdef _GMP_H_HAVE_FILE
__GMP_DECLSPEC int gmp_fscanf (FILE *, const char *, ...);
#endif
#define gmp_scanf __gmp_scanf
__GMP_DECLSPEC int gmp_scanf (const char *, ...);
#define gmp_sscanf __gmp_sscanf
__GMP_DECLSPEC int gmp_sscanf (const char *, const char *, ...);
#define gmp_vfscanf __gmp_vfscanf
#if defined (_GMP_H_HAVE_FILE) && defined (_GMP_H_HAVE_VA_LIST)
__GMP_DECLSPEC int gmp_vfscanf (FILE *, const char *, va_list);
#endif
#define gmp_vscanf __gmp_vscanf
#if defined (_GMP_H_HAVE_VA_LIST)
__GMP_DECLSPEC int gmp_vscanf (const char *, va_list);
#endif
#define gmp_vsscanf __gmp_vsscanf
#if defined (_GMP_H_HAVE_VA_LIST)
__GMP_DECLSPEC int gmp_vsscanf (const char *, const char *, va_list);
#endif
/**************** Integer (i.e. Z) routines. ****************/
#define _mpz_realloc __gmpz_realloc
#define mpz_realloc __gmpz_realloc
__GMP_DECLSPEC void *_mpz_realloc (mpz_ptr, mp_size_t);
#define mpz_abs __gmpz_abs
#if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpz_abs)
__GMP_DECLSPEC void mpz_abs (mpz_ptr, mpz_srcptr);
#endif
#define mpz_add __gmpz_add
__GMP_DECLSPEC void mpz_add (mpz_ptr, mpz_srcptr, mpz_srcptr);
#define mpz_add_ui __gmpz_add_ui
__GMP_DECLSPEC void mpz_add_ui (mpz_ptr, mpz_srcptr, unsigned long int);
#define mpz_addmul __gmpz_addmul
__GMP_DECLSPEC void mpz_addmul (mpz_ptr, mpz_srcptr, mpz_srcptr);
#define mpz_addmul_ui __gmpz_addmul_ui
__GMP_DECLSPEC void mpz_addmul_ui (mpz_ptr, mpz_srcptr, unsigned long int);
#define mpz_and __gmpz_and
__GMP_DECLSPEC void mpz_and (mpz_ptr, mpz_srcptr, mpz_srcptr);
#define mpz_array_init __gmpz_array_init
__GMP_DECLSPEC void mpz_array_init (mpz_ptr, mp_size_t, mp_size_t);
#define mpz_bin_ui __gmpz_bin_ui
__GMP_DECLSPEC void mpz_bin_ui (mpz_ptr, mpz_srcptr, unsigned long int);
#define mpz_bin_uiui __gmpz_bin_uiui
__GMP_DECLSPEC void mpz_bin_uiui (mpz_ptr, unsigned long int, unsigned long int);
#define mpz_cdiv_q __gmpz_cdiv_q
__GMP_DECLSPEC void mpz_cdiv_q (mpz_ptr, mpz_srcptr, mpz_srcptr);
#define mpz_cdiv_q_2exp __gmpz_cdiv_q_2exp
__GMP_DECLSPEC void mpz_cdiv_q_2exp (mpz_ptr, mpz_srcptr, mp_bitcnt_t);
#define mpz_cdiv_q_ui __gmpz_cdiv_q_ui
__GMP_DECLSPEC unsigned long int mpz_cdiv_q_ui (mpz_ptr, mpz_srcptr, unsigned long int);
#define mpz_cdiv_qr __gmpz_cdiv_qr
__GMP_DECLSPEC void mpz_cdiv_qr (mpz_ptr, mpz_ptr, mpz_srcptr, mpz_srcptr);
#define mpz_cdiv_qr_ui __gmpz_cdiv_qr_ui
__GMP_DECLSPEC unsigned long int mpz_cdiv_qr_ui (mpz_ptr, mpz_ptr, mpz_srcptr, unsigned long int);
#define mpz_cdiv_r __gmpz_cdiv_r
__GMP_DECLSPEC void mpz_cdiv_r (mpz_ptr, mpz_srcptr, mpz_srcptr);
#define mpz_cdiv_r_2exp __gmpz_cdiv_r_2exp
__GMP_DECLSPEC void mpz_cdiv_r_2exp (mpz_ptr, mpz_srcptr, mp_bitcnt_t);
#define mpz_cdiv_r_ui __gmpz_cdiv_r_ui
__GMP_DECLSPEC unsigned long int mpz_cdiv_r_ui (mpz_ptr, mpz_srcptr, unsigned long int);
#define mpz_cdiv_ui __gmpz_cdiv_ui
__GMP_DECLSPEC unsigned long int mpz_cdiv_ui (mpz_srcptr, unsigned long int) __GMP_ATTRIBUTE_PURE;
#define mpz_clear __gmpz_clear
__GMP_DECLSPEC void mpz_clear (mpz_ptr);
#define mpz_clears __gmpz_clears
__GMP_DECLSPEC void mpz_clears (mpz_ptr, ...);
#define mpz_clrbit __gmpz_clrbit
__GMP_DECLSPEC void mpz_clrbit (mpz_ptr, mp_bitcnt_t);
#define mpz_cmp __gmpz_cmp
__GMP_DECLSPEC int mpz_cmp (mpz_srcptr, mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#define mpz_cmp_d __gmpz_cmp_d
__GMP_DECLSPEC int mpz_cmp_d (mpz_srcptr, double) __GMP_ATTRIBUTE_PURE;
#define _mpz_cmp_si __gmpz_cmp_si
__GMP_DECLSPEC int _mpz_cmp_si (mpz_srcptr, signed long int) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#define _mpz_cmp_ui __gmpz_cmp_ui
__GMP_DECLSPEC int _mpz_cmp_ui (mpz_srcptr, unsigned long int) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#define mpz_cmpabs __gmpz_cmpabs
__GMP_DECLSPEC int mpz_cmpabs (mpz_srcptr, mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#define mpz_cmpabs_d __gmpz_cmpabs_d
__GMP_DECLSPEC int mpz_cmpabs_d (mpz_srcptr, double) __GMP_ATTRIBUTE_PURE;
#define mpz_cmpabs_ui __gmpz_cmpabs_ui
__GMP_DECLSPEC int mpz_cmpabs_ui (mpz_srcptr, unsigned long int) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#define mpz_com __gmpz_com
__GMP_DECLSPEC void mpz_com (mpz_ptr, mpz_srcptr);
#define mpz_combit __gmpz_combit
__GMP_DECLSPEC void mpz_combit (mpz_ptr, mp_bitcnt_t);
#define mpz_congruent_p __gmpz_congruent_p
__GMP_DECLSPEC int mpz_congruent_p (mpz_srcptr, mpz_srcptr, mpz_srcptr) __GMP_ATTRIBUTE_PURE;
#define mpz_congruent_2exp_p __gmpz_congruent_2exp_p
__GMP_DECLSPEC int mpz_congruent_2exp_p (mpz_srcptr, mpz_srcptr, mp_bitcnt_t) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#define mpz_congruent_ui_p __gmpz_congruent_ui_p
__GMP_DECLSPEC int mpz_congruent_ui_p (mpz_srcptr, unsigned long, unsigned long) __GMP_ATTRIBUTE_PURE;
#define mpz_divexact __gmpz_divexact
__GMP_DECLSPEC void mpz_divexact (mpz_ptr, mpz_srcptr, mpz_srcptr);
#define mpz_divexact_ui __gmpz_divexact_ui
__GMP_DECLSPEC void mpz_divexact_ui (mpz_ptr, mpz_srcptr, unsigned long);
#define mpz_divisible_p __gmpz_divisible_p
__GMP_DECLSPEC int mpz_divisible_p (mpz_srcptr, mpz_srcptr) __GMP_ATTRIBUTE_PURE;
#define mpz_divisible_ui_p __gmpz_divisible_ui_p
__GMP_DECLSPEC int mpz_divisible_ui_p (mpz_srcptr, unsigned long) __GMP_ATTRIBUTE_PURE;
#define mpz_divisible_2exp_p __gmpz_divisible_2exp_p
__GMP_DECLSPEC int mpz_divisible_2exp_p (mpz_srcptr, mp_bitcnt_t) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#define mpz_dump __gmpz_dump
__GMP_DECLSPEC void mpz_dump (mpz_srcptr);
#define mpz_export __gmpz_export
__GMP_DECLSPEC void *mpz_export (void *, size_t *, int, size_t, int, size_t, mpz_srcptr);
#define mpz_fac_ui __gmpz_fac_ui
__GMP_DECLSPEC void mpz_fac_ui (mpz_ptr, unsigned long int);
#define mpz_2fac_ui __gmpz_2fac_ui
__GMP_DECLSPEC void mpz_2fac_ui (mpz_ptr, unsigned long int);
#define mpz_mfac_uiui __gmpz_mfac_uiui
__GMP_DECLSPEC void mpz_mfac_uiui (mpz_ptr, unsigned long int, unsigned long int);
#define mpz_primorial_ui __gmpz_primorial_ui
__GMP_DECLSPEC void mpz_primorial_ui (mpz_ptr, unsigned long int);
#define mpz_fdiv_q __gmpz_fdiv_q
__GMP_DECLSPEC void mpz_fdiv_q (mpz_ptr, mpz_srcptr, mpz_srcptr);
#define mpz_fdiv_q_2exp __gmpz_fdiv_q_2exp
__GMP_DECLSPEC void mpz_fdiv_q_2exp (mpz_ptr, mpz_srcptr, mp_bitcnt_t);
#define mpz_fdiv_q_ui __gmpz_fdiv_q_ui
__GMP_DECLSPEC unsigned long int mpz_fdiv_q_ui (mpz_ptr, mpz_srcptr, unsigned long int);
#define mpz_fdiv_qr __gmpz_fdiv_qr
__GMP_DECLSPEC void mpz_fdiv_qr (mpz_ptr, mpz_ptr, mpz_srcptr, mpz_srcptr);
#define mpz_fdiv_qr_ui __gmpz_fdiv_qr_ui
__GMP_DECLSPEC unsigned long int mpz_fdiv_qr_ui (mpz_ptr, mpz_ptr, mpz_srcptr, unsigned long int);
#define mpz_fdiv_r __gmpz_fdiv_r
__GMP_DECLSPEC void mpz_fdiv_r (mpz_ptr, mpz_srcptr, mpz_srcptr);
#define mpz_fdiv_r_2exp __gmpz_fdiv_r_2exp
__GMP_DECLSPEC void mpz_fdiv_r_2exp (mpz_ptr, mpz_srcptr, mp_bitcnt_t);
#define mpz_fdiv_r_ui __gmpz_fdiv_r_ui
__GMP_DECLSPEC unsigned long int mpz_fdiv_r_ui (mpz_ptr, mpz_srcptr, unsigned long int);
#define mpz_fdiv_ui __gmpz_fdiv_ui
__GMP_DECLSPEC unsigned long int mpz_fdiv_ui (mpz_srcptr, unsigned long int) __GMP_ATTRIBUTE_PURE;
#define mpz_fib_ui __gmpz_fib_ui
__GMP_DECLSPEC void mpz_fib_ui (mpz_ptr, unsigned long int);
#define mpz_fib2_ui __gmpz_fib2_ui
__GMP_DECLSPEC void mpz_fib2_ui (mpz_ptr, mpz_ptr, unsigned long int);
#define mpz_fits_sint_p __gmpz_fits_sint_p
__GMP_DECLSPEC int mpz_fits_sint_p (mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#define mpz_fits_slong_p __gmpz_fits_slong_p
__GMP_DECLSPEC int mpz_fits_slong_p (mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#define mpz_fits_sshort_p __gmpz_fits_sshort_p
__GMP_DECLSPEC int mpz_fits_sshort_p (mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#define mpz_fits_uint_p __gmpz_fits_uint_p
#if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpz_fits_uint_p)
__GMP_DECLSPEC int mpz_fits_uint_p (mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#endif
#define mpz_fits_ulong_p __gmpz_fits_ulong_p
#if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpz_fits_ulong_p)
__GMP_DECLSPEC int mpz_fits_ulong_p (mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#endif
#define mpz_fits_ushort_p __gmpz_fits_ushort_p
#if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpz_fits_ushort_p)
__GMP_DECLSPEC int mpz_fits_ushort_p (mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#endif
#define mpz_gcd __gmpz_gcd
__GMP_DECLSPEC void mpz_gcd (mpz_ptr, mpz_srcptr, mpz_srcptr);
#define mpz_gcd_ui __gmpz_gcd_ui
__GMP_DECLSPEC unsigned long int mpz_gcd_ui (mpz_ptr, mpz_srcptr, unsigned long int);
#define mpz_gcdext __gmpz_gcdext
__GMP_DECLSPEC void mpz_gcdext (mpz_ptr, mpz_ptr, mpz_ptr, mpz_srcptr, mpz_srcptr);
#define mpz_get_d __gmpz_get_d
__GMP_DECLSPEC double mpz_get_d (mpz_srcptr) __GMP_ATTRIBUTE_PURE;
#define mpz_get_d_2exp __gmpz_get_d_2exp
__GMP_DECLSPEC double mpz_get_d_2exp (signed long int *, mpz_srcptr);
#define mpz_get_si __gmpz_get_si
__GMP_DECLSPEC /* signed */ long int mpz_get_si (mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#define mpz_get_str __gmpz_get_str
__GMP_DECLSPEC char *mpz_get_str (char *, int, mpz_srcptr);
#define mpz_get_ui __gmpz_get_ui
#if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpz_get_ui)
__GMP_DECLSPEC unsigned long int mpz_get_ui (mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#endif
#define mpz_getlimbn __gmpz_getlimbn
#if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpz_getlimbn)
__GMP_DECLSPEC mp_limb_t mpz_getlimbn (mpz_srcptr, mp_size_t) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#endif
#define mpz_hamdist __gmpz_hamdist
__GMP_DECLSPEC mp_bitcnt_t mpz_hamdist (mpz_srcptr, mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#define mpz_import __gmpz_import
__GMP_DECLSPEC void mpz_import (mpz_ptr, size_t, int, size_t, int, size_t, const void *);
#define mpz_init __gmpz_init
__GMP_DECLSPEC void mpz_init (mpz_ptr) __GMP_NOTHROW;
#define mpz_init2 __gmpz_init2
__GMP_DECLSPEC void mpz_init2 (mpz_ptr, mp_bitcnt_t);
#define mpz_inits __gmpz_inits
__GMP_DECLSPEC void mpz_inits (mpz_ptr, ...) __GMP_NOTHROW;
#define mpz_init_set __gmpz_init_set
__GMP_DECLSPEC void mpz_init_set (mpz_ptr, mpz_srcptr);
#define mpz_init_set_d __gmpz_init_set_d
__GMP_DECLSPEC void mpz_init_set_d (mpz_ptr, double);
#define mpz_init_set_si __gmpz_init_set_si
__GMP_DECLSPEC void mpz_init_set_si (mpz_ptr, signed long int);
#define mpz_init_set_str __gmpz_init_set_str
__GMP_DECLSPEC int mpz_init_set_str (mpz_ptr, const char *, int);
#define mpz_init_set_ui __gmpz_init_set_ui
__GMP_DECLSPEC void mpz_init_set_ui (mpz_ptr, unsigned long int);
#define mpz_inp_raw __gmpz_inp_raw
#ifdef _GMP_H_HAVE_FILE
__GMP_DECLSPEC size_t mpz_inp_raw (mpz_ptr, FILE *);
#endif
#define mpz_inp_str __gmpz_inp_str
#ifdef _GMP_H_HAVE_FILE
__GMP_DECLSPEC size_t mpz_inp_str (mpz_ptr, FILE *, int);
#endif
#define mpz_invert __gmpz_invert
__GMP_DECLSPEC int mpz_invert (mpz_ptr, mpz_srcptr, mpz_srcptr);
#define mpz_ior __gmpz_ior
__GMP_DECLSPEC void mpz_ior (mpz_ptr, mpz_srcptr, mpz_srcptr);
#define mpz_jacobi __gmpz_jacobi
__GMP_DECLSPEC int mpz_jacobi (mpz_srcptr, mpz_srcptr) __GMP_ATTRIBUTE_PURE;
#define mpz_kronecker mpz_jacobi /* alias */
#define mpz_kronecker_si __gmpz_kronecker_si
__GMP_DECLSPEC int mpz_kronecker_si (mpz_srcptr, long) __GMP_ATTRIBUTE_PURE;
#define mpz_kronecker_ui __gmpz_kronecker_ui
__GMP_DECLSPEC int mpz_kronecker_ui (mpz_srcptr, unsigned long) __GMP_ATTRIBUTE_PURE;
#define mpz_si_kronecker __gmpz_si_kronecker
__GMP_DECLSPEC int mpz_si_kronecker (long, mpz_srcptr) __GMP_ATTRIBUTE_PURE;
#define mpz_ui_kronecker __gmpz_ui_kronecker
__GMP_DECLSPEC int mpz_ui_kronecker (unsigned long, mpz_srcptr) __GMP_ATTRIBUTE_PURE;
#define mpz_lcm __gmpz_lcm
__GMP_DECLSPEC void mpz_lcm (mpz_ptr, mpz_srcptr, mpz_srcptr);
#define mpz_lcm_ui __gmpz_lcm_ui
__GMP_DECLSPEC void mpz_lcm_ui (mpz_ptr, mpz_srcptr, unsigned long);
#define mpz_legendre mpz_jacobi /* alias */
#define mpz_lucnum_ui __gmpz_lucnum_ui
__GMP_DECLSPEC void mpz_lucnum_ui (mpz_ptr, unsigned long int);
#define mpz_lucnum2_ui __gmpz_lucnum2_ui
__GMP_DECLSPEC void mpz_lucnum2_ui (mpz_ptr, mpz_ptr, unsigned long int);
#define mpz_millerrabin __gmpz_millerrabin
__GMP_DECLSPEC int mpz_millerrabin (mpz_srcptr, int) __GMP_ATTRIBUTE_PURE;
#define mpz_mod __gmpz_mod
__GMP_DECLSPEC void mpz_mod (mpz_ptr, mpz_srcptr, mpz_srcptr);
#define mpz_mod_ui mpz_fdiv_r_ui /* same as fdiv_r because divisor unsigned */
#define mpz_mul __gmpz_mul
__GMP_DECLSPEC void mpz_mul (mpz_ptr, mpz_srcptr, mpz_srcptr);
#define mpz_mul_2exp __gmpz_mul_2exp
__GMP_DECLSPEC void mpz_mul_2exp (mpz_ptr, mpz_srcptr, mp_bitcnt_t);
#define mpz_mul_si __gmpz_mul_si
__GMP_DECLSPEC void mpz_mul_si (mpz_ptr, mpz_srcptr, long int);
#define mpz_mul_ui __gmpz_mul_ui
__GMP_DECLSPEC void mpz_mul_ui (mpz_ptr, mpz_srcptr, unsigned long int);
#define mpz_neg __gmpz_neg
#if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpz_neg)
__GMP_DECLSPEC void mpz_neg (mpz_ptr, mpz_srcptr);
#endif
#define mpz_nextprime __gmpz_nextprime
__GMP_DECLSPEC void mpz_nextprime (mpz_ptr, mpz_srcptr);
#define mpz_prevprime __gmpz_prevprime
__GMP_DECLSPEC int mpz_prevprime (mpz_ptr, mpz_srcptr);
#define mpz_out_raw __gmpz_out_raw
#ifdef _GMP_H_HAVE_FILE
__GMP_DECLSPEC size_t mpz_out_raw (FILE *, mpz_srcptr);
#endif
#define mpz_out_str __gmpz_out_str
#ifdef _GMP_H_HAVE_FILE
__GMP_DECLSPEC size_t mpz_out_str (FILE *, int, mpz_srcptr);
#endif
#define mpz_perfect_power_p __gmpz_perfect_power_p
__GMP_DECLSPEC int mpz_perfect_power_p (mpz_srcptr) __GMP_ATTRIBUTE_PURE;
#define mpz_perfect_square_p __gmpz_perfect_square_p
#if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpz_perfect_square_p)
__GMP_DECLSPEC int mpz_perfect_square_p (mpz_srcptr) __GMP_ATTRIBUTE_PURE;
#endif
#define mpz_popcount __gmpz_popcount
#if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpz_popcount)
__GMP_DECLSPEC mp_bitcnt_t mpz_popcount (mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#endif
#define mpz_pow_ui __gmpz_pow_ui
__GMP_DECLSPEC void mpz_pow_ui (mpz_ptr, mpz_srcptr, unsigned long int);
#define mpz_powm __gmpz_powm
__GMP_DECLSPEC void mpz_powm (mpz_ptr, mpz_srcptr, mpz_srcptr, mpz_srcptr);
#define mpz_powm_sec __gmpz_powm_sec
__GMP_DECLSPEC void mpz_powm_sec (mpz_ptr, mpz_srcptr, mpz_srcptr, mpz_srcptr);
#define mpz_powm_ui __gmpz_powm_ui
__GMP_DECLSPEC void mpz_powm_ui (mpz_ptr, mpz_srcptr, unsigned long int, mpz_srcptr);
#define mpz_probab_prime_p __gmpz_probab_prime_p
__GMP_DECLSPEC int mpz_probab_prime_p (mpz_srcptr, int) __GMP_ATTRIBUTE_PURE;
#define mpz_random __gmpz_random
__GMP_DECLSPEC void mpz_random (mpz_ptr, mp_size_t);
#define mpz_random2 __gmpz_random2
__GMP_DECLSPEC void mpz_random2 (mpz_ptr, mp_size_t);
#define mpz_realloc2 __gmpz_realloc2
__GMP_DECLSPEC void mpz_realloc2 (mpz_ptr, mp_bitcnt_t);
#define mpz_remove __gmpz_remove
__GMP_DECLSPEC mp_bitcnt_t mpz_remove (mpz_ptr, mpz_srcptr, mpz_srcptr);
#define mpz_root __gmpz_root
__GMP_DECLSPEC int mpz_root (mpz_ptr, mpz_srcptr, unsigned long int);
#define mpz_rootrem __gmpz_rootrem
__GMP_DECLSPEC void mpz_rootrem (mpz_ptr, mpz_ptr, mpz_srcptr, unsigned long int);
#define mpz_rrandomb __gmpz_rrandomb
__GMP_DECLSPEC void mpz_rrandomb (mpz_ptr, gmp_randstate_ptr, mp_bitcnt_t);
#define mpz_scan0 __gmpz_scan0
__GMP_DECLSPEC mp_bitcnt_t mpz_scan0 (mpz_srcptr, mp_bitcnt_t) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#define mpz_scan1 __gmpz_scan1
__GMP_DECLSPEC mp_bitcnt_t mpz_scan1 (mpz_srcptr, mp_bitcnt_t) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#define mpz_set __gmpz_set
__GMP_DECLSPEC void mpz_set (mpz_ptr, mpz_srcptr);
#define mpz_set_d __gmpz_set_d
__GMP_DECLSPEC void mpz_set_d (mpz_ptr, double);
#define mpz_set_f __gmpz_set_f
__GMP_DECLSPEC void mpz_set_f (mpz_ptr, mpf_srcptr);
#define mpz_set_q __gmpz_set_q
#if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpz_set_q)
__GMP_DECLSPEC void mpz_set_q (mpz_ptr, mpq_srcptr);
#endif
#define mpz_set_si __gmpz_set_si
__GMP_DECLSPEC void mpz_set_si (mpz_ptr, signed long int);
#define mpz_set_str __gmpz_set_str
__GMP_DECLSPEC int mpz_set_str (mpz_ptr, const char *, int);
#define mpz_set_ui __gmpz_set_ui
__GMP_DECLSPEC void mpz_set_ui (mpz_ptr, unsigned long int);
#define mpz_setbit __gmpz_setbit
__GMP_DECLSPEC void mpz_setbit (mpz_ptr, mp_bitcnt_t);
#define mpz_size __gmpz_size
#if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpz_size)
__GMP_DECLSPEC size_t mpz_size (mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#endif
#define mpz_sizeinbase __gmpz_sizeinbase
__GMP_DECLSPEC size_t mpz_sizeinbase (mpz_srcptr, int) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#define mpz_sqrt __gmpz_sqrt
__GMP_DECLSPEC void mpz_sqrt (mpz_ptr, mpz_srcptr);
#define mpz_sqrtrem __gmpz_sqrtrem
__GMP_DECLSPEC void mpz_sqrtrem (mpz_ptr, mpz_ptr, mpz_srcptr);
#define mpz_sub __gmpz_sub
__GMP_DECLSPEC void mpz_sub (mpz_ptr, mpz_srcptr, mpz_srcptr);
#define mpz_sub_ui __gmpz_sub_ui
__GMP_DECLSPEC void mpz_sub_ui (mpz_ptr, mpz_srcptr, unsigned long int);
#define mpz_ui_sub __gmpz_ui_sub
__GMP_DECLSPEC void mpz_ui_sub (mpz_ptr, unsigned long int, mpz_srcptr);
#define mpz_submul __gmpz_submul
__GMP_DECLSPEC void mpz_submul (mpz_ptr, mpz_srcptr, mpz_srcptr);
#define mpz_submul_ui __gmpz_submul_ui
__GMP_DECLSPEC void mpz_submul_ui (mpz_ptr, mpz_srcptr, unsigned long int);
#define mpz_swap __gmpz_swap
__GMP_DECLSPEC void mpz_swap (mpz_ptr, mpz_ptr) __GMP_NOTHROW;
#define mpz_tdiv_ui __gmpz_tdiv_ui
__GMP_DECLSPEC unsigned long int mpz_tdiv_ui (mpz_srcptr, unsigned long int) __GMP_ATTRIBUTE_PURE;
#define mpz_tdiv_q __gmpz_tdiv_q
__GMP_DECLSPEC void mpz_tdiv_q (mpz_ptr, mpz_srcptr, mpz_srcptr);
#define mpz_tdiv_q_2exp __gmpz_tdiv_q_2exp
__GMP_DECLSPEC void mpz_tdiv_q_2exp (mpz_ptr, mpz_srcptr, mp_bitcnt_t);
#define mpz_tdiv_q_ui __gmpz_tdiv_q_ui
__GMP_DECLSPEC unsigned long int mpz_tdiv_q_ui (mpz_ptr, mpz_srcptr, unsigned long int);
#define mpz_tdiv_qr __gmpz_tdiv_qr
__GMP_DECLSPEC void mpz_tdiv_qr (mpz_ptr, mpz_ptr, mpz_srcptr, mpz_srcptr);
#define mpz_tdiv_qr_ui __gmpz_tdiv_qr_ui
__GMP_DECLSPEC unsigned long int mpz_tdiv_qr_ui (mpz_ptr, mpz_ptr, mpz_srcptr, unsigned long int);
#define mpz_tdiv_r __gmpz_tdiv_r
__GMP_DECLSPEC void mpz_tdiv_r (mpz_ptr, mpz_srcptr, mpz_srcptr);
#define mpz_tdiv_r_2exp __gmpz_tdiv_r_2exp
__GMP_DECLSPEC void mpz_tdiv_r_2exp (mpz_ptr, mpz_srcptr, mp_bitcnt_t);
#define mpz_tdiv_r_ui __gmpz_tdiv_r_ui
__GMP_DECLSPEC unsigned long int mpz_tdiv_r_ui (mpz_ptr, mpz_srcptr, unsigned long int);
#define mpz_tstbit __gmpz_tstbit
__GMP_DECLSPEC int mpz_tstbit (mpz_srcptr, mp_bitcnt_t) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#define mpz_ui_pow_ui __gmpz_ui_pow_ui
__GMP_DECLSPEC void mpz_ui_pow_ui (mpz_ptr, unsigned long int, unsigned long int);
#define mpz_urandomb __gmpz_urandomb
__GMP_DECLSPEC void mpz_urandomb (mpz_ptr, gmp_randstate_ptr, mp_bitcnt_t);
#define mpz_urandomm __gmpz_urandomm
__GMP_DECLSPEC void mpz_urandomm (mpz_ptr, gmp_randstate_ptr, mpz_srcptr);
#define mpz_xor __gmpz_xor
#define mpz_eor __gmpz_xor
__GMP_DECLSPEC void mpz_xor (mpz_ptr, mpz_srcptr, mpz_srcptr);
#define mpz_limbs_read __gmpz_limbs_read
__GMP_DECLSPEC mp_srcptr mpz_limbs_read (mpz_srcptr);
#define mpz_limbs_write __gmpz_limbs_write
__GMP_DECLSPEC mp_ptr mpz_limbs_write (mpz_ptr, mp_size_t);
#define mpz_limbs_modify __gmpz_limbs_modify
__GMP_DECLSPEC mp_ptr mpz_limbs_modify (mpz_ptr, mp_size_t);
#define mpz_limbs_finish __gmpz_limbs_finish
__GMP_DECLSPEC void mpz_limbs_finish (mpz_ptr, mp_size_t);
#define mpz_roinit_n __gmpz_roinit_n
__GMP_DECLSPEC mpz_srcptr mpz_roinit_n (mpz_ptr, mp_srcptr, mp_size_t);
#define MPZ_ROINIT_N(xp, xs) {{0, (xs),(xp) }}
/**************** Rational (i.e. Q) routines. ****************/
#define mpq_abs __gmpq_abs
#if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpq_abs)
__GMP_DECLSPEC void mpq_abs (mpq_ptr, mpq_srcptr);
#endif
#define mpq_add __gmpq_add
__GMP_DECLSPEC void mpq_add (mpq_ptr, mpq_srcptr, mpq_srcptr);
#define mpq_canonicalize __gmpq_canonicalize
__GMP_DECLSPEC void mpq_canonicalize (mpq_ptr);
#define mpq_clear __gmpq_clear
__GMP_DECLSPEC void mpq_clear (mpq_ptr);
#define mpq_clears __gmpq_clears
__GMP_DECLSPEC void mpq_clears (mpq_ptr, ...);
#define mpq_cmp __gmpq_cmp
__GMP_DECLSPEC int mpq_cmp (mpq_srcptr, mpq_srcptr) __GMP_ATTRIBUTE_PURE;
#define _mpq_cmp_si __gmpq_cmp_si
__GMP_DECLSPEC int _mpq_cmp_si (mpq_srcptr, long, unsigned long) __GMP_ATTRIBUTE_PURE;
#define _mpq_cmp_ui __gmpq_cmp_ui
__GMP_DECLSPEC int _mpq_cmp_ui (mpq_srcptr, unsigned long int, unsigned long int) __GMP_ATTRIBUTE_PURE;
#define mpq_cmp_z __gmpq_cmp_z
__GMP_DECLSPEC int mpq_cmp_z (mpq_srcptr, mpz_srcptr) __GMP_ATTRIBUTE_PURE;
#define mpq_div __gmpq_div
__GMP_DECLSPEC void mpq_div (mpq_ptr, mpq_srcptr, mpq_srcptr);
#define mpq_div_2exp __gmpq_div_2exp
__GMP_DECLSPEC void mpq_div_2exp (mpq_ptr, mpq_srcptr, mp_bitcnt_t);
#define mpq_equal __gmpq_equal
__GMP_DECLSPEC int mpq_equal (mpq_srcptr, mpq_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#define mpq_get_num __gmpq_get_num
__GMP_DECLSPEC void mpq_get_num (mpz_ptr, mpq_srcptr);
#define mpq_get_den __gmpq_get_den
__GMP_DECLSPEC void mpq_get_den (mpz_ptr, mpq_srcptr);
#define mpq_get_d __gmpq_get_d
__GMP_DECLSPEC double mpq_get_d (mpq_srcptr) __GMP_ATTRIBUTE_PURE;
#define mpq_get_str __gmpq_get_str
__GMP_DECLSPEC char *mpq_get_str (char *, int, mpq_srcptr);
#define mpq_init __gmpq_init
__GMP_DECLSPEC void mpq_init (mpq_ptr);
#define mpq_inits __gmpq_inits
__GMP_DECLSPEC void mpq_inits (mpq_ptr, ...);
#define mpq_inp_str __gmpq_inp_str
#ifdef _GMP_H_HAVE_FILE
__GMP_DECLSPEC size_t mpq_inp_str (mpq_ptr, FILE *, int);
#endif
#define mpq_inv __gmpq_inv
__GMP_DECLSPEC void mpq_inv (mpq_ptr, mpq_srcptr);
#define mpq_mul __gmpq_mul
__GMP_DECLSPEC void mpq_mul (mpq_ptr, mpq_srcptr, mpq_srcptr);
#define mpq_mul_2exp __gmpq_mul_2exp
__GMP_DECLSPEC void mpq_mul_2exp (mpq_ptr, mpq_srcptr, mp_bitcnt_t);
#define mpq_neg __gmpq_neg
#if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpq_neg)
__GMP_DECLSPEC void mpq_neg (mpq_ptr, mpq_srcptr);
#endif
#define mpq_out_str __gmpq_out_str
#ifdef _GMP_H_HAVE_FILE
__GMP_DECLSPEC size_t mpq_out_str (FILE *, int, mpq_srcptr);
#endif
#define mpq_set __gmpq_set
__GMP_DECLSPEC void mpq_set (mpq_ptr, mpq_srcptr);
#define mpq_set_d __gmpq_set_d
__GMP_DECLSPEC void mpq_set_d (mpq_ptr, double);
#define mpq_set_den __gmpq_set_den
__GMP_DECLSPEC void mpq_set_den (mpq_ptr, mpz_srcptr);
#define mpq_set_f __gmpq_set_f
__GMP_DECLSPEC void mpq_set_f (mpq_ptr, mpf_srcptr);
#define mpq_set_num __gmpq_set_num
__GMP_DECLSPEC void mpq_set_num (mpq_ptr, mpz_srcptr);
#define mpq_set_si __gmpq_set_si
__GMP_DECLSPEC void mpq_set_si (mpq_ptr, signed long int, unsigned long int);
#define mpq_set_str __gmpq_set_str
__GMP_DECLSPEC int mpq_set_str (mpq_ptr, const char *, int);
#define mpq_set_ui __gmpq_set_ui
__GMP_DECLSPEC void mpq_set_ui (mpq_ptr, unsigned long int, unsigned long int);
#define mpq_set_z __gmpq_set_z
__GMP_DECLSPEC void mpq_set_z (mpq_ptr, mpz_srcptr);
#define mpq_sub __gmpq_sub
__GMP_DECLSPEC void mpq_sub (mpq_ptr, mpq_srcptr, mpq_srcptr);
#define mpq_swap __gmpq_swap
__GMP_DECLSPEC void mpq_swap (mpq_ptr, mpq_ptr) __GMP_NOTHROW;
/**************** Float (i.e. F) routines. ****************/
#define mpf_abs __gmpf_abs
__GMP_DECLSPEC void mpf_abs (mpf_ptr, mpf_srcptr);
#define mpf_add __gmpf_add
__GMP_DECLSPEC void mpf_add (mpf_ptr, mpf_srcptr, mpf_srcptr);
#define mpf_add_ui __gmpf_add_ui
__GMP_DECLSPEC void mpf_add_ui (mpf_ptr, mpf_srcptr, unsigned long int);
#define mpf_ceil __gmpf_ceil
__GMP_DECLSPEC void mpf_ceil (mpf_ptr, mpf_srcptr);
#define mpf_clear __gmpf_clear
__GMP_DECLSPEC void mpf_clear (mpf_ptr);
#define mpf_clears __gmpf_clears
__GMP_DECLSPEC void mpf_clears (mpf_ptr, ...);
#define mpf_cmp __gmpf_cmp
__GMP_DECLSPEC int mpf_cmp (mpf_srcptr, mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#define mpf_cmp_z __gmpf_cmp_z
__GMP_DECLSPEC int mpf_cmp_z (mpf_srcptr, mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#define mpf_cmp_d __gmpf_cmp_d
__GMP_DECLSPEC int mpf_cmp_d (mpf_srcptr, double) __GMP_ATTRIBUTE_PURE;
#define mpf_cmp_si __gmpf_cmp_si
__GMP_DECLSPEC int mpf_cmp_si (mpf_srcptr, signed long int) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#define mpf_cmp_ui __gmpf_cmp_ui
__GMP_DECLSPEC int mpf_cmp_ui (mpf_srcptr, unsigned long int) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#define mpf_div __gmpf_div
__GMP_DECLSPEC void mpf_div (mpf_ptr, mpf_srcptr, mpf_srcptr);
#define mpf_div_2exp __gmpf_div_2exp
__GMP_DECLSPEC void mpf_div_2exp (mpf_ptr, mpf_srcptr, mp_bitcnt_t);
#define mpf_div_ui __gmpf_div_ui
__GMP_DECLSPEC void mpf_div_ui (mpf_ptr, mpf_srcptr, unsigned long int);
#define mpf_dump __gmpf_dump
__GMP_DECLSPEC void mpf_dump (mpf_srcptr);
#define mpf_eq __gmpf_eq
__GMP_DECLSPEC int mpf_eq (mpf_srcptr, mpf_srcptr, mp_bitcnt_t) __GMP_ATTRIBUTE_PURE;
#define mpf_fits_sint_p __gmpf_fits_sint_p
__GMP_DECLSPEC int mpf_fits_sint_p (mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#define mpf_fits_slong_p __gmpf_fits_slong_p
__GMP_DECLSPEC int mpf_fits_slong_p (mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#define mpf_fits_sshort_p __gmpf_fits_sshort_p
__GMP_DECLSPEC int mpf_fits_sshort_p (mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#define mpf_fits_uint_p __gmpf_fits_uint_p
__GMP_DECLSPEC int mpf_fits_uint_p (mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#define mpf_fits_ulong_p __gmpf_fits_ulong_p
__GMP_DECLSPEC int mpf_fits_ulong_p (mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#define mpf_fits_ushort_p __gmpf_fits_ushort_p
__GMP_DECLSPEC int mpf_fits_ushort_p (mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#define mpf_floor __gmpf_floor
__GMP_DECLSPEC void mpf_floor (mpf_ptr, mpf_srcptr);
#define mpf_get_d __gmpf_get_d
__GMP_DECLSPEC double mpf_get_d (mpf_srcptr) __GMP_ATTRIBUTE_PURE;
#define mpf_get_d_2exp __gmpf_get_d_2exp
__GMP_DECLSPEC double mpf_get_d_2exp (signed long int *, mpf_srcptr);
#define mpf_get_default_prec __gmpf_get_default_prec
__GMP_DECLSPEC mp_bitcnt_t mpf_get_default_prec (void) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#define mpf_get_prec __gmpf_get_prec
__GMP_DECLSPEC mp_bitcnt_t mpf_get_prec (mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#define mpf_get_si __gmpf_get_si
__GMP_DECLSPEC long mpf_get_si (mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#define mpf_get_str __gmpf_get_str
__GMP_DECLSPEC char *mpf_get_str (char *, mp_exp_t *, int, size_t, mpf_srcptr);
#define mpf_get_ui __gmpf_get_ui
__GMP_DECLSPEC unsigned long mpf_get_ui (mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#define mpf_init __gmpf_init
__GMP_DECLSPEC void mpf_init (mpf_ptr);
#define mpf_init2 __gmpf_init2
__GMP_DECLSPEC void mpf_init2 (mpf_ptr, mp_bitcnt_t);
#define mpf_inits __gmpf_inits
__GMP_DECLSPEC void mpf_inits (mpf_ptr, ...);
#define mpf_init_set __gmpf_init_set
__GMP_DECLSPEC void mpf_init_set (mpf_ptr, mpf_srcptr);
#define mpf_init_set_d __gmpf_init_set_d
__GMP_DECLSPEC void mpf_init_set_d (mpf_ptr, double);
#define mpf_init_set_si __gmpf_init_set_si
__GMP_DECLSPEC void mpf_init_set_si (mpf_ptr, signed long int);
#define mpf_init_set_str __gmpf_init_set_str
__GMP_DECLSPEC int mpf_init_set_str (mpf_ptr, const char *, int);
#define mpf_init_set_ui __gmpf_init_set_ui
__GMP_DECLSPEC void mpf_init_set_ui (mpf_ptr, unsigned long int);
#define mpf_inp_str __gmpf_inp_str
#ifdef _GMP_H_HAVE_FILE
__GMP_DECLSPEC size_t mpf_inp_str (mpf_ptr, FILE *, int);
#endif
#define mpf_integer_p __gmpf_integer_p
__GMP_DECLSPEC int mpf_integer_p (mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#define mpf_mul __gmpf_mul
__GMP_DECLSPEC void mpf_mul (mpf_ptr, mpf_srcptr, mpf_srcptr);
#define mpf_mul_2exp __gmpf_mul_2exp
__GMP_DECLSPEC void mpf_mul_2exp (mpf_ptr, mpf_srcptr, mp_bitcnt_t);
#define mpf_mul_ui __gmpf_mul_ui
__GMP_DECLSPEC void mpf_mul_ui (mpf_ptr, mpf_srcptr, unsigned long int);
#define mpf_neg __gmpf_neg
__GMP_DECLSPEC void mpf_neg (mpf_ptr, mpf_srcptr);
#define mpf_out_str __gmpf_out_str
#ifdef _GMP_H_HAVE_FILE
__GMP_DECLSPEC size_t mpf_out_str (FILE *, int, size_t, mpf_srcptr);
#endif
#define mpf_pow_ui __gmpf_pow_ui
__GMP_DECLSPEC void mpf_pow_ui (mpf_ptr, mpf_srcptr, unsigned long int);
#define mpf_random2 __gmpf_random2
__GMP_DECLSPEC void mpf_random2 (mpf_ptr, mp_size_t, mp_exp_t);
#define mpf_reldiff __gmpf_reldiff
__GMP_DECLSPEC void mpf_reldiff (mpf_ptr, mpf_srcptr, mpf_srcptr);
#define mpf_set __gmpf_set
__GMP_DECLSPEC void mpf_set (mpf_ptr, mpf_srcptr);
#define mpf_set_d __gmpf_set_d
__GMP_DECLSPEC void mpf_set_d (mpf_ptr, double);
#define mpf_set_default_prec __gmpf_set_default_prec
__GMP_DECLSPEC void mpf_set_default_prec (mp_bitcnt_t) __GMP_NOTHROW;
#define mpf_set_prec __gmpf_set_prec
__GMP_DECLSPEC void mpf_set_prec (mpf_ptr, mp_bitcnt_t);
#define mpf_set_prec_raw __gmpf_set_prec_raw
__GMP_DECLSPEC void mpf_set_prec_raw (mpf_ptr, mp_bitcnt_t) __GMP_NOTHROW;
#define mpf_set_q __gmpf_set_q
__GMP_DECLSPEC void mpf_set_q (mpf_ptr, mpq_srcptr);
#define mpf_set_si __gmpf_set_si
__GMP_DECLSPEC void mpf_set_si (mpf_ptr, signed long int);
#define mpf_set_str __gmpf_set_str
__GMP_DECLSPEC int mpf_set_str (mpf_ptr, const char *, int);
#define mpf_set_ui __gmpf_set_ui
__GMP_DECLSPEC void mpf_set_ui (mpf_ptr, unsigned long int);
#define mpf_set_z __gmpf_set_z
__GMP_DECLSPEC void mpf_set_z (mpf_ptr, mpz_srcptr);
#define mpf_size __gmpf_size
__GMP_DECLSPEC size_t mpf_size (mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#define mpf_sqrt __gmpf_sqrt
__GMP_DECLSPEC void mpf_sqrt (mpf_ptr, mpf_srcptr);
#define mpf_sqrt_ui __gmpf_sqrt_ui
__GMP_DECLSPEC void mpf_sqrt_ui (mpf_ptr, unsigned long int);
#define mpf_sub __gmpf_sub
__GMP_DECLSPEC void mpf_sub (mpf_ptr, mpf_srcptr, mpf_srcptr);
#define mpf_sub_ui __gmpf_sub_ui
__GMP_DECLSPEC void mpf_sub_ui (mpf_ptr, mpf_srcptr, unsigned long int);
#define mpf_swap __gmpf_swap
__GMP_DECLSPEC void mpf_swap (mpf_ptr, mpf_ptr) __GMP_NOTHROW;
#define mpf_trunc __gmpf_trunc
__GMP_DECLSPEC void mpf_trunc (mpf_ptr, mpf_srcptr);
#define mpf_ui_div __gmpf_ui_div
__GMP_DECLSPEC void mpf_ui_div (mpf_ptr, unsigned long int, mpf_srcptr);
#define mpf_ui_sub __gmpf_ui_sub
__GMP_DECLSPEC void mpf_ui_sub (mpf_ptr, unsigned long int, mpf_srcptr);
#define mpf_urandomb __gmpf_urandomb
__GMP_DECLSPEC void mpf_urandomb (mpf_ptr, gmp_randstate_ptr, mp_bitcnt_t);
/************ Low level positive-integer (i.e. N) routines. ************/
/* This is ugly, but we need to make user calls reach the prefixed function. */
#define mpn_add __MPN(add)
#if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpn_add)
__GMP_DECLSPEC mp_limb_t mpn_add (mp_ptr, mp_srcptr, mp_size_t, mp_srcptr, mp_size_t);
#endif
#define mpn_add_1 __MPN(add_1)
#if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpn_add_1)
__GMP_DECLSPEC mp_limb_t mpn_add_1 (mp_ptr, mp_srcptr, mp_size_t, mp_limb_t) __GMP_NOTHROW;
#endif
#define mpn_add_n __MPN(add_n)
__GMP_DECLSPEC mp_limb_t mpn_add_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t);
#define mpn_addmul_1 __MPN(addmul_1)
__GMP_DECLSPEC mp_limb_t mpn_addmul_1 (mp_ptr, mp_srcptr, mp_size_t, mp_limb_t);
#define mpn_cmp __MPN(cmp)
#if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpn_cmp)
__GMP_DECLSPEC int mpn_cmp (mp_srcptr, mp_srcptr, mp_size_t) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#endif
#define mpn_zero_p __MPN(zero_p)
#if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpn_zero_p)
__GMP_DECLSPEC int mpn_zero_p (mp_srcptr, mp_size_t) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#endif
#define mpn_divexact_1 __MPN(divexact_1)
__GMP_DECLSPEC void mpn_divexact_1 (mp_ptr, mp_srcptr, mp_size_t, mp_limb_t);
#define mpn_divexact_by3(dst,src,size) \
mpn_divexact_by3c (dst, src, size, __GMP_CAST (mp_limb_t, 0))
#define mpn_divexact_by3c __MPN(divexact_by3c)
__GMP_DECLSPEC mp_limb_t mpn_divexact_by3c (mp_ptr, mp_srcptr, mp_size_t, mp_limb_t);
#define mpn_divmod_1(qp,np,nsize,dlimb) \
mpn_divrem_1 (qp, __GMP_CAST (mp_size_t, 0), np, nsize, dlimb)
#define mpn_divrem __MPN(divrem)
__GMP_DECLSPEC mp_limb_t mpn_divrem (mp_ptr, mp_size_t, mp_ptr, mp_size_t, mp_srcptr, mp_size_t);
#define mpn_divrem_1 __MPN(divrem_1)
__GMP_DECLSPEC mp_limb_t mpn_divrem_1 (mp_ptr, mp_size_t, mp_srcptr, mp_size_t, mp_limb_t);
#define mpn_divrem_2 __MPN(divrem_2)
__GMP_DECLSPEC mp_limb_t mpn_divrem_2 (mp_ptr, mp_size_t, mp_ptr, mp_size_t, mp_srcptr);
#define mpn_div_qr_1 __MPN(div_qr_1)
__GMP_DECLSPEC mp_limb_t mpn_div_qr_1 (mp_ptr, mp_limb_t *, mp_srcptr, mp_size_t, mp_limb_t);
#define mpn_div_qr_2 __MPN(div_qr_2)
__GMP_DECLSPEC mp_limb_t mpn_div_qr_2 (mp_ptr, mp_ptr, mp_srcptr, mp_size_t, mp_srcptr);
#define mpn_gcd __MPN(gcd)
__GMP_DECLSPEC mp_size_t mpn_gcd (mp_ptr, mp_ptr, mp_size_t, mp_ptr, mp_size_t);
#define mpn_gcd_11 __MPN(gcd_11)
__GMP_DECLSPEC mp_limb_t mpn_gcd_11 (mp_limb_t, mp_limb_t) __GMP_ATTRIBUTE_PURE;
#define mpn_gcd_1 __MPN(gcd_1)
__GMP_DECLSPEC mp_limb_t mpn_gcd_1 (mp_srcptr, mp_size_t, mp_limb_t) __GMP_ATTRIBUTE_PURE;
#define mpn_gcdext_1 __MPN(gcdext_1)
__GMP_DECLSPEC mp_limb_t mpn_gcdext_1 (mp_limb_signed_t *, mp_limb_signed_t *, mp_limb_t, mp_limb_t);
#define mpn_gcdext __MPN(gcdext)
__GMP_DECLSPEC mp_size_t mpn_gcdext (mp_ptr, mp_ptr, mp_size_t *, mp_ptr, mp_size_t, mp_ptr, mp_size_t);
#define mpn_get_str __MPN(get_str)
__GMP_DECLSPEC size_t mpn_get_str (unsigned char *, int, mp_ptr, mp_size_t);
#define mpn_hamdist __MPN(hamdist)
__GMP_DECLSPEC mp_bitcnt_t mpn_hamdist (mp_srcptr, mp_srcptr, mp_size_t) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#define mpn_lshift __MPN(lshift)
__GMP_DECLSPEC mp_limb_t mpn_lshift (mp_ptr, mp_srcptr, mp_size_t, unsigned int);
#define mpn_mod_1 __MPN(mod_1)
__GMP_DECLSPEC mp_limb_t mpn_mod_1 (mp_srcptr, mp_size_t, mp_limb_t) __GMP_ATTRIBUTE_PURE;
#define mpn_mul __MPN(mul)
__GMP_DECLSPEC mp_limb_t mpn_mul (mp_ptr, mp_srcptr, mp_size_t, mp_srcptr, mp_size_t);
#define mpn_mul_1 __MPN(mul_1)
__GMP_DECLSPEC mp_limb_t mpn_mul_1 (mp_ptr, mp_srcptr, mp_size_t, mp_limb_t);
#define mpn_mul_n __MPN(mul_n)
__GMP_DECLSPEC void mpn_mul_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t);
#define mpn_sqr __MPN(sqr)
__GMP_DECLSPEC void mpn_sqr (mp_ptr, mp_srcptr, mp_size_t);
#define mpn_neg __MPN(neg)
#if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpn_neg)
__GMP_DECLSPEC mp_limb_t mpn_neg (mp_ptr, mp_srcptr, mp_size_t);
#endif
#define mpn_com __MPN(com)
__GMP_DECLSPEC void mpn_com (mp_ptr, mp_srcptr, mp_size_t);
#define mpn_perfect_square_p __MPN(perfect_square_p)
__GMP_DECLSPEC int mpn_perfect_square_p (mp_srcptr, mp_size_t) __GMP_ATTRIBUTE_PURE;
#define mpn_perfect_power_p __MPN(perfect_power_p)
__GMP_DECLSPEC int mpn_perfect_power_p (mp_srcptr, mp_size_t) __GMP_ATTRIBUTE_PURE;
#define mpn_popcount __MPN(popcount)
__GMP_DECLSPEC mp_bitcnt_t mpn_popcount (mp_srcptr, mp_size_t) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE;
#define mpn_pow_1 __MPN(pow_1)
__GMP_DECLSPEC mp_size_t mpn_pow_1 (mp_ptr, mp_srcptr, mp_size_t, mp_limb_t, mp_ptr);
/* undocumented now, but retained here for upward compatibility */
#define mpn_preinv_mod_1 __MPN(preinv_mod_1)
__GMP_DECLSPEC mp_limb_t mpn_preinv_mod_1 (mp_srcptr, mp_size_t, mp_limb_t, mp_limb_t) __GMP_ATTRIBUTE_PURE;
#define mpn_random __MPN(random)
__GMP_DECLSPEC void mpn_random (mp_ptr, mp_size_t);
#define mpn_random2 __MPN(random2)
__GMP_DECLSPEC void mpn_random2 (mp_ptr, mp_size_t);
#define mpn_rshift __MPN(rshift)
__GMP_DECLSPEC mp_limb_t mpn_rshift (mp_ptr, mp_srcptr, mp_size_t, unsigned int);
#define mpn_scan0 __MPN(scan0)
__GMP_DECLSPEC mp_bitcnt_t mpn_scan0 (mp_srcptr, mp_bitcnt_t) __GMP_ATTRIBUTE_PURE;
#define mpn_scan1 __MPN(scan1)
__GMP_DECLSPEC mp_bitcnt_t mpn_scan1 (mp_srcptr, mp_bitcnt_t) __GMP_ATTRIBUTE_PURE;
#define mpn_set_str __MPN(set_str)
__GMP_DECLSPEC mp_size_t mpn_set_str (mp_ptr, const unsigned char *, size_t, int);
#define mpn_sizeinbase __MPN(sizeinbase)
__GMP_DECLSPEC size_t mpn_sizeinbase (mp_srcptr, mp_size_t, int);
#define mpn_sqrtrem __MPN(sqrtrem)
__GMP_DECLSPEC mp_size_t mpn_sqrtrem (mp_ptr, mp_ptr, mp_srcptr, mp_size_t);
#define mpn_sub __MPN(sub)
#if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpn_sub)
__GMP_DECLSPEC mp_limb_t mpn_sub (mp_ptr, mp_srcptr, mp_size_t, mp_srcptr, mp_size_t);
#endif
#define mpn_sub_1 __MPN(sub_1)
#if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpn_sub_1)
__GMP_DECLSPEC mp_limb_t mpn_sub_1 (mp_ptr, mp_srcptr, mp_size_t, mp_limb_t) __GMP_NOTHROW;
#endif
#define mpn_sub_n __MPN(sub_n)
__GMP_DECLSPEC mp_limb_t mpn_sub_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t);
#define mpn_submul_1 __MPN(submul_1)
__GMP_DECLSPEC mp_limb_t mpn_submul_1 (mp_ptr, mp_srcptr, mp_size_t, mp_limb_t);
#define mpn_tdiv_qr __MPN(tdiv_qr)
__GMP_DECLSPEC void mpn_tdiv_qr (mp_ptr, mp_ptr, mp_size_t, mp_srcptr, mp_size_t, mp_srcptr, mp_size_t);
#define mpn_and_n __MPN(and_n)
__GMP_DECLSPEC void mpn_and_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t);
#define mpn_andn_n __MPN(andn_n)
__GMP_DECLSPEC void mpn_andn_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t);
#define mpn_nand_n __MPN(nand_n)
__GMP_DECLSPEC void mpn_nand_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t);
#define mpn_ior_n __MPN(ior_n)
__GMP_DECLSPEC void mpn_ior_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t);
#define mpn_iorn_n __MPN(iorn_n)
__GMP_DECLSPEC void mpn_iorn_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t);
#define mpn_nior_n __MPN(nior_n)
__GMP_DECLSPEC void mpn_nior_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t);
#define mpn_xor_n __MPN(xor_n)
__GMP_DECLSPEC void mpn_xor_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t);
#define mpn_xnor_n __MPN(xnor_n)
__GMP_DECLSPEC void mpn_xnor_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t);
#define mpn_copyi __MPN(copyi)
__GMP_DECLSPEC void mpn_copyi (mp_ptr, mp_srcptr, mp_size_t);
#define mpn_copyd __MPN(copyd)
__GMP_DECLSPEC void mpn_copyd (mp_ptr, mp_srcptr, mp_size_t);
#define mpn_zero __MPN(zero)
__GMP_DECLSPEC void mpn_zero (mp_ptr, mp_size_t);
#define mpn_cnd_add_n __MPN(cnd_add_n)
__GMP_DECLSPEC mp_limb_t mpn_cnd_add_n (mp_limb_t, mp_ptr, mp_srcptr, mp_srcptr, mp_size_t);
#define mpn_cnd_sub_n __MPN(cnd_sub_n)
__GMP_DECLSPEC mp_limb_t mpn_cnd_sub_n (mp_limb_t, mp_ptr, mp_srcptr, mp_srcptr, mp_size_t);
#define mpn_sec_add_1 __MPN(sec_add_1)
__GMP_DECLSPEC mp_limb_t mpn_sec_add_1 (mp_ptr, mp_srcptr, mp_size_t, mp_limb_t, mp_ptr);
#define mpn_sec_add_1_itch __MPN(sec_add_1_itch)
__GMP_DECLSPEC mp_size_t mpn_sec_add_1_itch (mp_size_t) __GMP_ATTRIBUTE_PURE;
#define mpn_sec_sub_1 __MPN(sec_sub_1)
__GMP_DECLSPEC mp_limb_t mpn_sec_sub_1 (mp_ptr, mp_srcptr, mp_size_t, mp_limb_t, mp_ptr);
#define mpn_sec_sub_1_itch __MPN(sec_sub_1_itch)
__GMP_DECLSPEC mp_size_t mpn_sec_sub_1_itch (mp_size_t) __GMP_ATTRIBUTE_PURE;
#define mpn_cnd_swap __MPN(cnd_swap)
__GMP_DECLSPEC void mpn_cnd_swap (mp_limb_t, volatile mp_limb_t *, volatile mp_limb_t *, mp_size_t);
#define mpn_sec_mul __MPN(sec_mul)
__GMP_DECLSPEC void mpn_sec_mul (mp_ptr, mp_srcptr, mp_size_t, mp_srcptr, mp_size_t, mp_ptr);
#define mpn_sec_mul_itch __MPN(sec_mul_itch)
__GMP_DECLSPEC mp_size_t mpn_sec_mul_itch (mp_size_t, mp_size_t) __GMP_ATTRIBUTE_PURE;
#define mpn_sec_sqr __MPN(sec_sqr)
__GMP_DECLSPEC void mpn_sec_sqr (mp_ptr, mp_srcptr, mp_size_t, mp_ptr);
#define mpn_sec_sqr_itch __MPN(sec_sqr_itch)
__GMP_DECLSPEC mp_size_t mpn_sec_sqr_itch (mp_size_t) __GMP_ATTRIBUTE_PURE;
#define mpn_sec_powm __MPN(sec_powm)
__GMP_DECLSPEC void mpn_sec_powm (mp_ptr, mp_srcptr, mp_size_t, mp_srcptr, mp_bitcnt_t, mp_srcptr, mp_size_t, mp_ptr);
#define mpn_sec_powm_itch __MPN(sec_powm_itch)
__GMP_DECLSPEC mp_size_t mpn_sec_powm_itch (mp_size_t, mp_bitcnt_t, mp_size_t) __GMP_ATTRIBUTE_PURE;
#define mpn_sec_tabselect __MPN(sec_tabselect)
__GMP_DECLSPEC void mpn_sec_tabselect (volatile mp_limb_t *, volatile const mp_limb_t *, mp_size_t, mp_size_t, mp_size_t);
#define mpn_sec_div_qr __MPN(sec_div_qr)
__GMP_DECLSPEC mp_limb_t mpn_sec_div_qr (mp_ptr, mp_ptr, mp_size_t, mp_srcptr, mp_size_t, mp_ptr);
#define mpn_sec_div_qr_itch __MPN(sec_div_qr_itch)
__GMP_DECLSPEC mp_size_t mpn_sec_div_qr_itch (mp_size_t, mp_size_t) __GMP_ATTRIBUTE_PURE;
#define mpn_sec_div_r __MPN(sec_div_r)
__GMP_DECLSPEC void mpn_sec_div_r (mp_ptr, mp_size_t, mp_srcptr, mp_size_t, mp_ptr);
#define mpn_sec_div_r_itch __MPN(sec_div_r_itch)
__GMP_DECLSPEC mp_size_t mpn_sec_div_r_itch (mp_size_t, mp_size_t) __GMP_ATTRIBUTE_PURE;
#define mpn_sec_invert __MPN(sec_invert)
__GMP_DECLSPEC int mpn_sec_invert (mp_ptr, mp_ptr, mp_srcptr, mp_size_t, mp_bitcnt_t, mp_ptr);
#define mpn_sec_invert_itch __MPN(sec_invert_itch)
__GMP_DECLSPEC mp_size_t mpn_sec_invert_itch (mp_size_t) __GMP_ATTRIBUTE_PURE;
/**************** mpz inlines ****************/
/* The following are provided as inlines where possible, but always exist as
library functions too, for binary compatibility.
Within gmp itself this inlining generally isn't relied on, since it
doesn't get done for all compilers, whereas if something is worth
inlining then it's worth arranging always.
There are two styles of inlining here. When the same bit of code is
wanted for the inline as for the library version, then __GMP_FORCE_foo
arranges for that code to be emitted and the __GMP_EXTERN_INLINE
directive suppressed, eg. mpz_fits_uint_p. When a different bit of code
is wanted for the inline than for the library version, then
__GMP_FORCE_foo arranges the inline to be suppressed, eg. mpz_abs. */
#if defined (__GMP_EXTERN_INLINE) && ! defined (__GMP_FORCE_mpz_abs)
__GMP_EXTERN_INLINE void
mpz_abs (mpz_ptr __gmp_w, mpz_srcptr __gmp_u)
{
if (__gmp_w != __gmp_u)
mpz_set (__gmp_w, __gmp_u);
__gmp_w->_mp_size = __GMP_ABS (__gmp_w->_mp_size);
}
#endif
#if GMP_NAIL_BITS == 0
#define __GMPZ_FITS_UTYPE_P(z,maxval) \
mp_size_t __gmp_n = z->_mp_size; \
mp_ptr __gmp_p = z->_mp_d; \
return (__gmp_n == 0 || (__gmp_n == 1 && __gmp_p[0] <= maxval));
#else
#define __GMPZ_FITS_UTYPE_P(z,maxval) \
mp_size_t __gmp_n = z->_mp_size; \
mp_ptr __gmp_p = z->_mp_d; \
return (__gmp_n == 0 || (__gmp_n == 1 && __gmp_p[0] <= maxval) \
|| (__gmp_n == 2 && __gmp_p[1] <= ((mp_limb_t) maxval >> GMP_NUMB_BITS)));
#endif
#if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpz_fits_uint_p)
#if ! defined (__GMP_FORCE_mpz_fits_uint_p)
__GMP_EXTERN_INLINE
#endif
int
mpz_fits_uint_p (mpz_srcptr __gmp_z) __GMP_NOTHROW
{
__GMPZ_FITS_UTYPE_P (__gmp_z, UINT_MAX);
}
#endif
#if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpz_fits_ulong_p)
#if ! defined (__GMP_FORCE_mpz_fits_ulong_p)
__GMP_EXTERN_INLINE
#endif
int
mpz_fits_ulong_p (mpz_srcptr __gmp_z) __GMP_NOTHROW
{
__GMPZ_FITS_UTYPE_P (__gmp_z, ULONG_MAX);
}
#endif
#if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpz_fits_ushort_p)
#if ! defined (__GMP_FORCE_mpz_fits_ushort_p)
__GMP_EXTERN_INLINE
#endif
int
mpz_fits_ushort_p (mpz_srcptr __gmp_z) __GMP_NOTHROW
{
__GMPZ_FITS_UTYPE_P (__gmp_z, USHRT_MAX);
}
#endif
#if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpz_get_ui)
#if ! defined (__GMP_FORCE_mpz_get_ui)
__GMP_EXTERN_INLINE
#endif
unsigned long
mpz_get_ui (mpz_srcptr __gmp_z) __GMP_NOTHROW
{
mp_ptr __gmp_p = __gmp_z->_mp_d;
mp_size_t __gmp_n = __gmp_z->_mp_size;
mp_limb_t __gmp_l = __gmp_p[0];
/* This is a "#if" rather than a plain "if" so as to avoid gcc warnings
about "<< GMP_NUMB_BITS" exceeding the type size, and to avoid Borland
C++ 6.0 warnings about condition always true for something like
"ULONG_MAX < GMP_NUMB_MASK". */
#if GMP_NAIL_BITS == 0 || defined (_LONG_LONG_LIMB)
/* limb==long and no nails, or limb==longlong, one limb is enough */
return (__gmp_n != 0 ? __gmp_l : 0);
#else
/* limb==long and nails, need two limbs when available */
__gmp_n = __GMP_ABS (__gmp_n);
if (__gmp_n <= 1)
return (__gmp_n != 0 ? __gmp_l : 0);
else
return __gmp_l + (__gmp_p[1] << GMP_NUMB_BITS);
#endif
}
#endif
#if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpz_getlimbn)
#if ! defined (__GMP_FORCE_mpz_getlimbn)
__GMP_EXTERN_INLINE
#endif
mp_limb_t
mpz_getlimbn (mpz_srcptr __gmp_z, mp_size_t __gmp_n) __GMP_NOTHROW
{
mp_limb_t __gmp_result = 0;
if (__GMP_LIKELY (__gmp_n >= 0 && __gmp_n < __GMP_ABS (__gmp_z->_mp_size)))
__gmp_result = __gmp_z->_mp_d[__gmp_n];
return __gmp_result;
}
#endif
#if defined (__GMP_EXTERN_INLINE) && ! defined (__GMP_FORCE_mpz_neg)
__GMP_EXTERN_INLINE void
mpz_neg (mpz_ptr __gmp_w, mpz_srcptr __gmp_u)
{
if (__gmp_w != __gmp_u)
mpz_set (__gmp_w, __gmp_u);
__gmp_w->_mp_size = - __gmp_w->_mp_size;
}
#endif
#if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpz_perfect_square_p)
#if ! defined (__GMP_FORCE_mpz_perfect_square_p)
__GMP_EXTERN_INLINE
#endif
int
mpz_perfect_square_p (mpz_srcptr __gmp_a)
{
mp_size_t __gmp_asize;
int __gmp_result;
__gmp_asize = __gmp_a->_mp_size;
__gmp_result = (__gmp_asize >= 0); /* zero is a square, negatives are not */
if (__GMP_LIKELY (__gmp_asize > 0))
__gmp_result = mpn_perfect_square_p (__gmp_a->_mp_d, __gmp_asize);
return __gmp_result;
}
#endif
#if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpz_popcount)
#if ! defined (__GMP_FORCE_mpz_popcount)
__GMP_EXTERN_INLINE
#endif
mp_bitcnt_t
mpz_popcount (mpz_srcptr __gmp_u) __GMP_NOTHROW
{
mp_size_t __gmp_usize;
mp_bitcnt_t __gmp_result;
__gmp_usize = __gmp_u->_mp_size;
__gmp_result = (__gmp_usize < 0 ? ~ __GMP_CAST (mp_bitcnt_t, 0) : __GMP_CAST (mp_bitcnt_t, 0));
if (__GMP_LIKELY (__gmp_usize > 0))
__gmp_result = mpn_popcount (__gmp_u->_mp_d, __gmp_usize);
return __gmp_result;
}
#endif
#if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpz_set_q)
#if ! defined (__GMP_FORCE_mpz_set_q)
__GMP_EXTERN_INLINE
#endif
void
mpz_set_q (mpz_ptr __gmp_w, mpq_srcptr __gmp_u)
{
mpz_tdiv_q (__gmp_w, mpq_numref (__gmp_u), mpq_denref (__gmp_u));
}
#endif
#if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpz_size)
#if ! defined (__GMP_FORCE_mpz_size)
__GMP_EXTERN_INLINE
#endif
size_t
mpz_size (mpz_srcptr __gmp_z) __GMP_NOTHROW
{
return __GMP_ABS (__gmp_z->_mp_size);
}
#endif
/**************** mpq inlines ****************/
#if defined (__GMP_EXTERN_INLINE) && ! defined (__GMP_FORCE_mpq_abs)
__GMP_EXTERN_INLINE void
mpq_abs (mpq_ptr __gmp_w, mpq_srcptr __gmp_u)
{
if (__gmp_w != __gmp_u)
mpq_set (__gmp_w, __gmp_u);
__gmp_w->_mp_num._mp_size = __GMP_ABS (__gmp_w->_mp_num._mp_size);
}
#endif
#if defined (__GMP_EXTERN_INLINE) && ! defined (__GMP_FORCE_mpq_neg)
__GMP_EXTERN_INLINE void
mpq_neg (mpq_ptr __gmp_w, mpq_srcptr __gmp_u)
{
if (__gmp_w != __gmp_u)
mpq_set (__gmp_w, __gmp_u);
__gmp_w->_mp_num._mp_size = - __gmp_w->_mp_num._mp_size;
}
#endif
/**************** mpn inlines ****************/
/* The comments with __GMPN_ADD_1 below apply here too.
The test for FUNCTION returning 0 should predict well. If it's assumed
{yp,ysize} will usually have a random number of bits then the high limb
won't be full and a carry out will occur a good deal less than 50% of the
time.
ysize==0 isn't a documented feature, but is used internally in a few
places.
Producing cout last stops it using up a register during the main part of
the calculation, though gcc (as of 3.0) on an "if (mpn_add (...))"
doesn't seem able to move the true and false legs of the conditional up
to the two places cout is generated. */
#define __GMPN_AORS(cout, wp, xp, xsize, yp, ysize, FUNCTION, TEST) \
do { \
mp_size_t __gmp_i; \
mp_limb_t __gmp_x; \
\
/* ASSERT ((ysize) >= 0); */ \
/* ASSERT ((xsize) >= (ysize)); */ \
/* ASSERT (MPN_SAME_OR_SEPARATE2_P (wp, xsize, xp, xsize)); */ \
/* ASSERT (MPN_SAME_OR_SEPARATE2_P (wp, xsize, yp, ysize)); */ \
\
__gmp_i = (ysize); \
if (__gmp_i != 0) \
{ \
if (FUNCTION (wp, xp, yp, __gmp_i)) \
{ \
do \
{ \
if (__gmp_i >= (xsize)) \
{ \
(cout) = 1; \
goto __gmp_done; \
} \
__gmp_x = (xp)[__gmp_i]; \
} \
while (TEST); \
} \
} \
if ((wp) != (xp)) \
__GMPN_COPY_REST (wp, xp, xsize, __gmp_i); \
(cout) = 0; \
__gmp_done: \
; \
} while (0)
#define __GMPN_ADD(cout, wp, xp, xsize, yp, ysize) \
__GMPN_AORS (cout, wp, xp, xsize, yp, ysize, mpn_add_n, \
(((wp)[__gmp_i++] = (__gmp_x + 1) & GMP_NUMB_MASK) == 0))
#define __GMPN_SUB(cout, wp, xp, xsize, yp, ysize) \
__GMPN_AORS (cout, wp, xp, xsize, yp, ysize, mpn_sub_n, \
(((wp)[__gmp_i++] = (__gmp_x - 1) & GMP_NUMB_MASK), __gmp_x == 0))
/* The use of __gmp_i indexing is designed to ensure a compile time src==dst
remains nice and clear to the compiler, so that __GMPN_COPY_REST can
disappear, and the load/add/store gets a chance to become a
read-modify-write on CISC CPUs.
Alternatives:
Using a pair of pointers instead of indexing would be possible, but gcc
isn't able to recognise compile-time src==dst in that case, even when the
pointers are incremented more or less together. Other compilers would
very likely have similar difficulty.
gcc could use "if (__builtin_constant_p(src==dst) && src==dst)" or
similar to detect a compile-time src==dst. This works nicely on gcc
2.95.x, it's not good on gcc 3.0 where __builtin_constant_p(p==p) seems
to be always false, for a pointer p. But the current code form seems
good enough for src==dst anyway.
gcc on x86 as usual doesn't give particularly good flags handling for the
carry/borrow detection. It's tempting to want some multi instruction asm
blocks to help it, and this was tried, but in truth there's only a few
instructions to save and any gain is all too easily lost by register
juggling setting up for the asm. */
#if GMP_NAIL_BITS == 0
#define __GMPN_AORS_1(cout, dst, src, n, v, OP, CB) \
do { \
mp_size_t __gmp_i; \
mp_limb_t __gmp_x, __gmp_r; \
\
/* ASSERT ((n) >= 1); */ \
/* ASSERT (MPN_SAME_OR_SEPARATE_P (dst, src, n)); */ \
\
__gmp_x = (src)[0]; \
__gmp_r = __gmp_x OP (v); \
(dst)[0] = __gmp_r; \
if (CB (__gmp_r, __gmp_x, (v))) \
{ \
(cout) = 1; \
for (__gmp_i = 1; __gmp_i < (n);) \
{ \
__gmp_x = (src)[__gmp_i]; \
__gmp_r = __gmp_x OP 1; \
(dst)[__gmp_i] = __gmp_r; \
++__gmp_i; \
if (!CB (__gmp_r, __gmp_x, 1)) \
{ \
if ((src) != (dst)) \
__GMPN_COPY_REST (dst, src, n, __gmp_i); \
(cout) = 0; \
break; \
} \
} \
} \
else \
{ \
if ((src) != (dst)) \
__GMPN_COPY_REST (dst, src, n, 1); \
(cout) = 0; \
} \
} while (0)
#endif
#if GMP_NAIL_BITS >= 1
#define __GMPN_AORS_1(cout, dst, src, n, v, OP, CB) \
do { \
mp_size_t __gmp_i; \
mp_limb_t __gmp_x, __gmp_r; \
\
/* ASSERT ((n) >= 1); */ \
/* ASSERT (MPN_SAME_OR_SEPARATE_P (dst, src, n)); */ \
\
__gmp_x = (src)[0]; \
__gmp_r = __gmp_x OP (v); \
(dst)[0] = __gmp_r & GMP_NUMB_MASK; \
if (__gmp_r >> GMP_NUMB_BITS != 0) \
{ \
(cout) = 1; \
for (__gmp_i = 1; __gmp_i < (n);) \
{ \
__gmp_x = (src)[__gmp_i]; \
__gmp_r = __gmp_x OP 1; \
(dst)[__gmp_i] = __gmp_r & GMP_NUMB_MASK; \
++__gmp_i; \
if (__gmp_r >> GMP_NUMB_BITS == 0) \
{ \
if ((src) != (dst)) \
__GMPN_COPY_REST (dst, src, n, __gmp_i); \
(cout) = 0; \
break; \
} \
} \
} \
else \
{ \
if ((src) != (dst)) \
__GMPN_COPY_REST (dst, src, n, 1); \
(cout) = 0; \
} \
} while (0)
#endif
#define __GMPN_ADDCB(r,x,y) ((r) < (y))
#define __GMPN_SUBCB(r,x,y) ((x) < (y))
#define __GMPN_ADD_1(cout, dst, src, n, v) \
__GMPN_AORS_1(cout, dst, src, n, v, +, __GMPN_ADDCB)
#define __GMPN_SUB_1(cout, dst, src, n, v) \
__GMPN_AORS_1(cout, dst, src, n, v, -, __GMPN_SUBCB)
/* Compare {xp,size} and {yp,size}, setting "result" to positive, zero or
negative. size==0 is allowed. On random data usually only one limb will
need to be examined to get a result, so it's worth having it inline. */
#define __GMPN_CMP(result, xp, yp, size) \
do { \
mp_size_t __gmp_i; \
mp_limb_t __gmp_x, __gmp_y; \
\
/* ASSERT ((size) >= 0); */ \
\
(result) = 0; \
__gmp_i = (size); \
while (--__gmp_i >= 0) \
{ \
__gmp_x = (xp)[__gmp_i]; \
__gmp_y = (yp)[__gmp_i]; \
if (__gmp_x != __gmp_y) \
{ \
/* Cannot use __gmp_x - __gmp_y, may overflow an "int" */ \
(result) = (__gmp_x > __gmp_y ? 1 : -1); \
break; \
} \
} \
} while (0)
#if defined (__GMPN_COPY) && ! defined (__GMPN_COPY_REST)
#define __GMPN_COPY_REST(dst, src, size, start) \
do { \
/* ASSERT ((start) >= 0); */ \
/* ASSERT ((start) <= (size)); */ \
__GMPN_COPY ((dst)+(start), (src)+(start), (size)-(start)); \
} while (0)
#endif
/* Copy {src,size} to {dst,size}, starting at "start". This is designed to
keep the indexing dst[j] and src[j] nice and simple for __GMPN_ADD_1,
__GMPN_ADD, etc. */
#if ! defined (__GMPN_COPY_REST)
#define __GMPN_COPY_REST(dst, src, size, start) \
do { \
mp_size_t __gmp_j; \
/* ASSERT ((size) >= 0); */ \
/* ASSERT ((start) >= 0); */ \
/* ASSERT ((start) <= (size)); */ \
/* ASSERT (MPN_SAME_OR_SEPARATE_P (dst, src, size)); */ \
__GMP_CRAY_Pragma ("_CRI ivdep"); \
for (__gmp_j = (start); __gmp_j < (size); __gmp_j++) \
(dst)[__gmp_j] = (src)[__gmp_j]; \
} while (0)
#endif
/* Enhancement: Use some of the smarter code from gmp-impl.h. Maybe use
mpn_copyi if there's a native version, and if we don't mind demanding
binary compatibility for it (on targets which use it). */
#if ! defined (__GMPN_COPY)
#define __GMPN_COPY(dst, src, size) __GMPN_COPY_REST (dst, src, size, 0)
#endif
#if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpn_add)
#if ! defined (__GMP_FORCE_mpn_add)
__GMP_EXTERN_INLINE
#endif
mp_limb_t
mpn_add (mp_ptr __gmp_wp, mp_srcptr __gmp_xp, mp_size_t __gmp_xsize, mp_srcptr __gmp_yp, mp_size_t __gmp_ysize)
{
mp_limb_t __gmp_c;
__GMPN_ADD (__gmp_c, __gmp_wp, __gmp_xp, __gmp_xsize, __gmp_yp, __gmp_ysize);
return __gmp_c;
}
#endif
#if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpn_add_1)
#if ! defined (__GMP_FORCE_mpn_add_1)
__GMP_EXTERN_INLINE
#endif
mp_limb_t
mpn_add_1 (mp_ptr __gmp_dst, mp_srcptr __gmp_src, mp_size_t __gmp_size, mp_limb_t __gmp_n) __GMP_NOTHROW
{
mp_limb_t __gmp_c;
__GMPN_ADD_1 (__gmp_c, __gmp_dst, __gmp_src, __gmp_size, __gmp_n);
return __gmp_c;
}
#endif
#if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpn_cmp)
#if ! defined (__GMP_FORCE_mpn_cmp)
__GMP_EXTERN_INLINE
#endif
int
mpn_cmp (mp_srcptr __gmp_xp, mp_srcptr __gmp_yp, mp_size_t __gmp_size) __GMP_NOTHROW
{
int __gmp_result;
__GMPN_CMP (__gmp_result, __gmp_xp, __gmp_yp, __gmp_size);
return __gmp_result;
}
#endif
#if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpn_zero_p)
#if ! defined (__GMP_FORCE_mpn_zero_p)
__GMP_EXTERN_INLINE
#endif
int
mpn_zero_p (mp_srcptr __gmp_p, mp_size_t __gmp_n) __GMP_NOTHROW
{
/* if (__GMP_LIKELY (__gmp_n > 0)) */
do {
if (__gmp_p[--__gmp_n] != 0)
return 0;
} while (__gmp_n != 0);
return 1;
}
#endif
#if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpn_sub)
#if ! defined (__GMP_FORCE_mpn_sub)
__GMP_EXTERN_INLINE
#endif
mp_limb_t
mpn_sub (mp_ptr __gmp_wp, mp_srcptr __gmp_xp, mp_size_t __gmp_xsize, mp_srcptr __gmp_yp, mp_size_t __gmp_ysize)
{
mp_limb_t __gmp_c;
__GMPN_SUB (__gmp_c, __gmp_wp, __gmp_xp, __gmp_xsize, __gmp_yp, __gmp_ysize);
return __gmp_c;
}
#endif
#if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpn_sub_1)
#if ! defined (__GMP_FORCE_mpn_sub_1)
__GMP_EXTERN_INLINE
#endif
mp_limb_t
mpn_sub_1 (mp_ptr __gmp_dst, mp_srcptr __gmp_src, mp_size_t __gmp_size, mp_limb_t __gmp_n) __GMP_NOTHROW
{
mp_limb_t __gmp_c;
__GMPN_SUB_1 (__gmp_c, __gmp_dst, __gmp_src, __gmp_size, __gmp_n);
return __gmp_c;
}
#endif
#if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpn_neg)
#if ! defined (__GMP_FORCE_mpn_neg)
__GMP_EXTERN_INLINE
#endif
mp_limb_t
mpn_neg (mp_ptr __gmp_rp, mp_srcptr __gmp_up, mp_size_t __gmp_n)
{
while (*__gmp_up == 0) /* Low zero limbs are unchanged by negation. */
{
*__gmp_rp = 0;
if (!--__gmp_n) /* All zero */
return 0;
++__gmp_up; ++__gmp_rp;
}
*__gmp_rp = (- *__gmp_up) & GMP_NUMB_MASK;
if (--__gmp_n) /* Higher limbs get complemented. */
mpn_com (++__gmp_rp, ++__gmp_up, __gmp_n);
return 1;
}
#endif
#if defined (__cplusplus)
}
#endif
/* Allow faster testing for negative, zero, and positive. */
#define mpz_sgn(Z) ((Z)->_mp_size < 0 ? -1 : (Z)->_mp_size > 0)
#define mpf_sgn(F) ((F)->_mp_size < 0 ? -1 : (F)->_mp_size > 0)
#define mpq_sgn(Q) ((Q)->_mp_num._mp_size < 0 ? -1 : (Q)->_mp_num._mp_size > 0)
/* When using GCC, optimize certain common comparisons. */
#if defined (__GNUC__) && __GNUC__ >= 2
#define mpz_cmp_ui(Z,UI) \
(__builtin_constant_p (UI) && (UI) == 0 \
? mpz_sgn (Z) : _mpz_cmp_ui (Z,UI))
#define mpz_cmp_si(Z,SI) \
(__builtin_constant_p ((SI) >= 0) && (SI) >= 0 \
? mpz_cmp_ui (Z, __GMP_CAST (unsigned long, SI)) \
: _mpz_cmp_si (Z,SI))
#define mpq_cmp_ui(Q,NUI,DUI) \
(__builtin_constant_p (NUI) && (NUI) == 0 ? mpq_sgn (Q) \
: __builtin_constant_p ((NUI) == (DUI)) && (NUI) == (DUI) \
? mpz_cmp (mpq_numref (Q), mpq_denref (Q)) \
: _mpq_cmp_ui (Q,NUI,DUI))
#define mpq_cmp_si(q,n,d) \
(__builtin_constant_p ((n) >= 0) && (n) >= 0 \
? mpq_cmp_ui (q, __GMP_CAST (unsigned long, n), d) \
: _mpq_cmp_si (q, n, d))
#else
#define mpz_cmp_ui(Z,UI) _mpz_cmp_ui (Z,UI)
#define mpz_cmp_si(Z,UI) _mpz_cmp_si (Z,UI)
#define mpq_cmp_ui(Q,NUI,DUI) _mpq_cmp_ui (Q,NUI,DUI)
#define mpq_cmp_si(q,n,d) _mpq_cmp_si(q,n,d)
#endif
/* Using "&" rather than "&&" means these can come out branch-free. Every
mpz_t has at least one limb allocated, so fetching the low limb is always
allowed. */
#define mpz_odd_p(z) (((z)->_mp_size != 0) & __GMP_CAST (int, (z)->_mp_d[0]))
#define mpz_even_p(z) (! mpz_odd_p (z))
/**************** C++ routines ****************/
#ifdef __cplusplus
__GMP_DECLSPEC_XX std::ostream& operator<< (std::ostream &, mpz_srcptr);
__GMP_DECLSPEC_XX std::ostream& operator<< (std::ostream &, mpq_srcptr);
__GMP_DECLSPEC_XX std::ostream& operator<< (std::ostream &, mpf_srcptr);
__GMP_DECLSPEC_XX std::istream& operator>> (std::istream &, mpz_ptr);
__GMP_DECLSPEC_XX std::istream& operator>> (std::istream &, mpq_ptr);
__GMP_DECLSPEC_XX std::istream& operator>> (std::istream &, mpf_ptr);
#endif
/* Source-level compatibility with GMP 2 and earlier. */
#define mpn_divmod(qp,np,nsize,dp,dsize) \
mpn_divrem (qp, __GMP_CAST (mp_size_t, 0), np, nsize, dp, dsize)
/* Source-level compatibility with GMP 1. */
#define mpz_mdiv mpz_fdiv_q
#define mpz_mdivmod mpz_fdiv_qr
#define mpz_mmod mpz_fdiv_r
#define mpz_mdiv_ui mpz_fdiv_q_ui
#define mpz_mdivmod_ui(q,r,n,d) \
(((r) == 0) ? mpz_fdiv_q_ui (q,n,d) : mpz_fdiv_qr_ui (q,r,n,d))
#define mpz_mmod_ui(r,n,d) \
(((r) == 0) ? mpz_fdiv_ui (n,d) : mpz_fdiv_r_ui (r,n,d))
/* Useful synonyms, but not quite compatible with GMP 1. */
#define mpz_div mpz_fdiv_q
#define mpz_divmod mpz_fdiv_qr
#define mpz_div_ui mpz_fdiv_q_ui
#define mpz_divmod_ui mpz_fdiv_qr_ui
#define mpz_div_2exp mpz_fdiv_q_2exp
#define mpz_mod_2exp mpz_fdiv_r_2exp
enum
{
GMP_ERROR_NONE = 0,
GMP_ERROR_UNSUPPORTED_ARGUMENT = 1,
GMP_ERROR_DIVISION_BY_ZERO = 2,
GMP_ERROR_SQRT_OF_NEGATIVE = 4,
GMP_ERROR_INVALID_ARGUMENT = 8,
GMP_ERROR_MPZ_OVERFLOW = 16
};
/* Define CC and CFLAGS which were used to build this version of GMP */
#define __GMP_CC "x86_64-w64-mingw32-gcc"
#define __GMP_CFLAGS "-O2 -pedantic -fomit-frame-pointer -m64 -mtune=k8 -march=k8"
/* Major version number is the value of __GNU_MP__ too, above. */
#define __GNU_MP_VERSION 6
#define __GNU_MP_VERSION_MINOR 3
#define __GNU_MP_VERSION_PATCHLEVEL 0
#define __GNU_MP_RELEASE (__GNU_MP_VERSION * 10000 + __GNU_MP_VERSION_MINOR * 100 + __GNU_MP_VERSION_PATCHLEVEL)
#define __GMP_H__
#endif /* __GMP_H__ */
| 84,311
|
C++
|
.h
| 1,810
| 44.224862
| 122
| 0.654666
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
22,463
|
arch.h
|
Nevcairiel_LAVFilters/thirdparty/64/include/avisynth/avs/arch.h
|
#ifndef _AVS_ARCH_H_
#define _AVS_ARCH_H_
#define AVS_ARCH x86_64 // e.g. i386
#endif // _AVS_ARCH_H_
| 126
|
C++
|
.h
| 4
| 30
| 56
| 0.541667
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,465
|
PostProcessor.h
|
Nevcairiel_LAVFilters/decoder/LAVAudio/PostProcessor.h
|
/*
* Copyright (C) 2010-2021 Hendrik Leppkes
* http://www.1f0.de
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
struct BufferDetails;
typedef struct ExtendedChannelMap_s
{
int idx;
int factor;
} ExtendedChannelMap[8];
inline void ExtChMapSet(ExtendedChannelMap *map, int ch, int idx, int factor)
{
(*map)[ch].idx = idx;
(*map)[ch].factor = factor;
}
inline void ExtChMapClear(ExtendedChannelMap *map)
{
for (unsigned i = 0; i < 8; ++i)
{
(*map)[i].idx = -1;
(*map)[i].factor = 0;
}
}
HRESULT ExtendedChannelMapping(BufferDetails *pcm, unsigned uOutChannels, const ExtendedChannelMap extMap);
| 1,355
|
C++
|
.h
| 39
| 32.025641
| 107
| 0.721374
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,466
|
stdafx.h
|
Nevcairiel_LAVFilters/decoder/LAVAudio/stdafx.h
|
/*
* Copyright (C) 2010-2021 Hendrik Leppkes
* http://www.1f0.de
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
// pre-compiled header
#pragma once
// Support for Version 6.0 styles
#pragma comment( \
linker, \
"\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#include "common_defines.h"
// include headers
#include <Windows.h>
#include <Commctrl.h>
#include <atlbase.h>
#include <atlconv.h>
#pragma warning(push)
#pragma warning(disable : 4244)
extern "C"
{
#define __STDC_CONSTANT_MACROS
#include "libavformat/avformat.h"
#include "libavcodec/avcodec.h"
#include "libavutil/opt.h"
#include "libavutil/intreadwrite.h"
#include "libswresample/swresample.h"
}
#pragma warning(pop)
#include "streams.h"
#include "DShowUtil.h"
#include "growarray.h"
| 1,592
|
C++
|
.h
| 45
| 33.622222
| 175
| 0.750325
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,467
|
Media.h
|
Nevcairiel_LAVFilters/decoder/LAVAudio/Media.h
|
/*
* Copyright (C) 2010-2021 Hendrik Leppkes
* http://www.1f0.de
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#define DBL_SECOND_MULT 10000000.0
#define RT_SECOND_MULT 10000000LL
#define INT24_MAX 8388607i32
#define INT24_MIN (-8388607i32 - 1)
#define LAV_CH_LAYOUT_5POINT1_BC (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY | AV_CH_BACK_CENTER)
#define LAV_CH_LAYOUT_5POINT1_WIDE \
(AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY | AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_RIGHT_OF_CENTER)
#define LAV_CH_LAYOUT_7POINT1_EXTRAWIDE (LAV_CH_LAYOUT_5POINT1_WIDE | AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT)
struct scmap_t
{
WORD nChannels;
DWORD dwChannelMask;
};
#define MAX_NUM_CC_CODECS 5
struct codec_config_t
{
int nCodecs;
AVCodecID codecs[MAX_NUM_CC_CODECS];
const char *name;
const char *description;
};
const codec_config_t *get_codec_config(LAVAudioCodec codec);
AVCodecID FindCodecId(const CMediaType *mt);
const char *find_codec_override(AVCodecID codec);
DWORD get_channel_mask(int num_channels);
const char *get_sample_format_desc(LAVAudioSampleFormat sfFormat);
const char *get_sample_format_desc(CMediaType &mt);
BYTE get_byte_per_sample(LAVAudioSampleFormat sfFormat);
LAVAudioSampleFormat get_lav_sample_fmt(AVSampleFormat sample_fmt, int bits = 0);
AVSampleFormat get_ff_sample_fmt(LAVAudioSampleFormat sample_fmt);
WORD get_channel_from_flag(DWORD dwMask, DWORD dwFlag);
DWORD get_flag_from_channel(DWORD dwMask, WORD wChannel);
const char *get_channel_desc(DWORD dwFlag);
// Gets a sample from the buffer for processing
// The sample is returned as a floating point, with either single or double precision, depending on the template type
// DO NOT USE WITH AN INTEGER TYPE - only double and float are allowed
template <class T> T get_sample_from_buffer(const BYTE *pBuffer, LAVAudioSampleFormat sfFormat);
void lav_spdif_bswap_buf16(uint16_t *dst, const uint16_t *src, int w);
| 2,642
|
C++
|
.h
| 57
| 44.263158
| 117
| 0.770249
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,468
|
BitstreamParser.h
|
Nevcairiel_LAVFilters/decoder/LAVAudio/BitstreamParser.h
|
/*
* Copyright (C) 2010-2021 Hendrik Leppkes
* http://www.1f0.de
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "parser/dts.h"
struct GetBitContext;
class CBitstreamParser
{
public:
CBitstreamParser();
~CBitstreamParser();
HRESULT Parse(AVCodecID codec, BYTE *pBuffer, DWORD dwSize);
void Reset();
private:
HRESULT ParseDTS(BYTE *pBuffer, DWORD dwSize);
HRESULT ParseAC3(BYTE *pBuffer, DWORD dwSize);
HRESULT ParseTrueHD(BYTE *pBuffer, DWORD dwSize);
public:
DWORD m_dwSampleRate = 0;
DWORD m_dwBlocks = 0;
DWORD m_dwFrameSize = 0;
DWORD m_dwSamples = 0;
BOOL m_bDTSHD = FALSE;
DTSHeader m_DTSHeader;
private:
GetBitContext *m_gb = nullptr;
void *m_pParserContext = nullptr;
};
| 1,477
|
C++
|
.h
| 43
| 31.162791
| 75
| 0.726316
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,469
|
resource.h
|
Nevcairiel_LAVFilters/decoder/LAVAudio/resource.h
|
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by LAVAudio.rc
//
#define IDD_PROPPAGE_AUDIO_SETTINGS 9
#define IDD_PROPPAGE_AUDIO_MIXING 10
#define IDD_PROPPAGE_FORMATS 11
#define IDD_PROPPAGE_STATUS 12
#define IDS_SETTINGS 101
#define IDS_STATUS 102
#define IDS_FORMATS 103
#define IDI_ICON1 104
#define IDS_MIXER 105
#define IDC_INPUT_STATUS 1013
#define IDC_OUTPUT_STATUS 1026
#define IDC_DRC 1034
#define IDC_DRC_LEVEL 1035
#define IDC_DRC_BOX 1036
#define IDC_DRC_LEVEL_TEXT 1037
#define IDC_LBL_DRC_LEVEL 1038
#define IDC_VOLUME 1039
#define IDC_VOLUME1 1040
#define IDC_VOLUME2 1041
#define IDC_VOLUME3 1042
#define IDC_VOLUME4 1043
#define IDC_VOLUME5 1044
#define IDC_VOLUME6 1045
#define IDC_VOLUME7 1046
#define IDC_VOLUME8 1047
#define IDC_VOLUME1_DESC 1048
#define IDC_VOLUME2_DESC 1049
#define IDC_VOLUME3_DESC 1050
#define IDC_VOLUME4_DESC 1051
#define IDC_VOLUME5_DESC 1052
#define IDC_VOLUME6_DESC 1053
#define IDC_VOLUME7_DESC 1054
#define IDC_VOLUME8_DESC 1055
#define IDC_CODECS 1056
#define IDC_CODECS_NONE 1059
#define IDC_LAVAUDIO_FOOTER 1060
#define IDC_BITSTREAMING 1061
#define IDC_BS_AC3 1062
#define IDC_BS_EAC3 1063
#define IDC_BS_TRUEHD 1064
#define IDC_BS_DTS 1065
#define IDC_BS_DTSHD 1066
#define IDC_BS_FORMATS 1067
#define IDC_BS_DTSHD_FRAMING 1068
#define IDC_BS_OPTIONS 1069
#define IDC_OPTIONS 1070
#define IDC_AUTO_AVSYNC 1071
#define IDC_LBL_INPUT_CODEC 1072
#define IDC_LBL_INPUT_CHANNEL 1073
#define IDC_LBL_INPUT_SAMPLERATE 1074
#define IDC_LBL_INPUT_FORMAT 1075
#define IDC_INPUT_SAMPLERATE 1076
#define IDC_INPUT_CODEC 1077
#define IDC_INPUT_CHANNEL 1078
#define IDC_INPUT_FORMAT 1079
#define IDC_LBL_OUTPUT_CODEC 1080
#define IDC_LBL_OUTPUT_CHANNEL 1081
#define IDC_LBL_OUTPUT_SAMPLERATE 1082
#define IDC_LBL_OUTPUT_FORMAT 1083
#define IDC_OUTPUT_SAMPLERATE 1084
#define IDC_OUTPUT_CODEC 1085
#define IDC_OUTPUT_CHANNEL 1086
#define IDC_OUTPUT_FORMAT 1087
#define IDC_STANDARD_CH_LAYOUT 1088
#define IDC_EXPAND_MONO 1089
#define IDC_EXPAND61 1090
#define IDC_OUTPUT_FORMATS 1091
#define IDC_LBL_OUTPUTFORMATS 1092
#define IDC_OUT_S16 1093
#define IDC_OUT_S24 1094
#define IDC_OUT_S32 1095
#define IDC_OUT_FP32 1096
#define IDC_OUT_U8 1097
#define IDC_LBL_OUTNOTE 1098
#define IDC_GROUP_DELAY 1099
#define IDC_DELAY_ENABLED 1100
#define IDC_DELAY 1101
#define IDC_DELAYSPIN 1102
#define IDC_LBL_FORMATS 1103
#define IDC_MIXING 1104
#define IDC_MIXER 1105
#define IDC_DOWNMIX 1106
#define IDC_OUTPUT_SPEAKERS 1108
#define IDC_UNTOUCHED_STEREO 1109
#define IDC_MIX_SETTINGS 1110
#define IDC_LBL_OUTPUT_SPEAKERS 1111
#define IDC_LBL_MIXING 1112
#define IDC_NORMALIZE_MATRIX 1113
#define IDC_CLIP_PROTECTION 1114
#define IDC_MIXING_MODE 1115
#define IDC_MIXMODE_NORMAL 1116
#define IDC_MIXMODE_DOLBY 1117
#define IDC_MIXMODE_DPL2 1118
#define IDC_MIX_LEVEL_CENTER 1121
#define IDC_MIX_LEVEL_SURROUND 1122
#define IDC_MIX_LEVEL_LFE 1123
#define IDC_LBL_CENTER_LEVEL 1124
#define IDC_LBL_SURROUND_LEVEL 1125
#define IDC_LBL_LFE_LEVEL 1126
#define IDC_MIX_LEVEL_CENTER_TEXT 1127
#define IDC_MIX_LEVEL_SURROUND_TEXT 1128
#define IDC_MIX_LEVEL_LFE_TEXT 1129
#define IDC_LBL_MIXING_LEVEL 1130
#define IDC_TRAYICON 1131
#define IDC_OUT_S16_DITHER 1132
#define IDC_OUTPUT51_LEGACY 1133
#define IDC_BS_FALLBACK 1135
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 106
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1134
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
| 5,192
|
C++
|
.h
| 121
| 41.892562
| 47
| 0.553452
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,470
|
AudioSettingsProp.h
|
Nevcairiel_LAVFilters/decoder/LAVAudio/AudioSettingsProp.h
|
/*
* Copyright (C) 2010-2021 Hendrik Leppkes
* http://www.1f0.de
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "LAVAudioSettings.h"
#include "BaseDSPropPage.h"
#include "Media.h"
// {2D8F1801-A70D-48F4-B76B-7F5AE022AB54}
DEFINE_GUID(CLSID_LAVAudioSettingsProp, 0x2d8f1801, 0xa70d, 0x48f4, 0xb7, 0x6b, 0x7f, 0x5a, 0xe0, 0x22, 0xab, 0x54);
// {C89FC33C-E60A-4C97-BEF4-ACC5762B6404}
DEFINE_GUID(CLSID_LAVAudioMixingProp, 0xc89fc33c, 0xe60a, 0x4c97, 0xbe, 0xf4, 0xac, 0xc5, 0x76, 0x2b, 0x64, 0x4);
// {20ED4A03-6AFD-4FD9-980B-2F6143AA0892}
DEFINE_GUID(CLSID_LAVAudioStatusProp, 0x20ed4a03, 0x6afd, 0x4fd9, 0x98, 0xb, 0x2f, 0x61, 0x43, 0xaa, 0x8, 0x92);
// {BD72668E-6BFF-4CD1-8480-D465708B336B}
DEFINE_GUID(CLSID_LAVAudioFormatsProp, 0xbd72668e, 0x6bff, 0x4cd1, 0x84, 0x80, 0xd4, 0x65, 0x70, 0x8b, 0x33, 0x6b);
class CLAVAudioSettingsProp : public CBaseDSPropPage
{
public:
CLAVAudioSettingsProp(LPUNKNOWN pUnk, HRESULT *phr);
~CLAVAudioSettingsProp();
HRESULT OnActivate();
HRESULT OnConnect(IUnknown *pUnk);
HRESULT OnDisconnect();
HRESULT OnApplyChanges();
INT_PTR OnReceiveMessage(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
private:
HRESULT LoadData();
void SetDirty()
{
m_bDirty = TRUE;
if (m_pPageSite)
{
m_pPageSite->OnStatusChange(PROPPAGESTATUS_DIRTY);
}
}
private:
ILAVAudioSettings *m_pAudioSettings = nullptr;
BOOL m_bDRCEnabled;
int m_iDRCLevel;
bool m_bBitstreaming[Bitstream_NB];
BOOL m_bDTSHDFraming;
BOOL m_bBitstreamingFallback;
BOOL m_bAutoAVSync;
BOOL m_bOutputStdLayout;
BOOL m_bOutput51Legacy;
BOOL m_bExpandMono;
BOOL m_bExpand61;
bool m_bSampleFormats[SampleFormat_NB];
BOOL m_bDither;
BOOL m_bAudioDelay;
int m_iAudioDelay;
BOOL m_TrayIcon;
};
class CLAVAudioMixingProp : public CBaseDSPropPage
{
public:
CLAVAudioMixingProp(LPUNKNOWN pUnk, HRESULT *phr);
~CLAVAudioMixingProp();
HRESULT OnActivate();
HRESULT OnConnect(IUnknown *pUnk);
HRESULT OnDisconnect();
HRESULT OnApplyChanges();
INT_PTR OnReceiveMessage(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
private:
HRESULT LoadData();
void SetDirty()
{
m_bDirty = TRUE;
if (m_pPageSite)
{
m_pPageSite->OnStatusChange(PROPPAGESTATUS_DIRTY);
}
}
private:
ILAVAudioSettings *m_pAudioSettings = nullptr;
BOOL m_bMixing;
DWORD m_dwSpeakerLayout;
DWORD m_dwFlags;
DWORD m_dwMixingMode;
DWORD m_dwMixCenter;
DWORD m_dwMixSurround;
DWORD m_dwMixLFE;
};
class CLAVAudioFormatsProp : public CBaseDSPropPage
{
public:
CLAVAudioFormatsProp(LPUNKNOWN pUnk, HRESULT *phr);
~CLAVAudioFormatsProp();
HRESULT OnActivate();
HRESULT OnConnect(IUnknown *pUnk);
HRESULT OnDisconnect();
HRESULT OnApplyChanges();
INT_PTR OnReceiveMessage(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
private:
HRESULT LoadData();
void SetDirty()
{
m_bDirty = TRUE;
if (m_pPageSite)
{
m_pPageSite->OnStatusChange(PROPPAGESTATUS_DIRTY);
}
}
private:
ILAVAudioSettings *m_pAudioSettings = nullptr;
bool m_bFormats[Codec_AudioNB];
};
class CLAVAudioStatusProp : public CBaseDSPropPage
{
public:
CLAVAudioStatusProp(LPUNKNOWN pUnk, HRESULT *phr);
~CLAVAudioStatusProp();
HRESULT OnActivate();
HRESULT OnDeactivate();
HRESULT OnConnect(IUnknown *pUnk);
HRESULT OnDisconnect();
INT_PTR OnReceiveMessage(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
private:
void UpdateVolumeDisplay();
private:
ILAVAudioStatus *m_pAudioStatus = nullptr;
int m_nChannels = 0;
};
| 4,504
|
C++
|
.h
| 138
| 28.173913
| 116
| 0.718469
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,471
|
parser.h
|
Nevcairiel_LAVFilters/decoder/LAVAudio/parser/parser.h
|
/*
* Copyright (C) 2010-2021 Hendrik Leppkes
* http://www.1f0.de
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
static inline const uint8_t *find_marker32_position(const uint8_t *pBuffer, size_t uBufSize, uint32_t marker)
{
uint32_t state = 0;
for (size_t i = 0; i < uBufSize; ++i)
{
state = (state << 8) | pBuffer[i];
if (state == marker)
{
return pBuffer + (i - 3);
}
}
return nullptr;
}
| 1,170
|
C++
|
.h
| 32
| 32.9375
| 109
| 0.684581
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,472
|
dts.h
|
Nevcairiel_LAVFilters/decoder/LAVAudio/parser/dts.h
|
/*
* Copyright (C) 2010-2021 Hendrik Leppkes
* http://www.1f0.de
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "parser.h"
/** DCA syncwords */
#define DCA_MARKER_RAW_BE 0x7FFE8001
#define DCA_MARKER_RAW_LE 0xFE7F0180
#define DCA_MARKER_14B_BE 0x1FFFE800
#define DCA_MARKER_14B_LE 0xFF1F00E8
/** DCA-HD specific block starts with this marker. */
#define DCA_HD_MARKER 0x64582025
/** DCA extension blocks */
#define DCA_XCH_MARKER 0x5a5a5a5a
#define DCA_XXCH_MARKER 0x47004A03
struct DTSParserContext;
struct DTSHeader
{
unsigned HasCore;
unsigned CRCPresent;
unsigned SamplesPerBlock;
unsigned Blocks;
unsigned FrameSize;
unsigned ChannelLayout;
unsigned SampleRate;
unsigned LFE;
// Extensions
unsigned ES;
unsigned XChChannelLayout;
unsigned IsHD;
unsigned HDTotalChannels;
unsigned HDSpeakerMask;
};
int init_dts_parser(DTSParserContext **pContext);
int close_dts_parser(DTSParserContext **pContext);
int parse_dts_header(DTSParserContext *pContext, DTSHeader *pHeader, uint8_t *pBuffer, unsigned uSize);
| 1,806
|
C++
|
.h
| 51
| 32.764706
| 103
| 0.757454
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,473
|
stdafx.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/stdafx.h
|
/*
* Copyright (C) 2010-2021 Hendrik Leppkes
* http://www.1f0.de
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
// pre-compiled header
#pragma once
// Support for Version 6.0 styles
#pragma comment( \
linker, \
"\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#include "common_defines.h"
// include headers
#include <Windows.h>
#include <Commctrl.h>
#include <atlbase.h>
#include <atlconv.h>
#include <d3d9.h>
#include <dxva2api.h>
#include <dvdmedia.h>
#pragma warning(push)
#pragma warning(disable : 4244)
extern "C"
{
#define __STDC_CONSTANT_MACROS
#include "libavcodec/avcodec.h"
#include "libswscale/swscale.h"
#include "libavfilter/avfilter.h"
#include "libavfilter/buffersink.h"
#include "libavfilter/buffersrc.h"
#include "libavutil/cpu.h"
#include "libavutil/intreadwrite.h"
#include "libavutil/pixdesc.h"
#include "libavutil/opt.h"
}
#pragma warning(pop)
#include "streams.h"
#include "DShowUtil.h"
#include "growarray.h"
#include "SubRenderIntf.h"
#define REF_SECOND_MULT 10000000LL
| 1,842
|
C++
|
.h
| 54
| 32.425926
| 175
| 0.756194
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,475
|
Media.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/Media.h
|
/*
* Copyright (C) 2010-2021 Hendrik Leppkes
* http://www.1f0.de
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "IMediaSideData.h"
#include "libavutil/mastering_display_metadata.h"
#include "libavutil/hdr_dynamic_metadata.h"
#include "libavutil/dovi_meta.h"
AVCodecID FindCodecId(const CMediaType *mt);
int getThreadFlags(AVCodecID codecId);
#define MAX_NUM_CC_CODECS 3
struct codec_config_t
{
int nCodecs;
AVCodecID codecs[MAX_NUM_CC_CODECS];
const char *name;
const char *description;
};
const codec_config_t *get_codec_config(LAVVideoCodec codec);
int flip_plane(BYTE *buffer, int stride, int height);
void fillDXVAExtFormat(DXVA2_ExtendedFormat &fmt, int range, int primaries, int matrix, int transfer,
int chroma_sample_location = 0, bool bClear = true);
void processFFHDRData(MediaSideDataHDR *sd, AVMasteringDisplayMetadata *ff);
void processFFHDR10PlusData(MediaSideDataHDR10Plus *sd, AVDynamicHDRPlus *ff, int width, int height);
void processFFDOVIData(MediaSideDataDOVIMetadata *sd, const AVDOVIMetadata *ff);
#define STATE_NOT_FOUND 0
#define STATE_EOS_FOUND 1
#define STATE_GOP_FOUND 2
int CheckForSequenceMarkers(AVCodecID codec, const uint8_t *buf, long len, uint32_t *state,
const uint8_t **pos = nullptr);
int sws_scale2(struct SwsContext *c, const uint8_t *const srcSlice[], const ptrdiff_t srcStride[], int srcSliceY,
int srcSliceH, uint8_t *const dst[], const ptrdiff_t dstStride[]);
| 2,215
|
C++
|
.h
| 47
| 43.851064
| 113
| 0.75
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,476
|
CCOutputPin.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/CCOutputPin.h
|
/*
* Copyright (C) 2010-2021 Hendrik Leppkes
* http://www.1f0.de
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
class CLAVVideo;
class CCCOutputPin : public CBaseOutputPin
{
public:
CCCOutputPin(TCHAR *pObjectName, CLAVVideo *pFilter, CCritSec *pcsFilter, HRESULT *phr, LPWSTR pName);
virtual ~CCCOutputPin();
// IUnknown
DECLARE_IUNKNOWN
STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void **ppv);
// CBasePin
virtual HRESULT CheckMediaType(const CMediaType *pmt);
virtual HRESULT GetMediaType(int iPosition, CMediaType *pmt);
virtual HRESULT Active(void);
// CBaseOutputPin
virtual HRESULT DecideBufferSize(IMemAllocator *pAlloc, ALLOCATOR_PROPERTIES *ppropInputRequest);
// CCOutputPin
STDMETHODIMP DeliverCCData(BYTE *pData, size_t size, REFERENCE_TIME rtTime);
private:
CMediaType m_CCmt;
};
| 1,585
|
C++
|
.h
| 39
| 37.461538
| 106
| 0.752276
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,481
|
VideoSettingsProp.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/VideoSettingsProp.h
|
/*
* Copyright (C) 2010-2021 Hendrik Leppkes
* http://www.1f0.de
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "LAVVideoSettings.h"
#include "BaseDSPropPage.h"
#include "Media.h"
// {278407C2-558C-4BED-83A0-B6FA454200BD}
DEFINE_GUID(CLSID_LAVVideoSettingsProp, 0x278407c2, 0x558c, 0x4bed, 0x83, 0xa0, 0xb6, 0xfa, 0x45, 0x42, 0x0, 0xbd);
// {2D4D6F88-8B41-40A2-B297-3D722816648B}
DEFINE_GUID(CLSID_LAVVideoFormatsProp, 0x2d4d6f88, 0x8b41, 0x40a2, 0xb2, 0x97, 0x3d, 0x72, 0x28, 0x16, 0x64, 0x8b);
class CLAVVideoSettingsProp : public CBaseDSPropPage
{
public:
CLAVVideoSettingsProp(LPUNKNOWN pUnk, HRESULT *phr);
~CLAVVideoSettingsProp();
HRESULT OnActivate();
HRESULT OnConnect(IUnknown *pUnk);
HRESULT OnDisconnect();
HRESULT OnApplyChanges();
INT_PTR OnReceiveMessage(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
private:
HRESULT LoadData();
HRESULT UpdateHWOptions();
HRESULT UpdateYADIFOptions();
void SetDirty()
{
m_bDirty = TRUE;
if (m_pPageSite)
{
m_pPageSite->OnStatusChange(PROPPAGESTATUS_DIRTY);
}
}
private:
ILAVVideoSettings *m_pVideoSettings = nullptr;
ILAVVideoStatus *m_pVideoStatus = nullptr;
DWORD m_dwNumThreads;
DWORD m_StreamAR;
DWORD m_DeintFieldOrder;
LAVDeintMode m_DeintMode;
DWORD m_dwRGBOutput;
BOOL m_bPixFmts[LAVOutPixFmt_NB];
DWORD m_HWAccel;
BOOL m_HWAccelCodecs[HWCodec_NB];
BOOL m_HWAccelCUVIDDXVA;
DWORD m_HWRes;
DWORD m_HWDeviceIndex;
DWORD m_HWDeintAlgo;
DWORD m_HWDeintOutMode;
LAVSWDeintModes m_SWDeint;
DWORD m_SWDeintOutMode;
DWORD m_DitherMode;
BOOL m_TrayIcon;
};
class CLAVVideoFormatsProp : public CBaseDSPropPage
{
public:
CLAVVideoFormatsProp(LPUNKNOWN pUnk, HRESULT *phr);
~CLAVVideoFormatsProp();
HRESULT OnActivate();
HRESULT OnConnect(IUnknown *pUnk);
HRESULT OnDisconnect();
HRESULT OnApplyChanges();
INT_PTR OnReceiveMessage(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
private:
HRESULT LoadData();
void SetDirty()
{
m_bDirty = TRUE;
if (m_pPageSite)
{
m_pPageSite->OnStatusChange(PROPPAGESTATUS_DIRTY);
}
}
private:
ILAVVideoSettings *m_pVideoSettings = nullptr;
BOOL m_bFormats[Codec_VideoNB];
BOOL m_bWMVDMO;
BOOL m_bDVD;
};
| 3,125
|
C++
|
.h
| 95
| 28.473684
| 115
| 0.718272
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,482
|
resource.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/resource.h
|
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by LAVVideo.rc
//
#define IDD_PROPPAGE_VIDEO_SETTINGS 9
#define IDD_PROPPAGE_FORMATS 10
#define IDS_SETTINGS 101
#define IDS_FORMATS 102
#define IDI_ICON1 103
#define IDS_FIELDORDER_AUTO 104
#define IDS_FIELDORDER_TOP 105
#define IDS_FIELDORDER_BOTTOM 106
#define IDS_DEINTMODE_AUTO 107
#define IDS_DEINTMODE_AGGRESSIVE 108
#define IDS_DEINTMODE_FORCE 109
#define IDS_DEINTMODE_DISABLE 110
#define IDC_CODECS 1001
#define IDC_LAVVIDEO_FOOTER 1002
#define IDC_VIDEO_SETTINGS 1003
#define IDC_STREAMAR 1004
#define IDC_THREADS 1005
#define IDC_LBL_MULTITHREAD 1006
#define IDC_OUTPUT_FORMATS 1008
#define IDC_OUT_YV12 1009
#define IDC_OUT_NV12 1010
#define IDC_OUT_P010 1011
#define IDC_OUT_P016 1012
#define IDC_OUT_YUY2 1013
#define IDC_OUT_P210 1014
#define IDC_OUT_P216 1015
#define IDC_OUT_AYUV 1016
#define IDC_OUT_Y410 1017
#define IDC_OUT_Y416 1018
#define IDC_OUT_RGB32 1019
#define IDC_OUT_RGB24 1020
#define IDC_OUT_420 1021
#define IDC_OUT_422 1022
#define IDC_OUT_444 1023
#define IDC_OUT_RGB 1024
#define IDC_OUT_8BIT 1025
#define IDC_OUT_10BIT 1026
#define IDC_OUT_16BIT 1027
#define IDC_OUT_UYVY 1028
#define IDC_OUT_RGB48 1029
#define IDC_LBL_RGBOUT 1030
#define IDC_RGBOUT_AUTO 1031
#define IDC_RGBOUT_TV 1032
#define IDC_RGBOUT_PC 1033
#define IDC_HWACCEL_SETTINGS 1034
#define IDC_LBL_HWACCEL 1035
#define IDC_HWACCEL 1036
#define IDC_LBL_HWCODECS 1037
#define IDC_HWACCEL_H264 1038
#define IDC_HWACCEL_VC1 1039
#define IDC_HWACCEL_MPEG2 1040
#define IDC_HW_DEINT 1041
#define IDC_LBL_HWDEINT_MODE 1046
#define IDC_HWDEINT_OUT_VIDEO 1047
#define IDC_HWDEINT_OUT_FILM 1048
#define IDC_LBL_DEINT_FIELDORDER 1049
#define IDC_DEINT_FIELDORDER 1050
#define IDC_LBL_DEINT_MODE 1051
#define IDC_HWACCEL_AVAIL 1053
#define IDC_DEINT_SETTINGS 1054
#define IDC_DEINT_MODE 1055
#define IDC_SWDEINT_MODE 1056
#define IDC_SWDEINT 1057
#define IDC_LBL_SWDEINT_MODE 1058
#define IDC_SWDEINT_OUT_FILM 1059
#define IDC_SWDEINT_OUT_VIDEO 1060
#define IDC_OUT_V210 1062
#define IDC_OUT_V410 1063
#define IDC_HWACCEL_MPEG4 1064
#define IDC_LBL_FORMATS 1065
#define IDC_DITHER_ORDERED 1066
#define IDC_DITHER_RANDOM 1067
#define IDC_CODECS_MSWMVDMO 1068
#define IDC_ACTIVE_DECODER 1069
#define IDC_OUT_YV24 1070
#define IDC_DVD_VIDEO 1071
#define IDC_GROUP_HWDEINT 1072
#define IDC_HWDEINT_ENABLE 1073
#define IDC_LBL_HWRESOLUTIONS 1074
#define IDC_HWRES_SD 1075
#define IDC_HWRES_HD 1076
#define IDC_HWRES_UHD 1077
#define IDC_HWACCEL_MPEG2_DVD 1078
#define IDC_TRAYICON 1079
#define IDC_HWACCEL_HEVC 1080
#define IDC_HWACCEL_VP9 1081
#define IDC_LBL_SWDEINT_ALGO 1082
#define IDC_LBL_HWACCEL_DEVICE 1083
#define IDC_HWACCEL_DEVICE 1084
#define IDC_HWACCEL_DEVICE_SELECT 1085
#define IDC_LBL_HWACCEL_DEVICE_SELECT 1086
#define IDC_LBL_HWACCEL_DEVICE_HINT 1087
#define IDC_HWACCEL_CUVID_DXVA 1088
#define IDC_HWACCEL_H264MVC 1089
#define IDC_HWACCEL_AV1 1090
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 111
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1091
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
| 4,651
|
C++
|
.h
| 109
| 41.651376
| 47
| 0.556706
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,483
|
pixconv_internal.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/pixconv/pixconv_internal.h
|
/*
* Copyright (C) 2010-2021 Hendrik Leppkes
* http://www.1f0.de
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "LAVPixFmtConverter.h"
#include <emmintrin.h>
#include "timer.h"
#include "Media.h"
extern __declspec(align(16)) const uint16_t dither_8x8_256[8][8];
| 987
|
C++
|
.h
| 24
| 39.291667
| 75
| 0.742708
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,484
|
pixconv_sse2_templates.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/pixconv/pixconv_sse2_templates.h
|
/*
* Copyright (C) 2010-2021 Hendrik Leppkes
* http://www.1f0.de
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include <emmintrin.h>
#include <smmintrin.h>
// Load the dithering coefficients for this line
// reg - register to load coefficients into
// line - index of line to process (0 based)
// bits - number of bits to dither (for 10 -> 8, set to 2)
#define PIXCONV_LOAD_DITHER_COEFFS(reg, line, bits, name) \
const uint16_t *name = dither_8x8_256[(line) % 8]; \
reg = _mm_load_si128((const __m128i *)name); \
reg = _mm_srli_epi16(reg, 8 - bits); /* shift to the required dithering strength */
// Load 8 16-bit pixels into a register, using aligned memory access
// reg - register to store pixels in
// src - memory pointer of the source
// bpp - bit depth of the pixels
#define PIXCONV_LOAD_PIXEL16(reg, src, bpp) \
reg = _mm_load_si128((const __m128i *)(src)); /* load (aligned) */ \
reg = _mm_slli_epi16(reg, 16 - bpp); /* shift to 16-bit */
// Load 2x8 16-bit pixels into registers, using aligned memory access
// reg1 - register to store pixels in
// reg2 - register to store pixels in
// src1 - memory pointer of the source
// src2 - memory pointer of the source
// bpp - bit depth of the pixels
#define PIXCONV_LOAD_PIXEL16X2(reg1, reg2, src1, src2, bpp) \
{ \
const __m128i shift = _mm_cvtsi32_si128(16 - bpp); \
reg1 = _mm_load_si128((const __m128i *)(src1)); \
reg2 = _mm_load_si128((const __m128i *)(src2)); \
reg1 = _mm_sll_epi16(reg1, shift); \
reg2 = _mm_sll_epi16(reg2, shift); \
}
// Load 8 16-bit pixels into a register, and dither them to 8 bit
// The 8-bit pixels will be in the high-bytes of the 8 16-bit parts
// NOTE: the low-bytes are clobbered, and not empty.
// reg - register to store pixels in
// dreg - register with dithering coefficients
// src - memory pointer of the source
// bpp - bit depth of the pixels
#define PIXCONV_LOAD_PIXEL16_DITHER_HIGH(reg, dreg, src, bpp) \
PIXCONV_LOAD_PIXEL16(reg, src, bpp) \
reg = _mm_adds_epu16(reg, dreg); /* dither */
// Load 8 16-bit pixels into a register, and dither them to 8 bit
// The 8-bit pixels will be in the low-bytes of the 8 16-bit parts
// reg - register to store pixels in
// dreg - register with dithering coefficients
// src - memory pointer of the source
// bpp - bit depth of the pixels
#define PIXCONV_LOAD_PIXEL16_DITHER(reg, dreg, src, bpp) \
PIXCONV_LOAD_PIXEL16_DITHER_HIGH(reg, dreg, src, bpp) \
reg = _mm_srli_epi16(reg, 8); /* shift to 8-bit */
// Load 8 16-bit pixels into a register, and dither them to 8 bit
// The 8-bit pixels will be in the 8 low-bytes in the register
// reg - register to store pixels in
// dreg - register with dithering coefficients
// src - memory pointer of the source
// bpp - bit depth of the pixels
#define PIXCONV_LOAD_PIXEL16_DITHER_PACKED(reg, dreg, zero, src, bpp) \
PIXCONV_LOAD_PIXEL16_DITHER(reg, dreg, src, bpp) /* load unpacked */ \
reg = _mm_packus_epi16(reg, zero); /* pack */
// Load 16 8-bit pixels into a register
// reg - register to store pixels in
// src - memory pointer of the source
#define PIXCONV_LOAD_PIXEL8(reg, src) reg = _mm_loadu_si128((const __m128i *)(src)); /* load (unaligned) */
// Load 128-bit into a register, using aligned memory access
// reg - register to store pixels in
// src - memory pointer of the source
#define PIXCONV_LOAD_ALIGNED(reg, src) reg = _mm_load_si128((const __m128i *)(src)); /* load (aligned) */
// Load 128-bit into a register, using streaming memory access
// reg - register to store pixels in
// src - memory pointer of the source
#define PIXCONV_STREAM_LOAD(reg, src) reg = _mm_stream_load_si128((__m128i *)(src)); /* load (streaming) */
#define PIXCONV_LOAD_PIXEL8_ALIGNED PIXCONV_LOAD_ALIGNED
// Put 128-bit into memory, using streaming write
#define PIXCONV_PUT_STREAM(dst, reg) _mm_stream_si128((__m128i *)(dst), reg); /* streaming write */
// Load 4 8-bit pixels into the register
// reg - register to store pixels in
// src - source memory
#define PIXCONV_LOAD_4PIXEL8(reg, src) reg = _mm_cvtsi32_si128(*(const int *)(src)); /* load 32-bit (4 pixel) */
// Load 4 16-bit pixels into the register
// reg - register to store pixels in
// src - source memory
#define PIXCONV_LOAD_4PIXEL16(reg, src) reg = _mm_loadl_epi64((const __m128i *)(src)); /* load 64-bit (4 pixel) */
// SSE2 Aligned memcpy
// dst - memory destination
// src - memory source
// len - size in bytes
#define PIXCONV_MEMCPY_ALIGNED(dst, src, len) \
{ \
const uint8_t *const srcLinePtr = (src); \
uint8_t *const dstLinePtr = (dst); \
__m128i r1, r2, r3, r4; \
ptrdiff_t i; \
for (i = 0; i < (len - 63); i += 64) \
{ \
PIXCONV_LOAD_ALIGNED(r1, srcLinePtr + i + 0) \
PIXCONV_LOAD_ALIGNED(r2, srcLinePtr + i + 16); \
PIXCONV_LOAD_ALIGNED(r3, srcLinePtr + i + 32); \
PIXCONV_LOAD_ALIGNED(r4, srcLinePtr + i + 48); \
PIXCONV_PUT_STREAM(dstLinePtr + i + 0, r1); \
PIXCONV_PUT_STREAM(dstLinePtr + i + 16, r2); \
PIXCONV_PUT_STREAM(dstLinePtr + i + 32, r3); \
PIXCONV_PUT_STREAM(dstLinePtr + i + 48, r4); \
} \
for (; i < len; i += 16) \
{ \
PIXCONV_LOAD_ALIGNED(r1, srcLinePtr + i); \
PIXCONV_PUT_STREAM(dstLinePtr + i, r1); \
} \
}
// SSE2 Aligned memcpy
// Copys the same size from two source into two destinations at the same time
// dst1 - memory destination
// src1 - memory source
// dst2 - memory destination
// src2 - memory source
// len - size in bytes
#define PIXCONV_MEMCPY_ALIGNED_TWO(dst1, src1, dst2, src2, len) \
{ \
const uint8_t *const src1LinePtr = (src1); \
const uint8_t *const src2LinePtr = (src2); \
uint8_t *const dst1LinePtr = (dst1); \
uint8_t *const dst2LinePtr = (dst2); \
__m128i r1, r2, r3, r4, r5, r6, r7, r8; \
ptrdiff_t i; \
for (i = 0; i < (len - 63); i += 64) \
{ \
PIXCONV_LOAD_ALIGNED(r1, src1LinePtr + i + 0); \
PIXCONV_LOAD_ALIGNED(r2, src1LinePtr + i + 16); \
PIXCONV_LOAD_ALIGNED(r3, src1LinePtr + i + 32); \
PIXCONV_LOAD_ALIGNED(r4, src1LinePtr + i + 48); \
PIXCONV_LOAD_ALIGNED(r5, src2LinePtr + i + 0); \
PIXCONV_LOAD_ALIGNED(r6, src2LinePtr + i + 16); \
PIXCONV_LOAD_ALIGNED(r7, src2LinePtr + i + 32); \
PIXCONV_LOAD_ALIGNED(r8, src2LinePtr + i + 48); \
PIXCONV_PUT_STREAM(dst1LinePtr + i + 0, r1); \
PIXCONV_PUT_STREAM(dst1LinePtr + i + 16, r2); \
PIXCONV_PUT_STREAM(dst1LinePtr + i + 32, r3); \
PIXCONV_PUT_STREAM(dst1LinePtr + i + 48, r4); \
PIXCONV_PUT_STREAM(dst2LinePtr + i + 0, r5); \
PIXCONV_PUT_STREAM(dst2LinePtr + i + 16, r6); \
PIXCONV_PUT_STREAM(dst2LinePtr + i + 32, r7); \
PIXCONV_PUT_STREAM(dst2LinePtr + i + 48, r8); \
} \
for (; i < len; i += 16) \
{ \
PIXCONV_LOAD_ALIGNED(r1, src1LinePtr + i); \
PIXCONV_LOAD_ALIGNED(r2, src2LinePtr + i); \
PIXCONV_PUT_STREAM(dst1LinePtr + i, r1); \
PIXCONV_PUT_STREAM(dst2LinePtr + i, r2); \
} \
}
| 9,271
|
C++
|
.h
| 170
| 49.547059
| 114
| 0.55218
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,485
|
LAVSubtitleFrame.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/subtitles/LAVSubtitleFrame.h
|
/*
* Copyright (C) 2010-2021 Hendrik Leppkes
* http://www.1f0.de
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
class CLAVSubRect : public IUnknown
{
public:
CLAVSubRect()
{
memset(&position, 0, sizeof(position));
memset(&size, 0, sizeof(size));
}
~CLAVSubRect()
{
SAFE_CO_FREE(pixels);
SAFE_CO_FREE(pixelsPal);
}
// IUnknown
STDMETHODIMP QueryInterface(REFIID riid, void **ppvObject)
{
if (riid == IID_IUnknown)
{
AddRef();
*ppvObject = (IUnknown *)this;
}
else
{
return E_NOINTERFACE;
}
return S_OK;
}
STDMETHODIMP_(ULONG) AddRef()
{
ULONG lRef = InterlockedIncrement(&m_cRef);
return max(ULONG(lRef), 1ul);
}
STDMETHODIMP_(ULONG) Release()
{
ULONG lRef = InterlockedDecrement(&m_cRef);
if (lRef == 0)
{
m_cRef++;
delete this;
return 0;
}
return max(ULONG(lRef), 1ul);
}
// Reset the reference count to 0, can be used after a copy-constructor
STDMETHODIMP ResetRefCount()
{
m_cRef = 0ul;
return S_OK;
}
public:
REFERENCE_TIME rtStart = AV_NOPTS_VALUE; ///< Start Time
REFERENCE_TIME rtStop = AV_NOPTS_VALUE; ///< Stop time
ULONGLONG id = 0; ///< Unique Identifier (same ID = same subtitle)
POINT position; ///< Position (relative to outputRect)
SIZE size; ///< Size
LPVOID pixels = nullptr; ///< Pixel Data
LPVOID pixelsPal = nullptr; ///< Pixel Data (in paletted form, required by dvd HLI)
int pitch = 0; ///< Pitch of the subtitle lines
bool forced = false; ///< Forced/Menu
bool freePixels = false; ///< If true, pixel data is free'ed upon destroy
private:
ULONG m_cRef = 0;
};
class CLAVSubtitleFrame
: public ISubRenderFrame
, public CUnknown
{
public:
CLAVSubtitleFrame(void);
virtual ~CLAVSubtitleFrame(void);
DECLARE_IUNKNOWN;
// ISubRenderFrame
STDMETHODIMP GetOutputRect(RECT *outputRect);
STDMETHODIMP GetClipRect(RECT *clipRect);
STDMETHODIMP GetBitmapCount(int *count);
STDMETHODIMP GetBitmap(int index, ULONGLONG *id, POINT *position, SIZE *size, LPCVOID *pixels, int *pitch);
STDMETHODIMP SetOutputRect(RECT outputRect);
STDMETHODIMP SetClipRect(RECT clipRect);
STDMETHODIMP AddBitmap(CLAVSubRect *subRect);
BOOL Empty() const { return m_NumBitmaps == 0; };
private:
RECT m_outputRect;
RECT m_clipRect;
CLAVSubRect **m_Bitmaps = nullptr;
int m_NumBitmaps = 0;
};
| 3,498
|
C++
|
.h
| 105
| 27.857143
| 111
| 0.62426
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,486
|
LAVVideoSubtitleInputPin.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/subtitles/LAVVideoSubtitleInputPin.h
|
/*
* Copyright (C) 2010-2021 Hendrik Leppkes
* http://www.1f0.de
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "DeCSS/DeCSSInputPin.h"
#include "SubRenderIntf.h"
#include "LAVSubtitleProvider.h"
class CLAVVideo;
class CLAVVideoSubtitleInputPin
: public CBaseInputPin
, public CDeCSSPinHelper
{
public:
CLAVVideoSubtitleInputPin(TCHAR *pObjectName, CLAVVideo *pFilter, CCritSec *pcsFilter, HRESULT *phr, LPWSTR pName);
virtual ~CLAVVideoSubtitleInputPin(void);
DECLARE_IUNKNOWN
STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void **ppv);
// IMemInputPin
STDMETHODIMP Receive(IMediaSample *pSample);
// CBasePin
HRESULT CheckMediaType(const CMediaType *mtIn);
HRESULT SetMediaType(const CMediaType *pmt);
HRESULT BreakConnect();
STDMETHODIMP BeginFlush();
STDMETHODIMP EndFlush();
HRESULT SetSubtitleConsumer(ISubRenderConsumer *pConsumer);
// KsPropertySet
STDMETHODIMP Set(REFGUID PropSet, ULONG Id, LPVOID InstanceData, ULONG InstanceLength, LPVOID PropertyData,
ULONG DataLength);
STDMETHODIMP QuerySupported(REFGUID PropSet, ULONG Id, ULONG *pTypeSupport);
protected:
CCritSec m_csReceive;
ISubRenderConsumer *m_pConsumer = nullptr;
CLAVSubtitleProvider *m_pProvider = nullptr;
CLAVVideo *m_pLAVVideo = nullptr;
};
| 2,073
|
C++
|
.h
| 51
| 36.862745
| 119
| 0.756219
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,487
|
LAVSubtitleConsumer.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/subtitles/LAVSubtitleConsumer.h
|
/*
* Copyright (C) 2010-2021 Hendrik Leppkes
* http://www.1f0.de
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "SubRenderOptionsImpl.h"
#include "LAVSubtitleFrame.h"
#include "../decoders/ILAVDecoder.h"
#define BLEND_FUNC_PARAMS \
(BYTE * video[4], ptrdiff_t videoStride[4], RECT vidRect, BYTE * subData[4], ptrdiff_t subStride[4], \
POINT position, SIZE size, LAVPixelFormat pixFmt, int bpp)
#define DECLARE_BLEND_FUNC(name) HRESULT name BLEND_FUNC_PARAMS
#define DECLARE_BLEND_FUNC_IMPL(name) DECLARE_BLEND_FUNC(CLAVSubtitleConsumer::name)
typedef struct LAVSubtitleConsumerContext
{
LPWSTR name; ///< name of the Consumer
LPWSTR version; ///< Version of the Consumer
SIZE originalVideoSize; ///< Size of the video
} LAVSubtitleConsumerContext;
class CLAVVideo;
class CLAVSubtitleConsumer
: public ISubRenderConsumer2
, public CSubRenderOptionsImpl
, public CUnknown
{
public:
CLAVSubtitleConsumer(CLAVVideo *pLAVVideo);
virtual ~CLAVSubtitleConsumer(void);
DECLARE_IUNKNOWN;
STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void **ppv);
DECLARE_ISUBRENDEROPTIONS;
// ISubRenderConsumer2
STDMETHODIMP GetMerit(ULONG *merit)
{
CheckPointer(merit, E_POINTER);
*merit = 0x00010000;
return S_OK;
}
STDMETHODIMP Connect(ISubRenderProvider *subtitleRenderer);
STDMETHODIMP Disconnect(void);
STDMETHODIMP DeliverFrame(REFERENCE_TIME start, REFERENCE_TIME stop, LPVOID context,
ISubRenderFrame *subtitleFrame);
STDMETHODIMP Clear(REFERENCE_TIME clearNewerThan = 0);
// LAV Internal methods
STDMETHODIMP RequestFrame(REFERENCE_TIME rtStart, REFERENCE_TIME rtStop);
STDMETHODIMP ProcessFrame(LAVFrame *pFrame);
STDMETHODIMP DisconnectProvider()
{
if (m_pProvider)
m_pProvider->Disconnect();
SafeRelease(&m_pProvider);
return S_OK;
}
BOOL HasProvider() const { return m_pProvider != nullptr; }
void SetVideoSize(LONG w, LONG h)
{
context.originalVideoSize.cx = w;
context.originalVideoSize.cy = h;
}
private:
STDMETHODIMP ProcessSubtitleBitmap(LAVPixelFormat pixFmt, int bpp, RECT videoRect, BYTE *videoData[4],
ptrdiff_t videoStride[4], RECT subRect, POINT subPosition, SIZE subSize,
const uint8_t *rgbData, ptrdiff_t pitch);
STDMETHODIMP SelectBlendFunction();
typedef HRESULT(CLAVSubtitleConsumer::*BlendFn) BLEND_FUNC_PARAMS;
BlendFn blend = nullptr;
DECLARE_BLEND_FUNC(blend_rgb_c);
template <class pixT, int nv12> DECLARE_BLEND_FUNC(blend_yuv_c);
private:
ISubRenderProvider *m_pProvider = nullptr;
ISubRenderFrame *m_SubtitleFrame = nullptr;
CAMEvent m_evFrame{FALSE};
SwsContext *m_pSwsContext = nullptr;
LAVPixelFormat m_PixFmt = LAVPixFmt_None;
LAVSubtitleConsumerContext context;
CLAVVideo *m_pLAVVideo = nullptr;
};
| 3,834
|
C++
|
.h
| 91
| 36.67033
| 111
| 0.701693
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,488
|
SubRenderOptionsImpl.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/subtitles/SubRenderOptionsImpl.h
|
/*
* Copyright (C) 2010-2021 Hendrik Leppkes
* http://www.1f0.de
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
/** Enum for the different types */
enum SubRenderOptionType
{
SROPT_TYPE_BOOL,
SROPT_TYPE_INT,
SROPT_TYPE_SIZE,
SROPT_TYPE_RECT,
SROPT_TYPE_ULONGLONG,
SROPT_TYPE_DOUBLE,
SROPT_TYPE_STRING,
SROPT_TYPE_BIN
};
typedef struct SubRenderOption
{
/**
* Name of the field
*/
LPCSTR name;
/**
* The offset relative to the options structure
*/
int offset;
/**
* The type of the options
*/
enum SubRenderOptionType type;
/**
* Flags
*/
int flags;
#define SROPT_FLAG_READONLY 1
} SubRenderOption;
class CSubRenderOptionsImpl : public ISubRenderOptions
{
public:
CSubRenderOptionsImpl(const struct SubRenderOption *options, void *context)
: options(options)
, context(context){};
virtual ~CSubRenderOptionsImpl(void){};
// ISubRenderOptions
STDMETHODIMP GetBool(LPCSTR field, bool *value);
STDMETHODIMP GetInt(LPCSTR field, int *value);
STDMETHODIMP GetSize(LPCSTR field, SIZE *value);
STDMETHODIMP GetRect(LPCSTR field, RECT *value);
STDMETHODIMP GetUlonglong(LPCSTR field, ULONGLONG *value);
STDMETHODIMP GetDouble(LPCSTR field, double *value);
STDMETHODIMP GetString(LPCSTR field, LPWSTR *value, int *chars);
STDMETHODIMP GetBin(LPCSTR field, LPVOID *value, int *size);
STDMETHODIMP SetBool(LPCSTR field, bool value);
STDMETHODIMP SetInt(LPCSTR field, int value);
STDMETHODIMP SetSize(LPCSTR field, SIZE value);
STDMETHODIMP SetRect(LPCSTR field, RECT value);
STDMETHODIMP SetUlonglong(LPCSTR field, ULONGLONG value);
STDMETHODIMP SetDouble(LPCSTR field, double value);
STDMETHODIMP SetString(LPCSTR field, LPWSTR value, int chars);
STDMETHODIMP SetBin(LPCSTR field, LPVOID value, int size);
virtual STDMETHODIMP OnSubOptionSet(LPCSTR field) { return E_NOTIMPL; }
private:
const SubRenderOption *options = nullptr;
void *context = nullptr;
};
#define DECLARE_ISUBRENDEROPTIONS \
STDMETHODIMP GetBool(LPCSTR field, bool *value) { return CSubRenderOptionsImpl::GetBool(field, value); } \
STDMETHODIMP GetInt(LPCSTR field, int *value) { return CSubRenderOptionsImpl::GetInt(field, value); } \
STDMETHODIMP GetSize(LPCSTR field, SIZE *value) { return CSubRenderOptionsImpl::GetSize(field, value); } \
STDMETHODIMP GetRect(LPCSTR field, RECT *value) { return CSubRenderOptionsImpl::GetRect(field, value); } \
STDMETHODIMP GetUlonglong(LPCSTR field, ULONGLONG *value) \
{ \
return CSubRenderOptionsImpl::GetUlonglong(field, value); \
} \
STDMETHODIMP GetDouble(LPCSTR field, double *value) { return CSubRenderOptionsImpl::GetDouble(field, value); } \
STDMETHODIMP GetString(LPCSTR field, LPWSTR *value, int *chars) \
{ \
return CSubRenderOptionsImpl::GetString(field, value, chars); \
} \
STDMETHODIMP GetBin(LPCSTR field, LPVOID *value, int *size) \
{ \
return CSubRenderOptionsImpl::GetBin(field, value, size); \
} \
\
STDMETHODIMP SetBool(LPCSTR field, bool value) { return CSubRenderOptionsImpl::SetBool(field, value); } \
STDMETHODIMP SetInt(LPCSTR field, int value) { return CSubRenderOptionsImpl::SetInt(field, value); } \
STDMETHODIMP SetSize(LPCSTR field, SIZE value) { return CSubRenderOptionsImpl::SetSize(field, value); } \
STDMETHODIMP SetRect(LPCSTR field, RECT value) { return CSubRenderOptionsImpl::SetRect(field, value); } \
STDMETHODIMP SetUlonglong(LPCSTR field, ULONGLONG value) \
{ \
return CSubRenderOptionsImpl::SetUlonglong(field, value); \
} \
STDMETHODIMP SetDouble(LPCSTR field, double value) { return CSubRenderOptionsImpl::SetDouble(field, value); } \
STDMETHODIMP SetString(LPCSTR field, LPWSTR value, int chars) \
{ \
return CSubRenderOptionsImpl::SetString(field, value, chars); \
} \
STDMETHODIMP SetBin(LPCSTR field, LPVOID value, int size) \
{ \
return CSubRenderOptionsImpl::SetBin(field, value, size); \
}
| 6,884
|
C++
|
.h
| 116
| 53.896552
| 116
| 0.50444
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,489
|
LAVSubtitleProvider.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/subtitles/LAVSubtitleProvider.h
|
/*
* Copyright (C) 2010-2021 Hendrik Leppkes
* http://www.1f0.de
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "SubRenderOptionsImpl.h"
#include "LAVSubtitleFrame.h"
class CLAVVideo;
typedef struct LAVSubtitleProviderContext
{
LPWSTR name; ///< name of the Provider
LPWSTR version; ///< Version of the Provider
LPWSTR yuvMatrix; ///< YUV Matrix
LPWSTR outputLevels; ///< RGB output levels
LPWSTR primaries; ///< Color Primaries
bool combineBitmaps; ///< Control if the provider combines all bitmaps into one
bool isBitmap;
bool isMovable;
} LAVSubtitleProviderContext;
struct _AM_PROPERTY_SPPAL;
struct _AM_PROPERTY_SPHLI;
class CLAVSubtitleProviderControlThread
: public CAMThread
, protected CCritSec
{
public:
CLAVSubtitleProviderControlThread();
~CLAVSubtitleProviderControlThread();
void SetConsumer2(ISubRenderConsumer2 *pConsumer2);
protected:
DWORD ThreadProc();
private:
ISubRenderConsumer2 *m_pConsumer2 = nullptr;
};
class CLAVSubtitleProvider
: public ISubRenderProvider
, public CSubRenderOptionsImpl
, public CUnknown
, private CCritSec
{
public:
CLAVSubtitleProvider(CLAVVideo *pLAVVideo, ISubRenderConsumer *pConsumer);
~CLAVSubtitleProvider(void);
DECLARE_IUNKNOWN;
DECLARE_ISUBRENDEROPTIONS;
// ISubRenderProvider
STDMETHODIMP RequestFrame(REFERENCE_TIME start, REFERENCE_TIME stop, LPVOID context);
STDMETHODIMP Disconnect(void);
// CLAVSubtitleProvider public
STDMETHODIMP SetConsumer(ISubRenderConsumer *pConsumer);
STDMETHODIMP DisconnectConsumer(void);
STDMETHODIMP InitDecoder(const CMediaType *pmt, AVCodecID codecId);
STDMETHODIMP Decode(BYTE *buf, int buflen, REFERENCE_TIME rtStart, REFERENCE_TIME rtStop);
STDMETHODIMP Flush();
STDMETHODIMP SetDVDPalette(struct _AM_PROPERTY_SPPAL *pPal);
STDMETHODIMP SetDVDHLI(struct _AM_PROPERTY_SPHLI *pHLI);
STDMETHODIMP SetDVDComposit(BOOL bComposit);
private:
void CloseDecoder();
void ProcessSubtitleFrame(AVSubtitle *sub, REFERENCE_TIME rtStart);
void ProcessSubtitleRect(AVSubtitleRect *rect, REFERENCE_TIME rtStart, REFERENCE_TIME rtStop);
void AddSubtitleRect(CLAVSubRect *rect);
CLAVSubRect *ProcessDVDHLI(CLAVSubRect *rect);
void ClearSubtitleRects();
void TimeoutSubtitleRects(REFERENCE_TIME rtStop);
enum
{
CNTRL_EXIT,
CNTRL_FLUSH
};
HRESULT ControlCmd(DWORD cmd) { return m_ControlThread->CallWorker(cmd); }
private:
friend class CLAVSubtitleProviderControlThread;
LAVSubtitleProviderContext context;
CLAVVideo *m_pLAVVideo = nullptr;
ISubRenderConsumer *m_pConsumer = nullptr;
ISubRenderConsumer2 *m_pConsumer2 = nullptr;
const AVCodec *m_pAVCodec = nullptr;
AVCodecContext *m_pAVCtx = nullptr;
AVCodecParserContext *m_pParser = nullptr;
REFERENCE_TIME m_rtLastFrame = AV_NOPTS_VALUE;
REFERENCE_TIME m_rtStartCache = AV_NOPTS_VALUE;
ULONGLONG m_SubPicId = 0;
BOOL m_bComposit = TRUE;
AVPacket *m_pSubtitlePacket = nullptr;
std::list<CLAVSubRect *> m_SubFrames;
struct _AM_PROPERTY_SPHLI *m_pHLI = nullptr;
CLAVSubtitleProviderControlThread *m_ControlThread = nullptr;
};
| 3,984
|
C++
|
.h
| 103
| 34.572816
| 98
| 0.756617
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,490
|
wmv9mft.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/decoders/wmv9mft.h
|
/*
* Copyright (C) 2010-2021 Hendrik Leppkes
* http://www.1f0.de
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "DecBase.h"
#include <mfidl.h>
#include <vector>
#include <queue>
////////////////////////////////////////////////////////////////////////////////
// Dynlink types
////////////////////////////////////////////////////////////////////////////////
typedef HRESULT STDAPICALLTYPE tMFStartup(ULONG Version, DWORD dwFlags);
typedef HRESULT STDAPICALLTYPE tMFShutdown();
typedef HRESULT STDAPICALLTYPE tMFCreateMediaType(IMFMediaType **ppMFType);
typedef HRESULT STDAPICALLTYPE tMFCreateSample(IMFSample **ppIMFSample);
typedef HRESULT STDAPICALLTYPE tMFCreateAlignedMemoryBuffer(DWORD cbMaxLength, DWORD cbAligment,
IMFMediaBuffer **ppBuffer);
typedef HRESULT STDAPICALLTYPE tMFAverageTimePerFrameToFrameRate(UINT64 unAverageTimePerFrame, UINT32 *punNumerator,
UINT32 *punDenominator);
#define MFMETHOD(name) tMF##name *##name
////////////////////////////////////////////////////////////////////////////////
// Class
////////////////////////////////////////////////////////////////////////////////
class CVC1HeaderParser;
class CDecWMV9MFT : public CDecBase
{
typedef struct _Buffer
{
IMFMediaBuffer *pBuffer = nullptr;
DWORD size = 0;
bool used = false;
} Buffer;
public:
CDecWMV9MFT(void);
virtual ~CDecWMV9MFT(void);
// ILAVDecoder
STDMETHODIMP InitDecoder(AVCodecID codec, const CMediaType *pmt);
STDMETHODIMP Decode(const BYTE *buffer, int buflen, REFERENCE_TIME rtStart, REFERENCE_TIME rtStop, BOOL bSyncPoint,
BOOL bDiscontinuity, IMediaSample *pSample);
STDMETHODIMP Flush();
STDMETHODIMP EndOfStream();
STDMETHODIMP GetPixelFormat(LAVPixelFormat *pPix, int *pBpp);
STDMETHODIMP_(BOOL) IsInterlaced(BOOL bAllowGuess);
STDMETHODIMP_(const WCHAR *) GetDecoderName() { return L"wmv9 mft"; }
STDMETHODIMP HasThreadSafeBuffers() { return S_OK; }
// CDecBase
STDMETHODIMP Init();
private:
STDMETHODIMP DestroyDecoder(bool bFull);
STDMETHODIMP ProcessOutput();
STDMETHODIMP SelectOutputType();
IMFMediaBuffer *CreateMediaBuffer(const BYTE *pData, DWORD dwDataLen);
static void wmv9_buffer_destruct(LAVFrame *pFrame);
IMFMediaBuffer *GetBuffer(DWORD dwRequiredSize);
void ReleaseBuffer(IMFMediaBuffer *pBuffer);
private:
IMFTransform *m_pMFT = nullptr;
BOOL m_bInterlaced = TRUE;
LAVPixelFormat m_OutPixFmt = LAVPixFmt_None;
AVCodecID m_nCodecId = AV_CODEC_ID_NONE;
CCritSec m_BufferCritSec;
std::vector<Buffer *> m_BufferQueue;
BOOL m_bNeedKeyFrame = TRUE;
BOOL m_bManualReorder = FALSE;
BOOL m_bReorderBufferValid = FALSE;
REFERENCE_TIME m_rtReorderBuffer = AV_NOPTS_VALUE;
std::queue<REFERENCE_TIME> m_timestampQueue;
CVC1HeaderParser *m_vc1Header = nullptr;
struct
{
HMODULE mfplat = NULL;
MFMETHOD(Startup);
MFMETHOD(Shutdown);
MFMETHOD(CreateAlignedMemoryBuffer);
MFMETHOD(CreateSample);
MFMETHOD(CreateMediaType);
MFMETHOD(AverageTimePerFrameToFrameRate);
} MF;
};
| 4,011
|
C++
|
.h
| 94
| 37.117021
| 119
| 0.661957
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,491
|
msdk_mvc.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/decoders/msdk_mvc.h
|
/*
* Copyright (C) 2010-2021 Hendrik Leppkes
* http://www.1f0.de
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "DecBase.h"
#include "IMediaSideData.h"
#include "mfxvideo.h"
#include "mfxmvc.h"
#include <deque>
#include <vector>
#define ASYNC_DEPTH 8
#define ASYNC_QUEUE_SIZE (ASYNC_DEPTH + 2)
// 10s timestamp offset to avoid negative timestamps
#define TIMESTAMP_OFFSET 100000000i64
#define MFX_IMPL_VIA_MASK 0x0F00
typedef struct _MVCBuffer
{
mfxFrameSurface1 surface = {0};
bool queued = false;
mfxSyncPoint sync = nullptr;
} MVCBuffer;
typedef struct _MVCGOP
{
std::deque<mfxU64> timestamps;
std::deque<MediaSideData3DOffset> offsets;
} MVCGOP;
class CDecMSDKMVC : public CDecBase
{
public:
CDecMSDKMVC();
virtual ~CDecMSDKMVC();
// ILAVDecoder
STDMETHODIMP InitDecoder(AVCodecID codec, const CMediaType *pmt);
STDMETHODIMP Decode(const BYTE *buffer, int buflen, REFERENCE_TIME rtStart, REFERENCE_TIME rtStop, BOOL bSyncPoint,
BOOL bDiscontinuity, IMediaSample *pSample);
STDMETHODIMP Flush();
STDMETHODIMP EndOfStream();
STDMETHODIMP GetPixelFormat(LAVPixelFormat *pPix, int *pBpp)
{
if (pPix)
*pPix = LAVPixFmt_NV12;
if (pBpp)
*pBpp = 8;
return S_OK;
}
STDMETHODIMP_(BOOL) IsInterlaced(BOOL bAllowGuess) { return FALSE; }
STDMETHODIMP_(const WCHAR *) GetDecoderName()
{
return (m_mfxImpl != MFX_IMPL_SOFTWARE) ? L"msdk mvc hw" : L"msdk mvc";
}
STDMETHODIMP HasThreadSafeBuffers() { return S_OK; }
// CDecBase
STDMETHODIMP Init();
private:
void DestroyDecoder(bool bFull);
STDMETHODIMP AllocateMVCExtBuffers();
MVCBuffer *GetBuffer();
MVCBuffer *FindBuffer(mfxFrameSurface1 *pSurface);
void ReleaseBuffer(mfxFrameSurface1 *pSurface);
HRESULT HandleOutput(MVCBuffer *pOutputBuffer);
HRESULT DeliverOutput(MVCBuffer *pBaseView, MVCBuffer *pExtraView);
HRESULT ParseSEI(const BYTE *buffer, size_t size, mfxU64 timestamp);
HRESULT ParseMVCNestedSEI(const BYTE *buffer, size_t size, mfxU64 timestamp);
HRESULT ParseUnregUserDataSEI(const BYTE *buffer, size_t size, mfxU64 timestamp);
HRESULT ParseOffsetMetadata(const BYTE *buffer, size_t size, mfxU64 timestamp);
void AddFrameToGOP(mfxU64 timestamp);
BOOL RemoveFrameFromGOP(MVCGOP *pGOP, mfxU64 timestamp);
void GetOffsetSideData(LAVFrame *pFrame, mfxU64 timestamp);
static void msdk_buffer_destruct(LAVFrame *pFrame);
private:
mfxSession m_mfxSession = nullptr;
mfxVersion m_mfxVersion = {0};
mfxIMPL m_mfxImpl = 0;
BOOL m_bDecodeReady = FALSE;
mfxVideoParam m_mfxVideoParams = {0};
mfxExtBuffer *m_mfxExtParam[1] = {0};
mfxExtMVCSeqDesc m_mfxExtMVCSeq = {0};
CCritSec m_BufferCritSec;
std::vector<MVCBuffer *> m_BufferQueue;
GrowableArray<BYTE> m_buff;
int m_nMP4NALUSize = 0;
MVCBuffer *m_pOutputQueue[ASYNC_QUEUE_SIZE] = {0};
int m_nOutputQueuePosition = 0;
std::deque<MVCGOP> m_GOPs;
MediaSideData3DOffset m_PrevOffset;
};
| 3,821
|
C++
|
.h
| 101
| 33.514851
| 119
| 0.727002
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,492
|
d3d11va.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/decoders/d3d11va.h
|
/*
* Copyright (C) 2017-2021 Hendrik Leppkes
* http://www.1f0.de
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "DecBase.h"
#include "avcodec.h"
#include <d3d11.h>
#include <dxgi.h>
#include "d3d11/D3D11SurfaceAllocator.h"
extern "C"
{
#include "libavutil/hwcontext.h"
#include "libavutil/hwcontext_d3d11va.h"
#include "libavcodec/d3d11va.h"
}
#define D3D11_QUEUE_SURFACES 4
typedef HRESULT(WINAPI *PFN_CREATE_DXGI_FACTORY1)(REFIID riid, void **ppFactory);
class CDecD3D11 : public CDecAvcodec
{
public:
CDecD3D11(void);
virtual ~CDecD3D11(void);
// ILAVDecoder
STDMETHODIMP Check();
STDMETHODIMP InitDecoder(AVCodecID codec, const CMediaType *pmt);
STDMETHODIMP GetPixelFormat(LAVPixelFormat *pPix, int *pBpp);
STDMETHODIMP Flush();
STDMETHODIMP EndOfStream();
STDMETHODIMP InitAllocator(IMemAllocator **ppAlloc);
STDMETHODIMP PostConnect(IPin *pPin);
STDMETHODIMP BreakConnect();
STDMETHODIMP_(long) GetBufferCount(long *pMaxBuffers = nullptr);
STDMETHODIMP_(const WCHAR *) GetDecoderName()
{
return m_bReadBackFallback ? (m_bDirect ? L"d3d11 cb direct" : L"d3d11 cb") : L"d3d11 native";
}
STDMETHODIMP HasThreadSafeBuffers() { return S_FALSE; }
STDMETHODIMP SetDirectOutput(BOOL bDirect)
{
m_bDirect = bDirect;
return S_OK;
}
STDMETHODIMP_(DWORD) GetHWAccelNumDevices();
STDMETHODIMP GetHWAccelDeviceInfo(DWORD dwIndex, BSTR *pstrDeviceName, DWORD *dwDeviceIdentifier);
STDMETHODIMP GetHWAccelActiveDevice(BSTR *pstrDeviceName);
// CDecBase
STDMETHODIMP Init();
protected:
HRESULT AdditionaDecoderInit();
HRESULT PostDecode();
HRESULT HandleDXVA2Frame(LAVFrame *pFrame);
HRESULT DeliverD3D11Frame(LAVFrame *pFrame);
HRESULT DeliverD3D11Readback(LAVFrame *pFrame);
HRESULT DeliverD3D11ReadbackDirect(LAVFrame *pFrame);
BOOL IsHardwareAccelerator() { return TRUE; }
private:
STDMETHODIMP DestroyDecoder(bool bFull);
STDMETHODIMP ReInitD3D11Decoder(AVCodecContext *c);
STDMETHODIMP CreateD3D11Device(UINT nDeviceIndex, ID3D11Device **ppDevice, DXGI_ADAPTER_DESC *pDesc);
STDMETHODIMP CreateD3D11Decoder();
STDMETHODIMP AllocateFramesContext(int width, int height, AVPixelFormat format, int nSurfaces,
AVBufferRef **pFramesCtx);
STDMETHODIMP FindVideoServiceConversion(AVCodecID codec, int profile, DXGI_FORMAT surface_format, GUID *input);
STDMETHODIMP FindDecoderConfiguration(const D3D11_VIDEO_DECODER_DESC *desc, D3D11_VIDEO_DECODER_CONFIG *pConfig);
STDMETHODIMP FillHWContext(AVD3D11VAContext *ctx);
STDMETHODIMP FlushDisplayQueue(BOOL bDeliver);
static enum AVPixelFormat get_d3d11_format(struct AVCodecContext *s, const enum AVPixelFormat *pix_fmts);
static int get_d3d11_buffer(struct AVCodecContext *c, AVFrame *pic, int flags);
private:
CD3D11SurfaceAllocator *m_pAllocator = nullptr;
AVBufferRef *m_pDevCtx = nullptr;
AVBufferRef *m_pFramesCtx = nullptr;
D3D11_VIDEO_DECODER_CONFIG m_DecoderConfig;
ID3D11VideoDecoder *m_pDecoder = nullptr;
int m_nOutputViews = 0;
ID3D11VideoDecoderOutputView **m_pOutputViews = nullptr;
DWORD m_dwSurfaceWidth = 0;
DWORD m_dwSurfaceHeight = 0;
DWORD m_dwSurfaceCount = 0;
DXGI_FORMAT m_SurfaceFormat = DXGI_FORMAT_UNKNOWN;
BOOL m_bReadBackFallback = FALSE;
BOOL m_bDirect = FALSE;
BOOL m_bFailHWDecode = FALSE;
ID3D11Texture2D *m_pD3D11StagingTexture = nullptr;
LAVFrame *m_FrameQueue[D3D11_QUEUE_SURFACES];
int m_FrameQueuePosition = 0;
int m_DisplayDelay = D3D11_QUEUE_SURFACES;
struct
{
HMODULE d3d11lib;
PFN_D3D11_CREATE_DEVICE mD3D11CreateDevice;
HMODULE dxgilib;
PFN_CREATE_DXGI_FACTORY1 mCreateDXGIFactory1;
} dx = {0};
DXGI_ADAPTER_DESC m_AdapterDesc = {0};
friend class CD3D11SurfaceAllocator;
};
| 4,669
|
C++
|
.h
| 112
| 37.008929
| 117
| 0.744972
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,493
|
dxva2dec.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/decoders/dxva2dec.h
|
/*
* Copyright (C) 2011-2021 Hendrik Leppkes
* http://www.1f0.de
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "DecBase.h"
#include "avcodec.h"
#include "libavcodec/dxva2.h"
#define DXVA2_MAX_SURFACES 64
#define DXVA2_QUEUE_SURFACES 4
typedef HRESULT WINAPI pDirect3DCreate9Ex(UINT, IDirect3D9Ex **);
typedef HRESULT WINAPI pCreateDeviceManager9(UINT *pResetToken, IDirect3DDeviceManager9 **);
typedef struct
{
int index;
bool used;
LPDIRECT3DSURFACE9 d3d;
uint64_t age;
} d3d_surface_t;
class CDXVA2SurfaceAllocator;
class CDecDXVA2 : public CDecAvcodec
{
public:
CDecDXVA2(void);
virtual ~CDecDXVA2(void);
// ILAVDecoder
STDMETHODIMP InitDecoder(AVCodecID codec, const CMediaType *pmt);
STDMETHODIMP GetPixelFormat(LAVPixelFormat *pPix, int *pBpp);
STDMETHODIMP Flush();
STDMETHODIMP EndOfStream();
STDMETHODIMP InitAllocator(IMemAllocator **ppAlloc);
STDMETHODIMP PostConnect(IPin *pPin);
STDMETHODIMP_(long) GetBufferCount(long *pMaxBuffers = nullptr);
STDMETHODIMP_(const WCHAR *) GetDecoderName()
{
return m_bNative ? L"dxva2n" : (m_bDirect ? L"dxva2cb direct" : L"dxva2cb");
}
STDMETHODIMP HasThreadSafeBuffers() { return m_bNative ? S_FALSE : S_OK; }
STDMETHODIMP SetDirectOutput(BOOL bDirect)
{
m_bDirect = bDirect;
return S_OK;
}
STDMETHODIMP_(DWORD) GetHWAccelNumDevices();
STDMETHODIMP GetHWAccelDeviceInfo(DWORD dwIndex, BSTR *pstrDeviceName, DWORD *dwDeviceIdentifier);
STDMETHODIMP GetHWAccelActiveDevice(BSTR *pstrDeviceName);
// CDecBase
STDMETHODIMP Init();
HRESULT SetNativeMode(BOOL bNative)
{
m_bNative = bNative;
return S_OK;
}
protected:
HRESULT AdditionaDecoderInit();
HRESULT PostDecode();
HRESULT HandleDXVA2Frame(LAVFrame *pFrame);
HRESULT DeliverDXVA2Frame(LAVFrame *pFrame);
BOOL IsHardwareAccelerator() { return TRUE; }
bool CopyFrame(LAVFrame *pFrame);
bool DeliverDirect(LAVFrame *pFrame);
private:
HRESULT InitD3D(UINT lAdapter);
HRESULT InitD3DEx(UINT lAdapter);
HRESULT InitD3DAdapterIdentifier(UINT lAdapter);
STDMETHODIMP DestroyDecoder(bool bFull, bool bNoAVCodec = false);
STDMETHODIMP FreeD3DResources();
STDMETHODIMP LoadDXVA2Functions();
HRESULT CreateD3DDeviceManager(IDirect3DDevice9 *pDevice, UINT *pReset, IDirect3DDeviceManager9 **ppManager);
HRESULT CreateDXVAVideoService(IDirect3DDeviceManager9 *pManager, IDirectXVideoDecoderService **ppService);
HRESULT FindVideoServiceConversion(AVCodecID codec, int profile, D3DFORMAT suggestedOutput, GUID *input,
D3DFORMAT *output);
HRESULT FindDecoderConfiguration(const GUID &input, const DXVA2_VideoDesc *pDesc,
DXVA2_ConfigPictureDecode *pConfig);
HRESULT CreateDXVA2Decoder(int nSurfaces = 0, IDirect3DSurface9 **ppSurfaces = nullptr);
HRESULT SetD3DDeviceManager(IDirect3DDeviceManager9 *pDevManager);
HRESULT DXVA2NotifyEVR();
HRESULT RetrieveVendorId(IDirect3DDeviceManager9 *pDevManager);
HRESULT CheckHWCompatConditions(GUID decoderGuid);
HRESULT FillHWContext(dxva_context *ctx);
HRESULT ReInitDXVA2Decoder(AVCodecContext *c);
static enum AVPixelFormat get_dxva2_format(struct AVCodecContext *s, const enum AVPixelFormat *pix_fmts);
static int get_dxva2_buffer(struct AVCodecContext *c, AVFrame *pic, int flags);
static void free_dxva2_buffer(void *opaque, uint8_t *data);
STDMETHODIMP FlushDisplayQueue(BOOL bDeliver);
STDMETHODIMP FlushFromAllocator();
private:
friend class CDXVA2SurfaceAllocator;
BOOL m_bNative = FALSE;
BOOL m_bDirect = FALSE;
CDXVA2SurfaceAllocator *m_pDXVA2Allocator = nullptr;
struct
{
HMODULE d3dlib;
pDirect3DCreate9Ex *direct3DCreate9Ex;
HMODULE dxva2lib;
pCreateDeviceManager9 *createDeviceManager;
} dx;
IDirect3D9 *m_pD3D = nullptr;
IDirect3DDevice9 *m_pD3DDev = nullptr;
IDirect3DDeviceManager9 *m_pD3DDevMngr = nullptr;
UINT m_pD3DResetToken = 0;
HANDLE m_hDevice = INVALID_HANDLE_VALUE;
IDirectXVideoDecoderService *m_pDXVADecoderService = nullptr;
IDirectXVideoDecoder *m_pDecoder = nullptr;
DXVA2_ConfigPictureDecode m_DXVAVideoDecoderConfig;
int m_NumSurfaces = 0;
d3d_surface_t m_pSurfaces[DXVA2_MAX_SURFACES];
uint64_t m_CurrentSurfaceAge = 1;
LPDIRECT3DSURFACE9 m_pRawSurface[DXVA2_MAX_SURFACES];
BOOL m_bFailHWDecode = FALSE;
LAVFrame *m_FrameQueue[DXVA2_QUEUE_SURFACES];
int m_FrameQueuePosition = 0;
AVPixelFormat m_DecoderPixelFormat = AV_PIX_FMT_NONE;
DWORD m_dwSurfaceWidth = 0;
DWORD m_dwSurfaceHeight = 0;
D3DFORMAT m_eSurfaceFormat = D3DFMT_UNKNOWN;
DWORD m_dwVendorId = 0;
DWORD m_dwDeviceId = 0;
char m_cDeviceName[512] = {0};
GUID m_guidDecoderDevice = GUID_NULL;
int m_DisplayDelay = DXVA2_QUEUE_SURFACES;
CMediaType m_MediaType;
};
| 5,755
|
C++
|
.h
| 138
| 36.630435
| 113
| 0.743021
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,494
|
quicksync.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/decoders/quicksync.h
|
/*
* Copyright (C) 2010-2021 Hendrik Leppkes
* http://www.1f0.de
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "DecBase.h"
#include "IQuickSyncDecoder.h"
typedef IQuickSyncDecoder *__stdcall pcreateQuickSync();
typedef void __stdcall pdestroyQuickSync(IQuickSyncDecoder *);
typedef DWORD __stdcall pcheck();
#include <queue>
class CDecQuickSync : public CDecBase
{
public:
CDecQuickSync(void);
virtual ~CDecQuickSync(void);
// ILAVDecoder
STDMETHODIMP Check();
STDMETHODIMP InitDecoder(AVCodecID codec, const CMediaType *pmt);
STDMETHODIMP Decode(const BYTE *buffer, int buflen, REFERENCE_TIME rtStart, REFERENCE_TIME rtStop, BOOL bSyncPoint,
BOOL bDiscontinuity, IMediaSample *pSample);
STDMETHODIMP Flush();
STDMETHODIMP EndOfStream();
STDMETHODIMP GetPixelFormat(LAVPixelFormat *pPix, int *pBpp);
STDMETHODIMP_(REFERENCE_TIME) GetFrameDuration();
STDMETHODIMP_(BOOL) IsInterlaced(BOOL bAllowGuess);
STDMETHODIMP_(const WCHAR *) GetDecoderName() { return L"quicksync"; }
STDMETHODIMP PostConnect(IPin *pPin);
STDMETHODIMP GetHWAccelActiveDevice(BSTR *pstrDeviceName)
{
CheckPointer(pstrDeviceName, E_POINTER);
*pstrDeviceName = SysAllocString(L"Intel\xae QuickSync");
if (!*pstrDeviceName)
return E_OUTOFMEMORY;
return S_OK;
}
// CDecBase
STDMETHODIMP Init();
private:
STDMETHODIMP DestroyDecoder(bool bFull);
static HRESULT QS_DeliverSurfaceCallback(void *obj, QsFrameData *data);
STDMETHODIMP HandleFrame(QsFrameData *data);
STDMETHODIMP CheckH264Sequence(const BYTE *buffer, size_t buflen, int nal_size, int *pRefFrames = nullptr,
int *pProfile = nullptr, int *pLevel = nullptr);
private:
struct
{
HMODULE quickSyncLib;
pcreateQuickSync *create;
pdestroyQuickSync *destroy;
pcheck *check;
} qs;
IQuickSyncDecoder *m_pDecoder = nullptr;
BOOL m_bNeedSequenceCheck = FALSE;
BOOL m_bInterlaced = TRUE;
BOOL m_bDI = FALSE;
BOOL m_bAVC1 = FALSE;
int m_nAVCNalSize = 0;
BOOL m_bEndOfSequence = FALSE;
BOOL m_bUseTimestampQueue;
std::queue<REFERENCE_TIME> m_timestampQueue;
DXVA2_ExtendedFormat m_DXVAExtendedFormat;
FOURCC m_Codec = 0;
IDirect3DDeviceManager9 *m_pD3DDevMngr = nullptr;
};
| 3,119
|
C++
|
.h
| 79
| 34.35443
| 119
| 0.719868
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,495
|
ILAVDecoder.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/decoders/ILAVDecoder.h
|
/*
* Copyright (C) 2010-2021 Hendrik Leppkes
* http://www.1f0.de
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "LAVVideoSettings.h"
#include "ILAVPinInfo.h"
/**
* List of internally used pixel formats
*
* Note for high bit-depth formats:
* All bX (9-16 bit) formats always use 2 bytes, are little-endian, and the values are right-aligned.
* That means that there are leading zero-bits, and not trailing like in DirectShow
* The actual number of valid bits is stored in the LAVFrame
*/
// clang-format off
typedef enum LAVPixelFormat {
LAVPixFmt_None = -1,
/* planar YUV */
LAVPixFmt_YUV420, ///< YUV 4:2:0, 8 bit
LAVPixFmt_YUV420bX, ///< YUV 4:2:0, 9-16 bit
LAVPixFmt_YUV422, ///< YUV 4:2:2, 8 bit
LAVPixFmt_YUV422bX, ///< YUV 4:2:2, 9-16 bit
LAVPixFmt_YUV444, ///< YUV 4:4:4, 8 bit
LAVPixFmt_YUV444bX, ///< YUV 4:4:4, 9-16 bit
/* packed/half-packed YUV */
LAVPixFmt_NV12, ///< YUV 4:2:0, U/V interleaved
LAVPixFmt_YUY2, ///< YUV 4:2:2, packed, YUYV order
LAVPixFmt_P016, ///< YUV 4:2:0, 10 to 16-bit, U/V interleaved, MSB aligned
/* RGB */
LAVPixFmt_RGB24, ///< RGB24, in BGR order
LAVPixFmt_RGB32, ///< RGB32, in BGRA order (A is invalid and should be 0xFF)
LAVPixFmt_ARGB32, ///< ARGB32, in BGRA order
LAVPixFmt_RGB48, ///< RGB48, in RGB order (16-bit per pixel)
LAVPixFmt_DXVA2, ///< DXVA2 Surface
LAVPixFmt_D3D11, ///< D3D11 Surface
LAVPixFmt_NB, ///< number of formats
} LAVPixelFormat;
// clang-format on
/**
* Structure describing a pixel format
*/
typedef struct LAVPixFmtDesc
{
int codedbytes; ///< coded byte per pixel in one plane (for packed and multibyte formats)
int planes; ///< number of planes
int planeWidth[4]; ///< log2 width factor
int planeHeight[4]; ///< log2 height factor
} LAVPixFmtDesc;
/**
* Get the Pixel Format Descriptor for the given format
*/
LAVPixFmtDesc getPixelFormatDesc(LAVPixelFormat pixFmt);
/**
* Map the LAV Pixel Format to a FFMpeg pixel format (for swscale, etc)
*/
AVPixelFormat getFFPixelFormatFromLAV(LAVPixelFormat pixFmt, int bpp);
typedef struct LAVDirectBuffer
{
BYTE *data[4]; ///< pointer to the picture planes
ptrdiff_t stride[4]; ///< stride of the planes (in bytes)
} LAVDirectBuffer;
typedef struct LAVFrameSideData
{
GUID guidType; ///< type of the side data
BYTE *data; ///< side data
size_t size; ///< size
} LAVFrameSideData;
/**
* A Video Frame
*
* Allocated by the decoder and passed through the processing chain.
*
* The Decoder should allocate frames by using ILAVVideoCallback::AllocateFrame()
* Frames need to be free'd with ILAVVideoCallback::ReleaseFrame()
*
* FIXME: Right now the avcodec decoder always reuses the buffers the next time its called!
* NYI: Some Post-Processing filters will require to hang on to frames longer then the normal delivery process.
* NYI: That means that the image buffers should not be re-used unless "destruct" released them.
*/
typedef struct LAVFrame
{
int width; ///< width of the frame (in pixel)
int height; ///< height of the frame (in pixel)
BYTE *data[4]; ///< pointer to the picture planes
BYTE *stereo[4]; ///< pointer to the second view picture planes
ptrdiff_t stride[4]; ///< stride of the planes (in bytes)
LAVPixelFormat format; ///< pixel format of the frame
int bpp; ///< bits per pixel, only meaningful for YUV420bX, YUV422bX or YUV444bX
REFERENCE_TIME rtStart; ///< start time of the frame. unset if AV_NOPTS_VALUE
REFERENCE_TIME rtStop; ///< stop time of the frame. unset if AV_NOPTS_VALUE
int repeat; ///< repeat frame flag, signals how much the frame should be delayed
AVRational aspect_ratio; ///< display aspect ratio (unset/invalid if either num or den is 0)
REFERENCE_TIME avgFrameDuration; ///< frame duration used for the media type to indicate fps (AV_NOPTS_VALUE or 0 =
///< use from input pin)
DXVA2_ExtendedFormat ext_format; ///< extended format flags (critical uses: indicate progressive/interlaced,
///< indicate limited/full range)
int key_frame; ///< frame is a key frame (field is not mandatory)
int interlaced; ///< frame is interlaced
int tff; ///< top field is first
char frame_type; ///< frame type char (I/P/B/?)
int flags; ///< frame flags
#define LAV_FRAME_FLAG_BUFFER_MODIFY 0x00000001
#define LAV_FRAME_FLAG_END_OF_SEQUENCE 0x00000002
#define LAV_FRAME_FLAG_FLUSH 0x00000004
#define LAV_FRAME_FLAG_REDRAW 0x00000008
#define LAV_FRAME_FLAG_DXVA_NOADDREF 0x00000010
#define LAV_FRAME_FLAG_MVC 0x00000020
LAVFrameSideData *side_data;
int side_data_count;
/* destruct function to free any buffers being held by this frame (may be null) */
void (*destruct)(struct LAVFrame *);
void *priv_data; ///< private data from the decoder (mostly for destruct)
bool direct;
bool (*direct_lock)(struct LAVFrame *, struct LAVDirectBuffer *);
void (*direct_unlock)(struct LAVFrame *);
} LAVFrame;
/**
* Allocate buffers for the LAVFrame "data" element to fit the pixfmt with the given stride
*
* This method also fills the stride argument in the LAVFrame properly.
* Its required that width/height and format are already set on the frame.
*
* @param pFrame Frame to fill
* @param stride stride to use (in pixel). If 0, a stride will be computed to fill usual alignment rules
* @return HRESULT
*/
HRESULT AllocLAVFrameBuffers(LAVFrame *pFrame, ptrdiff_t stride = 0);
/**
* Destruct a LAV Frame, freeing its data pointers
*/
HRESULT FreeLAVFrameBuffers(LAVFrame *pFrame);
/**
* Copy a LAV Frame, including a memcpy of the data
*/
HRESULT CopyLAVFrame(LAVFrame *pSrc, LAVFrame **ppDst);
/**
* Copy the buffers in the LAV Frame, calling destruct on the old buffers.
*
* Usually useful to release decoder-specific buffers, and move to memory buffers
*/
HRESULT CopyLAVFrameInPlace(LAVFrame *pFrame);
/**
* Add Side Data to the frame and return a pointer to it
*/
BYTE *AddLAVFrameSideData(LAVFrame *pFrame, GUID guidType, size_t size);
/**
* Get a side data entry from the frame by its type
*/
BYTE *GetLAVFrameSideData(LAVFrame *pFrame, GUID guidType, size_t *pSize);
typedef struct LAVPinInfo
{
DWORD flags; ///< Flags that describe the video content (see ILAVPinInfo.h for valid values)
AVPixelFormat pix_fmt; ///< The pixel format used
int has_b_frames;
} LAVPinInfo;
/**
* Interface into the LAV Video core for the decoder implementations
* This interface offers all required functions to properly communicate with the core
*/
interface ILAVVideoCallback
{
/**
* Allocate and initialize a new frame
*
* @param ppFrame variable to receive the frame
* @return HRESULT
*/
STDMETHOD(AllocateFrame)(LAVFrame * *ppFrame) PURE;
/**
* Destruct and release frame
* This function calls the "destruct" function on the frame, and releases it afterwards
*
* @param ppFrame variable of the frame, will be nulled
* @return HRESULT
*/
STDMETHOD(ReleaseFrame)(LAVFrame * *ppFrame) PURE;
/**
* Deliver the frame
* The decoder gives up control of the frame at this point, and hands it over to the processing chain
*
* @param pFrame frame to deliver
* @return HRESULT
*/
STDMETHOD(Deliver)(LAVFrame * pFrame) PURE;
/**
* Get the extension of the currently loaded file
*
* @result WCHAR string to the extension. Callers needs to free the memory with CoTaskMemFree
*/
STDMETHOD_(LPWSTR, GetFileExtension)() PURE;
/**
* Get Decode Flags
*
* @return flags
*/
STDMETHOD_(DWORD, GetDecodeFlags)() PURE;
#define LAV_VIDEO_DEC_FLAG_STREAMAR_BLACKLIST 0x00000001
#define LAV_VIDEO_DEC_FLAG_ONLY_DTS 0x00000002
#define LAV_VIDEO_DEC_FLAG_LAVSPLITTER 0x00000008
#define LAV_VIDEO_DEC_FLAG_DVD 0x00000010
#define LAV_VIDEO_DEC_FLAG_NO_MT 0x00000020
#define LAV_VIDEO_DEC_FLAG_SAGE_HACK 0x00000040
#define LAV_VIDEO_DEC_FLAG_LIVE 0x00000080
/**
* Get the input media type
*
* @result media type
*/
STDMETHOD_(CMediaType &, GetInputMediaType)() PURE;
/**
* Query the LAVPinInfo
*/
STDMETHOD(GetLAVPinInfo)(LAVPinInfo & info) PURE;
/**
* Get a reference to the output pin
*/
STDMETHOD_(CBasePin *, GetOutputPin)() PURE;
/**
* Get the output media type
*
* @result media type
*/
STDMETHOD_(CMediaType &, GetOutputMediaType)() PURE;
/**
* Strip the packet for DVD decoding
*/
STDMETHOD(DVDStripPacket)(BYTE * &p, long &len) PURE;
/**
* Get a Dummy frame used for flusing
*/
STDMETHOD_(LAVFrame *, GetFlushFrame)() PURE;
/**
* Ask the decoder to release all DXVA resources
*/
STDMETHOD(ReleaseAllDXVAResources)() PURE;
/**
* Get the index of the GPU device to be used for HW decoding, DWORD_MAX if not set
*/
STDMETHOD_(DWORD, GetGPUDeviceIndex)() PURE;
/**
* Check if the input is using a dynamic allocator
*/
STDMETHOD_(BOOL, HasDynamicInputAllocator)() PURE;
/**
* Set the x264 build info
*/
STDMETHOD(SetX264Build)(int nBuild) PURE;
/**
* Get the x264 build info
*/
STDMETHOD_(int, GetX264Build)() PURE;
};
/**
* Decoder interface
*
* Every decoder needs to implement this to interface with the LAV Video core
*/
interface ILAVDecoder
{
/**
* Virtual destructor
*/
virtual ~ILAVDecoder(void){};
/**
* Initialize interfaces with the LAV Video core
* This function should also be used to create all interfaces with external DLLs
*
* @param pSettings reference to the settings interface
* @param pCallback reference to the callback interface
* @return S_OK on success, error code if this decoder is lacking an external support dll
*/
STDMETHOD(InitInterfaces)(ILAVVideoSettings * pSettings, ILAVVideoCallback * pCallback) PURE;
/**
* Check if the decoder is functional
*/
STDMETHOD(Check)() PURE;
/**
* Initialize the codec to decode a stream specified by codec and pmt.
*
* @param codec Codec Id
* @param pmt DirectShow Media Type
* @return S_OK on success, an error code otherwise
*/
STDMETHOD(InitDecoder)(AVCodecID codec, const CMediaType *pmt) PURE;
/**
* Decode a frame.
*
* @param pSample Media Sample to decode
* @return S_OK if decoding was successful, S_FALSE if no frame could be extracted, an error code if the decoder is
* not compatible with the bitstream
*
* Note: When returning an actual error code, the filter will switch to the fallback software decoder! This should
* only be used for catastrophic failures, like trying to decode a unsupported format on a hardware decoder.
*/
STDMETHOD(Decode)(IMediaSample * pSample) PURE;
/**
* Flush the decoder after a seek.
* The decoder should discard any remaining data.
*
* @return unused
*/
STDMETHOD(Flush)() PURE;
/**
* End of Stream
* The decoder is asked to output any buffered frames for immediate delivery
*
* @return unused
*/
STDMETHOD(EndOfStream)() PURE;
/**
* Query the decoder for the current pixel format
* Mostly used by the media type creation logic before playback starts
*
* @return the pixel format used in the decoding process
*/
STDMETHOD(GetPixelFormat)(LAVPixelFormat * pPix, int *pBpp) PURE;
/**
* Get the frame duration.
*
* This function is not mandatory, and if you cannot provide any specific duration, return 0.
*/
STDMETHOD_(REFERENCE_TIME, GetFrameDuration)() PURE;
/**
* Query whether the format can potentially be interlaced.
* This function should return false if the format can 100% not be interlaced, and true if it can be interlaced (but
* also progressive).
*/
STDMETHOD_(BOOL, IsInterlaced)(BOOL bAllowGuess) PURE;
/**
* Allows the decoder to handle an allocator.
* Used by DXVA2 decoding
*/
STDMETHOD(InitAllocator)(IMemAllocator * *ppAlloc) PURE;
/**
* Function called after connection is established, with the pin as argument
*/
STDMETHOD(PostConnect)(IPin * pPin) PURE;
/**
* Notify the decoder the output connection was broken
*/
STDMETHOD(BreakConnect)() PURE;
/**
* Get the number of sample buffers optimal for this decoder
*/
STDMETHOD_(long, GetBufferCount)(long *pMaxBuffers = nullptr) PURE;
/**
* Get the name of the decoder
*/
STDMETHOD_(const WCHAR *, GetDecoderName)() PURE;
/**
* Get whether the decoder outputs thread-safe buffers
*/
STDMETHOD(HasThreadSafeBuffers)() PURE;
/**
* Toggle direct frame output mode for hardware decoders
*/
STDMETHOD(SetDirectOutput)(BOOL bDirect) PURE;
/**
* Get the number of available hw accel devices
*/
STDMETHOD_(DWORD, GetHWAccelNumDevices)() PURE;
/**
* Get information about a hwaccel device
*/
STDMETHOD(GetHWAccelDeviceInfo)(DWORD dwIndex, BSTR * pstrDeviceName, DWORD * dwDeviceIdentifier) PURE;
/**
* Get the description of the currently active hwaccel device
*/
STDMETHOD(GetHWAccelActiveDevice)(BSTR * pstrDeviceName) PURE;
};
/**
* Decoder creation functions
*
* They are listed here so that including their header files is not required
*/
ILAVDecoder *CreateDecoderAVCodec();
ILAVDecoder *CreateDecoderWMV9MFT();
ILAVDecoder *CreateDecoderCUVID();
ILAVDecoder *CreateDecoderQuickSync();
ILAVDecoder *CreateDecoderDXVA2();
ILAVDecoder *CreateDecoderDXVA2Native();
ILAVDecoder *CreateDecoderD3D11();
ILAVDecoder *CreateDecoderMSDKMVC();
HRESULT VerifyD3D9Device(DWORD &dwIndex, DWORD dwDeviceId);
HRESULT VerifyD3D11Device(DWORD &dwIndex, DWORD dwDeviceId);
| 15,005
|
C++
|
.h
| 400
| 33.16
| 120
| 0.688566
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,498
|
cuvid.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/decoders/cuvid.h
|
/*
* Copyright (C) 2010-2021 Hendrik Leppkes
* http://www.1f0.de
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "DecBase.h"
#define MAX_DECODE_FRAMES 20
#define DISPLAY_DELAY 4
#define MAX_PIC_INDEX 64
#include "cuvid/dynlink_cuda.h"
#include "cuvid/dynlink_nvcuvid.h"
#define CUDA_INIT_D3D9
#include "cuvid/dynlink_cuda_d3d.h"
#include "parsers/AnnexBConverter.h"
#include <queue>
#define CUMETHOD(name) t##name *##name
class CDecCuvid : public CDecBase
{
public:
CDecCuvid(void);
virtual ~CDecCuvid(void);
// ILAVDecoder
STDMETHODIMP InitDecoder(AVCodecID codec, const CMediaType *pmt);
STDMETHODIMP Decode(const BYTE *buffer, int buflen, REFERENCE_TIME rtStart, REFERENCE_TIME rtStop, BOOL bSyncPoint,
BOOL bDiscontinuity, IMediaSample *pSample);
STDMETHODIMP Flush();
STDMETHODIMP EndOfStream();
STDMETHODIMP GetPixelFormat(LAVPixelFormat *pPix, int *pBpp);
STDMETHODIMP_(REFERENCE_TIME) GetFrameDuration();
STDMETHODIMP_(BOOL) IsInterlaced(BOOL bAllowGuess);
STDMETHODIMP_(const WCHAR *) GetDecoderName() { return L"cuvid"; }
STDMETHODIMP GetHWAccelActiveDevice(BSTR *pstrDeviceName);
// CDecBase
STDMETHODIMP Init();
private:
STDMETHODIMP LoadCUDAFuncRefs();
STDMETHODIMP DestroyDecoder(bool bFull);
STDMETHODIMP InitD3D9(int best_device, DWORD requested_device);
STDMETHODIMP CreateCUVIDDecoder(cudaVideoCodec codec, DWORD dwWidth, DWORD dwHeight, int nBitdepth,
bool bProgressiveSequence);
STDMETHODIMP DecodeSequenceData();
// CUDA Callbacks
static int CUDAAPI HandleVideoSequence(void *obj, CUVIDEOFORMAT *cuvidfmt);
static int CUDAAPI HandlePictureDecode(void *obj, CUVIDPICPARAMS *cuvidpic);
static int CUDAAPI HandlePictureDisplay(void *obj, CUVIDPARSERDISPINFO *cuviddisp);
STDMETHODIMP Display(CUVIDPARSERDISPINFO *cuviddisp);
STDMETHODIMP Deliver(CUVIDPARSERDISPINFO *cuviddisp, int field = 0);
CUVIDPARSERDISPINFO *GetNextFrame();
STDMETHODIMP FlushParser();
STDMETHODIMP CheckH264Sequence(const BYTE *buffer, int buflen);
STDMETHODIMP CheckHEVCSequence(const BYTE *buffer, int buflen, int *bitdepth);
int GetMaxGflopsGraphicsDeviceId();
private:
struct
{
HMODULE cudaLib;
CUMETHOD(cuInit);
CUMETHOD(cuCtxCreate);
CUMETHOD(cuCtxDestroy);
CUMETHOD(cuCtxPushCurrent);
CUMETHOD(cuCtxPopCurrent);
CUMETHOD(cuD3D9CtxCreate);
CUMETHOD(cuMemAllocHost);
CUMETHOD(cuMemFreeHost);
CUMETHOD(cuMemcpyDtoH);
CUMETHOD(cuDeviceGetCount);
CUMETHOD(cuDriverGetVersion);
CUMETHOD(cuDeviceGetName);
CUMETHOD(cuDeviceComputeCapability);
CUMETHOD(cuDeviceGetAttribute);
HMODULE cuvidLib;
CUMETHOD(cuvidCtxLockCreate);
CUMETHOD(cuvidCtxLockDestroy);
CUMETHOD(cuvidCtxLock);
CUMETHOD(cuvidCtxUnlock);
CUMETHOD(cuvidCreateVideoParser);
CUMETHOD(cuvidParseVideoData);
CUMETHOD(cuvidDestroyVideoParser);
CUMETHOD(cuvidCreateDecoder);
CUMETHOD(cuvidDecodePicture);
CUMETHOD(cuvidDestroyDecoder);
CUMETHOD(cuvidMapVideoFrame);
CUMETHOD(cuvidUnmapVideoFrame);
#ifdef _M_AMD64
CUMETHOD(cuvidMapVideoFrame64);
CUMETHOD(cuvidUnmapVideoFrame64);
#endif
} cuda;
IDirect3D9 *m_pD3D9 = nullptr;
IDirect3DDevice9 *m_pD3DDevice9 = nullptr;
CUcontext m_cudaContext = 0;
CUvideoctxlock m_cudaCtxLock = 0;
CUvideoparser m_hParser = 0;
CUVIDEOFORMATEX m_VideoParserExInfo;
CUvideodecoder m_hDecoder = 0;
CUVIDDECODECREATEINFO m_VideoDecoderInfo;
CUVIDEOFORMAT m_VideoFormat;
CUVIDPARSERDISPINFO m_DisplayQueue[DISPLAY_DELAY];
int m_DisplayPos = 0;
CUVIDPICPARAMS m_PicParams[MAX_PIC_INDEX];
BOOL m_bVDPAULevelC = FALSE;
char m_cudaDeviceName[256] = {0};
BOOL m_bForceSequenceUpdate = FALSE;
BOOL m_bInterlaced = FALSE;
BOOL m_bDoubleRateDeint = FALSE;
BOOL m_bFlushing = FALSE;
REFERENCE_TIME m_rtAvgTimePerFrame = AV_NOPTS_VALUE;
REFERENCE_TIME m_rtPrevDiff = AV_NOPTS_VALUE;
BOOL m_bWaitForKeyframe = FALSE;
int m_iFullRange = -1;
DXVA2_ExtendedFormat m_DXVAExtendedFormat;
BYTE *m_pbRawNV12 = nullptr;
int m_cRawNV12 = 0;
CAnnexBConverter *m_AnnexBConverter = nullptr;
BOOL m_bFormatIncompatible = FALSE;
BOOL m_bNeedSequenceCheck = FALSE;
BOOL m_bUseTimestampQueue = FALSE;
std::queue<REFERENCE_TIME> m_timestampQueue;
int m_nSoftTelecine = 0;
BOOL m_bTFF = TRUE;
BOOL m_bARPresent = TRUE;
BOOL m_bEndOfSequence = FALSE;
int m_DisplayDelay = DISPLAY_DELAY;
};
| 5,476
|
C++
|
.h
| 138
| 34.101449
| 119
| 0.730994
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,499
|
dynlink_cuda.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/decoders/cuvid/dynlink_cuda.h
|
/*
* Copyright 1993-2015 NVIDIA Corporation. All rights reserved.
*
* Please refer to the NVIDIA end user license agreement (EULA) associated
* with this source code for terms and conditions that govern your use of
* this software. Any use, reproduction, disclosure, or distribution of
* this software and related documentation outside the terms of the EULA
* is strictly prohibited.
*
*/
#ifndef __cuda_h__
#define __cuda_h__
/**
* CUDA API version support
*/
#include "dynlink_cuda_cuda.h"
#endif //__cuda_h__
| 527
|
C++
|
.h
| 17
| 29.176471
| 74
| 0.750495
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,501
|
dynlink_cuda_d3d.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/decoders/cuvid/dynlink_cuda_d3d.h
|
/*
* Copyright 1993-2015 NVIDIA Corporation. All rights reserved.
*
* Please refer to the NVIDIA end user license agreement (EULA) associated
* with this source code for terms and conditions that govern your use of
* this software. Any use, reproduction, disclosure, or distribution of
* this software and related documentation outside the terms of the EULA
* is strictly prohibited.
*
*/
#ifndef __cuda_d3d_h__
#define __cuda_d3d_h__
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64)
#pragma warning(disable: 4312)
#if defined (CUDA_INIT_D3D9) || defined(CUDA_INIT_D3D10) || defined(CUDA_INIT_D3D11)
#include <Windows.h>
#include <mmsystem.h>
#endif
#ifdef CUDA_INIT_D3D9
#pragma warning( disable : 4996 ) // disable deprecated warning
#include <strsafe.h>
#pragma warning( default : 4996 )
/**
* CUDA 2.x compatibility - Flags to register a D3D9 graphics resource
*/
typedef enum CUd3d9register_flags_enum
{
CU_D3D9_REGISTER_FLAGS_NONE = 0x00,
CU_D3D9_REGISTER_FLAGS_ARRAY = 0x01,
} CUd3d9register_flags;
/**
* CUDA 2.x compatibility - Flags for D3D9 mapping and unmapping interop resources
*/
typedef enum CUd3d9map_flags_enum
{
CU_D3D9_MAPRESOURCE_FLAGS_NONE = 0x00,
CU_D3D9_MAPRESOURCE_FLAGS_READONLY = 0x01,
CU_D3D9_MAPRESOURCE_FLAGS_WRITEDISCARD = 0x02,
} CUd3d9map_flags;
// D3D9/CUDA interop (CUDA 1.x compatible API). These functions are deprecated, please use the ones below
typedef CUresult CUDAAPI tcuD3D9Begin(IDirect3DDevice9 *pDevice);
typedef CUresult CUDAAPI tcuD3D9End(void);
typedef CUresult CUDAAPI tcuD3D9RegisterVertexBuffer(IDirect3DVertexBuffer9 *pVB);
typedef CUresult CUDAAPI tcuD3D9MapVertexBuffer(CUdeviceptr *pDevPtr, unsigned int *pSize, IDirect3DVertexBuffer9 *pVB);
typedef CUresult CUDAAPI tcuD3D9UnmapVertexBuffer(IDirect3DVertexBuffer9 *pVB);
typedef CUresult CUDAAPI tcuD3D9UnregisterVertexBuffer(IDirect3DVertexBuffer9 *pVB);
// D3D9/CUDA interop (CUDA 2.x compatible)
typedef CUresult CUDAAPI tcuD3D9GetDirect3DDevice(IDirect3DDevice9 **ppD3DDevice);
typedef CUresult CUDAAPI tcuD3D9RegisterResource(IDirect3DResource9 *pResource, unsigned int Flags);
typedef CUresult CUDAAPI tcuD3D9UnregisterResource(IDirect3DResource9 *pResource);
typedef CUresult CUDAAPI tcuD3D9MapResources(unsigned int count, IDirect3DResource9 **ppResource);
typedef CUresult CUDAAPI tcuD3D9UnmapResources(unsigned int count, IDirect3DResource9 **ppResource);
typedef CUresult CUDAAPI tcuD3D9ResourceSetMapFlags(IDirect3DResource9 *pResource, unsigned int Flags);
typedef CUresult CUDAAPI tcuD3D9ResourceGetSurfaceDimensions(unsigned int *pWidth, unsigned int *pHeight, unsigned int *pDepth, IDirect3DResource9 *pResource, unsigned int Face, unsigned int Level);
typedef CUresult CUDAAPI tcuD3D9ResourceGetMappedArray(CUarray *pArray, IDirect3DResource9 *pResource, unsigned int Face, unsigned int Level);
typedef CUresult CUDAAPI tcuD3D9ResourceGetMappedPointer(CUdeviceptr *pDevPtr, IDirect3DResource9 *pResource, unsigned int Face, unsigned int Level);
typedef CUresult CUDAAPI tcuD3D9ResourceGetMappedSize(unsigned int *pSize, IDirect3DResource9 *pResource, unsigned int Face, unsigned int Level);
typedef CUresult CUDAAPI tcuD3D9ResourceGetMappedPitch(unsigned int *pPitch, unsigned int *pPitchSlice, IDirect3DResource9 *pResource, unsigned int Face, unsigned int Level);
// D3D9/CUDA interop (CUDA 2.0+)
typedef CUresult CUDAAPI tcuD3D9GetDevice(CUdevice *pCudaDevice, const char *pszAdapterName);
typedef CUresult CUDAAPI tcuD3D9CtxCreate(CUcontext *pCtx, CUdevice *pCudaDevice, unsigned int Flags, IDirect3DDevice9 *pD3DDevice);
typedef CUresult CUDAAPI tcuGraphicsD3D9RegisterResource(CUgraphicsResource *pCudaResource, IDirect3DResource9 *pD3DResource, unsigned int Flags);
#endif
#ifdef CUDA_INIT_D3D10
#include <dxgi.h>
#include <d3d10_1.h>
#include <d3d10.h>
#pragma warning( disable : 4996 ) // disable deprecated warning
#include <strsafe.h>
#pragma warning( default : 4996 )
// D3D11/CUDA interop (CUDA 3.0)
typedef CUresult CUDAAPI tcuD3D10GetDevice(CUdevice *pCudaDevice, IDXGIAdapter *pAdapter);
typedef CUresult CUDAAPI tcuD3D10CtxCreate(CUcontext *pCtx, CUdevice *pCudaDevice, unsigned int Flags, ID3D10Device *pD3DDevice);
typedef CUresult CUDAAPI tcuGraphicsD3D10RegisterResource(CUgraphicsResource *pCudaResource, ID3D10Resource *pD3DResource, unsigned int Flags);
#endif // CUDA_INIT_D3D10
#ifdef CUDA_INIT_D3D11
#include <dxgi.h>
#include <d3d11.h>
#pragma warning( disable : 4996 ) // disable deprecated warning
#include <strsafe.h>
#pragma warning( default : 4996 )
// D3D11/CUDA interop (CUDA 3.0)
typedef CUresult CUDAAPI tcuD3D11GetDevice(CUdevice *pCudaDevice, IDXGIAdapter *pAdapter);
typedef CUresult CUDAAPI tcuD3D11CtxCreate(CUcontext *pCtx, CUdevice *pCudaDevice, unsigned int Flags, ID3D11Device *pD3DDevice);
typedef CUresult CUDAAPI tcuGraphicsD3D11RegisterResource(CUgraphicsResource *pCudaResource, ID3D11Resource *pD3DResource, unsigned int Flags);
#endif // CUDA_INIT_D3D11
#endif // WIN32
#endif // __cuda_d3d_h__
| 5,067
|
C++
|
.h
| 88
| 55.954545
| 198
| 0.816734
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
22,502
|
dynlink_nvcuvid.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/decoders/cuvid/dynlink_nvcuvid.h
|
/*
* This copyright notice applies to this header file only:
*
* Copyright (c) 2010-2024 NVIDIA 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.
*/
/********************************************************************************************************************/
//! \file nvcuvid.h
//! NVDECODE API provides video decoding interface to NVIDIA GPU devices.
//! \date 2015-2024
//! This file contains the interface constants, structure definitions and function prototypes.
/********************************************************************************************************************/
#if !defined(__NVCUVID_H__)
#define __NVCUVID_H__
#include "dynlink_cuviddec.h"
#if defined(__cplusplus)
extern "C" {
#endif /* __cplusplus */
#define MAX_CLOCK_TS 3
/***********************************************/
//!
//! High-level helper APIs for video sources
//!
/***********************************************/
typedef void *CUvideosource;
typedef void *CUvideoparser;
typedef long long CUvideotimestamp;
/************************************************************************/
//! \enum cudaVideoState
//! Video source state enums
//! Used in cuvidSetVideoSourceState and cuvidGetVideoSourceState APIs
/************************************************************************/
typedef enum {
cudaVideoState_Error = -1, /**< Error state (invalid source) */
cudaVideoState_Stopped = 0, /**< Source is stopped (or reached end-of-stream) */
cudaVideoState_Started = 1 /**< Source is running and delivering data */
} cudaVideoState;
/************************************************************************/
//! \enum cudaAudioCodec
//! Audio compression enums
//! Used in CUAUDIOFORMAT structure
/************************************************************************/
typedef enum {
cudaAudioCodec_MPEG1=0, /**< MPEG-1 Audio */
cudaAudioCodec_MPEG2, /**< MPEG-2 Audio */
cudaAudioCodec_MP3, /**< MPEG-1 Layer III Audio */
cudaAudioCodec_AC3, /**< Dolby Digital (AC3) Audio */
cudaAudioCodec_LPCM, /**< PCM Audio */
cudaAudioCodec_AAC, /**< AAC Audio */
} cudaAudioCodec;
/************************************************************************/
//! \ingroup STRUCTS
//! \struct TIMECODESET
//! Used to store Time code set extracted from H264 and HEVC codecs
/************************************************************************/
typedef struct _TIMECODESET
{
unsigned int time_offset_value;
unsigned short n_frames;
unsigned char clock_timestamp_flag;
unsigned char units_field_based_flag;
unsigned char counting_type;
unsigned char full_timestamp_flag;
unsigned char discontinuity_flag;
unsigned char cnt_dropped_flag;
unsigned char seconds_value;
unsigned char minutes_value;
unsigned char hours_value;
unsigned char seconds_flag;
unsigned char minutes_flag;
unsigned char hours_flag;
unsigned char time_offset_length;
unsigned char reserved;
} TIMECODESET;
/************************************************************************/
//! \ingroup STRUCTS
//! \struct TIMECODE
//! Used to extract Time code in H264 and HEVC codecs
/************************************************************************/
typedef struct _TIMECODE
{
TIMECODESET time_code_set[MAX_CLOCK_TS];
unsigned char num_clock_ts;
} NVTIMECODE;
/**********************************************************************************/
//! \ingroup STRUCTS
//! \struct SEIMASTERINGDISPLAYINFO
//! Used to extract mastering display color volume SEI in H264 and HEVC codecs
/**********************************************************************************/
typedef struct _SEIMASTERINGDISPLAYINFO
{
unsigned short display_primaries_x[3];
unsigned short display_primaries_y[3];
unsigned short white_point_x;
unsigned short white_point_y;
unsigned int max_display_mastering_luminance;
unsigned int min_display_mastering_luminance;
} SEIMASTERINGDISPLAYINFO;
/**********************************************************************************/
//! \ingroup STRUCTS
//! \struct SEICONTENTLIGHTLEVELINFO
//! Used to extract content light level info SEI in H264 and HEVC codecs
/**********************************************************************************/
typedef struct _SEICONTENTLIGHTLEVELINFO
{
unsigned short max_content_light_level;
unsigned short max_pic_average_light_level;
unsigned int reserved;
} SEICONTENTLIGHTLEVELINFO;
/**********************************************************************************/
//! \ingroup STRUCTS
//! \struct TIMECODEMPEG2
//! Used to extract Time code in MPEG2 codec
/**********************************************************************************/
typedef struct _TIMECODEMPEG2
{
unsigned char drop_frame_flag;
unsigned char time_code_hours;
unsigned char time_code_minutes;
unsigned char marker_bit;
unsigned char time_code_seconds;
unsigned char time_code_pictures;
} TIMECODEMPEG2;
/**********************************************************************************/
//! \ingroup STRUCTS
//! \struct SEIALTERNATIVETRANSFERCHARACTERISTICS
//! Used to extract alternative transfer characteristics SEI in H264 and HEVC codecs
/**********************************************************************************/
typedef struct _SEIALTERNATIVETRANSFERCHARACTERISTICS
{
unsigned char preferred_transfer_characteristics;
} SEIALTERNATIVETRANSFERCHARACTERISTICS;
/**********************************************************************************/
//! \ingroup STRUCTS
//! \struct CUSEIMESSAGE;
//! Used in CUVIDSEIMESSAGEINFO structure
/**********************************************************************************/
typedef struct _CUSEIMESSAGE
{
unsigned char sei_message_type; /**< OUT: SEI Message Type */
unsigned char reserved[3];
unsigned int sei_message_size; /**< OUT: SEI Message Size */
} CUSEIMESSAGE;
/************************************************************************************************/
//! \ingroup STRUCTS
//! \struct CUVIDEOFORMAT
//! Video format
//! Used in cuvidGetSourceVideoFormat API
/************************************************************************************************/
typedef struct
{
cudaVideoCodec codec; /**< OUT: Compression format */
/**
* OUT: frame rate = numerator / denominator (for example: 30000/1001)
*/
struct {
/**< OUT: frame rate numerator (0 = unspecified or variable frame rate) */
unsigned int numerator;
/**< OUT: frame rate denominator (0 = unspecified or variable frame rate) */
unsigned int denominator;
} frame_rate;
unsigned char progressive_sequence; /**< OUT: 0=interlaced, 1=progressive */
unsigned char bit_depth_luma_minus8; /**< OUT: high bit depth luma. E.g, 2 for 10-bitdepth, 4 for 12-bitdepth */
unsigned char bit_depth_chroma_minus8; /**< OUT: high bit depth chroma. E.g, 2 for 10-bitdepth, 4 for 12-bitdepth */
unsigned char min_num_decode_surfaces; /**< OUT: Minimum number of decode surfaces to be allocated for correct
decoding. The client can send this value in ulNumDecodeSurfaces
(in CUVIDDECODECREATEINFO structure).
This guarantees correct functionality and optimal video memory
usage but not necessarily the best performance, which depends on
the design of the overall application. The optimal number of
decode surfaces (in terms of performance and memory utilization)
should be decided by experimentation for each application, but it
cannot go below min_num_decode_surfaces.
If this value is used for ulNumDecodeSurfaces then it must be
returned to parser during sequence callback. */
unsigned int coded_width; /**< OUT: coded frame width in pixels */
unsigned int coded_height; /**< OUT: coded frame height in pixels */
/**
* area of the frame that should be displayed
* typical example:
* coded_width = 1920, coded_height = 1088
* display_area = { 0,0,1920,1080 }
*/
struct {
int left; /**< OUT: left position of display rect */
int top; /**< OUT: top position of display rect */
int right; /**< OUT: right position of display rect */
int bottom; /**< OUT: bottom position of display rect */
} display_area;
cudaVideoChromaFormat chroma_format; /**< OUT: Chroma format */
unsigned int bitrate; /**< OUT: video bitrate (bps, 0=unknown) */
/**
* OUT: Display Aspect Ratio = x:y (4:3, 16:9, etc)
*/
struct {
int x;
int y;
} display_aspect_ratio;
/**
* Video Signal Description
* Refer section E.2.1 (VUI parameters semantics) of H264 spec file
*/
struct {
unsigned char video_format : 3; /**< OUT: 0-Component, 1-PAL, 2-NTSC, 3-SECAM, 4-MAC, 5-Unspecified */
unsigned char video_full_range_flag : 1; /**< OUT: indicates the black level and luma and chroma range */
unsigned char reserved_zero_bits : 4; /**< Reserved bits */
unsigned char color_primaries; /**< OUT: chromaticity coordinates of source primaries */
unsigned char transfer_characteristics; /**< OUT: opto-electronic transfer characteristic of the source picture */
unsigned char matrix_coefficients; /**< OUT: used in deriving luma and chroma signals from RGB primaries */
} video_signal_description;
unsigned int seqhdr_data_length; /**< OUT: Additional bytes following (CUVIDEOFORMATEX) */
} CUVIDEOFORMAT;
/****************************************************************/
//! \ingroup STRUCTS
//! \struct CUVIDOPERATINGPOINTINFO
//! Operating point information of scalable bitstream
/****************************************************************/
typedef struct
{
cudaVideoCodec codec;
union
{
struct
{
unsigned char operating_points_cnt;
unsigned char reserved24_bits[3];
unsigned short operating_points_idc[32];
} av1;
unsigned char CodecReserved[1024];
};
} CUVIDOPERATINGPOINTINFO;
/**********************************************************************************/
//! \ingroup STRUCTS
//! \struct CUVIDSEIMESSAGEINFO
//! Used in cuvidParseVideoData API with PFNVIDSEIMSGCALLBACK pfnGetSEIMsg
/**********************************************************************************/
typedef struct _CUVIDSEIMESSAGEINFO
{
void *pSEIData; /**< OUT: SEI Message Data */
CUSEIMESSAGE *pSEIMessage; /**< OUT: SEI Message Info */
unsigned int sei_message_count; /**< OUT: SEI Message Count */
unsigned int picIdx; /**< OUT: SEI Message Pic Index */
} CUVIDSEIMESSAGEINFO;
/****************************************************************/
//! \ingroup STRUCTS
//! \struct CUVIDAV1SEQHDR
//! AV1 specific sequence header information
/****************************************************************/
typedef struct {
unsigned int max_width;
unsigned int max_height;
unsigned char reserved[1016];
} CUVIDAV1SEQHDR;
/****************************************************************/
//! \ingroup STRUCTS
//! \struct CUVIDEOFORMATEX
//! Video format including raw sequence header information
//! Used in cuvidGetSourceVideoFormat API
/****************************************************************/
typedef struct
{
CUVIDEOFORMAT format; /**< OUT: CUVIDEOFORMAT structure */
union {
CUVIDAV1SEQHDR av1;
unsigned char raw_seqhdr_data[1024]; /**< OUT: Sequence header data */
};
} CUVIDEOFORMATEX;
/****************************************************************/
//! \ingroup STRUCTS
//! \struct CUAUDIOFORMAT
//! Audio formats
//! Used in cuvidGetSourceAudioFormat API
/****************************************************************/
typedef struct
{
cudaAudioCodec codec; /**< OUT: Compression format */
unsigned int channels; /**< OUT: number of audio channels */
unsigned int samplespersec; /**< OUT: sampling frequency */
unsigned int bitrate; /**< OUT: For uncompressed, can also be used to determine bits per sample */
unsigned int reserved1; /**< Reserved for future use */
unsigned int reserved2; /**< Reserved for future use */
} CUAUDIOFORMAT;
/***************************************************************/
//! \enum CUvideopacketflags
//! Data packet flags
//! Used in CUVIDSOURCEDATAPACKET structure
/***************************************************************/
typedef enum {
CUVID_PKT_ENDOFSTREAM = 0x01, /**< Set when this is the last packet for this stream */
CUVID_PKT_TIMESTAMP = 0x02, /**< Timestamp is valid */
CUVID_PKT_DISCONTINUITY = 0x04, /**< Set when a discontinuity has to be signalled */
CUVID_PKT_ENDOFPICTURE = 0x08, /**< Set when the packet contains exactly one frame or one field */
CUVID_PKT_NOTIFY_EOS = 0x10, /**< If this flag is set along with CUVID_PKT_ENDOFSTREAM, an additional (dummy)
display callback will be invoked with null value of CUVIDPARSERDISPINFO which
should be interpreted as end of the stream. */
} CUvideopacketflags;
/*****************************************************************************/
//! \ingroup STRUCTS
//! \struct CUVIDSOURCEDATAPACKET
//! Data Packet
//! Used in cuvidParseVideoData API
//! IN for cuvidParseVideoData
/*****************************************************************************/
typedef struct _CUVIDSOURCEDATAPACKET
{
unsigned long flags; /**< IN: Combination of CUVID_PKT_XXX flags */
unsigned long payload_size; /**< IN: number of bytes in the payload (may be zero if EOS flag is set) */
const unsigned char *payload; /**< IN: Pointer to packet payload data (may be NULL if EOS flag is set) */
CUvideotimestamp timestamp; /**< IN: Presentation time stamp (10MHz clock), only valid if
CUVID_PKT_TIMESTAMP flag is set */
} CUVIDSOURCEDATAPACKET;
// Callback for packet delivery
typedef int (CUDAAPI *PFNVIDSOURCECALLBACK)(void *, CUVIDSOURCEDATAPACKET *);
/**************************************************************************************************************************/
//! \ingroup STRUCTS
//! \struct CUVIDSOURCEPARAMS
//! Describes parameters needed in cuvidCreateVideoSource API
//! NVDECODE API is intended for HW accelerated video decoding so CUvideosource doesn't have audio demuxer for all supported
//! containers. It's recommended to clients to use their own or third party demuxer if audio support is needed.
/**************************************************************************************************************************/
typedef struct _CUVIDSOURCEPARAMS
{
unsigned int ulClockRate; /**< IN: Time stamp units in Hz (0=default=10000000Hz) */
unsigned int bAnnexb : 1; /**< IN: AV1 annexB stream */
unsigned int uReserved : 31; /**< Reserved for future use - set to zero */
unsigned int uReserved1[6]; /**< Reserved for future use - set to zero */
void *pUserData; /**< IN: User private data passed in to the data handlers */
PFNVIDSOURCECALLBACK pfnVideoDataHandler; /**< IN: Called to deliver video packets */
PFNVIDSOURCECALLBACK pfnAudioDataHandler; /**< IN: Called to deliver audio packets. */
void *pvReserved2[8]; /**< Reserved for future use - set to NULL */
} CUVIDSOURCEPARAMS;
/**********************************************/
//! \ingroup ENUMS
//! \enum CUvideosourceformat_flags
//! CUvideosourceformat_flags
//! Used in cuvidGetSourceVideoFormat API
/**********************************************/
typedef enum {
CUVID_FMT_EXTFORMATINFO = 0x100 /**< Return extended format structure (CUVIDEOFORMATEX) */
} CUvideosourceformat_flags;
#if !defined(__APPLE__)
/***************************************************************************************************************************/
//! \ingroup FUNCTS
//! \fn CUresult CUDAAPI cuvidCreateVideoSource(CUvideosource *pObj, const char *pszFileName, CUVIDSOURCEPARAMS *pParams)
//! Create CUvideosource object. CUvideosource spawns demultiplexer thread that provides two callbacks:
//! pfnVideoDataHandler() and pfnAudioDataHandler()
//! NVDECODE API is intended for HW accelerated video decoding so CUvideosource doesn't have audio demuxer for all supported
//! containers. It's recommended to clients to use their own or third party demuxer if audio support is needed.
/***************************************************************************************************************************/
typedef CUresult CUDAAPI tcuvidCreateVideoSource(CUvideosource *pObj, const char *pszFileName, CUVIDSOURCEPARAMS *pParams);
/***************************************************************************************************************************/
//! \ingroup FUNCTS
//! \fn CUresult CUDAAPI cuvidCreateVideoSourceW(CUvideosource *pObj, const wchar_t *pwszFileName, CUVIDSOURCEPARAMS *pParams)
//! Create video source
/***************************************************************************************************************************/
typedef CUresult CUDAAPI tcuvidCreateVideoSourceW(CUvideosource *pObj, const wchar_t *pwszFileName, CUVIDSOURCEPARAMS *pParams);
/********************************************************************/
//! \ingroup FUNCTS
//! \fn CUresult CUDAAPI cuvidDestroyVideoSource(CUvideosource obj)
//! Destroy video source
/********************************************************************/
typedef CUresult CUDAAPI tcuvidDestroyVideoSource(CUvideosource obj);
/******************************************************************************************/
//! \ingroup FUNCTS
//! \fn CUresult CUDAAPI cuvidSetVideoSourceState(CUvideosource obj, cudaVideoState state)
//! Set video source state to:
//! cudaVideoState_Started - to signal the source to run and deliver data
//! cudaVideoState_Stopped - to stop the source from delivering the data
//! cudaVideoState_Error - invalid source
/******************************************************************************************/
typedef CUresult CUDAAPI tcuvidSetVideoSourceState(CUvideosource obj, cudaVideoState state);
/******************************************************************************************/
//! \ingroup FUNCTS
//! \fn cudaVideoState CUDAAPI cuvidGetVideoSourceState(CUvideosource obj)
//! Get video source state
//! Returns:
//! cudaVideoState_Started - if Source is running and delivering data
//! cudaVideoState_Stopped - if Source is stopped or reached end-of-stream
//! cudaVideoState_Error - if Source is in error state
/******************************************************************************************/
typedef cudaVideoState CUDAAPI tcuvidGetVideoSourceState(CUvideosource obj);
/******************************************************************************************************************/
//! \ingroup FUNCTS
//! \fn CUresult CUDAAPI cuvidGetSourceVideoFormat(CUvideosource obj, CUVIDEOFORMAT *pvidfmt, unsigned int flags)
//! Gets video source format in pvidfmt, flags is set to combination of CUvideosourceformat_flags as per requirement
/******************************************************************************************************************/
typedef CUresult CUDAAPI tcuvidGetSourceVideoFormat(CUvideosource obj, CUVIDEOFORMAT *pvidfmt, unsigned int flags);
/**************************************************************************************************************************/
//! \ingroup FUNCTS
//! \fn CUresult CUDAAPI cuvidGetSourceAudioFormat(CUvideosource obj, CUAUDIOFORMAT *paudfmt, unsigned int flags)
//! Get audio source format
//! NVDECODE API is intended for HW accelerated video decoding so CUvideosource doesn't have audio demuxer for all supported
//! containers. It's recommended to clients to use their own or third party demuxer if audio support is needed.
/**************************************************************************************************************************/
typedef CUresult CUDAAPI tcuvidGetSourceAudioFormat(CUvideosource obj, CUAUDIOFORMAT *paudfmt, unsigned int flags);
#endif
/**********************************************************************************/
//! \ingroup STRUCTS
//! \struct CUVIDPARSERDISPINFO
//! Used in cuvidParseVideoData API with PFNVIDDISPLAYCALLBACK pfnDisplayPicture
/**********************************************************************************/
typedef struct _CUVIDPARSERDISPINFO
{
int picture_index; /**< OUT: Index of the current picture */
int progressive_frame; /**< OUT: 1 if progressive frame; 0 otherwise */
int top_field_first; /**< OUT: 1 if top field is displayed first; 0 otherwise */
int repeat_first_field; /**< OUT: Number of additional fields (1=ivtc, 2=frame doubling, 4=frame tripling,
-1=unpaired field) */
CUvideotimestamp timestamp; /**< OUT: Presentation time stamp */
} CUVIDPARSERDISPINFO;
/***********************************************************************************************************************/
//! Parser callbacks
//! The parser will call these synchronously from within cuvidParseVideoData(), whenever there is sequence change or a picture
//! is ready to be decoded and/or displayed. First argument in functions is "void *pUserData" member of structure CUVIDSOURCEPARAMS
//! Return values from these callbacks are interpreted as below. If the callbacks return failure, it will be propagated by
//! cuvidParseVideoData() to the application.
//! Parser picks default operating point as 0 and outputAllLayers flag as 0 if PFNVIDOPPOINTCALLBACK is not set or return value is
//! -1 or invalid operating point.
//! PFNVIDSEQUENCECALLBACK : 0: fail, 1: succeeded, > 1: override dpb size of parser (set by CUVIDPARSERPARAMS::ulMaxNumDecodeSurfaces
//! while creating parser)
//! PFNVIDDECODECALLBACK : 0: fail, >=1: succeeded
//! PFNVIDDISPLAYCALLBACK : 0: fail, >=1: succeeded
//! PFNVIDOPPOINTCALLBACK : <0: fail, >=0: succeeded (bit 0-9: OperatingPoint, bit 10-10: outputAllLayers, bit 11-30: reserved)
//! PFNVIDSEIMSGCALLBACK : 0: fail, >=1: succeeded
/***********************************************************************************************************************/
typedef int (CUDAAPI *PFNVIDSEQUENCECALLBACK)(void *, CUVIDEOFORMAT *);
typedef int (CUDAAPI *PFNVIDDECODECALLBACK)(void *, CUVIDPICPARAMS *);
typedef int (CUDAAPI *PFNVIDDISPLAYCALLBACK)(void *, CUVIDPARSERDISPINFO *);
typedef int (CUDAAPI *PFNVIDOPPOINTCALLBACK)(void *, CUVIDOPERATINGPOINTINFO*);
typedef int (CUDAAPI *PFNVIDSEIMSGCALLBACK) (void *, CUVIDSEIMESSAGEINFO *);
/**************************************/
//! \ingroup STRUCTS
//! \struct CUVIDPARSERPARAMS
//! Used in cuvidCreateVideoParser API
/**************************************/
typedef struct _CUVIDPARSERPARAMS
{
cudaVideoCodec CodecType; /**< IN: cudaVideoCodec_XXX */
unsigned int ulMaxNumDecodeSurfaces; /**< IN: Max # of decode surfaces (parser will cycle through these) */
unsigned int ulClockRate; /**< IN: Timestamp units in Hz (0=default=10000000Hz) */
unsigned int ulErrorThreshold; /**< IN: % Error threshold (0-100) for calling pfnDecodePicture (100=always
IN: call pfnDecodePicture even if picture bitstream is fully corrupted) */
unsigned int ulMaxDisplayDelay; /**< IN: Max display queue delay (improves pipelining of decode with display)
0=no delay (recommended values: 2..4) */
unsigned int bAnnexb : 1; /**< IN: AV1 annexB stream */
unsigned int uReserved : 31; /**< Reserved for future use - set to zero */
unsigned int uReserved1[4]; /**< IN: Reserved for future use - set to 0 */
void *pUserData; /**< IN: User data for callbacks */
PFNVIDSEQUENCECALLBACK pfnSequenceCallback; /**< IN: Called before decoding frames and/or whenever there is a fmt change */
PFNVIDDECODECALLBACK pfnDecodePicture; /**< IN: Called when a picture is ready to be decoded (decode order) */
PFNVIDDISPLAYCALLBACK pfnDisplayPicture; /**< IN: Called whenever a picture is ready to be displayed (display order) */
PFNVIDOPPOINTCALLBACK pfnGetOperatingPoint; /**< IN: Called from AV1 sequence header to get operating point of a AV1
scalable bitstream */
PFNVIDSEIMSGCALLBACK pfnGetSEIMsg; /**< IN: Called when all SEI messages are parsed for particular frame */
void *pvReserved2[5]; /**< Reserved for future use - set to NULL */
CUVIDEOFORMATEX *pExtVideoInfo; /**< IN: [Optional] sequence header data from system layer */
} CUVIDPARSERPARAMS;
/************************************************************************************************/
//! \ingroup FUNCTS
//! \fn CUresult CUDAAPI cuvidCreateVideoParser(CUvideoparser *pObj, CUVIDPARSERPARAMS *pParams)
//! Create video parser object and initialize
/************************************************************************************************/
typedef CUresult CUDAAPI tcuvidCreateVideoParser(CUvideoparser *pObj, CUVIDPARSERPARAMS *pParams);
/************************************************************************************************/
//! \ingroup FUNCTS
//! \fn CUresult CUDAAPI cuvidParseVideoData(CUvideoparser obj, CUVIDSOURCEDATAPACKET *pPacket)
//! Parse the video data from source data packet in pPacket
//! Extracts parameter sets like SPS, PPS, bitstream etc. from pPacket and
//! calls back pfnDecodePicture with CUVIDPICPARAMS data for kicking of HW decoding
//! calls back pfnSequenceCallback with CUVIDEOFORMAT data for initial sequence header or when
//! the decoder encounters a video format change
//! calls back pfnDisplayPicture with CUVIDPARSERDISPINFO data to display a video frame
/************************************************************************************************/
typedef CUresult CUDAAPI tcuvidParseVideoData(CUvideoparser obj, CUVIDSOURCEDATAPACKET *pPacket);
/************************************************************************************************/
//! \ingroup FUNCTS
//! \fn CUresult CUDAAPI cuvidDestroyVideoParser(CUvideoparser obj)
//! Destroy the video parser
/************************************************************************************************/
typedef CUresult CUDAAPI tcuvidDestroyVideoParser(CUvideoparser obj);
/**********************************************************************************************/
#if defined(__cplusplus)
}
#endif /* __cplusplus */
#endif // __NVCUVID_H__
| 30,588
|
C++
|
.h
| 505
| 56.178218
| 134
| 0.520959
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,504
|
DXVA2SurfaceAllocator.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/decoders/dxva2/DXVA2SurfaceAllocator.h
|
/*
* Copyright (C) 2010-2021 Hendrik Leppkes
* http://www.1f0.de
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Initial Design and Concept taken from MPC-HC, licensed under GPLv2
*/
#pragma once
#include <Mfidl.h>
#include "MediaSampleSideData.h"
class CDecDXVA2;
interface __declspec(uuid("50A8A9A1-FF44-45C1-9DC2-79066ED1E576")) ILAVDXVA2Sample : public IUnknown
{
STDMETHOD_(int, GetDXSurfaceId()) = 0;
};
class CDXVA2Sample
: public CMediaSampleSideData
, public IMFGetService
, public ILAVDXVA2Sample
{
friend class CDXVA2SurfaceAllocator;
public:
CDXVA2Sample(CDXVA2SurfaceAllocator *pAlloc, HRESULT *phr);
virtual ~CDXVA2Sample();
STDMETHODIMP QueryInterface(REFIID riid, __deref_out void **ppv);
STDMETHODIMP_(ULONG) AddRef();
STDMETHODIMP_(ULONG) Release();
// IMFGetService::GetService
STDMETHODIMP GetService(REFGUID guidService, REFIID riid, LPVOID *ppv);
// ILAVDXVA2Sample
STDMETHODIMP_(int) GetDXSurfaceId();
// Override GetPointer because this class does not manage a system memory buffer.
// The EVR uses the MR_BUFFER_SERVICE service to get the Direct3D surface.
STDMETHODIMP GetPointer(BYTE **ppBuffer);
private:
// Sets the pointer to the Direct3D surface.
void SetSurface(DWORD surfaceId, IDirect3DSurface9 *pSurf);
IDirect3DSurface9 *m_pSurface = nullptr;
DWORD m_dwSurfaceId = 0;
};
interface __declspec(uuid("23F80BD8-2654-4F74-B7CC-621868D0A850")) ILAVDXVA2SurfaceAllocator : public IUnknown
{
STDMETHOD_(void, DecoderDestruct)() = 0;
};
class CDXVA2SurfaceAllocator
: public CBaseAllocator
, public ILAVDXVA2SurfaceAllocator
{
public:
CDXVA2SurfaceAllocator(CDecDXVA2 *m_pDXVA2Dec, HRESULT *phr);
virtual ~CDXVA2SurfaceAllocator(void);
DECLARE_IUNKNOWN;
STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void **ppv);
HRESULT Alloc();
void Free();
STDMETHODIMP_(BOOL) DecommitInProgress()
{
CAutoLock cal(this);
return m_bDecommitInProgress;
}
STDMETHODIMP_(BOOL) IsCommited()
{
CAutoLock cal(this);
return m_bCommitted;
}
STDMETHODIMP_(void) DecoderDestruct() { m_pDec = nullptr; }
private:
CDecDXVA2 *m_pDec = nullptr;
IDirect3DSurface9 **m_ppRTSurfaceArray = nullptr;
UINT m_nSurfaceArrayCount = 0;
};
| 3,057
|
C++
|
.h
| 84
| 32.559524
| 110
| 0.738321
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,505
|
dxva_common.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/decoders/dxva2/dxva_common.h
|
/*
* Copyright (C) 2011-2021 Hendrik Leppkes
* http://www.1f0.de
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
/* Align dimensions for hardware and codec requirements */
DWORD dxva_align_dimensions(AVCodecID codec, DWORD dim);
#define VEND_ID_ATI 0x1002
#define VEND_ID_NVIDIA 0x10DE
#define VEND_ID_INTEL 0x8086
/* hardware mode description */
typedef struct
{
const char *name;
const GUID *guid;
int codec;
const int *profiles;
} dxva_mode_t;
extern const dxva_mode_t dxva_modes[];
const dxva_mode_t *get_dxva_mode_from_guid(const GUID *guid);
int check_dxva_mode_compatibility(const dxva_mode_t *mode, int codec, int profile, bool b8Bit);
int check_dxva_codec_profile(const AVCodecContext *ctx, int hwpixfmt);
#define H264_CHECK_PROFILE(profile) (((profile) & ~FF_PROFILE_H264_CONSTRAINED) <= FF_PROFILE_H264_HIGH)
#define HEVC_CHECK_PROFILE(profile) ((profile) <= FF_PROFILE_HEVC_MAIN_10)
#define VP9_CHECK_PROFILE(profile) ((profile) == FF_PROFILE_VP9_0 || (profile) == FF_PROFILE_VP9_2)
| 1,731
|
C++
|
.h
| 39
| 42.333333
| 104
| 0.747031
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,506
|
mfxmvc.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/decoders/mvc/include/mfxmvc.h
|
/******************************************************************************* *\
Copyright (C) 2010-2013 Intel Corporation. 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 Intel Corporation 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 INTEL CORPORATION "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 INTEL CORPORATION 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.
File Name: mfxmvc.h
*******************************************************************************/
#ifndef __MFXMVC_H__
#define __MFXMVC_H__
#include "mfxdefs.h"
#ifdef __cplusplus
extern "C" {
#endif
/* CodecProfile, CodecLevel */
enum {
/* MVC profiles */
MFX_PROFILE_AVC_MULTIVIEW_HIGH =118,
MFX_PROFILE_AVC_STEREO_HIGH =128
};
/* Extended Buffer Ids */
enum {
MFX_EXTBUFF_MVC_SEQ_DESC = MFX_MAKEFOURCC('M','V','C','D'),
MFX_EXTBUFF_MVC_TARGET_VIEWS = MFX_MAKEFOURCC('M','V','C','T')
};
typedef struct {
mfxU16 ViewId;
mfxU16 NumAnchorRefsL0;
mfxU16 NumAnchorRefsL1;
mfxU16 AnchorRefL0[16];
mfxU16 AnchorRefL1[16];
mfxU16 NumNonAnchorRefsL0;
mfxU16 NumNonAnchorRefsL1;
mfxU16 NonAnchorRefL0[16];
mfxU16 NonAnchorRefL1[16];
} mfxMVCViewDependency;
typedef struct {
mfxU16 TemporalId;
mfxU16 LevelIdc;
mfxU16 NumViews;
mfxU16 NumTargetViews;
mfxU16 *TargetViewId;
} mfxMVCOperationPoint;
typedef struct {
mfxExtBuffer Header;
mfxU32 NumView;
mfxU32 NumViewAlloc;
mfxMVCViewDependency *View;
mfxU32 NumViewId;
mfxU32 NumViewIdAlloc;
mfxU16 *ViewId;
mfxU32 NumOP;
mfxU32 NumOPAlloc;
mfxMVCOperationPoint *OP;
mfxU16 NumRefsTotal;
mfxU32 Reserved[16];
} mfxExtMVCSeqDesc;
typedef struct {
mfxExtBuffer Header;
mfxU16 TemporalId;
mfxU32 NumView;
mfxU16 ViewId[1024];
} mfxExtMVCTargetViews ;
#ifdef __cplusplus
} // extern "C"
#endif
#endif
| 3,048
|
C++
|
.h
| 83
| 33.722892
| 83
| 0.73018
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,507
|
mfxsession.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/decoders/mvc/include/mfxsession.h
|
/*******************************************************************************
Copyright (C) 2013 Intel Corporation. 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 Intel Corporation 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 INTEL CORPORATION "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 INTEL CORPORATION 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.
File Name: mfxsession.h
*******************************************************************************/
#ifndef __MFXSESSION_H__
#define __MFXSESSION_H__
#include "mfxcommon.h"
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
/* Global Functions */
typedef struct _mfxSession *mfxSession;
mfxStatus MFX_CDECL MFXInit(mfxIMPL impl, mfxVersion *ver, mfxSession *session);
mfxStatus MFX_CDECL MFXInitEx(mfxInitParam par, mfxSession *session);
mfxStatus MFX_CDECL MFXClose(mfxSession session);
mfxStatus MFX_CDECL MFXQueryIMPL(mfxSession session, mfxIMPL *impl);
mfxStatus MFX_CDECL MFXQueryVersion(mfxSession session, mfxVersion *version);
mfxStatus MFX_CDECL MFXJoinSession(mfxSession session, mfxSession child);
mfxStatus MFX_CDECL MFXDisjoinSession(mfxSession session);
mfxStatus MFX_CDECL MFXCloneSession(mfxSession session, mfxSession *clone);
mfxStatus MFX_CDECL MFXSetPriority(mfxSession session, mfxPriority priority);
mfxStatus MFX_CDECL MFXGetPriority(mfxSession session, mfxPriority *priority);
mfxStatus MFX_CDECL MFXDoWork(mfxSession session);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
| 2,647
|
C++
|
.h
| 48
| 53.895833
| 80
| 0.775802
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| false
| false
| false
| false
| false
| false
|
22,508
|
mfxstructures.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/decoders/mvc/include/mfxstructures.h
|
/******************************************************************************* *\
Copyright (C) 2007-2018 Intel Corporation. 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 Intel Corporation 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 INTEL CORPORATION "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 INTEL CORPORATION 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.
File Name: mfxstructures.h
*******************************************************************************/
#ifndef __MFXSTRUCTURES_H__
#define __MFXSTRUCTURES_H__
#include "mfxcommon.h"
#if !defined (__GNUC__)
#pragma warning(disable: 4201)
#endif
#ifdef __cplusplus
extern "C" {
#endif
/* Frame ID for SVC and MVC */
typedef struct {
mfxU16 TemporalId;
mfxU16 PriorityId;
union {
struct {
mfxU16 DependencyId;
mfxU16 QualityId;
};
struct {
mfxU16 ViewId;
};
};
} mfxFrameId;
#pragma pack(push, 4)
/* Frame Info */
typedef struct {
mfxU32 reserved[4];
mfxU16 reserved4;
mfxU16 BitDepthLuma;
mfxU16 BitDepthChroma;
mfxU16 Shift;
mfxFrameId FrameId;
mfxU32 FourCC;
union {
struct { /* Frame parameters */
mfxU16 Width;
mfxU16 Height;
mfxU16 CropX;
mfxU16 CropY;
mfxU16 CropW;
mfxU16 CropH;
};
struct { /* Buffer parameters (for plain formats like P8) */
mfxU64 BufferSize;
mfxU32 reserved5;
};
};
mfxU32 FrameRateExtN;
mfxU32 FrameRateExtD;
mfxU16 reserved3;
mfxU16 AspectRatioW;
mfxU16 AspectRatioH;
mfxU16 PicStruct;
mfxU16 ChromaFormat;
mfxU16 reserved2;
} mfxFrameInfo;
#pragma pack(pop)
/* FourCC */
enum {
MFX_FOURCC_NV12 = MFX_MAKEFOURCC('N','V','1','2'), /* Native Format */
MFX_FOURCC_YV12 = MFX_MAKEFOURCC('Y','V','1','2'),
MFX_FOURCC_NV16 = MFX_MAKEFOURCC('N','V','1','6'),
MFX_FOURCC_YUY2 = MFX_MAKEFOURCC('Y','U','Y','2'),
MFX_FOURCC_RGB3 = MFX_MAKEFOURCC('R','G','B','3'), /* deprecated */
MFX_FOURCC_RGB4 = MFX_MAKEFOURCC('R','G','B','4'), /* ARGB in that order, A channel is 8 MSBs */
MFX_FOURCC_P8 = 41, /* D3DFMT_P8 */
MFX_FOURCC_P8_TEXTURE = MFX_MAKEFOURCC('P','8','M','B'),
MFX_FOURCC_P010 = MFX_MAKEFOURCC('P','0','1','0'),
MFX_FOURCC_P210 = MFX_MAKEFOURCC('P','2','1','0'),
MFX_FOURCC_BGR4 = MFX_MAKEFOURCC('B','G','R','4'), /* ABGR in that order, A channel is 8 MSBs */
MFX_FOURCC_A2RGB10 = MFX_MAKEFOURCC('R','G','1','0'), /* ARGB in that order, A channel is two MSBs */
MFX_FOURCC_ARGB16 = MFX_MAKEFOURCC('R','G','1','6'), /* ARGB in that order, 64 bits, A channel is 16 MSBs */
MFX_FOURCC_ABGR16 = MFX_MAKEFOURCC('B','G','1','6'), /* ABGR in that order, 64 bits, A channel is 16 MSBs */
MFX_FOURCC_R16 = MFX_MAKEFOURCC('R','1','6','U'),
MFX_FOURCC_AYUV = MFX_MAKEFOURCC('A','Y','U','V'), /* YUV 4:4:4, AYUV in that order, A channel is 8 MSBs */
MFX_FOURCC_AYUV_RGB4 = MFX_MAKEFOURCC('A','V','U','Y'), /* ARGB in that order, A channel is 8 MSBs stored in AYUV surface*/
MFX_FOURCC_UYVY = MFX_MAKEFOURCC('U','Y','V','Y'),
MFX_FOURCC_Y210 = MFX_MAKEFOURCC('Y','2','1','0'),
MFX_FOURCC_Y410 = MFX_MAKEFOURCC('Y','4','1','0'),
};
/* PicStruct */
enum {
MFX_PICSTRUCT_UNKNOWN =0x00,
MFX_PICSTRUCT_PROGRESSIVE =0x01,
MFX_PICSTRUCT_FIELD_TFF =0x02,
MFX_PICSTRUCT_FIELD_BFF =0x04,
MFX_PICSTRUCT_FIELD_REPEATED=0x10, /* first field repeated, pic_struct=5 or 6 in H.264 */
MFX_PICSTRUCT_FRAME_DOUBLING=0x20, /* pic_struct=7 in H.264 */
MFX_PICSTRUCT_FRAME_TRIPLING=0x40, /* pic_struct=8 in H.264 */
MFX_PICSTRUCT_FIELD_SINGLE =0x100,
MFX_PICSTRUCT_FIELD_TOP =MFX_PICSTRUCT_FIELD_SINGLE | MFX_PICSTRUCT_FIELD_TFF,
MFX_PICSTRUCT_FIELD_BOTTOM =MFX_PICSTRUCT_FIELD_SINGLE | MFX_PICSTRUCT_FIELD_BFF,
MFX_PICSTRUCT_FIELD_PAIRED_PREV =0x200,
MFX_PICSTRUCT_FIELD_PAIRED_NEXT =0x400,
};
/* ColorFormat */
enum {
MFX_CHROMAFORMAT_MONOCHROME =0,
MFX_CHROMAFORMAT_YUV420 =1,
MFX_CHROMAFORMAT_YUV422 =2,
MFX_CHROMAFORMAT_YUV444 =3,
MFX_CHROMAFORMAT_YUV400 = MFX_CHROMAFORMAT_MONOCHROME,
MFX_CHROMAFORMAT_YUV411 = 4,
MFX_CHROMAFORMAT_YUV422H = MFX_CHROMAFORMAT_YUV422,
MFX_CHROMAFORMAT_YUV422V = 5,
MFX_CHROMAFORMAT_RESERVED1 = 6
};
enum {
MFX_TIMESTAMP_UNKNOWN = -1
};
enum {
MFX_FRAMEORDER_UNKNOWN = -1
};
/* DataFlag in mfxFrameData */
enum {
MFX_FRAMEDATA_ORIGINAL_TIMESTAMP = 0x0001
};
/* Corrupted in mfxFrameData */
enum {
MFX_CORRUPTION_MINOR = 0x0001,
MFX_CORRUPTION_MAJOR = 0x0002,
MFX_CORRUPTION_ABSENT_TOP_FIELD = 0x0004,
MFX_CORRUPTION_ABSENT_BOTTOM_FIELD = 0x0008,
MFX_CORRUPTION_REFERENCE_FRAME = 0x0010,
MFX_CORRUPTION_REFERENCE_LIST = 0x0020
};
#pragma pack(push, 4)
typedef struct
{
mfxU32 U : 10;
mfxU32 Y : 10;
mfxU32 V : 10;
mfxU32 A : 2;
} mfxY410;
#pragma pack(pop)
#pragma pack(push, 4)
typedef struct
{
mfxU32 B : 10;
mfxU32 G : 10;
mfxU32 R : 10;
mfxU32 A : 2;
} mfxA2RGB10;
#pragma pack(pop)
/* Frame Data Info */
typedef struct {
union {
mfxExtBuffer **ExtParam;
mfxU64 reserved2;
};
mfxU16 NumExtParam;
mfxU16 reserved[9];
mfxU16 MemType;
mfxU16 PitchHigh;
mfxU64 TimeStamp;
mfxU32 FrameOrder;
mfxU16 Locked;
union{
mfxU16 Pitch;
mfxU16 PitchLow;
};
/* color planes */
union {
mfxU8 *Y;
mfxU16 *Y16;
mfxU8 *R;
};
union {
mfxU8 *UV; /* for UV merged formats */
mfxU8 *VU; /* for VU merged formats */
mfxU8 *CbCr; /* for CbCr merged formats */
mfxU8 *CrCb; /* for CrCb merged formats */
mfxU8 *Cb;
mfxU8 *U;
mfxU16 *U16;
mfxU8 *G;
mfxY410 *Y410; /* for Y410 format (merged AVYU) */
};
union {
mfxU8 *Cr;
mfxU8 *V;
mfxU16 *V16;
mfxU8 *B;
mfxA2RGB10 *A2RGB10; /* for A2RGB10 format (merged ARGB) */
};
mfxU8 *A;
mfxMemId MemId;
/* Additional Flags */
mfxU16 Corrupted;
mfxU16 DataFlag;
} mfxFrameData;
/* Frame Surface */
typedef struct {
mfxU32 reserved[4];
mfxFrameInfo Info;
mfxFrameData Data;
} mfxFrameSurface1;
enum {
MFX_TIMESTAMPCALC_UNKNOWN = 0,
MFX_TIMESTAMPCALC_TELECINE = 1,
};
/* Transcoding Info */
typedef struct {
mfxU32 reserved[7];
mfxU16 LowPower;
mfxU16 BRCParamMultiplier;
mfxFrameInfo FrameInfo;
mfxU32 CodecId;
mfxU16 CodecProfile;
mfxU16 CodecLevel;
mfxU16 NumThread;
union {
struct { /* Encoding Options */
mfxU16 TargetUsage;
mfxU16 GopPicSize;
mfxU16 GopRefDist;
mfxU16 GopOptFlag;
mfxU16 IdrInterval;
mfxU16 RateControlMethod;
union {
mfxU16 InitialDelayInKB;
mfxU16 QPI;
mfxU16 Accuracy;
};
mfxU16 BufferSizeInKB;
union {
mfxU16 TargetKbps;
mfxU16 QPP;
mfxU16 ICQQuality;
};
union {
mfxU16 MaxKbps;
mfxU16 QPB;
mfxU16 Convergence;
};
mfxU16 NumSlice;
mfxU16 NumRefFrame;
mfxU16 EncodedOrder;
};
struct { /* Decoding Options */
mfxU16 DecodedOrder;
mfxU16 ExtendedPicStruct;
mfxU16 TimeStampCalc;
mfxU16 SliceGroupsPresent;
mfxU16 MaxDecFrameBuffering;
mfxU16 EnableReallocRequest;
mfxU16 reserved2[7];
};
struct { /* JPEG Decoding Options */
mfxU16 JPEGChromaFormat;
mfxU16 Rotation;
mfxU16 JPEGColorFormat;
mfxU16 InterleavedDec;
mfxU8 SamplingFactorH[4];
mfxU8 SamplingFactorV[4];
mfxU16 reserved3[5];
};
struct { /* JPEG Encoding Options */
mfxU16 Interleaved;
mfxU16 Quality;
mfxU16 RestartInterval;
mfxU16 reserved5[10];
};
};
} mfxInfoMFX;
typedef struct {
mfxU32 reserved[8];
mfxFrameInfo In;
mfxFrameInfo Out;
} mfxInfoVPP;
typedef struct {
mfxU32 AllocId;
mfxU32 reserved[2];
mfxU16 reserved3;
mfxU16 AsyncDepth;
union {
mfxInfoMFX mfx;
mfxInfoVPP vpp;
};
mfxU16 Protected;
mfxU16 IOPattern;
mfxExtBuffer** ExtParam;
mfxU16 NumExtParam;
mfxU16 reserved2;
} mfxVideoParam;
/* IOPattern */
enum {
MFX_IOPATTERN_IN_VIDEO_MEMORY = 0x01,
MFX_IOPATTERN_IN_SYSTEM_MEMORY = 0x02,
MFX_IOPATTERN_IN_OPAQUE_MEMORY = 0x04,
MFX_IOPATTERN_OUT_VIDEO_MEMORY = 0x10,
MFX_IOPATTERN_OUT_SYSTEM_MEMORY = 0x20,
MFX_IOPATTERN_OUT_OPAQUE_MEMORY = 0x40
};
/* CodecId */
enum {
MFX_CODEC_AVC =MFX_MAKEFOURCC('A','V','C',' '),
MFX_CODEC_HEVC =MFX_MAKEFOURCC('H','E','V','C'),
MFX_CODEC_MPEG2 =MFX_MAKEFOURCC('M','P','G','2'),
MFX_CODEC_VC1 =MFX_MAKEFOURCC('V','C','1',' '),
MFX_CODEC_CAPTURE =MFX_MAKEFOURCC('C','A','P','T'),
MFX_CODEC_VP9 =MFX_MAKEFOURCC('V','P','9',' '),
MFX_CODEC_AV1 =MFX_MAKEFOURCC('A','V','1',' ')
};
/* CodecProfile, CodecLevel */
enum {
MFX_PROFILE_UNKNOWN =0,
MFX_LEVEL_UNKNOWN =0,
/* AVC Profiles & Levels */
MFX_PROFILE_AVC_CONSTRAINT_SET0 = (0x100 << 0),
MFX_PROFILE_AVC_CONSTRAINT_SET1 = (0x100 << 1),
MFX_PROFILE_AVC_CONSTRAINT_SET2 = (0x100 << 2),
MFX_PROFILE_AVC_CONSTRAINT_SET3 = (0x100 << 3),
MFX_PROFILE_AVC_CONSTRAINT_SET4 = (0x100 << 4),
MFX_PROFILE_AVC_CONSTRAINT_SET5 = (0x100 << 5),
MFX_PROFILE_AVC_BASELINE =66,
MFX_PROFILE_AVC_MAIN =77,
MFX_PROFILE_AVC_EXTENDED =88,
MFX_PROFILE_AVC_HIGH =100,
MFX_PROFILE_AVC_HIGH_422 =122,
MFX_PROFILE_AVC_CONSTRAINED_BASELINE =MFX_PROFILE_AVC_BASELINE + MFX_PROFILE_AVC_CONSTRAINT_SET1,
MFX_PROFILE_AVC_CONSTRAINED_HIGH =MFX_PROFILE_AVC_HIGH + MFX_PROFILE_AVC_CONSTRAINT_SET4
+ MFX_PROFILE_AVC_CONSTRAINT_SET5,
MFX_PROFILE_AVC_PROGRESSIVE_HIGH =MFX_PROFILE_AVC_HIGH + MFX_PROFILE_AVC_CONSTRAINT_SET4,
MFX_LEVEL_AVC_1 =10,
MFX_LEVEL_AVC_1b =9,
MFX_LEVEL_AVC_11 =11,
MFX_LEVEL_AVC_12 =12,
MFX_LEVEL_AVC_13 =13,
MFX_LEVEL_AVC_2 =20,
MFX_LEVEL_AVC_21 =21,
MFX_LEVEL_AVC_22 =22,
MFX_LEVEL_AVC_3 =30,
MFX_LEVEL_AVC_31 =31,
MFX_LEVEL_AVC_32 =32,
MFX_LEVEL_AVC_4 =40,
MFX_LEVEL_AVC_41 =41,
MFX_LEVEL_AVC_42 =42,
MFX_LEVEL_AVC_5 =50,
MFX_LEVEL_AVC_51 =51,
MFX_LEVEL_AVC_52 =52,
/* MPEG-2 Profiles & Levels */
MFX_PROFILE_MPEG2_SIMPLE =0x50,
MFX_PROFILE_MPEG2_MAIN =0x40,
MFX_PROFILE_MPEG2_HIGH =0x10,
MFX_LEVEL_MPEG2_LOW =0xA,
MFX_LEVEL_MPEG2_MAIN =0x8,
MFX_LEVEL_MPEG2_HIGH =0x4,
MFX_LEVEL_MPEG2_HIGH1440 =0x6,
/* VC1 Profiles & Levels */
MFX_PROFILE_VC1_SIMPLE =(0+1),
MFX_PROFILE_VC1_MAIN =(4+1),
MFX_PROFILE_VC1_ADVANCED =(12+1),
/* VC1 levels for simple & main profiles */
MFX_LEVEL_VC1_LOW =(0+1),
MFX_LEVEL_VC1_MEDIAN =(2+1),
MFX_LEVEL_VC1_HIGH =(4+1),
/* VC1 levels for the advanced profile */
MFX_LEVEL_VC1_0 =(0x00+1),
MFX_LEVEL_VC1_1 =(0x01+1),
MFX_LEVEL_VC1_2 =(0x02+1),
MFX_LEVEL_VC1_3 =(0x03+1),
MFX_LEVEL_VC1_4 =(0x04+1),
/* HEVC Profiles & Levels & Tiers */
MFX_PROFILE_HEVC_MAIN =1,
MFX_PROFILE_HEVC_MAIN10 =2,
MFX_PROFILE_HEVC_MAINSP =3,
MFX_PROFILE_HEVC_REXT =4,
MFX_LEVEL_HEVC_1 = 10,
MFX_LEVEL_HEVC_2 = 20,
MFX_LEVEL_HEVC_21 = 21,
MFX_LEVEL_HEVC_3 = 30,
MFX_LEVEL_HEVC_31 = 31,
MFX_LEVEL_HEVC_4 = 40,
MFX_LEVEL_HEVC_41 = 41,
MFX_LEVEL_HEVC_5 = 50,
MFX_LEVEL_HEVC_51 = 51,
MFX_LEVEL_HEVC_52 = 52,
MFX_LEVEL_HEVC_6 = 60,
MFX_LEVEL_HEVC_61 = 61,
MFX_LEVEL_HEVC_62 = 62,
MFX_TIER_HEVC_MAIN = 0,
MFX_TIER_HEVC_HIGH = 0x100,
/* VP9 Profiles */
MFX_PROFILE_VP9_0 = 1,
MFX_PROFILE_VP9_1 = 2,
MFX_PROFILE_VP9_2 = 3,
MFX_PROFILE_VP9_3 = 4,
};
/* GopOptFlag */
enum {
MFX_GOP_CLOSED =1,
MFX_GOP_STRICT =2
};
/* TargetUsages: from 1 to 7 inclusive */
enum {
MFX_TARGETUSAGE_1 =1,
MFX_TARGETUSAGE_2 =2,
MFX_TARGETUSAGE_3 =3,
MFX_TARGETUSAGE_4 =4,
MFX_TARGETUSAGE_5 =5,
MFX_TARGETUSAGE_6 =6,
MFX_TARGETUSAGE_7 =7,
MFX_TARGETUSAGE_UNKNOWN =0,
MFX_TARGETUSAGE_BEST_QUALITY =MFX_TARGETUSAGE_1,
MFX_TARGETUSAGE_BALANCED =MFX_TARGETUSAGE_4,
MFX_TARGETUSAGE_BEST_SPEED =MFX_TARGETUSAGE_7
};
/* RateControlMethod */
enum {
MFX_RATECONTROL_CBR =1,
MFX_RATECONTROL_VBR =2,
MFX_RATECONTROL_CQP =3,
MFX_RATECONTROL_AVBR =4,
MFX_RATECONTROL_RESERVED1 =5,
MFX_RATECONTROL_RESERVED2 =6,
MFX_RATECONTROL_RESERVED3 =100,
MFX_RATECONTROL_RESERVED4 =7,
MFX_RATECONTROL_LA =8,
MFX_RATECONTROL_ICQ =9,
MFX_RATECONTROL_VCM =10,
MFX_RATECONTROL_LA_ICQ =11,
MFX_RATECONTROL_LA_EXT =12,
MFX_RATECONTROL_LA_HRD =13,
MFX_RATECONTROL_QVBR =14,
};
/* Trellis control*/
enum {
MFX_TRELLIS_UNKNOWN =0,
MFX_TRELLIS_OFF =0x01,
MFX_TRELLIS_I =0x02,
MFX_TRELLIS_P =0x04,
MFX_TRELLIS_B =0x08
};
typedef struct {
mfxExtBuffer Header;
mfxU16 reserved1;
mfxU16 RateDistortionOpt; /* tri-state option */
mfxU16 MECostType;
mfxU16 MESearchType;
mfxI16Pair MVSearchWindow;
mfxU16 EndOfSequence; /* tri-state option */
mfxU16 FramePicture; /* tri-state option */
mfxU16 CAVLC; /* tri-state option */
mfxU16 reserved2[2];
mfxU16 RecoveryPointSEI; /* tri-state option */
mfxU16 ViewOutput; /* tri-state option */
mfxU16 NalHrdConformance; /* tri-state option */
mfxU16 SingleSeiNalUnit; /* tri-state option */
mfxU16 VuiVclHrdParameters; /* tri-state option */
mfxU16 RefPicListReordering; /* tri-state option */
mfxU16 ResetRefList; /* tri-state option */
mfxU16 RefPicMarkRep; /* tri-state option */
mfxU16 FieldOutput; /* tri-state option */
mfxU16 IntraPredBlockSize;
mfxU16 InterPredBlockSize;
mfxU16 MVPrecision;
mfxU16 MaxDecFrameBuffering;
mfxU16 AUDelimiter; /* tri-state option */
mfxU16 EndOfStream; /* tri-state option */
mfxU16 PicTimingSEI; /* tri-state option */
mfxU16 VuiNalHrdParameters; /* tri-state option */
} mfxExtCodingOption;
enum {
MFX_B_REF_UNKNOWN = 0,
MFX_B_REF_OFF = 1,
MFX_B_REF_PYRAMID = 2
};
enum {
MFX_LOOKAHEAD_DS_UNKNOWN = 0,
MFX_LOOKAHEAD_DS_OFF = 1,
MFX_LOOKAHEAD_DS_2x = 2,
MFX_LOOKAHEAD_DS_4x = 3
};
enum {
MFX_BPSEI_DEFAULT = 0x00,
MFX_BPSEI_IFRAME = 0x01
};
enum {
MFX_SKIPFRAME_NO_SKIP = 0,
MFX_SKIPFRAME_INSERT_DUMMY = 1,
MFX_SKIPFRAME_INSERT_NOTHING = 2,
MFX_SKIPFRAME_BRC_ONLY = 3,
};
/* Intra refresh types */
enum {
MFX_REFRESH_NO = 0,
MFX_REFRESH_VERTICAL = 1,
MFX_REFRESH_HORIZONTAL = 2,
MFX_REFRESH_SLICE = 3
};
typedef struct {
mfxExtBuffer Header;
mfxU16 IntRefType;
mfxU16 IntRefCycleSize;
mfxI16 IntRefQPDelta;
mfxU32 MaxFrameSize;
mfxU32 MaxSliceSize;
mfxU16 BitrateLimit; /* tri-state option */
mfxU16 MBBRC; /* tri-state option */
mfxU16 ExtBRC; /* tri-state option */
mfxU16 LookAheadDepth;
mfxU16 Trellis;
mfxU16 RepeatPPS; /* tri-state option */
mfxU16 BRefType;
mfxU16 AdaptiveI; /* tri-state option */
mfxU16 AdaptiveB; /* tri-state option */
mfxU16 LookAheadDS;
mfxU16 NumMbPerSlice;
mfxU16 SkipFrame;
mfxU8 MinQPI; /* 1..51, 0 = default */
mfxU8 MaxQPI; /* 1..51, 0 = default */
mfxU8 MinQPP; /* 1..51, 0 = default */
mfxU8 MaxQPP; /* 1..51, 0 = default */
mfxU8 MinQPB; /* 1..51, 0 = default */
mfxU8 MaxQPB; /* 1..51, 0 = default */
mfxU16 FixedFrameRate; /* tri-state option */
mfxU16 DisableDeblockingIdc;
mfxU16 DisableVUI;
mfxU16 BufferingPeriodSEI;
mfxU16 EnableMAD; /* tri-state option */
mfxU16 UseRawRef; /* tri-state option */
} mfxExtCodingOption2;
/* WeightedPred */
enum {
MFX_WEIGHTED_PRED_UNKNOWN = 0,
MFX_WEIGHTED_PRED_DEFAULT = 1,
MFX_WEIGHTED_PRED_EXPLICIT = 2,
MFX_WEIGHTED_PRED_IMPLICIT = 3
};
/* ScenarioInfo */
enum {
MFX_SCENARIO_UNKNOWN = 0,
MFX_SCENARIO_DISPLAY_REMOTING = 1,
MFX_SCENARIO_VIDEO_CONFERENCE = 2,
MFX_SCENARIO_ARCHIVE = 3,
MFX_SCENARIO_LIVE_STREAMING = 4,
MFX_SCENARIO_CAMERA_CAPTURE = 5
};
/* ContentInfo */
enum {
MFX_CONTENT_UNKNOWN = 0,
MFX_CONTENT_FULL_SCREEN_VIDEO = 1,
MFX_CONTENT_NON_VIDEO_SCREEN = 2
};
/* PRefType */
enum {
MFX_P_REF_DEFAULT = 0,
MFX_P_REF_SIMPLE = 1,
MFX_P_REF_PYRAMID = 2
};
typedef struct {
mfxExtBuffer Header;
mfxU16 NumSliceI;
mfxU16 NumSliceP;
mfxU16 NumSliceB;
mfxU16 WinBRCMaxAvgKbps;
mfxU16 WinBRCSize;
mfxU16 QVBRQuality;
mfxU16 EnableMBQP;
mfxU16 IntRefCycleDist;
mfxU16 DirectBiasAdjustment; /* tri-state option */
mfxU16 GlobalMotionBiasAdjustment; /* tri-state option */
mfxU16 MVCostScalingFactor;
mfxU16 MBDisableSkipMap; /* tri-state option */
mfxU16 WeightedPred;
mfxU16 WeightedBiPred;
mfxU16 AspectRatioInfoPresent; /* tri-state option */
mfxU16 OverscanInfoPresent; /* tri-state option */
mfxU16 OverscanAppropriate; /* tri-state option */
mfxU16 TimingInfoPresent; /* tri-state option */
mfxU16 BitstreamRestriction; /* tri-state option */
mfxU16 LowDelayHrd; /* tri-state option */
mfxU16 MotionVectorsOverPicBoundaries; /* tri-state option */
mfxU16 reserved1[2];
mfxU16 ScenarioInfo;
mfxU16 ContentInfo;
mfxU16 PRefType;
mfxU16 FadeDetection; /* tri-state option */
mfxU16 reserved2[2];
mfxU16 GPB; /* tri-state option */
mfxU32 MaxFrameSizeI;
mfxU32 MaxFrameSizeP;
mfxU32 reserved3[3];
mfxU16 EnableQPOffset; /* tri-state option */
mfxI16 QPOffset[8]; /* FrameQP = QPX + QPOffset[pyramid_layer]; QPX = QPB for B-pyramid, QPP for P-pyramid */
mfxU16 NumRefActiveP[8];
mfxU16 NumRefActiveBL0[8];
mfxU16 NumRefActiveBL1[8];
mfxU16 reserved6;
mfxU16 TransformSkip; /* tri-state option; HEVC transform_skip_enabled_flag */
mfxU16 TargetChromaFormatPlus1; /* Minus 1 specifies target encoding chroma format (see ColorFormat enum). May differ from input one. */
mfxU16 TargetBitDepthLuma; /* Target encoding bit depth for luma samples. May differ from input one. */
mfxU16 TargetBitDepthChroma; /* Target encoding bit depth for chroma samples. May differ from input one. */
mfxU16 BRCPanicMode; /* tri-state option */
mfxU16 LowDelayBRC; /* tri-state option */
mfxU16 EnableMBForceIntra; /* tri-state option */
mfxU16 AdaptiveMaxFrameSize; /* tri-state option */
mfxU16 RepartitionCheckEnable; /* tri-state option */
mfxU16 reserved5[3];
mfxU16 EncodedUnitsInfo; /* tri-state option */
mfxU16 EnableNalUnitType; /* tri-state option */
mfxU16 ExtBrcAdaptiveLTR; /* tri-state option for ExtBRC */
mfxU16 reserved[163];
} mfxExtCodingOption3;
/* IntraPredBlockSize/InterPredBlockSize */
enum {
MFX_BLOCKSIZE_UNKNOWN = 0,
MFX_BLOCKSIZE_MIN_16X16 = 1, /* 16x16 */
MFX_BLOCKSIZE_MIN_8X8 = 2, /* 16x16, 8x8 */
MFX_BLOCKSIZE_MIN_4X4 = 3 /* 16x16, 8x8, 4x4 */
};
/* MVPrecision */
enum {
MFX_MVPRECISION_UNKNOWN = 0,
MFX_MVPRECISION_INTEGER = (1 << 0),
MFX_MVPRECISION_HALFPEL = (1 << 1),
MFX_MVPRECISION_QUARTERPEL = (1 << 2)
};
enum {
MFX_CODINGOPTION_UNKNOWN =0,
MFX_CODINGOPTION_ON =0x10,
MFX_CODINGOPTION_OFF =0x20,
MFX_CODINGOPTION_ADAPTIVE =0x30
};
/* Data Flag for mfxBitstream*/
enum {
MFX_BITSTREAM_COMPLETE_FRAME = 0x0001, /* the bitstream contains a complete frame or field pair of data */
MFX_BITSTREAM_EOS = 0x0002
};
/* Extended Buffer Ids */
enum {
MFX_EXTBUFF_CODING_OPTION = MFX_MAKEFOURCC('C','D','O','P'),
MFX_EXTBUFF_CODING_OPTION_SPSPPS = MFX_MAKEFOURCC('C','O','S','P'),
MFX_EXTBUFF_VPP_DONOTUSE = MFX_MAKEFOURCC('N','U','S','E'),
MFX_EXTBUFF_VPP_AUXDATA = MFX_MAKEFOURCC('A','U','X','D'),
MFX_EXTBUFF_VPP_DENOISE = MFX_MAKEFOURCC('D','N','I','S'),
MFX_EXTBUFF_VPP_SCENE_ANALYSIS = MFX_MAKEFOURCC('S','C','L','Y'),
MFX_EXTBUFF_VPP_SCENE_CHANGE = MFX_EXTBUFF_VPP_SCENE_ANALYSIS,
MFX_EXTBUFF_VPP_PROCAMP = MFX_MAKEFOURCC('P','A','M','P'),
MFX_EXTBUFF_VPP_DETAIL = MFX_MAKEFOURCC('D','E','T',' '),
MFX_EXTBUFF_VIDEO_SIGNAL_INFO = MFX_MAKEFOURCC('V','S','I','N'),
MFX_EXTBUFF_VPP_DOUSE = MFX_MAKEFOURCC('D','U','S','E'),
MFX_EXTBUFF_OPAQUE_SURFACE_ALLOCATION = MFX_MAKEFOURCC('O','P','Q','S'),
MFX_EXTBUFF_AVC_REFLIST_CTRL = MFX_MAKEFOURCC('R','L','S','T'),
MFX_EXTBUFF_VPP_FRAME_RATE_CONVERSION = MFX_MAKEFOURCC('F','R','C',' '),
MFX_EXTBUFF_PICTURE_TIMING_SEI = MFX_MAKEFOURCC('P','T','S','E'),
MFX_EXTBUFF_AVC_TEMPORAL_LAYERS = MFX_MAKEFOURCC('A','T','M','L'),
MFX_EXTBUFF_CODING_OPTION2 = MFX_MAKEFOURCC('C','D','O','2'),
MFX_EXTBUFF_VPP_IMAGE_STABILIZATION = MFX_MAKEFOURCC('I','S','T','B'),
MFX_EXTBUFF_VPP_PICSTRUCT_DETECTION = MFX_MAKEFOURCC('I','D','E','T'),
MFX_EXTBUFF_ENCODER_CAPABILITY = MFX_MAKEFOURCC('E','N','C','P'),
MFX_EXTBUFF_ENCODER_RESET_OPTION = MFX_MAKEFOURCC('E','N','R','O'),
MFX_EXTBUFF_ENCODED_FRAME_INFO = MFX_MAKEFOURCC('E','N','F','I'),
MFX_EXTBUFF_VPP_COMPOSITE = MFX_MAKEFOURCC('V','C','M','P'),
MFX_EXTBUFF_VPP_VIDEO_SIGNAL_INFO = MFX_MAKEFOURCC('V','V','S','I'),
MFX_EXTBUFF_ENCODER_ROI = MFX_MAKEFOURCC('E','R','O','I'),
MFX_EXTBUFF_VPP_DEINTERLACING = MFX_MAKEFOURCC('V','P','D','I'),
MFX_EXTBUFF_AVC_REFLISTS = MFX_MAKEFOURCC('R','L','T','S'),
MFX_EXTBUFF_DEC_VIDEO_PROCESSING = MFX_MAKEFOURCC('D','E','C','V'),
MFX_EXTBUFF_VPP_FIELD_PROCESSING = MFX_MAKEFOURCC('F','P','R','O'),
MFX_EXTBUFF_CODING_OPTION3 = MFX_MAKEFOURCC('C','D','O','3'),
MFX_EXTBUFF_CHROMA_LOC_INFO = MFX_MAKEFOURCC('C','L','I','N'),
MFX_EXTBUFF_MBQP = MFX_MAKEFOURCC('M','B','Q','P'),
MFX_EXTBUFF_MB_FORCE_INTRA = MFX_MAKEFOURCC('M','B','F','I'),
MFX_EXTBUFF_HEVC_TILES = MFX_MAKEFOURCC('2','6','5','T'),
MFX_EXTBUFF_MB_DISABLE_SKIP_MAP = MFX_MAKEFOURCC('M','D','S','M'),
MFX_EXTBUFF_HEVC_PARAM = MFX_MAKEFOURCC('2','6','5','P'),
MFX_EXTBUFF_DECODED_FRAME_INFO = MFX_MAKEFOURCC('D','E','F','I'),
MFX_EXTBUFF_TIME_CODE = MFX_MAKEFOURCC('T','M','C','D'),
MFX_EXTBUFF_HEVC_REGION = MFX_MAKEFOURCC('2','6','5','R'),
MFX_EXTBUFF_PRED_WEIGHT_TABLE = MFX_MAKEFOURCC('E','P','W','T'),
MFX_EXTBUFF_DIRTY_RECTANGLES = MFX_MAKEFOURCC('D','R','O','I'),
MFX_EXTBUFF_MOVING_RECTANGLES = MFX_MAKEFOURCC('M','R','O','I'),
MFX_EXTBUFF_CODING_OPTION_VPS = MFX_MAKEFOURCC('C','O','V','P'),
MFX_EXTBUFF_VPP_ROTATION = MFX_MAKEFOURCC('R','O','T',' '),
MFX_EXTBUFF_ENCODED_SLICES_INFO = MFX_MAKEFOURCC('E','N','S','I'),
MFX_EXTBUFF_VPP_SCALING = MFX_MAKEFOURCC('V','S','C','L'),
MFX_EXTBUFF_HEVC_REFLIST_CTRL = MFX_EXTBUFF_AVC_REFLIST_CTRL,
MFX_EXTBUFF_HEVC_REFLISTS = MFX_EXTBUFF_AVC_REFLISTS,
MFX_EXTBUFF_HEVC_TEMPORAL_LAYERS = MFX_EXTBUFF_AVC_TEMPORAL_LAYERS,
MFX_EXTBUFF_VPP_MIRRORING = MFX_MAKEFOURCC('M','I','R','R'),
MFX_EXTBUFF_MV_OVER_PIC_BOUNDARIES = MFX_MAKEFOURCC('M','V','P','B'),
MFX_EXTBUFF_VPP_COLORFILL = MFX_MAKEFOURCC('V','C','L','F'),
MFX_EXTBUFF_DECODE_ERROR_REPORT = MFX_MAKEFOURCC('D', 'E', 'R', 'R'),
MFX_EXTBUFF_VPP_COLOR_CONVERSION = MFX_MAKEFOURCC('V', 'C', 'S', 'C'),
MFX_EXTBUFF_CONTENT_LIGHT_LEVEL_INFO = MFX_MAKEFOURCC('L', 'L', 'I', 'S'),
MFX_EXTBUFF_MASTERING_DISPLAY_COLOUR_VOLUME = MFX_MAKEFOURCC('D', 'C', 'V', 'S'),
MFX_EXTBUFF_MULTI_FRAME_PARAM = MFX_MAKEFOURCC('M', 'F', 'R', 'P'),
MFX_EXTBUFF_MULTI_FRAME_CONTROL = MFX_MAKEFOURCC('M', 'F', 'R', 'C'),
MFX_EXTBUFF_ENCODED_UNITS_INFO = MFX_MAKEFOURCC('E', 'N', 'U', 'I'),
MFX_EXTBUFF_VPP_MCTF = MFX_MAKEFOURCC('M', 'C', 'T', 'F'),
MFX_EXTBUFF_VP9_SEGMENTATION = MFX_MAKEFOURCC('9', 'S', 'E', 'G'),
MFX_EXTBUFF_VP9_TEMPORAL_LAYERS = MFX_MAKEFOURCC('9', 'T', 'M', 'L'),
MFX_EXTBUFF_VP9_PARAM = MFX_MAKEFOURCC('9', 'P', 'A', 'R'),
MFX_EXTBUFF_AVC_ROUNDING_OFFSET = MFX_MAKEFOURCC('R','N','D','O'),
};
/* VPP Conf: Do not use certain algorithms */
typedef struct {
mfxExtBuffer Header;
mfxU32 NumAlg;
mfxU32* AlgList;
} mfxExtVPPDoNotUse;
typedef struct {
mfxExtBuffer Header;
mfxU16 DenoiseFactor;
} mfxExtVPPDenoise;
typedef struct {
mfxExtBuffer Header;
mfxU16 DetailFactor;
} mfxExtVPPDetail;
typedef struct {
mfxExtBuffer Header;
mfxF64 Brightness;
mfxF64 Contrast;
mfxF64 Hue;
mfxF64 Saturation;
} mfxExtVPPProcAmp;
/* statistics collected for decode, encode and vpp */
typedef struct {
mfxU32 reserved[16];
mfxU32 NumFrame;
mfxU64 NumBit;
mfxU32 NumCachedFrame;
} mfxEncodeStat;
typedef struct {
mfxU32 reserved[16];
mfxU32 NumFrame;
mfxU32 NumSkippedFrame;
mfxU32 NumError;
mfxU32 NumCachedFrame;
} mfxDecodeStat;
typedef struct {
mfxU32 reserved[16];
mfxU32 NumFrame;
mfxU32 NumCachedFrame;
} mfxVPPStat;
typedef struct {
mfxExtBuffer Header;
union{
struct{
mfxU32 SpatialComplexity;
mfxU32 TemporalComplexity;
};
struct{
mfxU16 PicStruct;
mfxU16 reserved[3];
};
};
mfxU16 SceneChangeRate;
mfxU16 RepeatedFrame;
} mfxExtVppAuxData;
/* CtrlFlags */
enum {
MFX_PAYLOAD_CTRL_SUFFIX = 0x00000001 /* HEVC suffix SEI */
};
typedef struct {
mfxU32 CtrlFlags;
mfxU32 reserved[3];
mfxU8 *Data; /* buffer pointer */
mfxU32 NumBit; /* number of bits */
mfxU16 Type; /* SEI message type in H.264 or user data start_code in MPEG-2 */
mfxU16 BufSize; /* payload buffer size in bytes */
} mfxPayload;
typedef struct {
mfxExtBuffer Header;
mfxU32 reserved[4];
mfxU16 reserved1;
mfxU16 MfxNalUnitType;
mfxU16 SkipFrame;
mfxU16 QP; /* per frame QP */
mfxU16 FrameType;
mfxU16 NumExtParam;
mfxU16 NumPayload; /* MPEG-2 user data or H.264 SEI message(s) */
mfxU16 reserved2;
mfxExtBuffer **ExtParam;
mfxPayload **Payload; /* for field pair, first field uses even payloads and second field uses odd payloads */
} mfxEncodeCtrl;
/* Buffer Memory Types */
enum {
/* Buffer types */
MFX_MEMTYPE_PERSISTENT_MEMORY =0x0002
};
/* Frame Memory Types */
#define MFX_MEMTYPE_BASE(x) (0x90ff & (x))
enum {
MFX_MEMTYPE_DXVA2_DECODER_TARGET =0x0010,
MFX_MEMTYPE_DXVA2_PROCESSOR_TARGET =0x0020,
MFX_MEMTYPE_VIDEO_MEMORY_DECODER_TARGET = MFX_MEMTYPE_DXVA2_DECODER_TARGET,
MFX_MEMTYPE_VIDEO_MEMORY_PROCESSOR_TARGET = MFX_MEMTYPE_DXVA2_PROCESSOR_TARGET,
MFX_MEMTYPE_SYSTEM_MEMORY =0x0040,
MFX_MEMTYPE_RESERVED1 =0x0080,
MFX_MEMTYPE_FROM_ENCODE = 0x0100,
MFX_MEMTYPE_FROM_DECODE = 0x0200,
MFX_MEMTYPE_FROM_VPPIN = 0x0400,
MFX_MEMTYPE_FROM_VPPOUT = 0x0800,
MFX_MEMTYPE_FROM_ENC = 0x2000,
MFX_MEMTYPE_FROM_PAK = 0x4000, //reserved
MFX_MEMTYPE_INTERNAL_FRAME = 0x0001,
MFX_MEMTYPE_EXTERNAL_FRAME = 0x0002,
MFX_MEMTYPE_OPAQUE_FRAME = 0x0004,
MFX_MEMTYPE_EXPORT_FRAME = 0x0008,
MFX_MEMTYPE_SHARED_RESOURCE = MFX_MEMTYPE_EXPORT_FRAME,
MFX_MEMTYPE_VIDEO_MEMORY_ENCODER_TARGET = 0x1000
};
typedef struct {
union {
mfxU32 AllocId;
mfxU32 reserved[1];
};
mfxU32 reserved3[3];
mfxFrameInfo Info;
mfxU16 Type; /* decoder or processor render targets */
mfxU16 NumFrameMin;
mfxU16 NumFrameSuggested;
mfxU16 reserved2;
} mfxFrameAllocRequest;
typedef struct {
mfxU32 AllocId;
mfxU32 reserved[3];
mfxMemId *mids; /* the array allocated by application */
mfxU16 NumFrameActual;
mfxU16 reserved2;
} mfxFrameAllocResponse;
/* FrameType */
enum {
MFX_FRAMETYPE_UNKNOWN =0x0000,
MFX_FRAMETYPE_I =0x0001,
MFX_FRAMETYPE_P =0x0002,
MFX_FRAMETYPE_B =0x0004,
MFX_FRAMETYPE_S =0x0008,
MFX_FRAMETYPE_REF =0x0040,
MFX_FRAMETYPE_IDR =0x0080,
MFX_FRAMETYPE_xI =0x0100,
MFX_FRAMETYPE_xP =0x0200,
MFX_FRAMETYPE_xB =0x0400,
MFX_FRAMETYPE_xS =0x0800,
MFX_FRAMETYPE_xREF =0x4000,
MFX_FRAMETYPE_xIDR =0x8000
};
enum {
MFX_HEVC_NALU_TYPE_UNKNOWN = 0,
MFX_HEVC_NALU_TYPE_TRAIL_N = ( 0+1),
MFX_HEVC_NALU_TYPE_TRAIL_R = ( 1+1),
MFX_HEVC_NALU_TYPE_RADL_N = ( 6+1),
MFX_HEVC_NALU_TYPE_RADL_R = ( 7+1),
MFX_HEVC_NALU_TYPE_RASL_N = ( 8+1),
MFX_HEVC_NALU_TYPE_RASL_R = ( 9+1),
MFX_HEVC_NALU_TYPE_IDR_W_RADL = (19+1),
MFX_HEVC_NALU_TYPE_IDR_N_LP = (20+1),
MFX_HEVC_NALU_TYPE_CRA_NUT = (21+1)
};
typedef enum {
MFX_HANDLE_DIRECT3D_DEVICE_MANAGER9 =1, /* IDirect3DDeviceManager9 */
MFX_HANDLE_D3D9_DEVICE_MANAGER = MFX_HANDLE_DIRECT3D_DEVICE_MANAGER9,
MFX_HANDLE_RESERVED1 = 2,
MFX_HANDLE_D3D11_DEVICE = 3,
MFX_HANDLE_VA_DISPLAY = 4,
MFX_HANDLE_RESERVED3 = 5,
} mfxHandleType;
typedef enum {
MFX_SKIPMODE_NOSKIP=0,
MFX_SKIPMODE_MORE=1,
MFX_SKIPMODE_LESS=2
} mfxSkipMode;
typedef struct {
mfxExtBuffer Header;
mfxU8 *SPSBuffer;
mfxU8 *PPSBuffer;
mfxU16 SPSBufSize;
mfxU16 PPSBufSize;
mfxU16 SPSId;
mfxU16 PPSId;
} mfxExtCodingOptionSPSPPS;
typedef struct {
mfxExtBuffer Header;
union {
mfxU8 *VPSBuffer;
mfxU64 reserved1;
};
mfxU16 VPSBufSize;
mfxU16 VPSId;
mfxU16 reserved[6];
} mfxExtCodingOptionVPS;
typedef struct {
mfxExtBuffer Header;
mfxU16 VideoFormat;
mfxU16 VideoFullRange;
mfxU16 ColourDescriptionPresent;
mfxU16 ColourPrimaries;
mfxU16 TransferCharacteristics;
mfxU16 MatrixCoefficients;
} mfxExtVideoSignalInfo;
typedef struct {
mfxExtBuffer Header;
mfxU32 NumAlg;
mfxU32 *AlgList;
} mfxExtVPPDoUse;
typedef struct {
mfxExtBuffer Header;
mfxU32 reserved1[2];
struct {
mfxFrameSurface1 **Surfaces;
mfxU32 reserved2[5];
mfxU16 Type;
mfxU16 NumSurface;
} In, Out;
} mfxExtOpaqueSurfaceAlloc;
typedef struct {
mfxExtBuffer Header;
mfxU16 NumRefIdxL0Active;
mfxU16 NumRefIdxL1Active;
struct {
mfxU32 FrameOrder;
mfxU16 PicStruct;
mfxU16 ViewId;
mfxU16 LongTermIdx;
mfxU16 reserved[3];
} PreferredRefList[32], RejectedRefList[16], LongTermRefList[16];
mfxU16 ApplyLongTermIdx;
mfxU16 reserved[15];
} mfxExtAVCRefListCtrl;
enum {
MFX_FRCALGM_PRESERVE_TIMESTAMP = 0x0001,
MFX_FRCALGM_DISTRIBUTED_TIMESTAMP = 0x0002,
MFX_FRCALGM_FRAME_INTERPOLATION = 0x0004
};
typedef struct {
mfxExtBuffer Header;
mfxU16 Algorithm;
mfxU16 reserved;
mfxU32 reserved2[15];
} mfxExtVPPFrameRateConversion;
enum {
MFX_IMAGESTAB_MODE_UPSCALE = 0x0001,
MFX_IMAGESTAB_MODE_BOXING = 0x0002
};
typedef struct {
mfxExtBuffer Header;
mfxU16 Mode;
mfxU16 reserved[11];
} mfxExtVPPImageStab;
enum {
MFX_PAYLOAD_OFF = 0,
MFX_PAYLOAD_IDR = 1
};
typedef struct {
mfxExtBuffer Header;
mfxU16 reserved[15];
mfxU16 InsertPayloadToggle;
mfxU16 DisplayPrimariesX[3];
mfxU16 DisplayPrimariesY[3];
mfxU16 WhitePointX;
mfxU16 WhitePointY;
mfxU32 MaxDisplayMasteringLuminance;
mfxU32 MinDisplayMasteringLuminance;
} mfxExtMasteringDisplayColourVolume;
typedef struct {
mfxExtBuffer Header;
mfxU16 reserved[9];
mfxU16 InsertPayloadToggle;
mfxU16 MaxContentLightLevel;
mfxU16 MaxPicAverageLightLevel;
} mfxExtContentLightLevelInfo;
typedef struct {
mfxExtBuffer Header;
mfxU32 reserved[14];
struct {
mfxU16 ClockTimestampFlag;
mfxU16 CtType;
mfxU16 NuitFieldBasedFlag;
mfxU16 CountingType;
mfxU16 FullTimestampFlag;
mfxU16 DiscontinuityFlag;
mfxU16 CntDroppedFlag;
mfxU16 NFrames;
mfxU16 SecondsFlag;
mfxU16 MinutesFlag;
mfxU16 HoursFlag;
mfxU16 SecondsValue;
mfxU16 MinutesValue;
mfxU16 HoursValue;
mfxU32 TimeOffset;
} TimeStamp[3];
} mfxExtPictureTimingSEI;
typedef struct {
mfxExtBuffer Header;
mfxU32 reserved1[4];
mfxU16 reserved2;
mfxU16 BaseLayerPID;
struct {
mfxU16 Scale;
mfxU16 reserved[3];
}Layer[8];
} mfxExtAvcTemporalLayers;
typedef struct {
mfxExtBuffer Header;
mfxU32 MBPerSec;
mfxU16 reserved[58];
} mfxExtEncoderCapability;
typedef struct {
mfxExtBuffer Header;
mfxU16 StartNewSequence;
mfxU16 reserved[11];
} mfxExtEncoderResetOption;
/*LongTermIdx*/
enum {
MFX_LONGTERM_IDX_NO_IDX = 0xFFFF
};
typedef struct {
mfxExtBuffer Header;
mfxU32 FrameOrder;
mfxU16 PicStruct;
mfxU16 LongTermIdx;
mfxU32 MAD;
mfxU16 BRCPanicMode;
mfxU16 QP;
mfxU32 SecondFieldOffset;
mfxU16 reserved[2];
struct {
mfxU32 FrameOrder;
mfxU16 PicStruct;
mfxU16 LongTermIdx;
mfxU16 reserved[4];
} UsedRefListL0[32], UsedRefListL1[32];
} mfxExtAVCEncodedFrameInfo;
typedef struct mfxVPPCompInputStream {
mfxU32 DstX;
mfxU32 DstY;
mfxU32 DstW;
mfxU32 DstH;
mfxU16 LumaKeyEnable;
mfxU16 LumaKeyMin;
mfxU16 LumaKeyMax;
mfxU16 GlobalAlphaEnable;
mfxU16 GlobalAlpha;
mfxU16 PixelAlphaEnable;
mfxU16 TileId;
mfxU16 reserved2[17];
} mfxVPPCompInputStream;
typedef struct {
mfxExtBuffer Header;
/* background color*/
union {
mfxU16 Y;
mfxU16 R;
};
union {
mfxU16 U;
mfxU16 G;
};
union {
mfxU16 V;
mfxU16 B;
};
mfxU16 NumTiles;
mfxU16 reserved1[23];
mfxU16 NumInputStream;
mfxVPPCompInputStream *InputStream;
} mfxExtVPPComposite;
/* TransferMatrix */
enum {
MFX_TRANSFERMATRIX_UNKNOWN = 0,
MFX_TRANSFERMATRIX_BT709 = 1,
MFX_TRANSFERMATRIX_BT601 = 2
};
/* NominalRange */
enum {
MFX_NOMINALRANGE_UNKNOWN = 0,
MFX_NOMINALRANGE_0_255 = 1,
MFX_NOMINALRANGE_16_235 = 2
};
typedef struct {
mfxExtBuffer Header;
mfxU16 reserved1[4];
union {
struct { // Init
struct {
mfxU16 TransferMatrix;
mfxU16 NominalRange;
mfxU16 reserved2[6];
} In, Out;
};
struct { // Runtime
mfxU16 TransferMatrix;
mfxU16 NominalRange;
mfxU16 reserved3[14];
};
};
} mfxExtVPPVideoSignalInfo;
/* ROI encoding mode */
enum {
MFX_ROI_MODE_PRIORITY = 0,
MFX_ROI_MODE_QP_DELTA = 1
};
typedef struct {
mfxExtBuffer Header;
mfxU16 NumROI;
mfxU16 ROIMode;
mfxU16 reserved1[10];
struct {
mfxU32 Left;
mfxU32 Top;
mfxU32 Right;
mfxU32 Bottom;
union {
mfxI16 Priority;
mfxI16 DeltaQP;
};
mfxU16 reserved2[7];
} ROI[256];
} mfxExtEncoderROI;
/*Deinterlacing Mode*/
enum {
MFX_DEINTERLACING_BOB = 1,
MFX_DEINTERLACING_ADVANCED = 2,
MFX_DEINTERLACING_AUTO_DOUBLE = 3,
MFX_DEINTERLACING_AUTO_SINGLE = 4,
MFX_DEINTERLACING_FULL_FR_OUT = 5,
MFX_DEINTERLACING_HALF_FR_OUT = 6,
MFX_DEINTERLACING_24FPS_OUT = 7,
MFX_DEINTERLACING_FIXED_TELECINE_PATTERN = 8,
MFX_DEINTERLACING_30FPS_OUT = 9,
MFX_DEINTERLACING_DETECT_INTERLACE = 10,
MFX_DEINTERLACING_ADVANCED_NOREF = 11,
MFX_DEINTERLACING_ADVANCED_SCD = 12,
MFX_DEINTERLACING_FIELD_WEAVING = 13
};
/*TelecinePattern*/
enum {
MFX_TELECINE_PATTERN_32 = 0,
MFX_TELECINE_PATTERN_2332 = 1,
MFX_TELECINE_PATTERN_FRAME_REPEAT = 2,
MFX_TELECINE_PATTERN_41 = 3,
MFX_TELECINE_POSITION_PROVIDED = 4
};
typedef struct {
mfxExtBuffer Header;
mfxU16 Mode;
mfxU16 TelecinePattern;
mfxU16 TelecineLocation;
mfxU16 reserved[9];
} mfxExtVPPDeinterlacing;
typedef struct {
mfxExtBuffer Header;
mfxU16 NumRefIdxL0Active;
mfxU16 NumRefIdxL1Active;
mfxU16 reserved[2];
struct mfxRefPic{
mfxU32 FrameOrder;
mfxU16 PicStruct;
mfxU16 reserved[5];
} RefPicList0[32], RefPicList1[32];
}mfxExtAVCRefLists;
enum {
MFX_VPP_COPY_FRAME =0x01,
MFX_VPP_COPY_FIELD =0x02,
MFX_VPP_SWAP_FIELDS =0x03
};
/*PicType*/
enum {
MFX_PICTYPE_UNKNOWN =0x00,
MFX_PICTYPE_FRAME =0x01,
MFX_PICTYPE_TOPFIELD =0x02,
MFX_PICTYPE_BOTTOMFIELD =0x04
};
typedef struct {
mfxExtBuffer Header;
mfxU16 Mode;
mfxU16 InField;
mfxU16 OutField;
mfxU16 reserved[25];
} mfxExtVPPFieldProcessing;
typedef struct {
mfxExtBuffer Header;
struct mfxIn{
mfxU16 CropX;
mfxU16 CropY;
mfxU16 CropW;
mfxU16 CropH;
mfxU16 reserved[12];
}In;
struct mfxOut{
mfxU32 FourCC;
mfxU16 ChromaFormat;
mfxU16 reserved1;
mfxU16 Width;
mfxU16 Height;
mfxU16 CropX;
mfxU16 CropY;
mfxU16 CropW;
mfxU16 CropH;
mfxU16 reserved[22];
}Out;
mfxU16 reserved[13];
} mfxExtDecVideoProcessing;
typedef struct {
mfxExtBuffer Header;
mfxU16 ChromaLocInfoPresentFlag;
mfxU16 ChromaSampleLocTypeTopField;
mfxU16 ChromaSampleLocTypeBottomField;
mfxU16 reserved[9];
} mfxExtChromaLocInfo;
/* MBQPMode */
enum {
MFX_MBQP_MODE_QP_VALUE = 0, // supported in CQP mode only
MFX_MBQP_MODE_QP_DELTA = 1
};
typedef struct {
mfxExtBuffer Header;
mfxU32 reserved[10];
mfxU16 Mode; // see MBQPMode enum
mfxU16 BlockSize; // QP block size, valid for HEVC only during Init and Runtime
mfxU32 NumQPAlloc; // Size of allocated by application QP or DeltaQP array
union {
mfxU8 *QP; // Block QP value. Valid when Mode = MFX_MBQP_MODE_QP_VALUE
mfxI8 *DeltaQP; // For block i: QP[i] = BrcQP[i] + DeltaQP[i]. Valid when Mode = MFX_MBQP_MODE_QP_DELTA
mfxU64 reserved2;
};
} mfxExtMBQP;
typedef struct {
mfxExtBuffer Header;
mfxU32 reserved[11];
mfxU32 MapSize;
union {
mfxU8 *Map;
mfxU64 reserved2;
};
} mfxExtMBForceIntra;
typedef struct {
mfxExtBuffer Header;
mfxU16 NumTileRows;
mfxU16 NumTileColumns;
mfxU16 reserved[74];
}mfxExtHEVCTiles;
typedef struct {
mfxExtBuffer Header;
mfxU32 reserved[11];
mfxU32 MapSize;
union {
mfxU8 *Map;
mfxU64 reserved2;
};
} mfxExtMBDisableSkipMap;
/*GeneralConstraintFlags*/
enum {
/* REXT Profile constraint flags*/
MFX_HEVC_CONSTR_REXT_MAX_12BIT = (1 << 0),
MFX_HEVC_CONSTR_REXT_MAX_10BIT = (1 << 1),
MFX_HEVC_CONSTR_REXT_MAX_8BIT = (1 << 2),
MFX_HEVC_CONSTR_REXT_MAX_422CHROMA = (1 << 3),
MFX_HEVC_CONSTR_REXT_MAX_420CHROMA = (1 << 4),
MFX_HEVC_CONSTR_REXT_MAX_MONOCHROME = (1 << 5),
MFX_HEVC_CONSTR_REXT_INTRA = (1 << 6),
MFX_HEVC_CONSTR_REXT_ONE_PICTURE_ONLY = (1 << 7),
MFX_HEVC_CONSTR_REXT_LOWER_BIT_RATE = (1 << 8)
};
/* SampleAdaptiveOffset */
enum {
MFX_SAO_UNKNOWN = 0x00,
MFX_SAO_DISABLE = 0x01,
MFX_SAO_ENABLE_LUMA = 0x02,
MFX_SAO_ENABLE_CHROMA = 0x04
};
#pragma pack(push, 4)
typedef struct {
mfxExtBuffer Header;
mfxU16 PicWidthInLumaSamples;
mfxU16 PicHeightInLumaSamples;
mfxU64 GeneralConstraintFlags;
mfxU16 SampleAdaptiveOffset; /* see enum SampleAdaptiveOffset, valid during Init and Runtime */
mfxU16 LCUSize;
mfxU16 reserved[116];
} mfxExtHEVCParam;
#pragma pack(pop)
/*ErrorTypes in mfxExtDecodeErrorReport*/
enum {
MFX_ERROR_PPS = (1 << 0),
MFX_ERROR_SPS = (1 << 1),
MFX_ERROR_SLICEHEADER = (1 << 2),
MFX_ERROR_SLICEDATA = (1 << 3),
MFX_ERROR_FRAME_GAP = (1 << 4),
};
typedef struct {
mfxExtBuffer Header;
mfxU32 ErrorTypes;
mfxU16 reserved[10];
} mfxExtDecodeErrorReport;
typedef struct {
mfxExtBuffer Header;
mfxU16 FrameType;
mfxU16 reserved[59];
} mfxExtDecodedFrameInfo;
typedef struct {
mfxExtBuffer Header;
mfxU16 DropFrameFlag;
mfxU16 TimeCodeHours;
mfxU16 TimeCodeMinutes;
mfxU16 TimeCodeSeconds;
mfxU16 TimeCodePictures;
mfxU16 reserved[7];
} mfxExtTimeCode;
/*RegionType*/
enum {
MFX_HEVC_REGION_SLICE = 0
};
/*RegionEncoding*/
enum {
MFX_HEVC_REGION_ENCODING_ON = 0,
MFX_HEVC_REGION_ENCODING_OFF = 1
};
typedef struct {
mfxExtBuffer Header;
mfxU32 RegionId;
mfxU16 RegionType;
mfxU16 RegionEncoding;
mfxU16 reserved[24];
} mfxExtHEVCRegion;
typedef struct {
mfxExtBuffer Header;
mfxU16 LumaLog2WeightDenom; // 0..7
mfxU16 ChromaLog2WeightDenom; // 0..7
mfxU16 LumaWeightFlag[2][32]; // [list] 0,1
mfxU16 ChromaWeightFlag[2][32]; // [list] 0,1
mfxI16 Weights[2][32][3][2]; // [list][list entry][Y, Cb, Cr][weight, offset]
mfxU16 reserved[58];
} mfxExtPredWeightTable;
typedef struct {
mfxExtBuffer Header;
mfxU16 EnableRoundingIntra; // tri-state option
mfxU16 RoundingOffsetIntra; // valid value [0,7]
mfxU16 EnableRoundingInter; // tri-state option
mfxU16 RoundingOffsetInter; // valid value [0,7]
mfxU16 reserved[24];
} mfxExtAVCRoundingOffset;
typedef struct {
mfxExtBuffer Header;
mfxU16 NumRect;
mfxU16 reserved1[11];
struct {
mfxU32 Left;
mfxU32 Top;
mfxU32 Right;
mfxU32 Bottom;
mfxU16 reserved2[8];
} Rect[256];
} mfxExtDirtyRect;
typedef struct {
mfxExtBuffer Header;
mfxU16 NumRect;
mfxU16 reserved1[11];
struct {
mfxU32 DestLeft;
mfxU32 DestTop;
mfxU32 DestRight;
mfxU32 DestBottom;
mfxU32 SourceLeft;
mfxU32 SourceTop;
mfxU16 reserved2[4];
} Rect[256];
} mfxExtMoveRect;
/* Angle */
enum {
MFX_ANGLE_0 = 0,
MFX_ANGLE_90 = 90,
MFX_ANGLE_180 = 180,
MFX_ANGLE_270 = 270
};
typedef struct {
mfxExtBuffer Header;
mfxU16 Angle;
mfxU16 reserved[11];
} mfxExtVPPRotation;
typedef struct {
mfxExtBuffer Header;
mfxU16 SliceSizeOverflow;
mfxU16 NumSliceNonCopliant;
mfxU16 NumEncodedSlice;
mfxU16 NumSliceSizeAlloc;
union {
mfxU16 *SliceSize;
mfxU64 reserved1;
};
mfxU16 reserved[20];
} mfxExtEncodedSlicesInfo;
/* ScalingMode */
enum {
MFX_SCALING_MODE_DEFAULT = 0,
MFX_SCALING_MODE_LOWPOWER = 1,
MFX_SCALING_MODE_QUALITY = 2
};
typedef struct {
mfxExtBuffer Header;
mfxU16 ScalingMode;
mfxU16 reserved[11];
} mfxExtVPPScaling;
typedef mfxExtAVCRefListCtrl mfxExtHEVCRefListCtrl;
typedef mfxExtAVCRefLists mfxExtHEVCRefLists;
typedef mfxExtAvcTemporalLayers mfxExtHEVCTemporalLayers;
/* MirroringType */
enum
{
MFX_MIRRORING_DISABLED = 0,
MFX_MIRRORING_HORIZONTAL = 1,
MFX_MIRRORING_VERTICAL = 2
};
typedef struct {
mfxExtBuffer Header;
mfxU16 Type;
mfxU16 reserved[11];
} mfxExtVPPMirroring;
typedef struct {
mfxExtBuffer Header;
mfxU16 StickTop; /* tri-state option */
mfxU16 StickBottom; /* tri-state option */
mfxU16 StickLeft; /* tri-state option */
mfxU16 StickRight; /* tri-state option */
mfxU16 reserved[8];
} mfxExtMVOverPicBoundaries;
typedef struct {
mfxExtBuffer Header;
mfxU16 Enable; /* tri-state option */
mfxU16 reserved[11];
} mfxExtVPPColorFill;
/* ChromaSiting */
enum {
MFX_CHROMA_SITING_UNKNOWN = 0x0000,
MFX_CHROMA_SITING_VERTICAL_TOP = 0x0001, /* Chroma samples are co-sited vertically on the top with the luma samples. */
MFX_CHROMA_SITING_VERTICAL_CENTER = 0x0002, /* Chroma samples are not co-sited vertically with the luma samples. */
MFX_CHROMA_SITING_VERTICAL_BOTTOM = 0x0004, /* Chroma samples are co-sited vertically on the bottom with the luma samples. */
MFX_CHROMA_SITING_HORIZONTAL_LEFT = 0x0010, /* Chroma samples are co-sited horizontally on the left with the luma samples. */
MFX_CHROMA_SITING_HORIZONTAL_CENTER = 0x0020 /* Chroma samples are not co-sited horizontally with the luma samples. */
};
typedef struct {
mfxExtBuffer Header;
mfxU16 ChromaSiting;
mfxU16 reserved[27];
} mfxExtColorConversion;
/* VP9ReferenceFrame */
enum {
MFX_VP9_REF_INTRA = 0,
MFX_VP9_REF_LAST = 1,
MFX_VP9_REF_GOLDEN = 2,
MFX_VP9_REF_ALTREF = 3
};
/* SegmentIdBlockSize */
enum {
MFX_VP9_SEGMENT_ID_BLOCK_SIZE_UNKNOWN = 0,
MFX_VP9_SEGMENT_ID_BLOCK_SIZE_8x8 = 8,
MFX_VP9_SEGMENT_ID_BLOCK_SIZE_16x16 = 16,
MFX_VP9_SEGMENT_ID_BLOCK_SIZE_32x32 = 32,
MFX_VP9_SEGMENT_ID_BLOCK_SIZE_64x64 = 64,
};
/* SegmentFeature */
enum {
MFX_VP9_SEGMENT_FEATURE_QINDEX = 0x0001,
MFX_VP9_SEGMENT_FEATURE_LOOP_FILTER = 0x0002,
MFX_VP9_SEGMENT_FEATURE_REFERENCE = 0x0004,
MFX_VP9_SEGMENT_FEATURE_SKIP = 0x0008 /* (0,0) MV, no residual */
};
typedef struct {
mfxU16 FeatureEnabled; /* see enum SegmentFeature */
mfxI16 QIndexDelta;
mfxI16 LoopFilterLevelDelta;
mfxU16 ReferenceFrame; /* see enum VP9ReferenceFrame */
mfxU16 reserved[12];
} mfxVP9SegmentParam;
typedef struct {
mfxExtBuffer Header;
mfxU16 NumSegments; /* 0..8 */
mfxVP9SegmentParam Segment[8];
mfxU16 SegmentIdBlockSize; /* see enum SegmentIdBlockSize */
mfxU32 NumSegmentIdAlloc; /* >= (Ceil(Width / SegmentIdBlockSize) * Ceil(Height / SegmentIdBlockSize)) */
union {
mfxU8 *SegmentId; /*[NumSegmentIdAlloc] = 0..7, index in Segment array, blocks of SegmentIdBlockSize map */
mfxU64 reserved1;
};
mfxU16 reserved[52];
} mfxExtVP9Segmentation;
typedef struct {
mfxU16 FrameRateScale; /* Layer[n].FrameRateScale = Layer[n - 1].FrameRateScale * (uint)m */
mfxU16 TargetKbps; /* affected by BRCParamMultiplier, Layer[n].TargetKbps > Layer[n - 1].TargetKbps */
mfxU16 reserved[14];
} mfxVP9TemporalLayer;
typedef struct {
mfxExtBuffer Header;
mfxVP9TemporalLayer Layer[8];
mfxU16 reserved[60];
} mfxExtVP9TemporalLayers;
typedef struct {
mfxExtBuffer Header;
mfxU16 FrameWidth;
mfxU16 FrameHeight;
mfxU16 WriteIVFHeaders; /* tri-state option */
mfxI16 reserved1[6];
mfxI16 QIndexDeltaLumaDC;
mfxI16 QIndexDeltaChromaAC;
mfxI16 QIndexDeltaChromaDC;
mfxU16 reserved[112];
} mfxExtVP9Param;
/* Multi-Frame Mode */
enum {
MFX_MF_DEFAULT = 0,
MFX_MF_DISABLED = 1,
MFX_MF_AUTO = 2,
MFX_MF_MANUAL = 3
};
/* Multi-Frame Initialization parameters */
typedef struct {
mfxExtBuffer Header;
mfxU16 MFMode;
mfxU16 MaxNumFrames;
mfxU16 reserved[58];
} mfxExtMultiFrameParam;
/* Multi-Frame Run-time controls */
typedef struct {
mfxExtBuffer Header;
mfxU32 Timeout; /* timeout in millisecond */
mfxU16 Flush; /* Flush internal frame buffer, e.g. submit all collected frames. */
mfxU16 reserved[57];
} mfxExtMultiFrameControl;
typedef struct {
mfxU16 Type;
mfxU16 reserved1;
mfxU32 Offset;
mfxU32 Size;
mfxU32 reserved[5];
} mfxEncodedUnitInfo;
typedef struct {
mfxExtBuffer Header;
union {
mfxEncodedUnitInfo *UnitInfo;
mfxU64 reserved1;
};
mfxU16 NumUnitsAlloc;
mfxU16 NumUnitsEncoded;
mfxU16 reserved[22];
} mfxExtEncodedUnitsInfo;
/* MCTF initialization & runtime */
typedef struct {
mfxExtBuffer Header;
mfxU16 FilterStrength;
mfxU16 reserved[27];
} mfxExtVppMctf;
#ifdef __cplusplus
} // extern "C"
#endif
#endif
| 55,070
|
C++
|
.h
| 1,572
| 30.071247
| 147
| 0.590038
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,509
|
mfxdefs.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/decoders/mvc/include/mfxdefs.h
|
/* ****************************************************************************** *\
Copyright (C) 2007-2018 Intel Corporation. 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 Intel Corporation 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 INTEL CORPORATION "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 INTEL CORPORATION 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.
File Name: mfxdefs.h
\* ****************************************************************************** */
#ifndef __MFXDEFS_H__
#define __MFXDEFS_H__
#define MFX_VERSION_MAJOR 1
#define MFX_VERSION_MINOR 27
#define MFX_VERSION_NEXT 1028
#ifndef MFX_VERSION
#define MFX_VERSION (MFX_VERSION_MAJOR * 1000 + MFX_VERSION_MINOR)
#endif
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
#if (defined( _WIN32 ) || defined ( _WIN64 )) && !defined (__GNUC__)
#define __INT64 __int64
#define __UINT64 unsigned __int64
#else
#define __INT64 long long
#define __UINT64 unsigned long long
#endif
#ifdef _WIN32
#define MFX_CDECL __cdecl
#define MFX_STDCALL __stdcall
#else
#define MFX_CDECL
#define MFX_STDCALL
#endif /* _WIN32 */
#define MFX_INFINITE 0xFFFFFFFF
typedef unsigned char mfxU8;
typedef char mfxI8;
typedef short mfxI16;
typedef unsigned short mfxU16;
typedef unsigned int mfxU32;
typedef int mfxI32;
#if defined( _WIN32 ) || defined ( _WIN64 )
typedef unsigned long mfxUL32;
typedef long mfxL32;
#else
typedef unsigned int mfxUL32;
typedef int mfxL32;
#endif
typedef float mfxF32;
typedef double mfxF64;
typedef __UINT64 mfxU64;
typedef __INT64 mfxI64;
typedef void* mfxHDL;
typedef mfxHDL mfxMemId;
typedef void* mfxThreadTask;
typedef char mfxChar;
typedef struct {
mfxI16 x;
mfxI16 y;
} mfxI16Pair;
typedef struct {
mfxHDL first;
mfxHDL second;
} mfxHDLPair;
/*********************************************************************************\
Error message
\*********************************************************************************/
typedef enum
{
/* no error */
MFX_ERR_NONE = 0, /* no error */
/* reserved for unexpected errors */
MFX_ERR_UNKNOWN = -1, /* unknown error. */
/* error codes <0 */
MFX_ERR_NULL_PTR = -2, /* null pointer */
MFX_ERR_UNSUPPORTED = -3, /* undeveloped feature */
MFX_ERR_MEMORY_ALLOC = -4, /* failed to allocate memory */
MFX_ERR_NOT_ENOUGH_BUFFER = -5, /* insufficient buffer at input/output */
MFX_ERR_INVALID_HANDLE = -6, /* invalid handle */
MFX_ERR_LOCK_MEMORY = -7, /* failed to lock the memory block */
MFX_ERR_NOT_INITIALIZED = -8, /* member function called before initialization */
MFX_ERR_NOT_FOUND = -9, /* the specified object is not found */
MFX_ERR_MORE_DATA = -10, /* expect more data at input */
MFX_ERR_MORE_SURFACE = -11, /* expect more surface at output */
MFX_ERR_ABORTED = -12, /* operation aborted */
MFX_ERR_DEVICE_LOST = -13, /* lose the HW acceleration device */
MFX_ERR_INCOMPATIBLE_VIDEO_PARAM = -14, /* incompatible video parameters */
MFX_ERR_INVALID_VIDEO_PARAM = -15, /* invalid video parameters */
MFX_ERR_UNDEFINED_BEHAVIOR = -16, /* undefined behavior */
MFX_ERR_DEVICE_FAILED = -17, /* device operation failure */
MFX_ERR_MORE_BITSTREAM = -18, /* expect more bitstream buffers at output */
MFX_ERR_INCOMPATIBLE_AUDIO_PARAM = -19, /* incompatible audio parameters */
MFX_ERR_INVALID_AUDIO_PARAM = -20, /* invalid audio parameters */
MFX_ERR_GPU_HANG = -21, /* device operation failure caused by GPU hang */
MFX_ERR_REALLOC_SURFACE = -22, /* bigger output surface required */
/* warnings >0 */
MFX_WRN_IN_EXECUTION = 1, /* the previous asynchronous operation is in execution */
MFX_WRN_DEVICE_BUSY = 2, /* the HW acceleration device is busy */
MFX_WRN_VIDEO_PARAM_CHANGED = 3, /* the video parameters are changed during decoding */
MFX_WRN_PARTIAL_ACCELERATION = 4, /* SW is used */
MFX_WRN_INCOMPATIBLE_VIDEO_PARAM = 5, /* incompatible video parameters */
MFX_WRN_VALUE_NOT_CHANGED = 6, /* the value is saturated based on its valid range */
MFX_WRN_OUT_OF_RANGE = 7, /* the value is out of valid range */
MFX_WRN_FILTER_SKIPPED = 10, /* one of requested filters has been skipped */
MFX_WRN_INCOMPATIBLE_AUDIO_PARAM = 11, /* incompatible audio parameters */
/* threading statuses */
MFX_TASK_DONE = MFX_ERR_NONE, /* task has been completed */
MFX_TASK_WORKING = 8, /* there is some more work to do */
MFX_TASK_BUSY = 9, /* task is waiting for resources */
/* plug-in statuses */
MFX_ERR_MORE_DATA_SUBMIT_TASK = -10000, /* return MFX_ERR_MORE_DATA but submit internal asynchronous task */
} mfxStatus;
// Application
#if defined(MFX_DISPATCHER_EXPOSED_PREFIX)
#include "mfxdispatcherprefixedfunctions.h"
#endif // MFX_DISPATCHER_EXPOSED_PREFIX
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* __MFXDEFS_H__ */
| 6,819
|
C++
|
.h
| 136
| 47.382353
| 118
| 0.612297
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
22,510
|
mfxvideo.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/decoders/mvc/include/mfxvideo.h
|
/* ****************************************************************************** *\
Copyright (C) 2007-2017 Intel Corporation. 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 Intel Corporation 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 INTEL CORPORATION "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 INTEL CORPORATION 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.
File Name: mfxvideo.h
\* ****************************************************************************** */
#ifndef __MFXVIDEO_H__
#define __MFXVIDEO_H__
#include "mfxsession.h"
#include "mfxvstructures.h"
#ifdef __cplusplus
extern "C"
{
#endif
/* MFXVideoCORE */
typedef struct {
mfxU32 reserved[4];
mfxHDL pthis;
mfxStatus (MFX_CDECL *Alloc) (mfxHDL pthis, mfxU32 nbytes, mfxU16 type, mfxMemId *mid);
mfxStatus (MFX_CDECL *Lock) (mfxHDL pthis, mfxMemId mid, mfxU8 **ptr);
mfxStatus (MFX_CDECL *Unlock) (mfxHDL pthis, mfxMemId mid);
mfxStatus (MFX_CDECL *Free) (mfxHDL pthis, mfxMemId mid);
} mfxBufferAllocator;
typedef struct {
mfxU32 reserved[4];
mfxHDL pthis;
mfxStatus (MFX_CDECL *Alloc) (mfxHDL pthis, mfxFrameAllocRequest *request, mfxFrameAllocResponse *response);
mfxStatus (MFX_CDECL *Lock) (mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr);
mfxStatus (MFX_CDECL *Unlock) (mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr);
mfxStatus (MFX_CDECL *GetHDL) (mfxHDL pthis, mfxMemId mid, mfxHDL *handle);
mfxStatus (MFX_CDECL *Free) (mfxHDL pthis, mfxFrameAllocResponse *response);
} mfxFrameAllocator;
/* VideoCORE */
mfxStatus MFX_CDECL MFXVideoCORE_SetBufferAllocator(mfxSession session, mfxBufferAllocator *allocator);
mfxStatus MFX_CDECL MFXVideoCORE_SetFrameAllocator(mfxSession session, mfxFrameAllocator *allocator);
mfxStatus MFX_CDECL MFXVideoCORE_SetHandle(mfxSession session, mfxHandleType type, mfxHDL hdl);
mfxStatus MFX_CDECL MFXVideoCORE_GetHandle(mfxSession session, mfxHandleType type, mfxHDL *hdl);
mfxStatus MFX_CDECL MFXVideoCORE_QueryPlatform(mfxSession session, mfxPlatform* platform);
mfxStatus MFX_CDECL MFXVideoCORE_SyncOperation(mfxSession session, mfxSyncPoint syncp, mfxU32 wait);
/* VideoENCODE */
mfxStatus MFX_CDECL MFXVideoENCODE_Query(mfxSession session, mfxVideoParam *in, mfxVideoParam *out);
mfxStatus MFX_CDECL MFXVideoENCODE_QueryIOSurf(mfxSession session, mfxVideoParam *par, mfxFrameAllocRequest *request);
mfxStatus MFX_CDECL MFXVideoENCODE_Init(mfxSession session, mfxVideoParam *par);
mfxStatus MFX_CDECL MFXVideoENCODE_Reset(mfxSession session, mfxVideoParam *par);
mfxStatus MFX_CDECL MFXVideoENCODE_Close(mfxSession session);
mfxStatus MFX_CDECL MFXVideoENCODE_GetVideoParam(mfxSession session, mfxVideoParam *par);
mfxStatus MFX_CDECL MFXVideoENCODE_GetEncodeStat(mfxSession session, mfxEncodeStat *stat);
mfxStatus MFX_CDECL MFXVideoENCODE_EncodeFrameAsync(mfxSession session, mfxEncodeCtrl *ctrl, mfxFrameSurface1 *surface, mfxBitstream *bs, mfxSyncPoint *syncp);
/* VideoDECODE */
mfxStatus MFX_CDECL MFXVideoDECODE_Query(mfxSession session, mfxVideoParam *in, mfxVideoParam *out);
mfxStatus MFX_CDECL MFXVideoDECODE_DecodeHeader(mfxSession session, mfxBitstream *bs, mfxVideoParam *par);
mfxStatus MFX_CDECL MFXVideoDECODE_QueryIOSurf(mfxSession session, mfxVideoParam *par, mfxFrameAllocRequest *request);
mfxStatus MFX_CDECL MFXVideoDECODE_Init(mfxSession session, mfxVideoParam *par);
mfxStatus MFX_CDECL MFXVideoDECODE_Reset(mfxSession session, mfxVideoParam *par);
mfxStatus MFX_CDECL MFXVideoDECODE_Close(mfxSession session);
mfxStatus MFX_CDECL MFXVideoDECODE_GetVideoParam(mfxSession session, mfxVideoParam *par);
mfxStatus MFX_CDECL MFXVideoDECODE_GetDecodeStat(mfxSession session, mfxDecodeStat *stat);
mfxStatus MFX_CDECL MFXVideoDECODE_SetSkipMode(mfxSession session, mfxSkipMode mode);
mfxStatus MFX_CDECL MFXVideoDECODE_GetPayload(mfxSession session, mfxU64 *ts, mfxPayload *payload);
mfxStatus MFX_CDECL MFXVideoDECODE_DecodeFrameAsync(mfxSession session, mfxBitstream *bs, mfxFrameSurface1 *surface_work, mfxFrameSurface1 **surface_out, mfxSyncPoint *syncp);
/* VideoVPP */
mfxStatus MFX_CDECL MFXVideoVPP_Query(mfxSession session, mfxVideoParam *in, mfxVideoParam *out);
mfxStatus MFX_CDECL MFXVideoVPP_QueryIOSurf(mfxSession session, mfxVideoParam *par, mfxFrameAllocRequest request[2]);
mfxStatus MFX_CDECL MFXVideoVPP_Init(mfxSession session, mfxVideoParam *par);
mfxStatus MFX_CDECL MFXVideoVPP_Reset(mfxSession session, mfxVideoParam *par);
mfxStatus MFX_CDECL MFXVideoVPP_Close(mfxSession session);
mfxStatus MFX_CDECL MFXVideoVPP_GetVideoParam(mfxSession session, mfxVideoParam *par);
mfxStatus MFX_CDECL MFXVideoVPP_GetVPPStat(mfxSession session, mfxVPPStat *stat);
mfxStatus MFX_CDECL MFXVideoVPP_RunFrameVPPAsync(mfxSession session, mfxFrameSurface1 *in, mfxFrameSurface1 *out, mfxExtVppAuxData *aux, mfxSyncPoint *syncp);
mfxStatus MFX_CDECL MFXVideoVPP_RunFrameVPPAsyncEx(mfxSession session, mfxFrameSurface1 *in, mfxFrameSurface1 *surface_work, mfxFrameSurface1 **surface_out, mfxSyncPoint *syncp);
#ifdef __cplusplus
} // extern "C"
#endif
#endif
| 6,290
|
C++
|
.h
| 92
| 66.608696
| 178
| 0.794175
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
22,511
|
mfxvstructures.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/decoders/mvc/include/mfxvstructures.h
|
/*******************************************************************************
Copyright (C) 2013 Intel Corporation. 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 Intel Corporation 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 INTEL CORPORATION "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 INTEL CORPORATION 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.
File Name: mfxvstructures.h
*******************************************************************************/
#include "mfxstructures.h"
| 1,662
|
C++
|
.h
| 25
| 65.2
| 80
| 0.749693
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| false
| false
| false
| false
| true
| false
|
22,512
|
mfxcommon.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/decoders/mvc/include/mfxcommon.h
|
/*******************************************************************************
Copyright (C) 2013-2018 Intel Corporation. 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 Intel Corporation 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 INTEL CORPORATION "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 INTEL CORPORATION 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.
File Name: mfxcommon.h
*******************************************************************************/
#ifndef __MFXCOMMON_H__
#define __MFXCOMMON_H__
#include "mfxdefs.h"
#if !defined (__GNUC__)
#pragma warning(disable: 4201)
#endif
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
#define MFX_MAKEFOURCC(A,B,C,D) ((((int)A))+(((int)B)<<8)+(((int)C)<<16)+(((int)D)<<24))
/* Extended Configuration Header Structure */
typedef struct {
mfxU32 BufferId;
mfxU32 BufferSz;
} mfxExtBuffer;
/* Library initialization and deinitialization */
typedef mfxI32 mfxIMPL;
#define MFX_IMPL_BASETYPE(x) (0x00ff & (x))
enum {
MFX_IMPL_AUTO = 0x0000, /* Auto Selection/In or Not Supported/Out */
MFX_IMPL_SOFTWARE = 0x0001, /* Pure Software Implementation */
MFX_IMPL_HARDWARE = 0x0002, /* Hardware Accelerated Implementation (default device) */
MFX_IMPL_AUTO_ANY = 0x0003, /* Auto selection of any hardware/software implementation */
MFX_IMPL_HARDWARE_ANY = 0x0004, /* Auto selection of any hardware implementation */
MFX_IMPL_HARDWARE2 = 0x0005, /* Hardware accelerated implementation (2nd device) */
MFX_IMPL_HARDWARE3 = 0x0006, /* Hardware accelerated implementation (3rd device) */
MFX_IMPL_HARDWARE4 = 0x0007, /* Hardware accelerated implementation (4th device) */
MFX_IMPL_RUNTIME = 0x0008,
MFX_IMPL_VIA_ANY = 0x0100,
MFX_IMPL_VIA_D3D9 = 0x0200,
MFX_IMPL_VIA_D3D11 = 0x0300,
MFX_IMPL_VIA_VAAPI = 0x0400,
MFX_IMPL_AUDIO = 0x8000,
MFX_IMPL_UNSUPPORTED = 0x0000 /* One of the MFXQueryIMPL returns */
};
/* Version Info */
typedef union {
struct {
mfxU16 Minor;
mfxU16 Major;
};
mfxU32 Version;
} mfxVersion;
/* session priority */
typedef enum
{
MFX_PRIORITY_LOW = 0,
MFX_PRIORITY_NORMAL = 1,
MFX_PRIORITY_HIGH = 2
} mfxPriority;
typedef struct _mfxEncryptedData mfxEncryptedData;
typedef struct {
union {
struct {
mfxEncryptedData* EncryptedData;
mfxExtBuffer **ExtParam;
mfxU16 NumExtParam;
};
mfxU32 reserved[6];
};
mfxI64 DecodeTimeStamp;
mfxU64 TimeStamp;
mfxU8* Data;
mfxU32 DataOffset;
mfxU32 DataLength;
mfxU32 MaxLength;
mfxU16 PicStruct;
mfxU16 FrameType;
mfxU16 DataFlag;
mfxU16 reserved2;
} mfxBitstream;
typedef struct _mfxSyncPoint *mfxSyncPoint;
/* GPUCopy */
enum {
MFX_GPUCOPY_DEFAULT = 0,
MFX_GPUCOPY_ON = 1,
MFX_GPUCOPY_OFF = 2
};
typedef struct {
mfxIMPL Implementation;
mfxVersion Version;
mfxU16 ExternalThreads;
union {
struct {
mfxExtBuffer **ExtParam;
mfxU16 NumExtParam;
};
mfxU16 reserved2[5];
};
mfxU16 GPUCopy;
mfxU16 reserved[21];
} mfxInitParam;
enum {
MFX_EXTBUFF_THREADS_PARAM = MFX_MAKEFOURCC('T','H','D','P')
};
typedef struct {
mfxExtBuffer Header;
mfxU16 NumThread;
mfxI32 SchedulingType;
mfxI32 Priority;
mfxU16 reserved[55];
} mfxExtThreadsParam;
/* PlatformCodeName */
enum {
MFX_PLATFORM_UNKNOWN = 0,
MFX_PLATFORM_SANDYBRIDGE = 1,
MFX_PLATFORM_IVYBRIDGE = 2,
MFX_PLATFORM_HASWELL = 3,
MFX_PLATFORM_BAYTRAIL = 4,
MFX_PLATFORM_BROADWELL = 5,
MFX_PLATFORM_CHERRYTRAIL = 6,
MFX_PLATFORM_SKYLAKE = 7,
MFX_PLATFORM_APOLLOLAKE = 8,
MFX_PLATFORM_KABYLAKE = 9,
MFX_PLATFORM_GEMINILAKE = 10,
MFX_PLATFORM_COFFEELAKE = 11,
MFX_PLATFORM_CANNONLAKE = 20,
MFX_PLATFORM_ICELAKE = 30,
};
typedef struct {
mfxU16 CodeName;
mfxU16 DeviceId;
mfxU16 reserved[14];
} mfxPlatform;
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
| 5,421
|
C++
|
.h
| 153
| 31.633987
| 97
| 0.672647
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
22,513
|
D3D11SurfaceAllocator.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/decoders/d3d11/D3D11SurfaceAllocator.h
|
/*
* Copyright (C) 2019-2021 Hendrik Leppkes
* http://www.1f0.de
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include <d3d11.h>
#include "MediaSampleSideData.h"
#include "ID3DVideoMemoryConfiguration.h"
class CDecD3D11;
class CD3D11MediaSample
: public CMediaSampleSideData
, public IMediaSampleD3D11
{
friend class CD3D11SurfaceAllocator;
public:
CD3D11MediaSample(CD3D11SurfaceAllocator *pAllocator, AVFrame *pFrame, HRESULT *phr);
virtual ~CD3D11MediaSample();
// IUnknown
STDMETHODIMP QueryInterface(REFIID riid, __deref_out void **ppv);
STDMETHODIMP_(ULONG) AddRef();
STDMETHODIMP_(ULONG) Release();
// IMediaSample
STDMETHODIMP GetPointer(BYTE **ppBuffer) { return E_NOTIMPL; }
// IMediaSampleD3D11
STDMETHODIMP GetD3D11Texture(int nView, ID3D11Texture2D **ppTexture, UINT *pArraySlice);
// LAV Interface
STDMETHODIMP GetAVFrameBuffer(AVFrame *pFrame);
private:
AVFrame *m_pFrame = nullptr;
void *m_pAllocatorCookie = nullptr;
};
class CD3D11SurfaceAllocator : public CBaseAllocator
{
public:
CD3D11SurfaceAllocator(CDecD3D11 *pDec, HRESULT *phr);
virtual ~CD3D11SurfaceAllocator();
STDMETHODIMP ReleaseBuffer(IMediaSample *pSample);
STDMETHODIMP_(BOOL) DecommitInProgress()
{
CAutoLock cal(this);
return m_bDecommitInProgress;
}
STDMETHODIMP_(BOOL) IsCommited()
{
CAutoLock cal(this);
return m_bCommitted;
}
STDMETHODIMP_(void) ForceDecommit();
// LAV interface
STDMETHODIMP_(void) DecoderDestruct()
{
CAutoLock cal(this);
m_pDec = nullptr;
}
protected:
virtual void Free(void);
virtual HRESULT Alloc(void);
private:
CDecD3D11 *m_pDec = nullptr;
AVBufferRef *m_pFramesCtx = nullptr;
friend class CD3D11MediaSample;
};
| 2,562
|
C++
|
.h
| 76
| 29.578947
| 92
| 0.730036
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,514
|
VC1HeaderParser.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/parsers/VC1HeaderParser.h
|
/*
* Copyright (C) 2010-2021 Hendrik Leppkes
* http://www.1f0.de
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
struct GetBitContext;
class CVC1HeaderParser
{
public:
CVC1HeaderParser(const BYTE *pData, size_t length, AVCodecID codec = AV_CODEC_ID_VC1);
~CVC1HeaderParser(void);
AVPictureType ParseVC1PictureType(const uint8_t *buf, int buflen);
public:
struct
{
int valid;
int profile;
int level;
int width;
int height;
int broadcast;
int interlaced;
AVRational ar;
int old_interlaced;
int bframes;
int finterp;
int rangered;
} hdr;
private:
void ParseVC1Header(const BYTE *pData, size_t length, AVCodecID codec);
void VC1ParseSequenceHeader(GetBitContext *gb);
};
| 1,524
|
C++
|
.h
| 46
| 28.608696
| 90
| 0.703476
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,515
|
MPEG2HeaderParser.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/parsers/MPEG2HeaderParser.h
|
/*
* Copyright (C) 2010-2021 Hendrik Leppkes
* http://www.1f0.de
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
struct GetBitContext;
class CMPEG2HeaderParser
{
public:
CMPEG2HeaderParser(const BYTE *pData, size_t length);
~CMPEG2HeaderParser(void);
public:
struct
{
int valid;
int profile;
int level;
int interlaced;
int chroma;
} hdr;
private:
void ParseMPEG2Header(const BYTE *pData, size_t length);
void MPEG2ParseSequenceHeader(GetBitContext *gb);
void MPEG2ParseExtHeader(GetBitContext *gb);
};
| 1,299
|
C++
|
.h
| 39
| 29.692308
| 75
| 0.723065
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,516
|
H264SequenceParser.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/parsers/H264SequenceParser.h
|
/*
* Copyright (C) 2010-2021 Hendrik Leppkes
* http://www.1f0.de
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
class CH264SequenceParser
{
public:
CH264SequenceParser(void);
virtual ~CH264SequenceParser(void);
HRESULT ParseNALs(const BYTE *buffer, size_t buflen, int nal_size);
public:
struct
{
int valid;
int profile;
int level;
int chroma;
int luma_bitdepth;
int chroma_bitdepth;
int ref_frames;
int interlaced;
int ar_present;
int full_range;
int primaries;
int trc;
int colorspace;
} sps;
struct
{
int valid;
} pps;
private:
HRESULT ParseSPS(const BYTE *buffer, size_t buflen);
};
| 1,465
|
C++
|
.h
| 49
| 25.163265
| 75
| 0.681108
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,518
|
HEVCSequenceParser.h
|
Nevcairiel_LAVFilters/decoder/LAVVideo/parsers/HEVCSequenceParser.h
|
/*
* Copyright (C) 2010-2021 Hendrik Leppkes
* http://www.1f0.de
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "ByteParser.h"
#define HEVC_REXT_PROFILE_MAIN_12 0x98
class CHEVCSequenceParser
{
public:
CHEVCSequenceParser();
~CHEVCSequenceParser();
HRESULT ParseNALs(const BYTE *buffer, size_t buflen, int nal_size);
public:
struct
{
int valid;
int profile;
int rext_profile;
int level;
int chroma;
int bitdepth;
} sps;
private:
HRESULT ParseSPS(const BYTE *buffer, size_t buflen);
};
| 1,297
|
C++
|
.h
| 40
| 28.75
| 75
| 0.711769
|
Nevcairiel/LAVFilters
| 7,362
| 788
| 84
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,527
|
test-gradient.cc
|
brndnmtthws_conky/tests/test-gradient.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* 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 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 "catch2/catch.hpp"
#include <colours.h>
#include <conky.h>
#include <gradient.h>
#include <iomanip>
#include <iostream>
const int width = 4;
const Colour colour = Colour::from_argb32(0xff996633); // brown
const long expected_hue = 256;
const long expected_value = 0x99; // max(0x99, 0x66, 0x33)
const long expected_chroma = 0x66; // (0x99 - 0x33)
const long expected_luma = 20712665L;
const long expected_saturation = 122880L;
const long expected_red = 0x99;
const long expected_green = 0x66;
const long expected_blue = 0x33;
const long full_scale = conky::gradient_factory::SCALE360;
std::ostream& operator<<(std::ostream& s, const Colour& c) {
s << '#';
s << std::setfill('0');
s << std::setw(2);
s << std::setbase(16);
s << (int)c.alpha << (int)c.red << (int)c.green << (int)c.blue;
return s;
}
TEST_CASE("gradient_factory::convert_from_rgb returns correct value") {
#ifdef BUILD_X11
state = nullptr;
#endif
SECTION("rgb_gradient_factory") {
auto factory = new conky::rgb_gradient_factory(width, colour, colour);
long result[3];
factory->convert_from_rgb(colour, result);
SECTION("red") { REQUIRE(result[0] == expected_red * full_scale); }
SECTION("green") { REQUIRE(result[1] == expected_green * full_scale); }
SECTION("blue") { REQUIRE(result[2] == expected_blue * full_scale); }
delete factory;
}
SECTION("hsv_gradient_factory") {
auto factory = new conky::hsv_gradient_factory(width, colour, colour);
long result[3];
factory->convert_from_rgb(colour, result);
SECTION("hue") { REQUIRE(result[0] == expected_hue * 60); }
SECTION("saturation") { REQUIRE(result[1] == expected_saturation); }
SECTION("value") { REQUIRE(result[2] == expected_value * full_scale); }
delete factory;
}
SECTION("hcl_gradient_factory") {
auto factory = new conky::hcl_gradient_factory(width, colour, colour);
long result[3];
factory->convert_from_rgb(colour, result);
SECTION("hue") { REQUIRE(result[0] == expected_hue * 60); }
SECTION("chroma") { REQUIRE(result[1] == expected_chroma * full_scale); }
SECTION("luma") { REQUIRE(result[2] == expected_luma); }
delete factory;
}
}
TEST_CASE(
"gradient_factory should convert to and from rgb "
"and get the initial value") {
SECTION("rgb_gradient_factory") {
long tmp[3];
auto factory = new conky::rgb_gradient_factory(width, colour, colour);
factory->convert_from_rgb(colour, tmp);
auto result = factory->convert_to_rgb(tmp);
REQUIRE(result == colour);
delete factory;
}
SECTION("hsv_gradient_factory") {
long tmp[3];
auto factory = new conky::hsv_gradient_factory(width, colour, colour);
factory->convert_from_rgb(colour, tmp);
auto result = factory->convert_to_rgb(tmp);
REQUIRE(result == colour);
delete factory;
}
SECTION("hcl_gradient_factory") {
long tmp[3];
auto factory = new conky::hcl_gradient_factory(width, colour, colour);
factory->convert_from_rgb(colour, tmp);
auto result = factory->convert_to_rgb(tmp);
REQUIRE(result == colour);
delete factory;
}
}
| 4,130
|
C++
|
.cc
| 112
| 33.598214
| 77
| 0.697319
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,528
|
test-common.cc
|
brndnmtthws_conky/tests/test-common.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* 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 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/>.
*
*/
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do
// this in one cpp file
#include "catch2/catch.hpp"
#include <common.h>
#include <conky.h>
extern char **environ;
std::string get_valid_environment_variable_name() {
if (getenv("HOME") != nullptr) { return "HOME"; }
// If HOME is not a valid environment variable name, try to get a valid one.
char *env_var = *environ;
for (int i = 1; env_var; i++) {
std::string variable_name(env_var);
int variable_name_length = variable_name.find('=');
variable_name = variable_name.substr(0, variable_name_length);
if (getenv(variable_name.c_str()) != nullptr) { return variable_name; }
env_var = *(environ + i);
}
return "";
}
std::string get_invalid_environment_variable_name() {
std::string variable_name = "INVALIDVARIABLENAME";
while (getenv(variable_name.c_str()) != nullptr) {
variable_name += std::to_string(variable_name.length());
}
return variable_name;
}
TEST_CASE("to_real_path becomes homedir", "[to_real_path]") {
REQUIRE(to_real_path("~/test") == std::string(getenv("HOME")) + "/test");
}
TEST_CASE("environment variables are substituted correctly",
"[variable_substitute]") {
std::string valid_name = get_valid_environment_variable_name();
std::string valid_value = getenv(valid_name.c_str());
std::string invalid_name = get_invalid_environment_variable_name();
SECTION("an empty string input returns an empty string") {
REQUIRE(variable_substitute("") == "");
}
SECTION("string in with no $ returns same string") {
std::string string_alpha = "abcdefghijklmnopqrstuvwxyz";
std::string string_numbers = "1234567890";
std::string string_special = "`~!@#$%^&*()-=_+[]{}\\|;:'\",<.>/?";
std::string string_valid_name = valid_name;
REQUIRE(variable_substitute(string_alpha) == string_alpha);
REQUIRE(variable_substitute(string_numbers) == string_numbers);
REQUIRE(variable_substitute(string_special) == string_special);
REQUIRE(variable_substitute(string_valid_name) == string_valid_name);
}
SECTION("invalid variables are removed from return string") {
std::string string_in_1 = "a$" + invalid_name + " z";
std::string string_in_2 = "a${" + invalid_name + "} z";
std::string string_in_3 = "a${" + invalid_name + " " + valid_name + "} z";
std::string string_in_4 = "a${ " + valid_name + "} z";
std::string string_in_5 = "a${" + valid_name + " } z";
std::string string_in_6 = "a$" + valid_name + "z z";
std::string string_in_7 = "a$" + invalid_name + "# z";
REQUIRE(variable_substitute(string_in_1) == "a z");
REQUIRE(variable_substitute(string_in_2) == "a z");
REQUIRE(variable_substitute(string_in_3) == "a z");
REQUIRE(variable_substitute(string_in_4) == "a z");
REQUIRE(variable_substitute(string_in_5) == "a z");
REQUIRE(variable_substitute(string_in_6) == "a z");
REQUIRE(variable_substitute(string_in_7) == "a# z");
}
SECTION("valid variable gets replaced in the return string") {
std::string string_in_1 = "a$" + valid_name + " z";
std::string string_in_2 = "a${" + valid_name + "} z";
std::string string_in_3 = "a$" + valid_name + "# z";
std::string string_var_replaced_1 = "a" + valid_value + " z";
std::string string_var_replaced_2 = "a" + valid_value + " z";
std::string string_var_replaced_3 = "a" + valid_value + "# z";
REQUIRE(variable_substitute(string_in_1) == string_var_replaced_1);
REQUIRE(variable_substitute(string_in_2) == string_var_replaced_2);
REQUIRE(variable_substitute(string_in_3) == string_var_replaced_3);
}
SECTION("$ without variable is ignored") {
std::string string_in_1 = "a$#z";
std::string string_in_2 = "a$2z";
REQUIRE(variable_substitute(string_in_1) == string_in_1);
REQUIRE(variable_substitute(string_in_2) == string_in_2);
}
SECTION("double $ gets converted to single $ and is passed over") {
std::string string_in_1 = "a$$sz";
std::string string_in_2 = "a$$" + valid_name + "z";
std::string string_out_1 = "a$sz";
std::string string_out_2 = "a$" + valid_name + "z";
REQUIRE(variable_substitute(string_in_1) == string_out_1);
REQUIRE(variable_substitute(string_in_2) == string_out_2);
}
SECTION("incomplete variable does not get replaced in return string") {
std::string string_in = "a${" + valid_name + " z";
REQUIRE(variable_substitute(string_in) == string_in);
}
}
TEST_CASE("cpu_percentage and cpu_barval return correct values") {
struct text_object obj0;
obj0.data.i = 0;
struct text_object obj1;
obj1.data.i = 1;
// struct text_object obj2;
// obj2.data.i = 2;
info.cpu_count = 1;
// SECTION("for non-existent cpu") {
// info.cpu_usage = new float[2];
// info.cpu_usage[0] = 0.253;
// info.cpu_usage[1] = 0.507;
// This does not exist in Catch2, but would be nice to have since that's
// what happens in this case.
// REQUIRE_EXIT(cpu_percentage(&obj2));
// REQUIRE_EXIT(cpu_barval(&obj2));
// delete[] info.cpu_usage;
// }
SECTION("for cpu_usage == nullptr") {
info.cpu_usage = nullptr;
REQUIRE(cpu_percentage(&obj0) == 0);
REQUIRE(cpu_barval(&obj0) == 0);
REQUIRE(cpu_percentage(&obj1) == 0);
REQUIRE(cpu_barval(&obj1) == 0);
}
SECTION("for cpu_usage has data") {
info.cpu_usage = new float[2];
info.cpu_usage[0] = 0.253;
info.cpu_usage[1] = 0.507;
REQUIRE(cpu_percentage(&obj0) == 25);
REQUIRE(cpu_barval(&obj0) == Approx(0.253));
REQUIRE(cpu_percentage(&obj1) == 51);
REQUIRE(cpu_barval(&obj1) == Approx(0.507));
delete[] info.cpu_usage;
}
}
TEST_CASE("mem_percentage and mem_barval return correct values") {
info.mem = 6;
SECTION("for memmax == 0") {
info.memmax = 0;
REQUIRE(mem_percentage(nullptr) == 0);
REQUIRE(mem_barval(nullptr) == 0);
}
SECTION("for memmax > 0") {
info.memmax = 24;
REQUIRE(mem_percentage(nullptr) == 25);
REQUIRE(mem_barval(nullptr) == Approx(0.25));
}
}
TEST_CASE("mem_with_buffers_barval returns correct value") {
info.memwithbuffers = 6;
SECTION("for memmax == 0") {
info.memmax = 0;
REQUIRE(mem_with_buffers_barval(nullptr) == 0);
}
SECTION("for memmax > 0") {
info.memmax = 24;
REQUIRE(mem_with_buffers_barval(nullptr) == Approx(0.25));
}
}
TEST_CASE("swap_percentage and swap_barval return correct values") {
info.swap = 6;
SECTION("for swapmax == 0") {
info.swapmax = 0;
REQUIRE(swap_percentage(nullptr) == 0);
REQUIRE(swap_barval(nullptr) == 0);
}
SECTION("for swapmax > 0") {
info.swapmax = 24;
REQUIRE(swap_percentage(nullptr) == 25);
REQUIRE(swap_barval(nullptr) == Approx(0.25));
}
}
| 7,774
|
C++
|
.cc
| 193
| 36.388601
| 78
| 0.659495
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,529
|
test-graph.cc
|
brndnmtthws_conky/tests/test-graph.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* 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 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 <tuple>
#include "catch2/catch.hpp"
#include "conky.h"
#include "lua-config.hh"
#include "specials.h"
#ifdef BUILD_GUI
#define SF_SHOWLOG (1 << 1)
// Specific value doesn't matter, but we check if the same one comes back
constexpr double default_scale = M_PI;
constexpr double default_width = 0;
constexpr double default_height = 25;
struct graph {
int id;
char flags;
int width, height;
bool colours_set;
Colour first_colour, last_colour;
double scale;
char tempgrad;
};
static std::pair<struct graph, bool> test_parse(const char *s) {
struct text_object obj;
bool result = scan_graph(&obj, s, default_scale,FALSE);
auto g = static_cast<struct graph *>(obj.special_data);
struct graph graph = *g;
free(g);
return {graph, result};
}
std::string unquote(const std::string &s) {
auto out = s;
out.erase(remove(out.begin(), out.end(), '\"'), out.end());
return out;
}
TEST_CASE("scan_graph correctly parses input strings") {
state = std::make_unique<lua::state>();
conky::export_symbols(*state);
SECTION("Trivial parse") {
auto [g, success] = test_parse("");
REQUIRE(g.width == default_width);
REQUIRE(g.height == default_height);
}
/* test parsing combinations of options */
const char *size_options[][2] = {{"30", "500"}, {"80", ""}, {"", ""}};
const char *color_options[][2] = {{"orange", "blue"},
{"#deadff", "#392014"},
{"000000", "000000"},
{"", ""}};
const char *scale_options[] = {"0.5", ""};
SECTION("subset of [height,width] [color1 color2] [scale] [-t] [-l]") {
for (auto size : size_options) {
for (auto colors : color_options) {
for (auto scale : scale_options) {
bool ends_at_first_size = false;
/* build an argument string by combining the selected options */
std::string s;
if (*size[0] != '\0') {
s += size[0];
s += ",";
if (*size[1] == '\0') {
/* if the size is just a height, it has to be the end of the
* argument string */
ends_at_first_size = true;
} else {
s += size[1];
}
s += " ";
}
if (!ends_at_first_size) {
s += colors[0];
s += " ";
s += colors[1];
s += " ";
s += scale;
}
/* parse the argument string */
auto [g, success] = test_parse(s.c_str());
printf("command: %s\n", s.c_str());
/* validate parsing of each component */
if (*size[0] == '\0') {
REQUIRE(g.width == default_width);
REQUIRE(g.height == default_height);
} else {
REQUIRE(g.height == atoi(size[0]));
REQUIRE(g.width == atoi(size[1]));
}
/* if second half of size is empty, no subsequent values should be
* set
*/
if (ends_at_first_size) {
REQUIRE(g.colours_set == false);
continue;
}
if (*colors[0] == '\0') {
REQUIRE(g.colours_set == false);
} else {
REQUIRE(g.colours_set == true);
REQUIRE(g.first_colour == parse_color(colors[0]));
REQUIRE(g.last_colour == parse_color(colors[1]));
}
if (*scale == '\0') {
REQUIRE(g.scale == default_scale);
} else {
REQUIRE(g.scale == 0.5);
}
REQUIRE(g.flags == 0);
REQUIRE(g.tempgrad == 0);
}
}
}
}
SECTION("[height,width] [color1 color2] [scale] [-t] [-l]") {
auto [g, success] = test_parse("21,340 orange blue 0.5 -t -l");
REQUIRE(success);
REQUIRE(g.width == 340);
REQUIRE(g.height == 21);
REQUIRE(g.colours_set == true);
REQUIRE(g.scale == 0.5);
REQUIRE(g.flags == SF_SHOWLOG);
REQUIRE(g.tempgrad == true);
}
SECTION("-t location") {
{
auto [g, success] = test_parse("21,340 red blue 0.5");
REQUIRE(g.tempgrad == false);
}
{
auto [g, success] = test_parse("21,340 red blue 0.5");
REQUIRE(g.tempgrad == false);
}
{
auto [g, success] = test_parse("-t 21,340 red blue 0.5");
REQUIRE(g.tempgrad == true);
}
{
auto [g, success] = test_parse("21,340 -t red blue 0.5");
REQUIRE(g.tempgrad == true);
}
}
}
TEST_CASE("scan_command correctly parses input strings") {
SECTION("parse commands") {
const char *command_options[][2] = {{"\"foo bar\"", "foo bar"},
{"\"foo bar\"\tbaz", "foo bar"},
{"\"foo bar\"\nbaz", "foo bar"},
{"\"foo bar\" baz", "foo bar"},
{"one two", "one"},
{"\"ls -t\"", "ls -t"},
{"\"ls -t\" 4309", "ls -t"},
{"foo-test", "foo-test"},
{"foo-test a b c", "foo-test"},
{"", ""}};
for (auto [command, expected_parsed] : command_options) {
auto [parsed, len] = scan_command(command);
REQUIRE(std::string(parsed) == expected_parsed);
if (command[0] == '"') {
REQUIRE(len == strlen(expected_parsed) + 2);
} else {
REQUIRE(len == strlen(expected_parsed));
}
}
}
}
#endif /* BUILD_GUI */
| 6,605
|
C++
|
.cc
| 190
| 26.357895
| 76
| 0.530286
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,530
|
test-darwin.cc
|
brndnmtthws_conky/tests/test-darwin.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* 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 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 "catch2/catch.hpp"
#include <darwin.h>
TEST_CASE("get_entropy_avail returns 1", "[get_entropy_avail]") {
unsigned int unused = 0;
REQUIRE(get_entropy_avail(&unused) == 1);
}
| 1,181
|
C++
|
.cc
| 33
| 33.787879
| 72
| 0.744105
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,531
|
test-core.cc
|
brndnmtthws_conky/tests/test-core.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* 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 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 "catch2/catch.hpp"
#include <core.h>
TEST_CASE("remove_comments returns correct value") {
SECTION("for no comments") {
char text[] = "test text\n";
size_t removed_chars = remove_comments(text);
REQUIRE(removed_chars == 0);
}
SECTION("for no comments but with backslashes") {
char text[] = "te\\st t\\ext\n";
size_t removed_chars = remove_comments(text);
REQUIRE(removed_chars == 0);
}
SECTION("for single line of comment") {
char text_with_newline[] = "#test text\n";
char text_no_newline[] = "#test text";
size_t removed_chars_with_newline = remove_comments(text_with_newline);
size_t removed_chars_no_newline = remove_comments(text_no_newline);
REQUIRE(removed_chars_with_newline == 11);
REQUIRE(removed_chars_no_newline == 10);
}
SECTION("for comment starting in middle of line") {
char text[] = "test #text\n";
size_t removed_chars = remove_comments(text);
REQUIRE(removed_chars == 6);
}
}
| 1,984
|
C++
|
.cc
| 54
| 33.592593
| 75
| 0.712422
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,532
|
test-algebra.cc
|
brndnmtthws_conky/tests/test-algebra.cc
|
#include "catch2/catch.hpp"
#include <algebra.h>
#include <config.h>
TEST_CASE("GetMatchTypeTest - ValidOperators") {
REQUIRE(get_match_type("a==b") == OP_EQ);
REQUIRE(get_match_type("a!=b") == OP_NEQ);
REQUIRE(get_match_type("a>b") == OP_GT);
REQUIRE(get_match_type("a>=b") == OP_GEQ);
REQUIRE(get_match_type("a<b") == OP_LT);
REQUIRE(get_match_type("a<=b") == OP_LEQ);
}
TEST_CASE("GetMatchTypeTest - InvalidOperators") {
REQUIRE(get_match_type("a=b") == -1);
REQUIRE(get_match_type("a!b") == -1);
REQUIRE(get_match_type("a=b") == -1);
}
TEST_CASE("GetMatchTypeTest - NoOperators") {
REQUIRE(get_match_type("abc") == -1);
REQUIRE(get_match_type("123") == -1);
REQUIRE(get_match_type("") == -1);
}
TEST_CASE("find_match_op identifies operators correctly", "[find_match_op]") {
SECTION("Single character operators") {
REQUIRE(find_match_op("a < b") == 2);
REQUIRE(find_match_op("a > b") == 2);
}
SECTION("Double character operators") {
REQUIRE(find_match_op("a == b") == 2);
REQUIRE(find_match_op("a != b") == 2);
REQUIRE(find_match_op("a >= b") == 2);
REQUIRE(find_match_op("a <= b") == 2);
}
SECTION("No operator present") { REQUIRE(find_match_op("a b") == -1); }
SECTION("Invalid operators") {
REQUIRE(find_match_op("a = b") == -1);
REQUIRE(find_match_op("a ! b") == -1);
}
SECTION("Operators at different positions") {
REQUIRE(find_match_op("x == y") == 2);
REQUIRE(find_match_op("x != y") == 2);
REQUIRE(find_match_op("x >= y") == 2);
REQUIRE(find_match_op("x <= y") == 2);
REQUIRE(find_match_op("x < y") == 2);
REQUIRE(find_match_op("x > y") == 2);
}
SECTION("Empty string") { REQUIRE(find_match_op("") == -1); }
}
TEST_CASE("GetMatchTypeTest - More test cases") {
REQUIRE(get_match_type("\"a!b\" == \"ab\"") == OP_EQ); // "a!b" == "ab"
REQUIRE(get_match_type("\"a!/b\" == \"a!/b\"") == OP_EQ); // "a!/b" == "a!/b"
REQUIRE(get_match_type("\"a!=/a==b\" == \"a!=/a==b\"") ==
OP_EQ); // "a!=/a==b" == "a!=/a==b"
REQUIRE(get_match_type("\"a!=/b==b\" == \"a!==/a==b\"") ==
OP_EQ); // "a!=/b==b" == "a!==/a==b"
REQUIRE(get_match_type("\"a!======b\" == \"!==/==\"") ==
OP_EQ); // "a!======b" == "!==/=="
REQUIRE(get_match_type("\" !=<>==\" == \" !=<>==\"") ==
OP_EQ); // " !=<>==" == " !=<>=="
REQUIRE(get_match_type("\"a!=><==\" < \"b!=><==\"") ==
OP_LT); // "a!=><==" < "b!=><=="
REQUIRE(get_match_type("\"!=<>==\" == \"!=<>==\"") ==
OP_EQ); // "!=<>==" == "!=<>=="
REQUIRE(get_match_type("\"=\" == \"=\"") == OP_EQ); // "=" == "="
REQUIRE(get_match_type("\"FRITZ!Box 7520 HI\" == \"off/any\"") ==
OP_EQ); // "FRITZ!Box 7520 HI" == "off/any"
}
TEST_CASE("CompareTest - ValidOperators") {
REQUIRE(compare("\"a\"==\"b\"") == 0);
REQUIRE(compare("\"a\"!=\"b\"") == 1);
REQUIRE(compare("\"a\">\"b\"") == 0);
REQUIRE(compare("\"a\">=\"b\"") == 0);
REQUIRE(compare("\"a\"<\"b\"") == 1);
REQUIRE(compare("\"a\"<=\"b\"") == 1);
}
TEST_CASE("CompareTest - ValidOperators with Integers") {
REQUIRE(compare("1==1") == 1);
REQUIRE(compare("1!=2") == 1);
REQUIRE(compare("2>1") == 1);
REQUIRE(compare("2>=1") == 1);
REQUIRE(compare("1<2") == 1);
REQUIRE(compare("1<=2") == 1);
}
TEST_CASE("CompareTest - ValidOperators with Doubles") {
REQUIRE(compare("1.0==1.0") == 1);
REQUIRE(compare("1.0!=2.0") == 1);
REQUIRE(compare("2.0>1.0") == 1);
REQUIRE(compare("2.0>=1.0") == 1);
REQUIRE(compare("1.0<2.0") == 1);
REQUIRE(compare("1.0<=2.0") == 1);
}
TEST_CASE("CompareTest - InvalidOperators") {
REQUIRE(compare("\"a\"=\"b\"") == -2);
REQUIRE(compare("\"a\"!\"b\"") == -2);
REQUIRE(compare("\"a\"=\"b\"") == -2);
}
TEST_CASE("CompareTest - NoOperators") {
REQUIRE(compare("abc") == -2);
REQUIRE(compare("123") == -2);
REQUIRE(compare("") == -2);
}
TEST_CASE("CompareTest - More test cases") {
REQUIRE(compare("\"a!b\" == \"ab\"") == 0); // "a!b" == "ab"
REQUIRE(compare("\"a!/b\" == \"a!/b\"") == 1); // "a!/b" == "a!/b"
REQUIRE(compare("\"a!=/a==b\" == \"a!=/a==b\"") ==
1); // "a!=/a==b" == "a!=/a==b"
REQUIRE(compare("\"a!=/b==b\" == \"a!==/a==b\"") ==
0); // "a!=/b==b" == "a!==/a==b"
REQUIRE(compare("\"a!======b\" == \"!==/==\"") ==
0); // "a!======b" == "!==/=="
REQUIRE(compare("\" !=<>==\" == \" !=<>==\"") ==
1); // " !=<>==" == " !=<>=="
REQUIRE(compare("\"a!=><==\" < \"b!=><==\"") == 1); // "a!=><==" < "b!=><=="
REQUIRE(compare("\"!=<>==\" == \"!=<>==\"") == 1); // "!=<>==" == "!=<>=="
REQUIRE(compare("\"=\" == \"=\"") == 1); // "=" == "="
REQUIRE(compare("\"FRITZ!Box 7520 HI\" == \"off/any\"") ==
0); // "FRITZ!Box 7520 HI" == "off/any"
}
| 4,879
|
C++
|
.cc
| 117
| 37.931624
| 80
| 0.470923
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,533
|
test-diskio.cc
|
brndnmtthws_conky/tests/test-diskio.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* 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 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 "catch2/catch.hpp"
#include <config.h>
#include <conky.h>
#include <diskio.h>
#if BUILD_X11
TEST_CASE("diskiographval returns correct value") {
struct text_object obj;
SECTION("for valid data") {
diskio_stat *diskio = new diskio_stat;
diskio->current = 2.5;
obj.data.opaque = diskio;
REQUIRE(diskiographval(&obj) == Approx(2.5));
delete diskio;
}
}
#endif
| 1,389
|
C++
|
.cc
| 43
| 29.930233
| 72
| 0.737117
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,534
|
test-conky.cc
|
brndnmtthws_conky/tests/test-conky.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* 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 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 "catch2/catch.hpp"
#include "conky.h"
#include "lua-config.hh"
TEST_CASE("Expressions can be evaluated", "[evaluate]") {
state = std::make_unique<lua::state>();
conky::export_symbols(*state);
SECTION("Simple expressions without substitutions can be evaluated") {
constexpr int kMaxSize = 10;
const char input[kMaxSize] = "text";
char result[kMaxSize]{'\0'};
evaluate(input, result, kMaxSize);
REQUIRE(strncmp(input, result, kMaxSize) == 0);
}
}
| 1,477
|
C++
|
.cc
| 41
| 33.609756
| 72
| 0.734637
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,535
|
test-colours.cc
|
brndnmtthws_conky/tests/test-colours.cc
|
#include "catch2/catch.hpp"
#include <colours.h>
#include <config.h>
TEST_CASE("parse_color correctly parses colours", "[colours][parse_color]") {
SECTION("parsing abbreviated hex color") {
auto colour = parse_color("#abc");
REQUIRE(colour.alpha == 255);
REQUIRE(colour.red == 0xaa);
REQUIRE(colour.green == 0xbb);
REQUIRE(colour.blue == 0xcc);
}
SECTION("parsing abbreviated hex color with alpha") {
auto colour = parse_color("#4abc");
REQUIRE(colour.alpha == 0x44);
REQUIRE(colour.red == 0xaa);
REQUIRE(colour.green == 0xbb);
REQUIRE(colour.blue == 0xcc);
}
SECTION("parsing hex red") {
auto colour = parse_color("#ff0000");
REQUIRE(colour.alpha == 255);
REQUIRE(colour.red == 255);
REQUIRE(colour.green == 0);
REQUIRE(colour.blue == 0);
}
SECTION("parsing hex green") {
auto colour = parse_color("#00ff00");
REQUIRE(colour.alpha == 255);
REQUIRE(colour.red == 0);
REQUIRE(colour.green == 255);
REQUIRE(colour.blue == 0);
}
SECTION("parsing hex blue") {
auto colour = parse_color("#0000ff");
REQUIRE(colour.alpha == 255);
REQUIRE(colour.red == 0);
REQUIRE(colour.green == 0);
REQUIRE(colour.blue == 255);
}
SECTION("parsing red") {
auto colour = parse_color("ff0000");
REQUIRE(colour.alpha == 255);
REQUIRE(colour.red == 255);
REQUIRE(colour.green == 0);
REQUIRE(colour.blue == 0);
}
SECTION("parsing green") {
auto colour = parse_color("00ff00");
REQUIRE(colour.alpha == 255);
REQUIRE(colour.red == 0);
REQUIRE(colour.green == 255);
REQUIRE(colour.blue == 0);
}
SECTION("parsing blue") {
auto colour = parse_color("0000ff");
REQUIRE(colour.alpha == 255);
REQUIRE(colour.red == 0);
REQUIRE(colour.green == 0);
REQUIRE(colour.blue == 255);
}
SECTION("argb values produce the expected result") {
auto colour = Colour::from_argb32(0x11223344);
REQUIRE(colour.alpha == 0x11);
REQUIRE(colour.red == 0x22);
REQUIRE(colour.green == 0x33);
REQUIRE(colour.blue == 0x44);
}
#ifdef BUILD_COLOUR_NAME_MAP
SECTION("it parses the colour 'red'") {
auto colour = parse_color("red");
REQUIRE(colour.alpha == 255);
REQUIRE(colour.red == 255);
REQUIRE(colour.green == 0);
REQUIRE(colour.blue == 0);
}
SECTION("it parses the colour 'green'") {
auto colour = parse_color("green");
REQUIRE(colour.alpha == 255);
REQUIRE(colour.red == 0);
REQUIRE(colour.green == 255);
REQUIRE(colour.blue == 0);
}
SECTION("it parses the colour 'blue'") {
auto colour = parse_color("blue");
REQUIRE(colour.alpha == 255);
REQUIRE(colour.red == 0);
REQUIRE(colour.green == 0);
REQUIRE(colour.blue == 255);
}
#endif /* BUILD_COLOUR_NAME_MAP */
SECTION("two identical colours should be equal") {
auto c = GENERATE(take(100, random((uint32_t)0, (uint32_t)0xffffffff)));
auto colour1 = Colour::from_argb32(c);
auto colour2 = Colour::from_argb32(c);
REQUIRE(colour1 == colour2);
}
}
| 3,060
|
C++
|
.cc
| 97
| 27.226804
| 77
| 0.642591
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,536
|
test-linux.cc
|
brndnmtthws_conky/tests/test-linux.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* 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 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 "catch2/catch.hpp"
#include <linux.h>
TEST_CASE("get_entropy_avail returns 0", "[get_entropy_avail]") {
unsigned int unused = 0;
REQUIRE(get_entropy_avail(&unused) == 0);
}
| 1,180
|
C++
|
.cc
| 33
| 33.757576
| 72
| 0.743881
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,537
|
test-fs.cc
|
brndnmtthws_conky/tests/test-fs.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* 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 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 "catch2/catch.hpp"
#include <fs.h>
TEST_CASE("fs_free_percentage returns correct value") {
struct text_object obj;
SECTION("for fs size == 0") {
fs_stat *fs = new fs_stat;
fs->size = 0;
fs->avail = 17;
fs->free = 97;
obj.data.opaque = fs;
REQUIRE(fs_free_percentage(&obj) == 0);
delete fs;
}
SECTION("for valid data") {
fs_stat *fs = new fs_stat;
fs->size = 68;
fs->avail = 17;
fs->free = 97;
obj.data.opaque = fs;
REQUIRE(fs_free_percentage(&obj) == 25);
delete fs;
}
}
| 1,548
|
C++
|
.cc
| 50
| 27.9
| 72
| 0.697377
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,538
|
nc.cc
|
brndnmtthws_conky/src/nc.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* 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 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 <config.h>
#include "nc.h"
#ifdef BUILD_NCURSES
WINDOW *ncurses_window;
#endif
namespace priv {
void out_to_ncurses_setting::lua_setter(lua::state &l, bool init) {
lua::stack_sentry s(l, -2);
Base::lua_setter(l, init);
if (init && do_convert(l, -1).first) {
ncurses_window = initscr();
start_color();
}
++s;
}
void out_to_ncurses_setting::cleanup(lua::state &l) {
lua::stack_sentry s(l, -1);
if (do_convert(l, -1).first) { endwin(); }
l.pop();
}
} // namespace priv
priv::out_to_ncurses_setting out_to_ncurses;
| 1,609
|
C++
|
.cc
| 50
| 29.94
| 72
| 0.722868
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,539
|
linux.cc
|
brndnmtthws_conky/src/linux.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2007 Toni Spets
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* 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 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 "linux.h"
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <limits.h>
#include <sys/stat.h>
#include <sys/sysinfo.h>
#include <sys/types.h>
#include <clocale>
#include "common.h"
#include "conky.h"
#include "diskio.h"
#include "logging.h"
#include "net_stat.h"
#include "proc.h"
#include "temphelper.h"
#ifndef HAVE_CLOCK_GETTIME
#include <sys/time.h>
#endif
#include <fcntl.h>
#include <unistd.h>
// #include <assert.h>
#include <time.h>
#include <unordered_map>
#include "setting.hh"
#include "top.h"
#include <arpa/inet.h>
#include <linux/sockios.h>
#include <net/if.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#ifdef _NET_IF_H
#define _LINUX_IF_H
#endif
#include <linux/route.h>
#include <linux/version.h>
#include <math.h>
#include <pthread.h>
#include <atomic>
#include <mutex>
/* The following ifdefs were adapted from gkrellm */
#include <linux/major.h>
#if !defined(MD_MAJOR)
#define MD_MAJOR 9
#endif
#if !defined(LVM_BLK_MAJOR)
#define LVM_BLK_MAJOR 58
#endif
#if !defined(NBD_MAJOR)
#define NBD_MAJOR 43
#endif
#if !defined(DM_MAJOR)
#define DM_MAJOR 253
#endif
#ifdef BUILD_WLAN
#include <iwlib.h>
#endif
struct sysfs {
int fd;
int arg;
char devtype[256];
char type[64];
float factor, offset;
};
/* To be used inside upspeed/f downspeed/f as ${gw_iface} variable */
char e_iface[64];
/* To use ${iface X} where X is a number and will
* return the current X NIC name */
static const unsigned int iface_len = 64U;
char interfaces_arr[MAX_NET_INTERFACES][iface_len] = {""};
#define SHORTSTAT_TEMPL "%*s %llu %llu %llu"
#define LONGSTAT_TEMPL "%*s %llu %llu %llu "
static conky::simple_config_setting<bool> top_cpu_separate("top_cpu_separate",
false, true);
/* This flag tells the linux routines to use the /proc system where possible,
* even if other api's are available, e.g. sysinfo() or getloadavg().
* the reason for this is to allow for /proc-based distributed monitoring.
* using a flag in this manner creates less confusing code. */
static int prefer_proc = 0;
/* To tell 'print_sysfs_sensor' whether to print the temperature
* in int or float */
static const char *temp2 = "empty";
void prepare_update(void) {}
int update_uptime(void) {
#ifdef HAVE_SYSINFO
if (!prefer_proc) {
struct sysinfo s_info;
sysinfo(&s_info);
info.uptime = (double)s_info.uptime;
} else
#endif
{
static int reported = 0;
FILE *fp;
if (!(fp = open_file("/proc/uptime", &reported))) {
info.uptime = 0.0;
return 0;
}
if (fscanf(fp, "%lf", &info.uptime) <= 0) info.uptime = 0;
fclose(fp);
}
return 0;
}
int check_mount(struct text_object *obj) {
int ret = 0;
FILE *mtab;
if (!obj->data.s) return 0;
if ((mtab = fopen("/proc/mounts", "r"))) {
char buf1[256], buf2[129];
while (fgets(buf1, 256, mtab)) {
sscanf(buf1, "%*s %128s", buf2);
if (!strcmp(obj->data.s, buf2)) {
ret = 1;
break;
}
}
fclose(mtab);
} else {
NORM_ERR("Could not open mtab");
}
return ret;
}
/* these things are also in sysinfo except Buffers:
* (that's why I'm reading them from proc) */
int update_meminfo(void) {
FILE *meminfo_fp;
static int reported = 0;
/* unsigned int a; */
char buf[256];
/* With multi-threading, calculations that require
* multiple steps to reach a final result can cause havok
* if the intermediary calculations are directly assigned to the
* information struct (they may be read by other functions in the meantime).
* These variables keep the calculations local to the function and finish off
* the function by assigning the results to the information struct */
unsigned long long sreclaimable = 0, curmem = 0, curbufmem = 0,
cureasyfree = 0;
info.memmax = info.memdirty = info.swap = info.swapfree = info.swapmax =
info.memwithbuffers = info.buffers = info.cached = info.memfree =
info.memeasyfree = info.legacymem = info.shmem = info.memavail =
info.free_bufcache = info.free_cached = 0;
if (!(meminfo_fp = open_file("/proc/meminfo", &reported))) { return 0; }
while (!feof(meminfo_fp)) {
if (fgets(buf, 255, meminfo_fp) == nullptr) { break; }
if (strncmp(buf, "MemTotal:", 9) == 0) {
sscanf(buf, "%*s %llu", &info.memmax);
} else if (strncmp(buf, "MemFree:", 8) == 0) {
sscanf(buf, "%*s %llu", &info.memfree);
} else if (strncmp(buf, "SwapTotal:", 10) == 0) {
sscanf(buf, "%*s %llu", &info.swapmax);
} else if (strncmp(buf, "SwapFree:", 9) == 0) {
sscanf(buf, "%*s %llu", &info.swapfree);
} else if (strncmp(buf, "Buffers:", 8) == 0) {
sscanf(buf, "%*s %llu", &info.buffers);
} else if (strncmp(buf, "Cached:", 7) == 0) {
sscanf(buf, "%*s %llu", &info.cached);
} else if (strncmp(buf, "Dirty:", 6) == 0) {
sscanf(buf, "%*s %llu", &info.memdirty);
} else if (strncmp(buf, "MemAvailable:", 13) == 0) {
sscanf(buf, "%*s %llu", &info.memavail);
} else if (strncmp(buf, "Shmem:", 6) == 0) {
sscanf(buf, "%*s %llu", &info.shmem);
} else if (strncmp(buf, "SReclaimable:", 13) == 0) {
sscanf(buf, "%*s %llu", &sreclaimable);
}
}
curmem = info.memwithbuffers = info.memmax - info.memfree;
cureasyfree = info.memfree;
info.swap = info.swapmax - info.swapfree;
/* Reclaimable memory: does not include shared memory, which is part of cached
but unreclaimable. Includes the reclaimable part of the Slab cache though.
Note: when shared memory is swapped out, shmem decreases and swapfree
decreases - we want this.
*/
curbufmem = (info.cached - info.shmem) + info.buffers + sreclaimable;
/* Calculate the memory usage.
*
* The Linux Kernel introduced a new field for memory available,
* when possible, use that.
* https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773
*/
if (no_buffers.get(*state)) {
#if LINUX_VERSION_CODE <= KERNEL_VERSION(3, 14, 0)
/* Now ('info.mem' - 'info.bufmem') is the *really used* (aka unreclaimable)
memory. When this value reaches the size of the physical RAM, and swap is
full or non-present, OOM happens. Therefore this is the value users want
to monitor, regarding their RAM.
*/
curmem -= curbufmem;
cureasyfree += curbufmem;
#else /* LINUX_VERSION_CODE <= KERNEL_VERSION(3, 14, 0) */
curmem = info.memmax - info.memavail;
cureasyfree += curbufmem;
#endif /* LINUX_VERSION_CODE <= KERNEL_VERSION(3, 14, 0) */
}
/* Now that we know that every calculation is finished we can wrap up
* by assigning the values to the information structure */
info.mem = curmem;
info.bufmem = curbufmem;
info.memeasyfree = cureasyfree;
info.legacymem =
info.memmax - (info.memfree + info.buffers + info.cached + sreclaimable);
info.free_cached = info.cached + sreclaimable;
info.free_bufcache = info.free_cached + info.buffers;
fclose(meminfo_fp);
return 0;
}
void print_laptop_mode(struct text_object *obj, char *p,
unsigned int p_max_size) {
FILE *fp;
int val = -1;
(void)obj;
if ((fp = fopen("/proc/sys/vm/laptop_mode", "r")) != nullptr) {
if (fscanf(fp, "%d\n", &val) <= 0) val = 0;
fclose(fp);
}
snprintf(p, p_max_size, "%d", val);
}
/* my system says:
* # cat /sys/block/sda/queue/scheduler
* noop [anticipatory] cfq
*/
void print_ioscheduler(struct text_object *obj, char *p,
unsigned int p_max_size) {
FILE *fp;
char buf[128];
if (!obj->data.s) goto out_fail;
snprintf(buf, 127, "/sys/block/%s/queue/scheduler", obj->data.s);
if ((fp = fopen(buf, "r")) == nullptr) goto out_fail;
while (fscanf(fp, "%127s", buf) == 1) {
if (buf[0] == '[') {
buf[strlen(buf) - 1] = '\0';
snprintf(p, p_max_size, "%s", buf + 1);
fclose(fp);
return;
}
}
fclose(fp);
out_fail:
snprintf(p, p_max_size, "%s", "n/a");
return;
}
class gw_info_s {
public:
gw_info_s() : iface(nullptr), ip(nullptr), count(0) {}
char *iface;
char *ip;
std::atomic<int> count;
std::mutex mutex;
void reset() {
std::lock_guard<std::mutex> lock(mutex);
free_and_zero(iface);
free_and_zero(ip);
}
};
static gw_info_s gw_info;
char *save_set_string(char *x, char *y) {
if (x != nullptr && strcmp((char *)x, (char *)y)) {
free_and_zero(x);
x = strndup("multiple", text_buffer_size.get(*state));
} else if (x == nullptr && y != nullptr) {
x = strndup(y, text_buffer_size.get(*state));
}
return x;
}
void update_gateway_info_failure(const char *reason) {
if (reason != nullptr) { perror(reason); }
// 2 pointers to 1 location causes a crash when we try to free them both
std::unique_lock<std::mutex> lock(gw_info.mutex);
free_and_zero(gw_info.iface);
free_and_zero(gw_info.ip);
gw_info.iface = strndup("failed", text_buffer_size.get(*state));
gw_info.ip = strndup("failed", text_buffer_size.get(*state));
}
/* Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT */
#define RT_ENTRY_FORMAT "%63s %lx %lx %x %*d %*d %*d %lx %*d %*d %*d\n"
FILE *check_procroute() {
FILE *fp;
if ((fp = fopen("/proc/net/route", "r")) == nullptr) {
update_gateway_info_failure("fopen()");
return nullptr;
}
/* skip over the table header line, which is always present */
if (fscanf(fp, "%*[^\n]\n") < 0) {
fclose(fp);
return nullptr;
}
return fp;
}
int update_gateway_info2(void) {
FILE *fp;
char iface[iface_len];
unsigned long dest;
unsigned long gate;
unsigned long mask;
unsigned int flags;
unsigned int x = 1;
unsigned int z = 1;
int strcmpreturn;
if ((fp = check_procroute()) != nullptr) {
while (!feof(fp)) {
strcmpreturn = 1;
if (fscanf(fp, RT_ENTRY_FORMAT, iface, &dest, &gate, &flags, &mask) !=
5) {
update_gateway_info_failure("fscanf()");
break;
}
if (!(dest || mask) && ((flags & RTF_GATEWAY) || !gate)) {
snprintf(e_iface, 64, "%s", iface);
}
if (1U == x) {
snprintf(interfaces_arr[x++], iface_len, "%s", iface);
continue;
} else if (0 == strcmp(iface, interfaces_arr[x - 1])) {
continue;
}
for (z = 1; z < iface_len - 1 && strcmpreturn == 1; z++) {
strcmpreturn = strcmp(iface, interfaces_arr[z]);
}
if (strcmpreturn == 1) {
snprintf(interfaces_arr[x++], iface_len, "%s", iface);
}
}
fclose(fp);
}
return 0;
}
int update_gateway_info(void) {
FILE *fp;
struct in_addr ina;
char iface[iface_len];
unsigned long dest, gate, mask;
unsigned int flags;
gw_info.reset();
gw_info.count = 0;
if ((fp = check_procroute()) != nullptr) {
while (!feof(fp)) {
if (fscanf(fp, RT_ENTRY_FORMAT, iface, &dest, &gate, &flags, &mask) !=
5) {
update_gateway_info_failure("fscanf()");
break;
}
if (!(dest || mask) && ((flags & RTF_GATEWAY) || !gate)) {
gw_info.count++;
snprintf(e_iface, 64, "%s", iface);
std::unique_lock<std::mutex> lock(gw_info.mutex);
gw_info.iface = save_set_string(gw_info.iface, iface);
ina.s_addr = gate;
gw_info.ip = save_set_string(gw_info.ip, inet_ntoa(ina));
}
}
fclose(fp);
}
return 0;
}
void free_gateway_info(struct text_object *obj) {
(void)obj;
gw_info.reset();
}
int gateway_exists(struct text_object *obj) {
(void)obj;
return !!gw_info.count;
}
void print_gateway_iface(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
std::lock_guard<std::mutex> lock(gw_info.mutex);
snprintf(p, p_max_size, "%s", gw_info.iface);
}
void print_gateway_iface2(struct text_object *obj, char *p,
unsigned int p_max_size) {
long int z = 0;
unsigned int x = 1;
unsigned int found = 0;
char buf[iface_len * iface_len] = {""};
char *buf_ptr = buf;
if (0 == strcmp(obj->data.s, "")) {
for (; x < iface_len - 1; x++) {
if (0 == strcmp("", interfaces_arr[x])) { break; }
buf_ptr += snprintf(buf_ptr, iface_len - 1, "%s, ", interfaces_arr[x]);
found = 1;
}
if (1 == found) {
--buf_ptr;
*(--buf_ptr) = '\0';
}
snprintf(p, p_max_size, "%s", buf);
return;
}
z = strtol(obj->data.s, (char **)NULL, 10);
if ((iface_len - 1) > z) { snprintf(p, p_max_size, "%s", interfaces_arr[z]); }
}
void print_gateway_ip(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
std::lock_guard<std::mutex> lock(gw_info.mutex);
snprintf(p, p_max_size, "%s", gw_info.ip);
}
void update_net_interfaces(FILE *net_dev_fp, bool is_first_update,
double time_between_updates) {
/* read each interface */
#ifdef BUILD_WLAN
// wireless info variables
struct wireless_info *winfo;
struct iwreq wrq;
#endif
for (int i = 0; i < MAX_NET_INTERFACES; i++) {
struct net_stat *ns;
char *s, *p;
long long r, t, last_recv, last_trans;
/* quit only after all non-header lines from /proc/net/dev parsed */
// FIXME: arbitrary size chosen to keep code simple.
char buf[256];
if (fgets(buf, 255, net_dev_fp) == nullptr) { break; }
p = buf;
/* change char * p to first non-space character, which is the beginning
* of the interface name */
while (*p != '\0' && isspace((unsigned char)*p)) { p++; }
s = p;
/* increment p until the end of the interface name has been reached */
while (*p != '\0' && *p != ':') { p++; }
if (*p == '\0') { continue; }
/* replace ':' with '\0' in output of /proc/net/dev */
*p = '\0';
p++;
/* get pointer to interface statistics with the interface name in s */
ns = get_net_stat(s, nullptr, NULL);
ns->up = 1;
memset(&(ns->addr.sa_data), 0, 14);
memset(ns->addrs, 0,
17 * MAX_NET_INTERFACES +
1); /* Up to 17 chars per ip, max MAX_NET_INTERFACES interfaces.
Nasty memory usage... */
/* bytes packets errs drop fifo frame compressed multicast|bytes ... */
sscanf(p, "%lld %*d %*d %*d %*d %*d %*d %*d %lld",
&r, &t);
/* if the interface is parsed the first time, then set recv and trans
* to currently received, meaning the change in network traffic is 0 */
if (ns->last_read_recv == -1) {
ns->recv = r;
is_first_update = true;
ns->last_read_recv = r;
}
if (ns->last_read_trans == -1) {
ns->trans = t;
is_first_update = true;
ns->last_read_trans = t;
}
/* move current traffic statistic to last thereby obsoleting the
* current statistic */
last_recv = ns->recv;
last_trans = ns->trans;
/* If recv or trans is less than last time, an overflow happened.
* In that case set the last traffic to the current one, don't set
* it to 0, else a spike in the download and upload speed will occur! */
if (r < ns->last_read_recv) {
last_recv = r;
} else {
ns->recv += (r - ns->last_read_recv);
}
ns->last_read_recv = r;
if (t < ns->last_read_trans) {
last_trans = t;
} else {
ns->trans += (t - ns->last_read_trans);
}
ns->last_read_trans = t;
/*** ip addr patch ***/
int file_descriptor = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
struct ifconf conf;
conf.ifc_buf = (char *)malloc(sizeof(struct ifreq) * MAX_NET_INTERFACES);
conf.ifc_len = sizeof(struct ifreq) * MAX_NET_INTERFACES;
memset(conf.ifc_buf, 0, conf.ifc_len);
ioctl(file_descriptor, SIOCGIFCONF, &conf);
for (unsigned int k = 0; k < conf.ifc_len / sizeof(struct ifreq); k++) {
struct net_stat *ns2;
ns2 = get_net_stat(conf.ifc_req[k].ifr_ifrn.ifrn_name, nullptr, NULL);
ns2->addr = conf.ifc_req[k].ifr_ifru.ifru_addr;
char temp_addr[18];
snprintf(temp_addr, sizeof(temp_addr), "%u.%u.%u.%u, ",
ns2->addr.sa_data[2] & 255, ns2->addr.sa_data[3] & 255,
ns2->addr.sa_data[4] & 255, ns2->addr.sa_data[5] & 255);
if (nullptr == strstr(ns2->addrs, temp_addr))
strncpy(ns2->addrs + strlen(ns2->addrs), temp_addr, 17);
}
close(file_descriptor);
free(conf.ifc_buf);
/*** end ip addr patch ***/
if (!is_first_update) {
/* calculate instantaneous speeds */
ns->net_rec[0] = (ns->recv - last_recv) / time_between_updates;
ns->net_trans[0] = (ns->trans - last_trans) / time_between_updates;
}
unsigned int curtmp1 = 0;
unsigned int curtmp2 = 0;
/* get an average over the last speed samples */
int samples = net_avg_samples.get(*state);
/* is OpenMP actually useful here? How large is samples? > 1000 ? */
#ifdef HAVE_OPENMP
#pragma omp parallel for reduction(+ : curtmp1, curtmp2) schedule(dynamic, 10)
#endif /* HAVE_OPENMP */
for (int j = 0; j < samples; j++) {
curtmp1 = curtmp1 + ns->net_rec[j];
curtmp2 = curtmp2 + ns->net_trans[j];
}
ns->recv_speed = curtmp1 / (double)samples;
ns->trans_speed = curtmp2 / (double)samples;
if (samples > 1) {
#ifdef HAVE_OPENMP
#pragma omp parallel for schedule(dynamic, 10)
#endif /* HAVE_OPENMP */
for (int j = samples; j > 1; j--) {
ns->net_rec[j - 1] = ns->net_rec[j - 2];
ns->net_trans[j - 1] = ns->net_trans[j - 2];
}
}
#ifdef BUILD_WLAN
/* update wireless info */
winfo = (struct wireless_info *)malloc(sizeof(struct wireless_info));
memset(winfo, 0, sizeof(struct wireless_info));
int skfd = iw_sockets_open();
if (iw_get_basic_config(skfd, s, &(winfo->b)) > -1) {
// set present winfo variables
if (iw_get_range_info(skfd, s, &(winfo->range)) >= 0) {
winfo->has_range = 1;
}
if (iw_get_stats(skfd, s, &(winfo->stats), &winfo->range,
winfo->has_range) >= 0) {
winfo->has_stats = 1;
}
if (iw_get_ext(skfd, s, SIOCGIWAP, &wrq) >= 0) {
winfo->has_ap_addr = 1;
memcpy(&(winfo->ap_addr), &(wrq.u.ap_addr), sizeof(sockaddr));
}
// get bitrate
if (iw_get_ext(skfd, s, SIOCGIWRATE, &wrq) >= 0) {
memcpy(&(winfo->bitrate), &(wrq.u.bitrate), sizeof(iwparam));
iw_print_bitrate(ns->bitrate, 16, winfo->bitrate.value);
}
// get link quality
if (winfo->has_range && winfo->has_stats) {
bool has_qual_level = (winfo->stats.qual.level != 0) ||
(winfo->stats.qual.updated & IW_QUAL_DBM);
if (has_qual_level &&
!(winfo->stats.qual.updated & IW_QUAL_QUAL_INVALID)) {
ns->link_qual = winfo->stats.qual.qual;
if (winfo->range.max_qual.qual > 0) {
ns->link_qual_max = winfo->range.max_qual.qual;
}
}
}
// get ap mac
if (winfo->has_ap_addr) { iw_sawap_ntop(&winfo->ap_addr, ns->ap); }
// get essid
if (winfo->b.has_essid) {
if (winfo->b.essid_on) {
snprintf(ns->essid, 34, "%s", winfo->b.essid);
} else {
snprintf(ns->essid, 34, "%s", "off/any");
}
}
// get channel and freq
if (winfo->b.has_freq) {
if (winfo->has_range == 1) {
ns->channel = iw_freq_to_channel(winfo->b.freq, &(winfo->range));
iw_print_freq_value(ns->freq, 16, winfo->b.freq);
} else {
ns->channel = 0;
ns->freq[0] = 0;
}
}
snprintf(ns->mode, 16, "%s", iw_operation_mode[winfo->b.mode]);
}
iw_sockets_close(skfd);
free(winfo);
#endif
}
}
#ifdef BUILD_IPV6
void update_ipv6_net_stats() {
FILE *file;
char v6addr[33];
char devname[21];
unsigned int netmask, scope;
struct net_stat *ns;
struct v6addr *lastv6;
// remove the old v6 addresses otherwise they are listed multiple times
for (unsigned int i = 0; i < MAX_NET_INTERFACES; i++) {
ns = &netstats[i];
while (ns->v6addrs != nullptr) {
lastv6 = ns->v6addrs;
ns->v6addrs = ns->v6addrs->next;
free(lastv6);
}
}
if ((file = fopen(PROCDIR "/net/if_inet6", "r")) == nullptr) { return; }
while (fscanf(file, "%32s %*02x %02x %02x %*02x %20s\n", v6addr, &netmask,
&scope, devname) != EOF) {
ns = get_net_stat(devname, nullptr, NULL);
if (ns->v6addrs == nullptr) {
lastv6 = (struct v6addr *)malloc(sizeof(struct v6addr));
ns->v6addrs = lastv6;
} else {
lastv6 = ns->v6addrs;
while (lastv6->next) lastv6 = lastv6->next;
lastv6->next = (struct v6addr *)malloc(sizeof(struct v6addr));
lastv6 = lastv6->next;
}
for (int i = 0; i < 16; i++)
sscanf(v6addr + 2 * i, "%2hhx", &(lastv6->addr.s6_addr[i]));
lastv6->netmask = netmask;
switch (scope) {
case 0: // global
lastv6->scope = 'G';
break;
case 16: // host-local
lastv6->scope = 'H';
break;
case 32: // link-local
lastv6->scope = 'L';
break;
case 64: // site-local
lastv6->scope = 'S';
break;
case 128: // compat
lastv6->scope = 'C';
break;
default:
lastv6->scope = '?';
}
lastv6->next = nullptr;
}
fclose(file);
}
#endif /* BUILD_IPV6 */
/**
* Parses information from /proc/net/dev and stores them in ???
*
* For the output format of /proc/net/dev @see http://linux.die.net/man/5/proc
*
* @return always returns 0. May change in the future, e.g. returning non zero
* if some error happened
**/
int update_net_stats(void) {
update_gateway_info();
update_gateway_info2();
FILE *net_dev_fp;
static int reported = 0;
/* variable to notify the parts averaging the download speed, that this
* is the first call ever to this function. This variable can't be used
* to decide if this is the first time an interface was parsed as there
* are many interfaces, which can be activated and deactivated at arbitrary
* times */
static bool is_first_update = true;
// FIXME: arbitrary size chosen to keep code simple.
char buf[256];
double time_between_updates;
/* get delta */
time_between_updates = current_update_time - last_update_time;
if (time_between_updates <= 0.0001) { return 0; }
/* open file /proc/net/dev. If not something went wrong, clear all
* network statistics */
if (!(net_dev_fp = open_file("/proc/net/dev", &reported))) {
clear_net_stats();
return 0;
}
/* ignore first two header lines in file /proc/net/dev. If somethings
* goes wrong, e.g. end of file reached, quit.
* (Why isn't clear_net_stats called for this case ??? */
char *one = fgets(buf, 255, net_dev_fp);
char *two = fgets(buf, 255, net_dev_fp);
if (!one || /* garbage */
!two) { /* garbage (field names) */
fclose(net_dev_fp);
return 0;
}
update_net_interfaces(net_dev_fp, is_first_update, time_between_updates);
#ifdef BUILD_IPV6
update_ipv6_net_stats();
#endif /* BUILD_IPV6 */
is_first_update = false;
fclose(net_dev_fp);
return 0;
}
int result;
int update_total_processes(void) {
DIR *dir;
struct dirent *entry;
int ignore1;
char ignore2;
info.procs = 0;
dir = opendir("/proc");
if (dir) {
while ((entry = readdir(dir))) {
if (sscanf(entry->d_name, "%d%c", &ignore1, &ignore2) == 1) {
info.procs++;
}
}
closedir(dir);
}
return 0;
}
int update_threads(void) {
#ifdef HAVE_SYSINFO
if (!prefer_proc) {
struct sysinfo s_info;
sysinfo(&s_info);
info.threads = s_info.procs;
} else
#endif
{
static int reported = 0;
FILE *fp;
if (!(fp = open_file("/proc/loadavg", &reported))) {
info.threads = 0;
return 0;
}
if (fscanf(fp, "%*f %*f %*f %*d/%hu", &info.threads) <= 0) info.threads = 0;
fclose(fp);
}
return 0;
}
#define CPU_SAMPLE_COUNT 15
struct cpu_info {
unsigned long long cpu_user;
unsigned long long cpu_system;
unsigned long long cpu_nice;
unsigned long long cpu_idle;
unsigned long long cpu_iowait;
unsigned long long cpu_irq;
unsigned long long cpu_softirq;
unsigned long long cpu_steal;
unsigned long long cpu_total;
unsigned long long cpu_active_total;
unsigned long long cpu_last_total;
unsigned long long cpu_last_active_total;
double cpu_val[CPU_SAMPLE_COUNT];
};
static short cpu_setup = 0;
/* Determine if this kernel gives us "extended" statistics information in
* /proc/stat.
* Kernels around 2.5 and earlier only reported user, system, nice, and
* idle values in proc stat.
* Kernels around 2.6 and greater report these PLUS iowait, irq, softirq,
* and steal */
void determine_longstat(char *buf) {
unsigned long long iowait = 0;
KFLAG_SETOFF(KFLAG_IS_LONGSTAT);
/* scanf will either return -1 or 1 because there is only 1 assignment */
if (sscanf(buf, "%*s %*d %*d %*d %*d %llu", &iowait) > 0) {
KFLAG_SETON(KFLAG_IS_LONGSTAT);
}
}
void determine_longstat_file(void) {
#define MAX_PROCSTAT_LINELEN 255
FILE *stat_fp;
static int reported = 0;
char buf[MAX_PROCSTAT_LINELEN + 1];
static int stat_initialized = 0;
/* only execute once */
if (stat_initialized) return;
if (!(stat_fp = open_file("/proc/stat", &reported))) return;
while (!feof(stat_fp) &&
fgets(buf, MAX_PROCSTAT_LINELEN, stat_fp) != nullptr) {
if (strncmp(buf, "cpu", 3) == 0) {
determine_longstat(buf);
break;
}
}
fclose(stat_fp);
stat_initialized = 1;
}
void get_cpu_count(void) {
FILE *stat_fp;
static int reported = 0;
char buf[256];
char *str1, *str2, *token, *subtoken;
char *saveptr1, *saveptr2;
int subtoken1 = -1;
int subtoken2 = -1;
if (info.cpu_usage) { return; }
if (!(stat_fp = open_file("/sys/devices/system/cpu/present", &reported))) {
return;
}
info.cpu_count = 0;
while (!feof(stat_fp)) {
if (fgets(buf, 255, stat_fp) == nullptr) { break; }
// Do some parsing here to handle skipped cpu numbers. For example,
// for an AMD FX(tm)-6350 Six-Core Processor /sys/.../present reports
// "0,3-7". I assume that chip is really an 8-core die with two cores
// disabled... Presumably you could also get "0,3-4,6", and other
// combos too...
for (str1 = buf;; str1 = nullptr) {
token = strtok_r(str1, ",", &saveptr1);
if (token == nullptr) break;
++info.cpu_count;
subtoken1 = -1;
subtoken2 = -1;
for (str2 = token;; str2 = nullptr) {
subtoken = strtok_r(str2, "-", &saveptr2);
if (subtoken == nullptr) break;
if (subtoken1 < 0)
subtoken1 = strtol(subtoken, nullptr, 10);
else
subtoken2 = strtol(subtoken, nullptr, 10);
}
if (subtoken2 > 0) info.cpu_count += subtoken2 - subtoken1;
}
}
info.cpu_usage = (float *)malloc((info.cpu_count + 1) * sizeof(float));
fclose(stat_fp);
}
#define TMPL_LONGSTAT "%*s %llu %llu %llu %llu %llu %llu %llu %llu"
#define TMPL_SHORTSTAT "%*s %llu %llu %llu %llu"
int update_stat(void) {
FILE *stat_fp;
static int reported = 0;
struct cpu_info *cpu = nullptr;
char buf[256];
int i;
unsigned int idx;
double curtmp;
const char *stat_template = nullptr;
unsigned int malloc_cpu_size = 0;
extern void *global_cpu;
static pthread_mutex_t last_stat_update_mutex = PTHREAD_MUTEX_INITIALIZER;
static double last_stat_update = 0.0;
float cur_total = 0.0;
/* since we use wrappers for this function, the update machinery
* can't eliminate double invocations of this function. Check for
* them here, otherwise cpu_usage counters are freaking out. */
pthread_mutex_lock(&last_stat_update_mutex);
if (last_stat_update == current_update_time) {
pthread_mutex_unlock(&last_stat_update_mutex);
return 0;
}
last_stat_update = current_update_time;
pthread_mutex_unlock(&last_stat_update_mutex);
/* add check for !info.cpu_usage since that mem is freed on a SIGUSR1 */
if (!cpu_setup || !info.cpu_usage) {
get_cpu_count();
cpu_setup = 1;
}
if (!stat_template) {
determine_longstat_file();
stat_template =
KFLAG_ISSET(KFLAG_IS_LONGSTAT) ? TMPL_LONGSTAT : TMPL_SHORTSTAT;
}
if (global_cpu) {
cpu = reinterpret_cast<struct cpu_info *>(global_cpu);
} else {
malloc_cpu_size = (info.cpu_count + 1) * sizeof(struct cpu_info);
cpu = (struct cpu_info *)malloc(malloc_cpu_size);
memset(cpu, 0, malloc_cpu_size);
global_cpu = cpu;
}
if (!(stat_fp = open_file("/proc/stat", &reported))) {
info.run_threads = 0;
if (info.cpu_usage) {
memset(info.cpu_usage, 0, info.cpu_count * sizeof(float));
}
return 0;
}
idx = 0;
while (!feof(stat_fp)) {
if (fgets(buf, 255, stat_fp) == nullptr) { break; }
if (strncmp(buf, "procs_running ", 14) == 0) {
sscanf(buf, "%*s %hu", &info.run_threads);
} else if (strncmp(buf, "cpu", 3) == 0) {
double delta;
if (isdigit((unsigned char)buf[3])) {
idx++; // just increment here since the CPU index can skip numbers
} else {
idx = 0;
}
if (idx > info.cpu_count) { continue; }
sscanf(buf, stat_template, &(cpu[idx].cpu_user), &(cpu[idx].cpu_nice),
&(cpu[idx].cpu_system), &(cpu[idx].cpu_idle),
&(cpu[idx].cpu_iowait), &(cpu[idx].cpu_irq),
&(cpu[idx].cpu_softirq), &(cpu[idx].cpu_steal));
cpu[idx].cpu_total = cpu[idx].cpu_user + cpu[idx].cpu_nice +
cpu[idx].cpu_system + cpu[idx].cpu_idle +
cpu[idx].cpu_iowait + cpu[idx].cpu_irq +
cpu[idx].cpu_softirq + cpu[idx].cpu_steal;
cpu[idx].cpu_active_total =
cpu[idx].cpu_total - (cpu[idx].cpu_idle + cpu[idx].cpu_iowait);
delta = current_update_time - last_update_time;
if (delta <= 0.001) { break; }
cur_total = (float)(cpu[idx].cpu_total - cpu[idx].cpu_last_total);
if (cur_total == 0.0) {
cpu[idx].cpu_val[0] = 1.0;
} else {
cpu[idx].cpu_val[0] =
(cpu[idx].cpu_active_total - cpu[idx].cpu_last_active_total) /
cur_total;
}
curtmp = 0;
int samples = std::min(cpu_avg_samples.get(*state), CPU_SAMPLE_COUNT);
for (i = 0; i < samples; i++) { curtmp = curtmp + cpu[idx].cpu_val[i]; }
info.cpu_usage[idx] = curtmp / samples;
cpu[idx].cpu_last_total = cpu[idx].cpu_total;
cpu[idx].cpu_last_active_total = cpu[idx].cpu_active_total;
for (i = samples - 1; i > 0 && i < CPU_SAMPLE_COUNT; i--) {
cpu[idx].cpu_val[i] = cpu[idx].cpu_val[i - 1];
}
}
}
fclose(stat_fp);
return 0;
}
int update_running_processes(void) {
update_stat();
return 0;
}
int update_cpu_usage(void) {
struct timespec tc = {0L, 100L * 1000000L};
update_stat();
if (-1 == (nanosleep(&tc, NULL))) {
NORM_ERR("update_cpu_usage(): nanosleep() failed");
return 0;
}
update_stat();
return 0;
}
void free_cpu(struct text_object *) { /* no-op */
}
// fscanf() that reads floats with points even if you are using a locale where
// floats are with commas
int fscanf_no_i18n(FILE *stream, const char *format, ...) {
int returncode;
va_list ap;
#ifdef BUILD_I18N
char *oldlocale = strdup(setlocale(LC_NUMERIC, nullptr));
setlocale(LC_NUMERIC, "C");
#endif
va_start(ap, format);
returncode = vfscanf(stream, format, ap);
va_end(ap);
#ifdef BUILD_I18N
setlocale(LC_NUMERIC, oldlocale);
free(oldlocale);
#endif
return returncode;
}
int update_load_average(void) {
#ifdef HAVE_GETLOADAVG
if (!prefer_proc) {
double v[3];
getloadavg(v, 3);
info.loadavg[0] = (float)v[0];
info.loadavg[1] = (float)v[1];
info.loadavg[2] = (float)v[2];
} else
#endif
{
static int reported = 0;
FILE *fp;
if (!(fp = open_file("/proc/loadavg", &reported))) {
info.loadavg[0] = info.loadavg[1] = info.loadavg[2] = 0.0;
return 0;
}
if (fscanf_no_i18n(fp, "%f %f %f", &info.loadavg[0], &info.loadavg[1],
&info.loadavg[2]) < 0)
info.loadavg[0] = info.loadavg[1] = info.loadavg[2] = 0.0;
fclose(fp);
}
return 0;
}
/***********************************************************/
/***********************************************************/
/***********************************************************/
static int no_dots(const struct dirent *d) {
if (d->d_name[0] == '.') { return 0; }
return 1;
}
static int get_first_file_in_a_directory(const char *dir, char *s,
int *reported) {
struct dirent **namelist;
int i, n;
n = scandir(dir, &namelist, no_dots, alphasort);
if (n < 0) {
if (!reported || !*reported) {
NORM_ERR("scandir for %s: %s", dir, strerror(errno));
if (reported) { *reported = 1; }
}
return 0;
} else {
if (n == 0) { return 0; }
strncpy(s, namelist[0]->d_name, 255);
s[255] = '\0';
for (i = 0; i < n; i++) { free(namelist[i]); }
free(namelist);
return 1;
}
}
/*
* Convert @dev "0" (hwmon number) or "k10temp" (hwmon name) to "hwmon2/device"
*/
static void get_dev_path(const char *dir, const char *dev, char *out_buf) {
struct dirent **namelist;
char path[512] = {'\0'};
char name[512] = {'\0'};
bool found = false;
size_t size;
int name_fd;
int i;
int n;
int ret;
/* "0" numbered case */
ret = sscanf(dev, "%d", &n);
if (ret == 1) {
snprintf(out_buf, 256, "hwmon%d/device", n);
return;
}
/* "k10temp" name case, need to search hwmon*->name to find a match */
n = scandir(dir, &namelist, no_dots, alphasort);
if (n < 0) {
NORM_ERR("scandir for %s: %s", dir, strerror(errno));
goto not_found;
}
if (n == 0) goto not_found;
/* Search each hwmon%s/name */
for (i = 0; i < n; i++) {
if (found) continue;
snprintf(path, 512, "%s%s/name", dir, namelist[i]->d_name);
name_fd = open(path, O_RDONLY);
if (name_fd < 0) {
snprintf(path, 512, "%s%s/device/name", dir, namelist[i]->d_name);
name_fd = open(path, O_RDONLY);
if (name_fd < 0) continue;
}
size = read(name_fd, name, strlen(dev));
if (size < strlen(dev)) {
close(name_fd);
continue;
}
ret = strncmp(dev, name, strlen(dev));
if (!ret) {
found = true;
snprintf(out_buf, 512, "%s/device", namelist[i]->d_name);
}
close(name_fd);
}
/* cleanup */
for (i = 0; i < n; i++) free(namelist[i]);
free(namelist);
if (found) return;
not_found:
out_buf[0] = '\0';
return;
}
static int open_sysfs_sensor(const char *dir, const char *dev, const char *type,
int n, int *divisor, char *devtype) {
char path[256];
char buf[512];
int fd;
int divfd;
memset(buf, 0, sizeof(buf));
/* if device is nullptr or *, get first */
if (dev == nullptr || strcmp(dev, "*") == 0) {
static int reported = 0;
if (!get_first_file_in_a_directory(dir, buf, &reported)) { return -1; }
dev = buf;
}
if (strcmp(dir, "/sys/class/hwmon/") == 0) {
if (*buf) {
/* buf holds result from get_first_file_in_a_directory() above,
* e.g. "hwmon0" -- append "/device" */
strncat(buf, "/device", 255 - strnlen(buf, 255));
} else {
/*
* @dev holds device number N or hwmon name as a string,
* convert them as:
* "0" -> "hwmon0/device"
* "k10temp" -> "hwmon2/device", where hwmon2/name is "k10temp"
*/
get_dev_path(dir, dev, buf);
/* Not found */
if (buf[0] == '\0') {
NORM_ERR("can't parse device \"%s\"", dev);
return -1;
}
dev = buf;
}
}
/* change vol to in, tempf to temp */
if (strcmp(type, "vol") == 0) {
type = "in";
} else if (strcmp(type, "tempf") == 0) {
type = "temp";
} else if (strcmp(type, "temp2") == 0) {
type = "temp";
}
DBGP("%s: dir=%s dev=%s type=%s n=%d\n", __func__, dir, dev, type, n);
/* construct path */
snprintf(path, 255, "%s%s/%s%d_input", dir, dev, type, n);
/* first, attempt to open file in /device */
fd = open(path, O_RDONLY);
if (fd < 0) {
/* if it fails, strip the /device from dev and attempt again */
size_t len_to_trunc = std::max((size_t)7, strnlen(buf, 255)) - 7;
buf[len_to_trunc] = 0;
snprintf(path, 255, "%s%s/%s%d_input", dir, dev, type, n);
fd = open(path, O_RDONLY);
if (fd < 0) {
NORM_ERR(
"can't open '%s': %s\nplease check your device or remove this "
"var from " PACKAGE_NAME,
path, strerror(errno));
}
}
strncpy(devtype, path, 255);
if (strcmp(type, "in") == 0 || strcmp(type, "temp") == 0 ||
strcmp(type, "tempf") == 0) {
*divisor = 1;
} else {
*divisor = 0;
}
/* fan does not use *_div as a read divisor */
if (strcmp("fan", type) == 0) { return fd; }
/* test if *_div file exist, open it and use it as divisor */
if (strcmp(type, "tempf") == 0) {
snprintf(path, 255, "%s%s/%s%d_div", dir, "one", "two", n);
} else {
snprintf(path, 255, "%s%s/%s%d_div", dir, dev, type, n);
}
divfd = open(path, O_RDONLY);
if (divfd > 0) {
/* read integer */
char divbuf[64];
int divn;
divn = read(divfd, divbuf, 63);
/* should read until n == 0 but I doubt that kernel will give these
* in multiple pieces. :) */
if (divn < 0) {
NORM_ERR("open_sysfs_sensor(): can't read from sysfs");
} else {
divbuf[divn] = '\0';
*divisor = strtol(divbuf, nullptr, 10);
}
close(divfd);
}
return fd;
}
static double get_sysfs_info(int *fd, int divisor, char *devtype, char *type) {
int val = 0;
if (*fd <= 0) { return 0; }
lseek(*fd, 0, SEEK_SET);
/* read integer */
{
char buf[64];
int n;
n = read(*fd, buf, 63);
/* should read until n == 0 but I doubt that kernel will give these
* in multiple pieces. :) */
if (n < 0) {
NORM_ERR("get_sysfs_info(): read from %s failed\n", devtype);
} else {
buf[n] = '\0';
val = strtol(buf, nullptr, 10);
}
}
close(*fd);
/* open file */
*fd = open(devtype, O_RDONLY);
if (*fd < 0) { NORM_ERR("can't open '%s': %s", devtype, strerror(errno)); }
/* My dirty hack for computing CPU value
* Filedil, from forums.gentoo.org */
/* if (strstr(devtype, "temp1_input") != nullptr) {
return -15.096 + 1.4893 * (val / 1000.0);
} */
/* divide voltage and temperature by 1000 */
/* or if any other divisor is given, use that */
if (0 == (strcmp(type, "temp2"))) {
temp2 = "temp2";
} else {
temp2 = "empty";
}
if (strcmp(type, "tempf") == 0) {
if (divisor > 1) {
return ((val / divisor + 40) * 9.0 / 5) - 40;
} else if (divisor) {
return ((val / 1000.0 + 40) * 9.0 / 5) - 40;
} else {
return ((val + 40) * 9.0 / 5) - 40;
}
} else {
if (divisor > 1) {
return val / divisor;
} else if (divisor) {
return val / 1000.0;
} else {
return val;
}
}
}
#define HWMON_RESET() \
{ \
buf1[0] = 0; \
factor = 1.0; \
offset = 0.0; \
}
static void parse_sysfs_sensor(struct text_object *obj, const char *arg,
const char *path, const char *type) {
char buf1[64], buf2[64];
float factor, offset;
int n, found = 0;
struct sysfs *sf;
memset(buf1, 0, 64);
memset(buf2, 0, 64);
if (sscanf(arg, "%63s %d %f %f", buf2, &n, &factor, &offset) == 4)
found = 1;
else
HWMON_RESET();
if (!found &&
sscanf(arg, "%63s %63s %d %f %f", buf1, buf2, &n, &factor, &offset) == 5)
found = 1;
else if (!found)
HWMON_RESET();
if (!found && sscanf(arg, "%63s %63s %d", buf1, buf2, &n) == 3)
found = 1;
else if (!found)
HWMON_RESET();
if (!found && sscanf(arg, "%63s %d", buf2, &n) == 2)
found = 1;
else if (!found)
HWMON_RESET();
if (!found) {
obj_be_plain_text(obj, "fail");
return;
}
DBGP("parsed %s args: '%s' '%s' %d %f %f\n", type, buf1, buf2, n, factor,
offset);
sf = (struct sysfs *)malloc(sizeof(struct sysfs));
memset(sf, 0, sizeof(struct sysfs));
sf->fd = open_sysfs_sensor(path, (*buf1) ? buf1 : 0, buf2, n, &sf->arg,
sf->devtype);
strncpy(sf->type, buf2, 63);
sf->factor = factor;
sf->offset = offset;
obj->data.opaque = sf;
}
#define PARSER_GENERATOR(name, path) \
void parse_##name##_sensor(struct text_object *obj, const char *arg) { \
parse_sysfs_sensor(obj, arg, path, #name); \
}
PARSER_GENERATOR(i2c, "/sys/bus/i2c/devices/")
PARSER_GENERATOR(hwmon, "/sys/class/hwmon/")
PARSER_GENERATOR(platform, "/sys/bus/platform/devices/")
void print_sysfs_sensor(struct text_object *obj, char *p,
unsigned int p_max_size) {
double r;
struct sysfs *sf = (struct sysfs *)obj->data.opaque;
if (!sf || sf->fd < 0) return;
r = get_sysfs_info(&sf->fd, sf->arg, sf->devtype, sf->type);
r = r * sf->factor + sf->offset;
if (0 == (strcmp(temp2, "temp2"))) {
temp_print(p, p_max_size, r, TEMP_CELSIUS, 0);
} else if (!strncmp(sf->type, "temp", 4)) {
temp_print(p, p_max_size, r, TEMP_CELSIUS, 1);
} else if (r >= 100.0 || r == 0) {
snprintf(p, p_max_size, "%d", (int)r);
} else {
snprintf(p, p_max_size, "%.1f", r);
}
}
void free_sysfs_sensor(struct text_object *obj) {
struct sysfs *sf = (struct sysfs *)obj->data.opaque;
if (!sf) return;
if (sf->fd >= 0) close(sf->fd);
free_and_zero(obj->data.opaque);
}
#define CPUFREQ_PREFIX "/sys/devices/system/cpu"
#define CPUFREQ_POSTFIX "cpufreq/scaling_cur_freq"
/* return system frequency in MHz (use divisor=1) or GHz (use divisor=1000) */
char get_freq(char *p_client_buffer, size_t client_buffer_size,
const char *p_format, int divisor, unsigned int cpu) {
FILE *f;
static int reported = 0;
char frequency[32];
char s[256];
double freq = 0;
if (!p_client_buffer || client_buffer_size <= 0 || !p_format ||
divisor <= 0) {
return 0;
}
if (!prefer_proc) {
char current_freq_file[128];
snprintf(current_freq_file, 127, "%s/cpu%d/%s", CPUFREQ_PREFIX, cpu - 1,
CPUFREQ_POSTFIX);
f = fopen(current_freq_file, "r");
if (f) {
/* if there's a cpufreq /sys node, read the current frequency from
* this node and divide by 1000 to get Mhz. */
if (fgets(s, sizeof(s), f)) {
s[strlen(s) - 1] = '\0';
freq = strtod(s, nullptr);
}
fclose(f);
snprintf(p_client_buffer, client_buffer_size, p_format,
(freq / 1000) / divisor);
return 1;
}
}
// open the CPU information file
f = open_file("/proc/cpuinfo", &reported);
if (!f) {
perror(PACKAGE_NAME ": Failed to access '/proc/cpuinfo' at get_freq()");
return 0;
}
// read the file
while (fgets(s, sizeof(s), f) != nullptr) {
#if defined(__i386) || defined(__x86_64)
// and search for the cpu mhz
if (strncmp(s, "cpu MHz", 7) == 0 && cpu == 0) {
#else
#if defined(__alpha)
// different on alpha
if (strncmp(s, "cycle frequency [Hz]", 20) == 0 && cpu == 0) {
#else
// this is different on ppc for some reason
if (strncmp(s, "clock", 5) == 0 && cpu == 0) {
#endif // defined(__alpha)
#endif // defined(__i386) || defined(__x86_64)
// copy just the number
strncpy(frequency, strchr(s, ':') + 2, 32);
#if defined(__alpha)
// strip " est.\n"
frequency[strlen(frequency) - 6] = '\0';
// kernel reports in Hz
freq = strtod(frequency, nullptr) / 1000000;
#else
// strip \n
frequency[strlen(frequency) - 1] = '\0';
freq = strtod(frequency, nullptr);
#endif
break;
}
if (strncmp(s, "processor", 9) == 0) {
cpu--;
continue;
}
}
fclose(f);
snprintf(p_client_buffer, client_buffer_size, p_format,
(float)freq / divisor);
return 1;
}
#define CPUFREQ_GOVERNOR "cpufreq/scaling_governor"
/* print the CPU scaling governor */
void print_cpugovernor(struct text_object *obj, char *p,
unsigned int p_max_size) {
FILE *fp;
char buf[64];
unsigned int cpu = obj->data.i;
cpu--;
snprintf(buf, 63, "%s/cpu%d/%s", CPUFREQ_PREFIX, cpu, CPUFREQ_GOVERNOR);
if ((fp = fopen(buf, "r")) != nullptr) {
while (fscanf(fp, "%63s", buf) == 1) {
snprintf(p, p_max_size, "%s", buf);
fclose(fp);
return;
}
}
}
#define CPUFREQ_VOLTAGE "cpufreq/scaling_voltages"
/* /sys/devices/system/cpu/cpu0/cpufreq/scaling_voltages looks something
* like this:
# frequency voltage
1800000 1340
1600000 1292
1400000 1100
1200000 988
1000000 1116
800000 1004
600000 988
* Peter Tarjan (ptarjan@citromail.hu) */
/* return cpu voltage in mV (use divisor=1) or V (use divisor=1000) */
static char get_voltage(char *p_client_buffer, size_t client_buffer_size,
const char *p_format, int divisor, unsigned int cpu) {
FILE *f;
char s[256];
int freq = 0;
int voltage = 0;
char current_freq_file[128];
int freq_comp = 0;
/* build the voltage file name */
cpu--;
snprintf(current_freq_file, 127, "%s/cpu%d/%s", CPUFREQ_PREFIX, cpu,
CPUFREQ_POSTFIX);
if (!p_client_buffer || client_buffer_size <= 0 || !p_format ||
divisor <= 0) {
return 0;
}
/* read the current cpu frequency from the /sys node */
f = fopen(current_freq_file, "r");
if (f) {
if (fgets(s, sizeof(s), f)) {
s[strlen(s) - 1] = '\0';
freq = strtod(s, nullptr);
}
fclose(f);
} else {
fprintf(stderr, PACKAGE_NAME ": Failed to access '%s' at ",
current_freq_file);
perror("get_voltage()");
return 0;
}
snprintf(current_freq_file, 127, "%s/cpu%d/%s", CPUFREQ_PREFIX, cpu,
CPUFREQ_VOLTAGE);
/* use the current cpu frequency to find the corresponding voltage */
f = fopen(current_freq_file, "r");
if (f) {
while (!feof(f)) {
char line[256];
if (fgets(line, 255, f) == nullptr) { break; }
sscanf(line, "%d %d", &freq_comp, &voltage);
if (freq_comp == freq) { break; }
}
fclose(f);
} else {
fprintf(stderr, PACKAGE_NAME ": Failed to access '%s' at ",
current_freq_file);
perror("get_voltage()");
return 0;
}
snprintf(p_client_buffer, client_buffer_size, p_format,
(float)voltage / divisor);
return 1;
}
void print_voltage_mv(struct text_object *obj, char *p,
unsigned int p_max_size) {
static int ok = 1;
if (ok) { ok = get_voltage(p, p_max_size, "%.0f", 1, obj->data.i); }
}
void print_voltage_v(struct text_object *obj, char *p,
unsigned int p_max_size) {
static int ok = 1;
if (ok) { ok = get_voltage(p, p_max_size, "%'.3f", 1000, obj->data.i); }
}
#define ACPI_FAN_DIR "/proc/acpi/fan/"
void get_acpi_fan(char *p_client_buffer, size_t client_buffer_size) {
static int reported = 0;
char buf[512];
char buf2[512];
FILE *fp;
if (!p_client_buffer || client_buffer_size <= 0) { return; }
/* yeah, slow... :/ */
if (!get_first_file_in_a_directory(ACPI_FAN_DIR, buf, &reported)) {
snprintf(p_client_buffer, client_buffer_size, "%s", "no fans?");
return;
}
snprintf(buf2, sizeof(buf2), "%s%.256s/state", ACPI_FAN_DIR, buf);
fp = open_file(buf2, &reported);
if (!fp) {
snprintf(p_client_buffer, client_buffer_size, "%s",
"can't open fan's state file");
return;
}
memset(buf, 0, sizeof(buf));
if (fscanf(fp, "%*s %99s", buf) <= 0) perror("fscanf()");
fclose(fp);
snprintf(p_client_buffer, client_buffer_size, "%s", buf);
}
#define SYSFS_AC_ADAPTER_DIR "/sys/class/power_supply"
#define ACPI_AC_ADAPTER_DIR "/proc/acpi/ac_adapter/"
/* Linux 2.6.25 onwards ac adapter info is in
/sys/class/power_supply/AC/
On my system I get the following.
/sys/class/power_supply/AC/uevent:
PHYSDEVPATH=/devices/LNXSYSTM:00/device:00/PNP0A08:00/device:01/PNP0C09:00/ACPI0003:00
PHYSDEVBUS=acpi
PHYSDEVDRIVER=ac
POWER_SUPPLY_NAME=AC
POWER_SUPPLY_TYPE=Mains
POWER_SUPPLY_ONLINE=1
Update: it seems the folder name is hardware-dependent. We add an additional
adapter argument, specifying the folder name.
Update: on some systems it's /sys/class/power_supply/ADP1 instead of
/sys/class/power_supply/AC
*/
void get_acpi_ac_adapter(char *p_client_buffer, size_t client_buffer_size,
const char *adapter) {
static int reported = 0;
char buf[512];
char buf2[512];
struct stat sb;
FILE *fp;
if (!p_client_buffer || client_buffer_size <= 0) { return; }
if (adapter)
snprintf(buf2, sizeof(buf2), "%s/%s/uevent", SYSFS_AC_ADAPTER_DIR, adapter);
else {
snprintf(buf2, sizeof(buf2), "%s/AC/uevent", SYSFS_AC_ADAPTER_DIR);
if (stat(buf2, &sb) == -1)
snprintf(buf2, sizeof(buf2), "%s/ADP1/uevent", SYSFS_AC_ADAPTER_DIR);
}
if (stat(buf2, &sb) == 0)
fp = open_file(buf2, &reported);
else
fp = 0;
if (fp) {
/* sysfs processing */
while (!feof(fp)) {
if (fgets(buf, sizeof(buf), fp) == nullptr) break;
if (strncmp(buf, "POWER_SUPPLY_ONLINE=", 20) == 0) {
int online = 0;
sscanf(buf, "POWER_SUPPLY_ONLINE=%d", &online);
snprintf(p_client_buffer, client_buffer_size, "%s-line",
(online ? "on" : "off"));
break;
}
}
fclose(fp);
} else {
/* yeah, slow... :/ */
if (!get_first_file_in_a_directory(ACPI_AC_ADAPTER_DIR, buf, &reported)) {
snprintf(p_client_buffer, client_buffer_size, "%s", "no ac_adapters?");
return;
}
snprintf(buf2, sizeof(buf2), "%s%.256s/state", ACPI_AC_ADAPTER_DIR, buf);
fp = open_file(buf2, &reported);
if (!fp) {
snprintf(p_client_buffer, client_buffer_size, "%s",
"No ac adapter found.... where is it?");
return;
}
memset(buf, 0, sizeof(buf));
if (fscanf(fp, "%*s %99s", buf) <= 0) perror("fscanf()");
fclose(fp);
snprintf(p_client_buffer, client_buffer_size, "%s", buf);
}
}
/*
/proc/acpi/thermal_zone/THRM/cooling_mode
cooling mode: active
/proc/acpi/thermal_zone/THRM/polling_frequency
<polling disabled>
/proc/acpi/thermal_zone/THRM/state
state: ok
/proc/acpi/thermal_zone/THRM/temperature
temperature: 45 C
/proc/acpi/thermal_zone/THRM/trip_points
critical (S5): 73 C
passive: 73 C: tc1=4 tc2=3 tsp=40 devices=0xcdf6e6c0
*/
#define ACPI_THERMAL_ZONE_DEFAULT "thermal_zone0"
#define ACPI_THERMAL_FORMAT "/sys/class/thermal/%s/temp"
int open_acpi_temperature(const char *name) {
char path[256];
int fd;
if (name == nullptr || strcmp(name, "*") == 0) {
snprintf(path, 255, ACPI_THERMAL_FORMAT, ACPI_THERMAL_ZONE_DEFAULT);
} else {
snprintf(path, 255, ACPI_THERMAL_FORMAT, name);
}
fd = open(path, O_RDONLY);
if (fd < 0) { NORM_ERR("can't open '%s': %s", path, strerror(errno)); }
return fd;
}
static double last_acpi_temp;
static double last_acpi_temp_time;
// the maximum length of the string inside a ACPI_THERMAL_FORMAT file including
// the ending 0
#define MAXTHERMZONELEN 7
double get_acpi_temperature(int fd) {
if (fd <= 0) { return 0; }
/* don't update acpi temperature too often */
if (current_update_time - last_acpi_temp_time < 11.32) {
return last_acpi_temp;
}
last_acpi_temp_time = current_update_time;
/* seek to beginning */
lseek(fd, 0, SEEK_SET);
/* read */
{
char buf[MAXTHERMZONELEN];
int n;
n = read(fd, buf, MAXTHERMZONELEN - 1);
if (n < 0) {
NORM_ERR("can't read fd %d: %s", fd, strerror(errno));
} else {
buf[n] = '\0';
sscanf(buf, "%lf", &last_acpi_temp);
last_acpi_temp /= 1000;
}
}
return last_acpi_temp;
}
/*
hipo@lepakko hipo $ cat /proc/acpi/battery/BAT1/info
present: yes
design capacity: 4400 mAh
last full capacity: 4064 mAh
battery technology: rechargeable
design voltage: 14800 mV
design capacity warning: 300 mAh
design capacity low: 200 mAh
capacity granularity 1: 32 mAh
capacity granularity 2: 32 mAh
model number: 02KT
serial number: 16922
battery type: LION
OEM info: SANYO
*/
/*
hipo@lepakko conky $ cat /proc/acpi/battery/BAT1/state
present: yes
capacity state: ok
charging state: unknown
present rate: 0 mA
remaining capacity: 4064 mAh
present voltage: 16608 mV
*/
/*
2213<@jupetkellari> jupet@lagi-unstable:~$ cat /proc/apm
2213<@jupetkellari> 1.16 1.2 0x03 0x01 0xff 0x10 -1% -1 ?
2213<@jupetkellari> (-1 ollee ei akkua kiinni, koska akku on pydll)
2214<@jupetkellari> jupet@lagi-unstable:~$ cat /proc/apm
2214<@jupetkellari> 1.16 1.2 0x03 0x01 0x03 0x09 98% -1 ?
2238<@jupetkellari> 1.16 1.2 0x03 0x00 0x00 0x01 100% -1 ? ilman verkkovirtaa
2239<@jupetkellari> 1.16 1.2 0x03 0x01 0x00 0x01 99% -1 ? verkkovirralla
2240<@jupetkellari> 1.16 1.2 0x03 0x01 0x03 0x09 100% -1 ? verkkovirralla ja
monitori pll 2241<@jupetkellari> 1.16 1.2 0x03 0x00 0x00 0x01 99% -1 ?
monitori pll mutta ilman verkkovirtaa
*/
/* Kapil Hari Paranjape <kapil@imsc.res.in>
Linux 2.6.24 onwards battery info is in
/sys/class/power_supply/BAT0/
On my system I get the following.
/sys/class/power_supply/BAT0/uevent:
PHYSDEVPATH=/devices/LNXSYSTM:00/device:00/PNP0A03:00/device:01/PNP0C09:00/PNP0C0A:00
PHYSDEVBUS=acpi
PHYSDEVDRIVER=battery
POWER_SUPPLY_NAME=BAT0
POWER_SUPPLY_TYPE=Battery
POWER_SUPPLY_STATUS=Discharging
POWER_SUPPLY_PRESENT=1
POWER_SUPPLY_TECHNOLOGY=Li-ion
POWER_SUPPLY_VOLTAGE_MIN_DESIGN=10800000
POWER_SUPPLY_VOLTAGE_NOW=10780000
POWER_SUPPLY_CURRENT_NOW=13970000
POWER_SUPPLY_ENERGY_FULL_DESIGN=47510000
POWER_SUPPLY_ENERGY_FULL=27370000
POWER_SUPPLY_ENERGY_NOW=11810000
POWER_SUPPLY_MODEL_NAME=IBM-92P1060
POWER_SUPPLY_MANUFACTURER=Panasonic
On some systems POWER_SUPPLY_ENERGY_* is replaced by POWER_SUPPLY_CHARGE_*
*/
/* Tiago Marques Vale <tiagomarquesvale@gmail.com>
Regarding the comment above, since kernel 2.6.36.1 I have
POWER_SUPPLY_POWER_NOW instead of POWER_SUPPLY_CURRENT_NOW
See http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=532000
*/
#define SYSFS_BATTERY_BASE_PATH "/sys/class/power_supply"
#define ACPI_BATTERY_BASE_PATH "/proc/acpi/battery"
#define APM_PATH "/proc/apm"
#define MAX_BATTERY_COUNT 4
static FILE *sysfs_bat_fp[MAX_BATTERY_COUNT] = {nullptr, NULL, NULL, NULL};
static FILE *acpi_bat_fp[MAX_BATTERY_COUNT] = {nullptr, NULL, NULL, NULL};
static FILE *apm_bat_fp[MAX_BATTERY_COUNT] = {nullptr, NULL, NULL, NULL};
static int batteries_initialized = 0;
static char batteries[MAX_BATTERY_COUNT][32];
static int acpi_last_full[MAX_BATTERY_COUNT];
static int acpi_design_capacity[MAX_BATTERY_COUNT];
/* e.g. "charging 75%" */
static char last_battery_str[MAX_BATTERY_COUNT][64];
/* e.g. "3h 15m" */
static char last_battery_time_str[MAX_BATTERY_COUNT][64];
static double last_battery_time[MAX_BATTERY_COUNT];
static int last_battery_perct[MAX_BATTERY_COUNT];
static double last_battery_perct_time[MAX_BATTERY_COUNT];
void init_batteries(void) {
int idx;
if (batteries_initialized) { return; }
#ifdef HAVE_OPENMP
#pragma omp parallel for schedule(dynamic, 10)
#endif /* HAVE_OPENMP */
for (idx = 0; idx < MAX_BATTERY_COUNT; idx++) { batteries[idx][0] = '\0'; }
batteries_initialized = 1;
}
int get_battery_idx(const char *bat) {
int idx;
for (idx = 0; idx < MAX_BATTERY_COUNT; idx++) {
if (!strlen(batteries[idx]) || !strcmp(batteries[idx], bat)) { break; }
}
/* if not found, enter a new entry */
if (!strlen(batteries[idx])) { snprintf(batteries[idx], 31, "%s", bat); }
return idx;
}
void set_return_value(char *buffer, unsigned int n, int item, int idx);
void get_battery_stuff(char *buffer, unsigned int n, const char *bat,
int item) {
static int idx, rep = 0, rep1 = 0, rep2 = 0;
char acpi_path[128];
char sysfs_path[128];
snprintf(acpi_path, 127, ACPI_BATTERY_BASE_PATH "/%s/state", bat);
snprintf(sysfs_path, 127, SYSFS_BATTERY_BASE_PATH "/%s/uevent", bat);
init_batteries();
idx = get_battery_idx(bat);
/* don't update battery too often */
if (current_update_time - last_battery_time[idx] < 29.5) {
set_return_value(buffer, n, item, idx);
return;
}
last_battery_time[idx] = current_update_time;
memset(last_battery_str[idx], 0, sizeof(last_battery_str[idx]));
memset(last_battery_time_str[idx], 0, sizeof(last_battery_time_str[idx]));
/* first try SYSFS if that fails try ACPI */
if (sysfs_bat_fp[idx] == nullptr && acpi_bat_fp[idx] == NULL &&
apm_bat_fp[idx] == nullptr) {
sysfs_bat_fp[idx] = open_file(sysfs_path, &rep);
}
if (sysfs_bat_fp[idx] == nullptr && acpi_bat_fp[idx] == NULL &&
apm_bat_fp[idx] == nullptr) {
acpi_bat_fp[idx] = open_file(acpi_path, &rep1);
}
if (sysfs_bat_fp[idx] != nullptr) {
/* SYSFS */
int present_rate = -1;
int remaining_capacity = -1;
char charging_state[64];
char present[4];
strncpy(charging_state, "unknown", 64);
while (!feof(sysfs_bat_fp[idx])) {
char buf[256];
if (fgets(buf, 256, sysfs_bat_fp[idx]) == nullptr) break;
/* let's just hope units are ok */
if (strncmp(buf, "POWER_SUPPLY_PRESENT=1", 22) == 0)
strncpy(present, "yes", 4);
else if (strncmp(buf, "POWER_SUPPLY_PRESENT=0", 22) == 0)
strncpy(present, "no", 4);
else if (strncmp(buf, "POWER_SUPPLY_STATUS=", 20) == 0)
sscanf(buf, "POWER_SUPPLY_STATUS=%63s", charging_state);
/* present_rate is not the same as the current flowing now but it
* is the same value which was used in the past. so we continue the
* tradition! */
else if (strncmp(buf, "POWER_SUPPLY_CURRENT_NOW=", 25) == 0)
sscanf(buf, "POWER_SUPPLY_CURRENT_NOW=%d", &present_rate);
else if (strncmp(buf, "POWER_SUPPLY_POWER_NOW=", 23) == 0)
sscanf(buf, "POWER_SUPPLY_POWER_NOW=%d", &present_rate);
else if (strncmp(buf, "POWER_SUPPLY_ENERGY_NOW=", 24) == 0)
sscanf(buf, "POWER_SUPPLY_ENERGY_NOW=%d", &remaining_capacity);
else if (strncmp(buf, "POWER_SUPPLY_ENERGY_FULL=", 25) == 0)
sscanf(buf, "POWER_SUPPLY_ENERGY_FULL=%d", &acpi_last_full[idx]);
else if (strncmp(buf, "POWER_SUPPLY_CHARGE_NOW=", 24) == 0)
sscanf(buf, "POWER_SUPPLY_CHARGE_NOW=%d", &remaining_capacity);
else if (strncmp(buf, "POWER_SUPPLY_CHARGE_FULL=", 25) == 0)
sscanf(buf, "POWER_SUPPLY_CHARGE_FULL=%d", &acpi_last_full[idx]);
}
fclose(sysfs_bat_fp[idx]);
sysfs_bat_fp[idx] = nullptr;
/* Hellf[i]re notes that remaining capacity can exceed acpi_last_full */
if (remaining_capacity > acpi_last_full[idx])
acpi_last_full[idx] = remaining_capacity; /* normalize to 100% */
/* not present */
if (strcmp(present, "No") == 0) {
strncpy(last_battery_str[idx], "not present", 64);
}
/* charging */
else if (strcmp(charging_state, "Charging") == 0) {
if (acpi_last_full[idx] != 0 && present_rate > 0) {
/* e.g. charging 75% */
snprintf(
last_battery_str[idx], sizeof(last_battery_str[idx]) - 1,
"charging %i%%",
(int)(((float)remaining_capacity / acpi_last_full[idx]) * 100));
/* e.g. 2h 37m */
format_seconds(
last_battery_time_str[idx], sizeof(last_battery_time_str[idx]) - 1,
(long)(((float)(acpi_last_full[idx] - remaining_capacity) /
present_rate) *
3600));
} else if (acpi_last_full[idx] != 0 && present_rate <= 0) {
snprintf(
last_battery_str[idx], sizeof(last_battery_str[idx]) - 1,
"charging %d%%",
(int)(((float)remaining_capacity / acpi_last_full[idx]) * 100));
snprintf(last_battery_time_str[idx],
sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown");
} else {
strncpy(last_battery_str[idx], "charging",
sizeof(last_battery_str[idx]) - 1);
snprintf(last_battery_time_str[idx],
sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown");
}
}
/* discharging */
else if (strncmp(charging_state, "Discharging", 64) == 0) {
if (present_rate > 0) {
/* e.g. discharging 35% */
snprintf(
last_battery_str[idx], sizeof(last_battery_str[idx]) - 1,
"discharging %i%%",
(int)(((float)remaining_capacity / acpi_last_full[idx]) * 100));
/* e.g. 1h 12m */
format_seconds(
last_battery_time_str[idx], sizeof(last_battery_time_str[idx]) - 1,
(long)(((float)remaining_capacity / present_rate) * 3600));
} else if (present_rate == 0) { /* Thanks to Nexox for this one */
snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1,
"full");
snprintf(last_battery_time_str[idx],
sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown");
} else {
snprintf(
last_battery_str[idx], sizeof(last_battery_str[idx]) - 1,
"discharging %d%%",
(int)(((float)remaining_capacity / acpi_last_full[idx]) * 100));
snprintf(last_battery_time_str[idx],
sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown");
}
}
/* charged */
/* thanks to Lukas Zapletal <lzap@seznam.cz> */
else if (strncmp(charging_state, "Charged", 64) == 0 ||
strncmp(charging_state, "Full", 64) == 0) {
/* Below happens with the second battery on my X40,
* when the second one is empty and the first one
* being charged. */
if (remaining_capacity == 0)
strncpy(last_battery_str[idx], "empty", 64);
else
strncpy(last_battery_str[idx], "charged", 64);
}
/* unknown, probably full / AC */
else {
if (acpi_last_full[idx] != 0 && remaining_capacity != acpi_last_full[idx])
snprintf(
last_battery_str[idx], 64, "unknown %d%%",
(int)(((float)remaining_capacity / acpi_last_full[idx]) * 100));
else
strncpy(last_battery_str[idx], "not present", 64);
}
} else if (acpi_bat_fp[idx] != nullptr) {
/* ACPI */
int present_rate = -1;
int remaining_capacity = -1;
char charging_state[64];
char present[5];
/* read last full capacity if it's zero */
if (acpi_last_full[idx] == 0) {
static int rep3 = 0;
char path[128];
FILE *fp;
snprintf(path, 127, ACPI_BATTERY_BASE_PATH "/%s/info", bat);
fp = open_file(path, &rep3);
if (fp != nullptr) {
while (!feof(fp)) {
char b[256];
if (fgets(b, 256, fp) == nullptr) { break; }
if (sscanf(b, "last full capacity: %d", &acpi_last_full[idx]) != 0) {
break;
}
}
fclose(fp);
}
}
fseek(acpi_bat_fp[idx], 0, SEEK_SET);
strncpy(charging_state, "unknown", 8);
while (!feof(acpi_bat_fp[idx])) {
char buf[256];
if (fgets(buf, 256, acpi_bat_fp[idx]) == nullptr) { break; }
/* let's just hope units are ok */
if (strncmp(buf, "present:", 8) == 0) {
sscanf(buf, "present: %4s", present);
} else if (strncmp(buf, "charging state:", 15) == 0) {
sscanf(buf, "charging state: %63s", charging_state);
} else if (strncmp(buf, "present rate:", 13) == 0) {
sscanf(buf, "present rate: %d", &present_rate);
} else if (strncmp(buf, "remaining capacity:", 19) == 0) {
sscanf(buf, "remaining capacity: %d", &remaining_capacity);
}
}
/* Hellf[i]re notes that remaining capacity can exceed acpi_last_full */
if (remaining_capacity > acpi_last_full[idx]) {
/* normalize to 100% */
acpi_last_full[idx] = remaining_capacity;
}
/* not present */
if (strcmp(present, "no") == 0) {
strncpy(last_battery_str[idx], "not present", 64);
/* charging */
} else if (strcmp(charging_state, "charging") == 0) {
if (acpi_last_full[idx] != 0 && present_rate > 0) {
/* e.g. charging 75% */
snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1,
"charging %i%%",
(int)((remaining_capacity * 100) / acpi_last_full[idx]));
/* e.g. 2h 37m */
format_seconds(
last_battery_time_str[idx], sizeof(last_battery_time_str[idx]) - 1,
(long)(((acpi_last_full[idx] - remaining_capacity) * 3600) /
present_rate));
} else if (acpi_last_full[idx] != 0 && present_rate <= 0) {
snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1,
"charging %d%%",
(int)((remaining_capacity * 100) / acpi_last_full[idx]));
snprintf(last_battery_time_str[idx],
sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown");
} else {
strncpy(last_battery_str[idx], "charging",
sizeof(last_battery_str[idx]) - 1);
snprintf(last_battery_time_str[idx],
sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown");
}
/* discharging */
} else if (strncmp(charging_state, "discharging", 64) == 0) {
if (present_rate > 0) {
/* e.g. discharging 35% */
snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1,
"discharging %i%%",
(int)((remaining_capacity * 100) / acpi_last_full[idx]));
/* e.g. 1h 12m */
format_seconds(last_battery_time_str[idx],
sizeof(last_battery_time_str[idx]) - 1,
(long)((remaining_capacity * 3600) / present_rate));
} else if (present_rate == 0) { /* Thanks to Nexox for this one */
snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1,
"charged");
snprintf(last_battery_time_str[idx],
sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown");
} else {
snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1,
"discharging %d%%",
(int)((remaining_capacity * 100) / acpi_last_full[idx]));
snprintf(last_battery_time_str[idx],
sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown");
}
/* charged */
} else if (strncmp(charging_state, "charged", 64) == 0) {
/* thanks to Lukas Zapletal <lzap@seznam.cz> */
/* Below happens with the second battery on my X40,
* when the second one is empty and the first one being charged. */
if (remaining_capacity == 0) {
strncpy(last_battery_str[idx], "empty", 6);
} else {
strncpy(last_battery_str[idx], "charged", 8);
}
/* unknown, probably full / AC */
} else {
if (strncmp(charging_state, "Full", 64) == 0) {
strncpy(last_battery_str[idx], "charged", 64);
} else if (acpi_last_full[idx] != 0 &&
remaining_capacity != acpi_last_full[idx]) {
snprintf(last_battery_str[idx], 64, "unknown %d%%",
(int)((remaining_capacity * 100) / acpi_last_full[idx]));
} else {
strncpy(last_battery_str[idx], "not present", 64);
}
}
fclose(acpi_bat_fp[idx]);
acpi_bat_fp[idx] = nullptr;
} else {
/* APM */
if (apm_bat_fp[idx] == nullptr) {
apm_bat_fp[idx] = open_file(APM_PATH, &rep2);
}
if (apm_bat_fp[idx] != nullptr) {
unsigned int ac, status, flag;
int life;
if (fscanf(apm_bat_fp[idx], "%*s %*s %*x %x %x %x %d%%", &ac,
&status, &flag, &life) <= 0)
goto read_bat_fp_end;
if (life == -1) {
/* could check now that there is ac */
snprintf(last_battery_str[idx], 64, "%s", "not present");
/* could check that status == 3 here? */
} else if (ac && life != 100) {
snprintf(last_battery_str[idx], 64, "charging %d%%", life);
} else {
snprintf(last_battery_str[idx], 64, "%d%%", life);
}
read_bat_fp_end:
/* it seemed to buffer it so file must be closed (or could use
* syscalls directly but I don't feel like coding it now) */
fclose(apm_bat_fp[idx]);
apm_bat_fp[idx] = nullptr;
}
}
set_return_value(buffer, n, item, idx);
}
void set_return_value(char *buffer, unsigned int n, int item, int idx) {
switch (item) {
case BATTERY_STATUS:
snprintf(buffer, n, "%s", last_battery_str[idx]);
break;
case BATTERY_TIME:
snprintf(buffer, n, "%s", last_battery_time_str[idx]);
break;
default:
break;
}
}
void get_battery_short_status(char *buffer, unsigned int n, const char *bat) {
get_battery_stuff(buffer, n, bat, BATTERY_STATUS);
if (0 == strncmp("charging", buffer, 8)) {
buffer[0] = 'C';
memmove(buffer + 1, buffer + 8, n - 8);
} else if (0 == strncmp("discharging", buffer, 11)) {
buffer[0] = 'D';
memmove(buffer + 1, buffer + 11, n - 11);
} else if (0 == strncmp("charged", buffer, 7)) {
buffer[0] = 'F';
memmove(buffer + 1, buffer + 7, n - 7);
} else if (0 == strncmp("not present", buffer, 11)) {
buffer[0] = 'N';
memmove(buffer + 1, buffer + 11, n - 11);
} else if (0 == strncmp("empty", buffer, 5)) {
buffer[0] = 'E';
memmove(buffer + 1, buffer + 5, n - 5);
} else if (0 == strncmp("unknown", buffer, 7)) {
buffer[0] = 'U';
memmove(buffer + 1, buffer + 7, n - 7);
}
// Otherwise, don't shorten.
}
void get_battery_power_draw(char *buffer, unsigned int n, const char *bat) {
static int reported = 0;
char current_now_path[256], voltage_now_path[256], current_now_val[256],
voltage_now_val[256];
char *ptr;
long current_now, voltage_now;
FILE *current_now_file;
FILE *voltage_now_file;
double result;
snprintf(current_now_path, 255, SYSFS_BATTERY_BASE_PATH "/%s/current_now",
bat);
snprintf(voltage_now_path, 255, SYSFS_BATTERY_BASE_PATH "/%s/voltage_now",
bat);
current_now_file = open_file(current_now_path, &reported);
voltage_now_file = open_file(voltage_now_path, &reported);
if (current_now_file != nullptr && voltage_now_file != nullptr) {
if (fgets(current_now_val, 256, current_now_file) &&
fgets(voltage_now_val, 256, voltage_now_file)) {
current_now = strtol(current_now_val, &ptr, 10);
voltage_now = strtol(voltage_now_val, &ptr, 10);
result = (double)(current_now * voltage_now) / (double)1000000000000;
snprintf(buffer, n, "%.1f", result);
}
fclose(current_now_file);
fclose(voltage_now_file);
}
}
int _get_battery_perct(const char *bat) {
static int reported = 0;
int idx;
char acpi_path[128];
char sysfs_path[128];
int remaining_capacity = -1;
snprintf(acpi_path, 127, ACPI_BATTERY_BASE_PATH "/%s/state", bat);
snprintf(sysfs_path, 127, SYSFS_BATTERY_BASE_PATH "/%s/uevent", bat);
idx = get_battery_idx(bat);
/* don't update battery too often */
if (current_update_time - last_battery_perct_time[idx] < 30) {
return last_battery_perct[idx];
}
last_battery_perct_time[idx] = current_update_time;
/* Only check for SYSFS or ACPI */
if (sysfs_bat_fp[idx] == nullptr && acpi_bat_fp[idx] == NULL &&
apm_bat_fp[idx] == nullptr) {
sysfs_bat_fp[idx] = open_file(sysfs_path, &reported);
reported = 0;
}
if (sysfs_bat_fp[idx] == nullptr && acpi_bat_fp[idx] == NULL &&
apm_bat_fp[idx] == nullptr) {
acpi_bat_fp[idx] = open_file(acpi_path, &reported);
}
if (sysfs_bat_fp[idx] != nullptr) {
/* SYSFS */
while (!feof(sysfs_bat_fp[idx])) {
char buf[256];
if (fgets(buf, 256, sysfs_bat_fp[idx]) == nullptr) break;
if (strncmp(buf, "POWER_SUPPLY_CHARGE_NOW=", 24) == 0) {
sscanf(buf, "POWER_SUPPLY_CHARGE_NOW=%d", &remaining_capacity);
} else if (strncmp(buf, "POWER_SUPPLY_CHARGE_FULL=", 25) == 0) {
sscanf(buf, "POWER_SUPPLY_CHARGE_FULL=%d", &acpi_design_capacity[idx]);
} else if (strncmp(buf, "POWER_SUPPLY_ENERGY_NOW=", 24) == 0) {
sscanf(buf, "POWER_SUPPLY_ENERGY_NOW=%d", &remaining_capacity);
} else if (strncmp(buf, "POWER_SUPPLY_ENERGY_FULL=", 25) == 0) {
sscanf(buf, "POWER_SUPPLY_ENERGY_FULL=%d", &acpi_design_capacity[idx]);
}
}
fclose(sysfs_bat_fp[idx]);
sysfs_bat_fp[idx] = nullptr;
} else if (acpi_bat_fp[idx] != nullptr) {
/* ACPI */
/* read last full capacity if it's zero */
if (acpi_design_capacity[idx] == 0) {
static int rep2;
char path[128];
FILE *fp;
snprintf(path, 127, ACPI_BATTERY_BASE_PATH "/%s/info", bat);
fp = open_file(path, &rep2);
if (fp != nullptr) {
while (!feof(fp)) {
char b[256];
if (fgets(b, 256, fp) == nullptr) { break; }
if (sscanf(b, "last full capacity: %d", &acpi_design_capacity[idx]) !=
0) {
break;
}
}
fclose(fp);
}
}
fseek(acpi_bat_fp[idx], 0, SEEK_SET);
while (!feof(acpi_bat_fp[idx])) {
char buf[256];
if (fgets(buf, 256, acpi_bat_fp[idx]) == nullptr) { break; }
if (buf[0] == 'r') {
sscanf(buf, "remaining capacity: %d", &remaining_capacity);
}
}
}
if (remaining_capacity < 0) { return 0; }
/* compute the battery percentage */
last_battery_perct[idx] =
(int)(((float)remaining_capacity / acpi_design_capacity[idx]) * 100);
if (last_battery_perct[idx] > 100) last_battery_perct[idx] = 100;
return last_battery_perct[idx];
}
int get_battery_perct(const char *bat) {
int idx, n = 0, total_capacity = 0, remaining_capacity;
;
#define BATTERY_LEN 8
char battery[BATTERY_LEN];
init_batteries();
/* Check if user asked for the mean percentage of all batteries. */
if (!strcmp(bat, "all")) {
for (idx = 0; idx < MAX_BATTERY_COUNT; idx++) {
snprintf(battery, BATTERY_LEN - 1, "BAT%d", idx);
#undef BATTERY_LEN
remaining_capacity = _get_battery_perct(battery);
if (remaining_capacity > 0) {
total_capacity += remaining_capacity;
n++;
}
}
if (n == 0)
return 0;
else
return total_capacity / n;
} else {
return _get_battery_perct(bat);
}
}
double get_battery_perct_bar(struct text_object *obj) {
int idx;
get_battery_perct(obj->data.s);
idx = get_battery_idx(obj->data.s);
return last_battery_perct[idx];
}
/* On Apple powerbook and ibook:
$ cat /proc/pmu/battery_0
flags : 00000013
charge : 3623
max_charge : 3720
current : 388
voltage : 16787
time rem. : 900
$ cat /proc/pmu/info
PMU driver version : 2
PMU firmware version : 0c
AC Power : 1
Battery count : 1
*/
/* defines as in <linux/pmu.h> */
#define PMU_BATT_PRESENT 0x00000001
#define PMU_BATT_CHARGING 0x00000002
static FILE *pmu_battery_fp;
static FILE *pmu_info_fp;
static char pb_battery_info[3][32];
static double pb_battery_info_update;
void powerbook_update_status(unsigned int flags, int ac);
void powerbook_update_percentage(long timeval, unsigned int flags, int ac,
int charge, int max_charge);
void powerbook_update_time(long timeval);
#define PMU_PATH "/proc/pmu"
void get_powerbook_batt_info(struct text_object *obj, char *buffer,
unsigned int n) {
static int reported = 0;
const char *batt_path = PMU_PATH "/battery_0";
const char *info_path = PMU_PATH "/info";
unsigned int flags = 0;
int charge = 0;
int max_charge = 1;
int ac = -1;
long timeval = -1;
/* don't update battery too often */
if (current_update_time - pb_battery_info_update < 29.5) {
snprintf(buffer, n, "%s", pb_battery_info[obj->data.i]);
return;
}
pb_battery_info_update = current_update_time;
if (pmu_battery_fp == nullptr) {
pmu_battery_fp = open_file(batt_path, &reported);
if (pmu_battery_fp == nullptr) { return; }
}
rewind(pmu_battery_fp);
while (!feof(pmu_battery_fp)) {
char buf[32];
if (fgets(buf, sizeof(buf), pmu_battery_fp) == nullptr) { break; }
if (buf[0] == 'f') {
sscanf(buf, "flags : %8x", &flags);
} else if (buf[0] == 'c' && buf[1] == 'h') {
sscanf(buf, "charge : %d", &charge);
} else if (buf[0] == 'm') {
sscanf(buf, "max_charge : %d", &max_charge);
} else if (buf[0] == 't') {
sscanf(buf, "time rem. : %ld", &timeval);
}
}
pmu_info_fp = open_file(info_path, &reported);
if (pmu_info_fp == nullptr) { return; }
rewind(pmu_info_fp);
while (!feof(pmu_info_fp)) {
char buf[32];
if (fgets(buf, sizeof(buf), pmu_info_fp) == nullptr) { break; }
if (buf[0] == 'A') { sscanf(buf, "AC Power : %d", &ac); }
}
powerbook_update_status(flags, ac);
powerbook_update_percentage(timeval, flags, ac, charge, max_charge);
powerbook_update_time(timeval);
snprintf(buffer, n, "%s", pb_battery_info[obj->data.i]);
}
void powerbook_update_status(unsigned int flags, int ac) {
/* update status string */
if ((ac && !(flags & PMU_BATT_PRESENT))) {
strncpy(pb_battery_info[PB_BATT_STATUS], "AC",
sizeof(pb_battery_info[PB_BATT_STATUS]));
} else if (ac && (flags & PMU_BATT_PRESENT) && !(flags & PMU_BATT_CHARGING)) {
strncpy(pb_battery_info[PB_BATT_STATUS], "charged",
sizeof(pb_battery_info[PB_BATT_STATUS]));
} else if ((flags & PMU_BATT_PRESENT) && (flags & PMU_BATT_CHARGING)) {
strncpy(pb_battery_info[PB_BATT_STATUS], "charging",
sizeof(pb_battery_info[PB_BATT_STATUS]));
} else {
strncpy(pb_battery_info[PB_BATT_STATUS], "discharging",
sizeof(pb_battery_info[PB_BATT_STATUS]));
}
}
void powerbook_update_percentage(long timeval, unsigned int flags, int ac,
int charge, int max_charge) {
/* update percentage string */
if (timeval == 0 && ac && (flags & PMU_BATT_PRESENT) &&
!(flags & PMU_BATT_CHARGING)) {
snprintf(pb_battery_info[PB_BATT_PERCENT],
sizeof(pb_battery_info[PB_BATT_PERCENT]), "%s", "100%%");
} else if (timeval == 0) {
snprintf(pb_battery_info[PB_BATT_PERCENT],
sizeof(pb_battery_info[PB_BATT_PERCENT]), "%s", "unknown");
} else {
snprintf(pb_battery_info[PB_BATT_PERCENT],
sizeof(pb_battery_info[PB_BATT_PERCENT]), "%d%%",
(charge * 100) / max_charge);
}
}
void powerbook_update_time(long timeval) {
/* update time string */
if (timeval == 0) { /* fully charged or battery not present */
snprintf(pb_battery_info[PB_BATT_TIME],
sizeof(pb_battery_info[PB_BATT_TIME]), "%s", "unknown");
} else if (timeval < 60 * 60) { /* don't show secs */
format_seconds_short(pb_battery_info[PB_BATT_TIME],
sizeof(pb_battery_info[PB_BATT_TIME]), timeval);
} else {
format_seconds(pb_battery_info[PB_BATT_TIME],
sizeof(pb_battery_info[PB_BATT_TIME]), timeval);
}
}
#define ENTROPY_AVAIL_PATH "/proc/sys/kernel/random/entropy_avail"
int get_entropy_avail(unsigned int *val) {
static int reported = 0;
FILE *fp;
if (!(fp = open_file(ENTROPY_AVAIL_PATH, &reported))) return 1;
if (fscanf(fp, "%u", val) != 1) return 1;
fclose(fp);
return 0;
}
#define ENTROPY_POOLSIZE_PATH "/proc/sys/kernel/random/poolsize"
int get_entropy_poolsize(unsigned int *val) {
static int reported = 0;
FILE *fp;
if (!(fp = open_file(ENTROPY_POOLSIZE_PATH, &reported))) return 1;
if (fscanf(fp, "%u", val) != 1) return 1;
fclose(fp);
return 0;
}
void print_disk_protect_queue(struct text_object *obj, char *p,
unsigned int p_max_size) {
FILE *fp;
char path[128];
int state;
snprintf(path, 127, "/sys/block/%s/device/unload_heads", obj->data.s);
if (access(path, F_OK)) {
snprintf(path, 127, "/sys/block/%s/queue/protect", obj->data.s);
}
if ((fp = fopen(path, "r")) == nullptr) {
snprintf(p, p_max_size, "%s", "n/a ");
return;
}
if (fscanf(fp, "%d\n", &state) != 1) {
fclose(fp);
snprintf(p, p_max_size, "%s", "failed");
return;
}
fclose(fp);
snprintf(p, p_max_size, "%s", (state > 0) ? "frozen" : "free ");
}
std::unordered_map<std::string, bool> dev_list;
/* Same as sf #2942117 but memoized using a linked list */
int is_disk(char *dev) {
std::string orig(dev);
std::string syspath("/sys/block/");
char *slash;
auto i = dev_list.find(orig);
if (i != dev_list.end()) return i->second;
while ((slash = strchr(dev, '/'))) *slash = '!';
syspath += dev;
return dev_list[orig] = !(access(syspath.c_str(), F_OK));
}
int update_diskio(void) {
FILE *fp;
static int reported = 0;
char buf[512], devbuf[64];
unsigned int major, minor;
int col_count = 0;
struct diskio_stat *cur;
unsigned int reads, writes;
unsigned int total_reads = 0, total_writes = 0;
stats.current = 0;
stats.current_read = 0;
stats.current_write = 0;
if (!(fp = open_file("/proc/diskstats", &reported))) { return 0; }
/* read reads and writes from all disks (minor = 0), including cd-roms
* and floppies, and sum them up */
while (fgets(buf, 512, fp)) {
col_count = sscanf(buf, "%u %u %s %*u %*u %u %*u %*u %*u %u", &major,
&minor, devbuf, &reads, &writes);
/* ignore subdevices (they have only 3 matching entries in their line)
* and virtual devices (LVM, network block devices, RAM disks, Loopback)
*
* XXX: ignore devices which are part of a SW RAID (MD_MAJOR) */
if (col_count == 5 && major != LVM_BLK_MAJOR && major != NBD_MAJOR &&
major != RAMDISK_MAJOR && major != LOOP_MAJOR && major != DM_MAJOR) {
/* check needed for kernel >= 2.6.31, see sf #2942117 */
if (is_disk(devbuf)) {
total_reads += reads;
total_writes += writes;
}
} else {
col_count = sscanf(buf, "%u %u %s %*u %u %*u %u", &major, &minor, devbuf,
&reads, &writes);
if (col_count != 5) { continue; }
}
cur = stats.next;
while (cur && strcmp(devbuf, cur->dev)) cur = cur->next;
if (cur) update_diskio_values(cur, reads, writes);
}
update_diskio_values(&stats, total_reads, total_writes);
fclose(fp);
return 0;
}
void print_distribution(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
int i, bytes_read;
char *buf;
struct stat sb;
if (stat("/etc/arch-release", &sb) == 0) {
snprintf(p, p_max_size, "%s", "Arch Linux");
return;
}
snprintf(p, p_max_size, "Unknown");
buf = readfile("/proc/version", &bytes_read, 1);
if (buf) {
/* I am assuming the distribution name is the first string in /proc/version
that:
- is preceded by a '('
- starts with a capital
- is followed by a space and a number
but i am not sure if this is always true... */
for (i = 1; i < bytes_read; i++) {
if (buf[i - 1] == '(' && buf[i] >= 'A' && buf[i] <= 'Z') break;
}
if (i < bytes_read) {
snprintf(p, p_max_size, "%s", &buf[i]);
for (i = 1; p[i]; i++) {
if (p[i - 1] == ' ' && p[i] >= '0' && p[i] <= '9') {
p[i - 1] = 0;
break;
}
}
}
free(buf);
}
}
/******************************************
* Calculate cpu total *
******************************************/
#define TMPL_SHORTPROC "%*s %llu %llu %llu %llu"
#define TMPL_LONGPROC "%*s %llu %llu %llu %llu %llu %llu %llu %llu"
static unsigned long long calc_cpu_total(void) {
static unsigned long long previous_total = 0;
unsigned long long total = 0;
unsigned long long t = 0;
int rc;
int ps;
char line[BUFFER_LEN] = {0};
unsigned long long cpu = 0;
unsigned long long niceval = 0;
unsigned long long systemval = 0;
unsigned long long idle = 0;
unsigned long long iowait = 0;
unsigned long long irq = 0;
unsigned long long softirq = 0;
unsigned long long steal = 0;
const char *template_ =
KFLAG_ISSET(KFLAG_IS_LONGSTAT) ? TMPL_LONGPROC : TMPL_SHORTPROC;
ps = open("/proc/stat", O_RDONLY);
rc = read(ps, line, BUFFER_LEN - 1);
close(ps);
if (rc < 0) { return 0; }
sscanf(line, template_, &cpu, &niceval, &systemval, &idle, &iowait, &irq,
&softirq, &steal);
total = cpu + niceval + systemval + idle + iowait + irq + softirq + steal;
t = total - previous_total;
previous_total = total;
return t;
}
/******************************************
* Calculate each processes cpu *
******************************************/
inline static void calc_cpu_each(unsigned long long total) {
float mul = 100.0;
if (top_cpu_separate.get(*state)) mul *= info.cpu_count;
for (struct process *p = first_process; p; p = p->next)
p->amount = mul * (p->user_time + p->kernel_time) / (float)total;
}
#ifdef BUILD_IOSTATS
static void calc_io_each(void) {
struct process *p;
unsigned long long sum = 0;
for (p = first_process; p; p = p->next) sum += p->read_bytes + p->write_bytes;
if (sum == 0) sum = 1; /* to avoid having NANs if no I/O occurred */
for (p = first_process; p; p = p->next)
p->io_perc = 100.0 * (p->read_bytes + p->write_bytes) / (float)sum;
}
#endif /* BUILD_IOSTATS */
/******************************************
* Extract information from /proc *
******************************************/
#define PROCFS_TEMPLATE "/proc/%d/stat"
#define PROCFS_CMDLINE_TEMPLATE "/proc/%d/cmdline"
/* These are the guts that extract information out of /proc.
* Anyone hoping to port wmtop should look here first. */
static void process_parse_stat(struct process *process) {
char line[BUFFER_LEN] = {0}, filename[BUFFER_LEN], procname[BUFFER_LEN];
char cmdline[BUFFER_LEN] = {0}, cmdline_filename[BUFFER_LEN],
cmdline_procname[BUFFER_LEN];
char basename[BUFFER_LEN] = {0};
char tmpstr[BUFFER_LEN] = {0};
char state[4];
int ps, cmdline_ps;
unsigned long user_time = 0;
unsigned long kernel_time = 0;
int rc;
int endl;
int nice_val;
char *lparen, *rparen;
struct stat process_stat;
snprintf(filename, sizeof(filename), PROCFS_TEMPLATE, process->pid);
snprintf(cmdline_filename, sizeof(cmdline_filename), PROCFS_CMDLINE_TEMPLATE,
process->pid);
ps = open(filename, O_RDONLY);
if (ps == -1) {
/* The process must have finished in the last few jiffies! */
return;
}
if (fstat(ps, &process_stat) != 0) {
close(ps);
return;
}
process->uid = process_stat.st_uid;
/* Mark process as up-to-date. */
process->time_stamp = g_time;
rc = read(ps, line, BUFFER_LEN - 1);
close(ps);
if (rc < 0) { return; }
/* Read /proc/<pid>/cmdline */
cmdline_ps = open(cmdline_filename, O_RDONLY);
if (cmdline_ps < 0) {
/* The process must have finished in the last few jiffies! */
return;
}
endl = read(cmdline_ps, cmdline, BUFFER_LEN - 1);
close(cmdline_ps);
if (endl < 0) { return; }
/* Some processes have null-separated arguments (see proc(5)); let's fix it */
int i = endl;
while (i && cmdline[i - 1] == 0) {
/* Skip past any trailing null characters */
--i;
}
while (i--) {
/* Replace null character between arguments with a space */
if (cmdline[i] == 0) { cmdline[i] = ' '; }
}
cmdline[endl] = 0;
/* We want to transform for example "/usr/bin/python program.py" to "python
* program.py"
* 1. search for first space
* 2. search for last / before first space
* 3. copy string from its position
*/
char *space_ptr = strchr(cmdline, ' ');
if (space_ptr == nullptr) {
strncpy(tmpstr, cmdline, BUFFER_LEN);
} else {
long int space_pos = space_ptr - cmdline;
strncpy(tmpstr, cmdline, space_pos);
tmpstr[space_pos] = 0;
}
char *slash_ptr = strrchr(tmpstr, '/');
if (slash_ptr == nullptr) {
strncpy(cmdline_procname, cmdline, BUFFER_LEN);
} else {
long int slash_pos = slash_ptr - tmpstr;
strncpy(cmdline_procname, cmdline + slash_pos + 1, BUFFER_LEN - slash_pos);
cmdline_procname[BUFFER_LEN - slash_pos] = 0;
}
/* Extract cpu times from data in /proc filesystem */
lparen = strchr(line, '(');
rparen = strrchr(line, ')');
if (!lparen || !rparen || rparen < lparen) return; // this should not happen
rc = MIN((unsigned)(rparen - lparen - 1), sizeof(procname) - 1);
strncpy(procname, lparen + 1, rc);
procname[rc] = '\0';
strncpy(basename, procname, strlen(procname) + 1);
if (strlen(procname) < strlen(cmdline_procname))
strncpy(procname, cmdline_procname, strlen(cmdline_procname) + 1);
rc = sscanf(rparen + 1,
"%3s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %lu "
"%lu %*s %*s %*s %d %*s %*s %*s %llu %llu",
state, &process->user_time, &process->kernel_time, &nice_val,
&process->vsize, &process->rss);
if (rc < 6) {
NORM_ERR("scanning data for %s failed, got only %d fields", procname, rc);
return;
}
if (state[0] == 'R') ++info.run_procs;
free_and_zero(process->name);
free_and_zero(process->basename);
process->name = strndup(procname, text_buffer_size.get(*::state));
process->basename = strndup(basename, text_buffer_size.get(*::state));
process->rss *= getpagesize();
process->total_cpu_time = process->user_time + process->kernel_time;
if (process->previous_user_time == ULONG_MAX) {
process->previous_user_time = process->user_time;
}
if (process->previous_kernel_time == ULONG_MAX) {
process->previous_kernel_time = process->kernel_time;
}
/* strangely, the values aren't monotonous */
if (process->previous_user_time > process->user_time)
process->previous_user_time = process->user_time;
if (process->previous_kernel_time > process->kernel_time)
process->previous_kernel_time = process->kernel_time;
/* store the difference of the user_time */
user_time = process->user_time - process->previous_user_time;
kernel_time = process->kernel_time - process->previous_kernel_time;
/* backup the process->user_time for next time around */
process->previous_user_time = process->user_time;
process->previous_kernel_time = process->kernel_time;
/* store only the difference of the user_time here... */
process->user_time = user_time;
process->kernel_time = kernel_time;
}
#ifdef BUILD_IOSTATS
#define PROCFS_TEMPLATE_IO "/proc/%d/io"
static void process_parse_io(struct process *process) {
static const char *read_bytes_str = "read_bytes:";
static const char *write_bytes_str = "write_bytes:";
char line[BUFFER_LEN] = {0}, filename[BUFFER_LEN];
int ps;
int rc;
char *pos, *endpos;
unsigned long long read_bytes, write_bytes;
snprintf(filename, sizeof(filename), PROCFS_TEMPLATE_IO, process->pid);
ps = open(filename, O_RDONLY);
if (ps < 0) {
/* The process must have finished in the last few jiffies!
* Or, the kernel doesn't support I/O accounting.
*/
return;
}
rc = read(ps, line, BUFFER_LEN - 1);
close(ps);
if (rc < 0) { return; }
pos = strstr(line, read_bytes_str);
if (pos == nullptr) {
/* these should not happen (unless the format of the file changes) */
return;
}
pos += strlen(read_bytes_str);
process->read_bytes = strtoull(pos, &endpos, 10);
if (endpos == pos) { return; }
pos = strstr(line, write_bytes_str);
if (pos == nullptr) { return; }
pos += strlen(write_bytes_str);
process->write_bytes = strtoull(pos, &endpos, 10);
if (endpos == pos) { return; }
if (process->previous_read_bytes == ULLONG_MAX) {
process->previous_read_bytes = process->read_bytes;
}
if (process->previous_write_bytes == ULLONG_MAX) {
process->previous_write_bytes = process->write_bytes;
}
/* store the difference of the byte counts */
read_bytes = process->read_bytes - process->previous_read_bytes;
write_bytes = process->write_bytes - process->previous_write_bytes;
/* backup the counts for next time around */
process->previous_read_bytes = process->read_bytes;
process->previous_write_bytes = process->write_bytes;
/* store only the difference here... */
process->read_bytes = read_bytes;
process->write_bytes = write_bytes;
}
#endif /* BUILD_IOSTATS */
/******************************************
* Get process structure for process pid *
******************************************/
/* This function seems to hog all of the CPU time.
* I can't figure out why - it doesn't do much. */
static void calculate_stats(struct process *process) {
/* compute each process cpu usage by reading /proc/<proc#>/stat */
process_parse_stat(process);
#ifdef BUILD_IOSTATS
process_parse_io(process);
#endif /* BUILD_IOSTATS */
/*
* Check name against the exclusion list
*/
/* if (process->counted && exclusion_expression &&
* !regexec(exclusion_expression, process->name, 0, 0, 0))
* process->counted = 0; */
}
/******************************************
* Update process table *
******************************************/
static void update_process_table(void) {
DIR *dir;
struct dirent *entry;
if (!(dir = opendir("/proc"))) { return; }
info.run_procs = 0;
/* Get list of processes from /proc directory */
while ((entry = readdir(dir))) {
pid_t pid;
if (sscanf(entry->d_name, "%d", &pid) > 0) {
/* compute each process cpu usage */
calculate_stats(get_process(pid));
}
}
closedir(dir);
}
void get_top_info(void) {
unsigned long long total = 0;
total = calc_cpu_total(); /* calculate the total of the processor */
update_process_table(); /* update the table with process list */
calc_cpu_each(total); /* and then the percentage for each task */
#ifdef BUILD_IOSTATS
calc_io_each(); /* percentage of I/O for each task */
#endif /* BUILD_IOSTATS */
}
/******************************************
* Check if more than one conky process *
* is running *
******************************************/
bool is_conky_already_running(void) {
DIR *dir;
struct dirent *ent;
char buf[512];
int instances = 0;
if (!(dir = opendir("/proc"))) {
NORM_ERR("can't open /proc: %s\n", strerror(errno));
return false;
}
while ((ent = readdir(dir)) != NULL) {
char *endptr = ent->d_name;
long lpid = strtol(ent->d_name, &endptr, 10);
if (*endptr != '\0') {
continue;
}
snprintf(buf, sizeof(buf), "/proc/%ld/stat", lpid);
FILE *fp = fopen(buf, "r");
if (!fp) {
continue;
}
if (fgets(buf, sizeof(buf), fp) != NULL) {
char *conky = strstr(buf, "(conky)");
if (conky) {
instances++;
}
}
fclose(fp);
}
closedir(dir);
return instances > 1;
}
| 96,118
|
C++
|
.cc
| 2,735
| 30.181353
| 123
| 0.605077
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,540
|
display-file.cc
|
brndnmtthws_conky/src/display-file.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Please see COPYING for details
*
* Copyright (C) 2018 François Revol et al.
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* 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 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 <config.h>
#include "conky.h"
#include "display-file.hh"
#include "nc.h"
#include <iostream>
#include <sstream>
#include <unordered_map>
/* filenames for output */
static conky::simple_config_setting<std::string> overwrite_file(
"overwrite_file", std::string(), true);
static FILE *overwrite_fpointer = nullptr;
static conky::simple_config_setting<std::string> append_file("append_file",
std::string(),
true);
static FILE *append_fpointer = nullptr;
namespace conky {
namespace {
conky::display_output_file file_output("file");
} // namespace
template <>
void register_output<output_t::FILE>(display_outputs_t &outputs) {
outputs.push_back(&file_output);
}
display_output_file::display_output_file(const std::string &name_)
: display_output_base(name_) {
// lowest priority, it's a fallback
priority = 0;
}
bool display_output_file::detect() {
if (static_cast<unsigned int>(!overwrite_file.get(*state).empty()) != 0u ||
static_cast<unsigned int>(!append_file.get(*state).empty()) != 0u) {
DBGP2("Display output '%s' enabled in config.", name.c_str());
return true;
}
return false;
}
bool display_output_file::initialize() { return true; }
bool display_output_file::shutdown() { return true; }
void display_output_file::draw_string(const char *s, int) {
if (overwrite_fpointer != nullptr) { fprintf(overwrite_fpointer, "%s\n", s); }
if (append_fpointer != nullptr) { fprintf(append_fpointer, "%s\n", s); }
}
void display_output_file::begin_draw_stuff() {
if (static_cast<unsigned int>(!overwrite_file.get(*state).empty()) != 0u) {
overwrite_fpointer = fopen(overwrite_file.get(*state).c_str(), "we");
if (overwrite_fpointer == nullptr) {
NORM_ERR("Cannot overwrite '%s'", overwrite_file.get(*state).c_str());
}
}
if (static_cast<unsigned int>(!append_file.get(*state).empty()) != 0u) {
append_fpointer = fopen(append_file.get(*state).c_str(), "ae");
if (append_fpointer == nullptr) {
NORM_ERR("Cannot append to '%s'", append_file.get(*state).c_str());
}
}
}
void display_output_file::end_draw_stuff() {
if (overwrite_fpointer != nullptr) {
fclose(overwrite_fpointer);
overwrite_fpointer = nullptr;
}
if (append_fpointer != nullptr) {
fclose(append_fpointer);
append_fpointer = nullptr;
}
}
} // namespace conky
| 3,423
|
C++
|
.cc
| 92
| 33.304348
| 80
| 0.681242
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,541
|
i8k.cc
|
brndnmtthws_conky/src/i8k.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2007 Toni Spets
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* 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 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "conky.h"
#include "logging.h"
#include "temphelper.h"
#include "text_object.h"
struct _i8k {
char *version;
char *bios;
char *serial;
char *cpu_temp;
char *left_fan_status;
char *right_fan_status;
char *left_fan_rpm;
char *right_fan_rpm;
char *ac_status;
char *buttons_status;
} i8k;
/* FIXME: there should be an ioctl interface to request specific data */
#define PROC_I8K "/proc/i8k"
#define I8K_DELIM " "
static char *i8k_procbuf = nullptr;
int update_i8k(void) {
FILE *fp;
if ((fp = fopen(PROC_I8K, "r")) == nullptr) {
NORM_ERR(
"/proc/i8k doesn't exist! use insmod to make sure the kernel driver is "
"loaded...");
return 1;
}
if (!i8k_procbuf) { i8k_procbuf = (char *)malloc(128 * sizeof(char)); }
memset(&i8k_procbuf[0], 0, 128);
if (fread(&i8k_procbuf[0], sizeof(char), 128, fp) == 0) {
NORM_ERR("something wrong with /proc/i8k...");
}
fclose(fp);
DBGP("read `%s' from /proc/i8k\n", i8k_procbuf);
i8k.version = strtok(&i8k_procbuf[0], I8K_DELIM);
i8k.bios = strtok(nullptr, I8K_DELIM);
i8k.serial = strtok(nullptr, I8K_DELIM);
i8k.cpu_temp = strtok(nullptr, I8K_DELIM);
i8k.left_fan_status = strtok(nullptr, I8K_DELIM);
i8k.right_fan_status = strtok(nullptr, I8K_DELIM);
i8k.left_fan_rpm = strtok(nullptr, I8K_DELIM);
i8k.right_fan_rpm = strtok(nullptr, I8K_DELIM);
i8k.ac_status = strtok(nullptr, I8K_DELIM);
i8k.buttons_status = strtok(nullptr, I8K_DELIM);
return 0;
}
static void print_i8k_fan_status(char *p, int p_max_size, const char *status) {
static const char *status_arr[] = {"off", "low", "high", "error"};
int i = status ? atoi(status) : 3;
if (i < 0 || i > 3) i = 3;
snprintf(p, p_max_size, "%s", status_arr[i]);
}
void print_i8k_left_fan_status(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
print_i8k_fan_status(p, p_max_size, i8k.left_fan_status);
}
void print_i8k_cpu_temp(struct text_object *obj, char *p,
unsigned int p_max_size) {
int cpu_temp;
(void)obj;
sscanf(i8k.cpu_temp, "%d", &cpu_temp);
temp_print(p, p_max_size, (double)cpu_temp, TEMP_CELSIUS, 1);
}
void print_i8k_right_fan_status(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
print_i8k_fan_status(p, p_max_size, i8k.right_fan_status);
}
void print_i8k_ac_status(struct text_object *obj, char *p,
unsigned int p_max_size) {
int ac_status;
(void)obj;
sscanf(i8k.ac_status, "%d", &ac_status);
if (ac_status == -1) {
snprintf(p, p_max_size, "%s", "disabled (read i8k docs)");
}
if (ac_status == 0) { snprintf(p, p_max_size, "%s", "off"); }
if (ac_status == 1) { snprintf(p, p_max_size, "%s", "on"); }
}
#define I8K_PRINT_GENERATOR(name) \
void print_i8k_##name(struct text_object *obj, char *p, \
unsigned int p_max_size) { \
(void)obj; \
const char *str = i8k.name ? i8k.name : "error"; \
snprintf(p, p_max_size, "%s", str); \
}
I8K_PRINT_GENERATOR(version)
I8K_PRINT_GENERATOR(bios)
I8K_PRINT_GENERATOR(serial)
I8K_PRINT_GENERATOR(left_fan_rpm)
I8K_PRINT_GENERATOR(right_fan_rpm)
I8K_PRINT_GENERATOR(buttons_status)
#undef I8K_PRINT_GENERATOR
| 4,537
|
C++
|
.cc
| 127
| 32.110236
| 80
| 0.654057
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,542
|
colours.cc
|
brndnmtthws_conky/src/colours.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* 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 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 "colours.h"
#include "logging.h"
#include <optional>
Colour Colour::from_argb32(uint32_t argb) {
Colour out;
out.alpha = argb >> 24;
out.red = (argb >> 16) % 256;
out.green = (argb >> 8) % 256;
out.blue = argb % 256;
return out;
}
#ifdef BUILD_COLOUR_NAME_MAP
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wregister"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wregister"
#include <colour-names.hh>
#pragma clang diagnostic pop
#pragma GCC diagnostic pop
#else /* BUILD_COLOUR_NAME_MAP */
#include "colour-names-stub.hh"
#endif /* BUILD_COLOUR_NAME_MAP */
std::optional<Colour> parse_color_name(const std::string &name) {
const rgb *value = color_name_hash::in_word_set(name.c_str(), name.length());
if (value == nullptr) {
return std::nullopt;
} else {
return Colour{value->red, value->green, value->blue};
}
}
std::optional<Colour> parse_hex_color(const std::string &color) {
const char *name = color.c_str();
size_t len = color.length();
// Skip a leading '#' if present.
if (name[0] == '#') {
name++;
len--;
}
static auto hex_nibble_value = [](char c) {
if (c >= '0' && c <= '9') {
return c - '0';
} else if (c >= 'a' && c <= 'f') {
return c - 'a' + 10;
} else if (c >= 'A' && c <= 'F') {
return c - 'A' + 10;
}
return -1;
};
const auto none = [&]() {
NORM_ERR("can't parse hex color '%s' (%d)", name, len);
return std::nullopt;
};
uint8_t argb[4] = {0xff, 0, 0, 0};
if (len == 3 || len == 4) {
bool skip_alpha = (len == 3);
for (size_t i = 0; i < len; i++) {
int nib = hex_nibble_value(name[i]);
if (nib < 0) { return none(); }
// Duplicate the nibble, so "#abc" -> 0xaa, 0xbb, 0xcc
int val = (nib << 4) + nib;
argb[skip_alpha + i] = val;
}
} else if (len == 6 || len == 8) {
bool skip_alpha = (len == 6);
for (size_t i = 0; i + 1 < len; i += 2) {
int nib1 = hex_nibble_value(name[i]);
int nib2 = hex_nibble_value(name[i + 1]);
if (nib1 < 0 || nib2 < 0) { return none(); }
int val = (nib1 << 4) + nib2;
argb[skip_alpha + i / 2] = val;
}
} else {
return none();
}
return Colour(argb[1], argb[2], argb[3], argb[0]);
}
Colour parse_color(const std::string &color) {
std::optional<Colour> result;
#define TRY_PARSER(name) \
std::optional<Colour> value_##name = name(color); \
if (value_##name.has_value()) { return value_##name.value(); }
TRY_PARSER(parse_color_name)
TRY_PARSER(parse_hex_color)
#undef TRY_PARSER
return ERROR_COLOUR;
}
Colour::Colour(const std::string &name) {
const auto result = parse_color(name);
this->red = result.red;
this->green = result.green;
this->blue = result.blue;
this->alpha = result.alpha;
}
| 3,893
|
C++
|
.cc
| 121
| 28.958678
| 79
| 0.635492
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,543
|
colour-settings.cc
|
brndnmtthws_conky/src/colour-settings.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Please see COPYING for details
*
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* 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 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 <config.h>
#include "colour-settings.h"
namespace priv {
void colour_setting::lua_setter(lua::state &l, bool init) {
lua::stack_sentry s(l, -2);
Base::lua_setter(l, init);
++s;
}
} // namespace priv
priv::colour_setting color[COLORS_CUSTOM] = {
{"color0", white_argb32}, {"color1", white_argb32},
{"color2", white_argb32}, {"color3", white_argb32},
{"color4", white_argb32}, {"color5", white_argb32},
{"color6", white_argb32}, {"color7", white_argb32},
{"color8", white_argb32}, {"color9", white_argb32}};
priv::colour_setting default_color("default_color", white_argb32);
| 1,465
|
C++
|
.cc
| 39
| 35.230769
| 72
| 0.71519
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,544
|
prioqueue.cc
|
brndnmtthws_conky/src/prioqueue.cc
|
/*
*
* prioqueue: a simple priority queue implementation
*
* The queue organises it's data internally using a doubly linked
* list, into which elements are inserted at the right position. This
* is definitely not the best algorithm for a priority queue, but it
* fits best for the given purpose, i.e. the top process sorting.
* This means we have a rather little amount of total elements (~200
* on a normal system), which are to be inserted into a queue of only
* the few top-most elements (10 at the current state). Additionally,
* at each update interval, the queue is drained completely and
* refilled from scratch.
*
* Copyright (C) 2009 Phil Sutter <phil@nwl.cc>
*
* Initially based on the former implementation of sorted processes in
* top.c, Copyright (C) 2005 David Carter <boojit@pundo.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 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 <climits> /* INT_MAX */
#include <cstdlib>
#include <cstring>
#include "conky.h"
struct prio_elem {
struct prio_elem *next, *prev;
void *data;
};
struct prio_queue {
/* Compare a and b. Return:
* <0 if a should come before b,
* >0 if b should come before a,
* 0 if don't care */
int (*compare)(void *a, void *b);
/* Free element payload. Called when dropping elements. */
void (*free)(void *a);
/* Maximum size of queue. The first
* elements in the list take precedence. */
int max_size;
/* The pointers to the actual list. */
struct prio_elem *head, *tail;
/* The current number of elements in the list. */
int cur_size;
};
/* nop callback to save us from conditional calling */
static void pq_free_nop(void *a) { (void)a; }
struct prio_queue *init_prio_queue() {
struct prio_queue *retval;
retval = static_cast<struct prio_queue *>(malloc(sizeof(struct prio_queue)));
memset(retval, 0, sizeof(struct prio_queue));
/* use pq_free_nop by default */
retval->free = &pq_free_nop;
/* Default to maximum possible size as restricted
* by the used data type. This also saves us from
* checking if caller has set this field or not. */
retval->max_size = INT_MAX;
return retval;
}
void pq_set_compare(struct prio_queue *queue,
int (*pqcompare)(void *a, void *b)) {
if (pqcompare != nullptr) { queue->compare = pqcompare; }
}
void pq_set_free(struct prio_queue *queue, void (*pqfree)(void *a)) {
if (pqfree != nullptr) { queue->free = pqfree; }
}
void pq_set_max_size(struct prio_queue *queue, int max_size) {
if (max_size >= 0) { queue->max_size = max_size; }
}
int pq_get_cur_size(struct prio_queue *queue) { return queue->cur_size; }
static struct prio_elem *init_prio_elem(void *data) {
struct prio_elem *retval;
retval = static_cast<struct prio_elem *>(malloc(sizeof(struct prio_elem)));
memset(retval, 0, sizeof(struct prio_elem));
retval->data = data;
return retval;
}
void insert_prio_elem(struct prio_queue *queue, void *data) {
struct prio_elem *cur;
/* queue->compare is a must-have */
if (queue->compare == nullptr) { return; }
/* empty queue, insert the first item */
if (queue->cur_size == 0) {
queue->cur_size++;
queue->head = queue->tail = init_prio_elem(data);
return;
}
/* short-cut 1: new item is lower than all others */
if (queue->compare(queue->tail->data, data) <= 0) {
if (queue->cur_size < queue->max_size) {
queue->cur_size++;
queue->tail->next = init_prio_elem(data);
queue->tail->next->prev = queue->tail;
queue->tail = queue->tail->next;
} else { /* list was already full */
(*queue->free)(data);
}
return;
}
/* short-cut 2: we have a new maximum */
if (queue->compare(queue->head->data, data) >= 0) {
queue->cur_size++;
queue->head->prev = init_prio_elem(data);
queue->head->prev->next = queue->head;
queue->head = queue->head->prev;
goto check_cur_size;
}
/* find the actual position if short-cuts failed */
for (cur = queue->head->next; cur != nullptr; cur = cur->next) {
if (queue->compare(cur->data, data) >= 0) {
queue->cur_size++;
cur->prev->next = init_prio_elem(data);
cur->prev->next->prev = cur->prev;
cur->prev->next->next = cur;
cur->prev = cur->prev->next;
break;
}
}
check_cur_size:
/* drop the lowest item if queue overrun */
if (queue->cur_size > queue->max_size) {
queue->cur_size--;
queue->tail = queue->tail->prev;
(*queue->free)(queue->tail->next->data);
free_and_zero(queue->tail->next);
}
}
void *pop_prio_elem(struct prio_queue *queue) {
struct prio_elem *tmp;
void *data;
if (queue->cur_size <= 0) { return nullptr; }
tmp = queue->head;
data = tmp->data;
queue->head = queue->head->next;
queue->cur_size--;
if (queue->head != nullptr) {
queue->head->prev = nullptr;
} else { /* list is now empty */
queue->tail = nullptr;
}
free(tmp);
return data;
}
void free_prio_queue(struct prio_queue *queue) {
void *data;
while ((data = pop_prio_elem(queue)) != nullptr) { (*queue->free)(data); }
free(queue);
}
| 5,667
|
C++
|
.cc
| 159
| 32.314465
| 79
| 0.672146
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,545
|
irc.cc
|
brndnmtthws_conky/src/irc.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Please see COPYING for details
*
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* 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 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 <libircclient.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include "conky.h"
#include "logging.h"
#include "text_object.h"
struct ll_text {
char *text;
struct ll_text *next;
};
struct obj_irc {
pthread_t *thread;
irc_session_t *session;
char *arg;
};
struct ctx {
char *chan;
int max_msg_lines;
struct ll_text *messages;
};
void ev_connected(irc_session_t *session, const char *, const char *,
const char **, unsigned int) {
struct ctx *ctxptr = (struct ctx *)irc_get_ctx(session);
if (irc_cmd_join(session, ctxptr->chan, nullptr) != 0) {
NORM_ERR("irc: %s", irc_strerror(irc_errno(session)));
}
}
void addmessage(struct ctx *ctxptr, char *nick, const char *text) {
struct ll_text *lastmsg = ctxptr->messages;
struct ll_text *newmsg = (struct ll_text *)malloc(sizeof(struct ll_text));
newmsg->text = (char *)malloc(strlen(nick) + strlen(text) + 4); // 4 = ": \n"
snprintf(newmsg->text, strlen(nick) + strlen(text) + 4, "%s: %s\n", nick,
text);
newmsg->next = nullptr;
int msgcnt = 1;
if (!lastmsg) {
ctxptr->messages = newmsg;
} else {
msgcnt++;
while (lastmsg->next) {
lastmsg = lastmsg->next;
msgcnt++;
if (msgcnt < 0) {
NORM_ERR("irc: too many messages, discarding the last one.");
free(newmsg->text);
free(newmsg);
return;
}
}
lastmsg->next = newmsg;
}
if (ctxptr->max_msg_lines > 0) {
newmsg = ctxptr->messages;
msgcnt -= ctxptr->max_msg_lines;
while ((msgcnt > 0) && (ctxptr->messages)) {
msgcnt--;
newmsg = ctxptr->messages->next;
free(ctxptr->messages->text);
free(ctxptr->messages);
ctxptr->messages = newmsg;
}
}
}
void ev_talkinchan(irc_session_t *session, const char *, const char *origin,
const char **params, unsigned int) {
char nickname[64];
struct ctx *ctxptr = (struct ctx *)irc_get_ctx(session);
irc_target_get_nick(origin, nickname, sizeof(nickname));
addmessage(ctxptr, nickname, params[1]);
}
void ev_num(irc_session_t *session, unsigned int event, const char *,
const char **params, unsigned int) {
char attachment[4] = "_00";
if (event == 433) { // nick in use
int len = strlen(params[1]) + 4;
char *newnick = (char *)malloc(len);
strncpy(newnick, params[1], len);
attachment[1] += rand() % 10;
attachment[2] += rand() % 10;
strncat(newnick, attachment, len - 1);
irc_cmd_nick(session, newnick);
free(newnick);
}
}
#define IRCSYNTAX \
"The correct syntax is ${irc server(:port) #channel (max_msg_lines)}"
#define IRCPORT 6667
#define IRCNICK "conky"
#define IRCSERVERPASS nullptr
#define IRCUSER nullptr
#define IRCREAL nullptr
void *ircclient(void *ptr) {
struct obj_irc *ircobj = (struct obj_irc *)ptr;
struct ctx *ctxptr = (struct ctx *)malloc(sizeof(struct ctx));
irc_callbacks_t callbacks;
char *server;
char *strport;
char *str_max_msg_lines;
unsigned int port;
memset(&callbacks, 0, sizeof(callbacks));
callbacks.event_connect = ev_connected;
callbacks.event_channel = ev_talkinchan;
callbacks.event_numeric = ev_num;
ircobj->session = irc_create_session(&callbacks);
server = strtok(ircobj->arg, " ");
ctxptr->chan = strtok(nullptr, " ");
if (!ctxptr->chan) { NORM_ERR("irc: %s", IRCSYNTAX); }
str_max_msg_lines = strtok(nullptr, " ");
if (str_max_msg_lines) {
ctxptr->max_msg_lines = strtol(str_max_msg_lines, nullptr, 10);
}
ctxptr->messages = nullptr;
irc_set_ctx(ircobj->session, ctxptr);
server = strtok(server, ":");
strport = strtok(nullptr, ":");
if (strport) {
port = strtol(strport, nullptr, 10);
if (port < 1 || port > 65535) port = IRCPORT;
} else {
port = IRCPORT;
}
int err = irc_connect(ircobj->session, server, port, IRCSERVERPASS, IRCNICK,
IRCUSER, IRCREAL);
if (err != 0) { err = irc_errno(ircobj->session); }
#ifdef BUILD_IPV6
if (err == LIBIRC_ERR_RESOLV) {
err = irc_connect6(ircobj->session, server, port, IRCSERVERPASS, IRCNICK,
IRCUSER, IRCREAL);
if (err != 0) { err = irc_errno(ircobj->session); }
}
#endif /* BUILD_IPV6 */
if (err != 0) { NORM_ERR("irc: %s", irc_strerror(err)); }
if (irc_run(ircobj->session) != 0) {
int ircerror = irc_errno(ircobj->session);
if (irc_is_connected(ircobj->session)) {
NORM_ERR("irc: %s", irc_strerror(ircerror));
} else {
NORM_ERR("irc: disconnected");
}
}
free(ircobj->arg);
free(ctxptr);
return nullptr;
}
void parse_irc_args(struct text_object *obj, const char *arg) {
struct obj_irc *opaque = (struct obj_irc *)malloc(sizeof(struct obj_irc));
opaque->thread = (pthread_t *)malloc(sizeof(pthread_t));
srand(time(nullptr));
opaque->session = nullptr;
opaque->arg = strdup(arg);
pthread_create(opaque->thread, nullptr, ircclient, opaque);
obj->data.opaque = opaque;
}
void print_irc(struct text_object *obj, char *p, unsigned int p_max_size) {
struct obj_irc *ircobj = (struct obj_irc *)obj->data.opaque;
struct ctx *ctxptr;
struct ll_text *nextmsg, *curmsg;
if (!ircobj->session) return;
if (!irc_is_connected(ircobj->session)) return;
ctxptr = (struct ctx *)irc_get_ctx(ircobj->session);
curmsg = ctxptr->messages;
while (curmsg) {
nextmsg = curmsg->next;
strncat(p, curmsg->text, p_max_size - strlen(p) - 1);
if (!ctxptr->max_msg_lines) {
free(curmsg->text);
free(curmsg);
}
curmsg = nextmsg;
}
if (p[0] != 0) { p[strlen(p) - 1] = 0; }
if (!ctxptr->max_msg_lines) { ctxptr->messages = nullptr; }
}
void free_irc(struct text_object *obj) {
struct obj_irc *ircobj = (struct obj_irc *)obj->data.opaque;
struct ctx *ctxptr;
struct ll_text *nextmsg, *curmsg = nullptr;
if (ircobj->session) {
if (irc_is_connected(ircobj->session)) {
ctxptr = (struct ctx *)irc_get_ctx(ircobj->session);
curmsg = ctxptr->messages;
irc_disconnect(ircobj->session);
}
pthread_join(*(ircobj->thread), nullptr);
irc_destroy_session(ircobj->session);
}
free(ircobj->thread);
free(obj->data.opaque);
while (curmsg) {
nextmsg = curmsg->next;
free(curmsg->text);
free(curmsg);
curmsg = nextmsg;
}
}
| 7,148
|
C++
|
.cc
| 219
| 28.794521
| 80
| 0.656345
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,546
|
net_stat.cc
|
brndnmtthws_conky/src/net_stat.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* 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 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 "net_stat.h"
#include <ctype.h>
#include <string.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <cerrno>
#include <cstring>
#include "conky.h"
#include "logging.h"
#include "net/if.h"
#include "specials.h"
#include "text_object.h"
#if defined(__sun)
#include <sys/sockio.h>
#endif
#if defined(__HAIKU__)
#include <sys/sockio.h>
#define IFF_RUNNING IFF_LINK
#endif
#ifndef SOCK_CLOEXEC
#define SOCK_CLOEXEC O_CLOEXEC
#endif /* SOCK_CLOEXEC */
#if defined(__linux__)
#include "linux.h"
#else
static char e_iface[50] = "empty";
static char interfaces_arr[MAX_NET_INTERFACES][64] = {""};
#endif /* __linux__ */
/* network interface stuff */
enum if_up_strictness_ { IFUP_UP, IFUP_LINK, IFUP_ADDR };
template <>
conky::lua_traits<if_up_strictness_>::Map
conky::lua_traits<if_up_strictness_>::map = {
{"up", IFUP_UP}, {"link", IFUP_LINK}, {"address", IFUP_ADDR}};
static conky::simple_config_setting<if_up_strictness_> if_up_strictness(
"if_up_strictness", IFUP_UP, true);
/**
* global array of structs containing network statistics for each interface
**/
struct net_stat netstats[MAX_NET_INTERFACES];
struct net_stat foo_netstats;
/**
* Returns pointer to specified interface in netstats array.
* If not found then add the specified interface to the array.
* The added interface will have all its members initialized to 0,
* because clear_net_stats() is called from main() in conky.cc!
*
* @param[in] dev device / interface name. Silently ignores char * == nullptr
**/
struct net_stat *get_net_stat(const char *dev, void * /*free_at_crash1*/,
void * /*free_at_crash2*/) {
unsigned int i;
if (dev == nullptr) { return nullptr; }
/* find interface stat */
for (i = 0; i < MAX_NET_INTERFACES; i++) {
if ((netstats[i].dev != nullptr) && strcmp(netstats[i].dev, dev) == 0) {
return &netstats[i];
}
}
/* wasn't found? add it */
for (i = 0; i < MAX_NET_INTERFACES; i++) {
if (netstats[i].dev == nullptr) {
netstats[i].dev = strndup(dev, text_buffer_size.get(*state));
/* initialize last_read_recv and last_read_trans to -1 denoting
* that they were never read before */
netstats[i].last_read_recv = -1;
netstats[i].last_read_trans = -1;
return &netstats[i];
}
}
clear_net_stats(&foo_netstats);
foo_netstats.dev = strndup(dev, text_buffer_size.get(*state));
/* initialize last_read_recv and last_read_trans to -1 denoting
* that they were never read before */
foo_netstats.last_read_recv = -1;
foo_netstats.last_read_trans = -1;
return &foo_netstats;
}
void parse_net_stat_arg(struct text_object *obj, const char *arg,
void *free_at_crash) {
#ifdef BUILD_IPV6
bool shownetmask = false;
bool showscope = false;
#endif /* BUILD_IPV6 */
char nextarg[21]; // longest arg possible is a devname (max 20 chars)
int i = 0;
struct net_stat *netstat = nullptr;
long int x = 0;
unsigned int found = 0;
char *arg_ptr = const_cast<char *>(arg);
char buf[64];
char *buf_ptr = buf;
if (arg == nullptr) { arg = DEFAULTNETDEV; }
if (0 == (strcmp("$gw_iface", arg)) || 0 == (strcmp("${gw_iface}", arg))) {
#if defined(__linux__)
update_gateway_info();
#endif
arg = e_iface;
}
if (0 == strncmp(arg, "${iface", 7)) {
if (nullptr != arg_ptr) {
for (; *arg_ptr; arg_ptr++) {
if (isdigit(static_cast<unsigned char>(*arg_ptr))) {
*buf_ptr++ = *arg_ptr;
found = 1;
}
}
}
if (1U == found) {
*buf_ptr = '\0';
x = strtol(buf, (char **)NULL, 10);
if (63L > x) { arg = interfaces_arr[x]; }
}
}
while (sscanf(arg + i, " %20s", nextarg) == 1) {
#ifdef BUILD_IPV6
if (strcmp(nextarg, "-n") == 0 || strcmp(nextarg, "--netmask") == 0) {
shownetmask = true;
} else if (strcmp(nextarg, "-s") == 0 || strcmp(nextarg, "--scope") == 0) {
showscope = true;
} else if (nextarg[0] == '-') { // multiple flags in 1 arg
for (int j = 1; nextarg[j] != 0; j++) {
if (nextarg[j] == 'n') { shownetmask = true; }
if (nextarg[j] == 's') { showscope = true; }
}
} else {
#endif /* BUILD_IPV6 */
netstat = get_net_stat(nextarg, obj, free_at_crash);
#ifdef BUILD_IPV6
}
#endif /* BUILD_IPV6 */
i += strlen(nextarg); // skip this arg
while (
!((isspace(static_cast<unsigned char>(arg[i])) != 0) || arg[i] == 0)) {
i++; // and skip the spaces in front of it
}
}
if (netstat == nullptr) {
netstat = get_net_stat(DEFAULTNETDEV, obj, free_at_crash);
}
#ifdef BUILD_IPV6
netstat->v6show_nm = shownetmask;
netstat->v6show_sc = showscope;
#endif /* BUILD_IPV6 */
obj->data.opaque = netstat;
}
void parse_net_stat_bar_arg(struct text_object *obj, const char *arg,
void *free_at_crash) {
if (arg != nullptr) {
arg = scan_bar(obj, arg, 1);
obj->data.opaque = get_net_stat(arg, obj, free_at_crash);
} else {
// default to DEFAULTNETDEV
char *buf = strndup(DEFAULTNETDEV, text_buffer_size.get(*state));
obj->data.opaque = get_net_stat(buf, obj, free_at_crash);
free(buf);
}
}
void print_downspeed(struct text_object *obj, char *p,
unsigned int p_max_size) {
auto *ns = static_cast<struct net_stat *>(obj->data.opaque);
if (ns == nullptr) { return; }
human_readable(ns->recv_speed, p, p_max_size);
}
void print_downspeedf(struct text_object *obj, char *p,
unsigned int p_max_size) {
auto *ns = static_cast<struct net_stat *>(obj->data.opaque);
if (ns == nullptr) { return; }
spaced_print(p, p_max_size, "%.1f", 8, ns->recv_speed / 1024.0);
}
void print_upspeed(struct text_object *obj, char *p, unsigned int p_max_size) {
auto *ns = static_cast<struct net_stat *>(obj->data.opaque);
if (ns == nullptr) { return; }
human_readable(ns->trans_speed, p, p_max_size);
}
void print_upspeedf(struct text_object *obj, char *p, unsigned int p_max_size) {
auto *ns = static_cast<struct net_stat *>(obj->data.opaque);
if (ns == nullptr) { return; }
spaced_print(p, p_max_size, "%.1f", 8, ns->trans_speed / 1024.0);
}
void print_totaldown(struct text_object *obj, char *p,
unsigned int p_max_size) {
auto *ns = static_cast<struct net_stat *>(obj->data.opaque);
if (ns == nullptr) { return; }
human_readable(ns->recv, p, p_max_size);
}
void print_totalup(struct text_object *obj, char *p, unsigned int p_max_size) {
auto *ns = static_cast<struct net_stat *>(obj->data.opaque);
if (ns == nullptr) { return; }
human_readable(ns->trans, p, p_max_size);
}
void print_addr(struct text_object *obj, char *p, unsigned int p_max_size) {
auto *ns = static_cast<struct net_stat *>(obj->data.opaque);
if (ns == nullptr) { return; }
if ((ns->addr.sa_data[2] & 255) == 0 && (ns->addr.sa_data[3] & 255) == 0 &&
(ns->addr.sa_data[4] & 255) == 0 && (ns->addr.sa_data[5] & 255) == 0) {
snprintf(p, p_max_size, "%s", "No Address");
} else {
snprintf(p, p_max_size, "%u.%u.%u.%u", ns->addr.sa_data[2] & 255,
ns->addr.sa_data[3] & 255, ns->addr.sa_data[4] & 255,
ns->addr.sa_data[5] & 255);
}
}
#ifdef __linux__
void print_addrs(struct text_object *obj, char *p, unsigned int p_max_size) {
struct net_stat *ns = (struct net_stat *)obj->data.opaque;
if (!ns) return;
if (0 != ns->addrs[0] && strlen(ns->addrs) > 2) {
ns->addrs[strlen(ns->addrs) - 2] = 0; /* remove ", " from end of string */
strncpy(p, ns->addrs, p_max_size);
} else {
strncpy(p, "0.0.0.0", p_max_size);
}
}
#ifdef BUILD_IPV6
void print_v6addrs(struct text_object *obj, char *p, unsigned int p_max_size) {
struct net_stat *ns = (struct net_stat *)obj->data.opaque;
char tempaddress[INET6_ADDRSTRLEN];
struct v6addr *current_v6 = ns->v6addrs;
if (p_max_size == 0) return;
if (!ns->v6addrs) {
snprintf(p, p_max_size, "%s", "No Address");
return;
}
*p = 0;
while (current_v6) {
inet_ntop(AF_INET6, &(current_v6->addr), tempaddress, INET6_ADDRSTRLEN);
strncat(p, tempaddress, p_max_size);
// netmask
if (ns->v6show_nm) {
char netmaskstr[5]; // max 5 chars (/128 + null-terminator)
snprintf(netmaskstr, sizeof(netmaskstr), "/%u", current_v6->netmask);
strncat(p, netmaskstr, p_max_size);
}
// scope
if (ns->v6show_sc) {
char scopestr[4];
snprintf(scopestr, sizeof(scopestr), "(%c)", current_v6->scope);
strncat(p, scopestr, p_max_size);
}
// next (or last) address
current_v6 = current_v6->next;
if (current_v6) strncat(p, ", ", p_max_size);
}
}
#endif /* BUILD_IPV6 */
#endif /* __linux__ */
#ifdef BUILD_GUI
/**
* This function is called periodically to update the download and upload graphs
*
* - evaluates argument strings like 'eth0 50,120 #FFFFFF #FF0000 0 -l'
* - sets the obj->data.opaque pointer to the interface specified
*
* @param[out] obj struct which will hold evaluated arguments
* @param[in] arg argument string to evaluate
**/
void parse_net_stat_graph_arg(struct text_object *obj, const char *arg,
void *free_at_crash) {
/* scan arguments and get interface name back */
auto [buf, skip] = scan_command(arg);
scan_graph(obj, arg + skip, 0, TRUE);
// default to DEFAULTNETDEV
if (buf != nullptr) {
#if defined(__linux__)
if (0 == (strcmp("$gw_iface", buf)) || 0 == (strcmp("${gw_iface}", buf))) {
update_gateway_info();
obj->data.opaque = get_net_stat(e_iface, obj, free_at_crash);
free(buf);
return;
}
#endif
obj->data.opaque = get_net_stat(buf, obj, free_at_crash);
free(buf);
return;
}
obj->data.opaque = get_net_stat(DEFAULTNETDEV, obj, free_at_crash);
}
/**
* returns the download speed in B/s for the interface referenced by obj
*
* @param[in] obj struct containing a member data, which is a struct
* containing a void * to a net_stat struct
**/
double downspeedgraphval(struct text_object *obj) {
auto *ns = static_cast<struct net_stat *>(obj->data.opaque);
return (ns != nullptr ? ns->recv_speed : 0);
}
double upspeedgraphval(struct text_object *obj) {
auto *ns = static_cast<struct net_stat *>(obj->data.opaque);
return (ns != nullptr ? ns->trans_speed : 0);
}
#endif /* BUILD_GUI */
#ifdef BUILD_WLAN
void print_wireless_essid(struct text_object *obj, char *p,
unsigned int p_max_size) {
struct net_stat *ns = (struct net_stat *)obj->data.opaque;
if (!ns) {
for (unsigned int i = 0; *(netstats[i].dev) != 0; i++) {
if (*(netstats[i].essid) != 0) {
snprintf(p, p_max_size, "%s", netstats[i].essid);
return;
}
}
return;
}
snprintf(p, p_max_size, "%s", ns->essid);
}
void print_wireless_mode(struct text_object *obj, char *p,
unsigned int p_max_size) {
struct net_stat *ns = (struct net_stat *)obj->data.opaque;
if (!ns) return;
snprintf(p, p_max_size, "%s", ns->mode);
}
void print_wireless_channel(struct text_object *obj, char *p,
unsigned int p_max_size) {
struct net_stat *ns = (struct net_stat *)obj->data.opaque;
if (!ns) return;
if (ns->channel != 0) {
snprintf(p, p_max_size, "%i", ns->channel);
} else {
snprintf(p, p_max_size, "%s", "/");
}
}
void print_wireless_frequency(struct text_object *obj, char *p,
unsigned int p_max_size) {
struct net_stat *ns = (struct net_stat *)obj->data.opaque;
if (!ns) return;
if (ns->freq[0] != 0) {
snprintf(p, p_max_size, "%s", ns->freq);
} else {
snprintf(p, p_max_size, "/");
}
}
void print_wireless_bitrate(struct text_object *obj, char *p,
unsigned int p_max_size) {
struct net_stat *ns = (struct net_stat *)obj->data.opaque;
if (!ns) return;
snprintf(p, p_max_size, "%s", ns->bitrate);
}
void print_wireless_ap(struct text_object *obj, char *p,
unsigned int p_max_size) {
struct net_stat *ns = (struct net_stat *)obj->data.opaque;
if (!ns) return;
snprintf(p, p_max_size, "%s", ns->ap);
}
void print_wireless_link_qual(struct text_object *obj, char *p,
unsigned int p_max_size) {
struct net_stat *ns = (struct net_stat *)obj->data.opaque;
if (!ns) return;
spaced_print(p, p_max_size, "%d", 4, ns->link_qual);
}
void print_wireless_link_qual_max(struct text_object *obj, char *p,
unsigned int p_max_size) {
struct net_stat *ns = (struct net_stat *)obj->data.opaque;
if (!ns) return;
spaced_print(p, p_max_size, "%d", 4, ns->link_qual_max);
}
void print_wireless_link_qual_perc(struct text_object *obj, char *p,
unsigned int p_max_size) {
struct net_stat *ns = (struct net_stat *)obj->data.opaque;
if (!ns) return;
if (ns->link_qual_max > 0) {
spaced_print(p, p_max_size, "%.0f", 5,
(double)ns->link_qual / ns->link_qual_max * 100);
} else {
spaced_print(p, p_max_size, "unk", 5);
}
}
double wireless_link_barval(struct text_object *obj) {
struct net_stat *ns = (struct net_stat *)obj->data.opaque;
if (!ns) return 0;
return (double)ns->link_qual / ns->link_qual_max;
}
#endif /* BUILD_WLAN */
/**
* Clears the global array of net_stat structs which contains networks
* statistics for every interface.
**/
void clear_net_stats() {
#ifdef BUILD_IPV6
struct v6addr *nextv6;
#endif /* BUILD_IPV6 */
int i;
for (i = 0; i < MAX_NET_INTERFACES; i++) {
free_and_zero(netstats[i].dev);
#ifdef BUILD_IPV6
while (netstats[i].v6addrs) {
nextv6 = netstats[i].v6addrs;
netstats[i].v6addrs = netstats[i].v6addrs->next;
free_and_zero(nextv6);
}
#endif /* BUILD_IPV6 */
}
memset(netstats, 0, sizeof(netstats));
}
void clear_net_stats(net_stat *in) {
#ifdef BUILD_IPV6
struct v6addr *nextv6;
#endif /* BUILD_IPV6 */
free_and_zero(in->dev);
#ifdef BUILD_IPV6
while (in->v6addrs) {
nextv6 = in->v6addrs;
in->v6addrs = in->v6addrs->next;
free_and_zero(nextv6);
}
#endif /* BUILD_IPV6 */
}
void parse_if_up_arg(struct text_object *obj, const char *arg) {
obj->data.opaque = strndup(arg, text_buffer_size.get(*state));
}
void free_if_up(struct text_object *obj) { free_and_zero(obj->data.opaque); }
/* We should check if this is ok with OpenBSD and NetBSD as well. */
int interface_up(struct text_object *obj) {
int fd;
struct ifreq ifr {};
auto *dev = static_cast<char *>(obj->data.opaque);
if (dev == nullptr) { return 0; }
#if defined(__APPLE__) && defined(__MACH__)
if ((fd = socket(PF_INET, SOCK_DGRAM, 0)) < 0) {
#else
if ((fd = socket(PF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0)) < 0) {
#endif
CRIT_ERR("could not create sockfd");
return 0;
}
strncpy(ifr.ifr_name, dev, IFNAMSIZ);
if (ioctl(fd, SIOCGIFFLAGS, &ifr) != 0) {
/* if device does not exist, treat like not up */
if (errno != ENODEV && errno != ENXIO) { perror("SIOCGIFFLAGS"); }
goto END_FALSE;
}
if ((ifr.ifr_flags & IFF_UP) == 0) { /* iface is not up */
goto END_FALSE;
}
if (if_up_strictness.get(*state) == IFUP_UP) { goto END_TRUE; }
#ifdef IFF_RUNNING
if ((ifr.ifr_flags & IFF_RUNNING) == 0) { goto END_FALSE; }
#endif
if (if_up_strictness.get(*state) == IFUP_LINK) { goto END_TRUE; }
if (ioctl(fd, SIOCGIFADDR, &ifr) != 0) {
perror("SIOCGIFADDR");
goto END_FALSE;
}
if ((reinterpret_cast<struct sockaddr_in *>(&(ifr.ifr_addr)))
->sin_addr.s_addr != 0u) {
goto END_TRUE;
}
END_FALSE:
close(fd);
return 0;
END_TRUE:
close(fd);
return 1;
}
class _dns_data {
public:
_dns_data() = default;
int nscount{0};
char **ns_list{nullptr};
void reset() {
nscount = 0;
ns_list = nullptr;
}
};
static _dns_data dns_data;
void free_dns_data(struct text_object *obj) {
int i;
(void)obj;
for (i = 0; i < dns_data.nscount; i++) { free(dns_data.ns_list[i]); }
free(dns_data.ns_list);
dns_data.reset();
}
int update_dns_data() {
FILE *fp;
char line[256];
// static double last_dns_update = 0.0;
/* maybe updating too often causes higher load because of /etc lying on a real
FS if (current_update_time - last_dns_update < 10.0) return 0;
last_dns_update = current_update_time;
*/
free_dns_data(nullptr);
if ((fp = fopen("/etc/resolv.conf", "re")) == nullptr) { return 0; }
while (feof(fp) == 0) {
if (fgets(line, 255, fp) == nullptr) { break; }
if (strncmp(line, "nameserver ", 11) == 0) {
line[strlen(line) - 1] = '\0'; // remove trailing newline
dns_data.nscount++;
dns_data.ns_list = static_cast<char **>(
realloc(dns_data.ns_list, dns_data.nscount * sizeof(char *)));
dns_data.ns_list[dns_data.nscount - 1] =
strndup(line + 11, text_buffer_size.get(*state));
}
}
fclose(fp);
return 0;
}
void parse_nameserver_arg(struct text_object *obj, const char *arg) {
obj->data.l = arg != nullptr ? strtol(arg, nullptr, 10) : 0;
}
void print_nameserver(struct text_object *obj, char *p,
unsigned int p_max_size) {
if (dns_data.nscount > obj->data.l) {
snprintf(p, p_max_size, "%s", dns_data.ns_list[obj->data.l]);
}
}
| 18,438
|
C++
|
.cc
| 535
| 30.321495
| 80
| 0.625821
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,547
|
bsdapm.cc
|
brndnmtthws_conky/src/bsdapm.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* 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 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 <fcntl.h>
#include <machine/apm_bios.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include "config.h"
#include "conky.h"
#include "text_object.h"
#define APMDEV "/dev/apm"
#define APM_UNKNOWN 255
#ifndef APM_AC_OFF
#define APM_AC_OFF 0
#endif
#ifndef APM_AC_ON
#define APM_AC_ON 1
#endif
#ifndef APM_BATT_CHARGING
#define APM_BATT_CHARGING 3
#endif
static int apm_getinfo(int fd, apm_info_t aip) {
#ifdef __OpenBSD__
if (ioctl(fd, APM_IOC_GETPOWER, aip) == -1) {
#else
if (ioctl(fd, APMIO_GETINFO, aip) == -1) {
#endif
return -1;
}
return 0;
}
void print_apm_adapter(struct text_object *obj, char *p,
unsigned int p_max_size) {
int fd;
const char *out;
#ifdef __OpenBSD__
struct apm_power_info a_info;
#else
struct apm_info a_info;
#endif
(void)obj;
fd = open(APMDEV, O_RDONLY);
if (fd < 0) {
snprintf(p, p_max_size, "%s", "ERR");
return;
}
if (apm_getinfo(fd, &a_info) != 0) {
close(fd);
snprintf(p, p_max_size, "%s", "ERR");
return;
}
close(fd);
#ifdef __OpenBSD__
#define ai_acline ac_state
#endif
switch (a_info.ai_acline) {
case APM_AC_OFF:
out = "off-line";
break;
case APM_AC_ON:
#ifdef __OpenBSD__
#define ai_batt_stat battery_state
#endif
if (a_info.ai_batt_stat == APM_BATT_CHARGING) {
out = "charging";
} else {
out = "on-line";
}
break;
default:
out = "unknown";
break;
}
snprintf(p, p_max_size, "%s", out);
}
void print_apm_battery_life(struct text_object *obj, char *p,
unsigned int p_max_size) {
int fd;
u_int batt_life;
const char *out;
#ifdef __OpenBSD__
struct apm_power_info a_info;
#else
struct apm_info a_info;
#endif
(void)obj;
fd = open(APMDEV, O_RDONLY);
if (fd < 0) {
snprintf(p, p_max_size, "%s", "ERR");
return;
}
if (apm_getinfo(fd, &a_info) != 0) {
close(fd);
snprintf(p, p_max_size, "%s", "ERR");
return;
}
close(fd);
#ifdef __OpenBSD__
#define ai_batt_life battery_life
#endif
batt_life = a_info.ai_batt_life;
if (batt_life == APM_UNKNOWN) {
out = "unknown";
} else if (batt_life <= 100) {
snprintf(p, p_max_size, "%d%%", batt_life);
return;
} else {
out = "ERR";
}
snprintf(p, p_max_size, "%s", out);
}
void print_apm_battery_time(struct text_object *obj, char *p,
unsigned int p_max_size) {
int fd;
int batt_time;
#ifdef __OpenBSD__
int h, m;
struct apm_power_info a_info;
#else
int h, m, s;
struct apm_info a_info;
#endif
(void)obj;
fd = open(APMDEV, O_RDONLY);
if (fd < 0) {
snprintf(p, p_max_size, "%s", "ERR");
return;
}
if (apm_getinfo(fd, &a_info) != 0) {
close(fd);
snprintf(p, p_max_size, "%s", "ERR");
return;
}
close(fd);
#ifdef __OpenBSD__
#define ai_batt_time minutes_left
#endif
batt_time = a_info.ai_batt_time;
if (batt_time == -1) {
snprintf(p, p_max_size, "%s", "unknown");
} else
#ifdef __OpenBSD__
{
h = batt_time / 60;
m = batt_time % 60;
snprintf(p, p_max_size, "%2d:%02d", h, m);
}
#else
{
h = batt_time;
s = h % 60;
h /= 60;
m = h % 60;
h /= 60;
snprintf(p, p_max_size, "%2d:%02d:%02d", h, m, s);
}
#endif
}
| 4,336
|
C++
|
.cc
| 183
| 20.306011
| 72
| 0.632203
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,548
|
setting.cc
|
brndnmtthws_conky/src/setting.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Please see COPYING for details
*
* Copyright (C) 2010 Pavel Labath et al.
*
* 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 <config.h>
#include "setting.hh"
#include <algorithm>
#include <memory>
#include <unordered_map>
#include <utility>
#include <vector>
namespace conky {
namespace {
typedef std::unordered_map<std::string, priv::config_setting_base *>
settings_map;
using settings_vector = std::vector<priv::config_setting_base *>;
/*
* We cannot construct this object statically, because order of object
* construction in different modules is not defined, so config_setting_base
* could be called before this object is constructed. Therefore, we create it on
* the first call to config_setting_base constructor.
*/
settings_map *settings;
/*
* Returns the setting record corresponding to the value at the specified index.
* If the value is not valid, returns nullptr and prints an error.
*/
priv::config_setting_base *get_setting(lua::state &l, int index) {
lua::Type type = l.type(index);
if (type != lua::TSTRING) {
NORM_ERR("invalid setting of type '%s'", l.type_name(type));
return nullptr;
}
const std::string &name = l.tostring(index);
auto iter = settings->find(name);
if (iter == settings->end()) {
NORM_ERR("Unknown setting '%s'", name.c_str());
return nullptr;
}
return iter->second;
}
const std::vector<std::string> settings_ordering{
"display",
"out_to_x",
"use_xft",
"font",
"font0",
"font1",
"font2",
"font3",
"font4",
"font5",
"font6",
"font7",
"font8",
"font9",
"color0",
"color1",
"color2",
"color3",
"color4",
"color5",
"color6",
"color7",
"color8",
"color9",
"default_color",
"default_shade_color",
"default_outline_color",
"border_inner_margin",
"border_outer_margin",
"border_width",
"alignment",
"xinerama_head",
"own_window_transparent",
"own_window_class",
"own_window_title",
"own_window_type",
"own_window_hints",
"own_window_argb_value",
"own_window_argb_visual",
"own_window_colour",
"own_window",
"double_buffer",
"out_to_wayland",
"imlib_cache_size",
};
// returns a vector of all settings, sorted in order of registration
settings_vector make_settings_vector() {
settings_vector ret;
ret.reserve(settings->size());
// for _some_ settings, the order matters, for others it does not. first we
// fill the vec with the settings which are ordered, then we add the remainder
// in.
for (auto &name : settings_ordering) {
if (settings->count(name) > 0) {
auto setting = settings->at(name);
ret.push_back(setting);
}
}
for (auto &setting : *settings) {
if (std::find(settings_ordering.begin(), settings_ordering.end(),
setting.second->name) == settings_ordering.end()) {
ret.push_back(setting.second);
}
}
auto start = ret.begin();
std::advance(start, settings_ordering.size());
sort(start, ret.end(), &priv::config_setting_base::seq_compare);
return ret;
}
/*
* Returns the seq_no for the new setting object. Also constructs settings
* object if needed.
*/
size_t get_next_seq_no() {
struct settings_constructor {
settings_constructor() { settings = new settings_map; }
~settings_constructor() {
delete settings;
settings = nullptr;
}
};
static settings_constructor constructor;
return settings->size();
}
} // namespace
namespace priv {
config_setting_base::config_setting_base(std::string name_)
: name(std::move(name_)), seq_no(get_next_seq_no()) {
bool inserted = settings->insert({name, this}).second;
if (!inserted) {
throw std::logic_error("Setting with name '" + name +
"' already registered");
}
}
void config_setting_base::lua_set(lua::state &l) {
std::lock_guard<lua::state> guard(l);
lua::stack_sentry s(l, -1);
l.checkstack(2);
l.getglobal("conky");
l.rawgetfield(-1, "config");
l.replace(-2);
l.insert(-2);
l.setfield(-2, name.c_str());
l.pop();
}
/*
* Performs the actual assignment of settings. Calls the setting-specific setter
* after some sanity-checking. stack on entry: | ..., new_config_table, key,
* value, old_value | stack on exit: | ..., new_config_table |
*/
void config_setting_base::process_setting(lua::state &l, bool init) {
lua::stack_sentry s(l, -3);
config_setting_base *ptr = get_setting(l, -3);
if (ptr == nullptr) { return; }
ptr->lua_setter(l, init);
l.pushvalue(-2);
l.insert(-2);
l.rawset(-4);
}
/*
* Called when user sets a new value for a setting
* stack on entry: | config_table, key, value |
* stack on exit: | |
*/
int config_setting_base::config__newindex(lua::state *l) {
lua::stack_sentry s(*l, -3);
l->checkstack(1);
l->getmetatable(-3);
l->replace(-4);
l->pushvalue(-2);
l->rawget(-4);
process_setting(*l, false);
return 0;
}
/*
* conky.config will not be a table, but a userdata with some metamethods we do
* this because we want to control access to the settings we use the metatable
* for storing the settings, that means having a setting whose name starts with
* "__" is a bad idea stack on entry: | ... | stack on exit: | ...
* new_config_table |
*/
void config_setting_base::make_conky_config(lua::state &l) {
lua::stack_sentry s(l);
l.checkstack(3);
l.newuserdata(1);
l.newtable();
{
l.pushboolean(false);
l.rawsetfield(-2, "__metatable");
l.pushvalue(-1);
l.rawsetfield(-2, "__index");
l.pushfunction(&priv::config_setting_base::config__newindex);
l.rawsetfield(-2, "__newindex");
}
l.setmetatable(-2);
++s;
}
} // namespace priv
void set_config_settings(lua::state &l) {
lua::stack_sentry s(l);
l.checkstack(6);
// Force creation of settings map. In the off chance we have no settings.
get_next_seq_no();
l.getglobal("conky");
{
if (l.type(-1) != lua::TTABLE) {
throw std::runtime_error("conky must be a table");
}
l.rawgetfield(-1, "config");
{
if (l.type(-1) != lua::TTABLE) {
throw std::runtime_error("conky.config must be a table");
}
priv::config_setting_base::make_conky_config(l);
l.rawsetfield(-3, "config");
l.rawgetfield(-2, "config");
l.getmetatable(-1);
l.replace(-2);
{
const settings_vector &v = make_settings_vector();
for (auto i : v) {
l.pushstring(i->name);
l.rawgetfield(-3, i->name.c_str());
l.pushnil();
priv::config_setting_base::process_setting(l, true);
}
}
l.pop();
// print error messages for unknown settings
l.pushnil();
while (l.next(-2)) {
l.pop();
get_setting(l, -1);
}
}
l.pop();
}
l.pop();
}
void cleanup_config_settings(lua::state &l) {
lua::stack_sentry s(l);
l.checkstack(2);
l.getglobal("conky");
l.rawgetfield(-1, "config");
l.replace(-2);
const settings_vector &v = make_settings_vector();
for (size_t i = v.size(); i > 0; --i) {
l.getfield(-1, v[i - 1]->name.c_str());
v[i - 1]->cleanup(l);
}
l.pop();
}
} // namespace conky
| 7,897
|
C++
|
.cc
| 272
| 25.143382
| 80
| 0.650482
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,549
|
ical.cc
|
brndnmtthws_conky/src/ical.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Please see COPYING for details
*
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* 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 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 <libical/ical.h>
#include "conky.h"
#include "logging.h"
struct ical_event {
icaltimetype start;
icalcomponent *event;
ical_event *next, *prev;
};
struct obj_ical {
struct ical_event *list;
icalcomponent *comps;
icalparser *parser;
unsigned int num;
};
char *read_stream(char *s, size_t size, void *d) {
return fgets(s, size, (FILE *)d);
}
struct ical_event *add_event(struct ical_event *listend,
icalcomponent *new_ev) {
struct ical_event *ev_new, *ev_cur;
icaltimetype start;
start = icalcomponent_get_dtstart(new_ev);
if (icaltime_compare(
start, icaltime_from_timet_with_zone(time(nullptr), 0, NULL)) <= 0) {
icalproperty *rrule =
icalcomponent_get_first_property(new_ev, ICAL_RRULE_PROPERTY);
if (rrule) {
icalrecur_iterator *ritr =
icalrecur_iterator_new(icalproperty_get_rrule(rrule), start);
icaltimetype nexttime = icalrecur_iterator_next(ritr);
while (!icaltime_is_null_time(nexttime)) {
if (icaltime_compare(nexttime, icaltime_from_timet_with_zone(
time(nullptr), 0, NULL)) > 0) {
start = nexttime;
break;
}
nexttime = icalrecur_iterator_next(ritr);
}
icalrecur_iterator_free(ritr);
} else
return nullptr;
}
ev_new = (struct ical_event *)malloc(sizeof(struct ical_event));
memset(ev_new, 0, sizeof(struct ical_event));
ev_new->event = new_ev;
ev_new->start = start;
if (listend) { // list already contains events
ev_cur = listend;
while (icaltime_compare(ev_new->start, ev_cur->start) <= 0) {
if (!ev_cur->prev) { // ev_new starts first
ev_new->next = ev_cur;
ev_cur->prev = ev_new;
return listend;
}
ev_cur = ev_cur->prev;
}
if (ev_cur == listend) { // ev_new starts last
ev_cur->next = ev_new;
ev_new->prev = ev_cur;
return ev_new;
}
// ev_new somewhere in the middle
ev_new->prev = ev_cur;
ev_new->next = ev_cur->next;
ev_cur->next->prev = ev_new;
ev_cur->next = ev_new;
return listend;
}
return ev_new;
}
void parse_ical_args(struct text_object *obj, const char *arg,
void *free_at_crash, void *free_at_crash2) {
char *filename = strdup(arg);
FILE *file;
icalparser *parser;
icalcomponent *allc, *curc;
struct ical_event *ll_start, *ll_end, *ll_new;
struct obj_ical *opaque;
unsigned int num;
if (sscanf(arg, "%d %s", &num, filename) != 2) {
free(filename);
free(obj);
CRIT_ERR_FREE(free_at_crash, free_at_crash2,
"wrong number of arguments for $ical");
}
file = fopen(filename, "r");
if (!file) {
free(obj);
free(free_at_crash);
CRIT_ERR_FREE(filename, free_at_crash2, "Can't read file %s", filename);
return;
}
free(filename);
parser = icalparser_new();
icalparser_set_gen_data(parser, file);
allc = icalparser_parse(parser, read_stream);
fclose(file);
curc = icalcomponent_get_first_component(allc, ICAL_VEVENT_COMPONENT);
if (!curc) {
icalparser_free(parser);
icalcomponent_free(allc);
NORM_ERR("No ical events available");
return;
}
ll_start = add_event(nullptr, curc);
ll_end = ll_start;
while (1) {
curc = icalcomponent_get_next_component(allc, ICAL_VEVENT_COMPONENT);
if (!curc) break;
ll_new = add_event(ll_end, curc);
if (!ll_start) { // first component was not added
ll_start = ll_new;
ll_end = ll_new;
} else if (ll_start->prev) {
ll_start = ll_start->prev;
} else if (ll_end->next) {
ll_end = ll_end->next;
}
}
opaque = (struct obj_ical *)malloc(sizeof(struct obj_ical));
opaque->list = ll_start;
opaque->parser = parser;
opaque->comps = allc;
opaque->num = num;
obj->data.opaque = opaque;
free(opaque);
}
void print_ical(struct text_object *obj, char *p, unsigned int p_max_size) {
struct obj_ical *ical_obj = (struct obj_ical *)obj->data.opaque;
struct ical_event *ll_current;
if (!ical_obj) return;
ll_current = ical_obj->list;
unsigned int i = 1;
while (1) {
if (!ll_current) return;
if (i > ical_obj->num) return;
if (i == ical_obj->num) break;
if (i < ical_obj->num) {
ll_current = ll_current->next;
i++;
}
}
snprintf(p, p_max_size, "%s",
icalproperty_get_summary(icalcomponent_get_first_property(
ll_current->event, ICAL_SUMMARY_PROPERTY)));
}
void free_ical(struct text_object *obj) {
struct obj_ical *ical_free_me = (struct obj_ical *)obj->data.opaque;
if (!ical_free_me) return;
icalcomponent_free(ical_free_me->comps);
icalparser_free(ical_free_me->parser);
while (ical_free_me->list) {
if (ical_free_me->list->next) {
ical_free_me->list = ical_free_me->list->next;
free_and_zero(ical_free_me->list->prev);
} else
free_and_zero(ical_free_me->list);
}
free(obj->data.opaque);
}
| 5,840
|
C++
|
.cc
| 183
| 27.191257
| 79
| 0.64535
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,550
|
luamm.cc
|
brndnmtthws_conky/src/luamm.cc
|
/*
*
* luamm: C++ binding for lua
*
* Copyright (C) 2010 Pavel Labath et al.
*
* 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 <config.h>
#include "luamm.hh"
namespace lua {
namespace {
#if LUA_VERSION_NUM >= 502
// These two functions were deprecated in 5.2. Limited backwards compatibility
// is provided by macros. We want them as real functions, because we take their
// addresses.
#undef lua_equal
int lua_equal(lua_State *L, int index1, int index2) {
return lua_compare(L, index1, index2, LUA_OPEQ);
}
#undef lua_lessthan
int lua_lessthan(lua_State *L, int index1, int index2) {
return lua_compare(L, index1, index2, LUA_OPLT);
}
#endif
// keys for storing values in lua registry
const char cpp_exception_metatable[] = "lua::cpp_exception_metatable";
const char cpp_function_metatable[] = "lua::cpp_function_metatable";
const char lua_exception_namespace[] = "lua::lua_exception_namespace";
const char this_cpp_object[] = "lua::this_cpp_object";
// converts C++ exceptions to strings, so lua can do something with them
int exception_to_string(lua_State *l) {
auto *ptr = static_cast<std::exception_ptr *>(lua_touserdata(l, -1));
assert(ptr);
try {
std::rethrow_exception(*ptr);
} catch (std::exception &e) { lua_pushstring(l, e.what()); } catch (...) {
lua_pushstring(l, typeid(*ptr).name());
}
return 1;
}
int absindex(lua_State *l, int index) {
return index < 0 && -index <= lua_gettop(l) ? lua_gettop(l) + 1 + index
: index;
}
// Just like getfield(), only without calling metamethods (or throwing random
// exceptions)
inline void rawgetfield(lua_State *l, int index, const char *k) {
index = absindex(l, index);
if (lua_checkstack(l, 1) == 0) { throw std::bad_alloc(); }
lua_pushstring(l, k);
lua_rawget(l, index);
}
// Just like setfield(), only without calling metamethods (or throwing random
// exceptions)
inline void rawsetfield(lua_State *l, int index, const char *k) {
index = absindex(l, index);
if (lua_checkstack(l, 2) == 0) { throw std::bad_alloc(); }
lua_pushstring(l, k);
lua_insert(l, -2);
lua_rawset(l, index);
}
int closure_trampoline(lua_State *l) {
lua_checkstack(l, 2);
rawgetfield(l, REGISTRYINDEX, this_cpp_object);
assert(lua_islightuserdata(l, -1));
auto *L = static_cast<state *>(lua_touserdata(l, -1));
lua_pop(l, 1);
try {
auto *fn = static_cast<cpp_function *>(L->touserdata(lua_upvalueindex(1)));
assert(fn);
return (*fn)(L);
} catch (lua::exception &e) {
// rethrow lua errors as such
e.push_lua_error(L);
} catch (...) {
// C++ exceptions (pointers to them, actually) are stored as lua userdata
// and then thrown
L->createuserdata<std::exception_ptr>(std::current_exception());
L->rawgetfield(REGISTRYINDEX, cpp_exception_metatable);
L->setmetatable(-2);
}
// lua_error does longjmp(), so destructors for objects in this function will
// not be called
return lua_error(l);
}
/*
* This function is called when lua encounters an error outside of any protected
* environment
* Throwing the exception through lua code appears to work, even if it was
* compiled without -fexceptions. If it turns out, it fails in some conditions,
* it could be replaced with some longjmp() magic. But that shouldn't be
* necessary, as this function will not be called under normal conditions (we
* execute everything in protected mode).
*/
int panic_throw(lua_State *l) {
if (lua_checkstack(l, 1) == 0) { throw std::bad_alloc(); }
rawgetfield(l, REGISTRYINDEX, this_cpp_object);
assert(lua_islightuserdata(l, -1));
auto *L = static_cast<state *>(lua_touserdata(l, -1));
lua_pop(l, 1);
throw lua::exception(L);
}
// protected mode wrappers for various lua functions
int safe_concat_trampoline(lua_State *l) {
lua_concat(l, lua_gettop(l));
return 1;
}
template <int (*compare)(lua_State *, int, int)>
int safe_compare_trampoline(lua_State *l) {
int r = compare(l, 1, 2);
lua_pop(l, 2);
lua_pushinteger(l, r);
return 1;
}
int safe_gc_trampoline(lua_State *l) {
int what = lua_tointeger(l, -2);
int data = lua_tointeger(l, -1);
lua_pop(l, 2);
lua_pushinteger(l, lua_gc(l, what, data));
return 1;
}
template <void (*misc)(lua_State *, int), int nresults>
int safe_misc_trampoline(lua_State *l) {
misc(l, 1);
return nresults;
}
// Overloaded for Lua 5.3+ as lua_gettable and others return an int
template <int (*misc)(lua_State *, int), int nresults>
int safe_misc_trampoline(lua_State *l) {
misc(l, 1);
return nresults;
}
int safe_next_trampoline(lua_State *l) {
int r = lua_next(l, 1);
lua_checkstack(l, 1);
lua_pushinteger(l, r);
return r != 0 ? 3 : 1;
}
} // namespace
std::string exception::get_error_msg(state *L) {
static const std::string default_msg("Unknown lua exception");
try {
return L->tostring(-1);
} catch (not_string_error &e) { return default_msg; }
}
exception::exception(state *l) : std::runtime_error(get_error_msg(l)), L(l) {
L->checkstack(1);
L->rawgetfield(REGISTRYINDEX, lua_exception_namespace);
L->insert(-2);
key = L->ref(-2);
L->pop(1);
}
exception::~exception() {
if (L == nullptr) { return; }
L->checkstack(1);
L->rawgetfield(REGISTRYINDEX, lua_exception_namespace);
L->unref(-1, key);
L->pop();
}
void exception::push_lua_error(state *l) {
if (l != L) {
throw std::runtime_error(
"Cannot transfer exceptions between different lua contexts");
}
l->checkstack(2);
l->rawgetfield(REGISTRYINDEX, lua_exception_namespace);
l->rawgeti(-1, key);
l->replace(-2);
}
state::state() {
if (lua_State *l = luaL_newstate()) {
cobj.reset(l, &lua_close);
} else {
// docs say this can happen only in case of a memory allocation error
throw std::bad_alloc();
}
// set our panic function
lua_atpanic(cobj.get(), panic_throw);
checkstack(2);
// store a pointer to ourselves
pushlightuserdata(this);
rawsetfield(REGISTRYINDEX, this_cpp_object);
// a metatable for C++ exceptions travelling through lua code
newmetatable(cpp_exception_metatable);
lua_pushcfunction(cobj.get(), &exception_to_string);
rawsetfield(-2, "__tostring");
pushboolean(false);
rawsetfield(-2, "__metatable");
pushdestructor<std::exception_ptr>();
rawsetfield(-2, "__gc");
pop();
// a metatable for C++ functions callable from lua code
newmetatable(cpp_function_metatable);
pushboolean(false);
rawsetfield(-2, "__metatable");
pushdestructor<cpp_function>();
rawsetfield(-2, "__gc");
pop();
// while they're travelling through C++ code, lua exceptions will reside here
newtable();
rawsetfield(REGISTRYINDEX, lua_exception_namespace);
luaL_openlibs(cobj.get());
}
void state::call(int nargs, int nresults, int errfunc) {
int r = lua_pcall(cobj.get(), nargs, nresults, errfunc);
if (r == 0) { return; }
if (r == LUA_ERRMEM) {
// memory allocation error, cross your fingers
throw std::bad_alloc();
}
checkstack(3);
rawgetfield(REGISTRYINDEX, cpp_exception_metatable);
if (getmetatable(-2)) {
if (rawequal(-1, -2)) {
// it's a C++ exception, rethrow it
auto *ptr = static_cast<std::exception_ptr *>(touserdata(-3));
assert(ptr);
/*
* we create a copy, so we can pop the object without fearing the
* exception will be collected by lua's GC
*/
std::exception_ptr t(*ptr);
ptr = nullptr;
pop(3);
std::rethrow_exception(t);
}
pop(2);
}
// it's a lua exception, wrap it
if (r == LUA_ERRERR) { throw lua::errfunc_error(this); }
{ throw lua::exception(this); }
}
void state::checkstack(int extra) {
if (lua_checkstack(cobj.get(), extra) == 0) { throw std::bad_alloc(); }
}
void state::concat(int n) {
assert(n >= 0);
checkstack(1);
lua_pushcfunction(cobj.get(), safe_concat_trampoline);
insert(-n - 1);
call(n, 1, 0);
}
bool state::equal(int index1, int index2) {
// avoid pcall overhead in trivial cases
if (rawequal(index1, index2)) { return true; }
return safe_compare(&safe_compare_trampoline<lua_equal>, index1, index2);
}
int state::gc(int what, int data) {
checkstack(3);
lua_pushcfunction(cobj.get(), safe_gc_trampoline);
pushinteger(what);
pushinteger(data);
call(2, 1, 0);
assert(state::_isnumber(-1));
int r = tointeger(-1);
pop();
return r;
}
void state::getfield(int index, const char *k) {
checkstack(1);
index = absindex(index);
pushstring(k);
gettable(index);
}
void state::getglobal(const char *name) {
#if LUA_VERSION_NUM >= 502
checkstack(1);
pushinteger(LUA_RIDX_GLOBALS);
gettable(REGISTRYINDEX);
getfield(-1, name);
replace(-2);
#else
getfield(LUA_GLOBALSINDEX, name);
#endif
}
void state::gettable(int index) {
checkstack(2);
pushvalue(index);
insert(-2);
lua_pushcfunction(cobj.get(), (&safe_misc_trampoline<&lua_gettable, 1>));
insert(-3);
call(2, 1, 0);
}
bool state::lessthan(int index1, int index2) {
return safe_compare(&safe_compare_trampoline<&lua_lessthan>, index1, index2);
}
void state::loadfile(const char *filename) {
switch (luaL_loadfile(cobj.get(), filename)) {
case 0:
return;
case LUA_ERRSYNTAX:
throw lua::syntax_error(this);
case LUA_ERRFILE:
throw lua::file_error(this);
case LUA_ERRMEM:
throw std::bad_alloc();
default:
assert(0);
}
}
void state::loadstring(const char *s) {
switch (luaL_loadstring(cobj.get(), s)) {
case 0:
return;
case LUA_ERRSYNTAX:
throw lua::syntax_error(this);
case LUA_ERRMEM:
throw std::bad_alloc();
default:
assert(0);
}
}
bool state::next(int index) {
checkstack(2);
pushvalue(index);
insert(-2);
lua_pushcfunction(cobj.get(), &safe_next_trampoline);
insert(-3);
call(2, MULTRET, 0);
assert(state::_isnumber(-1));
int r = tointeger(-1);
pop();
return r != 0;
}
void state::pushclosure(const cpp_function &fn, int n) {
checkstack(2);
createuserdata<cpp_function>(fn);
rawgetfield(REGISTRYINDEX, cpp_function_metatable);
setmetatable(-2);
insert(-n - 1);
lua_pushcclosure(cobj.get(), &closure_trampoline, n + 1);
}
void state::rawgetfield(int index, const char *k) {
lua::rawgetfield(cobj.get(), index, k);
}
void state::rawsetfield(int index, const char *k) {
lua::rawsetfield(cobj.get(), index, k);
}
bool state::safe_compare(lua_CFunction trampoline, int index1, int index2) {
// if one of the indexes is invalid, return false
if (isnone(index1) || isnone(index2)) { return false; }
// convert relative indexes into absolute
index1 = absindex(index1);
index2 = absindex(index2);
checkstack(3);
lua_pushcfunction(cobj.get(), trampoline);
pushvalue(index1);
pushvalue(index2);
call(2, 1, 0);
assert(state::_isnumber(-1));
int r = tointeger(-1);
pop();
return r != 0;
}
void state::setfield(int index, const char *k) {
checkstack(1);
index = absindex(index);
pushstring(k);
insert(-2);
settable(index);
}
void state::setglobal(const char *name) {
#if LUA_VERSION_NUM >= 502
stack_sentry s(*this, -1);
checkstack(1);
pushinteger(LUA_RIDX_GLOBALS);
gettable(REGISTRYINDEX);
insert(-2);
setfield(-2, name);
pop();
#else
setfield(LUA_GLOBALSINDEX, name);
#endif
}
void state::settable(int index) {
checkstack(2);
pushvalue(index);
insert(-3);
lua_pushcfunction(cobj.get(), (&safe_misc_trampoline<&lua_settable, 0>));
insert(-4);
call(3, 0, 0);
}
std::string state::tostring(int index) {
size_t len;
const char *str = lua_tolstring(cobj.get(), index, &len);
if (str == nullptr) { throw not_string_error(); }
return std::string(str, len);
}
} // namespace lua
| 12,327
|
C++
|
.cc
| 401
| 27.708229
| 80
| 0.683904
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,551
|
mysql.cc
|
brndnmtthws_conky/src/mysql.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* 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 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 "mysql.h"
#include "conky.h"
#include "logging.h"
#include <mysql.h>
#include "setting.hh"
namespace {
conky::simple_config_setting<std::string> host("mysql_host", "localhost",
false);
conky::range_config_setting<in_port_t> port("mysql_port", 0, 0xffff, 0, false);
conky::simple_config_setting<std::string> user("mysql_user", "root", false);
conky::simple_config_setting<std::string> password("mysql_password",
std::string(), false);
conky::simple_config_setting<std::string> db("mysql_db", "mysql", false);
} // namespace
void mysql_finish(MYSQL *conn, MYSQL_RES *res) {
if (nullptr != res) { mysql_free_result(res); }
mysql_close(conn);
mysql_library_end();
}
void print_mysql(struct text_object *obj, char *p, unsigned int p_max_size) {
MYSQL *conn = mysql_init(nullptr);
MYSQL_RES *res = nullptr;
if (conn == nullptr) {
NORM_ERR("Can't initialize MySQL");
mysql_library_end();
return;
}
if (!mysql_real_connect(conn, host.get(*state).c_str(),
user.get(*state).c_str(),
password.get(*state).c_str(), db.get(*state).c_str(),
port.get(*state), nullptr, 0)) {
NORM_ERR("MySQL: %s", mysql_error(conn));
mysql_finish(conn, res);
return;
}
if (mysql_query(conn, obj->data.s)) {
NORM_ERR("MySQL: %s", mysql_error(conn));
mysql_finish(conn, res);
return;
}
res = mysql_use_result(conn);
if (res == nullptr) {
NORM_ERR("MySQL: %s", mysql_error(conn));
mysql_finish(conn, res);
return;
}
MYSQL_ROW row = mysql_fetch_row(res);
if (row) {
snprintf(p, p_max_size, "%s", row[0]);
} else {
NORM_ERR("MySQL: '%s' returned no results", obj->data.s);
}
mysql_finish(conn, res);
}
| 2,843
|
C++
|
.cc
| 81
| 30.358025
| 79
| 0.649365
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,552
|
display-http.cc
|
brndnmtthws_conky/src/display-http.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Please see COPYING for details
*
* Copyright (C) 2018 François Revol et al.
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* 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 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 <config.h>
#include "conky.h"
#include "display-http.hh"
#include <iostream>
#include <sstream>
#include <unordered_map>
#include <microhttpd.h>
namespace conky {
namespace {
conky::display_output_http http_output;
} // namespace
template <>
void register_output<output_t::HTTP>(display_outputs_t &outputs) {
outputs.push_back(&http_output);
}
// TODO: cleanup namespace
// namespace priv {
#ifdef MHD_YES
/* older API */
#define MHD_Result int
#endif /* MHD_YES */
std::string webpage;
struct MHD_Daemon *httpd;
static conky::simple_config_setting<bool> http_refresh("http_refresh", false,
true);
static conky::simple_config_setting<unsigned short> http_port("http_port",
HTTPPORT, true);
MHD_Result sendanswer(void *cls, struct MHD_Connection *connection,
const char *url, const char *method, const char *version,
const char *upload_data, size_t *upload_data_size,
void **con_cls) {
struct MHD_Response *response = MHD_create_response_from_buffer(
webpage.length(), (void *)webpage.c_str(), MHD_RESPMEM_PERSISTENT);
MHD_Result ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
MHD_destroy_response(response);
if (cls || url || method || version || upload_data || upload_data_size ||
con_cls) {} // make compiler happy
return ret;
}
class out_to_http_setting : public conky::simple_config_setting<bool> {
typedef conky::simple_config_setting<bool> Base;
protected:
virtual void lua_setter(lua::state &l, bool init) {
lua::stack_sentry s(l, -2);
Base::lua_setter(l, init);
if (init && do_convert(l, -1).first) {
/* warn about old default port */
if (http_port.get(*state) == 10080) {
NORM_ERR(
"warning: port 10080 is blocked by browsers "
"like Firefox and Chromium, you may want to change http_port.");
}
httpd =
MHD_start_daemon(MHD_USE_SELECT_INTERNALLY, http_port.get(*state),
nullptr, NULL, &sendanswer, nullptr, MHD_OPTION_END);
}
++s;
}
virtual void cleanup(lua::state &l) {
lua::stack_sentry s(l, -1);
if (do_convert(l, -1).first) {
MHD_stop_daemon(httpd);
httpd = nullptr;
}
l.pop();
}
public:
out_to_http_setting() : Base("out_to_http", false, false) {}
};
static out_to_http_setting out_to_http;
std::string string_replace_all(std::string original, const std::string &oldpart,
const std::string &newpart,
std::string::size_type start) {
std::string::size_type i = start;
int oldpartlen = oldpart.length();
while (1) {
i = original.find(oldpart, i);
if (i == std::string::npos) { break; }
original.replace(i, oldpartlen, newpart);
}
return original;
}
//} // namespace priv
display_output_http::display_output_http() : display_output_base("http") {
priority = 0;
httpd = NULL;
}
bool display_output_http::detect() {
if (/*priv::*/ out_to_http.get(*state)) {
DBGP2("Display output '%s' enabled in config.", name.c_str());
return true;
}
return false;
}
bool display_output_http::initialize() {
if (/*priv::*/ out_to_http.get(*state)) {
is_active = true;
return true;
}
return false;
}
bool display_output_http::shutdown() { return true; }
void display_output_http::begin_draw_text() {
#define WEBPAGE_START1 \
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" " \
"\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html " \
"xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta " \
"http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />"
#define WEBPAGE_START2 \
"<title>Conky</title></head><body style=\"font-family: monospace\"><p>"
#define WEBPAGE_END "</p></body></html>"
if (out_to_http.get(*state)) {
webpage = WEBPAGE_START1;
if (http_refresh.get(*state)) {
webpage.append("<meta http-equiv=\"refresh\" content=\"");
std::stringstream update_interval_str;
update_interval_str << update_interval.get(*state);
webpage.append(update_interval_str.str());
webpage.append("\" />");
}
webpage.append(WEBPAGE_START2);
}
}
void display_output_http::end_draw_text() { webpage.append(WEBPAGE_END); }
void display_output_http::draw_string(const char *s, int) {
std::string::size_type origlen = webpage.length();
webpage.append(s);
webpage = string_replace_all(webpage, "\n", "<br />", origlen);
webpage = string_replace_all(webpage, " ", " ", origlen);
webpage = string_replace_all(webpage, " ", " ", origlen);
webpage.append("<br />");
}
} // namespace conky
| 5,840
|
C++
|
.cc
| 158
| 32.158228
| 80
| 0.646684
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,553
|
libmpdclient.cc
|
brndnmtthws_conky/src/libmpdclient.cc
|
/*
*
* libmpdclient
* (c)2003-2006 by Warren Dukes (warren.dukes@gmail.com)
* This project's homepage is: http://www.musicpd.org
*
* 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 the Music Player Daemon 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 FOUNDATION 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.
*
*/
#include "libmpdclient.h"
#include "conky.h"
#include <fcntl.h>
#include <sys/param.h>
#include <sys/types.h>
#include <unistd.h>
#include <cctype>
#include <cerrno>
#include <climits>
#ifdef WIN32
#include <winsock.h>
#include <ws2tcpip.h>
#else
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/un.h>
#endif
#ifndef SUN_LEN
#define SUN_LEN(a) sizeof(a)
#endif
#ifndef SOCK_CLOEXEC
#define SOCK_CLOEXEC O_CLOEXEC
#endif /* SOCK_CLOEXEC */
/* (bits + 1) / 3 (plus the sign character) */
#define INTLEN ((sizeof(int) * CHAR_BIT + 1) / 3 + 1)
#define LONGLONGLEN ((sizeof(long long) * CHAR_BIT + 1) / 3 + 1)
#define COMMAND_LIST 1
#define COMMAND_LIST_OK 2
#ifndef MPD_NO_GAI
#ifdef AI_ADDRCONFIG
#define MPD_HAVE_GAI
#endif
#endif
#ifndef MSG_DONTWAIT
#define MSG_DONTWAIT 0
#endif
#ifdef WIN32
#define SELECT_ERRNO_IGNORE (errno == WSAEINTR || errno == WSAEINPROGRESS)
#define SENDRECV_ERRNO_IGNORE SELECT_ERRNO_IGNORE
#else
#define SELECT_ERRNO_IGNORE (errno == EINTR)
#define SENDRECV_ERRNO_IGNORE (errno == EINTR || errno == EAGAIN)
#define winsock_dll_error(c) 0
#define closesocket(s) close(s)
#define WSACleanup() \
do { /* nothing */ \
} while (0)
#endif
#ifdef WIN32
static int winsock_dll_error(mpd_Connection *connection) {
WSADATA wsaData;
if ((WSAStartup(MAKEWORD(2, 2), &wsaData)) != 0 ||
LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) {
strncpy(connection->errorStr, "Could not find usable WinSock DLL.",
MPD_ERRORSTR_MAX_LENGTH);
connection->error = MPD_ERROR_SYSTEM;
return 1;
}
return 0;
}
static int do_connect_fail(mpd_Connection *connection,
const struct sockaddr *serv_addr, int addrlen) {
int iMode = 1; /* 0 = blocking, else non-blocking */
ioctlsocket(connection->sock, FIONBIO, (u_long FAR *)&iMode);
return (connect(connection->sock, serv_addr, addrlen) == SOCKET_ERROR &&
WSAGetLastError() != WSAEWOULDBLOCK);
}
#else /* !WIN32 (sane operating systems) */
static int do_connect_fail(mpd_Connection *connection,
const struct sockaddr *serv_addr, int addrlen) {
int flags = fcntl(connection->sock, F_GETFL, 0);
fcntl(connection->sock, F_SETFL, flags | O_NONBLOCK);
return static_cast<int>(connect(connection->sock, serv_addr, addrlen) < 0 &&
errno != EINPROGRESS);
}
#endif /* !WIN32 */
static int uds_connect(mpd_Connection *connection, const char *host,
float timeout) {
struct sockaddr_un addr {};
strncpy(addr.sun_path, host, sizeof(addr.sun_path) - 1);
addr.sun_family = AF_UNIX;
addr.sun_path[sizeof(addr.sun_path) - 1] = 0;
connection->sock = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
if (connection->sock < 0) {
snprintf(connection->errorStr, MPD_ERRORSTR_MAX_LENGTH,
"problems creating socket: %s", strerror(errno));
connection->error = MPD_ERROR_SYSTEM;
return -1;
}
mpd_setConnectionTimeout(connection, timeout);
/* connect stuff */
if (do_connect_fail(connection, reinterpret_cast<struct sockaddr *>(&addr),
SUN_LEN(&addr)) != 0) {
snprintf(connection->errorStr, MPD_ERRORSTR_MAX_LENGTH,
"problems connecting socket: %s", strerror(errno));
closesocket(connection->sock);
connection->sock = -1;
connection->error = MPD_ERROR_SYSTEM;
return -1;
}
return 0;
}
#ifdef MPD_HAVE_GAI
static int mpd_connect(mpd_Connection *connection, const char *host, int port,
float timeout) {
int error;
char service[INTLEN + 1];
struct addrinfo hints {};
struct addrinfo *res = nullptr;
struct addrinfo *addrinfo = nullptr;
if (*host == '/') { return uds_connect(connection, host, timeout); }
/* Setup hints */
hints.ai_flags = AI_ADDRCONFIG;
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_addrlen = 0;
hints.ai_addr = nullptr;
hints.ai_canonname = nullptr;
hints.ai_next = nullptr;
snprintf(service, sizeof(service), "%i", port);
error = getaddrinfo(host, service, &hints, &addrinfo);
if (error != 0) {
snprintf(connection->errorStr, MPD_ERRORSTR_MAX_LENGTH,
"host \"%s\" not found: %s", host, gai_strerror(error));
connection->error = MPD_ERROR_UNKHOST;
return -1;
}
for (res = addrinfo; res != nullptr; res = res->ai_next) {
/* create socket */
if (connection->sock > -1) { closesocket(connection->sock); }
connection->sock =
socket(res->ai_family, SOCK_STREAM | SOCK_CLOEXEC, res->ai_protocol);
if (connection->sock < 0) {
snprintf(connection->errorStr, MPD_ERRORSTR_MAX_LENGTH,
"problems creating socket: %s", strerror(errno));
connection->error = MPD_ERROR_SYSTEM;
freeaddrinfo(addrinfo);
return -1;
}
mpd_setConnectionTimeout(connection, timeout);
/* connect stuff */
if (do_connect_fail(connection, res->ai_addr, res->ai_addrlen) != 0) {
/* try the next address family */
closesocket(connection->sock);
connection->sock = -1;
continue;
}
}
freeaddrinfo(addrinfo);
if (connection->sock < 0) {
snprintf(connection->errorStr, MPD_ERRORSTR_MAX_LENGTH,
"problems connecting to \"%s\" on port %i: %s", host, port,
strerror(errno));
connection->error = MPD_ERROR_CONNPORT;
return -1;
}
return 0;
}
#else /* !MPD_HAVE_GAI */
static int mpd_connect(mpd_Connection *connection, const char *host, int port,
float timeout) {
struct hostent he, *he_res = 0;
int he_errno;
char hostbuff[2048];
struct sockaddr *dest;
int destlen;
struct sockaddr_in sin;
if (*host == '/') return uds_connect(connection, host, timeout);
#ifdef HAVE_GETHOSTBYNAME_R
if (gethostbyname_r(host, &he, hostbuff, sizeof(hostbuff), &he_res,
&he_errno)) { // get the host info
snprintf(connection->errorStr, MPD_ERRORSTR_MAX_LENGTH, "%s ('%s')",
hstrerror(h_errno), host);
connection->error = MPD_ERROR_UNKHOST;
return -1;
}
#else /* HAVE_GETHOSTBYNAME_R */
if (!(he_res = gethostbyname(host))) {
snprintf(connection->errorStr, MPD_ERRORSTR_MAX_LENGTH,
"host \"%s\" not found", host);
connection->error = MPD_ERROR_UNKHOST;
return -1;
}
#endif /* HAVE_GETHOSTBYNAME_R */
memset(&sin, 0, sizeof(struct sockaddr_in));
/* dest.sin_family = he_res->h_addrtype; */
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
switch (he_res->h_addrtype) {
case AF_INET:
memcpy((char *)&sin.sin_addr.s_addr, (char *)he_res->h_addr,
he_res->h_length);
dest = (struct sockaddr *)&sin;
destlen = sizeof(struct sockaddr_in);
break;
default:
strncpy(connection->errorStr, "address type is not IPv4",
MPD_ERRORSTR_MAX_LENGTH);
connection->error = MPD_ERROR_SYSTEM;
return -1;
break;
}
if (connection->sock > -1) { closesocket(connection->sock); }
if ((connection->sock = socket(dest->sa_family, SOCK_STREAM, 0)) < 0) {
strncpy(connection->errorStr, "problems creating socket",
MPD_ERRORSTR_MAX_LENGTH);
connection->error = MPD_ERROR_SYSTEM;
return -1;
}
mpd_setConnectionTimeout(connection, timeout);
/* connect stuff */
if (do_connect_fail(connection, dest, destlen)) {
snprintf(connection->errorStr, MPD_ERRORSTR_MAX_LENGTH,
"problems connecting to \"%s\" on port %i", host, port);
connection->error = MPD_ERROR_CONNPORT;
return -1;
}
return 0;
}
#endif /* !MPD_HAVE_GAI */
const char *mpdTagItemKeys[MPD_TAG_NUM_OF_ITEM_TYPES] = {
"Artist", "Album", "Title", "Track", "Name", "Genre", "Date",
"Composer", "Performer", "Comment", "Disc", "Filename", "Any"};
static char *mpd_sanitizeArg(const char *arg) {
size_t i;
char *ret;
const char *c;
char *rc;
/* instead of counting in that loop above,
* just use a bit more memory and halve running time */
ret = static_cast<char *>(malloc(strlen(arg) * 2 + 1));
c = arg;
rc = ret;
for (i = strlen(arg) + 1; i != 0; --i) {
if (*c == '"' || *c == '\\') { *rc++ = '\\'; }
*(rc++) = *(c++);
}
return ret;
}
static mpd_ReturnElement *mpd_newReturnElement(const char *name,
const char *value) {
auto *ret =
static_cast<mpd_ReturnElement *>(malloc(sizeof(mpd_ReturnElement)));
ret->name = strndup(name, text_buffer_size.get(*state));
ret->value = strndup(value, text_buffer_size.get(*state));
return ret;
}
static void mpd_freeReturnElement(mpd_ReturnElement *re) {
free(re->name);
free(re->value);
free(re);
}
void mpd_setConnectionTimeout(mpd_Connection *connection, float timeout) {
connection->timeout.tv_sec = static_cast<int>(timeout);
connection->timeout.tv_usec =
static_cast<int>((timeout - connection->timeout.tv_sec) * 1e6 + 0.5);
}
static int mpd_parseWelcome(mpd_Connection *connection, const char *host,
int port, /* char *rt, */ char *output) {
char *tmp;
char *test;
int i;
if (static_cast<int>(strncmp(output, MPD_WELCOME_MESSAGE,
strlen(MPD_WELCOME_MESSAGE)) != 0) != 0) {
snprintf(connection->errorStr, MPD_ERRORSTR_MAX_LENGTH,
"mpd not running on port %i on host \"%s\"", port, host);
connection->error = MPD_ERROR_NOTMPD;
return 1;
}
tmp = &output[strlen(MPD_WELCOME_MESSAGE)];
for (i = 0; i < 3; i++) {
if (tmp != nullptr) { connection->version[i] = strtol(tmp, &test, 10); }
if ((tmp == nullptr) || (test[0] != '.' && test[0] != '\0')) {
snprintf(connection->errorStr, MPD_ERRORSTR_MAX_LENGTH,
"error parsing version number at \"%s\"",
&output[strlen(MPD_WELCOME_MESSAGE)]);
connection->error = MPD_ERROR_NOTMPD;
return 1;
}
tmp = ++test;
}
return 0;
}
mpd_Connection *mpd_newConnection(const char *host, int port, float timeout) {
int err;
char *rt;
char *output = nullptr;
auto *connection =
static_cast<mpd_Connection *>(malloc(sizeof(mpd_Connection)));
struct timeval tv {};
fd_set fds;
strncpy(connection->buffer, "", 1);
connection->buflen = 0;
connection->bufstart = 0;
strncpy(connection->errorStr, "", MPD_ERRORSTR_MAX_LENGTH);
connection->error = 0;
connection->doneProcessing = 0;
connection->commandList = 0;
connection->listOks = 0;
connection->doneListOk = 0;
connection->sock = -1;
connection->returnElement = nullptr;
connection->request = nullptr;
if (winsock_dll_error(connection)) { return connection; }
if (mpd_connect(connection, host, port, timeout) < 0) { return connection; }
while ((rt = strstr(connection->buffer, "\n")) == nullptr) {
tv.tv_sec = connection->timeout.tv_sec;
tv.tv_usec = connection->timeout.tv_usec;
FD_ZERO(&fds);
FD_SET(connection->sock, &fds);
if ((err = select(connection->sock + 1, &fds, nullptr, nullptr, &tv)) ==
1) {
int readed;
readed = recv(connection->sock, &(connection->buffer[connection->buflen]),
MPD_BUFFER_MAX_LENGTH - connection->buflen, 0);
if (readed <= 0) {
snprintf(connection->errorStr, MPD_ERRORSTR_MAX_LENGTH,
"problems getting a response from \"%s\" on port %i : %s",
host, port, strerror(errno));
connection->error = MPD_ERROR_NORESPONSE;
return connection;
}
connection->buflen += readed;
connection->buffer[connection->buflen] = '\0';
} else if (err < 0) {
if SELECT_ERRNO_IGNORE { continue; }
snprintf(connection->errorStr, MPD_ERRORSTR_MAX_LENGTH,
"problems connecting to \"%s\" on port %i", host, port);
connection->error = MPD_ERROR_CONNPORT;
return connection;
} else {
snprintf(connection->errorStr, MPD_ERRORSTR_MAX_LENGTH,
"timeout in attempting to get a response from \"%s\" on "
"port %i",
host, port);
connection->error = MPD_ERROR_NORESPONSE;
return connection;
}
}
*rt = '\0';
output = strndup(connection->buffer, text_buffer_size.get(*state));
strncpy(connection->buffer, rt + 1, MPD_BUFFER_MAX_LENGTH);
connection->buflen = strlen(connection->buffer);
if (mpd_parseWelcome(connection, host, port, /* rt, */ output) == 0) {
connection->doneProcessing = 1;
}
free(output);
return connection;
}
void mpd_clearError(mpd_Connection *connection) {
connection->error = 0;
connection->errorStr[0] = '\0';
}
void mpd_closeConnection(mpd_Connection *connection) {
if (connection != nullptr) {
closesocket(connection->sock);
free_and_zero(connection->returnElement);
free_and_zero(connection->request);
free(connection);
}
WSACleanup();
}
static void mpd_executeCommand(mpd_Connection *connection,
const char *command) {
int ret;
struct timeval tv {};
fd_set fds;
const char *commandPtr = command;
int commandLen = strlen(command);
if ((connection->doneProcessing == 0) && (connection->commandList == 0)) {
strncpy(connection->errorStr, "not done processing current command",
MPD_ERRORSTR_MAX_LENGTH);
connection->error = 1;
return;
}
mpd_clearError(connection);
FD_ZERO(&fds);
FD_SET(connection->sock, &fds);
tv.tv_sec = connection->timeout.tv_sec;
tv.tv_usec = connection->timeout.tv_usec;
do {
ret = static_cast<int>(
select(connection->sock + 1, nullptr, &fds, nullptr, &tv));
if (ret != 1 && !SELECT_ERRNO_IGNORE) { break; }
ret = send(connection->sock, commandPtr, commandLen, MSG_DONTWAIT);
if (ret <= 0) {
if SENDRECV_ERRNO_IGNORE { continue; }
snprintf(connection->errorStr, MPD_ERRORSTR_MAX_LENGTH,
"problems giving command \"%s\"", command);
connection->error = MPD_ERROR_SENDING;
return;
}
commandPtr += ret;
commandLen -= ret;
} while (commandLen > 0);
if (commandLen > 0) {
perror("");
snprintf(connection->errorStr, MPD_ERRORSTR_MAX_LENGTH,
"timeout sending command \"%s\"", command);
connection->error = MPD_ERROR_TIMEOUT;
return;
}
if (connection->commandList == 0) {
connection->doneProcessing = 0;
} else if (connection->commandList == COMMAND_LIST_OK) {
connection->listOks++;
}
}
static void mpd_getNextReturnElement(mpd_Connection *connection) {
char *output = nullptr;
char *rt = nullptr;
char *name = nullptr;
char *value = nullptr;
fd_set fds;
struct timeval tv {};
char *tok = nullptr;
int readed;
char *bufferCheck = nullptr;
int err;
int pos;
if (connection->returnElement != nullptr) {
mpd_freeReturnElement(connection->returnElement);
}
connection->returnElement = nullptr;
if ((connection->doneProcessing != 0) ||
((connection->listOks != 0) && (connection->doneListOk != 0))) {
strncpy(connection->errorStr, "already done processing current command",
MPD_ERRORSTR_MAX_LENGTH);
connection->error = 1;
return;
}
bufferCheck = connection->buffer + connection->bufstart;
while (connection->bufstart >= connection->buflen ||
((rt = strchr(bufferCheck, '\n')) == nullptr)) {
if (connection->buflen >= MPD_BUFFER_MAX_LENGTH) {
memmove(connection->buffer, connection->buffer + connection->bufstart,
connection->buflen - connection->bufstart + 1);
connection->buflen -= connection->bufstart;
connection->bufstart = 0;
}
if (connection->buflen >= MPD_BUFFER_MAX_LENGTH) {
strncpy(connection->errorStr, "buffer overrun", MPD_ERRORSTR_MAX_LENGTH);
connection->error = MPD_ERROR_BUFFEROVERRUN;
connection->doneProcessing = 1;
connection->doneListOk = 0;
return;
}
bufferCheck = connection->buffer + connection->buflen;
tv.tv_sec = connection->timeout.tv_sec;
tv.tv_usec = connection->timeout.tv_usec;
FD_ZERO(&fds);
FD_SET(connection->sock, &fds);
if ((err = static_cast<int>(select(connection->sock + 1, &fds, nullptr,
nullptr, &tv) == 1)) != 0) {
readed = recv(connection->sock, connection->buffer + connection->buflen,
MPD_BUFFER_MAX_LENGTH - connection->buflen, MSG_DONTWAIT);
if (readed < 0 && SENDRECV_ERRNO_IGNORE) { continue; }
if (readed <= 0) {
strncpy(connection->errorStr, "connection closed",
MPD_ERRORSTR_MAX_LENGTH);
connection->error = MPD_ERROR_CONNCLOSED;
connection->doneProcessing = 1;
connection->doneListOk = 0;
return;
}
connection->buflen += readed;
connection->buffer[connection->buflen] = '\0';
} else {
strncpy(connection->errorStr, "connection timeout",
MPD_ERRORSTR_MAX_LENGTH);
connection->error = MPD_ERROR_TIMEOUT;
connection->doneProcessing = 1;
connection->doneListOk = 0;
return;
}
}
*rt = '\0';
output = connection->buffer + connection->bufstart;
connection->bufstart = rt - connection->buffer + 1;
if (strcmp(output, "OK") == 0) {
if (connection->listOks > 0) {
strncpy(connection->errorStr, "expected more list_OK's",
MPD_ERRORSTR_MAX_LENGTH);
connection->error = 1;
}
connection->listOks = 0;
connection->doneProcessing = 1;
connection->doneListOk = 0;
return;
}
if (strcmp(output, "list_OK") == 0) {
if (connection->listOks == 0) {
strncpy(connection->errorStr, "got an unexpected list_OK",
MPD_ERRORSTR_MAX_LENGTH);
connection->error = 1;
} else {
connection->doneListOk = 1;
connection->listOks--;
}
return;
}
if (strncmp(output, "ACK", strlen("ACK")) == 0) {
char *test;
char *needle;
int val;
strncpy(connection->errorStr, output, MPD_ERRORSTR_MAX_LENGTH);
connection->error = MPD_ERROR_ACK;
connection->errorCode = MPD_ACK_ERROR_UNK;
connection->errorAt = MPD_ERROR_AT_UNK;
connection->doneProcessing = 1;
connection->doneListOk = 0;
needle = strchr(output, '[');
if (needle == nullptr) { return; }
val = strtol(needle + 1, &test, 10);
if (*test != '@') { return; }
connection->errorCode = val;
val = strtol(test + 1, &test, 10);
if (*test != ']') { return; }
connection->errorAt = val;
return;
}
tok = strchr(output, ':');
if (tok == nullptr) { return; }
pos = tok - output;
value = ++tok;
name = output;
name[pos] = '\0';
if (value[0] == ' ') {
connection->returnElement = mpd_newReturnElement(name, &(value[1]));
} else {
snprintf(connection->errorStr, MPD_ERRORSTR_MAX_LENGTH,
"error parsing: %s:%s", name, value);
connection->error = 1;
}
}
void mpd_finishCommand(mpd_Connection *connection) {
while ((connection != nullptr) && (connection->doneProcessing == 0)) {
if (connection->doneListOk != 0) { connection->doneListOk = 0; }
mpd_getNextReturnElement(connection);
}
}
static void mpd_finishListOkCommand(mpd_Connection *connection) {
while ((connection->doneProcessing == 0) && (connection->listOks != 0) &&
(connection->doneListOk == 0)) {
mpd_getNextReturnElement(connection);
}
}
int mpd_nextListOkCommand(mpd_Connection *connection) {
mpd_finishListOkCommand(connection);
if (connection->doneProcessing == 0) { connection->doneListOk = 0; }
if (connection->listOks == 0 || (connection->doneProcessing != 0)) {
return -1;
}
return 0;
}
void mpd_sendStatusCommand(mpd_Connection *connection) {
mpd_executeCommand(connection, "status\n");
}
mpd_Status *mpd_getStatus(mpd_Connection *connection) {
mpd_Status *status;
/* mpd_executeCommand(connection, "status\n");
if (connection->error) {
return nullptr;
} */
if ((connection->doneProcessing != 0) ||
((connection->listOks != 0) && (connection->doneListOk != 0))) {
return nullptr;
}
if (connection->returnElement == nullptr) {
mpd_getNextReturnElement(connection);
}
status = static_cast<mpd_Status *>(malloc(sizeof(mpd_Status)));
status->volume = -1;
status->repeat = 0;
status->random = 0;
status->playlist = -1;
status->playlistLength = -1;
status->state = -1;
status->song = 0;
status->songid = 0;
status->elapsedTime = 0;
status->totalTime = 0;
status->bitRate = 0;
status->sampleRate = 0;
status->bits = 0;
status->channels = 0;
status->crossfade = -1;
status->error = nullptr;
status->updatingDb = 0;
if (connection->error != 0) {
free(status);
return nullptr;
}
while (connection->returnElement != nullptr) {
mpd_ReturnElement *re = connection->returnElement;
if (strcmp(re->name, "volume") == 0) {
status->volume = strtol(re->value, nullptr, 10);
} else if (strcmp(re->name, "repeat") == 0) {
status->repeat = strtol(re->value, nullptr, 10);
} else if (strcmp(re->name, "random") == 0) {
status->random = strtol(re->value, nullptr, 10);
} else if (strcmp(re->name, "playlist") == 0) {
status->playlist = strtol(re->value, nullptr, 10);
} else if (strcmp(re->name, "playlistlength") == 0) {
status->playlistLength = strtol(re->value, nullptr, 10);
} else if (strcmp(re->name, "bitrate") == 0) {
status->bitRate = strtol(re->value, nullptr, 10);
} else if (strcmp(re->name, "state") == 0) {
if (strcmp(re->value, "play") == 0) {
status->state = MPD_STATUS_STATE_PLAY;
} else if (strcmp(re->value, "stop") == 0) {
status->state = MPD_STATUS_STATE_STOP;
} else if (strcmp(re->value, "pause") == 0) {
status->state = MPD_STATUS_STATE_PAUSE;
} else {
status->state = MPD_STATUS_STATE_UNKNOWN;
}
} else if (strcmp(re->name, "song") == 0) {
status->song = strtol(re->value, nullptr, 10);
} else if (strcmp(re->name, "songid") == 0) {
status->songid = strtol(re->value, nullptr, 10);
} else if (strcmp(re->name, "time") == 0) {
char *tok = strchr(re->value, ':');
/* the second strchr below is a safety check */
if ((tok != nullptr) && (strchr(tok, 0) > (tok + 1))) {
/* strtol stops at the first non-[0-9] char: */
status->elapsedTime = strtol(re->value, nullptr, 10);
status->totalTime = strtol(tok + 1, nullptr, 10);
}
} else if (strcmp(re->name, "error") == 0) {
status->error = strndup(re->value, text_buffer_size.get(*state));
} else if (strcmp(re->name, "xfade") == 0) {
status->crossfade = strtol(re->value, nullptr, 10);
} else if (strcmp(re->name, "updating_db") == 0) {
status->updatingDb = strtol(re->value, nullptr, 10);
} else if (strcmp(re->name, "audio") == 0) {
char *tok = strchr(re->value, ':');
if ((tok != nullptr) && (strchr(tok, 0) > (tok + 1))) {
status->sampleRate = strtol(re->value, nullptr, 10);
status->bits = strtol(++tok, nullptr, 10);
tok = strchr(tok, ':');
if ((tok != nullptr) && (strchr(tok, 0) > (tok + 1))) {
status->channels = strtol(tok + 1, nullptr, 10);
}
}
}
mpd_getNextReturnElement(connection);
if (connection->error != 0) {
free(status);
return nullptr;
}
}
if (connection->error != 0) {
free(status);
return nullptr;
}
if (status->state < 0) {
strncpy(connection->errorStr, "state not found", MPD_ERRORSTR_MAX_LENGTH);
connection->error = 1;
free(status);
return nullptr;
}
return status;
}
void mpd_freeStatus(mpd_Status *status) {
free_and_zero(status->error);
free(status);
}
void mpd_sendStatsCommand(mpd_Connection *connection) {
mpd_executeCommand(connection, "stats\n");
}
mpd_Stats *mpd_getStats(mpd_Connection *connection) {
mpd_Stats *stats;
/* mpd_executeCommand(connection, "stats\n");
if (connection->error) {
return nullptr;
} */
if ((connection->doneProcessing != 0) ||
((connection->listOks != 0) && (connection->doneListOk != 0))) {
return nullptr;
}
if (connection->returnElement == nullptr) {
mpd_getNextReturnElement(connection);
}
stats = static_cast<mpd_Stats *>(malloc(sizeof(mpd_Stats)));
stats->numberOfArtists = 0;
stats->numberOfAlbums = 0;
stats->numberOfSongs = 0;
stats->uptime = 0;
stats->dbUpdateTime = 0;
stats->playTime = 0;
stats->dbPlayTime = 0;
if (connection->error != 0) {
free(stats);
return nullptr;
}
while (connection->returnElement != nullptr) {
mpd_ReturnElement *re = connection->returnElement;
if (strcmp(re->name, "artists") == 0) {
stats->numberOfArtists = strtol(re->value, nullptr, 10);
} else if (strcmp(re->name, "albums") == 0) {
stats->numberOfAlbums = strtol(re->value, nullptr, 10);
} else if (strcmp(re->name, "songs") == 0) {
stats->numberOfSongs = strtol(re->value, nullptr, 10);
} else if (strcmp(re->name, "uptime") == 0) {
stats->uptime = strtol(re->value, nullptr, 10);
} else if (strcmp(re->name, "db_update") == 0) {
stats->dbUpdateTime = strtol(re->value, nullptr, 10);
} else if (strcmp(re->name, "playtime") == 0) {
stats->playTime = strtol(re->value, nullptr, 10);
} else if (strcmp(re->name, "db_playtime") == 0) {
stats->dbPlayTime = strtol(re->value, nullptr, 10);
}
mpd_getNextReturnElement(connection);
if (connection->error != 0) {
free(stats);
return nullptr;
}
}
if (connection->error != 0) {
free(stats);
return nullptr;
}
return stats;
}
void mpd_freeStats(mpd_Stats *stats) { free(stats); }
mpd_SearchStats *mpd_getSearchStats(mpd_Connection *connection) {
mpd_SearchStats *stats;
mpd_ReturnElement *re;
if ((connection->doneProcessing != 0) ||
((connection->listOks != 0) && (connection->doneListOk != 0))) {
return nullptr;
}
if (connection->returnElement == nullptr) {
mpd_getNextReturnElement(connection);
}
if (connection->error != 0) { return nullptr; }
stats = static_cast<mpd_SearchStats *>(malloc(sizeof(mpd_SearchStats)));
stats->numberOfSongs = 0;
stats->playTime = 0;
while (connection->returnElement != nullptr) {
re = connection->returnElement;
if (strcmp(re->name, "songs") == 0) {
stats->numberOfSongs = strtol(re->value, nullptr, 10);
} else if (strcmp(re->name, "playtime") == 0) {
stats->playTime = strtol(re->value, nullptr, 10);
}
mpd_getNextReturnElement(connection);
if (connection->error != 0) {
free(stats);
return nullptr;
}
}
if (connection->error != 0) {
free(stats);
return nullptr;
}
return stats;
}
void mpd_freeSearchStats(mpd_SearchStats *stats) { free(stats); }
static void mpd_initSong(mpd_Song *song) {
song->file = nullptr;
song->artist = nullptr;
song->albumartist = nullptr;
song->album = nullptr;
song->track = nullptr;
song->title = nullptr;
song->name = nullptr;
song->date = nullptr;
/* added by Qball */
song->genre = nullptr;
song->composer = nullptr;
song->performer = nullptr;
song->disc = nullptr;
song->comment = nullptr;
song->time = MPD_SONG_NO_TIME;
song->pos = MPD_SONG_NO_NUM;
song->id = MPD_SONG_NO_ID;
}
static void mpd_finishSong(mpd_Song *song) {
free_and_zero(song->file);
free_and_zero(song->artist);
free_and_zero(song->albumartist);
free_and_zero(song->album);
free_and_zero(song->title);
free_and_zero(song->track);
free_and_zero(song->name);
free_and_zero(song->date);
free_and_zero(song->genre);
free_and_zero(song->composer);
free_and_zero(song->disc);
free_and_zero(song->comment);
}
mpd_Song *mpd_newSong() {
auto *ret = static_cast<mpd_Song *>(malloc(sizeof(mpd_Song)));
mpd_initSong(ret);
return ret;
}
void mpd_freeSong(mpd_Song *song) {
mpd_finishSong(song);
free(song);
}
mpd_Song *mpd_songDup(mpd_Song *song) {
mpd_Song *ret = mpd_newSong();
if (song->file != nullptr) {
ret->file = strndup(song->file, text_buffer_size.get(*state));
}
if (song->artist != nullptr) {
ret->artist = strndup(song->artist, text_buffer_size.get(*state));
}
if (song->albumartist != nullptr) {
ret->artist = strndup(song->albumartist, text_buffer_size.get(*state));
}
if (song->album != nullptr) {
ret->album = strndup(song->album, text_buffer_size.get(*state));
}
if (song->title != nullptr) {
ret->title = strndup(song->title, text_buffer_size.get(*state));
}
if (song->track != nullptr) {
ret->track = strndup(song->track, text_buffer_size.get(*state));
}
if (song->name != nullptr) {
ret->name = strndup(song->name, text_buffer_size.get(*state));
}
if (song->date != nullptr) {
ret->date = strndup(song->date, text_buffer_size.get(*state));
}
if (song->genre != nullptr) {
ret->genre = strndup(song->genre, text_buffer_size.get(*state));
}
if (song->composer != nullptr) {
ret->composer = strndup(song->composer, text_buffer_size.get(*state));
}
if (song->disc != nullptr) {
ret->disc = strndup(song->disc, text_buffer_size.get(*state));
}
if (song->comment != nullptr) {
ret->comment = strndup(song->comment, text_buffer_size.get(*state));
}
ret->time = song->time;
ret->pos = song->pos;
ret->id = song->id;
return ret;
}
static void mpd_initDirectory(mpd_Directory *directory) {
directory->path = nullptr;
}
static void mpd_finishDirectory(mpd_Directory *directory) {
free_and_zero(directory->path);
}
mpd_Directory *mpd_newDirectory() {
auto *directory = static_cast<mpd_Directory *>(malloc(sizeof(mpd_Directory)));
mpd_initDirectory(directory);
return directory;
}
void mpd_freeDirectory(mpd_Directory *directory) {
mpd_finishDirectory(directory);
free(directory);
}
mpd_Directory *mpd_directoryDup(mpd_Directory *directory) {
mpd_Directory *ret = mpd_newDirectory();
if (directory->path != nullptr) {
ret->path = strndup(directory->path, text_buffer_size.get(*state));
}
return ret;
}
static void mpd_initPlaylistFile(mpd_PlaylistFile *playlist) {
playlist->path = nullptr;
}
static void mpd_finishPlaylistFile(mpd_PlaylistFile *playlist) {
free_and_zero(playlist->path);
}
mpd_PlaylistFile *mpd_newPlaylistFile() {
auto *playlist =
static_cast<mpd_PlaylistFile *>(malloc(sizeof(mpd_PlaylistFile)));
mpd_initPlaylistFile(playlist);
return playlist;
}
void mpd_freePlaylistFile(mpd_PlaylistFile *playlist) {
mpd_finishPlaylistFile(playlist);
free(playlist);
}
mpd_PlaylistFile *mpd_playlistFileDup(mpd_PlaylistFile *playlist) {
mpd_PlaylistFile *ret = mpd_newPlaylistFile();
if (playlist->path != nullptr) {
ret->path = strndup(playlist->path, text_buffer_size.get(*state));
}
return ret;
}
static void mpd_initInfoEntity(mpd_InfoEntity *entity) {
entity->info.directory = nullptr;
}
static void mpd_finishInfoEntity(mpd_InfoEntity *entity) {
if (entity->info.directory != nullptr) {
if (entity->type == MPD_INFO_ENTITY_TYPE_DIRECTORY) {
mpd_freeDirectory(entity->info.directory);
} else if (entity->type == MPD_INFO_ENTITY_TYPE_SONG) {
mpd_freeSong(entity->info.song);
} else if (entity->type == MPD_INFO_ENTITY_TYPE_PLAYLISTFILE) {
mpd_freePlaylistFile(entity->info.playlistFile);
}
}
}
mpd_InfoEntity *mpd_newInfoEntity() {
auto *entity = static_cast<mpd_InfoEntity *>(malloc(sizeof(mpd_InfoEntity)));
mpd_initInfoEntity(entity);
return entity;
}
void mpd_freeInfoEntity(mpd_InfoEntity *entity) {
mpd_finishInfoEntity(entity);
free(entity);
}
static void mpd_sendInfoCommand(mpd_Connection *connection, char *command) {
mpd_executeCommand(connection, command);
}
mpd_InfoEntity *mpd_getNextInfoEntity(mpd_Connection *connection) {
mpd_InfoEntity *entity = nullptr;
if ((connection->doneProcessing != 0) ||
((connection->listOks != 0) && (connection->doneListOk != 0))) {
return nullptr;
}
if (connection->returnElement == nullptr) {
mpd_getNextReturnElement(connection);
}
if (connection->returnElement != nullptr) {
if (strcmp(connection->returnElement->name, "file") == 0) {
entity = mpd_newInfoEntity();
entity->type = MPD_INFO_ENTITY_TYPE_SONG;
entity->info.song = mpd_newSong();
entity->info.song->file = strndup(connection->returnElement->value,
text_buffer_size.get(*state));
} else if (strcmp(connection->returnElement->name, "directory") == 0) {
entity = mpd_newInfoEntity();
entity->type = MPD_INFO_ENTITY_TYPE_DIRECTORY;
entity->info.directory = mpd_newDirectory();
entity->info.directory->path = strndup(connection->returnElement->value,
text_buffer_size.get(*state));
} else if (strcmp(connection->returnElement->name, "playlist") == 0) {
entity = mpd_newInfoEntity();
entity->type = MPD_INFO_ENTITY_TYPE_PLAYLISTFILE;
entity->info.playlistFile = mpd_newPlaylistFile();
entity->info.playlistFile->path = strndup(
connection->returnElement->value, text_buffer_size.get(*state));
} else if (strcmp(connection->returnElement->name, "cpos") == 0) {
entity = mpd_newInfoEntity();
entity->type = MPD_INFO_ENTITY_TYPE_SONG;
entity->info.song = mpd_newSong();
entity->info.song->pos =
strtol(connection->returnElement->value, nullptr, 10);
} else {
connection->error = 1;
strncpy(connection->errorStr, "problem parsing song info",
MPD_ERRORSTR_MAX_LENGTH);
return nullptr;
}
} else {
return nullptr;
}
mpd_getNextReturnElement(connection);
while (connection->returnElement != nullptr) {
mpd_ReturnElement *re = connection->returnElement;
if (strcmp(re->name, "file") == 0) { return entity; }
if (strcmp(re->name, "directory") == 0) { return entity; }
if (strcmp(re->name, "playlist") == 0) { return entity; }
if (strcmp(re->name, "cpos") == 0) { return entity; }
if (entity->type == MPD_INFO_ENTITY_TYPE_SONG &&
(strlen(re->value) != 0u)) {
if ((entity->info.song->artist == nullptr) &&
strcmp(re->name, "Artist") == 0) {
entity->info.song->artist =
strndup(re->value, text_buffer_size.get(*state));
} else if ((entity->info.song->albumartist == nullptr) &&
strcmp(re->name, "AlbumArtist") == 0) {
entity->info.song->albumartist =
strndup(re->value, text_buffer_size.get(*state));
} else if ((entity->info.song->album == nullptr) &&
strcmp(re->name, "Album") == 0) {
entity->info.song->album =
strndup(re->value, text_buffer_size.get(*state));
} else if ((entity->info.song->title == nullptr) &&
strcmp(re->name, "Title") == 0) {
entity->info.song->title =
strndup(re->value, text_buffer_size.get(*state));
} else if ((entity->info.song->track == nullptr) &&
strcmp(re->name, "Track") == 0) {
entity->info.song->track =
strndup(re->value, text_buffer_size.get(*state));
} else if ((entity->info.song->name == nullptr) &&
strcmp(re->name, "Name") == 0) {
entity->info.song->name =
strndup(re->value, text_buffer_size.get(*state));
} else if (entity->info.song->time == MPD_SONG_NO_TIME &&
strcmp(re->name, "Time") == 0) {
entity->info.song->time = strtol(re->value, nullptr, 10);
} else if (entity->info.song->pos == MPD_SONG_NO_NUM &&
strcmp(re->name, "Pos") == 0) {
entity->info.song->pos = strtol(re->value, nullptr, 10);
} else if (entity->info.song->id == MPD_SONG_NO_ID &&
strcmp(re->name, "Id") == 0) {
entity->info.song->id = strtol(re->value, nullptr, 10);
} else if ((entity->info.song->date == nullptr) &&
strcmp(re->name, "Date") == 0) {
entity->info.song->date =
strndup(re->value, text_buffer_size.get(*state));
} else if ((entity->info.song->genre == nullptr) &&
strcmp(re->name, "Genre") == 0) {
entity->info.song->genre =
strndup(re->value, text_buffer_size.get(*state));
} else if ((entity->info.song->composer == nullptr) &&
strcmp(re->name, "Composer") == 0) {
entity->info.song->composer =
strndup(re->value, text_buffer_size.get(*state));
} else if ((entity->info.song->performer == nullptr) &&
strcmp(re->name, "Performer") == 0) {
entity->info.song->performer =
strndup(re->value, text_buffer_size.get(*state));
} else if ((entity->info.song->disc == nullptr) &&
strcmp(re->name, "Disc") == 0) {
entity->info.song->disc =
strndup(re->value, text_buffer_size.get(*state));
} else if ((entity->info.song->comment == nullptr) &&
strcmp(re->name, "Comment") == 0) {
entity->info.song->comment =
strndup(re->value, text_buffer_size.get(*state));
}
} else if (entity->type == MPD_INFO_ENTITY_TYPE_DIRECTORY) {
} else if (entity->type == MPD_INFO_ENTITY_TYPE_PLAYLISTFILE) {
}
mpd_getNextReturnElement(connection);
}
return entity;
}
static char *mpd_getNextReturnElementNamed(mpd_Connection *connection,
const char *name) {
if ((connection->doneProcessing != 0) ||
((connection->listOks != 0) && (connection->doneListOk != 0))) {
return nullptr;
}
mpd_getNextReturnElement(connection);
while (connection->returnElement != nullptr) {
mpd_ReturnElement *re = connection->returnElement;
if (strcmp(re->name, name) == 0) {
return strndup(re->value, text_buffer_size.get(*state));
}
mpd_getNextReturnElement(connection);
}
return nullptr;
}
char *mpd_getNextTag(mpd_Connection *connection, int type) {
if (type < 0 || type >= MPD_TAG_NUM_OF_ITEM_TYPES ||
type == MPD_TAG_ITEM_ANY) {
return nullptr;
}
if (type == MPD_TAG_ITEM_FILENAME) {
return mpd_getNextReturnElementNamed(connection, "file");
}
return mpd_getNextReturnElementNamed(connection, mpdTagItemKeys[type]);
}
char *mpd_getNextArtist(mpd_Connection *connection) {
return mpd_getNextReturnElementNamed(connection, "Artist");
}
char *mpd_getNextAlbum(mpd_Connection *connection) {
return mpd_getNextReturnElementNamed(connection, "Album");
}
void mpd_sendPlaylistInfoCommand(mpd_Connection *connection, int songPos) {
int len = strlen("playlistinfo") + 2 + INTLEN + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "playlistinfo \"%i\"\n", songPos);
mpd_sendInfoCommand(connection, string);
free(string);
}
void mpd_sendPlaylistIdCommand(mpd_Connection *connection, int id) {
int len = strlen("playlistid") + 2 + INTLEN + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "playlistid \"%i\"\n", id);
mpd_sendInfoCommand(connection, string);
free(string);
}
void mpd_sendPlChangesCommand(mpd_Connection *connection, long long playlist) {
int len = strlen("plchanges") + 2 + LONGLONGLEN + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "plchanges \"%lld\"\n", playlist);
mpd_sendInfoCommand(connection, string);
free(string);
}
void mpd_sendPlChangesPosIdCommand(mpd_Connection *connection,
long long playlist) {
int len = strlen("plchangesposid") + 2 + LONGLONGLEN + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "plchangesposid \"%lld\"\n", playlist);
mpd_sendInfoCommand(connection, string);
free(string);
}
void mpd_sendListallCommand(mpd_Connection *connection, const char *dir) {
char *sDir = mpd_sanitizeArg(dir);
int len = strlen("listall") + 2 + strlen(sDir) + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "listall \"%s\"\n", sDir);
mpd_sendInfoCommand(connection, string);
free(string);
free(sDir);
}
void mpd_sendListallInfoCommand(mpd_Connection *connection, const char *dir) {
char *sDir = mpd_sanitizeArg(dir);
int len = strlen("listallinfo") + 2 + strlen(sDir) + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "listallinfo \"%s\"\n", sDir);
mpd_sendInfoCommand(connection, string);
free(string);
free(sDir);
}
void mpd_sendLsInfoCommand(mpd_Connection *connection, const char *dir) {
char *sDir = mpd_sanitizeArg(dir);
int len = strlen("lsinfo") + 2 + strlen(sDir) + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "lsinfo \"%s\"\n", sDir);
mpd_sendInfoCommand(connection, string);
free(string);
free(sDir);
}
void mpd_sendCurrentSongCommand(mpd_Connection *connection) {
mpd_executeCommand(connection, "currentsong\n");
}
void mpd_sendSearchCommand(mpd_Connection *connection, int table,
const char *str) {
mpd_startSearch(connection, 0);
mpd_addConstraintSearch(connection, table, str);
mpd_commitSearch(connection);
}
void mpd_sendFindCommand(mpd_Connection *connection, int table,
const char *str) {
mpd_startSearch(connection, 1);
mpd_addConstraintSearch(connection, table, str);
mpd_commitSearch(connection);
}
void mpd_sendListCommand(mpd_Connection *connection, int table,
const char *arg1) {
char st[7];
int len;
char *string;
if (table == MPD_TABLE_ARTIST) {
strncpy(st, "artist", strlen("artist") + 1);
} else if (table == MPD_TABLE_ALBUM) {
strncpy(st, "album", strlen("album") + 1);
} else {
connection->error = 1;
strncpy(connection->errorStr, "unknown table for list",
MPD_ERRORSTR_MAX_LENGTH);
return;
}
if (arg1 != nullptr) {
char *sanitArg1 = mpd_sanitizeArg(arg1);
len = strlen("list") + 1 + strlen(sanitArg1) + 2 + strlen(st) + 3;
string = static_cast<char *>(malloc(len));
snprintf(string, len, "list %s \"%s\"\n", st, sanitArg1);
free(sanitArg1);
} else {
len = strlen("list") + 1 + strlen(st) + 2;
string = static_cast<char *>(malloc(len));
snprintf(string, len, "list %s\n", st);
}
mpd_sendInfoCommand(connection, string);
free(string);
}
void mpd_sendAddCommand(mpd_Connection *connection, const char *file) {
char *sFile = mpd_sanitizeArg(file);
int len = strlen("add") + 2 + strlen(sFile) + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "add \"%s\"\n", sFile);
mpd_executeCommand(connection, string);
free(string);
free(sFile);
}
int mpd_sendAddIdCommand(mpd_Connection *connection, const char *file) {
int retval = -1;
char *sFile = mpd_sanitizeArg(file);
int len = strlen("addid") + 2 + strlen(sFile) + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "addid \"%s\"\n", sFile);
mpd_sendInfoCommand(connection, string);
free(string);
free(sFile);
string = mpd_getNextReturnElementNamed(connection, "Id");
if (string != nullptr) {
retval = strtol(string, nullptr, 10);
free(string);
}
return retval;
}
void mpd_sendDeleteCommand(mpd_Connection *connection, int songPos) {
int len = strlen("delete") + 2 + INTLEN + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "delete \"%i\"\n", songPos);
mpd_sendInfoCommand(connection, string);
free(string);
}
void mpd_sendDeleteIdCommand(mpd_Connection *connection, int id) {
int len = strlen("deleteid") + 2 + INTLEN + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "deleteid \"%i\"\n", id);
mpd_sendInfoCommand(connection, string);
free(string);
}
void mpd_sendSaveCommand(mpd_Connection *connection, const char *name) {
char *sName = mpd_sanitizeArg(name);
int len = strlen("save") + 2 + strlen(sName) + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "save \"%s\"\n", sName);
mpd_executeCommand(connection, string);
free(string);
free(sName);
}
void mpd_sendLoadCommand(mpd_Connection *connection, const char *name) {
char *sName = mpd_sanitizeArg(name);
int len = strlen("load") + 2 + strlen(sName) + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "load \"%s\"\n", sName);
mpd_executeCommand(connection, string);
free(string);
free(sName);
}
void mpd_sendRmCommand(mpd_Connection *connection, const char *name) {
char *sName = mpd_sanitizeArg(name);
int len = strlen("rm") + 2 + strlen(sName) + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "rm \"%s\"\n", sName);
mpd_executeCommand(connection, string);
free(string);
free(sName);
}
void mpd_sendRenameCommand(mpd_Connection *connection, const char *from,
const char *to) {
char *sFrom = mpd_sanitizeArg(from);
char *sTo = mpd_sanitizeArg(to);
int len = strlen("rename") + 2 + strlen(sFrom) + 3 + strlen(sTo) + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "rename \"%s\" \"%s\"\n", sFrom, sTo);
mpd_executeCommand(connection, string);
free(string);
free(sFrom);
free(sTo);
}
void mpd_sendShuffleCommand(mpd_Connection *connection) {
mpd_executeCommand(connection, "shuffle\n");
}
void mpd_sendClearCommand(mpd_Connection *connection) {
mpd_executeCommand(connection, "clear\n");
}
void mpd_sendPlayCommand(mpd_Connection *connection, int songPos) {
int len = strlen("play") + 2 + INTLEN + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "play \"%i\"\n", songPos);
mpd_sendInfoCommand(connection, string);
free(string);
}
void mpd_sendPlayIdCommand(mpd_Connection *connection, int id) {
int len = strlen("playid") + 2 + INTLEN + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "playid \"%i\"\n", id);
mpd_sendInfoCommand(connection, string);
free(string);
}
void mpd_sendStopCommand(mpd_Connection *connection) {
mpd_executeCommand(connection, "stop\n");
}
void mpd_sendPauseCommand(mpd_Connection *connection, int pauseMode) {
int len = strlen("pause") + 2 + INTLEN + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "pause \"%i\"\n", pauseMode);
mpd_executeCommand(connection, string);
free(string);
}
void mpd_sendNextCommand(mpd_Connection *connection) {
mpd_executeCommand(connection, "next\n");
}
void mpd_sendMoveCommand(mpd_Connection *connection, int from, int to) {
int len = strlen("move") + 2 + INTLEN + 3 + INTLEN + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "move \"%i\" \"%i\"\n", from, to);
mpd_sendInfoCommand(connection, string);
free(string);
}
void mpd_sendMoveIdCommand(mpd_Connection *connection, int id, int to) {
int len = strlen("moveid") + 2 + INTLEN + 3 + INTLEN + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "moveid \"%i\" \"%i\"\n", id, to);
mpd_sendInfoCommand(connection, string);
free(string);
}
void mpd_sendSwapCommand(mpd_Connection *connection, int song1, int song2) {
int len = strlen("swap") + 2 + INTLEN + 3 + INTLEN + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "swap \"%i\" \"%i\"\n", song1, song2);
mpd_sendInfoCommand(connection, string);
free(string);
}
void mpd_sendSwapIdCommand(mpd_Connection *connection, int id1, int id2) {
int len = strlen("swapid") + 2 + INTLEN + 3 + INTLEN + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "swapid \"%i\" \"%i\"\n", id1, id2);
mpd_sendInfoCommand(connection, string);
free(string);
}
void mpd_sendSeekCommand(mpd_Connection *connection, int song, int seek_time) {
int len = strlen("seek") + 2 + INTLEN + 3 + INTLEN + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "seek \"%i\" \"%i\"\n", song, seek_time);
mpd_sendInfoCommand(connection, string);
free(string);
}
void mpd_sendSeekIdCommand(mpd_Connection *connection, int id, int seek_time) {
int len = strlen("seekid") + 2 + INTLEN + 3 + INTLEN + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "seekid \"%i\" \"%i\"\n", id, seek_time);
mpd_sendInfoCommand(connection, string);
free(string);
}
void mpd_sendUpdateCommand(mpd_Connection *connection, char *path) {
char *sPath = mpd_sanitizeArg(path);
int len = strlen("update") + 2 + strlen(sPath) + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "update \"%s\"\n", sPath);
mpd_sendInfoCommand(connection, string);
free(string);
free(sPath);
}
int mpd_getUpdateId(mpd_Connection *connection) {
char *jobid;
int ret = 0;
jobid = mpd_getNextReturnElementNamed(connection, "updating_db");
if (jobid != nullptr) {
ret = strtol(jobid, nullptr, 10);
free(jobid);
}
return ret;
}
void mpd_sendPrevCommand(mpd_Connection *connection) {
mpd_executeCommand(connection, "previous\n");
}
void mpd_sendRepeatCommand(mpd_Connection *connection, int repeatMode) {
int len = strlen("repeat") + 2 + INTLEN + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "repeat \"%i\"\n", repeatMode);
mpd_executeCommand(connection, string);
free(string);
}
void mpd_sendRandomCommand(mpd_Connection *connection, int randomMode) {
int len = strlen("random") + 2 + INTLEN + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "random \"%i\"\n", randomMode);
mpd_executeCommand(connection, string);
free(string);
}
void mpd_sendSetvolCommand(mpd_Connection *connection, int volumeChange) {
int len = strlen("setvol") + 2 + INTLEN + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "setvol \"%i\"\n", volumeChange);
mpd_executeCommand(connection, string);
free(string);
}
void mpd_sendVolumeCommand(mpd_Connection *connection, int volumeChange) {
int len = strlen("volume") + 2 + INTLEN + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "volume \"%i\"\n", volumeChange);
mpd_executeCommand(connection, string);
free(string);
}
void mpd_sendCrossfadeCommand(mpd_Connection *connection, int seconds) {
int len = strlen("crossfade") + 2 + INTLEN + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "crossfade \"%i\"\n", seconds);
mpd_executeCommand(connection, string);
free(string);
}
void mpd_sendPasswordCommand(mpd_Connection *connection, const char *pass) {
char *sPass = mpd_sanitizeArg(pass);
int len = strlen("password") + 2 + strlen(sPass) + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "password \"%s\"\n", sPass);
mpd_executeCommand(connection, string);
free(string);
free(sPass);
}
void mpd_sendCommandListBegin(mpd_Connection *connection) {
if (connection->commandList != 0) {
strncpy(connection->errorStr, "already in command list mode",
MPD_ERRORSTR_MAX_LENGTH);
connection->error = 1;
return;
}
connection->commandList = COMMAND_LIST;
mpd_executeCommand(connection, "command_list_begin\n");
}
void mpd_sendCommandListOkBegin(mpd_Connection *connection) {
if (connection->commandList != 0) {
strncpy(connection->errorStr, "already in command list mode",
MPD_ERRORSTR_MAX_LENGTH);
connection->error = 1;
return;
}
connection->commandList = COMMAND_LIST_OK;
mpd_executeCommand(connection, "command_list_ok_begin\n");
connection->listOks = 0;
}
void mpd_sendCommandListEnd(mpd_Connection *connection) {
if (connection->commandList == 0) {
strncpy(connection->errorStr, "not in command list mode",
MPD_ERRORSTR_MAX_LENGTH);
connection->error = 1;
return;
}
connection->commandList = 0;
mpd_executeCommand(connection, "command_list_end\n");
}
void mpd_sendOutputsCommand(mpd_Connection *connection) {
mpd_executeCommand(connection, "outputs\n");
}
mpd_OutputEntity *mpd_getNextOutput(mpd_Connection *connection) {
mpd_OutputEntity *output = nullptr;
if ((connection->doneProcessing != 0) ||
((connection->listOks != 0) && (connection->doneListOk != 0))) {
return nullptr;
}
if (connection->error != 0) { return nullptr; }
output = static_cast<mpd_OutputEntity *>(malloc(sizeof(mpd_OutputEntity)));
output->id = -10;
output->name = nullptr;
output->enabled = 0;
if (connection->returnElement == nullptr) {
mpd_getNextReturnElement(connection);
}
while (connection->returnElement != nullptr) {
mpd_ReturnElement *re = connection->returnElement;
if (strcmp(re->name, "outputid") == 0) {
if (output != nullptr && output->id >= 0) { return output; }
output->id = strtol(re->value, nullptr, 10);
} else if (strcmp(re->name, "outputname") == 0) {
output->name = strndup(re->value, text_buffer_size.get(*state));
} else if (strcmp(re->name, "outputenabled") == 0) {
output->enabled = strtol(re->value, nullptr, 10);
}
mpd_getNextReturnElement(connection);
if (connection->error != 0) {
free(output);
return nullptr;
}
}
return output;
}
void mpd_sendEnableOutputCommand(mpd_Connection *connection, int outputId) {
int len = strlen("enableoutput") + 2 + INTLEN + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "enableoutput \"%i\"\n", outputId);
mpd_executeCommand(connection, string);
free(string);
}
void mpd_sendDisableOutputCommand(mpd_Connection *connection, int outputId) {
int len = strlen("disableoutput") + 2 + INTLEN + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "disableoutput \"%i\"\n", outputId);
mpd_executeCommand(connection, string);
free(string);
}
void mpd_freeOutputElement(mpd_OutputEntity *output) {
free(output->name);
free(output);
}
/** odd naming, but it gets the not allowed commands */
void mpd_sendNotCommandsCommand(mpd_Connection *connection) {
mpd_executeCommand(connection, "notcommands\n");
}
/** odd naming, but it gets the allowed commands */
void mpd_sendCommandsCommand(mpd_Connection *connection) {
mpd_executeCommand(connection, "commands\n");
}
/** Get the next returned command */
char *mpd_getNextCommand(mpd_Connection *connection) {
return mpd_getNextReturnElementNamed(connection, "command");
}
void mpd_sendUrlHandlersCommand(mpd_Connection *connection) {
mpd_executeCommand(connection, "urlhandlers\n");
}
char *mpd_getNextHandler(mpd_Connection *connection) {
return mpd_getNextReturnElementNamed(connection, "handler");
}
void mpd_sendTagTypesCommand(mpd_Connection *connection) {
mpd_executeCommand(connection, "tagtypes\n");
}
char *mpd_getNextTagType(mpd_Connection *connection) {
return mpd_getNextReturnElementNamed(connection, "tagtype");
}
void mpd_startSearch(mpd_Connection *connection, int exact) {
if (connection->request != nullptr) {
strncpy(connection->errorStr, "search already in progress",
MPD_ERRORSTR_MAX_LENGTH);
connection->error = 1;
return;
}
if (exact != 0) {
connection->request = strndup("find", text_buffer_size.get(*state));
} else {
connection->request = strndup("search", text_buffer_size.get(*state));
}
}
void mpd_startStatsSearch(mpd_Connection *connection) {
if (connection->request != nullptr) {
strncpy(connection->errorStr, "search already in progress",
MPD_ERRORSTR_MAX_LENGTH);
connection->error = 1;
return;
}
connection->request = strndup("count", text_buffer_size.get(*state));
}
void mpd_startPlaylistSearch(mpd_Connection *connection, int exact) {
if (connection->request != nullptr) {
strncpy(connection->errorStr, "search already in progress",
MPD_ERRORSTR_MAX_LENGTH);
connection->error = 1;
return;
}
if (exact != 0) {
connection->request = strndup("playlistfind", text_buffer_size.get(*state));
} else {
connection->request =
strndup("playlistsearch", text_buffer_size.get(*state));
}
}
void mpd_startFieldSearch(mpd_Connection *connection, int type) {
const char *strtype;
int len;
if (connection->request != nullptr) {
strncpy(connection->errorStr, "search already in progress",
MPD_ERRORSTR_MAX_LENGTH);
connection->error = 1;
return;
}
if (type < 0 || type >= MPD_TAG_NUM_OF_ITEM_TYPES) {
strncpy(connection->errorStr, "invalid type specified",
MPD_ERRORSTR_MAX_LENGTH);
connection->error = 1;
return;
}
strtype = mpdTagItemKeys[type];
len = 5 + strlen(strtype) + 1;
connection->request = static_cast<char *>(malloc(len));
snprintf(connection->request, len, "list %c%s",
tolower(static_cast<unsigned char>(strtype[0])), strtype + 1);
}
void mpd_addConstraintSearch(mpd_Connection *connection, int type,
const char *name) {
const char *strtype;
char *arg;
int len;
char *string;
if (connection->request == nullptr) {
strncpy(connection->errorStr, "no search in progress",
MPD_ERRORSTR_MAX_LENGTH);
connection->error = 1;
return;
}
if (type < 0 || type >= MPD_TAG_NUM_OF_ITEM_TYPES) {
strncpy(connection->errorStr, "invalid type specified",
MPD_ERRORSTR_MAX_LENGTH);
connection->error = 1;
return;
}
if (name == nullptr) {
strncpy(connection->errorStr, "no name specified", MPD_ERRORSTR_MAX_LENGTH);
connection->error = 1;
return;
}
string = strndup(connection->request, text_buffer_size.get(*state));
strtype = mpdTagItemKeys[type];
arg = mpd_sanitizeArg(name);
len = strlen(string) + 1 + strlen(strtype) + 2 + strlen(arg) + 2;
connection->request = static_cast<char *>(realloc(connection->request, len));
snprintf(connection->request, len, "%s %c%s \"%s\"", string,
tolower(static_cast<unsigned char>(strtype[0])), strtype + 1, arg);
free(string);
free(arg);
}
void mpd_commitSearch(mpd_Connection *connection) {
int len;
if (connection->request == nullptr) {
strncpy(connection->errorStr, "no search in progress",
MPD_ERRORSTR_MAX_LENGTH);
connection->error = 1;
return;
}
len = strlen(connection->request) + 2;
connection->request = static_cast<char *>(realloc(connection->request, len));
connection->request[len - 2] = '\n';
connection->request[len - 1] = '\0';
mpd_sendInfoCommand(connection, connection->request);
free_and_zero(connection->request);
}
/**
* @param connection a MpdConnection
* @param path the path to the playlist.
*
* List the content, with full metadata, of a stored playlist. */
void mpd_sendListPlaylistInfoCommand(mpd_Connection *connection, char *path) {
char *arg = mpd_sanitizeArg(path);
int len = strlen("listplaylistinfo") + 2 + strlen(arg) + 3;
auto *query = static_cast<char *>(malloc(len));
snprintf(query, len, "listplaylistinfo \"%s\"\n", arg);
mpd_sendInfoCommand(connection, query);
free(arg);
free(query);
}
/**
* @param connection a MpdConnection
* @param path the path to the playlist.
*
* List the content of a stored playlist. */
void mpd_sendListPlaylistCommand(mpd_Connection *connection, char *path) {
char *arg = mpd_sanitizeArg(path);
int len = strlen("listplaylist") + 2 + strlen(arg) + 3;
auto *query = static_cast<char *>(malloc(len));
snprintf(query, len, "listplaylist \"%s\"\n", arg);
mpd_sendInfoCommand(connection, query);
free(arg);
free(query);
}
void mpd_sendPlaylistClearCommand(mpd_Connection *connection, char *path) {
char *sPath = mpd_sanitizeArg(path);
int len = strlen("playlistclear") + 2 + strlen(sPath) + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "playlistclear \"%s\"\n", sPath);
mpd_executeCommand(connection, string);
free(sPath);
free(string);
}
void mpd_sendPlaylistAddCommand(mpd_Connection *connection, char *playlist,
char *path) {
char *sPlaylist = mpd_sanitizeArg(playlist);
char *sPath = mpd_sanitizeArg(path);
int len =
strlen("playlistadd") + 2 + strlen(sPlaylist) + 3 + strlen(sPath) + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "playlistadd \"%s\" \"%s\"\n", sPlaylist, sPath);
mpd_executeCommand(connection, string);
free(sPlaylist);
free(sPath);
free(string);
}
void mpd_sendPlaylistMoveCommand(mpd_Connection *connection, char *playlist,
int from, int to) {
char *sPlaylist = mpd_sanitizeArg(playlist);
int len = strlen("playlistmove") + 2 + strlen(sPlaylist) + 3 + INTLEN + 3 +
INTLEN + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "playlistmove \"%s\" \"%i\" \"%i\"\n", sPlaylist, from,
to);
mpd_executeCommand(connection, string);
free(sPlaylist);
free(string);
}
void mpd_sendPlaylistDeleteCommand(mpd_Connection *connection, char *playlist,
int pos) {
char *sPlaylist = mpd_sanitizeArg(playlist);
int len = strlen("playlistdelete") + 2 + strlen(sPlaylist) + 3 + INTLEN + 3;
auto *string = static_cast<char *>(malloc(len));
snprintf(string, len, "playlistdelete \"%s\" \"%i\"\n", sPlaylist, pos);
mpd_executeCommand(connection, string);
free(sPlaylist);
free(string);
}
| 63,345
|
C++
|
.cc
| 1,706
| 32.460727
| 80
| 0.658301
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,554
|
mail.cc
|
brndnmtthws_conky/src/mail.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* 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 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 "config.h"
#include "mail.h"
#include "common.h"
#include "conky.h"
#include "logging.h"
#include "text_object.h"
#include <netdb.h>
#include <netinet/in.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>
#include <cerrno>
#include <cinttypes>
#include <climits>
#include <cstdio>
#include <cstring>
#include <dirent.h>
#include <termios.h>
#include <cmath>
#include <memory>
#include <mutex>
#include <sstream>
#include "update-cb.hh"
struct local_mail_s {
char *mbox;
int mail_count;
int new_mail_count;
int seen_mail_count;
int unseen_mail_count;
int flagged_mail_count;
int unflagged_mail_count;
int forwarded_mail_count;
int unforwarded_mail_count;
int replied_mail_count;
int unreplied_mail_count;
int draft_mail_count;
int trashed_mail_count;
float interval;
time_t last_mtime;
time_t last_ctime; /* needed for mutt at least */
double last_update;
};
class mail_fail : public std::runtime_error {
public:
explicit mail_fail(const std::string &what_arg) : runtime_error(what_arg) {}
};
std::pair<std::string, bool> priv::current_mail_spool_setting::do_convert(
lua::state &l, int index) {
auto ret = Base::do_convert(l, index);
if (ret.second) { ret.first = variable_substitute(ret.first); }
return ret;
}
priv::current_mail_spool_setting current_mail_spool;
namespace {
enum { DEFAULT_MAIL_INTERVAL = 300 /*seconds*/ };
enum { MP_USER, MP_PASS, MP_FOLDER, MP_COMMAND, MP_HOST, MP_PORT };
struct mail_result {
unsigned long unseen{0};
unsigned long used{0};
unsigned long messages{0};
mail_result() = default;
};
class mail_cb
: public conky::callback<mail_result, std::string, std::string, std::string,
std::string, std::string, in_port_t> {
typedef conky::callback<mail_result, std::string, std::string, std::string,
std::string, std::string, in_port_t>
Base;
protected:
addrinfo *ai;
uint16_t fail;
uint16_t retries;
void resolve_host() {
struct addrinfo hints {};
char portbuf[8];
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
snprintf(portbuf, 8, "%" SCNu16, get<MP_PORT>());
if (int res = getaddrinfo(get<MP_HOST>().c_str(), portbuf, &hints, &ai)) {
throw mail_fail(std::string("IMAP getaddrinfo: ") + gai_strerror(res));
}
}
int connect() {
for (struct addrinfo *rp = ai; rp != nullptr; rp = rp->ai_next) {
int sockfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sockfd == -1) { continue; }
if (::connect(sockfd, rp->ai_addr, rp->ai_addrlen) != -1) {
return sockfd;
}
close(sockfd);
}
throw mail_fail("Unable to connect to mail server");
}
void merge(callback_base &&other) override {
auto &&o = dynamic_cast<mail_cb &&>(other);
if (retries < o.retries) {
retries = o.retries;
fail = 0;
}
Base::merge(std::move(other));
}
mail_cb(uint32_t period, const Tuple &tuple, uint16_t retries_)
: Base(period, false, tuple, true),
ai(nullptr),
fail(0),
retries(retries_) {}
~mail_cb() override {
if (ai != nullptr) { freeaddrinfo(ai); }
}
};
struct mail_param_ex : public mail_cb::Tuple {
uint16_t retries{0};
uint32_t period{1};
mail_param_ex() = default;
};
class imap_cb : public mail_cb {
using Base = mail_cb;
void check_status(char *recvbuf);
void unseen_command(unsigned long old_unseen, unsigned long old_messages);
protected:
void work() override;
public:
imap_cb(uint32_t period, const Tuple &tuple, uint16_t retries_)
: Base(period, tuple, retries_) {}
};
class pop3_cb : public mail_cb {
using Base = mail_cb;
protected:
void work() override;
public:
pop3_cb(uint32_t period, const Tuple &tuple, uint16_t retries_)
: Base(period, tuple, retries_) {}
};
struct mail_param_ex *global_mail;
} // namespace
static void update_mail_count(struct local_mail_s *mail) {
struct stat st {};
if (mail == nullptr) { return; }
/* TODO: use that fine file modification notify on Linux 2.4 */
/* don't check mail so often (9.5s is minimum interval) */
if (current_update_time - mail->last_update < 9.5) { return; }
mail->last_update = current_update_time;
if (stat(mail->mbox, &st) != 0) {
static int rep = 0;
if (rep == 0) {
NORM_ERR("can't stat %s: %s", mail->mbox, strerror(errno));
rep = 1;
}
return;
}
#if HAVE_DIRENT_H
/* maildir format */
if (S_ISDIR(st.st_mode)) {
DIR *dir;
std::string dirname(mail->mbox);
struct dirent *dirent;
char *mailflags;
mail->mail_count = mail->new_mail_count = 0;
mail->seen_mail_count = mail->unseen_mail_count = 0;
mail->flagged_mail_count = mail->unflagged_mail_count = 0;
mail->forwarded_mail_count = mail->unforwarded_mail_count = 0;
mail->replied_mail_count = mail->unreplied_mail_count = 0;
mail->draft_mail_count = mail->trashed_mail_count = 0;
/* checking the cur subdirectory */
dirname = dirname + "/cur";
dir = opendir(dirname.c_str());
if (dir == nullptr) {
NORM_ERR("cannot open directory");
return;
}
dirent = readdir(dir);
while (dirent != nullptr) {
/* . and .. are skipped */
if (dirent->d_name[0] != '.') {
mail->mail_count++;
mailflags = strdup(dirent->d_name);
if (mailflags == nullptr) {
NORM_ERR("malloc");
return;
}
strncpy(mailflags, strrchr(dirent->d_name, ','),
strlen(strrchr(dirent->d_name, ',')));
if (strchr(mailflags, 'T') ==
nullptr) { /* The message is not in the trash */
if (strchr(mailflags, 'S') !=
nullptr) { /*The message has been seen */
mail->seen_mail_count++;
} else {
mail->unseen_mail_count++;
}
if (strchr(mailflags, 'F') != nullptr) { /*The message was flagged */
mail->flagged_mail_count++;
} else {
mail->unflagged_mail_count++;
}
if (strchr(mailflags, 'P') !=
nullptr) { /*The message was forwarded */
mail->forwarded_mail_count++;
} else {
mail->unforwarded_mail_count++;
}
if (strchr(mailflags, 'R') != nullptr) { /*The message was replied */
mail->replied_mail_count++;
} else {
mail->unreplied_mail_count++;
}
if (strchr(mailflags, 'D') != nullptr) { /*The message is a draft */
mail->draft_mail_count++;
}
} else {
mail->trashed_mail_count++;
}
free(mailflags);
}
dirent = readdir(dir);
}
closedir(dir);
dirname.resize(dirname.size() - 3);
dirname = dirname + "new";
dir = opendir(dirname.c_str());
if (dir == nullptr) {
NORM_ERR("cannot open directory");
return;
}
dirent = readdir(dir);
while (dirent != nullptr) {
/* . and .. are skipped */
if (dirent->d_name[0] != '.') {
mail->new_mail_count++;
mail->mail_count++;
mail->unseen_mail_count++; /* new messages cannot have been seen */
}
dirent = readdir(dir);
}
closedir(dir);
return;
}
#endif
/* mbox format */
if (st.st_mtime != mail->last_mtime || st.st_ctime != mail->last_ctime) {
/* yippee, modification time has changed, let's read mail count! */
static int rep;
FILE *fp;
int reading_status = 0;
/* could lock here but I don't think it's really worth it because
* this isn't going to write mail spool */
mail->new_mail_count = mail->mail_count = 0;
/* these flags are not supported for mbox */
mail->seen_mail_count = mail->unseen_mail_count = -1;
mail->flagged_mail_count = mail->unflagged_mail_count = -1;
mail->forwarded_mail_count = mail->unforwarded_mail_count = -1;
mail->replied_mail_count = mail->unreplied_mail_count = -1;
mail->draft_mail_count = mail->trashed_mail_count = -1;
fp = open_file(mail->mbox, &rep);
if (fp == nullptr) { return; }
/* NOTE: adds mail as new if there isn't Status-field at all */
while (feof(fp) == 0) {
char buf[128];
if (fgets(buf, 128, fp) == nullptr) { break; }
if (strncmp(buf, "From ", 5) == 0) {
/* ignore MAILER-DAEMON */
if (strncmp(buf + 5, "MAILER-DAEMON ", 14) != 0) {
mail->mail_count++;
if (reading_status == 1) {
mail->new_mail_count++;
} else {
reading_status = 1;
}
}
} else {
if (reading_status == 1 && strncmp(buf, "X-Mozilla-Status:", 17) == 0) {
int xms = strtol(buf + 17, nullptr, 16);
/* check that mail isn't marked for deletion */
if ((xms & 0x0008) != 0) {
mail->trashed_mail_count++;
reading_status = 0;
/* Don't check whether the trashed email is unread */
continue;
}
/* check that mail isn't already read */
if ((xms & 0x0001) == 0) { mail->new_mail_count++; }
/* check for an additional X-Status header */
reading_status = 2;
continue;
}
if (reading_status == 1 && strncmp(buf, "Status:", 7) == 0) {
/* check that mail isn't already read */
if (strchr(buf + 7, 'R') == nullptr) { mail->new_mail_count++; }
reading_status = 2;
continue;
}
if (reading_status >= 1 && strncmp(buf, "X-Status:", 9) == 0) {
/* check that mail isn't marked for deletion */
if (strchr(buf + 9, 'D') != nullptr) { mail->trashed_mail_count++; }
reading_status = 0;
continue;
}
}
/* skip until \n */
while (strchr(buf, '\n') == nullptr && (feof(fp) == 0)) {
if (fgets(buf, 128, fp) == nullptr) { break; }
}
}
fclose(fp);
if (reading_status != 0) { mail->new_mail_count++; }
mail->last_mtime = st.st_mtime;
mail->last_ctime = st.st_ctime;
}
}
void parse_local_mail_args(struct text_object *obj, const char *arg) {
float n1;
char mbox[256];
struct local_mail_s *locmail;
if (arg == nullptr) {
n1 = 9.5;
strncpy(mbox, current_mail_spool.get(*state).c_str(), sizeof(mbox));
} else {
if (sscanf(arg, "%s %f", mbox, &n1) != 2) {
n1 = 9.5;
strncpy(mbox, arg, sizeof(mbox));
}
}
std::string dst = variable_substitute(mbox);
locmail =
static_cast<struct local_mail_s *>(malloc(sizeof(struct local_mail_s)));
memset(locmail, 0, sizeof(struct local_mail_s));
locmail->mbox = strndup(dst.c_str(), text_buffer_size.get(*state));
locmail->interval = n1;
obj->data.opaque = locmail;
}
#define PRINT_MAILS_GENERATOR(x) \
void print_##x##mails(struct text_object *obj, char *p, \
unsigned int p_max_size) { \
struct local_mail_s *locmail = (struct local_mail_s *)obj->data.opaque; \
if (!locmail) return; \
update_mail_count(locmail); \
snprintf(p, p_max_size, "%d", locmail->x##mail_count); \
}
PRINT_MAILS_GENERATOR()
PRINT_MAILS_GENERATOR(new_)
PRINT_MAILS_GENERATOR(seen_)
PRINT_MAILS_GENERATOR(unseen_)
PRINT_MAILS_GENERATOR(flagged_)
PRINT_MAILS_GENERATOR(unflagged_)
PRINT_MAILS_GENERATOR(forwarded_)
PRINT_MAILS_GENERATOR(unforwarded_)
PRINT_MAILS_GENERATOR(replied_)
PRINT_MAILS_GENERATOR(unreplied_)
PRINT_MAILS_GENERATOR(draft_)
PRINT_MAILS_GENERATOR(trashed_)
void free_local_mails(struct text_object *obj) {
auto *locmail = static_cast<struct local_mail_s *>(obj->data.opaque);
if (locmail == nullptr) { return; }
free_and_zero(locmail->mbox);
free_and_zero(obj->data.opaque);
}
#define MAXDATASIZE 1000
namespace {
enum mail_type { POP3_TYPE, IMAP_TYPE };
} // namespace
std::unique_ptr<mail_param_ex> parse_mail_args(mail_type type,
const char *arg) {
using std::get;
std::unique_ptr<mail_param_ex> mail;
char *tmp;
char host[129];
char user[129];
char pass[129];
if (sscanf(arg, "%128s %128s %128s", host, user, pass) != 3) {
if (type == POP3_TYPE) {
NORM_ERR("Scanning POP3 args failed");
} else if (type == IMAP_TYPE) {
NORM_ERR("Scanning IMAP args failed");
}
return mail;
}
// see if password needs prompting
if (pass[0] == '*' && pass[1] == '\0') {
int fp = fileno(stdin);
struct termios term {};
tcgetattr(fp, &term);
term.c_lflag &= ~ECHO;
tcsetattr(fp, TCSANOW, &term);
printf("Enter mailbox password (%s@%s): ", user, host);
if (scanf("%128s", pass) != 1) { pass[0] = 0; }
printf("\n");
term.c_lflag |= ECHO;
tcsetattr(fp, TCSANOW, &term);
}
mail = std::make_unique<mail_param_ex>();
get<MP_HOST>(*mail) = host;
get<MP_USER>(*mail) = user;
get<MP_PASS>(*mail) = pass;
// now we check for optional args
tmp = const_cast<char *>(strstr(arg, "-r "));
if (tmp != nullptr) {
tmp += 3;
sscanf(tmp, "%" SCNu16, &mail->retries);
} else {
mail->retries = 5; // 5 retries after failure
}
float interval = DEFAULT_MAIL_INTERVAL;
tmp = const_cast<char *>(strstr(arg, "-i "));
if (tmp != nullptr) {
tmp += 3;
sscanf(tmp, "%f", &interval);
}
mail->period = std::max(lround(interval / active_update_interval()), 1l);
tmp = const_cast<char *>(strstr(arg, "-p "));
if (tmp != nullptr) {
tmp += 3;
sscanf(tmp, "%" SCNu16, &get<MP_PORT>(*mail));
} else {
if (type == POP3_TYPE) {
get<MP_PORT>(*mail) = 110; // default pop3 port
} else if (type == IMAP_TYPE) {
get<MP_PORT>(*mail) = 143; // default imap port
}
}
if (type == IMAP_TYPE) {
tmp = const_cast<char *>(strstr(arg, "-f "));
if (tmp != nullptr) {
int len = 0;
tmp += 3;
if (tmp[0] == '\'') {
len = strstr(tmp + 1, "'") - tmp - 1;
tmp++;
}
get<MP_FOLDER>(*mail).assign(tmp, len);
} else {
get<MP_FOLDER>(*mail) = "INBOX"; // default imap inbox
}
}
tmp = const_cast<char *>(strstr(arg, "-e "));
if (tmp != nullptr) {
int len = 0;
tmp += 3;
if (tmp[0] == '\'') { len = strstr(tmp + 1, "'") - tmp - 1; }
get<MP_COMMAND>(*mail).assign(tmp + 1, len);
}
return mail;
}
void parse_imap_mail_args(struct text_object *obj, const char *arg) {
static int rep = 0;
if (arg == nullptr) {
if ((global_mail == nullptr) && (rep == 0)) {
// something is wrong, warn once then stop
NORM_ERR(
"There's a problem with your mail settings. "
"Check that the global mail settings are properly defined"
" (line %li).",
obj->line);
rep = 1;
return;
}
obj->data.opaque = global_mail;
return;
}
// process
obj->data.opaque = parse_mail_args(IMAP_TYPE, arg).release();
}
void parse_pop3_mail_args(struct text_object *obj, const char *arg) {
static int rep = 0;
if (arg == nullptr) {
if ((global_mail == nullptr) && (rep == 0)) {
// something is wrong, warn once then stop
NORM_ERR(
"There's a problem with your mail settings. "
"Check that the global mail settings are properly defined"
" (line %li).",
obj->line);
rep = 1;
return;
}
obj->data.opaque = global_mail;
return;
}
// process
obj->data.opaque = parse_mail_args(POP3_TYPE, arg).release();
}
namespace {
class mail_setting : public conky::simple_config_setting<std::string> {
using Base = conky::simple_config_setting<std::string>;
mail_type type;
protected:
void lua_setter(lua::state &l, bool init) override {
lua::stack_sentry s(l, -2);
Base::lua_setter(l, init);
if (init && (global_mail == nullptr)) {
const std::string &t = do_convert(l, -1).first;
if (static_cast<unsigned int>(!t.empty()) != 0u) {
global_mail = parse_mail_args(type, t.c_str()).release();
}
}
++s;
}
void cleanup(lua::state &l) override {
lua::stack_sentry s(l, -1);
delete global_mail;
global_mail = nullptr;
l.pop();
}
public:
mail_setting(const std::string &name, mail_type type_)
: Base(name), type(type_) {}
};
mail_setting imap("imap", IMAP_TYPE);
mail_setting pop3("pop3", POP3_TYPE);
} // namespace
void free_mail_obj(struct text_object *obj) {
if (obj->data.opaque == nullptr) { return; }
if (obj->data.opaque != global_mail) {
auto *mail = static_cast<mail_param_ex *>(obj->data.opaque);
delete mail;
obj->data.opaque = nullptr;
}
}
static void command(int sockfd, const std::string &cmd, char *response,
const char *verify) {
struct timeval fetchtimeout {};
fd_set fdset;
ssize_t total = 0;
int numbytes = 0;
if (send(sockfd, cmd.c_str(), cmd.length(), 0) == -1) {
throw mail_fail("send: " + strerror_r(errno));
}
DBGP2("command() command: %s", cmd.c_str());
while (1) {
fetchtimeout.tv_sec = 60; // 60 second timeout i guess
fetchtimeout.tv_usec = 0;
FD_ZERO(&fdset);
FD_SET(sockfd, &fdset);
if (select(sockfd + 1, &fdset, nullptr, nullptr, &fetchtimeout) == 0) {
throw mail_fail("select: read timeout");
}
if ((numbytes = recv(sockfd, response + total, MAXDATASIZE - 1 - total,
0)) == -1) {
throw mail_fail("recv: " + strerror_r(errno));
}
total += numbytes;
response[total] = '\0';
DBGP2("command() received: %s", response);
if (strstr(response, verify) != nullptr) { return; }
if (numbytes == 0) { throw mail_fail("Unexpected response from server"); }
}
}
void imap_cb::check_status(char *recvbuf) {
char *reply;
reply = strstr(recvbuf, " (MESSAGES ");
if ((reply == nullptr) || strlen(reply) < 2) {
throw mail_fail("Unexpected response from server");
}
reply += 2;
*strchr(reply, ')') = '\0';
std::lock_guard<std::mutex> lock(result_mutex);
if (sscanf(reply, "MESSAGES %lu UNSEEN %lu", &result.messages,
&result.unseen) != 2) {
throw mail_fail(std::string("Error parsing response: ") + recvbuf);
}
}
void imap_cb::unseen_command(unsigned long old_unseen,
unsigned long old_messages) {
if (!get<MP_COMMAND>().empty() &&
(result.unseen > old_unseen ||
(result.messages > old_messages && result.unseen > 0)) &&
system(get<MP_COMMAND>().c_str()) == -1) {
perror("system()");
}
}
void imap_cb::work() {
int sockfd, numbytes;
char recvbuf[MAXDATASIZE];
unsigned long old_unseen = ULONG_MAX;
unsigned long old_messages = ULONG_MAX;
bool has_idle = false;
while (fail < retries) {
struct timeval fetchtimeout {};
int res;
fd_set fdset;
if (ai == nullptr) { resolve_host(); }
try {
sockfd = connect();
command(sockfd, "", recvbuf, "* OK");
command(sockfd, "abc CAPABILITY\r\n", recvbuf, "abc OK");
if (strstr(recvbuf, " IDLE ") != nullptr) { has_idle = true; }
std::ostringstream str;
str << "a1 login " << get<MP_USER>() << " {" << get<MP_PASS>().length()
<< "}\r\n";
command(sockfd, str.str(), recvbuf, "+");
command(sockfd, get<MP_PASS>() + "\r\n", recvbuf, "a1 OK");
command(sockfd,
"a2 STATUS \"" + get<MP_FOLDER>() + "\" (MESSAGES UNSEEN)\r\n",
recvbuf, "a2 OK");
check_status(recvbuf);
unseen_command(old_unseen, old_messages);
fail = 0;
old_unseen = result.unseen;
old_messages = result.messages;
if (!has_idle) {
try {
command(sockfd, "a3 LOGOUT\r\n", recvbuf, "a3 OK");
} catch (mail_fail &e) {
NORM_ERR("Error while communicating with IMAP server: %s", e.what());
}
close(sockfd);
return;
}
command(sockfd, "a4 SELECT \"" + get<MP_FOLDER>() + "\"\r\n", recvbuf,
"a4 OK");
command(sockfd, "a5 IDLE\r\n", recvbuf, "+ idling");
recvbuf[0] = '\0';
while (1) {
/*
* RFC 2177 says we have to re-idle every 29 minutes.
* We'll do it every 20 minutes to be safe.
*/
fetchtimeout.tv_sec = 1200;
fetchtimeout.tv_usec = 0;
DBGP2("idling...");
FD_ZERO(&fdset);
FD_SET(sockfd, &fdset);
FD_SET(donefd(), &fdset);
res = select(std::max(sockfd, donefd()) + 1, &fdset, nullptr, nullptr,
&fetchtimeout);
if ((res == -1 && errno == EINTR) || FD_ISSET(donefd(), &fdset)) {
try {
command(sockfd, "DONE\r\n", recvbuf, "a5 OK");
command(sockfd, "a3 LOGOUT\r\n", recvbuf, "a3 OK");
} catch (mail_fail &e) {
NORM_ERR("Error while communicating with IMAP server: %s",
e.what());
}
close(sockfd);
return;
}
if (res > 0) {
if ((numbytes = recv(sockfd, recvbuf, MAXDATASIZE - 1, 0)) == -1) {
throw mail_fail("recv idling");
}
} else {
throw mail_fail("");
}
recvbuf[numbytes] = '\0';
DBGP2("imap_thread() received: %s", recvbuf);
unsigned long messages, recent = 0;
bool force_check = 0;
if (strlen(recvbuf) > 2) {
char *buf = recvbuf;
buf = strstr(buf, "EXISTS");
while ((buf != nullptr) && strlen(buf) > 1 &&
(strstr(buf + 1, "EXISTS") != nullptr)) {
buf = strstr(buf + 1, "EXISTS");
}
if (buf != nullptr) {
// back up until we reach '*'
while (buf >= recvbuf && buf < (recvbuf + MAXDATASIZE) - 1 &&
buf[0] != '*') {
buf--;
}
if (sscanf(buf, "* %lu EXISTS\r\n", &messages) == 1) {
std::lock_guard<std::mutex> lock(result_mutex);
if (result.messages != messages) {
force_check = 1;
result.messages = messages;
}
}
}
buf = recvbuf;
buf = strstr(buf, "RECENT");
while ((buf != nullptr) && strlen(buf) > 1 &&
(strstr(buf + 1, "RECENT") != nullptr)) {
buf = strstr(buf + 1, "RECENT");
}
if (buf != nullptr) {
// back up until we reach '*'
while (buf >= recvbuf && buf < (recvbuf + MAXDATASIZE) - 1 &&
buf[0] != '*') {
buf--;
}
if (sscanf(buf, "* %lu RECENT\r\n", &recent) != 1) { recent = 0; }
}
}
/* check if we got a BYE from server */
if (strstr(recvbuf, "* BYE") != nullptr) {
// need to re-connect
throw mail_fail("");
}
/*
* check if we got a FETCH from server, recent was
* something other than 0, or we had a timeout
*/
if (recent > 0 || (strstr(recvbuf, " FETCH ") != nullptr) ||
fetchtimeout.tv_sec == 0 || force_check) {
// re-check messages and unseen
command(sockfd, "DONE\r\n", recvbuf, "a5 OK");
command(
sockfd,
"a2 STATUS \"" + get<MP_FOLDER>() + "\" (MESSAGES UNSEEN)\r\n",
recvbuf, "a2 OK");
check_status(recvbuf);
command(sockfd, "a5 IDLE\r\n", recvbuf, "+ idling");
}
unseen_command(old_unseen, old_messages);
fail = 0;
old_unseen = result.unseen;
old_messages = result.messages;
}
} catch (mail_fail &e) {
if (sockfd != -1) { close(sockfd); }
freeaddrinfo(ai);
ai = nullptr;
++fail;
if (*e.what() != 0) {
NORM_ERR("Error while communicating with IMAP server: %s", e.what());
}
NORM_ERR("Trying IMAP connection again for %s@%s (try %u/%u)",
get<MP_USER>().c_str(), get<MP_HOST>().c_str(), fail + 1,
retries);
sleep(fail); /* sleep more for the more failures we have */
}
if (is_done()) { return; }
}
}
void print_imap_unseen(struct text_object *obj, char *p,
unsigned int p_max_size) {
auto *mail = static_cast<struct mail_param_ex *>(obj->data.opaque);
if (mail == nullptr) { return; }
auto cb = conky::register_cb<imap_cb>(mail->period, *mail, mail->retries);
snprintf(p, p_max_size, "%lu", cb->get_result_copy().unseen);
}
void print_imap_messages(struct text_object *obj, char *p,
unsigned int p_max_size) {
auto *mail = static_cast<struct mail_param_ex *>(obj->data.opaque);
if (mail == nullptr) { return; }
auto cb = conky::register_cb<imap_cb>(mail->period, *mail, mail->retries);
snprintf(p, p_max_size, "%lu", cb->get_result_copy().messages);
}
void pop3_cb::work() {
int sockfd;
char recvbuf[MAXDATASIZE];
char *reply;
unsigned long old_unseen = ULONG_MAX;
while (fail < retries) {
if (ai == nullptr) { resolve_host(); }
try {
sockfd = connect();
command(sockfd, "", recvbuf, "+OK ");
command(sockfd, "USER " + get<MP_USER>() + "\r\n", recvbuf, "+OK ");
command(sockfd, "PASS " + get<MP_PASS>() + "\r\n", recvbuf, "+OK ");
command(sockfd, "STAT\r\n", recvbuf, "+OK ");
// now we get the data
reply = recvbuf + 4;
{
std::lock_guard<std::mutex> lock(result_mutex);
sscanf(reply, "%lu %lu", &result.unseen, &result.used);
}
command(sockfd, "QUIT\r\n", recvbuf, "+OK");
if (get<MP_COMMAND>().length() > 1 && result.unseen > old_unseen &&
system(get<MP_COMMAND>().c_str()) == -1) {
perror("system()");
}
fail = 0;
return;
} catch (mail_fail &e) {
if (sockfd != -1) { close(sockfd); }
freeaddrinfo(ai);
ai = nullptr;
++fail;
if (*e.what() != 0) {
NORM_ERR("Error while communicating with POP3 server: %s", e.what());
}
NORM_ERR("Trying POP3 connection again for %s@%s (try %u/%u)",
get<MP_USER>().c_str(), get<MP_HOST>().c_str(), fail + 1,
retries);
sleep(fail); /* sleep more for the more failures we have */
}
if (is_done()) { return; }
}
}
void print_pop3_unseen(struct text_object *obj, char *p,
unsigned int p_max_size) {
auto *mail = static_cast<struct mail_param_ex *>(obj->data.opaque);
if (mail == nullptr) { return; }
auto cb = conky::register_cb<pop3_cb>(mail->period, *mail, mail->retries);
snprintf(p, p_max_size, "%lu", cb->get_result_copy().unseen);
}
void print_pop3_used(struct text_object *obj, char *p,
unsigned int p_max_size) {
auto *mail = static_cast<struct mail_param_ex *>(obj->data.opaque);
if (mail == nullptr) { return; }
auto cb = conky::register_cb<pop3_cb>(mail->period, *mail, mail->retries);
snprintf(p, p_max_size, "%.1f", cb->get_result_copy().used / 1024.0 / 1024.0);
}
| 28,456
|
C++
|
.cc
| 825
| 28.190303
| 80
| 0.573405
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,555
|
c++wrap.cc
|
brndnmtthws_conky/src/c++wrap.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Please see COPYING for details
*
* Copyright (C) 2010 Pavel Labath et al.
*
* 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 "config.h"
#include "c++wrap.hh"
#include <unistd.h>
#include <cstdio>
/* force use of POSIX strerror_r instead of non-portable GNU specific */
#ifdef _GNU_SOURCE
#undef _GNU_SOURCE
#endif
#include <cstring>
#if __cplusplus <= 199711L
#define thread_local __thread
#endif
#if !defined(HAVE_PIPE2) || !defined(HAVE_O_CLOEXEC)
#include <fcntl.h>
namespace {
int pipe2_emulate(int pipefd[2], int flags) {
if (pipe(pipefd) == -1) { return -1; }
if ((flags & O_CLOEXEC) != 0) {
// we emulate O_CLOEXEC if the system does not have it
// not very thread-safe, but at least it works
for (int i = 0; i < 2; ++i) {
int r = fcntl(pipefd[i], F_GETFD);
if (r == -1) { return -1; }
if (fcntl(pipefd[i], F_SETFD, r | FD_CLOEXEC) == -1) { return -1; }
}
}
return 0;
}
int (*const pipe2_ptr)(int[2], int) = &pipe2_emulate;
} // namespace
#else
int (*const pipe2_ptr)(int[2], int) = &pipe2;
#endif
std::string strerror_r(int errnum) {
static thread_local char buf[100];
if (strerror_r(errnum, buf, sizeof buf) != 0) {
snprintf(buf, sizeof buf, "Unknown error %i", errnum);
}
return buf;
}
std::pair<int, int> pipe2(int flags) {
int fd[2];
if (pipe2_ptr(fd, flags) == -1) { throw errno_error("pipe2"); }
{ return std::pair<int, int>(fd[0], fd[1]); }
}
| 2,103
|
C++
|
.cc
| 66
| 29.439394
| 73
| 0.680178
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,556
|
fs.cc
|
brndnmtthws_conky/src/fs.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* 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 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 "fs.h"
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <cctype>
#include <cerrno>
#include "conky.h"
#include "logging.h"
#include "specials.h"
#include "text_object.h"
#ifdef HAVE_SYS_STATFS_H
#include <sys/statfs.h>
#endif
#if defined(__sun)
#include <sys/statvfs.h>
#include <sys/types.h>
#endif
#if defined(__FreeBSD__)
#include "freebsd.h"
#elif defined(__DragonFly__)
#include "dragonfly.h"
#elif defined(__HAIKU__)
#include "haiku.h"
#elif defined(__APPLE__) && defined(__MACH__)
#include "darwin.h"
#endif
#if !defined(HAVE_STRUCT_STATFS_F_FSTYPENAME) && !defined(__OpenBSD__) && \
!defined(__FreeBSD__) && !defined(__DragonFly__) && !defined(__sun) && \
!defined(__HAIKU__) && !(defined(__APPLE__) && defined(__MACH__))
#include <mntent.h>
#endif
#define MAX_FS_STATS 64
static struct fs_stat fs_stats_[MAX_FS_STATS];
struct fs_stat *fs_stats = fs_stats_;
static void update_fs_stat(struct fs_stat *fs);
void get_fs_type(const char *path, char *result);
int update_fs_stats() {
unsigned i;
static double last_fs_update = 0.0;
if (current_update_time - last_fs_update < 13) { return 0; }
for (i = 0; i < MAX_FS_STATS; ++i) {
if (fs_stats[i].set != 0) { update_fs_stat(&fs_stats[i]); }
}
last_fs_update = current_update_time;
return 0;
}
void clear_fs_stats() {
unsigned i;
for (i = 0; i < MAX_FS_STATS; ++i) {
memset(&fs_stats[i], 0, sizeof(struct fs_stat));
}
}
struct fs_stat *prepare_fs_stat(const char *s) {
struct fs_stat *next = nullptr;
unsigned i;
/* lookup existing or get new */
for (i = 0; i < MAX_FS_STATS; ++i) {
if (fs_stats[i].set != 0) {
if (strncmp(fs_stats[i].path, s, DEFAULT_TEXT_BUFFER_SIZE) == 0) {
return &fs_stats[i];
}
} else {
next = &fs_stats[i];
}
}
/* new path */
if (next == nullptr) {
NORM_ERR("too many fs stats");
return nullptr;
}
strncpy(next->path, s, DEFAULT_TEXT_BUFFER_SIZE);
next->set = 1;
next->errored = 0;
update_fs_stat(next);
return next;
}
#if defined(__APPLE__)
#define statfs_func statfs
#define statfs_struct statfs
#else
#define statfs_func statfs64
#define statfs_struct statfs64
#endif /* defined(__APPLE__) */
static void update_fs_stat(struct fs_stat *fs) {
#if defined(__sun)
struct statvfs s;
if (statvfs(fs->path, &s) == 0) {
fs->size = (long long)s.f_blocks * s.f_frsize;
fs->avail = (long long)s.f_bavail * s.f_frsize;
fs->free = (long long)s.f_bfree * s.f_frsize;
(void)strncpy(fs->type, s.f_basetype, sizeof(fs->type));
#else
struct statfs_struct s {};
if (statfs_func(fs->path, &s) == 0) {
fs->size = static_cast<long long>(s.f_blocks) * s.f_bsize;
/* bfree (root) or bavail (non-roots) ? */
fs->avail = static_cast<long long>(s.f_bavail) * s.f_bsize;
fs->free = static_cast<long long>(s.f_bfree) * s.f_bsize;
fs->errored = 0;
get_fs_type(fs->path, fs->type);
#endif
} else {
if (fs->errored == 0) {
NORM_ERR("statfs '%s': %s", fs->path, strerror(errno));
fs->errored = 1;
}
fs->size = 0;
fs->avail = 0;
fs->free = 0;
strncpy(fs->type, "unknown", DEFAULT_TEXT_BUFFER_SIZE);
}
}
void get_fs_type(const char *path, char *result) {
#if defined(HAVE_STRUCT_STATFS_F_FSTYPENAME) || defined(__FreeBSD__) || \
defined(__OpenBSD__) || defined(__DragonFly__) || defined(__HAIKU__) || \
(defined(__APPLE__) && defined(__MACH__))
struct statfs_struct s {};
if (statfs_func(path, &s) == 0) {
strncpy(result, s.f_fstypename, DEFAULT_TEXT_BUFFER_SIZE);
} else {
NORM_ERR("statfs '%s': %s", path, strerror(errno));
}
return;
#elif defined(__sun)
assert(0); /* not used - see update_fs_stat() */
#else /* HAVE_STRUCT_STATFS_F_FSTYPENAME */
struct mntent *me;
FILE *mtab = setmntent("/proc/mounts", "r");
char *search_path;
int match;
char *slash;
if (mtab == nullptr) {
NORM_ERR("setmntent /proc/mounts: %s", strerror(errno));
strncpy(result, "unknown", DEFAULT_TEXT_BUFFER_SIZE);
return;
}
me = getmntent(mtab);
// find our path in the mtab
search_path = strdup(path);
do {
while ((match = strcmp(search_path, me->mnt_dir)) && getmntent(mtab))
;
if (!match) break;
fseek(mtab, 0, SEEK_SET);
slash = strrchr(search_path, '/');
if (slash == nullptr) {
CRIT_ERR("invalid path '%s'", path);
} else {
if (strlen(slash) == 1) /* trailing slash */
*(slash) = '\0';
else if (strlen(slash) > 1)
*(slash + 1) = '\0';
else
CRIT_ERR("found a crack in the matrix!");
}
} while (strlen(search_path) > 0);
free(search_path);
endmntent(mtab);
if (me && !match) {
strncpy(result, me->mnt_type, DEFAULT_TEXT_BUFFER_SIZE);
return;
}
#endif /* HAVE_STRUCT_STATFS_F_FSTYPENAME */
strncpy(result, "unknown", DEFAULT_TEXT_BUFFER_SIZE);
}
void init_fs_bar(struct text_object *obj, const char *arg) {
arg = scan_bar(obj, arg, 1);
if (arg != nullptr) {
while (isspace(static_cast<unsigned char>(*arg)) != 0) { arg++; }
if (*arg == '\0') { arg = "/"; }
} else {
arg = "/";
}
obj->data.opaque = prepare_fs_stat(arg);
}
static double get_fs_perc(struct text_object *obj, bool get_free) {
auto *fs = static_cast<struct fs_stat *>(obj->data.opaque);
double ret = 0.0;
if ((fs != nullptr) && (fs->size != 0)) {
if (get_free) {
ret = fs->avail;
} else {
ret = fs->size - fs->free;
}
ret /= fs->size;
}
return ret;
}
double fs_barval(struct text_object *obj) { return get_fs_perc(obj, false); }
double fs_free_barval(struct text_object *obj) {
return get_fs_perc(obj, true);
}
void init_fs(struct text_object *obj, const char *arg) {
obj->data.opaque = prepare_fs_stat(arg != nullptr ? arg : "/");
}
uint8_t fs_free_percentage(struct text_object *obj) {
return get_fs_perc(obj, true) * 100;
}
uint8_t fs_used_percentage(struct text_object *obj) {
return get_fs_perc(obj, false) * 100;
}
#define HUMAN_PRINT_FS_GENERATOR(name, expr) \
void print_fs_##name(struct text_object *obj, char *p, \
unsigned int p_max_size) { \
struct fs_stat *fs = (struct fs_stat *)obj->data.opaque; \
if (fs) human_readable(expr, p, p_max_size); \
}
HUMAN_PRINT_FS_GENERATOR(free, fs->avail)
HUMAN_PRINT_FS_GENERATOR(size, fs->size)
HUMAN_PRINT_FS_GENERATOR(used, fs->size - fs->free)
void print_fs_type(struct text_object *obj, char *p, unsigned int p_max_size) {
auto *fs = static_cast<struct fs_stat *>(obj->data.opaque);
if (fs != nullptr) { snprintf(p, p_max_size, "%s", fs->type); }
}
| 7,732
|
C++
|
.cc
| 242
| 28.739669
| 79
| 0.639012
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
22,557
|
mpd.cc
|
brndnmtthws_conky/src/mpd.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* 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 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 "mpd.h"
#include <cmath>
#include <mutex>
#include "conky.h"
#include "libmpdclient.h"
#include "logging.h"
#include "timeinfo.h"
#include "update-cb.hh"
namespace {
/* this is true if the current host was set from MPD_HOST */
bool mpd_environment_host = false;
class mpd_host_setting : public conky::simple_config_setting<std::string> {
using Base = conky::simple_config_setting<std::string>;
protected:
void lua_setter(lua::state &l, bool init) override;
public:
mpd_host_setting() : Base("mpd_host", "localhost", false) {}
};
void mpd_host_setting::lua_setter(lua::state &l, bool init) {
lua::stack_sentry s(l, -2);
if (l.isnil(-2)) {
// get the value from environment
mpd_environment_host = true;
const char *t = getenv("MPD_HOST");
if (t != nullptr) {
l.checkstack(1);
const char *h = strchr(t, '@');
if (h != nullptr) {
if (h[1] != 0) { l.pushstring(h + 1); }
} else {
l.pushstring(t);
}
l.replace(-3);
}
}
Base::lua_setter(l, init);
++s;
}
class mpd_password_setting : public conky::simple_config_setting<std::string> {
using Base = conky::simple_config_setting<std::string>;
protected:
void lua_setter(lua::state &l, bool init) override;
public:
mpd_password_setting() : Base("mpd_password", std::string(), false) {}
};
void mpd_password_setting::lua_setter(lua::state &l, bool init) {
lua::stack_sentry s(l, -2);
/* for security, dont use environment password when user specifies host in
* config */
if (l.isnil(-2) && mpd_environment_host) {
// get the value from environment
const char *t = getenv("MPD_HOST");
if (t != nullptr) {
const char *p = strchr(t, '@');
if (p != nullptr) {
l.checkstack(1);
l.pushstring(t, p - t);
l.replace(-3);
}
}
}
Base::lua_setter(l, init);
++s;
}
conky::range_config_setting<in_port_t> mpd_port("mpd_port", 1, 65535, 6600,
false);
mpd_host_setting mpd_host;
mpd_password_setting mpd_password;
struct mpd_result {
float progress{};
int bitrate{};
int elapsed{};
int is_playing{};
int length{};
int vol{};
std::string album;
std::string albumartist;
std::string artist;
std::string comment;
std::string date;
std::string file;
std::string name;
std::string random;
std::string repeat;
std::string status;
std::string title;
std::string track;
};
class mpd_cb : public conky::callback<mpd_result> {
using Base = conky::callback<mpd_result>;
mpd_Connection *conn;
protected:
void work() override;
public:
explicit mpd_cb(uint32_t period)
: Base(period, false, Tuple()), conn(nullptr) {}
~mpd_cb() override {
if (conn != nullptr) { mpd_closeConnection(conn); }
}
};
void mpd_cb::work() {
mpd_Status *status;
mpd_InfoEntity *entity;
mpd_result mpd_info;
do {
if (conn == nullptr) {
conn = mpd_newConnection(mpd_host.get(*state).c_str(),
mpd_port.get(*state), 10);
}
if (static_cast<unsigned int>(!mpd_password.get(*state).empty()) != 0u) {
mpd_sendPasswordCommand(conn, mpd_password.get(*state).c_str());
mpd_finishCommand(conn);
}
if (conn->error != 0) {
NORM_ERR("MPD error: %s\n", conn->errorStr);
mpd_closeConnection(conn);
conn = nullptr;
mpd_info.status = "MPD not responding";
break;
}
mpd_sendStatusCommand(conn);
if ((status = mpd_getStatus(conn)) == nullptr) {
NORM_ERR("MPD error: %s\n", conn->errorStr);
mpd_closeConnection(conn);
conn = nullptr;
mpd_info.status = "MPD not responding";
break;
}
mpd_finishCommand(conn);
if ((conn == nullptr) || (conn->error != 0)) {
// fprintf(stderr, "%s\n", conn->errorStr);
mpd_closeConnection(conn);
conn = nullptr;
break;
}
mpd_info.vol = status->volume;
if (status->random == 0) {
mpd_info.random = "Off";
} else if (status->random == 1) {
mpd_info.random = "On";
} else {
mpd_info.random = "";
}
if (status->repeat == 0) {
mpd_info.repeat = "Off";
} else if (status->repeat == 1) {
mpd_info.repeat = "On";
} else {
mpd_info.repeat = "";
}
/* if (status->error) {
printf("error: %s\n", status->error);
} */
switch (status->state) {
case MPD_STATUS_STATE_PLAY:
mpd_info.status = "Playing";
break;
case MPD_STATUS_STATE_STOP:
mpd_info.status = "Stopped";
break;
case MPD_STATUS_STATE_PAUSE:
mpd_info.status = "Paused";
break;
default:
mpd_info.status = "";
break;
}
if (status->state == MPD_STATUS_STATE_PLAY ||
status->state == MPD_STATUS_STATE_PAUSE) {
mpd_info.is_playing = 1;
mpd_info.bitrate = status->bitRate;
mpd_info.progress =
((0 != status->totalTime)
? static_cast<float>(status->elapsedTime) / status->totalTime
: 0.0);
mpd_info.elapsed = status->elapsedTime;
mpd_info.length = status->totalTime;
} else {
mpd_info.progress = 0;
mpd_info.is_playing = 0;
mpd_info.elapsed = 0;
}
if (conn->error != 0) {
// fprintf(stderr, "%s\n", conn->errorStr);
mpd_closeConnection(conn);
conn = nullptr;
break;
}
mpd_sendCurrentSongCommand(conn);
while ((entity = mpd_getNextInfoEntity(conn)) != nullptr) {
mpd_Song *song = entity->info.song;
if (entity->type != MPD_INFO_ENTITY_TYPE_SONG) {
mpd_freeInfoEntity(entity);
continue;
}
#define SETSTRING(a, b) \
if (b) \
(a) = b; \
else \
(a) = "";
SETSTRING(mpd_info.album, song->album);
SETSTRING(mpd_info.albumartist, song->albumartist);
SETSTRING(mpd_info.artist, song->artist);
SETSTRING(mpd_info.comment, song->comment);
SETSTRING(mpd_info.date, song->date);
SETSTRING(mpd_info.file, song->file);
SETSTRING(mpd_info.name, song->name);
SETSTRING(mpd_info.title, song->title);
SETSTRING(mpd_info.track, song->track);
if (entity != nullptr) {
mpd_freeInfoEntity(entity);
entity = nullptr;
}
}
mpd_finishCommand(conn);
if ((conn != nullptr) && (conn->error != 0)) {
// fprintf(stderr, "%s\n", conn->errorStr);
mpd_closeConnection(conn);
conn = nullptr;
break;
}
if (conn->error != 0) {
// fprintf(stderr, "%s\n", conn->errorStr);
mpd_closeConnection(conn);
conn = nullptr;
break;
}
mpd_freeStatus(status);
/* if (conn) {
mpd_closeConnection(conn);
conn = 0;
} */
} while (0);
std::lock_guard<std::mutex> lock(Base::result_mutex);
result = mpd_info; // don't forget to save results!
}
mpd_result get_mpd() {
uint32_t period = std::max(
lround(music_player_interval.get(*state) / active_update_interval()), 1l);
return conky::register_cb<mpd_cb>(period)->get_result_copy();
}
} // namespace
static inline void format_media_player_time(char *buf, const int size,
int seconds) {
int days, hours, minutes;
if (times_in_seconds.get(*state)) {
snprintf(buf, size, "%d", seconds);
return;
}
days = seconds / (24 * 60 * 60);
seconds %= (24 * 60 * 60);
hours = seconds / (60 * 60);
seconds %= (60 * 60);
minutes = seconds / 60;
seconds %= 60;
if (days > 0) {
snprintf(buf, size, "%i days %i:%02i:%02i", days, hours, minutes, seconds);
} else if (hours > 0) {
snprintf(buf, size, "%i:%02i:%02i", hours, minutes, seconds);
} else {
snprintf(buf, size, "%i:%02i", minutes, seconds);
}
}
void print_mpd_elapsed(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
format_media_player_time(p, p_max_size, get_mpd().elapsed);
}
void print_mpd_length(struct text_object *obj, char *p,
unsigned int p_max_size) {
(void)obj;
format_media_player_time(p, p_max_size, get_mpd().length);
}
uint8_t mpd_percentage(struct text_object *obj) {
(void)obj;
return round_to_positive_int(get_mpd().progress * 100.0f);
}
double mpd_barval(struct text_object *obj) {
(void)obj;
return get_mpd().progress;
}
void print_mpd_smart(struct text_object *obj, char *p,
unsigned int p_max_size) {
const mpd_result &mpd_info = get_mpd();
int len = obj->data.i;
if (len == 0 || static_cast<unsigned int>(len) > p_max_size) {
len = p_max_size;
}
memset(p, 0, p_max_size);
if ((static_cast<unsigned int>(!mpd_info.artist.empty()) != 0u) &&
(static_cast<unsigned int>(!mpd_info.title.empty()) != 0u)) {
snprintf(p, len, "%s - %s", mpd_info.artist.c_str(),
mpd_info.title.c_str());
} else if (static_cast<unsigned int>(!get_mpd().title.empty()) != 0u) {
snprintf(p, len, "%s", mpd_info.title.c_str());
} else if (static_cast<unsigned int>(!mpd_info.artist.empty()) != 0u) {
snprintf(p, len, "%s", mpd_info.artist.c_str());
} else if (static_cast<unsigned int>(!mpd_info.file.empty()) != 0u) {
snprintf(p, len, "%s", mpd_info.file.c_str());
} else {
*p = 0;
}
}
int check_mpd_playing(struct text_object *obj) {
(void)obj;
return get_mpd().is_playing;
}
#define MPD_PRINT_GENERATOR(name, fmt, acc) \
void print_mpd_##name(struct text_object *obj, char *p, \
unsigned int p_max_size) { \
if (obj->data.i && (unsigned int)obj->data.i < p_max_size) \
p_max_size = obj->data.i; \
snprintf(p, p_max_size, fmt, get_mpd().name acc); \
}
MPD_PRINT_GENERATOR(album, "%s", .c_str())
MPD_PRINT_GENERATOR(albumartist, "%s", .c_str())
MPD_PRINT_GENERATOR(artist, "%s", .c_str())
MPD_PRINT_GENERATOR(bitrate, "%d", )
MPD_PRINT_GENERATOR(comment, "%s", .c_str())
MPD_PRINT_GENERATOR(date, "%s", .c_str())
MPD_PRINT_GENERATOR(file, "%s", .c_str())
MPD_PRINT_GENERATOR(name, "%s", .c_str())
MPD_PRINT_GENERATOR(random, "%s", .c_str())
MPD_PRINT_GENERATOR(repeat, "%s", .c_str())
MPD_PRINT_GENERATOR(status, "%s", .c_str())
MPD_PRINT_GENERATOR(title, "%s", .c_str())
MPD_PRINT_GENERATOR(track, "%s", .c_str())
MPD_PRINT_GENERATOR(vol, "%d", )
#undef MPD_PRINT_GENERATOR
| 11,460
|
C++
|
.cc
| 356
| 27.230337
| 80
| 0.609502
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
22,558
|
user.cc
|
brndnmtthws_conky/src/user.cc
|
/*
*
* Conky, a system monitor, based on torsmo
*
* Any original torsmo code is licensed under the BSD license
*
* All code written since the fork of torsmo is licensed under the GPL
*
* Please see COPYING for details
*
* Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
* Copyright (c) 2005-2024 Brenden Matthews, Philip Kovacs, et. al.
* (see AUTHORS)
* 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 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 <config.h>
#include <grp.h>
#include <pwd.h>
#include <cerrno>
#include <memory>
#include "conky.h"
#include "logging.h"
void print_uid_name(struct text_object *obj, char *p, unsigned int p_max_size) {
struct passwd *pw;
uid_t uid;
char *firstinvalid;
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
generate_text_internal(objbuf.get(), max_user_text.get(*state), *obj->sub);
errno = 0;
uid = strtol(objbuf.get(), &firstinvalid, 10);
if (errno == 0 && objbuf.get() != firstinvalid) {
pw = getpwuid(uid);
if (pw != nullptr) {
snprintf(p, p_max_size, "%s", pw->pw_name);
} else {
NORM_ERR("The uid %d doesn't exist", uid);
}
} else {
NORM_ERR("$uid_name didn't receive a uid as argument");
}
}
void print_gid_name(struct text_object *obj, char *p, unsigned int p_max_size) {
struct group *grp;
gid_t gid;
char *firstinvalid;
std::unique_ptr<char[]> objbuf(new char[max_user_text.get(*state)]);
generate_text_internal(objbuf.get(), max_user_text.get(*state), *obj->sub);
errno = 0;
gid = strtol(objbuf.get(), &firstinvalid, 10);
if (errno == 0 && objbuf.get() != firstinvalid) {
grp = getgrgid(gid);
if (grp != nullptr) {
snprintf(p, p_max_size, "%s", grp->gr_name);
} else {
NORM_ERR("The gid %d doesn't exist", gid);
}
} else {
NORM_ERR("$gid_name didn't receive a gid as argument");
}
}
| 2,484
|
C++
|
.cc
| 73
| 31.123288
| 80
| 0.685393
|
brndnmtthws/conky
| 7,161
| 615
| 75
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.