repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
dorinbotan/M1280-Board-Drivers
|
Clock/Clock/spi.c
|
#include "spi.h"
#include <avr/interrupt.h>
void spi_init(uint8_t data_order,
uint8_t mode,
uint8_t clock_polarity,
uint8_t clock_phase)
{
uint8_t has_callback_function = 0;
// MOSI SCK SS
DDRB |= _BV(DDB2) | _BV(DDB1) | _BV(DDB0);
SPCR = (
(has_callback_function << SPIE) |
_BV(SPE) |
(data_order << DORD) |
(mode << MSTR) |
(clock_polarity << CPOL) |
(clock_phase << CPHA) |
_BV(SPR1) |
_BV(SPR0)
);
}
uint8_t spi_send_byte(uint8_t value)
{
uint8_t received_byte;
uint8_t tmp = SREG;
cli();
SPDR = value;
while(!(SPSR & _BV(SPIF))){}
received_byte = SPDR;
sei();
SREG = tmp;
return received_byte;
}
|
dorinbotan/M1280-Board-Drivers
|
HandIn/display.h
|
<gh_stars>0
#ifndef DISPLAY_H_
#define DISPLAY_H_
#include <avr/io.h>
// void init_7_segment(); (No need for this)
void display_7_segment(float value, uint8_t no_of_decimals);
#endif /* DISPLAY_H_ */
|
dorinbotan/M1280-Board-Drivers
|
twi.h
|
<gh_stars>0
#ifndef TWI_H_
#define TWI_H_
#include <avr/io.h>
uint8_t twi_init(long sclFrequency);
void twi_write(uint8_t device, uint8_t address, uint8_t *data, int len, void (*callback)(uint8_t*));
void twi_read(uint8_t device, uint8_t address, int len, void (*callback)(uint8_t*));
#endif /* TWI_H_ */
|
krishnaa208/Qt-Calculator
|
src/Calculator/mainwindow.h
|
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
private slots:
void digitPressed();
void dotPressed();
void unaryPressed();
void clearPressed();
void equalPressed();
void binaryPressed();
};
#endif // MAINWINDOW_H
|
krishnaa208/Qt-Calculator
|
src/Calculator/release/moc_predefs.h
|
#define __DBL_MIN_EXP__ (-1021)
#define __cpp_attributes 200809
#define __UINT_LEAST16_MAX__ 65535
#define __ATOMIC_ACQUIRE 2
#define __FLT_MIN__ 1.17549435082228750797e-38F
#define __GCC_IEC_559_COMPLEX 2
#define __UINT_LEAST8_TYPE__ unsigned char
#define _WIN32 1
#define __INTMAX_C(c) c ## LL
#define __CHAR_BIT__ 8
#define __UINT8_MAX__ 255
#define __i586 1
#define __WINT_MAX__ 65535
#define __cpp_static_assert 200410
#define __ORDER_LITTLE_ENDIAN__ 1234
#define __SIZE_MAX__ 4294967295U
#define __WCHAR_MAX__ 65535
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 1
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 1
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 1
#define __DBL_DENORM_MIN__ double(4.94065645841246544177e-324L)
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 1
#define __GCC_ATOMIC_CHAR_LOCK_FREE 2
#define __GCC_IEC_559 2
#define __FLT_EVAL_METHOD__ 2
#define __cpp_binary_literals 201304
#define __GCC_ATOMIC_CHAR32_T_LOCK_FREE 2
#define __cpp_variadic_templates 200704
#define __UINT_FAST64_MAX__ 18446744073709551615ULL
#define __SIG_ATOMIC_TYPE__ int
#define __DBL_MIN_10_EXP__ (-307)
#define __FINITE_MATH_ONLY__ 0
#define __GNUC_PATCHLEVEL__ 3
#define __UINT_FAST8_MAX__ 255
#define __has_include(STR) __has_include__(STR)
#define _stdcall __attribute__((__stdcall__))
#define __DEC64_MAX_EXP__ 385
#define __INT8_C(c) c
#define __UINT_LEAST64_MAX__ 18446744073709551615ULL
#define __SHRT_MAX__ 32767
#define __LDBL_MAX__ 1.18973149535723176502e+4932L
#define __UINT_LEAST8_MAX__ 255
#define __GCC_ATOMIC_BOOL_LOCK_FREE 2
#define __UINTMAX_TYPE__ long long unsigned int
#define __DEC32_EPSILON__ 1E-6DF
#define __OPTIMIZE__ 1
#define __UINT32_MAX__ 4294967295U
#define __GXX_EXPERIMENTAL_CXX0X__ 1
#define __LDBL_MAX_EXP__ 16384
#define __WINT_MIN__ 0
#define __SCHAR_MAX__ 127
#define __WCHAR_MIN__ 0
#define __INT64_C(c) c ## LL
#define __DBL_DIG__ 15
#define __GCC_ATOMIC_POINTER_LOCK_FREE 2
#define __SIZEOF_INT__ 4
#define __SIZEOF_POINTER__ 4
#define __GCC_ATOMIC_CHAR16_T_LOCK_FREE 2
#define __USER_LABEL_PREFIX__ _
#define __STDC_HOSTED__ 1
#define __WIN32 1
#define __LDBL_HAS_INFINITY__ 1
#define __FLT_EPSILON__ 1.19209289550781250000e-7F
#define __GXX_WEAK__ 1
#define __LDBL_MIN__ 3.36210314311209350626e-4932L
#define __DEC32_MAX__ 9.999999E96DF
#define __MINGW32__ 1
#define __INT32_MAX__ 2147483647
#define __SIZEOF_LONG__ 4
#define __UINT16_C(c) c
#define __DECIMAL_DIG__ 21
#define __has_include_next(STR) __has_include_next__(STR)
#define __LDBL_HAS_QUIET_NAN__ 1
#define __GNUC__ 4
#define _cdecl __attribute__((__cdecl__))
#define __GXX_RTTI 1
#define __FLT_HAS_DENORM__ 1
#define __SIZEOF_LONG_DOUBLE__ 12
#define __BIGGEST_ALIGNMENT__ 16
#define __DBL_MAX__ double(1.79769313486231570815e+308L)
#define _thiscall __attribute__((__thiscall__))
#define __cpp_raw_strings 200710
#define __INT_FAST32_MAX__ 2147483647
#define __WINNT 1
#define __DBL_HAS_INFINITY__ 1
#define __INT64_MAX__ 9223372036854775807LL
#define __WINNT__ 1
#define __DEC32_MIN_EXP__ (-94)
#define __INT_FAST16_TYPE__ short int
#define _fastcall __attribute__((__fastcall__))
#define __LDBL_HAS_DENORM__ 1
#define __cplusplus 201103L
#define __DEC128_MAX__ 9.999999999999999999999999999999999E6144DL
#define __INT_LEAST32_MAX__ 2147483647
#define __DEC32_MIN__ 1E-95DF
#define __pentium 1
#define __DEPRECATED 1
#define __DBL_MAX_EXP__ 1024
#define __DEC128_EPSILON__ 1E-33DL
#define __ATOMIC_HLE_RELEASE 131072
#define __WIN32__ 1
#define __PTRDIFF_MAX__ 2147483647
#define __ATOMIC_HLE_ACQUIRE 65536
#define __GNUG__ 4
#define __LONG_LONG_MAX__ 9223372036854775807LL
#define __SIZEOF_SIZE_T__ 4
#define __cpp_rvalue_reference 200610
#define __SIZEOF_WINT_T__ 2
#define __GCC_HAVE_DWARF2_CFI_ASM 1
#define __GXX_ABI_VERSION 1002
#define __FLT_MIN_EXP__ (-125)
#define __cpp_lambdas 200907
#define __INT_FAST64_TYPE__ long long int
#define __DBL_MIN__ double(2.22507385850720138309e-308L)
#define __FLT_MIN_10_EXP__ (-37)
#define __DECIMAL_BID_FORMAT__ 1
#define __GXX_TYPEINFO_EQUALITY_INLINE 0
#define __DEC128_MIN__ 1E-6143DL
#define __REGISTER_PREFIX__
#define __UINT16_MAX__ 65535
#define __DBL_HAS_DENORM__ 1
#define __cdecl __attribute__((__cdecl__))
#define __UINT8_TYPE__ unsigned char
#define __i386 1
#define __FLT_MANT_DIG__ 24
#define __i586__ 1
#define __VERSION__ "4.9.3"
#define __UINT64_C(c) c ## ULL
#define __cpp_unicode_characters 200704
#define __GCC_ATOMIC_INT_LOCK_FREE 2
#define _X86_ 1
#define __FLOAT_WORD_ORDER__ __ORDER_LITTLE_ENDIAN__
#define __INT32_C(c) c
#define __DEC64_EPSILON__ 1E-15DD
#define __ORDER_PDP_ENDIAN__ 3412
#define __DEC128_MIN_EXP__ (-6142)
#define __code_model_32__ 1
#define __INT_FAST32_TYPE__ int
#define __UINT_LEAST16_TYPE__ short unsigned int
#define __INT16_MAX__ 32767
#define __i386__ 1
#define __SIZE_TYPE__ unsigned int
#define __UINT64_MAX__ 18446744073709551615ULL
#define __INT8_TYPE__ signed char
#define __FLT_RADIX__ 2
#define __INT_LEAST16_TYPE__ short int
#define __LDBL_EPSILON__ 1.08420217248550443401e-19L
#define __UINTMAX_C(c) c ## ULL
#define __SIG_ATOMIC_MAX__ 2147483647
#define __GCC_ATOMIC_WCHAR_T_LOCK_FREE 2
#define __SIZEOF_PTRDIFF_T__ 4
#define __pentium__ 1
#define __DEC32_SUBNORMAL_MIN__ 0.000001E-95DF
#define __MSVCRT__ 1
#define __INT_FAST16_MAX__ 32767
#define __UINT_FAST32_MAX__ 4294967295U
#define __UINT_LEAST64_TYPE__ long long unsigned int
#define __FLT_HAS_QUIET_NAN__ 1
#define __FLT_MAX_10_EXP__ 38
#define __LONG_MAX__ 2147483647L
#define __DEC128_SUBNORMAL_MIN__ 0.000000000000000000000000000000001E-6143DL
#define __FLT_HAS_INFINITY__ 1
#define __cpp_unicode_literals 200710
#define __UINT_FAST16_TYPE__ short unsigned int
#define __DEC64_MAX__ 9.999999999999999E384DD
#define __CHAR16_TYPE__ short unsigned int
#define __PRAGMA_REDEFINE_EXTNAME 1
#define __INT_LEAST16_MAX__ 32767
#define __DEC64_MANT_DIG__ 16
#define __UINT_LEAST32_MAX__ 4294967295U
#define __GCC_ATOMIC_LONG_LOCK_FREE 2
#define __INT_LEAST64_TYPE__ long long int
#define __INT16_TYPE__ short int
#define __INT_LEAST8_TYPE__ signed char
#define __DEC32_MAX_EXP__ 97
#define __INT_FAST8_MAX__ 127
#define __INTPTR_MAX__ 2147483647
#define __GXX_MERGED_TYPEINFO_NAMES 0
#define __stdcall __attribute__((__stdcall__))
#define __EXCEPTIONS 1
#define __LDBL_MANT_DIG__ 64
#define __DBL_HAS_QUIET_NAN__ 1
#define __SIG_ATOMIC_MIN__ (-__SIG_ATOMIC_MAX__ - 1)
#define __INTPTR_TYPE__ int
#define __UINT16_TYPE__ short unsigned int
#define __WCHAR_TYPE__ short unsigned int
#define __SIZEOF_FLOAT__ 4
#define __UINTPTR_MAX__ 4294967295U
#define __DEC64_MIN_EXP__ (-382)
#define __cpp_decltype 200707
#define __INT_FAST64_MAX__ 9223372036854775807LL
#define __GCC_ATOMIC_TEST_AND_SET_TRUEVAL 1
#define __FLT_DIG__ 6
#define __UINT_FAST64_TYPE__ long long unsigned int
#define __INT_MAX__ 2147483647
#define WIN32 1
#define __INT64_TYPE__ long long int
#define __FLT_MAX_EXP__ 128
#define __DBL_MANT_DIG__ 53
#define __INT_LEAST64_MAX__ 9223372036854775807LL
#define __DEC64_MIN__ 1E-383DD
#define __WINT_TYPE__ short unsigned int
#define __UINT_LEAST32_TYPE__ unsigned int
#define __SIZEOF_SHORT__ 2
#define __LDBL_MIN_EXP__ (-16381)
#define __INT_LEAST8_MAX__ 127
#define __WCHAR_UNSIGNED__ 1
#define __LDBL_MAX_10_EXP__ 4932
#define __ATOMIC_RELAXED 0
#define __DBL_EPSILON__ double(2.22044604925031308085e-16L)
#define __thiscall __attribute__((__thiscall__))
#define __UINT8_C(c) c
#define __INT_LEAST32_TYPE__ int
#define __SIZEOF_WCHAR_T__ 2
#define __UINT64_TYPE__ long long unsigned int
#define __INT_FAST8_TYPE__ signed char
#define __fastcall __attribute__((__fastcall__))
#define __GNUC_STDC_INLINE__ 1
#define __DBL_DECIMAL_DIG__ 17
#define __DEC_EVAL_METHOD__ 2
#define __ORDER_BIG_ENDIAN__ 4321
#define __UINT32_C(c) c ## U
#define __INTMAX_MAX__ 9223372036854775807LL
#define __cpp_alias_templates 200704
#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
#define WINNT 1
#define __FLT_DENORM_MIN__ 1.40129846432481707092e-45F
#define __INT8_MAX__ 127
#define __UINT_FAST32_TYPE__ unsigned int
#define __CHAR32_TYPE__ unsigned int
#define __FLT_MAX__ 3.40282346638528859812e+38F
#define __cpp_constexpr 200704
#define __INT32_TYPE__ int
#define __SIZEOF_DOUBLE__ 8
#define __INTMAX_TYPE__ long long int
#define i386 1
#define _INTEGRAL_MAX_BITS 64
#define __DEC128_MAX_EXP__ 6145
#define __ATOMIC_CONSUME 1
#define __GNUC_MINOR__ 9
#define __UINTMAX_MAX__ 18446744073709551615ULL
#define __DEC32_MANT_DIG__ 7
#define __DBL_MAX_10_EXP__ 308
#define __LDBL_DENORM_MIN__ 3.64519953188247460253e-4951L
#define __INT16_C(c) c
#define __STDC__ 1
#define __PTRDIFF_TYPE__ int
#define __ATOMIC_SEQ_CST 5
#define __UINT32_TYPE__ unsigned int
#define __UINTPTR_TYPE__ unsigned int
#define __DEC64_SUBNORMAL_MIN__ 0.000000000000001E-383DD
#define __DEC128_MANT_DIG__ 34
#define __LDBL_MIN_10_EXP__ (-4931)
#define __SIZEOF_LONG_LONG__ 8
#define __cpp_user_defined_literals 200809
#define __GCC_ATOMIC_LLONG_LOCK_FREE 2
#define __LDBL_DIG__ 18
#define __FLT_DECIMAL_DIG__ 9
#define __UINT_FAST16_MAX__ 65535
#define __GCC_ATOMIC_SHORT_LOCK_FREE 2
#define __UINT_FAST8_TYPE__ unsigned char
#define __ATOMIC_ACQ_REL 4
#define __ATOMIC_RELEASE 3
#define __declspec(x) __attribute__((x))
|
krishnaa208/Qt-Calculator
|
src/Calculator/ui_mainwindow.h
|
/********************************************************************************
** Form generated from reading UI file 'mainwindow.ui'
**
** Created by: Qt User Interface Compiler version 5.9.1
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_MAINWINDOW_H
#define UI_MAINWINDOW_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_MainWindow
{
public:
QWidget *centralWidget;
QPushButton *c;
QLabel *label;
QPushButton *mp;
QPushButton *percent;
QPushButton *divide;
QPushButton *multiply;
QPushButton *_7;
QPushButton *_8;
QPushButton *_9;
QPushButton *minus;
QPushButton *_4;
QPushButton *_5;
QPushButton *_6;
QPushButton *plus;
QPushButton *_1;
QPushButton *_2;
QPushButton *_3;
QPushButton *equal;
QPushButton *_0;
QPushButton *dot;
void setupUi(QMainWindow *MainWindow)
{
if (MainWindow->objectName().isEmpty())
MainWindow->setObjectName(QStringLiteral("MainWindow"));
MainWindow->setEnabled(true);
MainWindow->resize(161, 261);
centralWidget = new QWidget(MainWindow);
centralWidget->setObjectName(QStringLiteral("centralWidget"));
c = new QPushButton(centralWidget);
c->setObjectName(QStringLiteral("c"));
c->setGeometry(QRect(0, 60, 41, 41));
c->setStyleSheet(QLatin1String("QPushButton {\n"
" background-color: rgb(215, 215, 215);\n"
" border: 1px solid gray;\n"
"}\n"
"QPushButton:pressed {\n"
" background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n"
" stop: 0 #BEBEBE, stop: 1 #D7D7D7);\n"
"}"));
label = new QLabel(centralWidget);
label->setObjectName(QStringLiteral("label"));
label->setGeometry(QRect(0, 0, 161, 61));
label->setAutoFillBackground(false);
label->setStyleSheet(QLatin1String("QLabel {\n"
" qproperty-alignment: 'AlignVCenter | AlignRight';\n"
" border: 1px solid gray;\n"
"}\n"
"\n"
"background-color : white;"));
mp = new QPushButton(centralWidget);
mp->setObjectName(QStringLiteral("mp"));
mp->setGeometry(QRect(40, 60, 41, 41));
mp->setStyleSheet(QLatin1String("QPushButton {\n"
" background-color: rgb(215, 215, 215);\n"
" border: 1px solid gray;\n"
"}\n"
"QPushButton:pressed {\n"
" background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n"
" stop: 0 #BEBEBE, stop: 1 #D7D7D7);\n"
"}"));
percent = new QPushButton(centralWidget);
percent->setObjectName(QStringLiteral("percent"));
percent->setGeometry(QRect(80, 60, 41, 41));
percent->setStyleSheet(QLatin1String("QPushButton {\n"
" background-color: rgb(215, 215, 215);\n"
" border: 1px solid gray;\n"
"}\n"
"QPushButton:pressed {\n"
" background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n"
" stop: 0 #BEBEBE, stop: 1 #D7D7D7);\n"
"}"));
divide = new QPushButton(centralWidget);
divide->setObjectName(QStringLiteral("divide"));
divide->setGeometry(QRect(120, 60, 41, 41));
divide->setStyleSheet(QLatin1String("QPushButton {\n"
" background-color: rgb(255, 151, 57);\n"
" color: white; \n"
" border: 1px solid gray;\n"
"}\n"
"\n"
"QPushButton:pressed {\n"
" background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n"
" stop: 0 #FF7832, stop: 1 #FF9739);\n"
"}"));
multiply = new QPushButton(centralWidget);
multiply->setObjectName(QStringLiteral("multiply"));
multiply->setGeometry(QRect(120, 100, 41, 41));
multiply->setStyleSheet(QLatin1String("QPushButton {\n"
" background-color: rgb(255, 151, 57);\n"
" color: white; \n"
" border: 1px solid gray;\n"
"}\n"
"\n"
"QPushButton:pressed {\n"
" background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n"
" stop: 0 #FF7832, stop: 1 #FF9739);\n"
"}"));
_7 = new QPushButton(centralWidget);
_7->setObjectName(QStringLiteral("_7"));
_7->setGeometry(QRect(0, 100, 41, 41));
_7->setStyleSheet(QLatin1String("QPushButton {\n"
" border: 1px solid gray;\n"
"}\n"
"QPushButton:pressed {\n"
" background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n"
" stop: 0 #dadbde, stop: 1 #f6f7fa);\n"
"}"));
_8 = new QPushButton(centralWidget);
_8->setObjectName(QStringLiteral("_8"));
_8->setGeometry(QRect(40, 100, 41, 41));
_8->setStyleSheet(QLatin1String("QPushButton {\n"
" border: 1px solid gray;\n"
"}\n"
"QPushButton:pressed {\n"
" background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n"
" stop: 0 #dadbde, stop: 1 #f6f7fa);\n"
"}"));
_9 = new QPushButton(centralWidget);
_9->setObjectName(QStringLiteral("_9"));
_9->setGeometry(QRect(80, 100, 41, 41));
_9->setStyleSheet(QLatin1String("QPushButton {\n"
" border: 1px solid gray;\n"
"}\n"
"QPushButton:pressed {\n"
" background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n"
" stop: 0 #dadbde, stop: 1 #f6f7fa);\n"
"}"));
minus = new QPushButton(centralWidget);
minus->setObjectName(QStringLiteral("minus"));
minus->setGeometry(QRect(120, 140, 41, 41));
minus->setStyleSheet(QLatin1String("QPushButton {\n"
" background-color: rgb(255, 151, 57);\n"
" color: white; \n"
" border: 1px solid gray;\n"
"}\n"
"\n"
"QPushButton:pressed {\n"
" background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n"
" stop: 0 #FF7832, stop: 1 #FF9739);\n"
"}"));
_4 = new QPushButton(centralWidget);
_4->setObjectName(QStringLiteral("_4"));
_4->setGeometry(QRect(0, 140, 41, 41));
_4->setStyleSheet(QLatin1String("QPushButton {\n"
" border: 1px solid gray;\n"
"}\n"
"QPushButton:pressed {\n"
" background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n"
" stop: 0 #dadbde, stop: 1 #f6f7fa);\n"
"}"));
_5 = new QPushButton(centralWidget);
_5->setObjectName(QStringLiteral("_5"));
_5->setGeometry(QRect(40, 140, 41, 41));
_5->setStyleSheet(QLatin1String("QPushButton {\n"
" border: 1px solid gray;\n"
"}\n"
"QPushButton:pressed {\n"
" background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n"
" stop: 0 #dadbde, stop: 1 #f6f7fa);\n"
"}"));
_6 = new QPushButton(centralWidget);
_6->setObjectName(QStringLiteral("_6"));
_6->setGeometry(QRect(80, 140, 41, 41));
_6->setStyleSheet(QLatin1String("QPushButton {\n"
" border: 1px solid gray;\n"
"}\n"
"QPushButton:pressed {\n"
" background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n"
" stop: 0 #dadbde, stop: 1 #f6f7fa);\n"
"}"));
plus = new QPushButton(centralWidget);
plus->setObjectName(QStringLiteral("plus"));
plus->setGeometry(QRect(120, 180, 41, 41));
plus->setStyleSheet(QLatin1String("QPushButton {\n"
" background-color: rgb(255, 151, 57);\n"
" color: white; \n"
" border: 1px solid gray;\n"
"}\n"
"\n"
"QPushButton:pressed {\n"
" background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n"
" stop: 0 #FF7832, stop: 1 #FF9739);\n"
"}"));
_1 = new QPushButton(centralWidget);
_1->setObjectName(QStringLiteral("_1"));
_1->setGeometry(QRect(0, 180, 41, 41));
_1->setStyleSheet(QLatin1String("QPushButton {\n"
" border: 1px solid gray;\n"
"}\n"
"QPushButton:pressed {\n"
" background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n"
" stop: 0 #dadbde, stop: 1 #f6f7fa);\n"
"}"));
_2 = new QPushButton(centralWidget);
_2->setObjectName(QStringLiteral("_2"));
_2->setGeometry(QRect(40, 180, 41, 41));
_2->setStyleSheet(QLatin1String("QPushButton {\n"
" border: 1px solid gray;\n"
"}\n"
"QPushButton:pressed {\n"
" background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n"
" stop: 0 #dadbde, stop: 1 #f6f7fa);\n"
"}"));
_3 = new QPushButton(centralWidget);
_3->setObjectName(QStringLiteral("_3"));
_3->setGeometry(QRect(80, 180, 41, 41));
_3->setStyleSheet(QLatin1String("QPushButton {\n"
" border: 1px solid gray;\n"
"}\n"
"QPushButton:pressed {\n"
" background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n"
" stop: 0 #dadbde, stop: 1 #f6f7fa);\n"
"}"));
equal = new QPushButton(centralWidget);
equal->setObjectName(QStringLiteral("equal"));
equal->setGeometry(QRect(120, 220, 41, 41));
equal->setStyleSheet(QLatin1String("QPushButton {\n"
" background-color: rgb(255, 151, 57);\n"
" color: white; \n"
" border: 1px solid gray;\n"
"}\n"
"\n"
"QPushButton:pressed {\n"
" background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n"
" stop: 0 #FF7832, stop: 1 #FF9739);\n"
"}"));
_0 = new QPushButton(centralWidget);
_0->setObjectName(QStringLiteral("_0"));
_0->setGeometry(QRect(0, 220, 81, 41));
_0->setStyleSheet(QLatin1String("QPushButton {\n"
" border: 1px solid gray;\n"
"}\n"
"QPushButton:pressed {\n"
" background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n"
" stop: 0 #dadbde, stop: 1 #f6f7fa);\n"
"}"));
dot = new QPushButton(centralWidget);
dot->setObjectName(QStringLiteral("dot"));
dot->setGeometry(QRect(80, 220, 41, 41));
dot->setStyleSheet(QLatin1String("QPushButton {\n"
" background-color: rgb(215, 215, 215);\n"
" border: 1px solid gray;\n"
"}\n"
"QPushButton:pressed {\n"
" background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n"
" stop: 0 #BEBEBE, stop: 1 #D7D7D7);\n"
"}"));
MainWindow->setCentralWidget(centralWidget);
retranslateUi(MainWindow);
QMetaObject::connectSlotsByName(MainWindow);
} // setupUi
void retranslateUi(QMainWindow *MainWindow)
{
MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", Q_NULLPTR));
c->setText(QApplication::translate("MainWindow", "c", Q_NULLPTR));
label->setText(QString());
mp->setText(QApplication::translate("MainWindow", "+/_", Q_NULLPTR));
percent->setText(QApplication::translate("MainWindow", "%", Q_NULLPTR));
divide->setText(QApplication::translate("MainWindow", "\303\267", Q_NULLPTR));
multiply->setText(QApplication::translate("MainWindow", "x", Q_NULLPTR));
_7->setText(QApplication::translate("MainWindow", "7", Q_NULLPTR));
_8->setText(QApplication::translate("MainWindow", "8", Q_NULLPTR));
_9->setText(QApplication::translate("MainWindow", "9", Q_NULLPTR));
minus->setText(QApplication::translate("MainWindow", "-", Q_NULLPTR));
_4->setText(QApplication::translate("MainWindow", "4", Q_NULLPTR));
_5->setText(QApplication::translate("MainWindow", "5", Q_NULLPTR));
_6->setText(QApplication::translate("MainWindow", "6", Q_NULLPTR));
plus->setText(QApplication::translate("MainWindow", "+", Q_NULLPTR));
_1->setText(QApplication::translate("MainWindow", "1", Q_NULLPTR));
_2->setText(QApplication::translate("MainWindow", "2", Q_NULLPTR));
_3->setText(QApplication::translate("MainWindow", "3", Q_NULLPTR));
equal->setText(QApplication::translate("MainWindow", "=", Q_NULLPTR));
_0->setText(QApplication::translate("MainWindow", "0", Q_NULLPTR));
dot->setText(QApplication::translate("MainWindow", ".", Q_NULLPTR));
} // retranslateUi
};
namespace Ui {
class MainWindow: public Ui_MainWindow {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_MAINWINDOW_H
|
Phantasm-Studios/Phantasm-rml-plugin
|
src/rml_system.h
|
<reponame>Phantasm-Studios/Phantasm-rml-plugin
#pragma once
#include "engine/plugin.h"
namespace Lumix {
IPlugin* createRMLSystem(Engine& engine);
} // namespace Lumix
|
PoundXI/pxi-encode
|
pxi-encode.c
|
<reponame>PoundXI/pxi-encode
/*
* (c) Copyright 2019, <NAME> <<EMAIL>>
* This project is licensed under the terms of the MIT license.
*/
#include <stdio.h> // fprintf()
#include <string.h> // strlen(), strcmp()
#include <unistd.h> // optarg, optopt, optind
#include <ctype.h> // isprint()
#include <stdlib.h> // exit()
typedef enum
{
percent_encode,
double_percent_encode,
c_backslash
} encode_format_t;
char *_prog_name = NULL;
char *_prog_version = "0.1.0";
// https://www.gnu.org/software/libc/manual/html_node/Example-of-Getopt.html
// https://www.gnu.org/software/libc/manual/html_node/Using-Getopt.html#Using-Getopt
int _option_force_encode_all_chars = 0; // 1 force encode all characters, 0 for partly.
int _option_print_version = 0;
char *_option_encode_format = NULL; // encoding format type
char *_input_str = NULL; // string to encode
int _is_input_str_from_pipe = 0;
int parse_options(int argc, char **argv)
{
int index;
int c;
// getopt() for parse command options
// <char> = just a flag (no param).
// <char>: = param is required.
// <char>:: = param is optional.
while ((c = getopt(argc, argv, "vfe:")) != -1) {
switch (c) {
case 'v':
_option_print_version = 1;
break;
case 'f':
_option_force_encode_all_chars = 1;
break;
case 'e':
_option_encode_format = optarg;
break;
case '?':
if (optopt == 'e')
fprintf(stderr, "Option -%c requires an argument.\n", optopt);
else if (isprint(optopt))
// other printable character
fprintf(stderr, "Unknown option `-%c'.\n", optopt);
else
// non-printable character
fprintf(stderr, "Unknown option character `\\x%x'.\n", optopt);
return 0;
default:
return 0;
}
}
// if no stdin read from pipe
if (_is_input_str_from_pipe == 0) {
for (index = optind; index < argc; index++) {
// Non-option argument
_input_str = argv[index];
}
}
return 1;
}
int is_valid_uri_char(char c)
{
char *uri_valid_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~";
size_t valid_chars_len = strlen(uri_valid_chars);
for (size_t i = 0 ; i < valid_chars_len ; i++) {
if (uri_valid_chars[i] == c)
return 1;
}
return 0;
}
void encode_string(char *str, size_t str_len, encode_format_t encode_format)
{
if (str != NULL) {
for(int i = 0 ; i < str_len ; i++) {
switch (encode_format) {
case c_backslash: {
printf("\\x%02X", str[i]);
break;
}
case percent_encode: {
if (!is_valid_uri_char(str[i]) || _option_force_encode_all_chars != 0)
printf("%%%02X", str[i]);
else
printf("%c", str[i]);
break;
}
case double_percent_encode: {
if (!is_valid_uri_char(str[i]) || _option_force_encode_all_chars != 0)
printf("%%25%02X", str[i]);
else
printf("%c", str[i]);
break;
}
}
}
printf("\n");
}
}
void print_usage()
{
printf("PXI-ENCODE (v%s) - This program is a simple string encoder\n", _prog_version);
printf("(c) Copyright 2019, <NAME> <<EMAIL>>\n");
printf("This project is licensed under the terms of the MIT license.\n");
printf("\n");
printf("Usage:\n");
printf(" $ %s input_string -e encode_format [-f]\n", _prog_name);
printf(" Or\n");
printf(" $ printf input_string | %s -e encode_format [-f]\n", _prog_name);
printf("\n");
printf("Options:\n");
printf(" -v print program version\n");
printf("\n");
printf(" -e (required) encode format\n");
printf(" - c_backslash => \\x48\\x65\\x6C\\x6C\\x6F\\x20\\x57\\x6F\\x72\\x6C\\x64\\x21\n");
printf(" - percent_encode => Hello%%20World%%21\n");
printf(" - double_percent_encode => Hello%%2520World%%2521\n");
printf("\n");
printf(" -f (optional) force encode all characters\n");
printf("\n");
printf("Examples:\n");
printf(" $ %s \"Hello World\" -e c_backslash\n", _prog_name);
printf(" $ %s \"Hello World\" -e percent_encode\n", _prog_name);
printf(" $ %s \"Hello World\" -e percent_encode -f\n", _prog_name);
}
int main(int argc, char **argv)
{
// check stdin pipe
if (!isatty(fileno(stdin))) {
int i = 0;
char buf[10240];
// read all data from stdin
while ((buf[i++] = getchar()) != EOF);
// end string with null byte
buf[i-1] = '\0';
// copy char array to char pointer
_input_str = malloc(strlen(buf) + 1);
strcpy(_input_str, buf);
_is_input_str_from_pipe = 1;
}
_prog_name = argv[0];
// parse options
if (parse_options(argc, argv) == 0) {
exit(1);
}
if (_option_print_version == 1) {
printf("v%s\n", _prog_version);
exit(0);
}
// input string
if (_input_str == NULL) {
print_usage();
exit(2);
}
size_t input_str_len = strlen(_input_str);
// encode format
if (_option_encode_format == NULL) {
print_usage();
exit(3);
}
// https://www.gnu.org/software/libc/manual/html_node/String_002fArray-Comparison.html
// strcmp return 0 if two strings are equal.
if (strcmp(_option_encode_format, "percent_encode") == 0) {
encode_string(_input_str, input_str_len, percent_encode);
} else if (strcmp(_option_encode_format, "double_percent_encode") == 0) {
encode_string(_input_str, input_str_len, double_percent_encode);
} else if (strcmp(_option_encode_format, "c_backslash") == 0) {
encode_string(_input_str, input_str_len, c_backslash);
} else {
print_usage();
}
return 0;
}
|
Simba-Cream/SCARF
|
condition_containing_assignment_no_comments.c
|
int main(int argc, char *argv[])
{
int a, b;
bool same;
a = 1;
b = 2;
same = false;
if(a == b)
{
same = false;
}
if(a = b)
{
same = true;
}
}
|
Simba-Cream/SCARF
|
source_code_test.c
|
{
int a, b;
bool same;
same = false;
if (a == b) {
same = false;
}
if (a = b) {
same = true;
}
if (1 == b) {
}
if ('v' == b) {
}
if ("hello world" == b) {
}
}
|
Simba-Cream/SCARF
|
condition_containing_assignment.c
|
/*************************************************************************\
* Copyright (C) <NAME>, 2015. *
* *
* This program is free software. You may use, modify, and redistribute it *
* under the terms of the GNU General Public License as published by the *
* Free Software Foundation, either version 3 or (at your option) any *
* later version. This program is distributed without any warranty. See *
* the file COPYING.gpl-v3 for details. *
\*************************************************************************/
/* condition_containing_assignment.c
Assign a variable value to the value of another variable inside a
condtion.
*/
int main(int argc, char *argv[])
{
int a, b;
bool same;
a = 1;
b = 2;
same = false;
if(a == b)
{
same = false;
}
if(a = b)
{
same = true;
}
}
|
Simba-Cream/SCARF
|
assignment_in_condition_test.c
|
if ( a = 1 )
{ a = b ; }
|
Frankie-Sun/TPNS-Flutter-Plugin
|
ios/Classes/XgFlutterPlugin.h
|
<reponame>Frankie-Sun/TPNS-Flutter-Plugin<gh_stars>10-100
//
// XgFlutterPlugin.h
// XgFlutterPlugin
//
// Created by rockzuo on 2019/12/3.
// Copyright © 2019 XG of Tencent. All rights reserved.
//
#import <Flutter/Flutter.h>
/**
@brief TPNS Flutter Plugin
*/
@interface XgFlutterPlugin : NSObject<FlutterPlugin>
// channel调用iOS API
@property FlutterMethodChannel *channel;
@end
|
chunkhang/SCDebugBridge
|
SCDebugBridge/SCDebugBridge.h
|
//
// SCDebugBridge.h
// SCRNDemo
//
// Created by aevit on 2017/9/25.
// Copyright © 2017年 Facebook. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>
@interface SCDebugBridge : NSObject <RCTBridgeModule>
#ifdef DEBUG
/**
get the debug ip and port
@return eg: @{@"ip": @"127.0.0.1", @"port": @"8081"}
*/
+ (NSDictionary*)getIpAndPort;
+ (BOOL)requiresMainQueueSetup;
#endif
@end
|
stimulant/MS-Cube-SDK
|
DeployTool/DeployManager.h
|
<reponame>stimulant/MS-Cube-SDK
#pragma once
#include "DeployApp.h"
#include <vector>
#include <map>
#include <string>
class DeployManager
{
//std::vector<DeployApp*> mApps;
std::map<std::string, DeployApp*> mApps;
static DeployManager* mInstance;
public:
DeployManager(void);
~DeployManager(void);
static DeployManager* instance();
bool LoadFromRegistry();
bool SaveToRegistry();
std::map<std::string, DeployApp*>& GetApps() { return mApps; }
void AddDeployApp(std::string appName, std::string appDirectory, std::string appExecutable);
void ServerUpdate();
bool ServerSendAppListToClient(SOCKET clientSocket);
bool ServerCheckAppsOnClient(SOCKET clientSocket);
};
|
stimulant/MS-Cube-SDK
|
Common/SocketHelper.h
|
<reponame>stimulant/MS-Cube-SDK
#pragma once
#include <winsock.h>
class SocketHelper
{
public:
// Global
static bool StartWinsock();
static void StopWinsock();
static void CloseConnection(SOCKET& hSocket);
// Client
static bool ConnectToServer(SOCKET& hSocket, int PortNo, const char* IPAddress);
// Server
static bool CreateServerSocket(SOCKET& hServerSocket, int PortNo);
static bool WaitForClient(SOCKET& hServerSocket, SOCKET& hClientSocket);
};
|
stimulant/MS-Cube-SDK
|
DeployTool/resource.h
|
<reponame>stimulant/MS-Cube-SDK
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by DeployTool.rc
//
#define IDR_MANIFEST 1
#define IDC_ADDAPP 2
#define IDM_ABOUTBOX 0x0010
#define IDD_TAB_DIALOG 102
#define IDR_MAINFRAME 128
#define IDD_DIALOG_PAGE1 130
#define IDD_DIALOG_PAGE2 131
#define IDB_BITMAP_INTRO 132
#define IDS_ABOUTBOX 134
#define IDR_MENU1 135
#define IDD_DIALOG1 136
#define IDD_ABOUTBOX 136
#define IDR_MENU2 137
#define IDC_TAB 1000
#define IDC_CUSTOM1 1002
#define IDC_LIST1 1003
#define IDC_APPLIST 1003
#define IDC_EDIT1 1004
#define IDC_SERVER_EDIT 1004
#define IDC_COMBO1 1005
#define IDC_COMBO_APPS 1005
#define IDC_ 1006
#define IDC_REMOVEAPP 1006
#define ID__OPTIONS 32771
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 138
#define _APS_NEXT_COMMAND_VALUE 32772
#define _APS_NEXT_CONTROL_VALUE 1007
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
|
stimulant/MS-Cube-SDK
|
DeployTool/DeployToolDlg.h
|
// TabDlg.h : header file
//
#pragma once
#include "afxcmn.h"
#include "TabPageClient.h"
#include "TabPageServer.h"
#include "ibtabctrl.h"
#define WM_TRAY_ICON_NOTIFY_MESSAGE (WM_USER + 1)
// CDeployToolDlg dialog
class CDeployToolDlg : public CDialog
{
// Construction
public:
CDeployToolDlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
enum { IDD = IDD_TAB_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
HICON mhIcon;
// Generated message map functions
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnDestroy();
virtual BOOL OnInitDialog();
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
DECLARE_MESSAGE_MAP()
private:
BOOL mbMinimizeToTray;
BOOL mbTrayIconVisible;
NOTIFYICONDATA mnidIconData;
CMenu mmnuTrayMenu;
UINT mnDefaultMenuItem;
CTabPageClient *mpClientTab;
CTabPageServer *mpServerTab;
int mbInit;
afx_msg LRESULT OnTrayNotify(WPARAM wParam, LPARAM lParam);
public:
CibTabCtrl mctrlTAB;
afx_msg void OnMove(int x, int y);
afx_msg void OnShowWindow(BOOL bShow, UINT nStatus);
void TraySetMinimizeToTray(BOOL bMinimizeToTray = TRUE);
BOOL TraySetMenu(UINT nResourceID,UINT nDefaultPos=0);
BOOL TraySetMenu(HMENU hMenu,UINT nDefaultPos=0);
BOOL TraySetMenu(LPCTSTR lpszMenuName,UINT nDefaultPos=0);
BOOL TrayUpdate();
BOOL TrayShow();
BOOL TrayHide();
void TraySetToolTip(LPCTSTR lpszToolTip);
void TraySetIcon(HICON hIcon);
void TraySetIcon(UINT nResourceID);
void TraySetIcon(LPCTSTR lpszResourceName);
BOOL TrayIsVisible();
afx_msg void OnTcnSelchangeTab(NMHDR *pNMHDR, LRESULT *pResult);
};
|
stimulant/MS-Cube-SDK
|
DeployTool/TabPageClient.h
|
#pragma once
#include <string>
#include <vector>
// CTabPageClient dialog
class CTabPageClient : public CDialog
{
DECLARE_DYNAMIC(CTabPageClient)
bool mfExitThread;
SOCKET mSocket;
bool mConnected;
std::string mStrDeployServer;
int mDeployPort;
char* mRecvBuffer;
std::vector<std::string> mAppNames;
void ClientThread();
public:
CTabPageClient(CWnd* pParent = NULL); // standard constructor
virtual ~CTabPageClient();
BOOL OnInitDialog();
// Dialog Data
enum { IDD = IDD_DIALOG_PAGE1 };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnShowWindow(BOOL bShow, UINT nStatus);
afx_msg void OnChangeServerEdit();
void Startup();
void Shutdown();
};
|
stimulant/MS-Cube-SDK
|
DeployTool/DeployTool.h
|
// Tab.h : main header file for the PROJECT_NAME application
//
#pragma once
#ifndef __AFXWIN_H__
#error include 'stdafx.h' before including this file for PCH
#endif
#include "resource.h" // main symbols
// CDeployToolApp:
// See Tab.cpp for the implementation of this class
//
class CDeployToolApp : public CWinApp
{
public:
CDeployToolApp();
// Overrides
public:
virtual BOOL InitInstance();
// Implementation
DECLARE_MESSAGE_MAP()
};
extern CDeployToolApp theApp;
|
stimulant/MS-Cube-SDK
|
Common/RegistryHelper.h
|
<filename>Common/RegistryHelper.h
#pragma once
#include <string>
class RegistryHelper
{
public:
static bool RegistryHelper::GetBoolRegValue(HKEY hKey, const std::string &strValueName, bool &bValue, bool bDefaultValue);
static bool RegistryHelper::GetIntRegValue(HKEY hKey, const std::string &strValueName, int &iValue, int iDefaultValue);
static bool RegistryHelper::GetStringRegValue(HKEY hKey, const std::string &strValueName, std::string &strValue, const std::string &strDefaultValue);
static bool RegistryHelper::CreateRegistryKey(HKEY hKeyRoot, LPCTSTR pszSubKey, HKEY &hNewKey);
};
|
stimulant/MS-Cube-SDK
|
DeployTool/DeployApp.h
|
#pragma once
#include "DeployFile.h"
#include <vector>
#include <string >
class DeployApp
{
std::string mAppName;
std::string mAppDirectory;
std::string mAppExecutable;
std::vector<DeployFile*> mFiles;
bool AddDirectoryFiles(std::string rootDirectory, std::string directory);
public:
DeployApp(std::string appName, std::string appDirectory, std::string appExecutable);
~DeployApp(void);
bool ServerIsAppSelected(SOCKET clientSocket);
bool ServerUpdate(SOCKET clientSocket);
bool ServerKillApp(SOCKET clientSocket);
bool ServerStartApp(SOCKET clientSocket);
std::string GetAppName() const { return mAppName; }
std::string GetAppDirectory() const { return mAppDirectory; }
std::string GetAppExecutable() const { return mAppExecutable; }
};
|
stimulant/MS-Cube-SDK
|
DeployTool/DeployFile.h
|
#pragma once
#include <string>
class DeployFile
{
std::string mStrFileName;
std::string mStrPath;
WIN32_FIND_DATA mFindData;
LONGLONG mFileSize;
public:
DeployFile(std::string strFileName, std::string strPath, WIN32_FIND_DATA findData);
~DeployFile(void);
bool ServerSendToClient(std::string appName, std::string rootDirector, SOCKET hSocket);
bool ServerAskIfNeedsUpdate(std::string appName, std::string rootDirector, SOCKET hSocket, bool& doesNeedUpdate);
bool ServerStartApp(SOCKET clientSocket);
static bool ClientDoesFileNeedUpdate(SOCKET hSocket);
static bool ClientReceiveFile(SOCKET hSocket);
};
|
stimulant/MS-Cube-SDK
|
Common/KinectAPI.h
|
<filename>Common/KinectAPI.h<gh_stars>10-100
#pragma once
#include "Kinect.h"
#include <map>
#include <array>
enum CommandType
{
BodiesCommand,
DepthCommand,
InvalidCommand
};
class KinectAPI
{
public:
static int BodiesToBinary(UINT64* trackingIds, std::map< JointType, std::array<float, 3> > *jointPositions, std::map< JointType, std::array<float, 4> > *jointOrientations, std::pair<HandState, HandState> *handStates, int bodyCount, char* binary);
static int DepthToBinary(int nWidth, int nHeight, UINT16 *pBuffer, USHORT nMinDepth, USHORT nMaxDepth, char* binary);
static CommandType BinaryToCommandAndLength(char* binary, int& binaryLength);
static bool BinaryToDepth(char* binary, char* depthBuffer, int& width, int& height);
static bool BinaryToBodies(char* binary, UINT64* trackingIds, std::map< JointType, std::array<float, 3> > *jointPositions, std::map< JointType, std::array<float, 4> > *jointOrientations, std::pair<HandState, HandState> *handStates, int& bodyCount);
};
|
stimulant/MS-Cube-SDK
|
DeployTool/TabPageServer.h
|
#pragma once
#include <vector>
// CTabPageServer dialog
class CTabPageServer : public CDialog
{
DECLARE_DYNAMIC(CTabPageServer)
bool mfExitThread;
SOCKET mServerSocket;
std::vector<SOCKET> mClients;
int mDeployPort;
char* mSendBuffer;
char* mRecvBuffer;
bool mAppListChanged;
void ServerConnectThread();
void ServerUpdateThread();
public:
CTabPageServer(CWnd* pParent = NULL); // standard constructor
virtual ~CTabPageServer();
BOOL OnInitDialog();
// Dialog Data
enum { IDD = IDD_DIALOG_PAGE2 };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnBnClickedAddApp();
afx_msg void OnBnClickedRemoveApp();
afx_msg void OnShowWindow(BOOL bShow, UINT nStatus);
void Startup();
void Shutdown();
};
|
stimulant/MS-Cube-SDK
|
Common/KinectData.h
|
<reponame>stimulant/MS-Cube-SDK
#pragma once
#include "Kinect.h"
#include <string>
#include <map>
#include <array>
class KinectData
{
// Kinect
IKinectSensor* mKinectSensor;
bool mKinectConnected;
ICoordinateMapper* mCoordinateMapper;
IBodyFrameReader* mBodyFrameReader;
IDepthFrameReader* mDepthFrameReader;
WAITABLE_HANDLE mBodyFrameEvent;
WAITABLE_HANDLE mDepthFrameEvent;
public:
KinectData();
~KinectData();
bool GetKinectDepth(IDepthFrame** ppDepthFrame, int& nWidth, int& nHeight, UINT16 *&pBuffer, USHORT& nMinDepth, USHORT& nMaxDepth);
bool GetKinectBodies(UINT64* trackingIds, std::map< JointType, std::array<float, 3> > *jointPositions, std::map< JointType, std::array<float, 4> > *jointOrientations, std::pair<HandState, HandState> *handStates, int& bodyCount);
};
|
stimulant/MS-Cube-SDK
|
KinectTransport/resource.h
|
<filename>KinectTransport/resource.h
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by KinectTransport.rc
//
#define IDR_MANIFEST 1
#define IDD_DLG_DIALOG 102
#define IDD_ABOUTBOX 103
#define IDM_ABOUT 104
#define IDC_MYICON 105
#define IDC_KINECTTRANSPORT 106
#define IDI_GREENLIGHT 111
#define IDI_REDLIGHT 112
#define IDC_SKELETONDATA 1001
#define IDC_BODIESENABLED1 1001
#define IDC_DEPTHDATA 1002
#define IDC_DEPTHENABLED1 1002
#define IDC_DESTINATIONHOST 1003
#define IDC_HOST1 1003
#define IDC_ENABLED1 1004
#define IDC_HOST2 1029
#define IDC_BODIESENABLED2 1030
#define IDC_DEPTHENABLED2 1031
#define IDC_ENABLED2 1032
#define IDC_HOST3 1033
#define IDC_BODIESENABLED3 1034
#define IDC_DEPTHENABLED3 1035
#define IDC_ENABLED3 1036
#define IDC_HOST4 1037
#define IDC_BODIESENABLED4 1038
#define IDC_DEPTHENABLED4 1039
#define IDC_ENABLED4 1040
#define IDC_ 1041
#define IDC_STARTONSTARTUP 1041
#define IDC_STATIC -1
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NO_MFC 1
#define _APS_NEXT_RESOURCE_VALUE 113
#define _APS_NEXT_COMMAND_VALUE 32771
#define _APS_NEXT_CONTROL_VALUE 1004
#define _APS_NEXT_SYMED_VALUE 110
#endif
#endif
|
yulei/lvgl
|
demos/stress/lv_demo_stress.c
|
<reponame>yulei/lvgl<filename>demos/stress/lv_demo_stress.c
/**
* @file lv_demo_stress.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_demo_stress.h"
#if LV_USE_DEMO_STRESS
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void auto_del(lv_obj_t * obj, uint32_t delay);
static void msgbox_del(lv_timer_t * tmr);
static void set_y_anim(void * obj, int32_t v);
static void set_width_anim(void * obj, int32_t v);
static void arc_set_end_angle_anim(void * obj, int32_t v);
static void obj_test_task_cb(lv_timer_t * tmr);
/**********************
* STATIC VARIABLES
**********************/
static lv_obj_t * main_page;
static lv_obj_t * ta;
static const char * mbox_btns[] = {"Ok", "Cancel", ""};
static uint32_t mem_free_start = 0;
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
void lv_demo_stress(void)
{
LV_LOG_USER("Starting stress test. (< 100 bytes permanent memory leak is normal due to fragmentation)");
lv_timer_create(obj_test_task_cb, LV_DEMO_STRESS_TIME_STEP, NULL);
}
/**********************
* STATIC FUNCTIONS
**********************/
static void obj_test_task_cb(lv_timer_t * tmr)
{
(void) tmr; /*Unused*/
static int16_t state = -1;
lv_anim_t a;
lv_obj_t * obj;
// printf("step start: %d\n", state);
switch(state) {
case -1:
{
lv_res_t res = lv_mem_test();
if(res != LV_RES_OK) {
LV_LOG_ERROR("Memory integrity error");
}
lv_mem_monitor_t mon;
lv_mem_monitor(&mon);
if(mem_free_start == 0) mem_free_start = mon.free_size;
LV_LOG_USER("mem leak since start: %d, frag: %3d %%", mem_free_start - mon.free_size, mon.frag_pct);
}
break;
case 0:
/* Holder for all object types */
main_page = lv_obj_create(lv_scr_act());
lv_obj_set_size(main_page, LV_HOR_RES / 2 , LV_VER_RES);
lv_obj_set_flex_flow(main_page, LV_FLEX_FLOW_COLUMN);
obj = lv_btn_create(main_page);
lv_obj_set_size(obj, 100, 70);
obj = lv_label_create(obj);
lv_label_set_text(obj, "Multi line\n"LV_SYMBOL_OK LV_SYMBOL_CLOSE LV_SYMBOL_WIFI);
break;
case 1:
{
obj = lv_tabview_create(lv_scr_act(), LV_DIR_TOP, 50);
lv_obj_set_size(obj, LV_HOR_RES / 2, LV_VER_RES / 2);
lv_obj_align(obj, LV_ALIGN_BOTTOM_RIGHT, 0, 0);
lv_obj_t * t = lv_tabview_add_tab(obj, "First");
t = lv_tabview_add_tab(obj, "Second");
lv_obj_t * c = lv_colorwheel_create(t, true);
lv_obj_set_size(c, 150, 150);
// c = lv_led_create(t, NULL);
// lv_obj_set_pos(c, 160, 20);
t = lv_tabview_add_tab(obj, LV_SYMBOL_EDIT " Edit");
t = lv_tabview_add_tab(obj, LV_SYMBOL_CLOSE);
lv_tabview_set_act(obj, 1, LV_ANIM_ON);
auto_del(obj, LV_DEMO_STRESS_TIME_STEP * 5 + 30);
}
break;
case 2:
obj = lv_btn_create(main_page);
lv_obj_set_size(obj, 200, 70);
/*Move to disabled state very slowly*/
lv_obj_add_state(obj, LV_STATE_DISABLED);
/*Add an infinite width change animation*/
lv_anim_init(&a);
lv_anim_set_var(&a, obj);
lv_anim_set_time(&a, LV_DEMO_STRESS_TIME_STEP * 2);
lv_anim_set_exec_cb(&a, set_width_anim);
lv_anim_set_values(&a, 100, 200);
lv_anim_set_playback_time(&a, LV_DEMO_STRESS_TIME_STEP * 2);
lv_anim_set_repeat_count(&a, LV_ANIM_REPEAT_INFINITE);
lv_anim_start(&a);
/*Delete the object a few sec later*/
auto_del(obj, LV_DEMO_STRESS_TIME_STEP * 10);
obj = lv_label_create(obj);
lv_label_set_text_fmt(obj, "Formatted:\n%d %s", 12, "Volt");
break;
case 3:
ta = lv_textarea_create(lv_scr_act());
lv_obj_align_to(ta, main_page, LV_ALIGN_OUT_RIGHT_TOP, 10, 10);
lv_obj_set_size(ta, LV_HOR_RES / 3, LV_VER_RES / 4);
lv_textarea_set_placeholder_text(ta, "The placeholder");
break;
case 4:
obj = lv_btn_create(main_page);
lv_obj_set_size(obj, 100, 70);
lv_obj_set_style_bg_img_src(obj, LV_SYMBOL_DUMMY"Text from\nstyle", 0);
lv_obj_del_async(obj); /*Delete on next call of `lv_task_handler` (so not now)*/
// obj = lv_btn_create(main_page);
// lv_obj_set_size(obj, LV_SIZE_CONTENT, LV_SIZE_CONTENT);
// lv_obj_set_style_bg_img_src(obj, LV_SYMBOL_LEFT);
// lv_obj_set_style_bg_img_opa(obj, LV_OPA_50);
// lv_obj_set_style_bg_img_tiled(obj, true);
// lv_obj_scroll_to_view(obj, LV_ANIM_ON);
break;
case 5:
lv_textarea_set_one_line(ta, true);
break;
case 6:
lv_obj_set_flex_flow(main_page, LV_FLEX_FLOW_COLUMN_WRAP);
break;
case 7:
obj = lv_bar_create(main_page);
lv_bar_set_range(obj, -1000, 2000);
lv_bar_set_value(obj, 1800, LV_ANIM_ON);
lv_bar_set_start_value(obj, -500, LV_ANIM_ON);
auto_del(obj, LV_DEMO_STRESS_TIME_STEP * 2 + 70);
obj = lv_slider_create(main_page);
lv_obj_set_style_anim_time(obj, LV_DEMO_STRESS_TIME_STEP * 8, 0);
lv_slider_set_value(obj, 5000, LV_ANIM_ON); /*Animate to out of range value*/
auto_del(obj, LV_DEMO_STRESS_TIME_STEP * 5 + 22);
obj = lv_switch_create(main_page);
obj = lv_switch_create(main_page);
lv_obj_add_state(obj, LV_STATE_CHECKED);
auto_del(obj, 730);
break;
case 8:
obj = lv_win_create(lv_scr_act(), 50);
lv_obj_set_size(obj, LV_HOR_RES / 2, LV_VER_RES / 2);
lv_obj_align(obj, LV_ALIGN_BOTTOM_RIGHT, 0, 0);
lv_win_add_title(obj, "Window title");
lv_win_add_btn(obj, LV_SYMBOL_CLOSE, 40);
lv_win_add_btn(obj, LV_SYMBOL_DOWN, 40);
auto_del(obj, LV_DEMO_STRESS_TIME_STEP * 3 + 5);
obj = lv_calendar_create(lv_win_get_content(obj));
break;
case 9:
lv_textarea_set_text(ta, "A very very long text which will should make the text area scrollable"
"Here area some dummy sentences to be sure the text area will be really scrollable.");
break;
case 10:
obj = lv_keyboard_create(lv_scr_act());
lv_keyboard_set_mode(obj, LV_KEYBOARD_MODE_TEXT_UPPER);
lv_anim_init(&a);
lv_anim_set_var(&a, obj);
lv_anim_set_values(&a, LV_VER_RES, LV_VER_RES - lv_obj_get_height(obj));
lv_anim_set_time(&a, LV_DEMO_STRESS_TIME_STEP + 3);
lv_anim_set_exec_cb(&a, set_y_anim);
lv_anim_start(&a);
auto_del(obj, LV_DEMO_STRESS_TIME_STEP * 2 + 18);
break;
case 11:
obj = lv_dropdown_create(main_page);
lv_dropdown_set_options(obj, "Zero\nOne\nTwo\nThree\nFour\nFive\nSix\nSeven\nEight");
lv_dropdown_open(obj);
lv_dropdown_set_selected(obj, 2);
auto_del(obj, LV_DEMO_STRESS_TIME_STEP * 3 + 11);
break;
case 12:
obj = lv_roller_create(main_page);
lv_roller_set_options(obj, "Zero\nOne\nTwo\nThree\nFour\nFive\nSix\nSeven\nEight", LV_ROLLER_MODE_INFINITE);
lv_roller_set_selected(obj, 2, LV_ANIM_ON);
auto_del(obj, LV_DEMO_STRESS_TIME_STEP * 20 + 22);
break;
case 13:
obj = lv_arc_create(main_page);
lv_anim_init(&a);
lv_anim_set_var(&a, obj);
lv_anim_set_values(&a, 180, 400);
lv_anim_set_time(&a, LV_DEMO_STRESS_TIME_STEP * 2);
lv_anim_set_delay(&a, LV_DEMO_STRESS_TIME_STEP + 25);
lv_anim_set_playback_time(&a, LV_DEMO_STRESS_TIME_STEP * 5);
lv_anim_set_repeat_count(&a, 3);
lv_anim_set_exec_cb(&a, arc_set_end_angle_anim);
lv_anim_start(&a);
obj = lv_meter_create(main_page);
lv_obj_scroll_to_view(obj, LV_ANIM_ON);
lv_meter_scale_t * scale = lv_meter_add_scale(obj);
lv_meter_add_needle_line(obj, scale, 3, lv_palette_main(LV_PALETTE_RED), -10);
auto_del(obj, LV_DEMO_STRESS_TIME_STEP * 6 + 30);
break;
case 14:
obj = lv_msgbox_create(NULL, "Title", "Some text on the message box with average length", mbox_btns, true);
lv_timer_t * msgbox_tmr = lv_timer_create(msgbox_del, LV_DEMO_STRESS_TIME_STEP * 5 + 30, obj);
lv_timer_set_repeat_count(msgbox_tmr, 1);
lv_obj_align(obj, LV_ALIGN_RIGHT_MID, -10, 0);
break;
case 15:
lv_textarea_set_one_line(ta, false);
break;
case 16:
{
lv_obj_t * tv = lv_tileview_create(lv_scr_act());
lv_obj_set_size(tv, 200, 200);
auto_del(tv, LV_DEMO_STRESS_TIME_STEP * 4 + 5);
obj = lv_tileview_add_tile(tv, 0, 0, LV_DIR_ALL);
obj = lv_label_create(obj);
lv_label_set_text(obj, "Tile: 0;0");
obj = lv_tileview_add_tile(tv, 0, 1, LV_DIR_ALL);
obj = lv_label_create(obj);
lv_label_set_text(obj, "Tile: 0;1");
obj = lv_tileview_add_tile(tv, 1, 1, LV_DIR_ALL);
obj = lv_label_create(obj);
lv_label_set_text(obj, "Tile: 1;1");
lv_obj_set_tile_id(tv, 1, 1, LV_ANIM_ON);
}
break;
case 18:
obj = lv_list_create(main_page);
{
lv_obj_t * b;
b = lv_list_add_btn(obj, LV_SYMBOL_OK, "1. Some very long text to scroll");
auto_del(b, 10);
lv_list_add_btn(obj, LV_SYMBOL_OK, "2. Some very long text to scroll");
lv_list_add_btn(obj, LV_SYMBOL_OK, "3. Some very long text to scroll");
b = lv_list_add_btn(obj, LV_SYMBOL_OK, "4. Some very long text to scroll");
auto_del(b, LV_DEMO_STRESS_TIME_STEP);
b = lv_list_add_btn(obj, LV_SYMBOL_OK, "5. Some very long text to scroll");
auto_del(b, LV_DEMO_STRESS_TIME_STEP + 90);
b = lv_list_add_btn(obj, LV_SYMBOL_OK, "6. Some very long text to scroll");
auto_del(b, LV_DEMO_STRESS_TIME_STEP + 10);
lv_obj_scroll_to_view(lv_obj_get_child(obj, -1), LV_ANIM_ON);
}
auto_del(obj, LV_DEMO_STRESS_TIME_STEP * 5 + 15);
obj = lv_table_create(main_page);
lv_table_set_cell_value(obj, 0, 0, "0,0");
lv_table_set_cell_value_fmt(obj, 3, 0, "%d,%d", 5, 0);
lv_table_set_row_cnt(obj, 5);
lv_table_set_cell_value_fmt(obj, 1, 0, "%s", "1,0");
lv_table_set_cell_value(obj, 1, 3, "1,3");
break;
case 19:
lv_textarea_set_cursor_pos(ta, 10);
lv_textarea_set_text(ta, "__INSERTED TEXT" LV_SYMBOL_EDIT"__");
break;
case 20:
lv_obj_set_flex_flow(main_page, LV_FLEX_FLOW_ROW_WRAP);
break;
case 21:
lv_textarea_set_cursor_pos(ta, 0);
lv_textarea_add_char(ta, '0');
lv_textarea_add_char(ta, '1');
lv_textarea_add_char(ta, '2');
lv_textarea_add_char(ta, '3');
lv_textarea_add_char(ta, '4');
lv_textarea_add_char(ta, '5');
lv_textarea_add_char(ta, '6');
lv_textarea_add_char(ta, '7');
lv_textarea_add_char(ta, '8');
lv_textarea_add_char(ta, '9');
lv_textarea_add_char(ta, 'A');
lv_textarea_add_char(ta, 'B');
lv_textarea_add_char(ta, 'C');
lv_textarea_add_char(ta, 'D');
lv_textarea_add_char(ta, 'E');
lv_textarea_add_char(ta, 'F');
lv_textarea_add_text(ta, LV_SYMBOL_OK);
lv_textarea_add_text(ta, LV_SYMBOL_CLOSE);
lv_textarea_add_text(ta, LV_SYMBOL_COPY);
lv_textarea_add_text(ta, LV_SYMBOL_SAVE);
lv_textarea_add_text(ta, LV_SYMBOL_PASTE);
break;
case 22:
obj = lv_spinbox_create(main_page);
lv_spinbox_set_digit_format(obj, 6, 3);
lv_spinbox_set_value(obj, 5678);
lv_spinbox_set_step(obj, 10);
lv_spinbox_increment(obj);
lv_spinbox_increment(obj);
lv_spinbox_increment(obj);
lv_spinbox_set_step(obj, 100);
lv_spinbox_increment(obj);
lv_spinbox_increment(obj);
lv_spinbox_set_step(obj, 1);
lv_spinbox_increment(obj);
lv_spinbox_increment(obj);
auto_del(obj, LV_DEMO_STRESS_TIME_STEP * 2 + 15);
lv_obj_scroll_by(main_page, 0, 20, LV_ANIM_ON);
break;
case 23:
obj = lv_chart_create(main_page);
{
lv_chart_series_t * s1 = lv_chart_add_series(obj, lv_palette_main(LV_PALETTE_RED), LV_CHART_AXIS_PRIMARY_Y);
lv_chart_set_next_value(obj, s1, 36);
lv_chart_set_next_value(obj, s1, -29);
lv_chart_set_next_value(obj, s1, 51);
lv_chart_set_next_value(obj, s1, 107);
lv_chart_set_next_value(obj, s1, 70);
lv_chart_set_next_value(obj, s1, 36);
lv_chart_set_next_value(obj, s1, -2);
lv_chart_set_next_value(obj, s1, 63);
lv_chart_set_next_value(obj, s1, 48);
lv_chart_set_next_value(obj, s1, 72);
auto_del(obj, LV_DEMO_STRESS_TIME_STEP * 3);
}
lv_obj_scroll_by(main_page, 0, 20, LV_ANIM_ON);
break;
case 24:
obj = lv_checkbox_create(main_page);
lv_checkbox_set_text(obj, "An option to select");
auto_del(obj, LV_DEMO_STRESS_TIME_STEP * 2 + 20);
obj = lv_checkbox_create(main_page);
lv_obj_add_state(obj, LV_STATE_CHECKED);
obj = lv_checkbox_create(main_page);
lv_obj_add_state(obj, LV_STATE_CHECKED | LV_STATE_DISABLED);
auto_del(obj, LV_DEMO_STRESS_TIME_STEP * 1 + 60);
lv_obj_scroll_by(main_page, 0, 20, LV_ANIM_ON);
break;
case 25:
lv_textarea_set_cursor_pos(ta, 20);
{
uint16_t i;
for(i = 0; i < 64; i++) {
lv_textarea_del_char_forward(ta);
}
}
break;
case 26:
lv_textarea_set_one_line(ta, true);
break;
case 29:
lv_obj_clean(main_page);
lv_obj_del(ta);
ta = NULL;
break;
case 31:
lv_obj_clean(lv_scr_act());
main_page = NULL;
state = -2;
break;
default:
break;
}
// printf("step end: %d\n", state);
state ++;
}
static void auto_del(lv_obj_t * obj, uint32_t delay)
{
lv_anim_t a;
lv_anim_init(&a);
lv_anim_set_var(&a, obj);
lv_anim_set_time(&a, 0);
lv_anim_set_delay(&a, delay);
lv_anim_set_ready_cb(&a, lv_obj_del_anim_ready_cb);
lv_anim_start(&a);
}
static void msgbox_del(lv_timer_t * tmr)
{
lv_msgbox_close(tmr->user_data);
}
static void set_y_anim(void * obj, int32_t v)
{
lv_obj_set_y(obj, v);
}
static void set_width_anim(void * obj, int32_t v)
{
lv_obj_set_width(obj, v);
}
static void arc_set_end_angle_anim(void * obj, int32_t v)
{
lv_arc_set_end_angle(obj, v);
}
#endif /* LV_USE_DEMO_STRESS */
|
Alikhalesi/thread-pool
|
examples/mandelbrot/include/fractal.h
|
<filename>examples/mandelbrot/include/fractal.h
/// Much of the code here is adopted from https://github.com/sol-prog/Mandelbrot_set
#pragma once
#include <complex>
#include <concepts>
#include <functional>
#include <mutex>
#include <span>
#include <vector>
// Use an alias to simplify the use of complex type
using complex = std::complex<double>;
struct rgb {
uint8_t r{};
uint8_t g{};
uint8_t b{};
};
/// @brief Simple range class for viewing window and fractal window
template <class T>
requires std::integral<T> || std::floating_point<T>
struct fractal_window {
T x_min{};
T x_max{};
T y_min{};
T y_max{};
constexpr T height() const noexcept { return y_max - y_min; }
constexpr T width() const noexcept { return x_max - x_min; }
constexpr T size() const noexcept { return width() * height(); }
};
/// @brief Performs smooth polynomial fitting to the given value.
rgb get_rgb_smooth(int n, int iter_max);
void save_ppm(const unsigned int &width, const unsigned int &height, std::span<rgb> colors,
std::string_view file_name);
/**
* @brief Convert a pixel coordinate to the complex domain
* @param scr Source domain (viewing window)
* @param fr Fractal domain (real and imaginary range)
* @param c Initial complex value
*/
complex scale(const fractal_window<int> &scr, const fractal_window<double> &fr, complex c);
/**
* @brief Check if a point is in the set or escapes to infinity, return the number if iterations
* @param c Complex number value, see scale
* @param iter_max Max number of iterations
* @param func The complex function used for the fractal.
*/
int escape(complex c, int iter_max, const std::function<complex(complex, complex)> &func);
/**
* @brief Calculate a single fractal row and returns it's color values.
* @param row The row to calculate (0 -> y_max)
* @param source_window The source viewing window for the fractal.
* @param fractal_window The fractal domain for imaginary and real parts.
* @param iter_max Max number of iterations
* @param func The fractal function to use.
* @return vector of rgb values calculated for the given row.
*/
std::vector<rgb> calculate_fractal_row(int row, fractal_window<int> source_window,
fractal_window<double> fractal_window, int iter_max,
std::function<complex(complex, complex)> func);
|
Alikhalesi/thread-pool
|
include/thread_pool/thread_pool.h
|
#pragma once
#include <concepts>
#include <functional>
#include <future>
#include <memory>
#include <queue>
#include <thread>
#include <type_traits>
#include "thread_pool/thread_safe_queue.h"
namespace dp {
namespace detail {
template <class T>
std::decay_t<T> decay_copy(T &&v) {
return std::forward<T>(v);
}
// bind F and parameter pack into a nullary one shot. Lambda captures by value.
template <typename... Args, typename F>
auto bind(F &&f, Args &&...args) {
return [f = decay_copy(std::forward<F>(f)),
... args = decay_copy(std::forward<Args>(args))]() mutable -> decltype(auto) {
return std::invoke(std::move(f), std::move(args)...);
};
}
} // namespace detail
template <typename FunctionType = std::function<void()>>
requires std::invocable<FunctionType> &&
std::is_same_v<void, std::invoke_result_t<FunctionType>>
class thread_pool {
public:
thread_pool(const unsigned int &number_of_threads = std::thread::hardware_concurrency()) {
for (std::size_t i = 0; i < number_of_threads; ++i) {
threads_.emplace_back([&](const std::stop_token stop_tok) {
do {
// check if we have task
if (queue_.empty()) {
// no tasks, so we wait instead of spinning
std::unique_lock lock(condition_mutex_);
condition_.wait(lock, stop_tok, [this]() { return !queue_.empty(); });
}
// ensure we have a task before getting task
// since the dtor notifies via the condition variable as well
if (!queue_.empty()) {
// get the task
auto task = queue_.pop();
// invoke the task
std::invoke(std::move(task));
// decrement in-flight counter
--in_flight_;
}
} while (!stop_tok.stop_requested());
});
}
}
~thread_pool() {
// wait for tasks to complete first
do {
std::this_thread::yield();
} while (in_flight_ > 0);
// stop all threads
for (auto &thread : threads_) {
thread.request_stop();
}
condition_.notify_all();
}
/// thread pool is non-copyable
thread_pool(const thread_pool &) = delete;
thread_pool &operator=(const thread_pool &) = delete;
/**
* @brief Enqueue a task into the thread pool that returns a result.
* @tparam Function An invokable type.
* @tparam Args Argument parameter pack
* @tparam ReturnType The return type of the Function
* @param f The callable function
* @param args The parameters that will be passed (copied) to the function.
* @return A std::future<ReturnType> that can be used to retrieve the returned value.
*/
template <typename Function, typename... Args,
typename ReturnType = std::invoke_result_t<Function &&, Args &&...>>
requires std::invocable<Function, Args...>
[[nodiscard]] std::future<ReturnType> enqueue(Function f, Args... args) {
/*
* use shared promise here so that we don't break the promise later (until C++23)
*
* with C++23 we can do the following:
*
* std::promise<ReturnType> promise;
* auto future = promise.get_future();
* auto task = [func = std::move(f), ...largs = std::move(args),
promise = std::move(promise)]() mutable {...};
*/
auto shared_promise = std::make_shared<std::promise<ReturnType>>();
auto task = [func = std::move(f), ... largs = std::move(args),
promise = shared_promise]() { promise->set_value(func(largs...)); };
// get the future before enqueuing the task
auto future = shared_promise->get_future();
// enqueue the task
enqueue_task(std::move(task));
return future;
}
/**
* @brief Enqueue a task to be executed in the thread pool that returns void.
* @tparam Function An invokable type.
* @tparam Args Argument parameter pack for Function
* @param func The callable to be executed
* @param args Arguments that will be passed to the function.
*/
template <typename Function, typename... Args>
requires std::invocable<Function, Args...> &&
std::is_same_v<void, std::invoke_result_t<Function &&, Args &&...>>
void enqueue_detach(Function &&func, Args &&...args) {
enqueue_task(detail::bind(std::forward<Function>(func), std::forward<Args>(args)...));
}
private:
template <typename Function>
void enqueue_task(Function &&f) {
++in_flight_;
{
std::lock_guard lock(condition_mutex_);
queue_.push(std::forward<Function>(f));
}
condition_.notify_all();
}
std::condition_variable_any condition_;
std::mutex condition_mutex_;
std::vector<std::jthread> threads_;
dp::thread_safe_queue<FunctionType> queue_;
std::atomic<int64_t> in_flight_{0};
};
/**
* @example mandelbrot/source/main.cpp
* Example showing how to use thread pool with tasks that return a value. Outputs a PPM image of
* a mandelbrot.
*/
} // namespace dp
|
Alikhalesi/thread-pool
|
include/thread_pool/thread_safe_queue.h
|
#pragma once
#include <condition_variable>
#include <deque>
#include <mutex>
namespace dp {
template <typename T>
class thread_safe_queue {
public:
using value_type = T;
using size_type = typename std::deque<T>::size_type;
thread_safe_queue() = default;
void push(T&& value) {
{
std::lock_guard lock(mutex_);
data_.push_back(std::forward<T>(value));
}
condition_variable_.notify_all();
}
bool empty() {
std::lock_guard lock(mutex_);
return data_.empty();
}
[[nodiscard]] size_type size() {
std::lock_guard lock(mutex_);
return data_.size();
}
[[nodiscard]] T pop() {
std::unique_lock lock(mutex_);
condition_variable_.wait(lock, [this] { return !data_.empty(); });
auto front = data_.front();
data_.pop_front();
return front;
}
private:
using mutex_type = std::mutex;
std::deque<T> data_;
mutable mutex_type mutex_{};
std::condition_variable condition_variable_{};
};
} // namespace dp
|
niwasmala/cordova-plugin-linphone
|
libs/arm64-apple-darwin.ios/include/srtp/config.h
|
/***************************************************************************
* config.h.cmake
* Copyright (C) 2014 Belledonne Communications, Grenoble France
*
****************************************************************************
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
****************************************************************************/
/* #undef ENABLE_DEBUGGING */
/* #undef SRTP_KERNEL */
/* #undef SRTP_KERNEL_LINUX */
#define DEV_URANDOM "/dev/urandom"
/* #undef GENERIC_AESICM */
/* #undef USE_SYSLOG */
#define ERR_REPORTING_STDOUT 1
/* #undef USE_ERR_REPORTING_FILE */
/* #undef ERR_REPORTING_FILE */
/* #undef SRTP_GDOI */
#define CPU_CISC 1
/* #undef CPU_RISC */
/* #undef HAVE_X86 */
/* #undef WORDS_BIGENDIAN */
#define HAVE_STDLIB_H 1
#define HAVE_UNISTD_H 1
/* #undef HAVE_BYTESWAP_H */
#define HAVE_STDINT_H 1
#define HAVE_INTTYPES_H 1
#define HAVE_SYS_TYPES_H 1
#define HAVE_MACHINE_TYPES_H 1
/* #undef HAVE_SYS_INT_TYPES_H */
#define HAVE_SYS_SOCKET_H 1
#define HAVE_NETINET_IN_H 1
#define HAVE_ARPA_INET_H 1
/* #undef HAVE_WINDOWS_H */
/* #undef HAVE_WINSOCK2_H */
#define HAVE_SYSLOG_H 1
#define HAVE_INET_ATON 1
#define HAVE_USLEEP 1
#define HAVE_SIGACTION 1
#define HAVE_UINT8_T 1
#define HAVE_UINT16_T 1
#define HAVE_UINT32_T 1
#define HAVE_UINT64_T 1
#define SIZEOF_UNSIGNED_LONG 8
#define SIZEOF_UNSIGNED_LONG_LONG 8
#ifndef __cplusplus
/* #undef inline */
#endif
|
niwasmala/cordova-plugin-linphone
|
libs/armv7-apple-darwin.ios/include/speex/speex_config_types.h
|
#ifndef __SPEEX_TYPES_H__
#define __SPEEX_TYPES_H__
typedef short spx_int16_t;
typedef unsigned short spx_uint16_t;
typedef long spx_int32_t;
typedef unsigned long spx_uint32_t;
#endif
|
niwasmala/cordova-plugin-linphone
|
src/ios/Linphone.h
|
<reponame>niwasmala/cordova-plugin-linphone
#import <Cordova/CDV.h>
#import <AudioToolbox/AudioToolbox.h>
#include "linphone/linphonecore.h"
@interface Linphone : CDVPlugin{
LinphoneCore *lc;
LinphoneCall *call;
}
@property (nonatomic) LinphoneCore *lc;
@property (nonatomic) LinphoneCall *call;
- (void)login:(CDVInvokedUrlCommand*)command;
- (void)logout:(CDVInvokedUrlCommand*)command;
- (void)call:(CDVInvokedUrlCommand*)command;
- (void)videocall:(CDVInvokedUrlCommand*)command;
- (void)hangup:(CDVInvokedUrlCommand*)command;
- (void)toggleVideo:(CDVInvokedUrlCommand*)command;
- (void)toggleSpeaker:(CDVInvokedUrlCommand*)command;
- (void)toggleMute:(CDVInvokedUrlCommand*)command;
- (void)sendDtmf:(CDVInvokedUrlCommand*)command;
@end
|
niwasmala/cordova-plugin-linphone
|
libs/armv7-apple-darwin.ios/include/ortp/event.h
|
/*
The oRTP library is an RTP (Realtime Transport Protocol - rfc3550) stack.
Copyright (C) 2001 <NAME> <EMAIL>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.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 library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef ortp_events_h
#define ortp_events_h
#include <ortp/str_utils.h>
#include <ortp/rtcp.h>
typedef mblk_t OrtpEvent;
typedef unsigned long OrtpEventType;
typedef enum {
OrtpRTPSocket,
OrtpRTCPSocket
} OrtpSocketType;
struct _OrtpEventData{
mblk_t *packet; /* most events are associated to a received packet */
struct sockaddr_storage source_addr;
socklen_t source_addrlen;
ortpTimeSpec ts;
union {
int telephone_event;
int payload_type;
bool_t dtls_stream_encrypted;
bool_t zrtp_stream_encrypted;
bool_t ice_processing_successful;
struct _ZrtpSas{
char sas[32]; // up to 31 + null characters
bool_t verified;
bool_t pad[3];
} zrtp_sas;
OrtpSocketType socket_type;
uint64_t tmmbr_mxtbr;
uint32_t received_rtt_character;
} info;
};
typedef struct _OrtpEventData OrtpEventData;
#ifdef __cplusplus
extern "C"{
#endif
ORTP_PUBLIC OrtpEvent * ortp_event_new(OrtpEventType tp);
ORTP_PUBLIC OrtpEventType ortp_event_get_type(const OrtpEvent *ev);
/* type is one of the following*/
#define ORTP_EVENT_STUN_PACKET_RECEIVED 1
#define ORTP_EVENT_PAYLOAD_TYPE_CHANGED 2
#define ORTP_EVENT_TELEPHONE_EVENT 3
#define ORTP_EVENT_RTCP_PACKET_RECEIVED 4 /**<when a RTCP packet is received from far end */
#define ORTP_EVENT_RTCP_PACKET_EMITTED 5 /**<fired when oRTP decides to send an automatic RTCP SR or RR */
#define ORTP_EVENT_ZRTP_ENCRYPTION_CHANGED 6
#define ORTP_EVENT_ZRTP_SAS_READY 7
#define ORTP_EVENT_ICE_CHECK_LIST_PROCESSING_FINISHED 8
#define ORTP_EVENT_ICE_SESSION_PROCESSING_FINISHED 9
#define ORTP_EVENT_ICE_GATHERING_FINISHED 10
#define ORTP_EVENT_ICE_LOSING_PAIRS_COMPLETED 11
#define ORTP_EVENT_ICE_RESTART_NEEDED 12
#define ORTP_EVENT_DTLS_ENCRYPTION_CHANGED 13
#define ORTP_EVENT_TMMBR_RECEIVED 14
ORTP_PUBLIC OrtpEventData * ortp_event_get_data(OrtpEvent *ev);
ORTP_PUBLIC void ortp_event_destroy(OrtpEvent *ev);
ORTP_PUBLIC OrtpEvent *ortp_event_dup(OrtpEvent *ev);
typedef struct OrtpEvQueue{
queue_t q;
ortp_mutex_t mutex;
} OrtpEvQueue;
ORTP_PUBLIC OrtpEvQueue * ortp_ev_queue_new(void);
ORTP_PUBLIC void ortp_ev_queue_destroy(OrtpEvQueue *q);
ORTP_PUBLIC OrtpEvent * ortp_ev_queue_get(OrtpEvQueue *q);
ORTP_PUBLIC void ortp_ev_queue_flush(OrtpEvQueue * qp);
struct _RtpSession;
/**
* Callback function when a RTCP packet of the interested type is found.
*
* @param evd the packet. Read-only, must NOT be changed.
* @param user_data user data provided when registered the callback
*
*/
typedef void (*OrtpEvDispatcherCb)(const OrtpEventData *evd, void *user_data);
typedef struct OrtpEvDispatcherData{
OrtpEventType type;
rtcp_type_t subtype;
OrtpEvDispatcherCb on_found;
void* user_data;
} OrtpEvDispatcherData;
typedef struct OrtpEvDispatcher{
OrtpEvQueue *q;
struct _RtpSession* session;
OList *cbs;
} OrtpEvDispatcher;
/**
* Constructs an OrtpEvDispatcher object. This object can be used to be notified
* when any RTCP type packet is received or emitted on the rtp session,
* given a callback registered with #ortp_ev_dispatcher_connect
*
* @param session RTP session to listen on. Cannot be NULL.
*
* @return OrtpEvDispatcher object newly created.
*/
ORTP_PUBLIC OrtpEvDispatcher * ortp_ev_dispatcher_new(struct _RtpSession* session);
/**
* Frees the memory for the given dispatcher. Note that user_data must be freed
* by caller, and so does the OrtpEvQueue.
*
* @param d OrtpEvDispatcher object
*/
ORTP_PUBLIC void ortp_ev_dispatcher_destroy(OrtpEvDispatcher *d);
/**
* Iterate method to be called periodically. If a RTCP packet is found and
* its type matches one of the callback connected with #ortp_ev_dispatcher_connect,
* this callback will be invoked in the current thread.
*
* @param d OrtpEvDispatcher object
*/
ORTP_PUBLIC void ortp_ev_dispatcher_iterate(OrtpEvDispatcher *d);
/**
* Connects a callback to the given type of event packet and, in case of RTCP event,
* for the given RTCP subtype.
* When any event is found, the callback is invoked. Multiple
* callbacks can be connected to the same type of event, and the same callback
* can be connected to multiple type of event.
*
* @param d OrtpEvDispatcher object
* @param type type of event to be notified of.
* @param subtype when type is set to ORTP_EVENT_RTCP_PACKET_RECEIVED or ORTP_EVENT_RTCP_PACKET_EMITTED, subtype of RTCP packet to be notified of. Otherwise this parameter is not used.
* @param on_receive function to call when a RTCP packet of the given type is found.
* @param user_data user data given as last argument of the callback. Can be NULL. MUST be freed by user.
*/
ORTP_PUBLIC void ortp_ev_dispatcher_connect(OrtpEvDispatcher *d
, OrtpEventType type
, rtcp_type_t subtype
, OrtpEvDispatcherCb on_receive
, void *user_data);
/**
* Disconnects the given callback for the given type and subtype on the given dispatcher.
*/
void ortp_ev_dispatcher_disconnect(OrtpEvDispatcher *d
, OrtpEventType type
, rtcp_type_t subtype
, OrtpEvDispatcherCb cb);
#ifdef __cplusplus
}
#endif
#endif
|
niwasmala/cordova-plugin-linphone
|
libs/arm64-apple-darwin.ios/include/belle-sip/utils.h
|
/*
belle-sip - SIP (RFC3261) library.
Copyright (C) 2010 Belledonne Communications SARL
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, see <http://www.gnu.org/licenses/>.
*/
#ifndef BELLE_SIP_UTILS_H
#define BELLE_SIP_UTILS_H
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include "belle-sip/defs.h"
BELLE_SIP_BEGIN_DECLS
BELLESIP_EXPORT void *belle_sip_malloc(size_t size);
BELLESIP_EXPORT void *belle_sip_malloc0(size_t size);
BELLESIP_EXPORT void *belle_sip_realloc(void *ptr, size_t size);
BELLESIP_EXPORT void belle_sip_free(void *ptr);
BELLESIP_EXPORT char * belle_sip_strdup(const char *s);
BELLE_SIP_END_DECLS
/***************/
/* logging api */
/***************/
typedef enum {
BELLE_SIP_LOG_FATAL=1,
BELLE_SIP_LOG_ERROR=1<<1,
BELLE_SIP_LOG_WARNING=1<<2,
BELLE_SIP_LOG_MESSAGE=1<<3,
BELLE_SIP_LOG_DEBUG=1<<4,
BELLE_SIP_LOG_END=1<<5
} belle_sip_log_level;
typedef void (*belle_sip_log_function_t)(belle_sip_log_level lev, const char *fmt, va_list args);
typedef enum {
BELLE_SIP_NOT_IMPLEMENTED = -2,
BELLE_SIP_BUFFER_OVERFLOW = -1,
BELLE_SIP_OK = 0
} belle_sip_error_code;
#ifdef __GNUC__
#define BELLE_SIP_CHECK_FORMAT_ARGS(m,n) __attribute__((format(printf,m,n)))
#else
#define BELLE_SIP_CHECK_FORMAT_ARGS(m,n)
#endif
BELLE_SIP_BEGIN_DECLS
BELLESIP_VAR_EXPORT belle_sip_log_function_t belle_sip_logv_out;
BELLESIP_VAR_EXPORT unsigned int __belle_sip_log_mask;
#define belle_sip_log_level_enabled(level) (__belle_sip_log_mask & (level))
#if !defined(_WIN32) && !defined(_WIN32_WCE)
#define belle_sip_logv(level,fmt,args) \
{\
if (belle_sip_logv_out!=NULL && belle_sip_log_level_enabled(level)) \
belle_sip_logv_out(level,fmt,args);\
if ((level)==BELLE_SIP_LOG_FATAL) abort();\
}while(0)
#else
BELLESIP_EXPORT void belle_sip_logv(int level, const char *fmt, va_list args);
#endif
#ifdef BELLE_SIP_DEBUG_MODE
static BELLESIP_INLINE void belle_sip_debug(const char *fmt,...)
{
va_list args;
va_start (args, fmt);
belle_sip_logv(BELLE_SIP_LOG_DEBUG, fmt, args);
va_end (args);
}
#else
#define belle_sip_debug(...)
#endif
#ifdef BELLE_SIP_NOMESSAGE_MODE
#define belle_sip_log(...)
#define belle_sip_message(...)
#define belle_sip_warning(...)
#else
static BELLESIP_INLINE void BELLE_SIP_CHECK_FORMAT_ARGS(2,3) belle_sip_log(belle_sip_log_level lev, const char *fmt,...){
va_list args;
va_start (args, fmt);
belle_sip_logv(lev, fmt, args);
va_end (args);
}
static BELLESIP_INLINE void BELLE_SIP_CHECK_FORMAT_ARGS(1,2) belle_sip_message(const char *fmt,...)
{
va_list args;
va_start (args, fmt);
belle_sip_logv(BELLE_SIP_LOG_MESSAGE, fmt, args);
va_end (args);
}
static BELLESIP_INLINE void BELLE_SIP_CHECK_FORMAT_ARGS(1,2) belle_sip_warning(const char *fmt,...)
{
va_list args;
va_start (args, fmt);
belle_sip_logv(BELLE_SIP_LOG_WARNING, fmt, args);
va_end (args);
}
#endif
static BELLESIP_INLINE void BELLE_SIP_CHECK_FORMAT_ARGS(1,2) belle_sip_error(const char *fmt,...)
{
va_list args;
va_start (args, fmt);
belle_sip_logv(BELLE_SIP_LOG_ERROR, fmt, args);
va_end (args);
}
static BELLESIP_INLINE void BELLE_SIP_CHECK_FORMAT_ARGS(1,2) belle_sip_fatal(const char *fmt,...)
{
va_list args;
va_start (args, fmt);
belle_sip_logv(BELLE_SIP_LOG_FATAL, fmt, args);
va_end (args);
}
BELLESIP_EXPORT void belle_sip_set_log_file(FILE *file);
BELLESIP_EXPORT void belle_sip_set_log_handler(belle_sip_log_function_t func);
BELLESIP_EXPORT belle_sip_log_function_t belle_sip_get_log_handler(void);
BELLESIP_EXPORT char * BELLE_SIP_CHECK_FORMAT_ARGS(1,2) belle_sip_strdup_printf(const char *fmt,...);
BELLESIP_EXPORT char * belle_sip_strcat_vprintf(char* dst, const char *fmt, va_list ap);
BELLESIP_EXPORT char * BELLE_SIP_CHECK_FORMAT_ARGS(2,3) belle_sip_strcat_printf(char* dst, const char *fmt,...);
BELLESIP_EXPORT belle_sip_error_code BELLE_SIP_CHECK_FORMAT_ARGS(4,5) belle_sip_snprintf(char *buff, size_t buff_size, size_t *offset, const char *fmt, ...);
BELLESIP_EXPORT belle_sip_error_code belle_sip_snprintf_valist(char *buff, size_t buff_size, size_t *offset, const char *fmt, va_list args);
BELLESIP_EXPORT void belle_sip_set_log_level(int level);
BELLESIP_EXPORT char * belle_sip_random_token(char *ret, size_t size);
BELLESIP_EXPORT unsigned char * belle_sip_random_bytes(unsigned char *ret, size_t size);
BELLESIP_EXPORT char * belle_sip_octets_to_text(const unsigned char *hash, size_t hash_len, char *ret, size_t size);
BELLESIP_EXPORT char * belle_sip_create_tag(char *ret, size_t size);
BELLESIP_EXPORT const char* belle_sip_version_to_string(void);
/**
* Returns string without surrounding quotes if any, else just call belle_sip_strdup().
**/
BELLESIP_EXPORT char *belle_sip_unquote_strdup(const char *str);
BELLESIP_EXPORT uint64_t belle_sip_time_ms(void);
BELLESIP_EXPORT unsigned int belle_sip_random(void);
#if defined(_WIN32)
#include <winsock2.h>
#include <ws2tcpip.h>
typedef SOCKET belle_sip_socket_t;
typedef HANDLE belle_sip_fd_t;
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
typedef int belle_sip_socket_t;
typedef int belle_sip_fd_t;
#endif
BELLESIP_EXPORT int belle_sip_getaddrinfo(const char *node, const char *service, const struct addrinfo *hints, struct addrinfo **res);
BELLESIP_EXPORT void belle_sip_freeaddrinfo(struct addrinfo *res);
typedef void (*belle_sip_background_task_end_callback_t)(void *);
BELLESIP_EXPORT unsigned long belle_sip_begin_background_task(const char *name, belle_sip_background_task_end_callback_t cb, void *data);
BELLESIP_EXPORT void belle_sip_end_background_task(unsigned long id);
/**
* create a directory if it doesn't already exists
*
* @param[in] path The directory to be created
* @return 0 in case of succes, -1 otherwise, note it returns -1 if the directory already exists
*/
BELLESIP_EXPORT int belle_sip_mkdir(const char *path);
BELLE_SIP_END_DECLS
#endif
|
fzj270452746/M4CoreFoundation
|
M4Core/Classes/M4CoreFoundation.framework/Headers/BaseRefreshCollectionViewController.h
|
<reponame>fzj270452746/M4CoreFoundation
//
// BaseRefreshCollectionViewController.h
// Test
//
// Created by hades on 2017/7/13.
// Copyright © 2017年 Hades. All rights reserved.
//
#import "BaseCollectionViewController.h"
#import "PageInfoModel.h"
@interface BaseRefreshCollectionViewController : BaseCollectionViewController {
PageInfoModel *_CurrentPageIndex;
RefreshStatus _LoadStatus;
}
- (void)receiveRefreshDataDidFinished:(BOOL)success pageInfo:(PageInfoModel *)pageInfo refreshStatus:(RefreshStatus) status;
- (void)refreshCollectionViewWithHeaderSel:(SEL)headerRefreshSelector withFooterRefreshSel:(SEL)footerRefreshSelector;
- (void)refreshCollectionViewWithSelector:(SEL)refreshSelector;
@end
|
fzj270452746/M4CoreFoundation
|
Example/M4Core/M4AppDelegate.h
|
//
// M4AppDelegate.h
// M4Core
//
// Created by <EMAIL> on 07/17/2017.
// Copyright (c) 2017 <EMAIL>. All rights reserved.
//
@import UIKit;
@interface M4AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
|
fzj270452746/M4CoreFoundation
|
M4Core/Classes/M4CoreFoundation.framework/Headers/WebViewProgressView.h
|
<reponame>fzj270452746/M4CoreFoundation
//
// WebViewProgressView.h
// Patrol
//
// Created by Benjamin on 4/7/17.
// Copyright © 2017 Cloud4Magic. All rights reserved.
//
#import "CoreUIView.h"
@interface WebViewProgressView : CoreUIView
@property (nonatomic, assign) float progress;
@property (nonatomic, strong) UIView *progressBarView;
@property (nonatomic, assign) NSTimeInterval barAnimationDuration; // default 0.1
@property (nonatomic, assign) NSTimeInterval fadeAnimationDuration; // default 0.27
@property (nonatomic, assign) NSTimeInterval fadeOutDelay; // default 0.1
- (void)setProgress:(float)progress animated:(BOOL)animated;
@end
|
fzj270452746/M4CoreFoundation
|
M4Core/Classes/M4CoreFoundation.framework/Headers/DebugMacro.h
|
//
// DebugMacro.h
// Patrol
//
// Created by Benjamin on 4/6/17.
// Copyright © 2017 Cloud4Magic. All rights reserved.
//
///////////////////////////////////////////////////////////////////////////////////////////////////
#define TICK NSDate *startTime = [NSDate date]
#define TOCK NSLog(@"Time: %f", -[startTime timeIntervalSinceNow])
///////////////////////////////////////////////////////////////////////////////////////////////////
#ifdef DEBUG
#define NSLog(FORMAT, ...) fprintf(stderr,"%s:%d \t%s\n",[[[NSString stringWithUTF8String:__FILE__] lastPathComponent] UTF8String], __LINE__, [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);
#else
#define NSLog(FORMAT, ...) nil
#endif
|
fzj270452746/M4CoreFoundation
|
M4Core/Classes/M4CoreFoundation.framework/Headers/BaseRefreshTableViewController.h
|
<gh_stars>0
//
// BaseRefreshTableViewController.h
// Patrol
//
// Created by Benjamin on 4/7/17.
// Copyright © 2017 Cloud4Magic. All rights reserved.
//
#import "BaseTableViewController.h"
#import "PageInfoModel.h"
@interface BaseRefreshTableViewController : BaseTableViewController {
PageInfoModel *_CurrentPageIndex;
RefreshStatus _LoadStatus;
}
- (void)receiveRefreshDataDidFinished:(BOOL)success pageInfo:(PageInfoModel *)pageInfo refreshStatus:(RefreshStatus) status;
- (void)refreshTableViewWithHeaderSel:(SEL)headerRefreshSelector withFooterRefreshSel:(SEL)footerRefreshSelector;
- (void)refreshTableViewWithSelector:(SEL)refreshSelector;
@end
|
fzj270452746/M4CoreFoundation
|
M4Core/Classes/M4CoreFoundation.framework/PrivateHeaders/CoreNibFileCache.h
|
//
// CoreNibFileCache.h
// Patrol
//
// Created by Benjamin on 4/6/17.
// Copyright © 2017 Cloud4Magic. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface CoreNibFileCache : NSObject
+ (CoreNibFileCache *)sharedInstance;
- (UINib *)nibWithNameKey:(NSString *)nameKey;
@end
|
fzj270452746/M4CoreFoundation
|
M4Core/Classes/M4CoreFoundation.framework/Headers/AppVersion.h
|
//
// AppVersion.h
// Patrol
//
// Created by Benjamin on 4/6/17.
// Copyright © 2017 Cloud4Magic. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface AppVersion : NSObject
+ (NSString *) appVersion;
+ (NSString *) verisonNumber;
+ (NSString *) buildingNumber;
@end
|
fzj270452746/M4CoreFoundation
|
M4Core/Classes/M4CoreFoundation.framework/Headers/iOSVersion.h
|
//
// iOSVersion.h
// Patrol
//
// Created by Benjamin on 4/6/17.
// Copyright © 2017 Cloud4Magic. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface iOSVersion : NSObject
//iOS system version
+ (NSString *) getCurrentDeviceSysVer; // e.g. @"2.0" "3.2.1"
+ (BOOL) currentDeviceSysVerEqual:(NSString *) version;
+ (BOOL) currentDeviceSysVerGreater:(NSString *)version;
+ (BOOL) currentDeviceSysVerGreaterOrEqual:(NSString *)version;
+ (BOOL) currentDeviceSysVerLess:(NSString *)version;
+ (BOOL) currentDeviceSysVerLessOrEqual:(NSString *)version;
@end
|
fzj270452746/M4CoreFoundation
|
M4Core/Classes/M4CoreFoundation.framework/Headers/ModelBaseClass.h
|
//
// ModelBaseClass.h
// AlsTravel
//
// Created by Benjamin on 3/1/17.
// Copyright © 2017 Cloud4Magic. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <YYModel/YYModel.h>
@interface ModelBaseClass : NSObject <NSCoding, NSCopying, YYModel>
@end
|
fzj270452746/M4CoreFoundation
|
M4Core/Classes/M4CoreFoundation.framework/Headers/M4CoreFoundation.h
|
<filename>M4Core/Classes/M4CoreFoundation.framework/Headers/M4CoreFoundation.h
//
// M4CoreFoundation.h
// M4CoreFoundation
//
// Created by hades on 2017/7/14.
// Copyright © 2017年 Hades. All rights reserved.
//
#import <UIKit/UIKit.h>
//! Project version number for M4CoreFoundation.
FOUNDATION_EXPORT double M4CoreFoundationVersionNumber;
//! Project version string for M4CoreFoundation.
FOUNDATION_EXPORT const unsigned char M4CoreFoundationVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <M4CoreFoundation/PublicHeader.h>
//Macros
#import <M4CoreFoundation/ColorMacro.h>
#import <M4CoreFoundation/DebugMacro.h>
#import <M4CoreFoundation/DeviceMacro.h>
//UIKit
#import <M4CoreFoundation/CoreUILabel.h>
#import <M4CoreFoundation/WebViewProgressView.h>
//Category
#import <M4CoreFoundation/UIView+Extension.h>
#import <M4CoreFoundation/UIImageView+Extension.h>
#import <M4CoreFoundation/NSString+Extension.h>
#import <M4CoreFoundation/UINavigationBar+Extension.h>
#import <M4CoreFoundation/UIButton+Extension.h>
#import <M4CoreFoundation/NSDate+Extension.h>
#import <M4CoreFoundation/CALayer+Extension.h>
#import <M4CoreFoundation/UIButton+Extension.h>
#import <M4CoreFoundation/UINavigationBar+Extension.h>
#import <M4CoreFoundation/UIViewController+MessageNotification.h>
#import <M4CoreFoundation/BaseUIViewController+NavigationButton.h>
//BaseClass
#import <M4CoreFoundation/CoreUIView.h>
#import <M4CoreFoundation/CoreUIViewController.h>
#import <M4CoreFoundation/CoreUIViewController+Notification.h>
#import <M4CoreFoundation/CoreTableViewCell.h>
#import <M4CoreFoundation/CoreCollectionViewCell.h>
#import <M4CoreFoundation/ModelBaseClass.h>
#import <M4CoreFoundation/ModelBaseClass+JSON.h>
#import <M4CoreFoundation/PageInfoModel.h>
#import <M4CoreFoundation/ShareInfoModel.h>
//ViewControllers
#import <M4CoreFoundation/RefreshFooter.h>
#import <M4CoreFoundation/RefreshHeader.h>
#import <M4CoreFoundation/BaseTableViewController.h>
#import <M4CoreFoundation/BaseUIViewController.h>
#import <M4CoreFoundation/BaseWebViewController.h>
#import <M4CoreFoundation/BaseCollectionViewController.h>
#import <M4CoreFoundation/BaseRefreshCollectionViewController.h>
#import <M4CoreFoundation/BaseRefreshTableViewController.h>
//Utility
#import <M4CoreFoundation/AppVersion.h>
#import <M4CoreFoundation/iOSVersion.h>
#import <M4CoreFoundation/CameraPhoto.h>
#import <M4CoreFoundation/Device.h>
//Foundation
#import <M4CoreFoundation/NSObject+JSON.h>
#import <M4CoreFoundation/CoreCache.h>
#import <M4CoreFoundation/CoreStore.h>
//SNS
#import <M4CoreFoundation/SocialShareSNS.h>
//Networking
#import <M4CoreFoundation/RESTfulAPIWrapper.h>
#import <M4CoreFoundation/HTTPStatusCodes.h>
#import <M4CoreFoundation/ServiceResultInfo.h>
//Notifications
#import <M4CoreFoundation/NotificationsName.h>
#import <M4CoreFoundation/MessageNotificationView.h>
#import <M4CoreFoundation/MessageNotificationManager.h>
|
fzj270452746/M4CoreFoundation
|
M4Core/Classes/M4CoreFoundation.framework/Headers/NSString+Extension.h
|
//
// NSString+Extension.h
// Patrol
//
// Created by Benjamin on 4/6/17.
// Copyright © 2017 Cloud4Magic. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSString (Extension)
+ (NSString *)createUUID;
- (NSString *)trimmingString;
- (NSString *)MD5Hash;
- (NSString *)SHA1;
- (NSNumber *)stringToNSNumber;
- (NSString *)reverse;
- (BOOL)stringContainsSubString:(NSString *)subString;
/**
nil, @"", @" ", @"\n" will Returns NO; otherwise Returns YES.
*/
- (BOOL)isNotBlank;
+ (BOOL)validateEmailWithString:(NSString*)email;
@end
|
fzj270452746/M4CoreFoundation
|
M4Core/Classes/M4CoreFoundation.framework/Headers/RefreshHeader.h
|
<filename>M4Core/Classes/M4CoreFoundation.framework/Headers/RefreshHeader.h
//
// RefreshHeader.h
// Patrol
//
// Created by Benjamin on 4/7/17.
// Copyright © 2017 Cloud4Magic. All rights reserved.
//
#import <MJRefresh/MJRefresh.h>
@interface RefreshHeader : MJRefreshGifHeader
@end
|
fzj270452746/M4CoreFoundation
|
M4Core/Classes/M4CoreFoundation.framework/Headers/BaseWebViewController.h
|
//
// BaseWebViewController.h
// Patrol
//
// Created by Benjamin on 4/7/17.
// Copyright © 2017 Cloud4Magic. All rights reserved.
//
#import "BaseUIViewController.h"
#import <WebKit/WebKit.h>
@class ShareInfoModel;
@interface BaseWebViewController : BaseUIViewController
@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) ShareInfoModel *sharingData;
- (void)setupWebViewBackButtonNavigationBar;
/**
* When you call this method, you should ensure that you had config share paltform activities that you want to share.
* If no, you should use SocialShareSNS class call - (void)configShareActivities:(NSArray< UIActivity *> *)applicationActivities;
*
*/
- (void)shareSNS;
@end
|
fzj270452746/M4CoreFoundation
|
M4Core/Classes/M4CoreFoundation.framework/Headers/ServiceResultInfo.h
|
<reponame>fzj270452746/M4CoreFoundation
//
// ServiceResultInfo.h
// SmallCP
//
// Created by Benjamin on 3/6/17.
// Copyright © 2017 Ananwu. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "HTTPStatusCodes.h"
@class ServiceResultInfo;
//Result Block
typedef void (^RESTfulResultHanlder)(id responsedata, ServiceResultInfo *resultStatusInfo);
/////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////
@interface ServiceResultInfo : NSObject
@property (nonatomic, assign) HTTPStatusCode statusCode;
@property (nonatomic, strong) NSError *errorInfo;
@property (nonatomic, copy) NSString *descriptionMsg;
@property (nonatomic, copy) NSString *errorCode;
@property (nonatomic, assign) NSTimeInterval timestamp;
@property (nonatomic, assign) BOOL finishStatus;
- (instancetype)initWithHTTPStatusCode:(HTTPStatusCode) httpCode errorInfo:(NSError *) error descriptionInfo:(NSString *) desription errorCode:(NSString *) code finishStatus:(BOOL) status;
- (instancetype)initWithErrorDescriptionInfo:(NSString *) desription errorCode:(NSString *) code finishStatus:(BOOL) status;
@end
/////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////
|
fzj270452746/M4CoreFoundation
|
M4Core/Classes/M4CoreFoundation.framework/Headers/CoreHeader.h
|
<filename>M4Core/Classes/M4CoreFoundation.framework/Headers/CoreHeader.h
//
// CoreHeader.h
// Patrol
//
// Created by Benjamin on 4/6/17.
// Copyright © 2017 Cloud4Magic. All rights reserved.
//
//Macros
#import "ColorMacro.h"
#import "DebugMacro.h"
#import "DeviceMacro.h"
//UIKit
#import "CoreUILabel.h"
//Category
#import "UIView+Extension.h"
#import "UIImageView+Extension.h"
#import "NSString+Extension.h"
#import "UINavigationBar+Extension.h"
#import "UIButton+Extension.h"
#import "NSDate+Extension.h"
#import "CALayer+Extension.h"
#import "UIButton+Extension.h"
#import "UINavigationBar+Extension.h"
//BaseClass
#import "CoreUIView.h"
#import "CoreUIViewController.h"
#import "CoreUIViewController+Notification.h"
#import "CoreTableViewCell.h"
#import "CoreCollectionViewCell.h"
#import "ModelBaseClass.h"
#import "ModelBaseClass+JSON.h"
#import "PageInfoModel.h"
#import "ShareInfoModel.h"
//Utility
#import "AppVersion.h"
#import "iOSVersion.h"
#import "CameraPhoto.h"
#import "Device.h"
//Foundation
#import "NSObject+JSON.h"
#import "CoreCache.h"
#import "CoreStore.h"
//SNS
#import "SocialShareSNS.h"
//Networking
#import "RESTfulAPIWrapper.h"
|
fzj270452746/M4CoreFoundation
|
M4Core/Classes/M4CoreFoundation.framework/Headers/CoreUIView.h
|
//
// CoreUIView.h
// Patrol
//
// Created by Benjamin on 4/6/17.
// Copyright © 2017 Cloud4Magic. All rights reserved.
//
#import <UIKit/UIKit.h>
// --- Core base UIView class root --- //
@interface CoreUIView : UIView
// Localization methods
@property (nonatomic, strong) NSString *localizationItemName;
- (NSString *)stringWithKey:(NSString *)key;
// UIView setup something
- (void)setup;
@end
// --- Core xib file base UIView class with IB_DESIGNABLE --- //
IB_DESIGNABLE
@interface CoreDesignableXibUIView : CoreUIView
- (id)initWithXib;
@end
|
fzj270452746/M4CoreFoundation
|
Example/M4Core/M4ViewController.h
|
//
// M4ViewController.h
// M4Core
//
// Created by <EMAIL> on 07/17/2017.
// Copyright (c) 2017 <EMAIL>. All rights reserved.
//
@import UIKit;
@interface M4ViewController : UIViewController
@end
|
fzj270452746/M4CoreFoundation
|
M4Core/Classes/M4CoreFoundation.framework/Headers/CoreCollectionViewCell.h
|
<gh_stars>0
//
// CoreCollectionViewCell.h
// Patrol
//
// Created by Benjamin on 4/6/17.
// Copyright © 2017 Cloud4Magic. All rights reserved.
//
#import <UIKit/UIKit.h>
// --- Core CollectionViewCell class root --- //
@interface CoreCollectionViewCell : UICollectionViewCell
// Localization methods
@property (nonatomic, strong) NSString *localizationItemName;
- (NSString *)stringWithKey:(NSString *)key;
// Setup something in here
- (void)setup;
+ (__kindof UICollectionViewCell *)reusableCellDequeueCollectionView:(UICollectionView *) collectionView forIndexPath:(NSIndexPath *)indexPath;
+ (NSString *)cellReuseIdentifier;
+ (CGSize)sizeOfCollectionViewCell;
@end
// --- Core Xib file CollectionViewCell class --- //
IB_DESIGNABLE
@interface CoreXibCollectionViewCell : CoreCollectionViewCell
+ (__kindof UICollectionViewCell *)reusableCellDequeueCollectionView:(UICollectionView *) collectionView forIndexPath:(NSIndexPath *)indexPath;
@end
|
fzj270452746/M4CoreFoundation
|
M4Core/Classes/M4CoreFoundation.framework/Headers/NotificationsName.h
|
//
// NotificationsName.h
// M4CLibrary
//
// Created by hades on 2017/7/12.
// Copyright © 2017年 Hades. All rights reserved.
//
#import <Foundation/Foundation.h>
extern NSString *const ExpiredToken ;
|
fzj270452746/M4CoreFoundation
|
Example/Pods/Target Support Files/M4Core/M4Core-umbrella.h
|
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#else
#ifndef FOUNDATION_EXPORT
#if defined(__cplusplus)
#define FOUNDATION_EXPORT extern "C"
#else
#define FOUNDATION_EXPORT extern
#endif
#endif
#endif
#import "AppVersion.h"
#import "BaseCollectionViewController.h"
#import "BaseRefreshCollectionViewController.h"
#import "BaseRefreshTableViewController.h"
#import "BaseTableViewController.h"
#import "BaseUIViewController+NavigationButton.h"
#import "BaseUIViewController.h"
#import "BaseWebViewController.h"
#import "CALayer+Extension.h"
#import "CameraPhoto.h"
#import "ColorMacro.h"
#import "CoreCache.h"
#import "CoreCollectionViewCell.h"
#import "CoreHeader.h"
#import "CoreStore.h"
#import "CoreTableViewCell.h"
#import "CoreUILabel.h"
#import "CoreUIView.h"
#import "CoreUIViewController+Notification.h"
#import "CoreUIViewController.h"
#import "DebugMacro.h"
#import "Device.h"
#import "DeviceMacro.h"
#import "HTTPStatusCodes.h"
#import "iOSVersion.h"
#import "M4CoreFoundation.h"
#import "MessageNotificationManager.h"
#import "MessageNotificationView.h"
#import "ModelBaseClass+JSON.h"
#import "ModelBaseClass.h"
#import "NotificationsName.h"
#import "NSDate+Extension.h"
#import "NSObject+JSON.h"
#import "NSString+Extension.h"
#import "PageInfoModel.h"
#import "RefreshFooter.h"
#import "RefreshHeader.h"
#import "RESTfulAPIWrapper.h"
#import "ServiceResultInfo.h"
#import "ShareInfoModel.h"
#import "SocialShareSNS.h"
#import "UIButton+Extension.h"
#import "UIImageView+Extension.h"
#import "UINavigationBar+Extension.h"
#import "UIView+Extension.h"
#import "UIViewController+MessageNotification.h"
#import "WebViewProgressView.h"
#import "CoreNibFileCache.h"
#import "RESTfulBaseService.h"
FOUNDATION_EXPORT double M4CoreVersionNumber;
FOUNDATION_EXPORT const unsigned char M4CoreVersionString[];
|
fzj270452746/M4CoreFoundation
|
M4Core/Classes/M4CoreFoundation.framework/Headers/BaseCollectionViewController.h
|
<reponame>fzj270452746/M4CoreFoundation<filename>M4Core/Classes/M4CoreFoundation.framework/Headers/BaseCollectionViewController.h
//
// BaseCollectionViewController.h
// Patrol
//
// Created by Benjamin on 4/7/17.
// Copyright © 2017 Cloud4Magic. All rights reserved.
//
#import "BaseUIViewController.h"
@interface BaseCollectionViewController : BaseUIViewController <UICollectionViewDelegate, UICollectionViewDataSource>
@property (nonatomic, weak) IBOutlet UICollectionView *collectionView;
@end
|
fzj270452746/M4CoreFoundation
|
M4Core/Classes/M4CoreFoundation.framework/Headers/RESTfulAPIWrapper.h
|
<reponame>fzj270452746/M4CoreFoundation<gh_stars>0
#import <UIKit/UIKit.h>
#import "ServiceResultInfo.h"
//HTTP Operation;
#define OPERATION_GET @"GET"
#define OPERATION_POST @"POST"
#define OPERATION_PUT @"PUT"
#define OPERATION_DELETE @"DELETE"
//Image Operation
#define OPERATION_IMAGE_DOWNLOAD @"GET"
#define OPERATION_IMAGE_UPLOAD @"POST"
@class ServiceResultInfo;
/////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////
@interface RESTfulAPIWrapper : NSObject
+ (instancetype)sharedInstance;
- (NSURLSessionDataTask *)operation:(NSString *)action urlResource:(NSString *)url actionCompletion:(RESTfulResultHanlder) completion;
- (NSURLSessionDataTask *)operation:(NSString *)action urlResource:(NSString *)url urlParameters:(NSDictionary *)params actionCompletion:(RESTfulResultHanlder) completion;
- (NSURLSessionDataTask *)operation:(NSString *)action urlResource:(NSString *)url urlParameters:(NSDictionary *)params imgName:(NSString *) name uploadImage:(UIImage *)image actionCompletion:(RESTfulResultHanlder) completion;
@end
/////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////
|
khushimakhub/c-code
|
Check sum of two prime numbers.c
|
two prime numbers −
Live Demo
#include <stdio.h>
int Sum(int n);
int main(){
int num, i;
printf("Enter number: ");
scanf("%d", &num);
int flag = 0;
for(i = 2; i <= num/2; ++i){
if (sum(i) == 1){
if (sum(num-i) == 1){
printf("\nThe given %d can be expressed as the sum of %d and %d\n\n", num, i, num - i);
flag = 1;
}
}
}
if (flag == 0)
printf("The given %d cannot be expressed as the sum of two prime numbers\n", num);
return 0;
}
int sum(int n){
int i, isPrime = 1;
for(i = 2; i <= n/2; ++i){
if(n % i == 0){
isPrime = 0;
break;
}
}
return isPrime;
}
|
khushimakhub/c-code
|
Data base management.c
|
<filename>Data base management.c
#include<iostream>
#include<string>
#include<conio.h>
#include<stdlib.h>
using namespace std;
int main();
void show_data(int searchkey); //function used to show data to end-user.
void get_data(int i); //function used to obtain data from end-user.
void search_student(int searchkey);
void add_student(); //This function is used to add record of new student.
void edit_student(int idnumber); //function is used to edit existing record.
void fullscreen();
int ts;
struct student //Structure student is made to store student attributes.
{
int rollno;
string name;
string fname;
string cell;
string dob;
string address;
};
student rec[50]; //This is basic array of defined structure to sore data.
int main()
{
system("CLS");
system("color B1");
int choice; //int variable used to determine which operation user want to do.
int idnumber; //int variable used to record ID number whih user want to edit.
int searchkey; //int variable to store student roll_no by which user can search.
cout<<"Enter The Total Number of Student(s)- Max 50: ";
cin>>ts;
while(ts--)
{
cout<<"\n\t\tWhat do you want to do?"<<endl;
cout<<"\t\t----------------------"<<endl;
cout<<"\t\t1-Add student"<<endl;
cout<<"\t\t2-Edit student"<<endl;
cout<<"\t\t3-Search student"<<endl;
cout<<"\t\t4-Quit Program"<<endl;
cout<<"\t\t----------------------"<<endl;
cout<<"Enter your choice: ";
cin>>choice;
switch(choice)
{
case 1: //If user presses 1 then student adding module would be displayed.
add_student();
break;
case 2: //If there are no records in array then it will ask the user to input records first.
if(rec[0].rollno==0)
{
cout<<"Please Add sudents first."<<endl;
system("pause");
main();
}
else //If records are present in array then it will show table.
{
cout<<endl;
cout<<"--------------------------------------------------------------------------------"<<endl;
cout<<"---------------------------Student record Table---------------------------------"<<endl;
cout<<"--------------------------------------------------------------------------------"<<endl;
cout<<"ID "<<"Roll "<<"Name "<<"Father\tCell no. "<<"DOB "<<"Address\n\n";
cout<<"--------------------------------------------------------------------------------"<<endl;
for(int i=0;i<=ts;i++)
{
show_data(i); //funtion is called with index value to show data.
}
cout<<"--------------------------------------------------------------------------------"<<endl;
cout<<"Which ID number your want to edit: ";
cin>>idnumber; //Asking the user at which ID he wants to make a change.
if(idnumber>ts || idnumber<0) //Validating the ID number.
{
cout<<"\nInvalid ID Number."<<endl;
}
else
{
edit_student(idnumber); //Passing ID number to Edit Function.
}
}
break;
case 3:
if(rec[0].rollno==0) //If no record exist then ask the user o enter records first.
{
cout<<"Please Add sudents first."<<endl;
system("pause");
main(); //Return to main so user can input new record.
}
else
{
cout<<"Enter roll_no of student you want to search: ";
cin>>searchkey; //roll_no as the search key can be entered by user.
search_student(searchkey);}
break;
case 4:
return 0; //Terminating the records.
break;
default: //Default value for ivalid Input.
cout<<"Invalid number."<<endl;
system("pause");
main();
}
}
return 0;
}
void get_data(int i) //Function for receiving data from user and populatiing the variables with values.
{
cout<<"Enter student roll number in format(1XXX): ";
cin>>rec[i].rollno;
cout<<"Enter student name: ";
cin>>rec[i].name;
cout<<"Enter student's Father name: ";
cin>>rec[i].fname;
cout<<"Enter student's cell phone number: ";
cin>>rec[i].cell;
cout<<"Enter student's Date of Birth(dd/mm/yyyy): ";
cin>>rec[i].dob;
cout<<"Enter student's Address: ";
cin>>rec[i].address;
}
void show_data(int searchkey) //Function for showing data on the screen.
{
int i=searchkey;
cout<<i<<" ";
cout<<rec[i].rollno<<" ";
cout<<rec[i].name<<" ";
cout<<rec[i].fname<<"\t";
cout<<rec[i].cell<<" ";
cout<<rec[i].dob<<" ";
cout<<rec[i].address<<"\n\n";
}
void search_student(int searchkey)
{
for(int i=0;i<=ts;i++) //Loop thrugh complete array.
{
if(rec[i].rollno==searchkey) //If roll number matches to search term.
{
cout<<"ID "<<"Roll "<<"Name "<<"Father\tCell no. "<<"DOB "<<"Address\n\n";
show_data(i); //A function is used inside another function.
}
}
}
void add_student() //This function is used to add record of new student.
{
for(int i=0;i<=ts;i++)
{
get_data(i); //Loop was processed 5 times to get input for 5 students.
}
system("CLS");
cout<<endl;
cout<<"--------------------------------------------------------------------------------"<<endl;
cout<<"---------------------------Student record Table---------------------------------"<<endl;
cout<<"--------------------------------------------------------------------------------"<<endl;
cout<<"ID "<<"Roll "<<"Name "<<"Father\tCell no. "<<"DOB "<<"Address\n\n";
cout<<"--------------------------------------------------------------------------------"<<endl;
for(int i=0;i<=ts;i++)
{
show_data(i); //Loop was processed for 5 times to show obtained records.
}
cout<<"--------------------------------------------------------------------------------"<<endl;
cout<<"---------------------------------FINISH-----------------------------------------"<<endl;
cout<<"--------------------------------------------------------------------------------"<<endl;
system("pause");
main(); //Return to main function to again show menu.
}
void edit_student(int idnumber) //function is used to edit existing record.
{
for(int i=0;i<=ts;i++) //Loop is started.
{
if(idnumber==i) //Through loop every value is compared with search term.
{
cout<<"\nExisted information about this record.\n\n";
cout<<"--------------------------------------------------------------------------------"<<endl;
cout<<"ID "<<"Roll "<<"Name "<<"Father\tCell no. "<<"DOB "<<"Address\n\n";
cout<<"--------------------------------------------------------------------------------"<<endl;
show_data(i); //Load information for existing record.
cout<<"\n\nEnter new data for above shown record.\n\n";
get_data(i); //Inputing data for that specific record.
cout<<"\n\nRecord updated successfully."<<endl;
system("pause");
main(); //Return to main function.
}
}
}
|
gurki/dispin
|
source/common.h
|
<gh_stars>1-10
#ifndef COMMON_H
#define COMMON_H
////////////////////////////////////////////////////////////////////////////////
// forward declarations
struct vec2;
void mark(
uchar* data,
const int width,
const int height,
const uchar value = 0,
const uchar mark = 255,
const uchar nonMark = 0
);
void sharpenEdges(
const uchar* data,
const int width,
const int height,
uchar* out,
const uchar thresh = 0
);
////////////////////////////////////////////////////////////////////////////////
struct vec2
{
vec2(const int x__ = 0, const int y__ = 0) :
x(x__),
y(y__)
{};
int x;
int y;
};
////////////////////////////////////////////////////////////////////////////////
// find and sharpen single-pixel edges
// e.g. [0 30 200 210] -> [0 200 200 210]
// CARE: does not work in place!
void sharpenEdges(
const uchar* data,
const int width,
const int height,
uchar* out,
const uchar thresh)
{
for (int row = 0; row < height; row++)
{
for (int col = 0; col < width; col++)
{
const int id = row * width + col;
out[id] = data[id];
// nothing to do for mask pixels
if (data[id] == 0) {
continue;
}
const uchar& val = data[id];
// get all pixel neighbours
const uchar vall = col > 0 ? data[id-1] : val;
const uchar valr = col < width-1 ? data[id+1] : val;
const uchar valu = row > 0 ? data[id-width] : val;
const uchar vald = row < height - 1 ? data[id+width] : val;
const uchar valul = row > 0 && col > 0 ? data[id-1-width] : val;
const uchar valur = row > 0 && col < width-1 ? data[id+1-width] : val;
const uchar valdl = row < height-1 && col > 0 ? data[id-1+width] : val;
const uchar valdr = row < height-1 && col < width-1 ? data[id+1+width] : val;
// is current pixel adjacent to mask?
const uchar min1 = MIN(MIN(vall, valr), MIN(valu, vald));
const uchar min2 = MIN(MIN(valul, valur), MIN(valdl, valdr));
const uchar min = MIN(min1, min2);
if (min <= thresh)
{
// if so, assign it the brightes neighbour to sharpen the edge
const uchar max1 = MAX(MAX(vall, valr), MAX(valu, vald));
const uchar max2 = MAX(MAX(valul, valur), MAX(valdl, valdr));
const uchar max = MAX(max1, max2);
out[id] = max;
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
// mark pixels with a certain value in a specific color
// mark all other pixels in another color
// default:
// set all zero pixels to white (255)
// set all non-zero pixels to black (0)
void mark(
uchar* data,
const int width,
const int height,
const uchar value,
const uchar mark,
const uchar nonMark)
{
for (int row = 0; row < height; row++)
{
for (int col = 0; col < width; col++)
{
const int id = row * width + col;
if (data[id] == value) {
data[id] = mark;
} else {
data[id] = nonMark;
}
}
}
}
#endif
|
gurki/dispin
|
source/linear.h
|
<filename>source/linear.h<gh_stars>1-10
#ifndef LINEAR_H
#define LINEAR_H
#include "common.h"
/*
comments in the vertical versions
*/
////////////////////////////////////////////////////////////////////////////////
// forward declarations
void fillLinearHorizontalSegment(
uchar* data,
const int width,
const int height,
vec2 pos0,
vec2 pos1
);
void fillLinearHorizontal(
uchar* data,
const int width,
const int height,
const int offset = 0,
const uchar thresh = 0
);
void fillLinearVerticalSegment(
uchar* data,
const int width,
const int height,
vec2 pos0,
vec2 pos1
);
void fillLinearVertical(
uchar* data,
const int width,
const int height,
const int offset = 0,
const uchar thresh = 0
);
void fillLinear(
uchar* data,
const int width,
const int height,
const int offset = 0,
const uchar thresh = 0,
const bool average = true
);
////////////////////////////////////////////////////////////////////////////////
void fillLinearHorizontalSegment(
uchar* data,
const int width,
const int height,
vec2 pos0,
vec2 pos1)
{
pos0.x = MAX(pos0.x, 0);
pos1.x = MIN(pos1.x, width - 1);
const int id0 = pos0.y * width + pos0.x;
const int id1 = pos1.y * width + pos1.x;
const uchar val0 = data[id0] > 0 ? data[id0] : data[id1];
const uchar val1 = data[id1] > 0 ? data[id1] : data[id0];
const int delta = (int)val1 - (int)val0;
const int dist = pos1.x - pos0.x;
float n = dist;
for (int col = pos1.x; col >= pos0.x; col--)
{
const int id = pos0.y * width + col;
data[id] = val0 + (uchar)(delta * n / dist);
n -= 1.0f;
}
}
////////////////////////////////////////////////////////////////////////////////
void fillLinearHorizontal(
uchar* data,
const int width,
const int height,
const int offset,
const uchar thresh)
{
for (int row = 0; row < height; row++)
{
bool isSearching = false;
vec2 pos0;
for (int col = 0; col < width; col++)
{
const int id = row * width + col;
if (!isSearching && data[id] <= thresh) {
isSearching = true;
pos0 = vec2(col - 1 - offset, row);
}
if (isSearching && (data[id] > thresh || col == width - 1)) {
vec2 pos1(col + offset, row);
fillLinearHorizontalSegment(data, width, height, pos0, pos1);
isSearching = false;
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
void fillLinearVerticalSegment(
uchar* data,
const int width,
const int height,
vec2 pos0,
vec2 pos1)
{
// don't go out of image range
pos0.y = MAX(pos0.y, 0);
pos1.y = MIN(pos1.y, height - 1);
// get linear indices
const int id0 = pos0.y * width + pos0.x;
const int id1 = pos1.y * width + pos1.x;
// get start and end values
// assign other side if we started/ended at a border
const uchar val0 = data[id0] > 0 ? data[id0] : data[id1];
const uchar val1 = data[id1] > 0 ? data[id1] : data[id0];
// create linear function
const int delta = (int)val1 - (int)val0;
const int dist = pos1.y - pos0.y;
float n = dist;
// go from end to start and assign linearly interpolated values
for (int row = pos1.y; row >= pos0.y; row--)
{
const int id = row * width + pos0.x;
data[id] = val0 + (uchar)(delta * n / dist);
n -= 1.0f;
}
}
////////////////////////////////////////////////////////////////////////////////
void fillLinearVertical(
uchar* data,
const int width,
const int height,
const int offset,
const uchar thresh)
{
for (int col = 0; col < width; col++)
{
bool isSearching = false;
vec2 pos0;
for (int row = 0; row < height; row++)
{
const int id = row * width + col;
// activate search mode if we found a dark enough pixel
if (!isSearching && data[id] <= thresh) {
isSearching = true;
// remember starting position
pos0 = vec2(col, row - 1 - offset);
}
// if we reached a bright pixel again or the end of the image, fill the line segment
if (isSearching && (data[id] > thresh || row == height - 1)) {
vec2 pos1(col, row + offset);
fillLinearVerticalSegment(data, width, height, pos0, pos1);
isSearching = false;
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
void fillLinear(
uchar* data,
const int width,
const int height,
const int offset,
const uchar thresh,
const bool average)
{
// fill hor and vert seperately
uchar vert[width * height];
std::memcpy(vert, data, sizeof vert);
fillLinearHorizontal(data, width, height, offset, thresh);
fillLinearVertical(vert, width, height, offset, thresh);
// blend
for (int i = 0; i < width * height; i++)
{
if (average) {
data[i] = 0.5f * data[i] + 0.5f * vert[i];
} else {
data[i] = MAX(data[i], vert[i]);
}
}
}
#endif
|
gurki/dispin
|
source/mipmap.h
|
<reponame>gurki/dispin
#ifndef MIPMAP_H
#define MIPMAP_H
////////////////////////////////////////////////////////////////////////////////
static inline int getIdAtScale(
const int width,
const int height,
const int x,
const int y,
const int scale)
{
// const int xoff = width * (1 - pow(2, floor(-scale / (3.0f / 2.0f))));
// const int yoff = height * (1 - pow(2, ceil(-scale / 2.0f)));
const int xoff = (scale == 0 ? 0 : 2.0f / 3.0f * width);
const int yoff = height * (scale == 0 ? 0 : 1 - pow(2, -scale + 1));
const int xs = floor(x / pow(2, scale));
const int ys = floor(y / pow(2, scale));
return (yoff + ys) * width + (xoff + xs);
}
////////////////////////////////////////////////////////////////////////////////
void fillPyramid(
uchar* data,
const int width,
const int height)
{
// allocate single channel mipmap
const int width2 = 3.0f / 2.0f * width;
const int height2 = height;
uchar mipmap[width2 * height2];
memset(mipmap, 0, sizeof mipmap);
// copy data to first mipmap level
for (int row = 0; row < height; row++)
{
for (int col = 0; col < width; col++)
{
const int id1 = row * width + col;
const int id2 = row * width2 + col;
mipmap[id2] = data[id1];
}
}
// build all levels up to 2x2 or even 1x1
for (int i = 1; i < ceil(log(width)) + 3; i++)
{
for (int row = 0; row < height; row += 2 * i)
{
for (int col = 0; col < width; col += 2 * i)
{
// get pixel neighbours on previous level
const int s = 2 * (i - 1);
const uchar c = mipmap[getIdAtScale(width2, height2, col, row, i - 1)];
const uchar r = mipmap[getIdAtScale(width2, height2, col + s, row, i - 1)];
const uchar rd = mipmap[getIdAtScale(width2, height2, col + s, row + s, i - 1)];
const uchar d = mipmap[getIdAtScale(width2, height2, col, row + s, i - 1)];
// compute downsampled value
// const uchar val = c; // exact
const uchar val = MAX(MAX(c, r), MAX(rd, d)); // max
// const uchar val = ((int)c + r + rd + d) / 4; // average
// assign value at current level
const int id = getIdAtScale(width2, height2, col, row, i);
mipmap[id] = val;
}
}
}
// fill maks in original data with neighbourhood information
for (int row = 0; row < height; row ++)
{
for (int col = 0; col < width; col ++)
{
int l = 0;
const int maxl = ceil(log(width)) + 3;
int id = row * width + col;
uchar val = data[id];
while(val == 0 && l++ <= maxl) {
const int ids = getIdAtScale(width2, height2, col, row, l);
val = mipmap[ids];
}
data[id] = val;
}
}
// cv::Mat img = cv::Mat(height, width, CV_8UC1, data);
// cv::imshow("window", img);
// cv::waitKey();
}
#endif
|
gurki/dispin
|
source/floodfill.h
|
#ifndef FLOOD_FILL_H
#define FLOOD_FILL_H
#include <stack>
using namespace std;
////////////////////////////////////////////////////////////////////////////////
// forward declarations
void floodFillIterative(
uchar* data,
const int width,
const int height,
const vec2& pos,
const uchar value,
const uchar maskValue
);
void floodFill(
uchar* data,
const int width,
const int height,
const vec2& pos,
const uchar value,
const uchar maskValue
);
void layerFloodFill(
uchar* data,
const int width,
const int height
);
////////////////////////////////////////////////////////////////////////////////
void floodFillIterative(
uchar* data,
const int width,
const int height,
const vec2& pos,
const uchar value,
const uchar maskValue)
{
stack<vec2> poss;
poss.push(pos);
while(!poss.empty())
{
const vec2& curr = poss.top();
if (curr.x < 0 || curr.x >= width || curr.y < 0 || curr.y >= height) {
return;
}
const int id = curr.y * width + curr.x;
if (data[id] != maskValue || data[id] == value) {
return;
}
data[id] = value;
poss.pop();
poss.push(vec2(pos.x - 1, pos.y));
poss.push(vec2(pos.x + 1, pos.y));
poss.push(vec2(pos.x, pos.y - 1));
poss.push(vec2(pos.x, pos.y + 1));
}
}
////////////////////////////////////////////////////////////////////////////////
void floodFill(
uchar* data,
const int width,
const int height,
const vec2& pos,
const uchar value,
const uchar maskValue)
{
// out of image
if (pos.x < 0 || pos.x >= width || pos.y < 0 || pos.y >= height) {
return;
}
const int id = pos.y * width + pos.x;
// not a hole
if (data[id] != maskValue) {
return;
}
// fill current pixel and proceed to neighbours
data[id] = value;
floodFill(data, width, height, vec2(pos.x - 1, pos.y), value, maskValue);
floodFill(data, width, height, vec2(pos.x + 1, pos.y), value, maskValue);
floodFill(data, width, height, vec2(pos.x, pos.y - 1), value, maskValue);
floodFill(data, width, height, vec2(pos.x, pos.y + 1), value, maskValue);
}
////////////////////////////////////////////////////////////////////////////////
void layerFloodFill(
uchar* data,
const int width,
const int height)
{
// (prioritised) fill holes from fore- (255) to background (1)
for (uchar layer = 255; layer > 0; layer--)
{
for (int row = 0; row < height; row++)
{
for (int col = 0; col < width; col++)
{
const int id = row * width + col;
// if we found a pixel on the current layer, fill all holes surrounding it
if (data[id] == layer)
{
floodFill(data, width, height, vec2(col - 1, row), layer, 0);
floodFill(data, width, height, vec2(col + 1, row), layer, 0);
floodFill(data, width, height, vec2(col, row - 1), layer, 0);
floodFill(data, width, height, vec2(col, row + 1), layer, 0);
}
}
}
}
}
#endif
|
jcg/d-tailor
|
3rdParty/transterm/map-output.h
|
<gh_stars>10-100
/* This file is part of TransTerm v2.0 BETA and is covered by the GNU GPL
* License version 2.0. See file LICENSE.txt for more details. */
#ifndef MAP_OUTPUT_H
#define MAP_OUTPUT_H
#include <iostream>
#include "seq.h"
#include "conf.h"
void output_map(ostream &, const Genome &, Confidence &, int=90, bool=true, bool=true);
void output_best_term(ostream &, const Confidence &, const Genome &);
#endif
|
jcg/d-tailor
|
3rdParty/transterm/analysis.h
|
<gh_stars>10-100
/* This file is part of TransTerm v2.0 BETA and is covered by the GNU GPL
* License version 2.0. See file LICENSE.txt for more details. */
#ifndef ANALYSIS_H
#define ANALYSIS_H
void plot_tthits_vs_terms(ostream &, Confidence &, Genome &);
void t2t_hitanal(ostream &, const Genome &, Confidence &, int, bool );
unsigned count_starts_in_genes(const Seq &, Direction dir);
#endif
|
jcg/d-tailor
|
3rdParty/transterm/ermolaeva-score.h
|
/* This file is part of TransTerm v2.0 BETA and is covered by the GNU GPL
* License version 2.0. See file LICENSE.txt for more details. */
#ifndef ERMOLAEVA_SCORE_H
#define ERMOLAEVA_SCORE_H
#include "seq.h"
typedef Energy (*HPScoreFcn)(char, char);
Energy tail_score(const Term &, Direction);
Energy hairpin_score(HPScoreFcn, const Term & );
Energy reverse_pair(char, char);
Energy forward_pair(char, char);
Energy loop_penalty(int);
void set_loop_pen(const string &);
//==== simple scores ===
/*
const Energy GC = -3;
const Energy AU = -2;
const Energy GU = -1;
const Energy MM = 4;
*/
//=== SVM model scores ===
/*
const Energy GC = -1.99;
const Energy AU = -0.99;
const Energy GU = 1;
const Energy MM = 4;
const float LOOP_PENALTY[20]={1000,1000,1000,
-0.75,0.25,1.24,
1.25, 2.50, 3.75, 5.00, 6.25, 7.50, 8.75,
10.00, 11.25, 12.50, 13.75, 15.00, 16.25, 17.5};
*/
//=== SVM model scores ===
/*
const Energy GC = -1;
const Energy AU = -0.67;
const Energy GU = 0.46;
const Energy MM = 1.83;
const float LOOP_PENALTY[20]={1000,1000,1000,
0.18, 0.0, 0.21,
0.33, 0.66, 0.99, 1.32, 1.65, 1.98, 2.31,
2.64, 2.97, 3.30, 3.63, 3.96, 4.29 };
*/
//=== Ermolaeva et al Scores ===
extern Energy ENERGY_CUTOFF;
extern Energy TAIL_CUTOFF;
extern Energy LOOP_PENALTY[20];
// stem energies
extern Energy GC;
extern Energy AU;
extern Energy GU;
extern Energy MM;
extern Energy GAP;
extern Energy MM_OPEN;
// stem size limits
//const unsigned MAX_STEM = 22;
//const unsigned MAX_LOOP = 13;
//const int MAX_STEM = 22;
//const int MAX_STEM = 200;
//const int MAX_LOOP = 13;
//const int MAX_HP = 2*MAX_STEM + MAX_LOOP + 2;
extern int MIN_STEM;
extern int MIN_LOOP;
extern int MAX_STEM;
extern int MAX_LOOP;
extern int MAX_HP;
const int REALLY_MAX_HP = 1000; // size of the allocated table
// required # of U's in the window next to the tail
extern int UWINDOW_SIZE;
extern int UWINDOW_REQUIRE;
// the energy of a hairpin pair on the forward strand
inline
Energy
forward_pair(char ch1, char ch2)
{
if((ch1 == 'G' && ch2 == 'C') || (ch1 == 'C' && ch2 == 'G')) return GC;
if((ch1 == 'T' && ch2 == 'A') || (ch1 == 'A' && ch2 == 'T')) return AU;
if((ch1 == 'T' && ch2 == 'G') || (ch1 == 'G' && ch2 == 'T')) return GU;
if(ch1 == PADDING_CHAR || ch2 == PADDING_CHAR) return 1000.0;
return MM;
}
// the energy of a hairpin pair on the reverse strand
inline
Energy
reverse_pair(char ch1, char ch2)
{
if((ch1 == 'G' && ch2 == 'C') || (ch1 == 'C' && ch2 == 'G')) return GC;
if((ch1 == 'T' && ch2 == 'A') || (ch1 == 'A' && ch2 == 'T')) return AU;
if((ch1 == 'A' && ch2 == 'C') || (ch1 == 'C' && ch2 == 'A')) return GU;
if(ch1 == PADDING_CHAR || ch2 == PADDING_CHAR) return 1000.0;
return MM;
}
// calculate the loop penalty
inline
Energy
loop_penalty(int len)
{
if(len > MAX_LOOP) return 1000.0;
// if(len >= sizeof(LOOP_PENALTY)/sizeof(float)) return 1000.0;
return LOOP_PENALTY[len];
}
#endif
|
jcg/d-tailor
|
3rdParty/transterm/gene-reader.h
|
<gh_stars>10-100
/* This file is part of TransTerm v2.0 BETA and is covered by the GNU GPL
* License version 2.0. See file LICENSE.txt for more details. */
#ifndef GENE_READER_H
#define GENE_READER_H
#include <iostream>
#include <fstream>
#include <string>
#include "seq.h"
using namespace std;
// abstract base class of all classes that can read annotation files
class GeneReader
{
public:
virtual bool read_genes(Genome &) = 0;
virtual ~GeneReader() {};
virtual bool good() = 0;
};
// read a .coords file from TIGR CMR
class CoordsReader : public GeneReader
{
public:
CoordsReader(const string &);
virtual ~CoordsReader() {}
bool read_genes(Genome &);
bool good() { return _in.good(); }
private:
ifstream _in;
};
// read a .ptt file from GenBank
class PTTReader : public GeneReader
{
public:
PTTReader(const string &);
virtual ~PTTReader() {}
bool read_genes(Genome &);
bool good() { return _in.good(); }
private:
ifstream _in;
string _id;
};
// return the correct reader class given a filename
GeneReader * gene_reader_factory(const string &);
#endif
|
jcg/d-tailor
|
3rdParty/transterm/seq.h
|
/* This file is part of TransTerm v2.0 BETA and is covered by the GNU GPL
* License version 2.0. See file LICENSE.txt for more details. */
#ifndef SEQ_H
#define SEQ_H
#include <string>
#include <vector>
#include <list>
#include <cstdlib>
#include <cstdio>
#include <cstring>
using namespace std;
typedef double Energy;
enum Direction {REVERSE=-1, BIDIR=0, FORWARD=1};
enum RegionType { GENE, HEAD2TAIL, TAIL2TAIL, HEAD2HEAD };
typedef const char * SeqPtr;
class Seq;
class Confidence;
// Represents a region of a sequence [start,end] (both pointers are inclusive)
struct Region
{
string name; // a description of the region
SeqPtr start, end; // pointers into seq at the start & end of the seq
const Seq * seq; // seq of which this is a region
string desc;
Region(const string & n, const Seq * seqq, SeqPtr s, SeqPtr e,
const string & d = "") :
name(n), start(s), end(e), seq(seqq), desc(d) {}
Region() : name(""), start(0), end(0), seq(0) {}
virtual ~Region() {}
// Direction of the region. Regions always "run" from start to end
// If end < start, the dreiction is "REVERSE"
virtual Direction dir() const
{
return (end < start) ? REVERSE : FORWARD;
}
// the 'left' of the region is always the 5' end of the sequence,
// regardless of the direction of the region. The 'right', likewise, is
// always the 3' end.
SeqPtr left() const { return min(start,end); }
SeqPtr right() const { return max(start,end); }
int length() const { return abs(start-end) + 1; }
};
// represents a terminator region. the 'region' is defined as the hairpin
// sequence --- the tail 'region' is not included.
struct Term : public Region
{
// terminator geometry
int gap;
int stem_len, loop_len;
list<int> gaps;
// terminator scores
Energy hp_energy, tail_energy;
int conf;
// a link to an 'equiv' term
const Term * partner;
list<Term*> opp_overlapping, overlapping;
Term() : Region(), gap(0), stem_len(0), loop_len(0)
{
init0();
lst = rst = 0;
}
Term(const Seq * s, Direction d, SeqPtr base, int sl,
int ll, int g)
: Region("", s, base - d*(geolength(sl, ll, g) - 1), base),
gap(g), stem_len(sl), loop_len(ll), sense(d)
{
init0();
rst = right() - stem_len + 1 - ((gap>0)?1:0);
lst = right_stem_top() - loop_len - 1;
}
Term(const Seq * s, Direction d, SeqPtr lsb1, SeqPtr lst1,
SeqPtr rst1, SeqPtr rsb1, list<int> & glist, Energy hpe = 0)
: Region("", s, min(lsb1, rsb1), max(lsb1, rsb1))
{
init0();
lst = min(lst1, rst1);
rst = max(lst1, rst1);
sense = d;
hp_energy = hpe;
loop_len = rst - lst - 1;
stem_len = right() - rst + 1;
// for backwards compatability, gap = true if there is a gap
gap = (abs(lst - left() + 1) != stem_len) ? 1 : 0;
gaps = glist;
}
virtual ~Term()
{
// if(gaps)
// {
// delete gaps;
// gaps = 0;
// }
}
Direction dir() const { return sense; }
Direction & dir() { return sense; }
// accessors for the energy assigned to this terminator
enum EnergyKind {TAIL, HAIRPIN};
Energy energy(EnergyKind k) const
{
return (k==HAIRPIN)?hp_energy:tail_energy;
}
// Pointers into the geometry of the terminator
SeqPtr left_stem_base() const { return left(); }
SeqPtr right_stem_base() const { return right(); }
SeqPtr left_stem_top() const { return lst; }
SeqPtr right_stem_top() const { return rst; }
private:
// return the size of the hairpin with the given geometry
int
geolength(int stem_len, int loop_len, int gap)
{
return 2*stem_len + loop_len + ((gap!=0)?1:0);
}
// set the things that shd be 0 to 0
void
init0()
{
hp_energy = tail_energy = 0.0;
conf = 0;
partner = 0;
}
Direction sense;
SeqPtr lst, rst;
};
typedef vector<const Term *> ConstTermVec;
// Represents a sequence
struct Seq
{
string name;
string desc;
unsigned long length; // number of characters in the seq
char * dna; // pointer to the sequence data
vector<Term*> terms; // list of Term features
vector<Region*> genes; // list of gene features
Seq() : name(""), desc(""), length(0), dna(0) {}
~Seq() { clear(); }
void clear();
SeqPtr left() const { return dna; }
SeqPtr right() const { return dna + length - 1; }
};
typedef vector<Seq*> Genome;
// represents an event happening in the sequence.
struct Event
{
const Region * reg;
// for paired events, extent is the location of the other event
SeqPtr place, extent;
enum Kind
{
Terminator,
ForwardGeneStart,
ForwardGeneEnd,
ReverseGeneStart,
ReverseGeneEnd
} kind;
Event() : reg(0), place(0), extent(0) {}
Event(const Region * r, SeqPtr p, Kind k, SeqPtr x=0) :
reg(r), place(p), extent(x), kind(k) {}
};
typedef vector<Event>::const_iterator event_iterator;
class EventResponder
{
public:
virtual ~EventResponder() {}
virtual void start(const Seq & seq, Direction dir)
{
_fwd_gene = _rvs_gene = 0;
}
virtual void end() {}
virtual void event(const Event & e) {}
virtual void terminator(const Term * term) {}
// if these are called from the subclass, they'll manage gene_count()
virtual void enter_gene(const Event & e);
virtual void leave_gene(const Event & e);
virtual void
enter_intergene(RegionType r, Direction d, const Event & e)
{
set(r, d, true);
}
virtual void
leave_intergene(RegionType r, Direction d, const Event & e)
{
set(r, d, false);
}
friend int er_confidence(const EventResponder &, const Confidence &, const Term &);
protected:
// you can't create a plain EventResponder --- must subclass
EventResponder()
{
_fwd_gene = _rvs_gene = 0;
_t2t = _h2t_fwd = _h2t_rvs = _h2h = false;
}
bool in_t2t() const { return _t2t; }
bool in_h2h() const { return _h2h; }
bool in_h2t_fwd() const { return _h2t_fwd; }
bool in_h2t_rvs() const { return _h2t_rvs; }
int gene_count() const { return _fwd_gene + _rvs_gene; }
int rvs_gene_count() const { return _rvs_gene; }
int fwd_gene_count() const { return _fwd_gene; }
private:
void set(RegionType r, Direction d, bool tf);
int _fwd_gene, _rvs_gene;
bool _t2t, _h2t_fwd, _h2t_rvs, _h2h;
};
#define EVERY_CHROM(ch, C) \
Genome::iterator C = ch.begin(); C != ch.end(); ++C
#define EVERY_CHROM_CONST(ch, C) \
Genome::const_iterator C = ch.begin(); C != ch.end(); ++C
#define EVERY_REGION(vec, R) \
vector<Region*>::iterator R = vec.begin(); R != vec.end(); ++R
#define EVERY_REGION_CONST(vec, R) \
vector<Region*>::const_iterator R = vec.begin(); R != vec.end(); ++R
#define EVERY_TERM(vec, T) \
vector<Term*>::iterator T = vec.begin(); T != vec.end(); ++T
#define EVERY_TERM_CONST(vec, T) \
vector<Term*>::const_iterator T = vec.begin(); T != vec.end(); ++T
#define EVERY_CTERM_CONST(vec, T) \
vector<const Term*>::const_iterator T = vec.begin(); T != vec.end(); ++T
const char PADDING_CHAR = 'x';
int seqindex(const Seq &, SeqPtr);
string subseq(SeqPtr, SeqPtr);
void read_seqs(istream &, Genome &);
void pad_seqs(Genome &, int);
void pad_seq(Seq &, int);
bool region_isleftof(const Region *, const Region *);
bool hp_overlap(const Term &, const Term &);
bool dominates(const Term &, const Term &);
string dir_str(Direction);
void scan_events(const Seq &, EventResponder &, int, int);
void reverse_scan_events(const Seq &, EventResponder &, int, int);
void sort_genes(Genome &);
Seq * chrom_for_id(Genome &, const string &);
void print_term_seq(ostream &, const Term &);
ostream & operator<<(ostream &, const Term &);
#endif
|
jcg/d-tailor
|
3rdParty/transterm/transterm.h
|
/* This file is part of TransTerm v2.0 BETA and is covered by the GNU GPL
* License version 2.0. See file LICENSE.txt for more details. */
#ifndef TRANSTERM_H
#define TRANSTERM_H
#include <string>
#include <vector>
#include <map>
#include <iostream>
using namespace std;
// global options
extern bool no_gaps;
extern int gene_start_cut;
extern int gene_end_cut;
#endif
|
jcg/d-tailor
|
3rdParty/transterm/conf.h
|
/* This file is part of TransTerm v2.0 BETA and is covered by the GNU GPL
* License version 2.0. See file LICENSE.txt for more details. */
#ifndef CONF_H
#define CONF_H
#include <map>
#include "distr.h"
#include "seq.h"
// Abstract base class for a confidence algorithm. Users must call prepare()
// first and then can call score() to get confidence score for a terminator
class Confidence
{
public:
virtual void prepare(const Genome &) = 0;
virtual int score(const Term &, RegionType) const = 0;
virtual ~Confidence() {}
};
// compute the confidence as described in the Ermolaeva et al 2000 paper.
// Note: the terms and genes must be sorted by their leftmost point before
// the call to prepare.
class ErmolaevaConfidence : public Confidence
{
public:
ErmolaevaConfidence() : prepared(false) {}
virtual ~ErmolaevaConfidence() {}
void prepare(const Genome &);
int score(const Term &, RegionType) const;
protected:
double K;
double t2t_L, h2t_L;
double t2t_N, h2t_N;
Distribution h2t_hp, h2t_tail;
Distribution t2t_hp, t2t_tail;
bool prepared;
int score_one(const Term &, RegionType) const;
};
// compute the confidence using the background distribution (usually random)
// read in from a given file.
class RandomConfidence : public Confidence
{
public:
RandomConfidence(const string &);
virtual ~RandomConfidence() {}
void prepare(const Genome &);
int score(const Term &, RegionType) const;
typedef vector<vector<unsigned long> > Histogram2d;
protected:
Histogram2d & get_table(double);
const Histogram2d & get_table(double) const;
void read_exp_table(const string &);
void fill_emp_table(RegionType, const ConstTermVec &);
unsigned long histvalue(const Histogram2d & hist, const Term &, double) const;
unsigned long & histvalue(Histogram2d & hist, const Term &, double);
int hbin(double, double, int, double) const;
int get_best_at(double) const;
unsigned long _sample_size;
//double _low_hp, _high_hp;
//double _low_tail, _high_tail;
map<int, double> _low_hp, _high_hp, _low_tail, _high_tail;
int _nbins;
map<int, Histogram2d> _exp_table;
map<RegionType, Histogram2d> _emp_table;
map<RegionType, unsigned long> _emp_len;
map<RegionType, double> _emp_at;
bool _prepared;
};
class RandomPValueConfidence : public RandomConfidence
{
public:
RandomPValueConfidence(const string &);
virtual ~RandomPValueConfidence() {}
virtual int score(const Term &, RegionType) const ;
protected:
void sum_exp_table();
};
int er_confidence(const EventResponder &, const Confidence &, const Term &);
Distribution signal_to_noise(Term::EnergyKind, const ConstTermVec &, const ConstTermVec &);
#endif
|
jcg/d-tailor
|
3rdParty/transterm/distr.h
|
<reponame>jcg/d-tailor
/* This file is part of TransTerm v2.0 BETA and is covered by the GNU GPL
* License version 2.0. See file LICENSE.txt for more details. */
#ifndef DISTR_H
#define DISTR_H
#include <vector>
#include <iostream>
#include <iomanip>
using namespace std;
// represents a "distribution" ---- really a binned vector so that float
// values go into the appropriate bin
struct Distribution
{
// default constructor makes empty null distribution
Distribution() : _min(0), _max(0), bs(0) {}
// distributions have a fixed range [mmin, mmax] and a set # of bins
// the range is broken into evenly sized bins
Distribution(double mmin, double mmax, unsigned bins) :
_min(mmin), _max(mmax), bs((_max-_min)/bins), d(bins) {}
// the number of bins in the histogram
unsigned size() const { return d.size(); }
// the 'x' range of values represented by bin i
double bin_lower(unsigned i) const { return _min + i*bs; }
double bin_upper(unsigned i) const { return min(_max,_min + (i+1)*bs); }
// the range of values represented by the histogram (as defined when
// created --- does not mean that we've /seen/ a value that low)
double low() const { return _min; }
double high() const { return _max; }
// the bin # (0-based) that the value v would go into
unsigned binfor(double v) const;
// accessors: [i] gives the value of bin i (0-based) --- if the distr is
// not const, can be used as an lvalue: dist[2] += 1.2; at(v) gives the
// value of the bin that v would go into (also can be used as an lvalue)
double operator[](unsigned i) const { return d[i]; }
double & operator[](unsigned i) { return d[i]; }
double & at(double v) { return d[binfor(v)]; }
double at(double v) const { return d[binfor(v)]; }
// interpolate a value for v
double interp(double v) const;
protected:
double _min, _max, bs;
vector<double> d;
};
ostream & operator<<(ostream &, const Distribution &);
#endif
|
jcg/d-tailor
|
3rdParty/transterm/search.h
|
<gh_stars>10-100
#ifndef SEARCH_H
#include <vector>
#include "seq.h"
using namespace std;
void every_hairpin_energy(Seq &, Direction, vector<Term> &);
int set_max_len_loop(int, int);
extern bool no_gaps;
#endif
|
jcg/d-tailor
|
3rdParty/transterm/util.h
|
/* This file is part of TransTerm v2.0 BETA and is covered by the GNU GPL
* License version 2.0. See file LICENSE.txt for more details. */
#ifndef UTIL_H
#define UTIL_H
#include <string>
#include <vector>
#include <iostream>
#include <cassert>
#include <cstdlib>
using namespace std;
void print_status(ostream &, unsigned long, unsigned long);
void split(const string &, char, vector<string> &);
string center(const string &, int);
string trim_front(const string &);
#endif
|
qaz734913414/Simd
|
src/Simd/SimdRuntime.h
|
<gh_stars>0
/*
* Simd Library (http://ermig1979.github.io/Simd).
*
* Copyright (c) 2011-2019 <NAME>.
*
* 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.
*/
#ifndef __SimdRuntime_h__
#define __SimdRuntime_h__
#include "Simd/SimdTime.h"
#include "Simd/SimdGemm.h"
#include <vector>
#include <limits>
#include <algorithm>
#include <string>
#ifdef SIMD_RUNTIME_STATISTIC
#include <sstream>
#include <iostream>
#include <iomanip>
#endif
namespace Simd
{
typedef ::std::string String;
template <class Func, class Args> struct Runtime
{
SIMD_INLINE Runtime()
: _best(NULL)
{
}
SIMD_INLINE ~Runtime()
{
#ifdef SIMD_RUNTIME_STATISTIC
if (!_info.empty())
{
std::sort(_candidates.begin(), _candidates.end(), [](const Candidate & a, const Candidate & b) { return a.Mean() < b.Mean(); });
std::cout << std::setprecision(3) << std::fixed;
std::cout << "Simd::Runtime " << _info << " : ";
for (size_t i = 0; i < _candidates.size(); ++i)
std::cout << _candidates[i].func.Name() << ": " << _candidates[i].Mean()*1000.0 << " ";
std::cout << std::endl;
}
#endif
}
SIMD_INLINE void Init(const Func & func)
{
_candidates.clear();
_candidates.push_back(Candidate(func));
_best = &_candidates[0].func;
}
SIMD_INLINE void Init(const std::vector<Func> & funcs)
{
assert(funcs.size() >= 1);
_candidates.clear();
for (size_t i = 0; i < funcs.size(); ++i)
_candidates.push_back(Candidate(funcs[i]));
_best = funcs.size() == 1 ? &_candidates[0].func : NULL;
}
SIMD_INLINE void Run(const Args & args)
{
if (_best)
_best->Run(args);
else
Test(args);
}
SIMD_INLINE size_t Size() const
{
return _candidates.size();
}
SIMD_INLINE const Func & At(size_t index) const
{
return _candidates[index].func;
}
private:
static const size_t TEST_COUNT = 3 + 2;
struct Candidate
{
Func func;
size_t count;
double sum, min, max;
SIMD_INLINE Candidate(const Func & f)
: func(f)
, count(0)
, sum(0)
, min(std::numeric_limits<double>::max())
, max(0)
{
}
SIMD_INLINE void Update(const double & value)
{
count += 1;
sum += value;
min = std::min(min, value);
max = std::max(max, value);
}
SIMD_INLINE double Mean() const
{
if( count > 2)
return (sum - min - max) / (count - 2);
else if (count > 0)
return sum / count;
else
return sum;
}
};
typedef std::vector<Candidate> Candidates;
Func * _best;
Candidates _candidates;
String _info;
SIMD_INLINE void Test(const Args & args)
{
assert(_candidates.size());
Candidate * current = Current();
if (current)
{
#ifdef SIMD_RUNTIME_STATISTIC
if (_info.empty())
_info = current->func.Info(args);
#endif
double start = Simd::Time();
current->func.Run(args);
current->Update(Simd::Time() - start);
}
else
{
_best = &Best()->func;
_best->Run(args);
}
}
SIMD_INLINE Candidate * Current()
{
size_t min = TEST_COUNT;
Candidate * current = NULL;
for (size_t i = 0; i < _candidates.size(); ++i)
{
if (_candidates[i].count < min)
{
min = _candidates[i].count;
current = &_candidates[i];
}
}
return current;
}
SIMD_INLINE Candidate * Best()
{
Candidate * best = &_candidates[0];
double min = best->Mean();
for (size_t i = 1; i < _candidates.size(); ++i)
{
double mean = _candidates[i].Mean();
if (mean < min)
{
min = mean;
best = &_candidates[i];
}
}
return best;
}
};
//-------------------------------------------------------------------------
struct GemmArgs
{
size_t M; size_t N; size_t K; const float * alpha; const float * A; size_t lda; const float * B; size_t ldb; const float * beta; float * C; size_t ldc;
SIMD_INLINE GemmArgs(size_t M_, size_t N_, size_t K_, const float * alpha_, const float * A_, size_t lda_, const float * B_, size_t ldb_, const float * beta_, float * C_, size_t ldc_)
:M(M_), N(N_), K(K_), alpha(alpha_), A(A_), lda(lda_), B(B_), ldb(ldb_), beta(beta_), ldc(ldc_), C(C_)
{}
};
struct GemmFunc
{
typedef SimdGemm32fNNPtr Func;
SIMD_INLINE GemmFunc(const Func & func, const String & name)
: _func(func)
, _name(name)
{
}
SIMD_INLINE String Name() const { return _name; }
SIMD_INLINE void Run(const GemmArgs & args)
{
_func(args.M, args.N, args.K, args.alpha, args.A, args.lda, args.B, args.ldb, args.beta, args.C, args.ldc);
}
#ifdef SIMD_RUNTIME_STATISTIC
SIMD_INLINE String Info(const GemmArgs & args) const
{
std::stringstream ss;
ss << "Gemm [" << args.M << ", " << args.N << ", " << args.K << "]";
return ss.str();
}
#endif
private:
Func _func;
String _name;
};
typedef std::vector<GemmFunc> GemmFuncs;
SIMD_INLINE GemmFuncs InitGemmFuncs(const GemmFunc::Func & func1, const String & name1, const GemmFunc::Func & func2 = NULL, const String & name2 = String())
{
GemmFuncs funcs;
funcs.push_back(GemmFunc(func1, name1));
if (func2)
funcs.push_back(GemmFunc(func2, name2));
return funcs;
}
typedef Runtime<GemmFunc, GemmArgs> RuntimeGemm;
//-------------------------------------------------------------------------
struct GemmCbArgs
{
size_t M; size_t N; size_t K; const float * A; const float * pB; float * C;
SIMD_INLINE GemmCbArgs(size_t M_, size_t N_, size_t K_, const float * A_, const float * pB_, float * C_)
:M(M_), N(N_), K(K_), A(A_), pB(pB_), C(C_)
{}
};
struct GemmCbFunc
{
typedef size_t (*BufferSizePtr)(size_t M, size_t N, size_t K, GemmKernelType type, bool compatibility);
typedef void (*ReorderBPtr)(size_t M, size_t N, size_t K, const float * B, float * pB, GemmKernelType type, bool compatibility);
typedef void (*RunPtr)(size_t M, size_t N, size_t K, const float * A, const float * pB, float * C, GemmKernelType type, bool compatibility);
SIMD_INLINE GemmCbFunc(BufferSizePtr bufferSize, ReorderBPtr reorderB, RunPtr run, GemmKernelType type, const String & name)
: _bufferSize(bufferSize)
, _reorderB(reorderB)
, _run(run)
, _type(type)
, _name(name)
{
}
SIMD_INLINE String Name() const { return _name; }
SIMD_INLINE void Run(const GemmCbArgs & args)
{
_run(args.M, args.N, args.K, args.A, args.pB, args.C, _type, _type != GemmKernelAny);
}
#ifdef SIMD_RUNTIME_STATISTIC
SIMD_INLINE String Info(const GemmCbArgs & args) const
{
std::stringstream ss;
ss << "GemmCb [" << args.M << ", " << args.N << ", " << args.K << "]";
return ss.str();
}
#endif
SIMD_INLINE GemmKernelType Type() const { return _type; }
SIMD_INLINE size_t BufferSize(size_t M, size_t N, size_t K) const
{
return _bufferSize(M, N, K, _type, _type != GemmKernelAny);
}
SIMD_INLINE void ReorderB(size_t M, size_t N, size_t K, const float * B, float * pB) const
{
_reorderB(M, N, K, B, pB, _type, _type != GemmKernelAny);
}
private:
BufferSizePtr _bufferSize;
ReorderBPtr _reorderB;
RunPtr _run;
GemmKernelType _type;
String _name;
};
typedef std::vector<GemmCbFunc> GemmCbFuncs;
SIMD_INLINE GemmCbFuncs InitGemmCbFuncs(GemmCbFunc::BufferSizePtr bufferSize, GemmCbFunc::ReorderBPtr reorderB, GemmCbFunc::RunPtr run,
const String & name, GemmKernelType begin, GemmKernelType end)
{
GemmCbFuncs funcs;
for (int i = (int)begin, n = (int)end; i <= n; ++i)
funcs.push_back(GemmCbFunc(bufferSize, reorderB, run, GemmKernelType(i), name + "-" + ToStr(i)));
return funcs;
}
typedef Runtime<GemmCbFunc, GemmCbArgs> RuntimeGemmCb;
}
#endif//__SimdRuntime_h__
|
qaz734913414/Simd
|
src/Simd/SimdSse1.h
|
<reponame>qaz734913414/Simd
/*
* Simd Library (http://ermig1979.github.io/Simd).
*
* Copyright (c) 2011-2019 <NAME>.
*
* 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.
*/
#ifndef __SimdSse_h__
#define __SimdSse_h__
#include "Simd/SimdDefs.h"
namespace Simd
{
#ifdef SIMD_SSE_ENABLE
namespace Sse
{
void Fill32f(float * dst, size_t size, const float * value);
void CosineDistance32f(const float * a, const float * b, size_t size, float * distance);
void Gemm32fNN(size_t M, size_t N, size_t K, const float * alpha, const float * A, size_t lda, const float * B, size_t ldb, const float * beta, float * C, size_t ldc);
void HogDeinterleave(const float * src, size_t srcStride, size_t width, size_t height, size_t count, float ** dst, size_t dstStride);
void HogFilterSeparable(const float * src, size_t srcStride, size_t width, size_t height, const float * rowFilter, size_t rowSize, const float * colFilter, size_t colSize, float * dst, size_t dstStride, int add);
void NeuralProductSum(const float * a, const float * b, size_t size, float * sum);
void NeuralAddVectorMultipliedByValue(const float * src, size_t size, const float * value, float * dst);
void NeuralAddVector(const float * src, size_t size, float * dst);
void NeuralAddValue(const float * value, float * dst, size_t size);
void NeuralRoughSigmoid(const float * src, size_t size, const float * slope, float * dst);
void NeuralRoughSigmoid2(const float * src, size_t size, const float * slope, float * dst);
void NeuralDerivativeSigmoid(const float * src, size_t size, const float * slope, float * dst);
void NeuralRoughTanh(const float * src, size_t size, const float * slope, float * dst);
void NeuralDerivativeTanh(const float * src, size_t size, const float * slope, float * dst);
void NeuralDerivativeRelu(const float * src, size_t size, const float * slope, float * dst);
void NeuralUpdateWeights(const float * x, size_t size, const float * a, const float * b, float * d, float * w);
void NeuralAdaptiveGradientUpdate(const float * delta, size_t size, size_t batch, const float * alpha, const float * epsilon, float * gradient, float * weight);
void NeuralAddConvolution2x2Forward(const float * src, size_t srcStride, size_t width, size_t height, const float * weights, float * dst, size_t dstStride);
void NeuralAddConvolution3x3Forward(const float * src, size_t srcStride, size_t width, size_t height, const float * weights, float * dst, size_t dstStride);
void NeuralAddConvolution4x4Forward(const float * src, size_t srcStride, size_t width, size_t height, const float * weights, float * dst, size_t dstStride);
void NeuralAddConvolution5x5Forward(const float * src, size_t srcStride, size_t width, size_t height, const float * weights, float * dst, size_t dstStride);
void NeuralAddConvolution2x2Backward(const float * src, size_t srcStride, size_t width, size_t height, const float * weights, float * dst, size_t dstStride);
void NeuralAddConvolution3x3Backward(const float * src, size_t srcStride, size_t width, size_t height, const float * weights, float * dst, size_t dstStride);
void NeuralAddConvolution4x4Backward(const float * src, size_t srcStride, size_t width, size_t height, const float * weights, float * dst, size_t dstStride);
void NeuralAddConvolution5x5Backward(const float * src, size_t srcStride, size_t width, size_t height, const float * weights, float * dst, size_t dstStride);
void NeuralAddConvolution2x2Sum(const float * src, size_t srcStride, const float * dst, size_t dstStride, size_t width, size_t height, float * sums);
void NeuralAddConvolution3x3Sum(const float * src, size_t srcStride, const float * dst, size_t dstStride, size_t width, size_t height, float * sums);
void NeuralAddConvolution4x4Sum(const float * src, size_t srcStride, const float * dst, size_t dstStride, size_t width, size_t height, float * sums);
void NeuralAddConvolution5x5Sum(const float * src, size_t srcStride, const float * dst, size_t dstStride, size_t width, size_t height, float * sums);
void NeuralPooling1x1Max3x3(const float * src, size_t srcStride, size_t width, size_t height, float * dst, size_t dstStride);
void NeuralPooling2x2Max2x2(const float * src, size_t srcStride, size_t width, size_t height, float * dst, size_t dstStride);
void NeuralPooling2x2Max3x3(const float * src, size_t srcStride, size_t width, size_t height, float * dst, size_t dstStride);
void SquaredDifferenceSum32f(const float * a, const float * b, size_t size, float * sum);
void SquaredDifferenceKahanSum32f(const float * a, const float * b, size_t size, float * sum);
void SvmSumLinear(const float * x, const float * svs, const float * weights, size_t length, size_t count, float * sum);
void SynetAddBias(const float * bias, size_t channels, size_t spatial, float * dst, SimdTensorFormatType format);
void SynetConvertImage(size_t batch, size_t channels, size_t spatial, const float * src, SimdTensorFormatType srcFormat, float * dst, SimdTensorFormatType dstFormat);
void SynetConvertFilter(size_t output, size_t input, size_t kernel, const float * src, SimdTensorFormatType srcFormat, float * dst, SimdTensorFormatType dstFormat);
void SynetEltwiseLayerForward(float const * const * src, const float * weight, size_t count, size_t size, SimdSynetEltwiseOperationType type, float * dst);
void SynetFusedLayerForward0(const float * src, const float * bias, const float * scale, size_t channels, size_t spatial, float * dst, SimdTensorFormatType format);
void SynetFusedLayerForward1(const float * src, const float * bias0, const float * scale1, const float * bias1, size_t channels, size_t spatial, float * dst, SimdTensorFormatType format);
void SynetFusedLayerForward2(const float * src, const float * scale, const float * bias, size_t channels, size_t spatial, const float * slope, float * dst, SimdTensorFormatType format);
void SynetFusedLayerForward3(const float * src, const float * bias, const float * scale, size_t channels, size_t spatial, float * dst, SimdTensorFormatType format);
void SynetFusedLayerForward4(const float * src, const float * bias0, const float * scale1, const float * bias1, size_t channels, size_t spatial, float * dst, SimdTensorFormatType format);
void SynetFusedLayerForward8(const float * src0, const float * src1, const float * src2, size_t channels, size_t spatial, float * dst, SimdTensorFormatType format);
void SynetFusedLayerForward9(const float * src0, const float * src1, const float * scale, const float * bias, size_t channels0, size_t channels1, size_t spatial, float * dst0, float * dst1, SimdTensorFormatType format);
void SynetHswish32f(const float * src, size_t size, const float * shift, const float * scale, float * dst);
void SynetInnerProductLayerForward(const float * src, const float * weight, const float * bias, size_t count, size_t size, float * dst);
void SynetPoolingForwardAverage(const float* src, size_t srcC, size_t srcH, size_t srcW, size_t kernelY, size_t kernelX,
size_t strideY, size_t strideX, size_t padY, size_t padX, float* dst, size_t dstH, size_t dstW, SimdBool excludePad, SimdTensorFormatType format);
void SynetPoolingForwardMax(const float * src, size_t srcC, size_t srcH, size_t srcW, size_t kernelY, size_t kernelX,
size_t strideY, size_t strideX, size_t padY, size_t padX, float * dst, size_t dstH, size_t dstW, SimdBool trans);
void SynetPreluLayerForward(const float * src, const float * slope, size_t channels, size_t spatial, float * dst, SimdTensorFormatType format);
void SynetRelu32f(const float* src, size_t size, const float* slope, float* dst);
void SynetRestrictRange32f(const float * src, size_t size, const float * lower, const float * upper, float * dst);
void SynetScaleLayerForward(const float * src, const float * scale, const float * bias, size_t channels, size_t spatial, float * dst, SimdTensorFormatType format);
void SynetShuffleLayerForward(const float* src0, size_t srcC0, const float* src1, size_t srcC1, size_t spatial, float* dst0, float* dst1, size_t dstC, SimdTensorFormatType format);
void WinogradKernel1x3Block1x4SetFilter(const float* src, size_t size, float* dst, SimdBool trans);
void WinogradKernel1x3Block1x4SetInput(const float* src, size_t srcChannels, size_t srcHeight, size_t srcWidth,
size_t padY, size_t padX, size_t padH, size_t padW, float* dst, size_t dstStride, SimdBool trans);
void WinogradKernel1x3Block1x4SetOutput(const float* src, size_t srcStride, float* dst, size_t dstChannels, size_t dstHeight, size_t dstWidth, SimdBool trans);
void WinogradKernel1x5Block1x4SetFilter(const float* src, size_t size, float* dst, SimdBool trans);
void WinogradKernel1x5Block1x4SetInput(const float* src, size_t srcChannels, size_t srcHeight, size_t srcWidth,
size_t padY, size_t padX, size_t padH, size_t padW, float* dst, size_t dstStride, SimdBool trans);
void WinogradKernel1x5Block1x4SetOutput(const float* src, size_t srcStride, float* dst, size_t dstChannels, size_t dstHeight, size_t dstWidth, SimdBool trans);
void WinogradKernel2x2Block2x2SetFilter(const float* src, size_t size, float* dst, SimdBool trans);
void WinogradKernel2x2Block2x2SetInput(const float* src, size_t srcChannels, size_t srcHeight, size_t srcWidth,
size_t padY, size_t padX, size_t padH, size_t padW, float* dst, size_t dstStride, SimdBool trans);
void WinogradKernel2x2Block2x2SetOutput(const float* src, size_t srcStride, float* dst, size_t dstChannels, size_t dstHeight, size_t dstWidth, SimdBool trans);
void WinogradKernel2x2Block4x4SetFilter(const float* src, size_t size, float* dst, SimdBool trans);
void WinogradKernel2x2Block4x4SetInput(const float* src, size_t srcChannels, size_t srcHeight, size_t srcWidth,
size_t padY, size_t padX, size_t padH, size_t padW, float* dst, size_t dstStride, SimdBool trans);
void WinogradKernel2x2Block4x4SetOutput(const float* src, size_t srcStride, float* dst, size_t dstChannels, size_t dstHeight, size_t dstWidth, SimdBool trans);
void WinogradKernel3x3Block2x2SetFilter(const float * src, size_t size, float * dst, SimdBool trans);
void WinogradKernel3x3Block2x2SetInput(const float* src, size_t srcChannels, size_t srcHeight, size_t srcWidth,
size_t padY, size_t padX, size_t padH, size_t padW, float* dst, size_t dstStride, SimdBool trans);
void WinogradKernel3x3Block2x2SetOutput(const float * src, size_t srcStride, float * dst, size_t dstChannels, size_t dstHeight, size_t dstWidth, SimdBool trans);
void WinogradKernel3x3Block3x3SetFilter(const float * src, size_t size, float * dst, SimdBool trans);
void WinogradKernel3x3Block3x3SetInput(const float* src, size_t srcChannels, size_t srcHeight, size_t srcWidth,
size_t padY, size_t padX, size_t padH, size_t padW, float* dst, size_t dstStride, SimdBool trans);
void WinogradKernel3x3Block3x3SetOutput(const float * src, size_t srcStride, float * dst, size_t dstChannels, size_t dstHeight, size_t dstWidth, SimdBool trans);
void WinogradKernel3x3Block4x4SetFilter(const float * src, size_t size, float * dst, SimdBool trans);
void WinogradKernel3x3Block4x4SetInput(const float* src, size_t srcChannels, size_t srcHeight, size_t srcWidth,
size_t padY, size_t padX, size_t padH, size_t padW, float* dst, size_t dstStride, SimdBool trans);
void WinogradKernel3x3Block4x4SetOutput(const float * src, size_t srcStride, float * dst, size_t dstChannels, size_t dstHeight, size_t dstWidth, SimdBool trans);
}
#endif// SIMD_SSE_ENABLE
}
#endif//__SimdSse_h__
|
arya-ht/error-of-derivatives
|
CalcError.c
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/*
*created by <NAME>
*/
float dverror(int, int, int);
int main(void) {
double j, k = 0, h = 0.0, N = 0, x = 0;
double absErr = 0.0, relErr;
printf("Enter k: ");
scanf("%lf", &k);
printf("Enter N: ");
scanf("%lf", &N);
h = 1 / N;
for (j = 0; j <= N; j++) {
x = j*h;
absErr += dverror(k,x,h);
}
relErr = absErr / k;
printf("%lf\n", absErr);
printf("%lf\n", relErr);
system("pause");
return 0;
}
float dverror(int h, int k, int x){
return fabs((k*cos(k*x))-((sin(k*(x+h))-(sin(k*x)))/h));
}
|
keith/dyld-shared-cache-extractor
|
dyld-shared-cache-extractor.c
|
#include <dlfcn.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define PATH_SIZE 200
static void (*extract)(const char *cache_path, const char *output_path,
void (^progress)(int, int));
static int get_library_path(char *output) {
FILE *pipe = popen("xcrun --sdk iphoneos --show-sdk-platform-path", "r");
if (!pipe)
return 1;
if (fgets(output, PATH_SIZE, pipe) == NULL)
return 1;
output[strlen(output) - 1] = '\0';
strcat(output, "/usr/lib/dsc_extractor.bundle");
return pclose(pipe);
}
__attribute__((noreturn))
__attribute__((__format__(__printf__, 1, 0))) static void
fail(const char *error, ...) {
va_list args;
va_start(args, error);
vfprintf(stderr, error, args);
va_end(args);
exit(EXIT_FAILURE);
}
static void extract_shared_cache(const char *library_path,
const char *cache_path,
const char *output_path) {
void *handle = dlopen(library_path, RTLD_LAZY);
if (!handle)
fail("error: failed to load bundle: %s\n", library_path);
*(void **)(&extract) =
dlsym(handle, "dyld_shared_cache_extract_dylibs_progress");
if (!extract)
fail("error: failed to load function from bundle: %s\n", library_path);
extract(cache_path, output_path, ^void(int completed, int total) {
printf("extracted %d/%d\n", completed, total);
});
}
int main(int argc, char *argv[]) {
if (argc != 3)
fail("Usage: %s <shared-cache-path> <output-path>\n", argv[0]);
const char *shared_cache = argv[1];
if (access(shared_cache, R_OK) != 0)
fail("error: shared cache path doesn't exist: %s\n", shared_cache);
char library_path[PATH_SIZE];
if (get_library_path(library_path) != 0)
fail("error: failed to fetch Xcode path\n");
if (access(library_path, R_OK) != 0)
fail("error: dsc_extractor.bundle wasn't found at expected path, Xcode "
"might have changed this location: %s\n",
library_path);
const char *output_path = argv[2];
extract_shared_cache(library_path, shared_cache, output_path);
return 0;
}
|
magic000/yamdi
|
yamdi.c
|
/*
* yamdi.c
*
* Copyright (c) 2007+, <NAME>
* 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 the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* -----------------------------------------------------------------------------
*
* Compile with:
* gcc yamdi.c -o yamdi -Wall -O2
*
* -----------------------------------------------------------------------------
*/
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <inttypes.h>
#include <errno.h>
#ifdef __MINGW32__
#define off_t _off64_t
#define fseeko(stream, offset, origin) fseeko64(stream, offset, origin)
#define ftello(stream) ftello64(stream)
#endif
#define YAMDI_VERSION "1.9"
#define YAMDI_OK 0
#define YAMDI_ERROR 1
#define YAMDI_FILE_TOO_SMALL 2
#define YAMDI_INVALID_SIGNATURE 3
#define YAMDI_INVALID_FLVVERSION 4
#define YAMDI_INVALID_DATASIZE 5
#define YAMDI_READ_ERROR 6
#define YAMDI_INVALID_PREVIOUSTAGSIZE 7
#define YAMDI_OUT_OF_MEMORY 8
#define YAMDI_H264_USELESS_NALU 9
#define YAMDI_RENAME_OUTPUT 10
#define YAMDI_INVALID_TAGTYPE 11
#define FLV_SIZE_HEADER 9
#define FLV_SIZE_PREVIOUSTAGSIZE 4
#define FLV_SIZE_TAGHEADER 11
#define FLV_TAG_AUDIO 8
#define FLV_TAG_VIDEO 9
#define FLV_TAG_SCRIPTDATA 18
#define FLV_PACKET_H263VIDEO 2
#define FLV_PACKET_SCREENVIDEO 3
#define FLV_PACKET_VP6VIDEO 4
#define FLV_PACKET_VP6ALPHAVIDEO 5
#define FLV_PACKET_SCREENV2VIDEO 6
#define FLV_PACKET_H264VIDEO 7
#define FLV_UI32(x) (unsigned int)(((*(x)) << 24) + ((*(x + 1)) << 16) + ((*(x + 2)) << 8) + (*(x + 3)))
#define FLV_UI24(x) (unsigned int)(((*(x)) << 16) + ((*(x + 1)) << 8) + (*(x + 2)))
#define FLV_UI16(x) (unsigned int)(((*(x)) << 8) + (*(x + 1)))
#define FLV_UI8(x) (unsigned int)(*(x))
#define FLV_TIMESTAMP(x) (int)(((*(x + 3)) << 24) + ((*(x)) << 16) + ((*(x + 1)) << 8) + (*(x + 2)))
typedef struct {
unsigned char *data;
size_t size;
size_t used;
} buffer_t;
typedef struct {
off_t offset; // Offset from the beginning of the file
// FLV spec v10
unsigned int tagtype;
size_t datasize; // Size of the data contained in this tag
int timestamp;
short keyframe; // Is this tag a keyframe?
size_t tagsize; // Size of the whole tag including header and data
} FLVTag_t;
typedef struct {
size_t nflvtags;
FLVTag_t *flvtag;
} FLVIndex_t;
typedef struct {
FLVIndex_t index;
int hascuepoints;
int canseektoend; // Set to 1 if the last video frame is a keyframe
short hasaudio;
struct {
short analyzed; // Are the audio specs complete and valid?
// Audio specs
short codecid;
short samplerate;
short samplesize;
short delay;
short stereo;
// Calculated values
size_t ntags; // # of audio tags
double datarate; // datasize / duration
uint64_t datasize; // Size of the audio data
uint64_t size; // Size of the audio tags (header + data)
int keyframerate; // Store every x tags a keyframe. Only used for -a
int keyframedistance; // The time between two keyframes. Only used for -a
int lasttimestamp;
size_t lastframeindex;
} audio;
short hasvideo;
struct {
short analyzed; // Are the video specs complete and valid?
// Video specs
short codecid;
int height;
int width;
// Calculated values
size_t ntags; // # of video tags
double framerate; // ntags / duration
double datarate; // datasize / duration
uint64_t datasize; // Size of the video data
uint64_t size; // Size of the video tags (header + data)
int lasttimestamp;
size_t lastframeindex;
} video;
short haskeyframes;
struct {
size_t lastkeyframeindex;
int lastkeyframetimestamp;
off_t lastkeyframelocation;
size_t nkeyframes; // # of key frames
off_t *keyframelocations; // Array of the filepositions of the keyframes (in the target file!)
int *keyframetimestamps; // Array of the timestamps of the keyframes
} keyframes;
uint64_t datasize; // Size of all audio and video tags (header + data + FLV_SIZE_PREVIOUSTAGSIZE)
uint64_t filesize; // [sic!]
int lasttimestamp;
int lastsecond;
size_t lastsecondindex;
struct {
char creator[256]; // -c
short addonlastkeyframe; // -k
short addonlastsecond; // -s, -l (deprecated)
short addonmetadata; // defaults to 1, -M does change it
short addaudiokeyframes; // -a
short keepmetadata; // -m (not implemented)
short stripmetadata; // -M
short xmlomitkeyframes; // -X
short overwriteinput; // -w
} options;
buffer_t onmetadata;
buffer_t onlastkeyframe;
buffer_t onlastsecond;
} FLV_t;
typedef struct {
unsigned char *bytes;
size_t length;
size_t byte;
short bit;
} bitstream_t;
typedef struct {
short valid;
int width;
int height;
} h264data_t;
int validateFLV(FILE *fp);
int initFLV(FLV_t *flv);
int indexFLV(FLV_t *flv, FILE *fp);
int finalizeFLV(FLV_t *flv, FILE *fp);
int writeFLV(FILE *out, FLV_t *flv, FILE *fp);
int freeFLV(FLV_t *flv);
void storeFLVFromStdin(FILE *fp);
int readFLVTag(FLVTag_t *flvtag, off_t offset, FILE *fp);
int readFLVTagData(unsigned char *ptr, size_t size, FLVTag_t *flvtag, FILE *stream);
int analyzeFLV(FLV_t *flv, FILE *fp);
int analyzeFLVH263VideoPacket(FLV_t *flv, FLVTag_t *flvtag, FILE *fp);
int analyzeFLVH264VideoPacket(FLV_t *flv, FLVTag_t *flvtag, FILE *fp);
int analyzeFLVScreenVideoPacket(FLV_t *flv, FLVTag_t *flvtag, FILE *fp);
int analyzeFLVVP6VideoPacket(FLV_t *flv, FLVTag_t *flvtag, FILE *fp);
int analyzeFLVVP6AlphaVideoPacket(FLV_t *flv, FLVTag_t *flvtag, FILE *fp);
int createFLVEvents(FLV_t *flv);
int createFLVEventOnMetaData(FLV_t *flv);
int createFLVEventOnLastKeyframe(FLV_t *flv);
int createFLVEventOnLastSecond(FLV_t *flv);
int writeBufferFLVScriptDataTag(buffer_t *buffer, int timestamp, size_t datasize);
int writeBufferFLVPreviousTagSize(buffer_t *buffer, size_t tagsize);
int writeBufferFLVScriptDataValueArray(buffer_t *buffer, const char *name, size_t len);
int writeBufferFLVScriptDataECMAArray(buffer_t *buffer, const char *name, size_t len);
int writeBufferFLVScriptDataVariableArray(buffer_t *buffer, const char *name);
int writeBufferFLVScriptDataVariableArrayEnd(buffer_t *buffer);
int writeBufferFLVScriptDataValueString(buffer_t *buffer, const char *name, const char *value);
int writeBufferFLVScriptDataValueBool(buffer_t *buffer, const char *name, int value);
int writeBufferFLVScriptDataValueDouble(buffer_t *buffer, const char *name, double value);
int writeBufferFLVScriptDataObject(buffer_t *buffer);
int writeBufferFLVScriptDataString(buffer_t *buffer, const char *s);
int writeBufferFLVScriptDataLongString(buffer_t *buffer, const char *s);
int writeBufferFLVBool(buffer_t *buffer, int value);
int writeBufferFLVDouble(buffer_t *buffer, double v);
int writeFLVHeader(FILE *fp, int hasaudio, int hasvideo);
int writeFLVDataTag(FILE *fp, int type, int timestamp, size_t datasize);
int writeFLVPreviousTagSize(FILE *fp, size_t tagsize);
void writeXMLMetadata(FILE *fp, const char *infile, const char *outfile, FLV_t *flv);
int readBytes(unsigned char *ptr, size_t size, FILE *stream);
int readH264NALUnit(h264data_t *h264data, unsigned char *nalu, int length);
void readH264SPS(h264data_t *h264data, bitstream_t *bitstream);
unsigned int readCodedU(bitstream_t *bitstream, int nbits, const char *name);
unsigned int readCodedUE(bitstream_t *bitstream, const char *name);
int readCodedSE(bitstream_t *bitstream, const char *name);
int readBits(bitstream_t *bitstream, int nbits);
int readBit(bitstream_t *bitstream);
int bufferInit(buffer_t *buffer);
int bufferFree(buffer_t *buffer);
int bufferReset(buffer_t *buffer);
int bufferAppendBuffer(buffer_t *dst, buffer_t *src);
int bufferAppendString(buffer_t *dst, const unsigned char *string);
int bufferAppendBytes(buffer_t *dst, const unsigned char *bytes, size_t nbytes);
int isBigEndian(void);
void printUsage(void);
int main(int argc, char **argv) {
FILE *fp_infile = NULL, *fp_outfile = NULL, *fp_xmloutfile = NULL;
int c, unlink_infile = 0;
char *infile, *outfile, *xmloutfile, *tempfile;
FLV_t flv;
#ifdef DEBUG
fprintf(stderr, "[core] sizeof size_t = %d\n", (int)sizeof(size_t));
fprintf(stderr, "[core] sizeof off_t = %d\n", (int)sizeof(off_t));
fprintf(stderr, "[core] sizeof uint64_t = %d\n", (int)sizeof(uint64_t));
fprintf(stderr, "[core] sizeof long long = %d\n", (int)sizeof(long long));
fprintf(stderr, "[core] sizeof double = %d\n", (int)sizeof(double));
#endif
opterr = 0;
infile = NULL;
outfile = NULL;
xmloutfile = NULL;
tempfile = NULL;
initFLV(&flv);
while((c = getopt(argc, argv, ":i:o:x:t:c:a:lskMXwh")) != -1) {
switch(c) {
case 'i':
infile = optarg;
break;
case 'o':
outfile = optarg;
break;
case 'x':
xmloutfile = optarg;
break;
case 't':
tempfile = optarg;
break;
case 'c':
strncpy(flv.options.creator, optarg, sizeof(flv.options.creator));
break;
case 'l':
case 's':
flv.options.addonlastsecond = 1;
break;
case 'k':
flv.options.addonlastkeyframe = 1;
break;
case 'a':
flv.options.addaudiokeyframes = 1;
flv.audio.keyframedistance = (int)strtol(optarg, (char **)NULL, 10);
if(flv.audio.keyframedistance <= 0) {
flv.audio.keyframedistance = 0;
flv.options.addaudiokeyframes = 0;
}
break;
/*
case 'm':
flv.options.keepmetadata = 1;
break;
*/
case 'M':
flv.options.stripmetadata = 1;
break;
case 'X':
flv.options.xmlomitkeyframes = 1;
break;
case 'w':
flv.options.overwriteinput = 1;
break;
case 'h':
printUsage();
exit(YAMDI_ERROR);
break;
case ':':
fprintf(stderr, "The option -%c expects a parameter. -h for help.\n", optopt);
exit(YAMDI_ERROR);
break;
case '?':
fprintf(stderr, "Unknown option: -%c. -h for help.\n", optopt);
exit(YAMDI_ERROR);
break;
default:
printUsage();
exit(YAMDI_ERROR);
break;
}
}
if(infile == NULL) {
fprintf(stderr, "Please use -i to provide an input file. -h for help.\n");
exit(YAMDI_ERROR);
}
if(outfile == NULL && xmloutfile == NULL) {
fprintf(stderr, "Please use -o or -x to provide at least one output file. -h for help.\n");
exit(YAMDI_ERROR);
}
if(tempfile == NULL && !strcmp(infile, "-")) {
fprintf(stderr, "Please use -t to specify a temporary file. -h for help.\n");
exit(YAMDI_ERROR);
}
// Check input file
if(!strcmp(infile, "-")) { // Read from stdin
// tempfile is available
// Check if the possible outfiles collide with the tempfile
if(outfile != NULL) {
if(!strcmp(tempfile, outfile)) {
fprintf(stderr, "The temporary file and the output file must not be the same.\n");
exit(YAMDI_ERROR);
}
}
if(xmloutfile != NULL) {
if(!strcmp(tempfile, xmloutfile)) {
fprintf(stderr, "The temporary file and the XML output file must not be the same.\n");
exit(YAMDI_ERROR);
}
}
}
else { // Read from file
// infile is available
// Check if the possible outfile collide with the infile
if(outfile != NULL) {
if(!strcmp(infile, outfile)) {
fprintf(stderr, "The input file and the output file must not be the same.\n");
exit(YAMDI_ERROR);
}
}
if(xmloutfile != NULL) {
if(!strcmp(infile, xmloutfile)) {
fprintf(stderr, "The input file and the XML output file must not be the same.\n");
exit(YAMDI_ERROR);
}
}
}
// Check output file
if(outfile != NULL) {
if(xmloutfile != NULL) {
if(!strcmp(outfile, xmloutfile)) {
fprintf(stderr, "The output file and the XML output file must not be the same.\n");
exit(YAMDI_ERROR);
}
}
}
// All checks are done. Open the files.
// Open the inputfile
// Store data to tempfile if inputfile is stdin
if(!strcmp(infile, "-")) {
fp_infile = fopen(tempfile, "wb");
if(fp_infile == NULL) {
fprintf(stderr, "Couldn't open the tempfile %s.\n", tempfile);
exit(YAMDI_ERROR);
}
// Store stdin to temporary file
storeFLVFromStdin(fp_infile);
// Close temporary file
fclose(fp_infile);
// Mimic normal input file, but don't forget to remove the temporary file
infile = tempfile;
unlink_infile = 1;
}
fp_infile = fopen(infile, "rb");
if(fp_infile == NULL) {
if(unlink_infile == 1)
unlink(infile);
exit(YAMDI_ERROR);
}
// Check if we have a valid FLV file
if(validateFLV(fp_infile) != YAMDI_OK) {
fclose(fp_infile);
if(unlink_infile == 1)
unlink(infile);
exit(YAMDI_ERROR);
}
// Open the outfile
fp_outfile = NULL;
if(outfile != NULL) {
if(strcmp(outfile, "-")) {
fp_outfile = fopen(outfile, "wb");
if(fp_outfile == NULL) {
fprintf(stderr, "Couldn't open %s.\n", outfile);
if(unlink_infile == 1)
unlink(infile);
exit(YAMDI_ERROR);
}
}
else
fp_outfile = stdout;
}
// Open the XML outputfile
fp_xmloutfile = NULL;
if(xmloutfile != NULL) {
if(strcmp(xmloutfile, "-")) {
fp_xmloutfile = fopen(xmloutfile, "wb");
if(fp_xmloutfile == NULL) {
fprintf(stderr, "Couldn't open %s.\n", xmloutfile);
if(unlink_infile == 1)
unlink(infile);
exit(YAMDI_ERROR);
}
}
else
fp_xmloutfile = stdout;
}
// Check the options
if(flv.options.stripmetadata == 1) {
flv.options.addonlastkeyframe = 0;
flv.options.addonlastsecond = 0;
flv.options.addonmetadata = 0;
}
else
flv.options.addonmetadata = 1;
// Create an index of the FLV file
if(indexFLV(&flv, fp_infile) != YAMDI_OK) {
fclose(fp_infile);
if(unlink_infile == 1)
unlink(infile);
exit(YAMDI_ERROR);
}
if(analyzeFLV(&flv, fp_infile) != YAMDI_OK) {
fclose(fp_infile);
if(unlink_infile == 1)
unlink(infile);
exit(YAMDI_ERROR);
}
if(finalizeFLV(&flv, fp_infile) != YAMDI_OK) {
fclose(fp_infile);
if(unlink_infile == 1)
unlink(infile);
exit(YAMDI_ERROR);
}
#ifdef DEBUG
fprintf(stderr, "[FLV] onmetadata = %d bytes (%d bytes allocated)\n", flv.onmetadata.used, flv.onmetadata.size);
fprintf(stderr, "[FLV] onlastsecond = %d bytes (%d bytes allocated)\n", flv.onlastsecond.used, flv.onlastsecond.size);
fprintf(stderr, "[FLV] onlastkeyframe = %d bytes (%d bytes allocated)\n", flv.onlastkeyframe.used, flv.onlastkeyframe.size);
#endif
if(fp_outfile != NULL)
writeFLV(fp_outfile, &flv, fp_infile);
if(fp_xmloutfile != NULL)
writeXMLMetadata(fp_xmloutfile, infile, outfile, &flv);
fclose(fp_infile);
// Remove the input file if it is the temporary file
if(unlink_infile == 1)
unlink(infile);
if(fp_outfile != NULL && fp_outfile != stdout)
fclose(fp_outfile);
if(fp_xmloutfile != NULL && fp_xmloutfile != stdout)
fclose(fp_xmloutfile);
if(flv.options.overwriteinput == 1 && strcmp(infile, "-") && outfile != NULL && strcmp(outfile, "-")) {
if(rename(outfile, infile) != 0)
exit(YAMDI_RENAME_OUTPUT);
}
freeFLV(&flv);
return YAMDI_OK;
}
int validateFLV(FILE *fp) {
unsigned char buffer[FLV_SIZE_HEADER + FLV_SIZE_PREVIOUSTAGSIZE];
off_t filesize;
fseeko(fp, 0, SEEK_END);
filesize = ftello(fp);
// Check for minimal FLV file length
if(filesize < (FLV_SIZE_HEADER + FLV_SIZE_PREVIOUSTAGSIZE))
return YAMDI_FILE_TOO_SMALL;
rewind(fp);
if(readBytes(buffer, FLV_SIZE_HEADER + FLV_SIZE_PREVIOUSTAGSIZE, fp) != YAMDI_OK)
return YAMDI_READ_ERROR;
// Check the FLV signature
if(buffer[0] != 'F' || buffer[1] != 'L' || buffer[2] != 'V')
return YAMDI_INVALID_SIGNATURE;
// Check the FLV version
if(FLV_UI8(&buffer[3]) != 1)
return YAMDI_INVALID_FLVVERSION;
// Check the DataOffset
if(FLV_UI32(&buffer[5]) != FLV_SIZE_HEADER)
return YAMDI_INVALID_DATASIZE;
// Check the PreviousTagSize0 value
if(FLV_UI32(&buffer[FLV_SIZE_HEADER]) != 0)
return YAMDI_INVALID_PREVIOUSTAGSIZE;
return YAMDI_OK;
}
int initFLV(FLV_t *flv) {
if(flv == NULL)
return YAMDI_ERROR;
memset(flv, 0, sizeof(FLV_t));
return YAMDI_OK;
}
int indexFLV(FLV_t *flv, FILE *fp) {
off_t offset;
size_t nflvtags;
FLVTag_t flvtag;
#ifdef DEBUG
fprintf(stderr, "[FLV] indexing file ...\n");
#endif
// Count how many tags are there in this FLV
offset = FLV_SIZE_HEADER + FLV_SIZE_PREVIOUSTAGSIZE;
nflvtags = 0;
while(readFLVTag(&flvtag, offset, fp) == YAMDI_OK) {
offset += (flvtag.tagsize + FLV_SIZE_PREVIOUSTAGSIZE);
nflvtags++;
}
flv->index.nflvtags = nflvtags;
#ifdef DEBUG
fprintf(stderr, "[FLV] nflvtags = %d\n", flv->index.nflvtags);
#endif
if(nflvtags == 0)
return YAMDI_OK;
// Allocate memory for the tag metadata index
flv->index.flvtag = (FLVTag_t *)calloc(flv->index.nflvtags, sizeof(FLVTag_t));
if(flv->index.flvtag == NULL)
return YAMDI_OUT_OF_MEMORY;
// Store the tag metadata in the index
offset = FLV_SIZE_HEADER + FLV_SIZE_PREVIOUSTAGSIZE;
nflvtags = 0;
while(readFLVTag(&flvtag, offset, fp) == YAMDI_OK) {
flv->index.flvtag[nflvtags].offset = flvtag.offset;
flv->index.flvtag[nflvtags].tagtype = flvtag.tagtype;
flv->index.flvtag[nflvtags].datasize = flvtag.datasize;
flv->index.flvtag[nflvtags].timestamp = flvtag.timestamp;
flv->index.flvtag[nflvtags].tagsize = flvtag.tagsize;
offset += (flv->index.flvtag[nflvtags].tagsize + FLV_SIZE_PREVIOUSTAGSIZE);
nflvtags++;
#ifdef DEBUG
if((nflvtags % 100) == 0)
fprintf(stderr, "[FLV] storing metadata (tag %d of %d)\r", nflvtags, flv->index.nflvtags);
#endif
}
#ifdef DEBUG
fprintf(stderr, "[FLV] storing metadata (tag %d of %d)\n", nflvtags, flv->index.nflvtags);
#endif
return YAMDI_OK;
}
void storeFLVFromStdin(FILE *fp) {
char buf[4096];
size_t bytes;
while((bytes = fread(buf, 1, sizeof(buf), stdin)) > 0)
fwrite(buf, 1, bytes, fp);
return;
}
int freeFLV(FLV_t *flv) {
if(flv->index.nflvtags != 0)
free(flv->index.flvtag);
if(flv->keyframes.keyframelocations != NULL)
free(flv->keyframes.keyframelocations);
if(flv->keyframes.keyframetimestamps != NULL)
free(flv->keyframes.keyframetimestamps);
bufferFree(&flv->onmetadata);
bufferFree(&flv->onlastsecond);
bufferFree(&flv->onlastkeyframe);
memset(flv, 0, sizeof(FLV_t));
return YAMDI_OK;
}
int analyzeFLV(FLV_t *flv, FILE *fp) {
int rv;
size_t i, index;
unsigned char flags;
FLVTag_t *flvtag;
#ifdef DEBUG
fprintf(stderr, "[FLV] analyzing FLV ...\n");
#endif
for(i = 0; i < flv->index.nflvtags; i++) {
flvtag = &flv->index.flvtag[i];
if(flvtag->tagtype == FLV_TAG_AUDIO) {
flv->hasaudio = 1;
flv->audio.ntags++;
flv->audio.datasize += flvtag->datasize;
flv->audio.size += flvtag->tagsize;
flv->audio.lasttimestamp = flvtag->timestamp;
flv->audio.lastframeindex = i;
readFLVTagData(&flags, 1, flvtag, fp);
if(flv->audio.analyzed == 0) {
// SoundFormat
flv->audio.codecid = (flags >> 4) & 0xf;
// SoundRate
flv->audio.samplerate = (flags >> 2) & 0x3;
// SoundSize
flv->audio.samplesize = (flags >> 1) & 0x1;
// SoundType
flv->audio.stereo = flags & 0x1;
if(flv->audio.codecid == 4 || flv->audio.codecid == 5 || flv->audio.codecid == 6) {
// Nellymoser
flv->audio.stereo = 0;
}
else if(flv->audio.codecid == 10) {
// AAC
flv->audio.samplerate = 3;
flv->audio.stereo = 1;
}
flv->audio.analyzed = 1;
}
}
else if(flvtag->tagtype == FLV_TAG_VIDEO) {
flv->hasvideo = 1;
flv->video.ntags++;
flv->video.datasize += flvtag->datasize;
flv->video.size += flvtag->tagsize;
flv->video.lasttimestamp = flvtag->timestamp;
flv->video.lastframeindex = i;
readFLVTagData(&flags, 1, flvtag, fp);
// Keyframes
flvtag->keyframe = (flags >> 4) & 0xf;
if(flvtag->keyframe == 1) {
flv->canseektoend = 1;
flv->keyframes.nkeyframes++;
flv->keyframes.lastkeyframeindex = i;
}
else
flv->canseektoend = 0;
if(flvtag->keyframe == 1 && flv->video.analyzed == 0) {
// Video Codec
flv->video.codecid = flags & 0xf;
switch(flv->video.codecid) {
case FLV_PACKET_H263VIDEO:
rv = analyzeFLVH263VideoPacket(flv, flvtag, fp);
break;
case FLV_PACKET_SCREENVIDEO:
rv = analyzeFLVScreenVideoPacket(flv, flvtag, fp);
break;
case FLV_PACKET_VP6VIDEO:
rv = analyzeFLVVP6VideoPacket(flv, flvtag, fp);
break;
case FLV_PACKET_VP6ALPHAVIDEO:
rv = analyzeFLVVP6AlphaVideoPacket(flv, flvtag, fp);
break;
case FLV_PACKET_SCREENV2VIDEO:
rv = analyzeFLVScreenVideoPacket(flv, flvtag, fp);
break;
case FLV_PACKET_H264VIDEO:
rv = analyzeFLVH264VideoPacket(flv, flvtag, fp);
break;
default:
rv = YAMDI_ERROR;
break;
}
if(rv == YAMDI_OK)
flv->video.analyzed = 1;
}
}
flv->lasttimestamp = flvtag->timestamp;
#ifdef DEBUG
if((i % 100) == 0)
fprintf(stderr, "[FLV] analyzing FLV (tag %d of %d)\r", i, flv->index.nflvtags);
#endif
}
#ifdef DEBUG
fprintf(stderr, "[FLV] analyzing FLV (tag %d of %d)\n", i, flv->index.nflvtags);
fprintf(stderr, "[FLV] lasttimestamp = %d ms\n", flv->lasttimestamp);
#endif
// Calculate the last second
if(flv->lasttimestamp >= 1000) {
flv->lastsecond = flv->lasttimestamp - 1000;
i = flv->index.nflvtags;
while(i != 0) {
flvtag = &flv->index.flvtag[i - 1];
if(flvtag->timestamp <= flv->lastsecond) {
flv->lastsecond += 1;
flv->lastsecondindex = (i - 1);
break;
}
i--;
}
}
else
flv->options.addonlastsecond = 0;
#ifdef DEBUG
fprintf(stderr, "[FLV] lastsecond = %d ms\n", flv->lastsecond);
fprintf(stderr, "[FLV] lastsecondindex = %d\n", flv->lastsecondindex);
#endif
// Calculate audio datarate
if(flv->audio.datasize != 0)
flv->audio.datarate = (double)flv->audio.datasize * 8.0 / 1024.0 / (double)flv->audio.lasttimestamp * 1000.0;
#ifdef DEBUG
fprintf(stderr, "[FLV] audio.codecid = %d\n", flv->audio.codecid);
fprintf(stderr, "[FLV] audio.lasttimestamp = %d ms\n", flv->audio.lasttimestamp);
fprintf(stderr, "[FLV] audio.lastframeindex = %d\n", flv->audio.lastframeindex);
fprintf(stderr, "[FLV] audio.ntags = %d\n", flv->audio.ntags);
fprintf(stderr, "[FLV] audio.datasize = %" PRIu64 " kb\n", flv->audio.datasize);
fprintf(stderr, "[FLV] audio.datarate = %f kbit/s\n", flv->audio.datarate);
#endif
// Calculate video framerate
if(flv->video.ntags != 0)
flv->video.framerate = (double)flv->video.ntags / (double)flv->video.lasttimestamp * 1000.0;
// Calculate video datarate
if(flv->video.datasize != 0)
flv->video.datarate = (double)flv->video.datasize * 8.0 / 1024.0 / (double)flv->lasttimestamp * 1000.0;
#ifdef DEBUG
fprintf(stderr, "[FLV] video.codecid = %d\n", flv->video.codecid);
fprintf(stderr, "[FLV] video.lasttimestamp = %d ms\n", flv->video.lasttimestamp);
fprintf(stderr, "[FLV] video.lastframeindex = %d\n", flv->video.lastframeindex);
fprintf(stderr, "[FLV] video.ntags = %d\n", flv->video.ntags);
fprintf(stderr, "[FLV] video.framerate = %f fps\n", flv->video.framerate);
fprintf(stderr, "[FLV] video.datasize = %" PRIu64 " kb\n", flv->video.datasize);
fprintf(stderr, "[FLV] video.datarate = %f kbit/s\n", flv->video.datarate);
fprintf(stderr, "[FLV] video.width = %d\n", flv->video.width);
fprintf(stderr, "[FLV] video.height = %d\n", flv->video.height);
#endif
// Calculate datasize
flv->datasize = flv->audio.size + (flv->audio.ntags * FLV_SIZE_PREVIOUSTAGSIZE) + flv->video.size + (flv->video.ntags * FLV_SIZE_PREVIOUSTAGSIZE);
#ifdef DEBUG
fprintf(stderr, "[FLV] datasize = %" PRIu64 " kb\n", flv->datasize);
#endif
// Fake keyframes if we have only audio and the corresponding option has been set
if(flv->options.addaudiokeyframes == 1 && flv->hasaudio == 1 && flv->hasvideo == 0) {
// Add a keyframe at least every x milliseconds
flv->audio.keyframerate = (int)((double)flv->audio.keyframedistance / (double)flv->audio.lasttimestamp * (double)flv->audio.ntags);
// If every frame is longer than the intervalthen add every frame a keyframe
if(flv->audio.keyframerate == 0)
flv->audio.keyframerate = 1;
else if(flv->audio.keyframerate >= flv->audio.ntags)
flv->audio.keyframerate = flv->audio.ntags;
#ifdef DEBUG
fprintf(stderr, "[FLV] audio.keyframerate = %d\n", flv->audio.keyframerate);
#endif
// Mark all audio tags that should be considered as a keyframe
index = 0;
for(i = 0; i < flv->index.nflvtags; i++) {
flvtag = &flv->index.flvtag[i];
if(flvtag->tagtype == FLV_TAG_AUDIO) {
if((index % flv->audio.keyframerate) == 0) {
flvtag->keyframe = 1;
flv->keyframes.nkeyframes++;
}
index++;
}
}
// Add an extra keyframe for the last frame
if(flv->index.flvtag[flv->audio.lastframeindex].keyframe == 0) {
flv->index.flvtag[flv->audio.lastframeindex].keyframe = 1;
flv->keyframes.nkeyframes++;
}
flv->canseektoend = 1;
flv->keyframes.lastkeyframeindex = flv->audio.lastframeindex;
}
else
flv->options.addaudiokeyframes = 0;
#ifdef DEBUG
fprintf(stderr, "[FLV] keyframes.nkeyframes = %d\n", flv->keyframes.nkeyframes);
fprintf(stderr, "[FLV] keyframes.lastkeyframeindex = %d\n", flv->keyframes.lastkeyframeindex);
#endif
// Allocate some memory for the keyframe index
if(flv->keyframes.nkeyframes != 0) {
flv->haskeyframes = 1;
flv->keyframes.keyframelocations = (off_t *)calloc(flv->keyframes.nkeyframes, sizeof(off_t));
if(flv->keyframes.keyframelocations == NULL)
return YAMDI_OUT_OF_MEMORY;
flv->keyframes.keyframetimestamps = (int *)calloc(flv->keyframes.nkeyframes, sizeof(int));
if(flv->keyframes.keyframetimestamps == NULL)
return YAMDI_OUT_OF_MEMORY;
}
return YAMDI_OK;
}
int finalizeFLV(FLV_t *flv, FILE *fp) {
size_t i, index;
FLVTag_t *flvtag;
// 2 passes
// 1. create onmetadata event to get the size of it (it doesn't matter if the values are not yet correct)
// 2. calculate the new keyframelocations and the final filesize
// pay attention to the size of these events
// onmetadata
// onlastsecond
// onlastkeyframe
// (oncuepoint) keep them from the input flv?
// 3. recreate the onmetadata event with the correct values
// filesize
// keyframelocations
// lastkeyframelocation
// Create the metadata tags. Even though we don't have all values,
// the size will not change. We need the size.
createFLVEvents(flv);
// Start calculating the final filesize
flv->filesize = 0;
// FLV header + PreviousTagSize
flv->filesize += FLV_SIZE_HEADER + FLV_SIZE_PREVIOUSTAGSIZE;
// onMetaData event
if(flv->options.addonmetadata == 1)
flv->filesize += flv->onmetadata.used;
// Calculate the final filesize and update the keyframe index
index = 0;
for(i = 0; i < flv->index.nflvtags; i++) {
flvtag = &flv->index.flvtag[i];
// Skip every script tag (subject to change if we want to keep existing events)
if(flvtag->tagtype != FLV_TAG_AUDIO && flvtag->tagtype != FLV_TAG_VIDEO)
continue;
// Take care of the onlastsecond event
if(flv->options.addonlastsecond == 1 && flv->lastsecondindex == i)
flv->filesize += flv->onlastsecond.used;
// Update the keyframe index only if there are keyframes ...
if(flv->haskeyframes == 1) {
if(flvtag->tagtype == FLV_TAG_VIDEO || flvtag->tagtype == FLV_TAG_AUDIO) {
// Keyframes
if(flvtag->keyframe == 1) {
// Take care of the onlastkeyframe event
if(flv->options.addonlastkeyframe == 1 && flv->keyframes.lastkeyframeindex == i)
flv->filesize += flv->onlastkeyframe.used;
flv->keyframes.keyframelocations[index] = flv->filesize;
flv->keyframes.keyframetimestamps[index] = flvtag->timestamp;
index++;
}
}
}
flv->filesize += flvtag->tagsize + FLV_SIZE_PREVIOUSTAGSIZE;
}
if(flv->haskeyframes == 1) {
flv->keyframes.lastkeyframetimestamp = flv->keyframes.keyframetimestamps[flv->keyframes.nkeyframes - 1];
flv->keyframes.lastkeyframelocation = flv->keyframes.keyframelocations[flv->keyframes.nkeyframes - 1];
}
#ifdef DEBUG
fprintf(stderr, "[FLV] keyframes.lastkeyframetimestamp = %d ms\n", flv->keyframes.lastkeyframetimestamp);
fprintf(stderr, "[FLV] keyframes.lastkeyframelocation = %" PRIi64 "\n", flv->keyframes.lastkeyframelocation);
fprintf(stderr, "[FLV] filesize = %" PRIu64 " kb\n", flv->filesize);
#endif
// Create the metadata tags with the correct values
createFLVEvents(flv);
return YAMDI_OK;
}
int writeFLV(FILE *out, FLV_t *flv, FILE *fp) {
size_t i, datasize = 0;
unsigned char *data = NULL, *d;
FLVTag_t *flvtag;
if(fp == NULL)
return YAMDI_ERROR;
// Write the header
writeFLVHeader(out, flv->hasaudio, flv->hasvideo);
writeFLVPreviousTagSize(out, 0);
// Write the onMetaData tag
if(flv->options.addonmetadata == 1)
fwrite(flv->onmetadata.data, flv->onmetadata.used, 1, out);
// Copy the audio and video tags
for(i = 0; i < flv->index.nflvtags; i++) {
flvtag = &flv->index.flvtag[i];
// Skip every script tag (subject to change if we want to keep existing events)
if(flvtag->tagtype != FLV_TAG_AUDIO && flvtag->tagtype != FLV_TAG_VIDEO)
continue;
// Write the onlastsecond event
if(flv->options.addonlastsecond == 1 && flv->lastsecondindex == i)
fwrite(flv->onlastsecond.data, flv->onlastsecond.used, 1, out);
// Write the onlastkeyframe event
if(flv->options.addonlastkeyframe == 1 && flv->keyframes.lastkeyframeindex == i)
fwrite(flv->onlastkeyframe.data, flv->onlastkeyframe.used, 1, out);
writeFLVDataTag(out, flvtag->tagtype, flvtag->timestamp, flvtag->datasize);
// Read the data
if(flvtag->datasize > datasize) {
d = (unsigned char *)realloc(data, flvtag->datasize);
if(d == NULL)
return YAMDI_OUT_OF_MEMORY;
data = d;
datasize = flvtag->datasize;
}
if(readFLVTagData(data, flvtag->datasize, flvtag, fp) != YAMDI_OK)
return YAMDI_READ_ERROR;
fwrite(data, flvtag->datasize, 1, out);
writeFLVPreviousTagSize(out, flvtag->tagsize);
}
if(data != NULL)
free(data);
// We are done!
return YAMDI_OK;
}
int writeFLVHeader(FILE *fp, int hasaudio, int hasvideo) {
unsigned char bytes[FLV_SIZE_HEADER];
// Signature
bytes[0] = 'F';
bytes[1] = 'L';
bytes[2] = 'V';
// Version
bytes[3] = 1;
// Flags
bytes[4] = 0;
if(hasaudio == 1)
bytes[4] |= 0x4;
if(hasvideo == 1)
bytes[4] |= 0x1;
// DataOffset
bytes[5] = ((FLV_SIZE_HEADER >> 24) & 0xff);
bytes[6] = ((FLV_SIZE_HEADER >> 16) & 0xff);
bytes[7] = ((FLV_SIZE_HEADER >> 8) & 0xff);
bytes[8] = ((FLV_SIZE_HEADER >> 0) & 0xff);
fwrite(bytes, FLV_SIZE_HEADER, 1, fp);
return YAMDI_OK;
}
int createFLVEvents(FLV_t *flv) {
if(flv->options.addonmetadata == 1)
createFLVEventOnMetaData(flv);
if(flv->options.addonlastkeyframe == 1)
createFLVEventOnLastKeyframe(flv);
if(flv->options.addonlastsecond == 1)
createFLVEventOnLastSecond(flv);
return YAMDI_OK;
}
int createFLVEventOnMetaData(FLV_t *flv) {
int pass = 0;
size_t i, length = 0;
buffer_t b;
bufferInit(&b);
onmetadatapass:
bufferReset(&b);
// ScriptDataObject
writeBufferFLVScriptDataObject(&b);
writeBufferFLVScriptDataECMAArray(&b, "onMetaData", length);
length = 0;
if(strlen(flv->options.creator) != 0) {
writeBufferFLVScriptDataValueString(&b, "creator", flv->options.creator); length++;
}
writeBufferFLVScriptDataValueString(&b, "metadatacreator", "Yet Another Metadata Injector for FLV - Version " YAMDI_VERSION "\0"); length++;
writeBufferFLVScriptDataValueBool(&b, "hasKeyframes", flv->haskeyframes); length++;
writeBufferFLVScriptDataValueBool(&b, "hasVideo", flv->hasvideo); length++;
writeBufferFLVScriptDataValueBool(&b, "hasAudio", flv->hasaudio); length++;
writeBufferFLVScriptDataValueBool(&b, "hasMetadata", 1); length++;
writeBufferFLVScriptDataValueBool(&b, "canSeekToEnd", flv->canseektoend); length++;
writeBufferFLVScriptDataValueDouble(&b, "duration", (double)flv->lasttimestamp / 1000.0); length++;
writeBufferFLVScriptDataValueDouble(&b, "datasize", (double)flv->datasize); length++;
if(flv->hasvideo == 1) {
writeBufferFLVScriptDataValueDouble(&b, "videosize", (double)flv->video.size); length++;
writeBufferFLVScriptDataValueDouble(&b, "framerate", (double)flv->video.framerate); length++;
writeBufferFLVScriptDataValueDouble(&b, "videodatarate", (double)flv->video.datarate); length++;
if(flv->video.analyzed == 1) {
writeBufferFLVScriptDataValueDouble(&b, "videocodecid", (double)flv->video.codecid); length++;
writeBufferFLVScriptDataValueDouble(&b, "width", (double)flv->video.width); length++;
writeBufferFLVScriptDataValueDouble(&b, "height", (double)flv->video.height); length++;
}
}
if(flv->hasaudio == 1) {
writeBufferFLVScriptDataValueDouble(&b, "audiosize", (double)flv->audio.size); length++;
writeBufferFLVScriptDataValueDouble(&b, "audiodatarate", (double)flv->audio.datarate); length++;
if(flv->audio.analyzed == 1) {
writeBufferFLVScriptDataValueDouble(&b, "audiocodecid", (double)flv->audio.codecid); length++;
writeBufferFLVScriptDataValueDouble(&b, "audiosamplerate", (double)flv->audio.samplerate); length++;
writeBufferFLVScriptDataValueDouble(&b, "audiosamplesize", (double)flv->audio.samplesize); length++;
writeBufferFLVScriptDataValueBool(&b, "stereo", flv->audio.stereo); length++;
}
}
writeBufferFLVScriptDataValueDouble(&b, "filesize", (double)flv->filesize); length++;
writeBufferFLVScriptDataValueDouble(&b, "lasttimestamp", (double)flv->lasttimestamp / 1000.0); length++;
if(flv->haskeyframes == 1) {
writeBufferFLVScriptDataValueDouble(&b, "lastkeyframetimestamp", (double)flv->keyframes.lastkeyframetimestamp / 1000.0); length++;
writeBufferFLVScriptDataValueDouble(&b, "lastkeyframelocation", (double)flv->keyframes.lastkeyframelocation); length++;
writeBufferFLVScriptDataVariableArray(&b, "keyframes"); length++;
writeBufferFLVScriptDataValueArray(&b, "filepositions", flv->keyframes.nkeyframes);
for(i = 0; i < flv->keyframes.nkeyframes; i++)
writeBufferFLVScriptDataValueDouble(&b, NULL, (double)flv->keyframes.keyframelocations[i]);
writeBufferFLVScriptDataValueArray(&b, "times", flv->keyframes.nkeyframes);
for(i = 0; i < flv->keyframes.nkeyframes; i++)
writeBufferFLVScriptDataValueDouble(&b, NULL, (double)flv->keyframes.keyframetimestamps[i] / 1000.0);
writeBufferFLVScriptDataVariableArrayEnd(&b);
}
writeBufferFLVScriptDataVariableArrayEnd(&b);
if(pass == 0) {
pass = 1;
goto onmetadatapass;
}
// Write the onMetaData tag
bufferReset(&flv->onmetadata);
writeBufferFLVScriptDataTag(&flv->onmetadata, 0, b.used);
bufferAppendBuffer(&flv->onmetadata, &b);
writeBufferFLVPreviousTagSize(&flv->onmetadata, flv->onmetadata.used);
bufferFree(&b);
return YAMDI_OK;
}
int createFLVEventOnLastSecond(FLV_t *flv) {
buffer_t b;
bufferInit(&b);
// ScriptDataObject
writeBufferFLVScriptDataObject(&b);
writeBufferFLVScriptDataECMAArray(&b, "onLastSecond", 0);
writeBufferFLVScriptDataVariableArrayEnd(&b);
// Write the onLastSecond tag
bufferReset(&flv->onlastsecond);
writeBufferFLVScriptDataTag(&flv->onlastsecond, flv->lastsecond, b.used);
bufferAppendBuffer(&flv->onlastsecond, &b);
writeBufferFLVPreviousTagSize(&flv->onlastsecond, flv->onlastsecond.used);
bufferFree(&b);
return YAMDI_OK;
}
int createFLVEventOnLastKeyframe(FLV_t *flv) {
buffer_t b;
bufferInit(&b);
// ScriptDataObject
writeBufferFLVScriptDataObject(&b);
writeBufferFLVScriptDataECMAArray(&b, "onLastKeyframe", 0);
writeBufferFLVScriptDataVariableArrayEnd(&b);
// Write the onLastKeyframe tag
bufferReset(&flv->onlastkeyframe);
writeBufferFLVScriptDataTag(&flv->onlastkeyframe, flv->keyframes.lastkeyframetimestamp - 1, b.used);
bufferAppendBuffer(&flv->onlastkeyframe, &b);
writeBufferFLVPreviousTagSize(&flv->onlastkeyframe, flv->onlastkeyframe.used);
bufferFree(&b);
return YAMDI_OK;
}
int writeBufferFLVScriptDataTag(buffer_t *buffer, int timestamp, size_t datasize) {
unsigned char bytes[FLV_SIZE_TAGHEADER];
bytes[ 0] = FLV_TAG_SCRIPTDATA;
// DataSize
bytes[ 1] = ((datasize >> 16) & 0xff);
bytes[ 2] = ((datasize >> 8) & 0xff);
bytes[ 3] = ((datasize >> 0) & 0xff);
// Timestamp
bytes[ 4] = ((timestamp >> 16) & 0xff);
bytes[ 5] = ((timestamp >> 8) & 0xff);
bytes[ 6] = ((timestamp >> 0) & 0xff);
// TimestampExtended
bytes[ 7] = ((timestamp >> 24) & 0xff);
// StreamID
bytes[ 8] = 0;
bytes[ 9] = 0;
bytes[10] = 0;
bufferAppendBytes(buffer, bytes, FLV_SIZE_TAGHEADER);
return YAMDI_OK;
}
int writeFLVDataTag(FILE *fp, int type, int timestamp, size_t datasize) {
unsigned char bytes[FLV_SIZE_TAGHEADER];
bytes[ 0] = type;
// DataSize
bytes[ 1] = ((datasize >> 16) & 0xff);
bytes[ 2] = ((datasize >> 8) & 0xff);
bytes[ 3] = ((datasize >> 0) & 0xff);
// Timestamp
bytes[ 4] = ((timestamp >> 16) & 0xff);
bytes[ 5] = ((timestamp >> 8) & 0xff);
bytes[ 6] = ((timestamp >> 0) & 0xff);
// TimestampExtended
bytes[ 7] = ((timestamp >> 24) & 0xff);
// StreamID
bytes[ 8] = 0;
bytes[ 9] = 0;
bytes[10] = 0;
fwrite(bytes, FLV_SIZE_TAGHEADER, 1, fp);
return YAMDI_OK;
}
int writeBufferFLVPreviousTagSize(buffer_t *buffer, size_t tagsize) {
unsigned char bytes[4];
bytes[0] = ((tagsize >> 24) & 0xff);
bytes[1] = ((tagsize >> 16) & 0xff);
bytes[2] = ((tagsize >> 8) & 0xff);
bytes[3] = ((tagsize >> 0) & 0xff);
bufferAppendBytes(buffer, bytes, 4);
return YAMDI_OK;
}
int writeFLVPreviousTagSize(FILE *fp, size_t tagsize) {
unsigned char bytes[4];
bytes[0] = ((tagsize >> 24) & 0xff);
bytes[1] = ((tagsize >> 16) & 0xff);
bytes[2] = ((tagsize >> 8) & 0xff);
bytes[3] = ((tagsize >> 0) & 0xff);
fwrite(bytes, 4, 1, fp);
return YAMDI_OK;
}
int analyzeFLVH263VideoPacket(FLV_t *flv, FLVTag_t *flvtag, FILE *fp) {
int startcode, picturesize;
unsigned char *buffer, data[10];
readFLVTagData(data, sizeof(data), flvtag, fp);
// Skip the VIDEODATA header
buffer = &data[1];
// 8bit |pppppppp|pppppppp|pvvvvvrr|rrrrrrss|swwwwwww|whhhhhhh|h
// 16bit |pppppppp|pppppppp|pvvvvvrr|rrrrrrss|swwwwwww|wwwwwwww|whhhhhhh|hhhhhhhh|h
startcode = FLV_UI24(buffer) >> 7;
if(startcode != 1)
return YAMDI_ERROR;
picturesize = ((buffer[3] & 0x3) << 1) + ((buffer[4] >> 7) & 0x1);
switch(picturesize) {
case 0: // Custom 8bit
flv->video.width = ((buffer[4] & 0x7f) << 1) + ((buffer[5] >> 7) & 0x1);
flv->video.height = ((buffer[5] & 0x7f) << 1) + ((buffer[6] >> 7) & 0x1);
break;
case 1: // Custom 16bit
flv->video.width = ((buffer[4] & 0x7f) << 9) + (buffer[5] << 1) + ((buffer[6] >> 7) & 0x1);
flv->video.height = ((buffer[6] & 0x7f) << 9) + (buffer[7] << 1) + ((buffer[8] >> 7) & 0x1);
break;
case 2: // CIF
flv->video.width = 352.0;
flv->video.height = 288.0;
break;
case 3: // QCIF
flv->video.width = 176.0;
flv->video.height = 144.0;
break;
case 4: // SQCIF
flv->video.width = 128.0;
flv->video.height = 96.0;
break;
case 5:
flv->video.width = 320.0;
flv->video.height = 240.0;
break;
case 6:
flv->video.width = 160.0;
flv->video.height = 120.0;
break;
default:
break;
}
return YAMDI_OK;
}
int analyzeFLVScreenVideoPacket(FLV_t *flv, FLVTag_t *flvtag, FILE *fp) {
unsigned char *buffer, data[5];
// |1111wwww|wwwwwwww|2222hhhh|hhhhhhhh|
readFLVTagData(data, sizeof(data), flvtag, fp);
// Skip the VIDEODATA header
buffer = &data[1];
flv->video.width = ((buffer[0] & 0xf) << 8) + buffer[1];
flv->video.height = ((buffer[2] & 0xf) << 8) + buffer[3];
return YAMDI_OK;
}
int analyzeFLVVP6VideoPacket(FLV_t *flv, FLVTag_t *flvtag, FILE *fp) {
int offset = 3; // default buffer offset for dim_y
unsigned char *buffer, data[10];
readFLVTagData(data, sizeof(data), flvtag, fp);
#if DEBUG
fprintf(stderr, "\n");
fprintf(stderr, "[VP6] ");
int i = 0;
for(i = 0; i < sizeof(data); i++)
fprintf(stderr, "%d=%d ", i, data[i]);
fprintf(stderr, "\n");
#endif
// Skip the VIDEODATA header
buffer = &data[1];
// VP6FLVVIDEOPACKET header (as described in the SWF Specs v10, page 249)
int hadjust = ((buffer[0] >> 4) & 0x0f);
int vadjust = (buffer[0] & 0x0f);
// Raw vp6 video data (http://wiki.multimedia.cx/index.php?title=On2_VP6)
int frame_mode = ((buffer[1] >> 7) & 0x01);
if(frame_mode != 0) // We need an iframe
return YAMDI_ERROR;
int marker = (buffer[1] & 0x01); // Without checking this value, we support all VP6 variants
int version2 = ((buffer[2] >> 1) & 0x03);
#if DEBUG
int version = ((buffer[2] >> 3) & 0x1f);
int interlace = (buffer[2] & 0x01);
fprintf(stderr, "[VP6] marker = %d\n", marker);
fprintf(stderr, "[VP6] version = %d\n", version);
fprintf(stderr, "[VP6] version2 = %d\n", version2);
fprintf(stderr, "[VP6] interlace = %d\n", interlace);
#endif
// In these cases there are 2 more bytes that we have to skip
if(marker == 1 || version2 == 0)
offset += 2;
#if DEBUG
fprintf(stderr, "[VP6] offset = %d\n", offset);
fprintf(stderr, "[VP6] dim_y = %d\n", buffer[offset]);
fprintf(stderr, "[VP6] dim_x = %d\n", buffer[offset + 1]);
fprintf(stderr, "[VP6] render_y = %d\n", buffer[offset + 2]);
fprintf(stderr, "[VP6] render_x = %d\n", buffer[offset + 3]);
#endif
// Now offset points to the resolution values: [dim_y, dim_x, render_y, render_x]
// Values represent macroblocks
flv->video.height = (buffer[offset + 0] * 16) - vadjust;
flv->video.width = (buffer[offset + 1] * 16) - hadjust;
return YAMDI_OK;
}
int analyzeFLVVP6AlphaVideoPacket(FLV_t *flv, FLVTag_t *flvtag, FILE *fp) {
unsigned char *buffer, data[9];
readFLVTagData(data, sizeof(data), flvtag, fp);
// Skip the VIDEODATA header
buffer = &data[1];
flv->video.width = buffer[7] * 16 - (buffer[0] >> 4);
flv->video.height = buffer[6] * 16 - (buffer[0] & 0x0f);
return YAMDI_OK;
}
int analyzeFLVH264VideoPacket(FLV_t *flv, FLVTag_t *flvtag, FILE *fp) {
int avcpackettype;
int i, length, offset, nSPS;
unsigned char *avcc;
unsigned char *buffer, data[flvtag->datasize];
h264data_t h264data;
readFLVTagData(data, sizeof(data), flvtag, fp);
// Skip the VIDEODATA header
buffer = &data[1];
avcpackettype = buffer[0];
#ifdef DEBUG
fprintf(stderr, "[FLV] AVCPacketType = %d\n", avcpackettype);
#endif
if(avcpackettype != 0)
return YAMDI_ERROR;
// AVCDecoderConfigurationRecord (14496-15, 5.2.4.1.1)
avcc = (unsigned char *)&buffer[4];
nSPS = avcc[5] & 0x1f;
#ifdef DEBUG
fprintf(stderr, "[AVC/H.264] AVCDecoderConfigurationRecord\n");
fprintf(stderr, "[AVC/H.264] configurationVersion = %d\n", avcc[0]);
fprintf(stderr, "[AVC/H.264] AVCProfileIndication = %d\n", avcc[1]);
fprintf(stderr, "[AVC/H.264] profile_compatibility = %d\n", avcc[2]);
fprintf(stderr, "[AVC/H.264] AVCLevelIndication = %d\n", avcc[3]);
fprintf(stderr, "[AVC/H.264] lengthSizeMinusOne = %d\n", avcc[4] & 0x3);
fprintf(stderr, "[AVC/H.264] numOfSequenceParameterSets = %d\n", nSPS);
#endif
offset = 6;
for(i = 0; i < nSPS; i++) {
length = (avcc[offset] << 8) + avcc[offset + 1];
#ifdef DEBUG
fprintf(stderr, "[AVC/H.264]\tsequenceParameterSetLength = %d bit\n", 8 * length);
#endif
memset(&h264data, 0, sizeof(h264data_t));
if(readH264NALUnit(&h264data, &avcc[offset + 2], length) == YAMDI_OK)
break;
offset += (2 + length);
}
// There would be some Picture Parameter Sets, but we don't need them. Bail out.
/*
int nPPS = avcc[offset++];
fprintf(stderr, "numOfPictureParameterSets = %d\n", nPPS);
for(i = 0; i < nPPS; i++) {
length = (avcc[offset] << 8) + avcc[offset + 1];
#ifdef DEBUG
fprintf(stderr, "[AVC/H.264]\tpictureParameterSetLength = %d bit\n", 8 * length);
#endif
readH264NALUnit(&avcc[offset + 2], length);
offset += (2 + length);
}
*/
if(h264data.valid == 0)
return YAMDI_ERROR;
flv->video.width = h264data.width;
flv->video.height = h264data.height;
return YAMDI_OK;
}
int writeBufferFLVScriptDataObject(buffer_t *buffer) {
unsigned char type = 2;
bufferAppendBytes(buffer, &type, 1);
return YAMDI_OK;
}
int writeBufferFLVScriptDataECMAArray(buffer_t *buffer, const char *name, size_t len) {
unsigned char type, bytes[4];
writeBufferFLVScriptDataString(buffer, name);
type = 8; // ECMAArray
bufferAppendBytes(buffer, &type, 1);
bytes[0] = ((len >> 24) & 0xff);
bytes[1] = ((len >> 16) & 0xff);
bytes[2] = ((len >> 8) & 0xff);
bytes[3] = ((len >> 0) & 0xff);
bufferAppendBytes(buffer, bytes, 4);
return YAMDI_OK;
}
int writeBufferFLVScriptDataValueArray(buffer_t *buffer, const char *name, size_t len) {
unsigned char type, bytes[4];
writeBufferFLVScriptDataString(buffer, name);
type = 10; // Value Array
bufferAppendBytes(buffer, &type, 1);
bytes[0] = ((len >> 24) & 0xff);
bytes[1] = ((len >> 16) & 0xff);
bytes[2] = ((len >> 8) & 0xff);
bytes[3] = ((len >> 0) & 0xff);
bufferAppendBytes(buffer, bytes, 4);
return YAMDI_OK;
}
int writeBufferFLVScriptDataVariableArray(buffer_t *buffer, const char *name) {
unsigned char type;
writeBufferFLVScriptDataString(buffer, name);
type = 3; // Variable Array
bufferAppendBytes(buffer, &type, 1);
return YAMDI_OK;
}
int writeBufferFLVScriptDataVariableArrayEnd(buffer_t *buffer) {
unsigned char bytes[3];
bytes[0] = 0;
bytes[1] = 0;
bytes[2] = 9;
bufferAppendBytes(buffer, bytes, 3);
return YAMDI_OK;
}
int writeBufferFLVScriptDataValueString(buffer_t *buffer, const char *name, const char *value) {
unsigned char type;
if(name != NULL)
writeBufferFLVScriptDataString(buffer, name);
type = 2; // DataString
bufferAppendBytes(buffer, &type, 1);
writeBufferFLVScriptDataString(buffer, value);
return YAMDI_OK;
}
int writeBufferFLVScriptDataValueBool(buffer_t *buffer, const char *name, int value) {
unsigned char type;
if(name != NULL)
writeBufferFLVScriptDataString(buffer, name);
type = 1; // Bool
bufferAppendBytes(buffer, &type, 1);
writeBufferFLVBool(buffer, value);
return YAMDI_OK;
}
int writeBufferFLVScriptDataValueDouble(buffer_t *buffer, const char *name, double value) {
unsigned char type;
if(name != NULL)
writeBufferFLVScriptDataString(buffer, name);
type = 0; // Double
bufferAppendBytes(buffer, &type, 1);
writeBufferFLVDouble(buffer, value);
return YAMDI_OK;
}
int writeBufferFLVScriptDataString(buffer_t *buffer, const char *s) {
size_t len;
unsigned char bytes[2];
len = strlen(s);
// critical, if only DataString is expected?
if(len > 0xffff)
writeBufferFLVScriptDataLongString(buffer, s);
else {
bytes[0] = ((len >> 8) & 0xff);
bytes[1] = ((len >> 0) & 0xff);
bufferAppendBytes(buffer, bytes, 2);
bufferAppendString(buffer, (unsigned char*)s);
}
return YAMDI_OK;
}
int writeBufferFLVScriptDataLongString(buffer_t *buffer, const char *s) {
size_t len;
unsigned char bytes[4];
len = strlen(s);
if(len > 0xffffffff)
len = 0xffffffff;
bytes[0] = ((len >> 24) & 0xff);
bytes[1] = ((len >> 16) & 0xff);
bytes[2] = ((len >> 8) & 0xff);
bytes[3] = ((len >> 0) & 0xff);
bufferAppendBytes(buffer, bytes, 4);
bufferAppendString(buffer, (unsigned char *)s);
return YAMDI_OK;
}
int writeBufferFLVBool(buffer_t *buffer, int value) {
unsigned char b;
b = (value & 1);
bufferAppendBytes(buffer, &b, 1);
return YAMDI_OK;
}
int writeBufferFLVDouble(buffer_t *buffer, double value) {
union {
unsigned char dc[8];
double dd;
} d;
unsigned char b[8];
d.dd = value;
if(isBigEndian()) {
b[0] = d.dc[0];
b[1] = d.dc[1];
b[2] = d.dc[2];
b[3] = d.dc[3];
b[4] = d.dc[4];
b[5] = d.dc[5];
b[6] = d.dc[6];
b[7] = d.dc[7];
}
else {
b[0] = d.dc[7];
b[1] = d.dc[6];
b[2] = d.dc[5];
b[3] = d.dc[4];
b[4] = d.dc[3];
b[5] = d.dc[2];
b[6] = d.dc[1];
b[7] = d.dc[0];
}
bufferAppendBytes(buffer, b, 8);
return YAMDI_OK;
}
int readFLVTag(FLVTag_t *flvtag, off_t offset, FILE *fp) {
int rv;
unsigned char buffer[FLV_SIZE_TAGHEADER];
memset(flvtag, 0, sizeof(FLVTag_t));
rv = fseeko(fp, offset, SEEK_SET);
if(rv != 0) {
#ifdef DEBUG
fprintf(stderr, "[FLV] %s\n", strerror(errno));
#endif
return YAMDI_READ_ERROR;
}
flvtag->offset = offset;
// Read the header
if(readBytes(buffer, FLV_SIZE_TAGHEADER, fp) != YAMDI_OK)
return YAMDI_READ_ERROR;
flvtag->tagtype = FLV_UI8(buffer);
// Assuming only known tags. Otherwise we only process the
// input file up to this point. It is not possible to detect
// where the next valid tag could be.
switch(flvtag->tagtype) {
case FLV_TAG_VIDEO:
case FLV_TAG_AUDIO:
case FLV_TAG_SCRIPTDATA:
break;
default:
return YAMDI_INVALID_TAGTYPE;
}
flvtag->datasize = (size_t)FLV_UI24(&buffer[1]);
flvtag->timestamp = FLV_TIMESTAMP(&buffer[4]);
// Skip the data
readBytes(NULL, flvtag->datasize, fp);
// Read the previous tag size
readBytes(buffer, FLV_SIZE_PREVIOUSTAGSIZE, fp);
// Check the previous tag size
// This is too picky. We don't need it.
/*
if(FLV_UI32(buffer) != (FLV_SIZE_TAGHEADER + flvtag->datasize))
return YAMDI_INVALID_PREVIOUSTAGSIZE;
*/
flvtag->tagsize = FLV_SIZE_TAGHEADER + flvtag->datasize;
return YAMDI_OK;
}
int readFLVTagData(unsigned char *ptr, size_t size, FLVTag_t *flvtag, FILE *stream) {
// check for size <= flvtag->datasize?
fseeko(stream, flvtag->offset + FLV_SIZE_TAGHEADER, SEEK_SET);
return readBytes(ptr, size, stream);
}
int readBytes(unsigned char *ptr, size_t size, FILE *stream) {
size_t bytesread;
if(ptr == NULL) {
fseeko(stream, (off_t)size, SEEK_CUR);
return YAMDI_OK;
}
bytesread = fread(ptr, 1, size, stream);
if(bytesread < size)
return YAMDI_READ_ERROR;
return YAMDI_OK;
}
int readH264NALUnit(h264data_t * h264data, unsigned char *nalu, int length) {
int i, numBytesInRBSP;
int nal_unit_type;
bitstream_t bitstream;
// See 14496-10, 7.3.1
#ifdef DEBUG
fprintf(stderr, "[AVC/H.264]\tNALU Header: %02x\n", nalu[0]);
fprintf(stderr, "[AVC/H.264]\t\tforbidden_zero_bit = %d\n", (nalu[0] >> 7) & 0x1);
fprintf(stderr, "[AVC/H.264]\t\tnal_ref_idc = %d\n", (nalu[0] >> 5) & 0x3);
fprintf(stderr, "[AVC/H.264]\t\tnal_unit_type = %d\n", nalu[0] & 0x1f);
fprintf(stderr, "[AVC/H.264]\tRBSP: ");
for(i = 1; i < length; i++)
fprintf(stderr, "%02x ", nalu[i]);
fprintf(stderr, "\n");
#endif
nal_unit_type = nalu[0] & 0x1f;
// We are only interested in NALUnits of type 7 (sequence parameter set, SPS)
if(nal_unit_type != 7)
return YAMDI_H264_USELESS_NALU;
bitstream.bytes = (unsigned char *)calloc(1, length - 1);
numBytesInRBSP = 0;
for(i = 1; i < length; i++) {
if(i + 2 < length && nalu[i] == 0x00 && nalu[i + 1] == 0x00 && nalu[i + 2] == 0x03) {
bitstream.bytes[numBytesInRBSP++] = nalu[i];
bitstream.bytes[numBytesInRBSP++] = nalu[i + 1];
i += 2;
}
else
bitstream.bytes[numBytesInRBSP++] = nalu[i];
}
bitstream.length = numBytesInRBSP;
bitstream.byte = 0;
bitstream.bit = 0;
#ifdef DEBUG
fprintf(stderr, "[AVC/H.264]\tSODB: ");
for(i = 0; i < bitstream.length; i++)
fprintf(stderr, "%02x ", bitstream.bytes[i]);
fprintf(stderr, "\n");
#endif
readH264SPS(h264data, &bitstream);
free(bitstream.bytes);
return YAMDI_OK;
}
void readH264SPS(h264data_t *h264data, bitstream_t *bitstream) {
int i, j;
unsigned int profile_idc;
unsigned int chroma_format_idc = 1, separate_color_plane_flag = 0;
unsigned int pic_width_in_mbs_minus1, pic_height_in_map_units_minus1;
unsigned int frame_mbs_only_flag;
unsigned int frame_cropping_flag;
unsigned int frame_crop_left_offset = 0, frame_crop_right_offset = 0, frame_crop_top_offset = 0, frame_crop_bottom_offset = 0;
unsigned int chromaArrayType;
/*
We need these values from SPS
chroma_format_idc
separate_color_plane_flag
pic_width_in_mbs_minus1
pic_height_in_map_units_minus1
frame_mbs_only_flag
frame_cropping_flag
frame_crop_left_offset
frame_crop_right_offset
frame_crop_top_offset
frame_crop_bottom_offset
*/
profile_idc = readCodedU(bitstream, 8, "profile_idc");
readCodedU(bitstream, 1, "constraint_set0_flag");
readCodedU(bitstream, 1, "constraint_set1_flag");
readCodedU(bitstream, 1, "constraint_set2_flag");
readCodedU(bitstream, 1, "constraint_set3_flag");
readCodedU(bitstream, 4, "reserved_zero_4bits");
readCodedU(bitstream, 8, "level_idc");
readCodedUE(bitstream, "seq_parameter_set_id");
if(
profile_idc == 100 ||
profile_idc == 110 ||
profile_idc == 122 ||
profile_idc == 244 ||
profile_idc == 44 ||
profile_idc == 83 ||
profile_idc == 86
) {
chroma_format_idc = readCodedUE(bitstream, "chroma_format_idc");
if(chroma_format_idc == 3)
separate_color_plane_flag = readCodedU(bitstream, 1, "separate_color_plane_flag");
readCodedUE(bitstream, "bit_depth_luma_minus8");
readCodedUE(bitstream, "bit_depth_chroma_minus8");
readCodedU(bitstream, 1, "qpprime_y_zero_transform_bypass_flag");
unsigned int seq_scaling_matrix_present_flag = readCodedU(bitstream, 1, "seq_scaling_matrix_present_flag");
if(seq_scaling_matrix_present_flag == 1) {
int sizeOfScalingList, delta_scale, lastScale, nextScale;
int seq_scaling_matrix_count = (chroma_format_idc != 3) ? 8 : 12;
unsigned int seq_scaling_list_present_flag;
for(i = 0; i < seq_scaling_matrix_count; i++) {
seq_scaling_list_present_flag = readCodedU(bitstream, 1, "seq_scaling_list_present_flag");
if(seq_scaling_list_present_flag == 1) {
sizeOfScalingList = (i < 6) ? 16 : 64;
lastScale = nextScale = 8;
for(j = 0; j < sizeOfScalingList; j++) {
if(nextScale != 0) {
delta_scale = readCodedSE(bitstream, "delta_scale");
nextScale = (lastScale + delta_scale + 256) % 256;
}
lastScale = (nextScale == 0) ? lastScale : nextScale;
}
}
}
}
}
readCodedUE(bitstream, "log2_max_frame_num_minus4");
unsigned int pic_order_cnt_type = readCodedUE(bitstream, "pic_order_cnt_type");
if(pic_order_cnt_type == 1) {
readCodedU(bitstream, 1, "delta_pic_order_always_zero_flag");
readCodedSE(bitstream, "offset_for_non_ref_pic");
readCodedSE(bitstream, "offset_for_top_to_bottom_field");
unsigned int num_ref_frames_in_pic_order_cnt_cycle = readCodedUE(bitstream, "num_ref_frames_in_pic_order_cnt_cycle");
for(i = 0; i < num_ref_frames_in_pic_order_cnt_cycle; i++)
readCodedSE(bitstream, "offset_for_ref_frame");
}
else if(pic_order_cnt_type == 0)
readCodedUE(bitstream, "log2_max_pic_order_cnt_lsb_minus4");
readCodedUE(bitstream, "max_num_ref_frames");
readCodedU(bitstream, 1, "gaps_in_frame_num_value_allowed_flag");
pic_width_in_mbs_minus1 = readCodedUE(bitstream, "pic_width_in_mbs_minus1");
pic_height_in_map_units_minus1 = readCodedUE(bitstream, "pic_height_in_map_units_minus1");
frame_mbs_only_flag = readCodedU(bitstream, 1, "frame_mbs_only_flag");
if(frame_mbs_only_flag == 0)
readCodedU(bitstream, 1, "mb_adaptive_frame_field_flag");
readCodedU(bitstream, 1, "direct_8x8_inference_flag");
frame_cropping_flag = readCodedU(bitstream, 1, "frame_cropping_flag");
if(frame_cropping_flag == 1) {
frame_crop_left_offset = readCodedUE(bitstream, "frame_crop_left_offset");
frame_crop_right_offset = readCodedUE(bitstream, "frame_crop_right_offset");
frame_crop_top_offset = readCodedUE(bitstream, "frame_crop_top_offset");
frame_crop_bottom_offset = readCodedUE(bitstream, "frame_crop_bottom_offset");
}
readCodedU(bitstream, 1, "vui_parameters_present_flag");
// and so on ... VUI is not interesting for us. We have everything we need.
// Now we have enough information to compute the width and height of this video stream
unsigned int picWidthInMbs = (pic_width_in_mbs_minus1 + 1);
unsigned int picHeightInMapUnits = (pic_height_in_map_units_minus1 + 1);
unsigned int frameHeightInMbs = (2 - frame_mbs_only_flag) * picHeightInMapUnits;
unsigned int width = picWidthInMbs * 16;
unsigned int height = frameHeightInMbs * 16;
#ifdef DEBUG
fprintf(stderr, "[AVC/H.264] width = %u (pre crop)\n", width);
fprintf(stderr, "[AVC/H.264] height = %u (pre crop)\n", height);
#endif
// Cropping
int cropLeft, cropRight;
int cropTop, cropBottom;
if(frame_cropping_flag == 1) {
// See 14496-10, Table 6-1
int subWidthC[4] = {1, 2, 2, 1};
int subHeightC[4] = {1, 2, 1, 1};
unsigned int cropUnitX, cropUnitY;
if(separate_color_plane_flag == 0)
chromaArrayType = chroma_format_idc;
else
chromaArrayType = 0;
if(chromaArrayType == 0) {
cropUnitX = 1;
cropUnitY = 2 - frame_mbs_only_flag;
}
else {
cropUnitX = subWidthC[chroma_format_idc];
cropUnitY = subHeightC[chroma_format_idc] * (2 - frame_mbs_only_flag);
}
cropLeft = cropUnitX * frame_crop_left_offset;
cropRight = cropUnitX * frame_crop_right_offset;
cropTop = cropUnitY * frame_crop_top_offset;
cropBottom = cropUnitY * frame_crop_bottom_offset;
}
else {
cropLeft = 0;
cropRight = 0;
cropTop = 0;
cropBottom = 0;
}
width = width - cropLeft - cropRight;
height = height - cropTop - cropBottom;
#ifdef DEBUG
fprintf(stderr, "[AVC/H.264] width = %u\n", width);
fprintf(stderr, "[AVC/H.264] height = %u\n", height);
#endif
h264data->valid = 1;
h264data->width = width;
h264data->height = height;
return;
}
unsigned int readCodedU(bitstream_t *bitstream, int nbits, const char *name) {
// unsigned integer with n bits
unsigned int bits = (unsigned int)readBits(bitstream, nbits);
#ifdef DEBUG
if(name != NULL)
fprintf(stderr, "[AVC/H.264]\t\t%s = %u\n", name, bits);
#endif
return bits;
}
unsigned int readCodedUE(bitstream_t *bitstream, const char *name) {
// unsigned integer Exp-Golomb coded (see 14496-10, 9.1)
int leadingZeroBits = -1;
int bit;
unsigned int codeNum = 0;
for(bit = 0; bit == 0; leadingZeroBits++) {
bit = readBit(bitstream);
if (bitstream->byte == bitstream->length) break;
}
codeNum = ((1 << leadingZeroBits) - 1 + (unsigned int)readBits(bitstream, leadingZeroBits));
#ifdef DEBUG
if(name != NULL)
fprintf(stderr, "[AVC/H.264]\t\t%s = %u\n", name, codeNum);
#endif
return codeNum;
}
int readCodedSE(bitstream_t *bitstream, const char *name) {
// signed integer Exp-Golomb coded (see 14496-10, 9.1 and 9.1.1)
unsigned int codeNum;
int codeNumSigned, sign;
codeNum = readCodedUE(bitstream, NULL);
sign = (codeNum % 2) + 1;
codeNumSigned = codeNum >> 1;
if(sign == 0)
codeNumSigned++;
else
codeNumSigned *= -1;
#ifdef DEBUG
if(name != NULL)
fprintf(stderr, "[AVC/H.264]\t\t%s = %d\n", name, codeNumSigned);
#endif
return codeNumSigned;
}
int readBits(bitstream_t *bitstream, int nbits) {
int i, rv = 0;
for(i = 0; i < nbits; i++) {
rv = (rv << 1);
rv += readBit(bitstream);
}
return rv;
}
int readBit(bitstream_t *bitstream) {
int bit;
if(bitstream->byte == bitstream->length)
return 0;
bit = (bitstream->bytes[bitstream->byte] >> (7 - bitstream->bit)) & 0x01;
bitstream->bit++;
if(bitstream->bit == 8) {
bitstream->byte++;
bitstream->bit = 0;
}
return bit;
}
int bufferInit(buffer_t *buffer) {
if(buffer == NULL)
return YAMDI_ERROR;
buffer->data = NULL;
buffer->size = 0;
buffer->used = 0;
return YAMDI_OK;
}
int bufferFree(buffer_t *buffer) {
if(buffer == NULL)
return YAMDI_ERROR;
if(buffer->data != NULL) {
free(buffer->data);
buffer->data = NULL;
}
return YAMDI_OK;
}
int bufferReset(buffer_t *buffer) {
if(buffer == NULL)
return YAMDI_ERROR;
buffer->used = 0;
return YAMDI_OK;
}
int bufferAppendString(buffer_t *dst, const unsigned char *string) {
if(string == NULL)
return YAMDI_OK;
return bufferAppendBytes(dst, string, strlen((char *)string));
}
int bufferAppendBuffer(buffer_t *dst, buffer_t *src) {
if(src == NULL)
return YAMDI_OK;
return bufferAppendBytes(dst, src->data, src->used);
}
int bufferAppendBytes(buffer_t *dst, const unsigned char *bytes, size_t nbytes) {
size_t size;
unsigned char *data;
if(dst == NULL)
return YAMDI_ERROR;
if(bytes == NULL)
return YAMDI_OK;
if(nbytes == 0)
return YAMDI_OK;
// Check if we have to increase the buffer size
if(dst->size < dst->used + nbytes) {
// Pre-allocating some memory. Round up to the next 1024 bound
size = ((dst->used + nbytes) / 1024 + 1) * 1024;
data = (unsigned char *)realloc(dst->data, size);
if(data == NULL)
return YAMDI_ERROR;
dst->data = data;
dst->size = size;
}
// Copy the stuff into the buffer
memcpy(&dst->data[dst->used], bytes, nbytes);
dst->used += nbytes;
return YAMDI_OK;
}
int isBigEndian(void) {
long one = 1;
return !(*((char *)(&one)));
}
void writeXMLMetadata(FILE *fp, const char *infile, const char *outfile, FLV_t *flv) {
size_t i;
fprintf(fp, "<?xml version='1.0' encoding='UTF-8'?>\n");
fprintf(fp, "<fileset>\n");
if(outfile != NULL)
fprintf(fp, "<flv name=\"%s\">\n", outfile);
else
fprintf(fp, "<flv name=\"%s\">\n", infile);
fprintf(fp, "<hasKeyframes>%s</hasKeyframes>\n", (flv->haskeyframes != 0) ? "true" : "false");
fprintf(fp, "<hasVideo>%s</hasVideo>\n", (flv->hasvideo != 0) ? "true" : "false");
fprintf(fp, "<hasAudio>%s</hasAudio>\n", (flv->hasaudio != 0) ? "true" : "false");
fprintf(fp, "<hasMetadata>true</hasMetadata>\n");
fprintf(fp, "<hasCuePoints>%s</hasCuePoints>\n", (flv->hascuepoints != 0) ? "true" : "false");
fprintf(fp, "<canSeekToEnd>%s</canSeekToEnd>\n", (flv->canseektoend != 0) ? "true" : "false");
fprintf(fp, "<audiocodecid>%d</audiocodecid>\n", flv->audio.codecid);
fprintf(fp, "<audiosamplerate>%d</audiosamplerate>\n", flv->audio.samplerate);
fprintf(fp, "<audiodatarate>%d</audiodatarate>\n", (int)flv->audio.datarate);
fprintf(fp, "<audiosamplesize>%d</audiosamplesize>\n", flv->audio.samplesize);
fprintf(fp, "<audiodelay>%.2f</audiodelay>\n", (double)flv->audio.delay);
fprintf(fp, "<stereo>%s</stereo>\n", (flv->audio.stereo != 0) ? "true" : "false");
fprintf(fp, "<videocodecid>%d</videocodecid>\n", flv->video.codecid);
fprintf(fp, "<framerate>%.2f</framerate>\n", flv->video.framerate);
fprintf(fp, "<videodatarate>%d</videodatarate>\n", (int)flv->video.datarate);
fprintf(fp, "<height>%d</height>\n", (int)flv->video.height);
fprintf(fp, "<width>%d</width>\n", (int)flv->video.width);
fprintf(fp, "<datasize>%" PRIu64 "</datasize>\n", flv->datasize);
fprintf(fp, "<audiosize>%" PRIu64 "</audiosize>\n", flv->audio.size);
fprintf(fp, "<videosize>%" PRIu64 "</videosize>\n", flv->video.size);
fprintf(fp, "<filesize>%" PRIu64 "</filesize>\n", flv->filesize);
fprintf(fp, "<lasttimestamp>%.2f</lasttimestamp>\n", (double)flv->lasttimestamp / 1000.0);
fprintf(fp, "<lastvideoframetimestamp>%.2f</lastvideoframetimestamp>\n", (double)flv->video.lasttimestamp / 1000.0);
fprintf(fp, "<lastkeyframetimestamp>%.2f</lastkeyframetimestamp>\n", (double)flv->keyframes.lastkeyframetimestamp / 1000.0);
fprintf(fp, "<lastkeyframelocation>%" PRIu64 "</lastkeyframelocation>\n", (uint64_t)flv->keyframes.lastkeyframelocation);
if(flv->options.xmlomitkeyframes == 0) {
fprintf(fp, "<keyframes>\n");
fprintf(fp, "<times>\n");
for(i = 0; i < flv->keyframes.nkeyframes; i++)
fprintf(fp, "<value id=\"%" PRIu64 "\">%.2f</value>\n", (uint64_t)i, (double)flv->keyframes.keyframetimestamps[i] / 1000.0);
fprintf(fp, "</times>\n");
fprintf(fp, "<filepositions>\n");
for(i = 0; i < flv->keyframes.nkeyframes; i++)
fprintf(fp, "<value id=\"%" PRIu64 "\">%" PRIu64 "</value>\n", (uint64_t)i, (uint64_t)flv->keyframes.keyframelocations[i]);
fprintf(fp, "</filepositions>\n");
fprintf(fp, "</keyframes>\n");
}
fprintf(fp, "<duration>%.2f</duration>\n", (double)flv->lasttimestamp / 1000.0);
fprintf(fp, "</flv>\n");
fprintf(fp, "</fileset>\n");
return;
}
void printUsage(void) {
fprintf(stderr, "NAME\n");
fprintf(stderr, "\tyamdi -- Yet Another Metadata Injector for FLV\n");
fprintf(stderr, "\tVersion: " YAMDI_VERSION "\n");
fprintf(stderr, "\n");
fprintf(stderr, "SYNOPSIS\n");
fprintf(stderr, "\tyamdi -i input file [-x xml file | -o output file [-x xml file]]\n");
fprintf(stderr, "\t [-t temporary file] [-c creator] [-a interval] [-skMXw] [-h]\n");
fprintf(stderr, "\n");
fprintf(stderr, "DESCRIPTION\n");
fprintf(stderr, "\tyamdi is a metadata injector for FLV files.\n");
fprintf(stderr, "\n");
fprintf(stderr, "\tOptions:\n");
fprintf(stderr, "\n");
fprintf(stderr, "\t-i\tThe source FLV file. If the file name is '-' the input\n");
fprintf(stderr, "\t\tfile will be read from stdin. Use the -t option to specify\n");
fprintf(stderr, "\t\ta temporary file.\n");
fprintf(stderr, "\n");
fprintf(stderr, "\t-o\tThe resulting FLV file with the metatags. If the file\n");
fprintf(stderr, "\t\tname is '-' the output will be written to stdout.\n");
fprintf(stderr, "\n");
fprintf(stderr, "\t-x\tAn XML file with the resulting metadata information. If the\n");
fprintf(stderr, "\t\toutput file is ommited, only metadata will be generated.\n");
fprintf(stderr, "\n");
fprintf(stderr, "\t-t\tA temporary file to store the source FLV file in if the\n");
fprintf(stderr, "\t\tinput file is read from stdin.\n");
fprintf(stderr, "\n");
fprintf(stderr, "\t-c\tA string that will be written into the creator tag.\n");
fprintf(stderr, "\n");
fprintf(stderr, "\t-s, -l\tAdd the onLastSecond event.\n");
fprintf(stderr, "\t\tThe -l option is deprecated and will be removed in a future\n");
fprintf(stderr, "\t\tversion.\n");
fprintf(stderr, "\n");
fprintf(stderr, "\t-k\tAdd the onLastKeyframe event.\n");
fprintf(stderr, "\n");
/*
fprintf(stderr, "\t-m\tLeave the existing metadata intact.\n");
fprintf(stderr, "\t\tMetadata that yamdi does not add is left untouched, e.g. onCuepoint.\n");
fprintf(stderr, "\n");
*/
fprintf(stderr, "\t-M\tStrip all metadata from the FLV. The -s and -k options will\n");
fprintf(stderr, "\t\tbe ignored.\n");
fprintf(stderr, "\n");
fprintf(stderr, "\t-X\tOmit the keyframes tag in the XML output.\n");
fprintf(stderr, "\n");
fprintf(stderr, "\t-a\tTime in milliseconds between keyframes if there is only audio.\n");
fprintf(stderr, "\t\tThis option will be ignored if there is a video stream. No\n");
fprintf(stderr, "\t\tkeyframes will be added if this option is omitted.\n");
fprintf(stderr, "\n");
fprintf(stderr, "\t-w\tReplace the input file with the output file. -i and -o are\n");
fprintf(stderr, "\t\trequired to be different files otherwise this option will be\n");
fprintf(stderr, "\t\tignored.\n");
fprintf(stderr, "\n");
fprintf(stderr, "\t-h\tThis description.\n");
fprintf(stderr, "\n");
fprintf(stderr, "COPYRIGHT\n");
fprintf(stderr, "\t(c) 2007+ Ingo Oppermann\n");
fprintf(stderr, "\n");
return;
}
|
iliabenson/2sat
|
src/2sat.c
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <assert.h>
static const int lineSize = 1024;
struct satVariable{
int64_t label; // variable label, and index into variableValues array
char value; // it's boolean value
int64_t size;
int64_t* indexes; // locations where it appears in terminals array, even index means it is the left variable in the clause, odd means right
int64_t count; // number of times it appears in terminals array, also length of indexes array
int64_t weightedCount; // how many it appears in clauses where variables have not been assigned yet
int64_t* negIndexes; // same but negated
int64_t negCount; // same but negated
int64_t negWeightedCount; // same but negated
char evaluated;
};
static void freePtr(void* ptr){
free(ptr);
ptr = NULL;
}
// @TODO: comment this out before submission
// static void testPrint(int64_t* terminals, int64_t numTerminals, char* variableValues, int64_t numVariableValues, struct satVariable* variableTable, int64_t numVariableTable){
// int64_t i, j;
// printf("Total number of terminals: %lld\n", numTerminals);
// printf("Total number of clauses: %lld\n", numTerminals / 2);
// printf("Number of variables: %lld\n", numVariableValues);
// printf("Number of used variables: %lld\n", numVariableTable);
// for(i = 0; i < numTerminals; i++){
// printf("%lld ", terminals[i]);
// if(i % 2 != 0){
// printf("\n");
// }
// }
// for(i = 0; i <= numVariableValues; i++){
// printf("%c ", variableValues[i]);
// }
// printf("\n\n");
// for(i = 0; i < numVariableTable; i++){
// printf("Variable: %lld, Value: %c, Positive Count: %lld/%lld, Negated Count: %lld/%lld\n", variableTable[i].label, variableTable[i].value, variableTable[i].count, variableTable[i].weightedCount, variableTable[i].negCount, variableTable[i].negWeightedCount);
// printf("Evaluated: %c\n", variableTable[i].evaluated);
// printf("Positive Index locations in terminals array: ");
// for(j = 0; j < variableTable[i].count; j++){
// printf("%lld ", variableTable[i].indexes[j]);
// }
// printf("\n");
// printf("Negated Index locations in terminals array: ");
// for(j = 0; j < variableTable[i].negCount; j++){
// printf("%lld ", variableTable[i].negIndexes[j]);
// }
// printf("\n\n");
// }
// }
// Destructive function, quick and dirty mutli delim string tokenizer
static char* Str_Tok_Multi(char* str, char const* delims){
static char* src = NULL;
char* p, *ret = 0;
if(str != NULL){
src = str;
}
if(src == NULL){
return NULL;
}
if((p = strpbrk(src, delims)) != NULL){
*p = 0;
ret = src;
src = ++p;
}else if (*src){
ret = src;
src = NULL;
}
return ret;
}
static void setToken(char* token, int64_t* terminals, int64_t position, int64_t* numVariableValues){
if(token){
terminals[position] = atoi(token);
if(abs(terminals[position]) > *numVariableValues){
*numVariableValues = abs(terminals[position]);
}
}
else{
fprintf(stderr,"Could not write a token, %s, exiting", token);
exit(EXIT_FAILURE);
}
}
static int64_t* readClauses(char* filename, int64_t* numTerminals, int64_t* numVariableValues){
int64_t* terminals = NULL;
int64_t count = 0;
FILE* fp = NULL;
char buffer[lineSize];
char delim[] = " ";
if((fp = fopen(filename, "r")) == NULL){
perror("ERROR: Could not open file!");
exit(EXIT_FAILURE);
}
while(fgets(buffer, lineSize, fp) != NULL){
count++;
}
*numTerminals = (2 * count); // each line has 2 variables (could be non-unique) so call that number of terminals
rewind(fp);
terminals = (int64_t*)malloc(*numTerminals * sizeof(int64_t));
count = 0;
while(fgets(buffer, lineSize, fp) != NULL){
if(buffer[strlen(buffer) - 1] == '\n'){
buffer[strlen(buffer) - 1] = '\0';
}
// Str_Tok_Multi is destructive
setToken(Str_Tok_Multi(buffer, delim), terminals, count, numVariableValues);
count++;
setToken(Str_Tok_Multi(NULL, delim), terminals, count, numVariableValues);
count++;
}
fclose(fp);
return terminals;
}
static char* findUsedVariables(int64_t* terminals, int64_t numTerminals , int64_t numVariableValues, int64_t* numVariableTable){
int64_t i;
char* variableValues = (char*)malloc((numVariableValues + 1) * sizeof(char));
memset(variableValues, 'X', (numVariableValues + 1) * sizeof(char)); // is value for this variable is not used in clauses, and therefor does not matter, however, for greedy if the variables sibling already sat the clause than it's value for that clause is 0, a variable can be used and have 0 weight, thus it is also represented by an X, later updated to F for purposes of local search.
variableValues[0] = 'S'; // P is just a place holder, should never print except for testPrint
for(i = 0; i < numTerminals; i++){
variableValues[abs(terminals[i])] = 'T'; // set all the present variables to T
}
for(i = 1; i <= numVariableValues; i++){
if(variableValues[i] == 'T'){
++*numVariableTable;
}
}
return variableValues;
}
static void growVarTableIndexArray(struct satVariable* variable, int64_t* size){
*size = *size * 2;
variable->indexes = (int64_t*)realloc(variable->indexes,*size * sizeof(int64_t));
variable->negIndexes = (int64_t*)realloc(variable->negIndexes,*size * sizeof(int64_t));
}
static struct satVariable* makeVariableTable(int64_t* terminals, int64_t numTerminals, int64_t numVariableTable){
int64_t i, j;
struct satVariable* variableTable = NULL;
variableTable = (struct satVariable*)malloc(numVariableTable * sizeof(struct satVariable));
for(i = 0; i < numVariableTable; i++){
variableTable[i].label = -1;
}
// @NOTE: slow but i only need to do this once
for(i = 0; i < numTerminals; i++){
for(j = 0; j < numVariableTable; j++){
if(variableTable[j].label == abs(terminals[i])){
if(terminals[i] > 0){
if(variableTable[j].count == variableTable[j].size){
growVarTableIndexArray(&variableTable[j], &variableTable[j].size);
}
variableTable[j].indexes[variableTable[j].count] = i;
variableTable[j].count++;
variableTable[j].weightedCount++;
}
else{
if(variableTable[j].negCount == variableTable[j].size){
growVarTableIndexArray(&variableTable[j], &variableTable[j].size);
}
variableTable[j].negIndexes[variableTable[j].negCount] = i;
variableTable[j].negCount++;
variableTable[j].negWeightedCount++;
}
break; // found existing variable and updated it, break out of inner loop
}
else if(variableTable[j].label == -1){
variableTable[j].label = abs(terminals[i]);
variableTable[j].value = 'T';
variableTable[j].size = 100;
variableTable[j].indexes = (int64_t*)malloc(variableTable[j].size * sizeof(int64_t));
variableTable[j].count = 0;
variableTable[j].weightedCount = 0;
variableTable[j].negIndexes = (int64_t*)malloc(variableTable[j].size * sizeof(int64_t));
variableTable[j].negCount = 0;
variableTable[j].negWeightedCount = 0;
variableTable[j].evaluated = 'F';
if(terminals[i] > 0){
variableTable[j].indexes[variableTable[j].count] = i;
variableTable[j].count++;
variableTable[j].weightedCount++;
}
else{
variableTable[j].negIndexes[variableTable[j].negCount] = i;
variableTable[j].negCount++;
variableTable[j].negWeightedCount++;
}
break; // made a new variable and updated it, break out of inner loop
}
}
}
// Shrink the indexes arrays
for(j = 0; j < numVariableTable; j++){
variableTable[j].indexes = (int64_t*)realloc(variableTable[j].indexes, variableTable[j].count * sizeof(int64_t));
variableTable[j].negIndexes = (int64_t*)realloc(variableTable[j].negIndexes, variableTable[j].negCount * sizeof(int64_t));
}
return variableTable;
}
static int64_t* makeReverseLookUpTable(int64_t* reverseLookUpTable, int64_t numVariableValues, struct satVariable* variableTable, int64_t numVariableTable){
int64_t i;
reverseLookUpTable = (int64_t*)malloc((numVariableValues + 1) * sizeof(int64_t));
memset(reverseLookUpTable, -1, (numVariableValues + 1) * sizeof(char));
for(i = 0; i < numVariableTable; i++){
reverseLookUpTable[variableTable[i].label] = i;
}
return reverseLookUpTable;
}
static inline void decrementSibWeight(int64_t instance, int64_t* terminals, struct satVariable* variableTable, int64_t* reverseLookUpTable){
int64_t sibling;
int64_t variabltTableIndex;
// determine if instance is left variable or right variable in the clause
if(instance % 2 == 0){
sibling = instance + 1;
}
else{
sibling = instance - 1;
}
// get sibling and look up it's index in reverseLookUpTable
// use the result to decrement its pos or neg weight in variableTable
if(terminals[sibling] > 0){
variabltTableIndex = reverseLookUpTable[terminals[sibling]];
variableTable[variabltTableIndex].weightedCount--;
}
else{
variabltTableIndex = reverseLookUpTable[abs(terminals[sibling])];
variableTable[variabltTableIndex].negWeightedCount--;
}
}
static void greedyAnalysis(int64_t* terminals, int64_t numTerminals, struct satVariable* variableTable, int64_t numVariableTable, int64_t* reverseLookUpTable){
int64_t count = 0;
int64_t dominant = 0;
int64_t i, current, largest;
while(count < numTerminals){
largest = 0;
current = -1;
for(i = 0; i < numVariableTable; i++){
if(variableTable[i].evaluated == 'F' && (variableTable[i].weightedCount >= largest || variableTable[i].negWeightedCount >= largest)){
current = i;
if(variableTable[i].weightedCount > variableTable[i].negWeightedCount){
largest = variableTable[i].weightedCount;
dominant = 1;
}
else{
largest = variableTable[i].negWeightedCount;
dominant = -1;
}
}
}
// found current largest
// assign value T/F
if(dominant > 0){
variableTable[current].value = 'T';
}
else{
variableTable[current].value = 'F';
}
// set evaluated to T
variableTable[current].evaluated = 'T';
// if largest is 0, it means i am examining an item that has no weight, thus its value does not matter but i still need to evaluate it
// this is probably due to it's sibling satifying the clauses, thus their weights do not need to be decremented as they are already at 0
if(largest != 0){
// go through currents indexes and decrease all of it's siblings weights by 1 since those clauses have been satisfied and siblings have no weight in them
// over decrementation is fine, only happens when variable has already been evaluated and set to -1 weight previously, all other decrementations are valid
for(i = 0; i < variableTable[current].count; i++){
decrementSibWeight(variableTable[current].indexes[i], terminals, variableTable, reverseLookUpTable);
}
for(i = 0; i < variableTable[current].negCount; i++){
decrementSibWeight(variableTable[current].negIndexes[i], terminals, variableTable, reverseLookUpTable);
}
}
// set weights to -1 since it has none anymore, weight will continue to decrease but as long as it is in the negatives after being evaluated all is fine
variableTable[current].weightedCount = -1;
variableTable[current].negWeightedCount = -1;
// increment count by currents total pos and neg counts
count = count + variableTable[current].count + variableTable[current].negCount;
}
}
static inline void updateVariableValues(char* variableValues, struct satVariable* variableTable, int64_t numVariableTable){
int64_t i;
for(i = 0; i < numVariableTable; i++){
variableValues[variableTable[i].label] = variableTable[i].value;
}
}
static inline void printValues(char* variableValues, int64_t numVariableValues){
int64_t i;
for(i = 1; i <= numVariableValues; i++){
printf("%c", variableValues[i]);
}
printf("\n");
}
static inline int64_t evaluateAssignments(int64_t* terminals, int64_t numTerminals, char* variableValues){
int64_t i;
int64_t count = 0;
for(i = 0; i < numTerminals - 1; i += 2){
if(terminals[i] > 0 && terminals[i + 1] > 0){
if(variableValues[abs(terminals[i])] == 'T' || variableValues[abs(terminals[i + 1])] == 'T'){
count++;
}
}
else if(terminals[i] > 0 && terminals[i + 1] < 0){
if(variableValues[abs(terminals[i])] == 'T' || variableValues[abs(terminals[i + 1])] == 'F'){
count++;
}
}
else if(terminals[i] < 0 && terminals[i + 1] > 0){
if(variableValues[abs(terminals[i])] == 'F' || variableValues[abs(terminals[i + 1])] == 'T'){
count++;
}
}
else if(terminals[i] < 0 && terminals[i + 1] < 0){
if(variableValues[abs(terminals[i])] == 'F' || variableValues[abs(terminals[i + 1])] == 'F'){
count++;
}
}
}
return count;
}
static int64_t randint(int64_t n) {
if((n - 1) == RAND_MAX){
return rand();
}else{
int64_t end = RAND_MAX / n;
assert (end > 0L);
end *= n;
int64_t r;
while ((r = rand()) >= end);
return r % n;
}
}
static inline int64_t selectRandVariable(int64_t* unSatTerminals, int64_t numUnSatTerminals, int64_t* reverseLookUpTable){
int64_t randIndex = randint(numUnSatTerminals);
int64_t selectedVariableIndex = -1;
// decide if i want left or right sibling
// if even i want left sibling, otherwise choose right
if(randint(numUnSatTerminals) % 2 == 0){
if(randIndex % 2 == 0){
selectedVariableIndex = reverseLookUpTable[abs(unSatTerminals[randIndex])];
}
else{
selectedVariableIndex = reverseLookUpTable[abs(unSatTerminals[randIndex - 1])];
}
}
else{
if(randIndex % 2 == 0){
selectedVariableIndex = reverseLookUpTable[abs(unSatTerminals[randIndex + 1])];
}
else{
selectedVariableIndex = reverseLookUpTable[abs(unSatTerminals[randIndex])];
}
}
return selectedVariableIndex; // in variableTable
}
static inline void flipVariableValue(struct satVariable* variable){
if(variable->value == 'T'){
variable->value = 'F';
}
else{
variable->value = 'T';
}
}
static int64_t* makeUnSatTerminals(int64_t* numUnSatTerminals, int64_t* terminals, int64_t numTerminals, char* variableValues){
int64_t i;
int64_t clauses = 0;
int64_t* unSatTerminals = NULL;
for(i = 0; i < numTerminals - 1; i += 2){
if(terminals[i] > 0 && terminals[i + 1] > 0){
if(variableValues[abs(terminals[i])] == 'F' || variableValues[abs(terminals[i + 1])] == 'F'){
clauses++;
}
}
else if(terminals[i] > 0 && terminals[i + 1] < 0){
if(variableValues[abs(terminals[i])] == 'F' || variableValues[abs(terminals[i + 1])] == 'T'){
clauses++;
}
}
else if(terminals[i] < 0 && terminals[i + 1] > 0){
if(variableValues[abs(terminals[i])] == 'T' || variableValues[abs(terminals[i + 1])] == 'F'){
clauses++;
}
}
else if(terminals[i] < 0 && terminals[i + 1] < 0){
if(variableValues[abs(terminals[i])] == 'T' || variableValues[abs(terminals[i + 1])] == 'T'){
clauses++;
}
}
}
*numUnSatTerminals = clauses * 2; // i just counted clauses
unSatTerminals = (int64_t*)malloc((clauses * 2) * sizeof(int64_t));
clauses = 0;
for(i = 0; i < numTerminals - 1; i += 2){
if(terminals[i] > 0 && terminals[i + 1] > 0){
if(variableValues[abs(terminals[i])] == 'F' || variableValues[abs(terminals[i + 1])] == 'F'){
unSatTerminals[clauses] = terminals[i];
unSatTerminals[clauses + 1] = terminals[i + 1];
clauses += 2;
}
}
else if(terminals[i] > 0 && terminals[i + 1] < 0){
if(variableValues[abs(terminals[i])] == 'F' || variableValues[abs(terminals[i + 1])] == 'T'){
unSatTerminals[clauses] = terminals[i];
unSatTerminals[clauses + 1] = terminals[i + 1];
clauses += 2;
}
}
else if(terminals[i] < 0 && terminals[i + 1] > 0){
if(variableValues[abs(terminals[i])] == 'T' || variableValues[abs(terminals[i + 1])] == 'F'){
unSatTerminals[clauses] = terminals[i];
unSatTerminals[clauses + 1] = terminals[i + 1];
clauses += 2;
}
}
else if(terminals[i] < 0 && terminals[i + 1] < 0){
if(variableValues[abs(terminals[i])] == 'T' || variableValues[abs(terminals[i + 1])] == 'T'){
unSatTerminals[clauses] = terminals[i];
unSatTerminals[clauses + 1] = terminals[i + 1];
clauses += 2;
}
}
}
return unSatTerminals;
}
static int64_t* removeClausesWithVariable(int64_t variableLabel, int64_t* unSatTerminals, int64_t* numUnSatTerminals){
int64_t i;
int64_t size = 0;
int64_t* newArray = (int64_t*)malloc(*numUnSatTerminals * sizeof(int64_t));
for(i = 0; i < *numUnSatTerminals; i++){
if(abs(unSatTerminals[i]) == variableLabel){
if(i % 2 == 0){
i++; // skip i, i + 1 skipped in loop increment
}
else{
size--; // reverse counter 1 to overwrite i - 1, i skipped in loop increment
}
}
else{
// add the terminal
newArray[size] = unSatTerminals[i];
size++;
}
}
freePtr(unSatTerminals);
*numUnSatTerminals = size;
newArray = (int64_t*)realloc(newArray, size * sizeof(int64_t));
return newArray;
}
static void localSearch(int64_t maxTries, int64_t* result, int64_t* terminals, int64_t numTerminals, struct satVariable* variableTable, int64_t numVariableTable, char* variableValues, int64_t* reverseLookUpTable){
int64_t i;
int64_t lastVariableFlippedIndex = -1;
int64_t currentResult = 0;
int64_t* unSatTerminals = NULL;
int64_t numUnSatTerminals = 0;
// NOTE: maybe modify this so that it uses all the terminals for random selection?
unSatTerminals = makeUnSatTerminals(&numUnSatTerminals, terminals, numTerminals, variableValues);
for(i = 0; i < maxTries; i++){
// still have tries but dont have any more unchecked variables to check
if(numUnSatTerminals == 0){
break;
}
// all possible clauses satisfied, i can stop
if(numTerminals / 2 == *result){
break;
}
lastVariableFlippedIndex = selectRandVariable(unSatTerminals, numUnSatTerminals, reverseLookUpTable);
flipVariableValue(&variableTable[lastVariableFlippedIndex]);
updateVariableValues(variableValues, variableTable, numVariableTable);
currentResult = evaluateAssignments(terminals, numTerminals, variableValues);
if(currentResult > *result){
*result = currentResult;
// rebuild unSatTerminals array
freePtr(unSatTerminals);
unSatTerminals = makeUnSatTerminals(&numUnSatTerminals, terminals, numTerminals, variableValues);
}
else{
// flip the value back, it will get updated next time through loop along the next selected variable being tested
flipVariableValue(&variableTable[lastVariableFlippedIndex]);
// remove all caluses from unSatTerminals with lastVariableFlippedIndex
unSatTerminals = removeClausesWithVariable(variableTable[lastVariableFlippedIndex].label, unSatTerminals, &numUnSatTerminals);
lastVariableFlippedIndex = -1;
// in case the next increment would exceed maxTries and i had an unsuccessfully last check, i want to restore my previous answer
if(i == maxTries - 1){
updateVariableValues(variableValues, variableTable, numVariableTable);
*result = evaluateAssignments(terminals, numTerminals, variableValues); // extra evaluation but just in case
}
}
}
freePtr(unSatTerminals);
}
static void localSearchRand(int64_t maxTries, int64_t* result, int64_t* terminals, int64_t numTerminals, struct satVariable* variableTable, int64_t numVariableTable, char* variableValues, int64_t* reverseLookUpTable){
int64_t i;
int64_t lastVariableFlippedIndex = -1;
int64_t currentResult = 0;
for(i = 0; i < maxTries; i++){
// all possible clauses satisfied, i can stop
if(numTerminals / 2 == *result){
break;
}
lastVariableFlippedIndex = selectRandVariable(terminals, numTerminals, reverseLookUpTable);
flipVariableValue(&variableTable[lastVariableFlippedIndex]);
updateVariableValues(variableValues, variableTable, numVariableTable);
currentResult = evaluateAssignments(terminals, numTerminals, variableValues);
if(currentResult > *result){
*result = currentResult;
}
else{
// flip the value back, it will get updated next time through loop along the next selected variable being tested
flipVariableValue(&variableTable[lastVariableFlippedIndex]);
// in case the next increment would exceed maxTries and i had an unsuccessfully last check, i want to restore my previous answer
if(i == maxTries - 1){
updateVariableValues(variableValues, variableTable, numVariableTable);
*result = evaluateAssignments(terminals, numTerminals, variableValues); // extra evaluation but just in case
}
}
}
}
int main(int argc, char* argv[]){
int64_t i;
int64_t* terminals = NULL; // all the terminals as they appear in the file, a terminal is a variable in a clause so (A v A) has 2 terminals but 1 variable
int64_t numTerminals = 0; // total number if variables (with repetition) referred to as terminals
char* variableValues = NULL; // this will contain the answer at the end, size has +1 for direct index mapping purposes
int64_t* reverseLookUpTable = NULL; // this table maps the (index) value of the variable values to the (value) index of it in the variableTable, same size as variableValues table, +1 for direct mapping
int64_t numVariableValues = 0; // number of variables in the files (used and unused)
struct satVariable* variableTable = NULL; // used for evaluation of each used variable, contains relevant info for that variable
int64_t numVariableTable = 0; // number of used variables in the file only
int64_t result = 0;
int64_t maxTries;
if(argc <= 1){
perror("ERROR: Must pass in file name of values!");
perror("Can specify the maximum number of tries for local search with a second parameter, must be integer");
exit(EXIT_FAILURE);
}
terminals = readClauses(argv[1], &numTerminals, &numVariableValues);
variableValues = findUsedVariables(terminals, numTerminals, numVariableValues, &numVariableTable);
variableTable = makeVariableTable(terminals, numTerminals, numVariableTable);
reverseLookUpTable = makeReverseLookUpTable(reverseLookUpTable, numVariableValues, variableTable, numVariableTable);
// use waited greedy to make a seeder assignment for local search
greedyAnalysis(terminals, numTerminals, variableTable, numVariableTable, reverseLookUpTable);
// testPrint(terminals, numTerminals, variableValues, numVariableValues, variableTable, numVariableTable);
updateVariableValues(variableValues, variableTable, numVariableTable);
result = evaluateAssignments(terminals, numTerminals, variableValues);
printf("Greedy Solution: %lld\n", (long long int)result);
//printValues(variableValues, numVariableValues);
// use local search as local search algorithm to improve answer, default for maxTries is 1/2 of the number of clauses, i think this is a good default
// but the default can be over written by the user if so chosen.
// this version of local search is greedy, we do not choose a random clause, but rather we choose a random clause from all unsatisfied clauses
maxTries = numTerminals / 2;
if(argc == 3){
maxTries = atoi(argv[2]);
}
printf("Using %lld as max tries for local search\n", (long long int)maxTries
);
localSearch(maxTries, &result, terminals, numTerminals, variableTable, numVariableTable, variableValues, reverseLookUpTable);
printf("local search Unsat Only Solution: %lld\n", (long long int)result);
localSearchRand(maxTries, &result, terminals, numTerminals, variableTable, numVariableTable, variableValues, reverseLookUpTable);
printf("local search random Solution: %lld\n", (long long int)result);
printValues(variableValues, numVariableValues);
freePtr(terminals);
freePtr(variableValues);
freePtr(reverseLookUpTable);
for(i = 0; i < numVariableTable; i++){
freePtr(variableTable[i].indexes);
freePtr(variableTable[i].negIndexes);
}
freePtr(variableTable);
return 0;
}
|
atzenn/VERGE
|
src/policy/feerate.h
|
// Copyright (c) 2009-2010 <NAME>
// Copyright (c) 2009-2017 The Bitcoin Core developers
// Copyright (c) 2018-2018 The VERGE Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef VERGE_POLICY_FEERATE_H
#define VERGE_POLICY_FEERATE_H
#include <amount.h>
#include <serialize.h>
#include <string>
extern const std::string CURRENCY_UNIT;
extern const size_t ONE_KILO_BYTE;
/**
* Fee rate in satoshis per kilobyte: CAmount / kB
*/
class CFeeRate
{
private:
CAmount nSatoshisPerK; // unit is satoshis-per-1,000-bytes
public:
/** Fee rate of 0 satoshis per kB */
CFeeRate() : nSatoshisPerK(0) { }
template<typename I>
CFeeRate(const I _nSatoshisPerK): nSatoshisPerK(_nSatoshisPerK) {
// We've previously had bugs creep in from silent double->int conversion...
static_assert(std::is_integral<I>::value, "CFeeRate should be used without floats");
}
/** Constructor for a fee rate in satoshis per kB. The size in bytes must not exceed (2^63 - 1)*/
CFeeRate(const CAmount& nFeePaid, size_t nBytes);
/**
* Return the fee in satoshis for the given size in bytes.
*/
CAmount GetFee(size_t nBytes) const;
/**
* Return the fee in satoshis for a size of 1000 bytes
*/
CAmount GetFeePerK() const { return GetFee(1000); }
friend bool operator<(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK < b.nSatoshisPerK; }
friend bool operator>(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK > b.nSatoshisPerK; }
friend bool operator==(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK == b.nSatoshisPerK; }
friend bool operator<=(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK <= b.nSatoshisPerK; }
friend bool operator>=(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK >= b.nSatoshisPerK; }
friend bool operator!=(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK != b.nSatoshisPerK; }
CFeeRate& operator+=(const CFeeRate& a) { nSatoshisPerK += a.nSatoshisPerK; return *this; }
std::string ToString() const;
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITE(nSatoshisPerK);
}
};
#endif // VERGE_POLICY_FEERATE_H
|
BirdandLion/SocialHubNets
|
SocialHubNets/SocialHubNets/Classes/NewFeature/Controllers/GPNewFeatureController.h
|
//
// GPNewFeatureController.h
// 我的微博
//
// Created by qianfeng on 16/1/9.
// Copyright (c) 2016年 kelvin. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface GPNewFeatureController : UIViewController
@end
|
patwonder/pbrt-v2-skin
|
src/core/memory.h
|
/*
pbrt source code Copyright(c) 1998-2012 <NAME> and <NAME>.
This file is part of pbrt.
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#if defined(_MSC_VER)
#pragma once
#endif
#ifndef PBRT_CORE_MEMORY_H
#define PBRT_CORE_MEMORY_H
// core/memory.h*
#include "pbrt.h"
#include "parallel.h"
// Memory Declarations
class ReferenceCounted {
protected:
ReferenceCounted() { nReferences = 0; }
~ReferenceCounted() {}
private:
mutable AtomicInt32 nReferences;
ReferenceCounted(const ReferenceCounted &);
ReferenceCounted &operator=(const ReferenceCounted &);
template<typename T>
friend class Reference;
};
template <typename T> class Reference {
public:
// Reference Public Methods
Reference(T* p = NULL) {
ptr = p;
if (ptr) AtomicIncrement(&ptr->nReferences);
}
Reference &operator=(T *p) {
if (p) AtomicIncrement(&p->nReferences);
if (ptr && AtomicDecrement(&ptr->nReferences) == 0) delete ptr;
ptr = p;
return *this;
}
Reference(const Reference &r) {
ptr = r.ptr;
if (ptr) AtomicIncrement(&ptr->nReferences);
}
Reference &operator=(const Reference &r) {
if (r.ptr) AtomicIncrement(&r.ptr->nReferences);
if (ptr && AtomicDecrement(&ptr->nReferences) == 0) delete ptr;
ptr = r.ptr;
return *this;
}
Reference(Reference &&r) {
ptr = r.ptr;
r.ptr = NULL;
}
Reference &operator=(Reference &&r) {
swap(ptr, r.ptr);
return *this;
}
template<class S>
friend class Reference;
template<class S>
Reference(S* p) {
ptr = p;
if (ptr) AtomicIncrement(&ptr->nReferences);
}
template<class S>
Reference &operator=(S *p) {
if (p) AtomicIncrement(&p->nReferences);
if (ptr && AtomicDecrement(&ptr->nReferences) == 0) delete ptr;
ptr = p;
return *this;
}
template<class S>
Reference(const Reference<S> &r) {
ptr = r.ptr;
if (ptr) AtomicIncrement(&ptr->nReferences);
}
template<class S>
Reference &operator=(const Reference<S> &r) {
if (r.ptr) AtomicIncrement(&r.ptr->nReferences);
if (ptr && AtomicDecrement(&ptr->nReferences) == 0) delete ptr;
ptr = r.ptr;
return *this;
}
template<class S>
Reference(Reference<S> &&r) {
ptr = r.ptr;
r.ptr = NULL;
}
template<class S>
Reference &operator=(Reference<S> &&r) {
if (ptr && AtomicDecrement(&ptr->nReferences) == 0) delete ptr;
ptr = r.ptr;
r.ptr = NULL;
return *this;
}
~Reference() {
if (ptr && AtomicDecrement(&ptr->nReferences) == 0)
delete ptr;
}
T *operator->() const { return ptr; }
operator bool() const { return ptr != NULL; }
T *GetPtr() const { return ptr; }
private:
T *ptr;
};
void *AllocAligned(size_t size);
template <typename T> T *AllocAligned(uint32_t count) {
return (T *)AllocAligned(count * sizeof(T));
}
void FreeAligned(void *);
class SelfishAllocator;
void InitTLSAllocator();
void CleanupTLSAllocator();
class MemoryArena {
public:
// MemoryArena Public Methods
MemoryArena(uint32_t bs = 32768);
~MemoryArena();
void *Alloc(uint32_t sz);
template<typename T> T *Alloc(uint32_t count = 1) {
T *ret = (T *)Alloc(count * sizeof(T));
for (uint32_t i = 0; i < count; ++i)
new (&ret[i]) T();
return ret;
}
void FreeAll();
private:
// MemoryArena Private Data
uint32_t curBlockPos, blockSize;
char *currentBlock;
vector<char *> usedBlocks, availableBlocks;
SelfishAllocator& allocator;
};
template <typename T, int logBlockSize> class BlockedArray {
public:
// BlockedArray Public Methods
BlockedArray(uint32_t nu, uint32_t nv, const T *d = NULL) {
uRes = nu;
vRes = nv;
uBlocks = RoundUp(uRes) >> logBlockSize;
uint32_t nAlloc = RoundUp(uRes) * RoundUp(vRes);
data = AllocAligned<T>(nAlloc);
for (uint32_t i = 0; i < nAlloc; ++i)
new (&data[i]) T();
if (d)
for (uint32_t v = 0; v < vRes; ++v)
for (uint32_t u = 0; u < uRes; ++u)
(*this)(u, v) = d[v * uRes + u];
}
uint32_t BlockSize() const { return 1 << logBlockSize; }
uint32_t RoundUp(uint32_t x) const {
return (x + BlockSize() - 1) & ~(BlockSize() - 1);
}
uint32_t uSize() const { return uRes; }
uint32_t vSize() const { return vRes; }
~BlockedArray() {
for (uint32_t i = 0; i < uRes * vRes; ++i)
data[i].~T();
FreeAligned(data);
}
uint32_t Block(uint32_t a) const { return a >> logBlockSize; }
uint32_t Offset(uint32_t a) const { return (a & (BlockSize() - 1)); }
T &operator()(uint32_t u, uint32_t v) {
uint32_t bu = Block(u), bv = Block(v);
uint32_t ou = Offset(u), ov = Offset(v);
uint32_t offset = BlockSize() * BlockSize() * (uBlocks * bv + bu);
offset += BlockSize() * ov + ou;
return data[offset];
}
const T &operator()(uint32_t u, uint32_t v) const {
uint32_t bu = Block(u), bv = Block(v);
uint32_t ou = Offset(u), ov = Offset(v);
uint32_t offset = BlockSize() * BlockSize() * (uBlocks * bv + bu);
offset += BlockSize() * ov + ou;
return data[offset];
}
void GetLinearArray(T *a) const {
for (uint32_t v = 0; v < vRes; ++v)
for (uint32_t u = 0; u < uRes; ++u)
*a++ = (*this)(u, v);
}
private:
// BlockedArray Private Data
T *data;
uint32_t uRes, vRes, uBlocks;
};
#endif // PBRT_CORE_MEMORY_H
|
patwonder/pbrt-v2-skin
|
src/accelerators/grid.h
|
<filename>src/accelerators/grid.h
/*
pbrt source code Copyright(c) 1998-2012 <NAME> and <NAME>.
This file is part of pbrt.
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#if defined(_MSC_VER)
#pragma once
#endif
#ifndef PBRT_ACCELERATORS_GRID_H
#define PBRT_ACCELERATORS_GRID_H
// accelerators/grid.h*
#include "pbrt.h"
#include "primitive.h"
// GridAccel Forward Declarations
struct Voxel;
// Voxel Declarations
struct Voxel {
// Voxel Public Methods
uint32_t size() const { return primitives.size(); }
Voxel() { }
Voxel(Reference<Primitive> op) {
allCanIntersect = false;
primitives.push_back(op);
}
void AddPrimitive(Reference<Primitive> prim) {
primitives.push_back(prim);
}
bool Intersect(const Ray &ray, Intersection *isect, RWMutexLock &lock);
bool IntersectP(const Ray &ray, RWMutexLock &lock);
bool IntersectExcept(const Ray &ray, Intersection *isect, uint32_t primitiveId, RWMutexLock &lock);
private:
vector<Reference<Primitive> > primitives;
bool allCanIntersect;
};
// GridAccel Declarations
class GridAccel : public Aggregate {
public:
// GridAccel Public Methods
GridAccel(const vector<Reference<Primitive> > &p, bool refineImmediately);
BBox WorldBound() const;
bool CanIntersect() const { return true; }
~GridAccel();
bool Intersect(const Ray &ray, Intersection *isect) const;
bool IntersectP(const Ray &ray) const;
bool IntersectExcept(const Ray &ray, Intersection *isect, uint32_t primitiveId) const override;
private:
// GridAccel Private Methods
int posToVoxel(const Point &P, int axis) const {
int v = Float2Int((P[axis] - bounds.pMin[axis]) *
invWidth[axis]);
return Clamp(v, 0, nVoxels[axis]-1);
}
float voxelToPos(int p, int axis) const {
return bounds.pMin[axis] + p * width[axis];
}
inline int offset(int x, int y, int z) const {
return z*nVoxels[0]*nVoxels[1] + y*nVoxels[0] + x;
}
// GridAccel Private Data
vector<Reference<Primitive> > primitives;
int nVoxels[3];
BBox bounds;
Vector width, invWidth;
Voxel **voxels;
MemoryArena voxelArena;
mutable RWMutex *rwMutex;
};
GridAccel *CreateGridAccelerator(const vector<Reference<Primitive> > &prims,
const ParamSet &ps);
#endif // PBRT_ACCELERATORS_GRID_H
|
patwonder/pbrt-v2-skin
|
src/core/shape.h
|
/*
pbrt source code Copyright(c) 1998-2012 <NAME> and <NAME>.
This file is part of pbrt.
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#if defined(_MSC_VER)
#pragma once
#endif
#ifndef PBRT_CORE_SHAPE_H
#define PBRT_CORE_SHAPE_H
// core/shape.h*
#include "pbrt.h"
#include "geometry.h"
#include "transform.h"
#include "diffgeom.h"
#include "memory.h"
// Shape Declarations
class Shape : public ReferenceCounted {
public:
// Shape Interface
Shape(const Transform *o2w, const Transform *w2o, bool ro);
virtual ~Shape();
virtual BBox ObjectBound() const = 0;
virtual BBox WorldBound() const;
virtual bool CanIntersect() const;
virtual void Refine(vector<Reference<Shape> > &refined) const;
virtual bool Intersect(const Ray &ray, float *tHit,
float *rayEpsilon, DifferentialGeometry *dg) const;
virtual bool IntersectP(const Ray &ray) const;
virtual void GetShadingGeometry(const Transform &obj2world,
const DifferentialGeometry &dg,
DifferentialGeometry *dgShading) const {
*dgShading = dg;
}
virtual float Area() const;
virtual Point Sample(float u1, float u2, Normal *Ns) const {
Severe("Unimplemented Shape::Sample() method called");
return Point();
}
virtual float Pdf(const Point &Pshape) const {
return 1.f / Area();
}
virtual Point Sample(const Point &P, float u1, float u2,
Normal *Ns) const {
return Sample(u1, u2, Ns);
}
virtual float Pdf(const Point &p, const Vector &wi) const;
// Shape Public Data
const Transform *ObjectToWorld, *WorldToObject;
const bool ReverseOrientation, TransformSwapsHandedness;
const uint32_t shapeId;
static uint32_t nextshapeId;
protected:
Shape(const Shape&);
};
class ShrinkableShape: public Shape {
public:
ShrinkableShape(const Transform *o2w, const Transform *w2o, bool ro);
virtual Reference<ShrinkableShape> Shrink(float distance) const = 0;
};
#endif // PBRT_CORE_SHAPE_H
|
patwonder/pbrt-v2-skin
|
src/renderers/profilefit.h
|
/*
Copyright(c) 2013-2014 <NAME>.
This file is part of fork of pbrt (pbrt-v2-skin).
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include "pbrt.h"
#include "renderer.h"
#include "skinlayer.h"
typedef vector<float> ParamRange;
class SkinCoefficients;
struct VariableParams;
class GaussianFitTask;
struct SpectralGaussianCoeffs {
vector<SampledSpectrum> coeffs;
SampledSpectrum error;
};
class MultipoleProfileFitRenderer : public Renderer {
public:
// MultipoleProfileFitRenderer Public Methods
MultipoleProfileFitRenderer(const vector<SkinLayer>& layers,
ParamRange f_mel, ParamRange f_eu, ParamRange f_blood,
ParamRange f_ohg, uint32_t desiredLength, uint32_t segments, const string& filename,
int idRange[2], int splitTasks, const string& pbrtFilePath);
void Render(const Scene* scene) override;
Spectrum Li(const Scene* scene, const RayDifferential& ray,
const Sample* sample, RNG& rng, MemoryArena& arena,
Intersection* isect, Spectrum* T) const override;
Spectrum Transmittance(const Scene* scene, const RayDifferential& ray,
const Sample* sample, RNG& rng, MemoryArena& arena) const override;
private:
// MultipoleProfileFitRenderer Private Data
vector<SkinLayer> layers;
ParamRange pr_f_mel;
ParamRange pr_f_eu;
ParamRange pr_f_blood;
ParamRange pr_f_ohg;
uint32_t desiredLength;
uint32_t nSegments;
string filename;
int idRange[2];
int splitTasks;
string pbrtFilePath;
// MultipoleProfileFitRenderer Private Methods
template <class Processor>
void ForRanges(const Processor& p) const;
static float NextParamFromId(uint32_t& id, ParamRange pr);
VariableParams ParamsFromId(uint32_t id) const;
vector<Task*> CreateGaussianFitTasks(const SkinCoefficients& coeffs,
const vector<float>& sigmas, SpectralGaussianCoeffs& sgc,
ProgressReporter& reporter, uint32_t id) const;
int GetTotalNumTasks() const;
void DoProfileFit() const;
void DoPbrtFileSplit() const;
};
MultipoleProfileFitRenderer* CreateMultipoleProfileFitRenderer(const ParamSet& params, const string& pbrtFilePath);
|
patwonder/pbrt-v2-skin
|
src/materials/layeredskin.h
|
/*
Copyright(c) 2013-2014 <NAME>.
This file is part of fork of pbrt (pbrt-v2-skin).
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include "material.h"
#include "skinlayer.h"
class SkinCoefficients;
struct MultipoleProfileData;
class LayeredSkin : public LayeredMaterial {
public:
// LayeredSkin Public Methods
LayeredSkin(const vector<SkinLayer>& layers, float roughness,
float nmperunit, const SkinCoefficients& coeff,
Reference<Texture<Spectrum> > Kr, Reference<Texture<Spectrum> > Kt,
Reference<Texture<float> > bumpMap, Reference<Texture<Spectrum> > albedo,
bool doubleRefSSLF, bool generateProfile, bool useMonteCarloProfile, uint64_t nPhotons,
bool lerpOnThinSlab, bool showIrradiancePoints, float irradiancePointSize,
bool rgbProfile, int desiredLength);
~LayeredSkin();
vector<float> GetLayerThickness() const override;
BSDF* GetBSDF(const DifferentialGeometry &dgGeom,
const DifferentialGeometry &dgShading,
MemoryArena &arena) const override;
BSSRDF* GetBSSRDF(const DifferentialGeometry &dgGeom,
const DifferentialGeometry &dgShading,
MemoryArena &arena) const override;
const MultipoleBSSRDF* GetMultipoleBSSRDF(
const DifferentialGeometry &dgGeom,
const DifferentialGeometry &dgShading,
MemoryArena &arena) const override;
bool HasSubsurfaceScattering() const override { return true; }
BumpMapping GetBumpMapping() const override {
return BumpMapping(bumpMap);
}
BSDF* GetLayeredBSDF(int layerIndex,
const DifferentialGeometry &dgGeom,
const DifferentialGeometry &dgShading,
MemoryArena &arena) const override;
BSSRDF* GetLayeredBSSRDF(int layerIndex,
const DifferentialGeometry &dgGeom,
const DifferentialGeometry &dgShading,
MemoryArena &arena) const override;
LayerParam GetLayerParam(int index) const override;
private:
// LayeredSkin Private Data
vector<SkinLayer> layers;
float roughness;
float nmperunit;
bool doubleRefSSLF;
SkinCoefficients* pcoeff;
LayerParam lps[3];
Reference<Texture<Spectrum> > Kr;
Reference<Texture<Spectrum> > Kt;
Reference<Texture<float> > bumpMap;
Reference<Texture<Spectrum> > albedo;
MultipoleBSSRDFData* preparedBSSRDFData;
MultipoleProfileData* profileData;
};
// Creator function
LayeredSkin* CreateLayeredSkinMaterial(const ParamSet& ps, const TextureParams& mp);
|
patwonder/pbrt-v2-skin
|
src/accelerators/bvh.h
|
<gh_stars>1-10
/*
pbrt source code Copyright(c) 1998-2012 <NAME> and <NAME>.
This file is part of pbrt.
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#if defined(_MSC_VER)
#pragma once
#endif
#ifndef PBRT_ACCELERATORS_BVH_H
#define PBRT_ACCELERATORS_BVH_H
// accelerators/bvh.h*
#include "pbrt.h"
#include "primitive.h"
struct BVHBuildNode;
// BVHAccel Forward Declarations
struct BVHPrimitiveInfo;
struct LinearBVHNode;
// BVHAccel Declarations
class BVHAccel : public Aggregate {
public:
// BVHAccel Public Methods
BVHAccel(const vector<Reference<Primitive> > &p, uint32_t maxPrims = 1,
const string &sm = "sah");
BBox WorldBound() const;
bool CanIntersect() const { return true; }
~BVHAccel();
bool Intersect(const Ray &ray, Intersection *isect) const;
bool IntersectP(const Ray &ray) const;
bool IntersectExcept(const Ray &r, Intersection* in, uint32_t primitiveId) const override;
private:
// BVHAccel Private Methods
BVHBuildNode *recursiveBuild(MemoryArena &buildArena,
vector<BVHPrimitiveInfo> &buildData, uint32_t start, uint32_t end,
uint32_t *totalNodes, vector<Reference<Primitive> > &orderedPrims);
uint32_t flattenBVHTree(BVHBuildNode *node, uint32_t *offset);
// BVHAccel Private Data
uint32_t maxPrimsInNode;
enum SplitMethod { SPLIT_MIDDLE, SPLIT_EQUAL_COUNTS, SPLIT_SAH };
SplitMethod splitMethod;
vector<Reference<Primitive> > primitives;
LinearBVHNode *nodes;
};
BVHAccel *CreateBVHAccelerator(const vector<Reference<Primitive> > &prims,
const ParamSet &ps);
#endif // PBRT_ACCELERATORS_BVH_H
|
patwonder/pbrt-v2-skin
|
src/multipole/MultipoleProfileCalculator/MultipoleProfileCalculator.h
|
<gh_stars>1-10
/*
Copyright(c) 2013-2014 <NAME>.
This file is part of fork of pbrt (pbrt-v2-skin).
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "mpc-types.h"
typedef struct {
// Index of refraction
float ior;
// Layer thickness
float thickness;
// Absorption coefficient
float mua;
// Reduced scattering coefficient
float musp;
// Anisotropy for the HGPF (probably not needed)
float g_HG;
} MPC_LayerSpec;
typedef struct {
// distance between adjacent samples
float desiredStepSize;
// number of samples in one direction
uint32 desiredLength;
// if lerping shoule be used when the slab is thin (< 2 mfp)
bool lerpOnThinSlab;
} MPC_Options;
typedef struct {
// number of samples
uint32 length;
// Profile data
float* pDistanceSquared;
float* pReflectance;
float* pTransmittance;
// statistics
float totalReflectance;
float totalTransmittance;
} MPC_Output;
// Profile calculation
MULTIPOLEPROFILECALCULATOR_API void MPC_CreateOutput(uint32 length, MPC_Output** oppOutput);
MULTIPOLEPROFILECALCULATOR_API void MPC_ComputeDiffusionProfile(uint32 numLayers, const MPC_LayerSpec* pLayerSpecs,
const MPC_Options* pOptions, MPC_Output** oppOutput);
MULTIPOLEPROFILECALCULATOR_API void MPC_ResampleForUniformDistanceSquaredDistribution(MPC_Output* pOutput, uint32 targetLength = 0);
MULTIPOLEPROFILECALCULATOR_API void MPC_ResampleDistribution(MPC_Output* pOutput, uint32 nSamplePoints, float* samplePoints);
MULTIPOLEPROFILECALCULATOR_API void MPC_FreeOutput(MPC_Output* pOutput);
MULTIPOLEPROFILECALCULATOR_API void MPC_ClearCache();
|
patwonder/pbrt-v2-skin
|
src/core/material.h
|
/*
pbrt source code Copyright(c) 1998-2012 <NAME> and <NAME>.
This file is part of pbrt.
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#if defined(_MSC_VER)
#pragma once
#endif
#ifndef PBRT_CORE_MATERIAL_H
#define PBRT_CORE_MATERIAL_H
// core/material.h*
#include "pbrt.h"
#include "memory.h"
#include "spectrum.h"
#include <vector>
using std::vector;
class BumpMapping {
public:
// BumpMapping Public Methods
BumpMapping(const Reference<Texture<float> >& bm) : bumpMap(bm) {}
void Bump(const DifferentialGeometry& dgGeom, const DifferentialGeometry& dgShading,
DifferentialGeometry* dgBump) const;
private:
// BumpMapping Private Data
Reference<Texture<float> > bumpMap;
};
// Material Declarations
class Material : public ReferenceCounted {
public:
// Material Interface
Material() : materialId(nextMaterialId++) {}
virtual BSDF *GetBSDF(const DifferentialGeometry &dgGeom,
const DifferentialGeometry &dgShading,
MemoryArena &arena) const = 0;
virtual BSSRDF *GetBSSRDF(const DifferentialGeometry &dgGeom,
const DifferentialGeometry &dgShading,
MemoryArena &arena) const {
return NULL;
}
virtual const MultipoleBSSRDF* GetMultipoleBSSRDF(const DifferentialGeometry &dgGeom,
const DifferentialGeometry &dgShading, MemoryArena &arena) const
{
return NULL;
}
virtual bool HasSubsurfaceScattering() const {
return false;
}
virtual BumpMapping GetBumpMapping() const {
return BumpMapping(NULL);
}
virtual ~Material();
static void Bump(const Reference<Texture<float> > &d, const DifferentialGeometry &dgGeom,
const DifferentialGeometry &dgShading, DifferentialGeometry *dgBump);
// Material Public Data
const uint32_t materialId;
protected:
// Material Protected Data
static uint32_t nextMaterialId;
};
// Wavelength dependent value
const int WLD_nSamples = 61;
extern const float WLD_lambdas[WLD_nSamples];
class WLDValue : public CoefficientSpectrum<WLD_nSamples> {
public:
typedef CoefficientSpectrum<WLD_nSamples> Base;
Spectrum toSpectrum() const {
return Spectrum::FromSampled(WLD_lambdas, c, WLD_nSamples);
}
SampledSpectrum toSampledSpectrum() const {
return SampledSpectrum::FromSampled(WLD_lambdas, c, WLD_nSamples);
}
float& operator[](uint32_t index) {
return c[index];
}
const float& operator[](uint32_t index) const {
return c[index];
}
WLDValue(float v = 0.f) : Base(v) { }
WLDValue(const Base& v) : Base(v) { }
static WLDValue FromSampled(const float* lambdas, const float* vals, int n) {
WLDValue res;
// Use linear interpolation to get value at each wavelength of interest
int idxSampledLambda = 0;
float lambda0 = 0.f, lambda1 = lambdas[0];
float val0 = vals[0], val1 = vals[0];
for (int i = 0; i < WLD_nSamples; i++) {
float lambda = WLD_lambdas[i];
while (lambda > lambda1 && idxSampledLambda < n - 1) {
++idxSampledLambda;
lambda0 = lambda1;
lambda1 = lambdas[idxSampledLambda];
val0 = val1;
val1 = vals[idxSampledLambda];
}
if (lambda <= lambda1) {
res[i] = Lerp((lambda - lambda0) / (lambda1 - lambda0), val0, val1);
} else
res[i] = val1;
}
return res;
}
float getValueForWL(float lambda) const {
if (lambda <= WLD_lambdas[0])
return c[0];
if (lambda >= WLD_lambdas[WLD_nSamples - 1])
return c[WLD_nSamples - 1];
int idxLambda = 1;
while (WLD_lambdas[idxLambda] < lambda)
idxLambda++;
return Lerp((lambda - WLD_lambdas[idxLambda - 1]) /
(WLD_lambdas[idxLambda] - WLD_lambdas[idxLambda - 1]),
c[idxLambda - 1], c[idxLambda]);
}
};
struct LayerParam {
LayerParam() {
mua = musp = WLDValue(0.f);
ga = b = 0.f;
isotropicHGPF = false;
}
// Thickness
float thickness;
// Absorption and (reduced) scattering coefficient
WLDValue mua, musp;
// Anisotropy and isotropy associated with HGPF
float ga, b;
// Whether to use modified version of HGPF that accounts for isotropic scattering
bool isotropicHGPF;
};
class LayeredMaterial : public Material {
public:
// LayeredMaterial Interface
virtual vector<float> GetLayerThickness() const = 0;
virtual BSDF* GetLayeredBSDF(int layerIndex,
const DifferentialGeometry &dgGeom,
const DifferentialGeometry &dgShading,
MemoryArena &arena) const = 0;
virtual BSSRDF* GetLayeredBSSRDF(int layerIndex,
const DifferentialGeometry &dgGeom,
const DifferentialGeometry &dgShading,
MemoryArena &arena) const
{
return NULL;
}
virtual LayerParam GetLayerParam(int layerIndex) const = 0;
};
class LayeredMaterialWrapper : public Material {
public:
LayeredMaterialWrapper(const Reference<LayeredMaterial>& layeredMaterial,
int layerIndex);
int GetLayerIndex() const;
BSDF* GetBSDF(const DifferentialGeometry &dgGeom,
const DifferentialGeometry &dgShading,
MemoryArena &arena) const override;
BSSRDF* GetBSSRDF(const DifferentialGeometry &dgGeom,
const DifferentialGeometry &dgShading,
MemoryArena &arena) const override;
private:
int layerIndex;
Reference<LayeredMaterial> layeredMaterial;
};
#endif // PBRT_CORE_MATERIAL_H
|
patwonder/pbrt-v2-skin
|
src/integrators/multipolesubsurface.h
|
/*
Copyright(c) 2013-2014 <NAME>.
This file is part of fork of pbrt (pbrt-v2-skin).
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "integrator.h"
#include "irradiancepoint.h"
struct SubsurfaceOctreeNode;
class MultipoleSubsurfaceIntegrator : public SurfaceIntegrator {
public:
// MultipoleSubsurfaceIntegrator Public Methods
void Preprocess(const Scene *scene, const Camera *camera,
const Renderer *renderer) override;
void RequestSamples(Sampler *sampler, Sample *sample,
const Scene *scene) override;
Spectrum Li(const Scene *scene, const Renderer *renderer,
const RayDifferential &ray, const Intersection &isect,
const Sample *sample, RNG &rng, MemoryArena &arena) const override;
MultipoleSubsurfaceIntegrator(int mdepth, float merror, float mindist,
const string &fn, const vector<Reference<Primitive> >* ops, float mix,
bool showIrradiancePoints, bool usePoissonPointFinder, bool incenter)
: originalPrimitives(*ops), mix(mix), showIrradiancePoints(showIrradiancePoints),
usePoissonPointFinder(usePoissonPointFinder), incenter(incenter)
{
maxSpecularDepth = mdepth;
maxError = merror;
minSampleDist = mindist;
filename = fn;
octree = NULL;
lightSampleOffsets = NULL;
bsdfSampleOffsets = NULL;
}
~MultipoleSubsurfaceIntegrator() {
delete [] lightSampleOffsets;
delete [] bsdfSampleOffsets;
}
private:
// MultipoleSubsurfaceIntegrator Private Data
int maxSpecularDepth;
float maxError, minSampleDist;
float mix;
bool showIrradiancePoints, usePoissonPointFinder, incenter;
string filename;
vector<IrradiancePoint> irradiancePoints;
BBox octreeBounds;
SubsurfaceOctreeNode *octree;
MemoryArena octreeArena;
const vector<Reference<Primitive> >& originalPrimitives;
// Declare sample parameters for light source sampling
LightSampleOffsets *lightSampleOffsets;
BSDFSampleOffsets *bsdfSampleOffsets;
};
MultipoleSubsurfaceIntegrator *CreateMultipoleSubsurfaceIntegrator(const ParamSet ¶ms,
const vector<Reference<Primitive> >* originalPrimitives);
|
patwonder/pbrt-v2-skin
|
src/materials/skincoeffs.h
|
/*
Copyright(c) 2013-2014 <NAME>.
This file is part of fork of pbrt (pbrt-v2-skin).
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include "material.h"
// Calculate various absorption/scattering coefficients of human skin
// http://omlc.ogi.edu/news/jan98/skinoptics.html
class SkinCoefficients {
public:
SkinCoefficients(float f_mel, float f_eu, float f_blood, float f_ohg,
float ga_epi, float ga_derm, float b_derm)
: f_mel(f_mel), f_eu(f_eu), f_blood(f_blood), f_ohg(f_ohg),
ga_epi(ga_epi), ga_derm(ga_derm), b_derm(b_derm) {}
// Baseline absorption coefficient, mua.skinbaseline
static WLDValue mua_skinbaseline() {
return calculate([] (float wl) {
return 0.244f + 85.3f * expf(-(wl - 154.f) / 66.2f);
});
}
// == Epidermis ============================================
// Absorption coefficient of a single eumelanosome, mua.eumel
static WLDValue mua_eumel() {
return calculate([] (float wl) {
return 6.6e11f * powf(wl, -3.33f);
});
}
// Absorption coefficient of a single pheomelanosome, mua.pheomel
static WLDValue mua_pheomel() {
return calculate([] (float wl) {
return 2.9e15f * powf(wl, -4.75f);
});
}
// Volume fraction of melanosomes in epidermis
float f_mel;
// Fraction of eumelanin in melanosomes
float f_eu;
// Net epidermal absorption coefficient, mua.epi
WLDValue mua_epi() const {
return f_mel * (f_eu * mua_eumel() + (1 - f_eu) * mua_pheomel()) +
(1 - f_mel) * mua_skinbaseline();
}
//// Scattering coefficient of the epidermis, mus.epi
//Spectrum mus_epi() const;
//// Anisotropy of the epidermis, g.epi
//float g_epi;
// Reduced scattering coefficient of the epidermis, musp.epi
static WLDValue musp_epi() {
return musp_Rayleigh() + musp_Mie_fibers();
}
// == Dermis ============================================
// Volume fraction of oxyhemoglobin, f_ohg
float f_ohg;
// Absorption coefficient of whole blood, mua.blood
// Data from: http://www.npsg.uwaterloo.ca/data/blood.php
WLDValue mua_blood() const {
const float ln10 = 2.303f;
const float molarWeight = 64500.f; // g/mole
const float concentration = 150.f; // g/L
return ln10 / molarWeight * concentration *
(f_ohg * WLDValue::FromSampled(
ohg_lambdas, ohg_vals, ohg_n) +
(1.f - f_ohg) * WLDValue::FromSampled(
dhg_lambdas, dhg_vals, dhg_n));
}
static WLDValue mua_ohg() {
const float ln10 = 2.303f;
const float molarWeight = 64500.f; // g/mole
const float concentration = 150.f; // g/L
return ln10 / molarWeight * concentration *
WLDValue::FromSampled(ohg_lambdas, ohg_vals, ohg_n);
}
static WLDValue mua_dhg() {
const float ln10 = 2.303f;
const float molarWeight = 64500.f; // g/mole
const float concentration = 150.f; // g/L
return ln10 / molarWeight * concentration *
WLDValue::FromSampled(dhg_lambdas, dhg_vals, dhg_n);
}
// Average volume fraction of blood, f.blood
float f_blood;
// Absorption coefficient of dermis perfused with blood, mua.derm
WLDValue mua_derm() const {
return f_blood * mua_blood() + (1 - f_blood) * mua_skinbaseline();
}
// (Reduced) Mie scattering coefficient of collagen fibers, musp_Mie.fibers
static WLDValue musp_Mie_fibers() {
return calculate([] (float wl) {
//return 2e5f * powf(wl, -1.5f);
return 147.4f * powf(wl, -0.22);
});
}
// (Reduced) Rayleigh scattering coefficient of the dermis, musp_Rayleigh
static WLDValue musp_Rayleigh() {
return calculate([] (float wl) {
return 2e12f * pow(wl, -4.f);
});
}
// (Reduced) scattering coefficient of dermis, musp.derm
static WLDValue musp_derm() {
// scale coeff by 50% as the dermis is more translucent
return musp_epi() * 0.5f;
}
// Anisotropy of the epidermis, ga.epi
float ga_epi;
// Anisotropy of the epidermis, ga.derm
float ga_derm;
// Isotropic scattering coefficient of the dermis, b.derm;
float b_derm;
private:
// Calculated SampledSpectrum from wavelength->value mapping
template <class MappingFunction>
static WLDValue calculate(const MappingFunction& mapping) {
WLDValue res;
for (int i = 0; i < WLD_nSamples; i++) {
res[i] = mapping(WLD_lambdas[i]);
}
return res;
}
static const float ohg_lambdas[];
static const float ohg_vals[];
static const int ohg_n;
static const float dhg_lambdas[];
static const float dhg_vals[];
static const int dhg_n;
};
|
patwonder/pbrt-v2-skin
|
src/integrators/diffusionutil.h
|
<reponame>patwonder/pbrt-v2-skin<gh_stars>1-10
/*
pbrt source code Copyright(c) 1998-2012 <NAME> and <NAME>.
This file is part of pbrt.
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include "octree.h"
#include "renderers/surfacepoints.h"
#include "irradiancepoint.h"
struct DiffusionReflectance {
// DiffusionReflectance Public Methods
DiffusionReflectance(const Spectrum &sigma_a, const Spectrum &sigmap_s,
float eta) {
A = (1.f + Fdr(eta)) / (1.f - Fdr(eta));
sigmap_t = sigma_a + sigmap_s;
sigma_tr = Sqrt(3.f * sigma_a * sigmap_t);
alphap = sigmap_s / sigmap_t;
zpos = Spectrum(1.f) / sigmap_t;
zneg = -zpos * (1.f + (4.f/3.f) * A);
}
Spectrum operator()(float d2) const {
Spectrum dpos = Sqrt(Spectrum(d2) + zpos * zpos);
Spectrum dneg = Sqrt(Spectrum(d2) + zneg * zneg);
Spectrum Rd = (alphap / (4.f * M_PI)) *
((zpos * (dpos * sigma_tr + Spectrum(1.f)) *
Exp(-sigma_tr * dpos)) / (dpos * dpos * dpos) -
(zneg * (dneg * sigma_tr + Spectrum(1.f)) *
Exp(-sigma_tr * dneg)) / (dneg * dneg * dneg));
return Rd.Clamp();
}
Spectrum operator()(Spectrum d2) const {
Spectrum dpos = Sqrt(d2 + zpos * zpos);
Spectrum dneg = Sqrt(d2 + zneg * zneg);
Spectrum Rd = (alphap / (4.f * M_PI)) *
((zpos * (dpos * sigma_tr + Spectrum(1.f)) *
Exp(-sigma_tr * dpos)) / (dpos * dpos * dpos) -
(zneg * (dneg * sigma_tr + Spectrum(1.f)) *
Exp(-sigma_tr * dneg)) / (dneg * dneg * dneg));
return Rd.Clamp();
}
Spectrum TotalReflectance() const {
Spectrum mfp = Spectrum(1.f) / sigmap_t;
Spectrum integral = 0.f;
Spectrum stepSize = (4.f * mfp) * (4.f * mfp) / 1024.f;
for (int i = 0; i < 1024; i++) {
Spectrum d2 = stepSize * i;
integral += (*this)(d2);
}
return integral * stepSize * M_PI;
}
// DiffusionReflectance Data
Spectrum zpos, zneg, sigmap_t, sigma_tr, alphap;
float A;
};
struct SubsurfaceOctreeNode {
// SubsurfaceOctreeNode Methods
SubsurfaceOctreeNode() {
isLeaf = true;
sumArea = 0.f;
for (int i = 0; i < 8; ++i)
ips[i] = NULL;
}
void Insert(const BBox &nodeBound, IrradiancePoint *ip,
MemoryArena &arena) {
Point pMid = .5f * nodeBound.pMin + .5f * nodeBound.pMax;
if (isLeaf) {
// Add _IrradiancePoint_ to leaf octree node
for (int i = 0; i < 8; ++i) {
if (!ips[i]) {
ips[i] = ip;
return;
}
}
// Convert leaf node to interior node, redistribute points
isLeaf = false;
IrradiancePoint *localIps[8];
for (int i = 0; i < 8; ++i) {
localIps[i] = ips[i];
children[i] = NULL;
}
for (int i = 0; i < 8; ++i) {
IrradiancePoint *ip = localIps[i];
// Add _IrradiancePoint_ _ip_ to interior octree node
int child = (ip->p.x > pMid.x ? 4 : 0) +
(ip->p.y > pMid.y ? 2 : 0) + (ip->p.z > pMid.z ? 1 : 0);
if (!children[child])
children[child] = arena.Alloc<SubsurfaceOctreeNode>();
BBox childBound = octreeChildBound(child, nodeBound, pMid);
children[child]->Insert(childBound, ip, arena);
}
/* fall through to interior case to insert the new point... */
}
// Add _IrradiancePoint_ _ip_ to interior octree node
int child = (ip->p.x > pMid.x ? 4 : 0) +
(ip->p.y > pMid.y ? 2 : 0) + (ip->p.z > pMid.z ? 1 : 0);
if (!children[child])
children[child] = arena.Alloc<SubsurfaceOctreeNode>();
BBox childBound = octreeChildBound(child, nodeBound, pMid);
children[child]->Insert(childBound, ip, arena);
}
void InitHierarchy() {
if (isLeaf) {
// Init _SubsurfaceOctreeNode_ leaf from _IrradiancePoint_s
float sumWt = 0.f;
uint32_t i;
for (i = 0; i < 8; ++i) {
if (!ips[i]) break;
Spectrum ipEt = ips[i]->E * ips[i]->area;
float wt = ipEt.y();
Et += ipEt;
p += wt * ips[i]->p;
n += wt * ips[i]->n;
sumWt += wt;
sumArea += ips[i]->area;
}
if (sumWt > 0.f) {
p /= sumWt;
n /= sumWt;
}
}
else {
// Init interior _SubsurfaceOctreeNode_
float sumWt = 0.f;
uint32_t nChildren = 0;
for (uint32_t i = 0; i < 8; ++i) {
if (!children[i]) continue;
++nChildren;
children[i]->InitHierarchy();
float wt = children[i]->Et.y();
Et += children[i]->Et;
p += wt * children[i]->p;
n += wt * children[i]->n;
sumWt += wt;
sumArea += children[i]->sumArea;
}
if (sumWt > 0.f) {
p /= sumWt;
n /= sumWt;
}
}
}
template<class ReflectanceCalculator>
Spectrum Mo(const BBox &nodeBound, const Point &pt, const Normal& nn,
const ReflectanceCalculator &Rd, float maxError) {
// No irradiance in subtree
if (Et.IsBlack())
return Spectrum(0.f);
// Compute $M_\roman{o}$ at node if error is low enough
float dw = sumArea / DistanceSquared(pt, p);
if (dw < maxError && !nodeBound.Inside(pt)) {
PBRT_SUBSURFACE_ADDED_INTERIOR_CONTRIBUTION(const_cast<SubsurfaceOctreeNode *>(this));
return Rd(ModifiedDistanceSquared(pt, nn, p, n)) * Et;
}
// Otherwise compute $M_\roman{o}$ from points in leaf or recursively visit children
Spectrum Mo = 0.f;
if (isLeaf) {
// Accumulate $M_\roman{o}$ from leaf node
for (int i = 0; i < 8; ++i) {
if (!ips[i]) break;
PBRT_SUBSURFACE_ADDED_POINT_CONTRIBUTION(const_cast<IrradiancePoint *>(ips[i]));
if (!ips[i]->E.IsBlack())
Mo += Rd(ModifiedDistanceSquared(pt, nn, ips[i]->p, ips[i]->n)) * ips[i]->E * ips[i]->area;
}
}
else {
// Recursively visit children nodes to compute $M_\roman{o}$
Point pMid = .5f * nodeBound.pMin + .5f * nodeBound.pMax;
for (int child = 0; child < 8; ++child) {
if (!children[child]) continue;
BBox childBound = octreeChildBound(child, nodeBound, pMid);
Mo += children[child]->Mo(childBound, pt, nn, Rd, maxError);
}
}
return Mo;
}
// SubsurfaceOctreeNode Public Data
Point p;
Normal n;
bool isLeaf;
Spectrum Et;
float sumArea;
union {
SubsurfaceOctreeNode *children[8];
IrradiancePoint *ips[8];
};
private:
static float ModifiedDistanceSquared(const Point& p, const Normal& n, const Point& ipp, const Normal& ipn) {
#if 1
return DistanceSquared(p, ipp);
#else
float lerpAmount = Clamp(0.3f - Dot(n, ipn), 0.f, 1.f);
const float scale = 0.5f;
// Lerp to scale * distance for opposing directions
return Lerp(lerpAmount, 1.f, scale) * Lerp(lerpAmount, 1.f, scale) * DistanceSquared(p, ipp);
#endif
}
};
|
patwonder/pbrt-v2-skin
|
src/integrators/layeredintegrator.h
|
<reponame>patwonder/pbrt-v2-skin<filename>src/integrators/layeredintegrator.h<gh_stars>1-10
/*
Copyright(c) 2013-2014 <NAME>.
This file is part of fork of pbrt (pbrt-v2-skin).
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "integrator.h"
class LayeredIntegrator : public SurfaceIntegrator {
public:
// LayeredIntegrator Public Methods
void Preprocess(const Scene *scene, const Camera *camera,
const Renderer *renderer) override;
void RequestSamples(Sampler *sampler, Sample *sample,
const Scene *scene) override;
Spectrum Li(const Scene *scene, const Renderer *renderer,
const RayDifferential &ray, const Intersection &isect,
const Sample *sample, RNG &rng, MemoryArena &arena) const override;
LayeredIntegrator(int md) { maxDepth = md; }
private:
// LayeredIntegrator Private Methods
// Spectral shading
float LiSpectral(uint32_t wlIndex, float pathThroughput, int bounces, bool specularBounce,
const Scene *scene, const Renderer *renderer,
const RayDifferential &ray, const Intersection &isect,
const Sample *sample, RNG &rng, MemoryArena &arena) const;
float RandomWalk(uint32_t wlIndex, float& pathThroughput,
const LayeredGeometricPrimitive* lprim,
const Scene *scene, const Renderer *renderer,
const RayDifferential& ray, uint32_t primitiveId,
const Sample* sample, RNG& rng, MemoryArena& arena,
RayDifferential* outRay, Intersection* outIsect) const;
// LayeredIntegrator Private Data
int maxDepth;
static const int SAMPLE_DEPTH = 3;
static const int TERM_DEPTH = 10;
LightSampleOffsets lightSampleOffsets[SAMPLE_DEPTH];
int lightNumOffset[SAMPLE_DEPTH];
BSDFSampleOffsets bsdfSampleOffsets[SAMPLE_DEPTH];
BSDFSampleOffsets pathSampleOffsets[SAMPLE_DEPTH];
};
LayeredIntegrator *CreateLayeredSurfaceIntegrator(const ParamSet ¶ms);
|
patwonder/pbrt-v2-skin
|
src/shapes/loopsubdiv.h
|
<reponame>patwonder/pbrt-v2-skin
/*
pbrt source code Copyright(c) 1998-2012 <NAME> and <NAME>.
This file is part of pbrt.
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#if defined(_MSC_VER)
#pragma once
#endif
#ifndef PBRT_SHAPES_LOOPSUBDIV_H
#define PBRT_SHAPES_LOOPSUBDIV_H
// shapes/loopsubdiv.h*
#include "shape.h"
struct SDVertex;
struct SDFace;
// LoopSubdiv Declarations
class LoopSubdiv : public ShrinkableShape {
public:
// LoopSubdiv Public Methods
LoopSubdiv(const Transform *o2w, const Transform *w2o, bool ro,
int nt, int nv, const int *vi,
const Point *P, int nlevels);
~LoopSubdiv();
bool CanIntersect() const;
void Refine(vector<Reference<Shape> > &refined) const;
Reference<ShrinkableShape> Shrink(float distance) const override;
BBox ObjectBound() const;
BBox WorldBound() const;
private:
// LoopSubdiv Private Methods
static float beta(int valence) {
if (valence == 3) return 3.f/16.f;
else return 3.f / (8.f * valence);
}
static Point weightOneRing(SDVertex *vert, float beta);
static Point weightBoundary(SDVertex *vert, float beta);
static float gamma(int valence) {
return 1.f / (valence + 3.f / (8.f * beta(valence)));
}
// LoopSubdiv Private Data
int nLevels;
vector<SDVertex *> vertices;
vector<SDFace *> faces;
};
LoopSubdiv *CreateLoopSubdivShape(const Transform *o2w, const Transform *w2o,
bool reverseOrientation, const ParamSet ¶ms);
#endif // PBRT_SHAPES_LOOPSUBDIV_H
|
patwonder/pbrt-v2-skin
|
src/core/multipole.h
|
/*
Copyright(c) 2013-2014 <NAME>.
This file is part of fork of pbrt (pbrt-v2-skin).
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
struct MultipoleProfileData;
struct RhoData {
vector<Spectrum> hd;
Spectrum hh;
};
class MultipoleBSSRDFData {
public:
// MultipoleBSSRDF Public Methods
MultipoleBSSRDFData(int layers, const Spectrum mua[], const Spectrum musp[], float et[], float thickness[],
const MultipoleProfileData* pData, const RhoData& rhoData, bool isMonteCarlo = false) {
if (layers > MAX_LAYERS)
layers = MAX_LAYERS;
nLayers = layers;
for (int i = 0; i < layers; i++) {
sig_a[i] = mua[i];
sigp_s[i] = musp[i];
e[i] = et[i];
d[i] = thickness[i];
}
this->pData = pData;
this->isMonteCarlo = isMonteCarlo;
this->rhoData = rhoData;
Info("Rho_hd_ for incident beam: %f; Rho_hh_: %f", rhoData.hd.back().y(), rhoData.hh.y());
}
int numLayers() const { return nLayers; }
float thickness(int layer) const { return d[layer]; }
float eta(int layer) const { return e[layer]; }
Spectrum sigma_a(int layer) const { return sig_a[layer]; }
Spectrum sigma_prime_s(int layer) const { return sigp_s[layer]; }
bool IsMonteCarlo() const { return isMonteCarlo; }
Spectrum rho(float costheta) const;
Spectrum rho() const;
Spectrum reflectance(float distanceSquared) const;
Spectrum transmittance(float distanceSquared) const;
Spectrum totalReflectance() const;
Spectrum totalTransmittance() const;
// MultipoleBSSRDFData Public Data
static const int MAX_LAYERS = 4;
private:
// MultipoleBSSRDFData Private Data
int nLayers;
float d[MAX_LAYERS];
float e[MAX_LAYERS];
Spectrum sig_a[MAX_LAYERS];
Spectrum sigp_s[MAX_LAYERS];
const MultipoleProfileData* pData;
bool isMonteCarlo;
RhoData rhoData;
// MultipoleBSSRDF Private Methods
void computeRhoIntegral();
};
void ComputeMultipoleProfile(int layers, const SampledSpectrum mua[], const SampledSpectrum musp[], float et[], float thickness[],
MultipoleProfileData** oppData, bool useMonteCarlo = false, bool lerpOnThinSlab = true, uint64_t nPhotons = 10000000,
int desiredLength = 512);
void ComputeRGBMultipoleProfile(int layers, const RGBSpectrum mua[], const RGBSpectrum musp[], float et[], float thickness[],
MultipoleProfileData** oppData, bool lerpOnThinSlab = true,
int desiredLength = 512);
void ComputeIrradiancePointsProfile(MultipoleProfileData** oppData, float radius);
void ReleaseMultipoleProfile(MultipoleProfileData* pData);
RhoData ComputeRhoDataFromBxDF(const BxDF* bxdf);
RhoData ComputeRoughRhoData();
|
patwonder/pbrt-v2-skin
|
src/multipole/MultipoleProfileCalculator/cachedallocator.h
|
<filename>src/multipole/MultipoleProfileCalculator/cachedallocator.h
/*
Copyright(c) 2013-2014 <NAME>.
This file is part of fork of pbrt (pbrt-v2-skin).
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include <unordered_map>
#include <vector>
#include <mutex>
#include <memory.h>
template <class Param, class Type>
class CPPAllocator {
public:
Type alloc(const Param& param) {
return ::operator new(param);
}
void free(const Type& p) {
::operator delete(p);
}
};
template <class Param, class Type, class TrueAllocator = CPPAllocator<Param, Type>, class Mutex = std::mutex>
class CachedAllocator {
public:
~CachedAllocator() {
clear();
}
Type alloc(const Param& param) {
{
std::lock_guard<Mutex> lock(mtx);
auto iter = cache.find(param);
if (iter != cache.end()) {
auto& blocks = iter->second;
if (blocks.size()) {
Type block = blocks.back();
blocks.pop_back();
return block;
}
}
}
Type block = allocator.alloc(param);
{
std::lock_guard<Mutex> lock(mtx);
paramMap.insert(make_pair(block, param));
}
return block;
}
void free(const Type& p) {
std::lock_guard<Mutex> lock(mtx);
auto iter = paramMap.find(p);
if (iter != paramMap.end()) {
cache[iter->second].push_back(p);
} else {
allocator.free(p);
}
}
void safeClear() {
std::lock_guard<Mutex> lock(mtx);
clear();
}
void clear() {
for (auto& pair : cache)
for (auto& block : pair.second)
allocator.free(block);
cache.clear();
paramMap.clear();
}
private:
std::unordered_map<Param, std::vector<Type> > cache;
std::unordered_map<Type, Param> paramMap;
Mutex mtx;
static TrueAllocator allocator;
};
template <class Param, class Type, class TrueAllocator, class Mutex>
TrueAllocator CachedAllocator<Param, Type, TrueAllocator, Mutex>::allocator;
template <class Param, class Type, class TrueAllocator, class Mutex>
void* operator new(size_t size, CachedAllocator<Param, Type, TrueAllocator, Mutex>& alloc) {
return alloc.alloc(size);
}
template <class Param, class Type, class TrueAllocator, class Mutex>
void operator delete(void* p, CachedAllocator<Param, Type, TrueAllocator, Mutex>& alloc) {
alloc.free(p);
}
|
patwonder/pbrt-v2-skin
|
src/renderers/surfacepoints.h
|
<reponame>patwonder/pbrt-v2-skin
/*
pbrt source code Copyright(c) 1998-2012 <NAME> and <NAME>.
This file is part of pbrt.
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#if defined(_MSC_VER)
#pragma once
#endif
#ifndef PBRT_RENDERERS_SURFACEPOINTS_H
#define PBRT_RENDERERS_SURFACEPOINTS_H
// renderers/surfacepoints.h*
#include "pbrt.h"
#include "geometry.h"
#include "renderer.h"
// SurfacePointsRenderer Declarations
struct SurfacePoint {
SurfacePoint() { }
SurfacePoint(const Point &pp, const Normal &nn, float a, float eps)
: p(pp), n(nn), area(a), rayEpsilon(eps) { }
// SurfacePoint Data
Point p;
Normal n;
float u, v;
uint32_t materialId;
float area, rayEpsilon;
};
class Tessellatable {
public:
// Tessellatable Interface Methods
virtual void TessellateSurfacePoints(float minDist, const BumpMapping& bump,
uint32_t materialId, vector<SurfacePoint>& points, ProgressReporter* pr = NULL,
bool incenter = false) const = 0;
virtual int GetTessellationWork() const = 0;
virtual ~Tessellatable() {}
};
class SurfacePointsRenderer : public Renderer {
public:
// SurfacePointsRenderer Public Methods
SurfacePointsRenderer(float md, const Point &pc, float t,
const string &fn)
: minDist(md), time(t), pCamera(pc), filename(fn) { }
void Render(const Scene *scene);
Spectrum Li(const Scene *scene, const RayDifferential &ray,
const Sample *sample, RNG &rng, MemoryArena &arena,
Intersection *isect, Spectrum *T) const;
Spectrum Transmittance(const Scene *scene, const RayDifferential &ray,
const Sample *sample, RNG &rng, MemoryArena &arena) const;
private:
// SurfacePointsRenderer Private Data
float minDist, time;
Point pCamera;
string filename;
friend void FindPoissonPointDistribution(const Point &pCamera, float time,
float minDist, const Scene *scene, vector<SurfacePoint> *points);
vector<SurfacePoint> points;
};
class TessellateSurfacePointsRenderer : public Renderer {
public:
// TessellateSurfacePointsRenderer Public Methods
TessellateSurfacePointsRenderer(float md, float t, const string &fn,
const vector<Reference<Primitive> >* ops, bool incenter = false)
: minDist(md), time(t), filename(fn), originalPrimitives(*ops),
incenter(incenter) { }
void Render(const Scene *scene);
Spectrum Li(const Scene *scene, const RayDifferential &ray,
const Sample *sample, RNG &rng, MemoryArena &arena,
Intersection *isect, Spectrum *T) const;
Spectrum Transmittance(const Scene *scene, const RayDifferential &ray,
const Sample *sample, RNG &rng, MemoryArena &arena) const;
private:
// TessellateSurfacePointsRenderer Private Data
float minDist, time;
string filename;
bool incenter;
friend void GetSurfacePointsThroughTessellation(float time, float minDist,
const Scene *scene, const vector<Reference<Primitive> >* originalPrimitives,
vector<SurfacePoint> *points, bool incenter);
vector<SurfacePoint> points;
const vector<Reference<Primitive> >& originalPrimitives;
};
void FindPoissonPointDistribution(const Point &pCamera, float time, float minDist,
const Scene *scene, vector<SurfacePoint> *points);
void GetSurfacePointsThroughTessellation(float time, float minDist,
const Scene *scene, const vector<Reference<Primitive> >* originalPrimitives,
vector<SurfacePoint> *points, bool incenter = false);
SurfacePointsRenderer *CreateSurfacePointsRenderer(const ParamSet ¶ms,
const Point &pCamera, float time);
TessellateSurfacePointsRenderer* CreateTessellateSurfacePointsRenderer(const ParamSet& params,
float time, const vector<Reference<Primitive> >* originalPrimitives);
#endif // PBRT_RENDERERS_SURFACEPOINTS_H
|
patwonder/pbrt-v2-skin
|
src/core/primitive.h
|
/*
pbrt source code Copyright(c) 1998-2012 <NAME> and <NAME>.
This file is part of pbrt.
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#if defined(_MSC_VER)
#pragma once
#endif
#ifndef PBRT_CORE_PRIMITIVE_H
#define PBRT_CORE_PRIMITIVE_H
// core/primitive.h*
#include "pbrt.h"
#include "shape.h"
#include "material.h"
class LayeredGeometricPrimitive;
// Primitive Declarations
class Primitive : public ReferenceCounted {
public:
// Primitive Interface
Primitive() : primitiveId(nextprimitiveId++) { }
virtual ~Primitive();
virtual BBox WorldBound() const = 0;
virtual bool CanIntersect() const;
virtual bool Intersect(const Ray &r, Intersection *in) const = 0;
virtual bool IntersectExcept(const Ray &r, Intersection* in, uint32_t primitiveId) const {
if (this->primitiveId == primitiveId) return false;
return Intersect(r, in);
}
virtual bool IntersectP(const Ray &r) const = 0;
virtual void Refine(vector<Reference<Primitive> > &refined) const;
void FullyRefine(vector<Reference<Primitive> > &refined) const;
virtual const AreaLight *GetAreaLight() const = 0;
virtual BSDF *GetBSDF(const DifferentialGeometry &dg,
const Transform &ObjectToWorld, MemoryArena &arena) const = 0;
virtual BSSRDF *GetBSSRDF(const DifferentialGeometry &dg,
const Transform &ObjectToWorld, MemoryArena &arena) const = 0;
virtual const MultipoleBSSRDF* GetMultipoleBSSRDF(const DifferentialGeometry &dg,
const Transform &ObjectToWorld, MemoryArena &arena) const = 0;
virtual void GetShadingGeometry(const DifferentialGeometry& dg,
const Transform &ObjectToWorld, DifferentialGeometry& dgShading) const = 0;
// Low-cost RTTI
virtual LayeredGeometricPrimitive* ToLayered() { return NULL; }
virtual const LayeredGeometricPrimitive* ToLayered() const { return NULL; }
// Primitive Public Data
const uint32_t primitiveId;
protected:
// Primitive Protected Data
static uint32_t nextprimitiveId;
};
// GeometricPrimitive Declarations
class GeometricPrimitive : public Primitive {
public:
// GeometricPrimitive Public Methods
bool CanIntersect() const;
void Refine(vector<Reference<Primitive> > &refined) const;
virtual BBox WorldBound() const;
virtual bool Intersect(const Ray &r, Intersection *isect) const;
virtual bool IntersectP(const Ray &r) const;
GeometricPrimitive(const Reference<Shape> &s,
const Reference<Material> &m, const AreaLight *a);
const AreaLight *GetAreaLight() const;
BSDF *GetBSDF(const DifferentialGeometry &dg,
const Transform &ObjectToWorld, MemoryArena &arena) const;
BSSRDF *GetBSSRDF(const DifferentialGeometry &dg,
const Transform &ObjectToWorld, MemoryArena &arena) const;
const MultipoleBSSRDF* GetMultipoleBSSRDF(const DifferentialGeometry &dg,
const Transform &ObjectToWorld, MemoryArena &arena) const override;
void GetShadingGeometry(const DifferentialGeometry& dg,
const Transform &ObjectToWorld, DifferentialGeometry& dgShading) const override;
const Shape* GetShape() const;
const Material* GetMaterial() const;
protected:
// GeometricPrimitive Private Data
Reference<Shape> shape;
Reference<Material> material;
private:
// GeometricPrimitive Private Data
const AreaLight *areaLight;
};
class LayeredGeometricPrimitive : public GeometricPrimitive {
public:
// LayeredGeometricPrimitive Public Methods
LayeredGeometricPrimitive(const Reference<Shape>& s,
const Reference<LayeredMaterial>& m, const AreaLight* a);
virtual bool IntersectInternal(const Ray& r, uint32_t primitiveId,
Intersection* isect, int* layerIndex) const = 0;
virtual BSDF *GetLayeredBSDF(int layerIndex,
const DifferentialGeometry &dg,
const Transform &ObjectToWorld, MemoryArena &arena) const = 0;
virtual BSSRDF *GetLayeredBSSRDF(int layerIndex,
const DifferentialGeometry &dg,
const Transform &ObjectToWorld, MemoryArena &arena) const = 0;
LayeredGeometricPrimitive* ToLayered() override { return this; }
const LayeredGeometricPrimitive* ToLayered() const override { return this; }
};
// TransformedPrimitive Declarations
class TransformedPrimitive : public Primitive {
public:
// TransformedPrimitive Public Methods
TransformedPrimitive(Reference<Primitive> &prim,
const AnimatedTransform &w2p)
: primitive(prim), WorldToPrimitive(w2p) { }
bool Intersect(const Ray &r, Intersection *in) const;
bool IntersectP(const Ray &r) const;
const AreaLight *GetAreaLight() const { return NULL; }
BSDF *GetBSDF(const DifferentialGeometry &dg,
const Transform &ObjectToWorld, MemoryArena &arena) const {
return NULL;
}
BSSRDF *GetBSSRDF(const DifferentialGeometry &dg,
const Transform &ObjectToWorld, MemoryArena &arena) const {
return NULL;
}
const MultipoleBSSRDF* GetMultipoleBSSRDF(const DifferentialGeometry &dg,
const Transform &ObjectToWorld, MemoryArena &arena) const override
{
return NULL;
}
void GetShadingGeometry(const DifferentialGeometry& dg,
const Transform &ObjectToWorld, DifferentialGeometry& dgShading) const override
{
primitive->GetShadingGeometry(dg, ObjectToWorld, dgShading);
}
BBox WorldBound() const {
return WorldToPrimitive.MotionBounds(primitive->WorldBound(), true);
}
private:
// TransformedPrimitive Private Data
Reference<Primitive> primitive;
const AnimatedTransform WorldToPrimitive;
};
// Aggregate Declarations
class Aggregate : public Primitive {
public:
// Aggregate Public Methods
const AreaLight *GetAreaLight() const;
BSDF *GetBSDF(const DifferentialGeometry &dg,
const Transform &, MemoryArena &) const;
BSSRDF *GetBSSRDF(const DifferentialGeometry &dg,
const Transform &, MemoryArena &) const;
const MultipoleBSSRDF* GetMultipoleBSSRDF(const DifferentialGeometry &dg,
const Transform &ObjectToWorld, MemoryArena &arena) const override;
void GetShadingGeometry(const DifferentialGeometry& dg,
const Transform &ObjectToWorld, DifferentialGeometry& dgShading) const override;
};
GeometricPrimitive* CreateGeometricPrimitive(
const Reference<Shape>& s, const Reference<Material>& m,
const AreaLight* a);
#endif // PBRT_CORE_PRIMITIVE_H
|
patwonder/pbrt-v2-skin
|
src/multipole/MultipoleProfileCalculator/fftndrcache.h
|
<gh_stars>1-10
/*
Copyright(c) 2013-2014 <NAME>.
This file is part of fork of pbrt (pbrt-v2-skin).
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include "tools/kiss_fftndr.h"
#include "cachedallocator.h"
struct NDRParams {
int dims[2];
bool inverse;
NDRParams(int dim0, int dim1, bool inv) {
dims[0] = dim0;
dims[1] = dim1;
inverse = inv;
}
bool operator==(const NDRParams& p) const {
return dims[0] == p.dims[0] && dims[1] == p.dims[1] && inverse == p.inverse;
}
};
namespace std {
template<>
class hash<NDRParams> {
public:
size_t operator()(const NDRParams& key) const {
return inthasher(key.dims[0]) + inthasher(key.dims[1]) + boolhasher(key.inverse);
}
private:
static hash<int> inthasher;
static hash<bool> boolhasher;
};
}
class NDRAllocator {
public:
kiss_fftndr_cfg alloc(const NDRParams& params) {
return kiss_fftndr_alloc(params.dims, 2, params.inverse, NULL, NULL);
}
void free(kiss_fftndr_cfg cfg) {
::kiss_fft_free(cfg);
}
};
typedef CachedAllocator<NDRParams, kiss_fftndr_cfg, NDRAllocator> NDRCache;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.